💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
sync recovery and log parsing
Prateek Sunal9fa7a7f6e8cc
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 1a047caf26..950877d54f 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@@ -18,7 +18,6 @@ import io.ente.ensu.domain.store.AppStoreimport kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.launch-import kotlinx.coroutines.runBlockingimport java.io.Fileclass AppViewModel(application: Application) : AndroidViewModel(application) {@@ -55,10 +54,10 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {init {val appVersion = runCatching { getAppVersion(application) }.getOrDefault("unknown")- val deviceInfo = "app=$appVersion\ndevice=${Build.MANUFACTURER} ${Build.MODEL}\nos=${Build.VERSION.RELEASE} (sdk=${Build.VERSION.SDK_INT})"- logRepository.log(LogLevel.Info, "App launched", details = deviceInfo, tag = "App")+ 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")- runBlocking {+ viewModelScope.launch {val endpoint = endpointPreferences.endpointFlow.first()val buildEndpoint = BuildConfig.API_ENDPOINT.trim()if (endpoint.isNullOrBlank()) {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 78a9742f86..e9ac5dd1c5 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@@ -38,6 +38,8 @@ import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.layout.wrapContentSizeimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.items+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.TextButtonimport androidx.compose.foundation.lazy.rememberLazyListStateimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.CircleShape@@ -98,6 +100,8 @@ import io.ente.ensu.domain.model.AttachmentTypeimport io.ente.ensu.domain.model.ChatMessageimport io.ente.ensu.domain.model.MessageAuthorimport io.ente.ensu.domain.state.ChatState+import io.ente.ensu.domain.state.OverflowDialogState+import io.ente.ensu.domain.util.formatBytesimport java.text.SimpleDateFormatimport java.util.Dateimport java.util.Locale@@ -121,7 +125,10 @@ fun ChatView(onCancelEdit: () -> Unit,onBranchChange: (String, Int) -> Unit,onOpenAttachment: (Attachment) -> Unit,- onStartDownload: (Boolean) -> Unit+ onStartDownload: (Boolean) -> Unit,+ onOverflowTrim: () -> Unit,+ onOverflowIncreaseContext: () -> Unit,+ onOverflowCancel: () -> Unit) {val showDownloadOnboarding = !chatState.isModelDownloaded &&chatState.messages.isEmpty() &&@@ -139,18 +146,21 @@ fun ChatView(!didAutoFocusInput &&!isDrawerOpen- LaunchedEffect(shouldAutoFocusInput) {+ LaunchedEffect(shouldAutoFocusInput, isDrawerOpen) {+ if (isDrawerOpen) {+ focusManager.clearFocus()+ wasDrawerOpen = true+ return@LaunchedEffect+ }+if (shouldAutoFocusInput) {focusRequestId += 1didAutoFocusInput = true+ wasDrawerOpen = false+ return@LaunchedEffect}- }- LaunchedEffect(isDrawerOpen) {- if (isDrawerOpen) {- focusManager.clearFocus()- wasDrawerOpen = true- } else if (wasDrawerOpen) {+ if (wasDrawerOpen) {val shouldRestoreFocus = chatState.isModelDownloaded &&!showDownloadOnboarding &&!chatState.isDownloading &&@@ -222,6 +232,15 @@ fun ChatView()}+ chatState.overflowDialog?.let { overflow ->+ OverflowDialog(+ state = overflow,+ onTrim = onOverflowTrim,+ onIncreaseContext = onOverflowIncreaseContext,+ onCancel = onOverflowCancel+ )+ }+val editingMessage = chatState.editingMessageId?.let { editingId ->chatState.messages.firstOrNull { it.id == editingId }}@@ -328,20 +347,16 @@ private fun MessageList(}}- LaunchedEffect(isGenerating) {+ val lastMessage = messages.lastOrNull()+ LaunchedEffect(isGenerating, lastMessage?.id) {if (isGenerating) {autoScrollEnabled = truelastHapticLength = 0}- }- val lastMessage = messages.lastOrNull()- LaunchedEffect(lastMessage?.id) {if (lastMessage == null) {lastUserMessageId = null- return@LaunchedEffect- }- if (lastMessage.author == MessageAuthor.User && lastMessage.id != lastUserMessageId) {+ } else if (lastMessage.author == MessageAuthor.User && lastMessage.id != lastUserMessageId) {lastUserMessageId = lastMessage.idif (!listState.isScrollInProgress || isAtBottom) {autoScrollEnabled = true@@ -600,6 +615,42 @@ private fun DownloadOnboarding(}}+@Composable+private fun OverflowDialog(+ state: OverflowDialogState,+ onTrim: () -> Unit,+ onIncreaseContext: () -> Unit,+ onCancel: () -> Unit+) {+ AlertDialog(+ onDismissRequest = onCancel,+ title = { Text(text = "Context limit reached", style = EnsuTypography.h3) },+ text = {+ Text(+ text = "Input uses ${state.inputTokens} tokens (budget ${state.inputBudget}). Trim history or increase context size?",+ style = EnsuTypography.body,+ color = EnsuColor.textPrimary()+ )+ },+ confirmButton = {+ TextButton(onClick = onTrim) {+ Text(text = "Trim history", color = EnsuColor.textPrimary())+ }+ },+ dismissButton = {+ Row(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {+ TextButton(onClick = onIncreaseContext) {+ Text(text = "Increase context", color = EnsuColor.textPrimary())+ }+ TextButton(onClick = onCancel) {+ Text(text = "Cancel", color = EnsuColor.textMuted())+ }+ }+ },+ containerColor = EnsuColor.backgroundBase()+ )+}+@OptIn(ExperimentalLayoutApi::class)@Composableprivate fun UserMessageBubble(@@ -1276,15 +1327,4 @@ private fun MessageInput(}}-private fun formatBytes(bytes: Long): String {- val units = arrayOf("B", "KB", "MB", "GB")- var size = bytes.toDouble()- var unitIndex = 0- while (size >= 1024 && unitIndex < units.size - 1) {- size /= 1024- unitIndex++- }- return String.format(Locale.US, "%.1f %s", size, units[unitIndex])-}-private val timestampFormatter = SimpleDateFormat("h:mm a", Locale.getDefault())diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/LaTeXView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/LaTeXView.ktindex 74946f24c6..e32b85d763 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/LaTeXView.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/LaTeXView.kt@@ -1,6 +1,11 @@package io.ente.ensu.chat+import android.content.Context+import android.util.TypedValue+import android.view.Viewimport android.view.ViewGroup+import android.widget.FrameLayout+import android.widget.TextViewimport androidx.compose.foundation.isSystemInDarkThemeimport androidx.compose.runtime.Composableimport androidx.compose.ui.Modifier@@ -17,33 +22,140 @@ fun LaTeXView(latex: String, modifier: Modifier = Modifier) {val isDark = isSystemInDarkTheme()val textColor = if (isDark) EnsuColor.textPrimaryDark else EnsuColor.textPrimaryLightval paddingPx = with(LocalDensity.current) { EnsuSpacing.cardPadding.dp.roundToPx() }+ val fontSizePx = 16f * LocalDensity.current.densityAndroidView(factory = { context ->- MTMathView(context).apply {+ LatexContainerView(context).apply {layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)- setPadding(paddingPx, paddingPx, paddingPx, paddingPx)- MathViewCompat.setMathTextAlignment(- this,- MTMathView.MTTextAlignment.KMTTextAlignmentLeft- )- this.textColor = textColor.toArgb()- this.fontSize = 16f * context.resources.displayMetrics.density- this.latex = latex+ update(latex, textColor.toArgb(), fontSizePx, paddingPx)}},update = { view ->- view.latex = latex- view.textColor = textColor.toArgb()- view.setPadding(paddingPx, paddingPx, paddingPx, paddingPx)- MathViewCompat.setMathTextAlignment(- view,- MTMathView.MTTextAlignment.KMTTextAlignmentLeft- )+ view.update(latex, textColor.toArgb(), fontSizePx, paddingPx)},modifier = modifier)}++private class LatexContainerView(context: Context) : FrameLayout(context) {+ private val mathView = MTMathView(context)+ private val fallbackView = TextView(context)++ init {+ addView(+ mathView,+ LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT,+ ViewGroup.LayoutParams.WRAP_CONTENT+ )+ )+ addView(+ fallbackView,+ LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT,+ ViewGroup.LayoutParams.WRAP_CONTENT+ )+ )+ fallbackView.visibility = View.GONE+ }++ fun update(latex: String, textColor: Int, fontSizePx: Float, paddingPx: Int) {+ val sanitizedLatex = latex.replace("\\boxed", "")++ fallbackView.text = latex+ fallbackView.setTextColor(textColor)+ fallbackView.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizePx)+ fallbackView.setPadding(paddingPx, paddingPx, paddingPx, paddingPx)++ mathView.textColor = textColor+ mathView.fontSize = fontSizePx+ mathView.setPadding(paddingPx, paddingPx, paddingPx, paddingPx)+ MathViewCompat.setMathTextAlignment(+ mathView,+ MTMathView.MTTextAlignment.KMTTextAlignmentLeft+ )+ MathViewCompat.setDisplayErrorInline(mathView, false)++ val shouldRender = latexLooksRenderable(sanitizedLatex)+ if (shouldRender) {+ mathView.latex = sanitizedLatex+ }++ val error = if (shouldRender) MathViewCompat.getError(mathView) else null+ val useFallback = !shouldRender || !error.isNullOrBlank()+ mathView.visibility = if (useFallback) View.GONE else View.VISIBLE+ fallbackView.visibility = if (useFallback) View.VISIBLE else View.GONE+ }+}++private object LatexRegex {+ val left = Regex("\\\\left")+ val right = Regex("\\\\right")+ val beginEnvironment = Regex("\\\\begin\\{([^}]+)\\}")+ val endEnvironment = Regex("\\\\end\\{([^}]+)\\}")+}++private fun latexLooksRenderable(latex: String): Boolean {+ val trimmed = latex.trim()+ if (trimmed.isEmpty()) {+ return false+ }++ var braceBalance = 0+ var escaped = false+ for (char in trimmed) {+ if (escaped) {+ escaped = false+ continue+ }+ if (char == '\\') {+ escaped = true+ continue+ }+ if (char == '{') {+ braceBalance += 1+ } else if (char == '}') {+ braceBalance -= 1+ if (braceBalance < 0) {+ return false+ }+ }+ }++ if (escaped || braceBalance != 0) {+ return false+ }++ if (countMatches(trimmed, LatexRegex.left) != countMatches(trimmed, LatexRegex.right)) {+ return false+ }++ return environmentsBalanced(trimmed)+}++private fun countMatches(text: String, regex: Regex): Int {+ return regex.findAll(text).count()+}++private fun environmentsBalanced(text: String): Boolean {+ val beginMatches = runCatching {+ LatexRegex.beginEnvironment+ .findAll(text)+ .map { it.groupValues[1] }+ .toList()+ }.getOrElse { return false }+ val endMatches = runCatching {+ LatexRegex.endEnvironment+ .findAll(text)+ .map { it.groupValues[1] }+ .toList()+ }.getOrElse { return false }+ if (beginMatches.size != endMatches.size) {+ return false+ }+ return beginMatches.sorted() == endMatches.sorted()+}diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.ktindex 5f761deec7..9cf687b55e 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt@@ -2,6 +2,7 @@ package io.ente.ensu.data.chatimport android.content.Contextimport io.ente.ensu.data.storage.CredentialStore+import io.ente.ensu.data.storage.FilePathManagerimport io.ente.ensu.domain.chat.ChatRepositoryimport io.ente.ensu.domain.model.Attachmentimport io.ente.ensu.domain.model.AttachmentType@@ -20,18 +21,13 @@ class RustChatRepository(credentialStore: CredentialStore) : ChatRepository {- private val attachmentsDir = File(context.filesDir, "attachments")- private val mainDbFile = File(context.filesDir, "llmchat.db")- private val attachmentsDbFile = File(context.filesDir, "llmchat_attachments.db")+ private val filePaths = FilePathManager(context)+ private val attachmentsDir = filePaths.attachmentsDir+ private val mainDbFile = filePaths.mainDbFile+ private val attachmentsDbFile = filePaths.attachmentsDbFileprivate val dbKey = credentialStore.getOrCreateChatDbKey()private var db: LlmChatDb = openDb()- init {- if (!attachmentsDir.exists()) {- attachmentsDir.mkdirs()- }- }-override fun listSessions(): List<ChatSession> = withDbRecovery {val sessions = db.listSessions()sessions.map { session ->diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.ktindex 6aba135a86..6eb232a925 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatSyncRepository.kt@@ -4,6 +4,7 @@ import android.content.Contextimport io.ente.ensu.data.EndpointPreferencesDataStoreimport io.ente.ensu.data.network.NetworkConfigurationimport io.ente.ensu.data.storage.CredentialStore+import io.ente.ensu.data.storage.FilePathManagerimport io.ente.ensu.domain.chat.ChatSyncRepositoryimport io.ente.labs.llmchat_sync.LlmChatSyncimport io.ente.labs.llmchat_sync.SyncAuth@@ -11,7 +12,6 @@ import io.ente.labs.llmchat_sync.SyncExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.withContext-import java.io.Fileclass RustChatSyncRepository(private val context: Context,@@ -19,13 +19,23 @@ class RustChatSyncRepository(private val endpointPreferences: EndpointPreferencesDataStore) : ChatSyncRepository {- private val syncEngine: LlmChatSync by lazy { buildSyncEngine() }+ private val filePaths = FilePathManager(context)+ private var syncEngine: LlmChatSync? = nulloverride suspend fun sync() {withContext(Dispatchers.IO) {try {- syncEngine.sync(buildAuth())+ syncEngine().sync(buildAuth())} catch (err: Throwable) {+ if (shouldResetSync(err)) {+ resetSyncState()+ try {+ syncEngine().sync(buildAuth())+ return@withContext+ } catch (retryErr: Throwable) {+ throw IllegalStateException(syncErrorMessage(retryErr), retryErr)+ }+ }throw IllegalStateException(syncErrorMessage(err), err)}}@@ -33,33 +43,23 @@ class RustChatSyncRepository(override suspend fun downloadAttachment(attachmentId: String, sessionId: String): Boolean {return withContext(Dispatchers.IO) {- syncEngine.downloadAttachment(attachmentId, sessionId, buildAuth())+ syncEngine().downloadAttachment(attachmentId, sessionId, buildAuth())}}- private fun buildSyncEngine(): LlmChatSync {- val baseDir = File(context.filesDir, "llmchat")- if (!baseDir.exists()) baseDir.mkdirs()-- val encryptedAttachmentsDir = File(baseDir, "chat_attachments_encrypted")- if (!encryptedAttachmentsDir.exists()) encryptedAttachmentsDir.mkdirs()-- val metaDir = File(baseDir, "sync_meta")- if (!metaDir.exists()) metaDir.mkdirs()+ private fun syncEngine(): LlmChatSync {+ return syncEngine ?: buildSyncEngine().also { syncEngine = it }+ }- val mainDb = File(context.filesDir, "llmchat.db").absolutePath- val attachmentsDb = File(context.filesDir, "llmchat_attachments.db").absolutePath+ private fun buildSyncEngine(): LlmChatSync {val dbKey = credentialStore.getOrCreateChatDbKey()- val plaintextDir = File(context.filesDir, "attachments")- if (!plaintextDir.exists()) plaintextDir.mkdirs()-return LlmChatSync.open(- mainDbPath = mainDb,- attachmentsDbPath = attachmentsDb,+ mainDbPath = filePaths.mainDbFile.absolutePath,+ attachmentsDbPath = filePaths.attachmentsDbFile.absolutePath,dbKey = dbKey,- attachmentsDir = encryptedAttachmentsDir.absolutePath,- metaDir = metaDir.absolutePath,- plaintextDir = plaintextDir.absolutePath+ attachmentsDir = filePaths.encryptedAttachmentsDir.absolutePath,+ metaDir = filePaths.syncMetaDir.absolutePath,+ plaintextDir = filePaths.plaintextAttachmentsDir.absolutePath)}@@ -90,6 +90,19 @@ class RustChatSyncRepository(return if (remainder == 0) token else token + "=".repeat(4 - remainder)}+ private fun shouldResetSync(error: Throwable): Boolean {+ val message = syncErrorMessage(error).lowercase()+ return message.contains("stream pull failed") ||+ message.contains("invalid blob") ||+ message.contains("invalid encrypted")+ }++ private fun resetSyncState() {+ runCatching { filePaths.syncMetaDir.deleteRecursively() }+ runCatching { filePaths.syncMetaDir.mkdirs() }+ syncEngine = null+ }+private fun syncErrorMessage(error: Throwable): String {val syncMessage = generateSequence(error) { it.cause }.filterIsInstance<SyncException.Message>()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 870c98dad8..c1931e8209 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,7 @@ import io.ente.ensu.domain.llm.GenerationSummaryimport io.ente.ensu.domain.llm.LlmMessageimport io.ente.ensu.domain.llm.LlmModelTargetimport io.ente.ensu.domain.llm.LlmProvider+import io.ente.ensu.domain.util.formatBytesimport io.ente.labs.inference_rs.ContextHandleimport io.ente.labs.inference_rs.ContextParamsimport io.ente.labs.inference_rs.GenerateChatRequest@@ -29,7 +30,6 @@ import java.io.Fileimport java.io.FileOutputStreamimport java.io.IOExceptionimport java.security.MessageDigest-import java.util.Localeimport java.util.concurrent.atomic.AtomicBooleanimport kotlin.math.max@@ -129,6 +129,7 @@ class InferenceRsProvider(val context = contextHandle ?: throw IllegalStateException("Model context not loaded")currentJobId = nullval mmprojPath = if (imageFiles.isEmpty()) null else mmprojPathFor(target)?.absolutePath+ val clampedTemperature = temperature.coerceIn(0.35f, 0.7f)val request = GenerateChatRequest(messages = messages.map { msg ->@@ -140,12 +141,12 @@ class InferenceRsProvider(mmprojPath = mmprojPath,mediaMarker = null,maxTokens = maxTokens,- temperature = temperature,- topP = null,- topK = null,- repeatPenalty = null,- frequencyPenalty = null,- presencePenalty = null,+ temperature = clampedTemperature,+ topP = 0.9f,+ topK = 50,+ repeatPenalty = 1.18f,+ frequencyPenalty = 0f,+ presencePenalty = 0f,seed = null,stopSequences = null,grammar = null@@ -407,17 +408,6 @@ class InferenceRsProvider(return digest.joinToString("") { "%02x".format(it) }}- private fun formatBytes(bytes: Long): String {- val units = arrayOf("B", "KB", "MB", "GB")- var size = bytes.toDouble()- var unitIndex = 0- while (size >= 1024 && unitIndex < units.size - 1) {- size /= 1024- unitIndex++- }- return String.format(Locale.US, "%.1f %s", size, units[unitIndex])- }-private fun generateStreamWithCallback(context: ContextHandle,request: GenerateChatRequest,diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.ktindex 790a3f15af..d729aa4258 100644--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.kt+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.kt@@ -180,16 +180,47 @@ class FileLogRepository(private fun formatLine(entry: LogEntry): String {val timestamp = lineTimestampFormatter.format(Date(entry.timestampMillis))val header = "[${entry.tag}][${entry.level.name.uppercase()}] [$timestamp]"- var out = "$header ${entry.message}".trimEnd() + "\n"-- entry.details?.takeIf { it.isNotBlank() }?.let { details ->- details.lines().forEach { line ->- out += "$header ⤷ $line\n"+ val details = entry.details.orEmpty()+ val shouldInline = entry.level == LogLevel.Info && details.isNotBlank() && !looksLikeStackTrace(details)+ val message = entry.message+ var out = "$header $message".trimEnd() + "\n"++ if (details.isNotBlank()) {+ if (shouldInline) {+ val inline = inlineDetails(details)+ if (inline.isNotBlank()) {+ out += "$inline\n"+ }+ } else {+ details.lines().forEach { line ->+ out += "$line\n"+ }}}return out}+ private fun inlineDetails(details: String): String {+ return details.lineSequence()+ .map { it.trim() }+ .filter { it.isNotEmpty() }+ .joinToString(" | ")+ }++ private fun looksLikeStackTrace(details: String): Boolean {+ return details.lineSequence()+ .map { it.trimStart() }+ .any { isStackTraceLine(it) }+ }++ private fun isStackTraceLine(line: String): Boolean {+ val trimmed = line.trimStart()+ return trimmed.startsWith("at ") ||+ trimmed.startsWith("...") ||+ trimmed.startsWith("Caused by") ||+ trimmed.startsWith("Suppressed:")+ }+private fun parseLogEntries(text: String): List<LogEntry> {if (text.isBlank()) return emptyList()@@ -205,6 +236,8 @@ class FileLogRepository(if (match == null) {if (current != null) {details.add(trimmed)+ } else if (entries.isNotEmpty() && shouldAttachToPrevious(trimmed)) {+ appendDetailToLast(entries, trimmed)} else {entries.add(LogEntry(@@ -227,13 +260,26 @@ class FileLogRepository(val trimmedMessage = message.trimStart()val isDetail = isDetailLine(trimmedMessage)if (isDetail) {+ val cleaned = when {+ trimmedMessage.startsWith("->") -> trimmedMessage.removePrefix("->").trim()+ trimmedMessage.startsWith("⤷") -> trimmedMessage.removePrefix("⤷").trim()+ else -> trimmedMessage+ }if (current != null) {- val cleaned = if (trimmedMessage.startsWith("⤷")) {- trimmedMessage.removePrefix("⤷").trim()- } else {- trimmedMessage- }details.add(cleaned)+ } else if (entries.isNotEmpty() && shouldAttachToPrevious(cleaned)) {+ appendDetailToLast(entries, cleaned)+ } else {+ entries.add(+ LogEntry(+ id = UUID.randomUUID().toString(),+ timestampMillis = System.currentTimeMillis(),+ level = LogLevel.Info,+ tag = "Log",+ message = cleaned,+ details = null+ )+ )}return@forEach}@@ -267,6 +313,20 @@ class FileLogRepository(return entries}+ private fun appendDetailToLast(entries: MutableList<LogEntry>, line: String) {+ if (entries.isEmpty()) return+ val last = entries.removeAt(entries.lastIndex)+ val updatedDetails = listOfNotNull(last.details?.takeIf { it.isNotBlank() }, line)+ .joinToString("\n")+ entries.add(last.copy(details = updatedDetails))+ }++ private fun shouldAttachToPrevious(line: String): Boolean {+ if (line.isBlank()) return false+ val trimmed = line.trimStart()+ return line.firstOrNull()?.isWhitespace() == true || isStackTraceLine(trimmed)+ }+private fun parseLevel(value: String): LogLevel? = when (value.uppercase()) {"INFO" -> LogLevel.Info"WARNING", "WARN" -> LogLevel.Warning@@ -276,7 +336,8 @@ class FileLogRepository(private fun isDetailLine(message: String): Boolean {val trimmed = message.trimStart()- return trimmed.startsWith("⤷") ||+ return trimmed.startsWith("->") ||+ trimmed.startsWith("⤷") ||trimmed.startsWith("at ") ||trimmed.startsWith("...") ||trimmed.startsWith("Caused by") ||diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/FilePathManager.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/FilePathManager.ktnew file mode 100644index 0000000000..9d77e7ac5b--- /dev/null+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/storage/FilePathManager.kt@@ -0,0 +1,21 @@+package io.ente.ensu.data.storage++import android.content.Context+import java.io.File++class FilePathManager(context: Context) {+ val attachmentsDir: File = ensureDir(File(context.filesDir, "attachments"))+ val mainDbFile: File = File(context.filesDir, "llmchat.db")+ val attachmentsDbFile: File = File(context.filesDir, "llmchat_attachments.db")+ val syncBaseDir: File = ensureDir(File(context.filesDir, "llmchat"))+ val encryptedAttachmentsDir: File = ensureDir(File(syncBaseDir, "chat_attachments_encrypted"))+ val syncMetaDir: File = ensureDir(File(syncBaseDir, "sync_meta"))+ val plaintextAttachmentsDir: File = attachmentsDir++ private fun ensureDir(dir: File): File {+ if (!dir.exists()) {+ dir.mkdirs()+ }+ return dir+ }+}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/ChatModels.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/ChatModels.ktindex 5b09b0b7f0..e17a7800d6 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/ChatModels.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/ChatModels.kt@@ -43,13 +43,6 @@ data class Attachment(const val SessionTitleMaxLength = 40-private fun sanitizeTitleText(text: String): String {- return text- .replace(Regex("[\r\n\t]+"), " ")- .replace(Regex("\\s+"), " ")- .trim()-}-fun sessionTitleFromText(text: String, fallback: String = "New Chat"): String {val trimmed = sanitizeTitleText(text)if (trimmed.isBlank()) return fallbackdiff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/TitleSanitizer.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/TitleSanitizer.ktnew file mode 100644index 0000000000..e250eaae93--- /dev/null+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/TitleSanitizer.kt@@ -0,0 +1,11 @@+package io.ente.ensu.domain.model++private val TitleLineBreakRegex = Regex("[\r\n\t]+")+private val TitleWhitespaceRegex = Regex("\\s+")++internal fun sanitizeTitleText(text: String): String {+ return text+ .replace(TitleLineBreakRegex, " ")+ .replace(TitleWhitespaceRegex, " ")+ .trim()+}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 affa0f81c3..b934110c11 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@@ -14,6 +14,7 @@ import io.ente.ensu.domain.model.ChatMessageimport io.ente.ensu.domain.model.ChatSessionimport io.ente.ensu.domain.model.LogLevelimport io.ente.ensu.domain.model.MessageAuthor+import io.ente.ensu.domain.model.sanitizeTitleTextimport io.ente.ensu.domain.model.sessionTitleFromTextimport io.ente.ensu.domain.preferences.SessionPreferencesimport io.ente.ensu.domain.state.AppState@@ -31,9 +32,10 @@ import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.isActiveimport kotlinx.coroutines.launch-import kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withContextimport java.io.File+import java.util.concurrent.ConcurrentHashMap+import java.util.concurrent.ConcurrentLinkedDequeimport kotlin.math.absimport kotlin.math.max@@ -51,6 +53,7 @@ class AppStore(private val messageStore = mutableMapOf<String, MutableList<ChatMessage>>()private val branchSelections = mutableMapOf<String, MutableMap<String, String>>()private val sessionSummaries = mutableMapOf<String, String>()+ private val sessionAccessTimes = mutableMapOf<String, Long>()private var scope: CoroutineScope? = nullprivate var generationJob: Job? = nullprivate var modelDownloadJob: Job? = null@@ -61,21 +64,28 @@ class AppStore(private var pendingSyncRequested = falseprivate var pendingSyncErrorHandler: ((String) -> Unit)? = nullprivate var pendingSyncSuccessHandler: (() -> Unit)? = null+ private var pendingOverflow: PendingOverflow? = null+ private var overflowBypassMessageId: String? = nullprivate val sessionSummarySystemPrompt ="You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words, no quotes, no emojis, no trailing punctuation, and output only the title."private val sessionSummaryMaxWords = 7- private val attachmentDownloads = mutableMapOf<String, AttachmentDownloadItem>()- private val attachmentDownloadQueue = ArrayDeque<String>()- private val attachmentDownloadActive = mutableMapOf<String, Job>()+ private val attachmentDownloads = ConcurrentHashMap<String, AttachmentDownloadItem>()+ private val attachmentDownloadQueue = ConcurrentLinkedDeque<String>()+ private val attachmentDownloadActive = ConcurrentHashMap<String, Job>()private val maxAttachmentDownloadConcurrency = 2fun bootstrap(scope: CoroutineScope) {this.scope = scopesessionSummaries.clear()- sessionSummaries.putAll(runBlocking { sessionPreferences.sessionSummaries.first() }.mapKeys { it.key.lowercase() })+ scope.launch {+ val summaries = sessionPreferences.sessionSummaries.first()+ sessionSummaries.clear()+ sessionSummaries.putAll(summaries.mapKeys { sessionKey(it.key) })+ applySessionSummariesToState()+ }if (_state.value.chat.sessions.isEmpty()) {loadSessionsFromDb()@@ -86,11 +96,10 @@ class AppStore(scope.launch {sessionPreferences.sessionSummaries.collectLatest { summaries ->sessionSummaries.clear()- sessionSummaries.putAll(summaries.mapKeys { it.key.lowercase() })+ sessionSummaries.putAll(summaries.mapKeys { sessionKey(it.key) })applySessionSummariesToState()}}-}private fun refreshModelDownloadInfo() {@@ -151,6 +160,8 @@ class AppStore())}+ markSessionAccess(session.id)+ trimSessionCaches()// Session is empty, no DB load needed.rebuildChatState(session.id)updateAttachmentDownloadState()@@ -219,19 +230,12 @@ class AppStore(}chatRepository.deleteSession(sessionId)- messageStore.remove(sessionId)- branchSelections.remove(sessionId)+ removeSessionCaches(sessionId)purgeAttachmentDownloads(sessionId)- sessionSummaries.remove(sessionId.lowercase())+ sessionSummaries.remove(sessionKey(sessionId))scope?.launch { sessionPreferences.setSessionSummary(sessionId, null) }- val remaining = currentState.chat.sessions.filterNot { it.id == sessionId }- val sessions = remaining-- sessions.forEach { session ->- messageStore.getOrPut(session.id) { mutableListOf() }- branchSelections.getOrPut(session.id) { mutableMapOf() }- }+ val sessions = currentState.chat.sessions.filterNot { it.id == sessionId }val newCurrent = if (isCurrent) {sessions.firstOrNull()?.id@@ -268,6 +272,7 @@ class AppStore(appState.copy(chat = appState.chat.copy(messages = emptyList(), branchSelections = emptyMap()))}}+ trimSessionCaches(sessions.map { it.id }.toSet())scope?.launch { sessionPreferences.setSelectedSessionId(newCurrent) }syncNow()@@ -563,6 +568,27 @@ class AppStore()}+ fun confirmOverflowTrim() {+ val pending = pendingOverflow ?: return+ val message = messageStore[pending.sessionId]?.firstOrNull { it.id == pending.messageId }+ if (message == null) {+ pendingOverflow = null+ overflowBypassMessageId = null+ clearOverflowDialog()+ return+ }+ overflowBypassMessageId = pending.messageId+ pendingOverflow = null+ clearOverflowDialog()+ startGeneration(pending.sessionId, message)+ }++ fun cancelOverflowDialog() {+ pendingOverflow = null+ overflowBypassMessageId = null+ clearOverflowDialog()+ }+fun updateModelSettings(state: ModelSettingsState) {_state.update { appState ->appState.copy(modelSettings = state)@@ -683,7 +709,7 @@ class AppStore(fun cancelAttachmentDownload(attachmentId: String) {attachmentDownloadActive[attachmentId]?.cancel()attachmentDownloadActive.remove(attachmentId)- attachmentDownloadQueue.removeAll { it == attachmentId }+ attachmentDownloadQueue.removeIf { it == attachmentId }attachmentDownloads[attachmentId]?.let { item ->attachmentDownloads[attachmentId] = item.copy(status = AttachmentDownloadStatus.Canceled)}@@ -708,7 +734,7 @@ class AppStore(ids.forEach { id ->attachmentDownloadActive[id]?.cancel()attachmentDownloadActive.remove(id)- attachmentDownloadQueue.removeAll { it == id }+ attachmentDownloadQueue.removeIf { it == id }attachmentDownloads.remove(id)}updateAttachmentDownloadState()@@ -737,7 +763,7 @@ class AppStore(if (path != null && File(path).exists()) {attachmentDownloadActive[attachment.id]?.cancel()attachmentDownloadActive.remove(attachment.id)- attachmentDownloadQueue.removeAll { it == attachment.id }+ attachmentDownloadQueue.removeIf { it == attachment.id }attachmentDownloads.remove(attachment.id)continue}@@ -784,7 +810,10 @@ class AppStore(private fun startNextAttachmentDownloads() {val scope = scope ?: returnwhile (attachmentDownloadActive.size < maxAttachmentDownloadConcurrency && attachmentDownloadQueue.isNotEmpty()) {- val id = attachmentDownloadQueue.removeFirst()+ val id = attachmentDownloadQueue.pollFirst() ?: continue+ if (attachmentDownloadActive.containsKey(id)) {+ continue+ }val item = attachmentDownloads[id] ?: continueif (item.status == AttachmentDownloadStatus.Completed || item.status == AttachmentDownloadStatus.Canceled) {continue@@ -859,8 +888,29 @@ class AppStore(generationJob?.cancel()sessionSummaryJob?.cancel()stopRequested = false- val generationToken = nextGenerationToken()+ val settings = _state.value.modelSettings+ val target = resolveTarget(settings)+ val prompt = buildPrompt(userMessage.text, userMessage.attachments)+ val historySelection = buildHistorySelection(+ sessionId = sessionId,+ promptText = prompt.text,+ promptImageCount = prompt.imageFiles.size,+ currentMessageId = userMessage.id,+ target = target+ )++ if (historySelection.wasTrimmed && overflowBypassMessageId != userMessage.id) {+ pendingOverflow = PendingOverflow(sessionId, userMessage.id)+ showOverflowDialog(historySelection, target)+ return+ }++ overflowBypassMessageId = null+ pendingOverflow = null+ clearOverflowDialog()++ val generationToken = nextGenerationToken()streamingParentId = userMessage.id_state.update { appState ->appState.copy(@@ -878,8 +928,6 @@ class AppStore(rebuildChatState(sessionId)generationJob = scope.launch {- val settings = _state.value.modelSettings- val target = resolveTarget(settings)val isActive = { isGenerationActive(generationToken, sessionId) }try {llmProvider.ensureModelReady(target) { progress ->@@ -930,8 +978,7 @@ class AppStore(if (!isActive()) return@launch- val prompt = buildPrompt(userMessage.text, userMessage.attachments)- val history = buildHistory(sessionId, prompt.text, userMessage.id)+ val history = historySelection.messagesval systemMessage = LlmMessage(text = SYSTEM_PROMPT,role = LlmMessageRole.System@@ -1077,7 +1124,7 @@ class AppStore(private fun applySessionSummariesToState() {_state.update { appState ->val updatedSessions = appState.chat.sessions.map { session ->- val summary = sessionSummaries[session.id.lowercase()]+ val summary = sessionSummaries[sessionKey(session.id)]if (!summary.isNullOrBlank() && summary != session.title) {session.copy(title = summary)} else {@@ -1091,7 +1138,7 @@ class AppStore(private fun scheduleSessionSummary(sessionId: String) {val scope = scope ?: returnsessionSummaryJob?.cancel()- if (sessionSummaries.containsKey(sessionId.lowercase())) return+ if (sessionSummaries.containsKey(sessionKey(sessionId))) returnval summaryInput = buildSessionSummaryInput(sessionId) ?: returnval target = resolveTarget(_state.value.modelSettings)@@ -1172,7 +1219,7 @@ class AppStore(private fun applySessionSummary(sessionId: String, summary: String) {val sanitized = sessionTitleFromText(summary, fallback = "New Chat")if (sanitized.isBlank()) return- val summaryKey = sessionId.lowercase()+ val summaryKey = sessionKey(sessionId)if (sessionSummaries[summaryKey] == sanitized) returnsessionSummaries[summaryKey] = sanitizedscope?.launch { sessionPreferences.setSessionSummary(sessionId, sanitized) }@@ -1200,18 +1247,49 @@ class AppStore(return summaryWords.joinToString(" ")}- private fun sanitizeTitleText(text: String): String {- return text- .replace(Regex("[\r\n\t]+"), " ")- .replace(Regex("\\s+"), " ")- .trim()- }-private fun loadMessagesFromDb(sessionId: String) {val messages = chatRepository.getMessages(sessionId)messageStore[sessionId] = messages.toMutableList()// Reset branch selections for this session. (Branch selection is computed in-memory.)branchSelections.getOrPut(sessionId) { mutableMapOf() }.clear()+ markSessionAccess(sessionId)+ trimSessionCaches()+ }++ private fun markSessionAccess(sessionId: String) {+ sessionAccessTimes[sessionId] = clock()+ }++ private fun trimSessionCaches(availableSessions: Set<String> = _state.value.chat.sessions.map { it.id }.toSet()) {+ val availableKeys = availableSessions.map(::sessionKey).toSet()+ sessionSummaries.keys.retainAll(availableKeys)++ val keepIds = LinkedHashSet<String>()+ val currentSessionId = _state.value.chat.currentSessionId+ if (currentSessionId != null && currentSessionId in availableSessions) {+ keepIds.add(currentSessionId)+ }+ val ordered = sessionAccessTimes.entries+ .filter { it.key in availableSessions }+ .sortedByDescending { it.value }+ .map { it.key }+ for (id in ordered) {+ if (keepIds.size >= MAX_CACHED_SESSIONS) break+ keepIds.add(id)+ }+ messageStore.keys.retainAll(keepIds)+ branchSelections.keys.retainAll(keepIds)+ sessionAccessTimes.keys.retainAll(keepIds)+ }++ private fun removeSessionCaches(sessionId: String) {+ messageStore.remove(sessionId)+ branchSelections.remove(sessionId)+ sessionAccessTimes.remove(sessionId)+ }++ private fun sessionKey(sessionId: String): String {+ return sessionId.lowercase()}private fun rebuildChatState(sessionId: String?) {@@ -1328,6 +1406,18 @@ class AppStore(selectionMap[selectionKey] = childId}+ private data class HistorySelection(+ val messages: List<LlmMessage>,+ val inputTokens: Int,+ val inputBudget: Int,+ val wasTrimmed: Boolean+ )++ private data class PendingOverflow(+ val sessionId: String,+ val messageId: String+ )+private fun buildPrompt(text: String, attachments: List<Attachment>): PromptResult {val builder = StringBuilder(text)val documents = attachments.filter { it.type == AttachmentType.Document }@@ -1359,16 +1449,27 @@ class AppStore(return PromptResult(builder.toString(), imageFiles)}- private fun buildHistory(sessionId: String, promptText: String, currentMessageId: String): List<LlmMessage> {+ private fun buildHistorySelection(+ sessionId: String,+ promptText: String,+ promptImageCount: Int,+ currentMessageId: String,+ target: LlmModelTarget+ ): HistorySelection {val path = buildSelectedPath(sessionId)- if (path.isEmpty()) return emptyList()-val historyMessages = path.takeWhile { it.id != currentMessageId }- val contextSize = resolveTarget(_state.value.modelSettings).contextLength ?: 4096- val maxOutput = resolveTarget(_state.value.modelSettings).maxTokens ?: 1024- val budget = contextSize - maxOutput - 256- var remaining = budget - estimateTokens(promptText)- if (remaining <= 0) return emptyList()+ val contextSize = target.contextLength ?: 4096+ val maxOutput = target.maxTokens ?: 1024+ val inputBudget = max(0, contextSize - maxOutput - OVERFLOW_SAFETY_TOKENS)+ val systemTokens = estimateTokens(SYSTEM_PROMPT)+ val promptTokens = estimatePromptTokens(promptText, promptImageCount)+ val historyTokens = historyMessages.sumOf { estimateTokens(historyText(it)) }+ val inputTokens = systemTokens + promptTokens + historyTokens+ var remaining = inputBudget - systemTokens - promptTokens++ if (remaining <= 0 || historyMessages.isEmpty()) {+ return HistorySelection(emptyList(), inputTokens, inputBudget, inputTokens > inputBudget)+ }val selected = mutableListOf<LlmMessage>()for (message in historyMessages.asReversed()) {@@ -1383,21 +1484,33 @@ class AppStore())remaining -= cost- } else if (selected.isEmpty()) {- selected.add(- LlmMessage(- text = trimToBudget(text, remaining),- role = if (message.author == MessageAuthor.User) LlmMessageRole.User else LlmMessageRole.Assistant,- hasAttachments = message.attachments.isNotEmpty()- )- )- break} else {break}}- return selected.reversed()+ return HistorySelection(selected.reversed(), inputTokens, inputBudget, inputTokens > inputBudget)+ }++ private fun showOverflowDialog(selection: HistorySelection, target: LlmModelTarget) {+ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ overflowDialog = io.ente.ensu.domain.state.OverflowDialogState(+ inputTokens = selection.inputTokens,+ inputBudget = selection.inputBudget,+ contextLength = target.contextLength ?: 4096,+ maxOutput = target.maxTokens ?: 1024+ )+ )+ )+ }+ }++ private fun clearOverflowDialog() {+ _state.update { appState ->+ appState.copy(chat = appState.chat.copy(overflowDialog = null))+ }}private fun historyText(message: ChatMessage): String {@@ -1421,9 +1534,18 @@ class AppStore(return max(1, text.length / 4)}+ private fun estimateImageTokens(imageCount: Int): Int {+ return imageCount * IMAGE_TOKEN_ESTIMATE+ }++ private fun estimatePromptTokens(promptText: String, imageCount: Int): Int {+ return estimateTokens(promptText) + estimateImageTokens(imageCount)+ }+private fun resolveTemperature(settings: ModelSettingsState): Float {val temperature = settings.temperature.trim().toFloatOrNull()- return temperature?.takeIf { it >= 0f } ?: DEFAULT_TEMPERATURE+ val resolved = temperature?.takeIf { it >= 0f } ?: DEFAULT_TEMPERATURE+ return resolved.coerceIn(0.35f, 0.7f)}private fun resolveTarget(settings: ModelSettingsState): LlmModelTarget {@@ -1445,7 +1567,7 @@ class AppStore(private fun loadSessionsFromDb() {val sessions = chatRepository.listSessions().map { session ->- val summary = sessionSummaries[session.id.lowercase()]+ val summary = sessionSummaries[sessionKey(session.id)]if (!summary.isNullOrBlank()) {session.copy(title = summary)} else {@@ -1453,11 +1575,6 @@ class AppStore(}}- sessions.forEach { session ->- messageStore.getOrPut(session.id) { mutableListOf() }- branchSelections.getOrPut(session.id) { mutableMapOf() }- }-val currentSessionId = _state.value.chat.currentSessionIdval sessionStillExists = currentSessionId != null && sessions.any { it.id == currentSessionId }@@ -1476,6 +1593,7 @@ class AppStore(} else {updateAttachmentDownloadState()}+ trimSessionCaches(sessions.map { it.id }.toSet())}private data class PromptResult(@@ -1489,7 +1607,10 @@ class AppStore(private const val DEFAULT_MMPROJ_URL ="https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"private const val MEDIA_MARKER = "<__media__>"- private const val DEFAULT_TEMPERATURE = 0.7f+ private const val OVERFLOW_SAFETY_TOKENS = 128+ private const val IMAGE_TOKEN_ESTIMATE = 768+ private const val DEFAULT_TEMPERATURE = 0.5f+ private const val MAX_CACHED_SESSIONS = 8private const val SYSTEM_PROMPT ="You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points. For math equations, put \$\$ on its own line (never inline). Example:\n\$\$\nx^2 + y^2 = z^2\n\$\$"}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/util/ByteFormatter.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/util/ByteFormatter.ktnew file mode 100644index 0000000000..f4c93bcdbe--- /dev/null+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/util/ByteFormatter.kt@@ -0,0 +1,14 @@+package io.ente.ensu.domain.util++import java.util.Locale++fun formatBytes(bytes: Long): String {+ val units = arrayOf("B", "KB", "MB", "GB")+ var size = bytes.toDouble()+ var unitIndex = 0+ while (size >= 1024 && unitIndex < units.size - 1) {+ size /= 1024+ unitIndex+++ }+ return String.format(Locale.US, "%.1f %s", size, units[unitIndex])+}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swiftindex 0d297eb68b..1b56d44339 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift@@ -8,30 +8,38 @@ struct ChatView: View {@EnvironmentObject private var appState: EnsuAppState@ObservedObject private var modelSettings = ModelSettingsStore.shared- @State private var isDrawerOpen = false- @State private var showSettings = false- @State private var toastMessage: ToastMessage?+ @StateObject private var viewState = ChatViewState()@StateObject private var keyboard = KeyboardObserver()- @State private var deleteSession: ChatSession?- @State private var developerTapCount = 0- @State private var lastDeveloperTapAt: Date?- @State private var isOpeningDeveloperSettings = false- @State private var showDeveloperAlert = false- @State private var showDeveloperSettings = false- @State private var showAttachmentDownloads = false- @State private var showSignInComingSoon = false- @State private var didAutoFocusInput = false@FocusState private var isInputFocused: Bool- @State private var inputBarHeight: CGFloat = 0- @State private var wasDrawerOpen = false- @State private var didDismissKeyboard = false- @State private var sessionTransitionId = UUID()private var editingMessage: ChatMessage? {guard let editingId = viewModel.editingMessageId else { return nil }return viewModel.messages.first { $0.id == editingId }}+ private var toastTrigger: ToastTrigger {+ ToastTrigger(+ syncError: viewModel.syncErrorMessage,+ syncSuccess: viewModel.syncSuccessMessage,+ generationError: viewModel.generationErrorMessage+ )+ }++ private var shouldAutoFocusInput: Bool {+ viewModel.isModelDownloaded+ && !viewModel.isDownloading+ && !viewModel.isGenerating+ && !viewState.didAutoFocusInput+ && !viewState.isDrawerOpen+ && !viewState.didDismissKeyboard+ && !viewState.showSettings+ && !viewState.showDeveloperSettings+ }++ private var modelSettingsSignature: String {+ "\(modelSettings.useCustomModel)|\(modelSettings.modelUrl)|\(modelSettings.mmprojUrl)"+ }+private let drawerWidth: CGFloat = 320private let drawerAutoThreshold: CGFloat = 900private let drawerHiddenOffset: CGFloat = -340@@ -63,21 +71,21 @@ struct ChatView: View {.gesture(DragGesture(minimumDistance: 20).onEnded { value in- guard !isDrawerOpen else { return }+ guard !viewState.isDrawerOpen else { return }guard value.startLocation.x <= 24 else { return }let horizontal = value.translation.widthlet vertical = value.translation.heightguard abs(horizontal) > abs(vertical), horizontal > 40 else { return }- isDrawerOpen = true+ viewState.isDrawerOpen = true})#endif}- if isDrawerOpen {+ if viewState.isDrawerOpen {Color.black.opacity(0.25).ignoresSafeArea()- .onTapGesture { isDrawerOpen = false }+ .onTapGesture { viewState.isDrawerOpen = false }#if os(iOS).gesture(DragGesture(minimumDistance: 20)@@ -85,7 +93,7 @@ struct ChatView: View {let horizontal = value.translation.widthlet vertical = value.translation.heightguard abs(horizontal) > abs(vertical), horizontal < -40 else { return }- isDrawerOpen = false+ viewState.isDrawerOpen = false})#endif@@ -97,101 +105,90 @@ struct ChatView: View {.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading).onChange(of: isWideLayout) { newValue inif newValue {- isDrawerOpen = false+ viewState.isDrawerOpen = false}}- .onChange(of: isDrawerOpen) { isOpen in+ .onChange(of: viewState.isDrawerOpen) { isOpen inif isOpen {isInputFocused = false- wasDrawerOpen = true- } else if wasDrawerOpen {+ viewState.wasDrawerOpen = true+ } else if viewState.wasDrawerOpen {let shouldRestoreFocus = viewModel.isModelDownloaded&& !viewModel.isDownloading&& !viewModel.isGenerating- && !didDismissKeyboard- && !showSettings- && !showDeveloperSettings+ && !viewState.didDismissKeyboard+ && !viewState.showSettings+ && !viewState.showDeveloperSettingsif shouldRestoreFocus {requestInputFocus()}- wasDrawerOpen = false+ viewState.wasDrawerOpen = false}}- .onChange(of: viewModel.syncErrorMessage) { message in- guard let message else { return }- showToast(message, duration: 2)- viewModel.syncErrorMessage = nil- }- .onChange(of: viewModel.syncSuccessMessage) { message in- guard let message else { return }- showToast(message, duration: 2)- viewModel.syncSuccessMessage = nil- }- .onChange(of: viewModel.generationErrorMessage) { message in- guard let message else { return }- showToast(message, duration: 2)- viewModel.generationErrorMessage = nil- }- .onChange(of: modelSettings.useCustomModel) { _ in- viewModel.refreshModelDownloadInfo()+ .onChange(of: toastTrigger) { trigger in+ handleToastTrigger(trigger)}- .onChange(of: modelSettings.modelUrl) { _ in- viewModel.refreshModelDownloadInfo()- }- .onChange(of: modelSettings.mmprojUrl) { _ in+ .onChange(of: modelSettingsSignature) { _ inviewModel.refreshModelDownloadInfo()}}- .sheet(isPresented: $showSettings) {+ .sheet(isPresented: $viewState.showSettings) {SettingsView(isLoggedIn: appState.isLoggedIn,email: CredentialStore.shared.email,onSignOut: {appState.logout()- showSettings = false- isDrawerOpen = false+ viewState.showSettings = false+ viewState.isDrawerOpen = false},onSignIn: {- handleSignInRequest()+ viewState.pendingSignInRequest = true+ viewState.showSettings = false})}- .onChange(of: showSettings) { isPresented in+ .onChange(of: viewState.showSettings) { isPresented inif isPresented {- didDismissKeyboard = true+ viewState.didDismissKeyboard = trueisInputFocused = false+ } else if viewState.pendingSignInRequest {+ viewState.pendingSignInRequest = false+ handleSignInRequest()}}- .sheet(isPresented: $showAttachmentDownloads) {+ .sheet(isPresented: $viewState.showAttachmentDownloads) {AttachmentDownloadsSheet(downloads: viewModel.attachmentDownloads,sessionTitle: { viewModel.sessionTitle(for: $0) },onCancel: { viewModel.cancelAttachmentDownload($0) },- onDismiss: { showAttachmentDownloads = false }+ onDismiss: { viewState.showAttachmentDownloads = false })}- .sheet(isPresented: $showSignInComingSoon) {+ .sheet(isPresented: $viewState.showSignInComingSoon) {ComingSoonSheet(title: "Sign in", message: "Coming soon") {- showSignInComingSoon = false+ viewState.showSignInComingSoon = false}}- .platformFullScreenCover(isPresented: $showDeveloperSettings) {+ .sheet(isPresented: $viewState.showModelSettings) {+ ModelSettingsView(embeddedInNavigation: true)+ }+ .platformFullScreenCover(isPresented: $viewState.showDeveloperSettings) {DeveloperSettingsView { message inshowToast(message, duration: 2)}}- .alert("Developer settings", isPresented: $showDeveloperAlert) {+ .alert("Developer settings", isPresented: $viewState.showDeveloperAlert) {Button("Yes") {- showDeveloperSettings = true- isOpeningDeveloperSettings = false+ viewState.showDeveloperSettings = true+ viewState.isOpeningDeveloperSettings = false}Button("Cancel", role: .cancel) {- isOpeningDeveloperSettings = false+ viewState.isOpeningDeveloperSettings = false}} message: {Text("Are you sure that you want to modify Developer settings?")}- .alert(item: $deleteSession) { session in+ .alert(item: $viewState.deleteSession) { session inAlert(title: Text("Delete Chat"),message: Text("Are you sure you want to delete this chat?"),@@ -201,8 +198,22 @@ struct ChatView: View {secondaryButton: .cancel())}+ .confirmationDialog("Context limit reached", item: $viewModel.overflowAlert, titleVisibility: .visible) { alert in+ Button("Trim history") {+ viewModel.confirmOverflowTrim()+ }+ Button("Increase context") {+ viewModel.cancelOverflowDialog()+ viewState.showModelSettings = true+ }+ Button("Cancel", role: .cancel) {+ viewModel.cancelOverflowDialog()+ }+ } message: { alert in+ Text("Input uses \(alert.inputTokens) tokens (budget \(alert.inputBudget)).")+ }.overlay(alignment: .bottom) {- if let toastMessage {+ if let toastMessage = viewState.toastMessage {ToastView(message: toastMessage.text).padding(.bottom, EnsuSpacing.xl).transition(.move(edge: .bottom).combined(with: .opacity))@@ -220,12 +231,12 @@ struct ChatView: View {showsMenuButton: showsMenuButton,attachmentDownloadSummary: viewModel.attachmentDownloadSummary,modelDownloadState: viewModel.downloadToast,- onMenu: { isDrawerOpen.toggle() },+ onMenu: { viewState.isDrawerOpen.toggle() },onSignIn: {handleSignInRequest()},onAttachmentDownloads: {- showAttachmentDownloads = true+ viewState.showAttachmentDownloads = true})@@ -248,7 +259,7 @@ struct ChatView: View {isGenerating: viewModel.isGenerating,sessionId: viewModel.currentSessionId,keyboardHeight: keyboard.height,- inputBarHeight: viewModel.isModelDownloaded ? inputBarHeight : 0,+ inputBarHeight: viewModel.isModelDownloaded ? viewState.inputBarHeight : 0,emptyStateTitle: "Welcome",emptyStateSubtitle: "Start typing to begin a conversation",onEdit: { message in@@ -265,12 +276,12 @@ struct ChatView: View {viewModel.changeBranch(for: message, delta: delta)},onDismissKeyboard: {- didDismissKeyboard = true+ viewState.didDismissKeyboard = trueisInputFocused = false}).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)- .id(sessionTransitionId)+ .id(viewState.sessionTransitionId).transition(sessionTransition).onAppear {viewModel.autoStartModelDownloadIfNeeded()@@ -281,14 +292,7 @@ struct ChatView: View {.zIndex(0)if viewModel.isModelDownloaded {- let shouldAutoFocus = viewModel.isModelDownloaded- && !viewModel.isDownloading- && !viewModel.isGenerating- && !didAutoFocusInput- && !isDrawerOpen- && !didDismissKeyboard- && !showSettings- && !showDeveloperSettings+ let shouldAutoFocus = shouldAutoFocusInputMessageInputView(text: $viewModel.draftText,@@ -299,7 +303,7 @@ struct ChatView: View {isProcessingAttachments: viewModel.isProcessingAttachments,isAttachmentDownloadBlocked: viewModel.isAttachmentDownloadBlocked,onSend: {- didDismissKeyboard = true+ viewState.didDismissKeyboard = trueisInputFocused = falseviewModel.sendDraft()},@@ -319,28 +323,28 @@ struct ChatView: View {viewModel.removeAttachment(attachment)},onUserFocus: {- didDismissKeyboard = false+ viewState.didDismissKeyboard = false},onDismissKeyboard: {- didDismissKeyboard = true+ viewState.didDismissKeyboard = true},isFocused: $isInputFocused).onPreferenceChange(InputBarHeightKey.self) { newValue in- inputBarHeight = newValue+ viewState.inputBarHeight = newValue}.onAppear {if shouldAutoFocus {requestInputFocus()- didAutoFocusInput = true- didDismissKeyboard = false+ viewState.didAutoFocusInput = true+ viewState.didDismissKeyboard = false}}.onChange(of: shouldAutoFocus) { newValue inif newValue {requestInputFocus()- didAutoFocusInput = true- didDismissKeyboard = false+ viewState.didAutoFocusInput = true+ viewState.didDismissKeyboard = false}}.zIndex(1)@@ -362,12 +366,12 @@ struct ChatView: View {.zIndex(2)}}- .animation(.easeInOut(duration: 0.32), value: sessionTransitionId)+ .animation(.easeInOut(duration: 0.32), value: viewState.sessionTransitionId)}.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top).onChange(of: viewModel.currentSessionId) { _ inwithAnimation(.easeInOut(duration: 0.32)) {- sessionTransitionId = UUID()+ viewState.sessionTransitionId = UUID()}}}@@ -381,21 +385,21 @@ struct ChatView: View {email: CredentialStore.shared.email,onNewChat: {viewModel.startNewSession()- isDrawerOpen = false+ viewState.isDrawerOpen = false},onSelectSession: { session inviewModel.selectSession(session)- isDrawerOpen = false+ viewState.isDrawerOpen = false},onDeleteSession: { session in- deleteSession = session+ viewState.deleteSession = session},onSync: {viewModel.syncNow(showErrors: true, showSuccess: true)},onOpenSettings: {- isDrawerOpen = false- showSettings = true+ viewState.isDrawerOpen = false+ viewState.showSettings = true},onDeveloperTap: {handleDeveloperTap()@@ -407,19 +411,44 @@ struct ChatView: View {drawer} else {drawer- .offset(x: isDrawerOpen ? 0 : drawerHiddenOffset)- .animation(.easeOut(duration: 0.25), value: isDrawerOpen)+ .offset(x: viewState.isDrawerOpen ? 0 : drawerHiddenOffset)+ .animation(.easeOut(duration: 0.25), value: viewState.isDrawerOpen)+ }+ }++ private func handleToastTrigger(_ trigger: ToastTrigger) {+ if let message = trigger.syncError {+ showToast(message, duration: 2)+ viewModel.syncErrorMessage = nil+ return+ }+ if let message = trigger.syncSuccess {+ showToast(message, duration: 2)+ viewModel.syncSuccessMessage = nil+ return+ }+ if let message = trigger.generationError {+ showToast(message, duration: 2)+ viewModel.generationErrorMessage = nil}}private func showToast(_ text: String, duration: TimeInterval) {+ viewState.toastTask?.cancel()withAnimation(.easeOut(duration: 0.2)) {- toastMessage = ToastMessage(text: text)+ viewState.toastMessage = ToastMessage(text: text)}- DispatchQueue.main.asyncAfter(deadline: .now() + duration) {+ let nanoseconds = UInt64(max(0, duration) * 1_000_000_000)+ viewState.toastTask = Task { @MainActor in+ do {+ try await Task.sleep(nanoseconds: nanoseconds)+ } catch {+ return+ }withAnimation(.easeIn(duration: 0.2)) {- toastMessage = nil+ viewState.toastMessage = nil}+ viewState.toastTask = nil}}@@ -433,35 +462,65 @@ struct ChatView: View {if EnsuFeatureFlags.enableSignIn {isShowingAuth = true} else {- showSignInComingSoon = true+ viewState.showSignInComingSoon = true}}private func handleDeveloperTap() {+ guard EnsuFeatureFlags.enableSignIn else { return }// Don't allow switching endpoints for logged-in users.guard !appState.isLoggedIn else { return }let now = Date()- if let lastDeveloperTapAt,+ if let lastDeveloperTapAt = viewState.lastDeveloperTapAt,now.timeIntervalSince(lastDeveloperTapAt) > 2 {- developerTapCount = 0+ viewState.developerTapCount = 0}- lastDeveloperTapAt = now- developerTapCount += 1+ viewState.lastDeveloperTapAt = now+ viewState.developerTapCount += 1- guard developerTapCount >= 5 else { return }- developerTapCount = 0+ guard viewState.developerTapCount >= 5 else { return }+ viewState.developerTapCount = 0presentDeveloperPrompt()}private func presentDeveloperPrompt() {- guard !isOpeningDeveloperSettings else { return }- isOpeningDeveloperSettings = true- showDeveloperAlert = true+ guard !viewState.isOpeningDeveloperSettings else { return }+ viewState.isOpeningDeveloperSettings = true+ viewState.showDeveloperAlert = true}}+private final class ChatViewState: ObservableObject {+ @Published var isDrawerOpen = false+ @Published var showSettings = false+ @Published var toastMessage: ToastMessage?+ @Published var deleteSession: ChatSession?+ @Published var developerTapCount = 0+ @Published var lastDeveloperTapAt: Date?+ @Published var isOpeningDeveloperSettings = false+ @Published var showDeveloperAlert = false+ @Published var showDeveloperSettings = false+ @Published var showModelSettings = false+ @Published var showAttachmentDownloads = false+ @Published var showSignInComingSoon = false+ @Published var pendingSignInRequest = false+ @Published var didAutoFocusInput = false+ @Published var inputBarHeight: CGFloat = 0+ @Published var wasDrawerOpen = false+ @Published var didDismissKeyboard = false+ @Published var sessionTransitionId = UUID()++ var toastTask: Task<Void, Never>?+}++private struct ToastTrigger: Equatable {+ let syncError: String?+ let syncSuccess: String?+ let generationError: String?+}+private struct DownloadOnboardingView: View {let isDownloading: Boollet downloadPercent: Int?@@ -485,7 +544,7 @@ private struct DownloadOnboardingView: View {if let totalBytes, let percent = downloadPercent, percent >= 0 {let clamped = min(max(percent, 0), 100)let downloaded = Int64(Double(totalBytes) * Double(clamped) / 100.0)- return "Downloading... \(formatBytes(downloaded)) / \(formatBytes(totalBytes))"+ return "Downloading... \(downloaded.formattedFileSize) / \(totalBytes.formattedFileSize)"}if let statusText, !statusText.isEmpty {return statusText@@ -536,11 +595,6 @@ private struct DownloadOnboardingView: View {}}- private func formatBytes(_ bytes: Int64) -> String {- let formatter = ByteCountFormatter()- formatter.countStyle = .file- return formatter.string(fromByteCount: bytes)- }}private struct ToastMessage: Identifiable {diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swiftindex 583a34eced..2352576584 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift@@ -315,7 +315,7 @@ struct ChatAttachment: Identifiable, Equatable {}var formattedSize: String {- ByteCountFormatter.string(fromByteCount: size, countStyle: .file)+ ChatViewModel.fileSizeFormatter.string(fromByteCount: size)}var iconName: String {@@ -345,7 +345,7 @@ struct AttachmentDownloadItem: Identifiable, Equatable {var errorMessage: String? = nilvar formattedSize: String {- ByteCountFormatter.string(fromByteCount: size, countStyle: .file)+ ChatViewModel.fileSizeFormatter.string(fromByteCount: size)}}@@ -418,14 +418,29 @@ struct DownloadToastState: Identifiable, Equatable {var offerRetryDownload: Bool}+struct OverflowAlertState: Identifiable, Equatable {+ let id = UUID()+ let inputTokens: Int+ let inputBudget: Int+ let contextLength: Int+ let maxOutput: Int+}+@MainActorfinal class ChatViewModel: ObservableObject {- private static let defaultTemperature: Float = 0.7+ private static let defaultTemperature: Float = 0.5private static let systemPrompt = "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points. For math equations, put $$ on its own line (never inline). Example:\n$$\nx^2 + y^2 = z^2\n$$"+ private static let overflowSafetyTokens = 128+ private static let imageTokenEstimate = 768private static let sessionTitleMaxLength = 40private static let sessionSummaryMaxWords = 7private static let sessionSummaryStoreKey = "ensu.session_summaries"private static let sessionSummarySystemPrompt = "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words, no quotes, no emojis, no trailing punctuation, and output only the title."+ fileprivate static let fileSizeFormatter: ByteCountFormatter = {+ let formatter = ByteCountFormatter()+ formatter.countStyle = .file+ return formatter+ }()private let logger = EnsuLogging.shared.logger("ChatViewModel")@@ -434,6 +449,7 @@ final class ChatViewModel: ObservableObject {@Published var messages: [ChatMessage]@Published var streamingResponse: String = ""@Published var streamingParentId: UUID? = nil+ @Published var overflowAlert: OverflowAlertState? = nilvar displayedStreamingResponse: String {guard let activeSession = activeGenerationSessionId,@@ -488,6 +504,8 @@ final class ChatViewModel: ObservableObject {private var pendingSyncShowErrors = falseprivate var pendingSyncShowSuccess = falseprivate var modelDownloadLoggedStart = false+ private var pendingOverflow: PendingOverflow?+ private var overflowBypassMessageId: UUID?private var attachmentDownloadQueue: [String] = []private var attachmentDownloadTasks: [String: Task<Void, Never>] = [:]@@ -622,9 +640,7 @@ final class ChatViewModel: ObservableObject {var modelDownloadSizeText: String {guard let bytes = modelDownloadSizeBytes else { return "Approx. size varies by model" }- let formatter = ByteCountFormatter()- formatter.countStyle = .file- return "Approx. \(formatter.string(fromByteCount: bytes))"+ return "Approx. \(Self.fileSizeFormatter.string(fromByteCount: bytes))"}func sessionTitle(for sessionId: UUID) -> String {@@ -911,6 +927,24 @@ final class ChatViewModel: ObservableObject {provider.stopGeneration()}+ func confirmOverflowTrim() {+ guard let pendingOverflow else { return }+ guard let node = messageStore[pendingOverflow.sessionId]?.first(where: { $0.id == pendingOverflow.messageId }) else {+ cancelOverflowDialog()+ return+ }+ overflowBypassMessageId = pendingOverflow.messageId+ self.pendingOverflow = nil+ overflowAlert = nil+ startGeneration(for: node)+ }++ func cancelOverflowDialog() {+ pendingOverflow = nil+ overflowBypassMessageId = nil+ overflowAlert = nil+ }+func refreshModelDownloadInfo() {let target = modelSettings.currentTarget()isModelDownloaded = provider.isModelDownloaded(target: target)@@ -1093,6 +1127,32 @@ final class ChatViewModel: ObservableObject {generationTask?.cancel()sessionSummaryTask?.cancel()stopRequested = false++ let target = modelSettings.currentTarget()+ let prompt = buildPrompt(text: userNode.text, attachments: userNode.attachments)+ let historySelection = buildHistorySelection(+ sessionId: userNode.sessionId,+ promptText: prompt.text,+ promptImageCount: prompt.imageFiles.count,+ currentMessageId: userNode.id,+ target: target+ )++ if historySelection.wasTrimmed && overflowBypassMessageId != userNode.id {+ pendingOverflow = PendingOverflow(sessionId: userNode.sessionId, messageId: userNode.id)+ overflowAlert = OverflowAlertState(+ inputTokens: historySelection.inputTokens,+ inputBudget: historySelection.inputBudget,+ contextLength: target.contextLength ?? 4096,+ maxOutput: target.maxTokens ?? 1024+ )+ return+ }++ overflowBypassMessageId = nil+ pendingOverflow = nil+ overflowAlert = nil+let generationId = UUID()activeGenerationId = generationIdactiveGenerationSessionId = userNode.sessionId@@ -1104,8 +1164,6 @@ final class ChatViewModel: ObservableObject {downloadToast = nilrebuildMessages(for: userNode.sessionId)- let target = modelSettings.currentTarget()-generationTask = Task {do {try await provider.ensureModelReady(target: target) { progress in@@ -1139,8 +1197,7 @@ final class ChatViewModel: ObservableObject {return}- let prompt = buildPrompt(text: userNode.text, attachments: userNode.attachments)- let history = buildHistory(sessionId: userNode.sessionId, promptText: prompt.text, currentMessageId: userNode.id)+ let history = historySelection.messageslet systemMessage = InferenceMessage(text: Self.systemPrompt, role: .system, hasAttachments: false)let messages = [systemMessage] + history + [InferenceMessage(text: prompt.text, role: .user, hasAttachments: !userNode.attachments.isEmpty)]@@ -1920,6 +1977,18 @@ final class ChatViewModel: ObservableObject {return destination}+ private struct HistorySelection {+ let messages: [InferenceMessage]+ let inputTokens: Int+ let inputBudget: Int+ let wasTrimmed: Bool+ }++ private struct PendingOverflow {+ let sessionId: UUID+ let messageId: UUID+ }+private func buildPrompt(text: String, attachments: [ChatAttachment]) -> PromptResult {var prompt = textlet documents = attachments.filter { $0.kind == .document }@@ -1945,33 +2014,44 @@ final class ChatViewModel: ObservableObject {return PromptResult(text: prompt, imageFiles: imageFiles)}- private func buildHistory(sessionId: UUID, promptText: String, currentMessageId: UUID) -> [InferenceMessage] {+ private func buildHistorySelection(+ sessionId: UUID,+ promptText: String,+ promptImageCount: Int,+ currentMessageId: UUID,+ target: InferenceModelTarget+ ) -> HistorySelection {let path = buildSelectedPath(for: sessionId)- let history = path.prefix { $0.id != currentMessageId }- if history.isEmpty { return [] }+ let historyMessages = path.prefix { $0.id != currentMessageId }- let target = modelSettings.currentTarget()let contextSize: Int = target.contextLength ?? 4096let maxTokens: Int = target.maxTokens ?? 1024- var budget: Int = contextSize - maxTokens - 256- budget -= estimateTokens(promptText)- if budget <= 0 { return [] }+ let inputBudget = max(0, contextSize - maxTokens - Self.overflowSafetyTokens)+ let systemTokens = estimateTokens(Self.systemPrompt)+ let promptTokens = estimatePromptTokens(promptText: promptText, imageCount: promptImageCount)+ let historyTokens = historyMessages.reduce(0) { total, node in+ total + estimateTokens(historyText(node))+ }+ let inputTokens = systemTokens + promptTokens + historyTokens+ var remaining = inputBudget - systemTokens - promptTokens++ if remaining <= 0 || historyMessages.isEmpty {+ return HistorySelection(messages: [], inputTokens: inputTokens, inputBudget: inputBudget, wasTrimmed: inputTokens > inputBudget)+ }var selected: [InferenceMessage] = []- for node in history.reversed() {+ for node in historyMessages.reversed() {let text = historyText(node)let cost = estimateTokens(text)- if cost <= budget {+ if cost <= remaining {selected.append(InferenceMessage(text: text, role: node.role == .user ? .user : .assistant, hasAttachments: !node.attachments.isEmpty))- budget -= cost- } else if selected.isEmpty {- selected.append(InferenceMessage(text: trimToBudget(text, budget: budget), role: node.role == .user ? .user : .assistant, hasAttachments: !node.attachments.isEmpty))- break+ remaining -= cost} else {break}}- return selected.reversed()++ return HistorySelection(messages: selected.reversed(), inputTokens: inputTokens, inputBudget: inputBudget, wasTrimmed: inputTokens > inputBudget)}private func historyText(_ node: MessageNode) -> String {@@ -1996,9 +2076,18 @@ final class ChatViewModel: ObservableObject {max(1, text.count / 4)}+ private func estimateImageTokens(_ imageCount: Int) -> Int {+ imageCount * Self.imageTokenEstimate+ }++ private func estimatePromptTokens(promptText: String, imageCount: Int) -> Int {+ estimateTokens(promptText) + estimateImageTokens(imageCount)+ }+private func resolveTemperature() -> Float {let value = Float(modelSettings.temperature.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))- return value.map { max(0, $0) } ?? Self.defaultTemperature+ let resolved = value.map { max(0, $0) } ?? Self.defaultTemperature+ return min(max(resolved, 0.35), 0.7)}private struct MessageNode: Identifiable {diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swiftindex 7387ef3d8a..932dfd78ef 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swift@@ -8,8 +8,9 @@ struct LaTeXView: View {@Environment(\.colorScheme) private var colorSchemevar body: some View {+ let sanitizedLatex = latex.replacingOccurrences(of: "\\boxed", with: "")MathLabelView(- latex: latex,+ latex: sanitizedLatex,textColor: colorScheme == .dark? PlatformColor(hex: "#E8E4DF"): PlatformColor(hex: "#1A1A1A")@@ -26,6 +27,7 @@ private struct MathLabelView: UIViewRepresentable {let label = MTMathUILabel()label.fontSize = 16label.textColor = textColor+ label.contentInsets = UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)label.latex = latexreturn label}@@ -33,6 +35,7 @@ private struct MathLabelView: UIViewRepresentable {func updateUIView(_ label: MTMathUILabel, context: Context) {label.latex = latexlabel.textColor = textColor+ label.contentInsets = UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)}}#elseif os(macOS)@@ -44,6 +47,7 @@ private struct MathLabelView: NSViewRepresentable {let label = MTMathUILabel()label.fontSize = 16label.textColor = textColor+ label.contentInsets = NSEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)label.latex = latexreturn label}@@ -51,6 +55,7 @@ private struct MathLabelView: NSViewRepresentable {func updateNSView(_ label: MTMathUILabel, context: Context) {label.latex = latexlabel.textColor = textColor+ label.contentInsets = NSEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)}}#endif