Skip to main content

agentmux_srv_core/identity/
accounts_changed.rs

1//! Tells every open window that an account changed, from the code that changes it.
2//!
3//! The Connectors pane, the pickers and the agent pane keep one cache of the accounts and refresh
4//! it on `identityaccounts:changed`. A path that writes an account row without publishing it leaves
5//! them stale until a remount, which is what an agent's Google connect did: the flow commits the
6//! account in the background, with no request of the person's window to refresh after. So the
7//! commit points (a connect finishing, a token refresh the provider refuses) announce it here, and a
8//! new path has one call to make.
9
10use std::sync::{Arc, OnceLock};
11
12use crate::backend::mps::Broker;
13use crate::backend::mps_events::{Event, GoogleNotice, IdentityAccountsChanged};
14
15static BROKER: OnceLock<Arc<Broker>> = OnceLock::new();
16
17/// Where the announcement goes, set once at startup. Until then (and in a unit test that doesn't
18/// install one) a change is recorded but not announced.
19pub fn install_broker(broker: Arc<Broker>) {
20    let _ = BROKER.set(broker);
21}
22
23/// An account was added, removed, reconnected or changed state: windows read the accounts again.
24pub fn announce() {
25    if let Some(broker) = BROKER.get() {
26        broker.publish_event::<IdentityAccountsChanged>(&(), vec![], 0);
27    }
28}
29
30/// The `google:notice` event: one line for the windows' notices, asking nothing ("Naki-2 gave
31/// Agent5 Calendar read"). Never mail, event or file content.
32#[derive(Debug, Clone, serde::Serialize, ts_rs::TS)]
33#[ts(export, export_to = "../../../frontend/types/rpc/")]
34pub struct GoogleNoticeEvent {
35    pub text: String,
36}
37
38/// Tells the windows what an agent did to a Google account, so the person sees it as it happens.
39pub fn tell_windows(text: String) {
40    if let Some(broker) = BROKER.get() {
41        broker.publish_event::<GoogleNotice>(&GoogleNoticeEvent { text }, vec![], 0);
42    }
43}
44
45#[cfg(test)]
46pub(crate) mod tests {
47    use std::sync::atomic::{AtomicUsize, Ordering};
48    use std::sync::Mutex;
49
50    use super::*;
51
52    /// How many times `identityaccounts:changed` has been published on the process's test broker.
53    /// Tests run side by side, so a test asserts it went up, not by how much.
54    pub(crate) fn announcements() -> usize {
55        counter().load(Ordering::SeqCst)
56    }
57
58    /// Installs the process's test broker (once) and counts what it publishes.
59    pub(crate) fn watch() {
60        counter();
61    }
62
63    /// The `google:notice` payloads the test broker has seen.
64    fn notices() -> &'static Mutex<Vec<String>> {
65        static SEEN: OnceLock<Mutex<Vec<String>>> = OnceLock::new();
66        SEEN.get_or_init(Default::default)
67    }
68
69    fn counter() -> &'static AtomicUsize {
70        static COUNT: OnceLock<Arc<AtomicUsize>> = OnceLock::new();
71        COUNT
72            .get_or_init(|| {
73                let count = Arc::new(AtomicUsize::new(0));
74                let seen = Arc::clone(&count);
75                let broker = Arc::new(Broker::new());
76                broker.add_observer(Arc::new(move |e| {
77                    if e.event == IdentityAccountsChanged::NAME {
78                        seen.fetch_add(1, Ordering::SeqCst);
79                    }
80                    if e.event == GoogleNotice::NAME {
81                        notices().lock().unwrap().push(format!("{:?}", e.data));
82                    }
83                }));
84                install_broker(broker);
85                count
86            })
87            .as_ref()
88    }
89
90    #[test]
91    fn telling_the_windows_publishes_one_line_for_their_notices() {
92        watch();
93        tell_windows("Naki-2 gave Agent5 Calendar read on me@example.com".to_string());
94        assert!(notices().lock().unwrap().iter().any(|n| n.contains("Naki-2 gave Agent5 Calendar read")));
95    }
96
97    #[test]
98    fn announcing_publishes_identityaccounts_changed() {
99        watch();
100        let before = announcements();
101        announce();
102        assert!(announcements() > before, "announce() publishes the event every window refreshes on");
103    }
104}