1use 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
42pub const WARM_MAX: Duration = Duration::from_secs(20);
46pub const SETTLED_FOR: Duration = Duration::from_secs(60);
48pub const GATE_GRACE: Duration = Duration::from_secs(30);
52const POLL: Duration = Duration::from_millis(500);
54pub const STAGGER: Duration = Duration::from_millis(250);
56const 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 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 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 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 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 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 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
187fn 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
201fn 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
210pub fn release(block_id: &str) {
213 global().release(block_id);
214}
215
216pub fn started(block_id: &str) {
218 global().started(block_id);
219}
220
221pub 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 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 release(&block_id);
254 }
255 result
256}
257
258pub struct AmbientGuard {
260 owner: String,
261}
262
263impl Drop for AmbientGuard {
264 fn drop(&mut self) {
265 release(&self.owner);
266 }
267}
268
269pub 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 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 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 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 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}