π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
scroll fix, session title update logic and more
Prateek Sunal93fa6d7cc67d
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 d0822f134d..5f761deec7 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@@ -38,9 +38,11 @@ class RustChatRepository(val messages = runCatching { db.getMessages(session.uuid) }.getOrNull().orEmpty()val firstMessage = messages.firstOrNull()?.text.orEmpty()val lastMessage = messages.lastOrNull()?.text+ val isPlaceholder = session.title.isBlank() || session.title.equals("New Chat", ignoreCase = true)+ val seedTitle = if (isPlaceholder) firstMessage else session.titleChatSession(id = session.uuid,- title = sessionTitleFromText(firstMessage, fallback = session.title),+ title = sessionTitleFromText(seedTitle, fallback = session.title),lastMessagePreview = lastMessage,updatedAtMillis = session.updatedAtUs / 1000)@@ -132,6 +134,10 @@ class RustChatRepository(db.updateMessageText(messageId, text)}+ override fun updateSessionTitle(sessionId: String, title: String) = withDbRecovery {+ db.updateSessionTitle(sessionId, title)+ }+private fun openDb(): LlmChatDb {return LlmChatDb.open(mainDbFile.absolutePath,diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatRepository.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatRepository.ktindex 58c9413bdc..7f883e06d8 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatRepository.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/chat/ChatRepository.kt@@ -21,4 +21,5 @@ interface ChatRepository {): ChatMessagefun updateMessageText(messageId: String, text: String)+ fun updateSessionTitle(sessionId: String, title: String)}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 c854bbb99f..5b09b0b7f0 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@@ -41,10 +41,17 @@ data class Attachment(val isUploading: Boolean = false)-const val SessionTitleMaxLength = 50+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 = text.trim()+ val trimmed = sanitizeTitleText(text)if (trimmed.isBlank()) return fallbackreturn if (trimmed.length <= SessionTitleMaxLength) {trimmeddiff --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 408c68d7c0..02c83120fb 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@@ -62,6 +62,10 @@ class AppStore(private var pendingSyncErrorHandler: ((String) -> Unit)? = nullprivate var pendingSyncSuccessHandler: (() -> Unit)? = null+ private val sessionSummarySystemPrompt =+ "You are a title generator. Summarize this conversation into a 4-5 word chat title. Reply with only the title, no quotes."+ private val sessionSummaryMaxWords = 5+private val attachmentDownloads = mutableMapOf<String, AttachmentDownloadItem>()private val attachmentDownloadQueue = ArrayDeque<String>()private val attachmentDownloadActive = mutableMapOf<String, Job>()@@ -71,7 +75,7 @@ class AppStore(this.scope = scopesessionSummaries.clear()- sessionSummaries.putAll(runBlocking { sessionPreferences.sessionSummaries.first() })+ sessionSummaries.putAll(runBlocking { sessionPreferences.sessionSummaries.first() }.mapKeys { it.key.lowercase() })if (_state.value.chat.sessions.isEmpty()) {loadSessionsFromDb()@@ -82,7 +86,7 @@ class AppStore(scope.launch {sessionPreferences.sessionSummaries.collectLatest { summaries ->sessionSummaries.clear()- sessionSummaries.putAll(summaries)+ sessionSummaries.putAll(summaries.mapKeys { it.key.lowercase() })applySessionSummariesToState()}}@@ -218,7 +222,7 @@ class AppStore(messageStore.remove(sessionId)branchSelections.remove(sessionId)purgeAttachmentDownloads(sessionId)- sessionSummaries.remove(sessionId)+ sessionSummaries.remove(sessionId.lowercase())scope?.launch { sessionPreferences.setSessionSummary(sessionId, null) }val remaining = currentState.chat.sessions.filterNot { it.id == sessionId }@@ -1048,6 +1052,9 @@ class AppStore(} else {session.title}+ if (updatedTitle != session.title) {+ chatRepository.updateSessionTitle(sessionId, updatedTitle)+ }session.copy(title = updatedTitle,lastMessagePreview = preview,@@ -1064,7 +1071,7 @@ class AppStore(private fun applySessionSummariesToState() {_state.update { appState ->val updatedSessions = appState.chat.sessions.map { session ->- val summary = sessionSummaries[session.id]+ val summary = sessionSummaries[session.id.lowercase()]if (!summary.isNullOrBlank() && summary != session.title) {session.copy(title = summary)} else {@@ -1078,8 +1085,16 @@ class AppStore(private fun scheduleSessionSummary(sessionId: String) {val scope = scope ?: returnsessionSummaryJob?.cancel()+ if (sessionSummaries.containsKey(sessionId.lowercase())) return+ val summaryInput = buildSessionSummaryInput(sessionId) ?: return+ val target = resolveTarget(_state.value.modelSettings)+sessionSummaryJob = scope.launch(Dispatchers.Default) {- val summary = buildSessionSummary(sessionId) ?: return@launch+ val summary = generateSessionSummary(+ input = summaryInput.text,+ fallback = summaryInput.fallback,+ target = target+ ) ?: return@launchif (!isActive) return@launchwithContext(Dispatchers.Main) {applySessionSummary(sessionId, summary)@@ -1087,28 +1102,79 @@ class AppStore(}}- private fun buildSessionSummary(sessionId: String): String? {- val firstUserMessage = messageStore[sessionId]- ?.asSequence()- ?.filter { it.author == MessageAuthor.User }- ?.minByOrNull { it.timestampMillis }+ private data class SessionSummaryInput(val text: String, val fallback: String)++ private fun buildSessionSummaryInput(sessionId: String): SessionSummaryInput? {+ val messages = messageStore[sessionId].orEmpty()+ if (messages.isEmpty()) return null+ val firstUser = messages.filter { it.author == MessageAuthor.User }+ .minByOrNull { it.timestampMillis }?: return null- val summary = summarizeQuestion(firstUserMessage.text)- if (summary.isBlank()) return null- val existing = sessionSummaries[sessionId]- if (!existing.isNullOrBlank() && existing == summary) return null- return summary+ val assistants = messages.filter { it.author == MessageAuthor.Assistant }+ if (assistants.size != 1) return null+ val firstAssistant = assistants.first()+ if (firstAssistant.isInterrupted) return null++ val fallback = summarizeQuestion(firstUser.text)+ if (fallback.isBlank()) return null+ val input = "User: ${firstUser.text}\nAssistant: ${firstAssistant.text}"+ return SessionSummaryInput(text = input, fallback = fallback)+ }++ private suspend fun generateSessionSummary(+ input: String,+ fallback: String,+ target: LlmModelTarget+ ): String? {+ if (!llmProvider.isModelDownloaded(target)) {+ return sessionTitleFromText(fallback, fallback = fallback)+ }+ val cleanedInput = sanitizeTitleText(input)+ if (cleanedInput.isBlank()) return sessionTitleFromText(fallback, fallback = fallback)++ val messages = listOf(+ LlmMessage(text = sessionSummarySystemPrompt, role = LlmMessageRole.System),+ LlmMessage(text = cleanedInput, role = LlmMessageRole.User)+ )++ val buffer = StringBuilder()+ try {+ llmProvider.generateChat(+ target = target,+ messages = messages,+ imageFiles = emptyList(),+ temperature = 0.2f,+ maxTokens = 64+ ) { token ->+ buffer.append(token)+ }+ } catch (err: Throwable) {+ val fallbackSummary = summarizeQuestion(fallback)+ return if (fallbackSummary.isBlank()) null else sessionTitleFromText(fallbackSummary, fallback = fallback)+ }++ val raw = sanitizeTitleText(buffer.toString())+ if (raw.isBlank()) return null+ val words = raw.split(" ")+ .map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }+ .filter { it.isNotBlank() }+ if (words.isEmpty()) return null+ val summary = words.take(sessionSummaryMaxWords).joinToString(" ")+ return sessionTitleFromText(summary, fallback = fallback)}private fun applySessionSummary(sessionId: String, summary: String) {- if (summary.isBlank()) return- if (sessionSummaries[sessionId] == summary) return- sessionSummaries[sessionId] = summary- scope?.launch { sessionPreferences.setSessionSummary(sessionId, summary) }+ val sanitized = sessionTitleFromText(summary, fallback = "New Chat")+ if (sanitized.isBlank()) return+ val summaryKey = sessionId.lowercase()+ if (sessionSummaries[summaryKey] == sanitized) return+ sessionSummaries[summaryKey] = sanitized+ scope?.launch { sessionPreferences.setSessionSummary(sessionId, sanitized) }+ chatRepository.updateSessionTitle(sessionId, sanitized)_state.update { appState ->val updatedSessions = appState.chat.sessions.map { session ->if (session.id == sessionId) {- session.copy(title = summary)+ session.copy(title = sanitized)} else {session}@@ -1118,19 +1184,23 @@ class AppStore(}private fun summarizeQuestion(text: String): String {- val cleaned = text- .replace(Regex("[\r\n]+"), " ")- .replace(Regex("\\s+"), " ")- .trim()+ val cleaned = sanitizeTitleText(text)if (cleaned.isBlank()) return ""val words = cleaned.split(" ").map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }.filter { it.isNotBlank() }if (words.isEmpty()) return ""- val summaryWords = words.take(6)+ val summaryWords = words.take(sessionSummaryMaxWords)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()@@ -1369,7 +1439,7 @@ class AppStore(private fun loadSessionsFromDb() {val sessions = chatRepository.listSessions().map { session ->- val summary = sessionSummaries[session.id]+ val summary = sessionSummaries[session.id.lowercase()]if (!summary.isNullOrBlank()) {session.copy(title = summary)} else {diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swiftindex 009e363b5e..aac42e9a2f 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift@@ -22,7 +22,9 @@ struct ChatView: View {@State private var didAutoFocusInput = false@State private var focusRequestId = 0@State private var dismissKeyboardId = 0+ @State private var inputBarHeight: CGFloat = 0@State private var wasDrawerOpen = false+ @State private var didDismissKeyboard = falseprivate var editingMessage: ChatMessage? {guard let editingId = viewModel.editingMessageId else { return nil }@@ -73,7 +75,12 @@ struct ChatView: View {dismissKeyboardId += 1wasDrawerOpen = true} else if wasDrawerOpen {- let shouldRestoreFocus = viewModel.isModelDownloaded && !viewModel.isDownloading && !viewModel.isGenerating+ let shouldRestoreFocus = viewModel.isModelDownloaded+ && !viewModel.isDownloading+ && !viewModel.isGenerating+ && !didDismissKeyboard+ && !showSettings+ && !showDeveloperSettingsif shouldRestoreFocus {focusRequestId += 1}@@ -90,6 +97,11 @@ struct ChatView: View {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) { _ inviewModel.refreshModelDownloadInfo()}@@ -117,6 +129,12 @@ struct ChatView: View {})}+ .onChange(of: showSettings) { isPresented in+ if isPresented {+ didDismissKeyboard = true+ dismissKeyboardId += 1+ }+ }.sheet(isPresented: $showAttachmentDownloads) {AttachmentDownloadsSheet(downloads: viewModel.attachmentDownloads,@@ -180,90 +198,92 @@ struct ChatView: View {Divider().background(EnsuColor.border)- let showDownloadOnboarding = viewModel.messages.isEmpty && !viewModel.isGenerating && !viewModel.isModelDownloaded-ZStack(alignment: .top) {- VStack(spacing: 0) {- if showDownloadOnboarding {- DownloadOnboardingView(- isDownloading: viewModel.isDownloading,- downloadPercent: viewModel.downloadToast?.percent,- statusText: viewModel.downloadToast?.status,- totalBytes: viewModel.modelDownloadSizeBytes,- sizeText: viewModel.modelDownloadSizeText,- onDownload: {- viewModel.startModelDownload(userInitiated: true)- }- )- } else {- MessageListView(- messages: viewModel.messages,- streamingResponse: viewModel.displayedStreamingResponse,- streamingParentId: viewModel.displayedStreamingParentId,- isGenerating: viewModel.isGenerating,- sessionId: viewModel.currentSessionId,- keyboardHeight: keyboard.height,- emptyStateTitle: "Welcome",- emptyStateSubtitle: "Start typing to begin a conversation",- onEdit: { message in- viewModel.beginEditing(message: message)- },- onCopy: { message in- copyToPasteboard(message.text)- showToast("Copied to clipboard", duration: 1)- },- onRetry: { message in- viewModel.retryAssistantResponse(message)- },- onBranchChange: { message, delta in- viewModel.changeBranch(for: message, delta: delta)- }- )+ MessageListView(+ messages: viewModel.messages,+ streamingResponse: viewModel.displayedStreamingResponse,+ streamingParentId: viewModel.displayedStreamingParentId,+ isGenerating: viewModel.isGenerating,+ sessionId: viewModel.currentSessionId,+ keyboardHeight: keyboard.height,+ inputBarHeight: inputBarHeight,+ emptyStateTitle: "Welcome",+ emptyStateSubtitle: "Start typing to begin a conversation",+ onEdit: { message in+ viewModel.beginEditing(message: message)+ },+ onCopy: { message in+ copyToPasteboard(message.text)+ showToast("Copied to clipboard", duration: 1)+ },+ onRetry: { message in+ viewModel.retryAssistantResponse(message)+ },+ onBranchChange: { message, delta in+ viewModel.changeBranch(for: message, delta: delta)}-- if !showDownloadOnboarding {- let shouldAutoFocus = viewModel.isModelDownloaded && !viewModel.isDownloading && !viewModel.isGenerating && !didAutoFocusInput && !isDrawerOpen-- MessageInputView(- text: $viewModel.draftText,- attachments: $viewModel.draftAttachments,- isGenerating: viewModel.isGenerating,- isDownloading: viewModel.isDownloading,- editingMessage: editingMessage,- isProcessingAttachments: viewModel.isProcessingAttachments,- isAttachmentDownloadBlocked: viewModel.isAttachmentDownloadBlocked,- focusRequestId: focusRequestId,- dismissKeyboardId: dismissKeyboardId,- onSend: {- viewModel.sendDraft()- },- onStop: {- viewModel.stopGenerating()- },- onCancelEdit: {- viewModel.cancelEditing()- },- onAddImage: { data, name in- viewModel.addImageAttachment(data: data, fileName: name)- },- onAddDocument: { url in- viewModel.addDocumentAttachment(url: url)- },- onRemoveAttachment: { attachment in- viewModel.removeAttachment(attachment)- }- )- .onAppear {- if shouldAutoFocus {- focusRequestId += 1- didAutoFocusInput = true- }+ )+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)+ .overlay(alignment: .bottom) {+ let shouldAutoFocus = viewModel.isModelDownloaded+ && !viewModel.isDownloading+ && !viewModel.isGenerating+ && !didAutoFocusInput+ && !isDrawerOpen+ && !didDismissKeyboard+ && !showSettings+ && !showDeveloperSettings++ MessageInputView(+ text: $viewModel.draftText,+ attachments: $viewModel.draftAttachments,+ isGenerating: viewModel.isGenerating,+ isDownloading: viewModel.isDownloading,+ editingMessage: editingMessage,+ isProcessingAttachments: viewModel.isProcessingAttachments,+ isAttachmentDownloadBlocked: viewModel.isAttachmentDownloadBlocked,+ focusRequestId: focusRequestId,+ dismissKeyboardId: dismissKeyboardId,+ onSend: {+ viewModel.sendDraft()+ },+ onStop: {+ viewModel.stopGenerating()+ },+ onCancelEdit: {+ viewModel.cancelEditing()+ },+ onAddImage: { data, name in+ viewModel.addImageAttachment(data: data, fileName: name)+ },+ onAddDocument: { url in+ viewModel.addDocumentAttachment(url: url)+ },+ onRemoveAttachment: { attachment in+ viewModel.removeAttachment(attachment)+ },+ onUserFocus: {+ didDismissKeyboard = false+ },+ onDismissKeyboard: {+ didDismissKeyboard = true}- .onChange(of: shouldAutoFocus) { newValue in- if newValue {- focusRequestId += 1- didAutoFocusInput = true- }+ )+ .onPreferenceChange(InputBarHeightKey.self) { newValue in+ inputBarHeight = newValue+ }+ .onAppear {+ if shouldAutoFocus {+ focusRequestId += 1+ didAutoFocusInput = true+ didDismissKeyboard = false+ }+ }+ .onChange(of: shouldAutoFocus) { newValue in+ if newValue {+ focusRequestId += 1+ didAutoFocusInput = true+ didDismissKeyboard = false}}}@@ -273,17 +293,6 @@ struct ChatView: View {.onChange(of: viewModel.messages.count) { _ inviewModel.autoStartModelDownloadIfNeeded()}-- if let downloadToast = viewModel.downloadToast, !showDownloadOnboarding, downloadToast.phase != .loading {- DownloadToastView(state: downloadToast) {- viewModel.downloadToast = nil- } onRetry: {- viewModel.retryDownload()- } onCancel: {- viewModel.cancelDownload()- }- .padding(.top, EnsuSpacing.lg)- }}}.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)@@ -559,7 +568,7 @@ private struct ChatAppBar: View {private var modelProgressState: DownloadToastState? {guard let modelDownloadState else { return nil }switch modelDownloadState.phase {- case .loading:+ case .loading, .downloading:return modelDownloadStatedefault:return nildiff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swiftindex 73c0dd2972..922c69fd40 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift@@ -462,6 +462,7 @@ final class ChatViewModel: ObservableObject {@Published var currentSessionMissingAttachments: [AttachmentDownloadItem] = []@Published var syncErrorMessage: String?@Published var syncSuccessMessage: String?+ @Published var generationErrorMessage: String?private let provider: InferenceRsProviderprivate let chatDb: LlmChatDb@@ -490,7 +491,9 @@ final class ChatViewModel: ObservableObject {init() {logger.info("Initializing")- let summaries = Self.loadSessionSummaries()+ let summaries = Self.loadSessionSummaries().reduce(into: [String: String]()) { result, item in+ result[item.key.lowercased()] = item.value+ }let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?? FileManager.default.temporaryDirectory@@ -542,8 +545,10 @@ final class ChatViewModel: ObservableObject {let sortedMessages = messages.sorted { $0.createdAtUs < $1.createdAtUs }let firstUserMessage = sortedMessages.first(where: { $0.sender == .selfUser })?.text ?? ""let lastMessage = sortedMessages.last?.text ?? ""- let summary = summaries[session.uuid]- let seedTitle = summary ?? firstUserMessage+ let summary = summaries[session.uuid.lowercased()]+ let isPlaceholderTitle = session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||+ session.title.caseInsensitiveCompare("New chat") == .orderedSame+ let seedTitle = summary ?? (isPlaceholderTitle ? firstUserMessage : session.title)let title = Self.sessionTitle(from: seedTitle, fallback: session.title)return ChatSession(id: id,@@ -673,8 +678,15 @@ final class ChatViewModel: ObservableObject {streamingParentId = nildownloadToast = nil}++ if let nodes = messageStore[session.id] {+ for node in nodes {+ logger.info("Message deleted", details: "id=\(node.id.uuidString) session=\(session.id.uuidString) role=\(node.role.rawValue)")+ }+ }+ logger.info("Session deleted", details: "id=\(session.id.uuidString)")try? chatDb.deleteSession(uuid: session.id.uuidString)- sessionSummaries.removeValue(forKey: session.id.uuidString)+ sessionSummaries.removeValue(forKey: sessionSummaryKey(session.id))persistSessionSummaries()sessions.removeAll { $0.id == session.id }@@ -716,7 +728,6 @@ final class ChatViewModel: ObservableObject {private func performSync(showErrors: Bool, showSuccess: Bool) {let log = loggerguard let auth = buildSyncAuth() else {- log.warning("Sync skipped", details: "not logged in")if showErrors {syncErrorMessage = "Sync failed: Sign in to sync"}@@ -825,11 +836,6 @@ final class ChatViewModel: ObservableObject {let attachments = draftAttachmentsguard !trimmed.isEmpty || !attachments.isEmpty else { return }- logger.info(- "Sent message",- details: "len=\(trimmed.count) attachments=\(attachments.count) edited=\(editingMessageId != nil)"- )-let sessionId = currentSessionId ?? createSessionForDraft()if !missingAttachments(for: sessionId).isEmpty {@@ -864,6 +870,11 @@ final class ChatViewModel: ObservableObject {return}+ logger.info(+ "Sent message",+ details: "id=\(messageId.uuidString) session=\(sessionId.uuidString) len=\(trimmed.count) attachments=\(attachments.count) edited=\(editingMessageId != nil)"+ )+let timestamp = Date(timeIntervalSince1970: Double(inserted.createdAtUs) / 1_000_000.0)let userNode = MessageNode(@@ -963,12 +974,38 @@ final class ChatViewModel: ObservableObject {}func autoStartModelDownloadIfNeeded() {- guard hasRequestedModelDownload else { return }guard !isDownloading && !isGenerating else { return }- if isModelDownloaded {+ let target = modelSettings.currentTarget()+ let isDownloaded = provider.isModelDownloaded(target: target)+ isModelDownloaded = isDownloaded+ if !isDownloaded {return}- startModelDownload(userInitiated: false)+ modelDownloadSizeBytes = nil+ modelDownloadTask?.cancel()+ modelDownloadTask = Task { [weak self] in+ guard let self else { return }+ do {+ try await self.provider.ensureModelReady(target: target) { progress in+ Task { @MainActor in+ self.handleProgress(progress)+ }+ }+ } catch {+ if self.isCancellation(error) {+ return+ }+ await MainActor.run {+ self.downloadToast = DownloadToastState(+ phase: .errorLoad,+ percent: -1,+ status: error.localizedDescription,+ offerRetryDownload: true+ )+ self.isDownloading = false+ }+ }+ }}func cancelDownload() {@@ -1032,6 +1069,7 @@ final class ChatViewModel: ObservableObject {let sessionId = created.flatMap { UUID(uuidString: $0.uuid) } ?? UUID()let updatedAt = created.map { Date(timeIntervalSince1970: Double($0.updatedAtUs) / 1_000_000.0) } ?? Date()+ logger.info("Session created", details: "id=\(sessionId.uuidString)")let session = ChatSession(id: sessionId, title: created?.title ?? "New chat", lastMessage: "", updatedAt: updatedAt)sessions.insert(session, at: 0)currentSessionId = session.id@@ -1122,15 +1160,27 @@ final class ChatViewModel: ObservableObject {finishGeneration(parent: userNode, response: buffer, tokenCount: tokenCount, totalTimeMs: summary.totalTimeMs, interrupted: false, generationId: generationId)} catch {- let interrupted = stopRequested || error.localizedDescription.lowercased().contains("cancel")- finishGeneration(parent: userNode, response: buffer, tokenCount: tokenCount, totalTimeMs: nil, interrupted: interrupted, generationId: generationId)+ let wasCancelled = stopRequested || isCancellation(error)+ if activeGenerationId == generationId && !wasCancelled {+ let details = "session=\(userNode.sessionId.uuidString) promptLen=\(prompt.text.count) responseLen=\(buffer.count) tokens=\(tokenCount)"+ logger.error("Generation failed", error, details: details)+ generationErrorMessage = "Response failed. Try again."+ }+ finishGeneration(parent: userNode, response: buffer, tokenCount: tokenCount, totalTimeMs: nil, interrupted: true, generationId: generationId)}}}private func finishGeneration(parent: MessageNode, response: String, tokenCount: Int, totalTimeMs: Int64?, interrupted: Bool, generationId: UUID) {let trimmed = response.trimmingCharacters(in: .whitespacesAndNewlines)- if !trimmed.isEmpty {+ let isActiveGeneration = activeGenerationId == generationId+ if trimmed.isEmpty {+ if isActiveGeneration && !interrupted && generationErrorMessage == nil {+ let details = "session=\(parent.sessionId.uuidString) promptLen=\(parent.text.count)"+ logger.warning("Generation returned empty response", details: details)+ generationErrorMessage = "No response from model. Try again."+ }+ } else {let tokensPerSecond: Double? = {guard let totalTimeMs, totalTimeMs > 0 else { return nil }return Double(tokenCount) / (Double(totalTimeMs) / 1000.0)@@ -1144,6 +1194,7 @@ final class ChatViewModel: ObservableObject {parentMessageUuid: parent.id.uuidString,attachments: meta), let assistantId = UUID(uuidString: inserted.uuid) {+ logger.info("Message created", details: "id=\(assistantId.uuidString) session=\(parent.sessionId.uuidString) role=assistant")let timestamp = Date(timeIntervalSince1970: Double(inserted.createdAtUs) / 1_000_000.0)let assistant = MessageNode(id: assistantId,@@ -1163,7 +1214,7 @@ final class ChatViewModel: ObservableObject {}}- if activeGenerationId == generationId {+ if isActiveGeneration {isGenerating = falseisDownloading = falsestreamingResponse = ""@@ -1411,8 +1462,11 @@ final class ChatViewModel: ObservableObject {let sortedMessages = messages.sorted { $0.createdAtUs < $1.createdAtUs }let firstUserMessage = sortedMessages.first(where: { $0.sender == .selfUser })?.text ?? ""let lastMessage = sortedMessages.last?.text ?? ""- let summary = sessionSummaries[session.uuid]- let title = summary ?? Self.sessionTitle(from: firstUserMessage, fallback: session.title)+ let summary = sessionSummaries[sessionSummaryKey(session.uuid)]+ let isPlaceholderTitle = session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||+ session.title.caseInsensitiveCompare("New chat") == .orderedSame+ let seedTitle = summary ?? (isPlaceholderTitle ? firstUserMessage : session.title)+ let title = Self.sessionTitle(from: seedTitle, fallback: session.title)return ChatSession(id: id,title: title,@@ -1609,7 +1663,11 @@ final class ChatViewModel: ObservableObject {let isPlaceholderTitle = session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||session.title.caseInsensitiveCompare("New chat") == .orderedSameif isPlaceholderTitle {- updated.title = Self.sessionTitle(from: preview, fallback: session.title)+ let updatedTitle = Self.sessionTitle(from: preview, fallback: session.title)+ if updatedTitle != session.title {+ _ = try? chatDb.updateSessionTitle(uuid: sessionId.uuidString, title: updatedTitle)+ }+ updated.title = updatedTitle}updated.lastMessage = previewupdated.updatedAt = date@@ -1619,9 +1677,10 @@ final class ChatViewModel: ObservableObject {private func scheduleSessionSummary(for sessionId: UUID) {sessionSummaryTask?.cancel()- guard sessionSummaries[sessionId.uuidString] == nil else { return }+ let summaryKey = sessionSummaryKey(sessionId)+ guard sessionSummaries[summaryKey] == nil else { return }guard let summaryInput = buildSessionSummaryInput(sessionId: sessionId) else { return }- let existingSummary = sessionSummaries[sessionId.uuidString]+ let existingSummary = sessionSummaries[summaryKey]let target = modelSettings.currentTarget()let provider = provider@@ -1653,10 +1712,7 @@ final class ChatViewModel: ObservableObject {guard let nodes = messageStore[sessionId], !nodes.isEmpty else { return nil }let sorted = nodes.sorted(by: { $0.timestamp < $1.timestamp })guard let firstUser = sorted.first(where: { $0.role == .user }) else { return nil }- let assistants = sorted.filter { $0.role == .assistant }- guard assistants.count == 1, let firstAssistant = assistants.first else { return nil }-- let input = "User: \(firstUser.text)\nAssistant: \(firstAssistant.text)"+ let input = "User: \(firstUser.text)"let fallback = Self.summarizeQuestion(firstUser.text)return (text: input, fallback: fallback)}@@ -1664,9 +1720,11 @@ final class ChatViewModel: ObservableObject {private func applySessionSummary(sessionId: UUID, summary: String) {let sanitized = Self.sessionTitle(from: summary, fallback: "New chat")guard !sanitized.isEmpty else { return }- if sessionSummaries[sessionId.uuidString] == sanitized { return }- sessionSummaries[sessionId.uuidString] = sanitized+ let summaryKey = sessionSummaryKey(sessionId)+ if sessionSummaries[summaryKey] == sanitized { return }+ sessionSummaries[summaryKey] = sanitizedpersistSessionSummaries()+ _ = try? chatDb.updateSessionTitle(uuid: sessionId.uuidString, title: sanitized)sessions = sessions.map { session inguard session.id == sessionId else { return session }var updated = session@@ -1680,6 +1738,14 @@ final class ChatViewModel: ObservableObject {UserDefaults.standard.set(data, forKey: Self.sessionSummaryStoreKey)}+ private func sessionSummaryKey(_ id: UUID) -> String {+ id.uuidString.lowercased()+ }++ private func sessionSummaryKey(_ id: String) -> String {+ id.lowercased()+ }+private static func loadSessionSummaries() -> [String: String] {guard let data = UserDefaults.standard.data(forKey: Self.sessionSummaryStoreKey) else { return [:] }return (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swiftindex 0c37719018..0447a4d6c2 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift@@ -19,6 +19,8 @@ struct MessageInputView: View {let onAddImage: (Data, String?) -> Voidlet onAddDocument: (URL) -> Voidlet onRemoveAttachment: (ChatAttachment) -> Void+ let onUserFocus: () -> Void+ let onDismissKeyboard: () -> Void@StateObject private var keyboard = KeyboardObserver()@FocusState private var isFocused: Bool@@ -93,6 +95,11 @@ struct MessageInputView: View {HStack(alignment: .bottom, spacing: EnsuSpacing.sm) {TextField(placeholder, text: $text, axis: .vertical).focused($isFocused)+ .onChange(of: isFocused) { focused in+ if focused {+ onUserFocus()+ }+ }.lineLimit(1...5).font(EnsuTypography.message).foregroundStyle(EnsuColor.textPrimary)@@ -102,6 +109,9 @@ struct MessageInputView: View {.onSubmit {if canSend {onSend()+ isFocused = false+ hideKeyboard()+ onDismissKeyboard()}}@@ -143,6 +153,9 @@ struct MessageInputView: View {} else if isSendEnabled {hapticMedium()onSend()+ isFocused = false+ hideKeyboard()+ onDismissKeyboard()}} label: {if sendIcon == "StopIcon" {@@ -172,12 +185,19 @@ struct MessageInputView: View {.padding(.horizontal, EnsuSpacing.inputHorizontal).padding(.vertical, inputVerticalPadding).frame(maxWidth: .infinity)- .background(EnsuColor.fillFaint)+ .background(.ultraThinMaterial).clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input + 4, style: .continuous))+ .shadow(color: Color.black.opacity(0.12), radius: 10, x: 0, y: 6).padding(.horizontal, EnsuSpacing.pageHorizontal).padding(.bottom, bottomPadding)}.frame(maxWidth: .infinity, alignment: .leading)+ .background(+ GeometryReader { proxy in+ Color.clear+ .preference(key: InputBarHeightKey.self, value: proxy.size.height)+ }+ )}if keyboard.isVisible {@@ -185,19 +205,21 @@ struct MessageInputView: View {hapticTap()isFocused = falsehideKeyboard()+ onDismissKeyboard()} label: {Image(systemName: "keyboard.chevron.compact.down").font(.system(size: 18, weight: .semibold))- .frame(width: 36, height: 36)- .background(EnsuColor.fillFaint)+ .scaleEffect(0.8)+ .padding(12)+ .background(.ultraThinMaterial).clipShape(Circle())+ .shadow(color: Color.black.opacity(0.12), radius: 6, x: 0, y: 2)}.padding(.trailing, EnsuSpacing.pageHorizontal).padding(.bottom, 64)}}.padding(.top, EnsuSpacing.sm)- .background(EnsuColor.backgroundBase).onAppear {if focusRequestId > 0 {requestFocus()@@ -302,6 +324,14 @@ struct MessageInputView: View {.padding(.horizontal, EnsuSpacing.pageHorizontal)}}++struct InputBarHeightKey: PreferenceKey {+ static var defaultValue: CGFloat = 0++ static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {+ value = nextValue()+ }+}#elseimport SwiftUIdiff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swiftindex 9fde094a9a..540b6f726e 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift@@ -12,6 +12,7 @@ struct MessageListView: View {let isGenerating: Boollet sessionId: UUID?let keyboardHeight: CGFloat+ let inputBarHeight: CGFloatlet emptyStateTitle: Stringlet emptyStateSubtitle: String?let onEdit: (ChatMessage) -> Void@@ -24,6 +25,7 @@ struct MessageListView: View {@State private var previewItem: AttachmentPreviewItem?@State private var lastHapticLength = 0@State private var wasAtBottomBeforeKeyboard = false+ @State private var isUserDragging = false#if os(iOS)@State private var haptic = UIImpactFeedbackGenerator(style: .medium)#endif@@ -32,83 +34,36 @@ struct MessageListView: View {GeometryReader { proxy inScrollViewReader { scrollProxy inScrollView {- LazyVStack(alignment: .leading, spacing: EnsuSpacing.lg) {- if messages.isEmpty && !isGenerating {- VStack(spacing: EnsuSpacing.sm) {- Text(emptyStateTitle)- .font(EnsuTypography.h2)- .foregroundStyle(EnsuColor.textPrimary)- if let emptyStateSubtitle {- Text(emptyStateSubtitle)- .font(EnsuTypography.body)- .foregroundStyle(EnsuColor.textMuted)- }- }- .multilineTextAlignment(.center)- .frame(maxWidth: .infinity, minHeight: proxy.size.height * 0.6)- }-- ForEach(messages) { message in- if message.role == .user {- UserMessageBubbleView(- message: message,- onEdit: { onEdit(message) },- onCopy: { onCopy(message) },- onBranchChange: { delta in onBranchChange(message, delta) },- onOpenAttachment: openAttachment- )- .id(message.id)- } else {- AssistantMessageBubbleView(- message: message,- onCopy: { onCopy(message) },- onRetry: { onRetry(message) },- onBranchChange: { delta in onBranchChange(message, delta) },- onOpenAttachment: openAttachment- )- .id(message.id)- }-- if isGenerating, streamingParentId == message.id {- StreamingBubbleView(text: streamingResponse)- .id("streaming-\(message.id.uuidString)")- }- }-- if isGenerating, streamingParentId == nil {- StreamingBubbleView(text: streamingResponse)- .id("streaming")- }-- Color.clear- .frame(height: 1)- .id("bottom")- .background(- GeometryReader { geo in- Color.clear- .preference(key: BottomOffsetKey.self, value: geo.frame(in: .named("scroll")).maxY)- }- )- }- .padding(.horizontal, EnsuSpacing.pageHorizontal)- .padding(.vertical, EnsuSpacing.lg)+ messageListContent()}+ .id(sessionId).coordinateSpace(name: "scroll").simultaneousGesture(- DragGesture().onChanged { _ in- autoScrollEnabled = false- }+ DragGesture()+ .onChanged { _ in+ isUserDragging = true+ autoScrollEnabled = false+ }+ .onEnded { _ in+ isUserDragging = false+ if isAtBottom {+ autoScrollEnabled = true+ }+ }).onPreferenceChange(BottomOffsetKey.self) { value in- let threshold: CGFloat = 24- isAtBottom = value < proxy.size.height + threshold+ let threshold: CGFloat = EnsuSpacing.xxxl+ let distanceToBottom = value - proxy.size.height+ isAtBottom = distanceToBottom <= threshold}.onChange(of: messages.count) { _ inscrollToBottom(scrollProxy)}.onChange(of: sessionId) { _ inautoScrollEnabled = true- scrollToBottom(scrollProxy, force: true)+ DispatchQueue.main.async {+ scrollToBottom(scrollProxy, force: true, animated: false)+ }}.onChange(of: streamingResponse) { newValue in#if os(iOS)@@ -121,7 +76,7 @@ struct MessageListView: View {}}#endif- scrollToBottom(scrollProxy)+ scrollToBottom(scrollProxy, animated: false)}.onChange(of: keyboardHeight) { newValue inif newValue > 0 {@@ -129,12 +84,17 @@ struct MessageListView: View {}if wasAtBottomBeforeKeyboard {autoScrollEnabled = true- scrollToBottom(scrollProxy, force: true)+ scrollToBottom(scrollProxy, force: true, animated: false)}if newValue == 0 {wasAtBottomBeforeKeyboard = false}}+ .onChange(of: inputBarHeight) { _ in+ if autoScrollEnabled && !isUserDragging {+ scrollToBottom(scrollProxy, force: true, animated: false)+ }+ }.onChange(of: isGenerating) { newValue inif newValue {autoScrollEnabled = true@@ -142,20 +102,28 @@ struct MessageListView: View {#if os(iOS)haptic.prepare()#endif- scrollToBottom(scrollProxy, force: true)+ #if os(iOS) || os(macOS)+ if #available(iOS 17.0, macOS 14.0, *) {+ scrollToBottom(scrollProxy, force: true, animated: false)+ } else {+ scrollToBottom(scrollProxy, force: true, animated: false)+ }+ #else+ scrollToBottom(scrollProxy, force: true, animated: false)+ #endif}}.onChange(of: isAtBottom) { newValue in- if newValue && isGenerating {+ if newValue && !isUserDragging {autoScrollEnabled = true- scrollToBottom(scrollProxy, force: true)+ scrollToBottom(scrollProxy, force: true, animated: false)}}.onAppear {#if os(iOS)haptic.prepare()#endif- scrollToBottom(scrollProxy, force: true)+ scrollToBottom(scrollProxy, force: true, animated: false)}}}@@ -164,9 +132,88 @@ struct MessageListView: View {}}- private func scrollToBottom(_ proxy: ScrollViewProxy, force: Bool = false) {+ @ViewBuilder+ private func messageListContent() -> some View {+ VStack(alignment: .leading, spacing: 0) {+ LazyVStack(alignment: .leading, spacing: EnsuSpacing.lg) {+ if messages.isEmpty && !isGenerating {+ VStack(spacing: EnsuSpacing.sm) {+ Text(emptyStateTitle)+ .font(EnsuTypography.h2)+ .foregroundStyle(EnsuColor.textPrimary)+ if let emptyStateSubtitle {+ Text(emptyStateSubtitle)+ .font(EnsuTypography.body)+ .foregroundStyle(EnsuColor.textMuted)+ }+ }+ .multilineTextAlignment(.center)+ .frame(maxWidth: .infinity, alignment: .top)+ .padding(.top, EnsuSpacing.lg)+ }++ ForEach(messages) { message in+ if message.role == .user {+ UserMessageBubbleView(+ message: message,+ onEdit: { onEdit(message) },+ onCopy: { onCopy(message) },+ onBranchChange: { delta in onBranchChange(message, delta) },+ onOpenAttachment: openAttachment+ )+ .id(message.id)+ } else {+ AssistantMessageBubbleView(+ message: message,+ onCopy: { onCopy(message) },+ onRetry: { onRetry(message) },+ onBranchChange: { delta in onBranchChange(message, delta) },+ onOpenAttachment: openAttachment+ )+ .id(message.id)+ }++ if isGenerating, streamingParentId == message.id {+ StreamingBubbleView(text: streamingResponse)+ .id("streaming-\(message.id.uuidString)")+ }+ }++ if isGenerating, streamingParentId == nil {+ StreamingBubbleView(text: streamingResponse)+ .id("streaming")+ }+ }+ .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .padding(.top, EnsuSpacing.lg)+ .padding(.bottom, EnsuSpacing.lg)++ Color.clear+ .frame(height: contentBottomPadding)+ .id("bottom")+ .background(+ GeometryReader { geo in+ Color.clear+ .preference(key: BottomOffsetKey.self, value: geo.frame(in: .named("scroll")).maxY)+ }+ )+ }+ }++ private var contentBottomPadding: CGFloat {+ let fallbackPadding = EnsuSpacing.xxxl + EnsuSpacing.xxl + 60+ let measuredPadding = inputBarHeight > 0 ? inputBarHeight + EnsuSpacing.md : fallbackPadding+ let basePadding = max(fallbackPadding, measuredPadding)+ return max(basePadding, keyboardHeight + EnsuSpacing.xxl)+ }++ private func scrollToBottom(_ proxy: ScrollViewProxy, force: Bool = false, animated: Bool = true) {guard force || (autoScrollEnabled && isAtBottom) else { return }- withAnimation(.easeOut(duration: 0.2)) {+ if animated {+ withAnimation(.easeOut(duration: 0.2)) {+ proxy.scrollTo("bottom", anchor: .bottom)+ }+ } else {proxy.scrollTo("bottom", anchor: .bottom)}}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Info.plist b/mobile/native/darwin/Apps/ensu/ensu/Info.plistindex 8637ed6b73..87482602a8 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Info.plist+++ b/mobile/native/darwin/Apps/ensu/ensu/Info.plist@@ -24,7 +24,7 @@<string>0.1.0</string><key>CFBundleVersion</key>- <string>4</string>+ <string>6</string><key>UILaunchStoryboardName</key><string>LaunchScreen</string>diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swiftindex d8bae492f8..8f18c4a728 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift@@ -57,7 +57,7 @@ final class ModelSettingsStore: ObservableObject {let url = useCustom ? modelUrl : Defaults.modelUrllet mmproj = useCustom ? (mmprojUrl.isEmpty ? nil : mmprojUrl) : Defaults.mmprojUrllet context = Int(contextLength)- let maxOutput = Int(maxTokens)+ let maxOutput = Int(maxTokens).flatMap { $0 > 0 ? $0 : nil }let id = useCustom ? "custom:\(url)" : "default"return InferenceModelTarget(id: id, url: url, mmprojUrl: mmproj, contextLength: context, maxTokens: maxOutput)}diff --git a/rust/llmchat_db_uniffi/src/api.rs b/rust/llmchat_db_uniffi/src/api.rsindex 8de67c51dc..d2b8a9fef7 100644--- a/rust/llmchat_db_uniffi/src/api.rs+++ b/rust/llmchat_db_uniffi/src/api.rs@@ -165,6 +165,11 @@ impl LlmChatDb {Ok(self.inner.delete_session(uuid)?)}+ pub fn update_session_title(&self, uuid: String, title: String) -> Result<(), DbError> {+ let uuid = Uuid::parse_str(&uuid).map_err(|e| DbError::Message(e.to_string()))?;+ Ok(self.inner.update_session_title(uuid, &title)?)+ }+pub fn insert_message(&self,session_uuid: String,