1use axum::extract::State;
10use axum::http::StatusCode;
11use axum::response::IntoResponse;
12use axum::Json;
13use serde_json::json;
14
15use agentmux_common::api_types::{UiPressKeysRequest, UiResetShortcutsRequest, UiRunCommandRequest, UiSetShortcutRequest, UiShortcutsListRequest};
16
17use super::ui_handlers::{err_response, proxy_data, target_block_id};
18use super::AppState;
19
20fn refused_command(command: &str) -> Option<&'static str> {
29 match command {
30 "files:deletePermanently" => Some("it can't be undone"),
31 "browser:pauseAll" | "browser:resumeAll" => Some("only the user pauses or resumes all agent browsing"),
33 _ => None,
34 }
35}
36
37fn shortcut_target(
43 own: &str,
44 requested: Option<&str>,
45 other: impl FnOnce(&str) -> Result<String, (StatusCode, String)>,
46) -> Result<String, (StatusCode, String)> {
47 match requested.map(str::trim).filter(|t| !t.is_empty()) {
48 None => Ok(own.to_string()),
49 Some(t) if t == own => Ok(own.to_string()),
50 Some(t) => other(t),
51 }
52}
53
54pub(crate) async fn handle_ui_shortcuts_list(
56 State(state): State<AppState>,
57 caller: Option<axum::Extension<crate::server::caller::Caller>>,
58 Json(req): Json<UiShortcutsListRequest>,
59) -> impl IntoResponse {
60 let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, None) {
61 Ok(b) => b,
62 Err((code, e)) => return err_response(code, e),
63 };
64 proxy_data(&state, "list_shortcuts", json!({ "block_id": block_id }), std::time::Duration::from_secs(10)).await
65}
66
67pub(crate) async fn handle_ui_run_command(
69 State(state): State<AppState>,
70 caller: Option<axum::Extension<crate::server::caller::Caller>>,
71 Json(req): Json<UiRunCommandRequest>,
72) -> impl IntoResponse {
73 let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, None) {
74 Ok(b) => b,
75 Err((code, e)) => return err_response(code, e),
76 };
77 if let Some(why) = refused_command(&req.command) {
78 return err_response(StatusCode::FORBIDDEN, format!("{} is not available to agents: {why}", req.command));
79 }
80 if req.command == "pane:close" {
81 return close_pane(&state, &req).await;
82 }
83 let target = match shortcut_target(&block_id, req.target.as_deref(), |t| {
84 target_block_id(&state, caller.as_deref(), &req.auth, Some(t))
85 }) {
86 Ok(t) => t,
87 Err((code, e)) => return err_response(code, e),
88 };
89 tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, command = %req.command, "[ui-automation] run command");
90 proxy_data(
91 &state,
92 "run_command",
93 json!({ "block_id": block_id, "command": req.command, "target": target }),
94 std::time::Duration::from_secs(10),
95 )
96 .await
97}
98
99pub(crate) async fn handle_ui_press_keys(
101 State(state): State<AppState>,
102 caller: Option<axum::Extension<crate::server::caller::Caller>>,
103 Json(req): Json<UiPressKeysRequest>,
104) -> impl IntoResponse {
105 let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, None) {
106 Ok(b) => b,
107 Err((code, e)) => return err_response(code, e),
108 };
109 let target = match shortcut_target(&block_id, req.target.as_deref(), |t| {
110 target_block_id(&state, caller.as_deref(), &req.auth, Some(t))
111 }) {
112 Ok(t) => t,
113 Err((code, e)) => return err_response(code, e),
114 };
115 tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, keys = %req.keys, "[ui-automation] press keys");
116 proxy_data(
117 &state,
118 "press_keys",
119 json!({ "block_id": block_id, "keys": req.keys, "target": target }),
120 std::time::Duration::from_secs(10),
121 )
122 .await
123}
124
125pub(crate) fn agent_name(agent_id: &str) -> String {
128 name_or_id(crate::server::native_memory_handlers::find_active_registry_record_by_slug(agent_id).map(|r| r.data.instance_name), agent_id)
129}
130
131fn name_or_id(name: Option<String>, agent_id: &str) -> String {
132 name.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| agent_id.to_string())
133}
134
135const MAX_BINDINGS: usize = 8;
137const MAX_KEY_LEN: usize = 64;
138const MAX_WHEN_LEN: usize = 200;
139
140pub(crate) async fn handle_ui_set_shortcut(
144 State(state): State<AppState>,
145 caller: Option<axum::Extension<crate::server::caller::Caller>>,
146 Json(req): Json<UiSetShortcutRequest>,
147) -> impl IntoResponse {
148 let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, None) {
149 Ok(b) => b,
150 Err((code, e)) => return err_response(code, e),
151 };
152 if let Some(why) = refused_command(&req.command) {
153 return err_response(StatusCode::FORBIDDEN, format!("{} is not available to agents: {why}", req.command));
154 }
155 if req.command.trim().is_empty() {
156 return err_response(StatusCode::BAD_REQUEST, "`command` is required: a command id from `shortcuts`".to_string());
157 }
158 if req.bindings.len() > MAX_BINDINGS || req.bindings.iter().any(|k| k.len() > MAX_KEY_LEN) || req.when.as_deref().is_some_and(|w| w.len() > MAX_WHEN_LEN) {
159 return err_response(StatusCode::BAD_REQUEST, format!("at most {MAX_BINDINGS} keys of {MAX_KEY_LEN} characters, and a `when` of {MAX_WHEN_LEN}"));
160 }
161 tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, command = %req.command, keys = ?req.bindings, "[ui-automation] set shortcut");
162 proxy_data(
163 &state,
164 "set_shortcut",
165 json!({ "block_id": block_id, "command": req.command, "bindings": req.bindings, "when": req.when, "agent": agent_name(&req.auth.agent_id) }),
166 std::time::Duration::from_secs(10),
167 )
168 .await
169}
170
171pub(crate) async fn handle_ui_reset_shortcuts(
173 State(state): State<AppState>,
174 caller: Option<axum::Extension<crate::server::caller::Caller>>,
175 Json(req): Json<UiResetShortcutsRequest>,
176) -> impl IntoResponse {
177 let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, None) {
178 Ok(b) => b,
179 Err((code, e)) => return err_response(code, e),
180 };
181 let command = req.command.as_deref().map(str::trim).filter(|c| !c.is_empty());
182 if command.is_none() && !req.all {
183 return err_response(StatusCode::BAD_REQUEST, "give `command`, or `all: true` to put every shortcut back on its default".to_string());
184 }
185 if let Some((command, why)) = command.and_then(|c| refused_command(c).map(|why| (c, why))) {
186 return err_response(StatusCode::FORBIDDEN, format!("{command} is not available to agents: {why}"));
187 }
188 tracing::info!(agent_id = %req.auth.agent_id, block_id = %block_id, command = ?command, all = req.all, "[ui-automation] reset shortcuts");
189 proxy_data(
190 &state,
191 "reset_shortcuts",
192 json!({ "block_id": block_id, "command": command, "all": req.all, "agent": agent_name(&req.auth.agent_id) }),
193 std::time::Duration::from_secs(10),
194 )
195 .await
196}
197
198async fn close_pane(state: &AppState, req: &UiRunCommandRequest) -> axum::response::Response {
203 let Some(target) = req.target.as_deref().map(str::trim).filter(|t| !t.is_empty()) else {
204 return err_response(
205 StatusCode::BAD_REQUEST,
206 "pane:close needs `target`, the pane to close (the user gets 30 seconds to keep it)".to_string(),
207 );
208 };
209 let (code, body) = crate::server::app_api::pane::close_pane_as(
210 state,
211 &req.auth.agent_id,
212 target,
213 Some("UI command pane:close"),
214 "UI command",
215 )
216 .await;
217 match code {
218 StatusCode::OK => Json(json!({ "ok": true, "data": { "ran": true, "closed": body } })).into_response(),
219 StatusCode::ACCEPTED => Json(json!({ "ok": true, "data": {
220 "ran": false,
221 "pending": body,
222 "reason": "its user has 30 seconds to keep it, and it closes after that unless they do",
223 } }))
224 .into_response(),
225 _ => err_response(code, body.get("error").and_then(|e| e.as_str()).unwrap_or("close failed").to_string()),
226 }
227}
228
229#[cfg(test)]
230mod tests {
231 #[test]
232 fn the_person_is_told_the_agents_name_and_falls_back_to_its_id() {
233 assert_eq!(super::name_or_id(Some("Opaz".into()), "opaz"), "Opaz");
234 assert_eq!(super::name_or_id(Some(" Loap-3 ".into()), "loap-loap-2-loap-3"), "Loap-3");
235 assert_eq!(super::name_or_id(Some("".into()), "opaz"), "opaz");
236 assert_eq!(super::name_or_id(None, "opaz"), "opaz");
237 }
238
239 use super::{refused_command, shortcut_target};
240 use axum::http::StatusCode;
241
242 #[test]
243 fn refuses_only_the_commands_the_owner_ruled_out() {
244 assert!(refused_command("files:deletePermanently").is_some());
245 assert!(refused_command("browser:pauseAll").is_some());
247 assert!(refused_command("browser:resumeAll").is_some());
248 assert!(refused_command("pane:close").is_none(), "pane:close goes through ClosePane's undo");
249 for allowed in ["tab:close", "split:right", "pane:replaceWithLauncher", "files:trash"] {
250 assert!(refused_command(allowed).is_none(), "{allowed} keeps its own confirmation or undo");
251 }
252 }
253
254 #[test]
257 fn a_shortcut_acts_on_the_callers_own_pane_or_one_it_drives() {
258 let refuse = |_: &str| -> Result<String, (StatusCode, String)> { Err((StatusCode::FORBIDDEN, "not yours".into())) };
259 let accept = |t: &str| -> Result<String, (StatusCode, String)> { Ok(t.to_string()) };
260 assert_eq!(shortcut_target("mine", None, refuse).unwrap(), "mine");
262 assert_eq!(shortcut_target("mine", Some(""), refuse).unwrap(), "mine");
263 assert_eq!(shortcut_target("mine", Some(" "), refuse).unwrap(), "mine");
264 assert_eq!(shortcut_target("mine", Some("mine"), refuse).unwrap(), "mine");
266 assert_eq!(shortcut_target("mine", Some(" theirs "), accept).unwrap(), "theirs");
268 let (code, why) = shortcut_target("mine", Some("theirs"), refuse).unwrap_err();
269 assert_eq!((code, why.as_str()), (StatusCode::FORBIDDEN, "not yours"));
270 }
271}