fix: restore offline mode — use last known user profile

Three bugs prevented offline mode from working after V2 migration:

1. activate_offline_session used user_id=0 (empty profile) instead of
   the last known user_id, so the user's library/settings were invisible

2. setManualOffline was called BEFORE activate_offline_session, but it
   requires the offline store to be initialized (which happens during
   session activation). Reordered: activate session first, then set
   manual offline.

3. LoginView called setManualOffline directly instead of delegating to
   the parent's handleStartOffline which has the correct order.

Also added "noPreviousSession" i18n message for users who never logged
in — they need to create a profile first before offline mode works.

cc
This commit is contained in:
vicrodh committed 2026-03-21 11:01:25 -06:00
1 parent c766357870
commit fb74f318a1
8 files changed
+39 -17

No files matched your search

+13 -10
View File
@@ -337,19 +337,22 @@ pub async fn deactivate_session(app: &tauri::AppHandle) -> Result<(), String> {
/// Activate an offline-only session (no remote auth required).
///
/// This creates a minimal session for offline/local library use.
/// Uses user_id = 0 as a special "offline user" marker.
/// Activates an offline session using the last known user profile.
/// If no previous session exists, falls back to user_id = 0 (empty profile).
pub async fn activate_offline_session(app: &tauri::AppHandle) -> Result<(), String> {
log::info!("[SessionLifecycle] Activating offline session");
// For offline mode, we use a special user_id of 0
// This is distinct from authenticated users
const OFFLINE_USER_ID: u64 = 0;
// Use last known user_id so offline mode has access to existing library,
// settings, and cached data. Fall back to 0 if never logged in.
let offline_user_id = UserDataPaths::load_last_user_id().unwrap_or(0);
log::info!(
"[SessionLifecycle] Activating offline session (user_id={}{})",
offline_user_id,
if offline_user_id == 0 { " — no previous session" } else { "" }
);
let user_paths = app.state::<UserDataPaths>();
let runtime_manager = app.state::<RuntimeManagerState>();
// Set user to offline user for path resolution
user_paths.set_user(OFFLINE_USER_ID);
user_paths.set_user(offline_user_id);
// Resolve directories (same as normal user but at user_id=0)
let data_dir = user_paths.user_data_dir()?;
@@ -400,14 +403,14 @@ pub async fn activate_offline_session(app: &tauri::AppHandle) -> Result<(), Stri
// But session_activated is true so queue commands work
runtime_manager
.manager()
.set_session_activated(true, OFFLINE_USER_ID)
.set_session_activated(true, offline_user_id)
.await;
// Emit event
let _ = app.emit(
"runtime:event",
RuntimeEvent::UserSessionActivated {
user_id: OFFLINE_USER_ID,
user_id: offline_user_id,
},
);
+4 -1
View File
@@ -280,7 +280,10 @@
async function handleStartOffline() {
try {
await setManualOffline(true);
// Delegate to parent — it handles the correct order:
// 1. activate_offline_session (init stores)
// 2. setManualOffline (requires stores)
// 3. setLoggedIn + navigate
onStartOffline?.();
} catch (err) {
console.error('Failed to enable offline mode:', err);
+1
View File
@@ -1430,6 +1430,7 @@
"trackNotAvailable": "Dieser Titel ist offline nicht verfügbar",
"featureDisabled": "Diese Funktion erfordert eine Internetverbindung",
"startWithoutLogin": "Offline starten (kein Zugriff auf Qobuz™-Dienste)",
"noPreviousSession": "Sie müssen sich mindestens einmal anmelden, bevor Sie den Offline-Modus verwenden können. Stellen Sie eine Internetverbindung her und melden Sie sich an.",
"noNetworkToast": "Keine Internetverbindung verfügbar",
"checkingNetwork": "Netzwerkverbindung wird überprüft...",
"available": "Vollständig offline verfügbar",
+1
View File
@@ -1527,6 +1527,7 @@
"trackNotAvailable": "This track is not available offline",
"featureDisabled": "This feature requires internet connection",
"startWithoutLogin": "Start offline (no access to Qobuz™ services)",
"noPreviousSession": "You need to log in at least once before using offline mode. Connect to the internet and log in to create your profile.",
"noNetworkToast": "No internet connection available",
"checkingNetwork": "Checking network connection...",
"available": "Fully Available Offline",
+1
View File
@@ -1527,6 +1527,7 @@
"trackNotAvailable": "Esta pista no esta disponible offline",
"featureDisabled": "Esta funcion requiere conexion a internet",
"startWithoutLogin": "Iniciar en modo offline (sin acceso a los servicios de Qobuz™)",
"noPreviousSession": "Necesitas iniciar sesión al menos una vez antes de usar el modo offline. Conéctate a internet e inicia sesión para crear tu perfil.",
"noNetworkToast": "No hay conexion a internet disponible",
"checkingNetwork": "Verificando conexion a internet...",
"available": "Totalmente Disponible Offline",
+1
View File
@@ -1430,6 +1430,7 @@
"trackNotAvailable": "Cette piste n'est pas disponible hors ligne",
"featureDisabled": "Cette fonctionnalité nécessite une connexion Internet",
"startWithoutLogin": "Démarrer hors ligne (pas d'accès aux services Qobuz™)",
"noPreviousSession": "Vous devez vous connecter au moins une fois avant d'utiliser le mode hors ligne. Connectez-vous à Internet et identifiez-vous pour créer votre profil.",
"noNetworkToast": "Aucune connexion Internet disponible",
"checkingNetwork": "Vérification de la connexion réseau...",
"available": "Entièrement disponible hors ligne",
+1
View File
@@ -1525,6 +1525,7 @@
"trackNotAvailable": "Esta faixa não está disponível offline",
"featureDisabled": "Este recurso requer conexão com a internet",
"startWithoutLogin": "Iniciar offline (sem acesso aos serviços do Qobuz™)",
"noPreviousSession": "Você precisa fazer login pelo menos uma vez antes de usar o modo offline. Conecte-se à internet e faça login para criar seu perfil.",
"noNetworkToast": "Nenhuma conexão com a internet disponível",
"checkingNetwork": "Verificando conexão de rede...",
"available": "Totalmente Disponível Offline",
+17 -6
View File
@@ -3404,16 +3404,27 @@
// Auth Handlers
async function handleStartOffline() {
// Enable manual offline mode and enter app without authentication
await setManualOffline(true);
// Activate offline session in backend (initializes minimal stores, sets session_activated=true)
// This allows queue commands to work even without remote auth
// Activate offline session FIRST — this initializes per-user stores
// (library, offline cache, audio settings) using the last known user profile.
// Must happen before setManualOffline which requires an active store.
try {
await invoke('v2_activate_offline_session');
} catch (err) {
console.error('[Offline] Failed to activate offline session:', err);
// Continue anyway - offline mode should be best-effort
// If no previous session exists, show friendly message
const errStr = String(err);
if (errStr.includes('No active session') || errStr.includes('no previous session')) {
showToast($t('offline.noPreviousSession'), 'error');
return;
}
// Continue for other errors - offline mode should be best-effort
}
// Now that stores are initialized, enable manual offline mode
try {
await setManualOffline(true);
} catch (err) {
console.warn('[Offline] setManualOffline failed (non-fatal):', err);
}
setLoggedIn({