1use std::collections::HashMap;
20use std::io::Write;
21use std::sync::{Arc, LazyLock, Mutex};
22use std::time::{Duration, Instant};
23
24use agentmux_common::api_types::{UiRecordRequest, UiRecordResponse};
25use axum::extract::State;
26use axum::http::StatusCode;
27use axum::response::{IntoResponse, Response};
28use axum::Json;
29use base64::Engine as _;
30use image::codecs::gif::{GifEncoder, Repeat};
31use image::imageops::FilterType;
32use image::{Delay, Frame, RgbaImage};
33use serde_json::json;
34use tokio::sync::oneshot;
35use tokio::task::JoinHandle;
36
37use super::ui_handlers::{err_response, get_host_ipc, not_waiting_on_user, proxy_to_host_timeout, target_block_id, verified_block_id};
38use super::AppState;
39
40pub(crate) const MAX_SECONDS: u32 = 30;
42pub(crate) const MAX_FPS: u32 = 10;
44pub(crate) const DEFAULT_FPS: u32 = 5;
45pub(crate) const FRAME_WIDTH: u32 = 800;
47pub(crate) const MAX_BYTES: usize = crate::backend::task_media::MAX_IMAGE_BYTES as usize - 1024 * 1024;
49const MIN_DELAY_MS: u64 = 20;
51const FRAME_TIMEOUT: Duration = Duration::from_secs(3);
54const MAX_FAILED_IN_A_ROW: u32 = 5;
56const RETENTION: Duration = Duration::from_secs(60 * 60);
58
59#[derive(Debug, Clone)]
61pub(crate) struct Finished {
62 pub path: std::path::PathBuf,
63 pub frames: u32,
64 pub skipped: u32,
66 pub seconds: f32,
67 pub ended: &'static str,
69}
70
71pub(crate) struct GifBuilder {
74 encoder: Option<GifEncoder<SharedBuf>>,
75 buf: SharedBuf,
76 held: Option<(RgbaImage, Instant)>,
77 frames: u32,
78 last_delay_ms: u64,
79 size: Option<(u32, u32)>,
81}
82
83#[derive(Clone, Default)]
85pub(crate) struct SharedBuf(Arc<Mutex<Vec<u8>>>);
86
87impl Write for SharedBuf {
88 fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
89 self.0.lock().unwrap_or_else(|e| e.into_inner()).extend_from_slice(data);
90 Ok(data.len())
91 }
92 fn flush(&mut self) -> std::io::Result<()> {
93 Ok(())
94 }
95}
96
97impl SharedBuf {
98 fn len(&self) -> usize {
99 self.0.lock().unwrap_or_else(|e| e.into_inner()).len()
100 }
101 fn take(&self) -> Vec<u8> {
102 std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner()))
103 }
104}
105
106impl GifBuilder {
107 pub(crate) fn new() -> Self {
108 let buf = SharedBuf::default();
109 let mut encoder = GifEncoder::new_with_speed(buf.clone(), 20);
111 let _ = encoder.set_repeat(Repeat::Infinite);
112 Self { encoder: Some(encoder), buf, held: None, frames: 0, last_delay_ms: 200, size: None }
113 }
114
115 pub(crate) fn push(&mut self, frame: RgbaImage, at: Instant) -> Result<(), String> {
117 let (w, h) = *self.size.get_or_insert((frame.width(), frame.height()));
118 let frame = if frame.dimensions() == (w, h) { frame } else { image::imageops::resize(&frame, w, h, FilterType::Triangle) };
119 if let Some((prev, prev_at)) = self.held.take() {
120 let ms = at.saturating_duration_since(prev_at).as_millis() as u64;
121 self.encode(prev, ms)?;
122 }
123 self.held = Some((frame, at));
124 Ok(())
125 }
126
127 fn encode(&mut self, frame: RgbaImage, ms: u64) -> Result<(), String> {
128 let ms = ms.max(MIN_DELAY_MS);
129 self.last_delay_ms = ms;
130 let delay = Delay::from_numer_denom_ms(ms.min(u64::from(u32::MAX)) as u32, 1);
131 self.encoder
132 .as_mut()
133 .ok_or_else(|| "the recording is already finished".to_string())?
134 .encode_frame(Frame::from_parts(frame, 0, 0, delay))
135 .map_err(|e| format!("encode a frame: {e}"))?;
136 self.frames += 1;
137 Ok(())
138 }
139
140 pub(crate) fn bytes_so_far(&self) -> usize {
142 self.buf.len()
143 }
144
145 pub(crate) fn frames(&self) -> u32 {
146 self.frames + u32::from(self.held.is_some())
147 }
148
149 pub(crate) fn finish(mut self) -> Result<(Vec<u8>, u32), String> {
151 if let Some((last, _)) = self.held.take() {
152 let ms = self.last_delay_ms;
153 self.encode(last, ms)?;
154 }
155 drop(self.encoder.take());
157 if self.frames == 0 {
158 return Err("no frame was captured".to_string());
159 }
160 Ok((self.buf.take(), self.frames))
161 }
162}
163
164pub(crate) fn frame_from(bytes: &[u8]) -> Result<RgbaImage, String> {
166 let img = image::load_from_memory(bytes).map_err(|e| format!("read the capture: {e}"))?;
167 Ok(scale_frame(img.to_rgba8()))
168}
169
170pub(crate) fn scale_frame(img: RgbaImage) -> RgbaImage {
172 let mut rgba = if img.width() > FRAME_WIDTH {
173 let h = ((u64::from(img.height()) * u64::from(FRAME_WIDTH)) / u64::from(img.width())).max(1) as u32;
174 image::imageops::resize(&img, FRAME_WIDTH, h, FilterType::Triangle)
175 } else {
176 img
177 };
178 for p in rgba.pixels_mut() {
179 p.0[3] = 255;
180 }
181 rgba
182}
183
184pub(crate) fn limits(fps: Option<u32>, seconds: Option<u32>) -> (u32, u32) {
186 (fps.unwrap_or(DEFAULT_FPS).clamp(1, MAX_FPS), seconds.unwrap_or(MAX_SECONDS).clamp(1, MAX_SECONDS))
187}
188
189struct Recording {
191 stop: Option<oneshot::Sender<()>>,
193 task: JoinHandle<Result<Finished, String>>,
194}
195
196static RECORDINGS: LazyLock<Mutex<HashMap<String, Recording>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
198
199fn dir() -> std::path::PathBuf {
200 crate::backend::base::get_mux_data_dir().join("tmp/ui-recordings")
201}
202
203fn prune_old(dir: &std::path::Path) {
204 let Ok(entries) = std::fs::read_dir(dir) else { return };
205 let now = std::time::SystemTime::now();
206 for entry in entries.flatten() {
207 let path = entry.path();
208 if path.extension().and_then(|e| e.to_str()) != Some("gif") {
209 continue;
210 }
211 let aged = entry.metadata().and_then(|m| m.modified()).ok().and_then(|m| now.duration_since(m).ok());
212 if aged.is_some_and(|age| age > RETENTION) {
213 let _ = std::fs::remove_file(&path);
214 }
215 }
216}
217
218async fn capture_frame(state: &AppState, host: &super::HostIpc, block_id: &str) -> Result<RgbaImage, String> {
220 let resp = proxy_to_host_timeout(
221 state,
222 host,
223 "screenshot",
224 json!({ "block_id": block_id, "format": "jpeg", "quality": 60, "whole_viewport": true }),
225 Some(FRAME_TIMEOUT),
226 )
227 .await?;
228 tokio::task::spawn_blocking(move || frame_of_response(&resp)).await.map_err(|e| e.to_string())?
229}
230
231pub(crate) fn frame_of_response(resp: &serde_json::Value) -> Result<RgbaImage, String> {
234 if resp.get("ok").and_then(|v| v.as_bool()) != Some(true) {
235 return Err(resp.get("error").and_then(|v| v.as_str()).unwrap_or("unknown host error").to_string());
236 }
237 let encoded = resp.pointer("/data/png_base64").and_then(|v| v.as_str()).unwrap_or("");
238 let bytes = base64::engine::general_purpose::STANDARD.decode(encoded).map_err(|e| format!("decode the capture: {e}"))?;
239 let mut img = image::load_from_memory(&bytes).map_err(|e| format!("read the capture: {e}"))?.to_rgba8();
240 if let Some(crop) = resp.pointer("/data/crop").and_then(|v| serde_json::from_value::<[f64; 4]>(v.clone()).ok()) {
242 let viewport = resp.pointer("/data/viewport_width").and_then(|v| v.as_f64()).unwrap_or(0.0);
243 img = crop_to(&img, crop, viewport)?;
244 }
245 super::screenshot_redact::redact_image(resp, &mut img)?;
246 Ok(scale_frame(img))
247}
248
249pub(crate) fn crop_to(img: &RgbaImage, crop: [f64; 4], viewport_width: f64) -> Result<RgbaImage, String> {
251 if viewport_width <= 0.0 {
252 return Err("the page's width is unknown, so the pane can't be cut out of the capture".to_string());
253 }
254 let scale = f64::from(img.width()) / viewport_width;
255 let at = |v: f64, limit: u32| -> u32 { (v * scale).round().clamp(0.0, f64::from(limit)) as u32 };
256 let (x0, y0) = (at(crop[0], img.width()), at(crop[1], img.height()));
257 let (x1, y1) = (at(crop[0] + crop[2], img.width()), at(crop[1] + crop[3], img.height()));
258 if x1 <= x0 || y1 <= y0 {
259 return Err("the pane is outside the capture".to_string());
260 }
261 Ok(image::imageops::crop_imm(img, x0, y0, x1 - x0, y1 - y0).to_image())
262}
263
264async fn run(
266 state: AppState,
267 host: super::HostIpc,
268 block_id: String,
269 fps: u32,
270 seconds: u32,
271 mut stop: oneshot::Receiver<()>,
272 first: RgbaImage,
273 started: Instant,
274) -> Result<Finished, String> {
275 let every = Duration::from_millis(1000 / u64::from(fps));
276 let mut first_builder = GifBuilder::new();
277 first_builder.push(first, started)?;
278 let mut builder = Some(first_builder);
279 let (mut skipped, mut failed_in_a_row) = (0u32, 0u32);
280 let mut last_error = String::new();
281 let ended = loop {
282 if let Err((_, why)) = not_waiting_on_user(&block_id) {
285 last_error = why;
286 break "pane held";
287 }
288 let frame_started = Instant::now();
289 match capture_frame(&state, &host, &block_id).await {
290 Ok(frame) => {
291 failed_in_a_row = 0;
292 let b = builder.take().ok_or("the recording is finished")?;
293 let (b, pushed) = tokio::task::spawn_blocking(move || {
294 let mut b = b;
295 let r = b.push(frame, frame_started);
296 (b, r)
297 })
298 .await
299 .map_err(|e| e.to_string())?;
300 builder = Some(b);
301 pushed?;
302 }
303 Err(e) => {
304 skipped += 1;
305 failed_in_a_row += 1;
306 last_error = e;
307 if failed_in_a_row >= MAX_FAILED_IN_A_ROW {
308 break "capture failed";
309 }
310 }
311 }
312 if builder.as_ref().is_some_and(|b| b.bytes_so_far() >= MAX_BYTES) {
313 break "size limit";
314 }
315 if started.elapsed() >= Duration::from_secs(u64::from(seconds)) {
316 break "time limit";
317 }
318 let wait = every.saturating_sub(frame_started.elapsed());
319 tokio::select! {
320 _ = &mut stop => break "stopped",
321 _ = tokio::time::sleep(wait) => {}
322 }
323 };
324 let elapsed = started.elapsed();
325 let builder = builder.take().ok_or("the recording is finished")?;
326 let (bytes, frames) = tokio::task::spawn_blocking(move || builder.finish())
327 .await
328 .map_err(|e| e.to_string())?
329 .map_err(|e| if last_error.is_empty() { e } else { format!("{e} ({last_error})") })?;
330 let dir = dir();
331 std::fs::create_dir_all(&dir).map_err(|e| format!("create the recordings folder: {e}"))?;
332 let path = dir.join(format!("{}.gif", uuid::Uuid::new_v4()));
333 std::fs::write(&path, &bytes).map_err(|e| format!("write the recording: {e}"))?;
334 prune_old(&dir);
335 Ok(Finished { path, frames, skipped, seconds: elapsed.as_secs_f32(), ended })
336}
337
338fn response(status: &str, message: String, finished: Option<&Finished>) -> Response {
339 response_with(status, message, finished, false)
340}
341
342fn response_with(status: &str, message: String, finished: Option<&Finished>, inline: bool) -> Response {
345 use base64::Engine as _;
346 let body = UiRecordResponse {
347 status: status.to_string(),
348 message,
349 gif_base64: finished
350 .filter(|_| inline)
351 .and_then(|f| std::fs::read(&f.path).ok())
352 .map(|b| base64::engine::general_purpose::STANDARD.encode(b)),
353 path: finished.map(|f| f.path.to_string_lossy().to_string()),
354 frames: finished.map_or(0, |f| f.frames),
355 skipped: finished.map_or(0, |f| f.skipped),
356 seconds: finished.map_or(0.0, |f| f.seconds),
357 };
358 (StatusCode::OK, Json(body)).into_response()
359}
360
361pub(crate) async fn handle_ui_record(
364 State(state): State<AppState>,
365 caller: Option<axum::Extension<crate::server::caller::Caller>>,
366 Json(req): Json<UiRecordRequest>,
367) -> impl IntoResponse {
368 let who = req.auth.agent_id.clone();
369 match req.op.as_str() {
370 "start" => {
371 let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
372 Ok(b) => b,
373 Err((code, e)) => return err_response(code, e),
374 };
375 let host = match get_host_ipc(&state).await {
376 Ok(h) => h,
377 Err(e) => return err_response(StatusCode::SERVICE_UNAVAILABLE, e),
378 };
379 let (fps, seconds) = limits(req.fps, req.seconds);
380 if RECORDINGS.lock().unwrap_or_else(|e| e.into_inner()).get(&who).is_some_and(|r| !r.task.is_finished()) {
381 return err_response(
382 StatusCode::CONFLICT,
383 "you are already recording: stop that recording first (UI record, op stop)".to_string(),
384 );
385 }
386 let started = Instant::now();
389 let first = match capture_frame(&state, &host, &block_id).await {
390 Ok(f) => f,
391 Err(e) => {
392 return err_response(
393 StatusCode::BAD_GATEWAY,
394 format!("couldn't capture the pane, so nothing is recording: {e} (a minimized or hidden window can't be captured)"),
395 )
396 }
397 };
398 let (tx, rx) = oneshot::channel();
399 {
400 let mut all = RECORDINGS.lock().unwrap_or_else(|e| e.into_inner());
401 if all.get(&who).is_some_and(|r| !r.task.is_finished()) {
402 return err_response(
403 StatusCode::CONFLICT,
404 "you are already recording: stop that recording first (UI record, op stop)".to_string(),
405 );
406 }
407 let task = tokio::spawn(run(state.clone(), host, block_id.clone(), fps, seconds, rx, first, started));
408 all.insert(who.clone(), Recording { stop: Some(tx), task });
409 }
410 tracing::info!(agent_id = %who, block_id = %block_id, fps, seconds, "[ui-automation] record start");
411 response(
412 "recording",
413 format!(
414 "Recording your pane at up to {fps} frames a second for at most {seconds} seconds. Do what you want to show, then call UI record with op stop; it returns the file."
415 ),
416 None,
417 )
418 }
419 "stop" => {
420 if let Err(e) = verified_block_id(&state, caller.as_deref(), &req.auth) {
422 return err_response(StatusCode::UNAUTHORIZED, e);
423 }
424 let Some(mut rec) = RECORDINGS.lock().unwrap_or_else(|e| e.into_inner()).remove(&who) else {
425 return err_response(StatusCode::NOT_FOUND, "you have no recording: start one first (UI record, op start)".to_string());
426 };
427 if let Some(stop) = rec.stop.take() {
428 let _ = stop.send(());
429 }
430 match rec.task.await {
431 Ok(Ok(f)) => {
432 tracing::info!(agent_id = %who, path = %f.path.display(), frames = f.frames, skipped = f.skipped, ended = f.ended, "[ui-automation] record stop");
433 let mut note = if f.skipped > 0 {
434 format!(" {} frame(s) were left out because the page could not be checked for secret fields or a capture failed.", f.skipped)
435 } else {
436 String::new()
437 };
438 if f.ended == "pane held" {
439 note.push_str(" It ended early because the pane went to the user (a hand-off, an approval, a question or a pause), which is never recorded.");
440 }
441 let msg = format!(
442 "Recording saved to {} ({} frames, {:.1} s, ended: {}).{note} Look at it before you attach it (Read shows an image; open it with Pane view \"media\" to see it move), then pass its path in files of Tasks update or submit.",
443 f.path.display(),
444 f.frames,
445 f.seconds,
446 f.ended
447 );
448 response_with("saved", msg, Some(&f), req.inline)
449 }
450 Ok(Err(e)) => err_response(StatusCode::BAD_GATEWAY, format!("the recording failed: {e}")),
451 Err(e) => err_response(StatusCode::INTERNAL_SERVER_ERROR, format!("the recording stopped unexpectedly: {e}")),
452 }
453 }
454 other => err_response(StatusCode::BAD_REQUEST, format!("op is start or stop, not {other:?}")),
455 }
456}
457
458#[cfg(test)]
459#[path = "ui_record_tests.rs"]
460mod tests;