Skip to main content

agentmux_srv_core/backend/remote_panes/
pane.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The viewing srv's channel for one remote agent
5//! (docs/specs/SPEC_REMOTE_PANES_WATCH_AND_DRIVE_AN_AGENT_ON_ANOTHER_COMPUTER_2026_11_20.md §4, §7): one feed and one
6//! [`Ring`] per (host, agent), however many panes and windows show it; the feed closes when the last one does. At
7//! most [`MAX_PANES`] are open at once (D13).
8//!
9//! The feed reconnects by itself while the host can't be reached, resuming from where the ring stands
10//! (`Last-Event-ID`); it ends, saying why, when the host refuses this computer (unpaired there, computers not
11//! allowed, the agent hidden, an AgentMux too old). What changes is told to subscribers as a [`Change`]; the lines
12//! themselves are read from the ring.
13
14use std::collections::HashMap;
15use std::sync::Arc;
16use std::time::Duration;
17
18use parking_lot::Mutex;
19use serde::Serialize;
20use tokio::sync::broadcast;
21use tokio_util::sync::CancellationToken;
22
23use super::host::{self, outdated_text, Host, Refusal};
24use super::ring::{Ring, SseEvent, SseParser, RING_BYTES};
25use crate::backend::tower::peers::Peers;
26
27/// The most remote agents open at once on this computer (D13).
28pub const MAX_PANES: usize = 6;
29/// The lines a page of older history asks the host for (its most).
30const OLDER_PAGE: u32 = 2000;
31/// The longest wait between two tries to reach a host that doesn't answer.
32const MAX_BACKOFF: Duration = Duration::from_secs(30);
33
34/// How the feed stands.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
36#[serde(tag = "state", rename_all = "snake_case")]
37pub enum Connection {
38    Connecting,
39    Live,
40    /// The host can't be reached now; another try follows.
41    Reconnecting { why: String },
42    /// The host refused, and nothing more is tried: its `reason` (`unpaired`, `computers_off`, `hidden`,
43    /// `outdated`, …) and what to tell the person.
44    Ended { reason: String, message: String },
45}
46
47/// What changed in a remote pane.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum Change {
50    /// The ring was replaced: it now holds `from_line..next_line`.
51    Snapshot { from_line: u64, next_line: u64 },
52    /// `count` lines were added from `line`.
53    Append { line: u64, count: usize },
54    /// The host started over (its transcript was rewritten, or the feed lost its place); a snapshot follows.
55    Reset { reason: String },
56    /// Older lines were read back from the host: the ring now starts at `from_line`.
57    Older { from_line: u64 },
58    Status(serde_json::Value),
59    Pending(serde_json::Value),
60    Connection(Connection),
61    /// The host's `hello` answered (at each open, so again after a reconnect): whether it lets this computer send.
62    Send(String),
63}
64
65/// Told every change of every pane: its computer, its agent and the change (srv publishes it to the window).
66pub type OnChange = Arc<dyn Fn(&str, &str, &Change) + Send + Sync>;
67
68/// One remote agent, as this computer shows it.
69pub struct RemotePane {
70    pub peer_id: String,
71    pub agent: String,
72    pub ring: Mutex<Ring>,
73    facts: Mutex<Facts>,
74    changes: broadcast::Sender<Change>,
75    stop: CancellationToken,
76    on_change: Option<OnChange>,
77}
78
79/// The latest of what the feed said about the agent.
80#[derive(Debug, Clone, Default)]
81pub struct Facts {
82    pub provider: String,
83    /// Who the agent is, as the snapshot names it.
84    pub identity: serde_json::Value,
85    pub status: serde_json::Value,
86    pub pending: serde_json::Value,
87    pub connection: Option<Connection>,
88    /// Whether the host lets this computer send, as its last `hello` said: `allowed`, `off`, or empty before it answered.
89    pub send: String,
90}
91
92/// What to do after one event.
93#[derive(Debug, Clone, PartialEq, Eq)]
94enum Step {
95    Continue,
96    /// The ring can't follow on: open the feed again for a fresh snapshot.
97    Resync,
98    /// The host stops showing this agent here.
99    End(String),
100}
101
102impl RemotePane {
103    fn new(peer_id: &str, agent: &str) -> Self {
104        Self {
105            peer_id: peer_id.to_string(),
106            agent: agent.to_string(),
107            ring: Mutex::new(Ring::new(RING_BYTES)),
108            facts: Mutex::new(Facts::default()),
109            changes: broadcast::channel(256).0,
110            stop: CancellationToken::new(),
111            on_change: None,
112        }
113    }
114
115    /// Reads the page of lines before the oldest held from the host, into the ring (as much as fits). How many
116    /// lines were added: none when nothing older exists, or the ring is full.
117    pub async fn read_older(&self, peers: &'static Peers) -> Result<usize, String> {
118        let (gen, before) = {
119            let ring = self.ring.lock();
120            (ring.gen().to_string(), ring.from_line())
121        };
122        if gen.is_empty() || before == 0 {
123            return Ok(0);
124        }
125        let host = Host::connect(peers, &self.peer_id).await?;
126        let page = host.history(&self.agent, &format!("{gen}:{before}"), OLDER_PAGE).await.map_err(|r| match r {
127            Refusal::Outdated { host_version } => outdated_text(&host.peer.hostname, &host_version, "show older lines"),
128            r => why(&r, &host.peer.hostname),
129        })?;
130        let lines: Vec<String> = page["lines"].as_array().map(|a| a.iter().filter_map(|l| l.as_str().map(str::to_string)).collect()).unwrap_or_default();
131        let (added, from_line) = {
132            let mut ring = self.ring.lock();
133            let added = ring.older(page["gen"].as_str().unwrap_or_default(), page["before"].as_u64().unwrap_or(u64::MAX), lines);
134            (added, ring.from_line())
135        };
136        if added > 0 {
137            self.tell(Change::Older { from_line });
138        }
139        Ok(added)
140    }
141
142    /// What changes from now on. A subscriber that falls behind reads the ring again.
143    pub fn subscribe(&self) -> broadcast::Receiver<Change> {
144        self.changes.subscribe()
145    }
146
147    pub fn facts(&self) -> Facts {
148        self.facts.lock().clone()
149    }
150
151    fn tell(&self, change: Change) {
152        // A stopped pane says nothing more but how it ended: its feed may finish a step after it was stopped.
153        if self.stop.is_cancelled() && !matches!(change, Change::Connection(Connection::Ended { .. })) {
154            return;
155        }
156        if let Change::Connection(c) = &change {
157            self.facts.lock().connection = Some(c.clone());
158        }
159        if let Some(on_change) = &self.on_change {
160            on_change(&self.peer_id, &self.agent, &change);
161        }
162        let _ = self.changes.send(change);
163    }
164
165    /// Applies one of the host's events.
166    fn apply(&self, event: &SseEvent) -> Step {
167        let data: serde_json::Value = serde_json::from_str(&event.data).unwrap_or_default();
168        let lines = || -> Vec<String> {
169            data["lines"].as_array().map(|a| a.iter().filter_map(|l| l.as_str().map(str::to_string)).collect()).unwrap_or_default()
170        };
171        let gen = data["gen"].as_str().unwrap_or_default();
172        match event.name.as_str() {
173            "snapshot" => {
174                let from_line = data["from_line"].as_u64().unwrap_or(0);
175                let (from_line, next_line) = {
176                    let mut ring = self.ring.lock();
177                    ring.snapshot(gen, from_line, lines());
178                    (ring.from_line(), ring.next_line())
179                };
180                {
181                    let mut facts = self.facts.lock();
182                    facts.provider = data["provider"].as_str().unwrap_or_default().to_string();
183                    facts.identity = data["agent"].clone();
184                }
185                self.tell(Change::Snapshot { from_line, next_line });
186                Step::Continue
187            }
188            "append" => {
189                let line = data["line"].as_u64().unwrap_or(0);
190                let appended = self.ring.lock().append(gen, line, lines());
191                match appended {
192                    Ok((_, 0)) => Step::Continue,
193                    Ok((line, count)) => {
194                        self.tell(Change::Append { line, count });
195                        Step::Continue
196                    }
197                    Err(_) => Step::Resync,
198                }
199            }
200            "reset" => {
201                let reason = data["reason"].as_str().unwrap_or_default().to_string();
202                if reason == "hidden" {
203                    return Step::End(reason);
204                }
205                self.tell(Change::Reset { reason });
206                Step::Continue
207            }
208            "status" => {
209                self.facts.lock().status = data.clone();
210                self.tell(Change::Status(data));
211                Step::Continue
212            }
213            "pending" => {
214                self.facts.lock().pending = data.clone();
215                self.tell(Change::Pending(data));
216                Step::Continue
217            }
218            _ => Step::Continue,
219        }
220    }
221}
222
223/// What a refusal ends the feed with, or `None` when it is worth trying again. `host` is the computer's name (empty
224/// when unknown).
225fn ending(refusal: &Refusal, host: &str) -> Option<Connection> {
226    let name = if host.is_empty() { "That computer" } else { host };
227    let (reason, message) = match refusal {
228        Refusal::Unreachable(_) => return None,
229        Refusal::Outdated { host_version } => ("outdated".to_string(), outdated_text(host, host_version, "show its agents here")),
230        Refusal::Newer { host_version } => ("newer".to_string(), host::newer_text(host, host_version)),
231        Refusal::Refused { status: 401, reason, error } if reason == "forgotten" => (reason.clone(), error.clone()),
232        Refusal::Refused { status: 401, .. } => ("unpaired".into(), "That computer no longer accepts this one (it was unpaired there). Pair again.".into()),
233        Refusal::Refused { status, reason, error } if *status == 403 || *status == 404 => {
234            let code = if reason.is_empty() { if *status == 404 { "not_found" } else { "refused" } } else { reason };
235            // A host that gave no words gets this computer's: never a banner with nothing in it.
236            let message = if !error.is_empty() {
237                error.clone()
238            } else if *status == 404 {
239                format!("{name} doesn't show that agent any more: it was closed or hidden there.")
240            } else {
241                format!("{name} refused to show that agent.")
242            };
243            (code.to_string(), message)
244        }
245        Refusal::Refused { .. } => return None,
246    };
247    Some(Connection::Ended { reason, message })
248}
249
250fn why(refusal: &Refusal, host: &str) -> String {
251    match refusal {
252        Refusal::Unreachable(why) => why.clone(),
253        Refusal::Refused { status, error, .. } => format!("{status} {error}"),
254        Refusal::Outdated { host_version } => outdated_text(host, host_version, "show its agents here"),
255        Refusal::Newer { host_version } => host::newer_text(host, host_version),
256    }
257}
258
259/// The name of the computer paired as `peer_id` (empty when it isn't paired any more).
260fn host_name(peers: &Peers, peer_id: &str) -> String {
261    peers.computers().into_iter().find(|p| p.id == peer_id).map(|p| p.hostname).unwrap_or_default()
262}
263
264/// The first wait before trying a host again.
265const FIRST_BACKOFF: Duration = Duration::from_secs(1);
266
267/// How long to wait before the next try, and the wait after that: a feed that brought lines before it was lost
268/// starts the backoff over; one that brought none (a host that opens the feed and ends it at once) keeps doubling.
269fn next_wait(backoff: Duration, brought_lines: bool) -> (Duration, Duration) {
270    let wait = if brought_lines { FIRST_BACKOFF } else { backoff };
271    (wait, (wait * 2).min(MAX_BACKOFF))
272}
273
274/// How one open feed ended.
275enum Lost {
276    /// Try again: why, whether it brought lines first, and whether to resume from where the ring stands.
277    Retry { why: String, brought_lines: bool, resume: bool },
278    Stopped,
279    Ended(Connection),
280}
281
282/// Opens the feed: the pairing kept here, the host's `hello`, then the signed open.
283async fn open(pane: &RemotePane, peers: &'static Peers, resume: bool) -> Result<reqwest::Response, Refusal> {
284    if !peers.computers().iter().any(|p| p.id == pane.peer_id) {
285        let message = "This computer no longer keeps its pairing with that computer. Pair again.".to_string();
286        return Err(Refusal::Refused { status: 401, reason: "forgotten".into(), error: message });
287    }
288    // Kept, but its secrets couldn't be read now (a locked keychain): worth trying again.
289    let host = Host::connect(peers, &pane.peer_id).await.map_err(Refusal::Unreachable)?;
290    let hello = host.hello().await?;
291    pane.facts.lock().send = hello.send.clone();
292    pane.tell(Change::Send(hello.send));
293    let last = if resume { pane.ring.lock().event_id() } else { None };
294    host.open_feed(&pane.agent, last.as_deref()).await
295}
296
297/// Reads an open feed into the pane until it is lost, stopped or ended.
298async fn follow(pane: &RemotePane, mut feed: reqwest::Response) -> Lost {
299    let mut parser = SseParser::default();
300    let mut brought_lines = false;
301    loop {
302        let chunk = tokio::select! {
303            // A stopped pane stops first, whatever else is ready.
304            biased;
305            _ = pane.stop.cancelled() => return Lost::Stopped,
306            c = feed.chunk() => c,
307        };
308        let why = match chunk {
309            Ok(Some(chunk)) => match parser.push(&chunk) {
310                Ok(events) => {
311                    for event in &events {
312                        match pane.apply(event) {
313                            Step::Continue => brought_lines |= matches!(event.name.as_str(), "snapshot" | "append"),
314                            Step::Resync => return Lost::Retry { why: "the feed lost its place".into(), brought_lines, resume: false },
315                            Step::End(reason) => {
316                                let message = "That agent is no longer shown to other computers.".to_string();
317                                return Lost::Ended(Connection::Ended { reason, message });
318                            }
319                        }
320                    }
321                    continue;
322                }
323                Err(e) => e,
324            },
325            Ok(None) => "the host closed the feed".to_string(),
326            Err(e) if e.is_timeout() => "the host went quiet".to_string(),
327            Err(_) => "the connection dropped".to_string(),
328        };
329        return Lost::Retry { why, brought_lines, resume: true };
330    }
331}
332
333/// Runs `pane`'s feed until it is stopped or the host refuses.
334async fn run(pane: Arc<RemotePane>, peers: &'static Peers) {
335    let mut backoff = FIRST_BACKOFF;
336    let mut resume = true;
337    pane.tell(Change::Connection(Connection::Connecting));
338    loop {
339        let opened = tokio::select! {
340            // A stopped pane stops first, whatever else is ready.
341            biased;
342            _ = pane.stop.cancelled() => return,
343            r = open(&pane, peers, resume) => r,
344        };
345        let (why, brought_lines) = match opened {
346            Ok(feed) => {
347                pane.tell(Change::Connection(Connection::Live));
348                match follow(&pane, feed).await {
349                    Lost::Stopped => return,
350                    Lost::Ended(end) => {
351                        pane.tell(Change::Connection(end));
352                        return;
353                    }
354                    Lost::Retry { why, brought_lines, resume: from_ring } => {
355                        resume = from_ring;
356                        (why, brought_lines)
357                    }
358                }
359            }
360            Err(refusal) => {
361                let name = host_name(peers, &pane.peer_id);
362                if let Some(end) = ending(&refusal, &name) {
363                    pane.tell(Change::Connection(end));
364                    return;
365                }
366                (why(&refusal, &name), false)
367            }
368        };
369        pane.tell(Change::Connection(Connection::Reconnecting { why }));
370        let (wait, next) = next_wait(backoff, brought_lines);
371        backoff = next;
372        tokio::select! {
373            // A stopped pane stops first, whatever else is ready.
374            biased;
375            _ = pane.stop.cancelled() => return,
376            _ = tokio::time::sleep(wait) => {}
377        }
378    }
379}
380
381/// The remote agents open on this computer.
382pub struct Panes {
383    open: Mutex<HashMap<(String, String), (Arc<RemotePane>, usize)>>,
384    /// Which (computer, agent) each of the window's panes shows.
385    blocks: Mutex<HashMap<String, (String, String)>>,
386    peers: &'static Peers,
387    on_change: Option<OnChange>,
388}
389
390static GLOBAL: std::sync::OnceLock<Panes> = std::sync::OnceLock::new();
391
392impl Panes {
393    pub fn new(peers: &'static Peers) -> Self {
394        Self { open: Mutex::new(HashMap::new()), blocks: Mutex::new(HashMap::new()), peers, on_change: None }
395    }
396
397    /// The same, telling `on_change` every change of every pane.
398    pub fn with_on_change(mut self, on_change: OnChange) -> Self {
399        self.on_change = Some(on_change);
400        self
401    }
402
403    /// Makes `panes` the app's, once (srv does at start, with its publisher); later calls keep the first.
404    pub fn install_global(panes: Panes) -> &'static Panes {
405        let _ = GLOBAL.set(panes);
406        Self::global()
407    }
408
409    /// The app's panes if srv has installed them; never makes a set of its own (one made early would lack the publisher).
410    pub fn installed() -> Option<&'static Panes> {
411        GLOBAL.get()
412    }
413
414    pub fn global() -> &'static Panes {
415        GLOBAL.get_or_init(|| Panes::new(Peers::global()))
416    }
417
418    pub fn peers(&self) -> &'static Peers {
419        self.peers
420    }
421
422    /// A pane showing `agent` of the host paired as `peer_id`: the open one, or a new one whose feed starts now.
423    /// Refused past [`MAX_PANES`]. Each open is closed with [`Panes::close`].
424    pub fn open(&self, peer_id: &str, agent: &str) -> Result<Arc<RemotePane>, String> {
425        let mut open = self.open.lock();
426        let key = (peer_id.to_string(), agent.to_string());
427        if let Some((pane, users)) = open.get_mut(&key) {
428            *users += 1;
429            return Ok(pane.clone());
430        }
431        if open.len() >= MAX_PANES {
432            return Err(format!("At most {MAX_PANES} agents of other computers can be open at once: close one first."));
433        }
434        let pane = Arc::new(RemotePane { on_change: self.on_change.clone(), ..RemotePane::new(peer_id, agent) });
435        tokio::spawn(run(pane.clone(), self.peers));
436        open.insert(key, (pane.clone(), 1));
437        Ok(pane)
438    }
439
440    /// The window's pane `block_id` shows `agent` of `peer_id`: opened once however often the pane asks (a reload
441    /// asks again), and the agent it showed before, if another, closed for it.
442    pub fn open_for(&self, block_id: &str, peer_id: &str, agent: &str) -> Result<Arc<RemotePane>, String> {
443        let want = (peer_id.to_string(), agent.to_string());
444        // Held across the look, the open and the record, so two opens of one pane at once count it once. (The
445        // lock order is `blocks`, then `open`, everywhere.)
446        let mut blocks = self.blocks.lock();
447        let before = blocks.get(block_id).cloned();
448        if before.as_ref() == Some(&want) {
449            if let Some(pane) = self.get(peer_id, agent) {
450                return Ok(pane);
451            }
452        }
453        if let Some((p, a)) = before {
454            blocks.remove(block_id);
455            self.close(&p, &a);
456        }
457        let pane = self.open(peer_id, agent)?;
458        blocks.insert(block_id.to_string(), want);
459        Ok(pane)
460    }
461
462    /// The pairing with `peer_id` was forgotten here: every pane of that computer ends now, saying so, and no
463    /// window pane counts as showing it.
464    pub fn end_computer(&self, peer_id: &str) {
465        let mut blocks = self.blocks.lock();
466        blocks.retain(|_, (p, _)| p != peer_id);
467        let ended: Vec<Arc<RemotePane>> = {
468            let mut open = self.open.lock();
469            let keys: Vec<_> = open.keys().filter(|(p, _)| p == peer_id).cloned().collect();
470            keys.into_iter().filter_map(|k| open.remove(&k)).map(|(pane, _)| pane).collect()
471        };
472        drop(blocks);
473        for pane in ended {
474            pane.stop.cancel();
475            let message = "This computer no longer keeps its pairing with that computer. Pair again.".to_string();
476            pane.tell(Change::Connection(Connection::Ended { reason: "forgotten".into(), message }));
477        }
478    }
479
480    /// The window's pane `block_id` is gone, or shows something else now.
481    pub fn close_for(&self, block_id: &str) {
482        let shown = self.blocks.lock().remove(block_id);
483        if let Some((peer_id, agent)) = shown {
484            self.close(&peer_id, &agent);
485        }
486    }
487
488    /// One shower of the pane is gone; the last one closes its feed and drops its ring.
489    pub fn close(&self, peer_id: &str, agent: &str) {
490        let mut open = self.open.lock();
491        let key = (peer_id.to_string(), agent.to_string());
492        let Some((pane, users)) = open.get_mut(&key) else { return };
493        *users -= 1;
494        if *users == 0 {
495            pane.stop.cancel();
496            open.remove(&key);
497        }
498    }
499
500    /// The open pane for `agent` of `peer_id`.
501    pub fn get(&self, peer_id: &str, agent: &str) -> Option<Arc<RemotePane>> {
502        self.open.lock().get(&(peer_id.to_string(), agent.to_string())).map(|(p, _)| p.clone())
503    }
504
505    pub fn len(&self) -> usize {
506        self.open.lock().len()
507    }
508
509    pub fn is_empty(&self) -> bool {
510        self.len() == 0
511    }
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517
518    fn event(name: &str, data: serde_json::Value) -> SseEvent {
519        SseEvent { name: name.into(), id: None, data: data.to_string() }
520    }
521
522    #[test]
523    fn the_feeds_events_fill_the_ring_and_say_what_changed() {
524        let pane = RemotePane::new("p", "demo");
525        let mut changes = pane.subscribe();
526        let snapshot = serde_json::json!({ "provider": "claude", "agent": { "name": "demo" }, "gen": "g", "from_line": 4, "next_line": 6, "lines": ["a", "b"] });
527        assert_eq!(pane.apply(&event("snapshot", snapshot)), Step::Continue);
528        assert_eq!(changes.try_recv().unwrap(), Change::Snapshot { from_line: 4, next_line: 6 });
529        assert_eq!(pane.facts().provider, "claude");
530
531        assert_eq!(pane.apply(&event("append", serde_json::json!({ "gen": "g", "line": 6, "lines": ["c"] }))), Step::Continue);
532        assert_eq!(changes.try_recv().unwrap(), Change::Append { line: 6, count: 1 });
533        assert_eq!(pane.ring.lock().range(0, 10), (4, vec!["a".to_string(), "b".into(), "c".into()]));
534
535        // Lines the ring can't follow on from: open again for a snapshot.
536        assert_eq!(pane.apply(&event("append", serde_json::json!({ "gen": "g", "line": 9, "lines": ["x"] }))), Step::Resync);
537        assert_eq!(pane.apply(&event("append", serde_json::json!({ "gen": "h", "line": 7, "lines": ["x"] }))), Step::Resync);
538
539        pane.apply(&event("status", serde_json::json!({ "state": "working" })));
540        assert_eq!(pane.facts().status["state"], "working");
541        assert_eq!(pane.apply(&event("reset", serde_json::json!({ "reason": "rewritten" }))), Step::Continue);
542        assert_eq!(pane.apply(&event("reset", serde_json::json!({ "reason": "hidden" }))), Step::End("hidden".into()));
543    }
544
545    #[test]
546    fn a_refusal_ends_the_feed_and_an_unreachable_host_is_tried_again() {
547        assert_eq!(ending(&Refusal::Unreachable("down".into()), "studio"), None);
548        assert_eq!(ending(&Refusal::Refused { status: 503, reason: String::new(), error: String::new() }, "studio"), None);
549        let ended = |r: Refusal| match ending(&r, "studio") {
550            Some(Connection::Ended { reason, .. }) => reason,
551            other => panic!("{other:?}"),
552        };
553        assert_eq!(ended(Refusal::Refused { status: 401, reason: "revoked".into(), error: String::new() }), "unpaired");
554        assert_eq!(ended(Refusal::Refused { status: 403, reason: "computers_off".into(), error: "off".into() }), "computers_off");
555        assert_eq!(ended(Refusal::Refused { status: 404, reason: String::new(), error: String::new() }), "not_found");
556        assert_eq!(ended(Refusal::Outdated { host_version: String::new() }), "outdated");
557        assert_eq!(ended(Refusal::Newer { host_version: "0.99.1".into() }), "newer");
558        assert!(matches!(ending(&Refusal::Newer { host_version: "0.99.1".into() }, "studio"), Some(Connection::Ended { message, .. }) if message.contains("studio") && message.contains("0.99.1")));
559        assert_eq!(ended(Refusal::Refused { status: 401, reason: "forgotten".into(), error: "pair again".into() }), "forgotten");
560    }
561
562    #[tokio::test]
563    async fn a_window_pane_opens_its_agent_once_and_switching_closes_the_one_it_showed() {
564        let dir = tempfile::tempdir().unwrap();
565        let (peers, _) = crate::backend::tower::peers::test_support::peers_in(dir.path());
566        let panes = Panes::new(peers);
567        panes.open_for("b1", "p", "a").unwrap();
568        panes.open_for("b1", "p", "a").expect("a reload asks again");
569        panes.open_for("b2", "p", "a").unwrap();
570        assert_eq!(panes.len(), 1);
571        panes.open_for("b1", "p", "other").unwrap();
572        assert_eq!(panes.len(), 2);
573        panes.close_for("b2");
574        assert!(panes.get("p", "a").is_none(), "b1 moved on and b2 closed: nothing shows it");
575        panes.close_for("b1");
576        panes.close_for("b1");
577        assert!(panes.is_empty());
578    }
579
580    #[tokio::test]
581    async fn forgetting_a_computer_ends_its_panes_at_once_and_leaves_the_others() {
582        let dir = tempfile::tempdir().unwrap();
583        let (peers, _) = crate::backend::tower::peers::test_support::peers_in(dir.path());
584        let panes = Panes::new(peers);
585        let gone = panes.open_for("b1", "p", "a").unwrap();
586        panes.open_for("b2", "p", "b").unwrap();
587        panes.open_for("b3", "q", "a").unwrap();
588        panes.end_computer("p");
589        assert!(gone.stop.is_cancelled());
590        assert!(matches!(gone.facts().connection, Some(Connection::Ended { ref reason, .. }) if reason == "forgotten"));
591        assert_eq!(panes.len(), 1, "only the other computer's pane is left");
592        panes.close_for("b1");
593        assert_eq!(panes.len(), 1, "its window pane no longer counts as showing it");
594        panes.close_for("b3");
595        assert!(panes.is_empty());
596    }
597
598    #[test]
599    fn a_feed_lost_before_it_brought_lines_waits_longer_each_time() {
600        let mut backoff = FIRST_BACKOFF;
601        let mut waits = Vec::new();
602        for _ in 0..7 {
603            let (wait, next) = next_wait(backoff, false);
604            waits.push(wait.as_secs());
605            backoff = next;
606        }
607        assert_eq!(waits, [1, 2, 4, 8, 16, 30, 30], "a host that opens and ends the feed at once is not hammered");
608        assert_eq!(next_wait(backoff, true), (FIRST_BACKOFF, FIRST_BACKOFF * 2), "a feed that brought lines starts over");
609    }
610
611    /// A pairing forgotten here ends the feed with its own words; one whose secrets can't be read now is tried again.
612    #[tokio::test]
613    async fn a_pairing_gone_here_ends_the_feed_and_an_unreadable_one_is_retried() {
614        let dir = tempfile::tempdir().unwrap();
615        let (peers, _) = crate::backend::tower::peers::test_support::peers_in(dir.path());
616        let pane = RemotePane::new("gone", "demo");
617        let refusal = open(&pane, peers, true).await.unwrap_err();
618        assert!(matches!(ending(&refusal, ""), Some(Connection::Ended { ref reason, ref message }) if reason == "forgotten" && message.contains("Pair again")));
619
620        // Kept on disk, but with no secrets to read (a keychain that refuses): not the end of it.
621        let peer = crate::backend::tower::peers::Peer {
622            id: "kept".into(),
623            hostname: "studio".into(),
624            host: "127.0.0.1".into(),
625            port: 9,
626            fingerprint: crate::backend::tower::peers::test_support::FP.into(),
627            device_id: "d".into(),
628            paired_ms: 1,
629            computer: true,
630            channel: String::new(),
631        };
632        crate::backend::tower::peers::test_support::keep(peers, peer);
633        let refusal = open(&RemotePane::new("kept", "demo"), peers, true).await.unwrap_err();
634        assert!(matches!(refusal, Refusal::Unreachable(_)), "{refusal:?}");
635        assert_eq!(ending(&refusal, "studio"), None);
636    }
637
638    /// The banner always has words, in this computer's voice, and an older computer is told which version to update to.
639    #[test]
640    fn a_refusal_with_no_words_still_ends_the_feed_with_some_and_an_older_computer_names_the_version() {
641        let words = |r: Refusal| match ending(&r, "studio") {
642            Some(Connection::Ended { message, .. }) => message,
643            other => panic!("{other:?}"),
644        };
645        let bare_404 = words(Refusal::Refused { status: 404, reason: String::new(), error: String::new() });
646        assert!(bare_404.contains("studio") && bare_404.contains("closed or hidden"), "{bare_404}");
647        let bare_403 = words(Refusal::Refused { status: 403, reason: String::new(), error: String::new() });
648        assert!(bare_403.contains("studio") && bare_403.contains("refused"), "{bare_403}");
649        assert_eq!(words(Refusal::Refused { status: 403, reason: "computers_off".into(), error: "it is off".into() }), "it is off");
650
651        let own = host::own_version();
652        let old = words(Refusal::Outdated { host_version: "0.60.1".into() });
653        assert_eq!(old, format!("studio runs AgentMux 0.60.1, which is too old to show its agents here: update it to AgentMux {own} or newer."));
654        let unknown = words(Refusal::Outdated { host_version: String::new() });
655        assert!(unknown.contains(&format!("update it to AgentMux {own} or newer")), "{unknown}");
656        assert_eq!(why(&Refusal::Outdated { host_version: "0.60.1".into() }, "studio"), old);
657    }
658}