Skip to main content

agentmux_srv/server/
ui_shortcuts.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agent-facing shortcuts (`ListShortcuts` / `RunCommand` / `PressKeys`, and `UI` `bind` / `reset`),
5//! docs/specs/PLAN_SHORTCUTS_VERIFIED_AND_APP_API_2026_10_10.md §4. Same
6//! identity model as the rest of `ui_handlers`: the caller's own pane is
7//! derived from its verified identity, never taken from the request.
8
9use 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
20// Each acts in the window that holds the caller's own pane (owner decision §8.1): the
21// host resolves that window from the verified block and calls the page's
22// `window.__agentmux_shortcuts` (frontend keybindings/app-api.ts), which
23// reveals `target` (a pane in that window, in any tab) before acting on it.
24
25/// Commands no agent may run: agents are first-class owners, so only what
26/// has no protection. A permanent delete can't be undone. The frontend
27/// refuses it too, and PressKeys of any key bound to it.
28fn refused_command(command: &str) -> Option<&'static str> {
29    match command {
30        "files:deletePermanently" => Some("it can't be undone"),
31        // The person's emergency stop on agent browsing: not for an agent to turn off, or to turn on and lock itself out.
32        "browser:pauseAll" | "browser:resumeAll" => Some("only the user pauses or resumes all agent browsing"),
33        _ => None,
34    }
35}
36
37/// The pane a command or key press acts on: the caller's own pane (`own`) when `requested` is
38/// absent or names it, else the pane `other` accepts (a browser pane it opened), else the
39/// refusal. A command is the person's own action as far as the app can tell, so an agent
40/// never runs one against the focused pane (which may be another agent's, or theirs) or any
41/// pane it doesn't drive.
42fn 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
54/// `POST /api/v1/ui/shortcuts/list` — backs `ListShortcuts`.
55pub(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
67/// `POST /api/v1/ui/shortcuts/run` — backs `RunCommand`.
68pub(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
99/// `POST /api/v1/ui/shortcuts/press` — backs `PressKeys`.
100pub(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
125/// What the person calls the agent: the name it was given, not the lowercase id it signs its requests with. The id
126/// stands in for an agent the registry does not know.
127pub(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
135/// The most keys, and the longest key or `when`, a request may carry: a command has a handful of keys.
136const MAX_BINDINGS: usize = 8;
137const MAX_KEY_LEN: usize = 64;
138const MAX_WHEN_LEN: usize = 200;
139
140/// `POST /api/v1/ui/shortcuts/set` — backs `UI` action `bind`. The page applies the same edit the Settings view
141/// makes and refuses what an agent may not do (a key another command has, a key the system takes); the person is
142/// told and can undo it.
143pub(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
171/// `POST /api/v1/ui/shortcuts/reset` — backs `UI` action `reset`.
172pub(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
198/// RunCommand `pane:close`: the pane named by `target`, closed the way
199/// ClosePane closes it (`app_api::pane::close_pane_as`): it waits 30 s for
200/// its user to keep it, and the answer says so. The key itself closes the
201/// focused pane at once, with no undo, so the page never runs it for MuxAPI.
202async 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        // The person's emergency stop on agent browsing is theirs to turn on and off.
246        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    /// A command or key press acts on the caller's own pane unless it names a pane it drives:
255    /// never the focused pane, which may be another agent's or the user's.
256    #[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        // No target: its own pane, not whatever is focused.
261        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        // Its own pane by name needs no further check.
265        assert_eq!(shortcut_target("mine", Some("mine"), refuse).unwrap(), "mine");
266        // Another pane goes through the ownership check, whose answer stands.
267        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}