Skip to main content

agentmux_srv/server/
agent_move_here.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Move an agent here from another pane of this AgentMux.
5//!
6//! A second pane of an agent that is live in another pane is refused (`open_in_other_pane`). This
7//! is the recovery the refused pane offers beside "Go there": stop the pane that holds the agent
8//! and let the refused pane have it. The holder pane stays open, showing the same notice with the
9//! roles swapped, so the move can be undone from there.
10//! Spec: docs/specs/SPEC_AGENT_SAME_PROCESS_DUPLICATE_PANE_RECOVERY_2026_10_01.md ยง4.3.
11
12use std::time::{Duration, Instant};
13
14use crate::backend::blockcontroller::{self, persistent};
15use crate::backend::obj::{self, Block};
16use crate::backend::rpc_types::AgentMoveHereResult;
17
18use super::AppState;
19
20/// How long the holder's turn in flight may finish before its CLI process is killed.
21const MOVE_GRACE: Duration = Duration::from_secs(10);
22/// How long the claimant waits for the holder's lease to drop after the process is told to stop.
23const MOVE_WAIT: Duration = Duration::from_secs(25);
24
25/// Stop the pane that holds `block_id`'s agent, wait for the agent to be free, and tell the holder
26/// pane where it went. `Ok` with no `from_block` when no other pane held it.
27pub(crate) async fn move_here(state: &AppState, block_id: &str) -> Result<AgentMoveHereResult, String> {
28    let mstore = state.mstore.clone();
29    let id = block_id.to_string();
30    let block = tokio::task::spawn_blocking(move || mstore.get::<Block>(&id))
31        .await
32        .map_err(|e| e.to_string())?
33        .map_err(|e| e.to_string())?
34        .ok_or_else(|| "block not found".to_string())?;
35    let uid = obj::meta_get_string(&block.meta, "agentId", "");
36    if uid.is_empty() {
37        return Err("this pane has no agent".to_string());
38    }
39    let Some(holder) = persistent::lifecycle::local_holder_of(&uid, block_id) else {
40        return Ok(AgentMoveHereResult { from_block: None });
41    };
42    let stopping = blockcontroller::get_controller(&holder)
43        .as_ref()
44        .and_then(|c| c.as_any().downcast_ref::<persistent::PersistentSubprocessController>())
45        .is_some_and(|p| p.release_to_other_instance(Instant::now() + MOVE_GRACE));
46    // A holder with no process to signal may already be exiting: the wait below decides.
47    tracing::info!(block_id, holder = %holder, stopping, "agent_admission.move_here: asked the holder pane to let go");
48
49    let deadline = Instant::now() + MOVE_WAIT;
50    while persistent::lifecycle::local_holder_of(&uid, block_id).is_some() {
51        if Instant::now() >= deadline {
52            return Err("The other pane did not let go in time. Try again in a few seconds.".to_string());
53        }
54        tokio::time::sleep(Duration::from_millis(100)).await;
55    }
56    // The agent is here: the refusal this pane asked the move for no longer stands, and an Open here mark has done its work.
57    crate::backend::open_here_mark::settle_after_move(block_id, &state.mstore, &Some(state.event_bus.clone()));
58    // The pane that lost the agent says so and offers the way back.
59    super::agent_takeover::surface_failure(state, &holder, &persistent::held_elsewhere_error(block_id, false));
60    Ok(AgentMoveHereResult { from_block: Some(holder) })
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use crate::server::tests::test_state;
67
68    #[tokio::test]
69    async fn a_pane_with_no_agent_is_refused() {
70        let state = test_state();
71        let e = move_here(&state, "mh-no-such-block").await.unwrap_err();
72        assert_eq!(e, "block not found");
73    }
74}