The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(app_state): extract shared types and helpers for ops modules
Steven Enamakel2e921d732a7e
diff --git a/crates/openhuman-core/src/desktop/app_state/ops/auth_timeout.rs b/crates/openhuman-core/src/desktop/app_state/ops/auth_timeout.rsdeleted file mode 100644index 1daf610a46..0000000000--- a/crates/openhuman-core/src/desktop/app_state/ops/auth_timeout.rs+++ /dev/null@@ -1,97 +0,0 @@-//! How long the current-user refresh may take, and how long a failed run of-//! them suppresses the next attempt.-//!-//! Split out because the two values are one decision: the backoff step is-//! *derived* from the fetch timeout so that widening the timeout cannot-//! re-open #5624's poll treadmill. Keeping them adjacent is what makes that-//! relationship reviewable.--use super::LOG_PREFIX;-use log::{debug, warn};-use once_cell::sync::Lazy;-use std::time::Duration;--/// Wall-clock budget for one `auth_get_me` refresh when nothing overrides it.-pub const DEFAULT_AUTH_FETCH_TIMEOUT_SECS: u64 = 5;-/// Smallest accepted override. Anything shorter would time out a healthy-/// backend on a merely slow link on every poll — the #5624 treadmill inverted.-pub const MIN_AUTH_FETCH_TIMEOUT_SECS: u64 = 2;-/// Largest accepted override.-///-/// The ceiling exists because this budget is spent *inside* the snapshot RPC,-/// concurrently with [`RUNTIME_SNAPSHOT_TIMEOUT`], and the frontend gives that-/// RPC 30s total. `12 + 10 = 22` leaves headroom; a larger value would let an-/// operator turn a slow backend into a failed snapshot call.-pub const MAX_AUTH_FETCH_TIMEOUT_SECS: u64 = 12;-/// Operator override for [`auth_fetch_timeout`]. A missing, non-numeric or-/// out-of-range value leaves the default in place (and is logged once).-pub const AUTH_FETCH_TIMEOUT_ENV_VAR: &str = "OPENHUMAN_AUTH_FETCH_TIMEOUT_SECS";--/// Floor under the first backoff step, independent of the fetch timeout.-///-/// Must stay above [`CURRENT_USER_REFRESH_TTL`], which governs how soon a poll-/// asks for a live fetch at all.-const CURRENT_USER_BACKOFF_BASE_FLOOR: Duration = Duration::from_secs(10);--/// Parse a raw override into a bounded timeout in seconds.-///-/// Pure and global-free so the clamp can be tested without touching the process-/// environment. `None`, unparseable input, and out-of-range values all fall back-/// to [`DEFAULT_AUTH_FETCH_TIMEOUT_SECS`].-pub fn parse_auth_fetch_timeout_secs(raw: Option<&str>) -> u64 {- auth_fetch_timeout_override(raw).unwrap_or(DEFAULT_AUTH_FETCH_TIMEOUT_SECS)-}--/// The override if `raw` names one inside the accepted range, else `None`.-///-/// Split from [`parse_auth_fetch_timeout_secs`] so the resolver can tell-/// "accepted" from "fell back" without re-deriving it by comparing strings —-/// which would report a valid `05` as ignored.-pub(super) fn auth_fetch_timeout_override(raw: Option<&str>) -> Option<u64> {- raw.map(str::trim)- .and_then(|s| s.parse::<u64>().ok())- .filter(|n| (MIN_AUTH_FETCH_TIMEOUT_SECS..=MAX_AUTH_FETCH_TIMEOUT_SECS).contains(n))-}--/// The effective `auth_get_me` timeout, resolved once per process.-///-/// Read through a function rather than held as a `const` so #5930's "5s may be-/// too tight" has an answer that does not need a rebuild. Every caller — the-/// `tokio::time::timeout` wrapper, the timeout log line, and the recorded-/// timeout error's message — reads the same value, so they cannot drift.-pub(super) fn auth_fetch_timeout() -> Duration {- static RESOLVED: Lazy<Duration> = Lazy::new(|| {- let raw = std::env::var(AUTH_FETCH_TIMEOUT_ENV_VAR).ok();- match (raw.as_deref(), auth_fetch_timeout_override(raw.as_deref())) {- (Some(raw), None) => warn!(- "{LOG_PREFIX} ignoring {AUTH_FETCH_TIMEOUT_ENV_VAR}={raw:?}: not an integer in \- {MIN_AUTH_FETCH_TIMEOUT_SECS}..={MAX_AUTH_FETCH_TIMEOUT_SECS}; \- using {DEFAULT_AUTH_FETCH_TIMEOUT_SECS}s"- ),- (Some(_), Some(secs)) => debug!(- "{LOG_PREFIX} auth fetch timeout overridden to {secs}s by {AUTH_FETCH_TIMEOUT_ENV_VAR}"- ),- (None, _) => {}- }- Duration::from_secs(parse_auth_fetch_timeout_secs(raw.as_deref()))- });- *RESOLVED-}--/// First backoff step after the backend fails to answer `auth_get_me`.-///-/// Derived from `fetch_timeout` rather than fixed, because the property that-/// actually stops the treadmill is *relational*: the step must outlast both the-/// fetch timeout and the frontend's ~5s `app_state_snapshot` poll, or the next-/// poll finds the window already expired and pays the full timeout again-/// (#5624 — 51 timeouts in one session, ~5s each). Making the timeout-/// configurable (#5930) without deriving this would let an operator re-open-/// that bug by widening the timeout past a fixed 10s step.-pub(super) fn current_user_backoff_base_for(fetch_timeout: Duration) -> Duration {- CURRENT_USER_BACKOFF_BASE_FLOOR.max(fetch_timeout.saturating_mul(2))-}--/// [`current_user_backoff_base_for`] applied to the effective timeout.-pub(super) fn current_user_backoff_base() -> Duration {- current_user_backoff_base_for(auth_fetch_timeout())-}diff --git a/crates/openhuman-core/src/desktop/app_state/ops/current_user.rs b/crates/openhuman-core/src/desktop/app_state/ops/current_user.rsdeleted file mode 100644index c0df8c8639..0000000000--- a/crates/openhuman-core/src/desktop/app_state/ops/current_user.rs+++ /dev/null@@ -1,565 +0,0 @@-//! The current-user cache: the positive cache (last `/auth/me` answer),-//! the negative cache (recent availability failures and their backoff),-//! and the blocking/background refresh paths that keep both in sync with-//! the backend. [`current_user_fetch`](super::current_user_fetch) does the-//! actual HTTP call; [`current_user_generation`](super::current_user_generation)-//! owns sign-out invalidation of these caches; [`staleness`](super::staleness)-//! reports how old the data being served is.--use super::auth_timeout::{auth_fetch_timeout, current_user_backoff_base};-use super::current_user_fetch::{fetch_current_user, sanitize_snapshot_user};-use super::current_user_generation::{- clear_current_user_failure_unless_stale, current_user_generation,- note_current_user_success_unless_stale, record_current_user_failure_locked,- record_current_user_failure_unless_stale,-};-use super::LOG_PREFIX;-use crate::api::config::effective_backend_api_url;-use crate::config::Config;-use log::debug;-use once_cell::sync::Lazy;-use parking_lot::Mutex;-use serde_json::Value;-use std::time::{Duration, Instant};--/// How long a positive `/auth/me` answer is served without asking the-/// backend again.-pub(super) const CURRENT_USER_REFRESH_TTL: Duration = Duration::from_secs(5);-/// Ceiling on the negative-cache backoff. Modest on purpose: this window is-/// time during which a recovered backend still will not be noticed, so it-/// trades a bounded amount of staleness for not stalling every poll. At the-/// cap a 5s poll loop attempts roughly one live fetch per twelve polls-/// instead of one per poll.-pub(super) const CURRENT_USER_BACKOFF_MAX: Duration = Duration::from_secs(60);--/// The positive cache: the last successful `/auth/me` answer, keyed on-/// `(api_base, token)`.-pub(super) static CURRENT_USER_CACHE: Lazy<Mutex<Option<CachedCurrentUser>>> =- Lazy::new(|| Mutex::new(None));-/// Negative counterpart to [`CURRENT_USER_CACHE`]: the last *availability*-/// failure against `auth_get_me`, so a client whose backend is unreachable stops-/// re-paying [`auth_fetch_timeout`] on every snapshot poll.-///-/// Kept separate from the positive cache rather than folded into it because the-/// two have different lifetimes and different readers —-/// [`peek_cached_current_user_identity`] must keep serving the last known-/// identity throughout an outage, and it reads only the positive cache.-pub(super) static CURRENT_USER_FAILURE: Lazy<Mutex<Option<CurrentUserFailure>>> =- Lazy::new(|| Mutex::new(None));--#[derive(Debug, Clone)]-pub(super) struct CachedCurrentUser {- pub(super) api_base: String,- pub(super) token: String,- pub(super) fetched_at: Instant,- pub(super) user: Value,-}--#[derive(Debug, Clone)]-pub(super) enum CurrentUserFetchError {- Rejected(String),- TransientResponse(String),- FetchFailed(String),- /// A recorded availability failure replayed from the backoff window- /// instead of going to the network (see- /// [`suppressed_current_user_failure`]).- ///- /// Carries the original error so callers that only want the message behave- /// exactly as before, plus the two numbers that distinguish "the backend- /// just failed" from "we did not ask the backend". Without this the- /// snapshot caller logs a replay — which costs microseconds and makes no- /// request — with the same `WARN … refresh failed` wording as a real 5s- /// timeout, so a healthy backoff reads in the logs like a hammering loop.- /// That misreading is what #5930 was filed on.- Suppressed {- inner: Box<CurrentUserFetchError>,- /// Length of the failure run that opened the window.- consecutive: u32,- /// How long until the next live attempt is allowed.- retry_in: Duration,- },-}--impl CurrentUserFetchError {- pub(super) fn message(&self) -> &str {- match self {- CurrentUserFetchError::Rejected(message)- | CurrentUserFetchError::TransientResponse(message)- | CurrentUserFetchError::FetchFailed(message) => message,- CurrentUserFetchError::Suppressed { inner, .. } => inner.message(),- }- }-}--impl CurrentUserFetchError {- /// Whether this failure says the *backend was not reachable or not healthy*,- /// as opposed to saying something about our credentials.- ///- /// Only these are worth backing off. A [`Rejected`](Self::Rejected) is the- /// backend answering, in time, that the token is no good — it drives the- /// deferred-session cleanup at the snapshot caller, and replaying it from a- /// cache would either delay that cleanup or, worse, hand the caller a- /// different variant than the one the backend actually produced.- pub(super) fn is_availability_failure(&self) -> bool {- match self {- CurrentUserFetchError::TransientResponse(_) | CurrentUserFetchError::FetchFailed(_) => {- true- }- CurrentUserFetchError::Rejected(_) => false,- // Defensive: a replay is not a new observation, and recording it- // would extend the window on evidence the backend never supplied.- // `fetch_current_user_cached` returns this variant before it can- // reach the recorder, so this arm should never actually run.- CurrentUserFetchError::Suppressed { .. } => false,- }- }-}--/// The last availability failure against `auth_get_me`, keyed the same way the-/// positive cache is so that changing environment or signing in as someone else-/// bypasses it rather than inheriting someone else's outage.-#[derive(Debug, Clone)]-pub(super) struct CurrentUserFailure {- pub(super) api_base: String,- pub(super) token: String,- pub(super) failed_at: Instant,- /// Failures in an unbroken run, counted from 1. Drives the backoff width.- pub(super) consecutive: u32,- /// Replayed verbatim while the window is open, so a caller that matches on- /// the variant sees what the backend really produced.- pub(super) error: CurrentUserFetchError,-}--/// How long a run of `consecutive` failures suppresses the next live attempt.-///-/// Doubles from [`current_user_backoff_base`] and saturates at-/// [`CURRENT_USER_BACKOFF_MAX`]. `consecutive` is 1-based; 0 is treated as 1 so-/// the function has no surprising zero-length window.-pub(super) fn current_user_backoff(consecutive: u32) -> Duration {- let steps = consecutive.saturating_sub(1).min(16);- current_user_backoff_base()- .saturating_mul(2u32.saturating_pow(steps))- .min(CURRENT_USER_BACKOFF_MAX)-}--/// The recorded failure for `(api_base, token)` if its backoff window is still-/// open, in which case the caller should return it instead of going to the-/// network.-pub(super) fn suppressed_current_user_failure(- api_base: &str,- token: &str,-) -> Option<(CurrentUserFetchError, u32, Duration)> {- let failure = CURRENT_USER_FAILURE.lock();- let entry = failure.as_ref()?;- if entry.api_base != api_base || entry.token != token {- return None;- }- let window = current_user_backoff(entry.consecutive);- let elapsed = entry.failed_at.elapsed();- (elapsed < window).then(|| (entry.error.clone(), entry.consecutive, window - elapsed))-}--/// Record an availability failure, extending the run when it is the same-/// `(api_base, token)` and starting a new one when it is not.-///-/// A [`CurrentUserFetchError::Rejected`] is ignored — see-/// [`CurrentUserFetchError::is_availability_failure`].-pub(super) fn record_current_user_failure(- api_base: &str,- token: &str,- error: CurrentUserFetchError,-) {- if !error.is_availability_failure() {- return;- }- let mut failure = CURRENT_USER_FAILURE.lock();- record_current_user_failure_locked(&mut failure, api_base, token, error);-}--/// Forget any recorded failure, so the next poll goes straight to the network.-///-/// Called on every success and on sign-out. Missing either one is the failure-/// mode that matters here: a stale record outliving its cause keeps the app on-/// the stored snapshot after the backend has already come back.-pub(super) fn clear_current_user_failure() {- *CURRENT_USER_FAILURE.lock() = None;-}--/// Record the timeout path's failure.-///-/// The timeout is applied by the snapshot caller, wrapping the whole of-/// `fetch_current_user_cached`, so when it fires that future is **dropped-/// mid-flight** and nothing inside it runs — including the failure recording on-/// its error path. Without this call the backoff would never engage for the one-/// case #5624 is actually about, which is timeouts rather than returned errors.-///-/// Takes the generation read before the timeout started, for the same reason the-/// refresh does: a sign-out during those `auth_fetch_timeout()` seconds means this-/// outage belongs to an identity that no longer exists, and recording it would-/// suppress the first poll of the next session.-pub(super) fn note_current_user_timeout(generation: u64, config: &Config, token: &str) {- record_current_user_failure_unless_stale(- generation,- ¤t_user_api_base(config),- token,- CurrentUserFetchError::FetchFailed(format!(- "request timed out after {}s",- auth_fetch_timeout().as_secs()- )),- );-}--/// The cache key both the positive and negative current-user caches are keyed-/// on. Factored out so the snapshot caller, which records the timeout path, and-/// the fetch itself cannot drift apart on how the base URL is normalised.-pub(super) fn current_user_api_base(config: &Config) -> String {- effective_backend_api_url(&config.api_url)- .trim()- .trim_end_matches('/')- .to_string()-}--pub(super) async fn fetch_current_user_cached(- config: &Config,- token: &str,- allow_cache: bool,- generation: u64,-) -> Result<Option<Value>, CurrentUserFetchError> {- let api_base = current_user_api_base(config);-- if allow_cache {- if let Some((user, age)) = cached_current_user(&api_base, token) {- if age < CURRENT_USER_REFRESH_TTL {- debug!(- "{LOG_PREFIX} using cached current user age_ms={}",- age.as_millis()- );- return Ok(Some(user));- }- // Stale-while-revalidate. The entry has expired, but we already- // know who this is — serve that and re-confirm it behind the poll- // instead of making the shell wait on a WAN round trip to be told- // the same thing. Blocking here is what put a floor of one round- // trip under every `app_state_snapshot` (#6180: 732 calls in 3.5h,- // not one of them under 500ms).- //- // The refresh cadence is unchanged by this: `refresh_current_user_now`- // stamps `fetched_at` when the request goes out, not when it lands,- // so the round trip is not folded into the next TTL window and the- // poll after this one expires on the same schedule it always did.- // Stamping at completion would have quietly halved the cadence —- // see the note there (#6190 review). The snapshot keeps reporting- // the true age of the data it is serving in- // `current_user_stale_seconds`.- //- // Only the expired-entry path revalidates in the background. With- // no entry at all the shell has no identity to render, so that- // first fetch after login still blocks, below.- spawn_current_user_refresh(config, token, generation);- debug!(- "{LOG_PREFIX} serving expired current user age_ms={} while refreshing behind the poll",- age.as_millis()- );- return Ok(Some(user));- }-- // Nothing fresh to serve, so this poll would normally go to the network- // — and if the backend is unreachable it would sit there for the full- // `auth_fetch_timeout` before the caller gives up and uses the stored- // snapshot anyway. Replay the recorded failure instead while its window- // is open. The caller's behaviour is unchanged (it already falls back on- // `Err`); it just does so in microseconds. Gated on `allow_cache` for- // the same reason the positive cache is: a pending-backend-validation- // pass is explicitly asking for a live answer.- if let Some((error, consecutive, remaining)) =- suppressed_current_user_failure(&api_base, token)- {- debug!(- "{LOG_PREFIX} skipping current user refresh; backend failed {consecutive}x, \- retrying in {}ms",- remaining.as_millis()- );- // Wrapped rather than returned bare so the caller can tell a replay- // from a live failure. Both fall back to the stored snapshot, but- // only one of them made a request, and logging them identically is- // what made a working backoff read as a hammering loop (#5930).- return Err(CurrentUserFetchError::Suppressed {- inner: Box::new(error),- consecutive,- retry_in: remaining,- });- }- }-- refresh_current_user_now(config, token, generation, RefreshOrigin::Blocking).await-}--/// The cached user for this identity and how old it is, if the cache holds one.-///-/// Reads under one lock and hands back an owned copy, so no caller holds-/// `CURRENT_USER_CACHE` across a decision — the freshness test and the-/// stale-while-revalidate branch below both need the same read.-pub(super) fn cached_current_user(api_base: &str, token: &str) -> Option<(Value, Duration)> {- let cache = CURRENT_USER_CACHE.lock();- let entry = cache.as_ref()?;- (entry.api_base == api_base && entry.token == token)- .then(|| (entry.user.clone(), entry.fetched_at.elapsed()))-}--/// Single-flight gate for the background refresh.-///-/// An async mutex held by the spawned task for its lifetime, taken with-/// `try_lock` so a poll that finds a refresh already running simply declines to-/// start a second one rather than queueing behind it. Same gate, same reason as-/// [`RUNTIME_SNAPSHOT_REBUILD`]: without it every overlapping poll launches its-/// own fetch. Using a guard rather than a flag means a panicking refresh-/// releases the gate instead of wedging it shut for the life of the process.-pub(super) static CURRENT_USER_REFRESH_INFLIGHT: Lazy<tokio::sync::Mutex<()>> =- Lazy::new(|| tokio::sync::Mutex::new(()));--/// Refresh the cached current user without making the caller wait for it.-///-/// Declines to start when the backoff window from an earlier failure is still-/// open — a background refresh would re-pay exactly the timeout that window-/// exists to avoid (#5624) — and when a previous poll's refresh is still in-/// flight.-pub(super) fn spawn_current_user_refresh(config: &Config, token: &str, generation: u64) {- if let Some((error, consecutive, remaining)) =- suppressed_current_user_failure(¤t_user_api_base(config), token)- {- // Logged here because the stale-while-revalidate return above means an- // outage no longer reaches the replay branch in- // `fetch_current_user_cached` — without this line a backend that has- // been down for minutes leaves no trace at all in the snapshot logs.- // `debug!`, not `warn!`: no request was made and nothing waited on it- // (#5930).- debug!(- "{LOG_PREFIX} not refreshing current user behind the poll; backend failed \- {consecutive}x, retrying in {}ms: {}",- remaining.as_millis(),- error.message()- );- return;- }- let gate: &'static tokio::sync::Mutex<()> = &CURRENT_USER_REFRESH_INFLIGHT;- let Ok(guard) = gate.try_lock() else {- return;- };-- let config = config.clone();- let token = token.to_string();- tokio::spawn(async move {- let _guard = guard;- // Bounded by the same budget the blocking path spends, so a hung- // backend cannot leave the gate closed for longer than one window.- match tokio::time::timeout(- auth_fetch_timeout(),- refresh_current_user_now(&config, &token, generation, RefreshOrigin::Background),- )- .await- {- Ok(Ok(_)) => {}- // The stale entry stands and the failure is recorded, so the next- // poll takes the backoff path. Not a failure of any user-visible- // operation — nothing was waiting on this.- Ok(Err(error)) => debug!(- "{LOG_PREFIX} background current user refresh failed; serving stale entry: {}",- error.message()- ),- Err(_) => {- debug!(- "{LOG_PREFIX} background current user refresh timed out after {}s; serving stale entry",- auth_fetch_timeout().as_secs()- );- // The generation is captured from when the refresh was launched and- // guards the timeout record against sign-out racing the timeout.- note_current_user_timeout(generation, &config, &token);- }- }- });-}--/// Where a refresh was started from, which decides whether its answer may still-/// be committed by the time it lands.-#[derive(Clone, Copy, PartialEq, Eq, Debug)]-pub(super) enum RefreshOrigin {- /// The caller is still awaiting this refresh and still holds the identity- /// it asked for, so the answer is authoritative by construction.- Blocking,- /// Detached from the poll that started it, and therefore able to outlive- /// the identity it was started for — a logout and re-login, or an- /// environment switch, can land in between.- Background,-}--/// Go to the backend, then reconcile the caches and freshness stamps with what-/// came back. The blocking half of [`fetch_current_user_cached`], split out so-/// the background refresh runs exactly the same path rather than a parallel-/// copy of it that could drift.-pub(super) async fn refresh_current_user_now(- config: &Config,- token: &str,- generation: u64,- origin: RefreshOrigin,-) -> Result<Option<Value>, CurrentUserFetchError> {- let api_base = current_user_api_base(config);- // The TTL clock starts when the request goes out, not when it lands.- //- // `fetched_at` is what `CURRENT_USER_REFRESH_TTL` is measured against, and- // the poll loop schedules itself from the previous *response*. Stamping at- // completion would therefore fold the round trip into the next window: a- // refresh taking `L` leaves the following poll only `TTL - L` from expiry,- // it reads the entry as fresh, and the refresh after that is skipped- // entirely — halving the cadence as a side effect of not blocking (#6190- // review). Stamping at initiation keeps the wall-clock refresh cadence- // exactly what it was before this path became non-blocking; the only thing- // that changed is who waits for it.- //- // It also errs the safe way. The data itself arrives at `started_at + L`,- // so calling it `started_at` slightly *overstates* its age and expires the- // entry sooner — never later. `note_current_user_success` below is the- // stamp that answers "how old is the data we are showing", and it stays at- // completion, because that is when the data actually arrived.- let started_at = Instant::now();- let fetched = match fetch_current_user(config, token).await {- Ok(user) => sanitize_snapshot_user(user),- Err(error) => {- if !record_current_user_failure_unless_stale(- generation,- &api_base,- token,- error.clone(),- ) {- debug!("{LOG_PREFIX} discarding current user failure that raced sign-out");- }- return Err(error);- }- };- // A detached refresh can land after the app has moved to another identity,- // and every write below is process-global. Committing then would regress- // the cache to the previous user — and `peek_cached_current_user_identity`- // reads that slot WITHOUT a key check (#926), so the regressed entry would- // be embedded in the agent's prompts as the current user. The keyed reads- // in `fetch_current_user_cached` would merely miss; that one would be- // wrong.- //- // The check and the commit share ONE lock acquisition, and nothing between- // them can suspend or release it. Validating through a separate read would- // leave a window in which a blocking refresh for a newer identity commits- // after this one has already decided it is current — narrow, but the- // runtime is multi-threaded, so "narrow" is not "impossible".- //- // The generation check (against sign-out) and the identity check (against- // a subsequent login the background refresh missed) are applied under the- // same lock. Sign-out bumps the generation before clearing the caches, so- // a refresh that read the old token before sign-out will read the old- // generation and fail the check — the cache it would restore was already- // cleared.- //- // The failure and freshness stamps stay OUTSIDE this scope: they take their- // own locks, and this module's rule is that `LAST_CURRENT_USER_SUCCESS` is- // never nested inside `CURRENT_USER_CACHE`. They therefore run *after* the- // commit rather than before it, which is also what lets a discarded refresh- // leave the newer identity's `CURRENT_USER_FAILURE` record alone —- // `clear_current_user_failure` is unkeyed and would otherwise wipe it. The- // stamp is only ever read as an age in seconds, so moving it to the far- // side of the commit cannot change an observable answer.- //- // When sign-out wins the generation race, the failure and success records- // are untouched — they were already cleared by `forget_current_user_caches`,- // and this refresh has no business touching them either.- let committed = {- let mut cache = CURRENT_USER_CACHE.lock();- let generation_mismatch = current_user_generation() != generation;- if generation_mismatch {- debug!(- "{LOG_PREFIX} discarding current user refresh that raced sign-out; \- generation bumped while in flight"- );- false- } else {- let moved_on = cache- .as_ref()- .is_some_and(|entry| entry.api_base != api_base || entry.token != token);- if origin == RefreshOrigin::Background && moved_on {- false- } else {- match fetched.clone() {- Some(user) => {- debug!("{LOG_PREFIX} refreshed current user from backend");- *cache = Some(CachedCurrentUser {- api_base: api_base.clone(),- token: token.to_string(),- fetched_at: started_at,- user,- });- }- None => {- debug!("{LOG_PREFIX} backend returned empty current user; clearing cache");- *cache = None;- }- }- true- }- }- };-- if !committed {- debug!(- "{LOG_PREFIX} discarding background current user refresh; the cache moved to \- another identity while it was in flight"- );- return Ok(fetched);- }-- // Keep all post-fetch records behind the same generation checks as the- // positive cache. A logout (or a subsequent login) can land after the- // cache commit and must not have its failure/success records overwritten.- clear_current_user_failure_unless_stale(generation);- if fetched.is_some() {- note_current_user_success_unless_stale(generation, &api_base, token);- }-- Ok(fetched)-}--/// Synchronous, network-free peek at the cached `auth_get_me` response,-/// returning only the identifying fields the prompt layer is allowed to-/// embed (`id`, `name`, `email`). Tokens stay locked behind the JWT-/// helpers — never returned through this path. See issue #926.-///-/// Returns `None` when no `auth_get_me` call has populated the cache-/// yet (CLI-only flows, fresh installs, signed-out sessions). The-/// cache TTL is **ignored** here intentionally — for prompt rendering-/// a slightly stale identity is fine; the freshness check only-/// matters for the snapshot RPC that fronts the React shell.-pub fn peek_cached_current_user_identity() -> Option<crate::agent::prompts::UserIdentity> {- let cache = CURRENT_USER_CACHE.lock();- let entry = cache.as_ref()?;- let user = entry.user.as_object()?;-- let pluck = |key: &str| -> Option<String> {- user.get(key)- .and_then(Value::as_str)- .map(str::trim)- .filter(|s| !s.is_empty())- .map(str::to_string)- };-- let id = pluck("id")- .or_else(|| pluck("user_id"))- .or_else(|| pluck("userId"));- let name = pluck("name")- .or_else(|| pluck("displayName"))- .or_else(|| pluck("display_name"))- .or_else(|| pluck("full_name"))- .or_else(|| pluck("fullName"));- let email = pluck("email");-- let identity = crate::agent::prompts::UserIdentity { id, name, email };- if identity.is_empty() {- None- } else {- Some(identity)- }-}diff --git a/crates/openhuman-core/src/desktop/app_state/ops/current_user_fetch.rs b/crates/openhuman-core/src/desktop/app_state/ops/current_user_fetch.rsdeleted file mode 100644index bd6bd3ed22..0000000000--- a/crates/openhuman-core/src/desktop/app_state/ops/current_user_fetch.rs+++ /dev/null@@ -1,117 +0,0 @@-//! The network call behind the current-user cache: a shared, pooled HTTP-//! client for `GET /auth/me`, and the plain fetch-and-classify logic that-//! turns its response into a [`CurrentUserFetchError`] or a sanitized user.--use super::current_user::CurrentUserFetchError;-use super::LOG_PREFIX;-use crate::api::config::effective_backend_api_url;-use crate::api::jwt::bearer_authorization_value;-use crate::config::Config;-use log::{debug, warn};-use once_cell::sync::Lazy;-use reqwest::{header::AUTHORIZATION, Client, Method, Url};-use serde_json::Value;-use std::time::Duration;--pub(super) const AUTH_ME_REVALIDATION_TRANSIENT_STATUSES: &[u16] =- &[408, 429, 500, 502, 503, 504, 520];--/// One process-wide client for `GET /auth/me`, so its pooled TCP+TLS-/// connection survives between snapshot polls instead of being handshaken-/// again on every one.-///-/// `app_state_snapshot` polls this endpoint for the life of the session. A-/// `Client` built per call gave each poll its own connection pool, so every one-/// paid a fresh TCP connect *and* TLS handshake before the request could go out-/// — two extra WAN round trips on top of the one the request itself costs.-/// Measured against the production backend over a ~250ms RTT link: ~780-1420ms-/// on a cold connection versus ~380-540ms on a reused one (#6180).-///-/// `reqwest::Client` is internally reference-counted and built to be shared;-/// holding one is the only way to keep its pool.-///-/// The product-identity header moved to the request rather than-/// `default_headers`, because this client now outlives-/// [`crate::api::product::set_product_identity`] — baking the header in here-/// would pin whichever identity happened to be installed when the first-/// snapshot ran. `MedullaClient` reads it per request for the same reason.-pub(super) static CURRENT_USER_CLIENT: Lazy<Result<Client, String>> = Lazy::new(|| {- // Platform-appropriate TLS backend — see [`crate::util::tls`].- crate::util::tls::tls_client_builder()- .http1_only()- .timeout(Duration::from_secs(30))- .connect_timeout(Duration::from_secs(10))- .build()- .map_err(|e| format!("failed to build HTTP client: {e}"))-});--pub(super) fn resolve_base(config: &Config) -> Result<Url, String> {- let base = effective_backend_api_url(&config.api_url);- let mut parsed =- Url::parse(base.trim()).map_err(|e| format!("invalid api_url '{}': {e}", base))?;- if !parsed.path().ends_with('/') && parsed.path() != "/" {- let normalized = format!("{}/", parsed.path());- parsed.set_path(&normalized);- }- Ok(parsed)-}--pub(super) async fn fetch_current_user(- config: &Config,- token: &str,-) -> Result<Option<Value>, CurrentUserFetchError> {- let client = CURRENT_USER_CLIENT- .as_ref()- .map_err(|e| CurrentUserFetchError::FetchFailed(e.clone()))?;- let base = resolve_base(config).map_err(CurrentUserFetchError::FetchFailed)?;- let url = base- .join("auth/me")- .map_err(|e| CurrentUserFetchError::FetchFailed(format!("build URL failed: {e}")))?;- let response = client- .request(Method::GET, url.clone())- // `GET /auth/me` is backend traffic like any other, so it carries the- // product identity. This request is hand-rolled rather than issued- // through `BackendOAuthClient`, so it inherits nothing from that path's- // default headers — see [`crate::api::product`].- .headers(crate::api::product::product_identity_headers())- .header(AUTHORIZATION, bearer_authorization_value(token))- .send()- .await- .map_err(|e| CurrentUserFetchError::FetchFailed(format!("request failed: {e}")))?;- let status = response.status();- let text = response.text().await.map_err(|e| {- CurrentUserFetchError::FetchFailed(format!("failed to read backend response body: {e}"))- })?;-- debug!("{LOG_PREFIX} GET /auth/me -> {}", status);-- if !status.is_success() {- let message = format!("{status} {text}");- warn!(- "{LOG_PREFIX} current user fetch failed: {} {}",- status, text- );- return if AUTH_ME_REVALIDATION_TRANSIENT_STATUSES.contains(&status.as_u16()) {- Err(CurrentUserFetchError::TransientResponse(message))- } else {- Err(CurrentUserFetchError::Rejected(message))- };- }-- let raw: Value =- serde_json::from_str(&text).unwrap_or_else(|_| Value::String(text.to_string()));- let user = raw- .as_object()- .and_then(|obj| obj.get("data"))- .cloned()- .unwrap_or(raw);- Ok(Some(user))-}--pub(super) fn sanitize_snapshot_user(user: Option<Value>) -> Option<Value> {- match user {- Some(Value::Object(map)) if map.is_empty() => None,- Some(Value::Null) => None,- other => other,- }-}diff --git a/crates/openhuman-core/src/desktop/app_state/ops/current_user_generation.rs b/crates/openhuman-core/src/desktop/app_state/ops/current_user_generation.rsdeleted file mode 100644index d19056fe1e..0000000000--- a/crates/openhuman-core/src/desktop/app_state/ops/current_user_generation.rs+++ /dev/null@@ -1,203 +0,0 @@-//! Sign-out invalidation for the current-user caches.-//!-//! `CURRENT_USER_CACHE`, `CURRENT_USER_FAILURE` and `LAST_CURRENT_USER_SUCCESS`-//! are all keyed on `(api_base, token)`, so clearing them is not enough on its-//! own:-//! `fetch_current_user_cached` awaits the network between reading them and-//! writing them, and a refresh already in flight when sign-out lands would-//! re-publish exactly the state the sign-out removed. A generation counter,-//! read when the token is read and re-checked under each cache's own lock,-//! is what closes that window (#5758).--use super::current_user::{- clear_current_user_failure, CachedCurrentUser, CurrentUserFailure, CurrentUserFetchError,- CURRENT_USER_CACHE, CURRENT_USER_FAILURE,-};-use super::staleness::{- clear_current_user_success, note_current_user_success_locked, LAST_CURRENT_USER_SUCCESS,-};-use super::LOG_PREFIX;-use log::debug;-use once_cell::sync::Lazy;-use serde_json::Value;-use std::sync::atomic::{AtomicU64, Ordering};-use std::time::Instant;--/// Bumped by [`forget_current_user_caches`]; read by `snapshot` before it-/// loads the session token, threaded into `fetch_current_user_cached`, and-/// checked again under the lock before either cache is written.-///-/// Counting rather than flagging keeps two overlapping sign-outs from-/// cancelling each other out.-pub(super) static CURRENT_USER_GENERATION: AtomicU64 = AtomicU64::new(0);--/// Serializes session-profile mutation with pending-session persistence. The-/// generation check must cover the profile write itself, not only the work-/// that prepares its input, or logout can bump the generation between the-/// check and `store_provider_token`.-pub static CURRENT_USER_SESSION_MUTATION_LOCK: Lazy<tokio::sync::Mutex<()>> =- Lazy::new(|| tokio::sync::Mutex::new(()));--/// The failure write itself, taking the guard rather than the lock, so a caller-/// that must decide *under* the lock can do so without re-entering it.-pub(super) fn record_current_user_failure_locked(- failure: &mut Option<CurrentUserFailure>,- api_base: &str,- token: &str,- error: CurrentUserFetchError,-) {- let consecutive = match failure.as_ref() {- Some(entry) if entry.api_base == api_base && entry.token == token => {- entry.consecutive.saturating_add(1)- }- _ => 1,- };- *failure = Some(CurrentUserFailure {- api_base: api_base.to_string(),- token: token.to_string(),- failed_at: Instant::now(),- consecutive,- error,- });-}--/// Drop every current-user cache.-///-/// Sign-out must forget the positive snapshot *and* the negative failure record-/// together: signing back in with the same JWT inside their windows would-/// otherwise replay pre-logout state — the old `/auth/me` snapshot for the rest-/// of [`CURRENT_USER_REFRESH_TTL`], and the old error for up to-/// [`CURRENT_USER_BACKOFF_MAX`].-///-/// The freshness stamp goes with them. `clear_current_user_success` already-/// says why — "so the next account does not inherit this one's freshness"-/// — and sign-out is exactly the case it names; until now it ran only on-/// the deferred-rejection path (#5930).-///-/// Public because the canonical sign-out path lives in-/// `security::credentials::ops::clear_session`, outside this module, and these-/// statics are private to it.-pub fn forget_current_user_caches() {- // Bump BEFORE taking either lock. That order is what makes the checks in- // `publish_current_user_unless_stale` and- // `record_current_user_failure_unless_stale` sufficient: a writer holding- // one of these locks either observes the bump and stands down, or read the- // generation before it — in which case its write necessarily completed and- // released the lock before the clear below could acquire it, so the clear- // lands second and wins. There is no interleaving that leaves pre-logout- // state behind.- CURRENT_USER_GENERATION.fetch_add(1, Ordering::SeqCst);- *CURRENT_USER_CACHE.lock() = None;- clear_current_user_failure();- clear_current_user_success();-}--/// The sign-out generation a refresh must still be running under to publish.-pub(super) fn current_user_generation() -> u64 {- CURRENT_USER_GENERATION.load(Ordering::SeqCst)-}--/// Record an availability failure only if `generation` is still current,-/// **checked while holding the failure lock**.-///-/// Checking before the lock would be a check-then-act: sign-out could land in-/// the gap and this write would then restore the negative cache it had just-/// cleared.-pub(super) fn record_current_user_failure_unless_stale(- generation: u64,- api_base: &str,- token: &str,- error: CurrentUserFetchError,-) -> bool {- if !error.is_availability_failure() {- return true;- }- let mut failure = CURRENT_USER_FAILURE.lock();- if current_user_generation() != generation {- return false;- }- record_current_user_failure_locked(&mut failure, api_base, token, error);- true-}--/// Stamp a refreshed user's freshness only if `generation` is still current,-/// **checked while holding the success lock** — the same check-then-act the-/// failure recorder avoids, for the same reason.-pub(super) fn note_current_user_success_unless_stale(- generation: u64,- api_base: &str,- token: &str,-) -> bool {- let mut success = LAST_CURRENT_USER_SUCCESS.lock();- if current_user_generation() != generation {- return false;- }- note_current_user_success_locked(&mut success, api_base, token);- true-}--/// Clear the failure record only while the refresh still belongs to the-/// current session generation.-pub(super) fn clear_current_user_failure_unless_stale(generation: u64) -> bool {- let mut failure = CURRENT_USER_FAILURE.lock();- if current_user_generation() != generation {- return false;- }- *failure = None;- true-}--/// Publish a fresh `/auth/me` answer to the positive cache, and drop any-/// recorded outage, only if `generation` is still current — each check taken-/// under the lock that guards the record it gates.-///-/// Returns `false` when sign-out won, in which case nothing was written.-pub(super) fn publish_current_user_unless_stale(- generation: u64,- api_base: &str,- token: &str,- fetched: Option<Value>,-) -> bool {- // Only a refreshed *user* makes the displayed data fresh: the backend can- // answer 200 with no user, and the caller then falls back to `stored_user`,- // so stamping here would report an age of ~0s for data that never changed.- //- // Taken before the cache lock and never inside it, because `ops_staleness`- // requires that `LAST_CURRENT_USER_SUCCESS` never nest inside- // `CURRENT_USER_CACHE`. Standing down here ends the publish: if sign-out has- // landed, none of the three records may be written.- if fetched.is_some() && !note_current_user_success_unless_stale(generation, api_base, token) {- return false;- }-- {- let mut cache = CURRENT_USER_CACHE.lock();- if current_user_generation() != generation {- return false;- }- match fetched {- Some(user) => {- debug!("{LOG_PREFIX} refreshed current user from backend");- *cache = Some(CachedCurrentUser {- api_base: api_base.to_string(),- token: token.to_string(),- fetched_at: Instant::now(),- user,- });- }- None => {- debug!("{LOG_PREFIX} backend returned empty current user; clearing cache");- *cache = None;- }- }- }-- // Clearing only ever removes state, so it cannot replay a pre-logout answer- // — but it could erase an outage a *new* session recorded after signing back- // in, so it takes the same guard.- let mut failure = CURRENT_USER_FAILURE.lock();- if current_user_generation() == generation {- *failure = None;- }- true-}diff --git a/crates/openhuman-core/src/desktop/app_state/ops/pending_session.rs b/crates/openhuman-core/src/desktop/app_state/ops/pending_session.rsdeleted file mode 100644index 1149b1adb7..0000000000--- a/crates/openhuman-core/src/desktop/app_state/ops/pending_session.rs+++ /dev/null@@ -1,338 +0,0 @@-//! Pending-session revalidation: activating (or rejecting) an app session-//! whose backend user id was not yet confirmed, moving it into its own-//! user directory, and rebinding the login-gated services and memory-//! context that go with it.--use super::current_user_generation::{- current_user_generation, forget_current_user_caches, CURRENT_USER_SESSION_MUTATION_LOCK,-};-use super::LOG_PREFIX;-use crate::api::rest::user_id_from_profile_payload;-use crate::config::Config;-use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};-use log::{debug, warn};-use serde_json::Value;-use std::collections::{BTreeMap, HashMap};-use std::fs;-use std::path::{Path, PathBuf};--/// Marks a stored `current_user` payload as not yet confirmed against the-/// backend — set on a locally-created session, cleared once `auth_get_me`-/// confirms the user id.-pub(super) const PENDING_BACKEND_VALIDATION_FIELD: &str = "pendingBackendValidation";--pub(super) fn snapshot_user_pending_backend_validation(user: Option<&Value>) -> bool {- user.and_then(Value::as_object)- .and_then(|obj| obj.get(PENDING_BACKEND_VALIDATION_FIELD))- .and_then(Value::as_bool)- .unwrap_or(false)-}--pub(super) fn clear_pending_backend_validation_flag(mut user: Value) -> Value {- if let Value::Object(ref mut map) = user {- map.remove(PENDING_BACKEND_VALIDATION_FIELD);- }- user-}--pub(super) fn pending_session_user_id_for_cleanup(- stored_user: Option<&Value>,- metadata: &BTreeMap<String, String>,-) -> Option<String> {- stored_user- .and_then(user_id_from_profile_payload)- .or_else(|| {- metadata- .get("user_id")- .map(String::as_str)- .map(str::trim)- .filter(|user_id| !user_id.is_empty())- .map(str::to_string)- })-}--pub(super) fn config_state_dir(config: &Config) -> Option<PathBuf> {- config.config_path.parent().map(Path::to_path_buf)-}--pub(super) fn same_config_state_dir(a: &Config, b: &Config) -> bool {- config_state_dir(a) == config_state_dir(b)-}--pub(super) fn config_dir_for_workspace_env() -> Option<PathBuf> {- let workspace = std::env::var_os("OPENHUMAN_WORKSPACE")?;- if workspace.as_os_str().is_empty() {- return None;- }-- // Resolve through the SAME workspace→config-dir mapping `config::load` uses- // (`resolve_config_dir_for_workspace`), not a private reimplementation.- // A copy here drifts from the loader: it independently doubled- // `~/.openhuman/workspace` into `~/.openhuman/.openhuman`, so- // `config_is_workspace_env_scoped` compared that against the loader's real- // `~/.openhuman` and returned false, mis-scoping credentials on session- // revalidation (#6079). Delegating keeps the two in lockstep, including the- // modern-layout recognition that fixes the doubling.- let workspace_dir = PathBuf::from(workspace);- let (config_dir, _workspace_dir) =- crate::config::resolve_config_dir_for_workspace(&workspace_dir);- Some(config_dir)-}--pub(super) fn config_is_workspace_env_scoped(config: &Config) -> bool {- let Some(config_dir) = config_state_dir(config) else {- return false;- };- config_dir_for_workspace_env()- .as_deref()- .is_some_and(|env_config_dir| env_config_dir == config_dir)-}--pub(super) async fn activate_revalidated_user_dir(user_id: &str) -> Result<Config, String> {- let root_dir = crate::config::default_root_openhuman_dir()- .map_err(|error| format!("failed to locate default root: {error}"))?;- let previous_active = crate::config::read_active_user_id(&root_dir);- let user_dir = crate::config::user_openhuman_dir(&root_dir, user_id);- fs::create_dir_all(&user_dir).map_err(|error| {- format!("failed to create user directory for revalidated pending session user_id={user_id}: {error}")- })?;- crate::config::write_active_user_id(&root_dir, user_id).map_err(|error| {- format!("failed to write active_user.toml for revalidated pending session user_id={user_id}: {error}")- })?;-- debug!(- "{LOG_PREFIX} activated user directory for revalidated pending session user_id={user_id}"- );- if previous_active.is_none() {- let pre_ws = crate::config::pre_login_user_dir(&root_dir).join("workspace");- if let Err(error) = crate::memory::conversations::purge_threads(pre_ws) {- debug!(- "{LOG_PREFIX} pre-login conversation purge skipped after pending session revalidation: {error}"- );- }- }-- let config = Config::load_from_default_paths().await.map_err(|error| {- format!("failed to reload config after pending session user activation: {error}")- })?;-- // The marker write above cleared the cached active workspace, and- // `load_from_default_paths` deliberately bypasses the runtime resolver, so- // nothing has refilled it. Resolve once through the authoritative path,- // which republishes the cache and announces the switch — otherwise a- // connected Event Log or notification client keeps the previous- // workspace's handle until some unrelated later config load happens- // (#5966). Publishing from `load_from_default_paths` itself would be- // wrong: it ignores `OPENHUMAN_WORKSPACE`, so under that override it does- // not know the runtime answer.- if let Err(error) = crate::config::active_workspace_dir().await {- warn!(- "{LOG_PREFIX} could not refresh the active workspace after pending session activation: {error}"- );- }-- Ok(config)-}--pub(super) async fn finish_revalidated_user_activation(- target_config: &Config,- user_id: &str,- service_rebind_source: Option<&Config>,- generation: u64,-) {- if let Err(error) = crate::cron::seed::prune_retired_jobs(target_config) {- warn!("{LOG_PREFIX} failed to prune retired cron jobs after pending session revalidation: {error}");- }-- // ── No explicit memory re-point here any more (#5560) ──────────────────- //- // This was `tinymemory_core::global::init(...)`, the in-process engine's- // process-global slot, which had to be re-pointed by hand at every- // activation site or it kept writing into the previous workspace.- // `memory::binding` is keyed on (workspace, `[subsystems.memory]`), and the- // context rebind immediately below re-points both — so memory follows it by- // construction. `CoreContext::memory_binding`'s docs state this property as- // the reason these sites need no memory call of their own.- if let Err(error) = crate::core::runtime::context::CoreContext::rebind_default_workspace(- &target_config.workspace_dir,- target_config.subsystems.memory.clone(),- ) {- warn!("{LOG_PREFIX} failed to rebind core context after pending session revalidation: {error}");- }- // No people-store rebind: people is served by the bound memory driver, and- // the core-context rebind above already moved that binding to the activated- // user's workspace.- crate::memory::conversations::register_conversation_persistence_subscriber(- target_config.workspace_dir.clone(),- );- if current_user_generation() != generation {- debug!("{LOG_PREFIX} skipping stale activation after pending session revalidation");- return;- }- if let Some(source_config) = service_rebind_source {- if current_user_generation() != generation {- debug!(- "{LOG_PREFIX} skipping stale login-gated service activation after pending session revalidation"- );- return;- }- crate::security::credentials::stop_login_gated_services(source_config).await;- if current_user_generation() != generation {- debug!(- "{LOG_PREFIX} skipping stale login-gated service restart after pending session revalidation"- );- return;- }- crate::security::credentials::start_login_gated_services(target_config).await;- } else {- debug!(- "{LOG_PREFIX} pending session revalidation left login-gated services running without restart"- );- }- crate::cron::scheduler_gate::set_signed_out(false);- crate::security::credentials::sentry_scope::bind(user_id);-}--pub(super) async fn remove_revalidated_source_profile(config: &Config) -> Result<(), String> {- let config = config.clone();- tokio::task::spawn_blocking(move || {- AuthService::from_config(&config)- .remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)- .map(|_| ())- .map_err(|e| e.to_string())- })- .await- .unwrap_or_else(|e| {- Err(format!(- "{LOG_PREFIX} revalidated source profile remove task panicked: {e}"- ))- })-}--pub(super) async fn persist_revalidated_session_user(- config: &Config,- token: &str,- base_metadata: BTreeMap<String, String>,- user: Value,- generation: u64,-) -> Result<Box<Config>, String> {- let (target_config, user_id, source_config, source_moved) = {- let _session_mutation_lock = CURRENT_USER_SESSION_MUTATION_LOCK.lock().await;- if current_user_generation() != generation {- return Err("pending session persistence became stale after sign-out".to_string());- }- let user_id = user_id_from_profile_payload(&user).ok_or_else(|| {- "backend user id required before clearing pending validation".to_string()- })?;- let workspace_env_scoped = config_is_workspace_env_scoped(config);- let target_config = if !workspace_env_scoped {- activate_revalidated_user_dir(&user_id).await?- } else {- debug!(- "{LOG_PREFIX} keeping revalidated pending session in OPENHUMAN_WORKSPACE-scoped config"- );- config.clone()- };- let source_config = config.clone();- let source_moved = !same_config_state_dir(config, &target_config);- let token = token.to_string();- let mut metadata: HashMap<String, String> = base_metadata.into_iter().collect();- metadata.insert("user_id".to_string(), user_id.clone());- metadata.insert("user_json".to_string(), user.to_string());-- let config_for_store = target_config.clone();- tokio::task::spawn_blocking(move || {- AuthService::from_config(&config_for_store)- .store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- &token,- metadata,- true,- )- .map(|_| ())- .map_err(|e| e.to_string())- })- .await- .unwrap_or_else(|e| {- Err(format!(- "{LOG_PREFIX} revalidated session persist task panicked: {e}"- ))- })?;-- if source_moved {- if let Err(error) = remove_revalidated_source_profile(&source_config).await {- warn!(- "{LOG_PREFIX} failed to remove source pending session profile after user activation: {error}"- );- }- }-- (target_config, user_id, source_config, source_moved)- };-- finish_revalidated_user_activation(- &target_config,- &user_id,- source_moved.then_some(&source_config),- generation,- )- .await;-- Ok(Box::new(target_config))-}--pub(super) async fn clear_deferred_session_after_backend_rejection(- config: &Config,- pending_user_id: Option<&str>,-) -> Result<(), String> {- let workspace_env_scoped = config_is_workspace_env_scoped(config);- let config_for_remove = config.clone();- let clear_result = tokio::task::spawn_blocking(move || {- AuthService::from_config(&config_for_remove)- .remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)- .map(|_| ())- .map_err(|e| e.to_string())- })- .await- .unwrap_or_else(|e| {- Err(format!(- "{LOG_PREFIX} deferred session clear task panicked: {e}"- ))- });-- forget_current_user_caches();- crate::cron::scheduler_gate::set_signed_out(true);-- match crate::config::default_root_openhuman_dir() {- Ok(root_dir) => {- let active_user = crate::config::read_active_user_id(&root_dir);- let should_clear_active_user = if workspace_env_scoped {- pending_user_id.is_some_and(|pending| active_user.as_deref() == Some(pending))- } else {- true- };- if should_clear_active_user {- if let Err(error) = crate::config::clear_active_user(&root_dir) {- warn!(- "{LOG_PREFIX} failed to clear active_user.toml for rejected pending session: {error}"- );- }- } else {- debug!(- "{LOG_PREFIX} preserving default active_user.toml for rejected OPENHUMAN_WORKSPACE-scoped pending session"- );- }- }- Err(error) if !workspace_env_scoped => {- warn!(- "{LOG_PREFIX} failed to locate default root while clearing rejected pending session: {error}"- );- }- Err(_) => {}- }- crate::security::credentials::stop_login_gated_services(config).await;- crate::security::credentials::sentry_scope::clear();-- clear_result-}diff --git a/crates/openhuman-core/src/desktop/app_state/ops/staleness.rs b/crates/openhuman-core/src/desktop/app_state/ops/staleness.rsdeleted file mode 100644index 239fa8c2b0..0000000000--- a/crates/openhuman-core/src/desktop/app_state/ops/staleness.rs+++ /dev/null@@ -1,94 +0,0 @@-//! How stale the `current_user` the snapshot is serving has become.-//!-//! Kept together because the three pieces are one contract: the stamp is-//! written on every successful `auth_get_me`, cleared when the identity goes-//! away, and read back keyed on the same `(api_base, token)` both caches use-//! — so one identity's freshness is never reported as another's (#5930).--use super::current_user::CURRENT_USER_FAILURE;-use once_cell::sync::Lazy;-use parking_lot::Mutex;-use std::time::Instant;--/// When the backend last returned an actual user for `auth_get_me` in this-// process — i.e. when the data the snapshot displays was last replaced.-//-// Deliberately not "when the backend was last healthy": a 200 carrying no user-// leaves the caller on `stored_user`, so counting it as a success would report-// a ~0s age for data that never changed.-///-/// Neither existing cache can answer "how old is the user data we are showing":-/// [`CURRENT_USER_FAILURE`] only knows about failures, and-/// [`CURRENT_USER_CACHE`] is set to `None` whenever the backend returns an-/// empty user, which erases the timestamp on a path that is not an outage.-/// `None` here means "no success yet this process" — the snapshot then reports-/// staleness with an unknown age rather than inventing one (#5930).-///-/// Keyed on `(api_base, token)` like both caches. An unkeyed timestamp would-/// outlive the identity that earned it: the ordinary-/// `credentials::clear_session` logout does not run the deferred-rejection-/// cleanup, so a logout and re-login in the same process — or simply a second-/// identity failing after a first succeeded — would report the previous-/// session's age as this one's.-pub(super) static LAST_CURRENT_USER_SUCCESS: Lazy<Mutex<Option<CurrentUserSuccess>>> =- Lazy::new(|| Mutex::new(None));--/// The last successful `auth_get_me`, with the identity it belongs to.-#[derive(Debug, Clone)]-pub(super) struct CurrentUserSuccess {- pub(super) api_base: String,- pub(super) token: String,- pub(super) at: Instant,-}--/// Stamp a refreshed user, so the snapshot can report how old the data it is-/// serving has become. Callers must not invoke this for an answer that carried-/// no user — see [`LAST_CURRENT_USER_SUCCESS`].-pub(super) fn note_current_user_success(api_base: &str, token: &str) {- note_current_user_success_locked(&mut LAST_CURRENT_USER_SUCCESS.lock(), api_base, token);-}--/// The stamp itself, taking the guard rather than the lock, so a caller that-/// must decide *under* the lock can do so without re-entering it.-pub(super) fn note_current_user_success_locked(- success: &mut Option<CurrentUserSuccess>,- api_base: &str,- token: &str,-) {- *success = Some(CurrentUserSuccess {- api_base: api_base.to_string(),- token: token.to_string(),- at: Instant::now(),- });-}--/// Forget the success stamp on sign-out, so the next account does not inherit-/// this one's freshness.-pub(super) fn clear_current_user_success() {- *LAST_CURRENT_USER_SUCCESS.lock() = None;-}--/// Whether the snapshot is being served from data the backend could not-/// refresh, and how long since it last did.-///-/// Keyed like both caches: a recorded failure only makes *this* `(api_base,-/// token)` stale. Without the key check, switching environment or signing in as-/// someone else would inherit the previous identity's outage and report the-/// fresh data it is about to fetch as stale.-///-/// The age is `None` when *this identity's* backend has not answered at all in-/// this process — the stored snapshot then came off disk, and its true age is-/// not knowable from here. A success recorded against a different `(api_base,-/// token)` is somebody else's freshness and is not reported as this one's.-pub(super) fn current_user_staleness(api_base: &str, token: &str) -> (bool, Option<u64>) {- let stale = CURRENT_USER_FAILURE- .lock()- .as_ref()- .is_some_and(|entry| entry.api_base == api_base && entry.token == token);- let age = LAST_CURRENT_USER_SUCCESS- .lock()- .as_ref()- .filter(|entry| entry.api_base == api_base && entry.token == token)- .map(|entry| entry.at.elapsed().as_secs());- (stale, age)-}diff --git a/crates/openhuman-core/src/desktop/app_state/ops/types.rs b/crates/openhuman-core/src/desktop/app_state/ops/types.rsindex 34ecab21ed..35cb30d0a0 100644--- a/crates/openhuman-core/src/desktop/app_state/ops/types.rs+++ b/crates/openhuman-core/src/desktop/app_state/ops/types.rs@@ -63,21 +63,6 @@ pub struct AppStateSnapshot {/// healed; the frontend raises a one-shot "settings were reset" notice/// (#5167). Serialized as `configRecovered`.pub config_recovered: bool,- /// `true` when `current_user` came from the stored snapshot because the- /// backend could not be refreshed — the plan tier, credit balance and- /// feature flags in it may be out of date (#5930).- ///- /// The frontend can warn on this; the core deliberately does not decide- /// what "significantly out of date" means, because that threshold belongs- /// to whatever surface is presenting the number.- pub current_user_stale: bool,- /// Seconds since the backend last answered `auth_get_me` in this process.- ///- /// Absent when it never has — the stored snapshot then came off disk and- /// its real age is not knowable here, which is a different statement from- /// "zero seconds old" and is why this is an `Option`.- #[serde(skip_serializing_if = "Option::is_none")]- pub current_user_stale_seconds: Option<u64>,}#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/crates/openhuman-core/src/desktop/app_state/ops_current_user_backoff_tests.rs b/crates/openhuman-core/src/desktop/app_state/ops_current_user_backoff_tests.rsdeleted file mode 100644index 9e57c5bb07..0000000000--- a/crates/openhuman-core/src/desktop/app_state/ops_current_user_backoff_tests.rs+++ /dev/null@@ -1,493 +0,0 @@-//! The current-user failure backoff, its replay, and the staleness it reports.-//!-//! Split out of `ops_tests.rs` for the layout gate. Kept as one file because-//! the three subjects are one mechanism: a failure is recorded, replayed while-//! its window is open (#5930), and surfaced as snapshot staleness — and the-//! helpers that seed an outage are shared across all three.--use super::*;-use once_cell::sync::Lazy as TestLazy;--// ── Current-user failure backoff (#5624) ────────────────────────────────────-//-// While the backend is unreachable, every `app_state_snapshot` poll used to-// re-attempt `auth_get_me` and re-pay the full `auth_fetch_timeout`, because a-// failure was never recorded anywhere: `fetch_current_user_cached` cached only-// successes, and on a timeout its future was dropped before it could cache-// anything at all. 51 timeouts in one session is what that costs at a 5s poll-// cadence. These cover the record, the window, and the fact that the fetch-// actually consults it.--/// Serializes the tests that seed `CURRENT_USER_FAILURE`.-///-/// Async-aware rather than the `parking_lot` guard the positive-cache tests-/// use, because one of these tests has to hold it across an `.await` — the-/// whole point of that test is that `fetch_current_user_cached` consults the-/// record. Kept distinct from `APP_STATE_CACHE_TEST_LOCK` because the two guard-/// different globals and nothing here writes the positive cache.-///-/// `pub(super)` because `ops_tests.rs` needs it too: a successful fetch calls-/// `clear_current_user_failure`, which wipes this global, so a test that lets a-/// real fetch complete has to serialise against the tests seeding outages here.-pub(super) static CURRENT_USER_FAILURE_TEST_LOCK: TestLazy<tokio::sync::Mutex<()>> =- TestLazy::new(|| tokio::sync::Mutex::new(()));--/// Drops the seeded outage on the way out, so one test cannot leak into the next.-pub(super) struct CurrentUserFailureResetGuard;--impl Drop for CurrentUserFailureResetGuard {- fn drop(&mut self) {- clear_current_user_failure();- }-}--/// Overwrite the failure record with one that failed `age` ago, so a test can-/// sit either side of a backoff window without sleeping.-pub(super) fn seed_current_user_failure(- api_base: &str,- token: &str,- consecutive: u32,- age: Duration,- error: CurrentUserFetchError,-) {- *CURRENT_USER_FAILURE.lock() = Some(CurrentUserFailure {- api_base: api_base.to_string(),- token: token.to_string(),- failed_at: Instant::now()- .checked_sub(age)- .expect("test ages are far smaller than process uptime"),- consecutive,- error,- });-}--#[test]-fn current_user_backoff_doubles_and_saturates_at_the_cap() {- let base = current_user_backoff_base();- assert_eq!(current_user_backoff(1), base);- assert_eq!(current_user_backoff(2), base * 2);- assert_eq!(current_user_backoff(3), base * 4);- assert_eq!(current_user_backoff(u32::MAX), CURRENT_USER_BACKOFF_MAX);- // 0 is not a state the recorder can produce, but the function must not- // answer it with a zero-length window.- assert_eq!(current_user_backoff(0), base);-- let mut previous = Duration::ZERO;- for consecutive in 1..=12 {- let window = current_user_backoff(consecutive);- assert!(- window >= previous,- "backoff must never narrow as failures accumulate: {consecutive} gave {window:?} after {previous:?}"- );- assert!(- window <= CURRENT_USER_BACKOFF_MAX,- "backoff must stay under the cap: {consecutive} gave {window:?}"- );- previous = window;- }-}--#[test]-fn the_first_backoff_step_outlasts_both_the_fetch_timeout_and_the_poll() {- // This is the property that actually stops the treadmill, and the one a- // future constant change could silently break. A first step shorter than- // the fetch timeout means the next poll finds the window already closed and- // pays the full 5s again — which is the bug, not the fix. It must also- // outlast the positive-cache TTL, because that TTL is what governs how soon- // a poll asks for a live fetch at all.- assert!(- current_user_backoff(1) > auth_fetch_timeout(),- "first backoff step {:?} must exceed the fetch timeout {:?}",- current_user_backoff(1),- auth_fetch_timeout()- );- assert!(- current_user_backoff(1) > CURRENT_USER_REFRESH_TTL,- "first backoff step {:?} must exceed the current-user cache TTL {:?}",- current_user_backoff(1),- CURRENT_USER_REFRESH_TTL- );-}--#[test]-fn a_recorded_failure_suppresses_a_retry_inside_its_window() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserFailureResetGuard;-- record_current_user_failure(- "https://api.example.test",- "token-a",- CurrentUserFetchError::FetchFailed("request timed out after 5s".to_string()),- );-- let (error, consecutive, remaining) =- suppressed_current_user_failure("https://api.example.test", "token-a")- .expect("a just-recorded failure must suppress the next attempt");- assert_eq!(consecutive, 1);- assert_eq!(error.message(), "request timed out after 5s");- assert!(remaining <= current_user_backoff_base() && !remaining.is_zero());-}--#[test]-fn a_recorded_failure_stops_suppressing_once_its_window_closes() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserFailureResetGuard;-- seed_current_user_failure(- "https://api.example.test",- "token-a",- 1,- current_user_backoff_base() + Duration::from_millis(1),- CurrentUserFetchError::FetchFailed("boom".to_string()),- );-- assert!(- suppressed_current_user_failure("https://api.example.test", "token-a").is_none(),- "a failure older than its window must let the next attempt through"- );-}--#[test]-fn consecutive_failures_widen_the_window() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserFailureResetGuard;-- for _ in 0..3 {- record_current_user_failure(- "https://api.example.test",- "token-a",- CurrentUserFetchError::FetchFailed("boom".to_string()),- );- }-- let (_, consecutive, _) =- suppressed_current_user_failure("https://api.example.test", "token-a")- .expect("still inside the widened window");- assert_eq!(consecutive, 3);-- // Three failures in, an attempt that would have been let through at the- // first window is still suppressed.- seed_current_user_failure(- "https://api.example.test",- "token-a",- 3,- current_user_backoff_base() + Duration::from_millis(1),- CurrentUserFetchError::FetchFailed("boom".to_string()),- );- assert!(- suppressed_current_user_failure("https://api.example.test", "token-a").is_some(),- "the third failure's window must outlast the first failure's"- );-}--#[test]-fn a_rejected_credential_is_never_recorded() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserFailureResetGuard;-- record_current_user_failure(- "https://api.example.test",- "token-a",- CurrentUserFetchError::Rejected("401 Unauthorized".to_string()),- );-- // Replaying a rejection from a cache would either delay the deferred-session- // cleanup the snapshot caller drives off that variant, or hand it a- // different variant than the backend produced.- assert!(- suppressed_current_user_failure("https://api.example.test", "token-a").is_none(),- "an auth rejection must not be backed off"- );-}--#[test]-fn a_different_token_or_backend_bypasses_the_record() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserFailureResetGuard;-- record_current_user_failure(- "https://api.example.test",- "token-a",- CurrentUserFetchError::FetchFailed("boom".to_string()),- );-- assert!(- suppressed_current_user_failure("https://api.example.test", "token-b").is_none(),- "signing in as someone else must not inherit the previous session's outage"- );- assert!(- suppressed_current_user_failure("https://other.example.test", "token-a").is_none(),- "switching environment must not inherit the previous backend's outage"- );- // …and the run it was recorded against is untouched by those probes.- assert!(suppressed_current_user_failure("https://api.example.test", "token-a").is_some());-}--#[test]-fn clearing_the_record_lets_the_next_attempt_through() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserFailureResetGuard;-- record_current_user_failure(- "https://api.example.test",- "token-a",- CurrentUserFetchError::FetchFailed("boom".to_string()),- );- assert!(suppressed_current_user_failure("https://api.example.test", "token-a").is_some());-- // What sign-out and every success both call. Missing either is the failure- // mode that matters: a record outliving its cause strands the app on the- // stored snapshot after the backend is back.- clear_current_user_failure();-- assert!(- suppressed_current_user_failure("https://api.example.test", "token-a").is_none(),- "a cleared record must not keep suppressing"- );-}--#[tokio::test]-async fn fetch_current_user_cached_replays_a_recorded_failure_without_calling_the_backend() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;- let _reset = CurrentUserFailureResetGuard;-- let mut config = Config::default();- // A closed loopback port. Nothing here should reach it — the point of the- // test is that the recorded failure short-circuits first — but if the probe- // is removed the call fails locally with a connection error instead of- // reaching out to the real backend.- config.api_url = Some("http://127.0.0.1:9/".to_string());- let api_base = current_user_api_base(&config);- assert!(- api_base.starts_with("http://127.0.0.1:9"),- "precondition: the override must survive backend-url resolution, got {api_base}; \- otherwise this test would talk to a real backend"- );-- let token = "token-a";- seed_current_user_failure(- &api_base,- token,- 1,- Duration::from_millis(1),- CurrentUserFetchError::FetchFailed("seeded outage marker".to_string()),- );-- let error = fetch_current_user_cached(&config, token, true, current_user_generation())- .await- .expect_err("a recorded failure inside its window must be replayed");-- assert_eq!(- error.message(),- "seeded outage marker",- "the fetch must replay the recorded failure rather than issue a request"- );-}--// ── Replay is distinguishable from a live failure (#5930) ───────────────────-//-// #5930 was filed on four `WRN … current user refresh failed … request timed-// out after 5s` lines seconds apart, read as the app hammering a failing-// endpoint. They were replays of one recorded failure — microseconds each, no-// request made — because the suppression path returned the recorded error-// verbatim and the snapshot caller had no way to tell the two apart. These pin-// the distinction so the same false alarm cannot be filed twice.--#[tokio::test]-async fn a_replayed_failure_is_tagged_suppressed_and_keeps_the_original_message() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;- let _reset = CurrentUserFailureResetGuard;-- let mut config = Config::default();- config.api_url = Some("http://127.0.0.1:9/".to_string());- let api_base = current_user_api_base(&config);- let token = "token-a";-- seed_current_user_failure(- &api_base,- token,- 3,- Duration::from_millis(1),- CurrentUserFetchError::FetchFailed("request timed out after 5s".to_string()),- );-- let error = fetch_current_user_cached(&config, token, true, current_user_generation())- .await- .expect_err("a recorded failure inside its window must be replayed");-- match &error {- CurrentUserFetchError::Suppressed {- inner,- consecutive,- retry_in,- } => {- assert_eq!(*consecutive, 3, "the run length must survive the replay");- assert!(- *retry_in > Duration::ZERO && *retry_in <= current_user_backoff(3),- "remaining window {retry_in:?} must be inside the step for 3 failures"- );- assert!(- matches!(**inner, CurrentUserFetchError::FetchFailed(_)),- "the original variant must be preserved, not flattened"- );- }- other => panic!("expected a Suppressed replay, got {other:?}"),- }-- assert_eq!(- error.message(),- "request timed out after 5s",- "callers reading only the message must be unaffected by the wrapper"- );-}--#[test]-fn a_suppressed_replay_is_never_recorded_as_a_fresh_failure() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserFailureResetGuard;-- let suppressed = CurrentUserFetchError::Suppressed {- inner: Box::new(CurrentUserFetchError::FetchFailed("boom".to_string())),- consecutive: 2,- retry_in: Duration::from_secs(7),- };- assert!(- !suppressed.is_availability_failure(),- "a replay is not a new observation; recording it would widen the window \- on evidence the backend never supplied"- );-- record_current_user_failure("https://api.example.test", "token-a", suppressed);- assert!(- suppressed_current_user_failure("https://api.example.test", "token-a").is_none(),- "recording a replay must be a no-op"- );-}--// ── Stale-snapshot age (#5930) ──────────────────────────────────────────────--/// Drops both the outage and the success stamp on the way out.-pub(super) struct CurrentUserStalenessResetGuard;--impl Drop for CurrentUserStalenessResetGuard {- fn drop(&mut self) {- clear_current_user_failure();- clear_current_user_success();- }-}--#[test]-fn staleness_is_reported_only_for_the_identity_that_actually_failed() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserStalenessResetGuard;- clear_current_user_failure();- clear_current_user_success();-- let api_base = "https://api.example.test";-- let (stale, age) = current_user_staleness(api_base, "token-a");- assert!(!stale, "no recorded failure means nothing is stale");- assert_eq!(- age, None,- "no success this process means the age is unknown"- );-- record_current_user_failure(- api_base,- "token-a",- CurrentUserFetchError::FetchFailed("boom".to_string()),- );-- assert!(- current_user_staleness(api_base, "token-a").0,- "the identity that failed is serving data it could not refresh"- );- assert!(- !current_user_staleness(api_base, "token-b").0,- "a different token must not inherit this identity's outage"- );- assert!(- !current_user_staleness("https://other.example.test", "token-a").0,- "a different backend must not inherit this environment's outage"- );-}--#[test]-fn a_success_stamps_the_age_and_clears_the_stale_flag() {- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserStalenessResetGuard;- clear_current_user_failure();- clear_current_user_success();-- let api_base = "https://api.example.test";- record_current_user_failure(- api_base,- "token-a",- CurrentUserFetchError::FetchFailed("boom".to_string()),- );- assert!(current_user_staleness(api_base, "token-a").0);-- // What `fetch_current_user_cached` does on every successful answer.- clear_current_user_failure();- note_current_user_success(api_base, "token-a");-- let (stale, age) = current_user_staleness(api_base, "token-a");- assert!(!stale, "a success must clear the stale flag");- assert!(- age.is_some(),- "once the backend has answered, the age of the data is knowable"- );-- // Sign-out must not leave the next account inheriting this one's freshness.- clear_current_user_success();- assert_eq!(current_user_staleness(api_base, "token-a").1, None);-}--#[test]-fn one_identitys_success_is_never_reported_as_anothers_age() {- // The stale flag was keyed on `(api_base, token)` from the start but the- // age was read from a bare global, so identity A succeeding and identity B- // then failing reported A's freshness against B's outage. The ordinary- // `credentials::clear_session` logout does not run the deferred-rejection- // cleanup either, so the same leak survived a logout and re-login in one- // process. Keying the stamp closes both.- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserStalenessResetGuard;- clear_current_user_failure();- clear_current_user_success();-- let api_base = "https://api.example.test";- note_current_user_success(api_base, "token-a");-- let (_, age_a) = current_user_staleness(api_base, "token-a");- assert!(- age_a.is_some(),- "the identity that succeeded knows its own age"- );-- let (_, age_b) = current_user_staleness(api_base, "token-b");- assert_eq!(- age_b, None,- "a different token must not inherit another identity's freshness"- );-- let (_, age_other_env) = current_user_staleness("https://other.example.test", "token-a");- assert_eq!(- age_other_env, None,- "a different backend must not inherit another environment's freshness"- );-- // The pairing that actually shipped the bug: B is stale, and must not be- // handed A's age alongside that.- record_current_user_failure(- api_base,- "token-b",- CurrentUserFetchError::FetchFailed("boom".to_string()),- );- let (stale_b, age_b) = current_user_staleness(api_base, "token-b");- assert!(stale_b, "B's outage is B's");- assert_eq!(- age_b, None,- "B has no success of its own, so its age is unknown"- );-}diff --git a/crates/openhuman-core/src/desktop/app_state/ops_signout_cache_tests.rs b/crates/openhuman-core/src/desktop/app_state/ops_signout_cache_tests.rsdeleted file mode 100644index dc336fd4cc..0000000000--- a/crates/openhuman-core/src/desktop/app_state/ops_signout_cache_tests.rs+++ /dev/null@@ -1,527 +0,0 @@-// Sign-out invalidation for the current-user caches (#5758).-//-// `super` is the `tests` module; its `use super::*` re-exports both the ops-// items under test and this suite's shared cache lock.-use super::*;--// The failure-cache test fixtures live in the backoff suite, which owns that-// global. Borrowing its lock rather than declaring a second one is the point:-// two locks over one static is exactly the interference this suite hit.-use super::super::current_user_backoff_tests::{- seed_current_user_failure, CurrentUserFailureResetGuard, CurrentUserStalenessResetGuard,- CURRENT_USER_FAILURE_TEST_LOCK,-};--// ── Sign-out cache invalidation (#5758) ────────────────────────────────────-//-// Both caches are keyed on `(api_base, token)`, so leaving either behind lets a-// re-login with the same JWT replay pre-logout state: the stale `/auth/me`-// snapshot from the positive cache, or the stale error from the negative one.-//-// `forget_current_user_caches` touches BOTH globals, so both cases hold both of-// this suite's cache locks — in this order, consistently, since no other test-// takes more than one.--// Sign-out itself must reach `forget_current_user_caches`, not merely be able-// to. The two direct-call cases below cannot see that wiring: deleting the call-// from `clear_session` leaves every test in this file, and in the credentials-// suite, passing. This one goes through the real entry point.-//-// `clear_session` clears the active-user marker under-// `default_root_openhuman_dir()`, which is derived from the process-global HOME,-// so it takes the shared env lock and pins HOME to its own tempdir -- the same-// precaution `clear_session_on_empty_store_reports_removed_false` documents.-#[tokio::test]-async fn signing_out_forgets_both_current_user_caches() {- let _env_lock = crate::config::TEST_ENV_LOCK- .lock()- .unwrap_or_else(|e| e.into_inner());- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;- let _reset = CurrentUserFailureResetGuard;-- let tmp = tempdir().expect("tempdir");- let previous_home = std::env::var_os("HOME");- unsafe { std::env::set_var("HOME", tmp.path()) };-- let api_base = "https://api.example.test";- let token = "jwt-5758-signout";- *CURRENT_USER_CACHE.lock() = Some(CachedCurrentUser {- api_base: api_base.into(),- token: token.into(),- fetched_at: Instant::now(),- user: json!({ "userId": "user-5758" }),- });- seed_current_user_failure(- api_base,- token,- 1,- Duration::from_millis(0),- CurrentUserFetchError::FetchFailed("backend unreachable".to_string()),- );- assert!(- CURRENT_USER_CACHE.lock().is_some()- && suppressed_current_user_failure(api_base, token).is_some(),- "precondition: both caches must be populated"- );-- let config = Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- ..Config::default()- };- crate::security::credentials::ops::clear_session(&config)- .await- .expect("clear_session on an empty store still succeeds");-- match previous_home {- Some(value) => unsafe { std::env::set_var("HOME", value) },- None => unsafe { std::env::remove_var("HOME") },- }-- assert!(- CURRENT_USER_CACHE.lock().is_none(),- "sign-out left the pre-logout /auth/me snapshot behind"- );- assert!(- suppressed_current_user_failure(api_base, token).is_none(),- "sign-out left the pre-logout availability failure behind"- );-}--/// A pending `/auth/me` response that finishes after logout must not recreate-/// the app-session profile that logout removed.-///-/// The call order makes the race deterministic: `generation` represents the-/// pending refresh, `clear_session` wins the session-mutation lock and bumps-/// the generation, and only then does the stale persistence attempt resume.-#[tokio::test]-async fn pending_revalidation_completing_after_logout_does_not_restore_the_session() {- let _env_lock = crate::config::TEST_ENV_LOCK- .lock()- .unwrap_or_else(|e| e.into_inner());- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;- let _reset = CurrentUserFailureResetGuard;-- let tmp = tempdir().expect("tempdir");- let previous_home = std::env::var_os("HOME");- unsafe { std::env::set_var("HOME", tmp.path()) };-- let config = Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- ..Config::default()- };- let auth = AuthService::from_config(&config);- auth.store_provider_token(- APP_SESSION_PROVIDER,- DEFAULT_AUTH_PROFILE_NAME,- "jwt-pending-before-logout",- HashMap::new(),- true,- )- .expect("seed pending app-session profile");-- let generation = current_user_generation();- crate::security::credentials::ops::clear_session(&config)- .await- .expect("logout succeeds");-- let error = persist_revalidated_session_user(- &config,- "jwt-pending-before-logout",- BTreeMap::new(),- json!({ "userId": "user-before-logout" }),- generation,- )- .await- .expect_err("stale pending persistence must stand down after logout");-- match previous_home {- Some(value) => unsafe { std::env::set_var("HOME", value) },- None => unsafe { std::env::remove_var("HOME") },- }-- assert!(- error.contains("became stale after sign-out"),- "unexpected stale-persistence error: {error}"- );- assert!(- auth.get_profile(APP_SESSION_PROVIDER, None)- .expect("read app-session profile")- .is_none(),- "the stale pending response recreated the app-session profile after logout"- );-}--#[test]-fn forget_current_user_caches_clears_the_positive_snapshot() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.blocking_lock();- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserFailureResetGuard;-- *CURRENT_USER_CACHE.lock() = Some(CachedCurrentUser {- api_base: "https://api.example.test".into(),- token: "jwt-5758".into(),- fetched_at: Instant::now(),- user: json!({ "userId": "user-5758" }),- });- assert!(- CURRENT_USER_CACHE.lock().is_some(),- "precondition: the snapshot must be cached for this test to mean anything"- );-- forget_current_user_caches();-- assert!(- CURRENT_USER_CACHE.lock().is_none(),- "the pre-logout /auth/me snapshot survived sign-out"- );-}--#[test]-fn forget_current_user_caches_clears_the_freshness_stamp() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.blocking_lock();- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserStalenessResetGuard;-- let api_base = "https://api.example.test";- let token = "jwt-5758c";- note_current_user_success(api_base, token);- assert!(- current_user_staleness(api_base, token).1.is_some(),- "precondition: the stamp must be set for this test to mean anything"- );-- forget_current_user_caches();-- assert_eq!(- current_user_staleness(api_base, token).1,- None,- "the pre-logout freshness stamp survived sign-out, so the next account \- would be told this one's data age"- );-}--#[test]-fn forget_current_user_caches_clears_the_negative_failure() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.blocking_lock();- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.blocking_lock();- let _reset = CurrentUserFailureResetGuard;-- let api_base = "https://api.example.test";- let token = "jwt-5758b";- seed_current_user_failure(- api_base,- token,- 1,- Duration::from_millis(0),- CurrentUserFetchError::FetchFailed("backend unreachable".to_string()),- );- assert!(- suppressed_current_user_failure(api_base, token).is_some(),- "precondition: the failure must be suppressing for this test to mean anything"- );-- forget_current_user_caches();-- assert!(- suppressed_current_user_failure(api_base, token).is_none(),- "the pre-logout availability failure survived sign-out, so a re-login with the same JWT would replay it"- );-}--// ── A refresh that races sign-out must not republish (#5758, review) ────────-//-// Clearing the two statics is not sufficient on its own. `fetch_current_user_cached`-// awaits the network between reading the caches and writing them, so a refresh-// already in flight when sign-out lands would write the pre-logout answer back-// afterwards — restoring exactly what sign-out just dropped.-//-// The synchronisation here is structural, not timed: the fake backend accepts-// the connection and then *waits*, so the request is provably in flight when-// sign-out runs, and the response is not released until after it.--/// Minimal `/auth/me` backend that hands control back to the test mid-request.-///-/// `Connection: close` rather than a Content-Length, so the body length is not-/// a thing this test can get subtly wrong.-async fn spawn_racing_backend(- body: &'static str,- status_line: &'static str,-) -> (- u16,- tokio::sync::oneshot::Receiver<()>,- tokio::sync::oneshot::Sender<()>,- tokio::task::JoinHandle<()>,-) {- use tokio::io::{AsyncReadExt, AsyncWriteExt};-- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind loopback");- let port = listener.local_addr().expect("local addr").port();-- let (in_flight_tx, in_flight_rx) = tokio::sync::oneshot::channel();- let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();-- let handle = tokio::spawn(async move {- let (mut socket, _) = listener.accept().await.expect("accept");-- // Drain enough of the request that the client has certainly sent it.- let mut buf = [0u8; 1024];- let _ = socket.read(&mut buf).await;-- // The request is in flight. Sign-out can happen now.- let _ = in_flight_tx.send(());- let _ = release_rx.await;-- let response = format!("{status_line}\r\nConnection: close\r\n\r\n{body}");- let _ = socket.write_all(response.as_bytes()).await;- let _ = socket.shutdown().await;- });-- (port, in_flight_rx, release_tx, handle)-}--#[tokio::test]-async fn a_successful_refresh_that_races_sign_out_does_not_repopulate_the_snapshot() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;- let _reset = CurrentUserFailureResetGuard;-- forget_current_user_caches();-- let (port, in_flight, release, server) = spawn_racing_backend(- r#"{"data":{"userId":"user-before-logout"}}"#,- "HTTP/1.1 200 OK",- )- .await;-- let mut config = Config::default();- config.api_url = Some(format!("http://127.0.0.1:{port}/"));- // Read where the caller reads it: alongside the token, before the refresh.- let generation = current_user_generation();- // Resolved before `config` moves into the task; the freshness stamp is keyed- // on it, so the assertion at the end needs the same string the fetch used.- let api_base_probe = current_user_api_base(&config);-- let fetch = tokio::spawn(async move {- fetch_current_user_cached(&config, "jwt-race", true, generation).await- });-- in_flight.await.expect("backend saw the request");- // The user signs out while the refresh is on the wire.- forget_current_user_caches();- let _ = release.send(());-- let result = fetch.await.expect("join fetch");- server.await.expect("join backend");-- assert!(- result.is_ok(),- "the caller that asked before sign-out still gets its answer"- );- assert!(- CURRENT_USER_CACHE.lock().is_none(),- "a refresh that finished after sign-out republished the pre-logout snapshot, \- which is the state sign-out exists to drop"- );- assert_eq!(- current_user_staleness(&api_base_probe, "jwt-race").1,- None,- "the raced refresh stamped the signed-out identity as freshly loaded"- );-}--#[tokio::test]-async fn a_failed_refresh_that_races_sign_out_does_not_record_a_failure() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;- let _reset = CurrentUserFailureResetGuard;-- forget_current_user_caches();-- // 500 is in AUTH_ME_REVALIDATION_TRANSIENT_STATUSES, so this takes the- // record-a-failure path rather than the rejection path.- let (port, in_flight, release, server) =- spawn_racing_backend("backend is down", "HTTP/1.1 500 Internal Server Error").await;-- let mut config = Config::default();- config.api_url = Some(format!("http://127.0.0.1:{port}/"));- let api_base = current_user_api_base(&config);- // Read where the caller reads it: alongside the token, before the refresh.- let generation = current_user_generation();-- let fetch = tokio::spawn(async move {- fetch_current_user_cached(&config, "jwt-race-err", true, generation).await- });-- in_flight.await.expect("backend saw the request");- forget_current_user_caches();- let _ = release.send(());-- let result = fetch.await.expect("join fetch");- server.await.expect("join backend");-- assert!(result.is_err(), "precondition: the fetch must have failed");- assert!(- suppressed_current_user_failure(&api_base, "jwt-race-err").is_none(),- "a failure recorded after sign-out would suppress the first poll of the \- next session, replaying an outage the new session never saw"- );-}--// The two above prove the guard across a real await. These two close the-// narrower window inside it: the moment between reading the generation and-// taking the lock. There is nothing to pause here — the "pause" IS the call-// order, which is why these are deterministic rather than timed.--#[tokio::test]-async fn a_sign_out_landing_after_the_generation_check_still_wins_the_snapshot() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- // Both globals are touched here, so both guards are needed. The failure- // lock is async, which is why these three were sync-only and unguarded.- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;- let _reset = CurrentUserFailureResetGuard;-- forget_current_user_caches();- // The refresh reads the generation, and is descheduled right here.- let generation = current_user_generation();- // Sign-out lands in that gap: it bumps, then clears both records.- forget_current_user_caches();- // The refresh resumes and tries to publish.- let published = publish_current_user_unless_stale(- generation,- "http://127.0.0.1:1/",- "jwt-before-logout",- Some(json!({ "userId": "user-before-logout" })),- );-- assert!(!published, "the publish must report that sign-out won");- assert!(- CURRENT_USER_CACHE.lock().is_none(),- "checking the generation before taking the cache lock leaves a window in \- which sign-out lands and the pre-logout snapshot is written anyway"- );-}--#[tokio::test]-async fn a_sign_out_landing_after_the_generation_check_still_wins_the_failure_record() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- // Both globals are touched here, so both guards are needed. The failure- // lock is async, which is why these three were sync-only and unguarded.- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;- let _reset = CurrentUserFailureResetGuard;-- forget_current_user_caches();- let generation = current_user_generation();- forget_current_user_caches();- let recorded = record_current_user_failure_unless_stale(- generation,- "http://127.0.0.1:1/",- "jwt-before-logout",- CurrentUserFetchError::FetchFailed("backend is down".to_string()),- );-- assert!(!recorded, "the record must report that sign-out won");- assert!(- CURRENT_USER_FAILURE.lock().is_none(),- "an outage recorded into that same window outlives the session it \- belonged to, and suppresses the next session's first poll"- );-}--#[tokio::test]-async fn publishing_under_the_current_generation_still_clears_a_recorded_outage() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- // Both globals are touched here, so both guards are needed. The failure- // lock is async, which is why these three were sync-only and unguarded.- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;- let _reset = CurrentUserFailureResetGuard;-- forget_current_user_caches();- let generation = current_user_generation();- record_current_user_failure(- "http://127.0.0.1:1/",- "jwt-live",- CurrentUserFetchError::FetchFailed("backend was down".to_string()),- );-- let published = publish_current_user_unless_stale(- generation,- "http://127.0.0.1:1/",- "jwt-live",- Some(json!({ "userId": "user-live" })),- );-- assert!(- published,- "no sign-out happened; the answer must be published"- );- assert!(- CURRENT_USER_CACHE.lock().is_some(),- "the fresh snapshot must reach the positive cache"- );- assert!(- CURRENT_USER_FAILURE.lock().is_none(),- "a success must retire the outage, or the backoff outlives its cause"- );-}--/// Sign-out between the profile load and the refresh must still win.-///-/// This is the window the generation moved to cover. `snapshot` reads the token-/// out of the auth profile — a load that busy-waits up to ~35s on a contended-/// lock — and only then starts the refresh. Reading the generation inside the-/// refresh meant a sign-out landing in that gap was already counted, so the-/// refresh compared the new generation against itself, passed, and published an-/// answer it had fetched with the token from before the sign-out.-///-/// Deterministic without a sleep: the sign-out is expressed by call order, and-/// the generation handed to the refresh is the one read before it.-#[tokio::test]-async fn a_sign_out_between_the_token_load_and_the_refresh_still_wins() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- let _failure_lock = CURRENT_USER_FAILURE_TEST_LOCK.lock().await;- let _reset = CurrentUserFailureResetGuard;-- forget_current_user_caches();-- // The snapshot reads the token, and the generation alongside it.- let generation = current_user_generation();-- // The user signs out while the auth profile lock is still being waited on.- forget_current_user_caches();-- let (port, in_flight, release, server) = spawn_racing_backend(- r#"{"data":{"userId":"user-before-logout"}}"#,- "HTTP/1.1 200 OK",- )- .await;-- let mut config = Config::default();- config.api_url = Some(format!("http://127.0.0.1:{port}/"));-- // Only now does the refresh start, still carrying the pre-sign-out token.- let fetch = tokio::spawn(async move {- fetch_current_user_cached(&config, "jwt-before-logout", true, generation).await- });-- in_flight.await.expect("backend saw the request");- let _ = release.send(());-- let result = fetch.await.expect("join fetch");- server.await.expect("join backend");-- assert!(result.is_ok(), "the caller still gets its answer");- assert!(- CURRENT_USER_CACHE.lock().is_none(),- "a refresh holding the pre-sign-out token republished the identity that \- sign-out exists to drop, because it read the generation after the \- sign-out rather than alongside the token"- );-}diff --git a/crates/openhuman-core/src/desktop/app_state/ops_snapshot_latency_tests.rs b/crates/openhuman-core/src/desktop/app_state/ops_snapshot_latency_tests.rsdeleted file mode 100644index 2a7eea3391..0000000000--- a/crates/openhuman-core/src/desktop/app_state/ops_snapshot_latency_tests.rs+++ /dev/null@@ -1,331 +0,0 @@-//! What one `app_state_snapshot` poll costs, and what the core can stop paying.-//!-//! Split out of `ops_tests.rs` for the layout gate. Kept as one file because-//! both subjects are one measurement: #6180 reported 732 snapshot calls in-//! ~3.5h with no call under 500ms and spikes to 1910ms, and the two tests here-//! pin the two halves of that number the core controls.--use super::tests::APP_STATE_CACHE_TEST_LOCK;-use super::*;-use serde_json::json;-// Measured against the production backend over a ~250ms RTT link, one-// `GET /auth/me` costs ~380-540ms on a warm connection and ~780-1420ms on a-// cold one — and a 404 for a route that does not exist on the same host costs-// the same as `/auth/me`, so the floor is the round trip itself, not the-// endpoint. Neither number is something the core can shrink. What it can do is-// stop paying them: not block the poll on the round trip, and not open a new-// connection each time it makes one. One test each.--/// Serve the identity we already have; re-confirm it behind the poll.-///-/// `fetch_current_user_cached` used to block on `GET /auth/me` the moment its-/// entry aged past the TTL, which — with the frontend scheduling the next poll-/// from the previous *response* — was every poll. That put a floor of one WAN-/// round trip under every `app_state_snapshot`. The stub here answers slowly on-/// purpose: an expired entry must come back immediately anyway, and the refresh-/// must still land.-#[tokio::test]-async fn an_expired_current_user_is_served_while_it_refreshes() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- // A successful refresh calls `clear_current_user_failure`, which wipes a- // global the backoff tests seed.- let _failure_lock = super::current_user_backoff_tests::CURRENT_USER_FAILURE_TEST_LOCK- .lock()- .await;- struct CacheResetGuard;- impl Drop for CacheResetGuard {- fn drop(&mut self) {- *CURRENT_USER_CACHE.lock() = None;- }- }- let _reset = CacheResetGuard;-- const BACKEND_DELAY: Duration = Duration::from_millis(2000);-- let app = axum::Router::new().route(- "/auth/me",- axum::routing::get(|| async move {- tokio::time::sleep(BACKEND_DELAY).await;- axum::Json(json!({ "success": true, "data": { "firstName": "from-backend" } }))- }),- );- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move {- let _ = axum::serve(listener, app).await;- });-- let config = Config {- api_url: Some(format!("http://{addr}")),- ..Config::default()- };- // The failure record is keyed on `(api_base, token)` and this base carries a- // fresh ephemeral port, so no seeded outage can match it and none is seeded- // here — nothing to clean up, and no cross-test write.- *CURRENT_USER_CACHE.lock() = Some(CachedCurrentUser {- api_base: current_user_api_base(&config),- token: "tok".into(),- fetched_at: Instant::now() - (CURRENT_USER_REFRESH_TTL + Duration::from_secs(1)),- user: json!({ "firstName": "from-cache" }),- });-- let started = Instant::now();- let served = fetch_current_user_cached(&config, "tok", true, current_user_generation())- .await- .expect("an expired entry is still an answer");- let waited = started.elapsed();-- assert_eq!(- served.as_ref().and_then(|u| u.get("firstName")),- Some(&json!("from-cache")),- "the expired entry must be what the poll is handed"- );- assert!(- waited < Duration::from_millis(400),- "the poll waited {waited:?} on the backend; serving the entry it already \- had is the whole point — this is #6180's per-poll round trip"- );-- // ...and the refresh must actually happen, or "fast" is just "never- // refreshes". Wait past the stub's delay for the cache to flip.- let refreshed = tokio::time::timeout(BACKEND_DELAY * 3, async {- loop {- let landed = CURRENT_USER_CACHE- .lock()- .as_ref()- .and_then(|entry| entry.user.get("firstName").cloned());- if landed == Some(json!("from-backend")) {- return;- }- tokio::time::sleep(Duration::from_millis(25)).await;- }- })- .await;- assert!(- refreshed.is_ok(),- "the background refresh never replaced the stale entry; \- serving stale forever is not stale-while-revalidate"- );-}--/// Successive `/auth/me` fetches must share one TCP connection.-///-/// `fetch_current_user` built a fresh `reqwest::Client` per call, and a-/// `Client` owns its connection pool — so every fetch opened a new connection-/// and paid a TCP handshake plus a TLS handshake before the request could go-/// out. Over a WAN link that is two extra round trips on top of the one the-/// request costs, and it is the gap between #6180's ~500ms floor and its-/// ~1900ms spikes.-///-/// Asserted on the wire, because `reqwest::Client` exposes no pool statistics:-/// the server sees a distinct ephemeral source port for every new connection,-/// so a reused connection is exactly one distinct peer address across N-/// requests.-#[tokio::test]-async fn current_user_fetches_reuse_one_connection() {- use axum::extract::ConnectInfo;- use std::collections::BTreeSet;- use std::net::SocketAddr;- use std::sync::{Arc, Mutex as StdMutex};-- type Peers = Arc<StdMutex<BTreeSet<SocketAddr>>>;- let peers: Peers = Arc::new(StdMutex::new(BTreeSet::new()));- let peers_for_route = peers.clone();-- let app = axum::Router::new().route(- "/auth/me",- axum::routing::get(move |ConnectInfo(peer): ConnectInfo<SocketAddr>| {- let peers = peers_for_route.clone();- async move {- peers.lock().unwrap().insert(peer);- axum::Json(json!({ "success": true, "data": { "firstName": "steven" } }))- }- }),- );- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move {- let _ = axum::serve(- listener,- app.into_make_service_with_connect_info::<SocketAddr>(),- )- .await;- });-- let config = Config {- api_url: Some(format!("http://{addr}")),- ..Config::default()- };-- // Sequential, like the poll loop: each call must find the previous call's- // connection idle in the pool and reuse it.- for _ in 0..3 {- fetch_current_user(&config, "tok")- .await- .expect("the stub answers /auth/me");- }-- let distinct = peers.lock().unwrap().len();- assert_eq!(- distinct, 1,- "three sequential /auth/me fetches opened {distinct} connections; each new \- one costs a TCP and a TLS handshake before the request goes out (#6180)"- );-}--/// A detached refresh must not commit an identity the app has already left.-///-/// The background refresh outlives the poll that started it, so a logout and-/// re-login (or an environment switch) can land while it is still in flight.-/// Every write it then makes is process-global. The keyed reads in-/// `fetch_current_user_cached` would only miss on a regressed entry — but-/// `peek_cached_current_user_identity` reads that same slot with **no** key-/// check, to embed the user in the agent's prompts (#926), so a regressed entry-/// is served there as the current user.-#[tokio::test]-async fn a_background_refresh_does_not_overwrite_a_newer_identity() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- let _failure_lock = super::current_user_backoff_tests::CURRENT_USER_FAILURE_TEST_LOCK- .lock()- .await;- struct CacheResetGuard;- impl Drop for CacheResetGuard {- fn drop(&mut self) {- *CURRENT_USER_CACHE.lock() = None;- }- }- let _reset = CacheResetGuard;-- let app = axum::Router::new().route(- "/auth/me",- axum::routing::get(|| async {- axum::Json(json!({ "success": true, "data": { "firstName": "signed-out-user" } }))- }),- );- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move {- let _ = axum::serve(listener, app).await;- });-- let stale_config = Config {- api_url: Some(format!("http://{addr}")),- ..Config::default()- };-- // The identity the app moved to while the refresh below was in flight.- *CURRENT_USER_CACHE.lock() = Some(CachedCurrentUser {- api_base: current_user_api_base(&stale_config),- token: "token-for-the-user-who-just-signed-in".into(),- fetched_at: Instant::now(),- user: json!({ "firstName": "signed-in-user" }),- });-- // The refresh the *previous* identity started, landing late.- refresh_current_user_now(- &stale_config,- "token-for-the-user-who-signed-out",- current_user_generation(),- RefreshOrigin::Background,- )- .await- .expect("the stub answers /auth/me");-- let cached = CURRENT_USER_CACHE- .lock()- .as_ref()- .and_then(|entry| entry.user.get("firstName").cloned());- assert_eq!(- cached,- Some(json!("signed-in-user")),- "a background refresh for the previous identity overwrote the current one; \- `peek_cached_current_user_identity` reads this slot unkeyed (#926)"- );-- // The blocking path is authoritative by construction — its caller is still- // awaiting it — so it must still commit.- refresh_current_user_now(- &stale_config,- "token-for-the-user-who-signed-out",- current_user_generation(),- RefreshOrigin::Blocking,- )- .await- .expect("the stub answers /auth/me");- let cached = CURRENT_USER_CACHE- .lock()- .as_ref()- .and_then(|entry| entry.user.get("firstName").cloned());- assert_eq!(- cached,- Some(json!("signed-out-user")),- "the blocking path must still commit; only detached refreshes are discarded"- );-}--/// The TTL clock must start when the request goes out, not when it lands.-///-/// `CURRENT_USER_REFRESH_TTL` is measured against `fetched_at`, and the poll-/// loop schedules itself from the previous *response*. Stamping `fetched_at` at-/// completion folds the round trip into the next window: a refresh taking `L`-/// leaves the following poll only `TTL - L` from expiry, that poll reads the-/// entry as fresh, and the refresh after it never happens — the cadence halves-/// as a silent side effect of no longer blocking (#6190 review). Stamping at-/// initiation keeps the wall-clock cadence exactly what it was before.-#[tokio::test]-async fn the_refresh_ttl_clock_starts_when_the_request_goes_out() {- let _cache_lock = APP_STATE_CACHE_TEST_LOCK.lock().await;- let _failure_lock = super::current_user_backoff_tests::CURRENT_USER_FAILURE_TEST_LOCK- .lock()- .await;- struct CacheResetGuard;- impl Drop for CacheResetGuard {- fn drop(&mut self) {- *CURRENT_USER_CACHE.lock() = None;- }- }- let _reset = CacheResetGuard;-- // Stands in for the WAN round trip the issue measured at ~380-540ms.- const BACKEND_LATENCY: Duration = Duration::from_millis(600);-- let app = axum::Router::new().route(- "/auth/me",- axum::routing::get(|| async move {- tokio::time::sleep(BACKEND_LATENCY).await;- axum::Json(json!({ "success": true, "data": { "firstName": "steven" } }))- }),- );- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();- let addr = listener.local_addr().unwrap();- tokio::spawn(async move {- let _ = axum::serve(listener, app).await;- });-- let config = Config {- api_url: Some(format!("http://{addr}")),- ..Config::default()- };- refresh_current_user_now(- &config,- "tok",- current_user_generation(),- RefreshOrigin::Blocking,- )- .await- .expect("the stub answers /auth/me");-- let age = CURRENT_USER_CACHE- .lock()- .as_ref()- .expect("the refresh committed an entry")- .fetched_at- .elapsed();-- assert!(- age >= BACKEND_LATENCY,- "the entry is {age:?} old immediately after a {BACKEND_LATENCY:?} fetch, so the clock \- was started on the response: the round trip has been folded into the next TTL window \- and the poll after next will skip its refresh (#6190)"- );-}