π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
fix(ensu): harden model download flows and settings cleanup
Prateek Sunal642dfb0c1f4c
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.ktindex 609eb3c37c..0c61601189 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt@@ -135,7 +135,6 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {private fun resolveModelDir(application: Application): File {val root = application.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?: application.getExternalFilesDir(null)- ?: application.externalCacheDir?: application.filesDirreturn File(root, "llm")}diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.ktindex 62780f8464..f3e067b804 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatMessages.kt@@ -600,13 +600,29 @@ private fun AssistantMessageBubble(modifier = Modifier.fillMaxWidth(),horizontalAlignment = Alignment.Start) {+ val actions = buildList {+ if (!message.isSynthetic) {+ add(MessageAction("Copy", HugeIcons.Copy01Icon) {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ clipboard.setText(AnnotatedString(stripHiddenMessageParts(message.text)))+ })+ }+ if (!message.isSynthetic || isLastMessage) {+ add(MessageAction("Retry", HugeIcons.RepeatIcon) {+ haptic.perform(HapticFeedbackType.TextHandleMove)+ onRetry()+ })+ }+ }+Box {Column(modifier = Modifier.fillMaxWidth()- .pointerInput(Unit) {+ .pointerInput(message.id, message.isSynthetic, isLastMessage) {detectTapGestures(onLongPress = { offset ->+ if (actions.isEmpty()) return@detectTapGestureshaptic.perform(HapticFeedbackType.LongPress)pressOffset = offsetshowMenu = true@@ -634,20 +650,7 @@ private fun AssistantMessageBubble(showMenu = showMenu,pressOffset = pressOffset,onDismiss = { showMenu = false },- actions = buildList {- if (!message.isSynthetic) {- add(MessageAction("Copy", HugeIcons.Copy01Icon) {- haptic.perform(HapticFeedbackType.TextHandleMove)- clipboard.setText(AnnotatedString(stripHiddenMessageParts(message.text)))- })- }- if (!message.isSynthetic || isLastMessage) {- add(MessageAction("Retry", HugeIcons.RepeatIcon) {- haptic.perform(HapticFeedbackType.TextHandleMove)- onRetry()- })- }- }+ actions = actions)}@@ -693,7 +696,7 @@ private fun MessageActionsMenu(onDismiss: () -> Unit,actions: List<MessageAction>) {- if (!showMenu) return+ if (!showMenu || actions.isEmpty()) returnval menuSurface = if (isSystemInDarkTheme()) Color(0xFF1C1C1E) else Color.Whiteval offset = IntOffset(pressOffset.x.roundToInt(), pressOffset.y.roundToInt())diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.ktindex 45cc8ae362..4c74f0739a 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt@@ -375,7 +375,9 @@ class InferenceRsProvider(return}ensureDownloadsEnqueued(target)+ val maxPolls = 7_200var emptyPollCount = 0+ var pollCount = 0while (true) {val progress = currentDownloadProgress(target)if (progress == null) {@@ -394,6 +396,10 @@ class InferenceRsProvider(}onProgress(progress)}+ pollCount += 1+ if (pollCount >= maxPolls) {+ throw IOException("Download timed out")+ }delay(500)}}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.ktindex 51713699e5..ff373a581c 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt@@ -141,11 +141,8 @@ class AppStore(developerSettings: DeveloperSettingsState,modelSettings: ModelSettingsState) {- _state.value = _state.value.copy(- developerSettings = developerSettings,- modelSettings = modelSettings- )- modelSettingsActions.refreshModelDownloadInfo()+ _state.value = _state.value.copy(developerSettings = developerSettings)+ modelSettingsActions.updateModelSettings(modelSettings)}fun signIn(email: String) = authActions.signIn(email)diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swiftindex 3bab90cbec..abafca6e8b 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift@@ -1193,6 +1193,7 @@ final class ChatViewModel: ObservableObject {func refreshModelDownloadInfo() {let target = modelSettings.currentTarget()+ provider.cancelStaleDownloads(target: target)isModelDownloaded = provider.isModelDownloaded(target: target)if isModelDownloaded {downloadProgressMonitorTask?.cancel()@@ -1295,6 +1296,7 @@ final class ChatViewModel: ObservableObject {}let target = modelSettings.currentTarget()+ provider.cancelStaleDownloads(target: target)let isDownloaded = provider.isModelDownloaded(target: target)if isDownloaded {isModelDownloaded = truediff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swiftindex aa70b3405b..f67b3b984e 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift@@ -244,6 +244,13 @@ final class InferenceRsProvider {}}+ func cancelStaleDownloads(target: InferenceModelTarget) {+ let targets = expectedTargets(for: target).map(downloadTarget(for:))+ Task {+ await downloadManager.cancelDownloads(except: targets)+ }+ }+func isModelDownloaded(target: InferenceModelTarget) -> Bool {let modelPath = modelPathFor(target: target)if !FileManager.default.fileExists(atPath: modelPath.path) {@@ -363,7 +370,7 @@ final class InferenceRsProvider {if size <= 0 {return true}- return !looksLikeGguf(file: url)+ return !url.looksLikeGgufFile}private func recoverFromCachedModelLoadFailure(modelPath: URL, mmprojPath: URL?) -> Bool {@@ -379,15 +386,6 @@ final class InferenceRsProvider {return removedAny}- private func looksLikeGguf(file: URL) -> Bool {- guard let handle = try? FileHandle(forReadingFrom: file) else { return false }- let data = handle.readData(ofLength: 4)- try? handle.close()- guard data.count == 4 else { return false }- let header = String(decoding: data, as: UTF8.self)- return header == "GGUF"- }-private func modelPathFor(target: InferenceModelTarget) -> URL {let base = modelDir.appendingPathComponent("models", isDirectory: true)let filename = URL(string: target.url)?.lastPathComponent ?? "model.gguf"@@ -518,6 +516,10 @@ final class InferenceRsProvider {func cancelDownload() {}+ func cancelStaleDownloads(target: InferenceModelTarget) {+ _ = target+ }+func isModelDownloaded(target: InferenceModelTarget) -> Bool {_ = targetreturn falsediff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/ModelDownloadManager.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelDownloadManager.swiftindex eb505a49be..c0850280b3 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Services/ModelDownloadManager.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelDownloadManager.swift@@ -41,7 +41,7 @@ final class ModelDownloadManager: NSObject {configuration.sessionSendsLaunchEvents = true#endifconfiguration.isDiscretionary = false- configuration.waitsForConnectivity = true+ configuration.waitsForConnectivity = truereturn URLSession(configuration: configuration, delegate: self, delegateQueue: delegateQueue)}()@@ -156,6 +156,20 @@ final class ModelDownloadManager: NSObject {clearAllRecords()}+ func cancelDownloads(except targets: [ModelDownloadTarget]) async {+ let allowedIds = Set(targets.map { recordId(for: $0.destination) })+ let tasks = await allTasks()+ tasks.forEach { task in+ guard let taskId = task.taskDescription, !allowedIds.contains(taskId) else { return }+ task.cancel()+ }+ mutateRecords { records in+ records.keys+ .filter { !allowedIds.contains($0) }+ .forEach { records.removeValue(forKey: $0) }+ }+ }+private func allTasks() async -> [URLSessionTask] {await withCheckedContinuation { continuation insession.getAllTasks { tasks in@@ -323,7 +337,7 @@ extension ModelDownloadManager: URLSessionDownloadDelegate, URLSessionTaskDelega}}-private extension URL {+extension URL {var looksLikeGgufFile: Bool {guard let handle = try? FileHandle(forReadingFrom: self) else { return false }let data = handle.readData(ofLength: 4)diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex efa2ac9d6c..a4900de734 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -19,7 +19,7 @@ import { savedLocalUser } from "ente-accounts/services/accounts-db";import { openAccountsManagePasskeysPage } from "ente-accounts/services/passkey";import { NavbarBase } from "ente-base/components/Navbar";import { useBaseContext } from "ente-base/context";-import { getKV } from "ente-base/kv";+import { getKV, removeKV } from "ente-base/kv";import log from "ente-base/log";import { savedLogs } from "ente-base/log-web";import { savedAuthToken } from "ente-base/token";@@ -1291,6 +1291,7 @@ const Page: React.FC = () => {setMmprojUrl(canMmproj ? (parsed.mmprojUrl ?? "") : "");setContextLength(clampedContextLength);setMaxTokens(parsed.maxTokens ?? "");+ void removeKV(MODEL_SETTINGS_STORAGE_KEY);});return;}@@ -3602,6 +3603,7 @@ const Page: React.FC = () => {const handleUseDefaultModel = useCallback(() => {if (typeof window !== "undefined") {window.localStorage.removeItem(MODEL_SETTINGS_STORAGE_KEY);+ void removeKV(MODEL_SETTINGS_STORAGE_KEY);}setUseCustomModel(false);setModelUrl("");