fix: eliminate double-brain session lifecycle (legacy vs V2)

Backend:
- v2_auto_login/v2_manual_login now FAIL if activate_session fails
  (was: log and continue with success:true, causing "logged in but not ready")
- Session activation is now REQUIRED, not optional

Frontend:
- Remove duplicate activate_user_session call from handleLoginSuccess
  (V2 login already activates session internally)
- Remove duplicate deactivate_user_session call from handleLogout
  (v2_logout already deactivates session internally)
- LoginView now uses runtime_bootstrap as SINGLE SOURCE OF TRUTH
  (was: v2_init_client + legacy is_logged_in/get_user_info checks)
- PlaylistDetailView uses runtime_get_status for user_id
  (was: legacy get_current_user_id)

This eliminates the "double-brain" where frontend used both legacy
and V2 paths, causing state divergence and intermittent failures.
This commit is contained in:
vicrodh committed 2026-02-15 14:39:44 -06:00
1 parent 59e3141aa6
commit deece54bcb
4 files changed
+81 -102

No files matched your search

+20 -2
View File
@@ -394,9 +394,18 @@ pub async fn v2_auto_login(
}
// Activate per-user session (initializes all per-user stores)
// This is REQUIRED - without it, user has auth but no stores, causing UserSessionNotActivated errors
if let Err(e) = crate::session_lifecycle::activate_session(&app, session.user_id).await {
log::error!("[V2] Session activation failed: {}", e);
// Non-fatal - consider login successful, stores can be initialized later
return Ok(V2LoginResponse {
success: false,
user_name: Some(session.display_name.clone()),
user_id: Some(session.user_id),
subscription: Some(session.subscription_label.clone()),
subscription_valid_until: session.subscription_valid_until.clone(),
error: Some(format!("Session activation failed: {}", e)),
error_code: Some("session_activation_failed".to_string()),
});
}
// Emit ready event
@@ -504,9 +513,18 @@ pub async fn v2_manual_login(
}
// Activate per-user session (initializes all per-user stores)
// This is REQUIRED - without it, user has auth but no stores, causing UserSessionNotActivated errors
if let Err(e) = crate::session_lifecycle::activate_session(&app, session.user_id).await {
log::error!("[V2] Session activation failed: {}", e);
// Non-fatal - consider login successful, stores can be initialized later
return Ok(V2LoginResponse {
success: false,
user_name: Some(session.display_name.clone()),
user_id: Some(session.user_id),
subscription: Some(session.subscription_label.clone()),
subscription_valid_until: session.subscription_valid_until.clone(),
error: Some(format!("Session activation failed: {}", e)),
error_code: Some("session_activation_failed".to_string()),
});
}
// Emit ready event
+50 -74
View File
@@ -45,6 +45,17 @@
};
});
// RuntimeStatus type from backend
interface RuntimeStatus {
state: string;
user_id: number | null;
client_initialized: boolean;
legacy_auth: boolean;
corebridge_auth: boolean;
session_activated: boolean;
degraded_reason: { code: string; message: string } | null;
}
async function initializeClient() {
try {
isInitializing = true;
@@ -64,89 +75,54 @@
}
}, LOGIN_TIMEOUT_MS);
// Phase 1: Initialize client (V2 - extracts bundle tokens)
const initResult = await invoke<{ state: string; client_initialized: boolean }>('v2_init_client');
console.log('[LoginView] v2_init_client result:', initResult);
// Check if already logged in (in-memory session)
const loggedIn = await invoke<boolean>('is_logged_in');
if (loggedIn) {
clearTimeoutTimer();
const userInfo = await invoke<{ user_name: string; subscription: string; subscription_valid_until?: string | null } | null>('get_user_info');
const userId = await invoke<number | null>('get_current_user_id');
// 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,
subscription: userInfo.subscription,
subscriptionValidUntil: userInfo.subscription_valid_until ?? null,
});
} else {
// 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;
}
// Check for saved credentials
initStatus = 'Checking saved credentials...';
const hasSavedCreds = await invoke<boolean>('has_saved_credentials');
// NOTE: Session activation removed from here.
// Session is now activated in runtime_bootstrap/v2_auto_login AFTER successful auth.
// This prevents activating session before login is confirmed.
// ToS check will use localStorage fallback if per-user storage isn't available.
// Load ToS acceptance (will fallback to localStorage if no session)
// Load ToS acceptance first (uses localStorage fallback before session)
initStatus = 'Loading preferences...';
await loadTosAcceptance();
// Phase 2: Auto-login with V2 (blocking CoreBridge auth)
if (hasSavedCreds && get(qobuzTosAccepted)) {
initStatus = 'Logging in...';
const response = await invoke<{
success: boolean;
user_name?: string;
user_id?: number;
subscription?: string;
subscription_valid_until?: string | null;
error?: string;
error_code?: string;
}>('v2_auto_login');
// Use runtime_bootstrap as the SINGLE SOURCE OF TRUTH for initialization.
// It does everything: init client, auto-login if saved creds, activate session.
// NO legacy is_logged_in/get_user_info checks - that causes state divergence.
initStatus = 'Initializing...';
const status = await invoke<RuntimeStatus>('runtime_bootstrap');
console.log('[LoginView] runtime_bootstrap result:', status);
if (response.success) {
// Validate that we have a valid user_id - NEVER allow 0
if (!response.user_id || response.user_id === 0) {
console.error('[LoginView] v2_auto_login returned success but invalid user_id');
error = $t('auth.v2AuthFailed');
clearTimeoutTimer();
// Check if session is fully active (authenticated + session activated)
if (status.session_activated && status.user_id && status.user_id > 0) {
// Session is valid - need to get user display info
// Use v2 command since session is active
clearTimeoutTimer();
try {
const userInfo = await invoke<{ user_name: string; subscription: string; subscription_valid_until?: string | null } | null>('get_user_info');
if (userInfo) {
console.log('[LoginView] Session restored for user_id:', status.user_id);
onLoginSuccess({
userName: userInfo.user_name,
userId: status.user_id,
subscription: userInfo.subscription,
subscriptionValidUntil: userInfo.subscription_valid_until ?? null,
});
return;
}
clearTimeoutTimer();
console.log('[LoginView] v2_auto_login successful, user_id:', response.user_id);
onLoginSuccess({
userName: response.user_name || 'User',
userId: response.user_id,
subscription: response.subscription || 'Active',
subscriptionValidUntil: response.subscription_valid_until ?? null,
});
return;
} else {
console.log('[LoginView] v2_auto_login failed:', response.error);
if (response.error_code === 'ineligible_user') {
error = $t('auth.ineligibleSubscription');
} else if (response.error_code === 'v2_auth_failed') {
error = $t('auth.v2AuthFailed');
} else if (response.error_code === 'v2_not_initialized') {
error = $t('auth.v2NotInitialized');
}
// Don't show error, just fall through to manual login
} catch (err) {
console.warn('[LoginView] Could not get user info, will show login form:', err);
}
}
// Check for degraded state
if (status.degraded_reason) {
console.warn('[LoginView] Runtime degraded:', status.degraded_reason);
if (status.degraded_reason.code === 'BundleExtractionFailed') {
initError = $t('auth.connectionFailed');
clearTimeoutTimer();
return;
}
}
// If client is initialized but no session, show login form
if (status.client_initialized && !status.session_activated) {
console.log('[LoginView] Client ready, no session - showing login form');
}
// If we reach here, no auto-login - clear timeout and show login form
clearTimeoutTimer();
} catch (err) {
@@ -340,11 +340,11 @@
// Subscribe to offline status changes and fetch current user ID
onMount(() => {
// Fetch current user ID for ownership check
invoke<number | null>('get_current_user_id').then(userId => {
currentUserId = userId;
// Fetch current user ID for ownership check via runtime contract (not legacy)
invoke<{ user_id: number | null }>('runtime_get_status').then(status => {
currentUserId = status.user_id;
}).catch(err => {
console.warn('Failed to get current user ID:', err);
console.warn('Failed to get current user ID from runtime:', err);
});
const unsubscribeOffline = subscribeOffline(() => {
+7 -22
View File
@@ -2296,27 +2296,17 @@
}
async function handleLoginSuccess(info: UserInfo) {
// CRITICAL: Validate and activate backend session FIRST, before setting UI login state.
// This prevents UI/backend state divergence if activation fails.
// (Fix for Issue 1: UI was entering logged-in state before backend session was valid)
// V2 login commands (v2_auto_login, v2_manual_login) now handle session activation internally.
// They return success:false if activation fails, so if we get here, session is already active.
// NO legacy activate_user_session call needed - that causes duplicate activation.
// Validate userId before any session operations
if (!info.userId || info.userId <= 0) {
console.error('[Session] Invalid userId received:', info.userId, '- cannot activate session');
// Don't set login state - session is broken
console.error('[Session] Invalid userId received:', info.userId, '- cannot proceed');
return;
}
// Activate per-user backend state FIRST
try {
await invoke('activate_user_session', { userId: info.userId });
} catch (err) {
console.error('[Session] Failed to activate user session:', err);
// Don't set login state if activation failed - backend is not ready
return;
}
// Backend session confirmed - NOW set UI login state
// Backend session already activated by V2 login - set UI login state
setLoggedIn(info);
// Set up per-user localStorage scoping and migrate old keys
@@ -2462,6 +2452,8 @@
async function handleLogout() {
try {
// v2_logout handles full session deactivation internally via session_lifecycle::deactivate_session()
// NO legacy deactivate_user_session call needed - that causes duplicate teardown
await invoke('v2_logout');
// Clear saved credentials from keyring
try {
@@ -2471,13 +2463,6 @@
console.error('Failed to clear credentials:', clearErr);
// Don't block logout if clearing fails
}
// Deactivate per-user backend state (closes DB connections)
try {
await invoke('deactivate_user_session');
console.log('[Session] Per-user session deactivated');
} catch (deactivateErr) {
console.error('[Session] Failed to deactivate user session:', deactivateErr);
}
// Clear per-user localStorage scoping
setStorageUserId(null);
// Clear session state