π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
fix to utf8 and other ui fixes
Prateek Sunal44bbfca2ac20
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 9569d0843f..abd68c803a 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@@ -361,7 +361,7 @@ private fun MessageList(state = listState,contentPadding = PaddingValues(top = EnsuSpacing.pageVertical.dp,- bottom = (EnsuSpacing.xxxl + EnsuSpacing.xl).dp + imePadding+ bottom = (EnsuSpacing.xxxl + EnsuSpacing.xl).dp),verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)) {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 a4069664b8..69356d48ca 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@@ -424,7 +424,9 @@ class InferenceRsProvider(when (event) {is GenerateEvent.Text -> {currentJobId = event.jobId- onToken(event.text)+ if (event.text.isNotEmpty()) {+ onToken(event.text)+ }}is GenerateEvent.Done -> Unitis GenerateEvent.Error -> {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 02c83120fb..7a14965d26 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@@ -63,7 +63,7 @@ class AppStore(private var pendingSyncSuccessHandler: (() -> Unit)? = nullprivate val sessionSummarySystemPrompt =- "You are a title generator. Summarize this conversation into a 4-5 word chat title. Reply with only the title, no quotes."+ "You are a title generator. Rewrite the message in 4-5 words for a chat title. Reply with only the title, no quotes."private val sessionSummaryMaxWords = 5private val attachmentDownloads = mutableMapOf<String, AttachmentDownloadItem>()diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swiftindex aac42e9a2f..ffbe65405d 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift@@ -20,8 +20,7 @@ struct ChatView: View {@State private var showDeveloperSettings = false@State private var showAttachmentDownloads = false@State private var didAutoFocusInput = false- @State private var focusRequestId = 0- @State private var dismissKeyboardId = 0+ @FocusState private var isInputFocused: Bool@State private var inputBarHeight: CGFloat = 0@State private var wasDrawerOpen = false@State private var didDismissKeyboard = false@@ -72,7 +71,7 @@ struct ChatView: View {}.onChange(of: isDrawerOpen) { isOpen inif isOpen {- dismissKeyboardId += 1+ isInputFocused = falsewasDrawerOpen = true} else if wasDrawerOpen {let shouldRestoreFocus = viewModel.isModelDownloaded@@ -82,7 +81,7 @@ struct ChatView: View {&& !showSettings&& !showDeveloperSettingsif shouldRestoreFocus {- focusRequestId += 1+ requestInputFocus()}wasDrawerOpen = false}@@ -132,7 +131,7 @@ struct ChatView: View {.onChange(of: showSettings) { isPresented inif isPresented {didDismissKeyboard = true- dismissKeyboardId += 1+ isInputFocused = false}}.sheet(isPresented: $showAttachmentDownloads) {@@ -221,6 +220,10 @@ struct ChatView: View {},onBranchChange: { message, delta inviewModel.changeBranch(for: message, delta: delta)+ },+ onDismissKeyboard: {+ didDismissKeyboard = true+ isInputFocused = false}).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)@@ -242,8 +245,6 @@ struct ChatView: View {editingMessage: editingMessage,isProcessingAttachments: viewModel.isProcessingAttachments,isAttachmentDownloadBlocked: viewModel.isAttachmentDownloadBlocked,- focusRequestId: focusRequestId,- dismissKeyboardId: dismissKeyboardId,onSend: {viewModel.sendDraft()},@@ -267,21 +268,22 @@ struct ChatView: View {},onDismissKeyboard: {didDismissKeyboard = true- }+ },+ isFocused: $isInputFocused).onPreferenceChange(InputBarHeightKey.self) { newValue ininputBarHeight = newValue}.onAppear {if shouldAutoFocus {- focusRequestId += 1+ requestInputFocus()didAutoFocusInput = truedidDismissKeyboard = false}}.onChange(of: shouldAutoFocus) { newValue inif newValue {- focusRequestId += 1+ requestInputFocus()didAutoFocusInput = truedidDismissKeyboard = false}@@ -349,6 +351,12 @@ struct ChatView: View {}}+ private func requestInputFocus() {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {+ isInputFocused = true+ }+ }+private func handleDeveloperTap() {// Don't allow switching endpoints for logged-in users.guard !appState.isLoggedIn else { return }diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swiftindex 922c69fd40..97d8c5e4a3 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift@@ -421,7 +421,7 @@ final class ChatViewModel: ObservableObject {private static let sessionTitleMaxLength = 40private static let sessionSummaryMaxWords = 5private static let sessionSummaryStoreKey = "ensu.session_summaries"- private static let sessionSummarySystemPrompt = "You are a title generator. Summarize this conversation into a 4-5 word chat title. Reply with only the title, no quotes."+ private static let sessionSummarySystemPrompt = "You are a title generator. Rewrite the message in 4-5 words for a chat title. Reply with only the title, no quotes."private let logger = EnsuLogging.shared.logger("ChatViewModel")@@ -1137,26 +1137,73 @@ final class ChatViewModel: ObservableObject {let bufferLock = NSLock()var buffer = ""var tokenCount = 0+ let uiUpdateInterval: TimeInterval = 0.05+ var lastUiUpdate = Date.distantPast+ var pendingSnapshot: String?+ var updateWorkItem: DispatchWorkItem?- do {- let summary = try await provider.generateChat(- target: target,- messages: messages,- imageFiles: prompt.imageFiles,- temperature: resolveTemperature(),- maxTokens: target.maxTokens ?? 1024- ) { token in+ let scheduleStreamingUpdate = {+ bufferLock.lock()+ if updateWorkItem != nil {+ bufferLock.unlock()+ return+ }+ let workItem = DispatchWorkItem { [weak self] in+ guard let self else { return }bufferLock.lock()- buffer.append(token)- tokenCount += self.estimateTokens(token)- let snapshot = buffer+ let snapshot = pendingSnapshot+ pendingSnapshot = nil+ updateWorkItem = nil+ lastUiUpdate = Date()bufferLock.unlock()-+ guard let snapshot else { return }Task { @MainActor inguard self.activeGenerationId == generationId else { return }self.streamingResponse = snapshot}}+ updateWorkItem = workItem+ bufferLock.unlock()+ DispatchQueue.main.asyncAfter(deadline: .now() + uiUpdateInterval, execute: workItem)+ }++ do {+ let summary = try await provider.generateChat(+ target: target,+ messages: messages,+ imageFiles: prompt.imageFiles,+ temperature: resolveTemperature(),+ maxTokens: target.maxTokens ?? 1024,+ onToken: { token in+ let tokenEstimate = max(1, token.count / 4)+ var snapshot = ""+ var shouldUpdateNow = false++ bufferLock.lock()+ buffer.append(token)+ tokenCount += tokenEstimate+ snapshot = buffer+ pendingSnapshot = snapshot+ let now = Date()+ shouldUpdateNow = now.timeIntervalSince(lastUiUpdate) >= uiUpdateInterval+ if shouldUpdateNow {+ lastUiUpdate = now+ pendingSnapshot = nil+ updateWorkItem?.cancel()+ updateWorkItem = nil+ }+ bufferLock.unlock()++ if shouldUpdateNow {+ Task { @MainActor in+ guard self.activeGenerationId == generationId else { return }+ self.streamingResponse = snapshot+ }+ } else {+ scheduleStreamingUpdate()+ }+ }+ )finishGeneration(parent: userNode, response: buffer, tokenCount: tokenCount, totalTimeMs: summary.totalTimeMs, interrupted: false, generationId: generationId)} catch {diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swiftindex 0447a4d6c2..173d0ef9da 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift@@ -11,8 +11,6 @@ struct MessageInputView: View {let editingMessage: ChatMessage?let isProcessingAttachments: Boollet isAttachmentDownloadBlocked: Bool- let focusRequestId: Int- let dismissKeyboardId: Intlet onSend: () -> Voidlet onStop: () -> Voidlet onCancelEdit: () -> Void@@ -22,10 +20,10 @@ struct MessageInputView: View {let onUserFocus: () -> Voidlet onDismissKeyboard: () -> Void- @StateObject private var keyboard = KeyboardObserver()- @FocusState private var isFocused: Bool+ @FocusState.Binding var isFocused: Bool@State private var selectedPhotoItem: PhotosPickerItem?+ @State private var inputResetToken = UUID()private var placeholder: String {if isAttachmentDownloadBlocked {@@ -51,16 +49,13 @@ struct MessageInputView: View {editBanner(for: editingMessage)}- let hasAttachmentContent = !attachments.isEmpty || isProcessingAttachments-- // Make the input bar a bit more compact when showing "Write a message..."- let inputVerticalPadding: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : 10- let textFieldPadding: CGFloat = hasAttachmentContent ? 2 : 6+ let inputVerticalPadding: CGFloat = 10+ let textFieldPadding: CGFloat = 6// Lift the bar slightly off the bottom edge.- let bottomPadding: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : EnsuSpacing.md+ let bottomPadding: CGFloat = EnsuSpacing.md- let inputStackSpacing: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : EnsuSpacing.sm+ let inputStackSpacing: CGFloat = EnsuSpacing.smVStack(alignment: .leading, spacing: inputStackSpacing) {if !attachments.isEmpty {@@ -94,6 +89,7 @@ struct MessageInputView: View {HStack(alignment: .bottom, spacing: EnsuSpacing.sm) {TextField(placeholder, text: $text, axis: .vertical)+ .id(inputResetToken).focused($isFocused).onChange(of: isFocused) { focused inif focused {@@ -114,6 +110,11 @@ struct MessageInputView: View {onDismissKeyboard()}}+ .onChange(of: text) { newValue in+ if newValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !isFocused {+ inputResetToken = UUID()+ }+ }if editingMessage == nil {PhotosPicker(selection: $selectedPhotoItem, matching: .images) {@@ -199,46 +200,9 @@ struct MessageInputView: View {})}-- if keyboard.isVisible {- Button {- hapticTap()- isFocused = false- hideKeyboard()- onDismissKeyboard()- } label: {- Image(systemName: "keyboard.chevron.compact.down")- .font(.system(size: 18, weight: .semibold))- .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)- .onAppear {- if focusRequestId > 0 {- requestFocus()- }- }- .onChange(of: focusRequestId) { _ in- requestFocus()- }- .onChange(of: dismissKeyboardId) { _ in- isFocused = false- hideKeyboard()- }- }-- private func requestFocus() {- DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {- isFocused = true- }}+ .padding(.top, EnsuSpacing.sm)+}private var attachmentIconSize: CGFloat {#if os(macOS)diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swiftindex 540b6f726e..0a4e0e2e43 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift@@ -19,6 +19,7 @@ struct MessageListView: View {let onCopy: (ChatMessage) -> Voidlet onRetry: (ChatMessage) -> Voidlet onBranchChange: (ChatMessage, Int) -> Void+ let onDismissKeyboard: () -> Void@State private var isAtBottom = true@State private var autoScrollEnabled = true@@ -43,6 +44,7 @@ struct MessageListView: View {.onChanged { _ inisUserDragging = trueautoScrollEnabled = false+ onDismissKeyboard()}.onEnded { _ inisUserDragging = false@@ -51,6 +53,12 @@ struct MessageListView: View {}})+ .simultaneousGesture(+ TapGesture()+ .onEnded {+ onDismissKeyboard()+ }+ ).onPreferenceChange(BottomOffsetKey.self) { value inlet threshold: CGFloat = EnsuSpacing.xxxllet distanceToBottom = value - proxy.size.height@@ -204,7 +212,7 @@ struct MessageListView: View {let fallbackPadding = EnsuSpacing.xxxl + EnsuSpacing.xxl + 60let measuredPadding = inputBarHeight > 0 ? inputBarHeight + EnsuSpacing.md : fallbackPaddinglet basePadding = max(fallbackPadding, measuredPadding)- return max(basePadding, keyboardHeight + EnsuSpacing.xxl)+ return basePadding}private func scrollToBottom(_ proxy: ScrollViewProxy, force: Bool = false, animated: Bool = true) {@@ -444,7 +452,7 @@ private struct AssistantMessageBubbleView: View {private struct StreamingBubbleView: View {let text: String- @State private var cursorOpacity: Double = 1+ private static let cursorGlyph = "β"var body: some View {HStack(alignment: .bottom) {@@ -453,17 +461,15 @@ private struct StreamingBubbleView: View {if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {LoadingDotsView()} else {- HStack(alignment: .bottom, spacing: 4) {- AssistantMessageRenderer(text: text, isStreaming: true, storageId: UUID().uuidString)- Rectangle()- .fill(EnsuColor.accent)- .frame(width: 2, height: 18)- .opacity(cursorOpacity)- .onAppear {- withAnimation(.easeInOut(duration: 0.53).repeatForever(autoreverses: true)) {- cursorOpacity = 0- }- }+ TimelineView(.periodic(from: .now, by: 0.55)) { context in+ let phase = Int(context.date.timeIntervalSinceReferenceDate * 2) % 2+ let showCursor = phase == 0+ let displayText = showCursor ? text + StreamingBubbleView.cursorGlyph : text+ AssistantMessageRenderer(+ text: displayText,+ isStreaming: true,+ storageId: UUID().uuidString+ )}}}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swiftindex ccd5e5e985..4b364b6f30 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift@@ -52,9 +52,9 @@ final class InferenceRsProvider {private var contextHandle: ContextHandle?private var currentModelId: String?private var backendInitialized = false- private var currentJobId: Int64?private var downloadCancelled = falseprivate var currentDownloadTask: URLSessionTask?+ private var currentJobId: Int64?init(modelDir: URL) {self.modelDir = modelDirdiff --git a/rust/inference_rs/Cargo.lock b/rust/inference_rs/Cargo.locknew file mode 100644index 0000000000..7aef510434--- /dev/null+++ b/rust/inference_rs/Cargo.lock@@ -0,0 +1,581 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]++[[package]]+name = "bindgen"+version = "0.72.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"+dependencies = [+ "bitflags",+ "cexpr",+ "clang-sys",+ "itertools",+ "log",+ "prettyplease",+ "proc-macro2",+ "quote",+ "regex",+ "rustc-hash",+ "shlex",+ "syn",+]++[[package]]+name = "bitflags"+version = "2.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"++[[package]]+name = "cc"+version = "1.2.54"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6354c81bbfd62d9cfa9cb3c773c2b7b2a3a482d569de977fd0e961f6e7c00583"+dependencies = [+ "find-msvc-tools",+ "jobserver",+ "libc",+ "shlex",+]++[[package]]+name = "cexpr"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"+dependencies = [+ "nom",+]++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "clang-sys"+version = "1.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"+dependencies = [+ "glob",+ "libc",+ "libloading",+]++[[package]]+name = "cmake"+version = "0.1.57"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d"+dependencies = [+ "cc",+]++[[package]]+name = "either"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"++[[package]]+name = "enumflags2"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"+dependencies = [+ "enumflags2_derive",+]++[[package]]+name = "enumflags2_derive"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db"++[[package]]+name = "find_cuda_helper"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9f9e65c593dd01ac77daad909ea4ad17f0d6d1776193fc8ea766356177abdad"+dependencies = [+ "glob",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+ "wasip2",+]++[[package]]+name = "glob"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"++[[package]]+name = "inference_rs"+version = "0.1.0"+dependencies = [+ "llama-cpp-2",+ "llama-cpp-sys-2",+ "parking_lot",+ "self_cell",+ "serde",+ "serde_json",+ "thiserror",+]++[[package]]+name = "itertools"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"+dependencies = [+ "either",+]++[[package]]+name = "itoa"+version = "1.0.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"++[[package]]+name = "jobserver"+version = "0.1.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"+dependencies = [+ "getrandom",+ "libc",+]++[[package]]+name = "libc"+version = "0.2.180"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc"++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "llama-cpp-2"+version = "0.1.131"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a256ab71761e7c46a24e21fe7d923e1e6b78d465f41c897277f79477da96b84"+dependencies = [+ "enumflags2",+ "llama-cpp-sys-2",+ "thiserror",+ "tracing",+ "tracing-core",+]++[[package]]+name = "llama-cpp-sys-2"+version = "0.1.131"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff5b2268a06180a67d8a1d3dd9d1f1c70d52de7b6f40f967ec4eabd90d0417ae"+dependencies = [+ "bindgen",+ "cc",+ "cmake",+ "find_cuda_helper",+ "glob",+ "walkdir",+]++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"++[[package]]+name = "memchr"+version = "2.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"++[[package]]+name = "minimal-lexical"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"++[[package]]+name = "nom"+version = "7.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"+dependencies = [+ "memchr",+ "minimal-lexical",+]++[[package]]+name = "once_cell"+version = "1.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[package]]+name = "pin-project-lite"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"++[[package]]+name = "prettyplease"+version = "0.2.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"+dependencies = [+ "proc-macro2",+ "syn",+]++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags",+]++[[package]]+name = "regex"+version = "1.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58"++[[package]]+name = "rustc-hash"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "self_cell"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b12e76d157a900eb52e81bc6e9f3069344290341720e9178cde2407113ac8d89"++[[package]]+name = "serde"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "serde_json"+version = "1.0.149"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"++[[package]]+name = "smallvec"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"++[[package]]+name = "syn"+version = "2.0.114"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-attributes",+ "tracing-core",+]++[[package]]+name = "tracing-attributes"+version = "0.1.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+ "valuable",+]++[[package]]+name = "unicode-ident"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"++[[package]]+name = "valuable"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "wasip2"+version = "1.0.2+wasi-0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "wit-bindgen"+version = "0.51.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"++[[package]]+name = "zmij"+version = "1.0.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfcd145825aace48cff44a8844de64bf75feec3080e0aa5cdbde72961ae51a65"diff --git a/rust/inference_rs/src/api.rs b/rust/inference_rs/src/api.rsindex f6ba6da037..37512dc62e 100644--- a/rust/inference_rs/src/api.rs+++ b/rust/inference_rs/src/api.rs@@ -102,6 +102,7 @@ fn register_job() -> (JobId, Arc<AtomicBool>) {(job_id, flag)}+struct JobGuard(JobId);impl Drop for JobGuard {@@ -172,6 +173,109 @@ fn find_stop_index(text: &str, stop_sequences: &[String], start: usize) -> Optiofound}+fn drain_utf8(pending: &mut Vec<u8>) -> String {+ let mut output = String::new();+ loop {+ match std::str::from_utf8(pending) {+ Ok(text) => {+ output.push_str(text);+ pending.clear();+ break;+ }+ Err(err) => {+ let valid_up_to = err.valid_up_to();+ if valid_up_to > 0 {+ let valid = std::str::from_utf8(&pending[..valid_up_to])+ .expect("valid UTF-8 prefix");+ output.push_str(valid);+ pending.drain(..valid_up_to);+ }++ match err.error_len() {+ None => break,+ Some(len) => {+ let len = len.min(pending.len());+ let lossy = String::from_utf8_lossy(&pending[..len]);+ output.push_str(&lossy);+ pending.drain(..len);+ }+ }+ }+ }+ }+ output+}++struct DecodeStep {+ text: Option<String>,+ stop: bool,+}++/// Incremental UTF-8 streaming decoder with stop-sequence handling.+struct StreamDecoder {+ generated_text: String,+ pending_bytes: Vec<u8>,+ stop_sequences: Vec<String>,+ max_stop_len: usize,+}++impl StreamDecoder {+ fn new(stop_sequences: &[String]) -> Self {+ let max_stop_len = stop_sequences.iter().map(|s| s.len()).max().unwrap_or(0);+ Self {+ generated_text: String::new(),+ pending_bytes: Vec::new(),+ stop_sequences: stop_sequences.to_vec(),+ max_stop_len,+ }+ }++ fn push_bytes(&mut self, bytes: &[u8]) -> DecodeStep {+ if !bytes.is_empty() {+ self.pending_bytes.extend_from_slice(bytes);+ }+ let piece = drain_utf8(&mut self.pending_bytes);+ self.push_text(piece)+ }++ fn flush(&mut self) -> DecodeStep {+ if self.pending_bytes.is_empty() {+ return DecodeStep { text: None, stop: false };+ }+ let piece = String::from_utf8_lossy(&self.pending_bytes).to_string();+ self.pending_bytes.clear();+ self.push_text(piece)+ }++ fn push_text(&mut self, piece: String) -> DecodeStep {+ if piece.is_empty() {+ return DecodeStep { text: None, stop: false };+ }++ let prev_len = self.generated_text.len();+ self.generated_text.push_str(&piece);++ if self.max_stop_len > 0 {+ let search_start = prev_len.saturating_sub(self.max_stop_len);+ if let Some(stop_index) =+ find_stop_index(&self.generated_text, &self.stop_sequences, search_start)+ {+ let new_piece = self.generated_text[prev_len..stop_index].to_string();+ self.generated_text.truncate(stop_index);+ return DecodeStep {+ text: if new_piece.is_empty() { None } else { Some(new_piece) },+ stop: true,+ };+ }+ }++ DecodeStep {+ text: Some(piece),+ stop: false,+ }+ }+}+#[allow(clippy::too_many_arguments)]fn run_generation_loop(ctx: &mut LlamaContext,@@ -181,12 +285,12 @@ fn run_generation_loop(job_id: JobId,max_tokens: usize,stop_sequences: &[String],- max_stop_len: usize,generated_tokens_count: &mut i32,mut pos: i32,mut logits_index: i32,) -> Result<(), String> {- let mut generated_text = String::new();+ let mut decoder = StreamDecoder::new(stop_sequences);+ let mut stop_triggered = false;let n_ctx = ctx.n_ctx();for _ in 0..max_tokens {@@ -205,40 +309,25 @@ fn run_generation_loop(break;}- let piece = ctx+ let bytes = ctx.model- .token_to_str(token, Special::Tokenize)+ .token_to_bytes(token, Special::Tokenize).map_err(|err| format_error("Detokenize failed", err))?;+ let step = decoder.push_bytes(&bytes);- if !piece.is_empty() {- let prev_len = generated_text.len();- generated_text.push_str(&piece);-- if max_stop_len > 0 {- let search_start = prev_len.saturating_sub(max_stop_len);- if let Some(stop_index) =- find_stop_index(&generated_text, stop_sequences, search_start)- {- let new_piece = &generated_text[prev_len..stop_index];- if !new_piece.is_empty() {- sink.add(GenerateEvent::Text {- job_id,- text: new_piece.to_string(),- token_id: Some(token.0),- });- }- generated_text.truncate(stop_index);- break;- }- }-+ if let Some(text) = step.text {sink.add(GenerateEvent::Text {job_id,- text: piece,+ text,token_id: Some(token.0),});}+ if step.stop {+ stop_triggered = true;+ break;+ }+let mut step_batch = LlamaBatch::new(1, 1);step_batch.add(token, pos, &[0], true)@@ -250,6 +339,17 @@ fn run_generation_loop(pos += 1;}+ if !stop_triggered {+ let step = decoder.flush();+ if let Some(text) = step.text {+ sink.add(GenerateEvent::Text {+ job_id,+ text,+ token_id: None,+ });+ }+ }+Ok(())}@@ -626,10 +726,15 @@ pub fn generate_chat_stream(let _job_guard = JobGuard(job_id);let start = Instant::now();+ sink.add(GenerateEvent::Text {+ job_id,+ text: String::new(),+ token_id: None,+ });+let max_tokens = max_tokens.unwrap_or(128);let max_tokens = usize::try_from(max_tokens.max(0)).unwrap_or(0);let stop_sequences = stop_sequences.unwrap_or_default();- let max_stop_len = stop_sequences.iter().map(|s| s.len()).max().unwrap_or(0);let mut prompt_tokens_count: i32 = 0;let mut generated_tokens_count: i32 = 0;@@ -751,7 +856,6 @@ pub fn generate_chat_stream(job_id,max_tokens,&stop_sequences,- max_stop_len,&mut generated_tokens_count,pos,logits_index,@@ -864,7 +968,6 @@ pub fn generate_chat_stream(job_id,max_tokens,&stop_sequences,- max_stop_len,&mut generated_tokens_count,n_past,-1,@@ -908,10 +1011,15 @@ pub fn generate_stream(let _job_guard = JobGuard(job_id);let start = Instant::now();+ sink.add(GenerateEvent::Text {+ job_id,+ text: String::new(),+ token_id: None,+ });+let max_tokens = request.max_tokens.unwrap_or(128);let max_tokens = usize::try_from(max_tokens.max(0)).unwrap_or(0);let stop_sequences = request.stop_sequences.clone().unwrap_or_default();- let max_stop_len = stop_sequences.iter().map(|s| s.len()).max().unwrap_or(0);let mut prompt_tokens_count: i32 = 0;let mut generated_tokens_count: i32 = 0;@@ -981,7 +1089,6 @@ pub fn generate_stream(job_id,max_tokens,&stop_sequences,- max_stop_len,&mut generated_tokens_count,pos,logits_index,@@ -1022,3 +1129,20 @@ pub fn cancel(job_id: JobId) -> Result<(), String> {}Ok(())}++#[cfg(test)]+mod tests {+ use super::StreamDecoder;++ #[test]+ fn stream_decoder_emits_complete_utf8() {+ let mut decoder = StreamDecoder::new(&[]);+ let step = decoder.push_bytes(&[0xF0, 0x9F]);+ assert!(step.text.is_none());+ assert!(!step.stop);++ let step = decoder.push_bytes(&[0x99, 0x82]);+ assert_eq!(step.text.as_deref(), Some("π"));+ assert!(!step.stop);+ }+}