Skip to main content

agentmux_srv/server/
http_open.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Pane and agent open.
5//! Split out of server/mod.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.1).
6
7use super::*;
8
9/// `POST /api/v1/pane/open` — open a pane (editor/term/browser/…).
10///
11/// Called by `agentmux-mcp`'s `OpenEditor` tool. Thin HTTP wrapper over
12/// `app_api::open_pane` (the same logic the WebSocket `pane.open` RPC uses):
13/// creates the block, enqueues the layout action, and broadcasts the updates
14/// so the frontend renders the pane. Body is `CommandPaneOpenData`.
15pub(super) async fn handle_pane_open(
16    State(state): State<AppState>,
17    grant: Option<axum::Extension<crate::backend::container::credential::ContainerGrant>>,
18    caller: Option<axum::Extension<super::caller::Caller>>,
19    Json(req): Json<crate::backend::rpc_types::CommandPaneOpenData>,
20) -> impl IntoResponse {
21    open_pane_for(state, grant, caller, req, false).await
22}
23
24/// `handle_pane_open`'s work. `built_by_srv` is true only for a request srv itself built from checked facts (the
25/// view of a paired computer's agent, whose meta no caller wrote): a container agent's snapshot step, which exists
26/// to confine what a request can read from its workspace, has nothing to confine there and would refuse the view.
27pub(crate) async fn open_pane_for(
28    state: AppState,
29    grant: Option<axum::Extension<crate::backend::container::credential::ContainerGrant>>,
30    caller: Option<axum::Extension<super::caller::Caller>>,
31    mut req: crate::backend::rpc_types::CommandPaneOpenData,
32    built_by_srv: bool,
33) -> axum::response::Response {
34    let by_agent = grant.is_some() || is_agent(caller.as_ref().map(|c| &c.0));
35    quiet_pane_open(&mut req, by_agent);
36    // An agent's placement is checked before anything is opened. The identity that opened the pane is the
37    // caller's token's, never a field of the request.
38    let opener = caller.as_ref().and_then(|c| c.0.uid()).filter(|_| by_agent).map(str::to_string);
39    let own = by_agent.then(|| app_api::agent_own_tab::own_panes(&state.mstore, grant.as_ref().map(|g| g.0.block_id.as_str()), opener.as_deref()));
40    if let (true, Err(e)) = (by_agent, app_api::floater_place::check(&req)) {
41        return (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response();
42    }
43    // A floating open counts against the ten a minute an agent may open and place (`pane_place`), so a loop of them is stopped.
44    if let (true, Some(agent)) = (by_agent && req.floating == Some(true), opener.as_deref()) {
45        if let Err(e) = super::deeplink_guard::check_place_rate(agent) {
46            return (StatusCode::TOO_MANY_REQUESTS, Json(json!({ "error": e }))).into_response();
47        }
48    }
49    // A container agent opens a read-only snapshot of a file in its workspace, or a Files pane confined to a folder of it, never a path a window would read freely.
50    let mut snapshot = None;
51    if let (Some(axum::Extension(grant)), false) = (grant, built_by_srv) {
52        // Reads and copies a file: off the async workers.
53        let taking = {
54            let (state, block) = (state.clone(), grant.block_id.clone());
55            tokio::task::spawn_blocking(move || super::container_pane_snapshot::open_for(&state, &block, req)).await
56        };
57        match taking.unwrap_or_else(|e| Err(format!("the snapshot couldn't be taken: {e}"))) {
58            Ok((checked, taken)) => (req, snapshot) = (checked, taken),
59            Err(e) => return (StatusCode::FORBIDDEN, Json(json!({ "error": e }))).into_response(),
60        }
61    }
62    if let Err(e) = check_meta(&state, caller.as_ref().and_then(|c| c.0.uid()), &mut req) {
63        return (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response();
64    }
65    // Set after the snapshot step, which may have rebuilt the request.
66    let kept_note = own.and_then(|own| app_api::agent_own_tab::keep_in_own_tab(&state.mstore, &own, &mut req));
67    // A pane on an SSH host reads and writes there as the user, with their
68    // SSH keys: over HTTP (where agents call from) that takes the agent's
69    // signed identity and the user's consent for that host, as `Shell` does
70    // (remote terminals spec §8.2). Named as the field or inside `meta`.
71    let mut opened_by_agent = None;
72    let mut opening = None;
73    if let Some(conn) = ssh_connection_of(&req) {
74        let block = req.split_reference_block_id.clone().unwrap_or_default();
75        let agent = match app_api::connections::verified_agent(&state, &block, req.auth.as_ref()) {
76            Ok(a) => a,
77            Err(e) => return (StatusCode::FORBIDDEN, Json(json!({ "error": e }))).into_response(),
78        };
79        let what = format!(
80            "open {} in {}",
81            req.file.as_deref().or(req.cwd.as_deref()).unwrap_or("a pane"),
82            req.view
83        );
84        if let Err(e) = app_api::connections::consent_for_ssh(&state, &block, &agent, &conn, &what).await {
85            return (StatusCode::FORBIDDEN, Json(json!({ "error": e }))).into_response();
86        }
87        // Until the pane is noted below, an install on this host asks.
88        opening = Some(crate::backend::remote::helper_consent::begin_agent_open(&conn));
89        opened_by_agent = Some(agent);
90    }
91    let title = req.title.clone();
92    // Set last: the snapshot step above may have rebuilt the request.
93    req.opener = opener.clone();
94    let floating = req.floating == Some(true);
95    // An agent that names no place gets a tab of its own pane group, not a split.
96    app_api::agent_tab_default::apply(&state, by_agent, opener.as_deref(), &mut req);
97    match app_api::open_pane(&state, req).await {
98        Ok(result) => {
99            if by_agent {
100                announce_agent_open(&state, &result.block_id, &result.tab_id, &result.view, title);
101            }
102            crate::server::pane_openers::note_docked(opener.as_deref(), &result, floating);
103            // The pane is the agent's: installing the helper from it is
104            // always asked about (SPEC_REMOTES_PANE_2026_10_05.md §4.9).
105            if let Some(agent) = &opened_by_agent {
106                crate::backend::remote::helper_consent::note_agent_pane(&result.block_id, agent);
107            }
108            drop(opening);
109            let mut body = json!(result);
110            if let Some(snap) = &snapshot {
111                snap.opened(&result.block_id);
112            }
113            let notes: Vec<String> = kept_note.into_iter().chain(snapshot.as_ref().map(|s| s.note())).collect();
114            if !notes.is_empty() {
115                body["note"] = json!(notes.join(" "));
116            }
117            (StatusCode::OK, Json(body)).into_response()
118        }
119        Err(e) => {
120            if let Some(snap) = &snapshot {
121                snap.discard();
122            }
123            (pane_open_error_status(&e), Json(json!({ "error": e }))).into_response()
124        }
125    }
126}
127
128/// The caller's `meta`, with srv's own keys taken out: a named browser profile only if the user lets the agent use it.
129fn check_meta(state: &AppState, who: Option<&str>, req: &mut crate::backend::rpc_types::CommandPaneOpenData) -> Result<(), String> {
130    let Some(meta) = req.meta.as_mut() else { return Ok(()) };
131    crate::server::browser_owner::strip_srv_only_keys(meta);
132    crate::server::browser_identity::check_new_tab(state, meta)
133        .and_then(|()| crate::server::browser_identity::check_agent_may_use(meta, who.unwrap_or_default()))
134}
135
136/// The HTTP status for a `pane.open` that failed: the caller's own mistake (a missing or invalid argument, a view
137/// that does not exist) is 400, an agent already at its floating-pane limit is 429, anything else is srv's (500).
138pub(crate) fn pane_open_error_status(e: &str) -> StatusCode {
139    if e.starts_with("MISSING_ARG") || e.starts_with("INVALID_VIEW") || e.starts_with("INVALID_ARG") {
140        StatusCode::BAD_REQUEST
141    } else if e.starts_with("FLOATER_LIMIT") {
142        StatusCode::TOO_MANY_REQUESTS
143    } else {
144        StatusCode::INTERNAL_SERVER_ERROR
145    }
146}
147
148/// Whether the caller is an agent AgentMux knows by its token. A person's own shell (`muxopen`, `muxsh`)
149/// calls the same routes and keeps its `focus`.
150pub(crate) fn is_agent(caller: Option<&super::caller::Caller>) -> bool {
151    caller.and_then(super::caller::Caller::uid).is_some()
152}
153
154/// Tell the windows an agent opened a pane. The one the person is in offers to show it; the agent's own open
155/// took neither their tab nor their focus.
156pub(crate) fn announce_agent_open(state: &AppState, block_id: &str, tab_id: &str, view: &str, title: Option<String>) {
157    let event = crate::backend::mps_events::PaneAgentOpenedEvent {
158        block_id: block_id.to_string(),
159        tab_id: tab_id.to_string(),
160        view: view.to_string(),
161        title: title.filter(|t| !t.trim().is_empty()),
162    };
163    state.broker.publish_event::<crate::backend::mps_events::PaneAgentOpened>(&event, vec![], 0);
164}
165
166/// What an agent's open does about focus: nothing. An agent's open never takes the person's tab, focus or
167/// caret, whatever `focus` it sent (docs/reports/REPORT_ACTION_RESULTS_ALWAYS_VISIBLE_ACROSS_WINDOWS_2026_10_31.md
168/// §4 item 9); a person's open (`agent` false) is left as sent.
169pub(crate) fn quiet_pane_open(req: &mut crate::backend::rpc_types::CommandPaneOpenData, agent: bool) {
170    if agent {
171        req.focus = Some(false);
172    }
173}
174
175/// [`quiet_pane_open`] for `agent.open`, single or in a batch.
176pub(crate) fn quiet_agent_open(req: &mut crate::backend::rpc_types::CommandAgentOpenData, agent: bool) {
177    if agent {
178        req.focus = Some(false);
179    }
180}
181
182/// The SSH connection a pane.open names (the field, or `connection` in a
183/// caller-supplied `meta`), in its canonical form; `None` for this computer
184/// or WSL.
185fn ssh_connection_of(req: &crate::backend::rpc_types::CommandPaneOpenData) -> Option<String> {
186    let from_meta = req
187        .meta
188        .as_ref()
189        .and_then(|m| m.get("connection"))
190        .and_then(|v| v.as_str());
191    [req.connection.as_deref(), from_meta]
192        .into_iter()
193        .flatten()
194        .find_map(|c| match crate::backend::remote::ConnTarget::parse(c.trim()) {
195            Ok(t @ crate::backend::remote::ConnTarget::Ssh(_)) => Some(t.name()),
196            _ => None,
197        })
198}
199
200/// `POST /api/v1/agent/open` — launch an agent into a pane (idempotent: an
201/// agent already open in the target tab returns its existing block with
202/// `created: false`, same as the RPC path).
203///
204/// Called by `agentmux-mcp`'s `OpenAgent` tool. Thin HTTP wrapper over
205/// `app_api::open_agent_impl` — the same logic the WebSocket `agent.open`
206/// RPC uses. Body is `CommandAgentOpenData` (`agent_id` by id or name;
207/// optional `tab_id`/`focus`/split placement).
208pub(super) async fn handle_agent_open(
209    State(state): State<AppState>,
210    caller: Option<axum::Extension<super::caller::Caller>>,
211    Json(mut req): Json<crate::backend::rpc_types::CommandAgentOpenData>,
212) -> impl IntoResponse {
213    app_api::agent_block::default_to_callers_tab(&state.mstore, caller.as_ref().map(|c| &c.0), &mut req);
214    let by_agent = is_agent(caller.as_ref().map(|c| &c.0));
215    quiet_agent_open(&mut req, by_agent);
216    match app_api::open_agent_impl(&state, req).await {
217        Ok(result) => {
218            // An agent already open is not news; a pane that just appeared is.
219            if by_agent && result.created {
220                announce_agent_open(&state, &result.block_id, &result.tab_id, "agent", None);
221            }
222            (StatusCode::OK, Json(json!(result))).into_response()
223        }
224        Err(e) => (open_error_status(&e), Json(json!({ "error": e }))).into_response(),
225    }
226}
227
228/// The HTTP status for `agent.open`'s own error vocabulary. AGENT_NOT_FOUND /
229/// TEMPLATE_NOT_OPENABLE / INVALID_PROVIDER / CLI_NOT_AVAILABLE are the caller's
230/// problem (a bad target, or a CLI that could not be installed); CLI_INSTALLING
231/// is neither — the CLI is on its way, so the same request will succeed shortly
232/// (503, retryable); anything else is a server-side failure.
233fn open_error_status(e: &str) -> StatusCode {
234    if e.starts_with("CLI_INSTALLING") {
235        StatusCode::SERVICE_UNAVAILABLE
236    } else if e.starts_with("AGENT_NOT_FOUND")
237        || e.starts_with("TEMPLATE_NOT_OPENABLE")
238        || e.starts_with("INVALID_PROVIDER")
239        || e.starts_with("CLI_NOT_AVAILABLE")
240    {
241        StatusCode::BAD_REQUEST
242    } else {
243        StatusCode::INTERNAL_SERVER_ERROR
244    }
245}
246
247#[cfg(test)]
248mod quiet_open_tests {
249    use super::*;
250
251    #[tokio::test]
252    async fn an_agents_open_is_announced_to_the_windows_with_the_title_it_gave() {
253        let state = crate::server::tests::test_state();
254        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
255        let rec = seen.clone();
256        state.broker.add_observer(std::sync::Arc::new(move |ev: &crate::backend::mps::MuxEvent| {
257            if ev.event == "pane:agentopened" {
258                rec.lock().unwrap().push(ev.data.clone().unwrap_or_default());
259            }
260        }));
261        announce_agent_open(&state, "b1", "t1", "editor", Some("notes.md".into()));
262        announce_agent_open(&state, "b2", "t1", "agent", Some("  ".into()));
263        let seen = seen.lock().unwrap();
264        assert_eq!(seen[0], json!({ "block_id": "b1", "tab_id": "t1", "view": "editor", "title": "notes.md" }));
265        assert_eq!(seen[1], json!({ "block_id": "b2", "tab_id": "t1", "view": "agent" }), "a blank title is no title");
266    }
267
268    /// Only an agent's open is announced: a person's own shell (`muxopen`) took the focus it asked for.
269    #[test]
270    fn the_routes_agents_open_through_announce_only_for_an_agent() {
271        let whole = include_str!("http_open.rs");
272        let production = &whole[..whole.find("#[cfg(test)]").unwrap()];
273        assert_eq!(production.matches("if by_agent").count(), 2, "pane.open and agent.open each announce, for an agent only");
274    }
275
276    #[test]
277    fn an_agents_open_never_asks_for_focus_whatever_it_sent() {
278        for sent in [None, Some(true), Some(false)] {
279            let mut pane = crate::backend::rpc_types::CommandPaneOpenData { focus: sent, ..Default::default() };
280            quiet_pane_open(&mut pane, true);
281            assert_eq!(pane.focus, Some(false), "pane.open {sent:?}");
282            let mut person = crate::backend::rpc_types::CommandPaneOpenData { focus: sent, ..Default::default() };
283            quiet_pane_open(&mut person, false);
284            assert_eq!(person.focus, sent, "a person's shell keeps its focus {sent:?}");
285            let mut agent = crate::backend::rpc_types::CommandAgentOpenData {
286                agent_id: "a".into(),
287                tab_id: None,
288                split_direction: None,
289                split_reference_block_id: None,
290                focus: sent,
291                into_block_id: None,
292            };
293            quiet_agent_open(&mut agent, true);
294            assert_eq!(agent.focus, Some(false), "agent.open {sent:?}");
295            quiet_agent_open(&mut agent, false);
296            assert_eq!(agent.focus, Some(false), "false stays false {sent:?}");
297        }
298    }
299
300    /// The routes agents call apply it: a handler that stopped would give an agent the person's focus again.
301    #[test]
302    fn every_route_an_agent_opens_through_applies_it() {
303        // Each handler's own body: the text from its `fn` to the next item, so these lines are not the match.
304        let whole = include_str!("http_open.rs");
305        let production = &whole[..whole.find("#[cfg(test)]").unwrap()];
306        let body_of = |name: &str| {
307            let from = production.find(&format!("async fn {name}(")).unwrap_or_else(|| panic!("{name} is gone"));
308            let rest = &production[from..];
309            &rest[..rest.find("
310}
311").unwrap_or(rest.len())]
312        };
313        assert!(body_of("open_pane_for").contains("quiet_pane_open(&mut req, "), "pane.open over HTTP");
314        assert!(body_of("handle_pane_open").contains("open_pane_for("), "pane.open reaches it");
315        let view = include_str!("app_api/remote_pane_view.rs");
316        assert!(view.contains("open_pane_for("), "Agents open with a view reaches it");
317        assert!(body_of("handle_agent_open").contains("quiet_agent_open(&mut req, "), "agent.open over HTTP");
318        let many = include_str!("app_api/agent_open_many.rs");
319        let many = &many[many.find("async fn handle_agent_open_many(").expect("the batch handler is gone")..];
320        assert!(many[..many.find("
321}").unwrap_or(many.len())].contains("quiet_agent_open(cmd, "), "agent.open in a batch");
322    }
323}
324
325#[cfg(test)]
326mod connection_tests {
327    use super::*;
328    use crate::backend::rpc_types::CommandPaneOpenData;
329
330    fn cmd(view: &str, connection: Option<&str>, meta: Option<serde_json::Value>) -> CommandPaneOpenData {
331        serde_json::from_value(serde_json::json!({
332            "view": view,
333            "file": "/home/u/a.txt",
334            "connection": connection,
335            "meta": meta,
336        }))
337        .unwrap()
338    }
339
340    #[test]
341    fn the_ssh_host_a_pane_open_names_is_found_wherever_it_is() {
342        assert_eq!(ssh_connection_of(&cmd("editor", Some("user@box"), None)).as_deref(), Some("user@box"));
343        assert_eq!(
344            ssh_connection_of(&cmd("files", None, Some(serde_json::json!({ "connection": "box:2222" })))).as_deref(),
345            Some("box:2222")
346        );
347        assert_eq!(ssh_connection_of(&cmd("editor", Some("local"), None)), None);
348        assert_eq!(ssh_connection_of(&cmd("editor", Some("wsl://Ubuntu"), None)), None);
349        assert_eq!(ssh_connection_of(&cmd("editor", None, None)), None);
350    }
351
352    #[test]
353    fn a_pane_on_a_connection_gets_it_in_its_meta_and_media_is_refused_there() {
354        let meta = app_api::pane::build_pane_meta(&cmd("editor", Some("user@box"), None)).unwrap();
355        assert_eq!(meta.get("connection"), Some(&serde_json::json!("user@box")));
356        assert_eq!(meta.get("file"), Some(&serde_json::json!("/home/u/a.txt")));
357        let local = app_api::pane::build_pane_meta(&cmd("editor", Some("local"), None)).unwrap();
358        assert!(local.get("connection").is_none());
359        let err = app_api::pane::build_pane_meta(&cmd("media", Some("user@box"), None)).unwrap_err();
360        assert!(err.starts_with("INVALID_ARG"), "{err}");
361    }
362}
363
364#[cfg(test)]
365mod open_error_status_tests {
366    use super::*;
367
368    #[test]
369    fn a_cli_that_is_still_installing_is_retryable_not_the_callers_fault() {
370        assert_eq!(
371            open_error_status("CLI_INSTALLING: claude 2.1.285 is still being installed"),
372            StatusCode::SERVICE_UNAVAILABLE
373        );
374    }
375
376    #[test]
377    fn the_callers_own_mistakes_are_400s() {
378        for e in [
379            "AGENT_NOT_FOUND: x",
380            "TEMPLATE_NOT_OPENABLE: x",
381            "INVALID_PROVIDER: x",
382            "CLI_NOT_AVAILABLE: x could not be installed",
383        ] {
384            assert_eq!(open_error_status(e), StatusCode::BAD_REQUEST, "{e}");
385        }
386    }
387
388    #[test]
389    fn anything_else_is_a_server_failure() {
390        assert_eq!(
391            open_error_status("agent.open: meta serialize: boom"),
392            StatusCode::INTERNAL_SERVER_ERROR
393        );
394    }
395}