1use std::path::PathBuf;
12
13use axum::body::Body;
14use axum::extract::{Query, State};
15use axum::http::StatusCode;
16use axum::response::{IntoResponse, Json, Response};
17use futures_util::StreamExt;
18use serde::Deserialize;
19use serde_json::{json, Value};
20use sha2::{Digest, Sha256};
21use tokio::io::AsyncWriteExt;
22
23use agentmux_common::time::now_ms;
24
25use crate::backend::storage::work_media::{AttachError, MediaItem, NewMedia};
26use crate::backend::storage::work_queue::WorkItem;
27use crate::backend::task_media;
28
29use super::work_tasks::clean;
30use super::AppState;
31
32const MAX_CAPTION: usize = 300;
34const MAX_NAME: usize = 200;
35
36#[derive(Debug, Clone, Deserialize)]
38pub(super) struct MediaRef {
39 pub sha256: String,
40 #[serde(default)]
41 pub name: String,
42 #[serde(default)]
43 pub caption: String,
44}
45
46fn error(status: StatusCode, msg: impl Into<String>) -> Response {
47 (status, Json(json!({ "error": msg.into() }))).into_response()
48}
49
50#[derive(Deserialize)]
51pub(super) struct UploadQuery {
52 name: Option<String>,
53}
54
55pub(super) async fn handle_work_media_upload(State(_state): State<AppState>, Query(q): Query<UploadQuery>, body: Body) -> Response {
60 let Some(root) = task_media::default_root() else {
61 return error(StatusCode::INTERNAL_SERVER_ERROR, "no data directory for task media");
62 };
63 upload_into(&root, q.name.unwrap_or_default(), body).await
64}
65
66pub(super) async fn upload_into(root: &std::path::Path, name: String, body: Body) -> Response {
67 let tmp = task_media::new_incoming_path(root);
68 if let Some(dir) = tmp.parent() {
69 if let Err(e) = tokio::fs::create_dir_all(dir).await {
70 return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string());
71 }
72 }
73 let written = async {
74 let mut out = tokio::fs::File::create(&tmp).await.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
75 let mut hasher = Sha256::new();
76 let mut total: u64 = 0;
77 let mut stream = body.into_data_stream();
78 while let Some(chunk) = stream.next().await {
79 let chunk = chunk.map_err(|e| (StatusCode::BAD_REQUEST, format!("upload interrupted: {e}")))?;
80 total += chunk.len() as u64;
81 if total > task_media::MAX_RECORDING_BYTES {
82 return Err((StatusCode::PAYLOAD_TOO_LARGE, format!("the file is larger than {} MiB", task_media::MAX_RECORDING_BYTES / (1024 * 1024))));
83 }
84 hasher.update(&chunk);
85 out.write_all(&chunk).await.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
86 }
87 out.flush().await.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
88 if total == 0 {
89 return Err((StatusCode::BAD_REQUEST, "empty body".to_string()));
90 }
91 Ok((hex::encode(hasher.finalize()), total))
92 }
93 .await;
94 let (sha, size) = match written {
95 Ok(v) => v,
96 Err((status, msg)) => {
97 let _ = tokio::fs::remove_file(&tmp).await;
98 return error(status, msg);
99 }
100 };
101 let root = root.to_path_buf();
102 let tmp2 = tmp.clone();
103 let done = tokio::task::spawn_blocking(move || -> Result<Value, (StatusCode, String)> {
104 let head = task_media::read_head(&tmp2).map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
105 let Some(found) = task_media::sniff(&head) else {
106 return Err((
107 StatusCode::UNSUPPORTED_MEDIA_TYPE,
108 "not a PNG, JPEG, GIF, WebP, SVG, MP4, MOV or WebM file (checked by its content, not its name)".to_string(),
109 ));
110 };
111 if size > task_media::max_bytes(found.kind) {
112 return Err((
113 StatusCode::PAYLOAD_TOO_LARGE,
114 format!("a {} is at most {} MiB", found.kind, task_media::max_bytes(found.kind) / (1024 * 1024)),
115 ));
116 }
117 task_media::commit(&root, &tmp2, &sha, &found).map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
118 Ok(json!({ "sha256": sha, "kind": found.kind, "mime": found.mime, "size": size }))
119 })
120 .await;
121 match done {
122 Ok(Ok(mut v)) => {
123 v["name"] = json!(file_name(&name));
124 Json(v).into_response()
125 }
126 Ok(Err((status, msg))) => {
127 let _ = tokio::fs::remove_file(&tmp).await;
128 error(status, msg)
129 }
130 Err(e) => {
131 let _ = tokio::fs::remove_file(&tmp).await;
132 error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
133 }
134 }
135}
136
137fn file_name(given: &str) -> String {
139 let base = given.rsplit(['/', '\\']).next().unwrap_or("").trim();
140 let base = if base.is_empty() { "file" } else { base };
141 clean(base).chars().take(MAX_NAME).collect()
142}
143
144pub(crate) fn find_stored(root: &std::path::Path, sha: &str) -> Option<(PathBuf, task_media::Sniff)> {
146 ["image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml", "video/mp4", "video/webm", "video/quicktime"]
147 .into_iter()
148 .find_map(|mime| {
149 let path = task_media::blob_path(root, sha, mime)?;
150 let head = task_media::read_head(&path).ok()?;
151 let found = task_media::sniff(&head)?;
152 (found.mime == mime).then_some((path, found))
153 })
154}
155
156#[derive(Debug, Default)]
158pub(super) struct MediaCall {
159 pub media: Vec<MediaRef>,
160 pub ui_change: Option<bool>,
161 pub no_media_reason: Option<String>,
162}
163
164fn bad(text: String) -> (StatusCode, Json<Value>) {
165 (StatusCode::BAD_REQUEST, Json(json!({ "ok": false, "error": text })))
166}
167
168pub(super) fn apply(state: &AppState, item: &WorkItem, agent: &str, uid: &str, call: &MediaCall) -> Result<Vec<MediaItem>, (StatusCode, Json<Value>)> {
171 let now = now_ms();
172 if call.media.len() > task_media::MAX_FILES_PER_CALL {
173 return Err(bad(format!("at most {} files in one call", task_media::MAX_FILES_PER_CALL)));
174 }
175 let mut ready: Vec<NewMedia> = Vec::new();
176 if !call.media.is_empty() {
177 let Some(root) = task_media::default_root() else { return Err(bad("no data directory for task media".into())) };
178 for m in &call.media {
179 let Some((path, found)) = find_stored(&root, &m.sha256) else {
180 return Err(bad(format!("{} was not uploaded (or was cleared): upload it again", if m.name.is_empty() { &m.sha256 } else { &m.name })));
181 };
182 let size = std::fs::metadata(&path).map(|md| md.len() as i64).unwrap_or(0);
183 ready.push(NewMedia {
184 sha256: m.sha256.clone(),
185 name: file_name(&m.name),
186 kind: found.kind.to_string(),
187 mime: found.mime.to_string(),
188 size,
189 caption: clean(&m.caption).chars().take(MAX_CAPTION).collect(),
190 attached_by: agent.to_string(),
191 attached_by_uid: uid.to_string(),
192 attempt: item.attempts,
193 });
194 }
195 }
196 let attached = match state.work_store.work_media_add_all(&item.id, &ready, now) {
198 Ok(Ok(rows)) => rows,
199 Ok(Err(why @ (AttachError::TooMany | AttachError::TooBig))) => return Err(bad(why.words())),
200 Err(e) => return Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() })))),
201 };
202 let reason = call.no_media_reason.as_deref().map(|r| clean(r).chars().take(MAX_CAPTION).collect::<String>());
203 if let Err(e) = state.work_store.work_ui_set(&item.id, call.ui_change, reason.as_deref(), item.attempts, now) {
204 return Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))));
205 }
206 Ok(attached)
207}
208
209pub(super) fn submit_refusal(state: &AppState, id: &str, attempt: i64) -> Option<String> {
212 let review = state.work_store.work_board_get(id).ok().flatten().is_some_and(|t| t.card.review_required);
213 let (ui, reason, reason_attempt) = state.work_store.work_ui_get(id).unwrap_or_default();
214 if !(review && ui) || (!reason.trim().is_empty() && reason_attempt == attempt) {
216 return None;
217 }
218 let has = state.work_store.work_media_in_attempt(id, attempt).unwrap_or(false);
219 (!has).then(|| refusal_text().to_string())
220}
221
222pub(super) fn refusal_text() -> &'static str {
223 "This task changes the UI and waits for the operator's OK, so it is handed in with media: attach a before/after screenshot, or a short recording for motion or an interaction (`files` on Tasks update or submit), captured from your own test build, then hand it in again. If you cannot capture one, say why in `no_media_reason` (Tasks update or submit)."
224}
225
226pub(super) fn pr_reminder(state: &AppState, id: &str, attempt: i64) -> Option<&'static str> {
228 let (ui, _, _) = state.work_store.work_ui_get(id).unwrap_or_default();
229 (ui && !state.work_store.work_media_in_attempt(id, attempt).unwrap_or(false))
230 .then_some("This task changes the UI: attach screenshots (`files`) from your own test build before you submit it.")
231}
232
233pub(super) fn attached_json(rows: &[MediaItem]) -> Value {
235 Value::Array(rows.iter().map(|r| json!({ "id": r.id, "name": r.name, "kind": r.kind, "size": r.size, "caption": r.caption })).collect())
236}
237
238#[cfg(test)]
239#[path = "work_media_tests.rs"]
240mod tests;