π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
update inference
Prateek Sunalf0f7a6cef704
diff --git a/.gitignore b/.gitignoreindex 6b8a7b3626..a22df027b5 100644--- a/.gitignore+++ b/.gitignore@@ -16,3 +16,7 @@ rust/cli/exports/# Nodenode_modules/++# Build artifacts+mobile/native/android/packages/rust/build/+mobile/native/darwin/Packages/Rust/build/diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xml b/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xmlindex fbd41fc674..94fd896b5c 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xml+++ b/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xml@@ -10,7 +10,8 @@android:theme="@style/Theme.Ensu"><activityandroid:name=".MainActivity"- android:exported="true">+ android:exported="true"+ android:windowSoftInputMode="adjustResize"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" />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 d2ccffe30d..22a682cb0f 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt@@ -8,9 +8,11 @@ import io.ente.ensu.data.SessionPreferencesDataStoreimport io.ente.ensu.data.auth.EnsuAuthServiceimport io.ente.ensu.data.logging.InMemoryLogRepositoryimport io.ente.ensu.data.storage.CredentialStore+import io.ente.ensu.data.llm.InferenceRsProviderimport io.ente.ensu.domain.store.AppStoreimport kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.launch+import java.io.Fileclass AppViewModel(application: Application) : AndroidViewModel(application) {private val sessionPreferences = SessionPreferencesDataStore(application)@@ -18,7 +20,10 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {private val credentialStore = CredentialStore(application)val logRepository = InMemoryLogRepository()- val store = AppStore(sessionPreferences, logRepository = logRepository)+ private val llmProvider = InferenceRsProvider(+ modelDir = File(application.filesDir, "llm")+ )+ val store = AppStore(sessionPreferences, llmProvider = llmProvider, logRepository = logRepository)val authService = EnsuAuthService(context = application,endpointPreferences = endpointPreferences,diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.ktindex fba07297e4..4fff2d78dd 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt@@ -2,6 +2,9 @@package io.ente.ensu+import android.content.Context+import android.net.Uri+import android.provider.OpenableColumnsimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.WindowInsets@@ -33,6 +36,7 @@ import io.ente.ensu.components.ChoiceDialogimport io.ente.ensu.data.auth.EnsuAuthServiceimport io.ente.ensu.designsystem.EnsuColorimport io.ente.ensu.designsystem.EnsuTypography+import io.ente.ensu.domain.model.Attachmentimport io.ente.ensu.domain.model.AttachmentTypeimport io.ente.ensu.domain.model.LogEntryimport io.ente.ensu.domain.state.AppState@@ -42,6 +46,9 @@ import io.ente.ensu.settings.DeveloperSettingsScreenimport io.ente.ensu.settings.LogViewerScreenimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.launch+import java.io.File+import java.io.FileOutputStream+import java.util.UUID@Composablefun HomeView(@@ -53,12 +60,48 @@ fun HomeView() {val drawerState = androidx.compose.material3.rememberDrawerState(DrawerValue.Closed)val scope = rememberCoroutineScope()+ val context = androidx.compose.ui.platform.LocalContext.currentvar isShowingAuth by remember { mutableStateOf(false) }var isShowingSignOutDialog by remember { mutableStateOf(false) }var destination by remember { mutableStateOf(HomeDestination.Chat) }+ val imagePicker = androidx.activity.compose.rememberLauncherForActivityResult(+ contract = androidx.activity.result.contract.ActivityResultContracts.GetContent()+ ) { uri ->+ if (uri != null) {+ store.setAttachmentProcessing(true)+ scope.launch {+ val attachment = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+ buildAttachmentFromUri(context, uri, io.ente.ensu.domain.model.AttachmentType.Image)+ }+ if (attachment != null) {+ store.addAttachment(attachment)+ } else {+ store.setAttachmentProcessing(false)+ }+ }+ }+ }++ val documentPicker = androidx.activity.compose.rememberLauncherForActivityResult(+ contract = androidx.activity.result.contract.ActivityResultContracts.OpenDocument()+ ) { uri ->+ if (uri != null) {+ store.setAttachmentProcessing(true)+ scope.launch {+ val attachment = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+ buildAttachmentFromUri(context, uri, io.ente.ensu.domain.model.AttachmentType.Document)+ }+ if (attachment != null) {+ store.addAttachment(attachment)+ } else {+ store.setAttachmentProcessing(false)+ }+ }+ }+ }+val currentSession = appState.chat.sessions.firstOrNull { it.id == appState.chat.currentSessionId }- val currentMessages = appState.chat.messages.filter { it.sessionId == currentSession?.id }ModalNavigationDrawer(drawerState = drawerState,@@ -107,7 +150,7 @@ fun HomeView(Column {EnsuTopBar(sessionTitle = currentSession?.title,- showBrand = currentMessages.isEmpty(),+ showBrand = appState.chat.messages.isEmpty(),isLoggedIn = appState.auth.isLoggedIn,onOpenDrawer = { scope.launch { drawerState.open() } },onSignIn = { isShowingAuth = true }@@ -135,11 +178,25 @@ fun HomeView(when (destination) {HomeDestination.Chat -> {ChatView(- chatState = appState.chat.copy(messages = currentMessages),+ chatState = appState.chat,onMessageChange = store::updateMessageText,onSend = store::sendMessage,- onStop = {},- onAttachmentSelected = { _: AttachmentType -> },+ onStop = store::stopGeneration,+ onCancelDownload = store::cancelDownload,+ onAttachmentSelected = { type ->+ when (type) {+ io.ente.ensu.domain.model.AttachmentType.Image -> {+ imagePicker.launch("image/*")+ }+ io.ente.ensu.domain.model.AttachmentType.Document -> {+ documentPicker.launch(arrayOf("*/*"))+ }+ }+ },+ onRemoveAttachment = store::removeAttachment,+ onEditMessage = { message -> store.beginEditing(message.id) },+ onRetryMessage = { message -> store.retryAssistantMessage(message.id) },+ onCancelEdit = store::cancelEditing,onBranchChange = store::updateBranchSelection)}@@ -147,7 +204,11 @@ fun HomeView(LogViewerScreen(logs = logs)}HomeDestination.ModelSettings -> {- ModelSettingsScreen()+ ModelSettingsScreen(+ state = appState.modelSettings,+ onSave = store::updateModelSettings,+ onReset = store::resetModelSettings+ )}HomeDestination.DeveloperSettings -> {DeveloperSettingsScreen(@@ -246,3 +307,64 @@ private enum class HomeDestination {DeveloperSettings}+private fun buildAttachmentFromUri(+ context: Context,+ uri: Uri,+ type: AttachmentType+): Attachment? {+ val resolver = context.contentResolver+ val name = queryDisplayName(resolver, uri)+ val size = querySize(resolver, uri)+ val rawName = name ?: when (type) {+ AttachmentType.Image -> "image"+ AttachmentType.Document -> "document"+ }+ val safeName = rawName.replace("/", "_")++ val attachmentsDir = File(context.filesDir, "attachments")+ if (!attachmentsDir.exists()) {+ attachmentsDir.mkdirs()+ }++ val destination = File(attachmentsDir, "${UUID.randomUUID()}_$safeName")+ return runCatching {+ val inputStream = resolver.openInputStream(uri) ?: return@runCatching null++ inputStream.use { input ->+ FileOutputStream(destination).use { output ->+ input.copyTo(output)+ }+ }++ val finalSize = destination.length().takeIf { it > 0 } ?: size ?: 0L++ Attachment(+ name = name ?: destination.name,+ sizeBytes = finalSize,+ type = type,+ localPath = destination.absolutePath,+ isUploading = false+ )+ }.getOrNull()+}++private fun queryDisplayName(resolver: android.content.ContentResolver, uri: Uri): String? {+ resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->+ if (cursor.moveToFirst()) {+ val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)+ if (index >= 0) return cursor.getString(index)+ }+ }+ return null+}++private fun querySize(resolver: android.content.ContentResolver, uri: Uri): Long? {+ resolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { cursor ->+ if (cursor.moveToFirst()) {+ val index = cursor.getColumnIndex(OpenableColumns.SIZE)+ if (index >= 0) return cursor.getLong(index)+ }+ }+ return null+}+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 3a48453d0a..f752c6dd27 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@@ -1,24 +1,31 @@package io.ente.ensu.chatimport androidx.compose.foundation.background-import androidx.compose.foundation.horizontalScrollimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.PaddingValuesimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeightimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.IntrinsicSizeimport androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.layout.navigationBarsPaddingimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.rememberLazyListStateimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.verticalScrollimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.automirrored.outlined.ArrowForwardimport androidx.compose.material.icons.outlined.AttachFile@@ -30,16 +37,21 @@ import androidx.compose.material.icons.outlined.Downloadimport androidx.compose.material.icons.outlined.Imageimport androidx.compose.material.icons.outlined.Refreshimport androidx.compose.material.icons.outlined.Code+import androidx.compose.material.icons.outlined.Closeimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.DropdownMenuimport androidx.compose.material3.DropdownMenuItemimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButton+import androidx.compose.material3.LinearProgressIndicatorimport androidx.compose.material3.Text+import androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.derivedStateOfimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier@@ -47,6 +59,7 @@ import androidx.compose.ui.graphics.SolidColorimport androidx.compose.foundation.text.KeyboardOptionsimport androidx.compose.ui.text.input.KeyboardCapitalizationimport androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport io.ente.ensu.components.ActionButtonimport io.ente.ensu.components.BranchSwitcher@@ -62,6 +75,7 @@ import io.ente.ensu.domain.state.ChatStateimport java.text.SimpleDateFormatimport java.util.Dateimport java.util.Locale+import kotlinx.coroutines.delay@Composablefun ChatView(@@ -69,38 +83,69 @@ fun ChatView(onMessageChange: (String) -> Unit,onSend: () -> Unit,onStop: () -> Unit,+ onCancelDownload: () -> Unit,onAttachmentSelected: (AttachmentType) -> Unit,+ onRemoveAttachment: (Attachment) -> Unit,+ onEditMessage: (ChatMessage) -> Unit,+ onRetryMessage: (ChatMessage) -> Unit,+ onCancelEdit: () -> Unit,onBranchChange: (String, Int) -> Unit) {- Column(modifier = Modifier.fillMaxSize()) {- MessageList(- modifier = Modifier- .weight(1f)- .padding(- start = EnsuSpacing.pageHorizontal.dp,- end = EnsuSpacing.pageHorizontal.dp,- top = EnsuSpacing.pageVertical.dp- ),- messages = chatState.messages,- branchSelections = chatState.branchSelections,- onBranchChange = onBranchChange- )+ Box(modifier = Modifier.fillMaxSize()) {+ Column(modifier = Modifier.fillMaxSize()) {+ MessageList(+ modifier = Modifier+ .weight(1f)+ .padding(+ start = EnsuSpacing.pageHorizontal.dp,+ end = EnsuSpacing.pageHorizontal.dp,+ top = EnsuSpacing.pageVertical.dp+ ),+ messages = chatState.messages,+ streamingResponse = chatState.streamingResponse,+ streamingParentId = chatState.streamingParentId,+ isGenerating = chatState.isGenerating,+ branchSelections = chatState.branchSelections,+ onEditMessage = onEditMessage,+ onRetryMessage = onRetryMessage,+ onBranchChange = onBranchChange+ )- MessageInput(- modifier = Modifier- .fillMaxWidth()- .navigationBarsPadding()- .background(EnsuColor.backgroundBase()),- messageText = chatState.messageText,- attachments = chatState.attachments,- isProcessingAttachments = chatState.isProcessingAttachments,- isGenerating = chatState.isGenerating,- isDownloading = chatState.isDownloading,- onMessageChange = onMessageChange,- onSend = onSend,- onStop = onStop,- onAttachmentSelected = onAttachmentSelected- )+ val editingMessage = chatState.editingMessageId?.let { editingId ->+ chatState.messages.firstOrNull { it.id == editingId }+ }++ MessageInput(+ modifier = Modifier+ .fillMaxWidth()+ .navigationBarsPadding()+ .background(EnsuColor.backgroundBase()),+ messageText = chatState.messageText,+ attachments = chatState.attachments,+ editingMessage = editingMessage,+ isProcessingAttachments = chatState.isProcessingAttachments,+ isGenerating = chatState.isGenerating,+ isDownloading = chatState.isDownloading,+ downloadPercent = chatState.downloadPercent,+ onMessageChange = onMessageChange,+ onSend = onSend,+ onStop = onStop,+ onAttachmentSelected = onAttachmentSelected,+ onRemoveAttachment = onRemoveAttachment,+ onCancelEdit = onCancelEdit+ )+ }++ val status = chatState.downloadStatus+ val showToast = status != null && (chatState.isDownloading || status.contains("Loading", ignoreCase = true))+ if (showToast) {+ DownloadToastOverlay(+ status = status ?: "",+ percent = chatState.downloadPercent ?: 0,+ isLoading = status?.contains("Loading", ignoreCase = true) == true,+ onCancel = onCancelDownload+ )+ }}}@@ -108,16 +153,59 @@ fun ChatView(private fun MessageList(modifier: Modifier,messages: List<ChatMessage>,+ streamingResponse: String,+ streamingParentId: String?,+ isGenerating: Boolean,branchSelections: Map<String, Int>,+ onEditMessage: (ChatMessage) -> Unit,+ onRetryMessage: (ChatMessage) -> Unit,onBranchChange: (String, Int) -> Unit) {- if (messages.isEmpty()) {+ if (messages.isEmpty() && !isGenerating) {EmptyState(modifier = modifier)return}+ val listState = rememberLazyListState()+ var autoScrollEnabled by remember { mutableStateOf(true) }+ val isAtBottom by remember {+ derivedStateOf {+ val layoutInfo = listState.layoutInfo+ val totalItems = layoutInfo.totalItemsCount+ if (totalItems == 0) {+ true+ } else {+ val lastVisible = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0+ lastVisible >= totalItems - 1+ }+ }+ }++ LaunchedEffect(isGenerating) {+ if (isGenerating) {+ autoScrollEnabled = true+ }+ }++ LaunchedEffect(listState.isScrollInProgress, isAtBottom) {+ if (listState.isScrollInProgress && !isAtBottom) {+ autoScrollEnabled = false+ }+ }++ LaunchedEffect(messages.size, streamingResponse, streamingParentId, isGenerating, autoScrollEnabled) {+ if (!autoScrollEnabled) return@LaunchedEffect+ if (messages.isEmpty()) return@LaunchedEffect+ val targetIndex = messages.lastIndex+ if (targetIndex >= 0) {+ listState.animateScrollToItem(targetIndex)+ }+ }+LazyColumn(modifier = modifier,+ state = listState,+ contentPadding = PaddingValues(bottom = (EnsuSpacing.xxxl + EnsuSpacing.xl).dp),verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)) {items(messages, key = { it.id }) { message ->@@ -126,6 +214,7 @@ private fun MessageList(UserMessageBubble(message = message,branchSelections = branchSelections,+ onEdit = { onEditMessage(message) },onBranchChange = onBranchChange)}@@ -133,10 +222,22 @@ private fun MessageList(AssistantMessageBubble(message = message,branchSelections = branchSelections,+ onRetry = { onRetryMessage(message) },onBranchChange = onBranchChange)}}++ if (isGenerating && streamingParentId == message.id) {+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ StreamingMessageBubble(text = streamingResponse)+ }+ }++ if (isGenerating && streamingParentId == null) {+ items(1) {+ StreamingMessageBubble(text = streamingResponse)+ }}}}@@ -156,10 +257,12 @@ private fun EmptyState(modifier: Modifier) {}}+@OptIn(ExperimentalLayoutApi::class)@Composableprivate fun UserMessageBubble(message: ChatMessage,branchSelections: Map<String, Int>,+ onEdit: () -> Unit,onBranchChange: (String, Int) -> Unit) {Column(@@ -168,6 +271,28 @@ private fun UserMessageBubble(.padding(start = EnsuSpacing.messageBubbleInset.dp),horizontalAlignment = Alignment.End) {+ if (message.attachments.isNotEmpty()) {+ FlowRow(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp, Alignment.End),+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)+ ) {+ message.attachments.forEach { attachment ->+ val icon = when (attachment.type) {+ AttachmentType.Image -> Icons.Outlined.Image+ AttachmentType.Document -> Icons.Outlined.Description+ }+ io.ente.ensu.components.AttachmentChip(+ name = attachment.name,+ size = "${attachment.sizeBytes / 1024} KB",+ icon = icon,+ isUploading = attachment.isUploading+ )+ }+ }+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ }+Text(text = message.text,style = EnsuTypography.message,@@ -180,7 +305,7 @@ private fun UserMessageBubble(Row(horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {ActionButton(icon = Icons.Outlined.Edit,- onTap = {},+ onTap = onEdit,contentDescription = "Edit")ActionButton(@@ -218,6 +343,7 @@ private fun UserMessageBubble(private fun AssistantMessageBubble(message: ChatMessage,branchSelections: Map<String, Int>,+ onRetry: () -> Unit,onBranchChange: (String, Int) -> Unit) {Column(@@ -226,11 +352,7 @@ private fun AssistantMessageBubble(.padding(end = EnsuSpacing.messageBubbleInset.dp),horizontalAlignment = Alignment.Start) {- Text(- text = message.text,- style = EnsuTypography.message,- color = EnsuColor.textPrimary()- )+ MarkdownView(markdown = message.text)if (message.isInterrupted) {Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))@@ -256,7 +378,7 @@ private fun AssistantMessageBubble()ActionButton(icon = Icons.Outlined.Refresh,- onTap = {},+ onTap = onRetry,contentDescription = "Retry")message.tokensPerSecond?.let { tokPerSec ->@@ -270,9 +392,8 @@ private fun AssistantMessageBubble(Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))- Row(verticalAlignment = Alignment.CenterVertically) {+ Row(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp), verticalAlignment = Alignment.CenterVertically) {TimestampText(message.timestampMillis)- Spacer(modifier = Modifier.weight(1f))if (message.branchCount > 1) {BranchSwitcher(currentIndex = branchSelections[message.id] ?: 1,@@ -291,6 +412,94 @@ private fun AssistantMessageBubble(}}+@Composable+private fun StreamingMessageBubble(text: String) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .padding(end = EnsuSpacing.messageBubbleInset.dp),+ horizontalAlignment = Alignment.Start+ ) {+ if (text.isBlank()) {+ LoadingDotsText()+ } else {+ Text(+ text = text,+ style = EnsuTypography.message,+ color = EnsuColor.textPrimary()+ )+ }+ }+}++@Composable+private fun LoadingDotsText() {+ var dotCount by remember { mutableStateOf(1) }++ LaunchedEffect(Unit) {+ while (true) {+ delay(450)+ dotCount = if (dotCount == 3) 1 else dotCount + 1+ }+ }++ Text(+ text = ".".repeat(dotCount),+ style = EnsuTypography.message,+ color = EnsuColor.textMuted()+ )+}++@Composable+private fun DownloadToastOverlay(+ status: String,+ percent: Int,+ isLoading: Boolean,+ onCancel: () -> Unit+) {+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .padding(top = EnsuSpacing.lg.dp),+ contentAlignment = Alignment.TopCenter+ ) {+ val title = if (isLoading) "Loading model" else "Downloading model"+ val clamped = percent.coerceIn(0, 100)+ Column(+ modifier = Modifier+ .padding(horizontal = EnsuSpacing.lg.dp)+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.toast.dp))+ .padding(EnsuSpacing.lg.dp)+ .fillMaxWidth()+ ) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(text = title, style = EnsuTypography.large, color = EnsuColor.textPrimary())+ Spacer(modifier = Modifier.weight(1f))+ IconButton(onClick = onCancel, modifier = Modifier.size(28.dp)) {+ Icon(+ imageVector = Icons.Outlined.StopCircle,+ contentDescription = "Cancel download",+ tint = EnsuColor.stopButton+ )+ }+ }+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ LinearProgressIndicator(+ progress = clamped / 100f,+ color = if (isLoading) EnsuColor.accent() else EnsuColor.accent(),+ trackColor = EnsuColor.border(),+ modifier = Modifier.fillMaxWidth()+ )+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(text = status, style = EnsuTypography.small, color = EnsuColor.textMuted())+ Spacer(modifier = Modifier.weight(1f))+ Text(text = "$clamped%", style = EnsuTypography.mini, color = EnsuColor.textMuted())+ }+ }+ }+}+@Composableprivate fun TimestampText(timestampMillis: Long) {Text(@@ -300,22 +509,81 @@ private fun TimestampText(timestampMillis: Long) {)}+@Composable+private fun EditBanner(message: ChatMessage, onCancelEdit: () -> Unit) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = EnsuSpacing.pageHorizontal.dp)+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp))+ .height(IntrinsicSize.Min)+ ) {+ Box(+ modifier = Modifier+ .fillMaxHeight()+ .width(3.dp)+ .background(EnsuColor.accent())+ )+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = EnsuSpacing.md.dp, vertical = EnsuSpacing.sm.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Icon(+ imageVector = Icons.Outlined.Edit,+ contentDescription = null,+ tint = EnsuColor.accent(),+ modifier = Modifier.size(14.dp)+ )+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))+ Text(+ text = "Editing:",+ style = EnsuTypography.small,+ color = EnsuColor.textMuted()+ )+ Spacer(modifier = Modifier.width(EnsuSpacing.xs.dp))+ Text(+ text = message.text,+ style = EnsuTypography.small,+ color = EnsuColor.textPrimary(),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.weight(1f)+ )+ IconButton(onClick = onCancelEdit, modifier = Modifier.size(24.dp)) {+ Icon(+ imageVector = Icons.Outlined.Close,+ contentDescription = "Cancel edit",+ tint = EnsuColor.textMuted()+ )+ }+ }+ }+}++@OptIn(ExperimentalLayoutApi::class)@Composableprivate fun MessageInput(modifier: Modifier,messageText: String,attachments: List<Attachment>,+ editingMessage: ChatMessage?,isProcessingAttachments: Boolean,isGenerating: Boolean,isDownloading: Boolean,+ downloadPercent: Int?,onMessageChange: (String) -> Unit,onSend: () -> Unit,onStop: () -> Unit,- onAttachmentSelected: (AttachmentType) -> Unit+ onAttachmentSelected: (AttachmentType) -> Unit,+ onRemoveAttachment: (Attachment) -> Unit,+ onCancelEdit: () -> Unit) {var showMenu by remember { mutableStateOf(false) }val placeholder = if (isDownloading) {- "Downloading model... (queue messages)"+ val percent = downloadPercent?.let { " ($it%)" } ?: ""+ "Downloading model...$percent"} else {"Compose your message..."}@@ -325,13 +593,20 @@ private fun MessageInput(.background(EnsuColor.backgroundBase()),verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {+ if (editingMessage != null) {+ EditBanner(message = editingMessage, onCancelEdit = onCancelEdit)+ }+if (attachments.isNotEmpty()) {- Row(+ val maxAttachmentHeight = 140.dp+ FlowRow(modifier = Modifier.fillMaxWidth()- .horizontalScroll(rememberScrollState())+ .heightIn(max = maxAttachmentHeight)+ .verticalScroll(rememberScrollState()).padding(horizontal = EnsuSpacing.pageHorizontal.dp),- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {attachments.forEach { attachment ->val icon = when (attachment.type) {@@ -342,7 +617,8 @@ private fun MessageInput(name = attachment.name,size = "${attachment.sizeBytes / 1024} KB",icon = icon,- isUploading = attachment.isUploading+ isUploading = attachment.isUploading,+ onDelete = { onRemoveAttachment(attachment) })}}@@ -398,38 +674,42 @@ private fun MessageInput(Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))- Box {- IconButton(- onClick = { showMenu = true },- enabled = !isGenerating && !isDownloading,- modifier = Modifier.size(36.dp)- ) {- Icon(- imageVector = Icons.Outlined.AttachFile,- contentDescription = "Attach"- )- }- DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {- DropdownMenuItem(- text = { Text(text = "Image") },- onClick = {- showMenu = false- onAttachmentSelected(AttachmentType.Image)- }- )- DropdownMenuItem(- text = { Text(text = "Document") },- onClick = {- showMenu = false- onAttachmentSelected(AttachmentType.Document)- }- )+ if (editingMessage == null) {+ Box {+ IconButton(+ onClick = { showMenu = true },+ enabled = !isGenerating && !isDownloading,+ modifier = Modifier.size(36.dp)+ ) {+ Icon(+ imageVector = Icons.Outlined.AttachFile,+ contentDescription = "Attach"+ )+ }+ DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {+ DropdownMenuItem(+ text = { Text(text = "Image") },+ onClick = {+ showMenu = false+ onAttachmentSelected(AttachmentType.Image)+ }+ )+ DropdownMenuItem(+ text = { Text(text = "Document") },+ onClick = {+ showMenu = false+ onAttachmentSelected(AttachmentType.Document)+ }+ )+ }}}+ val canSend = messageText.isNotBlank() || attachments.isNotEmpty()+IconButton(onClick = if (isGenerating) onStop else onSend,- enabled = !isDownloading,+ enabled = !isDownloading && (isGenerating || canSend),modifier = Modifier.size(36.dp)) {val icon = when {diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.ktnew file mode 100644index 0000000000..47aaf6d076--- /dev/null+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt@@ -0,0 +1,306 @@+package io.ente.ensu.chat++import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.IntrinsicSize+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.selection.SelectionContainer+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.outlined.ContentCopy+import androidx.compose.material3.Divider+import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalClipboardManager+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.buildAnnotatedString+import androidx.compose.ui.text.font.FontStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.text.withStyle+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import io.ente.ensu.designsystem.EnsuColor+import io.ente.ensu.designsystem.EnsuCornerRadius+import io.ente.ensu.designsystem.EnsuSpacing+import io.ente.ensu.designsystem.EnsuTypography++@Composable+fun MarkdownView(markdown: String) {+ val blocks = MarkdownParser.parse(markdown)+ SelectionContainer {+ Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {+ blocks.forEach { block ->+ when (block) {+ is MarkdownBlock.Heading -> {+ Text(+ text = markdownAnnotatedText(block.text),+ style = headingStyle(block.level),+ color = EnsuColor.textPrimary()+ )+ }+ is MarkdownBlock.Paragraph -> {+ Text(+ text = markdownAnnotatedText(block.text),+ style = EnsuTypography.message,+ color = EnsuColor.textPrimary()+ )+ }+ is MarkdownBlock.BlockQuote -> {+ BlockQuoteView(text = block.text)+ }+ is MarkdownBlock.Code -> {+ CodeBlockView(code = block.text)+ }+ is MarkdownBlock.ListItems -> {+ Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp)) {+ block.items.forEach { item ->+ Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {+ Text(text = "β’", style = EnsuTypography.message, color = EnsuColor.textPrimary())+ Text(+ text = markdownAnnotatedText(item),+ style = EnsuTypography.message,+ color = EnsuColor.textPrimary()+ )+ }+ }+ }+ }+ MarkdownBlock.Divider -> {+ Divider(color = EnsuColor.border())+ }+ }+ }+ }+ }+}++@Composable+private fun BlockQuoteView(text: String) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .height(IntrinsicSize.Min)+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.card.dp))+ .padding(EnsuSpacing.cardPadding.dp)+ ) {+ Box(+ modifier = Modifier+ .fillMaxHeight()+ .width(3.dp)+ .background(EnsuColor.border())+ )+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))+ Text(+ text = markdownAnnotatedText(text),+ style = EnsuTypography.message,+ color = EnsuColor.textPrimary()+ )+ }+}++@Composable+private fun CodeBlockView(code: String) {+ val clipboard = LocalClipboardManager.current+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.codeBlock.dp))+ .border(1.dp, EnsuColor.border(), RoundedCornerShape(EnsuCornerRadius.codeBlock.dp))+ ) {+ Row(+ modifier = Modifier+ .horizontalScroll(rememberScrollState())+ .padding(+ start = EnsuSpacing.cardPadding.dp,+ end = (EnsuSpacing.cardPadding + 28).dp,+ top = EnsuSpacing.cardPadding.dp,+ bottom = EnsuSpacing.cardPadding.dp+ )+ ) {+ Text(+ text = code,+ style = EnsuTypography.code,+ color = EnsuColor.textPrimary()+ )+ }++ IconButton(+ onClick = { clipboard.setText(AnnotatedString(code)) },+ modifier = Modifier+ .align(Alignment.TopEnd)+ .padding(EnsuSpacing.xs.dp)+ .size(28.dp)+ ) {+ Icon(+ imageVector = Icons.Outlined.ContentCopy,+ contentDescription = "Copy code",+ tint = EnsuColor.textMuted()+ )+ }+ }+}++private fun headingStyle(level: Int): TextStyle {+ val size = when (level) {+ 1 -> 20.sp+ 2 -> 18.sp+ else -> 16.sp+ }+ return EnsuTypography.message.copy(fontSize = size, fontWeight = FontWeight.SemiBold, lineHeight = (size.value + 6).sp)+}++private fun markdownAnnotatedText(text: String): AnnotatedString {+ val pattern = Regex("(\\*\\*[^*]+\\*\\*|`[^`]+`|\\*[^*]+\\*)")+ val codeFamily = EnsuTypography.code.fontFamily+ return buildAnnotatedString {+ var currentIndex = 0+ pattern.findAll(text).forEach { match ->+ val start = match.range.first+ val end = match.range.last + 1+ if (start > currentIndex) {+ append(text.substring(currentIndex, start))+ }+ val token = match.value+ when {+ token.startsWith("**") -> {+ withStyle(SpanStyle(fontWeight = FontWeight.SemiBold)) {+ append(token.removePrefix("**").removeSuffix("**"))+ }+ }+ token.startsWith("`") -> {+ withStyle(SpanStyle(fontFamily = codeFamily)) {+ append(token.removePrefix("`").removeSuffix("`"))+ }+ }+ token.startsWith("*") -> {+ withStyle(SpanStyle(fontStyle = FontStyle.Italic)) {+ append(token.removePrefix("*").removeSuffix("*"))+ }+ }+ }+ currentIndex = end+ }+ if (currentIndex < text.length) {+ append(text.substring(currentIndex))+ }+ }+}++private sealed class MarkdownBlock {+ data class Heading(val level: Int, val text: String) : MarkdownBlock()+ data class Paragraph(val text: String) : MarkdownBlock()+ data class BlockQuote(val text: String) : MarkdownBlock()+ data class Code(val text: String) : MarkdownBlock()+ data class ListItems(val items: List<String>) : MarkdownBlock()+ data object Divider : MarkdownBlock()+}++private object MarkdownParser {+ fun parse(text: String): List<MarkdownBlock> {+ val blocks = mutableListOf<MarkdownBlock>()+ val segments = text.split("```")+ segments.forEachIndexed { index, segment ->+ if (index % 2 == 1) {+ val code = segment.trim()+ if (code.isNotEmpty()) {+ blocks.add(MarkdownBlock.Code(code))+ }+ } else {+ blocks.addAll(parseTextBlocks(segment))+ }+ }+ return blocks+ }++ private fun parseTextBlocks(text: String): List<MarkdownBlock> {+ val lines = text.split("\n")+ val blocks = mutableListOf<MarkdownBlock>()+ val paragraph = mutableListOf<String>()+ val listItems = mutableListOf<String>()++ fun flushParagraph() {+ if (paragraph.isNotEmpty()) {+ blocks.add(MarkdownBlock.Paragraph(paragraph.joinToString("\n")))+ paragraph.clear()+ }+ }++ fun flushList() {+ if (listItems.isNotEmpty()) {+ blocks.add(MarkdownBlock.ListItems(listItems.toList()))+ listItems.clear()+ }+ }++ for (line in lines) {+ val trimmed = line.trim()+ if (trimmed.isEmpty()) {+ flushParagraph()+ flushList()+ continue+ }++ if (trimmed == "---" || trimmed == "***" || trimmed == "___") {+ flushParagraph()+ flushList()+ blocks.add(MarkdownBlock.Divider)+ continue+ }++ if (trimmed.startsWith("# ") || trimmed.startsWith("## ") || trimmed.startsWith("### ")) {+ flushParagraph()+ flushList()+ val level = trimmed.takeWhile { it == '#' }.length.coerceIn(1, 3)+ val headingText = trimmed.dropWhile { it == '#' || it == ' ' }+ blocks.add(MarkdownBlock.Heading(level, headingText))+ continue+ }++ if (trimmed.startsWith(">")) {+ flushParagraph()+ flushList()+ val quote = trimmed.dropWhile { it == '>' || it == ' ' }+ blocks.add(MarkdownBlock.BlockQuote(quote))+ continue+ }++ if (trimmed.startsWith("- ") || trimmed.startsWith("* ")) {+ flushParagraph()+ listItems.add(trimmed.drop(2))+ continue+ }++ val orderedMatch = Regex("^(\\d+)\\. ").find(trimmed)+ if (orderedMatch != null) {+ flushParagraph()+ listItems.add(trimmed.substring(orderedMatch.value.length))+ continue+ }++ paragraph.add(line)+ }++ flushParagraph()+ flushList()+ return blocks+ }+}diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.ktindex 026447de5b..017e3eb772 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt@@ -36,8 +36,6 @@ import androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip-import androidx.compose.ui.graphics.Brush-import androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dp@@ -119,19 +117,10 @@ private fun DrawerHeader(onOpenDeveloperSettings: () -> Unit,onOpenModelSettings: () -> Unit) {- val backgroundBrush = Brush.linearGradient(- colors = listOf(- EnsuColor.accent().copy(alpha = 0.2f),- EnsuColor.backgroundBase()- ),- start = Offset(0f, 0f),- end = Offset(600f, 600f)- )-Column(modifier = Modifier.fillMaxWidth()- .background(backgroundBrush)+ .background(EnsuColor.backgroundBase()).padding(EnsuSpacing.lg.dp),verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.ktindex 4dcbbc6442..187844e5e1 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.kt@@ -1,5 +1,6 @@package io.ente.ensu.components+import androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Row@@ -7,16 +8,23 @@ import androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.width-import androidx.compose.material3.AssistChip-import androidx.compose.material3.AssistChipDefaults+import androidx.compose.foundation.layout.widthIn+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.outlined.Closeimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.Icon+import androidx.compose.material3.IconButtonimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport io.ente.ensu.designsystem.EnsuColor+import io.ente.ensu.designsystem.EnsuCornerRadius+import io.ente.ensu.designsystem.EnsuSpacingimport io.ente.ensu.designsystem.EnsuTypography@Composable@@ -27,25 +35,55 @@ fun AttachmentChip(isUploading: Boolean,onDelete: (() -> Unit)? = null) {- AssistChip(- onClick = { onDelete?.invoke() },- label = {- Column(verticalArrangement = Arrangement.Center) {- Text(text = name, style = EnsuTypography.small, maxLines = 1)- Text(text = size, style = EnsuTypography.mini, color = EnsuColor.textMuted())- }- },- leadingIcon = {- Icon(imageVector = icon, contentDescription = null, modifier = Modifier.size(16.dp))- },- trailingIcon = {- if (isUploading) {- CircularProgressIndicator(- modifier = Modifier.size(12.dp),- strokeWidth = 2.dp+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .widthIn(max = 220.dp)+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp))+ .padding(horizontal = 10.dp, vertical = 6.dp)+ ) {+ Icon(+ imageVector = icon,+ contentDescription = null,+ modifier = Modifier.size(14.dp),+ tint = EnsuColor.textMuted()+ )+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))+ Column(+ modifier = Modifier.widthIn(max = 160.dp),+ verticalArrangement = Arrangement.Center+ ) {+ Text(+ text = name,+ style = EnsuTypography.small,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ color = EnsuColor.textPrimary()+ )+ Text(+ text = size,+ style = EnsuTypography.mini,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ color = EnsuColor.textMuted()+ )+ }+ if (isUploading) {+ Spacer(modifier = Modifier.width(EnsuSpacing.xs.dp))+ CircularProgressIndicator(+ modifier = Modifier.size(12.dp),+ strokeWidth = 2.dp+ )+ }+ if (onDelete != null) {+ Spacer(modifier = Modifier.width(EnsuSpacing.xs.dp))+ IconButton(onClick = onDelete, modifier = Modifier.size(24.dp)) {+ Icon(+ imageVector = Icons.Outlined.Close,+ contentDescription = "Remove attachment",+ tint = EnsuColor.textMuted())}- },- colors = AssistChipDefaults.assistChipColors(containerColor = EnsuColor.fillFaint())- )+ }+ }}diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.ktindex 38cc293a0b..e96349faef 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.kt@@ -8,6 +8,7 @@ import androidx.compose.material3.Textimport androidx.compose.material3.TextButtonimport androidx.compose.material3.ButtonDefaultsimport androidx.compose.runtime.Composable+import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.dpimport io.ente.ensu.designsystem.EnsuColor@@ -22,7 +23,7 @@ fun BranchSwitcher() {if (totalCount <= 1) return- Row {+ Row(verticalAlignment = Alignment.CenterVertically) {TextButton(onClick = onPrevious,enabled = currentIndex > 1,diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.ktindex aaab5048a9..fbd73dd7ee 100644--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt@@ -29,13 +29,47 @@ import androidx.compose.ui.unit.dpimport io.ente.ensu.designsystem.EnsuColorimport io.ente.ensu.designsystem.EnsuSpacingimport io.ente.ensu.designsystem.EnsuTypography+import io.ente.ensu.domain.state.ModelSettingsState@Composable-fun ModelSettingsScreen() {- var modelUrl by remember { mutableStateOf("") }- var mmprojUrl by remember { mutableStateOf("") }- var contextLength by remember { mutableStateOf("") }- var maxTokens by remember { mutableStateOf("") }+fun ModelSettingsScreen(+ state: ModelSettingsState,+ onSave: (ModelSettingsState) -> Unit,+ onReset: () -> Unit+) {+ var modelUrl by remember(state) { mutableStateOf(state.modelUrl) }+ var mmprojUrl by remember(state) { mutableStateOf(state.mmprojUrl) }+ var contextLength by remember(state) { mutableStateOf(state.contextLength) }+ var maxTokens by remember(state) { mutableStateOf(state.maxTokens) }++ val suggestedModels = listOf(+ SuggestedModel(+ title = "Qwen3-VL 2B Instruct (Q4_K_M)",+ subtitle = "Requires mmproj",+ url = "https://huggingface.co/LiquidAI/Qwen3-VL-2B-Instruct-GGUF/resolve/main/Qwen3-VL-2B-Instruct-Q4_K_M.gguf",+ mmproj = "https://huggingface.co/LiquidAI/Qwen3-VL-2B-Instruct-GGUF/resolve/main/mmproj-qwen3-vl-2b.gguf"+ ),+ SuggestedModel(+ title = "LFM 2.5 1.2B Instruct (Q4_0)",+ subtitle = "Smallest download",+ url = "https://huggingface.co/LiquidAI/LFM2.5-1.2B-GGUF/resolve/main/LFM2.5-1.2B-Q4_0.gguf",+ mmproj = null+ ),+ SuggestedModel(+ title = "LFM 2.5 VL 1.6B (Q4_0)",+ subtitle = "Requires mmproj",+ url = "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf",+ mmproj = "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"+ ),+ SuggestedModel(+ title = "Llama 3.2 1B Instruct (Q4_K_M)",+ subtitle = "Fastest load",+ url = "https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf",+ mmproj = null+ )+ )++ val isCustomSelected = state.useCustomModel && modelUrl.isNotBlank()Column(modifier = Modifier@@ -44,8 +78,14 @@ fun ModelSettingsScreen() {.padding(EnsuSpacing.pageHorizontal.dp)) {SectionHeader("Selected model")- Text(text = "Qwen3-VL 2B Instruct", style = EnsuTypography.body)- Text(text = "Not loaded", style = EnsuTypography.small, color = EnsuColor.textMuted())+ val selectedLabel = if (isCustomSelected) "Custom model" else "Default model"+ Text(text = selectedLabel, style = EnsuTypography.body)+ if (isCustomSelected) {+ Text(text = modelUrl, style = EnsuTypography.small, color = EnsuColor.textMuted())+ } else {+ Text(text = DEFAULT_MODEL_NAME, style = EnsuTypography.small, color = EnsuColor.textMuted())+ Text(text = DEFAULT_MODEL_URL, style = EnsuTypography.mini, color = EnsuColor.textMuted())+ }Spacer(modifier = Modifier.height(EnsuSpacing.xl.dp))SectionHeader("Custom Hugging Face model")@@ -74,22 +114,16 @@ fun ModelSettingsScreen() {Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))Text(text = "Suggested models:", style = EnsuTypography.small, color = EnsuColor.textMuted())- SuggestedModelCard(- title = "Qwen3-VL 2B Instruct (Q4_K_M)",- subtitle = "Requires mmproj"- )- SuggestedModelCard(- title = "LFM 2.5 1.2B Instruct (Q4_0)",- subtitle = "Smallest download"- )- SuggestedModelCard(- title = "LFM 2.5 VL 1.6B (Q4_0)",- subtitle = "Requires mmproj"- )- SuggestedModelCard(- title = "Llama 3.2 1B Instruct (Q4_K_M)",- subtitle = "Fastest load"- )+ suggestedModels.forEach { model ->+ SuggestedModelCard(+ title = model.title,+ subtitle = model.subtitle,+ onFill = {+ modelUrl = model.url+ mmprojUrl = model.mmproj.orEmpty()+ }+ )+ }Spacer(modifier = Modifier.height(EnsuSpacing.xl.dp))SectionHeader("Custom limits (optional)")@@ -129,7 +163,17 @@ fun ModelSettingsScreen() {Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))Button(- onClick = {},+ onClick = {+ onSave(+ state.copy(+ useCustomModel = true,+ modelUrl = modelUrl,+ mmprojUrl = mmprojUrl,+ contextLength = contextLength,+ maxTokens = maxTokens+ )+ )+ },modifier = Modifier.fillMaxWidth(),colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent())) {@@ -138,7 +182,13 @@ fun ModelSettingsScreen() {Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))- TextButton(onClick = {}) {+ TextButton(onClick = {+ onReset()+ modelUrl = ""+ mmprojUrl = ""+ contextLength = ""+ maxTokens = ""+ }) {Text(text = "Use Default Model", style = EnsuTypography.body, color = EnsuColor.accent())}@@ -157,7 +207,7 @@ private fun SectionHeader(title: String) {}@Composable-private fun SuggestedModelCard(title: String, subtitle: String) {+private fun SuggestedModelCard(title: String, subtitle: String, onFill: () -> Unit) {Card(modifier = Modifier.fillMaxWidth().padding(vertical = EnsuSpacing.xs.dp)@@ -165,9 +215,20 @@ private fun SuggestedModelCard(title: String, subtitle: String) {Column(modifier = Modifier.padding(EnsuSpacing.md.dp)) {Text(text = title, style = EnsuTypography.body)Text(text = subtitle, style = EnsuTypography.small, color = EnsuColor.textMuted())- TextButton(onClick = {}) {+ TextButton(onClick = onFill) {Text(text = "Fill", style = EnsuTypography.small, color = EnsuColor.accent())}}}}++private data class SuggestedModel(+ val title: String,+ val subtitle: String,+ val url: String,+ val mmproj: String?+)++private const val DEFAULT_MODEL_NAME = "LFM 2.5 VL 1.6B (Q4_0)"+private const val DEFAULT_MODEL_URL =+ "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf"diff --git a/mobile/native/android/apps/ensu/data/build.gradle.kts b/mobile/native/android/apps/ensu/data/build.gradle.ktsindex 17b19a6c77..cf505fb46e 100644--- a/mobile/native/android/apps/ensu/data/build.gradle.kts+++ b/mobile/native/android/apps/ensu/data/build.gradle.kts@@ -25,6 +25,7 @@ android {dependencies {implementation(project(":domain"))implementation(project(":crypto-auth-core"))+ implementation(project(":rust"))implementation("androidx.core:core-ktx:1.12.0")implementation("androidx.datastore:datastore-preferences:1.1.1")implementation("androidx.security:security-crypto:1.1.0-alpha06")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.ktnew file mode 100644index 0000000000..ce3026af55--- /dev/null+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt@@ -0,0 +1,368 @@+package io.ente.ensu.data.llm++import io.ente.ensu.domain.llm.DownloadProgress+import io.ente.ensu.domain.llm.GenerationSummary+import io.ente.ensu.domain.llm.LlmMessage+import io.ente.ensu.domain.llm.LlmModelTarget+import io.ente.ensu.domain.llm.LlmProvider+import io.ente.labs.inference_rs.ContextHandle+import io.ente.labs.inference_rs.ContextParams+import io.ente.labs.inference_rs.GenerateChatRequest+import io.ente.labs.inference_rs.GenerateEvent+import io.ente.labs.inference_rs.GenerateEventCallback+import io.ente.labs.inference_rs.GenerateSummary as NativeSummary+import io.ente.labs.inference_rs.ModelHandle+import io.ente.labs.inference_rs.ModelLoadParams+import io.ente.labs.inference_rs.initBackend+import io.ente.labs.inference_rs.loadModel+import io.ente.labs.inference_rs.createContext+import io.ente.labs.inference_rs.generateChatStream+import io.ente.labs.inference_rs.cancel+import io.ente.labs.inference_rs.uniffiEnsureInitialized+import io.ente.labs.inference_rs.InferenceException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import okhttp3.OkHttpClient+import okhttp3.Request+import okhttp3.Call+import java.io.File+import java.io.FileOutputStream+import java.io.IOException+import java.security.MessageDigest+import java.util.Locale+import java.util.concurrent.atomic.AtomicBoolean+import kotlin.math.max++class InferenceRsProvider(+ private val modelDir: File,+ private val ioDispatcher: kotlinx.coroutines.CoroutineDispatcher = Dispatchers.IO+) : LlmProvider {+ private val httpClient = OkHttpClient()+ private val downloadCancelled = AtomicBoolean(false)+ @Volatile private var downloadCall: Call? = null++ @Volatile private var modelHandle: ModelHandle? = null+ @Volatile private var contextHandle: ContextHandle? = null+ @Volatile private var currentModelId: String? = null+ @Volatile private var currentJobId: Long? = null+ private var backendInitialized = false++ init {+ uniffiEnsureInitialized()+ }++ override suspend fun ensureModelReady(+ target: LlmModelTarget,+ onProgress: (DownloadProgress) -> Unit+ ) {+ withContext(ioDispatcher) {+ if (!backendInitialized) {+ initBackend()+ backendInitialized = true+ }++ if (currentModelId == target.id && contextHandle != null && modelHandle != null) {+ return@withContext+ }++ unloadModel()++ val modelFile = modelPathFor(target)+ val mmprojFile = mmprojPathFor(target)+ val mmprojUrl = target.mmprojUrl++ val downloads = mutableListOf<DownloadTarget>()+ if (!modelFile.exists()) {+ downloads.add(DownloadTarget("Model", target.url, modelFile))+ }+ if (mmprojFile != null && !mmprojUrl.isNullOrBlank() && !mmprojFile.exists()) {+ downloads.add(DownloadTarget("Mmproj", mmprojUrl, mmprojFile))+ }++ if (downloads.isNotEmpty()) {+ downloadCancelled.set(false)+ onProgress(DownloadProgress(0, "Starting download..."))+ modelFile.parentFile?.mkdirs()+ mmprojFile?.parentFile?.mkdirs()++ val lengths = downloads.map { fetchContentLength(it.url) }+ val totalBytes = lengths.filterNotNull().sum()+ val hasTotal = lengths.all { it != null } && totalBytes > 0+ var downloadedSoFar = 0L++ downloads.forEachIndexed { index, download ->+ val fileTotal = lengths[index]+ downloadFile(download.url, download.destination) { downloaded, total ->+ val overallDownloaded = downloadedSoFar + downloaded+ val percent = if (hasTotal) {+ ((overallDownloaded * 100) / totalBytes).toInt()+ } else {+ val step = 100f / downloads.size+ val filePercent = total?.let { downloaded.toFloat() / it } ?: 0f+ ((index * step) + (filePercent * step)).toInt()+ }+ val status = if (hasTotal) {+ "Downloading... ${formatBytes(overallDownloaded)} / ${formatBytes(totalBytes)}"+ } else {+ "Downloading ${download.label.lowercase()}... ${formatBytes(downloaded)}"+ }+ onProgress(DownloadProgress(percent.coerceIn(0, 99), status))+ }+ downloadedSoFar += fileTotal ?: download.destination.length()+ }+ }++ onProgress(DownloadProgress(100, "Loading model..."))+ loadWithFallbacks(target, modelFile)+ onProgress(DownloadProgress(100, "Ready"))+ }+ }++ override suspend fun generateChat(+ target: LlmModelTarget,+ messages: List<LlmMessage>,+ imageFiles: List<File>,+ temperature: Float,+ maxTokens: Int,+ onToken: (String) -> Unit+ ): GenerationSummary = withContext(ioDispatcher) {+ val context = contextHandle ?: throw IllegalStateException("Model context not loaded")+ val mmprojPath = if (imageFiles.isEmpty()) null else mmprojPathFor(target)?.absolutePath++ val request = GenerateChatRequest(+ messages = messages.map { msg ->+ io.ente.labs.inference_rs.ChatMessage(msg.isUserRole(), msg.text)+ },+ templateOverride = null,+ addAssistant = true,+ imagePaths = imageFiles.map { it.absolutePath },+ mmprojPath = mmprojPath,+ mediaMarker = null,+ maxTokens = maxTokens,+ temperature = temperature,+ topP = null,+ topK = null,+ repeatPenalty = null,+ frequencyPenalty = null,+ presencePenalty = null,+ seed = null,+ stopSequences = null,+ grammar = null+ )++ val summary = generateStreamWithCallback(context, request, onToken)+ GenerationSummary(summary.jobId, summary.generatedTokens ?: 0, summary.totalTimeMs)+ }++ override fun stopGeneration() {+ currentJobId?.let { cancel(it) }+ }++ override fun resetContext() {+ val model = modelHandle ?: return+ val contextParams = ContextParams(+ contextSize = null,+ nThreads = null,+ nBatch = null+ )+ contextHandle?.destroy()+ contextHandle = createContext(model, contextParams)+ }++ override fun cancelDownload() {+ downloadCancelled.set(true)+ downloadCall?.cancel()+ }++ private fun LlmMessage.isUserRole(): String {+ return if (isUser) "user" else "assistant"+ }++ private fun unloadModel() {+ contextHandle?.destroy()+ contextHandle = null+ modelHandle?.destroy()+ modelHandle = null+ currentModelId = null+ }++ private fun loadWithFallbacks(target: LlmModelTarget, modelFile: File) {+ val desiredCtx = target.contextLength ?: 4096+ val contexts = listOf(desiredCtx, 4096, 2048, 1024).distinct().filter { it > 0 }+ val threads = max(1, Runtime.getRuntime().availableProcessors() - 1)+ val batch = 512++ val modelParams = ModelLoadParams(+ modelPath = modelFile.absolutePath,+ nGpuLayers = 0,+ useMmap = true,+ useMlock = false+ )++ val model = loadModel(modelParams)+ modelHandle = model++ var lastError: Throwable? = null+ for (ctx in contexts) {+ try {+ val contextParams = ContextParams(+ contextSize = ctx,+ nThreads = threads,+ nBatch = batch+ )+ contextHandle = createContext(model, contextParams)+ currentModelId = target.id+ return+ } catch (err: Throwable) {+ lastError = err+ }+ }+ unloadModel()+ throw lastError ?: IllegalStateException("Failed to load model")+ }++ private fun downloadFile(+ url: String,+ dest: File,+ onProgress: (Long, Long?) -> Unit+ ) {+ val tmp = File(dest.absolutePath + ".tmp")+ if (tmp.exists()) tmp.delete()++ val request = Request.Builder().url(url).build()+ val call = httpClient.newCall(request)+ downloadCall = call++ val response = call.execute()+ if (!response.isSuccessful) {+ response.close()+ throw IOException("Download failed: HTTP ${response.code}")+ }++ val body = response.body ?: throw IOException("Empty response body")+ val totalBytes = body.contentLength().takeIf { it > 0 }+ var downloaded = 0L++ FileOutputStream(tmp).use { out ->+ body.byteStream().use { input ->+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)+ while (true) {+ if (downloadCancelled.get()) {+ call.cancel()+ response.close()+ tmp.delete()+ throw IOException("Download cancelled")+ }+ val read = input.read(buffer)+ if (read == -1) break+ out.write(buffer, 0, read)+ downloaded += read+ onProgress(downloaded, totalBytes)+ }+ }+ }+ response.close()++ if (!looksLikeGguf(tmp)) {+ tmp.delete()+ throw IOException("Downloaded file is not GGUF")+ }+ if (dest.exists()) dest.delete()+ tmp.renameTo(dest)+ }++ private fun fetchContentLength(url: String): Long? {+ val request = Request.Builder().url(url).head().build()+ return try {+ httpClient.newCall(request).execute().use { response ->+ if (!response.isSuccessful) return null+ response.body?.contentLength()?.takeIf { it > 0 }+ ?: response.header("Content-Length")?.toLongOrNull()+ }+ } catch (_: IOException) {+ null+ }+ }++ private data class DownloadTarget(+ val label: String,+ val url: String,+ val destination: File+ )++ private fun modelPathFor(target: LlmModelTarget): File {+ val baseDir = File(modelDir, "models")+ val filename = target.url.substringAfterLast('/').ifBlank { "model.gguf" }+ return if (target.id.startsWith("custom:")) {+ val customDir = File(baseDir, "custom")+ File(customDir, "${hash(target.url)}_$filename")+ } else {+ File(baseDir, filename)+ }+ }++ private fun mmprojPathFor(target: LlmModelTarget): File? {+ val url = target.mmprojUrl ?: return null+ val baseDir = File(modelDir, "models")+ val filename = url.substringAfterLast('/').ifBlank { "mmproj.gguf" }+ return if (target.id.startsWith("custom:")) {+ val customDir = File(baseDir, "custom")+ File(customDir, "${hash(url)}_$filename")+ } else {+ File(baseDir, filename)+ }+ }++ private fun looksLikeGguf(file: File): Boolean {+ if (!file.exists() || file.length() < 4) return false+ val header = ByteArray(4)+ file.inputStream().use { input ->+ if (input.read(header) != 4) return false+ }+ return header.contentEquals("GGUF".toByteArray())+ }++ private fun hash(value: String): String {+ val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray())+ 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,+ onToken: (String) -> Unit+ ): NativeSummary {+ var error: Throwable? = null++ val callback = object : GenerateEventCallback {+ override fun onEvent(event: GenerateEvent) {+ when (event) {+ is GenerateEvent.Text -> {+ currentJobId = event.jobId+ onToken(event.text)+ }+ is GenerateEvent.Done -> Unit+ is GenerateEvent.Error -> {+ error = InferenceException.Message(event.message)+ }+ }+ }+ }++ val summary = generateChatStream(context, request, callback)++ error?.let { throw it }+ return summary+ }+}diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.ktnew file mode 100644index 0000000000..a80c09980c--- /dev/null+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt@@ -0,0 +1,49 @@+package io.ente.ensu.domain.llm++import java.io.File+++data class LlmModelTarget(+ val id: String,+ val url: String,+ val mmprojUrl: String? = null,+ val contextLength: Int? = null,+ val maxTokens: Int? = null+)++data class DownloadProgress(+ val percent: Int,+ val status: String+)++data class LlmMessage(+ val text: String,+ val isUser: Boolean,+ val hasAttachments: Boolean = false+)++data class GenerationSummary(+ val jobId: Long,+ val generatedTokens: Int,+ val totalTimeMs: Long?+)++interface LlmProvider {+ suspend fun ensureModelReady(+ target: LlmModelTarget,+ onProgress: (DownloadProgress) -> Unit+ )++ suspend fun generateChat(+ target: LlmModelTarget,+ messages: List<LlmMessage>,+ imageFiles: List<File>,+ temperature: Float,+ maxTokens: Int,+ onToken: (String) -> Unit+ ): GenerationSummary++ fun stopGeneration()+ fun resetContext()+ fun cancelDownload()+}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 a297b2cc3d..aba8370946 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@@ -10,6 +10,7 @@ enum class MessageAuthor {data class ChatMessage(val id: String = UUID.randomUUID().toString(),val sessionId: String,+ val parentId: String? = null,val author: MessageAuthor,val text: String,val timestampMillis: Long,@@ -36,5 +37,6 @@ data class Attachment(val name: String,val sizeBytes: Long,val type: AttachmentType,+ val localPath: String? = null,val isUploading: Boolean = false)diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.ktindex ec423448fb..a1c7098e65 100644--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt@@ -10,8 +10,11 @@ data class ChatState(val currentSessionId: String? = null,val messages: List<ChatMessage> = emptyList(),val streamingResponse: String = "",+ val streamingParentId: String? = null,val isGenerating: Boolean = false,val isDownloading: Boolean = false,+ val downloadPercent: Int? = null,+ val downloadStatus: String? = null,val messageText: String = "",val attachments: List<Attachment> = emptyList(),val editingMessageId: String? = null,diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.ktindex 015aaa13bd..11c91ac738 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@@ -1,7 +1,10 @@package io.ente.ensu.domain.store-import io.ente.ensu.domain.logging.LogRepository-import io.ente.ensu.domain.logging.NoOpLogRepository+import io.ente.ensu.domain.llm.LlmMessage+import io.ente.ensu.domain.llm.LlmModelTarget+import io.ente.ensu.domain.llm.LlmProvider+import io.ente.ensu.domain.model.Attachment+import io.ente.ensu.domain.model.AttachmentTypeimport io.ente.ensu.domain.model.AuthStateimport io.ente.ensu.domain.model.ChatMessageimport io.ente.ensu.domain.model.ChatSession@@ -9,24 +12,38 @@ import io.ente.ensu.domain.model.LogLevelimport io.ente.ensu.domain.model.MessageAuthorimport io.ente.ensu.domain.preferences.SessionPreferencesimport io.ente.ensu.domain.state.AppState-import io.ente.ensu.domain.state.ChatState+import io.ente.ensu.domain.state.ModelSettingsState+import io.ente.ensu.domain.logging.LogRepository+import io.ente.ensu.domain.logging.NoOpLogRepositoryimport kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Jobimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.updateimport kotlinx.coroutines.launch+import kotlin.math.abs+import kotlin.math.maxclass AppStore(private val sessionPreferences: SessionPreferences,+ private val llmProvider: LlmProvider,private val clock: () -> Long = { System.currentTimeMillis() },private val logRepository: LogRepository = NoOpLogRepository) {private val _state = MutableStateFlow(AppState())val state: StateFlow<AppState> = _state.asStateFlow()+ private val messageStore = mutableMapOf<String, MutableList<ChatMessage>>()+ private val branchSelections = mutableMapOf<String, MutableMap<String, String>>()+ private var scope: CoroutineScope? = null+ private var generationJob: Job? = null+ private var stopRequested = false+ private var streamingParentId: String? = null+fun bootstrap(scope: CoroutineScope) {+ this.scope = scopelogRepository.log(LogLevel.Info, "EnsΕ« started")if (_state.value.chat.sessions.isEmpty()) {@@ -43,16 +60,36 @@ class AppStore(appState}}+ rebuildChatState(storedId)}}}}fun createNewSession(): String {+ generationJob?.cancel()+ llmProvider.stopGeneration()+ streamingParentId = null+ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isGenerating = false,+ isDownloading = false,+ streamingResponse = "",+ streamingParentId = null,+ downloadPercent = null,+ downloadStatus = null+ )+ )+ }+val session = ChatSession(title = "New Chat",updatedAtMillis = clock())+ messageStore[session.id] = mutableListOf()+ branchSelections[session.id] = mutableMapOf()+_state.update { appState ->val updatedSessions = listOf(session) + appState.chat.sessionsappState.copy(@@ -60,18 +97,34 @@ class AppStore(sessions = updatedSessions,currentSessionId = session.id,messageText = "",- attachments = emptyList()+ attachments = emptyList(),+ editingMessageId = null))}+ rebuildChatState(session.id)logRepository.log(LogLevel.Info, "Created new session")return session.id}fun selectSession(sessionId: String) {+ generationJob?.cancel()+ llmProvider.stopGeneration()+ streamingParentId = null_state.update { appState ->- appState.copy(chat = appState.chat.copy(currentSessionId = sessionId))+ appState.copy(+ chat = appState.chat.copy(+ currentSessionId = sessionId,+ isGenerating = false,+ isDownloading = false,+ streamingResponse = "",+ streamingParentId = null,+ downloadPercent = null,+ downloadStatus = null+ )+ )}+ rebuildChatState(sessionId)logRepository.log(LogLevel.Info, "Selected session", sessionId)}@@ -88,56 +141,168 @@ class AppStore(}fun updateBranchSelection(messageId: String, selectedIndex: Int) {+ val sessionId = _state.value.chat.currentSessionId ?: return+ val messages = messageStore[sessionId].orEmpty()+ val byId = messages.associateBy { it.id }+ val message = byId[messageId] ?: return+ val parentKey = message.parentId?.takeIf { byId.containsKey(it) } ?: "__root__"+ val siblings = dedupeSiblings(buildChildrenMap(messages)[parentKey].orEmpty())+ if (siblings.isEmpty()) return+ val index = (selectedIndex - 1).coerceIn(0, siblings.lastIndex)+ val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }+ selectionMap[parentKey] = siblings[index].id+ rebuildChatState(sessionId)+ }++ fun beginEditing(messageId: String) {+ val sessionId = _state.value.chat.currentSessionId ?: return+ val message = messageStore[sessionId]?.firstOrNull { it.id == messageId } ?: return+ if (message.author != MessageAuthor.User) return+_state.update { appState ->- val updatedSelections = appState.chat.branchSelections.toMutableMap()- updatedSelections[messageId] = selectedIndex- appState.copy(chat = appState.chat.copy(branchSelections = updatedSelections))+ appState.copy(+ chat = appState.chat.copy(+ editingMessageId = message.id,+ messageText = message.text,+ attachments = message.attachments+ )+ )}}+ fun cancelEditing() {+ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ editingMessageId = null,+ messageText = "",+ attachments = emptyList()+ )+ )+ }+ }++ fun setAttachmentProcessing(isProcessing: Boolean) {+ _state.update { appState ->+ appState.copy(chat = appState.chat.copy(isProcessingAttachments = isProcessing))+ }+ }++ fun addAttachment(attachment: Attachment) {+ if (_state.value.chat.isGenerating || _state.value.chat.isDownloading) return++ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ attachments = appState.chat.attachments + attachment,+ isProcessingAttachments = false+ )+ )+ }+ }++ fun removeAttachment(attachment: Attachment) {+ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ attachments = appState.chat.attachments.filterNot { it.id == attachment.id }+ )+ )+ }+ }++ fun stopGeneration() {+ stopRequested = true+ llmProvider.stopGeneration()+ }++ fun cancelDownload() {+ generationJob?.cancel()+ llmProvider.cancelDownload()+ streamingParentId = null+ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isGenerating = false,+ isDownloading = false,+ streamingResponse = "",+ streamingParentId = null,+ downloadPercent = null,+ downloadStatus = "Download cancelled"+ )+ )+ }+ }++ fun retryAssistantMessage(messageId: String) {+ val sessionId = _state.value.chat.currentSessionId ?: return+ val message = messageStore[sessionId]?.firstOrNull { it.id == messageId } ?: return+ if (message.author != MessageAuthor.Assistant) return+ val parentId = message.parentId ?: return+ val parent = messageStore[sessionId]?.firstOrNull { it.id == parentId } ?: return++ llmProvider.resetContext()+ startGeneration(sessionId, parent)+ }+fun sendMessage() {val currentState = _state.value+ if (currentState.chat.isGenerating || currentState.chat.isDownloading) returnval text = currentState.chat.messageText.trim()- if (text.isEmpty()) return- val sessionId = currentState.chat.currentSessionId ?: return+ val attachments = currentState.chat.attachments+ if (text.isEmpty() && attachments.isEmpty()) return++ val sessionId = currentState.chat.currentSessionId ?: createNewSession()val timestamp = clock()+ val editingMessageId = currentState.chat.editingMessageId+ val parentId = if (editingMessageId != null) {+ val existing = messageStore[sessionId]?.firstOrNull { it.id == editingMessageId }+ existing?.parentId+ } else {+ buildSelectedPath(sessionId).lastOrNull()?.id+ }+val userMessage = ChatMessage(sessionId = sessionId,+ parentId = parentId,author = MessageAuthor.User,text = text,- timestampMillis = timestamp- )- val assistantMessage = ChatMessage(- sessionId = sessionId,- author = MessageAuthor.Assistant,- text = "Thinking about: $text",- timestampMillis = timestamp + 3000+ timestampMillis = timestamp,+ attachments = attachments)+ messageStore.getOrPut(sessionId) { mutableListOf() }.add(userMessage)+ updateSelectionForParent(sessionId, parentId, userMessage.id)+_state.update { appState ->- val updatedMessages = appState.chat.messages + userMessage + assistantMessage- val updatedSessions = appState.chat.sessions.map { session ->- if (session.id == sessionId) {- session.copy(- lastMessagePreview = text,- updatedAtMillis = timestamp- )- } else {- session- }- }appState.copy(chat = appState.chat.copy(- messages = updatedMessages,messageText = "",- sessions = updatedSessions+ attachments = emptyList(),+ editingMessageId = null))}++ updateCurrentSessionPreview(sessionId, text, timestamp)+ rebuildChatState(sessionId)+ startGeneration(sessionId, userMessage)logRepository.log(LogLevel.Info, "Sent message", text)}+ fun updateModelSettings(state: ModelSettingsState) {+ _state.update { appState ->+ appState.copy(modelSettings = state)+ }+ }++ fun resetModelSettings() {+ _state.update { appState ->+ appState.copy(modelSettings = ModelSettingsState())+ }+ }+fun signIn(email: String) {_state.update { appState ->appState.copy(auth = AuthState(isLoggedIn = true, email = email))@@ -152,14 +317,392 @@ class AppStore(logRepository.log(LogLevel.Info, "Signed out")}+ private fun startGeneration(sessionId: String, userMessage: ChatMessage) {+ val scope = scope ?: return+ generationJob?.cancel()+ stopRequested = false++ streamingParentId = userMessage.id+ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isGenerating = true,+ isDownloading = false,+ streamingResponse = "",+ streamingParentId = userMessage.id,+ downloadPercent = null,+ downloadStatus = null+ )+ )+ }+ rebuildChatState(sessionId)++ generationJob = scope.launch {+ val settings = _state.value.modelSettings+ val target = resolveTarget(settings)+ try {+ llmProvider.ensureModelReady(target) { progress ->+ val downloading = (progress.percent in 0..99) || progress.status.contains("Loading", ignoreCase = true)+ val finished = progress.status.contains("Ready", ignoreCase = true)+ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isDownloading = downloading && !finished,+ downloadPercent = progress.percent.takeIf { it >= 0 },+ downloadStatus = progress.status+ )+ )+ }+ }+ } catch (err: Throwable) {+ val cancelled = err is kotlinx.coroutines.CancellationException ||+ err.message?.contains("cancel", ignoreCase = true) == true+ streamingParentId = null+ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isGenerating = false,+ isDownloading = false,+ streamingParentId = null,+ downloadPercent = null,+ downloadStatus = if (cancelled) "Download cancelled" else null+ )+ )+ }+ if (!cancelled) {+ logRepository.log(LogLevel.Error, "Model load failed", err.message ?: "")+ }+ return@launch+ }++ val prompt = buildPrompt(userMessage.text, userMessage.attachments)+ val history = buildHistory(sessionId, prompt.text, userMessage.id)+ val llmMessages = history + LlmMessage(+ text = prompt.text,+ isUser = true,+ hasAttachments = userMessage.attachments.isNotEmpty()+ )++ val buffer = StringBuilder()+ var tokenCount = 0++ try {+ val summary = llmProvider.generateChat(+ target = target,+ messages = llmMessages,+ imageFiles = prompt.imageFiles,+ temperature = 0.7f,+ maxTokens = target.maxTokens ?: 1024+ ) { token ->+ buffer.append(token)+ tokenCount += estimateTokens(token)+ _state.update { appState ->+ appState.copy(chat = appState.chat.copy(streamingResponse = buffer.toString()))+ }+ }++ finishGeneration(sessionId, userMessage, buffer, tokenCount, summary.totalTimeMs, false)+ } catch (err: Throwable) {+ val interrupted = stopRequested || err.message?.contains("cancel", ignoreCase = true) == true+ finishGeneration(sessionId, userMessage, buffer, tokenCount, null, interrupted)+ if (!interrupted) {+ logRepository.log(LogLevel.Error, "Generation failed", err.message ?: "")+ }+ }+ }+ }++ private fun finishGeneration(+ sessionId: String,+ parentMessage: ChatMessage,+ buffer: StringBuilder,+ tokenCount: Int,+ totalTimeMs: Long?,+ interrupted: Boolean+ ) {+ val finalText = buffer.toString().trim()+ if (finalText.isNotEmpty()) {+ val tokensPerSecond = if (totalTimeMs != null && totalTimeMs > 0) {+ tokenCount.toDouble() / (totalTimeMs / 1000.0)+ } else null++ val assistantMessage = ChatMessage(+ sessionId = sessionId,+ parentId = parentMessage.id,+ author = MessageAuthor.Assistant,+ text = finalText,+ timestampMillis = clock(),+ isInterrupted = interrupted,+ tokensPerSecond = tokensPerSecond+ )++ messageStore.getOrPut(sessionId) { mutableListOf() }.add(assistantMessage)+ updateSelectionForParent(sessionId, parentMessage.id, assistantMessage.id)+ updateCurrentSessionPreview(sessionId, finalText, assistantMessage.timestampMillis)+ }++ streamingParentId = null+ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ isGenerating = false,+ isDownloading = false,+ streamingResponse = "",+ streamingParentId = null,+ downloadPercent = null,+ downloadStatus = null+ )+ )+ }+ rebuildChatState(sessionId)+ }++ private fun updateCurrentSessionPreview(sessionId: String, preview: String, timestamp: Long) {+ _state.update { appState ->+ val updatedSessions = appState.chat.sessions.map { session ->+ if (session.id == sessionId) {+ session.copy(lastMessagePreview = preview, updatedAtMillis = timestamp)+ } else {+ session+ }+ }+ appState.copy(chat = appState.chat.copy(sessions = updatedSessions))+ }+ }++ private fun rebuildChatState(sessionId: String?) {+ if (sessionId == null) {+ _state.update { appState ->+ appState.copy(chat = appState.chat.copy(messages = emptyList(), branchSelections = emptyMap()))+ }+ return+ }+ val messages = messageStore[sessionId].orEmpty()+ val path = buildSelectedPath(sessionId)+ val childrenMap = buildChildrenMap(messages)+ val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }+ val branchSelectionIndices = mutableMapOf<String, Int>()+ val byId = messages.associateBy { it.id }++ val displayMessages = path.map { message ->+ val parentKey = message.parentId?.takeIf { byId.containsKey(it) } ?: "__root__"+ val siblings = dedupeSiblings(childrenMap[parentKey].orEmpty())+ if (siblings.size > 1) {+ val selectedId = selectionMap[parentKey]+ val index = siblings.indexOfFirst { it.id == selectedId }+ branchSelectionIndices[message.id] = if (index >= 0) index + 1 else siblings.size+ }+ message.copy(branchCount = max(1, siblings.size))+ }++ _state.update { appState ->+ appState.copy(+ chat = appState.chat.copy(+ messages = displayMessages,+ branchSelections = branchSelectionIndices+ )+ )+ }+ }++ private fun buildSelectedPath(sessionId: String): List<ChatMessage> {+ val messages = messageStore[sessionId].orEmpty()+ if (messages.isEmpty()) return emptyList()++ val byId = messages.associateBy { it.id }+ val childrenMap = buildChildrenMap(messages)+ val roots = dedupeSiblings(messages.filter { message ->+ val parentId = message.parentId+ parentId == null || byId[parentId] == null+ })+ if (roots.isEmpty()) return emptyList()++ val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }+ var current = selectChild(selectionMap, "__root__", roots)+ val path = mutableListOf<ChatMessage>()+ val visited = mutableSetOf<String>()++ while (current != null && visited.add(current.id)) {+ path.add(current)+ if (current.id == streamingParentId) break+ val children = dedupeSiblings(childrenMap[current.id].orEmpty())+ if (children.isEmpty()) break+ current = selectChild(selectionMap, current.id, children)+ }+ return path+ }++ private fun selectChild(+ selectionMap: MutableMap<String, String>,+ selectionKey: String,+ candidates: List<ChatMessage>+ ): ChatMessage? {+ if (candidates.isEmpty()) return null+ val selectedId = selectionMap[selectionKey]+ val selected = candidates.firstOrNull { it.id == selectedId }+ return selected ?: candidates.last()+ }++ private fun buildChildrenMap(messages: List<ChatMessage>): Map<String, List<ChatMessage>> {+ val map = mutableMapOf<String, MutableList<ChatMessage>>()+ val byId = messages.associateBy { it.id }+ messages.forEach { message ->+ val parentKey = message.parentId?.takeIf { byId.containsKey(it) } ?: "__root__"+ map.getOrPut(parentKey) { mutableListOf() }.add(message)+ }+ return map+ }++ private fun dedupeSiblings(messages: List<ChatMessage>): List<ChatMessage> {+ if (messages.size <= 1) return messages.sortedBy { it.timestampMillis }+ val sorted = messages.sortedBy { it.timestampMillis }+ val result = mutableListOf<ChatMessage>()+ for (message in sorted) {+ val last = result.lastOrNull()+ if (last != null && isDuplicate(last, message)) {+ continue+ }+ result.add(message)+ }+ return result+ }++ private fun isDuplicate(left: ChatMessage, right: ChatMessage): Boolean {+ if (left.author != right.author) return false+ if (left.text != right.text) return false+ if (!attachmentsSignature(left.attachments).contentEquals(attachmentsSignature(right.attachments))) return false+ return abs(left.timestampMillis - right.timestampMillis) <= 2_000+ }++ private fun attachmentsSignature(attachments: List<Attachment>): Array<String> {+ return attachments.map { "${it.type}:${it.name}" }.toTypedArray()+ }++ private fun updateSelectionForParent(sessionId: String, parentId: String?, childId: String) {+ val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }+ val selectionKey = parentId ?: "__root__"+ selectionMap[selectionKey] = childId+ }++ private fun buildPrompt(text: String, attachments: List<Attachment>): PromptResult {+ val builder = StringBuilder(text)+ val documents = attachments.filter { it.type == AttachmentType.Document }+ val images = attachments.filter { it.type == AttachmentType.Image }++ documents.forEachIndexed { index, attachment ->+ builder.append("\n\n----- BEGIN DOCUMENT: Document ${index + 1} -----\n")+ builder.append("Attached document: ${attachment.name}\n")+ builder.append("----- END DOCUMENT: Document ${index + 1} -----")+ }++ val imageFiles = images.mapNotNull { attachment ->+ val path = attachment.localPath ?: return@mapNotNull null+ java.io.File(path).takeIf { it.exists() }+ }++ if (imageFiles.isNotEmpty()) {+ builder.append("\n\n[")+ builder.append(imageFiles.size)+ builder.append(" image attachment")+ if (imageFiles.size > 1) builder.append("s")+ builder.append(" provided]")+ imageFiles.forEach {+ builder.append("\n")+ builder.append(MEDIA_MARKER)+ }+ }++ return PromptResult(builder.toString(), imageFiles)+ }++ private fun buildHistory(sessionId: String, promptText: String, currentMessageId: String): List<LlmMessage> {+ 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 selected = mutableListOf<LlmMessage>()+ for (message in historyMessages.asReversed()) {+ val text = historyText(message)+ val cost = estimateTokens(text)+ if (cost <= remaining) {+ selected.add(LlmMessage(text, message.author == MessageAuthor.User, message.attachments.isNotEmpty()))+ remaining -= cost+ } else if (selected.isEmpty()) {+ selected.add(LlmMessage(trimToBudget(text, remaining), message.author == MessageAuthor.User, message.attachments.isNotEmpty()))+ break+ } else {+ break+ }+ }++ return selected.reversed()+ }++ private fun historyText(message: ChatMessage): String {+ var text = message.text+ if (message.author == MessageAuthor.Assistant) {+ text = text.replace(Regex("<think>[\\s\\S]*?</think>"), "")+ text = text.replace(Regex("<todo_list>[\\s\\S]*?</todo_list>"), "")+ } else if (message.attachments.isNotEmpty()) {+ text += "\n\n[${message.attachments.size} attachments attached]"+ }+ return text.trim()+ }++ private fun trimToBudget(text: String, budget: Int): String {+ if (budget <= 0) return ""+ val maxChars = budget * 4+ return if (text.length <= maxChars) text else text.takeLast(maxChars)+ }++ private fun estimateTokens(text: String): Int {+ return max(1, text.length / 4)+ }++ private fun resolveTarget(settings: ModelSettingsState): LlmModelTarget {+ val useCustom = settings.useCustomModel && settings.modelUrl.isNotBlank()+ val url = if (useCustom) settings.modelUrl else DEFAULT_MODEL_URL+ val mmproj = if (useCustom) settings.mmprojUrl.takeIf { it.isNotBlank() } else DEFAULT_MMPROJ_URL+ val contextLength = settings.contextLength.toIntOrNull()+ val maxTokens = settings.maxTokens.toIntOrNull()+ val id = if (useCustom) "custom:${url.hashCode()}" else "default"++ return LlmModelTarget(+ id = id,+ url = url,+ mmprojUrl = mmproj,+ contextLength = contextLength,+ maxTokens = maxTokens+ )+ }+private fun seedSessions() {val now = clock()- val sessions = listOf(- ChatSession(title = "Ensu starter", lastMessagePreview = "Welcome to EnsΕ«", updatedAtMillis = now - 3_600_000),- ChatSession(title = "Project notes", lastMessagePreview = "Draft the plan", updatedAtMillis = now - 86_400_000)- )+ val session = ChatSession(title = "New Chat", lastMessagePreview = null, updatedAtMillis = now)+ messageStore[session.id] = mutableListOf()+ branchSelections[session.id] = mutableMapOf()_state.update { appState ->- appState.copy(chat = appState.chat.copy(sessions = sessions, currentSessionId = sessions.first().id))+ appState.copy(chat = appState.chat.copy(sessions = listOf(session), currentSessionId = session.id))}+ rebuildChatState(session.id)+ }++ private data class PromptResult(+ val text: String,+ val imageFiles: List<java.io.File>+ )++ companion object {+ private const val DEFAULT_MODEL_URL =+ "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf"+ 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__>"}}diff --git a/mobile/native/android/apps/ensu/settings.gradle.kts b/mobile/native/android/apps/ensu/settings.gradle.ktsindex c719f77e08..149638d66a 100644--- a/mobile/native/android/apps/ensu/settings.gradle.kts+++ b/mobile/native/android/apps/ensu/settings.gradle.kts@@ -15,4 +15,6 @@ dependencyResolutionManagement {}rootProject.name = "ensu"-include(":app-ui", ":domain", ":data", ":crypto-auth-core")+include(":app-ui", ":domain", ":data", ":crypto-auth-core", ":rust")++project(":rust").projectDir = file("../../packages/rust")diff --git a/mobile/native/android/packages/rust/build.gradle.kts b/mobile/native/android/packages/rust/build.gradle.ktsnew file mode 100644index 0000000000..7234fdaa61--- /dev/null+++ b/mobile/native/android/packages/rust/build.gradle.kts@@ -0,0 +1,29 @@+plugins {+ id("com.android.library")+ id("org.jetbrains.kotlin.android")+}++android {+ namespace = "io.ente.ensu.rust"+ compileSdk = 34++ defaultConfig {+ minSdk = 23+ }++ sourceSets["main"].jniLibs.srcDir("src/main/jniLibs")++ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_17+ targetCompatibility = JavaVersion.VERSION_17+ }++ kotlinOptions {+ jvmTarget = "17"+ }+}++dependencies {+ implementation("net.java.dev.jna:jna:5.14.0@aar")+ implementation("androidx.annotation:annotation:1.7.1")+}diff --git a/mobile/native/android/packages/rust/tool/build_android.sh b/mobile/native/android/packages/rust/tool/build_android.shnew file mode 100755index 0000000000..d2b50542b5--- /dev/null+++ b/mobile/native/android/packages/rust/tool/build_android.sh@@ -0,0 +1,41 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+REPO_ROOT="$(cd "$ROOT/../../../../.." && pwd)"+UNIFFI_RUST_DIR="$REPO_ROOT/rust/inference_rs_uniffi"+CORE_ROOT="$REPO_ROOT/rust/inference_rs"+PATCH_SCRIPT="$CORE_ROOT/tool/patch_llama_mtmd.sh"+OUT_DIR="$ROOT/src/main/jniLibs"+NDK_VERSION="27.0.12077973"+NDK_ROOT_PATH="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}/ndk/$NDK_VERSION"++if [[ -z "${ANDROID_HOME:-}" && -z "${ANDROID_SDK_ROOT:-}" ]]; then+ echo "ANDROID_HOME or ANDROID_SDK_ROOT must be set" >&2+ exit 1+fi++if [[ ! -d "$NDK_ROOT_PATH" ]]; then+ echo "Android NDK not found at $NDK_ROOT_PATH" >&2+ exit 1+fi++"$PATCH_SCRIPT"++export ANDROID_NDK="$NDK_ROOT_PATH"+export ANDROID_NDK_ROOT="$NDK_ROOT_PATH"+export NDK_ROOT="$NDK_ROOT_PATH"+export CARGO_CFG_TARGET_FEATURE="${CARGO_CFG_TARGET_FEATURE:-}"++mkdir -p "$OUT_DIR"++pushd "$UNIFFI_RUST_DIR" >/dev/null+cargo ndk \+ --platform 23 \+ --link-libcxx-shared \+ -t arm64-v8a \+ -t armeabi-v7a \+ -t x86_64 \+ -o "$OUT_DIR" \+ build --release+popd >/dev/nulldiff --git a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxprojindex 288be3ab5f..c6607c199a 100644--- a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj+++ b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj@@ -10,6 +10,8 @@DACC3DAB2E604C9C00DAF993 /* Sodium in Frameworks */ = {isa = PBXBuildFile; productRef = DA72BCAB2E5F87B000D128FF /* Sodium */; };DACC3DC92E618D6A00DAF993 /* EnteNetwork in Frameworks */ = {isa = PBXBuildFile; productRef = DACC3DC82E618D6A00DAF993 /* EnteNetwork */; };21BBA57867859DAD206D6A46 /* EnteNetwork in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DACC3DC82E618D6A00DAF993 /* EnteNetwork */; };+ DAB0F20D2F5E123400ABCD01 /* InferenceRS in Frameworks */ = {isa = PBXBuildFile; productRef = DAB0F20C2F5E123400ABCD01 /* InferenceRS */; };+ DAB0F20E2F5E123400ABCD01 /* InferenceRS in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DAB0F20C2F5E123400ABCD01 /* InferenceRS */; };DAF584672E61BB8300F8A08F /* ZIPFoundation in Frameworks */ = {isa = PBXBuildFile; productRef = DAF584662E61BB8300F8A08F /* ZIPFoundation */; };/* End PBXBuildFile section */@@ -59,6 +61,7 @@buildActionMask = 2147483647;files = (DACC3DC92E618D6A00DAF993 /* EnteNetwork in Frameworks */,+ DAB0F20D2F5E123400ABCD01 /* InferenceRS in Frameworks */,);runOnlyForDeploymentPostprocessing = 0;};@@ -67,6 +70,7 @@buildActionMask = 2147483647;files = (21BBA57867859DAD206D6A46 /* EnteNetwork in Frameworks (macOS) */,+ DAB0F20E2F5E123400ABCD01 /* InferenceRS in Frameworks (macOS) */,);runOnlyForDeploymentPostprocessing = 0;};@@ -134,6 +138,7 @@name = ensu;packageProductDependencies = (DACC3DC82E618D6A00DAF993 /* EnteNetwork */,+ DAB0F20C2F5E123400ABCD01 /* InferenceRS */,);productName = ensu;productReference = DA72BC612E5F87A000D128FF /* ensu.app */;@@ -158,6 +163,7 @@name = "ensu-macos";packageProductDependencies = (DACC3DC82E618D6A00DAF993 /* EnteNetwork */,+ DAB0F20C2F5E123400ABCD01 /* InferenceRS */,);productName = Ensu;productReference = 77E1DDDF900AB047CB554122 /* Ensu.app */;@@ -241,6 +247,7 @@packageReferences = (DA72BCAA2E5F87B000D128FF /* XCRemoteSwiftPackageReference "swift-sodium" */,DACC3DC62E618D5300DAF993 /* XCLocalSwiftPackageReference "../../Packages/EnteNetwork" */,+ DAB0F20B2F5E123400ABCD01 /* XCLocalSwiftPackageReference "../../Packages/Rust" */,DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */,);preferredProjectObjectVersion = 77;@@ -817,6 +824,10 @@isa = XCLocalSwiftPackageReference;relativePath = ../../Packages/EnteNetwork;};+ DAB0F20B2F5E123400ABCD01 /* XCLocalSwiftPackageReference "../../Packages/Rust" */ = {+ isa = XCLocalSwiftPackageReference;+ relativePath = ../../Packages/Rust;+ };/* End XCLocalSwiftPackageReference section *//* Begin XCRemoteSwiftPackageReference section */@@ -848,6 +859,10 @@isa = XCSwiftPackageProductDependency;productName = EnteNetwork;};+ DAB0F20C2F5E123400ABCD01 /* InferenceRS */ = {+ isa = XCSwiftPackageProductDependency;+ productName = InferenceRS;+ };DAF584662E61BB8300F8A08F /* ZIPFoundation */ = {isa = XCSwiftPackageProductDependency;package = DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */;diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swiftindex da48e5de97..e2a89d9838 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift@@ -136,6 +136,7 @@ struct ChatView: View {MessageListView(messages: viewModel.messages,streamingResponse: viewModel.streamingResponse,+ streamingParentId: viewModel.streamingParentId,isGenerating: viewModel.isGenerating,onEdit: { message inviewModel.beginEditing(message: message)@@ -171,8 +172,11 @@ struct ChatView: View {onCancelEdit: {viewModel.cancelEditing()},- onAddAttachment: { kind in- viewModel.addAttachment(kind: kind)+ onAddImage: { data, name in+ viewModel.addImageAttachment(data: data, fileName: name)+ },+ onAddDocument: { url in+ viewModel.addDocumentAttachment(url: url)},onRemoveAttachment: { attachment inviewModel.removeAttachment(attachment)@@ -184,7 +188,9 @@ struct ChatView: View {DownloadToastView(state: downloadToast) {viewModel.downloadToast = nil} onRetry: {- viewModel.simulateDownload()+ viewModel.retryDownload()+ } onCancel: {+ viewModel.cancelDownload()}.padding(.top, EnsuSpacing.lg)}@@ -212,7 +218,7 @@ struct ChatView: View {deleteSession = session},onSync: {- viewModel.simulateDownload()+ viewModel.retryDownload()},onShowLogs: {showToast("Logs are not available yet.", duration: 2)diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swiftindex 9f9859363c..d22867e44d 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift@@ -10,13 +10,15 @@ struct ChatAttachment: Identifiable, Equatable {let name: Stringlet size: Int64let kind: Kind+ let url: URL?var isUploading: Bool- init(id: UUID = UUID(), name: String, size: Int64, kind: Kind, isUploading: Bool = false) {+ init(id: UUID = UUID(), name: String, size: Int64, kind: Kind, url: URL? = nil, isUploading: Bool = false) {self.id = idself.name = nameself.size = sizeself.kind = kind+ self.url = urlself.isUploading = isUploading}@@ -109,6 +111,7 @@ final class ChatViewModel: ObservableObject {@Published var currentSessionId: UUID?@Published var messages: [ChatMessage]@Published var streamingResponse: String = ""+ @Published var streamingParentId: UUID? = nil@Published var isGenerating: Bool = false@Published var isDownloading: Bool = false@Published var isProcessingAttachments: Bool = false@@ -117,39 +120,27 @@ final class ChatViewModel: ObservableObject {@Published var editingMessageId: UUID?@Published var downloadToast: DownloadToastState?- private var streamingTask: Task<Void, Never>?+ private let provider: InferenceRsProvider+ private let modelSettings = ModelSettingsStore.shared++ private var messageStore: [UUID: [MessageNode]] = [:]+ private var branchSelections: [UUID: [String: UUID]] = [:]+ private let rootId = UUID(uuidString: "00000000-0000-0000-0000-000000000000")!+ private var generationTask: Task<Void, Never>?+ private var stopRequested = false+ private var activeGenerationId: UUID?+ private var activeGenerationSessionId: UUID?init() {- let sampleSessions = [- ChatSession(title: "Daily brief", lastMessage: "Summarize today's highlights", updatedAt: Date()),- ChatSession(title: "Travel notes", lastMessage: "Itinerary draft", updatedAt: Date().addingTimeInterval(-3600 * 6)),- ChatSession(title: "Project outline", lastMessage: "Architecture review", updatedAt: Date().addingTimeInterval(-3600 * 30)),- ChatSession(title: "Weekend ideas", lastMessage: "Check local events", updatedAt: Date().addingTimeInterval(-3600 * 80))- ]-- self.sessions = sampleSessions- self.currentSessionId = sampleSessions.first?.id-- self.messages = [- ChatMessage(- role: .assistant,- text: "Welcome to ensu. Here's a snapshot of what this UI supports.\n\n<think>We should greet the user and highlight the key controls so they can explore the UI components.</think>\n\n<todo_list>{\"title\":\"Getting started\",\"status\":\"Optional\",\"items\":[\"Open the drawer to switch chats\",\"Try editing a user message\",\"Preview markdown and code blocks\"]}</todo_list>\n\n## Markdown preview\nYou can paste snippets here and we'll render headings, lists, and code blocks.\n\n```swift\nstruct HelloWorld: View {\n var body: some View {\n Text(\"Hello, Ensu\")\n }\n}\n```"- ),- ChatMessage(- role: .user,- text: "Share the next steps for our onboarding flow.",- attachments: [- ChatAttachment(name: "brief.pdf", size: 482_000, kind: .document),- ChatAttachment(name: "flow.png", size: 221_000, kind: .image)- ],- branchCount: 3- ),- ChatMessage(- role: .assistant,- text: "Absolutely. I can draft a step-by-step onboarding doc or outline the key user journeys. Let me know which format you prefer.",- tokensPerSecond: 3.2- )- ]+ let session = ChatSession(title: "New chat", lastMessage: "", updatedAt: Date())+ self.sessions = [session]+ self.currentSessionId = session.id+ self.messages = []+ self.messageStore[session.id] = []+ self.branchSelections[session.id] = [:]++ let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first ?? FileManager.default.temporaryDirectory+ self.provider = InferenceRsProvider(modelDir: baseDir.appendingPathComponent("llm", isDirectory: true))}var currentSession: ChatSession? {@@ -158,33 +149,66 @@ final class ChatViewModel: ObservableObject {}func startNewSession() {- streamingTask?.cancel()+ generationTask?.cancel()+ provider.stopGeneration()+ stopRequested = false+ activeGenerationId = nil+ activeGenerationSessionId = nilisGenerating = false+ isDownloading = falsestreamingResponse = ""+ streamingParentId = nil+ downloadToast = nildraftText = ""draftAttachments = []+ editingMessageId = nillet session = ChatSession(title: "New chat", lastMessage: "", updatedAt: Date())sessions.insert(session, at: 0)currentSessionId = session.id- messages = []+ messageStore[session.id] = []+ branchSelections[session.id] = [:]+ rebuildMessages(for: session.id)}func selectSession(_ session: ChatSession) {- streamingTask?.cancel()+ generationTask?.cancel()+ provider.stopGeneration()+ stopRequested = false+ activeGenerationId = nil+ activeGenerationSessionId = nilisGenerating = false+ isDownloading = falsestreamingResponse = ""+ streamingParentId = nil+ downloadToast = nilcurrentSessionId = session.id- messages = [- ChatMessage(role: .assistant, text: "Loading \(session.title)β¦")- ]+ rebuildMessages(for: session.id)}func deleteSession(_ session: ChatSession) {+ if currentSessionId == session.id {+ generationTask?.cancel()+ provider.stopGeneration()+ stopRequested = false+ activeGenerationId = nil+ activeGenerationSessionId = nil+ isGenerating = false+ isDownloading = false+ streamingResponse = ""+ streamingParentId = nil+ downloadToast = nil+ }sessions.removeAll { $0.id == session.id }+ messageStore[session.id] = nil+ branchSelections[session.id] = nilif currentSessionId == session.id {currentSessionId = sessions.first?.id- messages = []+ if let next = currentSessionId {+ rebuildMessages(for: next)+ } else {+ messages = []+ }}}@@ -201,18 +225,54 @@ final class ChatViewModel: ObservableObject {draftAttachments = []}- func addAttachment(kind: ChatAttachment.Kind) {+ func addImageAttachment(data: Data, fileName: String?) {guard !isGenerating && !isDownloading else { return }isProcessingAttachments = true- let name = kind == .image ? "photo.png" : "document.pdf"- let size = Int64.random(in: 120_000...980_000)- let attachment = ChatAttachment(name: name, size: size, kind: kind, isUploading: false)+ Task.detached { [weak self] in+ guard let self else { return }+ do {+ let url = try self.writeAttachment(data: data, fileName: fileName ?? "photo.jpg")+ let attachment = ChatAttachment(+ name: url.lastPathComponent,+ size: Int64(data.count),+ kind: .image,+ url: url,+ isUploading: false+ )+ await MainActor.run {+ self.draftAttachments.append(attachment)+ self.isProcessingAttachments = false+ }+ } catch {+ await MainActor.run { self.isProcessingAttachments = false }+ }+ }+ }- Task { @MainActor in- try? await Task.sleep(nanoseconds: 350_000_000)- draftAttachments.append(attachment)- isProcessingAttachments = false+ func addDocumentAttachment(url: URL) {+ guard !isGenerating && !isDownloading else { return }+ isProcessingAttachments = true++ Task.detached { [weak self] in+ guard let self else { return }+ do {+ let storedUrl = try self.copyAttachment(from: url)+ let size = (try? FileManager.default.attributesOfItem(atPath: storedUrl.path)[.size] as? NSNumber)?.int64Value ?? 0+ let attachment = ChatAttachment(+ name: storedUrl.lastPathComponent,+ size: size,+ kind: .document,+ url: storedUrl,+ isUploading: false+ )+ await MainActor.run {+ self.draftAttachments.append(attachment)+ self.isProcessingAttachments = false+ }+ } catch {+ await MainActor.run { self.isProcessingAttachments = false }+ }}}@@ -222,129 +282,515 @@ final class ChatViewModel: ObservableObject {func sendDraft() {let trimmed = draftText.trimmingCharacters(in: .whitespacesAndNewlines)- guard !trimmed.isEmpty else { return }-- if let editingMessageId, let index = messages.firstIndex(where: { $0.id == editingMessageId }) {- messages[index].text = trimmed- messages[index].attachments = draftAttachments- self.editingMessageId = nil- } else {- messages.append(- ChatMessage(- role: .user,- text: trimmed,- attachments: draftAttachments- )- )- }+ let attachments = draftAttachments+ guard !trimmed.isEmpty || !attachments.isEmpty else { return }++ let sessionId = currentSessionId ?? createSessionForDraft()+ let timestamp = Date()++ let parentId: UUID? = {+ if let editingId = editingMessageId {+ let existing = messageStore[sessionId]?.first { $0.id == editingId }+ return existing?.parentId+ }+ return buildSelectedPath(for: sessionId).last?.id+ }()++ let userNode = MessageNode(+ id: UUID(),+ sessionId: sessionId,+ parentId: parentId,+ role: .user,+ text: trimmed,+ timestamp: timestamp,+ attachments: attachments,+ isInterrupted: false,+ tokensPerSecond: nil+ )++ messageStore[sessionId, default: []].append(userNode)+ updateSelection(for: sessionId, parentId: parentId, childId: userNode.id)- updateCurrentSession(lastMessage: trimmed)draftText = ""draftAttachments = []- startStreamingResponse(for: trimmed)+ editingMessageId = nil++ updateSessionPreview(sessionId: sessionId, preview: trimmed, date: timestamp)+ rebuildMessages(for: sessionId)+ startGeneration(for: userNode)}func stopGenerating() {- streamingTask?.cancel()- streamingTask = nil+ stopRequested = true+ provider.stopGeneration()+ }- guard isGenerating else { return }+ func cancelDownload() {+ generationTask?.cancel()+ provider.cancelDownload()+ stopRequested = true+ activeGenerationId = nil+ activeGenerationSessionId = nilisGenerating = false+ isDownloading = false+ streamingResponse = ""+ streamingParentId = nil+ downloadToast = nil+ }- let responseText = streamingResponse.trimmingCharacters(in: .whitespacesAndNewlines)- if !responseText.isEmpty {- messages.append(- ChatMessage(- role: .assistant,- text: responseText,- isInterrupted: true- )- )+ func retryDownload() {+ let target = modelSettings.currentTarget()+ Task {+ do {+ try await provider.ensureModelReady(target: target) { progress in+ Task { @MainActor in+ self.handleProgress(progress)+ }+ }+ } catch {+ if isCancellation(error) {+ return+ }+ downloadToast = DownloadToastState(phase: .errorDownload, percent: -1, status: error.localizedDescription, offerRetryDownload: true)+ }}- streamingResponse = ""}func retryAssistantResponse(_ message: ChatMessage) {guard message.role == .assistant else { return }- startStreamingResponse(for: message.text)+ guard let sessionId = currentSessionId else { return }+ guard let parent = messageStore[sessionId]?.first(where: { $0.id == message.id })?.parentId,+ let userNode = messageStore[sessionId]?.first(where: { $0.id == parent }) else {+ return+ }+ provider.resetContext()+ startGeneration(for: userNode)}func changeBranch(for message: ChatMessage, delta: Int) {- guard let index = messages.firstIndex(where: { $0.id == message.id }) else { return }- let current = messages[index].branchIndex- let total = messages[index].branchCount- let next = max(1, min(total, current + delta))- messages[index].branchIndex = next- }-- func simulateDownload() {- downloadToast = DownloadToastState(phase: .downloading, percent: 0, status: "Preparingβ¦", offerRetryDownload: false)- isDownloading = true-- Task { @MainActor in- for step in stride(from: 5, through: 100, by: 5) {- try? await Task.sleep(nanoseconds: 150_000_000)- downloadToast?.percent = step- if step < 100 {- downloadToast?.phase = .downloading- downloadToast?.status = "Downloading modelβ¦"- } else {- downloadToast?.phase = .loading- downloadToast?.status = "Loading modelβ¦"+ guard let sessionId = currentSessionId else { return }+ guard let node = messageStore[sessionId]?.first(where: { $0.id == message.id }) else { return }+ let parentKey = node.parentId?.uuidString ?? "__root__"+ let parentId = node.parentId ?? rootId+ let siblings = dedupeSiblings(childrenFor(sessionId: sessionId, parentId: parentId))+ guard !siblings.isEmpty else { return }+ let selectionMap = branchSelections[sessionId] ?? [:]+ let currentId = selectionMap[parentKey] ?? siblings.last?.id+ let currentIndex = siblings.firstIndex { $0.id == currentId } ?? (siblings.count - 1)+ let nextIndex = max(0, min(siblings.count - 1, currentIndex + delta))+ branchSelections[sessionId, default: [:]][parentKey] = siblings[nextIndex].id+ rebuildMessages(for: sessionId)+ }++ private func createSessionForDraft() -> UUID {+ let session = ChatSession(title: "New chat", lastMessage: "", updatedAt: Date())+ sessions.insert(session, at: 0)+ currentSessionId = session.id+ messageStore[session.id] = []+ branchSelections[session.id] = [:]+ return session.id+ }++ private func startGeneration(for userNode: MessageNode) {+ generationTask?.cancel()+ stopRequested = false+ let generationId = UUID()+ activeGenerationId = generationId+ activeGenerationSessionId = userNode.sessionId+ isGenerating = true+ isDownloading = false+ streamingResponse = ""+ streamingParentId = userNode.id+ downloadToast = nil+ rebuildMessages(for: userNode.sessionId)++ let target = modelSettings.currentTarget()++ generationTask = Task {+ do {+ try await provider.ensureModelReady(target: target) { progress in+ Task { @MainActor in+ guard self.activeGenerationId == generationId else { return }+ self.handleProgress(progress)+ }+ }+ } catch {+ if isCancellation(error) {+ if self.activeGenerationId == generationId {+ isGenerating = false+ isDownloading = false+ streamingParentId = nil+ downloadToast = nil+ activeGenerationId = nil+ activeGenerationSessionId = nil+ }+ return}+ if self.activeGenerationId == generationId {+ isGenerating = false+ isDownloading = false+ streamingParentId = nil+ downloadToast = DownloadToastState(phase: .errorDownload, percent: -1, status: error.localizedDescription, offerRetryDownload: true)+ activeGenerationId = nil+ activeGenerationSessionId = nil+ }+ return}- try? await Task.sleep(nanoseconds: 350_000_000)- downloadToast?.phase = .complete- downloadToast?.status = "Model ready"- isDownloading = false- try? await Task.sleep(nanoseconds: 800_000_000)- downloadToast = nil+ let prompt = buildPrompt(text: userNode.text, attachments: userNode.attachments)+ let history = buildHistory(sessionId: userNode.sessionId, promptText: prompt.text, currentMessageId: userNode.id)+ let messages = history + [InferenceMessage(text: prompt.text, isUser: true, hasAttachments: !userNode.attachments.isEmpty)]++ let bufferLock = NSLock()+ var buffer = ""+ var tokenCount = 0++ do {+ let summary = try await provider.generateChat(+ target: target,+ messages: messages,+ imageFiles: prompt.imageFiles,+ temperature: 0.7,+ maxTokens: target.maxTokens ?? 1024+ ) { token in+ bufferLock.lock()+ buffer.append(token)+ tokenCount += self.estimateTokens(token)+ let snapshot = buffer+ bufferLock.unlock()++ Task { @MainActor in+ guard self.activeGenerationId == generationId else { return }+ self.streamingResponse = snapshot+ }+ }++ 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)+ }}}- private func startStreamingResponse(for prompt: String) {- streamingTask?.cancel()- streamingResponse = ""- isGenerating = true+ 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 tokensPerSecond: Double? = {+ guard let totalTimeMs, totalTimeMs > 0 else { return nil }+ return Double(tokenCount) / (Double(totalTimeMs) / 1000.0)+ }()++ let assistant = MessageNode(+ id: UUID(),+ sessionId: parent.sessionId,+ parentId: parent.id,+ role: .assistant,+ text: trimmed,+ timestamp: Date(),+ attachments: [],+ isInterrupted: interrupted,+ tokensPerSecond: tokensPerSecond+ )- let response = "Here is a draft response for: \(prompt).\n\n- Keep the tone warm\n- Highlight the next action\n- Offer a follow-up question"- let words = response.split(separator: " ")+ messageStore[parent.sessionId, default: []].append(assistant)+ updateSelection(for: parent.sessionId, parentId: parent.id, childId: assistant.id)+ updateSessionPreview(sessionId: parent.sessionId, preview: trimmed, date: assistant.timestamp)+ }- streamingTask = Task { @MainActor in- for word in words {- if Task.isCancelled { return }- streamingResponse += (streamingResponse.isEmpty ? "" : " ") + word- try? await Task.sleep(nanoseconds: 120_000_000)- }+ if activeGenerationId == generationId {+ isGenerating = false+ isDownloading = false+ streamingResponse = ""+ streamingParentId = nil+ downloadToast = nil+ activeGenerationId = nil+ activeGenerationSessionId = nil+ }- finishStreamingResponse()+ if currentSessionId == parent.sessionId {+ rebuildMessages(for: parent.sessionId)}}- private func finishStreamingResponse() {- streamingTask = nil- let finalText = streamingResponse.trimmingCharacters(in: .whitespacesAndNewlines)- guard !finalText.isEmpty else {- isGenerating = false+ private func handleProgress(_ progress: InferenceDownloadProgress) {+ if progress.percent == -1 {+ downloadToast = DownloadToastState(phase: .errorDownload, percent: -1, status: progress.status, offerRetryDownload: true)+ isDownloading = falsereturn}- messages.append(- ChatMessage(- role: .assistant,- text: finalText,- tokensPerSecond: Double.random(in: 2.6...3.8)+ let isLoading = progress.status.localizedCaseInsensitiveContains("Loading")+ let isReady = progress.status.localizedCaseInsensitiveContains("Ready")++ if isLoading {+ downloadToast = DownloadToastState(phase: .loading, percent: progress.percent, status: progress.status, offerRetryDownload: false)+ isDownloading = true+ return+ }++ if isReady {+ downloadToast = DownloadToastState(phase: .complete, percent: 100, status: progress.status, offerRetryDownload: false)+ isDownloading = false+ Task { @MainActor in+ try? await Task.sleep(nanoseconds: 1_500_000_000)+ if self.downloadToast?.phase == .complete {+ self.downloadToast = nil+ }+ }+ return+ }++ downloadToast = DownloadToastState(phase: .downloading, percent: progress.percent, status: progress.status, offerRetryDownload: false)+ isDownloading = progress.percent >= 0 && progress.percent < 100+ }++ private func rebuildMessages(for sessionId: UUID) {+ let path = buildSelectedPath(for: sessionId)+ let childrenMap = childrenByParent(sessionId: sessionId)+ let selectionMap = branchSelections[sessionId, default: [:]]++ messages = path.map { node in+ let parentKey = node.parentId?.uuidString ?? "__root__"+ let parentId = node.parentId ?? rootId+ let siblings = dedupeSiblings(childrenMap[parentId] ?? [])+ let selectedId = selectionMap[parentKey]+ let index = siblings.firstIndex { $0.id == selectedId } ?? (siblings.count - 1)++ return ChatMessage(+ id: node.id,+ role: node.role,+ text: node.text,+ timestamp: node.timestamp,+ attachments: node.attachments,+ isInterrupted: node.isInterrupted,+ tokensPerSecond: node.tokensPerSecond,+ branchIndex: max(1, index + 1),+ branchCount: max(1, siblings.count))- )- streamingResponse = ""- isGenerating = false- updateCurrentSession(lastMessage: finalText)+ }+ }++ private func buildSelectedPath(for sessionId: UUID) -> [MessageNode] {+ guard let nodes = messageStore[sessionId], !nodes.isEmpty else { return [] }+ let byId = Dictionary(uniqueKeysWithValues: nodes.map { ($0.id, $0) })+ let childrenMap = childrenByParent(sessionId: sessionId)+ let roots = dedupeSiblings(nodes.filter { node in+ guard let parentId = node.parentId else { return true }+ return byId[parentId] == nil+ })+ guard !roots.isEmpty else { return [] }++ let selectionMap = branchSelections[sessionId, default: [:]]+ var current = selectChild(selectionMap: selectionMap, selectionKey: "__root__", candidates: roots)+ var path: [MessageNode] = []+ var visited = Set<UUID>()++ while let node = current, visited.insert(node.id).inserted {+ path.append(node)+ if node.id == streamingParentId { break }+ let children = dedupeSiblings(childrenMap[node.id] ?? [])+ if children.isEmpty { break }+ current = selectChild(selectionMap: selectionMap, selectionKey: node.id.uuidString, candidates: children)+ }+ return path+ }++ private func selectChild(selectionMap: [String: UUID], selectionKey: String, candidates: [MessageNode]) -> MessageNode? {+ guard !candidates.isEmpty else { return nil }+ if let selectedId = selectionMap[selectionKey],+ let selected = candidates.first(where: { $0.id == selectedId }) {+ return selected+ }+ return candidates.last+ }++ private func childrenByParent(sessionId: UUID) -> [UUID: [MessageNode]] {+ var map: [UUID: [MessageNode]] = [:]+ guard let nodes = messageStore[sessionId] else { return map }+ let byId = Dictionary(uniqueKeysWithValues: nodes.map { ($0.id, $0) })+ for node in nodes {+ let parent = node.parentId.flatMap { byId[$0] != nil ? $0 : nil } ?? rootId+ map[parent, default: []].append(node)+ }+ return map+ }++ private func childrenFor(sessionId: UUID, parentId: UUID) -> [MessageNode] {+ let map = childrenByParent(sessionId: sessionId)+ return map[parentId] ?? []+ }++ private func dedupeSiblings(_ nodes: [MessageNode]) -> [MessageNode] {+ guard nodes.count > 1 else { return nodes.sorted(by: { $0.timestamp < $1.timestamp }) }+ let sorted = nodes.sorted(by: { $0.timestamp < $1.timestamp })+ var result: [MessageNode] = []+ for node in sorted {+ if let last = result.last, isDuplicate(last, node) {+ continue+ }+ result.append(node)+ }+ return result+ }++ private func isDuplicate(_ lhs: MessageNode, _ rhs: MessageNode) -> Bool {+ guard lhs.role == rhs.role else { return false }+ guard lhs.text == rhs.text else { return false }+ guard attachmentSignature(lhs.attachments) == attachmentSignature(rhs.attachments) else { return false }+ return abs(lhs.timestamp.timeIntervalSince(rhs.timestamp)) <= 2+ }++ private func attachmentSignature(_ attachments: [ChatAttachment]) -> [String] {+ attachments.map { "\($0.kind)-\($0.name)" }+ }++ private func updateSelection(for sessionId: UUID, parentId: UUID?, childId: UUID) {+ let key = parentId?.uuidString ?? "__root__"+ branchSelections[sessionId, default: [:]][key] = childId+ }++ private func updateSessionPreview(sessionId: UUID, preview: String, date: Date) {+ sessions = sessions.map { session in+ guard session.id == sessionId else { return session }+ var updated = session+ updated.lastMessage = preview+ updated.updatedAt = date+ return updated+ }+ }++ private func isCancellation(_ error: Error) -> Bool {+ if error is CancellationError { return true }+ return error.localizedDescription.localizedCaseInsensitiveContains("cancel")+ }++ private nonisolated func attachmentsDirectory() throws -> URL {+ let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ ?? FileManager.default.temporaryDirectory+ let dir = base.appendingPathComponent("llm", isDirectory: true)+ .appendingPathComponent("attachments", isDirectory: true)+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)+ return dir+ }++ private nonisolated func writeAttachment(data: Data, fileName: String) throws -> URL {+ let dir = try attachmentsDirectory()+ let safeName = fileName.replacingOccurrences(of: "/", with: "_")+ let destination = dir.appendingPathComponent("\(UUID().uuidString)_\(safeName)")+ try data.write(to: destination, options: .atomic)+ return destination+ }++ private nonisolated func copyAttachment(from url: URL) throws -> URL {+ let dir = try attachmentsDirectory()+ let safeName = url.lastPathComponent.replacingOccurrences(of: "/", with: "_")+ let destination = dir.appendingPathComponent("\(UUID().uuidString)_\(safeName)")++ let needsSecurity = url.startAccessingSecurityScopedResource()+ defer {+ if needsSecurity {+ url.stopAccessingSecurityScopedResource()+ }+ }++ if FileManager.default.fileExists(atPath: destination.path) {+ try FileManager.default.removeItem(at: destination)+ }+ try FileManager.default.copyItem(at: url, to: destination)+ return destination+ }++ private func buildPrompt(text: String, attachments: [ChatAttachment]) -> PromptResult {+ var prompt = text+ let documents = attachments.filter { $0.kind == .document }+ let images = attachments.filter { $0.kind == .image }++ for (index, attachment) in documents.enumerated() {+ prompt += "\n\n----- BEGIN DOCUMENT: Document \(index + 1) -----\n"+ prompt += "Attached document: \(attachment.name)\n"+ prompt += "----- END DOCUMENT: Document \(index + 1) -----"+ }++ let imageFiles = images.compactMap { $0.url }+ if !imageFiles.isEmpty {+ let mediaMarker = "<__media__>"+ prompt += "\n\n[\(imageFiles.count) image attachment"+ if imageFiles.count > 1 { prompt += "s" }+ prompt += " provided]"+ for _ in imageFiles {+ prompt += "\n\(mediaMarker)"+ }+ }++ return PromptResult(text: prompt, imageFiles: imageFiles)+ }++ private func buildHistory(sessionId: UUID, promptText: String, currentMessageId: UUID) -> [InferenceMessage] {+ let path = buildSelectedPath(for: sessionId)+ let history = path.prefix { $0.id != currentMessageId }+ if history.isEmpty { return [] }++ let target = modelSettings.currentTarget()+ let contextSize = target.contextLength ?? 4096+ let maxTokens = target.maxTokens ?? 1024+ var budget = contextSize - maxTokens - 256+ budget -= estimateTokens(promptText)+ if budget <= 0 { return [] }++ var selected: [InferenceMessage] = []+ for node in history.reversed() {+ let text = historyText(node)+ let cost = estimateTokens(text)+ if cost <= budget {+ selected.append(InferenceMessage(text: text, isUser: node.role == .user, hasAttachments: !node.attachments.isEmpty))+ budget -= cost+ } else if selected.isEmpty {+ selected.append(InferenceMessage(text: trimToBudget(text, budget: budget), isUser: node.role == .user, hasAttachments: !node.attachments.isEmpty))+ break+ } else {+ break+ }+ }+ return selected.reversed()+ }++ private func historyText(_ node: MessageNode) -> String {+ var text = node.text+ if node.role == .assistant {+ text = text.replacingOccurrences(of: "<think>[\\s\\S]*?</think>", with: "", options: .regularExpression)+ text = text.replacingOccurrences(of: "<todo_list>[\\s\\S]*?</todo_list>", with: "", options: .regularExpression)+ } else if !node.attachments.isEmpty {+ text += "\n\n[\(node.attachments.count) attachments attached]"+ }+ return text.trimmingCharacters(in: .whitespacesAndNewlines)+ }++ private func trimToBudget(_ text: String, budget: Int) -> String {+ guard budget > 0 else { return "" }+ let maxChars = budget * 4+ if text.count <= maxChars { return text }+ return String(text.suffix(maxChars))+ }++ private func estimateTokens(_ text: String) -> Int {+ max(1, text.count / 4)+ }++ private struct MessageNode: Identifiable {+ let id: UUID+ let sessionId: UUID+ let parentId: UUID?+ let role: ChatMessage.Role+ let text: String+ let timestamp: Date+ let attachments: [ChatAttachment]+ let isInterrupted: Bool+ let tokensPerSecond: Double?}- private func updateCurrentSession(lastMessage: String) {- guard let currentSessionId, let index = sessions.firstIndex(where: { $0.id == currentSessionId }) else { return }- sessions[index].lastMessage = lastMessage- sessions[index].updatedAt = Date()+ private struct PromptResult {+ let text: String+ let imageFiles: [URL]}}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/DownloadToastView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/DownloadToastView.swiftindex ef5e61b6ef..e735864bda 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/DownloadToastView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/DownloadToastView.swift@@ -4,6 +4,7 @@ struct DownloadToastView: View {let state: DownloadToastStatelet onDismiss: () -> Voidlet onRetry: () -> Void+ let onCancel: () -> Voidprivate var isComplete: Bool {state.phase == .complete@@ -66,7 +67,7 @@ struct DownloadToastView: View {Spacer()if !isComplete && !hasError {- Button(action: onDismiss) {+ Button(action: onCancel) {Image(systemName: "xmark").font(.system(size: 12, weight: .semibold))}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swiftindex c1b88283c5..143b9296a9 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift@@ -1,4 +1,7 @@import SwiftUI+import PhotosUI+import UniformTypeIdentifiers+import UIKitstruct MessageInputView: View {@Binding var text: String@@ -10,42 +13,54 @@ struct MessageInputView: View {let onSend: () -> Voidlet onStop: () -> Voidlet onCancelEdit: () -> Void- let onAddAttachment: (ChatAttachment.Kind) -> Void+ let onAddImage: (Data, String?) -> Void+ let onAddDocument: (URL) -> Voidlet onRemoveAttachment: (ChatAttachment) -> Void@StateObject private var keyboard = KeyboardObserver()@FocusState private var isFocused: Bool+ @State private var isImagePickerPresented = false+ @State private var isDocumentPickerPresented = falseprivate var placeholder: String {isDownloading ? "Downloading model... (queue messages)" : "Compose your message..."}private var canSend: Bool {- !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !isGenerating && !isDownloading+ let hasContent = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty+ return hasContent && !isGenerating && !isDownloading}var body: some View {ZStack(alignment: .bottomTrailing) {- VStack(spacing: EnsuSpacing.sm) {+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {if let editingMessage {editBanner(for: editingMessage)}- if !attachments.isEmpty {- FlowLayout(spacing: EnsuSpacing.sm) {- ForEach(attachments) { attachment in- AttachmentChip(- name: attachment.name,- size: attachment.formattedSize,- icon: attachment.iconName,- isUploading: attachment.isUploading- ) {- onRemoveAttachment(attachment)+ let hasAttachmentContent = !attachments.isEmpty || isProcessingAttachments+ let inputVerticalPadding: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : EnsuSpacing.inputVertical+ let textFieldPadding: CGFloat = hasAttachmentContent ? 2 : 8+ let bottomPadding: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : EnsuSpacing.sm+ let inputStackSpacing: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : EnsuSpacing.sm++ VStack(alignment: .leading, spacing: inputStackSpacing) {+ if !attachments.isEmpty {+ let maxAttachmentHeight = CGFloat(3) * 40 + CGFloat(2) * EnsuSpacing.sm+ let shouldScroll = attachments.count > 4++ Group {+ if shouldScroll {+ ScrollView(.vertical, showsIndicators: false) {+ attachmentFlowLayout+ }+ .frame(maxHeight: maxAttachmentHeight)+ } else {+ attachmentFlowLayout}}+ .padding(.horizontal, EnsuSpacing.pageHorizontal)}- .padding(.horizontal, EnsuSpacing.pageHorizontal)- }if isProcessingAttachments {HStack(spacing: EnsuSpacing.sm) {@@ -67,7 +82,7 @@ struct MessageInputView: View {.foregroundStyle(EnsuColor.textPrimary).platformTextFieldStyle().platformTextInputAutocapitalization(.sentences)- .padding(.vertical, 8)+ .padding(.vertical, textFieldPadding).onSubmit {if canSend {onSend()@@ -77,10 +92,10 @@ struct MessageInputView: View {if editingMessage == nil {Menu {Button("Image") {- onAddAttachment(.image)+ isImagePickerPresented = true}Button("Document") {- onAddAttachment(.document)+ isDocumentPickerPresented = true}} label: {Image(systemName: "paperclip")@@ -95,6 +110,28 @@ struct MessageInputView: View {.buttonStyle(.plain).frame(width: 32, height: 32, alignment: .center)#endif+ .sheet(isPresented: $isImagePickerPresented) {+ ImagePicker(+ onPick: { data, name in+ onAddImage(data, name)+ isImagePickerPresented = false+ },+ onCancel: {+ isImagePickerPresented = false+ }+ )+ }+ .sheet(isPresented: $isDocumentPickerPresented) {+ DocumentPicker(+ onPick: { url in+ onAddDocument(url)+ isDocumentPickerPresented = false+ },+ onCancel: {+ isDocumentPickerPresented = false+ }+ )+ }}Button {@@ -112,14 +149,17 @@ struct MessageInputView: View {.disabled(isDownloading || (!canSend && !isGenerating))}.padding(.horizontal, EnsuSpacing.inputHorizontal)- .padding(.vertical, EnsuSpacing.inputVertical)+ .padding(.vertical, inputVerticalPadding)+ .frame(maxWidth: .infinity).background(EnsuColor.fillFaint).clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous)).padding(.horizontal, EnsuSpacing.pageHorizontal)- .padding(.bottom, EnsuSpacing.sm)+ .padding(.bottom, bottomPadding)}+ .frame(maxWidth: .infinity, alignment: .leading)+ }- if keyboard.isVisible {+ if keyboard.isVisible {Button {isFocused = falsehideKeyboard()@@ -146,6 +186,22 @@ struct MessageInputView: View {#endif}+ private var attachmentFlowLayout: some View {+ FlowLayout(spacing: EnsuSpacing.sm) {+ ForEach(attachments) { attachment in+ AttachmentChip(+ name: attachment.name,+ size: attachment.formattedSize,+ icon: attachment.iconName,+ isUploading: attachment.isUploading+ ) {+ onRemoveAttachment(attachment)+ }+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+private var sendIcon: String {if isGenerating {return "stop.fill"@@ -205,3 +261,91 @@ struct MessageInputView: View {.padding(.horizontal, EnsuSpacing.pageHorizontal)}}++private struct ImagePicker: UIViewControllerRepresentable {+ let onPick: (Data, String?) -> Void+ let onCancel: () -> Void++ func makeCoordinator() -> Coordinator {+ Coordinator(onPick: onPick, onCancel: onCancel)+ }++ func makeUIViewController(context: Context) -> PHPickerViewController {+ var config = PHPickerConfiguration(photoLibrary: .shared())+ config.filter = .images+ config.selectionLimit = 1+ let picker = PHPickerViewController(configuration: config)+ picker.delegate = context.coordinator+ return picker+ }++ func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {}++ final class Coordinator: NSObject, PHPickerViewControllerDelegate {+ private let onPick: (Data, String?) -> Void+ private let onCancel: () -> Void++ init(onPick: @escaping (Data, String?) -> Void, onCancel: @escaping () -> Void) {+ self.onPick = onPick+ self.onCancel = onCancel+ }++ func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {+ guard let result = results.first else {+ onCancel()+ return+ }+ let provider = result.itemProvider+ let typeIdentifier = UTType.image.identifier+ provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, _ in+ DispatchQueue.main.async {+ guard let data else {+ self.onCancel()+ return+ }+ self.onPick(data, provider.suggestedName)+ }+ }+ }+ }+}++private struct DocumentPicker: UIViewControllerRepresentable {+ let onPick: (URL) -> Void+ let onCancel: () -> Void++ func makeCoordinator() -> Coordinator {+ Coordinator(onPick: onPick, onCancel: onCancel)+ }++ func makeUIViewController(context: Context) -> UIDocumentPickerViewController {+ let picker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.data], asCopy: true)+ picker.delegate = context.coordinator+ picker.allowsMultipleSelection = false+ return picker+ }++ func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {}++ final class Coordinator: NSObject, UIDocumentPickerDelegate {+ private let onPick: (URL) -> Void+ private let onCancel: () -> Void++ init(onPick: @escaping (URL) -> Void, onCancel: @escaping () -> Void) {+ self.onPick = onPick+ self.onCancel = onCancel+ }++ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {+ guard let url = urls.first else {+ onCancel()+ return+ }+ onPick(url)+ }++ func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {+ onCancel()+ }+ }+}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swiftindex 6510133867..38d82f3b2a 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift@@ -3,6 +3,7 @@ import SwiftUIstruct MessageListView: View {let messages: [ChatMessage]let streamingResponse: String+ let streamingParentId: UUID?let isGenerating: Boollet onEdit: (ChatMessage) -> Voidlet onCopy: (ChatMessage) -> Void@@ -11,6 +12,7 @@ struct MessageListView: View {let onBranchChange: (ChatMessage, Int) -> Void@State private var isAtBottom = true+ @State private var autoScrollEnabled = truevar body: some View {GeometryReader { proxy in@@ -43,9 +45,14 @@ struct MessageListView: View {).id(message.id)}++ if isGenerating, streamingParentId == message.id {+ StreamingBubbleView(text: streamingResponse)+ .id("streaming")+ }}- if isGenerating {+ if isGenerating, streamingParentId == nil {StreamingBubbleView(text: streamingResponse).id("streaming")}@@ -64,6 +71,11 @@ struct MessageListView: View {.padding(.vertical, EnsuSpacing.lg)}.coordinateSpace(name: "scroll")+ .simultaneousGesture(+ DragGesture().onChanged { _ in+ autoScrollEnabled = false+ }+ ).onPreferenceChange(BottomOffsetKey.self) { value inlet threshold: CGFloat = 24isAtBottom = value < proxy.size.height + threshold@@ -74,18 +86,21 @@ struct MessageListView: View {.onChange(of: streamingResponse) { _ inscrollToBottom(scrollProxy)}- .onChange(of: isGenerating) { _ in- scrollToBottom(scrollProxy)+ .onChange(of: isGenerating) { newValue in+ if newValue {+ autoScrollEnabled = true+ scrollToBottom(scrollProxy, force: true)+ }}.onAppear {- scrollToBottom(scrollProxy)+ scrollToBottom(scrollProxy, force: true)}}}}- private func scrollToBottom(_ proxy: ScrollViewProxy) {- guard isAtBottom else { return }+ private func scrollToBottom(_ proxy: ScrollViewProxy, force: Bool = false) {+ guard force || (autoScrollEnabled && isAtBottom) else { return }withAnimation(.easeOut(duration: 0.2)) {proxy.scrollTo("bottom", anchor: .bottom)}@@ -188,7 +203,6 @@ private struct AssistantMessageBubbleView: View {HStack(spacing: EnsuSpacing.sm) {TimestampView(date: message.timestamp)- Spacer()if message.branchCount > 1 {BranchSwitcherView(currentIndex: message.branchIndex,@@ -213,7 +227,7 @@ private struct StreamingBubbleView: View {var body: some View {HStack(alignment: .bottom) {VStack(alignment: .leading, spacing: EnsuSpacing.sm) {- if text.isEmpty {+ if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {LoadingDotsView()} else {HStack(alignment: .bottom, spacing: 4) {diff --git a/mobile/native/darwin/Apps/ensu/ensu/Components/EnsuComponents.swift b/mobile/native/darwin/Apps/ensu/ensu/Components/EnsuComponents.swiftindex 0fc78a1ce3..f695f10859 100644--- a/mobile/native/darwin/Apps/ensu/ensu/Components/EnsuComponents.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/Components/EnsuComponents.swift@@ -114,7 +114,9 @@ struct AttachmentChip: View {Text(size).font(EnsuTypography.mini).foregroundStyle(EnsuColor.textMuted)+ .lineLimit(1)}+ .frame(maxWidth: 180, alignment: .leading)if isUploading {ProgressView()diff --git a/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift b/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swiftindex fb6318aaf1..1c8842c04d 100644--- a/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift+++ b/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift@@ -3,7 +3,7 @@ import SwiftUIstruct ModelSettingsView: View {@Environment(\.dismiss) private var dismiss- @State private var useCustomModel = false+ @ObservedObject private var settings = ModelSettingsStore.shared@State private var modelUrl: String = ""@State private var mmprojUrl: String = ""@State private var contextLength: String = ""@@ -19,24 +19,24 @@ struct ModelSettingsView: View {SuggestedModel(name: "Qwen3-VL 2B Instruct (Q4_K_M)",details: "Multimodal β’ requires mmproj",- url: "https://huggingface.co/.../qwen3-vl-2b.Q4_K_M.gguf",- mmproj: "https://huggingface.co/.../mmproj-qwen3-vl-2b.gguf"+ url: "https://huggingface.co/LiquidAI/Qwen3-VL-2B-Instruct-GGUF/resolve/main/Qwen3-VL-2B-Instruct-Q4_K_M.gguf",+ mmproj: "https://huggingface.co/LiquidAI/Qwen3-VL-2B-Instruct-GGUF/resolve/main/mmproj-qwen3-vl-2b.gguf"),SuggestedModel(name: "LFM 2.5 1.2B Instruct (Q4_0)",details: "Text only",- url: "https://huggingface.co/.../lfm-2.5-1.2b.Q4_0.gguf"+ url: "https://huggingface.co/LiquidAI/LFM2.5-1.2B-GGUF/resolve/main/LFM2.5-1.2B-Q4_0.gguf"),SuggestedModel(name: "LFM 2.5 VL 1.6B (Q4_0)",details: "Multimodal β’ requires mmproj",- url: "https://huggingface.co/.../lfm-2.5-vl-1.6b.Q4_0.gguf",- mmproj: "https://huggingface.co/.../mmproj-lfm-2.5-vl.gguf"+ url: "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf",+ mmproj: "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"),SuggestedModel(name: "Llama 3.2 1B Instruct (Q4_K_M)",details: "Text only",- url: "https://huggingface.co/.../llama-3.2-1b.Q4_K_M.gguf"+ url: "https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf")]@@ -56,6 +56,12 @@ struct ModelSettingsView: View {content#endif}+ .onAppear {+ modelUrl = settings.modelUrl+ mmprojUrl = settings.mmprojUrl+ contextLength = settings.contextLength+ maxTokens = settings.maxTokens+ }#if os(macOS).safeAreaInset(edge: .top) {MacSheetHeader(@@ -86,12 +92,24 @@ struct ModelSettingsView: View {sectionHeader("Selected model")VStack(alignment: .leading, spacing: EnsuSpacing.xs) {- Text("Default model")- .font(EnsuTypography.body)- .foregroundStyle(EnsuColor.textPrimary)- Text("Loaded")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.success)+ if settings.useCustomModel && !settings.modelUrl.isEmpty {+ Text("Custom model")+ .font(EnsuTypography.body)+ .foregroundStyle(EnsuColor.textPrimary)+ Text(settings.modelUrl)+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)+ } else {+ Text("Default model")+ .font(EnsuTypography.body)+ .foregroundStyle(EnsuColor.textPrimary)+ Text(ModelSettingsStore.defaultModelName)+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)+ Text(ModelSettingsStore.defaultModelUrl)+ .font(EnsuTypography.mini)+ .foregroundStyle(EnsuColor.textMuted)+ }}Divider().background(EnsuColor.border)@@ -248,14 +266,19 @@ struct ModelSettingsView: View {guard validate() else { return }isSaving = true- DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {+ settings.saveCustomModel(+ url: modelUrl,+ mmproj: mmprojUrl,+ contextLength: contextLength,+ maxTokens: maxTokens+ )isSaving = false- useCustomModel = true}}private func resetTapped() {- useCustomModel = false+ settings.resetToDefault()modelUrl = ""mmprojUrl = ""contextLength = ""diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swiftnew file mode 100644index 0000000000..09ac410ff6--- /dev/null+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift@@ -0,0 +1,389 @@+import Foundation+import CryptoKit+import InferenceRS++final class InferenceRsProvider {+ private let modelDir: URL+ private var modelHandle: ModelHandle?+ private var contextHandle: ContextHandle?+ private var currentModelId: String?+ private var backendInitialized = false+ private var currentJobId: Int64?+ private var downloadCancelled = false+ private var currentDownloadTask: URLSessionTask?++ init(modelDir: URL) {+ self.modelDir = modelDir+ try? FileManager.default.createDirectory(at: modelDir, withIntermediateDirectories: true, attributes: nil)+ }++ func ensureModelReady(+ target: InferenceModelTarget,+ onProgress: @escaping (InferenceDownloadProgress) -> Void+ ) async throws {+ if currentModelId == target.id, modelHandle != nil, contextHandle != nil {+ return+ }++ unloadModel()++ if !backendInitialized {+ try initBackend()+ backendInitialized = true+ }++ let modelPath = modelPathFor(target: target)+ let mmprojPath = mmprojPathFor(target: target)++ var downloads: [DownloadTarget] = []+ if !FileManager.default.fileExists(atPath: modelPath.path) {+ downloads.append(DownloadTarget(label: "Model", url: target.url, destination: modelPath))+ }+ if let mmprojUrl = target.mmprojUrl, let mmprojPath,+ !FileManager.default.fileExists(atPath: mmprojPath.path) {+ downloads.append(DownloadTarget(label: "Mmproj", url: mmprojUrl, destination: mmprojPath))+ }++ if !downloads.isEmpty {+ downloadCancelled = false+ onProgress(InferenceDownloadProgress(percent: 0, status: "Starting download..."))+ var lengths: [Int64?] = []+ for download in downloads {+ lengths.append(await fetchContentLength(for: download.url))+ }++ let totalBytes = lengths.compactMap { $0 }.reduce(0, +)+ let hasTotal = lengths.allSatisfy { $0 != nil } && totalBytes > 0+ var downloadedSoFar: Int64 = 0++ for (index, download) in downloads.enumerated() {+ let fileTotal = lengths[index]+ try await downloadFile(from: download.url, to: download.destination) { [self] downloaded, total in+ let overallDownloaded = downloadedSoFar + downloaded+ let percent: Int+ if hasTotal {+ percent = Int((Double(overallDownloaded) / Double(totalBytes)) * 100.0)+ } else {+ let step = 100.0 / Double(downloads.count)+ let filePercent = total.map { Double(downloaded) / Double($0) } ?? 0+ percent = Int((Double(index) * step) + (filePercent * step))+ }++ let status = if hasTotal {+ "Downloading... \(self.formatBytes(overallDownloaded)) / \(self.formatBytes(totalBytes))"+ } else {+ "Downloading \(download.label.lowercased())... \(self.formatBytes(downloaded))"+ }++ onProgress(InferenceDownloadProgress(percent: min(99, max(0, percent)), status: status))+ }+ let finishedBytes = fileTotal ?? fileSize(download.destination)+ downloadedSoFar += finishedBytes+ }+ }++ onProgress(InferenceDownloadProgress(percent: 100, status: "Loading model..."))+ try loadModelHandle(target: target, modelPath: modelPath)+ onProgress(InferenceDownloadProgress(percent: 100, status: "Ready"))+ }++ func generateChat(+ target: InferenceModelTarget,+ messages: [InferenceMessage],+ imageFiles: [URL],+ temperature: Float,+ maxTokens: Int,+ onToken: @escaping (String) -> Void+ ) async throws -> InferenceGenerationSummary {+ guard let context = contextHandle else {+ throw NSError(domain: "InferenceRsProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "Model not loaded"])+ }++ let nativeMessages = messages.map {+ InferenceRS.ChatMessage(role: $0.isUser ? "user" : "assistant", content: $0.text)+ }++ let mmprojPath = imageFiles.isEmpty ? nil : mmprojPathFor(target: target)?.path++ let request = GenerateChatRequest(+ messages: nativeMessages,+ templateOverride: nil,+ addAssistant: true,+ imagePaths: imageFiles.map { $0.path },+ mmprojPath: mmprojPath,+ mediaMarker: nil,+ maxTokens: Int32(maxTokens),+ temperature: temperature,+ topP: nil,+ topK: nil,+ repeatPenalty: nil,+ frequencyPenalty: nil,+ presencePenalty: nil,+ seed: nil,+ stopSequences: nil,+ grammar: nil+ )++ var error: Error?+ let lock = NSLock()++ let sink = CallbackSink { event in+ switch event {+ case let .text(jobId, text, _):+ self.currentJobId = jobId+ onToken(text)+ case .done:+ break+ case let .error(_, message):+ lock.lock()+ error = NSError(domain: "InferenceRsProvider", code: -2, userInfo: [NSLocalizedDescriptionKey: message])+ lock.unlock()+ }+ }++ let summary: GenerateSummary = try await withCheckedThrowingContinuation { continuation in+ Task.detached {+ do {+ let summary = try generateChatStream(context: context, request: request, callback: sink)+ lock.lock()+ let localError = error+ lock.unlock()+ if let localError {+ continuation.resume(throwing: localError)+ } else {+ continuation.resume(returning: summary)+ }+ } catch {+ continuation.resume(throwing: error)+ }+ }+ }++ return InferenceGenerationSummary(+ jobId: summary.jobId,+ generatedTokens: Int(summary.generatedTokens ?? 0),+ totalTimeMs: summary.totalTimeMs+ )+ }++ func stopGeneration() {+ if let jobId = currentJobId {+ cancel(jobId: jobId)+ }+ }++ func resetContext() {+ guard let model = modelHandle else { return }+ let contextParams = ContextParams(contextSize: nil, nThreads: nil, nBatch: nil)+ contextHandle = nil+ contextHandle = try? createContext(model: model, params: contextParams)+ }++ func cancelDownload() {+ downloadCancelled = true+ currentDownloadTask?.cancel()+ }++ private func unloadModel() {+ contextHandle = nil+ modelHandle = nil+ currentModelId = nil+ }++ private func loadModelHandle(target: InferenceModelTarget, modelPath: URL) throws {+ let params = ModelLoadParams(modelPath: modelPath.path, nGpuLayers: 0, useMmap: true, useMlock: false)+ let model = try InferenceRS.loadModel(params: params)+ modelHandle = model++ let desiredContext = target.contextLength ?? 4096+ let candidates = Array(Set([desiredContext, 4096, 2048, 1024])).filter { $0 > 0 }+ let threadCount = max(1, ProcessInfo.processInfo.activeProcessorCount - 1)++ for contextSize in candidates {+ do {+ let contextParams = ContextParams(contextSize: Int32(contextSize), nThreads: Int32(threadCount), nBatch: Int32(512))+ contextHandle = try createContext(model: model, params: contextParams)+ currentModelId = target.id+ return+ } catch {+ continue+ }+ }+ throw NSError(domain: "InferenceRsProvider", code: -5, userInfo: [NSLocalizedDescriptionKey: "Failed to create context"])+ }++ private func downloadFile(+ from urlString: String,+ to destination: URL,+ onProgress: @escaping (Int64, Int64?) -> Void+ ) async throws {+ guard let url = URL(string: urlString) else {+ throw NSError(domain: "InferenceRsProvider", code: -7, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])+ }++ var request = URLRequest(url: url)+ request.httpMethod = "GET"++ let (bytes, response) = try await URLSession.shared.bytes(for: request)+ currentDownloadTask = bytes.task++ if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {+ throw NSError(+ domain: "InferenceRsProvider",+ code: -9,+ userInfo: [NSLocalizedDescriptionKey: "Download failed (HTTP \(http.statusCode))"]+ )+ }++ var totalBytes: Int64? = response.expectedContentLength > 0 ? response.expectedContentLength : nil+ if totalBytes == nil, let http = response as? HTTPURLResponse,+ let lengthHeader = http.value(forHTTPHeaderField: "Content-Length"),+ let length = Int64(lengthHeader) {+ totalBytes = length+ }++ try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)+ let tmp = destination.appendingPathExtension("tmp")+ if FileManager.default.fileExists(atPath: tmp.path) {+ try FileManager.default.removeItem(at: tmp)+ }+ FileManager.default.createFile(atPath: tmp.path, contents: nil)+ let handle = try FileHandle(forWritingTo: tmp)++ var buffer = [UInt8]()+ buffer.reserveCapacity(64 * 1024)+ var downloaded: Int64 = 0+ var lastProgressUpdate: Int64 = 0+ let updateThreshold: Int64 = 512 * 1024++ defer {+ currentDownloadTask = nil+ }++ for try await byte in bytes {+ if downloadCancelled {+ try? handle.close()+ try? FileManager.default.removeItem(at: tmp)+ throw CancellationError()+ }++ buffer.append(byte)+ downloaded += 1++ if buffer.count >= 64 * 1024 {+ handle.write(Data(buffer))+ buffer.removeAll(keepingCapacity: true)+ }++ if downloaded - lastProgressUpdate >= updateThreshold {+ lastProgressUpdate = downloaded+ onProgress(downloaded, totalBytes)+ }+ }++ if !buffer.isEmpty {+ handle.write(Data(buffer))+ }+ try handle.close()+ onProgress(downloaded, totalBytes)++ if !looksLikeGguf(file: tmp) {+ try? FileManager.default.removeItem(at: tmp)+ throw NSError(domain: "InferenceRsProvider", code: -6, userInfo: [NSLocalizedDescriptionKey: "Downloaded file is not GGUF"])+ }++ if FileManager.default.fileExists(atPath: destination.path) {+ try FileManager.default.removeItem(at: destination)+ }+ try FileManager.default.moveItem(at: tmp, to: destination)+ }++ private func fetchContentLength(for urlString: String) async -> Int64? {+ guard let url = URL(string: urlString) else { return nil }+ var request = URLRequest(url: url)+ request.httpMethod = "HEAD"++ do {+ let (_, response) = try await URLSession.shared.data(for: request)+ if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {+ return nil+ }+ if response.expectedContentLength > 0 {+ return response.expectedContentLength+ }+ if let http = response as? HTTPURLResponse,+ let header = http.value(forHTTPHeaderField: "Content-Length"),+ let length = Int64(header) {+ return length+ }+ } catch {+ return nil+ }+ return nil+ }++ private func fileSize(_ url: URL) -> Int64 {+ let attrs = try? FileManager.default.attributesOfItem(atPath: url.path)+ return (attrs?[.size] as? NSNumber)?.int64Value ?? 0+ }++ private struct DownloadTarget {+ let label: String+ let url: String+ let destination: URL+ }++ private func looksLikeGguf(file: URL) -> Bool {+ guard let handle = try? FileHandle(forReadingFrom: file) else { return false }+ let data = handle.readData(ofLength: 4)+ try? handle.close()+ guard data.count == 4 else { return false }+ let header = String(decoding: data, as: UTF8.self)+ return header == "GGUF"+ }++ private func formatBytes(_ bytes: Int64) -> String {+ let formatter = ByteCountFormatter()+ formatter.countStyle = .file+ return formatter.string(fromByteCount: bytes)+ }++ private func modelPathFor(target: InferenceModelTarget) -> URL {+ let base = modelDir.appendingPathComponent("models", isDirectory: true)+ let filename = URL(string: target.url)?.lastPathComponent ?? "model.gguf"+ if target.id.hasPrefix("custom:") {+ let custom = base.appendingPathComponent("custom", isDirectory: true)+ return custom.appendingPathComponent("\(hash(target.url))_\(filename)")+ }+ return base.appendingPathComponent(filename)+ }++ private func mmprojPathFor(target: InferenceModelTarget) -> URL? {+ guard let url = target.mmprojUrl else { return nil }+ let base = modelDir.appendingPathComponent("models", isDirectory: true)+ let filename = URL(string: url)?.lastPathComponent ?? "mmproj.gguf"+ if target.id.hasPrefix("custom:") {+ let custom = base.appendingPathComponent("custom", isDirectory: true)+ return custom.appendingPathComponent("\(hash(url))_\(filename)")+ }+ return base.appendingPathComponent(filename)+ }++ private func hash(_ value: String) -> String {+ let data = Data(value.utf8)+ let hashed = SHA256.hash(data: data)+ return hashed.map { String(format: "%02x", $0) }.joined()+ }+}++private final class CallbackSink: GenerateEventCallback, @unchecked Sendable {+ private let handler: (GenerateEvent) -> Void++ init(handler: @escaping (GenerateEvent) -> Void) {+ self.handler = handler+ }++ func onEvent(event: GenerateEvent) {+ handler(event)+ }+}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceTypes.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceTypes.swiftnew file mode 100644index 0000000000..36a3ff5381--- /dev/null+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceTypes.swift@@ -0,0 +1,26 @@+import Foundation++struct InferenceModelTarget: Equatable {+ let id: String+ let url: String+ let mmprojUrl: String?+ let contextLength: Int?+ let maxTokens: Int?+}++struct InferenceDownloadProgress: Equatable {+ let percent: Int+ let status: String+}++struct InferenceMessage {+ let text: String+ let isUser: Bool+ let hasAttachments: Bool+}++struct InferenceGenerationSummary {+ let jobId: Int64+ let generatedTokens: Int+ let totalTimeMs: Int64?+}diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swiftnew file mode 100644index 0000000000..e25aa5ffc6--- /dev/null+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift@@ -0,0 +1,84 @@+import Foundation++@MainActor+final class ModelSettingsStore: ObservableObject {+ static let shared = ModelSettingsStore()++ @Published var useCustomModel: Bool {+ didSet { persist() }+ }+ @Published var modelUrl: String {+ didSet { persist() }+ }+ @Published var mmprojUrl: String {+ didSet { persist() }+ }+ @Published var contextLength: String {+ didSet { persist() }+ }+ @Published var maxTokens: String {+ didSet { persist() }+ }++ private let defaults = UserDefaults.standard++ private init() {+ self.useCustomModel = defaults.bool(forKey: Keys.useCustomModel)+ self.modelUrl = defaults.string(forKey: Keys.modelUrl) ?? ""+ self.mmprojUrl = defaults.string(forKey: Keys.mmprojUrl) ?? ""+ self.contextLength = defaults.string(forKey: Keys.contextLength) ?? ""+ self.maxTokens = defaults.string(forKey: Keys.maxTokens) ?? ""+ }++ func saveCustomModel(url: String, mmproj: String, contextLength: String, maxTokens: String) {+ useCustomModel = true+ modelUrl = url+ mmprojUrl = mmproj+ self.contextLength = contextLength+ self.maxTokens = maxTokens+ }++ func resetToDefault() {+ useCustomModel = false+ modelUrl = ""+ mmprojUrl = ""+ contextLength = ""+ maxTokens = ""+ }++ func currentTarget() -> InferenceModelTarget {+ let useCustom = useCustomModel && !modelUrl.isEmpty+ let url = useCustom ? modelUrl : Defaults.modelUrl+ let mmproj = useCustom ? (mmprojUrl.isEmpty ? nil : mmprojUrl) : Defaults.mmprojUrl+ let context = Int(contextLength)+ let maxOutput = Int(maxTokens)+ let id = useCustom ? "custom:\(url)" : "default"+ return InferenceModelTarget(id: id, url: url, mmprojUrl: mmproj, contextLength: context, maxTokens: maxOutput)+ }++ static var defaultModelName: String { Defaults.modelName }+ static var defaultModelUrl: String { Defaults.modelUrl }+ static var defaultMmprojUrl: String? { Defaults.mmprojUrl }++ private func persist() {+ defaults.set(useCustomModel, forKey: Keys.useCustomModel)+ defaults.set(modelUrl, forKey: Keys.modelUrl)+ defaults.set(mmprojUrl, forKey: Keys.mmprojUrl)+ defaults.set(contextLength, forKey: Keys.contextLength)+ defaults.set(maxTokens, forKey: Keys.maxTokens)+ }++ private enum Keys {+ static let useCustomModel = "ensu.model.use_custom"+ static let modelUrl = "ensu.model.url"+ static let mmprojUrl = "ensu.model.mmproj"+ static let contextLength = "ensu.model.context"+ static let maxTokens = "ensu.model.max_tokens"+ }++ private enum Defaults {+ static let modelName = "LFM 2.5 VL 1.6B (Q4_0)"+ static let modelUrl = "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf"+ static let mmprojUrl = "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"+ }+}diff --git a/mobile/native/darwin/Packages/Rust/Package.swift b/mobile/native/darwin/Packages/Rust/Package.swiftnew file mode 100644index 0000000000..6a845d59ad--- /dev/null+++ b/mobile/native/darwin/Packages/Rust/Package.swift@@ -0,0 +1,34 @@+// swift-tools-version: 5.9+import PackageDescription++let package = Package(+ name: "InferenceRS",+ platforms: [+ .iOS(.v13),+ .macOS(.v10_15),+ ],+ products: [+ .library(name: "InferenceRS", targets: ["InferenceRS"]),+ ],+ targets: [+ .binaryTarget(+ name: "InferenceRSFFI",+ path: "InferenceRSFFI.xcframework"+ ),+ .target(+ name: "InferenceRS",+ dependencies: ["InferenceRSFFI"],+ path: "Sources/InferenceRS",+ linkerSettings: [+ .linkedFramework("Accelerate"),+ .linkedFramework("Metal"),+ .linkedFramework("MetalKit")+ ]+ ),+ .testTarget(+ name: "InferenceRSTests",+ dependencies: ["InferenceRS"],+ path: "Tests/InferenceRSTests"+ ),+ ]+)diff --git a/mobile/native/darwin/Packages/Rust/README.md b/mobile/native/darwin/Packages/Rust/README.mdnew file mode 100644index 0000000000..175e106eed--- /dev/null+++ b/mobile/native/darwin/Packages/Rust/README.md@@ -0,0 +1,99 @@+# InferenceRS (Swift)++Swift bindings generated via UniFFI for the Rust core in `../rust`.++## Generate bindings++From the repo root:++```bash+cd swift+./tool/generate_bindings.sh+```++This writes the Swift sources plus the UniFFI header/modulemap into+`swift/Sources/InferenceRS`.++## Build the xcframework++From the repo root:++```bash+cd swift+./tool/build_xcframework.sh+```++This produces `swift/InferenceRSFFI.xcframework`, which the Swift package+references as a binary target.++## Use in an app (SwiftPM)++Add the package to your app and import `InferenceRS`:++```swift+import InferenceRS++try initBackend()+let model = try loadModel(+ params: ModelLoadParams(modelPath: "/path/to/model.gguf", nGpuLayers: nil, useMmap: nil, useMlock: nil)+)+let context = try createContext(+ model: model,+ params: ContextParams(contextSize: 4096, nThreads: 4, nBatch: 128)+)++let request = GenerateChatRequest(+ messages: [+ ChatMessage(role: "system", content: "You are a helpful assistant."),+ ChatMessage(role: "user", content: "Say hello")+ ],+ templateOverride: nil,+ addAssistant: true,+ imagePaths: nil,+ mmprojPath: nil,+ mediaMarker: nil,+ maxTokens: 64,+ temperature: 0.7,+ topP: 0.9,+ topK: nil,+ repeatPenalty: nil,+ frequencyPenalty: nil,+ presencePenalty: nil,+ seed: nil,+ stopSequences: nil,+ grammar: nil+)++final class StreamHandler: GenerateEventCallback {+ func onEvent(event: GenerateEvent) {+ switch event {+ case let .text(_, text, _):+ print(text)+ case let .done(summary):+ print("Done: \(summary.generatedTokens ?? 0) tokens")+ case let .error(_, message):+ print("Error: \(message)")+ }+ }+}++let summary = try generateChatStream(+ context: context,+ request: request,+ callback: StreamHandler()+)+print("Summary job id: \(summary.jobId)")+```++Notes:+- Generation runs synchronously; invoke on a background queue if needed.+- Callback interfaces are class-only (`AnyObject`) in Swift.++## Run tests++Build the xcframework first, then set a model path to enable the integration test:++```bash+./tool/build_xcframework.sh+INFERENCE_RS_TEST_MODEL=/path/to/model.gguf swift test+```diff --git a/mobile/native/darwin/Packages/Rust/Tests/InferenceRSTests/InferenceRSTests.swift b/mobile/native/darwin/Packages/Rust/Tests/InferenceRSTests/InferenceRSTests.swiftnew file mode 100644index 0000000000..7c9ffd61d9--- /dev/null+++ b/mobile/native/darwin/Packages/Rust/Tests/InferenceRSTests/InferenceRSTests.swift@@ -0,0 +1,149 @@+import XCTest+import InferenceRS++final class GenerateEventCollector: GenerateEventCallback {+ private(set) var events: [GenerateEvent] = []++ func onEvent(event: GenerateEvent) {+ events.append(event)+ }++ var hasDone: Bool {+ events.contains { event in+ if case .done = event { return true }+ return false+ }+ }++ var lastError: String? {+ events.compactMap { event in+ if case let .error(_, message) = event { return message }+ return nil+ }.last+ }++ var textOutput: String {+ events.compactMap { event in+ if case let .text(_, text, _) = event { return text }+ return nil+ }.joined()+ }+}++final class InferenceRSTests: XCTestCase {+ func testInitBackend() throws {+ try initBackend()+ }++ func testGenerateChatStreamWhenModelProvided() throws {+ let env = ProcessInfo.processInfo.environment+ guard let modelPath = env["INFERENCE_RS_TEST_MODEL"] ?? env["INFERENCE_RS_TEST_MODEL_PATH"] else {+ throw XCTSkip("Set INFERENCE_RS_TEST_MODEL to run the integration test.")+ }++ try initBackend()++ let model = try loadModel(+ params: ModelLoadParams(+ modelPath: modelPath,+ nGpuLayers: nil,+ useMmap: nil,+ useMlock: nil+ )+ )++ let context = try createContext(+ model: model,+ params: ContextParams(contextSize: 2048, nThreads: nil, nBatch: nil)+ )++ let request = GenerateChatRequest(+ messages: [+ ChatMessage(role: "system", content: "You are a helpful assistant."),+ ChatMessage(role: "user", content: "Say hello in one short sentence.")+ ],+ templateOverride: nil,+ addAssistant: true,+ imagePaths: nil,+ mmprojPath: nil,+ mediaMarker: nil,+ maxTokens: 24,+ temperature: 0.7,+ topP: 0.9,+ topK: nil,+ repeatPenalty: nil,+ frequencyPenalty: nil,+ presencePenalty: nil,+ seed: 42,+ stopSequences: nil,+ grammar: nil+ )++ let collector = GenerateEventCollector()+ let summary = try generateChatStream(context: context, request: request, callback: collector)++ XCTAssertGreaterThan(summary.jobId, 0)+ XCTAssertTrue(collector.hasDone)+ XCTAssertNil(collector.lastError)+ print("Swift text output: \(collector.textOutput)")+ }++ func testGenerateChatStreamWithImageWhenProvided() throws {+ let env = ProcessInfo.processInfo.environment+ guard let modelPath = env["INFERENCE_RS_TEST_MODEL"] ?? env["INFERENCE_RS_TEST_MODEL_PATH"] else {+ throw XCTSkip("Set INFERENCE_RS_TEST_MODEL to run the integration test.")+ }+ guard let mmprojPath = env["INFERENCE_RS_TEST_MMPROJ"] ?? env["INFERENCE_RS_TEST_MMPROJ_PATH"] else {+ throw XCTSkip("Set INFERENCE_RS_TEST_MMPROJ to run the vision test.")+ }+ guard let imagePath = env["INFERENCE_RS_TEST_IMAGE"] ?? env["INFERENCE_RS_TEST_IMAGE_PATH"] else {+ throw XCTSkip("Set INFERENCE_RS_TEST_IMAGE to run the vision test.")+ }++ try initBackend()++ let model = try loadModel(+ params: ModelLoadParams(+ modelPath: modelPath,+ nGpuLayers: nil,+ useMmap: nil,+ useMlock: nil+ )+ )++ let context = try createContext(+ model: model,+ params: ContextParams(contextSize: 2048, nThreads: nil, nBatch: nil)+ )++ let request = GenerateChatRequest(+ messages: [+ ChatMessage(role: "system", content: "You are a helpful assistant."),+ ChatMessage(role: "user", content: "What color is the car? Answer in one word.")+ ],+ templateOverride: nil,+ addAssistant: true,+ imagePaths: [imagePath],+ mmprojPath: mmprojPath,+ mediaMarker: nil,+ maxTokens: 24,+ temperature: 0.2,+ topP: 0.9,+ topK: nil,+ repeatPenalty: nil,+ frequencyPenalty: nil,+ presencePenalty: nil,+ seed: 42,+ stopSequences: nil,+ grammar: nil+ )++ let collector = GenerateEventCollector()+ let summary = try generateChatStream(context: context, request: request, callback: collector)++ XCTAssertGreaterThan(summary.jobId, 0)+ XCTAssertTrue(collector.hasDone)+ XCTAssertNil(collector.lastError)+ print("Swift image output: \(collector.textOutput)")+ }+}diff --git a/mobile/native/darwin/Packages/Rust/rust/Cargo.lock b/mobile/native/darwin/Packages/Rust/rust/Cargo.locknew file mode 100644index 0000000000..b3da5bafae--- /dev/null+++ b/mobile/native/darwin/Packages/Rust/rust/Cargo.lock@@ -0,0 +1,1064 @@+# 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 = "anyhow"+version = "1.0.100"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"++[[package]]+name = "askama"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75363874b771be265f4ffe307ca705ef6f3baa19011c149da8674a87f1b75c4"+dependencies = [+ "askama_derive",+ "itoa",+ "percent-encoding",+ "serde",+ "serde_json",+]++[[package]]+name = "askama_derive"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "129397200fe83088e8a68407a8e2b1f826cf0086b21ccdb866a722c8bcd3a94f"+dependencies = [+ "askama_parser",+ "basic-toml",+ "memchr",+ "proc-macro2",+ "quote",+ "rustc-hash",+ "serde",+ "serde_derive",+ "syn",+]++[[package]]+name = "askama_parser"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6ab5630b3d5eaf232620167977f95eb51f3432fc76852328774afbd242d4358"+dependencies = [+ "memchr",+ "serde",+ "serde_derive",+ "winnow",+]++[[package]]+name = "autocfg"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"++[[package]]+name = "basic-toml"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a"+dependencies = [+ "serde",+]++[[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 = "bytes"+version = "1.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3"++[[package]]+name = "camino"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e629a66d692cb9ff1a1c664e41771b3dcaf961985a9774c0eb0bd1b51cf60a48"+dependencies = [+ "serde_core",+]++[[package]]+name = "cargo-platform"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"+dependencies = [+ "serde",+]++[[package]]+name = "cargo_metadata"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"+dependencies = [+ "camino",+ "cargo-platform",+ "semver",+ "serde",+ "serde_json",+ "thiserror 2.0.17",+]++[[package]]+name = "cc"+version = "1.2.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "755d2fce177175ffca841e9a06afdb2c4ab0f593d53b4dee48147dfaade85932"+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 = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys",+]++[[package]]+name = "fastrand"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"++[[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 = "fs-err"+version = "2.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88a41f105fe1d5b6b34b2055e3dc59bb79b46b48b2040b9e6c7b4b5de097aa41"+dependencies = [+ "autocfg",+]++[[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 = "goblin"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47"+dependencies = [+ "log",+ "plain",+ "scroll",+]++[[package]]+name = "hashbrown"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "indexmap"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"+dependencies = [+ "equivalent",+ "hashbrown",+ "serde",+ "serde_core",+]++[[package]]+name = "inference_rs"+version = "0.1.0"+dependencies = [+ "llama-cpp-2",+ "llama-cpp-sys-2",+ "parking_lot",+ "self_cell",+ "serde",+ "serde_json",+ "thiserror 1.0.69",+]++[[package]]+name = "inference_rs_uniffi"+version = "0.1.0"+dependencies = [+ "inference_rs",+ "serde",+ "thiserror 1.0.69",+ "uniffi",+]++[[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 = "linux-raw-sys"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"++[[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 1.0.69",+ "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 = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pin-project-lite"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"++[[package]]+name = "plain"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"++[[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.105"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "535d180e0ecab6268a3e718bb9fd44db66bbbc256257165fc699dadf70d16fe7"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.43"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74d9a594b72ae6656596548f56f667211f8a97b3d4c3d467150794690dc40a"+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 = "rustix"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34"+dependencies = [+ "bitflags",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys",+]++[[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 = "scroll"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6"+dependencies = [+ "scroll_derive",+]++[[package]]+name = "scroll_derive"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "self_cell"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b12e76d157a900eb52e81bc6e9f3069344290341720e9178cde2407113ac8d89"++[[package]]+name = "semver"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"+dependencies = [+ "serde",+ "serde_core",+]++[[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 = "serde_spanned"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776"+dependencies = [+ "serde_core",+]++[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"++[[package]]+name = "siphasher"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"++[[package]]+name = "smallvec"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"++[[package]]+name = "smawk"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c"++[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"++[[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 = "tempfile"+version = "3.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "655da9c7eb6305c55742045d5a8d2037996d61d8de95806335c7c86ce0f82e9c"+dependencies = [+ "fastrand",+ "getrandom",+ "once_cell",+ "rustix",+ "windows-sys",+]++[[package]]+name = "textwrap"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057"+dependencies = [+ "smawk",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8"+dependencies = [+ "thiserror-impl 2.0.17",+]++[[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 = "thiserror-impl"+version = "2.0.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "toml"+version = "0.9.11+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3afc9a848309fe1aaffaed6e1546a7a14de1f935dc9d89d32afd9a44bab7c46"+dependencies = [+ "indexmap",+ "serde_core",+ "serde_spanned",+ "toml_datetime",+ "toml_parser",+ "toml_writer",+ "winnow",+]++[[package]]+name = "toml_datetime"+version = "0.7.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_parser"+version = "1.0.6+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3198b4b0a8e11f09dd03e133c0280504d0801269e9afa46362ffde1cbeebf44"+dependencies = [+ "winnow",+]++[[package]]+name = "toml_writer"+version = "1.0.6+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607"++[[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 = "uniffi"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8c6dec3fc6645f71a16a3fa9ff57991028153bd194ca97f4b55e610c73ce66a"+dependencies = [+ "anyhow",+ "cargo_metadata",+ "uniffi_bindgen",+ "uniffi_core",+ "uniffi_macros",+ "uniffi_pipeline",+]++[[package]]+name = "uniffi_bindgen"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ed0150801958d4825da56a41c71f000a457ac3a4613fa9647df78ac4b6b6881"+dependencies = [+ "anyhow",+ "askama",+ "camino",+ "cargo_metadata",+ "fs-err",+ "glob",+ "goblin",+ "heck",+ "indexmap",+ "once_cell",+ "serde",+ "tempfile",+ "textwrap",+ "toml",+ "uniffi_internal_macros",+ "uniffi_meta",+ "uniffi_pipeline",+ "uniffi_udl",+]++[[package]]+name = "uniffi_core"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0ef62e69762fbb9386dcb6c87cd3dd05d525fa8a3a579a290892e60ddbda47e"+dependencies = [+ "anyhow",+ "bytes",+ "once_cell",+ "static_assertions",+]++[[package]]+name = "uniffi_internal_macros"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98f51ebca0d9a4b2aa6c644d5ede45c56f73906b96403c08a1985e75ccb64a01"+dependencies = [+ "anyhow",+ "indexmap",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "uniffi_macros"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db9d12529f1223d014fd501e5f29ca0884d15d6ed5ddddd9f506e55350327dc3"+dependencies = [+ "camino",+ "fs-err",+ "once_cell",+ "proc-macro2",+ "quote",+ "serde",+ "syn",+ "toml",+ "uniffi_meta",+]++[[package]]+name = "uniffi_meta"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9df6d413db2827c68588f8149d30d49b71d540d46539e435b23a7f7dbd4d4f86"+dependencies = [+ "anyhow",+ "siphasher",+ "uniffi_internal_macros",+ "uniffi_pipeline",+]++[[package]]+name = "uniffi_pipeline"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a806dddc8208f22efd7e95a5cdf88ed43d0f3271e8f63b47e757a8bbdb43b63a"+dependencies = [+ "anyhow",+ "heck",+ "indexmap",+ "tempfile",+ "uniffi_internal_macros",+]++[[package]]+name = "uniffi_udl"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d1a7339539bf6f6fa3e9b534dece13f778bda2d54b1a6d4e40b4d6090ac26e7"+dependencies = [+ "anyhow",+ "textwrap",+ "uniffi_meta",+ "weedle2",+]++[[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 = "weedle2"+version = "5.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e"+dependencies = [+ "nom",+]++[[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 = "winnow"+version = "0.7.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829"+dependencies = [+ "memchr",+]++[[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.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd8f3f50b848df28f887acb68e41201b5aea6bc8a8dacc00fb40635ff9a72fea"diff --git a/mobile/native/darwin/Packages/Rust/rust/Cargo.toml b/mobile/native/darwin/Packages/Rust/rust/Cargo.tomlnew file mode 100644index 0000000000..c27283923d--- /dev/null+++ b/mobile/native/darwin/Packages/Rust/rust/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "inference_rs_uniffi"+version = "0.1.0"+edition = "2024"++[lib]+name = "inference_rs_uniffi"+crate-type = ["staticlib", "cdylib"]++[dependencies]+inference_rs = { path = "../../../../../../rust/inference_rs" }+serde = { version = "1", features = ["derive"] }+thiserror = "1"+uniffi = { version = "0.31.0" }diff --git a/mobile/native/darwin/Packages/Rust/rust/src/api.rs b/mobile/native/darwin/Packages/Rust/rust/src/api.rsnew file mode 100644index 0000000000..0e6dd77fca--- /dev/null+++ b/mobile/native/darwin/Packages/Rust/rust/src/api.rs@@ -0,0 +1,325 @@+use inference_rs as core;+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use thiserror::Error;++#[derive(Debug, Error, uniffi::Error)]+pub enum InferenceError {+ #[error("{0}")]+ Message(String),+}++impl From<String> for InferenceError {+ fn from(value: String) -> Self {+ Self::Message(value)+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct ModelLoadParams {+ pub model_path: String,+ pub n_gpu_layers: Option<i32>,+ pub use_mmap: Option<bool>,+ pub use_mlock: Option<bool>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct ContextParams {+ pub context_size: Option<i32>,+ pub n_threads: Option<i32>,+ pub n_batch: Option<i32>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct ModelInfo {+ pub bos_token_id: Option<i32>,+ pub eos_token_id: Option<i32>,+ pub bos_token: Option<String>,+ pub eos_token: Option<String>,+ pub chat_template: Option<String>,+ pub metadata_json: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct ChatMessage {+ pub role: String,+ pub content: String,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct GenerateRequest {+ pub prompt: String,+ pub max_tokens: Option<i32>,+ pub temperature: Option<f32>,+ pub top_p: Option<f32>,+ pub top_k: Option<i32>,+ pub repeat_penalty: Option<f32>,+ pub frequency_penalty: Option<f32>,+ pub presence_penalty: Option<f32>,+ pub seed: Option<i64>,+ pub stop_sequences: Option<Vec<String>>,+ pub grammar: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct GenerateChatRequest {+ pub messages: Vec<ChatMessage>,+ pub template_override: Option<String>,+ pub add_assistant: Option<bool>,+ pub image_paths: Option<Vec<String>>,+ pub mmproj_path: Option<String>,+ pub media_marker: Option<String>,+ pub max_tokens: Option<i32>,+ pub temperature: Option<f32>,+ pub top_p: Option<f32>,+ pub top_k: Option<i32>,+ pub repeat_penalty: Option<f32>,+ pub frequency_penalty: Option<f32>,+ pub presence_penalty: Option<f32>,+ pub seed: Option<i64>,+ pub stop_sequences: Option<Vec<String>>,+ pub grammar: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct GenerateSummary {+ pub job_id: i64,+ pub prompt_tokens: Option<i32>,+ pub generated_tokens: Option<i32>,+ pub total_time_ms: Option<i64>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Enum)]+pub enum GenerateEvent {+ Text {+ job_id: i64,+ text: String,+ token_id: Option<i32>,+ },+ Done { summary: GenerateSummary },+ Error { job_id: i64, message: String },+}++#[derive(uniffi::Object)]+pub struct ModelHandle {+ handle: core::ModelHandleRef,+}++#[derive(uniffi::Object)]+pub struct ContextHandle {+ handle: core::ContextHandleRef,+}++#[uniffi::export(callback_interface)]+pub trait GenerateEventCallback: Send + Sync {+ fn on_event(&self, event: GenerateEvent);+}++impl From<ModelLoadParams> for core::ModelLoadParams {+ fn from(value: ModelLoadParams) -> Self {+ Self {+ model_path: value.model_path,+ n_gpu_layers: value.n_gpu_layers,+ use_mmap: value.use_mmap,+ use_mlock: value.use_mlock,+ }+ }+}++impl From<ContextParams> for core::ContextParams {+ fn from(value: ContextParams) -> Self {+ Self {+ context_size: value.context_size,+ n_threads: value.n_threads,+ n_batch: value.n_batch,+ }+ }+}++impl From<core::ModelInfo> for ModelInfo {+ fn from(value: core::ModelInfo) -> Self {+ Self {+ bos_token_id: value.bos_token_id,+ eos_token_id: value.eos_token_id,+ bos_token: value.bos_token,+ eos_token: value.eos_token,+ chat_template: value.chat_template,+ metadata_json: value.metadata_json,+ }+ }+}++impl From<ChatMessage> for core::ChatMessage {+ fn from(value: ChatMessage) -> Self {+ Self {+ role: value.role,+ content: value.content,+ }+ }+}++impl From<GenerateRequest> for core::GenerateRequest {+ fn from(value: GenerateRequest) -> Self {+ Self {+ prompt: value.prompt,+ max_tokens: value.max_tokens,+ temperature: value.temperature,+ top_p: value.top_p,+ top_k: value.top_k,+ repeat_penalty: value.repeat_penalty,+ frequency_penalty: value.frequency_penalty,+ presence_penalty: value.presence_penalty,+ seed: value.seed,+ stop_sequences: value.stop_sequences,+ grammar: value.grammar,+ }+ }+}++impl From<GenerateChatRequest> for core::GenerateChatRequest {+ fn from(value: GenerateChatRequest) -> Self {+ Self {+ messages: value.messages.into_iter().map(Into::into).collect(),+ template_override: value.template_override,+ add_assistant: value.add_assistant,+ image_paths: value.image_paths,+ mmproj_path: value.mmproj_path,+ media_marker: value.media_marker,+ max_tokens: value.max_tokens,+ temperature: value.temperature,+ top_p: value.top_p,+ top_k: value.top_k,+ repeat_penalty: value.repeat_penalty,+ frequency_penalty: value.frequency_penalty,+ presence_penalty: value.presence_penalty,+ seed: value.seed,+ stop_sequences: value.stop_sequences,+ grammar: value.grammar,+ }+ }+}++impl From<core::GenerateSummary> for GenerateSummary {+ fn from(value: core::GenerateSummary) -> Self {+ Self {+ job_id: value.job_id,+ prompt_tokens: value.prompt_tokens,+ generated_tokens: value.generated_tokens,+ total_time_ms: value.total_time_ms,+ }+ }+}++impl From<core::GenerateEvent> for GenerateEvent {+ fn from(value: core::GenerateEvent) -> Self {+ match value {+ core::GenerateEvent::Text {+ job_id,+ text,+ token_id,+ } => Self::Text {+ job_id,+ text,+ token_id,+ },+ core::GenerateEvent::Done { summary } => Self::Done {+ summary: summary.into(),+ },+ core::GenerateEvent::Error { job_id, message } => Self::Error { job_id, message },+ }+ }+}++struct CallbackSink {+ callback: Box<dyn GenerateEventCallback>,+}++impl core::EventSink for CallbackSink {+ fn add(&mut self, event: core::GenerateEvent) {+ self.callback.on_event(event.into());+ }+}++#[uniffi::export]+pub fn init_backend() -> Result<(), InferenceError> {+ core::init_backend().map_err(InferenceError::from)+}++#[uniffi::export]+pub fn load_model(params: ModelLoadParams) -> Result<Arc<ModelHandle>, InferenceError> {+ let model = core::load_model(params.into()).map_err(InferenceError::from)?;+ Ok(Arc::new(ModelHandle { handle: model }))+}++#[uniffi::export]+pub fn create_context(+ model: Arc<ModelHandle>,+ params: ContextParams,+) -> Result<Arc<ContextHandle>, InferenceError> {+ let context = core::create_context(model.handle.clone(), params.into()).map_err(InferenceError::from)?;+ Ok(Arc::new(ContextHandle { handle: context }))+}++#[uniffi::export]+pub fn tokenize(+ model: Arc<ModelHandle>,+ text: String,+ add_bos: bool,+ special: bool,+) -> Result<Vec<i32>, InferenceError> {+ core::tokenize(model.handle.as_ref(), text, add_bos, special)+ .map_err(InferenceError::from)+}++#[uniffi::export]+pub fn detokenize(model: Arc<ModelHandle>, tokens: Vec<i32>) -> Result<String, InferenceError> {+ core::detokenize(model.handle.as_ref(), tokens).map_err(InferenceError::from)+}++#[uniffi::export]+pub fn get_model_info(model: Arc<ModelHandle>) -> Result<ModelInfo, InferenceError> {+ core::get_model_info(model.handle.as_ref())+ .map(Into::into)+ .map_err(InferenceError::from)+}++#[uniffi::export]+pub fn apply_chat_template(+ model: Arc<ModelHandle>,+ messages: Vec<ChatMessage>,+ template_override: Option<String>,+ add_assistant: bool,+) -> Result<String, InferenceError> {+ let messages = messages.into_iter().map(Into::into).collect();+ core::apply_chat_template(model.handle.as_ref(), messages, template_override, add_assistant)+ .map_err(InferenceError::from)+}++#[uniffi::export]+pub fn generate_chat_stream(+ context: Arc<ContextHandle>,+ request: GenerateChatRequest,+ callback: Box<dyn GenerateEventCallback>,+) -> Result<GenerateSummary, InferenceError> {+ let mut sink = CallbackSink { callback };+ core::generate_chat_stream(context.handle.as_ref(), request.into(), &mut sink)+ .map(Into::into)+ .map_err(InferenceError::from)+}++#[uniffi::export]+pub fn generate_stream(+ context: Arc<ContextHandle>,+ request: GenerateRequest,+ callback: Box<dyn GenerateEventCallback>,+) -> Result<GenerateSummary, InferenceError> {+ let mut sink = CallbackSink { callback };+ core::generate_stream(context.handle.as_ref(), request.into(), &mut sink)+ .map(Into::into)+ .map_err(InferenceError::from)+}++#[uniffi::export]+pub fn cancel(job_id: i64) {+ let _ = core::cancel(job_id);+}diff --git a/mobile/native/darwin/Packages/Rust/rust/src/lib.rs b/mobile/native/darwin/Packages/Rust/rust/src/lib.rsnew file mode 100644index 0000000000..dce5d9a1da--- /dev/null+++ b/mobile/native/darwin/Packages/Rust/rust/src/lib.rs@@ -0,0 +1,7 @@+#![allow(unexpected_cfgs)]++mod api;++uniffi::setup_scaffolding!("inference_rs_uniffi");++pub use api::*;diff --git a/mobile/native/darwin/Packages/Rust/rust/uniffi.toml b/mobile/native/darwin/Packages/Rust/rust/uniffi.tomlnew file mode 100644index 0000000000..f3de948c2b--- /dev/null+++ b/mobile/native/darwin/Packages/Rust/rust/uniffi.toml@@ -0,0 +1,8 @@+[bindings.swift]+link_frameworks = ["Accelerate", "Metal", "MetalKit", "Foundation"]++[bindings.kotlin]+package_name = "io.ente.labs.inference_rs"+cdylib_name = "inference_rs_uniffi"+android = true+kotlin_target_version = "1.9.0"diff --git a/mobile/native/darwin/Packages/Rust/tool/build_xcframework.sh b/mobile/native/darwin/Packages/Rust/tool/build_xcframework.shnew file mode 100755index 0000000000..cd6a10c807--- /dev/null+++ b/mobile/native/darwin/Packages/Rust/tool/build_xcframework.sh@@ -0,0 +1,62 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+REPO_ROOT="$(cd "$ROOT/../../../../.." && pwd)"+RUST_DIR="$ROOT/rust"+CORE_ROOT="$REPO_ROOT/rust/inference_rs"+PATCH_SCRIPT="$CORE_ROOT/tool/patch_llama_mtmd.sh"+LIB_NAME="libinference_rs_uniffi.a"++"$PATCH_SCRIPT"++"$ROOT/tool/generate_bindings.sh"++HEADER_DIR="$ROOT/build/headers"+HEADER_SRC="$ROOT/Sources/InferenceRS/inference_rs_uniffiFFI.h"+MODULEMAP_SRC="$ROOT/Sources/InferenceRS/inference_rs_uniffiFFI.modulemap"++rm -rf "$HEADER_DIR"+mkdir -p "$ROOT/build/ios" "$ROOT/build/macos" "$HEADER_DIR"++if [[ ! -f "$HEADER_SRC" ]] || [[ ! -f "$MODULEMAP_SRC" ]]; then+ echo "Expected UniFFI headers in $ROOT/Sources/InferenceRS" >&2+ exit 1+fi++cp "$HEADER_SRC" "$HEADER_DIR/"+cp "$MODULEMAP_SRC" "$HEADER_DIR/module.modulemap"++export IPHONEOS_DEPLOYMENT_TARGET=13.0+export CMAKE_OSX_DEPLOYMENT_TARGET=13.0++cargo rustc --manifest-path "$RUST_DIR/Cargo.toml" --release --target aarch64-apple-ios --lib --crate-type staticlib+cargo rustc --manifest-path "$RUST_DIR/Cargo.toml" --release --target aarch64-apple-ios-sim --lib --crate-type staticlib+cargo rustc --manifest-path "$RUST_DIR/Cargo.toml" --release --target x86_64-apple-ios --lib --crate-type staticlib++cp "$RUST_DIR/target/aarch64-apple-ios/release/$LIB_NAME" "$ROOT/build/ios/$LIB_NAME"++lipo -create \+ "$RUST_DIR/target/aarch64-apple-ios-sim/release/$LIB_NAME" \+ "$RUST_DIR/target/x86_64-apple-ios/release/$LIB_NAME" \+ -output "$ROOT/build/ios/${LIB_NAME%.a}-sim.a"++unset IPHONEOS_DEPLOYMENT_TARGET+export MACOSX_DEPLOYMENT_TARGET=10.15+export CMAKE_OSX_DEPLOYMENT_TARGET=10.15++cargo rustc --manifest-path "$RUST_DIR/Cargo.toml" --release --target aarch64-apple-darwin --lib --crate-type staticlib+cargo rustc --manifest-path "$RUST_DIR/Cargo.toml" --release --target x86_64-apple-darwin --lib --crate-type staticlib++lipo -create \+ "$RUST_DIR/target/aarch64-apple-darwin/release/$LIB_NAME" \+ "$RUST_DIR/target/x86_64-apple-darwin/release/$LIB_NAME" \+ -output "$ROOT/build/macos/$LIB_NAME"++rm -rf "$ROOT/InferenceRSFFI.xcframework"++xcodebuild -create-xcframework \+ -library "$ROOT/build/ios/$LIB_NAME" -headers "$HEADER_DIR" \+ -library "$ROOT/build/ios/${LIB_NAME%.a}-sim.a" -headers "$HEADER_DIR" \+ -library "$ROOT/build/macos/$LIB_NAME" -headers "$HEADER_DIR" \+ -output "$ROOT/InferenceRSFFI.xcframework"diff --git a/mobile/native/darwin/Packages/Rust/tool/generate_bindings.sh b/mobile/native/darwin/Packages/Rust/tool/generate_bindings.shnew file mode 100755index 0000000000..edb43f9418--- /dev/null+++ b/mobile/native/darwin/Packages/Rust/tool/generate_bindings.sh@@ -0,0 +1,35 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+REPO_ROOT="$(cd "$ROOT/../../../../.." && pwd)"+RUST_DIR="$ROOT/rust"+CORE_ROOT="$REPO_ROOT/rust/inference_rs"+PATCH_SCRIPT="$CORE_ROOT/tool/patch_llama_mtmd.sh"+OUT_DIR="$ROOT/Sources/InferenceRS"++"$PATCH_SCRIPT"++cargo build --manifest-path "$RUST_DIR/Cargo.toml" --release++if [[ "$(uname -s)" == "Darwin" ]]; then+ LIB_EXT="dylib"+elif [[ "$(uname -s)" == "Linux" ]]; then+ LIB_EXT="so"+else+ LIB_EXT="dll"+fi++LIB_PATH="$RUST_DIR/target/release/libinference_rs_uniffi.$LIB_EXT"++if [[ ! -f "$LIB_PATH" ]]; then+ echo "Expected $LIB_PATH to exist" >&2+ exit 1+fi++mkdir -p "$OUT_DIR"+rm -f "$OUT_DIR"/inference_rs_*++pushd "$RUST_DIR" >/dev/null+uniffi-bindgen generate "$LIB_PATH" --language swift --out-dir "$OUT_DIR" --crate inference_rs_uniffi+popd >/dev/nulldiff --git a/rust/inference_rs_uniffi/Cargo.lock b/rust/inference_rs_uniffi/Cargo.locknew file mode 100644index 0000000000..b3da5bafae--- /dev/null+++ b/rust/inference_rs_uniffi/Cargo.lock@@ -0,0 +1,1064 @@+# 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 = "anyhow"+version = "1.0.100"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"++[[package]]+name = "askama"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75363874b771be265f4ffe307ca705ef6f3baa19011c149da8674a87f1b75c4"+dependencies = [+ "askama_derive",+ "itoa",+ "percent-encoding",+ "serde",+ "serde_json",+]++[[package]]+name = "askama_derive"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "129397200fe83088e8a68407a8e2b1f826cf0086b21ccdb866a722c8bcd3a94f"+dependencies = [+ "askama_parser",+ "basic-toml",+ "memchr",+ "proc-macro2",+ "quote",+ "rustc-hash",+ "serde",+ "serde_derive",+ "syn",+]++[[package]]+name = "askama_parser"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6ab5630b3d5eaf232620167977f95eb51f3432fc76852328774afbd242d4358"+dependencies = [+ "memchr",+ "serde",+ "serde_derive",+ "winnow",+]++[[package]]+name = "autocfg"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"++[[package]]+name = "basic-toml"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a"+dependencies = [+ "serde",+]++[[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 = "bytes"+version = "1.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3"++[[package]]+name = "camino"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e629a66d692cb9ff1a1c664e41771b3dcaf961985a9774c0eb0bd1b51cf60a48"+dependencies = [+ "serde_core",+]++[[package]]+name = "cargo-platform"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"+dependencies = [+ "serde",+]++[[package]]+name = "cargo_metadata"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"+dependencies = [+ "camino",+ "cargo-platform",+ "semver",+ "serde",+ "serde_json",+ "thiserror 2.0.17",+]++[[package]]+name = "cc"+version = "1.2.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "755d2fce177175ffca841e9a06afdb2c4ab0f593d53b4dee48147dfaade85932"+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 = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys",+]++[[package]]+name = "fastrand"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"++[[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 = "fs-err"+version = "2.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88a41f105fe1d5b6b34b2055e3dc59bb79b46b48b2040b9e6c7b4b5de097aa41"+dependencies = [+ "autocfg",+]++[[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 = "goblin"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47"+dependencies = [+ "log",+ "plain",+ "scroll",+]++[[package]]+name = "hashbrown"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "indexmap"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"+dependencies = [+ "equivalent",+ "hashbrown",+ "serde",+ "serde_core",+]++[[package]]+name = "inference_rs"+version = "0.1.0"+dependencies = [+ "llama-cpp-2",+ "llama-cpp-sys-2",+ "parking_lot",+ "self_cell",+ "serde",+ "serde_json",+ "thiserror 1.0.69",+]++[[package]]+name = "inference_rs_uniffi"+version = "0.1.0"+dependencies = [+ "inference_rs",+ "serde",+ "thiserror 1.0.69",+ "uniffi",+]++[[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 = "linux-raw-sys"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"++[[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 1.0.69",+ "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 = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pin-project-lite"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"++[[package]]+name = "plain"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"++[[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.105"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "535d180e0ecab6268a3e718bb9fd44db66bbbc256257165fc699dadf70d16fe7"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.43"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc74d9a594b72ae6656596548f56f667211f8a97b3d4c3d467150794690dc40a"+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 = "rustix"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34"+dependencies = [+ "bitflags",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys",+]++[[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 = "scroll"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6"+dependencies = [+ "scroll_derive",+]++[[package]]+name = "scroll_derive"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "self_cell"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b12e76d157a900eb52e81bc6e9f3069344290341720e9178cde2407113ac8d89"++[[package]]+name = "semver"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"+dependencies = [+ "serde",+ "serde_core",+]++[[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 = "serde_spanned"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776"+dependencies = [+ "serde_core",+]++[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"++[[package]]+name = "siphasher"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"++[[package]]+name = "smallvec"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"++[[package]]+name = "smawk"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c"++[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"++[[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 = "tempfile"+version = "3.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "655da9c7eb6305c55742045d5a8d2037996d61d8de95806335c7c86ce0f82e9c"+dependencies = [+ "fastrand",+ "getrandom",+ "once_cell",+ "rustix",+ "windows-sys",+]++[[package]]+name = "textwrap"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057"+dependencies = [+ "smawk",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8"+dependencies = [+ "thiserror-impl 2.0.17",+]++[[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 = "thiserror-impl"+version = "2.0.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "toml"+version = "0.9.11+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3afc9a848309fe1aaffaed6e1546a7a14de1f935dc9d89d32afd9a44bab7c46"+dependencies = [+ "indexmap",+ "serde_core",+ "serde_spanned",+ "toml_datetime",+ "toml_parser",+ "toml_writer",+ "winnow",+]++[[package]]+name = "toml_datetime"+version = "0.7.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_parser"+version = "1.0.6+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3198b4b0a8e11f09dd03e133c0280504d0801269e9afa46362ffde1cbeebf44"+dependencies = [+ "winnow",+]++[[package]]+name = "toml_writer"+version = "1.0.6+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607"++[[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 = "uniffi"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8c6dec3fc6645f71a16a3fa9ff57991028153bd194ca97f4b55e610c73ce66a"+dependencies = [+ "anyhow",+ "cargo_metadata",+ "uniffi_bindgen",+ "uniffi_core",+ "uniffi_macros",+ "uniffi_pipeline",+]++[[package]]+name = "uniffi_bindgen"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ed0150801958d4825da56a41c71f000a457ac3a4613fa9647df78ac4b6b6881"+dependencies = [+ "anyhow",+ "askama",+ "camino",+ "cargo_metadata",+ "fs-err",+ "glob",+ "goblin",+ "heck",+ "indexmap",+ "once_cell",+ "serde",+ "tempfile",+ "textwrap",+ "toml",+ "uniffi_internal_macros",+ "uniffi_meta",+ "uniffi_pipeline",+ "uniffi_udl",+]++[[package]]+name = "uniffi_core"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0ef62e69762fbb9386dcb6c87cd3dd05d525fa8a3a579a290892e60ddbda47e"+dependencies = [+ "anyhow",+ "bytes",+ "once_cell",+ "static_assertions",+]++[[package]]+name = "uniffi_internal_macros"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98f51ebca0d9a4b2aa6c644d5ede45c56f73906b96403c08a1985e75ccb64a01"+dependencies = [+ "anyhow",+ "indexmap",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "uniffi_macros"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db9d12529f1223d014fd501e5f29ca0884d15d6ed5ddddd9f506e55350327dc3"+dependencies = [+ "camino",+ "fs-err",+ "once_cell",+ "proc-macro2",+ "quote",+ "serde",+ "syn",+ "toml",+ "uniffi_meta",+]++[[package]]+name = "uniffi_meta"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9df6d413db2827c68588f8149d30d49b71d540d46539e435b23a7f7dbd4d4f86"+dependencies = [+ "anyhow",+ "siphasher",+ "uniffi_internal_macros",+ "uniffi_pipeline",+]++[[package]]+name = "uniffi_pipeline"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a806dddc8208f22efd7e95a5cdf88ed43d0f3271e8f63b47e757a8bbdb43b63a"+dependencies = [+ "anyhow",+ "heck",+ "indexmap",+ "tempfile",+ "uniffi_internal_macros",+]++[[package]]+name = "uniffi_udl"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d1a7339539bf6f6fa3e9b534dece13f778bda2d54b1a6d4e40b4d6090ac26e7"+dependencies = [+ "anyhow",+ "textwrap",+ "uniffi_meta",+ "weedle2",+]++[[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 = "weedle2"+version = "5.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e"+dependencies = [+ "nom",+]++[[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 = "winnow"+version = "0.7.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829"+dependencies = [+ "memchr",+]++[[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.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd8f3f50b848df28f887acb68e41201b5aea6bc8a8dacc00fb40635ff9a72fea"diff --git a/rust/inference_rs_uniffi/Cargo.toml b/rust/inference_rs_uniffi/Cargo.tomlnew file mode 100644index 0000000000..c3921f47bc--- /dev/null+++ b/rust/inference_rs_uniffi/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "inference_rs_uniffi"+version = "0.1.0"+edition = "2024"++[lib]+name = "inference_rs_uniffi"+crate-type = ["staticlib", "cdylib"]++[dependencies]+inference_rs = { path = "../inference_rs" }+serde = { version = "1", features = ["derive"] }+thiserror = "1"+uniffi = { version = "0.31.0" }diff --git a/rust/inference_rs_uniffi/src/api.rs b/rust/inference_rs_uniffi/src/api.rsnew file mode 100644index 0000000000..0e6dd77fca--- /dev/null+++ b/rust/inference_rs_uniffi/src/api.rs@@ -0,0 +1,325 @@+use inference_rs as core;+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use thiserror::Error;++#[derive(Debug, Error, uniffi::Error)]+pub enum InferenceError {+ #[error("{0}")]+ Message(String),+}++impl From<String> for InferenceError {+ fn from(value: String) -> Self {+ Self::Message(value)+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct ModelLoadParams {+ pub model_path: String,+ pub n_gpu_layers: Option<i32>,+ pub use_mmap: Option<bool>,+ pub use_mlock: Option<bool>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct ContextParams {+ pub context_size: Option<i32>,+ pub n_threads: Option<i32>,+ pub n_batch: Option<i32>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct ModelInfo {+ pub bos_token_id: Option<i32>,+ pub eos_token_id: Option<i32>,+ pub bos_token: Option<String>,+ pub eos_token: Option<String>,+ pub chat_template: Option<String>,+ pub metadata_json: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct ChatMessage {+ pub role: String,+ pub content: String,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct GenerateRequest {+ pub prompt: String,+ pub max_tokens: Option<i32>,+ pub temperature: Option<f32>,+ pub top_p: Option<f32>,+ pub top_k: Option<i32>,+ pub repeat_penalty: Option<f32>,+ pub frequency_penalty: Option<f32>,+ pub presence_penalty: Option<f32>,+ pub seed: Option<i64>,+ pub stop_sequences: Option<Vec<String>>,+ pub grammar: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct GenerateChatRequest {+ pub messages: Vec<ChatMessage>,+ pub template_override: Option<String>,+ pub add_assistant: Option<bool>,+ pub image_paths: Option<Vec<String>>,+ pub mmproj_path: Option<String>,+ pub media_marker: Option<String>,+ pub max_tokens: Option<i32>,+ pub temperature: Option<f32>,+ pub top_p: Option<f32>,+ pub top_k: Option<i32>,+ pub repeat_penalty: Option<f32>,+ pub frequency_penalty: Option<f32>,+ pub presence_penalty: Option<f32>,+ pub seed: Option<i64>,+ pub stop_sequences: Option<Vec<String>>,+ pub grammar: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Record)]+pub struct GenerateSummary {+ pub job_id: i64,+ pub prompt_tokens: Option<i32>,+ pub generated_tokens: Option<i32>,+ pub total_time_ms: Option<i64>,+}++#[derive(Debug, Clone, Serialize, Deserialize, uniffi::Enum)]+pub enum GenerateEvent {+ Text {+ job_id: i64,+ text: String,+ token_id: Option<i32>,+ },+ Done { summary: GenerateSummary },+ Error { job_id: i64, message: String },+}++#[derive(uniffi::Object)]+pub struct ModelHandle {+ handle: core::ModelHandleRef,+}++#[derive(uniffi::Object)]+pub struct ContextHandle {+ handle: core::ContextHandleRef,+}++#[uniffi::export(callback_interface)]+pub trait GenerateEventCallback: Send + Sync {+ fn on_event(&self, event: GenerateEvent);+}++impl From<ModelLoadParams> for core::ModelLoadParams {+ fn from(value: ModelLoadParams) -> Self {+ Self {+ model_path: value.model_path,+ n_gpu_layers: value.n_gpu_layers,+ use_mmap: value.use_mmap,+ use_mlock: value.use_mlock,+ }+ }+}++impl From<ContextParams> for core::ContextParams {+ fn from(value: ContextParams) -> Self {+ Self {+ context_size: value.context_size,+ n_threads: value.n_threads,+ n_batch: value.n_batch,+ }+ }+}++impl From<core::ModelInfo> for ModelInfo {+ fn from(value: core::ModelInfo) -> Self {+ Self {+ bos_token_id: value.bos_token_id,+ eos_token_id: value.eos_token_id,+ bos_token: value.bos_token,+ eos_token: value.eos_token,+ chat_template: value.chat_template,+ metadata_json: value.metadata_json,+ }+ }+}++impl From<ChatMessage> for core::ChatMessage {+ fn from(value: ChatMessage) -> Self {+ Self {+ role: value.role,+ content: value.content,+ }+ }+}++impl From<GenerateRequest> for core::GenerateRequest {+ fn from(value: GenerateRequest) -> Self {+ Self {+ prompt: value.prompt,+ max_tokens: value.max_tokens,+ temperature: value.temperature,+ top_p: value.top_p,+ top_k: value.top_k,+ repeat_penalty: value.repeat_penalty,+ frequency_penalty: value.frequency_penalty,+ presence_penalty: value.presence_penalty,+ seed: value.seed,+ stop_sequences: value.stop_sequences,+ grammar: value.grammar,+ }+ }+}++impl From<GenerateChatRequest> for core::GenerateChatRequest {+ fn from(value: GenerateChatRequest) -> Self {+ Self {+ messages: value.messages.into_iter().map(Into::into).collect(),+ template_override: value.template_override,+ add_assistant: value.add_assistant,+ image_paths: value.image_paths,+ mmproj_path: value.mmproj_path,+ media_marker: value.media_marker,+ max_tokens: value.max_tokens,+ temperature: value.temperature,+ top_p: value.top_p,+ top_k: value.top_k,+ repeat_penalty: value.repeat_penalty,+ frequency_penalty: value.frequency_penalty,+ presence_penalty: value.presence_penalty,+ seed: value.seed,+ stop_sequences: value.stop_sequences,+ grammar: value.grammar,+ }+ }+}++impl From<core::GenerateSummary> for GenerateSummary {+ fn from(value: core::GenerateSummary) -> Self {+ Self {+ job_id: value.job_id,+ prompt_tokens: value.prompt_tokens,+ generated_tokens: value.generated_tokens,+ total_time_ms: value.total_time_ms,+ }+ }+}++impl From<core::GenerateEvent> for GenerateEvent {+ fn from(value: core::GenerateEvent) -> Self {+ match value {+ core::GenerateEvent::Text {+ job_id,+ text,+ token_id,+ } => Self::Text {+ job_id,+ text,+ token_id,+ },+ core::GenerateEvent::Done { summary } => Self::Done {+ summary: summary.into(),+ },+ core::GenerateEvent::Error { job_id, message } => Self::Error { job_id, message },+ }+ }+}++struct CallbackSink {+ callback: Box<dyn GenerateEventCallback>,+}++impl core::EventSink for CallbackSink {+ fn add(&mut self, event: core::GenerateEvent) {+ self.callback.on_event(event.into());+ }+}++#[uniffi::export]+pub fn init_backend() -> Result<(), InferenceError> {+ core::init_backend().map_err(InferenceError::from)+}++#[uniffi::export]+pub fn load_model(params: ModelLoadParams) -> Result<Arc<ModelHandle>, InferenceError> {+ let model = core::load_model(params.into()).map_err(InferenceError::from)?;+ Ok(Arc::new(ModelHandle { handle: model }))+}++#[uniffi::export]+pub fn create_context(+ model: Arc<ModelHandle>,+ params: ContextParams,+) -> Result<Arc<ContextHandle>, InferenceError> {+ let context = core::create_context(model.handle.clone(), params.into()).map_err(InferenceError::from)?;+ Ok(Arc::new(ContextHandle { handle: context }))+}++#[uniffi::export]+pub fn tokenize(+ model: Arc<ModelHandle>,+ text: String,+ add_bos: bool,+ special: bool,+) -> Result<Vec<i32>, InferenceError> {+ core::tokenize(model.handle.as_ref(), text, add_bos, special)+ .map_err(InferenceError::from)+}++#[uniffi::export]+pub fn detokenize(model: Arc<ModelHandle>, tokens: Vec<i32>) -> Result<String, InferenceError> {+ core::detokenize(model.handle.as_ref(), tokens).map_err(InferenceError::from)+}++#[uniffi::export]+pub fn get_model_info(model: Arc<ModelHandle>) -> Result<ModelInfo, InferenceError> {+ core::get_model_info(model.handle.as_ref())+ .map(Into::into)+ .map_err(InferenceError::from)+}++#[uniffi::export]+pub fn apply_chat_template(+ model: Arc<ModelHandle>,+ messages: Vec<ChatMessage>,+ template_override: Option<String>,+ add_assistant: bool,+) -> Result<String, InferenceError> {+ let messages = messages.into_iter().map(Into::into).collect();+ core::apply_chat_template(model.handle.as_ref(), messages, template_override, add_assistant)+ .map_err(InferenceError::from)+}++#[uniffi::export]+pub fn generate_chat_stream(+ context: Arc<ContextHandle>,+ request: GenerateChatRequest,+ callback: Box<dyn GenerateEventCallback>,+) -> Result<GenerateSummary, InferenceError> {+ let mut sink = CallbackSink { callback };+ core::generate_chat_stream(context.handle.as_ref(), request.into(), &mut sink)+ .map(Into::into)+ .map_err(InferenceError::from)+}++#[uniffi::export]+pub fn generate_stream(+ context: Arc<ContextHandle>,+ request: GenerateRequest,+ callback: Box<dyn GenerateEventCallback>,+) -> Result<GenerateSummary, InferenceError> {+ let mut sink = CallbackSink { callback };+ core::generate_stream(context.handle.as_ref(), request.into(), &mut sink)+ .map(Into::into)+ .map_err(InferenceError::from)+}++#[uniffi::export]+pub fn cancel(job_id: i64) {+ let _ = core::cancel(job_id);+}diff --git a/rust/inference_rs_uniffi/src/lib.rs b/rust/inference_rs_uniffi/src/lib.rsnew file mode 100644index 0000000000..dce5d9a1da--- /dev/null+++ b/rust/inference_rs_uniffi/src/lib.rs@@ -0,0 +1,7 @@+#![allow(unexpected_cfgs)]++mod api;++uniffi::setup_scaffolding!("inference_rs_uniffi");++pub use api::*;diff --git a/rust/inference_rs_uniffi/uniffi.toml b/rust/inference_rs_uniffi/uniffi.tomlnew file mode 100644index 0000000000..f3de948c2b--- /dev/null+++ b/rust/inference_rs_uniffi/uniffi.toml@@ -0,0 +1,8 @@+[bindings.swift]+link_frameworks = ["Accelerate", "Metal", "MetalKit", "Foundation"]++[bindings.kotlin]+package_name = "io.ente.labs.inference_rs"+cdylib_name = "inference_rs_uniffi"+android = true+kotlin_target_version = "1.9.0"