agentmux_srv/server/
browser_find.rs1use axum::extract::State;
12use axum::http::StatusCode;
13use axum::response::IntoResponse;
14use axum::Json;
15use serde_json::json;
16
17use agentmux_common::api_types::{UiBrowserElementMatch, UiBrowserFindRequest};
18
19use crate::server::ui_handlers::{err_response, proxy_data, target_block_id};
20use crate::server::AppState;
21
22fn host_body(block_id: &str, query: &UiBrowserElementMatch) -> Result<serde_json::Value, String> {
25 let role = query.role.as_deref().map(str::trim).filter(|r| !r.is_empty());
26 if query.name.trim().is_empty() && role.is_none() {
27 return Err("find needs a name (part of the element's accessible name), a role, or both".to_string());
28 }
29 Ok(json!({ "block_id": block_id, "role": role, "name": query.name, "exact": query.exact }))
30}
31
32pub(crate) async fn handle_ui_browser_find(
33 State(state): State<AppState>,
34 caller: Option<axum::Extension<crate::server::caller::Caller>>,
35 Json(req): Json<UiBrowserFindRequest>,
36) -> impl IntoResponse {
37 let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
40 Ok(b) => b,
41 Err((code, e)) => return err_response(code, e),
42 };
43 let body = match host_body(&block_id, &req.query) {
44 Ok(b) => b,
45 Err(e) => return err_response(StatusCode::BAD_REQUEST, e),
46 };
47 tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, "[ui-automation] browser find");
48 proxy_data(&state, "find", body, std::time::Duration::from_secs(30)).await
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 fn q(role: Option<&str>, name: &str, exact: bool) -> UiBrowserElementMatch {
56 UiBrowserElementMatch { role: role.map(str::to_string), name: name.to_string(), exact }
57 }
58
59 #[test]
60 fn the_host_gets_the_pane_and_the_query() {
61 let body = host_body("b1", &q(Some(" button "), "Save", true)).unwrap();
62 assert_eq!(body, json!({ "block_id": "b1", "role": "button", "name": "Save", "exact": true }));
63 let body = host_body("b1", &q(None, "Save", false)).unwrap();
64 assert_eq!(body["role"], serde_json::Value::Null);
65 assert!(host_body("b1", &q(Some("dialog"), "", false)).is_ok(), "a role alone is enough");
66 }
67
68 #[test]
69 fn a_find_for_nothing_in_particular_is_refused() {
70 let e = host_body("b1", &q(Some(" "), " ", false)).unwrap_err();
71 assert!(e.starts_with("find needs a name"), "{e}");
72 }
73
74 #[test]
75 fn the_request_reads_its_query_beside_the_signature() {
76 let req: UiBrowserFindRequest = serde_json::from_value(json!({
77 "agent_id": "a", "ts_secs": 1, "sig": "s", "pane": "p", "role": "link", "name": "Next"
78 }))
79 .unwrap();
80 assert_eq!(req.query, q(Some("link"), "Next", false));
81 assert_eq!(req.pane.as_deref(), Some("p"));
82 }
83}