π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Check RAM before loading models
laurenspriem4dbd0c29982c
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 20e31de0a2..65f7c89e6a 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@@ -8,6 +8,7 @@ import androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScopeimport io.ente.ensu.data.AdvancedSettingsDataStoreimport io.ente.ensu.data.AdvancedSettingsSnapshot+import io.ente.ensu.data.AndroidDeviceCapabilityProviderimport io.ente.ensu.data.EndpointPreferencesDataStoreimport io.ente.ensu.data.SessionPreferencesDataStoreimport io.ente.ensu.data.auth.EnsuAuthService@@ -31,12 +32,14 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {val advancedSettingsDataStore = AdvancedSettingsDataStore(application)private val credentialStore = CredentialStore(application)val appVersion = runCatching { getAppVersion(application) }.getOrDefault("unknown")+ private val deviceCapabilityProvider = AndroidDeviceCapabilityProvider(application)val logRepository = FileLogRepository(application)private val llmProvider = InferenceRsProvider(context = application,modelDir = resolveModelDir(application),- legacyModelDir = File(application.filesDir, "llm")+ legacyModelDir = File(application.filesDir, "llm"),+ deviceCapabilityProvider = deviceCapabilityProvider)private val chatRepository = RustChatRepository(application, credentialStore)private val chatSyncRepository = RustChatSyncRepository(@@ -61,6 +64,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {chatRepository = chatRepository,chatSyncRepository = chatSyncRepository,llmProvider = llmProvider,+ deviceCapabilityProvider = deviceCapabilityProvider,ensuDefaults = ensuDefaults,logRepository = logRepository)diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.ktindex 36f1590ad5..754b99a13e 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt@@ -141,6 +141,7 @@ internal fun HomeNavigation(onStartDownload = { userInitiated ->store.startModelDownload(userInitiated = userInitiated)},+ onDismissUnsupportedDeviceDialog = store::dismissUnsupportedDeviceDialog,onOverflowTrim = store::confirmOverflowTrim,onOverflowCancel = store::cancelOverflowDialog)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 73b20d5d8c..e1ce3c0b3e 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@@ -92,6 +92,7 @@ internal fun MessageList(streamingParentId: String?,isGenerating: Boolean,isModelDownloaded: Boolean,+ isChatUnsupported: Boolean,isDownloading: Boolean,downloadPercent: Int?,downloadStatus: String?,@@ -104,7 +105,7 @@ internal fun MessageList(onStartDownload: (Boolean) -> Unit) {if (messages.isEmpty() && !isGenerating) {- if (!isModelDownloaded) {+ if (!isModelDownloaded && !isChatUnsupported) {DownloadOnboarding(modifier = modifier,isDownloading = isDownloading,diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatOverlays.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatOverlays.ktindex ae4a7d5567..4a2dbc0033 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatOverlays.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatOverlays.kt@@ -29,6 +29,7 @@ import io.ente.ensu.designsystem.EnsuCornerRadiusimport io.ente.ensu.designsystem.EnsuSpacingimport io.ente.ensu.designsystem.EnsuTypographyimport io.ente.ensu.designsystem.HugeIcons+import io.ente.ensu.domain.device.ChatDeviceCapabilityimport io.ente.ensu.domain.state.OverflowDialogStateimport io.ente.ensu.domain.util.formatBytesimport io.ente.ensu.utils.rememberEnsuHaptics@@ -66,6 +67,61 @@ internal fun OverflowDialog()}+@Composable+internal fun UnsupportedDeviceDialog(+ capability: ChatDeviceCapability.UnsupportedLowMemory,+ onDismiss: () -> Unit+) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(text = "Chat unavailable on this device", style = EnsuTypography.h3) },+ text = {+ Text(+ text = unsupportedDeviceMessage(capability),+ style = EnsuTypography.body,+ color = EnsuColor.textPrimary()+ )+ },+ confirmButton = {+ TextButton(onClick = onDismiss) {+ Text(text = "Got it", color = EnsuColor.textPrimary())+ }+ },+ containerColor = EnsuColor.backgroundBase()+ )+}++@Composable+internal fun UnsupportedChatInputNotice(+ capability: ChatDeviceCapability.UnsupportedLowMemory,+ modifier: Modifier = Modifier+) {+ Column(+ modifier = modifier+ .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.md.dp)+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.card.dp))+ .padding(EnsuSpacing.md.dp)+ ) {+ Text(+ text = "Chat unavailable on this device",+ style = EnsuTypography.large,+ color = EnsuColor.textPrimary()+ )+ Text(+ text = unsupportedDeviceMessage(capability),+ style = EnsuTypography.body,+ color = EnsuColor.textMuted(),+ modifier = Modifier.padding(top = EnsuSpacing.xs.dp)+ )+ }+}++private fun unsupportedDeviceMessage(capability: ChatDeviceCapability.UnsupportedLowMemory): String =+ "Ensu runs the AI model locally and needs at least 4 GB of RAM. " ++ "This device does not have enough memory for chat. " ++ "You can still view existing chats, but sending new messages is disabled. " ++ "Reported memory: ${formatBytes(capability.totalMemoryBytes)}."+@Composableinternal fun DownloadToastOverlay(status: String,diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.ktindex 1ac7457b30..3e3f791691 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt@@ -47,6 +47,7 @@ import androidx.compose.ui.unit.dpimport androidx.core.content.ContextCompatimport io.ente.ensu.designsystem.EnsuColorimport io.ente.ensu.designsystem.EnsuSpacing+import io.ente.ensu.domain.device.ChatDeviceCapabilityimport io.ente.ensu.domain.model.Attachmentimport io.ente.ensu.domain.model.AttachmentTypeimport io.ente.ensu.domain.model.ChatMessage@@ -69,6 +70,7 @@ fun ChatView(onBranchChange: (String, Int) -> Unit,onOpenAttachment: (Attachment) -> Unit,onStartDownload: (Boolean) -> Unit,+ onDismissUnsupportedDeviceDialog: () -> Unit,onOverflowTrim: () -> Unit,onOverflowCancel: () -> Unit) {@@ -79,6 +81,8 @@ fun ChatView(val latestOnMessageChange by rememberUpdatedState(onMessageChange)val sessionKey = chatState.currentSessionId ?: "new-session"val latestSessionKey by rememberUpdatedState(sessionKey)+ val unsupportedCapability = chatState.deviceCapability as? ChatDeviceCapability.UnsupportedLowMemory+ val isChatUnsupported = unsupportedCapability != nullvar pendingVoiceSessionKey by remember { mutableStateOf<String?>(null) }val voiceController = rememberVoiceTranscriptionController(onTranscript = { transcript ->@@ -96,6 +100,7 @@ fun ChatView(val canStartVoiceInput = !chatState.isGenerating &&!chatState.isDownloading &&!chatState.isAttachmentDownloadBlocked &&+ !isChatUnsupported &&editingMessage == nullval latestCanStartVoiceInput by rememberUpdatedState(canStartVoiceInput)@@ -118,12 +123,14 @@ fun ChatView(val showDownloadOnboarding by remember(chatState.isModelDownloaded,chatState.messages,- chatState.isGenerating+ chatState.isGenerating,+ isChatUnsupported) {derivedStateOf {!chatState.isModelDownloaded &&chatState.messages.isEmpty() &&- !chatState.isGenerating+ !chatState.isGenerating &&+ !isChatUnsupported}}@@ -134,6 +141,7 @@ fun ChatView(val shouldAutoFocusInput = chatState.isModelDownloaded &&!showDownloadOnboarding &&+ !isChatUnsupported &&!chatState.isDownloading &&!chatState.isGenerating &&!didAutoFocusInput &&@@ -156,6 +164,7 @@ fun ChatView(if (wasDrawerOpen) {val shouldRestoreFocus = chatState.isModelDownloaded &&!showDownloadOnboarding &&+ !isChatUnsupported &&!chatState.isDownloading &&!chatState.isGeneratingif (shouldRestoreFocus) {@@ -206,6 +215,7 @@ fun ChatView(streamingParentId = chatState.streamingParentId,isGenerating = chatState.isGenerating,isModelDownloaded = chatState.isModelDownloaded,+ isChatUnsupported = isChatUnsupported,isDownloading = chatState.isDownloading,downloadPercent = chatState.downloadPercent,downloadStatus = chatState.downloadStatus,@@ -228,7 +238,18 @@ fun ChatView()}- if (!showDownloadOnboarding) {+ if (unsupportedCapability != null) {+ UnsupportedChatInputNotice(+ capability = unsupportedCapability,+ modifier = Modifier+ .fillMaxWidth()+ .navigationBarsPadding()+ .background(EnsuColor.backgroundBase())+ .onGloballyPositioned { coords ->+ inputBarHeightDp = with(density) { coords.size.height.toDp() }+ }+ )+ } else if (!showDownloadOnboarding) {MessageInput(modifier = Modifier.fillMaxWidth()@@ -280,6 +301,13 @@ fun ChatView(}}+ if (chatState.showUnsupportedDeviceDialog && unsupportedCapability != null) {+ UnsupportedDeviceDialog(+ capability = unsupportedCapability,+ onDismiss = onDismissUnsupportedDeviceDialog+ )+ }+val imeVisible = WindowInsets.ime.getBottom(density) > 0if (imeVisible && inputBarHeightDp > 0.dp) {IconButton(diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/AndroidDeviceCapabilityProvider.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/AndroidDeviceCapabilityProvider.ktnew file mode 100644index 0000000000..8122fcbd8a--- /dev/null+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/AndroidDeviceCapabilityProvider.kt@@ -0,0 +1,24 @@+package io.ente.ensu.data++import android.app.ActivityManager+import android.content.Context+import io.ente.ensu.domain.device.CHAT_MIN_RAM_BYTES+import io.ente.ensu.domain.device.ChatDeviceCapability+import io.ente.ensu.domain.device.DeviceCapabilityProvider++class AndroidDeviceCapabilityProvider(context: Context) : DeviceCapabilityProvider {+ private val appContext = context.applicationContext++ override fun chatCapability(): ChatDeviceCapability {+ val activityManager = appContext.getSystemService(ActivityManager::class.java)+ ?: return ChatDeviceCapability.Unknown+ val memoryInfo = ActivityManager.MemoryInfo()+ activityManager.getMemoryInfo(memoryInfo)+ val totalMemoryBytes = memoryInfo.totalMem+ return if (totalMemoryBytes < CHAT_MIN_RAM_BYTES) {+ ChatDeviceCapability.UnsupportedLowMemory(totalMemoryBytes)+ } else {+ ChatDeviceCapability.Supported(totalMemoryBytes)+ }+ }+}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 2110bc3131..bb726b4d38 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@@ -5,6 +5,9 @@ import android.content.Contextimport android.net.Uriimport android.os.Environmentimport android.util.Log+import io.ente.ensu.domain.device.DeviceCapabilityProvider+import io.ente.ensu.domain.device.UnknownDeviceCapabilityProvider+import io.ente.ensu.domain.device.requireChatSupportedimport io.ente.ensu.domain.llm.DownloadProgressimport io.ente.ensu.domain.llm.GenerationSummaryimport io.ente.ensu.domain.llm.LlmMessage@@ -53,6 +56,7 @@ class InferenceRsProvider(context: Context,private val modelDir: File,private val legacyModelDir: File? = null,+ private val deviceCapabilityProvider: DeviceCapabilityProvider = UnknownDeviceCapabilityProvider,private val ioDispatcher: kotlinx.coroutines.CoroutineDispatcher = Dispatchers.IO) : LlmProvider {private data class LoadedModelKey(@@ -121,6 +125,7 @@ class InferenceRsProvider(maxTokens: Int?,onToken: (String) -> Unit): GenerationSummary = withContext(ioDispatcher) {+ deviceCapabilityProvider.chatCapability().requireChatSupported()val context = contextHandle ?: throw IllegalStateException("Model context not loaded")currentJobId = nullval mmprojPath = if (imageFiles.isEmpty()) {@@ -362,6 +367,7 @@ class InferenceRsProvider(target: LlmModelTarget,onProgress: (DownloadProgress) -> Unit) {+ deviceCapabilityProvider.chatCapability().requireChatSupported()val modelKey = LoadedModelKey(target.id, target.contextLength)if (!backendInitialized) {initBackend()diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/device/ChatDeviceCapability.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/device/ChatDeviceCapability.ktnew file mode 100644index 0000000000..ccd1897ab1--- /dev/null+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/device/ChatDeviceCapability.kt@@ -0,0 +1,41 @@+package io.ente.ensu.domain.device++const val CHAT_MIN_RAM_BYTES: Long = 4_000_000_000L++sealed interface ChatDeviceCapability {+ val totalMemoryBytes: Long?++ data class Supported(+ override val totalMemoryBytes: Long?+ ) : ChatDeviceCapability++ data class UnsupportedLowMemory(+ override val totalMemoryBytes: Long,+ val requiredMemoryBytes: Long = CHAT_MIN_RAM_BYTES+ ) : ChatDeviceCapability++ object Unknown : ChatDeviceCapability {+ override val totalMemoryBytes: Long? = null+ }+}++interface DeviceCapabilityProvider {+ fun chatCapability(): ChatDeviceCapability+}++object UnknownDeviceCapabilityProvider : DeviceCapabilityProvider {+ override fun chatCapability(): ChatDeviceCapability = ChatDeviceCapability.Unknown+}++class UnsupportedDeviceMemoryException(+ val capability: ChatDeviceCapability.UnsupportedLowMemory+) : IllegalStateException("Device does not have enough RAM for local chat")++fun ChatDeviceCapability.isChatSupported(): Boolean =+ this !is ChatDeviceCapability.UnsupportedLowMemory++fun ChatDeviceCapability.requireChatSupported() {+ if (this is ChatDeviceCapability.UnsupportedLowMemory) {+ throw UnsupportedDeviceMemoryException(this)+ }+}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.ktindex 224cee0ed1..1a7e113f80 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt@@ -1,5 +1,6 @@package io.ente.ensu.domain.state+import io.ente.ensu.domain.device.ChatDeviceCapabilityimport io.ente.ensu.domain.model.Attachmentimport io.ente.ensu.domain.model.ChatMessageimport io.ente.ensu.domain.model.ChatSession@@ -28,6 +29,8 @@ data class ChatState(val isModelDownloaded: Boolean = false,val modelDownloadSizeBytes: Long? = null,val hasRequestedModelDownload: Boolean = false,+ val deviceCapability: ChatDeviceCapability = ChatDeviceCapability.Unknown,+ val showUnsupportedDeviceDialog: Boolean = false,val overflowDialog: OverflowDialogState? = null)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 34826ff49e..d3203cd75e 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@@ -2,12 +2,16 @@ package io.ente.ensu.domain.storeimport io.ente.ensu.domain.chat.ChatRepositoryimport io.ente.ensu.domain.chat.ChatSyncRepository+import io.ente.ensu.domain.device.ChatDeviceCapability+import io.ente.ensu.domain.device.DeviceCapabilityProvider+import io.ente.ensu.domain.device.UnknownDeviceCapabilityProviderimport io.ente.ensu.domain.llm.LlmProviderimport io.ente.ensu.domain.logging.LogRepositoryimport io.ente.ensu.domain.logging.NoOpLogRepositoryimport io.ente.ensu.domain.model.Attachmentimport io.ente.ensu.domain.model.ChatMessageimport io.ente.ensu.domain.model.EnsuDefaults+import io.ente.ensu.domain.model.LogLevelimport io.ente.ensu.domain.preferences.SessionPreferencesimport io.ente.ensu.domain.state.AppStateimport io.ente.ensu.domain.state.DeveloperSettingsState@@ -16,12 +20,14 @@ import kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launchclass AppStore(private val sessionPreferences: SessionPreferences,private val chatRepository: ChatRepository,private val chatSyncRepository: ChatSyncRepository? = null,private val llmProvider: LlmProvider,+ private val deviceCapabilityProvider: DeviceCapabilityProvider = UnknownDeviceCapabilityProvider,val ensuDefaults: EnsuDefaults,private val clock: () -> Long = { System.currentTimeMillis() },private val logRepository: LogRepository = NoOpLogRepository@@ -60,10 +66,45 @@ class AppStore(attachmentActions.setScope(scope)syncActions.setScope(scope)modelSettingsActions.setScope(scope)+ refreshDeviceCapability(scope)chatActions.bootstrap(scope)modelSettingsActions.refreshModelDownloadInfo()}+ fun refreshDeviceCapability(scope: CoroutineScope? = null) {+ val capability = deviceCapabilityProvider.chatCapability()+ val unsupported = capability is ChatDeviceCapability.UnsupportedLowMemory+ _state.value = _state.value.copy(+ chat = _state.value.chat.copy(+ deviceCapability = capability,+ showUnsupportedDeviceDialog = unsupported || _state.value.chat.showUnsupportedDeviceDialog,+ isDownloading = if (unsupported) false else _state.value.chat.isDownloading,+ downloadPercent = if (unsupported) null else _state.value.chat.downloadPercent,+ downloadStatus = if (unsupported) null else _state.value.chat.downloadStatus,+ hasRequestedModelDownload = if (unsupported) false else _state.value.chat.hasRequestedModelDownload+ )+ )+ if (unsupported) {+ scope?.let { coroutineScope ->+ coroutineScope.launch {+ sessionPreferences.setModelDownloadRequested(false)+ }+ }+ }+ logRepository.log(+ LogLevel.Info,+ "Chat device capability evaluated",+ details = "capability=$capability",+ tag = "App"+ )+ }++ fun dismissUnsupportedDeviceDialog() {+ _state.value = _state.value.copy(+ chat = _state.value.chat.copy(showUnsupportedDeviceDialog = false)+ )+ }+fun hydrateModelDownloadRequested(requested: Boolean) {if (!requested) return_state.value = _state.value.copy(diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.ktindex b1f46439e4..3c8f932982 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt@@ -1,6 +1,7 @@package io.ente.ensu.domain.storeimport io.ente.ensu.domain.chat.ChatRepository+import io.ente.ensu.domain.device.isChatSupportedimport io.ente.ensu.domain.logging.LogRepositoryimport io.ente.ensu.domain.llm.LlmMessageimport io.ente.ensu.domain.llm.LlmMessageRole@@ -286,6 +287,7 @@ internal class ChatStoreActions(if (state.value.chat.isGenerating) {stopGeneration()}+ if (!state.value.chat.deviceCapability.isChatSupported()) returnval sessionId = state.value.chat.currentSessionId ?: return// For synthetic interrupted placeholders, find the parent user message directly@@ -311,6 +313,7 @@ internal class ChatStoreActions(fun sendMessage() {val currentState = state.valueif (currentState.chat.isGenerating || currentState.chat.isDownloading) return+ if (!currentState.chat.deviceCapability.isChatSupported()) returnval text = currentState.chat.messageText.trim()val attachments = currentState.chat.attachmentsif (text.isEmpty() && attachments.isEmpty()) return@@ -455,6 +458,7 @@ internal class ChatStoreActions(private fun startGeneration(sessionId: String, userMessage: ChatMessage) {val scope = scope ?: return+ if (!state.value.chat.deviceCapability.isChatSupported()) returngenerationJob?.cancel()sessionSummaryJob?.cancel()stopRequested = false@@ -795,6 +799,9 @@ internal class ChatStoreActions(fallback: String,target: LlmModelTarget): String? {+ if (!state.value.chat.deviceCapability.isChatSupported()) {+ return sessionTitleFromText(fallback, fallback = fallback)+ }if (!llmProvider.isModelDownloaded(target)) {return sessionTitleFromText(fallback, fallback = fallback)}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.ktindex 2235fdb854..e3bda13767 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt@@ -1,5 +1,6 @@package io.ente.ensu.domain.store+import io.ente.ensu.domain.device.isChatSupportedimport io.ente.ensu.domain.llm.LlmModelTargetimport io.ente.ensu.domain.llm.LlmProviderimport io.ente.ensu.domain.logging.LogRepository@@ -62,6 +63,24 @@ internal class ModelSettingsActions(}fun refreshModelDownloadInfo() {+ if (!state.value.chat.deviceCapability.isChatSupported()) {+ downloadProgressMonitorJob?.cancel()+ modelDownloadJob?.cancel()+ llmProvider.cancelDownload()+ persistModelDownloadRequested(false)+ state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isDownloading = false,+ downloadPercent = null,+ downloadStatus = null,+ modelDownloadSizeBytes = null,+ hasRequestedModelDownload = false+ )+ )+ }+ return+ }val target = resolveTarget(state.value.modelSettings)val isDownloaded = llmProvider.isModelDownloaded(target)if (isDownloaded) {@@ -130,6 +149,7 @@ internal class ModelSettingsActions(fun startModelDownload(userInitiated: Boolean = true) {val scope = scope ?: returnval currentState = state.value+ if (!currentState.chat.deviceCapability.isChatSupported()) returnif (modelDownloadJob?.isActive == true) returnif (currentState.chat.isDownloading || currentState.chat.isGenerating) returnif (!userInitiated && !currentState.chat.hasRequestedModelDownload) return@@ -256,6 +276,7 @@ internal class ModelSettingsActions(val scope = scope ?: returnval currentState = state.valueif (currentState.chat.isGenerating || currentState.chat.isDownloading) return+ if (!currentState.chat.deviceCapability.isChatSupported()) returnval target = resolveTarget(currentState.modelSettings)if (!llmProvider.isModelDownloaded(target)) returndiff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swiftindex 8d0d13397a..a93f299f5e 100644--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatView.swift@@ -28,6 +28,7 @@ struct ChatView: View {private var shouldAutoFocusInput: Bool {viewModel.isModelDownloaded+ && !viewModel.isChatUnsupported&& !viewModel.isDownloading&& !viewModel.isGenerating&& !viewState.didAutoFocusInput@@ -125,6 +126,7 @@ struct ChatView: View {viewState.wasDrawerOpen = true} else if viewState.wasDrawerOpen {let shouldRestoreFocus = viewModel.isModelDownloaded+ && !viewModel.isChatUnsupported&& !viewModel.isDownloading&& !viewModel.isGenerating&& !viewState.didDismissKeyboard@@ -201,6 +203,13 @@ struct ChatView: View {secondaryButton: .cancel())}+ .alert("Chat unavailable on this device", isPresented: $viewModel.showUnsupportedDeviceDialog) {+ Button("Got it") {+ viewModel.dismissUnsupportedDeviceDialog()+ }+ } message: {+ Text(viewModel.unsupportedDeviceMessage)+ }.confirmationDialog("Conversation too long", isPresented: overflowDialogPresented, titleVisibility: .visible) {Button("Continue") {viewModel.confirmOverflowTrim()@@ -277,7 +286,7 @@ struct ChatView: View {.animation(.easeInOut(duration: 0.32))ZStack(alignment: .bottom) {- let shouldShowDownloadOnboarding = !viewModel.isModelDownloaded+ let shouldShowDownloadOnboarding = !viewModel.isModelDownloaded && !viewModel.isChatUnsupportedMessageListView(messages: viewModel.messages,@@ -286,7 +295,7 @@ struct ChatView: View {isGenerating: viewModel.isGenerating,sessionId: viewModel.currentSessionId,keyboardHeight: keyboard.height,- inputBarHeight: viewModel.isModelDownloaded ? viewState.inputBarHeight : 0,+ inputBarHeight: (viewModel.isModelDownloaded || viewModel.isChatUnsupported) ? viewState.inputBarHeight : 0,emptyStateTitle: "Welcome",emptyStateSubtitle: "Start typing to begin a conversation",onEdit: { message in@@ -318,7 +327,15 @@ struct ChatView: View {}.zIndex(0)- if viewModel.isModelDownloaded {+ if viewModel.isChatUnsupported {+ UnsupportedChatInputNotice(message: viewModel.unsupportedDeviceMessage)+ .frame(maxWidth: .infinity, alignment: .bottom)+ .onPreferenceChange(InputBarHeightKey.self) { newValue in+ viewState.inputBarHeight = newValue+ }+ .padding(.bottom, keyboard.isVisible ? keyboard.height : 0)+ .zIndex(1)+ } else if viewModel.isModelDownloaded {let shouldAutoFocus = shouldAutoFocusInputMessageInputView(diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swiftindex cdb4ed9e30..337c1878dd 100644--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/ChatViewModel.swift@@ -458,6 +458,8 @@ final class ChatViewModel: ObservableObject {@Published var isModelDownloaded: Bool = false@Published var modelDownloadSizeBytes: Int64?@Published var hasRequestedModelDownload: Bool = false+ @Published var deviceCapability: ChatDeviceCapability = .unknown+ @Published var showUnsupportedDeviceDialog: Bool = false@Published var attachmentDownloads: [AttachmentDownloadItem] = []@Published var currentSessionMissingAttachments: [AttachmentDownloadItem] = []@Published var syncState: SyncState = .idle@@ -468,6 +470,7 @@ final class ChatViewModel: ObservableObject {@Published var draftCursorMoveToken = UUID()private let provider: InferenceRsProvider+ private let deviceCapabilityProvider = ProcessInfoChatDeviceCapabilityProvider()private let voiceTranscriber: VoiceTranscriptionServiceprivate var chatDb: EnsuDbprivate var syncEngine: EnsuSync@@ -602,9 +605,47 @@ final class ChatViewModel: ObservableObject {refreshAttachmentDownloadState()}+ refreshDeviceCapability()refreshModelDownloadInfo()}+ var isChatUnsupported: Bool {+ !deviceCapability.isChatSupported+ }++ var unsupportedDeviceMessage: String {+ Self.unsupportedDeviceMessage(for: deviceCapability)+ }++ func refreshDeviceCapability() {+ let capability = deviceCapabilityProvider.chatCapability()+ deviceCapability = capability+ logger.info("Chat device capability evaluated", details: "\(capability)")+ guard !capability.isChatSupported else { return }+ showUnsupportedDeviceDialog = true+ isDownloading = false+ downloadToast = nil+ modelDownloadSizeBytes = nil+ hasRequestedModelDownload = false+ modelDownloadTask?.cancel()+ downloadProgressMonitorTask?.cancel()+ sharedModelReadyTask?.cancel()+ clearSharedModelReadyTask()+ provider.cancelDownload()+ }++ func dismissUnsupportedDeviceDialog() {+ showUnsupportedDeviceDialog = false+ }++ static func unsupportedDeviceMessage(for capability: ChatDeviceCapability) -> String {+ var message = "Ensu runs the AI model locally and needs at least 4 GB of RAM. This device does not have enough memory for chat. You can still view existing chats, but sending new messages is disabled."+ if let totalMemoryBytes = capability.totalMemoryBytes {+ message += " Reported memory: \(Int64(totalMemoryBytes).formattedFileSize)."+ }+ return message+ }+private func reopenSyncStoresIfNeeded(force: Bool = false) {let hasSyncDb = FileManager.default.fileExists(atPath: syncDbPath)let hasActiveDb = FileManager.default.fileExists(atPath: activeDbPath)@@ -1140,6 +1181,7 @@ final class ChatViewModel: ObservableObject {private func prewarmImageInferenceIfDownloaded() {guard !isGenerating && !isDownloading else { return }+ guard !isChatUnsupported else { return }let target = modelSettings.currentTarget()guard provider.isModelDownloaded(target: target) else { return }@@ -1196,6 +1238,10 @@ final class ChatViewModel: ObservableObject {func sendDraft() {guard !isGenerating && !isDownloading && !isAttachmentDownloadBlocked else { return }+ guard !isChatUnsupported else {+ showUnsupportedDeviceDialog = true+ return+ }let trimmed = draftText.trimmingCharacters(in: .whitespacesAndNewlines)let attachments = draftAttachments@@ -1321,6 +1367,13 @@ final class ChatViewModel: ObservableObject {}func refreshModelDownloadInfo() {+ guard !isChatUnsupported else {+ isDownloading = false+ downloadToast = nil+ modelDownloadSizeBytes = nil+ hasRequestedModelDownload = false+ return+ }let target = modelSettings.currentTarget()provider.cancelStaleDownloads(target: target)isModelDownloaded = provider.isModelDownloaded(target: target)@@ -1365,6 +1418,9 @@ final class ChatViewModel: ObservableObject {}private func ensureModelReadyShared(target: InferenceModelTarget) async throws {+ if isChatUnsupported {+ throw UnsupportedDeviceMemoryError(capability: deviceCapability)+ }let modelKey = modelReadyKey(for: target)if let existingTask = sharedModelReadyTask, sharedModelReadyKey == modelKey {try await existingTask.value@@ -1421,6 +1477,10 @@ final class ChatViewModel: ObservableObject {func startModelDownload(userInitiated: Bool = true) {guard !isDownloading && !isGenerating else { return }+ guard !isChatUnsupported else {+ showUnsupportedDeviceDialog = true+ return+ }if userInitiated {hasRequestedModelDownload = true}@@ -1470,6 +1530,11 @@ final class ChatViewModel: ObservableObject {func autoStartModelDownloadIfNeeded() {guard !isDownloading && !isGenerating else { return }+ guard !isChatUnsupported else {+ isDownloading = false+ downloadToast = nil+ return+ }let target = modelSettings.currentTarget()let isDownloaded = provider.isModelDownloaded(target: target)isModelDownloaded = isDownloaded@@ -1527,6 +1592,10 @@ final class ChatViewModel: ObservableObject {if isGenerating {stopGenerating()}+ guard !isChatUnsupported else {+ showUnsupportedDeviceDialog = true+ return+ }guard let sessionId = currentSessionId else { return }let userNode: MessageNode?@@ -1588,6 +1657,10 @@ final class ChatViewModel: ObservableObject {}private func startGeneration(for userNode: MessageNode) {+ guard !isChatUnsupported else {+ showUnsupportedDeviceDialog = true+ return+ }generationTask?.cancel()sessionSummaryTask?.cancel()stopRequested = false@@ -2486,6 +2559,7 @@ final class ChatViewModel: ObservableObject {}private func scheduleSessionSummary(for sessionId: UUID) {+ guard !isChatUnsupported else { return }sessionSummaryTask?.cancel()let summaryKey = sessionSummaryKey(sessionId)guard sessionSummaries[summaryKey] == nil else { return }@@ -2668,6 +2742,9 @@ final class ChatViewModel: ObservableObject {}private func userFacingModelReadyError(_ error: Error, wasDownloaded: Bool) -> String {+ if let error = error as? UnsupportedDeviceMemoryError {+ return Self.unsupportedDeviceMessage(for: error.capability)+ }if isOutOfStorageError(error) {return "Not enough storage space to download the model. Please free up space and try again."}diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/Components/ChatViewComponents.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/Components/ChatViewComponents.swiftindex bbd42dc137..32b130f6d0 100644--- a/mobile/native/darwin/Apps/Ensu/Ensu/Chat/Components/ChatViewComponents.swift+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Chat/Components/ChatViewComponents.swift@@ -78,6 +78,34 @@ struct DownloadOnboardingView: View {}+struct UnsupportedChatInputNotice: View {+ let message: String++ var body: some View {+ VStack(alignment: .leading, spacing: EnsuSpacing.xs) {+ Text("Chat unavailable on this device")+ .font(EnsuTypography.large)+ .foregroundStyle(EnsuColor.textPrimary)++ Text(message)+ .font(EnsuTypography.body)+ .foregroundStyle(EnsuColor.textMuted)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(EnsuSpacing.md)+ .background(EnsuColor.fillFaint)+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card))+ .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .padding(.vertical, EnsuSpacing.md)+ .background(+ GeometryReader { proxy in+ Color.clear.preference(key: InputBarHeightKey.self, value: proxy.size.height)+ }+ )+ .background(EnsuColor.backgroundBase)+ }+}+struct SignInComingSoonDialog: View {let title: Stringlet message: Stringdiff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/InferenceRsProvider.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/InferenceRsProvider.swiftindex cb4fab54d2..0d914c57d2 100644--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/InferenceRsProvider.swift+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Services/InferenceRsProvider.swift@@ -89,6 +89,7 @@ final class InferenceRsProvider {}private let modelDir: URL+ private let deviceCapabilityProvider: ChatDeviceCapabilityProvidingprivate let downloadManager = ModelDownloadManager.sharedprivate var modelHandle: ModelHandle?private var contextHandle: ContextHandle?@@ -101,8 +102,12 @@ final class InferenceRsProvider {private var rustDownloadCancelled = falseprivate let logger = EnsuLogging.shared.logger("InferenceRsProvider")- init(modelDir: URL) {+ init(+ modelDir: URL,+ deviceCapabilityProvider: ChatDeviceCapabilityProviding = ProcessInfoChatDeviceCapabilityProvider()+ ) {self.modelDir = modelDir+ self.deviceCapabilityProvider = deviceCapabilityProvidertry? FileManager.default.createDirectory(at: modelDir, withIntermediateDirectories: true, attributes: nil)}@@ -120,6 +125,10 @@ final class InferenceRsProvider {onProgress: @escaping (InferenceDownloadProgress) -> Void,allowRecovery: Bool) async throws {+ let capability = deviceCapabilityProvider.chatCapability()+ if !capability.isChatSupported {+ throw UnsupportedDeviceMemoryError(capability: capability)+ }let modelKey = LoadedModelKey(id: target.id, requestedContextLength: target.contextLength)if currentModelKey == modelKey, modelHandle != nil, contextHandle != nil {return@@ -197,6 +206,10 @@ final class InferenceRsProvider {maxTokens: Int?,onToken: @escaping (String) -> Void) async throws -> InferenceGenerationSummary {+ let capability = deviceCapabilityProvider.chatCapability()+ if !capability.isChatSupported {+ throw UnsupportedDeviceMemoryError(capability: capability)+ }guard let context = contextHandle else {throw NSError(domain: "InferenceRsProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "Model not loaded"])}diff --git a/mobile/native/darwin/Apps/Ensu/Ensu/Services/ModelSettingsStore.swift b/mobile/native/darwin/Apps/Ensu/Ensu/Services/ModelSettingsStore.swiftindex e221e9bae7..2c01f36982 100644--- a/mobile/native/darwin/Apps/Ensu/Ensu/Services/ModelSettingsStore.swift+++ b/mobile/native/darwin/Apps/Ensu/Ensu/Services/ModelSettingsStore.swift@@ -1,5 +1,56 @@import Foundation+let chatMinimumRAMBytes: UInt64 = 4_000_000_000++enum ChatDeviceCapability: Equatable {+ case supported(totalMemoryBytes: UInt64?)+ case unsupportedLowMemory(totalMemoryBytes: UInt64, requiredMemoryBytes: UInt64)+ case unknown++ var isChatSupported: Bool {+ if case .unsupportedLowMemory = self {+ return false+ }+ return true+ }++ var totalMemoryBytes: UInt64? {+ switch self {+ case .supported(let totalMemoryBytes):+ return totalMemoryBytes+ case .unsupportedLowMemory(let totalMemoryBytes, _):+ return totalMemoryBytes+ case .unknown:+ return nil+ }+ }+}++protocol ChatDeviceCapabilityProviding {+ func chatCapability() -> ChatDeviceCapability+}++struct ProcessInfoChatDeviceCapabilityProvider: ChatDeviceCapabilityProviding {+ func chatCapability() -> ChatDeviceCapability {+ let totalMemoryBytes = ProcessInfo.processInfo.physicalMemory+ if totalMemoryBytes < chatMinimumRAMBytes {+ return .unsupportedLowMemory(+ totalMemoryBytes: totalMemoryBytes,+ requiredMemoryBytes: chatMinimumRAMBytes+ )+ }+ return .supported(totalMemoryBytes: totalMemoryBytes)+ }+}++struct UnsupportedDeviceMemoryError: LocalizedError {+ let capability: ChatDeviceCapability++ var errorDescription: String? {+ "Device does not have enough RAM for local chat"+ }+}+@MainActorfinal class ModelSettingsStore: ObservableObject {static let shared = ModelSettingsStore()