Skip to main content

agentmux_srv_core/backend/tower/
peers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Other AgentMux computers on the LAN in Tower
5//! (SPEC_TOWER_TASK_MANAGER_PANE_2026_10_08.md §8.3): this computer pairs as
6//! a viewer device of the other one, the way a phone does, and reads its
7//! processes from the viewer listener.
8//!
9//! - **Pairing:** the other computer's pairing link (`agentmux://pair?…`,
10//!   its "Pair a device" panel) carries its address, viewer port, certificate
11//!   fingerprint and a one-time code. [`pair`] redeems the code for a viewer
12//!   token over TLS pinned to that fingerprint (`viewer::client`).
13//! - **What is kept:** the peer's address, port and fingerprint in
14//!   `tower-peers.json` in the data directory; the token in the secret store
15//!   (the OS keychain), never in the file.
16//! - **Reading:** `GET /agentmux/viewer/procs` with the token. The other
17//!   computer answers only if its user turned sharing on, and its user can
18//!   revoke this device from their paired-device list.
19//! - **A moved peer:** the fingerprint, not the address, is what is trusted,
20//!   so when the stored address doesn't answer, the address LAN discovery
21//!   now has for that hostname is tried, and kept if it answers.
22
23use std::path::PathBuf;
24use std::sync::Mutex;
25use std::time::Duration;
26
27use serde::{Deserialize, Serialize};
28
29use crate::backend::rpc_types::{TowerPeerInfo, TowerSnapshot};
30use crate::backend::viewer::client::pinned_client;
31
32/// `TowerSampleReq::connection` for a paired computer: `peer:<id>`.
33pub const PEER_PREFIX: &str = "peer:";
34
35pub const FILE: &str = "tower-peers.json";
36const TIMEOUT: Duration = Duration::from_secs(8);
37
38/// One paired computer, as kept on disk (no secret here).
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct Peer {
41    pub id: String,
42    pub hostname: String,
43    pub host: String,
44    pub port: u16,
45    pub fingerprint: String,
46    /// This computer's device id on the peer (what its user revokes).
47    pub device_id: String,
48    pub paired_ms: i64,
49    /// Paired as a computer that watches the peer's agents (`backend::remote_panes`): it signs with a key of its
50    /// own, kept in the secret store beside its token. The peer lets such a pairing read only its agents, so Tower
51    /// doesn't list it.
52    #[serde(default)]
53    pub computer: bool,
54    /// The channel of the instance it paired with, as that instance said at pairing (its reply's `channel`); empty for a
55    /// pairing made before it was kept. What tells one instance of a host that runs several from the others.
56    #[serde(default)]
57    pub channel: String,
58}
59
60impl Peer {
61    fn info(&self) -> TowerPeerInfo {
62        TowerPeerInfo {
63            connection: format!("{PEER_PREFIX}{}", self.id),
64            hostname: self.hostname.clone(),
65            address: format!("{}:{}", self.host, self.port),
66            paired_ms: self.paired_ms,
67        }
68    }
69
70    pub fn secret_key(&self) -> String {
71        format!("tower-peer:{}", self.id)
72    }
73
74    /// Where a computer pairing's signing key is kept in the secret store.
75    pub fn signing_key_secret(&self) -> String {
76        format!("tower-peer-key:{}", self.id)
77    }
78
79    pub(crate) fn url(&self, host: &str, path: &str) -> String {
80        url_at(host, self.port, path)
81    }
82}
83
84fn url_at(host: &str, port: u16, path: &str) -> String {
85    // An IPv6 address needs brackets in a URL.
86    let host = if host.contains(':') && !host.starts_with('[') { format!("[{host}]") } else { host.to_string() };
87    format!("https://{host}:{port}{path}")
88}
89
90/// The viewer ports `host`'s AgentMux instances advertise now, from the LAN
91/// discovery probe a phone sends (UDP 47891): the answering instance's, then
92/// its siblings' (other channels on that host). Empty when nothing answers.
93async fn probe_viewer_ports(host: &str) -> Vec<u16> {
94    use crate::backend::lan::discovery::{UDP_DISCOVERY_PORT, UDP_PROBE_TYPE, UDP_PROTOCOL_VERSION};
95    let Ok(ip) = host.parse::<std::net::IpAddr>() else { return Vec::new() };
96    let bind = if ip.is_ipv6() { "[::]:0" } else { "0.0.0.0:0" };
97    let Ok(sock) = tokio::net::UdpSocket::bind(bind).await else { return Vec::new() };
98    let probe = serde_json::json!({ "type": UDP_PROBE_TYPE, "v": UDP_PROTOCOL_VERSION }).to_string();
99    if sock.send_to(probe.as_bytes(), (ip, UDP_DISCOVERY_PORT)).await.is_err() {
100        return Vec::new();
101    }
102    let mut buf = vec![0u8; 8192];
103    match tokio::time::timeout(Duration::from_millis(1500), sock.recv_from(&mut buf)).await {
104        Ok(Ok((n, _))) => viewer_ports_of(&buf[..n]),
105        _ => Vec::new(),
106    }
107}
108
109/// The viewer ports in a discovery reply: its own, then its siblings'.
110fn viewer_ports_of(reply: &[u8]) -> Vec<u16> {
111    let Ok(v) = serde_json::from_slice::<serde_json::Value>(reply) else { return Vec::new() };
112    let port = |x: &serde_json::Value| x.get("viewer_port").and_then(|p| p.as_u64()).and_then(|p| u16::try_from(p).ok());
113    let mut ports: Vec<u16> = port(&v).into_iter().collect();
114    for s in v.get("siblings").and_then(|s| s.as_array()).into_iter().flatten() {
115        if let Some(p) = port(s).filter(|p| !ports.contains(p)) {
116            ports.push(p);
117        }
118    }
119    ports
120}
121
122/// What a pairing link says.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct Link {
125    pub host: String,
126    pub port: u16,
127    pub fingerprint: String,
128    pub code: String,
129    pub hostname: String,
130}
131
132/// Parse an `agentmux://pair?v=1&host=…&port=…&fp=…&code=…&hostname=…` link.
133pub fn parse_link(link: &str) -> Result<Link, String> {
134    let bad = |why: &str| format!("That isn't a pairing link ({why}). Copy it from the other computer's \u{201c}Pair a device\u{201d} panel.");
135    let url = url::Url::parse(link.trim()).map_err(|_| bad("not a link"))?;
136    if url.scheme() != "agentmux" || url.host_str() != Some("pair") {
137        return Err(bad("not an agentmux://pair link"));
138    }
139    let get = |k: &str| url.query_pairs().find(|(key, _)| key == k).map(|(_, v)| v.into_owned());
140    if get("v").as_deref() != Some("1") {
141        return Err(bad("an unknown version"));
142    }
143    let fingerprint = get("fp").filter(|f| f.len() == 64 && f.bytes().all(|b| b.is_ascii_hexdigit())).ok_or_else(|| bad("no fingerprint"))?;
144    let host = get("host").filter(|h| h.parse::<std::net::IpAddr>().is_ok()).ok_or_else(|| bad("no address"))?;
145    Ok(Link {
146        host,
147        port: get("port").and_then(|p| p.parse().ok()).filter(|&p| p > 0).ok_or_else(|| bad("no port"))?,
148        fingerprint: fingerprint.to_ascii_lowercase(),
149        code: get("code").filter(|c| !c.is_empty()).ok_or_else(|| bad("no code"))?,
150        hostname: get("hostname").unwrap_or_default(),
151    })
152}
153
154/// Where peers' tokens are kept: the secret store (the OS keychain) in the
155/// app; in memory in tests, which must not touch the user's keychain.
156pub trait Tokens: Send + Sync {
157    fn put(&self, key: &str, token: &str) -> Result<(), String>;
158    fn get(&self, key: &str) -> Result<String, String>;
159    fn delete(&self, key: &str) -> Result<(), String>;
160}
161
162struct SecretStore;
163
164impl Tokens for SecretStore {
165    fn put(&self, key: &str, token: &str) -> Result<(), String> {
166        crate::identity::secret_store::put(key, token)
167    }
168    fn get(&self, key: &str) -> Result<String, String> {
169        crate::identity::secret_store::get(key).map(|t| t.as_str().to_string())
170    }
171    fn delete(&self, key: &str) -> Result<(), String> {
172        crate::identity::secret_store::delete(key)
173    }
174}
175
176/// The kept peers, from `dir` (the data directory).
177pub struct Peers {
178    dir: Option<PathBuf>,
179    lock: Mutex<()>,
180    tokens: Box<dyn Tokens>,
181}
182
183impl Peers {
184    pub fn new(dir: Option<PathBuf>) -> Self {
185        Self::with_tokens(dir, Box::new(SecretStore))
186    }
187
188    pub fn with_tokens(dir: Option<PathBuf>, tokens: Box<dyn Tokens>) -> Self {
189        Self { dir, lock: Mutex::new(()), tokens }
190    }
191
192    pub fn global() -> &'static Peers {
193        static GLOBAL: std::sync::OnceLock<Peers> = std::sync::OnceLock::new();
194        GLOBAL.get_or_init(|| Peers::new(Some(crate::backend::base::get_mux_data_dir())))
195    }
196
197    fn path(&self) -> Option<PathBuf> {
198        self.dir.as_ref().map(|d| d.join(FILE))
199    }
200
201    fn load(&self) -> Vec<Peer> {
202        self.path()
203            .and_then(|p| std::fs::read(p).ok())
204            .and_then(|b| serde_json::from_slice(&b).ok())
205            .unwrap_or_default()
206    }
207
208    fn save(&self, peers: &[Peer]) -> Result<(), String> {
209        let path = self.path().ok_or("no data directory")?;
210        let tmp = path.with_extension("json.tmp");
211        std::fs::write(&tmp, serde_json::to_vec_pretty(peers).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
212        std::fs::rename(&tmp, &path).map_err(|e| e.to_string())
213    }
214
215    /// The computers Tower reads (paired as a viewer device, not to watch agents).
216    pub fn list(&self) -> Vec<TowerPeerInfo> {
217        let _g = self.lock.lock().unwrap();
218        self.load().iter().filter(|p| !p.computer).map(Peer::info).collect()
219    }
220
221    /// The computers this one paired with to watch their agents.
222    pub fn computers(&self) -> Vec<Peer> {
223        let _g = self.lock.lock().unwrap();
224        self.load().into_iter().filter(|p| p.computer).collect()
225    }
226
227    /// Where its secrets are kept.
228    pub(crate) fn tokens(&self) -> &dyn Tokens {
229        self.tokens.as_ref()
230    }
231
232    pub fn get(&self, id: &str) -> Option<Peer> {
233        let _g = self.lock.lock().unwrap();
234        self.load().into_iter().find(|p| p.id == id)
235    }
236
237    fn put(&self, peer: Peer) -> Result<(), String> {
238        let _g = self.lock.lock().unwrap();
239        let mut all = self.load();
240        all.retain(|p| p.id != peer.id);
241        all.push(peer);
242        self.save(&all)
243    }
244
245    /// Forget a peer here (its token too). The other computer still lists
246    /// this device until its user revokes it.
247    pub fn forget(&self, id: &str) -> Result<(), String> {
248        let Some(peer) = self.get(id) else { return Ok(()) };
249        // The token first, with no lock held: a keychain delete may wait on
250        // the OS asking the user, and must not stall every listing meanwhile.
251        // If it fails the entry stays, so Forget can be tried again rather
252        // than leaving a token nothing points to.
253        let removed = |key: String| {
254            self.tokens.delete(&key).map_err(|e| format!("Couldn't remove the pairing with {} from the keychain: {e}", peer.hostname))
255        };
256        removed(peer.secret_key())?;
257        if peer.computer {
258            removed(peer.signing_key_secret())?;
259        }
260        let _g = self.lock.lock().unwrap();
261        let mut all = self.load();
262        all.retain(|p| p.id != id);
263        self.save(&all)
264    }
265
266    /// Record that a peer now answers at `host:port`, if it is still kept (it
267    /// may have been forgotten while the request that found it was in
268    /// flight: then nothing is written).
269    fn moved_to(&self, id: &str, host: &str, port: u16) {
270        let _g = self.lock.lock().unwrap();
271        let mut all = self.load();
272        let Some(peer) = all.iter_mut().find(|p| p.id == id) else { return };
273        (peer.host, peer.port) = (host.to_string(), port);
274        let _ = self.save(&all);
275    }
276}
277
278#[derive(Deserialize)]
279struct PairReply {
280    token: String,
281    device_id: String,
282    #[serde(default)]
283    hostname: String,
284    #[serde(default)]
285    channel: String,
286}
287
288/// Pair with the computer the link names, as `device_name` (this computer), for Tower.
289pub async fn pair(peers: &'static Peers, link: &str, device_name: &str) -> Result<TowerPeerInfo, String> {
290    pair_with(peers, link, device_name, None).await.map(|p| p.info())
291}
292
293/// Pair with the computer the link names, as `device_name`. With `key` (the private half, PKCS#8 base64, and the
294/// public half, base64), as a computer that watches its agents and signs with that key (`backend::remote_panes`).
295pub(crate) async fn pair_with(peers: &'static Peers, link: &str, device_name: &str, key: Option<(String, String)>) -> Result<Peer, String> {
296    let link = parse_link(link)?;
297    let client = pinned_client(&link.fingerprint, TIMEOUT)?;
298    let probe = Peer {
299        id: uuid::Uuid::new_v4().to_string(),
300        hostname: link.hostname.clone(),
301        host: link.host.clone(),
302        port: link.port,
303        fingerprint: link.fingerprint.clone(),
304        device_id: String::new(),
305        paired_ms: agentmux_common::time::now_ms(),
306        computer: key.is_some(),
307        channel: String::new(),
308    };
309    let mut body = serde_json::json!({ "code": link.code, "device_name": device_name });
310    if let Some((_, public)) = &key {
311        (body["device_kind"], body["device_key"]) = (serde_json::json!("computer"), serde_json::json!(public));
312    }
313    let resp = client
314        .post(probe.url(&link.host, "/agentmux/viewer/pair"))
315        .json(&body)
316        .send()
317        .await
318        .map_err(|e| unreachable(&probe, &e))?;
319    let status = resp.status();
320    if status == reqwest::StatusCode::UNAUTHORIZED {
321        return Err("The code was refused: it works once, for two minutes. Show a new one on the other computer.".into());
322    }
323    if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
324        return Err("Too many wrong codes: wait a minute and try again.".into());
325    }
326    if !status.is_success() {
327        let reason = resp.json::<serde_json::Value>().await.ok().and_then(|j| j["reason"].as_str().map(str::to_string));
328        if reason.as_deref() == Some("computers_off") {
329            return Err(format!(
330                "{} doesn't let other computers watch its agents. Its person can turn on \u{201c}Allow other computers to watch agents here\u{201d} in its Settings.",
331                if link.hostname.is_empty() { "The other computer" } else { &link.hostname }
332            ));
333        }
334        return Err(format!("The other computer refused to pair ({status})."));
335    }
336    let reply: PairReply = resp.json().await.map_err(|e| format!("The other computer answered oddly: {e}"))?;
337    let peer = Peer {
338        hostname: if reply.hostname.is_empty() { link.hostname } else { reply.hostname },
339        device_id: reply.device_id,
340        channel: reply.channel,
341        ..probe
342    };
343    // The keychain writes may wait on the OS asking the user's consent, which
344    // can't be cancelled: never on an async worker.
345    let token = reply.token;
346    let kept = peer.clone();
347    tokio::task::spawn_blocking(move || {
348        let mut secrets = vec![(peer.secret_key(), token)];
349        if let Some((private, _)) = key {
350            secrets.push((peer.signing_key_secret(), private));
351        }
352        let mut written = Vec::new();
353        let mut result = Ok(());
354        for (name, value) in &secrets {
355            result = peers.tokens.put(name, value);
356            if result.is_err() {
357                break;
358            }
359            written.push(name);
360        }
361        if result.is_ok() {
362            result = peers.put(peer.clone());
363        }
364        if result.is_err() {
365            for name in written {
366                if let Err(d) = peers.tokens.delete(name) {
367                    tracing::warn!(error = %d, "tower: could not remove a secret after a failed pairing");
368                }
369            }
370        }
371        result
372    })
373    .await
374    .map_err(|e| e.to_string())??;
375    Ok(kept)
376}
377
378fn unreachable(peer: &Peer, e: &reqwest::Error) -> String {
379    let why = if e.is_timeout() {
380        "it didn't answer".to_string()
381    } else if format!("{e:?}").contains("fingerprint") {
382        "its certificate isn't the one it was paired with".to_string()
383    } else {
384        "the connection failed".to_string()
385    };
386    format!("Can't reach {} at {}:{} ({why}).", if peer.hostname.is_empty() { "the other computer" } else { &peer.hostname }, peer.host, peer.port)
387}
388
389/// A paired computer's snapshot. `moved`: the addresses LAN discovery has for
390/// its hostname, tried in turn when the kept one doesn't answer.
391pub async fn sample(peers: &'static Peers, id: &str, filter: &str, moved: Vec<String>) -> Result<TowerSnapshot, String> {
392    let mut peer = peers.get(id).filter(|p| !p.computer).ok_or("That computer is no longer paired.")?;
393    // A keychain read (bounded, but blocking): off the async workers.
394    let key = peer.secret_key();
395    let token = tokio::task::spawn_blocking(move || peers.tokens.get(&key))
396        .await
397        .map_err(|e| e.to_string())?
398        .map_err(|e| format!("Couldn't read the pairing with {}: {e}", peer.hostname))?;
399    let client = pinned_client(&peer.fingerprint, TIMEOUT)?;
400    let mut hosts = vec![peer.host.clone()];
401    hosts.extend(moved.into_iter().filter(|h| *h != peer.host));
402    // The kept port at each address first; only if none answers, the ports the
403    // addresses advertise now (a restarted peer may have another). The pinned
404    // fingerprint decides which of them is really this peer.
405    let mut candidates: Vec<(String, u16)> = hosts.iter().map(|h| (h.clone(), peer.port)).collect();
406    let mut probed = false;
407    let mut next = 0;
408    let mut last_err = String::new();
409    loop {
410        if next == candidates.len() {
411            if probed {
412                break;
413            }
414            probed = true;
415            for h in &hosts {
416                for p in probe_viewer_ports(h).await {
417                    if !candidates.contains(&(h.clone(), p)) {
418                        candidates.push((h.clone(), p));
419                    }
420                }
421            }
422            if next == candidates.len() {
423                break;
424            }
425        }
426        let (host, port) = candidates[next].clone();
427        next += 1;
428        let resp = match client
429            .get(url_at(&host, port, "/agentmux/viewer/procs"))
430            .query(&[("filter", filter)])
431            .bearer_auth(&token)
432            .send()
433            .await
434        {
435            Ok(r) => r,
436            Err(e) => {
437                last_err = unreachable(&Peer { host: host.clone(), port, ..peer.clone() }, &e);
438                continue;
439            }
440        };
441        match resp.status() {
442            s if s.is_success() => {
443                if host != peer.host || port != peer.port {
444                    (peer.host, peer.port) = (host.clone(), port);
445                    let id = peer.id.clone();
446                    let _ = tokio::task::spawn_blocking(move || peers.moved_to(&id, &host, port)).await;
447                }
448                let mut snap: TowerSnapshot = resp.json().await.map_err(|e| format!("{} answered oddly: {e}", peer.hostname))?;
449                snap.remote = true;
450                return Ok(snap);
451            }
452            reqwest::StatusCode::UNAUTHORIZED => {
453                return Err(format!("{} no longer accepts this computer (it was unpaired there). Forget it and pair again.", peer.hostname))
454            }
455            reqwest::StatusCode::FORBIDDEN => {
456                return Err(format!("{} doesn't share its processes. Turn on \u{201c}Share this computer's processes with paired devices\u{201d} in its Tower.", peer.hostname))
457            }
458            s => return Err(format!("{} refused ({s}).", peer.hostname)),
459        }
460    }
461    Err(last_err)
462}
463
464#[cfg(any(test, feature = "test-support"))]
465pub mod test_support {
466    use super::*;
467
468    pub const FP: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
469
470    /// Tokens in memory: tests never touch the user's keychain.
471    #[derive(Default)]
472    pub struct MemTokens(pub std::sync::Mutex<std::collections::HashMap<String, String>>);
473
474    impl Tokens for std::sync::Arc<MemTokens> {
475        fn put(&self, key: &str, token: &str) -> Result<(), String> {
476            self.0.lock().unwrap().insert(key.into(), token.into());
477            Ok(())
478        }
479        fn get(&self, key: &str) -> Result<String, String> {
480            self.0.lock().unwrap().get(key).cloned().ok_or_else(|| "no token".into())
481        }
482        fn delete(&self, key: &str) -> Result<(), String> {
483            self.0.lock().unwrap().remove(key);
484            Ok(())
485        }
486    }
487
488    /// Keeps `peer` as pairing would, without its secrets.
489    pub fn keep(peers: &Peers, peer: Peer) {
490        peers.put(peer).unwrap();
491    }
492
493    /// Peers for one test, kept for the test binary's life (`pair` and
494    /// `sample` take `'static`, as the app's `Peers::global()` is).
495    pub fn peers_in(dir: &std::path::Path) -> (&'static Peers, std::sync::Arc<MemTokens>) {
496        let tokens = std::sync::Arc::new(MemTokens::default());
497        (Box::leak(Box::new(Peers::with_tokens(Some(dir.to_path_buf()), Box::new(tokens.clone())))), tokens)
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use super::test_support::*;
504    use super::*;
505
506    #[test]
507    fn a_pairing_link_is_read_and_anything_else_refused() {
508        let link = format!("agentmux://pair?v=1&host=198.51.100.20&port=47900&fp={FP}&code=ABCDEFGHJK&hostname=studio&channel=stable");
509        assert_eq!(
510            parse_link(&link).unwrap(),
511            Link { host: "198.51.100.20".into(), port: 47900, fingerprint: FP.into(), code: "ABCDEFGHJK".into(), hostname: "studio".into() }
512        );
513        assert!(parse_link("https://example.com/pair?v=1").is_err());
514        assert!(parse_link(&link.replace("v=1", "v=9")).is_err(), "unknown version");
515        assert!(parse_link(&link.replace(FP, "abc")).is_err(), "short fingerprint");
516        assert!(parse_link(&link.replace("198.51.100.20", "evil.example")).is_err(), "an address, not a name");
517        assert!(parse_link(&link.replace("&code=ABCDEFGHJK", "")).is_err());
518    }
519
520    #[test]
521    fn a_discovery_reply_gives_its_viewer_port_then_its_siblings() {
522        let reply = br#"{"type":"agentmux_discover_response","v":1,"viewer_port":29702,
523            "siblings":[{"channel":"dev","viewer_port":29703},{"channel":"x"},{"viewer_port":29702}]}"#;
524        assert_eq!(viewer_ports_of(reply), vec![29702, 29703]);
525        assert!(viewer_ports_of(b"not json").is_empty());
526        assert!(viewer_ports_of(br#"{"type":"agentmux_discover_response"}"#).is_empty(), "no viewer listener up");
527    }
528
529    #[test]
530    fn peers_are_kept_without_their_token_and_forgotten() {
531        let dir = tempfile::tempdir().unwrap();
532        let (peers, _) = peers_in(dir.path());
533        let peer = Peer {
534            id: "p1".into(),
535            hostname: "studio".into(),
536            host: "2001:db8::1".into(),
537            port: 47900,
538            fingerprint: FP.into(),
539            device_id: "d1".into(),
540            paired_ms: 5,
541            computer: false,
542            channel: String::new(),
543        };
544        peers.put(peer.clone()).unwrap();
545        // A pairing to watch a peer's agents is kept beside it, and is not Tower's.
546        peers.put(Peer { id: "c1".into(), computer: true, ..peer.clone() }).unwrap();
547        assert_eq!(peers.computers().iter().map(|p| p.id.as_str()).collect::<Vec<_>>(), ["c1"]);
548        let list = peers.list();
549        assert_eq!(list.len(), 1);
550        assert_eq!(list[0].connection, "peer:p1");
551        assert_eq!(peer.url("2001:db8::1", "/x"), "https://[2001:db8::1]:47900/x");
552        let on_disk = std::fs::read_to_string(dir.path().join(FILE)).unwrap();
553        assert!(!on_disk.contains("amxv_"), "no token on disk");
554        peers.forget("p1").unwrap();
555        assert!(peers.list().is_empty());
556        // A request that found it at a new address after it was forgotten
557        // doesn't bring it back.
558        peers.moved_to("p1", "198.51.100.30", 47901);
559        assert!(peers.list().is_empty());
560    }
561
562    /// Nothing listening: an error that says so, and nothing kept.
563    #[tokio::test]
564    async fn pairing_with_nothing_listening_fails_closed() {
565        let dir = tempfile::tempdir().unwrap();
566        let (peers, _) = peers_in(dir.path());
567        // Nothing listens on this port; the error is about reaching it.
568        let link = format!("agentmux://pair?v=1&host=127.0.0.1&port=9&fp={FP}&code=ABCDEFGHJK&hostname=studio");
569        let err = pair(peers, &link, "me").await.unwrap_err();
570        assert!(err.contains("Can't reach studio"), "{err}");
571        assert!(peers.list().is_empty(), "nothing kept");
572    }
573}