Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(core): remove unused app state modules and re-export test helpers

Steven Enamakel32c3a47991f2
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context.rs
index dc9a12174d..0a19e9cd74 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context.rs
@@ -24,3 +24,8 @@ mod tests;
pub use scout_run::{run_context_scout, run_context_scout_with_catalog};
pub use tool::AgentPrepareContextTool;
+
+#[cfg(test)]
+use scout_run::{
+ extract_context_bundle, is_expected_billing_failure, log_scout_failure, scout_failure_signal,
+};
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.rs
deleted file mode 100644
index bd7a4d6031..0000000000
--- a/crates/openhuman-core/src/desktop/app_state/ops_auth_timeout.rs
+++ /dev/null
@@ -1,94 +0,0 @@
-// How long the current-user refresh may take, and how long a failed run of
-// them suppresses the next attempt.
-//
-// Split out of `ops_part_01.rs` 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.
-//
-// `include!`d into `ops.rs`, so everything here shares that module's scope.
-
-/// 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.
-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.
-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.
-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.
-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_generation.rs b/crates/openhuman-core/src/desktop/app_state/ops_current_user_generation.rs
deleted file mode 100644
index f0f02a8dbc..0000000000
--- a/crates/openhuman-core/src/desktop/app_state/ops_current_user_generation.rs
+++ /dev/null
@@ -1,185 +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).
-
-/// 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.
-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.
-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.
-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.
-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.
-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.
-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.
-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_part_01.rs b/crates/openhuman-core/src/desktop/app_state/ops_part_01.rs
deleted file mode 100644
index aca14dd03d..0000000000
--- a/crates/openhuman-core/src/desktop/app_state/ops_part_01.rs
+++ /dev/null
@@ -1,720 +0,0 @@
-use std::collections::{BTreeMap, HashMap};
-use std::fs;
-#[cfg(unix)]
-use std::fs::File;
-use std::io::Write;
-use std::path::{Path, PathBuf};
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
-
-use log::{debug, warn};
-use once_cell::sync::Lazy;
-use parking_lot::Mutex;
-use reqwest::{header::AUTHORIZATION, Client, Method, Url};
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
-use tempfile::NamedTempFile;
-
-use crate::api::config::effective_backend_api_url;
-use crate::api::jwt::bearer_authorization_value;
-use crate::api::rest::user_id_from_profile_payload;
-use crate::config::rpc as config_rpc;
-use crate::config::Config;
-use crate::inference::LocalAiStatus;
-use crate::platform::service::{ServiceState, ServiceStatus};
-use crate::security::credentials::session_support::{
- is_local_session_token, load_app_session_profile, session_state_from_profile,
- session_token_from_profile,
-};
-use crate::security::credentials::{
- AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,
-};
-use crate::rpc::RpcOutcome;
-
-const LOG_PREFIX: &str = "[app_state]";
-const APP_STATE_FILENAME: &str = "app-state.json";
-const CURRENT_USER_REFRESH_TTL: Duration = Duration::from_secs(5);
-// Runtime-status widgets (local AI / autocomplete / service) tolerate ~10s of
-// staleness. A short TTL (was 2s < the ~2.4s build
-// time) meant the cache was stale before it was even written, so the frontend's
-// ~4s `app_state_snapshot` poll never hit the fast path and every poll re-ran
-// the full 4-way fan-out (issue #4249 profiling: this, combined with the lack
-// of a single-flight gate, pegged ~2 cores and starved the shared tokio runtime
-// the agent harness runs on — the agent's turns stalled 50-100s between model
-// calls even though inference itself was idle).
-const RUNTIME_SNAPSHOT_TTL: Duration = Duration::from_secs(10);
-/// Ceiling on that 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.
-const CURRENT_USER_BACKOFF_MAX: Duration = Duration::from_secs(60);
-const RUNTIME_SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(10);
-const SNAPSHOT_SUB_OP_TIMEOUT: Duration = Duration::from_secs(5);
-const PENDING_BACKEND_VALIDATION_FIELD: &str = "pendingBackendValidation";
-const AUTH_ME_REVALIDATION_TRANSIENT_STATUSES: &[u16] = &[408, 429, 500, 502, 503, 504, 520];
-static APP_STATE_FILE_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
-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.
-static CURRENT_USER_FAILURE: Lazy<Mutex<Option<CurrentUserFailure>>> =
- Lazy::new(|| Mutex::new(None));
-static RUNTIME_SNAPSHOT_CACHE: Lazy<Mutex<Option<CachedRuntimeSnapshot>>> =
- Lazy::new(|| Mutex::new(None));
-/// Single-flight gate for the runtime-snapshot rebuild. Concurrent callers whose
-/// cache read missed serialize here so only ONE runs the expensive sub-op
-/// fan-out; the rest wait, then re-read the cache the winner populated (see the
-/// double-check in `build_runtime_snapshot`). This is an async mutex because the
-/// guard is held across `.await` points (the sub-op `join`). Without it, every
-/// overlapping `app_state_snapshot` poll launched its own build — the rebuild
-/// stampede described on `RUNTIME_SNAPSHOT_TTL`.
-static RUNTIME_SNAPSHOT_REBUILD: Lazy<tokio::sync::Mutex<()>> =
- Lazy::new(|| tokio::sync::Mutex::new(()));
-static SNAPSHOT_REQ_COUNTER: AtomicU64 = AtomicU64::new(0);
-
-#[derive(Debug, Clone)]
-struct CachedRuntimeSnapshot {
- snapshot: RuntimeSnapshot,
- fetched_at: Instant,
- /// Config identity (`workspace_dir`) the snapshot was built for. The cache
- /// holds one entry process-wide, so a snapshot built for one config must
- /// never be served to another — otherwise a different user/workspace (or an
- /// E2E test with an injected service mock) reads a stale, foreign runtime.
- config_key: PathBuf,
-}
-
-#[derive(Debug, Clone)]
-struct CachedCurrentUser {
- api_base: String,
- token: String,
- fetched_at: Instant,
- user: Value,
-}
-
-#[derive(Debug, Clone)]
-enum SnapshotCurrentUser {
- User(Option<Value>),
- DeferredSessionRejected,
-}
-
-impl SnapshotCurrentUser {
- fn user(user: Option<Value>) -> Self {
- Self::User(user)
- }
-}
-
-type SnapshotCurrentUserResult = (SnapshotCurrentUser, Option<Box<Config>>);
-
-fn snapshot_current_user_result(user: Option<Value>) -> SnapshotCurrentUserResult {
- (SnapshotCurrentUser::user(user), None)
-}
-
-#[derive(Debug, Clone)]
-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 {
- 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.
- 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)]
-struct CurrentUserFailure {
- api_base: String,
- token: String,
- failed_at: Instant,
- /// Failures in an unbroken run, counted from 1. Drives the backoff width.
- consecutive: u32,
- /// Replayed verbatim while the window is open, so a caller that matches on
- /// the variant sees what the backend really produced.
- 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.
-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.
-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`].
-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.
-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.
-fn note_current_user_timeout(generation: u64, config: &Config, token: &str) {
- record_current_user_failure_unless_stale(
- generation,
- &current_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.
-fn current_user_api_base(config: &Config) -> String {
- effective_backend_api_url(&config.api_url)
- .trim()
- .trim_end_matches('/')
- .to_string()
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-#[serde(rename_all = "camelCase")]
-pub struct StoredOnboardingTasks {
- #[serde(default)]
- pub accessibility_permission_granted: bool,
- #[serde(default)]
- pub local_model_consent_given: bool,
- #[serde(default)]
- pub local_model_download_started: bool,
- #[serde(default)]
- pub enabled_tools: Vec<String>,
- #[serde(default)]
- pub connected_sources: Vec<String>,
- #[serde(default)]
- pub updated_at_ms: Option<u64>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, Default)]
-#[serde(rename_all = "camelCase")]
-pub struct StoredAppState {
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub encryption_key: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub onboarding_tasks: Option<StoredOnboardingTasks>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub keyring_consent: Option<crate::security::keyring_consent::ConsentPreference>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AppStateSnapshot {
- pub auth: crate::security::credentials::responses::AuthStateResponse,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub session_token: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub current_user: Option<Value>,
- pub onboarding_completed: bool,
- /// Deprecated — the welcome agent has been removed. Retained in the
- /// snapshot for backward compatibility with frontend code that still
- /// reads it. This value may be `false` in newer configs; routing no
- /// longer depends on this field.
- pub chat_onboarding_completed: bool,
- pub analytics_enabled: bool,
- pub local_state: StoredAppState,
- pub keyring_status: crate::security::keyring_consent::KeyringStatus,
- pub runtime: RuntimeSnapshot,
- /// Process + component health, folded into this snapshot so the frontend
- /// hydrates the daemon-health store from the same poll instead of running a
- /// second `health_snapshot` poller. Fields stay snake_case (the type has no
- /// camelCase rename) to match the frontend's existing health parser.
- pub health: crate::platform::health::HealthSnapshot,
- /// `true` when this session's config loader had to recover a corrupted
- /// `config.toml` (renamed to `.corrupted.<ts>` and reset to defaults / a
- /// backup). Latched at boot so it stays reported even after the file is
- /// 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)]
-#[serde(rename_all = "camelCase")]
-pub struct RuntimeSnapshot {
- pub local_ai: LocalAiStatus,
- pub service: ServiceStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Default)]
-#[serde(rename_all = "camelCase")]
-pub struct StoredAppStatePatch {
- #[serde(default)]
- pub encryption_key: Option<Option<String>>,
- #[serde(default)]
- pub onboarding_tasks: Option<Option<StoredOnboardingTasks>>,
- #[serde(default)]
- pub keyring_consent:
- Option<Option<crate::security::keyring_consent::ConsentPreference>>,
-}
-
-fn app_state_path(config: &Config) -> Result<PathBuf, String> {
- let state_dir = config.workspace_dir.join("state");
- fs::create_dir_all(&state_dir).map_err(|e| {
- format!(
- "failed to create workspace state dir {}: {e}",
- state_dir.display()
- )
- })?;
- Ok(state_dir.join(APP_STATE_FILENAME))
-}
-
-fn corrupted_app_state_path(path: &Path) -> PathBuf {
- let timestamp = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .map(|value| value.as_millis())
- .unwrap_or(0);
- path.with_extension(format!("json.corrupted.{timestamp}"))
-}
-
-fn quarantine_corrupted_app_state(path: &Path, reason: &str) {
- let quarantine_path = corrupted_app_state_path(path);
- warn!(
- "{LOG_PREFIX} quarantining corrupted app state {} -> {} ({reason})",
- path.display(),
- quarantine_path.display()
- );
-
- if let Err(rename_error) = fs::rename(path, &quarantine_path) {
- warn!(
- "{LOG_PREFIX} failed to quarantine {} via rename: {}",
- path.display(),
- rename_error
- );
- if let Err(remove_error) = fs::remove_file(path) {
- warn!(
- "{LOG_PREFIX} failed to remove unreadable app state {}: {}",
- path.display(),
- remove_error
- );
- }
- }
-}
-
-fn load_stored_app_state_unlocked(config: &Config) -> Result<StoredAppState, String> {
- let path = app_state_path(config)?;
- if !path.exists() {
- return Ok(StoredAppState::default());
- }
-
- let raw = match fs::read_to_string(&path) {
- Ok(raw) => raw,
- Err(error) => {
- warn!(
- "{LOG_PREFIX} failed to read {}; falling back to defaults: {}",
- path.display(),
- error
- );
- quarantine_corrupted_app_state(&path, &error.to_string());
- return Ok(StoredAppState::default());
- }
- };
-
- match serde_json::from_str::<StoredAppState>(&raw) {
- Ok(state) => Ok(state),
- Err(error) => {
- warn!(
- "{LOG_PREFIX} failed to parse {}; falling back to defaults: {}",
- path.display(),
- error
- );
- quarantine_corrupted_app_state(&path, &error.to_string());
- Ok(StoredAppState::default())
- }
- }
-}
-
-pub(crate) fn load_stored_app_state(config: &Config) -> Result<StoredAppState, String> {
- let _guard = APP_STATE_FILE_LOCK.lock();
- load_stored_app_state_unlocked(config)
-}
-
-fn sync_parent_dir(path: &Path) -> Result<(), String> {
- // Directory fsync is a POSIX-only durability guarantee — on Unix we
- // open the parent dir and call `sync_all()` so the rename of the
- // temp file into place is persisted even if the host crashes before
- // the next buffer flush. On Windows, opening a directory as a
- // regular file requires `FILE_FLAG_BACKUP_SEMANTICS` which
- // `std::fs::File::open` does not set, so the call fails with
- // "Access is denied. (os error 5)". Since Windows uses a different
- // durability model (and `NamedTempFile::persist` issues an atomic
- // MoveFileEx which is already durable enough for our config files),
- // we skip the fsync entirely on non-Unix and return Ok. Mirrors the
- // existing `sync_directory` guard in `config/schema/load.rs`.
- #[cfg(unix)]
- if let Some(parent) = path.parent() {
- File::open(parent)
- .and_then(|dir| dir.sync_all())
- .map_err(|e| format!("failed to sync directory {}: {e}", parent.display()))?;
- }
- #[cfg(not(unix))]
- {
- let _ = path;
- }
- Ok(())
-}
-
-fn save_stored_app_state_unlocked(config: &Config, state: &StoredAppState) -> Result<(), String> {
- let path = app_state_path(config)?;
- let payload = serde_json::to_string_pretty(state)
- .map_err(|e| format!("failed to serialize app state: {e}"))?;
- let parent = path
- .parent()
- .ok_or_else(|| format!("failed to resolve parent dir for {}", path.display()))?;
- let mut temp_file = NamedTempFile::new_in(parent)
- .map_err(|e| format!("failed to create temp file in {}: {e}", parent.display()))?;
- temp_file
- .write_all(payload.as_bytes())
- .map_err(|e| format!("failed to write temp app state for {}: {e}", path.display()))?;
- temp_file
- .as_file_mut()
- .sync_all()
- .map_err(|e| format!("failed to sync temp app state for {}: {e}", path.display()))?;
- sync_parent_dir(&path)?;
- temp_file.persist(&path).map_err(|e| {
- format!(
- "failed to persist app state {}: {}",
- path.display(),
- e.error
- )
- })?;
- sync_parent_dir(&path)?;
- Ok(())
-}
-
-pub fn save_app_state(config: &Config, state: &StoredAppState) -> Result<(), String> {
- let _guard = APP_STATE_FILE_LOCK.lock();
- save_stored_app_state_unlocked(config, state)
-}
-
-/// 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.
-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}"))
-});
-
-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)
-}
-
-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))
-}
-
-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,
- }
-}
-
-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)
-}
-
-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
-}
-
-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)
- })
-}
-
-fn config_state_dir(config: &Config) -> Option<PathBuf> {
- config.config_path.parent().map(Path::to_path_buf)
-}
-
-fn same_config_state_dir(a: &Config, b: &Config) -> bool {
- config_state_dir(a) == config_state_dir(b)
-}
-
-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)
-}
-
-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)
-}
-
-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)
-}
diff --git a/crates/openhuman-core/src/desktop/app_state/ops_part_02.rs b/crates/openhuman-core/src/desktop/app_state/ops_part_02.rs
deleted file mode 100644
index 9001ceed90..0000000000
--- a/crates/openhuman-core/src/desktop/app_state/ops_part_02.rs
+++ /dev/null
@@ -1,682 +0,0 @@
-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);
-}
-
-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}"
- ))
- })
-}
-
-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))
-}
-
-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
-}
-
-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.
-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.
-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.
-fn spawn_current_user_refresh(config: &Config, token: &str, generation: u64) {
- if let Some((error, consecutive, remaining)) =
- suppressed_current_user_failure(&current_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)]
-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.
-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)
- }
-}
-
-/// Return the cached runtime snapshot when it is still within
-/// `RUNTIME_SNAPSHOT_TTL`, else `None`. Kept as a small helper so both the
-/// fast-path read and the post-lock double-check share identical freshness logic.
-/// A service-status mock is injected via `OPENHUMAN_SERVICE_MOCK` (test-only env
-/// hook that production `service` status already honors). While it is active the
-/// runtime snapshot must never be served from — or written to — the process-
-/// global cache: the mock's state changes between calls, so caching it would
-/// both mask the freshly-injected value and poison later (non-mocked) reads.
-fn service_status_mock_active() -> bool {
- std::env::var_os("OPENHUMAN_SERVICE_MOCK").is_some()
-}
-
-fn fresh_cached_runtime_snapshot(config: &Config, req_id: u64) -> Option<RuntimeSnapshot> {
- if service_status_mock_active() {
- return None;
- }
- let cache = RUNTIME_SNAPSHOT_CACHE.lock();
- let entry = cache.as_ref()?;
- // A snapshot built for a different config identity is a miss: rebuild against
- // this config rather than serve another workspace's runtime.
- if entry.config_key != config.workspace_dir {
- return None;
- }
- let age = entry.fetched_at.elapsed();
- if age < RUNTIME_SNAPSHOT_TTL {
- debug!(
- "{LOG_PREFIX} build_runtime_snapshot: returning cached snapshot req_id={req_id} age_ms={}",
- age.as_millis()
- );
- Some(entry.snapshot.clone())
- } else {
- None
- }
-}
-
-async fn build_runtime_snapshot(config: &Config, req_id: u64) -> RuntimeSnapshot {
- // Fast path: a fresh cached snapshot serves every poller without touching the
- // sub-op fan-out.
- if let Some(snapshot) = fresh_cached_runtime_snapshot(config, req_id) {
- return snapshot;
- }
-
- // Cache miss: single-flight the rebuild so only one caller runs the expensive
- // fan-out. Waiters re-check the cache the winner just populated (this
- // double-check) and return it instead of launching a duplicate build —
- // collapsing an N-way stampede into one build per TTL window.
- let _rebuild_guard = RUNTIME_SNAPSHOT_REBUILD.lock().await;
- if let Some(snapshot) = fresh_cached_runtime_snapshot(config, req_id) {
- debug!(
- "{LOG_PREFIX} build_runtime_snapshot: coalesced onto concurrent rebuild req_id={req_id}"
- );
- return snapshot;
- }
-
- let config_for_local_ai = config.clone();
- let config_for_service = config.clone();
-
- let t0 = Instant::now();
-
- let (local_ai, service) = tokio::join!(
- async {
- let t = Instant::now();
- let status = match tokio::time::timeout(
- SNAPSHOT_SUB_OP_TIMEOUT,
- crate::inference::rpc::inference_status(&config_for_local_ai),
- )
- .await
- {
- Ok(Ok(outcome)) => outcome.value,
- Ok(Err(error)) => {
- warn!("{LOG_PREFIX} local_ai status failed during snapshot: {error}");
- crate::inference::LocalAiStatus::disabled(&config_for_local_ai)
- }
- Err(_) => {
- warn!(
- "{LOG_PREFIX} local_ai timed out after {}s; using degraded sub-snapshot req_id={}",
- SNAPSHOT_SUB_OP_TIMEOUT.as_secs(),
- req_id,
- );
- crate::inference::LocalAiStatus::disabled(&config_for_local_ai)
- }
- };
- (status, t.elapsed().as_millis())
- },
- async {
- let t = Instant::now();
- let status = tokio::task::spawn_blocking(move || {
- crate::platform::service::status(&config_for_service)
- })
- .await
- .unwrap_or_else(|_| Err(anyhow::anyhow!("service status task panicked")));
- let status = match status {
- Ok(s) => s,
- Err(error) => {
- let message = error.to_string();
- warn!("{LOG_PREFIX} service status failed during snapshot: {message}");
- ServiceStatus {
- state: ServiceState::Unknown(message.clone()),
- unit_path: None,
- label: "OpenHuman".to_string(),
- details: Some(message),
- }
- }
- };
- (status, t.elapsed().as_millis())
- }
- );
-
- let total_ms = t0.elapsed().as_millis();
- debug!(
- "{LOG_PREFIX} build_runtime_snapshot timings req_id={} local_ai_ms={} service_ms={} total_ms={}",
- req_id,
- local_ai.1, service.1,
- total_ms,
- );
-
- let snapshot = RuntimeSnapshot {
- local_ai: local_ai.0,
- service: service.0,
- };
-
- // Don't cache a snapshot built under an injected service mock (see
- // `service_status_mock_active`) — it would poison later non-mocked reads.
- if !service_status_mock_active() {
- *RUNTIME_SNAPSHOT_CACHE.lock() = Some(CachedRuntimeSnapshot {
- snapshot: snapshot.clone(),
- fetched_at: Instant::now(),
- config_key: config.workspace_dir.clone(),
- });
- }
-
- snapshot
-}
diff --git a/crates/openhuman-core/src/desktop/app_state/ops_part_03.rs b/crates/openhuman-core/src/desktop/app_state/ops_part_03.rs
deleted file mode 100644
index 3497b07b87..0000000000
--- a/crates/openhuman-core/src/desktop/app_state/ops_part_03.rs
+++ /dev/null
@@ -1,396 +0,0 @@
-
-pub async fn snapshot() -> Result<RpcOutcome<AppStateSnapshot>, String> {
- let req_id = SNAPSHOT_REQ_COUNTER.fetch_add(1, Ordering::Relaxed);
- let t_total = Instant::now();
-
- let t_config = Instant::now();
- let config = config_rpc::load_config_with_timeout().await?;
- // Latch corruption recovery from *this* poll's load, not only from boot.
- // `load_config_with_timeout` re-reads config.toml on every snapshot, so a
- // config that becomes corrupt after boot is healed here — carrying a fresh
- // `recovered_from_corruption`. Without this, that mid-session recovery would
- // be dropped (the boot latch never saw it) and the notice never surfaces
- // (#5167). No-op when the load was clean; idempotent once latched.
- super::latch_from_config(&config);
- let config_ms = t_config.elapsed().as_millis();
-
- let t_auth = Instant::now();
- // Load the `app-session` auth profile exactly once and derive both
- // the session-state view and the raw token from it. The previous
- // implementation called `build_session_state` + `get_session_token`
- // separately, which acquired the auth-profile file lock twice per
- // snapshot. On Windows this doubled the surface area for the
- // "Timed out waiting for auth profile lock" failure reported in
- // Sentry against `openhuman.app_state_snapshot`.
- //
- // `load_app_session_profile` calls `acquire_lock()`, which busy-waits
- // with `thread::sleep` for up to ~35s when the lock is contended. Calling
- // it directly on a tokio worker thread blocks that thread for the entire
- // wait, exhausting the thread pool under concurrent snapshot calls and
- // triggering `ERR_CONNECTION_TIMED_OUT` on all RPC connections.
- // Read the sign-out generation BEFORE the profile load, not before the
- // refresh. The token this snapshot is about is the one that load returns, so
- // the generation has to be the one in force when that token was read.
- // Capturing it later leaves a window — sign-out lands between the load and the
- // refresh, the refresh reads the *new* generation, and then publishes an answer
- // fetched with the *old* token, passing its own staleness check.
- // `load_app_session_profile` busy-waits up to ~35s on a contended lock, so that
- // window is not a narrow one.
- let session_mutation_lock = super::CURRENT_USER_SESSION_MUTATION_LOCK.lock().await;
- let generation = current_user_generation();
- let config_for_profile = config.clone();
- let session_profile =
- tokio::task::spawn_blocking(move || load_app_session_profile(&config_for_profile))
- .await
- .unwrap_or_else(|e| Err(format!("[app_state] auth profile load task panicked: {e}")))?;
- drop(session_mutation_lock);
- let mut auth = session_state_from_profile(session_profile.as_ref());
- let mut session_token = session_token_from_profile(session_profile.as_ref());
- let stored_user = sanitize_snapshot_user(auth.user.clone());
- let pending_backend_validation = snapshot_user_pending_backend_validation(stored_user.as_ref());
- let session_metadata = session_profile
- .as_ref()
- .map(|profile| profile.metadata.clone())
- .unwrap_or_default();
- let pending_session_user_id = pending_backend_validation
- .then(|| pending_session_user_id_for_cleanup(stored_user.as_ref(), &session_metadata))
- .flatten();
- let auth_ms = t_auth.elapsed().as_millis();
-
- // Resolve the live current-user refresh and the runtime snapshot
- // CONCURRENTLY. Both touch the backend and both already fall back to local
- // data (stored_user / degraded runtime), so running them in parallel rather
- // than serially halves the worst-case bootstrap latency when the backend is
- // unreachable. Together with the fast auth-profile lock reclaim this keeps
- // the first `app_state_snapshot` from stranding the UI on "Initializing
- // OpenHuman" (the FE clears `isBootstrapping` on this call). `tokio::join!`
- // polls both on the current task — no extra threads.
- let t_enrich = Instant::now();
- let current_user_future = Box::pin(async {
- let Some(token) = session_token.clone().filter(|t| !t.trim().is_empty()) else {
- return snapshot_current_user_result(stored_user.clone());
- };
- if is_local_session_token(&token) {
- return snapshot_current_user_result(stored_user.clone());
- }
- match tokio::time::timeout(
- auth_fetch_timeout(),
- fetch_current_user_cached(&config, &token, !pending_backend_validation, generation),
- )
- .await
- {
- Ok(Ok(Some(fresh_user))) => {
- if pending_backend_validation && user_id_from_profile_payload(&fresh_user).is_none()
- {
- warn!(
- "{LOG_PREFIX} pending current user refresh returned a user without an id; keeping stored pending session for retry"
- );
- return snapshot_current_user_result(stored_user.clone());
- }
- let fresh_user = clear_pending_backend_validation_flag(fresh_user);
- if pending_backend_validation {
- let snapshot_config = match persist_revalidated_session_user(
- &config,
- &token,
- session_metadata.clone(),
- fresh_user.clone(),
- generation,
- )
- .await
- {
- Ok(snapshot_config) => {
- debug!(
- "{LOG_PREFIX} cleared pending backend validation after successful current user refresh"
- );
- snapshot_config
- }
- Err(error) => {
- warn!(
- "{LOG_PREFIX} failed to persist cleared pending backend validation: {error}"
- );
- return snapshot_current_user_result(stored_user.clone());
- }
- };
- return (
- SnapshotCurrentUser::user(Some(fresh_user)),
- Some(snapshot_config),
- );
- }
- snapshot_current_user_result(Some(fresh_user))
- }
- Ok(Ok(None)) if pending_backend_validation => {
- warn!(
- "{LOG_PREFIX} backend returned empty user for pending session revalidation; clearing stored app session"
- );
- if let Err(error) = clear_deferred_session_after_backend_rejection(
- &config,
- pending_session_user_id.as_deref(),
- )
- .await
- {
- warn!("{LOG_PREFIX} failed to clear rejected pending session: {error}");
- }
- (SnapshotCurrentUser::DeferredSessionRejected, None)
- }
- Ok(Ok(None)) => snapshot_current_user_result(stored_user.clone()),
- Ok(Err(CurrentUserFetchError::Rejected(error))) if pending_backend_validation => {
- warn!(
- "{LOG_PREFIX} pending current user refresh was rejected; clearing stored app session: {error}"
- );
- if let Err(clear_error) = clear_deferred_session_after_backend_rejection(
- &config,
- pending_session_user_id.as_deref(),
- )
- .await
- {
- warn!("{LOG_PREFIX} failed to clear rejected pending session: {clear_error}");
- }
- (SnapshotCurrentUser::DeferredSessionRejected, None)
- }
- Ok(Err(CurrentUserFetchError::FetchFailed(error))) if pending_backend_validation => {
- warn!(
- "{LOG_PREFIX} pending current user refresh failed before a backend response; keeping stored pending session for retry: {error}"
- );
- snapshot_current_user_result(stored_user.clone())
- }
- Ok(Err(CurrentUserFetchError::TransientResponse(error)))
- if pending_backend_validation =>
- {
- warn!(
- "{LOG_PREFIX} pending current user refresh received transient backend response; keeping stored pending session: {error}"
- );
- snapshot_current_user_result(stored_user.clone())
- }
- Ok(Err(CurrentUserFetchError::Suppressed {
- inner,
- consecutive,
- retry_in,
- })) => {
- // Not a failure of *this* poll: the backoff window opened by an
- // earlier failure is still running, so no request was made and
- // this arm cost microseconds. Logging it at `warn` with the
- // same wording as a live failure is what made a working backoff
- // look like a hammering loop in #5930's own log evidence.
- debug!(
- "{LOG_PREFIX} current user refresh suppressed; backend unavailable or unhealthy \
- {consecutive}x, next live attempt in {}s, using stored snapshot fallback: {}",
- retry_in.as_secs(),
- inner.message()
- );
- snapshot_current_user_result(stored_user.clone())
- }
- Ok(Err(error)) => {
- warn!(
- "{LOG_PREFIX} current user refresh failed; using stored snapshot fallback: {}",
- error.message()
- );
- snapshot_current_user_result(stored_user.clone())
- }
- Err(_) if pending_backend_validation => {
- warn!(
- "{LOG_PREFIX} pending current user fetch timed out after {}s; keeping stored pending session for retry",
- auth_fetch_timeout().as_secs()
- );
- note_current_user_timeout(generation, &config, &token);
- snapshot_current_user_result(stored_user.clone())
- }
- Err(_) => {
- warn!(
- "{LOG_PREFIX} current user fetch timed out after {}s; using stored snapshot fallback",
- auth_fetch_timeout().as_secs()
- );
- note_current_user_timeout(generation, &config, &token);
- snapshot_current_user_result(stored_user.clone())
- }
- }
- });
- let runtime_future = Box::pin(async {
- match tokio::time::timeout(
- RUNTIME_SNAPSHOT_TIMEOUT,
- build_runtime_snapshot(&config, req_id),
- )
- .await
- {
- Ok(snapshot) => snapshot,
- Err(_) => {
- warn!(
- "{LOG_PREFIX} build_runtime_snapshot timed out after {}s req_id={}; returning degraded runtime snapshot",
- RUNTIME_SNAPSHOT_TIMEOUT.as_secs(),
- req_id
- );
- degraded_runtime_snapshot(&config)
- }
- }
- });
- let (current_user_result, runtime) = tokio::join!(current_user_future, runtime_future);
- let enrich_ms = t_enrich.elapsed().as_millis();
- let (current_user, revalidated_config) = current_user_result;
- // Read before the `DeferredSessionRejected` arm below clears
- // `session_token`, and keyed off the same `config` the fetch used so the
- // answer describes this identity's backend, not a previous one's.
- //
- // A rejected session is excluded outright: that arm is about to clear
- // `auth`, `session_token` and `current_user`, and a signed-out snapshot
- // carrying `currentUserStale: true` would describe a user it no longer
- // reports.
- //
- // The token is matched to the fetch above, which filters on the *trimmed*
- // token being non-empty but keys the failure record on the raw one.
- // Trimming here instead would look up a key that was never written, and
- // staleness would read as `false` for every token with surrounding
- // whitespace.
- let session_rejected = matches!(current_user, SnapshotCurrentUser::DeferredSessionRejected);
- let (current_user_stale, current_user_stale_seconds) = match session_token
- .as_deref()
- .filter(|_| !session_rejected)
- .filter(|&token| !token.trim().is_empty() && !is_local_session_token(token))
- {
- Some(token) => current_user_staleness(&current_user_api_base(&config), token),
- // Signed out, rejected, or a local-only token that never talks to the
- // backend: there is nothing for the stored snapshot to be stale
- // relative to.
- None => (false, None),
- };
- let mut snapshot_config = config.clone();
- if let Some(revalidated_config) = revalidated_config {
- snapshot_config = *revalidated_config;
- }
- let current_user = match current_user {
- SnapshotCurrentUser::User(current_user) => {
- if pending_backend_validation {
- if let Some(user_id) = current_user.as_ref().and_then(user_id_from_profile_payload)
- {
- auth.user_id = Some(user_id);
- }
- }
- auth.user = current_user.clone();
- current_user
- }
- SnapshotCurrentUser::DeferredSessionRejected => {
- auth.is_authenticated = false;
- auth.user_id = None;
- auth.user = None;
- auth.profile_id = None;
- session_token = None;
- None
- }
- };
- let runtime = if same_config_state_dir(&config, &snapshot_config) {
- runtime
- } else {
- warn!(
- "{LOG_PREFIX} pending session revalidation changed config scope; rebuilding runtime snapshot with activated user config"
- );
- match tokio::time::timeout(
- RUNTIME_SNAPSHOT_TIMEOUT,
- build_runtime_snapshot(&snapshot_config, req_id),
- )
- .await
- {
- Ok(snapshot) => snapshot,
- Err(_) => {
- warn!(
- "{LOG_PREFIX} activated-config runtime snapshot timed out after {}s req_id={}; returning degraded runtime snapshot",
- RUNTIME_SNAPSHOT_TIMEOUT.as_secs(),
- req_id
- );
- degraded_runtime_snapshot(&snapshot_config)
- }
- }
- };
-
- let t_local_state = Instant::now();
- let local_state = load_stored_app_state(&snapshot_config)?;
- crate::security::keyring_consent::policy::initialize(
- local_state.keyring_consent.clone(),
- );
- let local_state_ms = t_local_state.elapsed().as_millis();
-
- let total_ms = t_total.elapsed().as_millis();
- debug!(
- "{LOG_PREFIX} snapshot timings req_id={} config_ms={} auth_ms={} enrich_ms={} local_state_ms={} total_ms={}",
- req_id, config_ms, auth_ms, enrich_ms, local_state_ms, total_ms
- );
-
- debug!(
- "{LOG_PREFIX} snapshot req_id={} auth={} onboarding={} chat_onboarding={} analytics={} local_ai_state={} service_state={:?}",
- req_id,
- auth.is_authenticated,
- snapshot_config.onboarding_completed,
- snapshot_config.chat_onboarding_completed,
- snapshot_config.observability.analytics_enabled,
- runtime.local_ai.state,
- runtime.service.state
- );
-
- let keyring_status = crate::security::keyring_consent::policy::current_status();
- let health = crate::platform::health::snapshot();
-
- Ok(RpcOutcome::new(
- AppStateSnapshot {
- auth,
- session_token,
- current_user,
- onboarding_completed: snapshot_config.onboarding_completed,
- chat_onboarding_completed: snapshot_config.chat_onboarding_completed,
- analytics_enabled: snapshot_config.observability.analytics_enabled,
- local_state,
- keyring_status,
- runtime,
- health,
- config_recovered: super::config_recovered_this_session(),
- current_user_stale,
- current_user_stale_seconds,
- },
- vec!["core app state snapshot fetched".to_string()],
- ))
-}
-
-fn degraded_runtime_snapshot(config: &Config) -> RuntimeSnapshot {
- RuntimeSnapshot {
- local_ai: crate::inference::LocalAiStatus::disabled(config),
- service: ServiceStatus {
- state: ServiceState::Unknown("snapshot timed out".to_string()),
- unit_path: None,
- label: "OpenHuman".to_string(),
- details: Some("runtime snapshot timed out".to_string()),
- },
- }
-}
-
-pub async fn update_local_state(
- patch: StoredAppStatePatch,
-) -> Result<RpcOutcome<StoredAppState>, String> {
- let config = config_rpc::load_config_with_timeout().await?;
- let _guard = APP_STATE_FILE_LOCK.lock();
- let mut current = load_stored_app_state_unlocked(&config)?;
-
- if let Some(encryption_key) = patch.encryption_key {
- current.encryption_key = encryption_key.and_then(|value| {
- let trimmed = value.trim().to_string();
- (!trimmed.is_empty()).then_some(trimmed)
- });
- }
-
- if let Some(onboarding_tasks) = patch.onboarding_tasks {
- current.onboarding_tasks = onboarding_tasks;
- }
-
- if let Some(keyring_consent) = patch.keyring_consent {
- current.keyring_consent = keyring_consent;
- }
-
- save_stored_app_state_unlocked(&config, &current)?;
-
- debug!(
- "{LOG_PREFIX} local state updated encryption_key={} onboarding_tasks={} keyring_consent={}",
- current.encryption_key.is_some(),
- current.onboarding_tasks.is_some(),
- current.keyring_consent.is_some(),
- );
-
- Ok(RpcOutcome::new(
- current,
- vec!["core local app state updated".to_string()],
- ))
-}
diff --git a/crates/openhuman-core/src/desktop/app_state/ops_staleness.rs b/crates/openhuman-core/src/desktop/app_state/ops_staleness.rs
deleted file mode 100644
index 0d9a4fbd4e..0000000000
--- a/crates/openhuman-core/src/desktop/app_state/ops_staleness.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-// How stale the `current_user` the snapshot is serving has become.
-//
-// Split out of `ops_part_01.rs` (layout gate) and 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).
-//
-// `include!`d into `ops.rs`, so everything here shares that module's scope.
-
-/// 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.
-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)]
-struct CurrentUserSuccess {
- api_base: String,
- token: String,
- 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`].
-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.
-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.
-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.
-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)
-}