Skip to main content

agentmux_srv_core/backend/remote/
helper_consent.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Asking before AgentMux's helper is installed on a host
5//! (SPEC_REMOTES_PANE_2026_10_05.md §4.9).
6//!
7//! The helper is software put on someone's machine, so nothing is uploaded
8//! until the user says so: in a modal over the pane that needs it
9//! (`sagas::pane_confirm`; with no pane, the approval window), which agents
10//! can neither read nor answer. `conn:helper` for the host, else
11//! the global `conn:helper`, says `ask` (the default), `always` or `never`.
12//! An install an agent's pane sets off is always asked about, whatever the
13//! setting: letting an agent use a host is not letting it install software
14//! there.
15//!
16//! The server installs the window and the settings ([`install`]) once srv is
17//! up; until then (and in tests) there is no one to ask, so nothing installs.
18
19use std::collections::{HashMap, HashSet};
20use std::future::Future;
21use std::pin::Pin;
22use std::sync::{Mutex, OnceLock};
23
24use tokio::sync::watch;
25
26/// What the settings say for a host.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Policy {
29    Ask,
30    Always,
31    Never,
32}
33
34impl Policy {
35    /// `always` and `never` as stored; anything else (unset included) is ask.
36    pub fn parse(value: &str) -> Policy {
37        match value.trim().to_ascii_lowercase().as_str() {
38            "always" => Policy::Always,
39            "never" => Policy::Never,
40            _ => Policy::Ask,
41        }
42    }
43
44    /// The host's own setting, else the global one.
45    pub fn resolve(host: &str, global: &str) -> Policy {
46        if host.trim().is_empty() {
47            Policy::parse(global)
48        } else {
49            Policy::parse(host)
50        }
51    }
52}
53
54/// What to do before installing.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Step {
57    Install,
58    Refuse,
59    Ask,
60}
61
62/// `Always` installs and `Never` refuses without asking, for the user's own
63/// panes only; an agent's always asks.
64pub fn step(policy: Policy, by_agent: bool) -> Step {
65    match (policy, by_agent) {
66        (_, true) | (Policy::Ask, false) => Step::Ask,
67        (Policy::Always, false) => Step::Install,
68        (Policy::Never, false) => Step::Refuse,
69    }
70}
71
72/// The user's answer to the question.
73#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
74pub struct Answer {
75    /// False when the window was closed, timed out or could not open.
76    pub answered: bool,
77    /// Install.
78    pub approve: bool,
79    /// "Don't ask again for this host".
80    pub remember: bool,
81}
82
83/// What an answer does: install or not, and what to store for the host.
84pub fn outcome(answer: Answer) -> (bool, Option<&'static str>) {
85    let install = answer.answered && answer.approve;
86    let remember = (answer.answered && answer.remember).then_some(if install { "always" } else { "never" });
87    (install, remember)
88}
89
90type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
91
92/// What [`allow_install`] needs from the server.
93pub struct Deps {
94    /// Ask the question in the pane (`block_id`), as a modal over it; with none
95    /// (empty), in the approval window over the main window.
96    pub ask: Box<dyn Fn(String, serde_json::Value) -> BoxFuture<Result<Answer, String>> + Send + Sync>,
97    /// `conn:helper` for the host, and the global one.
98    pub settings: Box<dyn Fn(&str) -> (String, String) + Send + Sync>,
99    /// Store `conn:helper` for the host.
100    pub remember: Box<dyn Fn(&str, &str) -> Result<(), String> + Send + Sync>,
101}
102
103static DEPS: OnceLock<Deps> = OnceLock::new();
104
105/// Called once, when srv is up.
106pub fn install(deps: Deps) {
107    let _ = DEPS.set(deps);
108}
109
110/// For tests that install the helper: every question is answered Install.
111#[cfg(test)]
112pub fn install_answering_yes() {
113    install(Deps {
114        ask: Box::new(|_, _| Box::pin(async { Ok(Answer { answered: true, approve: true, remember: false }) })),
115        settings: Box::new(|_| (String::new(), String::new())),
116        remember: Box::new(|_, _| Ok(())),
117    });
118}
119
120/// The most agent panes remembered; past it the oldest go (a pane that old
121/// has long since installed the helper, or not).
122const MAX_AGENT_PANES: usize = 512;
123
124/// Panes an agent opened on a host, and the agent: an install from one of
125/// them is the agent's doing. Kept in memory, not in the pane's meta, which
126/// any caller holding srv's key could clear. `opening` counts the agent
127/// `pane.open`s in flight per host: until one returns its pane isn't noted
128/// yet, so any install on that host asks.
129#[derive(Default)]
130struct AgentPanes {
131    by_block: HashMap<String, String>,
132    order: std::collections::VecDeque<String>,
133    opening: HashMap<String, u32>,
134}
135
136fn agent_panes() -> &'static Mutex<AgentPanes> {
137    static PANES: OnceLock<Mutex<AgentPanes>> = OnceLock::new();
138    PANES.get_or_init(|| Mutex::new(AgentPanes::default()))
139}
140
141fn lock() -> std::sync::MutexGuard<'static, AgentPanes> {
142    agent_panes().lock().unwrap_or_else(|e| e.into_inner())
143}
144
145/// Hosts (by [`host_key`]) remembered until srv restarts.
146type Hosts = OnceLock<Mutex<HashSet<String>>>;
147
148fn hosts(set: &'static Hosts) -> std::sync::MutexGuard<'static, HashSet<String>> {
149    set.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
150}
151
152/// Hosts the user answered "Not now" for since srv started.
153fn declined() -> std::sync::MutexGuard<'static, HashSet<String>> {
154    static DECLINED: Hosts = OnceLock::new();
155    hosts(&DECLINED)
156}
157
158/// Hosts whose terminals were durable by default ([`Mode::Default`]) and whose helper
159/// didn't get installed since srv started: the question went unanswered, or
160/// the install failed. Their panes are plain until then, unless durable is
161/// asked for.
162///
163/// [`Mode::Default`]: crate::backend::blockcontroller::durable_mode::Mode::Default
164fn not_installed_hosts() -> std::sync::MutexGuard<'static, HashSet<String>> {
165    static NOT_INSTALLED: Hosts = OnceLock::new();
166    hosts(&NOT_INSTALLED)
167}
168
169/// Whether `connection`'s helper didn't get installed for a terminal durable by default, since srv started.
170pub fn not_installed(connection: &str) -> bool {
171    not_installed_hosts().contains(&host_key(connection))
172}
173
174/// `connection`'s helper didn't get installed for a terminal durable by default.
175pub fn note_not_installed(connection: &str) {
176    not_installed_hosts().insert(host_key(connection));
177}
178
179/// Whether a durable pane on `connection` runs as a plain SSH terminal
180/// instead, because the user doesn't want the helper there (§4.9: "Not now,
181/// or Never: the pane falls back"): the host is set to Never, or the user
182/// answered "Not now" for it since srv started. Set to Always, never. Also
183/// a host the helper can't run on (a Windows host), whatever the setting.
184pub fn plain_instead(connection: &str) -> bool {
185    if unsupported_host(connection) {
186        return true;
187    }
188    let Some(deps) = DEPS.get() else {
189        return false;
190    };
191    let (host, global) = (deps.settings)(connection);
192    plain_for(
193        Policy::resolve(&host, &global),
194        declined().contains(&host_key(connection)),
195    )
196}
197
198/// Hosts found since srv started to be ones the helper can't run on.
199fn unsupported() -> std::sync::MutexGuard<'static, HashSet<String>> {
200    static UNSUPPORTED: Hosts = OnceLock::new();
201    hosts(&UNSUPPORTED)
202}
203
204/// Whether `connection`'s host was found to be one the helper can't run on.
205pub fn unsupported_host(connection: &str) -> bool {
206    unsupported().contains(&host_key(connection))
207}
208
209/// `connection`'s host can't run the helper (a Windows host, spec §6.4 of
210/// the remote-terminals spec): its durable panes run as plain SSH terminals.
211pub fn note_unsupported(connection: &str) {
212    unsupported().insert(host_key(connection));
213}
214
215/// [`plain_instead`] from the host's policy and whether the user answered
216/// "Not now" for it since srv started.
217fn plain_for(policy: Policy, declined: bool) -> bool {
218    match policy {
219        Policy::Always => false,
220        Policy::Never => true,
221        Policy::Ask => declined,
222    }
223}
224
225/// Hosts the user answered Install for since srv started: the host's other
226/// terminals install without asking again, the first maybe still uploading.
227fn approved() -> std::sync::MutexGuard<'static, HashSet<String>> {
228    static APPROVED: Hosts = OnceLock::new();
229    hosts(&APPROVED)
230}
231
232/// The helper was removed from `connection`'s host: what was answered for it
233/// since srv started (Install, Not now, a failed try) no longer holds, and
234/// its next need asks again. A stored Always or Never is a setting, and stays.
235pub fn forget_answers(connection: &str) {
236    let key = host_key(connection);
237    approved().remove(&key);
238    declined().remove(&key);
239    not_installed_hosts().remove(&key);
240}
241
242/// Remember an answer until srv restarts: "Not now" for [`plain_instead`],
243/// Install so the host isn't asked again; each undoes the other. A closed
244/// window is no answer.
245pub(crate) fn note_answer(connection: &str, answer: Answer) {
246    if !answer.answered {
247        return;
248    }
249    let key = host_key(connection);
250    if answer.approve {
251        declined().remove(&key);
252        approved().insert(key);
253    } else {
254        approved().remove(&key);
255        declined().insert(key);
256    }
257}
258
259/// One host, however it is spelled.
260fn host_key(connection: &str) -> String {
261    super::ConnTarget::parse(connection)
262        .map(|t| t.name())
263        .unwrap_or_else(|_| connection.trim().to_string())
264}
265
266/// `block_id` was opened by `agent` (a verified agent's `pane.open` on a host).
267pub fn note_agent_pane(block_id: &str, agent: &str) {
268    lock().note(block_id, agent);
269}
270
271impl AgentPanes {
272    /// [`note_agent_pane`] in this set: past [`MAX_AGENT_PANES`] the oldest go.
273    fn note(&mut self, block_id: &str, agent: &str) {
274        if block_id.is_empty() {
275            return;
276        }
277        if self.by_block.insert(block_id.to_string(), agent.to_string()).is_none() {
278            self.order.push_back(block_id.to_string());
279        }
280        while self.order.len() > MAX_AGENT_PANES {
281            if let Some(old) = self.order.pop_front() {
282                self.by_block.remove(&old);
283            }
284        }
285    }
286}
287
288/// An agent's `pane.open` on a host is in flight while this lives.
289pub struct AgentOpening(String);
290
291impl Drop for AgentOpening {
292    fn drop(&mut self) {
293        let mut panes = lock();
294        if let Some(n) = panes.opening.get_mut(&self.0) {
295            *n = n.saturating_sub(1);
296            if *n == 0 {
297                panes.opening.remove(&self.0);
298            }
299        }
300    }
301}
302
303/// Call before an agent's `pane.open` on `connection`; hold the guard until
304/// the pane is noted ([`note_agent_pane`]).
305pub fn begin_agent_open(connection: &str) -> AgentOpening {
306    let key = host_key(connection);
307    *lock().opening.entry(key.clone()).or_default() += 1;
308    AgentOpening(key)
309}
310
311fn agent_of(block_id: Option<&str>) -> Option<String> {
312    let block_id = block_id.filter(|b| !b.is_empty())?;
313    lock().by_block.get(block_id).cloned()
314}
315
316fn agent_opening(connection: &str) -> bool {
317    lock().opening.contains_key(&host_key(connection))
318}
319
320/// The question (§4.9).
321pub fn question(connection: &str, agent: Option<&str>) -> serde_json::Value {
322    let who = match agent {
323        Some(a) => format!("{a} is using a pane on {connection} that needs it. "),
324        None => String::new(),
325    };
326    serde_json::json!({
327        "kind": "consent",
328        "title": format!("Install AgentMux's helper on {connection}?"),
329        "message": format!(
330            "{who}The helper enables file browsing and terminals that survive disconnects. \
331             It is about 500 KB, in ~/.agentmux-remote on that machine; it needs no root, \
332             and you can remove it any time from Connectors > Remotes."
333        ),
334        "checkbox": format!("Don't ask again for {connection}"),
335        "ok_label": "Install",
336        "cancel_label": "Not now",
337    })
338}
339
340/// What needs the helper on a host: it decides what an answer given earlier
341/// for the host (since srv started) means now.
342#[derive(Debug, Clone, Copy, PartialEq, Eq)]
343pub enum Need {
344    /// The host's files: after a Not now, Reconnect asks again.
345    Files,
346    /// A terminal: a Not now holds until srv restarts, and so does an earlier
347    /// failed try when it is durable only `by_default`.
348    Terminal { by_default: bool },
349}
350
351/// Whether the helper may be installed on `connection` now, for the pane
352/// `block_id` (`None`: no pane, which counts as an agent's doing). `Err`
353/// says why not, for the pane to show.
354pub async fn allow_install(connection: &str, block_id: Option<&str>, need: Need) -> Result<(), String> {
355    let deps = DEPS
356        .get()
357        .ok_or_else(|| "AgentMux could not ask whether to install its helper".to_string())?;
358    allow_install_with(deps, connection, block_id, need).await
359}
360
361/// The user's question per host while it is open: their other panes on that
362/// host wait for its answer instead of asking again.
363fn open_questions() -> std::sync::MutexGuard<'static, HashMap<String, watch::Receiver<Option<Answer>>>> {
364    static OPEN: OnceLock<Mutex<HashMap<String, watch::Receiver<Option<Answer>>>>> = OnceLock::new();
365    OPEN.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
366}
367
368/// What was answered for the host since srv started, as it holds for
369/// `need`: `None` to ask. Read with the open questions locked, so a question
370/// closing meanwhile can't be missed (its answer is noted before it closes).
371fn held(connection: &str, key: &str, need: Need) -> Option<Result<(), String>> {
372    // A failed try first: an Install answered before it doesn't make the
373    // upload work this time.
374    if need == (Need::Terminal { by_default: true }) && not_installed_hosts().contains(key) {
375        return Some(Err("it didn't install on this host earlier".to_string()));
376    }
377    if approved().contains(key) {
378        return Some(Ok(()));
379    }
380    match need {
381        Need::Terminal { .. } if declined().contains(key) => {
382            Some(Err(format!("you chose not to install AgentMux's helper on {connection}")))
383        }
384        _ => None,
385    }
386}
387
388/// Ask the user about `connection` once: a question already open for the
389/// host answers this pane too, and so does an answer given earlier
390/// ([`held`]). A failed question counts as no answer.
391async fn ask_once(deps: &Deps, connection: &str, block_id: &str, need: Need) -> Result<(), String> {
392    let key = host_key(connection);
393    let tx = loop {
394        let open = {
395            let mut open = open_questions();
396            match open.get(&key) {
397                Some(rx) => Err(rx.clone()),
398                None => {
399                    if let Some(earlier) = held(connection, &key, need) {
400                        return earlier;
401                    }
402                    let (tx, rx) = watch::channel(None);
403                    open.insert(key.clone(), rx);
404                    Ok(tx)
405                }
406            }
407        };
408        match open {
409            Ok(tx) => break tx,
410            Err(mut rx) => match rx.wait_for(Option::is_some).await {
411                Ok(answer) => return verdict(connection, answer.unwrap_or_default()),
412                // The asking pane went away without an answer (closed, or
413                // stopped): this pane asks instead. The user said nothing
414                // about it.
415                Err(_) => continue,
416            },
417        }
418    };
419    // However this ends, even dropped with its pane, the question closes.
420    let _open = OpenQuestion(key);
421    let answer = match (deps.ask)(block_id.to_string(), question(connection, None)).await {
422        Ok(answer) => answer,
423        Err(e) => {
424            tracing::warn!(connection = %connection, error = %e, "helper install: could not ask");
425            Answer::default()
426        }
427    };
428    record(deps, connection, None, answer);
429    // Unanswered, for a terminal durable only by default: a failed try,
430    // noted before the question closes so a terminal arriving now sees it.
431    if !answer.answered && need == (Need::Terminal { by_default: true }) {
432        note_not_installed(connection);
433    }
434    let _ = tx.send(Some(answer));
435    verdict(connection, answer)
436}
437
438/// What an answer means for the pane: install, or why not.
439fn verdict(connection: &str, answer: Answer) -> Result<(), String> {
440    if outcome(answer).0 {
441        Ok(())
442    } else if answer.answered {
443        Err(format!("you chose not to install AgentMux's helper on {connection}"))
444    } else {
445        Err(format!("nobody answered whether to install AgentMux's helper on {connection}"))
446    }
447}
448
449/// A host's open question, closed on drop.
450struct OpenQuestion(String);
451
452impl Drop for OpenQuestion {
453    fn drop(&mut self) {
454        open_questions().remove(&self.0);
455    }
456}
457
458/// Store and log an answer once, where it was asked.
459fn record(deps: &Deps, connection: &str, agent: Option<&str>, answer: Answer) {
460    let (install, remember) = outcome(answer);
461    if let Some(value) = remember {
462        if let Err(e) = (deps.remember)(connection, value) {
463            tracing::warn!(connection = %connection, error = %e, "helper install: could not store the answer");
464        }
465    }
466    tracing::info!(connection = %connection, agent = ?agent, install, remember = ?remember, "helper install: asked");
467    note_answer(connection, answer);
468}
469
470/// [`allow_install`] with its dependencies given.
471async fn allow_install_with(deps: &Deps, connection: &str, block_id: Option<&str>, need: Need) -> Result<(), String> {
472    let agent = agent_of(block_id);
473    let by_agent = agent.is_some() || block_id.is_none_or(str::is_empty) || agent_opening(connection);
474    let (host, global) = (deps.settings)(connection);
475    match step(Policy::resolve(&host, &global), by_agent) {
476        Step::Install => return Ok(()),
477        Step::Refuse => {
478            return Err(format!(
479                "installing AgentMux's helper on {connection} is set to Never (change it in Connectors > Remotes)"
480            ))
481        }
482        Step::Ask => {}
483    }
484    if !by_agent {
485        return ask_once(deps, connection, block_id.unwrap_or_default(), need).await;
486    }
487    // An agent's question names the agent, and is its own.
488    let answer = (deps.ask)(
489        block_id.unwrap_or_default().to_string(),
490        question(connection, agent.as_deref()),
491    )
492    .await?;
493    record(deps, connection, agent.as_deref(), answer);
494    verdict(connection, answer)
495}
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500
501    /// A restart brings back all of a host's terminals at once: they share
502    /// one question rather than each opening its own window.
503    #[tokio::test]
504    async fn a_hosts_panes_share_one_question() {
505        use std::sync::atomic::{AtomicUsize, Ordering};
506        let asked = std::sync::Arc::new(AtomicUsize::new(0));
507        let deps = {
508            let asked = asked.clone();
509            Deps {
510                ask: Box::new(move |_, _| {
511                    asked.fetch_add(1, Ordering::SeqCst);
512                    Box::pin(async {
513                        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
514                        Ok(Answer { answered: true, approve: true, remember: false })
515                    })
516                }),
517                settings: Box::new(|_| (String::new(), String::new())),
518                remember: Box::new(|_, _| Ok(())),
519            }
520        };
521        let (a, b, c) = tokio::join!(
522            allow_install_with(&deps, "me@shared-question-host", Some("blk-shared-1"), Need::Files),
523            allow_install_with(&deps, " me@shared-question-host ", Some("blk-shared-2"), Need::Files),
524            allow_install_with(&deps, "me@other-question-host", Some("blk-shared-3"), Need::Files),
525        );
526        assert_eq!((a, b, c), (Ok(()), Ok(()), Ok(())));
527        assert_eq!(asked.load(Ordering::SeqCst), 2, "one question per host");
528
529        // A terminal that gets to the host after the question closed (the
530        // first is still uploading the helper) doesn't ask again.
531        let later = allow_install_with(&deps, "me@shared-question-host", Some("blk-shared-4"), Need::Files).await;
532        assert_eq!(later, Ok(()));
533        assert_eq!(asked.load(Ordering::SeqCst), 2, "Install holds until srv restarts");
534
535        // Removing the helper (Remotes) undoes it: the next need asks again.
536        forget_answers(" me@shared-question-host ");
537        let after_removal = allow_install_with(&deps, "me@shared-question-host", Some("blk-shared-5"), Need::Files).await;
538        assert_eq!(after_removal, Ok(()));
539        assert_eq!(asked.load(Ordering::SeqCst), 3, "asked again after the helper was removed");
540
541    }
542
543    /// A terminal holds a Not now (and, durable only by default, an earlier
544    /// failed try) until srv restarts, read in the same step that would open a
545    /// question; Files asks again (its Reconnect).
546    #[tokio::test]
547    async fn what_an_earlier_answer_means_depends_on_the_need() {
548        use std::sync::atomic::{AtomicUsize, Ordering};
549        static ASKED: AtomicUsize = AtomicUsize::new(0);
550        static DEPS_COUNTS: OnceLock<Deps> = OnceLock::new();
551        let deps = DEPS_COUNTS.get_or_init(|| Deps {
552            ask: Box::new(|_, _| {
553                ASKED.fetch_add(1, Ordering::SeqCst);
554                Box::pin(async { Ok(Answer { answered: true, approve: false, remember: false }) })
555            }),
556            settings: Box::new(|_| (String::new(), String::new())),
557            remember: Box::new(|_, _| Ok(())),
558        });
559        let terminal = Need::Terminal { by_default: true };
560        note_answer("me@need-declined-host", Answer { answered: true, approve: false, remember: false });
561        assert!(allow_install_with(deps, "me@need-declined-host", Some("blk-need-1"), terminal).await.is_err());
562        assert_eq!(ASKED.load(Ordering::SeqCst), 0, "a terminal isn't asked again after Not now");
563        let _ = allow_install_with(deps, "me@need-declined-host", Some("blk-need-2"), Need::Files).await;
564        assert_eq!(ASKED.load(Ordering::SeqCst), 1, "Files' Reconnect asks again");
565
566        note_not_installed("me@need-failed-host");
567        let failed = allow_install_with(deps, "me@need-failed-host", Some("blk-need-3"), terminal).await;
568        assert_eq!(failed, Err("it didn't install on this host earlier".to_string()));
569        assert_eq!(ASKED.load(Ordering::SeqCst), 1);
570        let chosen = Need::Terminal { by_default: false };
571        let _ = allow_install_with(deps, "me@need-failed-host", Some("blk-need-4"), chosen).await;
572        assert_eq!(ASKED.load(Ordering::SeqCst), 2, "a terminal set to durable asks");
573    }
574
575    /// Install was answered but the upload failed: a terminal durable only by
576    /// default doesn't try again (Files may). And a question closed
577    /// unanswered is noted as a failed try before it closes, so no terminal
578    /// slips in between and asks again.
579    #[tokio::test]
580    async fn a_failed_or_unanswered_try_holds_for_default_terminals() {
581        use std::sync::atomic::{AtomicUsize, Ordering};
582        static ASKED: AtomicUsize = AtomicUsize::new(0);
583        static DEPS_NO_ANSWER: OnceLock<Deps> = OnceLock::new();
584        let deps = DEPS_NO_ANSWER.get_or_init(|| Deps {
585            ask: Box::new(|_, _| {
586                ASKED.fetch_add(1, Ordering::SeqCst);
587                Box::pin(async { Ok(Answer::default()) })
588            }),
589            settings: Box::new(|_| (String::new(), String::new())),
590            remember: Box::new(|_, _| Ok(())),
591        });
592        let terminal = Need::Terminal { by_default: true };
593        note_answer("me@approved-failed-host", Answer { answered: true, approve: true, remember: false });
594        note_not_installed("me@approved-failed-host");
595        let retry = allow_install_with(deps, "me@approved-failed-host", Some("blk-af-1"), terminal).await;
596        assert!(retry.is_err(), "a failed install outweighs the Install answer");
597        let files = allow_install_with(deps, "me@approved-failed-host", Some("blk-af-2"), Need::Files).await;
598        assert_eq!(files, Ok(()), "Files tries again on the Install answer");
599        assert_eq!(ASKED.load(Ordering::SeqCst), 0);
600
601        let unanswered = allow_install_with(deps, "me@unanswered-host", Some("blk-af-3"), terminal).await;
602        assert!(unanswered.is_err());
603        assert!(not_installed("me@unanswered-host"), "noted before the question closed");
604    }
605
606    /// The pane asking is closed mid-question: a pane waiting on its answer
607    /// asks instead, rather than taking the closed pane's "no answer".
608    #[tokio::test]
609    async fn a_waiting_pane_asks_when_the_asking_pane_closes() {
610        use std::sync::atomic::{AtomicUsize, Ordering};
611        static ASKED: AtomicUsize = AtomicUsize::new(0);
612        static DEPS_SECOND_ANSWERS: OnceLock<Deps> = OnceLock::new();
613        let deps = DEPS_SECOND_ANSWERS.get_or_init(|| Deps {
614            ask: Box::new(|_, _| {
615                if ASKED.fetch_add(1, Ordering::SeqCst) == 0 {
616                    Box::pin(std::future::pending())
617                } else {
618                    Box::pin(async { Ok(Answer { answered: true, approve: true, remember: false }) })
619                }
620            }),
621            settings: Box::new(|_| (String::new(), String::new())),
622            remember: Box::new(|_, _| Ok(())),
623        });
624        let asking = tokio::spawn(allow_install_with(deps, "me@handover-host", Some("blk-handover-1"), Need::Files));
625        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
626        let waiting = tokio::spawn(allow_install_with(deps, "me@handover-host", Some("blk-handover-2"), Need::Files));
627        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
628        asking.abort();
629        let waited = tokio::time::timeout(std::time::Duration::from_secs(5), waiting).await;
630        assert_eq!(waited.expect("the waiting pane gets an answer").unwrap(), Ok(()));
631        assert_eq!(ASKED.load(Ordering::SeqCst), 2, "asked again, by the pane still open");
632    }
633
634    /// The pane asking is closed mid-question: the question doesn't stay
635    /// open for the host, answering every later pane "no answer".
636    #[tokio::test]
637    async fn a_question_whose_pane_closed_is_not_left_open() {
638        static DEPS_NEVER_ANSWERS: OnceLock<Deps> = OnceLock::new();
639        let deps = DEPS_NEVER_ANSWERS.get_or_init(|| Deps {
640            ask: Box::new(|_, _| Box::pin(std::future::pending())),
641            settings: Box::new(|_| (String::new(), String::new())),
642            remember: Box::new(|_, _| Ok(())),
643        });
644        let asking = tokio::spawn(allow_install_with(deps, "me@closed-question-host", Some("blk-closed"), Need::Files));
645        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
646        assert!(open_questions().contains_key("me@closed-question-host"));
647        asking.abort();
648        let _ = asking.await;
649        assert!(!open_questions().contains_key("me@closed-question-host"));
650    }
651
652    #[test]
653    fn the_hosts_setting_wins_over_the_global_one() {
654        assert_eq!(Policy::resolve("", ""), Policy::Ask);
655        assert_eq!(Policy::resolve("", "Always"), Policy::Always);
656        assert_eq!(Policy::resolve("never", "always"), Policy::Never);
657        assert_eq!(Policy::resolve("ask", "never"), Policy::Ask);
658        assert_eq!(Policy::resolve("nonsense", "always"), Policy::Ask);
659    }
660
661    #[test]
662    fn an_agents_install_is_always_asked_about() {
663        assert_eq!(step(Policy::Always, false), Step::Install);
664        assert_eq!(step(Policy::Never, false), Step::Refuse);
665        assert_eq!(step(Policy::Ask, false), Step::Ask);
666        for p in [Policy::Ask, Policy::Always, Policy::Never] {
667            assert_eq!(step(p, true), Step::Ask, "{p:?}");
668        }
669    }
670
671    #[test]
672    fn the_four_answers() {
673        let a = |approve, remember| Answer { answered: true, approve, remember };
674        assert_eq!(outcome(a(true, false)), (true, None), "Install");
675        assert_eq!(outcome(a(true, true)), (true, Some("always")), "Always for this host");
676        assert_eq!(outcome(a(false, false)), (false, None), "Not now");
677        assert_eq!(outcome(a(false, true)), (false, Some("never")), "Never for this host");
678        let closed = Answer { answered: false, approve: false, remember: true };
679        assert_eq!(outcome(closed), (false, None), "a closed window stores nothing");
680    }
681
682    #[test]
683    fn a_host_the_user_doesnt_want_the_helper_on_gets_a_plain_terminal() {
684        assert!(plain_for(Policy::Never, false), "Never");
685        assert!(plain_for(Policy::Ask, true), "Not now, since srv started");
686        assert!(!plain_for(Policy::Ask, false), "not asked yet");
687        assert!(!plain_for(Policy::Always, true), "Always wins over an earlier Not now");
688    }
689
690    #[test]
691    fn not_now_is_remembered_until_an_install_and_a_closed_window_is_no_answer() {
692        let a = |answered, approve| Answer { answered, approve, remember: false };
693        let host = "me@declined-host";
694        note_answer(host, a(false, false));
695        assert!(!declined().contains(host), "a closed window");
696        note_answer(&format!(" {host} "), a(true, false));
697        assert!(declined().contains(host), "Not now, however the host is spelled");
698        note_answer(host, a(true, true));
699        assert!(!declined().contains(host), "a later Install");
700    }
701
702    #[test]
703    fn a_host_the_helper_cant_run_on_gets_a_plain_terminal_whatever_the_setting() {
704        assert!(!plain_instead("me@windows-host"));
705        note_unsupported(" me@windows-host ");
706        assert!(plain_instead("me@windows-host"));
707    }
708
709    #[test]
710    fn the_question_names_the_host_and_the_agent() {
711        let q = question("db1", Some("korp"));
712        assert_eq!(q["kind"], "consent");
713        assert!(q["title"].as_str().unwrap().contains("db1"));
714        assert!(q["message"].as_str().unwrap().starts_with("korp is using"));
715        assert_eq!(q["ok_label"], "Install");
716        assert!(!question("db1", None)["message"].as_str().unwrap().contains("is using"));
717    }
718
719    #[test]
720    fn a_pane_an_agent_opened_is_the_agents() {
721        note_agent_pane("blk-agent-opened", "korp");
722        assert_eq!(agent_of(Some("blk-agent-opened")).as_deref(), Some("korp"));
723        assert_eq!(agent_of(Some("blk-users-own")), None);
724        assert_eq!(agent_of(None), None);
725    }
726
727    #[test]
728    fn a_host_an_agent_is_opening_a_pane_on_asks() {
729        assert!(!agent_opening("me@opening-host"));
730        let first = begin_agent_open("me@opening-host");
731        let second = begin_agent_open(" me@opening-host ");
732        assert!(agent_opening("me@opening-host"), "however it is spelled");
733        assert!(!agent_opening("me@other-host"));
734        drop(first);
735        assert!(agent_opening("me@opening-host"), "one still in flight");
736        drop(second);
737        assert!(!agent_opening("me@opening-host"));
738    }
739
740    /// In a set of its own: filling the shared one evicted what the test
741    /// above had just noted, when the two ran at once.
742    #[test]
743    fn the_agent_panes_kept_are_bounded() {
744        let mut panes = AgentPanes::default();
745        for i in 0..MAX_AGENT_PANES + 10 {
746            panes.note(&format!("blk-bound-{i}"), "korp");
747        }
748        assert!(panes.by_block.len() <= MAX_AGENT_PANES);
749        assert_eq!(panes.by_block.len(), panes.order.len());
750        assert!(!panes.by_block.contains_key("blk-bound-0"), "the oldest went");
751    }
752}