π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Run the legacy model migration as a UI-gated startup step
Manav Rathi3359018a443d
diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/App.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/App.ktindex 1062e5581e..b0a52863c3 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/App.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/App.kt@@ -1,12 +1,39 @@package io.ente.ensu+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.height+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import io.ente.ensu.designsystem.EnsuColor@Composablefun App(appViewModel: AppViewModel) {val appState by appViewModel.store.state.collectAsState()+ val isReady by appViewModel.isReady.collectAsState()+ if (!isReady) {+ Column(+ modifier = Modifier+ .fillMaxSize()+ .background(EnsuColor.backgroundBase()),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center+ ) {+ CircularProgressIndicator(color = EnsuColor.action())+ Spacer(Modifier.height(16.dp))+ Text("Preparing your model...", color = EnsuColor.textMuted())+ }+ return+ }RootView(appState = appState,store = appViewModel.store,diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.ktindex 79743983c3..3423d82536 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt@@ -21,7 +21,10 @@ import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.dropimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launch+import kotlinx.coroutines.withContextclass AppViewModel(application: Application) : AndroidViewModel(application) {private val sessionPreferences = SessionPreferencesDataStore(application)@@ -33,6 +36,8 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {val logRepository = FileLogRepository(application)private val modelDownloader = ModelDownloader(application)+ private val _isReady = MutableStateFlow(!modelDownloader.needsMigration())+ val isReady = _isReady.asStateFlow()private val llmProvider = LlmProvider(downloader = modelDownloader,transcriber = transcriber,@@ -55,11 +60,8 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {val launchMessage = "App launched app=$appVersion device=${Build.MANUFACTURER} ${Build.MODEL} os=${Build.VERSION.RELEASE} (sdk=${Build.VERSION.SDK_INT})"logRepository.log(LogLevel.Info, launchMessage, tag = "App")- viewModelScope.launch(Dispatchers.IO) {- modelDownloader.migrate()- }-viewModelScope.launch {+ withContext(Dispatchers.IO) { modelDownloader.migrate() }val initialSettings = runCatching {advancedSettingsDataStore.settingsFlow.first()}.getOrDefault(AdvancedSettingsSnapshot())@@ -69,6 +71,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {)store.hydrateModelDownloadRequested(sessionPreferences.modelDownloadRequested.first())store.bootstrap(viewModelScope)+ _isReady.value = trueadvancedSettingsDataStore.settingsFlow.drop(1).collectLatest { settings ->store.applyPersistedSettings(diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.ktindex ade686241b..58ab1b2d99 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt@@ -104,7 +104,7 @@ class LlmProvider(val mmprojPath = downloader.mmprojPath(target.downloadTarget)?.takeIf { File(it).exists() }?: return@withLock- ensureModelReadyLocked(target) { }+ ensureModelReadyLocked(target, onProgress = {})val context = loadedContext ?: return@withLockunloadTranscriptionModelIfLoaded()context.prewarmMultimodal(mmprojPath, null)@@ -171,7 +171,8 @@ class LlmProvider(private suspend fun ensureModelReadyLocked(target: LlmModelTarget,- onProgress: (DownloadProgress) -> Unit+ onProgress: (DownloadProgress) -> Unit,+ allowRecovery: Boolean = true) {deviceCapabilityProvider.chatCapability().requireChatSupported()val modelKey = LoadedModelKey(target.id, target.contextLength)@@ -186,10 +187,19 @@ class LlmProvider(unloadModel()- downloader.download(target.downloadTarget, onProgress)+ val downloaded = downloader.download(target.downloadTarget, onProgress)onProgress(DownloadProgress(100, "Loading model...", phase = DownloadPhase.Loading))- loadWithFallbacks(target, downloader.modelPath(target.downloadTarget))+ try {+ loadWithFallbacks(target, downloader.modelPath(target.downloadTarget))+ } catch (error: Throwable) {+ if (allowRecovery && !downloaded && downloader.removeDownloaded(target.downloadTarget)) {+ onProgress(DownloadProgress(0, "Starting download...", phase = DownloadPhase.Downloading))+ ensureModelReadyLocked(target, onProgress, allowRecovery = false)+ return+ }+ throw error+ }onProgress(DownloadProgress(100, "Ready", phase = DownloadPhase.Ready))}diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadJobService.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadJobService.ktindex e865687f1e..aff8906d07 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadJobService.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloadJobService.kt@@ -9,6 +9,7 @@ import android.content.ComponentNameimport android.content.Contextimport android.os.Buildimport android.os.SystemClock+import android.util.Logimport androidx.annotation.RequiresApiimport androidx.core.app.NotificationChannelCompatimport androidx.core.app.NotificationCompat@@ -44,6 +45,7 @@ class ModelDownloadJobService : JobService() {}companion object {+ private const val TAG = "ModelDownloadJob"private const val CHANNEL_ID = "model-download"private const val NOTIFICATION_ID = 1private const val JOB_ID = 1@@ -68,12 +70,22 @@ class ModelDownloadJobService : JobService() {downloadActive = truelastNotifyMs = 0L}- val scheduler = appContext.getSystemService(JobScheduler::class.java) ?: return+ val scheduler = appContext.getSystemService(JobScheduler::class.java)+ if (scheduler == null) {+ Log.w(TAG, "JobScheduler unavailable")+ return+ }val job = JobInfo.Builder(JOB_ID, ComponentName(appContext, ModelDownloadJobService::class.java)).setUserInitiated(true).setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build()- runCatching { scheduler.schedule(job) }+ val result = runCatching { scheduler.schedule(job) }.getOrElse { error ->+ Log.w(TAG, "Download job schedule failed", error)+ return+ }+ if (result != JobScheduler.RESULT_SUCCESS) {+ Log.w(TAG, "Download job not scheduled")+ }}fun update(percent: Int, indeterminate: Boolean) {diff --git a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloader.kt b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloader.ktindex bc9c996b85..8384ae0683 100644--- a/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloader.kt+++ b/mobile/native/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelDownloader.kt@@ -4,9 +4,10 @@ import android.content.Contextimport android.os.Environmentimport android.util.Logimport io.ente.ensu.bindings.ModelDownloadCallback-import io.ente.ensu.bindings.ModelDownloadProgressimport io.ente.ensu.bindings.ModelDownloadCore+import io.ente.ensu.bindings.ModelDownloadProgressimport io.ente.ensu.bindings.ModelDownloadTarget+import io.ente.ensu.bindings.migrateLegacyDirimport io.ente.ensu.bindings.uniffiEnsureInitializedimport java.io.Fileimport kotlin.coroutines.coroutineContext@@ -16,16 +17,22 @@ import kotlinx.coroutines.withContextclass ModelDownloader(context: Context) {private val appContext = context.applicationContext+ private val modelsDir = File(appContext.noBackupFilesDir, "models")+ private val legacyDir = appContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ ?.let { File(it, "llm") }private val core: ModelDownloadCoreinit {uniffiEnsureInitialized()ModelDownloadJobService.attach(appContext)- core = ModelDownloadCore(- File(appContext.noBackupFilesDir, "models").absolutePath,- appContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)- ?.let { File(it, "llm").absolutePath }- )+ core = ModelDownloadCore(modelsDir.absolutePath)+ }++ fun needsMigration(): Boolean = legacyDir?.exists() == true++ fun migrate() {+ File(appContext.filesDir, "llm").deleteRecursively()+ legacyDir?.let { migrateLegacyDir(modelsDir.absolutePath, it.absolutePath) }}val isDownloadActive: Boolean get() = core.isDownloadActive()@@ -36,24 +43,20 @@ class ModelDownloader(context: Context) {fun isDownloaded(target: ModelDownloadTarget): Boolean = core.isDownloaded(target)- fun cancel() = core.cancel()+ fun removeDownloaded(target: ModelDownloadTarget): Boolean = core.removeDownloaded(target)- fun migrate() {- File(appContext.filesDir, "llm").deleteRecursively()- core.migrate()- }+ fun cancel() = core.cancel()suspend fun estimateDownloadSize(target: ModelDownloadTarget): Long? = withContext(Dispatchers.IO) {core.estimatedDownloadSize(target)}- suspend fun download(target: ModelDownloadTarget, onProgress: (DownloadProgress) -> Unit) {+ suspend fun download(target: ModelDownloadTarget, onProgress: (DownloadProgress) -> Unit): Boolean {val downloadJob = coroutineContext[Job]- core.migrate()- if (core.isDownloaded(target)) return+ if (core.isDownloaded(target)) return falseModelDownloadJobService.begin { core.cancel() }- try {+ return try {core.download(target,object : ModelDownloadCallback {diff --git a/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloader.swift b/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloader.swiftindex 66ea212f01..1ca64d8120 100644--- a/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloader.swift+++ b/mobile/native/apple/apps/ensu/Ensu/Services/ModelDownloader.swift@@ -10,11 +10,11 @@ final class ModelDownloader {let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?? FileManager.default.temporaryDirectorylet modelsDir = baseDir.appendingPathComponent("models", isDirectory: true)- core = ModelDownloadCore(+ core = ModelDownloadCore(modelsDir: modelsDir.path)+ migrateLegacyDir(modelsDir: modelsDir.path,legacyDir: baseDir.appendingPathComponent("llm", isDirectory: true).path)- core.migrate()var excludedDir = modelsDirvar values = URLResourceValues()values.isExcludedFromBackup = true@@ -58,7 +58,6 @@ final class ModelDownloader {target: ModelDownloadTarget,onProgress: @escaping (DownloadProgress) -> Void) async throws -> Bool {- core.migrate()if core.isDownloaded(target: target) {return false}@@ -70,9 +69,10 @@ final class ModelDownloader {core.cancel()}}+ var succeeded = falsedefer {if #available(iOS 26.0, *) {- ModelDownloadBackgroundTask.end()+ ModelDownloadBackgroundTask.end(success: succeeded)}}@@ -102,6 +102,7 @@ final class ModelDownloader {core.cancel()downloadTask.cancel()}+ succeeded = truereturn true}}@@ -157,7 +158,11 @@ private enum ModelDownloadBackgroundTask {subtitle: "")request.strategy = .fail- try? BGTaskScheduler.shared.submit(request)+ do {+ try BGTaskScheduler.shared.submit(request)+ } catch {+ logger.warning("Background download task not scheduled", details: "\(error)")+ }}static func update(downloadedBytes: Int64, totalBytes: Int64?) {@@ -169,14 +174,14 @@ private enum ModelDownloadBackgroundTask {task.progress.completedUnitCount = min(downloadedBytes, totalBytes)}- static func end() {+ static func end(success: Bool) {lock.lock()downloadActive = falseonExpiration = nillet task = taskSelf.task = nillock.unlock()- task?.setTaskCompleted(success: true)+ task?.setTaskCompleted(success: success)}private static func adopt(_ bgTask: BGContinuedProcessingTask) {diff --git a/rust/bindings/uniffi/ensu/src/model_downloader.rs b/rust/bindings/uniffi/ensu/src/model_downloader.rsindex 8f61d6663e..b128763117 100644--- a/rust/bindings/uniffi/ensu/src/model_downloader.rs+++ b/rust/bindings/uniffi/ensu/src/model_downloader.rs@@ -1,4 +1,4 @@-use std::path::PathBuf;+use std::path::Path;use std::sync::Arc;use crate::download::DownloadError;@@ -58,6 +58,11 @@ pub trait ModelDownloadCallback: Send + Sync {fn is_cancelled(&self) -> bool;}+#[uniffi::export]+pub fn migrate_legacy_dir(models_dir: String, legacy_dir: String) {+ ente_model_download::migrate_legacy_dir(Path::new(&models_dir), Path::new(&legacy_dir));+}+#[derive(uniffi::Object)]pub struct ModelDownloadCore {inner: ente_model_download::ModelDownloader,@@ -66,12 +71,9 @@ pub struct ModelDownloadCore {#[uniffi::export]impl ModelDownloadCore {#[uniffi::constructor]- pub fn new(models_dir: String, legacy_dir: Option<String>) -> Arc<Self> {+ pub fn new(models_dir: String) -> Arc<Self> {Arc::new(Self {- inner: ente_model_download::ModelDownloader::new(- models_dir,- legacy_dir.map(PathBuf::from),- ),+ inner: ente_model_download::ModelDownloader::new(models_dir),})}@@ -97,10 +99,6 @@ impl ModelDownloadCore {self.inner.estimated_download_size(&target.into())}- pub fn migrate(&self) {- self.inner.migrate();- }-pub fn cancel(&self) {self.inner.cancel();}diff --git a/rust/crates/model-download/src/downloader.rs b/rust/crates/model-download/src/downloader.rsindex e7b2935b47..db1286cf46 100644--- a/rust/crates/model-download/src/downloader.rs+++ b/rust/crates/model-download/src/downloader.rs@@ -1,6 +1,5 @@use std::fs;use std::path::{Path, PathBuf};-use std::sync::Mutex;use std::sync::atomic::{AtomicBool, Ordering};use std::time::Duration;@@ -29,22 +28,18 @@ pub struct ModelDownloadProgress {pub struct ModelDownloader {models_dir: PathBuf,- legacy_dir: Option<PathBuf>,cancelled: AtomicBool,active: AtomicBool,- migration_done: Mutex<bool>,}impl ModelDownloader {- pub fn new(models_dir: impl Into<PathBuf>, legacy_dir: Option<PathBuf>) -> Self {+ pub fn new(models_dir: impl Into<PathBuf>) -> Self {let models_dir = models_dir.into();let _ = fs::create_dir_all(&models_dir);Self {models_dir,- legacy_dir,cancelled: AtomicBool::new(false),active: AtomicBool::new(false),- migration_done: Mutex::new(false),}}@@ -93,7 +88,6 @@ impl ModelDownloader {mut on_progress: impl FnMut(ModelDownloadProgress),is_cancelled: impl Fn() -> bool,) -> Result<bool, download::Error> {- self.migrate();if self.is_downloaded(target) {return Ok(false);}@@ -138,52 +132,6 @@ impl ModelDownloader {})}- /// Moves files from `<legacy_dir>/models` into the models dir via a- /// staged copy and rename, then discards the legacy dir. Retries on the- /// next call (or process) if any file could not be moved.- pub fn migrate(&self) {- let mut done = self.migration_done.lock().unwrap();- if *done {- return;- }- let Some(legacy_dir) = &self.legacy_dir else {- *done = true;- return;- };- if !legacy_dir.exists() {- *done = true;- return;- }-- let legacy_models = legacy_dir.join("models");- let mut all_moved = true;- for file in walk_files(&legacy_models) {- let Ok(relative) = file.strip_prefix(&legacy_models) else {- continue;- };- let dest = self.models_dir.join(relative);- if dest.exists() {- continue;- }- if let Some(parent) = dest.parent() {- let _ = fs::create_dir_all(parent);- }- if fs::rename(&file, &dest).is_ok() {- continue;- }- let staged = PathBuf::from(format!("{}.migrating", dest.display()));- let copied = fs::copy(&file, &staged).and_then(|_| fs::rename(&staged, &dest));- if copied.is_err() {- let _ = fs::remove_file(&staged);- all_moved = false;- }- }- if all_moved {- let _ = fs::remove_dir_all(legacy_dir);- *done = true;- }- }-fn expected_targets(&self, target: &ModelDownloadTarget) -> Vec<Target> {let ModelDownloadTarget::Gguf {id,@@ -263,6 +211,41 @@ pub fn format_bytes(bytes: u64) -> String {format!("{size:.1} {}", UNITS[unit])}+pub fn migrate_legacy_dir(models_dir: &Path, legacy_dir: &Path) {+ if !legacy_dir.exists() {+ return;+ }+ let legacy_models = legacy_dir.join("models");+ let mut all_moved = true;+ for file in walk_files(&legacy_models) {+ if file.extension().is_some_and(|ext| ext == "tmp") || !gguf::looks_like_gguf(&file) {+ continue;+ }+ let Ok(relative) = file.strip_prefix(&legacy_models) else {+ continue;+ };+ let dest = models_dir.join(relative);+ if dest.exists() {+ continue;+ }+ if let Some(parent) = dest.parent() {+ let _ = fs::create_dir_all(parent);+ }+ if fs::rename(&file, &dest).is_ok() {+ continue;+ }+ let staged = PathBuf::from(format!("{}.migrating", dest.display()));+ let copied = fs::copy(&file, &staged).and_then(|_| fs::rename(&staged, &dest));+ if copied.is_err() {+ let _ = fs::remove_file(&staged);+ all_moved = false;+ }+ }+ if all_moved {+ let _ = fs::remove_dir_all(legacy_dir);+ }+}+fn walk_files(dir: &Path) -> Vec<PathBuf> {let mut files = Vec::new();let Ok(entries) = fs::read_dir(dir) else {@@ -306,7 +289,7 @@ mod tests {#[test]fn paths_use_url_filenames_and_hash_custom_models() {let dir = scratch_dir("paths");- let downloader = ModelDownloader::new(&dir, None);+ let downloader = ModelDownloader::new(&dir);assert_eq!(downloader.model_path(&target("default:1")),@@ -331,7 +314,7 @@ mod tests {#[test]fn is_downloaded_requires_gguf_magic_on_all_files() {let dir = scratch_dir("is-downloaded");- let downloader = ModelDownloader::new(&dir, None);+ let downloader = ModelDownloader::new(&dir);let target = target("default:1");assert!(!downloader.is_downloaded(&target));@@ -351,7 +334,7 @@ mod tests {#[test]fn download_skips_when_already_present() {let dir = scratch_dir("skip");- let downloader = ModelDownloader::new(&dir, None);+ let downloader = ModelDownloader::new(&dir);let target = target("default:1");fs::write(dir.join("main.gguf"), b"GGUFdata").unwrap();fs::write(dir.join("mmproj.gguf"), b"GGUFdata").unwrap();@@ -365,24 +348,28 @@ mod tests {}#[test]- fn migrate_moves_files_and_discards_legacy_dir() {+ fn migrate_moves_models_and_discards_legacy_dir() {let base = scratch_dir("migrate");let legacy = base.join("llm");let legacy_models = legacy.join("models");fs::create_dir_all(legacy_models.join("custom")).unwrap();fs::write(legacy_models.join("main.gguf"), b"GGUFmain").unwrap();fs::write(legacy_models.join("custom/abc_x.gguf"), b"GGUFcustom").unwrap();- fs::write(legacy.join("stale.tmp"), b"junk").unwrap();+ fs::write(legacy_models.join("main.gguf.tmp"), b"GGUFpartial").unwrap();+ fs::write(legacy_models.join("main.gguf.tmp.ranges.json"), b"{}").unwrap();+ fs::write(legacy_models.join("main.gguf.metadata.json"), b"{}").unwrap();let models_dir = base.join("models");- let downloader = ModelDownloader::new(&models_dir, Some(legacy.clone()));- downloader.migrate();+ migrate_legacy_dir(&models_dir, &legacy);assert_eq!(fs::read(models_dir.join("main.gguf")).unwrap(), b"GGUFmain");assert_eq!(fs::read(models_dir.join("custom/abc_x.gguf")).unwrap(),b"GGUFcustom");+ assert!(!models_dir.join("main.gguf.tmp").exists());+ assert!(!models_dir.join("main.gguf.tmp.ranges.json").exists());+ assert!(!models_dir.join("main.gguf.metadata.json").exists());assert!(!legacy.exists());let _ = fs::remove_dir_all(base);@@ -399,8 +386,7 @@ mod tests {fs::create_dir_all(&models_dir).unwrap();fs::write(models_dir.join("main.gguf"), b"GGUFnew").unwrap();- let downloader = ModelDownloader::new(&models_dir, Some(legacy.clone()));- downloader.migrate();+ migrate_legacy_dir(&models_dir, &legacy);assert_eq!(fs::read(models_dir.join("main.gguf")).unwrap(), b"GGUFnew");assert!(!legacy.exists());diff --git a/rust/crates/model-download/src/lib.rs b/rust/crates/model-download/src/lib.rsindex 732c0d7faf..4ec5bad2a1 100644--- a/rust/crates/model-download/src/lib.rs+++ b/rust/crates/model-download/src/lib.rs@@ -2,4 +2,6 @@ pub mod download;mod downloader;pub mod gguf;-pub use downloader::{ModelDownloadProgress, ModelDownloadTarget, ModelDownloader};+pub use downloader::{+ ModelDownloadProgress, ModelDownloadTarget, ModelDownloader, migrate_legacy_dir,+};