Skip to main content

agentmux_srv/server/app_api/
remote_pane_view.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents open` with `host` and `view: true` (`POST /api/v1/agent/open_view`): puts a pane over an agent of another
5//! computer on the caller's own window, through the same path `pane.open` takes for the caller (an agent's pane goes in
6//! a tab of its own group, without the person's focus). The pane opens watching: a block's meta can't turn driving on
7//! (driving is a person's click in the pane, remote-pane-drive.ts), so an agent can put a view on its person's screen
8//! and never drive it (docs/specs/SPEC_REMOTE_PANES_WATCH_AND_DRIVE_AN_AGENT_ON_ANOTHER_COMPUTER_2026_11_20.md ยง6, D4).
9//!
10//! Only a computer this one is paired with can be shown: pairing is the person's act (the Swarm's pairing panel).
11
12use axum::extract::State;
13use axum::http::StatusCode;
14use axum::response::{IntoResponse, Response};
15use axum::Json;
16use serde::Deserialize;
17use serde_json::json;
18
19use crate::backend::tower::peers::{Peer, Peers};
20
21use super::AppState;
22
23/// The route's body: the computer as `Agents list` names it (`name`, or `name/channel` when it runs several AgentMux
24/// instances) and the agent on it.
25#[derive(Debug, Deserialize)]
26pub(crate) struct OpenViewReq {
27    pub host: String,
28    pub agent: String,
29    /// The caller's own pane, as `pane.open` takes it: the view goes in that pane's tab (`handle_pane_open` checks it
30    /// against the caller's token and replaces one that is not its own).
31    #[serde(default)]
32    pub block_id: Option<String>,
33}
34
35/// The paired computer `host` names: its name (any case) and, when given, its channel. Several of one name are
36/// refused with what tells them apart, never guessed.
37fn computer_named<'a>(computers: &'a [Peer], host: &str) -> Result<&'a Peer, String> {
38    let (name, channel) = match host.trim().split_once('/') {
39        Some((name, rest)) => (name.trim(), Some(rest.split('/').next().unwrap_or("").trim())),
40        None => (host.trim(), None),
41    };
42    if name.is_empty() {
43        return Err("Agents open view: name the computer in host".to_string());
44    }
45    let found: Vec<&Peer> = computers
46        .iter()
47        .filter(|p| p.computer && p.hostname.trim().eq_ignore_ascii_case(name))
48        .filter(|p| channel.map_or(true, |c| c.is_empty() || p.channel.eq_ignore_ascii_case(c)))
49        .collect();
50    match found.as_slice() {
51        [] => Err(format!(
52            "Agents open view: this computer is not paired with {name}. Its person pairs it from the Swarm (click one of its agents and paste the host's pairing link); nothing is shown until then."
53        )),
54        [one] => Ok(one),
55        several => {
56            let channels: Vec<&str> = several.iter().map(|p| p.channel.as_str()).collect();
57            Err(format!("Agents open view: {name} is paired more than once ({}); say which with host \"{name}/<channel>\".", channels.join(", ")))
58        }
59    }
60}
61
62/// The block meta of a pane over `agent` of the paired computer `computer`: the same the Swarm's click gives it
63/// (open-remote-pane.ts), and nothing that says driving. `provider` is the agent's provider as its feed named it: the
64/// pane reads its transcript in that provider's format, so a pane that didn't know it would read a Codex or Gemini
65/// agent's lines as Claude's.
66fn view_meta(computer: &str, agent: &str, provider: Option<&str>) -> crate::backend::obj::MetaMapType {
67    let mut meta = crate::backend::obj::MetaMapType::new();
68    meta.insert("view".into(), json!("agent"));
69    meta.insert("agentId".into(), json!(format!("remote:{computer}:{agent}")));
70    meta.insert("remote:computer".into(), json!(computer));
71    meta.insert("remote:agent".into(), json!(agent));
72    meta.insert("agentName".into(), json!(agent));
73    // A provider this build doesn't know has no format to give: the pane reads it as the default.
74    if let Some((provider, config)) = provider.and_then(|p| crate::backend::providers::get_provider(p).map(|c| (p, c))) {
75        meta.insert("agentProvider".into(), json!(provider));
76        meta.insert("agentOutputFormat".into(), json!(config.styled_output_format));
77    }
78    meta
79}
80
81/// How long the open waits for the agent's feed to say which provider it is. A computer that is slow or away costs this
82/// much, and the pane opens anyway (it shows "reconnecting" and reads the default format until it is open).
83const PROVIDER_WAIT: std::time::Duration = std::time::Duration::from_secs(4);
84
85/// The provider of `agent` on the paired computer `peer_id`, from the first snapshot of its feed, which is closed again
86/// (the pane opens its own). None when the feed said nothing in time or ended.
87async fn provider_of(peer_id: &str, agent: &str) -> Option<String> {
88    let panes = crate::backend::remote_panes::pane::Panes::global();
89    let pane = panes.open(peer_id, agent).ok()?;
90    let deadline = tokio::time::Instant::now() + PROVIDER_WAIT;
91    let found = loop {
92        let facts = pane.facts();
93        if !facts.provider.is_empty() {
94            break Some(facts.provider);
95        }
96        let ended = matches!(facts.connection, Some(crate::backend::remote_panes::pane::Connection::Ended { .. }));
97        if ended || tokio::time::Instant::now() >= deadline {
98            break None;
99        }
100        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
101    };
102    panes.close(peer_id, agent);
103    found
104}
105
106fn refused(status: StatusCode, error: String) -> Response {
107    (status, Json(json!({ "error": error }))).into_response()
108}
109
110/// `POST /api/v1/agent/open_view`.
111pub(crate) async fn handle_agent_open_view(
112    State(state): State<AppState>,
113    grant: Option<axum::Extension<crate::backend::container::credential::ContainerGrant>>,
114    caller: Option<axum::Extension<crate::server::caller::Caller>>,
115    Json(req): Json<OpenViewReq>,
116) -> Response {
117    let agent = req.agent.trim();
118    if agent.is_empty() {
119        return refused(StatusCode::BAD_REQUEST, "Agents open view: name the agent in agent_id".to_string());
120    }
121    let computers = Peers::global().computers();
122    let computer = match computer_named(&computers, &req.host) {
123        Ok(c) => c,
124        Err(e) => return refused(StatusCode::BAD_REQUEST, e),
125    };
126    let provider = provider_of(&computer.id, agent).await;
127    let cmd = crate::backend::rpc_types::CommandPaneOpenData {
128        view: "agent".to_string(),
129        meta: Some(view_meta(&computer.id, agent, provider.as_deref())),
130        split_reference_block_id: req.block_id.as_deref().map(str::trim).filter(|b| !b.is_empty()).map(str::to_string),
131        ..Default::default()
132    };
133    // The same route as any pane an agent opens: its placement, its tab, no focus taken, and the person told.
134    // A container agent's open takes this route too: the meta is srv's own, so its snapshot step (for files) is not asked.
135    crate::server::http_open::open_pane_for(state, grant, caller, cmd, true).await
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    fn peer(id: &str, hostname: &str, channel: &str, computer: bool) -> Peer {
143        Peer {
144            id: id.into(),
145            hostname: hostname.into(),
146            host: "10.0.0.2".into(),
147            port: 1,
148            fingerprint: String::new(),
149            device_id: String::new(),
150            paired_ms: 0,
151            computer,
152            channel: channel.into(),
153        }
154    }
155
156    #[test]
157    fn a_computer_is_found_by_its_name_in_any_case_and_only_if_it_was_paired_to_watch() {
158        let all = [peer("a", "Area54", "stable", true), peer("t", "Tower", "stable", false)];
159        assert_eq!(computer_named(&all, "area54").unwrap().id, "a");
160        // A Tower peer is not a computer to watch: nothing is shown of it.
161        assert!(computer_named(&all, "Tower").unwrap_err().contains("not paired"));
162        assert!(computer_named(&all, "gamerlove").unwrap_err().contains("not paired"));
163        assert!(computer_named(&all, "  ").unwrap_err().contains("name the computer"));
164    }
165
166    #[test]
167    fn two_instances_of_one_host_are_told_apart_by_channel_never_guessed() {
168        let all = [peer("s", "Area54", "stable", true), peer("d", "Area54", "dev", true)];
169        let err = computer_named(&all, "Area54").unwrap_err();
170        assert!(err.contains("paired more than once") && err.contains("stable") && err.contains("dev"), "{err}");
171        assert_eq!(computer_named(&all, "Area54/dev").unwrap().id, "d");
172        assert_eq!(computer_named(&all, "Area54/stable/install").unwrap().id, "s");
173        assert!(computer_named(&all, "Area54/nightly").unwrap_err().contains("not paired"));
174    }
175
176    #[test]
177    fn the_pane_it_opens_names_the_computer_and_agent_and_says_nothing_of_driving() {
178        let meta = view_meta("c1", "Korp", None);
179        assert_eq!(meta["view"], json!("agent"));
180        assert_eq!(meta["agentId"], json!("remote:c1:Korp"));
181        assert_eq!(meta["remote:computer"], json!("c1"));
182        assert_eq!(meta["remote:agent"], json!("Korp"));
183        assert!(meta.keys().all(|k| !k.contains("driv") && !k.contains("send")), "{:?}", meta.keys().collect::<Vec<_>>());
184        assert!(!meta.contains_key("agentProvider"), "no provider is known: the pane reads the default");
185    }
186
187    #[test]
188    fn the_agents_provider_gives_the_pane_its_transcript_format() {
189        let codex = view_meta("c1", "Pell", Some("codex"));
190        assert_eq!(codex["agentProvider"], json!("codex"));
191        assert_eq!(codex["agentOutputFormat"], json!("codex-json"));
192        let claude = view_meta("c1", "Korp", Some("claude"));
193        assert_eq!(claude["agentOutputFormat"], json!("claude-stream-json"));
194        // A provider this build doesn't know is not guessed at.
195        assert!(!view_meta("c1", "X", Some("no-such-provider")).contains_key("agentOutputFormat"));
196    }
197
198    /// A container agent holds a grant, which sends a file open through a snapshot step that refuses every view but
199    /// the file ones. A view srv built itself from a paired computer is not a file: it skips that step.
200    #[tokio::test]
201    async fn a_container_agent_may_open_a_view_srv_built_but_not_one_it_wrote() {
202        use crate::server::http_open::open_pane_for;
203        let grant = || {
204            Some(axum::Extension(crate::backend::container::credential::ContainerGrant {
205                block_id: "no-such-block".into(),
206                agent_token: None,
207            }))
208        };
209        let view = || crate::backend::rpc_types::CommandPaneOpenData {
210            view: "agent".to_string(),
211            meta: Some(view_meta("c1", "Korp", None)),
212            ..Default::default()
213        };
214        let state = crate::server::tests::test_state();
215        let written = open_pane_for(state.clone(), grant(), None, view(), false).await;
216        assert_eq!(written.status(), StatusCode::FORBIDDEN, "a request the container wrote still goes through the snapshot step");
217        let built = open_pane_for(state, grant(), None, view(), true).await;
218        assert_ne!(built.status(), StatusCode::FORBIDDEN, "the view srv built is not turned away as a file open");
219    }
220}