Skip to main content

agentmux_srv_core/backend/
pin_asks.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's ask to move or forget one pin, waiting for the person (`app_api::pin_ask`).
5//!
6//! A pin says which key or install may speak under an agent's name, so changing one is the person's: the pins
7//! screen, or one click on a card in the asking agent's own pane. srv builds each ask from its own record of the pin,
8//! never from words the agent wrote, and keeps it here; the window shows it as a card. The person's answer reaches
9//! srv only through the window (`pins.ask.answer`), takes the ask whole by its id, and carries nothing else: what is
10//! changed is what the card showed, and an agent can neither answer nor change an ask that is waiting.
11//!
12//! An ask nobody answers ends after [`OPEN_MS`] and counts as a no. A no is remembered for [`SETTLED_MS`], so the same
13//! change is not asked again at once.
14
15use std::sync::{Mutex, OnceLock};
16
17use serde::{Deserialize, Serialize};
18
19/// One pin change an agent asked the person for.
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
21#[ts(export, export_to = "../../../frontend/types/rpc/")]
22pub struct PinAsk {
23    /// Names this ask only: an answer to another ask, or to one that was replaced, changes nothing.
24    pub id: String,
25    /// `move` (accept the key or install that was refused for the name) or `forget` (drop the pin).
26    pub change: String,
27    /// `lan` (a key pinned to a name on the local network) or `wan` (an install pinned through the cloud).
28    pub kind: String,
29    /// The agent name the pin is for.
30    pub agent_id: String,
31    /// The channel of a `wan` pin; empty for `lan`.
32    pub channel: String,
33    /// The key (a short fingerprint) or install (`host~id8`) pinned now.
34    pub from: String,
35    /// The install the pinned key is bound to, as `host~id8`; empty when it is bound to none.
36    pub from_install: String,
37    /// What the pin becomes: the refused key or install. Empty for `forget`.
38    pub to: String,
39    /// The install behind the refused key, as `host~id8`; empty when the key came with no certificate.
40    pub to_install: String,
41    /// The agent's reason, as it wrote it.
42    pub reason: String,
43    /// The agent that asked, by its name.
44    pub agent: String,
45    /// The agent that asked, by its id: the one the log names.
46    pub asker_id: String,
47    /// The asking agent's pane, where the card shows.
48    pub block_id: String,
49    #[ts(type = "number")]
50    pub requested_ms: u64,
51}
52
53/// How an ask ended.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Outcome {
56    /// The person allowed it and the pin changed.
57    Allowed,
58    /// The person said no.
59    Declined,
60    /// Nobody answered in time: a no.
61    Expired,
62}
63
64/// What an ask comes to.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub enum Asked {
67    /// The person is asked: the card is shown. `new` when this ask made it, not one already waiting.
68    Waiting { ask: PinAsk, new: bool },
69    /// This same change ended a short while ago.
70    Settled { outcome: Outcome, retry_after_ms: u64 },
71}
72
73/// At most this many asks wait at once; the oldest goes first.
74const MAX_OPEN: usize = 16;
75/// An ask nobody answers ends after this long, as a no.
76pub const OPEN_MS: u64 = 10 * 60 * 1000;
77/// How long how an ask ended is remembered; a no also keeps the same change from being asked again for this long.
78pub const SETTLED_MS: u64 = 10 * 60 * 1000;
79
80struct Settled {
81    identity: String,
82    /// What the yes or no was for: the change, the pin, the agent that asked and the key or install it named.
83    pin: String,
84    outcome: Outcome,
85    at_ms: u64,
86}
87
88#[derive(Default)]
89struct State {
90    open: Vec<PinAsk>,
91    settled: Vec<Settled>,
92}
93
94#[derive(Default)]
95pub struct Asks {
96    state: Mutex<State>,
97}
98
99pub fn asks() -> &'static Asks {
100    static ASKS: OnceLock<Asks> = OnceLock::new();
101    ASKS.get_or_init(Asks::default)
102}
103
104/// The change an ask is for, by what the person is shown and who asks: the same agent asking the same change again is the
105/// same ask, and another agent's ask for it is its own, in its own pane.
106fn identity(ask: &PinAsk) -> String {
107    [&ask.change, &ask.kind, &ask.agent_id, &ask.channel, &ask.from, &ask.to, &ask.asker_id].map(String::as_str).join("\u{1f}")
108}
109
110/// What a yes was for, as the agent that asked can say it again: the change, the pin, the asker, and the key or install it named
111/// (the refused one for a move, the pinned one for a forget). Another agent, or the same one naming something else, does not match.
112fn allowed_key(change: &str, kind: &str, agent_id: &str, channel: &str, asker_id: &str, named: &str) -> String {
113    [change, kind, agent_id, channel, asker_id, named].join("\u{1f}")
114}
115
116/// What `ask` was shown as the thing named: where an agent says what it saw (`expect`).
117fn named_by(ask: &PinAsk) -> &str {
118    if ask.change == "move" {
119        &ask.to
120    } else {
121        &ask.from
122    }
123}
124
125/// One ask waits for a pin from one agent at a time: the same agent asking another change for it replaces its own ask.
126fn same_pin_and_asker(a: &PinAsk, b: &PinAsk) -> bool {
127    a.kind == b.kind && a.agent_id == b.agent_id && a.channel == b.channel && a.asker_id == b.asker_id
128}
129
130impl Asks {
131    fn lock(&self, now_ms: u64) -> std::sync::MutexGuard<'_, State> {
132        let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
133        let (kept, ended): (Vec<_>, Vec<_>) = std::mem::take(&mut state.open).into_iter().partition(|ask| now_ms.saturating_sub(ask.requested_ms) < OPEN_MS);
134        state.open = kept;
135        for ask in ended {
136            state.settled.push(Settled { identity: identity(&ask), pin: allowed_key(&ask.change, &ask.kind, &ask.agent_id, &ask.channel, &ask.asker_id, named_by(&ask)), outcome: Outcome::Expired, at_ms: ask.requested_ms.saturating_add(OPEN_MS) });
137        }
138        state.settled.retain(|s| now_ms.saturating_sub(s.at_ms) < SETTLED_MS);
139        state
140    }
141
142    /// Asks the person. The same change that is already waiting is asked once, and the card stays as it is (what
143    /// the person is shown never changes under them); another change for the same pin replaces it, with a new id.
144    pub fn ask(&self, ask: PinAsk, now_ms: u64) -> Asked {
145        let mut state = self.lock(now_ms);
146        let id = identity(&ask);
147        if let Some(pos) = state.settled.iter().position(|s| s.identity == id) {
148            let s = &state.settled[pos];
149            let (outcome, at_ms) = (s.outcome, s.at_ms);
150            // An ask that timed out is told once; the next ask is a new one.
151            if outcome == Outcome::Expired {
152                state.settled.remove(pos);
153            }
154            return Asked::Settled { outcome, retry_after_ms: SETTLED_MS.saturating_sub(now_ms.saturating_sub(at_ms)) };
155        }
156        if let Some(kept) = state.open.iter().find(|k| identity(k) == id) {
157            return Asked::Waiting { ask: kept.clone(), new: false };
158        }
159        state.open.retain(|k| !same_pin_and_asker(k, &ask));
160        if state.open.len() >= MAX_OPEN {
161            state.open.remove(0);
162        }
163        state.open.push(ask.clone());
164        Asked::Waiting { ask, new: true }
165    }
166
167    /// The asks waiting for the person.
168    pub fn list(&self, now_ms: u64) -> Vec<PinAsk> {
169        self.lock(now_ms).open.clone()
170    }
171
172    /// Takes ask `id` out of the waiting ones, once: whoever gets it is the one answer to it.
173    pub fn take(&self, id: &str, now_ms: u64) -> Option<PinAsk> {
174        let mut state = self.lock(now_ms);
175        let pos = state.open.iter().position(|ask| ask.id == id)?;
176        Some(state.open.remove(pos))
177    }
178
179    /// Remembers how a taken ask ended.
180    pub fn settle(&self, ask: &PinAsk, outcome: Outcome, now_ms: u64) {
181        let mut state = self.lock(now_ms);
182        let id = identity(ask);
183        state.settled.retain(|s| s.identity != id);
184        state.settled.push(Settled { identity: id, pin: allowed_key(&ask.change, &ask.kind, &ask.agent_id, &ask.channel, &ask.asker_id, named_by(ask)), outcome, at_ms: now_ms });
185    }
186
187    /// How long ago the person allowed this kind of change for this pin, when they did within [`SETTLED_MS`]: what an agent
188    /// asking again is told once the pin has moved and there is nothing left to ask about.
189    pub fn allowed_ago_ms(&self, change: &str, kind: &str, agent_id: &str, channel: &str, asker_id: &str, named: &str, now_ms: u64) -> Option<u64> {
190        let pin = allowed_key(change, kind, agent_id, channel, asker_id, named);
191        self.lock(now_ms).settled.iter().filter(|s| s.pin == pin && s.outcome == Outcome::Allowed).map(|s| now_ms.saturating_sub(s.at_ms)).min()
192    }
193
194    /// Ends every ask for the pin of `agent_id` that is waiting: the pin changed by another way.
195    pub fn forget_pin(&self, kind: &str, agent_id: &str, channel: &str, now_ms: u64) {
196        self.lock(now_ms).open.retain(|k| !(k.kind == kind && k.agent_id == agent_id && k.channel == channel));
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    fn ask(id: &str, change: &str, from: &str, to: &str, at: u64) -> PinAsk {
205        PinAsk {
206            id: id.into(),
207            change: change.into(),
208            kind: "lan".into(),
209            agent_id: "opaz".into(),
210            channel: String::new(),
211            from: from.into(),
212            from_install: "charlie~2vb2zq".into(),
213            to: to.into(),
214            to_install: "charlie~iavk4j".into(),
215            reason: "charlie runs the stable install".into(),
216            agent: "Fenn".into(),
217            asker_id: "fenn".into(),
218            block_id: "b1".into(),
219            requested_ms: at,
220        }
221    }
222
223    #[test]
224    fn the_same_change_is_asked_once_and_the_card_is_not_rewritten() {
225        let asks = Asks::default();
226        assert!(matches!(asks.ask(ask("a", "move", "f1", "f2", 10), 10), Asked::Waiting { new: true, .. }));
227        let Asked::Waiting { ask: kept, new } = asks.ask(ask("b", "move", "f1", "f2", 20), 20) else { panic!("waiting") };
228        assert!(!new);
229        assert_eq!((kept.id.as_str(), kept.requested_ms), ("a", 10));
230        assert_eq!(asks.list(20).len(), 1);
231    }
232
233    #[test]
234    fn another_change_for_the_same_pin_replaces_the_ask_and_the_old_id_answers_nothing() {
235        let asks = Asks::default();
236        asks.ask(ask("a", "move", "f1", "f2", 10), 10);
237        asks.ask(ask("b", "forget", "f1", "", 20), 20);
238        let waiting = asks.list(20);
239        assert_eq!(waiting.len(), 1);
240        assert_eq!(waiting[0].id, "b");
241        assert!(asks.take("a", 20).is_none(), "the id of the replaced ask is gone");
242        assert_eq!(asks.take("b", 20).map(|a| a.change), Some("forget".to_string()));
243        assert!(asks.take("b", 20).is_none(), "an ask is taken once");
244    }
245
246    #[test]
247    fn a_no_is_remembered_and_the_same_change_is_not_asked_again_at_once() {
248        let asks = Asks::default();
249        asks.ask(ask("a", "move", "f1", "f2", 0), 0);
250        let taken = asks.take("a", 100).unwrap();
251        asks.settle(&taken, Outcome::Declined, 100);
252        assert_eq!(asks.ask(ask("b", "move", "f1", "f2", 200), 200), Asked::Settled { outcome: Outcome::Declined, retry_after_ms: SETTLED_MS - 100 });
253        assert!(asks.list(200).is_empty());
254        assert!(matches!(asks.ask(ask("c", "move", "f1", "f2", 100 + SETTLED_MS), 100 + SETTLED_MS), Asked::Waiting { new: true, .. }));
255    }
256
257    #[test]
258    fn a_yes_is_remembered_so_the_asking_agent_can_read_it() {
259        let asks = Asks::default();
260        asks.ask(ask("a", "move", "f1", "f2", 0), 0);
261        let taken = asks.take("a", 5).unwrap();
262        asks.settle(&taken, Outcome::Allowed, 5);
263        assert!(matches!(asks.ask(ask("b", "move", "f1", "f2", 6), 6), Asked::Settled { outcome: Outcome::Allowed, .. }));
264        assert!(matches!(asks.ask(ask("b", "move", "f1", "f2", 7), 7), Asked::Settled { outcome: Outcome::Allowed, .. }), "and it stays readable");
265    }
266
267    #[test]
268    fn an_ask_nobody_answers_ends_as_a_no_is_told_once_and_cannot_be_answered_late() {
269        let asks = Asks::default();
270        asks.ask(ask("a", "move", "f1", "f2", 0), 0);
271        assert!(asks.list(OPEN_MS).is_empty());
272        assert!(asks.take("a", OPEN_MS).is_none(), "too late to allow it");
273        assert!(matches!(asks.ask(ask("b", "move", "f1", "f2", OPEN_MS + 1), OPEN_MS + 1), Asked::Settled { outcome: Outcome::Expired, .. }));
274        assert!(matches!(asks.ask(ask("c", "move", "f1", "f2", OPEN_MS + 2), OPEN_MS + 2), Asked::Waiting { new: true, .. }), "the next ask is a new one");
275    }
276
277    #[test]
278    fn the_oldest_goes_when_too_many_wait() {
279        let asks = Asks::default();
280        for n in 0..=MAX_OPEN {
281            let mut a = ask(&format!("a{n}"), "move", "f1", "f2", n as u64);
282            a.agent_id = format!("name{n}");
283            asks.ask(a, n as u64);
284        }
285        let waiting = asks.list(MAX_OPEN as u64);
286        assert_eq!(waiting.len(), MAX_OPEN);
287        assert!(waiting.iter().all(|a| a.id != "a0"));
288    }
289
290    #[test]
291    fn an_agent_asking_again_after_a_yes_is_told_how_long_ago() {
292        let asks = Asks::default();
293        assert_eq!(asks.allowed_ago_ms("move", "lan", "opaz", "", "fenn", "f2", 0), None);
294        asks.ask(ask("a", "move", "f1", "f2", 0), 0);
295        let taken = asks.take("a", 5).unwrap();
296        asks.settle(&taken, Outcome::Allowed, 5);
297        assert_eq!(asks.allowed_ago_ms("move", "lan", "opaz", "", "fenn", "f2", 65), Some(60));
298        assert_eq!(asks.allowed_ago_ms("forget", "lan", "opaz", "", "fenn", "f1", 65), None, "a yes to a move is not a yes to a forget");
299        assert_eq!(asks.allowed_ago_ms("move", "lan", "opaz", "", "fenn", "f3", 65), None, "nor is it a yes to another key than the one allowed");
300        assert_eq!(asks.allowed_ago_ms("move", "lan", "opaz", "", "someone-else", "f2", 65), None, "nor is it told to another agent");
301        assert_eq!(asks.allowed_ago_ms("move", "lan", "opaz", "", "fenn", "f2", 5 + SETTLED_MS), None, "and it is forgotten after a while");
302    }
303
304    #[test]
305    fn two_agents_asking_the_same_change_each_have_their_own_ask_in_their_own_pane() {
306        let asks = Asks::default();
307        asks.ask(ask("a", "move", "f1", "f2", 0), 0);
308        let mut other = ask("b", "move", "f1", "f2", 1);
309        other.asker_id = "korp".into();
310        other.agent = "Korp".into();
311        other.block_id = "b2".into();
312        let Asked::Waiting { ask: second, new } = asks.ask(other.clone(), 1) else { panic!("waiting") };
313        assert!(new, "it is not told it is the first agent's ask");
314        assert_eq!((second.id.as_str(), second.block_id.as_str()), ("b", "b2"));
315        assert_eq!(asks.list(1).len(), 2);
316        // The first agent's no is not the second agent's.
317        let first = asks.take("a", 2).unwrap();
318        asks.settle(&first, Outcome::Declined, 2);
319        assert!(matches!(asks.ask(other, 3), Asked::Waiting { new: false, .. }), "the second agent's ask still waits and is not declined");
320        // One agent replacing its own ask leaves the other agents' alone.
321        let mut forget = ask("c", "forget", "f1", "", 4);
322        forget.asker_id = "korp".into();
323        asks.ask(forget, 4);
324        let waiting: Vec<_> = asks.list(4).into_iter().map(|a| a.id).collect();
325        assert_eq!(waiting, vec!["c".to_string()]);
326    }
327
328    #[test]
329    fn a_pin_changed_another_way_ends_its_ask() {
330        let asks = Asks::default();
331        asks.ask(ask("a", "move", "f1", "f2", 0), 0);
332        asks.forget_pin("lan", "opaz", "", 1);
333        assert!(asks.list(1).is_empty());
334    }
335}