Skip to main content

agentmux_srv/server/app_api/
pins.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `pins.list` / `pins.forget` / `pins.adopt`: the keys and installs this
5//! machine has pinned to the names of agents that speak to it from elsewhere
6//! (the LAN name pin, and the WAN install pin), and the way to move one.
7//!
8//! A pin decides who may speak as an agent, so changing one needs proof. The
9//! operator's own window, proven by the host, may change any of them. An agent's
10//! connection may list the pins (fingerprints only) and `adopt` a refused LAN key,
11//! but only when srv itself finds the key vouched for by the install that hosts the
12//! agent (`lan_continuity`, SPEC_LAN_KEY_CONTINUITY_2026_10_29.md): the caller's
13//! word counts for nothing. `forget` stays with the window: forgetting a pin makes
14//! the next key shown for the name first-seen, which is exactly how an impostor
15//! would get in, and it has no proof to ask for. Every change is logged to
16//! `logs/pin-changes.log`, with who made it.
17//! `forget` drops a pin so the next key or install shown for the name is
18//! pinned; `adopt` pins the key or install that was last refused for it.
19
20use serde_json::json;
21
22use super::*;
23use crate::backend::rpc_types::{
24    CommandPinsChangeData, CommandPinsListData, LanPinInfo, PinnedSendersResult, RefusedInstanceInfo, RefusedKeyInfo, WanPinInfo,
25    COMMAND_PINS_ADOPT, COMMAND_PINS_FORGET, COMMAND_PINS_LIST,
26};
27use crate::server::reactive::lan_continuity::{self, fingerprint};
28use crate::server::reactive::lan_refusals;
29
30pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
31    super::pin_ask::register(engine, state);
32    let st = state.clone();
33    engine.register_typed(COMMAND_PINS_LIST, move |_req: CommandPinsListData, ctx| {
34        let state = st.clone();
35        async move {
36            // Fingerprints only, never a key: an agent may read them.
37            if ctx.agent_id.is_empty() {
38                operator(&ctx)?;
39            }
40            list(&state)
41        }
42    });
43
44    let st = state.clone();
45    engine.register_typed(COMMAND_PINS_FORGET, move |req: CommandPinsChangeData, ctx| {
46        let state = st.clone();
47        async move {
48            operator(&ctx)?;
49            change(&state, &req, Change::Forget, None)?;
50            list(&state)
51        }
52    });
53
54    let st = state.clone();
55    engine.register_typed(COMMAND_PINS_ADOPT, move |req: CommandPinsChangeData, ctx| {
56        let state = st.clone();
57        async move {
58            if ctx.agent_id.is_empty() {
59                operator(&ctx)?;
60                change(&state, &req, Change::Adopt, None)?;
61            } else {
62                agent_adopt(&state, &ctx, &req).await?;
63            }
64            list(&state)
65        }
66    });
67}
68
69/// An agent's `adopt` of a refused LAN key: done only if the install that hosts the
70/// agent vouches for it and this machine trusts that install, found by srv now. The
71/// exception is a name with no pin yet: its first key can be accepted without a vouch
72/// (there is no pin to move), and the acceptance is logged as the agent that made it.
73async fn agent_adopt(state: &AppState, ctx: &RpcContext, req: &CommandPinsChangeData) -> Result<(), String> {
74    use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
75    if req.kind != "lan" {
76        return Err("pins: an agent adopts a LAN key only; an install pin needs the user's window".to_string());
77    }
78    let agent = req.agent_id.trim().to_lowercase();
79    if agent.is_empty() {
80        return Err("pins: no agent named".to_string());
81    }
82    let refused = lan_refusals::get(&agent).ok_or_else(|| format!("pins: no other key has been shown for {agent} since AgentMux started"))?;
83    confirm_shown(req.expect.as_deref(), &fingerprint(&refused.key_b64), &agent)?;
84    // A name with no pin yet: the key was shown and no trusted install vouched for it, so nothing was pinned.
85    // Accepting it is a choice, the person's or an agent's, and is recorded as whoever made it.
86    if state.mstore.lan_peer_pubkey_pin_since(&agent).map_err(|e| format!("pins: {e}"))?.is_none() {
87        let shown = BASE64.decode(&refused.key_b64).map_err(|_| "pins: the refused key is not a key".to_string())?;
88        if let Some(why) = lan_continuity::retired_reason(state, &agent, &shown) {
89            return Err(format!("pins: not accepted: {why}"));
90        }
91        let held = state.mstore.lan_peer_pubkey_pin_get_or_set(&agent, &refused.key_b64).map_err(|e| format!("pins: {e}"))?;
92        if held != refused.key_b64 {
93            return Err(format!("pins: another key was pinned for {agent} in the meantime; look at it again"));
94        }
95        lan_refusals::clear(&agent);
96        lan_continuity::audit(&json!({ "action": "first-pin", "kind": "lan", "agent": agent, "to": fingerprint(&held), "by": ctx.agent_id }));
97        state.broker.publish_event::<crate::backend::mps_events::PinsChanged>(&(), vec![], 0);
98        return Ok(());
99    }
100    let key = BASE64.decode(&refused.key_b64).map_err(|_| "pins: the refused key is not a key".to_string())?;
101    lan_continuity::move_if_vouched(state, &agent, &key, refused.cert.as_ref(), &ctx.agent_id, true)
102        .await
103        .map(|_| ())
104        .map_err(|why| format!("pins: not vouched for, so not accepted: {why}"))
105}
106
107fn operator(ctx: &RpcContext) -> Result<(), String> {
108    ctx.operator_only("only the user lists or changes the keys and installs pinned to agent names")
109}
110
111#[derive(Clone, Copy, PartialEq, Eq)]
112pub(super) enum Change {
113    Forget,
114    Adopt,
115}
116
117impl Change {
118    fn as_str(self) -> &'static str {
119        match self {
120            Change::Forget => "forget",
121            Change::Adopt => "adopt",
122        }
123    }
124}
125
126fn list(state: &AppState) -> Result<PinnedSendersResult, String> {
127    let mut lan: Vec<LanPinInfo> = state
128        .mstore
129        .lan_peer_pins_list()
130        .map_err(|e| format!("pins: could not read the LAN pins: {e}"))?
131        .into_iter()
132        .map(|(agent_id, key, pinned_at, uid_pins)| {
133            let refused = lan_refusals::get(&agent_id)
134                .filter(|r| r.key_b64 != key)
135                .map(|r| RefusedKeyInfo { key_fp: fingerprint(&r.key_b64), last_seen_at: r.last_seen_at, count: r.count, why: r.why });
136            let bound_to = state.mstore.lan_pin_installed(&agent_id).ok().flatten().map(|i| label(&i.host_hint, &i.instance_id));
137            LanPinInfo { key_fp: fingerprint(&key), agent_id, pinned_at, uid_pins, refused, bound_to }
138        })
139        .collect();
140    // A name with no pin that showed a key nobody vouched for is listed with no pinned key (`key_fp` empty),
141    // so the person can accept it once.
142    let pinned: std::collections::HashSet<String> = lan.iter().map(|p| p.agent_id.to_lowercase()).collect();
143    let mut first: Vec<LanPinInfo> = lan_refusals::all()
144        .into_iter()
145        .filter(|(name, _)| !pinned.contains(name))
146        .map(|(agent_id, r)| LanPinInfo {
147            agent_id,
148            key_fp: String::new(),
149            pinned_at: 0,
150            uid_pins: 0,
151            refused: Some(RefusedKeyInfo { key_fp: fingerprint(&r.key_b64), last_seen_at: r.last_seen_at, count: r.count, why: r.why }),
152            bound_to: None,
153        })
154        .collect();
155    first.sort_by(|a, b| a.agent_id.cmp(&b.agent_id));
156    lan.extend(first);
157    let wan = match crate::backend::storage::wan_identity::global() {
158        Some(wan) => wan
159            .agent_instance_pins_list()
160            .map_err(|e| format!("pins: could not read the WAN pins: {e}"))?
161            .into_iter()
162            .map(|p| WanPinInfo {
163                instance: label(&p.host_hint, &p.instance_id),
164                refused: p.conflict.map(|c| RefusedInstanceInfo {
165                    instance: label(&c.host_hint, &c.instance_id),
166                    last_seen_at: c.last_seen_at,
167                    count: c.count as u32,
168                }),
169                agent_id: p.agent_id,
170                channel: p.channel,
171                pinned_at: p.pinned_at,
172            })
173            .collect(),
174        None => Vec::new(),
175    };
176    Ok(PinnedSendersResult { lan, wan })
177}
178
179pub(super) fn label(host_hint: &str, instance_id: &str) -> String {
180    agentmux_common::jekt_sign::wan_instance_display_label(host_hint, instance_id)
181}
182
183/// Changes one pin. `by` is the agent that asked and that the person allowed on a card (`pin_ask`), and `None` when the
184/// person's own window makes the change: the log says which, and for an agent's change it says the person confirmed it.
185pub(super) fn change(state: &AppState, req: &CommandPinsChangeData, how: Change, by: Option<&str>) -> Result<(), String> {
186    let agent = req.agent_id.trim().to_lowercase();
187    if agent.is_empty() {
188        return Err("pins: no agent named".to_string());
189    }
190    let done = match req.kind.as_str() {
191        "lan" => change_lan(state, &agent, how, req.expect.as_deref(), by)?,
192        "wan" => change_wan(&agent, req.channel.as_deref().ok_or("pins: a WAN pin needs its channel")?, how, req.expect.as_deref())?,
193        other => return Err(format!("pins: unknown kind {other:?} (lan or wan)")),
194    };
195    // Accepting the first key of a name that had no pin is a `first-pin`, as it is when an agent or a vouching install does it.
196    let action = if how == Change::Adopt && req.kind == "lan" && done.0.is_none() { "first-pin" } else { how.as_str() };
197    let mut entry = json!({ "action": action, "kind": req.kind, "agent": agent, "channel": req.channel, "from": done.0, "to": done.1, "by": by.unwrap_or("operator") });
198    if by.is_some() {
199        entry["confirmed_by"] = json!("person");
200    }
201    lan_continuity::audit(&entry);
202    state.broker.publish_event::<crate::backend::mps_events::PinsChanged>(&(), vec![], 0);
203    super::pin_ask::pin_changed(state, &req.kind, &agent, req.channel.as_deref().unwrap_or_default());
204    Ok(())
205}
206
207/// What a change moved: the pin before and after, as screen labels.
208type Moved = (Option<String>, Option<String>);
209
210/// An adoption is of what the screen showed: `shown` must be the refused key or
211/// install srv holds now, or something else was refused in between.
212pub(super) fn confirm_shown(expect: Option<&str>, held: &str, agent: &str) -> Result<(), String> {
213    match expect {
214        Some(shown) if shown == held => Ok(()),
215        Some(_) => Err(format!("pins: what was refused for {agent} has changed since the list; look at it again")),
216        None => Err("pins: say which key or install is being accepted".to_string()),
217    }
218}
219
220fn change_lan(state: &AppState, agent: &str, how: Change, expect: Option<&str>, by: Option<&str>) -> Result<Moved, String> {
221    let store_err = |e: crate::backend::storage::error::StoreError| format!("pins: {e}");
222    match how {
223        Change::Forget => {
224            let old = state
225                .mstore
226                .lan_peer_pin_forget(agent)
227                .map_err(store_err)?
228                .ok_or_else(|| format!("pins: no LAN pin for {agent}"))?;
229            lan_refusals::clear(agent);
230            Ok((Some(fingerprint(&old)), None))
231        }
232        Change::Adopt => {
233            let refused = lan_refusals::get(agent).ok_or_else(|| format!("pins: no other key has been shown for {agent} since AgentMux started"))?;
234            confirm_shown(expect, &fingerprint(&refused.key_b64), agent)?;
235            let old = state.mstore.lan_peer_pubkey_pin_replace(agent, &refused.key_b64).map_err(store_err)?;
236            if let Some(old) = &old {
237                let retired_by = by.map_or_else(|| "operator".to_string(), |agent| format!("{agent}, confirmed by the person"));
238                lan_continuity::retire(state, agent, old, &retired_by);
239            }
240            lan_refusals::clear(agent);
241            Ok((old.map(|k| fingerprint(&k)), Some(fingerprint(&refused.key_b64))))
242        }
243    }
244}
245
246fn change_wan(agent: &str, channel: &str, how: Change, expect: Option<&str>) -> Result<Moved, String> {
247    let wan = crate::backend::storage::wan_identity::global().ok_or("pins: this install has no WAN identity")?;
248    let store_err = |e: crate::backend::storage::error::StoreError| format!("pins: {e}");
249    let pin = wan
250        .agent_instance_pin_get(agent, channel)
251        .map_err(store_err)?
252        .ok_or_else(|| format!("pins: no WAN pin for {agent} on {channel}"))?;
253    let from = Some(label(&pin.host_hint, &pin.instance_id));
254    match how {
255        Change::Forget => {
256            wan.agent_instance_pin_forget(agent, channel).map_err(store_err)?;
257            Ok((from, None))
258        }
259        Change::Adopt => {
260            let c = pin.conflict.ok_or_else(|| format!("pins: no other install has spoken for {agent} on {channel}"))?;
261            confirm_shown(expect, &label(&c.host_hint, &c.instance_id), agent)?;
262            wan.agent_instance_pin_replace(agent, channel, &c.instance_id, &c.host_hint, agentmux_common::time::now_secs())
263                .map_err(store_err)?;
264            Ok((from, Some(label(&c.host_hint, &c.instance_id))))
265        }
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272    use serde_json::Value;
273
274    async fn call(state: &AppState, ctx: Option<RpcContext>, command: &'static str, data: Value) -> (String, Option<Value>) {
275        let (engine, mut rx) = WshRpcEngine::new();
276        register(&engine, state);
277        if let Some(ctx) = ctx {
278            engine.set_rpc_context(ctx);
279        }
280        engine.handle_message(RpcMessage { command: command.into(), reqid: "r".into(), data: Some(data), ..Default::default() });
281        let resp = tokio::time::timeout(std::time::Duration::from_secs(10), rx.recv()).await.unwrap().unwrap();
282        (resp.error, resp.data)
283    }
284
285    #[tokio::test]
286    async fn only_the_proven_operator_window_changes_pins_and_an_agent_only_adopts_with_proof() {
287        let state = crate::server::tests::test_state();
288        let forget = json!({ "kind": "lan", "agent_id": "maop" });
289        for (command, data) in [(COMMAND_PINS_LIST, json!({})), (COMMAND_PINS_FORGET, forget.clone()), (COMMAND_PINS_ADOPT, forget.clone())] {
290            let (unproven, _) = call(&state, None, command, data.clone()).await;
291            assert!(unproven.starts_with("FORBIDDEN") && unproven.contains("isn't the AgentMux window"), "{command}: {unproven}");
292        }
293        let agent = || Some(RpcContext { agent_id: "AgentX".into(), ..Default::default() });
294        // Forgetting a pin has no proof to ask for, so it stays with the window.
295        let (err, _) = call(&state, agent(), COMMAND_PINS_FORGET, forget.clone()).await;
296        assert!(err.starts_with("FORBIDDEN"), "{err}");
297        // Listing is fingerprints only; adopting needs the vouch, and says what was missing.
298        let (err, _) = call(&state, agent(), COMMAND_PINS_LIST, json!({})).await;
299        assert_eq!(err, "");
300        let (err, _) = call(&state, agent(), COMMAND_PINS_ADOPT, forget.clone()).await;
301        assert!(!err.starts_with("FORBIDDEN") && err.contains("no other key has been shown"), "{err}");
302        let (err, _) = call(&state, agent(), COMMAND_PINS_ADOPT, json!({ "kind": "wan", "agent_id": "maop", "channel": "stable" })).await;
303        assert!(err.contains("LAN key only"), "{err}");
304    }
305
306    #[tokio::test]
307    async fn an_agent_adopts_a_refused_lan_key_only_when_the_install_that_hosts_it_vouches() {
308        use agentmux_common::jekt_sign::{generate_lan_keypair, WanKeyRecord};
309        use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
310        let state = crate::server::tests::test_state();
311        let tmp = |name: &str| {
312            let dir = tempfile::tempdir().unwrap();
313            let wan = std::sync::Arc::new(crate::backend::storage::wan_identity::WanIdentityStore::open(&dir.path().join(name)).unwrap());
314            (dir, wan)
315        };
316        let (_sdir, sender) = tmp("sender.db");
317        let (_rdir, receiver) = tmp("receiver.db");
318        let host = sender.instance_ensure("starpower").unwrap();
319        receiver.instance_ensure("narko").unwrap();
320        receiver.agent_instance_pin_get_or_set("clare", "stable", &host.instance_id, &host.host_hint, agentmux_common::time::now_secs()).unwrap();
321        state.mstore.set_wan_identity(receiver);
322
323        let (old, _) = generate_lan_keypair([1u8; 32]);
324        let (new, _) = generate_lan_keypair([2u8; 32]);
325        let (new_b64, old_b64) = (BASE64.encode(new), BASE64.encode(old));
326        state.mstore.lan_peer_pubkey_pin_get_or_set("pinagent", &old_b64).unwrap();
327        let install = crate::backend::storage::lan_peer_pin_installs::PinInstall { instance_id: host.instance_id.clone(), host_hint: host.host_hint.clone() };
328        assert!(state.mstore.lan_pin_bind("pinagent", &old_b64, &install, agentmux_common::time::now_secs()).unwrap());
329        let agent = || Some(RpcContext { agent_id: "AgentX".into(), ..Default::default() });
330        let adopt = json!({ "kind": "lan", "agent_id": "pinagent", "expect": fingerprint(&new_b64) });
331
332        // Refused with no certificate: not accepted, and the pin stays.
333        lan_refusals::pin_mismatch_with("pinagent", &new_b64, None, Some("no certificate".into()));
334        let (err, _) = call(&state, agent(), COMMAND_PINS_ADOPT, adopt.clone()).await;
335        assert!(err.contains("not vouched for") && err.contains("no certificate"), "{err}");
336        assert_eq!(state.mstore.lan_peer_pubkey_pin_load("pinagent").unwrap().as_deref(), Some(old_b64.as_str()));
337
338        // Refused with the hosting install's certificate: accepted, and the audit line names the agent that asked.
339        let vouch = WanKeyRecord::certify(&host.private_key, "pinagent", "lan", &new, &host.host_hint, agentmux_common::time::now_secs() + 5).unwrap();
340        lan_refusals::pin_mismatch_with("pinagent", &new_b64, Some(vouch), None);
341        let (err, _) = call(&state, agent(), COMMAND_PINS_ADOPT, adopt).await;
342        assert_eq!(err, "");
343        assert_eq!(state.mstore.lan_peer_pubkey_pin_load("pinagent").unwrap().as_deref(), Some(new_b64.as_str()));
344        let audited = lan_continuity::AUDITED.lock().unwrap().iter().any(|e| e["agent"] == "pinagent" && e["by"] == "AgentX" && e["vouched_by"]["path"] == "pinned-instance");
345        assert!(audited, "who accepted what, and why");
346    }
347
348    #[tokio::test]
349    async fn an_agent_cannot_accept_a_retired_key_for_a_name_with_no_pin() {
350        use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
351        let state = crate::server::tests::test_state();
352        let key = BASE64.encode([8u8; 32]);
353        state.mstore.lan_retired_put("retiredname", &fingerprint(&key), 1_790_000_000, "operator").unwrap();
354        lan_refusals::first_contact_with("retiredname", &key, None, None);
355        let agent = || Some(RpcContext { agent_id: "AgentX".into(), ..Default::default() });
356        let adopt = json!({ "kind": "lan", "agent_id": "retiredname", "expect": fingerprint(&key) });
357        let (err, _) = call(&state, agent(), COMMAND_PINS_ADOPT, adopt).await;
358        assert!(err.contains("was retired on"), "{err}");
359        assert!(state.mstore.lan_peer_pubkey_pin_load("retiredname").unwrap().is_none(), "nothing was pinned");
360    }
361
362    #[tokio::test]
363    async fn the_operator_lists_forgets_and_adopts_a_lan_pin() {
364        let state = crate::server::tests::test_state();
365        state.mstore.lan_peer_pubkey_pin_get_or_set("pinops", "key-a").unwrap();
366        lan_refusals::pin_mismatch("pinops", "key-b");
367        let op = || Some(RpcContext::operator_for_tests());
368
369        let (err, data) = call(&state, op(), COMMAND_PINS_LIST, json!({})).await;
370        assert_eq!(err, "");
371        let lan = &data.unwrap()["lan"];
372        let row = lan.as_array().unwrap().iter().find(|r| r["agent_id"] == "pinops").unwrap().clone();
373        assert_eq!(row["key_fp"], fingerprint("key-a"));
374        assert_eq!(row["refused"]["key_fp"], fingerprint("key-b"), "{row}");
375        assert!(!row.to_string().contains("key-a"), "never the key itself: {row}");
376
377        // Adopt what the screen showed: nothing, or another key, is refused.
378        let (err, _) = call(&state, op(), COMMAND_PINS_ADOPT, json!({ "kind": "lan", "agent_id": "pinops" })).await;
379        assert!(err.contains("say which key"), "{err}");
380        lan_refusals::pin_mismatch("pinops", "key-c"); // something else is refused after the list was drawn
381        let (err, _) = call(&state, op(), COMMAND_PINS_ADOPT, json!({ "kind": "lan", "agent_id": "pinops", "expect": fingerprint("key-b") })).await;
382        assert!(err.contains("has changed since the list"), "{err}");
383        assert_eq!(state.mstore.lan_peer_pubkey_pin_load("pinops").unwrap().as_deref(), Some("key-a"), "nothing moved");
384        lan_refusals::pin_mismatch("pinops", "key-b");
385        let (err, _) = call(&state, op(), COMMAND_PINS_ADOPT, json!({ "kind": "lan", "agent_id": "PinOps", "expect": fingerprint("key-b") })).await;
386        assert_eq!(err, "");
387        assert_eq!(state.mstore.lan_peer_pubkey_pin_load("pinops").unwrap().as_deref(), Some("key-b"));
388        let (err, _) = call(&state, op(), COMMAND_PINS_ADOPT, json!({ "kind": "lan", "agent_id": "pinops" })).await;
389        assert!(err.contains("no other key has been shown"), "{err}");
390
391        let (err, _) = call(&state, op(), COMMAND_PINS_FORGET, json!({ "kind": "lan", "agent_id": "pinops" })).await;
392        assert_eq!(err, "");
393        assert!(state.mstore.lan_peer_pubkey_pin_load("pinops").unwrap().is_none());
394        let (err, _) = call(&state, op(), COMMAND_PINS_FORGET, json!({ "kind": "lan", "agent_id": "pinops" })).await;
395        assert!(err.contains("no LAN pin"), "{err}");
396    }
397
398    #[tokio::test]
399    async fn a_request_for_nothing_sensible_is_refused() {
400        let state = crate::server::tests::test_state();
401        let op = || Some(RpcContext::operator_for_tests());
402        let (err, _) = call(&state, op(), COMMAND_PINS_FORGET, json!({ "kind": "usb", "agent_id": "x" })).await;
403        assert!(err.contains("unknown kind"), "{err}");
404        let (err, _) = call(&state, op(), COMMAND_PINS_FORGET, json!({ "kind": "lan", "agent_id": "  " })).await;
405        assert!(err.contains("no agent named"), "{err}");
406        let (err, _) = call(&state, op(), COMMAND_PINS_FORGET, json!({ "kind": "wan", "agent_id": "x" })).await;
407        assert!(err.contains("needs its channel") || err.contains("no WAN identity"), "{err}");
408    }
409
410    #[tokio::test]
411    async fn a_name_with_no_pin_is_listed_with_its_first_key_and_the_person_or_an_agent_accepts_it_once() {
412        use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
413        let state = crate::server::tests::test_state();
414        let key = BASE64.encode([4u8; 32]);
415        lan_refusals::first_contact_with("pinfirst-a", &key, None, Some("the peer sent no certificate for the key".into()));
416        let window = || Some(RpcContext::operator_for_tests());
417        let (err, data) = call(&state, window(), COMMAND_PINS_LIST, json!({})).await;
418        assert_eq!(err, "");
419        let row = data.unwrap()["lan"].as_array().unwrap().iter().find(|p| p["agent_id"] == "pinfirst-a").cloned().expect("listed");
420        assert_eq!((row["key_fp"].as_str(), row["pinned_at"].as_i64()), (Some(""), Some(0)), "nothing is pinned");
421        assert_eq!(row["refused"]["key_fp"], fingerprint(&key));
422        assert!(state.mstore.lan_peer_pubkey_pin_load("pinfirst-a").unwrap().is_none());
423
424        // The window accepts what it was shown, and the name is pinned.
425        let adopt = json!({ "kind": "lan", "agent_id": "pinfirst-a", "expect": fingerprint(&key) });
426        let (err, _) = call(&state, window(), COMMAND_PINS_ADOPT, adopt).await;
427        assert_eq!(err, "");
428        assert_eq!(state.mstore.lan_peer_pubkey_pin_load("pinfirst-a").unwrap().as_deref(), Some(key.as_str()));
429        let by_window = lan_continuity::AUDITED.lock().unwrap().iter().filter(|e| e["agent"] == "pinfirst-a" && e["action"] == "first-pin").count();
430        assert_eq!(by_window, 1, "the window's accept of a first key is a first-pin line too");
431
432        // An agent may accept a first key too (no vouching install is needed), recorded as the agent.
433        let key_b = BASE64.encode([5u8; 32]);
434        lan_refusals::first_contact_with("pinfirst-b", &key_b, None, None);
435        let adopt_b = json!({ "kind": "lan", "agent_id": "pinfirst-b", "expect": fingerprint(&key_b) });
436        let agent = || Some(RpcContext { agent_id: "AgentX".into(), ..Default::default() });
437        let (err, _) = call(&state, agent(), COMMAND_PINS_ADOPT, adopt_b).await;
438        assert_eq!(err, "");
439        assert_eq!(state.mstore.lan_peer_pubkey_pin_load("pinfirst-b").unwrap().as_deref(), Some(key_b.as_str()));
440        let audited = lan_continuity::AUDITED
441            .lock()
442            .unwrap()
443            .iter()
444            .filter(|e| e["agent"] == "pinfirst-b" && e["action"] == "first-pin")
445            .cloned()
446            .collect::<Vec<_>>();
447        assert_eq!(audited.len(), 1);
448        assert_eq!(audited[0]["by"], "AgentX");
449        assert!(lan_refusals::get("pinfirst-b").is_none(), "nothing left to accept");
450
451        // What the screen showed must still be what is held: another key in between is refused.
452        let key_c = BASE64.encode([6u8; 32]);
453        lan_refusals::first_contact_with("pinfirst-c", &key_c, None, None);
454        let stale = json!({ "kind": "lan", "agent_id": "pinfirst-c", "expect": "0000000000" });
455        let (err, _) = call(&state, agent(), COMMAND_PINS_ADOPT, stale).await;
456        assert!(err.contains("has changed since the list"), "{err}");
457        assert!(state.mstore.lan_peer_pubkey_pin_load("pinfirst-c").unwrap().is_none());
458    }
459}