Skip to main content

agentmux_srv/server/
needs_key.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A moved agent that waits for its route's Vault key takes the route once the key is in the Vault
5//! (`model_gateway::pending_route`, docs/specs/SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER_2026_11_24.md 7.3). Run whenever the Vault
6//! announces a change, so a key the person adds from the request, the Vault pane or anywhere else is found.
7
8use super::AppState;
9use crate::backend::model_gateway::pending_route::{self, Settled};
10use crate::backend::vault::route_key;
11
12/// Settles every agent that waits for a route: the ones whose key is here now take their route. Tells the windows when one did, so the
13/// `Needs a key` tag leaves its tile.
14pub(crate) fn settle_all(state: &AppState) {
15    let Ok(defs) = state.mstore.agent_def_list() else { return };
16    let (taken, relaunch_these) = settle_each(state, &defs, |label| route_key::present(&state.identity_store, label));
17    if taken {
18        state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
19    }
20    relaunch_off_the_runtime(state, relaunch_these);
21}
22
23/// Settles each agent that waits: whether anything changed (the windows are told), and the agents that took their route, the only ones
24/// whose panes are restarted onto it. `key_present` says whether the Vault has a key, by label.
25fn settle_each(state: &AppState, defs: &[crate::backend::storage::AgentDefinition], key_present: impl Fn(&str) -> bool) -> (bool, Vec<String>) {
26    let mut taken = false;
27    let mut relaunch_these = Vec::new();
28    for def in defs {
29        // One read per agent: nearly every agent waits for nothing.
30        if pending_route::pending_of(&state.mstore, &def.id).is_none() {
31            continue;
32        }
33        match pending_route::settle(&state.mstore, &def.id, &key_present) {
34            Settled::Taken(choice) => {
35                tracing::info!(agent = %def.id, route = %choice.route, "a moved agent took its route: its key is here");
36                taken = true;
37                relaunch_these.push(def.id.clone());
38            }
39            Settled::Dropped => taken = true,
40            Settled::Waiting(_) | Settled::Nothing => {}
41        }
42    }
43    (taken, relaunch_these)
44}
45
46/// The Vault announces a change from async handlers, and a restart can wait on a pane's controller (a lock, and for an idle pane a stop
47/// and a start): it runs on a blocking thread, as a route switch's does, so adding a key never holds up a runtime worker.
48fn relaunch_off_the_runtime(state: &AppState, agents: Vec<String>) {
49    if agents.is_empty() {
50        return;
51    }
52    let state = state.clone();
53    let run = move || {
54        for id in &agents {
55            relaunch(&state, id);
56        }
57    };
58    match tokio::runtime::Handle::try_current() {
59        Ok(runtime) => {
60            runtime.spawn_blocking(run);
61        }
62        // Not on the runtime: nothing to hold up.
63        Err(_) => run(),
64    }
65}
66
67/// A pane of the agent that runs already is on its harness's own sign-in: the route's gateway environment is installed only when a
68/// pane starts (`launch::carry_for_block`), so saving the choice would leave it there until someone restarted it. Each such pane is
69/// restarted at the end of its turn, as for any change of route, and the relaunch gives it the route. A pane that is not running, or
70/// is a one-shot (a container agent's), reads the route when it starts.
71fn relaunch(state: &AppState, def_id: &str) {
72    let (restarted, next_turn, failed) = crate::server::account_episodes::restart_panes_of(state, def_id);
73    for why in &failed {
74        tracing::warn!(agent = %def_id, %why, "a moved agent took its route, but a pane could not be restarted onto it");
75    }
76    tracing::info!(agent = %def_id, restarted, next_turn, failed = failed.len(), "a moved agent's panes were sent to its new route");
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use crate::backend::model_gateway::pending_route::Pending;
83
84    #[tokio::test]
85    async fn an_agent_that_waits_for_a_key_this_computer_lacks_keeps_waiting() {
86        let state = crate::server::tests::test_state();
87        let mut def = crate::backend::storage::agents::test_agent_def("needs-key-1", "Waiter", "claude", "host", 1, "");
88        state.mstore.agent_def_insert(&mut def).unwrap();
89        let first = crate::backend::model_gateway::catalog::ROUTES.first().expect("the catalog has a route");
90        let pending = Pending { harness: first.harness.to_string(), route: first.id.to_string(), model: first.default_model.to_string(), key_label: first.key_label.to_string() };
91        pending_route::set_pending(&state.mstore, "needs-key-1", &pending).unwrap();
92        settle_all(&state);
93        assert_eq!(pending_route::pending_of(&state.mstore, "needs-key-1"), Some(pending), "no key here: it keeps waiting");
94        assert!(crate::backend::model_gateway::launch::choice_of(&state.mstore, "needs-key-1").is_none());
95    }
96
97    /// An agent that waits for the catalog's first route, in a state of its own.
98    fn waiting(state: &AppState, id: &str) -> crate::backend::storage::AgentDefinition {
99        let mut def = crate::backend::storage::agents::test_agent_def(id, id, "claude", "host", 1, "");
100        state.mstore.agent_def_insert(&mut def).unwrap();
101        let first = crate::backend::model_gateway::catalog::ROUTES.first().expect("the catalog has a route");
102        let pending = Pending { harness: first.harness.to_string(), route: first.id.to_string(), model: first.default_model.to_string(), key_label: first.key_label.to_string() };
103        pending_route::set_pending(&state.mstore, id, &pending).unwrap();
104        def
105    }
106
107    #[tokio::test]
108    async fn only_an_agent_that_took_its_route_is_sent_to_restart_its_panes() {
109        let state = crate::server::tests::test_state();
110        let (took, still, chose) = (waiting(&state, "restart-took"), waiting(&state, "restart-still"), waiting(&state, "restart-chose"));
111        // The person chose a route of their own for the third meanwhile: its pending one is dropped, not taken.
112        let first = crate::backend::model_gateway::catalog::ROUTES.first().unwrap();
113        crate::backend::model_gateway::launch::set_choice(&state.mstore, "restart-chose", first.harness, first.id, first.default_model).unwrap();
114        let (changed, relaunch) = settle_each(&state, &[took], |_| true);
115        assert!(changed);
116        assert_eq!(relaunch, vec!["restart-took".to_string()], "taken: its panes restart");
117        let (changed, relaunch) = settle_each(&state, &[still], |_| false);
118        assert!(!changed && relaunch.is_empty(), "still waiting: nothing changed, nothing restarts");
119        let (changed, relaunch) = settle_each(&state, &[chose], |_| true);
120        assert!(changed && relaunch.is_empty(), "dropped: the windows are told, no pane restarts");
121    }
122
123    #[tokio::test]
124    async fn taking_a_route_with_no_pane_open_has_nothing_to_restart() {
125        let state = crate::server::tests::test_state();
126        let mut def = crate::backend::storage::agents::test_agent_def("needs-key-3", "Paneless", "claude", "host", 1, "");
127        state.mstore.agent_def_insert(&mut def).unwrap();
128        assert_eq!(crate::server::account_episodes::restart_panes_of(&state, "needs-key-3"), (0, 0, Vec::new()));
129        relaunch(&state, "needs-key-3");
130    }
131
132    #[tokio::test]
133    async fn an_agent_that_waits_for_nothing_is_left_alone() {
134        let state = crate::server::tests::test_state();
135        let mut def = crate::backend::storage::agents::test_agent_def("needs-key-2", "Plain", "claude", "host", 1, "");
136        state.mstore.agent_def_insert(&mut def).unwrap();
137        settle_all(&state);
138        assert!(pending_route::pending_of(&state.mstore, "needs-key-2").is_none());
139    }
140}