Skip to main content

agentmux_srv_core/identity/
token_warmup.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One refresh at a time per Claude config dir (#6081).
5//!
6//! The Claude CLI refreshes its own OAuth token, and the refresh token rotates: a refresh spends
7//! the old one. Two CLIs that start on the same `CLAUDE_CONFIG_DIR` while its access token has
8//! expired both refresh; the second presents the token the first just spent, is refused, and
9//! can leave the dir signed out. A boot does exactly that: every pane that shares an identity
10//! resumes within milliseconds, and an ambient side call (Haiku) joins them.
11//!
12//! So while a dir's token is expired, one process goes first and the rest wait:
13//!   - the first spawn finds no entry and an expired token, and takes the dir (`Entry::owner` is
14//!     its block). It runs at once; its CLI does the refresh;
15//!   - a later spawn, or an ambient call, on that dir waits until the token is fresh again, the
16//!     owner's first turn has ended or its process is gone, or the owner's hold runs out:
17//!     [`GATE_GRACE`] until its process is up, [`WARM_MAX`] after. Those that waited start
18//!     [`STAGGER`] apart, so a dozen panes do not all hit the API in the same millisecond;
19//!   - an ambient call takes the dir itself when the token is expired and nobody has it.
20//!
21//! An owner whose hold runs out (a resumed CLI that waits for its first prompt before it
22//! refreshes, or a refresh that failed) does not hand the dir to the next waiter: the dir is
23//! unclaimed for [`SETTLED_FOR`], so the panes behind it go together rather than one by one.
24//!
25//! This never refreshes a token itself and never blocks for good: a dead refresh token or an
26//! owner that never reports back costs one hold. The wait comes before the account is resolved
27//! (`inject_after_warmup`), so the status the spawn gate reads is the one after the refresh, not
28//! before it.
29
30use std::collections::HashMap;
31use std::path::{Path, PathBuf};
32use std::sync::atomic::{AtomicU64, Ordering};
33use std::sync::{Arc, Mutex, OnceLock};
34use std::time::Duration;
35
36use tokio::time::{sleep_until, timeout, Instant};
37
38use crate::backend::mps::Broker;
39use crate::backend::storage::store::Store;
40use crate::identity::resolver::{OAuthProbeStatus, SpawnGateError};
41
42/// The longest a dir stays taken once its owner's process is up and its first turn has not ended.
43/// A CLI that refreshes does so in its first seconds; one that waits for a prompt first (a resumed
44/// pane) must not hold the panes behind it for long.
45pub const WARM_MAX: Duration = Duration::from_secs(20);
46/// How long a dir stays unclaimed after an owner's hold ran out.
47pub const SETTLED_FOR: Duration = Duration::from_secs(60);
48/// The longest it stays taken by a spawn whose process has not started: the time the gate and the
49/// env take. A spawn that fails after the dir was taken (a gate refusal, a deleted agent) holds it
50/// no longer than this.
51pub const GATE_GRACE: Duration = Duration::from_secs(30);
52/// How often a waiter looks at the token file, which nothing signals when it changes.
53const POLL: Duration = Duration::from_millis(500);
54/// The gap between spawns that waited on the same dir.
55pub const STAGGER: Duration = Duration::from_millis(250);
56/// A token this close to expiry counts as expired: the CLI refreshes inside its own margin.
57const STALE_MARGIN_MS: i64 = 5 * 60 * 1000;
58
59struct Entry {
60    owner: String,
61    deadline: Instant,
62}
63
64enum Step {
65    Go,
66    Wait(Instant),
67}
68
69#[derive(Default)]
70struct Inner {
71    taken: HashMap<PathBuf, Entry>,
72    /// Dirs whose owner's hold ran out, and until when no one claims them again.
73    settled: HashMap<PathBuf, Instant>,
74    next_release: HashMap<PathBuf, Instant>,
75}
76
77#[derive(Default)]
78struct Warmup {
79    inner: Mutex<Inner>,
80    wake: tokio::sync::Notify,
81}
82
83impl Warmup {
84    /// Decide for `owner` on `dir`. An ambient owner's hold starts at [`WARM_MAX`]: it has no
85    /// process start to wait for.
86    fn step(&self, dir: &Path, owner: &str, stale: bool, ambient: bool, now: Instant) -> Step {
87        let mut g = self.inner.lock().unwrap();
88        if g.taken.get(dir).is_some_and(|e| e.deadline <= now) {
89            if let Some(e) = g.taken.remove(dir) {
90                tracing::warn!(
91                    target: "identity",
92                    dir = %dir.display(),
93                    owner = %e.owner,
94                    "token warm-up: owner's hold ran out before its token refreshed — dir released to all"
95                );
96                g.settled.insert(dir.to_path_buf(), now + SETTLED_FOR);
97            }
98        }
99        match g.taken.get(dir) {
100            Some(e) if e.owner == owner => Step::Go,
101            Some(e) if stale => Step::Wait(e.deadline),
102            Some(_) => Step::Go,
103            None => {
104                if stale && !g.settled.get(dir).is_some_and(|until| *until > now) {
105                    tracing::info!(
106                        target: "identity",
107                        dir = %dir.display(),
108                        owner,
109                        "token warm-up: access token expired — {owner} goes first, others on this dir wait"
110                    );
111                    let hold = if ambient { WARM_MAX } else { GATE_GRACE };
112                    g.taken.insert(dir.to_path_buf(), Entry { owner: owner.to_string(), deadline: now + hold });
113                }
114                Step::Go
115            }
116        }
117    }
118
119    /// The slot a caller that waited starts at: [`STAGGER`] after the last one on this dir.
120    fn reserve_release(&self, dir: &Path, now: Instant) -> Instant {
121        let mut g = self.inner.lock().unwrap();
122        let at = g.next_release.get(dir).copied().filter(|t| *t > now).unwrap_or(now);
123        g.next_release.insert(dir.to_path_buf(), at + STAGGER);
124        at
125    }
126
127    async fn enter(&self, dir: &Path, owner: &str, ambient: bool, is_stale: impl Fn() -> bool) {
128        // A caller dropped while it waited out its stagger must not leave the dir it took held.
129        let mut undo = ReleaseOnDrop { warmup: self, owner, armed: true };
130        let mut waited = false;
131        loop {
132            let notified = self.wake.notified();
133            tokio::pin!(notified);
134            notified.as_mut().enable();
135            let now = Instant::now();
136            match self.step(dir, owner, is_stale(), ambient, now) {
137                Step::Go => break,
138                Step::Wait(deadline) => {
139                    waited = true;
140                    let _ = timeout(POLL.min(deadline.saturating_duration_since(now)), notified).await;
141                }
142            }
143        }
144        if waited {
145            sleep_until(self.reserve_release(dir, Instant::now())).await;
146        }
147        undo.armed = false;
148    }
149
150    /// `owner`'s process is up: it now holds its dir for the first turn, up to [`WARM_MAX`].
151    fn started(&self, owner: &str) {
152        let mut g = self.inner.lock().unwrap();
153        let until = Instant::now() + WARM_MAX;
154        for e in g.taken.values_mut().filter(|e| e.owner == owner) {
155            e.deadline = until;
156        }
157    }
158
159    /// Free every dir `owner` holds. True if there was one.
160    fn release(&self, owner: &str) -> bool {
161        let mut g = self.inner.lock().unwrap();
162        let before = g.taken.len();
163        g.taken.retain(|_, e| e.owner != owner);
164        let released = g.taken.len() != before;
165        drop(g);
166        if released {
167            self.wake.notify_waiters();
168        }
169        released
170    }
171}
172
173struct ReleaseOnDrop<'a> {
174    warmup: &'a Warmup,
175    owner: &'a str,
176    armed: bool,
177}
178
179impl Drop for ReleaseOnDrop<'_> {
180    fn drop(&mut self) {
181        if self.armed {
182            self.warmup.release(self.owner);
183        }
184    }
185}
186
187/// The map key for a config dir: the same dir spelled two ways (a trailing separator, the other
188/// slash, case on Windows) is one dir. An ambient call names its dir from the block's `cmd:env`, a
189/// spawn from the bound account; they must meet.
190fn key_of(dir: &Path) -> PathBuf {
191    let s = dir.to_string_lossy().replace('\\', "/");
192    let s = s.trim_end_matches('/');
193    PathBuf::from(if cfg!(windows) { s.to_lowercase() } else { s.to_string() })
194}
195
196fn global() -> &'static Warmup {
197    static GLOBAL: OnceLock<Warmup> = OnceLock::new();
198    GLOBAL.get_or_init(Warmup::default)
199}
200
201/// Whether the Claude token in `dir` has expired, or will within the CLI's own margin, and holds
202/// a refresh token to renew it with. Anything else (fresh, no file, no refresh token, a keychain
203/// platform) is not ours to wait on.
204fn token_is_stale(dir: &Path) -> bool {
205    let now_ms = agentmux_common::time::now_ms();
206    crate::identity::resolver::probe_oauth_status("claude", &dir.to_string_lossy(), now_ms + STALE_MARGIN_MS)
207        == Some(OAuthProbeStatus::Expired)
208}
209
210/// A spawn on `block_id`'s bound Claude dir is over, or its first turn is: whoever waited on it
211/// may go. Cheap and safe to call on every turn end and every process exit.
212pub fn release(block_id: &str) {
213    global().release(block_id);
214}
215
216/// The CLI process for `block_id` is running: its first turn may take [`WARM_MAX`] to end.
217pub fn started(block_id: &str) {
218    global().started(block_id);
219}
220
221/// `inject_identity_env_async`, after waiting for this block's dir: the single-flight comes
222/// first, so the account the gate resolves and the status it probes are the ones after the
223/// refresh. A block with no bound Claude dir goes straight through.
224pub async fn inject_after_warmup(
225    mstore: Arc<Store>,
226    id_store: Arc<Store>,
227    identity_store: Arc<Store>,
228    broker: Option<Arc<Broker>>,
229    block_id: String,
230    env_vars: HashMap<String, String>,
231    own_claude_endpoint: bool,
232) -> Result<HashMap<String, String>, SpawnGateError> {
233    // An agent on a model server of its own discards the account's login, so there is no dir to wait for.
234    let dir = if own_claude_endpoint {
235        None
236    } else {
237        let (m, i, s, b) = (mstore.clone(), id_store.clone(), identity_store.clone(), block_id.clone());
238        tokio::task::spawn_blocking(move || crate::identity::resolver::resolve_bound_oauth_config_dir(&m, &i, &s, &b))
239            .await
240            .ok()
241            .flatten()
242    };
243    if let Some(dir) = dir {
244        let probe = dir.clone();
245        global().enter(&key_of(&dir), &block_id, false, move || token_is_stale(&probe)).await;
246    }
247    let result = crate::identity::resolver::inject_identity_env_async(
248        mstore, id_store, identity_store, broker, block_id.clone(), env_vars, own_claude_endpoint,
249    )
250    .await;
251    if result.is_err() {
252        // The gate refused: no process will start, so the dir this spawn took is nobody's.
253        release(&block_id);
254    }
255    result
256}
257
258/// Holds a dir for an ambient call while its token is expired; frees it when dropped.
259pub struct AmbientGuard {
260    owner: String,
261}
262
263impl Drop for AmbientGuard {
264    fn drop(&mut self) {
265        release(&self.owner);
266    }
267}
268
269/// Wait before an ambient CLI runs on `config_dir` (its `CLAUDE_CONFIG_DIR`) while a spawn on it
270/// is refreshing the expired token. No dir, or a blank one: the call has none of its own to protect.
271pub async fn ambient_gate(config_dir: Option<&str>) -> AmbientGuard {
272    static NEXT: AtomicU64 = AtomicU64::new(0);
273    let owner = format!("ambient:{}", NEXT.fetch_add(1, Ordering::Relaxed));
274    if let Some(dir) = config_dir.filter(|d| !d.trim().is_empty()) {
275        let dir = PathBuf::from(dir);
276        let probe = dir.clone();
277        global().enter(&key_of(&dir), &owner, true, move || token_is_stale(&probe)).await;
278    }
279    AmbientGuard { owner }
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285    use std::sync::atomic::AtomicBool;
286
287    fn dir() -> PathBuf {
288        PathBuf::from("/identities/a/claude")
289    }
290
291    fn stale_flag(v: bool) -> Arc<AtomicBool> {
292        Arc::new(AtomicBool::new(v))
293    }
294
295    #[tokio::test(start_paused = true)]
296    async fn the_first_spawn_on_an_expired_dir_goes_first_and_the_second_waits() {
297        let w = Arc::new(Warmup::default());
298        let stale = stale_flag(true);
299        let (s1, s2) = (stale.clone(), stale.clone());
300        w.enter(&dir(), "a", false, move || s1.load(Ordering::SeqCst)).await;
301
302        let second = {
303            let w = w.clone();
304            tokio::spawn(async move { w.enter(&dir(), "b", false, move || s2.load(Ordering::SeqCst)).await })
305        };
306        tokio::time::sleep(Duration::from_secs(5)).await;
307        assert!(!second.is_finished(), "b must wait while a holds the dir and the token is expired");
308
309        assert!(w.release("a"));
310        second.await.unwrap();
311    }
312
313    #[tokio::test(start_paused = true)]
314    async fn a_waiter_goes_once_the_token_is_fresh_though_the_owner_is_still_in_its_turn() {
315        let w = Arc::new(Warmup::default());
316        let stale = stale_flag(true);
317        let s1 = stale.clone();
318        w.enter(&dir(), "a", false, move || s1.load(Ordering::SeqCst)).await;
319
320        let s2 = stale.clone();
321        let second = {
322            let w = w.clone();
323            tokio::spawn(async move { w.enter(&dir(), "b", false, move || s2.load(Ordering::SeqCst)).await })
324        };
325        tokio::time::sleep(Duration::from_secs(3)).await;
326        assert!(!second.is_finished());
327        stale.store(false, Ordering::SeqCst);
328        tokio::time::sleep(POLL * 2).await;
329        second.await.unwrap();
330    }
331
332    #[tokio::test(start_paused = true)]
333    async fn a_fresh_token_makes_nobody_wait() {
334        let w = Warmup::default();
335        for owner in ["a", "b", "c"] {
336            w.enter(&dir(), owner, false, || false).await;
337        }
338        assert!(!w.release("a"), "nothing was taken");
339    }
340
341    #[tokio::test(start_paused = true)]
342    async fn the_owner_entering_again_does_not_wait_for_itself() {
343        let w = Warmup::default();
344        w.enter(&dir(), "a", false, || true).await;
345        timeout(Duration::from_millis(1), w.enter(&dir(), "a", false, || true)).await.expect("a respawn must not wait");
346    }
347
348    #[tokio::test(start_paused = true)]
349    async fn an_owner_that_never_refreshes_frees_the_dir_to_everyone_at_once() {
350        let w = Arc::new(Warmup::default());
351        w.enter(&dir(), "a", false, || true).await;
352        w.started("a");
353        let mut waiting = Vec::new();
354        for owner in ["b", "c"] {
355            let w = w.clone();
356            waiting.push(tokio::spawn(async move { w.enter(&dir(), owner, false, || true).await }));
357        }
358        tokio::time::sleep(WARM_MAX - Duration::from_secs(1)).await;
359        assert!(waiting.iter().all(|h| !h.is_finished()));
360        tokio::time::sleep(Duration::from_secs(3)).await;
361        // Neither took the dir over from the other: both are through, after a stagger apart.
362        for h in waiting {
363            h.await.unwrap();
364        }
365        assert!(!w.release("b") && !w.release("c"), "the dir stays unclaimed for a while");
366        // Even a newcomer is not held, while the dir is settled.
367        timeout(Duration::from_millis(1), w.enter(&dir(), "d", false, || true)).await.expect("settled");
368    }
369
370    #[tokio::test(start_paused = true)]
371    async fn a_spawn_that_never_starts_its_process_frees_the_dir_after_the_grace() {
372        let w = Arc::new(Warmup::default());
373        w.enter(&dir(), "a", false, || true).await;
374        let second = {
375            let w = w.clone();
376            tokio::spawn(async move { w.enter(&dir(), "b", false, || true).await })
377        };
378        tokio::time::sleep(GATE_GRACE - Duration::from_secs(1)).await;
379        assert!(!second.is_finished());
380        tokio::time::sleep(Duration::from_secs(3)).await;
381        second.await.unwrap();
382    }
383
384    #[tokio::test(start_paused = true)]
385    async fn the_same_dir_spelled_two_ways_is_one_dir() {
386        assert_eq!(key_of(Path::new("/identities/a/claude/")), key_of(Path::new("/identities/a/claude")));
387        assert_eq!(key_of(Path::new(r"C:\Ids\a\claude\")), key_of(Path::new("C:/Ids/a/claude")));
388        if cfg!(windows) {
389            assert_eq!(key_of(Path::new("C:/IDS/a")), key_of(Path::new("c:/ids/A")));
390        }
391    }
392
393    #[tokio::test(start_paused = true)]
394    async fn spawns_that_waited_start_a_stagger_apart() {
395        let w = Arc::new(Warmup::default());
396        let stale = stale_flag(true);
397        let s0 = stale.clone();
398        w.enter(&dir(), "a", false, move || s0.load(Ordering::SeqCst)).await;
399        let mut waiters = Vec::new();
400        for owner in ["b", "c", "d"] {
401            let (w, s) = (w.clone(), stale.clone());
402            waiters.push(tokio::spawn(async move {
403                w.enter(&dir(), owner, false, move || s.load(Ordering::SeqCst)).await;
404                Instant::now()
405            }));
406        }
407        tokio::time::sleep(Duration::from_secs(1)).await;
408        stale.store(false, Ordering::SeqCst);
409        let mut at = Vec::new();
410        for h in waiters {
411            at.push(h.await.unwrap());
412        }
413        at.sort();
414        assert!(at[1] - at[0] >= STAGGER, "second start {:?} after the first", at[1] - at[0]);
415        assert!(at[2] - at[1] >= STAGGER, "third start {:?} after the second", at[2] - at[1]);
416    }
417
418    #[tokio::test(start_paused = true)]
419    async fn an_ambient_call_waits_while_the_token_is_expired_and_goes_once_it_is_fresh() {
420        let w = Arc::new(Warmup::default());
421        let stale = stale_flag(true);
422        let s1 = stale.clone();
423        w.enter(&dir(), "a", false, move || s1.load(Ordering::SeqCst)).await;
424
425        let s2 = stale.clone();
426        let ambient = {
427            let w = w.clone();
428            tokio::spawn(async move { w.enter(&dir(), "ambient:0", true, move || s2.load(Ordering::SeqCst)).await })
429        };
430        tokio::time::sleep(Duration::from_secs(10)).await;
431        assert!(!ambient.is_finished(), "the ambient call waits while a refreshes");
432        stale.store(false, Ordering::SeqCst);
433        tokio::time::sleep(POLL * 2).await;
434        ambient.await.unwrap();
435    }
436
437    #[tokio::test(start_paused = true)]
438    async fn an_ambient_call_goes_when_the_owners_turn_ends_though_the_token_is_still_expired() {
439        let w = Arc::new(Warmup::default());
440        w.enter(&dir(), "a", false, || true).await;
441        let ambient = {
442            let w = w.clone();
443            tokio::spawn(async move { w.enter(&dir(), "ambient:0", true, || true).await })
444        };
445        tokio::time::sleep(Duration::from_secs(5)).await;
446        assert!(!ambient.is_finished());
447        w.release("a");
448        ambient.await.unwrap();
449    }
450
451    #[tokio::test(start_paused = true)]
452    async fn an_ambient_call_on_an_expired_dir_holds_it_against_a_spawn() {
453        let w = Arc::new(Warmup::default());
454        w.enter(&dir(), "ambient:0", true, || true).await;
455        let spawn = {
456            let w = w.clone();
457            tokio::spawn(async move { w.enter(&dir(), "a", false, || true).await })
458        };
459        tokio::time::sleep(Duration::from_secs(5)).await;
460        assert!(!spawn.is_finished());
461        w.release("ambient:0");
462        spawn.await.unwrap();
463    }
464
465    #[tokio::test(start_paused = true)]
466    async fn a_caller_dropped_while_it_waits_leaves_no_dir_held() {
467        let w = Arc::new(Warmup::default());
468        let stale = stale_flag(true);
469        let s0 = stale.clone();
470        w.enter(&dir(), "a", false, move || s0.load(Ordering::SeqCst)).await;
471        // b waits for a, then (a gone, token still expired) takes the dir, then staggers.
472        let b = {
473            let (w, s) = (w.clone(), stale.clone());
474            tokio::spawn(async move { w.enter(&dir(), "b", false, move || s.load(Ordering::SeqCst)).await })
475        };
476        tokio::time::sleep(Duration::from_secs(1)).await;
477        w.release("a");
478        // Earlier waiters booked the next slots (b has not run yet), so b, once it takes the dir,
479        // has a stagger to wait out.
480        for _ in 0..3 {
481            w.reserve_release(&dir(), Instant::now());
482        }
483        tokio::time::sleep(Duration::from_millis(10)).await;
484        b.abort();
485        let _ = b.await;
486        assert!(!w.release("b"), "aborting b already freed what it took");
487    }
488
489    #[tokio::test(start_paused = true)]
490    async fn different_dirs_do_not_wait_for_each_other() {
491        let w = Warmup::default();
492        w.enter(Path::new("/identities/a/claude"), "a", false, || true).await;
493        timeout(Duration::from_millis(1), w.enter(Path::new("/identities/b/claude"), "b", false, || true))
494            .await
495            .expect("another dir's token is its own");
496    }
497
498    fn write_creds(dir: &Path, expires_at_ms: i64, refresh: &str) {
499        let body = serde_json::json!({"claudeAiOauth": {"accessToken": "x", "refreshToken": refresh, "expiresAt": expires_at_ms}});
500        std::fs::write(dir.join(".credentials.json"), body.to_string()).unwrap();
501    }
502
503    #[test]
504    fn staleness_reads_the_credentials_file() {
505        let tmp = tempfile::tempdir().unwrap();
506        let now = agentmux_common::time::now_ms();
507
508        assert!(!token_is_stale(tmp.path()), "no file: not ours to wait on");
509        write_creds(tmp.path(), now - 1_000, "r");
510        assert!(token_is_stale(tmp.path()));
511        write_creds(tmp.path(), now + 60_000, "r");
512        assert!(token_is_stale(tmp.path()), "inside the CLI's own refresh margin");
513        write_creds(tmp.path(), now + 3_600_000, "r");
514        assert!(!token_is_stale(tmp.path()));
515        write_creds(tmp.path(), now - 1_000, "");
516        assert!(!token_is_stale(tmp.path()), "no refresh token: waiting cannot help");
517    }
518
519    #[tokio::test(start_paused = true)]
520    async fn the_ambient_gate_with_no_dir_does_not_wait() {
521        let g = timeout(Duration::from_millis(1), ambient_gate(None)).await.expect("no dir, no wait");
522        drop(g);
523        timeout(Duration::from_millis(1), ambient_gate(Some("  "))).await.expect("a blank dir is no dir");
524    }
525}