From c4b28e37ea0a65688e9a29d169e2ff01ba6d2d8f Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sat, 14 Feb 2026 22:59:20 -0600 Subject: [PATCH] fix(session): prevent false login state with userId=0 Addresses race condition and invalid state issues identified by Codex diagnostic: 1. CoreBridge: Add try_get() and is_initialized() methods to gracefully handle uninitialized state instead of panicking 2. auth.rs: Use try_get() for V2 auth in login/auto_login/logout to avoid panic if CoreBridge init is still in progress 3. LoginView.svelte: Reject userId=0 as fallback - if userInfo or userId is missing/invalid, don't call onLoginSuccess (require re-login) 4. +page.svelte: - Move get_audio_settings call to after sessionReady is set - Add explicit userId > 0 check before activate_user_session - Return early if activation fails to prevent sessionReady from being set in broken state These are tactical fixes aligned with ADR_RUNTIME_SESSION_CONTRACT.md invariants. Full runtime state machine implementation to follow. --- src-tauri/src/commands/auth.rs | 33 ++++++++++++++--------- src-tauri/src/core_bridge.rs | 16 +++++++++++ src/lib/components/views/LoginView.svelte | 8 ++++-- src/routes/+page.svelte | 24 ++++++++++++----- 4 files changed, 60 insertions(+), 21 deletions(-) diff --git a/src-tauri/src/commands/auth.rs b/src-tauri/src/commands/auth.rs index f0eaafe6f..308da49fa 100644 --- a/src-tauri/src/commands/auth.rs +++ b/src-tauri/src/commands/auth.rs @@ -92,11 +92,15 @@ pub async fn login( } // Also authenticate V2 CoreBridge client for the new architecture - let bridge = core_bridge.get().await; - if let Err(e) = bridge.login(&email, &password).await { - log::warn!("[Auth] V2 CoreBridge login failed (non-blocking): {}", e); + // Use try_get() to gracefully handle case where CoreBridge init is still in progress + if let Some(bridge) = core_bridge.try_get().await { + if let Err(e) = bridge.login(&email, &password).await { + log::warn!("[Auth] V2 CoreBridge login failed (non-blocking): {}", e); + } else { + log::info!("[Auth] V2 CoreBridge authenticated successfully"); + } } else { - log::info!("[Auth] V2 CoreBridge authenticated successfully"); + log::warn!("[Auth] V2 CoreBridge not yet initialized, skipping V2 auth"); } Ok(LoginResponse { @@ -168,10 +172,11 @@ pub async fn logout( let client = state.client.read().await; client.logout().await; - // Also logout from V2 CoreBridge - let bridge = core_bridge.get().await; - if let Err(e) = bridge.logout().await { - log::warn!("[Auth] V2 CoreBridge logout failed: {}", e); + // Also logout from V2 CoreBridge (if initialized) + if let Some(bridge) = core_bridge.try_get().await { + if let Err(e) = bridge.logout().await { + log::warn!("[Auth] V2 CoreBridge logout failed: {}", e); + } } Ok(()) @@ -263,11 +268,15 @@ pub async fn auto_login( } // Also authenticate V2 CoreBridge client for the new architecture - let bridge = core_bridge.get().await; - if let Err(e) = bridge.login(&creds.email, &creds.password).await { - log::warn!("[Auth/Auto] V2 CoreBridge login failed (non-blocking): {}", e); + // Use try_get() to gracefully handle case where CoreBridge init is still in progress + if let Some(bridge) = core_bridge.try_get().await { + if let Err(e) = bridge.login(&creds.email, &creds.password).await { + log::warn!("[Auth/Auto] V2 CoreBridge login failed (non-blocking): {}", e); + } else { + log::info!("[Auth/Auto] V2 CoreBridge authenticated successfully"); + } } else { - log::info!("[Auth/Auto] V2 CoreBridge authenticated successfully"); + log::warn!("[Auth/Auto] V2 CoreBridge not yet initialized, skipping V2 auth"); } Ok(LoginResponse { diff --git a/src-tauri/src/core_bridge.rs b/src-tauri/src/core_bridge.rs index 03ac09dda..98820805d 100644 --- a/src-tauri/src/core_bridge.rs +++ b/src-tauri/src/core_bridge.rs @@ -239,6 +239,22 @@ impl CoreBridgeState { |opt| opt.as_ref().expect("CoreBridge not initialized") ) } + + /// Try to get the bridge, returns None if not initialized yet + /// Use this for operations that should gracefully handle uninitialized state + pub async fn try_get(&self) -> Option + '_> { + let guard = self.0.read().await; + if guard.is_some() { + Some(tokio::sync::RwLockReadGuard::map(guard, |opt| opt.as_ref().unwrap())) + } else { + None + } + } + + /// Check if the bridge is initialized + pub async fn is_initialized(&self) -> bool { + self.0.read().await.is_some() + } } impl Default for CoreBridgeState { diff --git a/src/lib/components/views/LoginView.svelte b/src/lib/components/views/LoginView.svelte index 58d51a8a6..41be16db6 100644 --- a/src/lib/components/views/LoginView.svelte +++ b/src/lib/components/views/LoginView.svelte @@ -73,7 +73,9 @@ clearTimeoutTimer(); const userInfo = await invoke<{ user_name: string; subscription: string; subscription_valid_until?: string | null } | null>('get_user_info'); const userId = await invoke('get_current_user_id'); - if (userInfo && userId) { + // CRITICAL: userId must be a valid positive number, never 0 or null + // If we can't get a valid userId, the session is broken and we need to re-login + if (userInfo && userId && userId > 0) { onLoginSuccess({ userName: userInfo.user_name, userId, @@ -81,7 +83,9 @@ subscriptionValidUntil: userInfo.subscription_valid_until ?? null, }); } else { - onLoginSuccess({ userName: 'User', userId: userId || 0, subscription: 'Active' }); + // Session is invalid - don't use userId=0 fallback, show login instead + console.warn('[LoginView] Session invalid: userInfo or userId missing/invalid, requiring re-login'); + // Don't call onLoginSuccess with invalid userId - let the login flow continue } return; } diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 3043bbe47..b88f8899f 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -2301,12 +2301,19 @@ // Activate per-user backend state (LoginView already did this for auto-login, // but we call again to ensure it's active for manual login too — it's idempotent) - if (info.userId) { + // CRITICAL: userId must be a valid positive number for activate_user_session + if (info.userId && info.userId > 0) { try { await invoke('activate_user_session', { userId: info.userId }); } catch (err) { console.error('[Session] Failed to activate user session:', err); + // Don't set sessionReady if activation failed + return; } + } else { + console.error('[Session] Invalid userId received:', info.userId, '- cannot activate session'); + // Don't set sessionReady - session is broken + return; } // Signal that per-user backend stores are ready — the launch update @@ -2324,6 +2331,13 @@ initBlacklistStore().catch(err => console.debug('[Blacklist] Init deferred:', err)); refreshUpdatePreferences().catch(err => console.debug('[Updates] Prefs refresh deferred:', err)); + // Load audio settings (normalization state) now that session is active + invoke<{ normalization_enabled: boolean }>('get_audio_settings').then((settings) => { + normalizationEnabled = settings.normalization_enabled; + }).catch((err) => { + console.error('[AudioSettings] Failed to load:', err); + }); + // Load favorites now that login is confirmed (sync with Qobuz) loadFavorites(); // Track favorites loadAlbumFavorites(); // Album favorites @@ -2637,12 +2651,8 @@ // Ignore storage errors } - // Load normalization enabled state from audio settings - invoke<{ normalization_enabled: boolean }>('get_audio_settings').then((settings) => { - normalizationEnabled = settings.normalization_enabled; - }).catch((err) => { - console.error('Failed to load audio settings:', err); - }); + // NOTE: Audio settings are loaded AFTER session is ready (in handleLoginSuccess) + // to avoid "No active session" errors from per-user state // Set up callback for cast disconnect handoff setOnAskContinueLocally(async (track, position) => {