Skip to main content

agentmux_srv/server/app_api/
agent_open_remote.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `agents.open` for an agent on another machine (`remote_ops::agent_ops`, spec ยง4.3): it opens the
5//! named agent into a tab of its own for the caller, "Team (slug@machine)", made the first time and
6//! reused after, the way a leader's workers open in "<Leader> team" (`agent_spawn::team`). The tab is
7//! made and the agent opened without focus, so the person's view stays where it is: nothing is
8//! brought forward and no tab but this one changes. With no window open the tab goes in a workspace
9//! of its own, and the agent runs there until a window shows it.
10
11use axum::http::StatusCode;
12use serde_json::{json, Value};
13
14use crate::backend::obj::Workspace;
15use crate::backend::rpc_types::CommandAgentOpenData;
16use crate::backend::service::WebCallType;
17
18use super::agent_lifecycle::{is_running, target_of};
19use super::agent_spawn::team::tab_named;
20use super::AppState;
21
22/// One caller's find-or-make of its tab at a time, so two opens together make one tab.
23static TAB_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
24
25/// The tab `who`'s agents open in.
26fn tab_name(who: &str) -> String {
27    format!("Team ({who})")
28}
29
30/// The workspace a new tab goes in: a window's, the main one first, else any that has tabs, else a
31/// workspace made for it (no window is opened onto it).
32async fn workspace_for_new_tab(state: &AppState, name: &str) -> Result<String, String> {
33    if let Some((_, workspace_id)) = crate::server::service::live_windows(&state.mstore).into_iter().next() {
34        return Ok(workspace_id);
35    }
36    let workspaces = state.mstore.get_all::<Workspace>().unwrap_or_default();
37    match workspaces.iter().find(|w| !w.tabids.is_empty()) {
38        Some(w) => Ok(w.oid.clone()),
39        None => super::layout::create_empty_workspace(state, name).await,
40    }
41}
42
43/// The caller's tab, made (not shown) if it isn't there yet: its id and name.
44async fn callers_tab(state: &AppState, who: &str) -> Result<(String, String), String> {
45    let _one_at_a_time = TAB_LOCK.lock().await;
46    let name = tab_name(who);
47    let workspaces = state.mstore.get_all::<Workspace>().unwrap_or_default();
48    if let Some(existing) = workspaces.iter().find_map(|w| tab_named(&state.mstore, w, &name)) {
49        return Ok((existing, name));
50    }
51    let workspace_id = workspace_for_new_tab(state, &name).await?;
52    let call = WebCallType {
53        service: "workspace".to_string(),
54        method: "CreateTab".to_string(),
55        uicontext: None,
56        args: vec![json!(workspace_id), json!(name), json!(false)],
57    };
58    let made = crate::server::service::handle_create_tab(state, &call).await;
59    match made.data.as_ref().and_then(|d| d.as_str()) {
60        Some(id) if made.error.is_none() => Ok((id.to_string(), name)),
61        _ => Err(format!("no tab '{name}' could be made: {}", made.error.unwrap_or_default())),
62    }
63}
64
65/// The status for `agent.open`'s own error vocabulary (the HTTP route's, `http_open`), plus a live
66/// instance elsewhere, which is a conflict.
67fn open_status(e: &str) -> StatusCode {
68    if e.starts_with("AGENT_LIVE_ELSEWHERE") {
69        StatusCode::CONFLICT
70    } else if ["AGENT_NOT_FOUND", "TEMPLATE_NOT_OPENABLE", "INVALID_PROVIDER", "CLI_NOT_AVAILABLE"].iter().any(|p| e.starts_with(p)) {
71        StatusCode::BAD_REQUEST
72    } else {
73        StatusCode::INTERNAL_SERVER_ERROR
74    }
75}
76
77/// `open` of `agent` for the agent `who` (`slug@machine`) on another machine. Opening an agent that
78/// already runs is not a start, so it does not use the sender's minute; one that has to start counts
79/// against the sender's start limit like `Agents start`.
80pub(crate) async fn run_remote(state: &AppState, who: &str, agent: &str) -> Result<Value, (StatusCode, String)> {
81    let blocking = state.clone();
82    let named = agent.to_string();
83    let target = tokio::task::spawn_blocking(move || target_of(&blocking, &named))
84        .await
85        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Agents open: {e}")))?
86        .map_err(|r| (r.status, r.message))?;
87    if !is_running(&target) {
88        crate::server::start_rate::allow(state, &format!("remote:{who}")).map_err(|e| (StatusCode::TOO_MANY_REQUESTS, e))?;
89    }
90    let (tab_id, tab_name) = callers_tab(state, who).await.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Agents open: {e}")))?;
91    let cmd = CommandAgentOpenData {
92        agent_id: target.agent_id.clone(),
93        tab_id: Some(tab_id.clone()),
94        split_direction: None,
95        split_reference_block_id: None,
96        focus: Some(false),
97        into_block_id: None,
98    };
99    let opened = super::agent_open::open_agent_impl(state, cmd).await.map_err(|e| (open_status(&e), format!("Agents open {}: {e}", target.name)))?;
100    Ok(json!({
101        "agent": target.name, "agent_id": target.agent_id, "created": opened.created,
102        "tab_id": opened.tab_id, "block_id": opened.block_id, "status": opened.status,
103        // An agent already shown in another tab stays there.
104        "tab_name": (opened.tab_id == tab_id).then_some(tab_name),
105        "note": "opened without focus; Agents stop ends it",
106    }))
107}
108
109#[cfg(test)]
110#[path = "agent_open_remote_tests.rs"]
111mod tests;