Skip to main content

agentmux_srv_core/identity/
sign_in_watch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A sign-in value the CLI has just refreshed is hidden from transcripts within moments of the write, not at the
5//! next account tick.
6//!
7//! The values in an account's sign-in file are withheld where srv reads the file (`oauth_probe`), which the spawn
8//! check and the 15 s account tick do. A CLI renews its tokens in between, so [`start`] watches each account's
9//! sign-in file (Claude's `.credentials.json`, Codex's and Grok's `auth.json`, Muse's `muse/auth.json`) through the
10//! shared [`FsWatchPool`] and reads the file again when it changes, whether the CLI writes it in place or replaces it
11//! (a temp file renamed over it). The accounts followed are read again every [`RECONCILE`], so an account that is added
12//! or deleted is followed or let go. It only reads: it never writes a sign-in file or logs a value.
13
14use std::collections::{HashMap, HashSet};
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17use std::time::Duration;
18
19use tokio::sync::broadcast::error::{RecvError, TryRecvError};
20
21use crate::backend::fs_watch::{FsWatchEventKind, FsWatchPool, Subscription};
22use crate::backend::providers::resolve_provider_alias;
23use crate::backend::storage::store::{SecretRef, Store};
24use crate::identity::resolver::{probe_oauth_status, sign_in_file};
25
26/// How often the accounts to follow are read again.
27const RECONCILE: Duration = Duration::from_secs(15);
28
29/// How long a burst of events (a file written in pieces, or replaced) settles before the file is read.
30const SETTLE: Duration = Duration::from_millis(150);
31
32/// A sign-in file followed, and what it is.
33struct Followed {
34    provider: String,
35    dir: String,
36    subscription: Subscription,
37}
38
39/// `path` as the pool reports it: the directory made canonical (the pool watches the canonical directory).
40fn normal(path: &Path) -> PathBuf {
41    let canonical_parent = path.parent().and_then(|p| p.canonicalize().ok());
42    match (canonical_parent, path.file_name()) {
43        (Some(parent), Some(name)) => parent.join(name),
44        _ => path.to_path_buf(),
45    }
46}
47
48/// The sign-in files of every account that keeps its sign-in in a config dir: file -> (provider, dir).
49fn wanted(accounts: &Store) -> HashMap<PathBuf, (String, String)> {
50    let mut out = HashMap::new();
51    for account in accounts.identity_list(None).unwrap_or_default() {
52        let SecretRef::OAuthConfigDir { dir } = &account.secret_ref else { continue };
53        let provider = resolve_provider_alias(&account.provider).to_string();
54        if let Some(file) = sign_in_file(&provider, Path::new(dir)) {
55            out.insert(normal(&file), (provider, dir.clone()));
56        }
57    }
58    out
59}
60
61/// Follows the files in `wanted` and lets go of the ones no longer in it.
62fn reconcile(pool: &Arc<FsWatchPool>, wanted: HashMap<PathBuf, (String, String)>, followed: &mut HashMap<PathBuf, Followed>) {
63    let gone: Vec<PathBuf> = followed.keys().filter(|file| !wanted.contains_key(*file)).cloned().collect();
64    for file in gone {
65        if let Some(f) = followed.remove(&file) {
66            pool.unsubscribe(f.subscription);
67        }
68    }
69    for (file, (provider, dir)) in wanted {
70        followed.entry(file.clone()).or_insert_with(|| Followed { subscription: pool.subscribe_file(&file), provider, dir });
71    }
72}
73
74/// Reads each of `files` once, which withholds what is in it.
75async fn look(files: HashSet<PathBuf>, followed: &HashMap<PathBuf, Followed>) {
76    let looks: Vec<(String, String)> = files.iter().filter_map(|f| followed.get(f)).map(|f| (f.provider.clone(), f.dir.clone())).collect();
77    let _ = tokio::task::spawn_blocking(move || {
78        let now = agentmux_common::time::now_ms();
79        for (provider, dir) in looks {
80            probe_oauth_status(&provider, &dir, now);
81        }
82    })
83    .await;
84}
85
86async fn run(pool: Arc<FsWatchPool>, accounts: Arc<Store>) {
87    // events() before the first subscription, or a change landing between them is missed.
88    let mut events = pool.events();
89    let mut followed: HashMap<PathBuf, Followed> = HashMap::new();
90    reconcile(&pool, wanted(&accounts), &mut followed);
91    let mut tick = tokio::time::interval(RECONCILE);
92    tick.tick().await;
93    loop {
94        let mut changed: HashSet<PathBuf> = HashSet::new();
95        tokio::select! {
96            _ = tick.tick() => {
97                let accounts = accounts.clone();
98                if let Ok(now_wanted) = tokio::task::spawn_blocking(move || wanted(&accounts)).await {
99                    reconcile(&pool, now_wanted, &mut followed);
100                }
101                continue;
102            }
103            event = events.recv() => match event {
104                Ok(e) if matches!(e.kind, FsWatchEventKind::Created | FsWatchEventKind::Modified | FsWatchEventKind::Other) => {
105                    changed.insert(normal(&e.path));
106                }
107                Ok(_) => continue,
108                Err(RecvError::Lagged(_)) => changed.extend(followed.keys().cloned()),
109                Err(RecvError::Closed) => break,
110            },
111        }
112        // A burst settles, then each file that changed is read once.
113        tokio::time::sleep(SETTLE).await;
114        loop {
115            match events.try_recv() {
116                Ok(e) => {
117                    changed.insert(normal(&e.path));
118                }
119                Err(TryRecvError::Lagged(_)) => changed.extend(followed.keys().cloned()),
120                Err(_) => break,
121            }
122        }
123        changed.retain(|file| followed.contains_key(file));
124        if !changed.is_empty() {
125            look(changed, &followed).await;
126        }
127    }
128}
129
130/// Starts following the sign-in files of the accounts in `accounts`. Needs a running tokio runtime.
131pub fn start(pool: Arc<FsWatchPool>, accounts: Arc<Store>) {
132    tokio::spawn(run(pool, accounts));
133}
134
135#[cfg(test)]
136#[path = "sign_in_watch_tests.rs"]
137mod tests;