Skip to main content

agentmux_srv/server/app_api/
remote_panes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Remote panes on the viewing computer (`remotepane.*`; `backend::remote_panes`,
5//! docs/specs/SPEC_REMOTE_PANES_WATCH_AND_DRIVE_AN_AGENT_ON_ANOTHER_COMPUTER_2026_11_20.md phase 2): the computers
6//! this one paired with to watch their agents, and the window's panes showing one.
7//!
8//! The window's, not an agent API: an agent connection is refused (pairing is a person's act, ยง5.1; an agent opening a
9//! view comes through `Agents open`, D4). A pane's changes are published as `remotepane:<computer>:<agent>`.
10
11use super::*;
12use crate::backend::mps_events::RemotePaneChanged;
13use crate::backend::remote_panes::{host, pane::Panes, wire};
14
15/// The newest lines a pane is given when it opens; older ones it reads with `remotepane.range`.
16const OPEN_TAIL: usize = 2000;
17/// The most lines one `remotepane.range` gives.
18const MAX_RANGE: u32 = 5000;
19
20fn the_windows(ctx: &RpcContext) -> Result<(), String> {
21    ctx.operator_only("remote panes are the AgentMux window's, not an agent API")
22}
23
24/// The app's panes, publishing their changes on `broker`.
25pub(crate) fn panes(broker: Arc<crate::backend::mps::Broker>) -> &'static Panes {
26    let publish: crate::backend::remote_panes::pane::OnChange = Arc::new(move |computer: &str, agent: &str, change| {
27        broker.publish_event_for::<RemotePaneChanged>(&wire::event_id(computer, agent), &wire::change(change), vec![], 0);
28    });
29    Panes::install_global(Panes::new(crate::backend::tower::peers::Peers::global()).with_on_change(publish))
30}
31
32/// The blocks an event says are gone: a deleted pane, or every pane of a deleted tab or workspace.
33fn blocks_gone(event: &agentmux_common::ipc::Event) -> Vec<String> {
34    use agentmux_common::ipc::Event;
35    match event {
36        Event::BlockDeleted { block_id, .. } => vec![block_id.clone()],
37        Event::TabDeleted { block_ids, .. } | Event::WorkspaceDeleted { block_ids, .. } => block_ids.clone(),
38        _ => Vec::new(),
39    }
40}
41
42/// Lets go of a remote pane's feed when its block is deleted, whether or not the window got to say so (a window closed
43/// or reloaded under the pane never runs its cleanup).
44pub(crate) fn spawn_block_closer(mut events: tokio::sync::broadcast::Receiver<agentmux_common::ipc::Event>) {
45    tokio::spawn(async move {
46        loop {
47            match events.recv().await {
48                Ok(event) => {
49                    let gone = blocks_gone(&event);
50                    if let (false, Some(panes)) = (gone.is_empty(), Panes::installed()) {
51                        gone.iter().for_each(|block| panes.close_for(block));
52                    }
53                }
54                Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
55                Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
56            }
57        }
58    });
59}
60
61fn computers(panes: &Panes) -> RemoteComputersResult {
62    RemoteComputersResult { computers: panes.peers().computers().iter().map(wire::computer).collect() }
63}
64
65pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
66    let panes = panes(state.broker.clone());
67    engine.register_typed(COMMAND_REMOTE_PANE_COMPUTERS, move |_req: Option<NoArgsReq>, ctx| async move {
68        the_windows(&ctx)?;
69        Ok(computers(panes))
70    });
71    let hostname = state.hostname.clone();
72    engine.register_typed(COMMAND_REMOTE_PANE_PAIR, move |req: RemotePanePairReq, ctx| {
73        let hostname = hostname.clone();
74        async move {
75            the_windows(&ctx)?;
76            let peer = host::pair(panes.peers(), &req.link, &hostname).await?;
77            Ok(wire::computer(&peer))
78        }
79    });
80    engine.register_typed(COMMAND_REMOTE_PANE_FORGET, move |req: RemotePaneForgetReq, ctx| async move {
81        the_windows(&ctx)?;
82        // The keychain deletes may wait on the OS: off the async workers.
83        let id = req.id.clone();
84        tokio::task::spawn_blocking(move || panes.peers().forget(&id)).await.map_err(|e| e.to_string())??;
85        // Its open panes end now, not at their feed's next reconnect.
86        panes.end_computer(&req.id);
87        Ok(computers(panes))
88    });
89    engine.register_typed(COMMAND_REMOTE_PANE_OPEN, move |req: RemotePaneOpenReq, ctx| async move {
90        the_windows(&ctx)?;
91        open(panes, &req)
92    });
93    register_reads(engine, panes);
94}
95
96fn register_reads(engine: &Arc<WshRpcEngine>, panes: &'static Panes) {
97    engine.register_typed(COMMAND_REMOTE_PANE_RANGE, move |req: RemotePaneRangeReq, ctx| async move {
98        the_windows(&ctx)?;
99        let pane = panes.get(&req.computer, &req.agent).ok_or("That remote agent isn't open here.")?;
100        Ok(wire::lines(&pane, req.offset, req.limit.min(MAX_RANGE) as usize))
101    });
102    engine.register_typed(COMMAND_REMOTE_PANE_OLDER, move |req: RemotePaneOlderReq, ctx| async move {
103        the_windows(&ctx)?;
104        let pane = panes.get(&req.computer, &req.agent).ok_or("That remote agent isn't open here.")?;
105        pane.read_older(panes.peers()).await?;
106        let from = pane.ring.lock().from_line();
107        Ok(wire::lines(&pane, from, 0))
108    });
109    engine.register_typed(COMMAND_REMOTE_PANE_SEND, move |req: RemotePaneSendReq, ctx| async move {
110        the_windows(&ctx)?;
111        send(panes, &req).await
112    });
113    engine.register_typed(COMMAND_REMOTE_PANE_CLOSE, move |req: RemotePaneCloseReq, ctx| async move {
114        the_windows(&ctx)?;
115        panes.close_for(&req.block_id);
116        Ok(())
117    });
118}
119
120/// `remotepane.send`: the person's message to the remote agent, signed as this computer and named for the person at
121/// this window (their claim, which the host records as such). The host decides whether this computer may drive.
122pub(crate) async fn send(panes: &Panes, req: &RemotePaneSendReq) -> Result<RemotePaneSendResult, String> {
123    if req.message.trim().is_empty() {
124        return Err("There is nothing to send.".into());
125    }
126    if uuid::Uuid::parse_str(&req.message_id).is_err() {
127        return Err("That message has no valid id: try sending it again.".into());
128    }
129    let host = host::Host::connect(panes.peers(), &req.computer).await?;
130    let user = std::env::var("USERNAME").or_else(|_| std::env::var("USER")).ok().filter(|u| !u.is_empty());
131    match host.send(&req.agent, &req.message, &req.message_id, user.as_deref()).await {
132        Ok((_, body)) => Ok(RemotePaneSendResult { status: body["state"].as_str().unwrap_or("accepted").to_string() }),
133        Err(refusal) => Err(refusal.send_text(&host.peer.hostname)),
134    }
135}
136
137/// `remotepane.open`: the pane `block_id` shows the agent; what is held of it now.
138pub(crate) fn open(panes: &Panes, req: &RemotePaneOpenReq) -> Result<RemotePaneOpenResult, String> {
139    let pane = panes.open_for(&req.block_id, &req.computer, &req.agent)?;
140    Ok(wire::opened(&pane, OPEN_TAIL))
141}
142
143#[cfg(test)]
144mod block_closer_tests {
145    use super::blocks_gone;
146    use agentmux_common::ipc::Event;
147
148    #[test]
149    fn a_deleted_block_tab_or_workspace_names_the_blocks_that_went() {
150        let block = Event::BlockDeleted { block_id: "b1".into(), tab_id: "t".into(), version: 1 };
151        assert_eq!(blocks_gone(&block), vec!["b1".to_string()]);
152        assert!(blocks_gone(&Event::TabDeleted { tab_id: "t".into(), workspace_id: "w".into(), block_ids: vec!["b1".into(), "b2".into()], version: 1 }).len() == 2);
153    }
154}