Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

latex, math and other fixes

Prateek Sunalb85042e6b2d7
diff --git a/mobile/native/android/apps/ensu/app-ui/build.gradle.kts b/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
index 95ab9ed473..f717f3d9e3 100644
--- a/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
+++ b/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
@@ -5,6 +5,10 @@ plugins {
id("org.jetbrains.kotlin.android")
}
+configurations.configureEach {
+ exclude(group = "com.google.guava", module = "listenablefuture")
+}
+
val apiEndpointOverride = (System.getenv("ENTE_API_ENDPOINT")
?: project.findProperty("ENTE_API_ENDPOINT") as? String)
?.trim()
@@ -45,7 +49,7 @@ android {
defaultConfig {
applicationId = "io.ente.ensu"
- minSdk = 23
+ minSdk = 24
targetSdk = 35
versionCode = 7
versionName = "0.1.2"
@@ -71,6 +75,14 @@ android {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
+ jniLibs {
+ pickFirsts += setOf(
+ "lib/arm64-v8a/libc++_shared.so",
+ "lib/armeabi-v7a/libc++_shared.so",
+ "lib/x86/libc++_shared.so",
+ "lib/x86_64/libc++_shared.so"
+ )
+ }
}
compileOptions {
@@ -108,6 +120,10 @@ dependencies {
implementation(project(":data"))
implementation(project(":crypto-auth-core"))
+ implementation("com.github.gregcockroft:AndroidMath:v1.1.0") {
+ exclude(group = "com.google.guava", module = "listenablefuture")
+ }
+
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
}
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.kt
index 71d920a455..78a9742f86 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
@@ -14,6 +14,7 @@ import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -23,15 +24,12 @@ import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
-import androidx.compose.foundation.layout.WindowInsets
-import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
-import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
@@ -63,6 +61,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
+import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
@@ -104,6 +103,8 @@ import java.util.Date
import java.util.Locale
import kotlin.math.roundToLong
import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.flow.distinctUntilChanged
@Composable
fun ChatView(
@@ -122,7 +123,6 @@ fun ChatView(
onOpenAttachment: (Attachment) -> Unit,
onStartDownload: (Boolean) -> Unit
) {
- val imePadding = WindowInsets.ime.asPaddingValues().calculateBottomPadding()
val showDownloadOnboarding = !chatState.isModelDownloaded &&
chatState.messages.isEmpty() &&
!chatState.isGenerating
@@ -175,26 +175,31 @@ fun ChatView(
val sessionKey = chatState.currentSessionId ?: "new-session"
Box(modifier = Modifier.fillMaxSize()) {
- AnimatedContent(
- targetState = sessionKey,
+ Column(
modifier = Modifier
.fillMaxSize()
- .imePadding(),
- transitionSpec = {
- val enter = fadeIn(animationSpec = tween(220, easing = FastOutSlowInEasing)) +
- slideInVertically(
- animationSpec = tween(220, easing = FastOutSlowInEasing)
- ) { it / 14 }
- val exit = fadeOut(animationSpec = tween(180)) +
- slideOutVertically(animationSpec = tween(180)) { -it / 14 }
- enter.togetherWith(exit)
- },
- label = "session-change"
+ .imePadding()
) {
- Column(modifier = Modifier.fillMaxSize()) {
+ AnimatedContent(
+ targetState = sessionKey,
+ modifier = Modifier
+ .weight(1f),
+ transitionSpec = {
+ val enter = fadeIn(animationSpec = tween(220, easing = FastOutSlowInEasing)) +
+ slideInVertically(animationSpec = tween(320, easing = FastOutSlowInEasing)) {
+ it / 12
+ }
+ val exit = fadeOut(animationSpec = tween(220, easing = FastOutSlowInEasing)) +
+ slideOutVertically(animationSpec = tween(320, easing = FastOutSlowInEasing)) {
+ -it / 12
+ }
+ enter.togetherWith(exit)
+ },
+ label = "session-change"
+ ) {
MessageList(
modifier = Modifier
- .weight(1f)
+ .fillMaxSize()
.padding(
start = EnsuSpacing.pageHorizontal.dp,
end = EnsuSpacing.pageHorizontal.dp
@@ -209,42 +214,44 @@ fun ChatView(
downloadStatus = chatState.downloadStatus,
modelDownloadSizeBytes = chatState.modelDownloadSizeBytes,
branchSelections = chatState.branchSelections,
- imePadding = imePadding,
onEditMessage = onEditMessage,
onRetryMessage = onRetryMessage,
onBranchChange = onBranchChange,
onOpenAttachment = onOpenAttachment,
onStartDownload = onStartDownload
)
+ }
- val editingMessage = chatState.editingMessageId?.let { editingId ->
- chatState.messages.firstOrNull { it.id == editingId }
- }
+ val editingMessage = chatState.editingMessageId?.let { editingId ->
+ chatState.messages.firstOrNull { it.id == editingId }
+ }
- if (!showDownloadOnboarding) {
- 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,
- isAttachmentDownloadBlocked = chatState.isAttachmentDownloadBlocked,
- attachmentDownloadPercent = chatState.attachmentDownloadProgress,
- onMessageChange = onMessageChange,
- onSend = onSend,
- onStop = onStop,
- onAttachmentSelected = onAttachmentSelected,
- onRemoveAttachment = onRemoveAttachment,
- onCancelEdit = onCancelEdit,
- focusRequestId = focusRequestId
- )
- }
+ if (!showDownloadOnboarding) {
+ 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,
+ isAttachmentDownloadBlocked = chatState.isAttachmentDownloadBlocked,
+ attachmentDownloadPercent = chatState.attachmentDownloadProgress,
+ onMessageChange = onMessageChange,
+ onSend = {
+ focusManager.clearFocus()
+ onSend()
+ },
+ onStop = onStop,
+ onAttachmentSelected = onAttachmentSelected,
+ onRemoveAttachment = onRemoveAttachment,
+ onCancelEdit = onCancelEdit,
+ focusRequestId = focusRequestId
+ )
}
}
@@ -278,7 +285,6 @@ private fun MessageList(
downloadStatus: String?,
modelDownloadSizeBytes: Long?,
branchSelections: Map<String, Int>,
- imePadding: androidx.compose.ui.unit.Dp,
onEditMessage: (ChatMessage) -> Unit,
onRetryMessage: (ChatMessage) -> Unit,
onBranchChange: (String, Int) -> Unit,
@@ -305,23 +311,20 @@ private fun MessageList(
return
}
- val listState = rememberLazyListState()
+ val listState = rememberLazyListState(
+ initialFirstVisibleItemIndex = if (messages.isNotEmpty()) messages.size else 0
+ )
val haptic = rememberEnsuHaptics()
var autoScrollEnabled by remember { mutableStateOf(true) }
+ var isAutoScrolling by remember { mutableStateOf(false) }
var lastHapticLength by remember { mutableStateOf(0) }
var shouldJumpToBottomOnLoad by remember { mutableStateOf(true) }
- var lastIsAtBottom by remember { mutableStateOf(true) }
- var wasAtBottomBeforeIme by remember { mutableStateOf(false) }
+ var wasAtBottomBeforeResize by remember { mutableStateOf(true) }
+ var lastViewportHeight by remember { mutableStateOf(0) }
+ var lastUserMessageId by remember { mutableStateOf<String?>(null) }
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
- }
+ !listState.canScrollForward
}
}
@@ -332,23 +335,35 @@ private fun MessageList(
}
}
+ val lastMessage = messages.lastOrNull()
+ LaunchedEffect(lastMessage?.id) {
+ if (lastMessage == null) {
+ lastUserMessageId = null
+ return@LaunchedEffect
+ }
+ if (lastMessage.author == MessageAuthor.User && lastMessage.id != lastUserMessageId) {
+ lastUserMessageId = lastMessage.id
+ if (!listState.isScrollInProgress || isAtBottom) {
+ autoScrollEnabled = true
+ }
+ }
+ }
+
LaunchedEffect(messages.size) {
if (shouldJumpToBottomOnLoad && messages.isNotEmpty()) {
- listState.scrollToItem(messages.size)
+ if (listState.firstVisibleItemIndex != messages.size) {
+ listState.scrollToItem(messages.size)
+ }
shouldJumpToBottomOnLoad = false
}
}
- LaunchedEffect(listState.isScrollInProgress, isAtBottom) {
- if (listState.isScrollInProgress && !isAtBottom) {
+ LaunchedEffect(listState.isScrollInProgress, isAtBottom, isAutoScrolling) {
+ if (listState.isScrollInProgress && !isAtBottom && !isAutoScrolling) {
autoScrollEnabled = false
}
}
- LaunchedEffect(isAtBottom) {
- lastIsAtBottom = isAtBottom
- }
-
LaunchedEffect(isAtBottom, isGenerating) {
if (isGenerating && isAtBottom) {
autoScrollEnabled = true
@@ -368,27 +383,57 @@ private fun MessageList(
if (!autoScrollEnabled) return@LaunchedEffect
val targetIndex = messages.size
if (targetIndex >= 0) {
- if (isGenerating) {
- listState.animateScrollToItem(targetIndex)
- } else {
- listState.scrollToItem(targetIndex)
+ isAutoScrolling = true
+ try {
+ if (isGenerating) {
+ listState.animateScrollToItem(targetIndex)
+ } else {
+ listState.scrollToItem(targetIndex)
+ }
+ } finally {
+ isAutoScrolling = false
}
}
}
- LaunchedEffect(imePadding) {
- if (imePadding > 0.dp) {
- wasAtBottomBeforeIme = lastIsAtBottom
- if (wasAtBottomBeforeIme) {
- delay(120)
- val targetIndex = messages.size
- if (targetIndex >= 0) {
- listState.scrollToItem(targetIndex)
+ LaunchedEffect(listState) {
+ snapshotFlow {
+ val layoutInfo = listState.layoutInfo
+ val viewportHeight = layoutInfo.viewportEndOffset - layoutInfo.viewportStartOffset
+ viewportHeight to isAtBottom
+ }
+ .distinctUntilChanged()
+ .collect { (viewportHeight, atBottom) ->
+ if (viewportHeight <= 0) {
+ return@collect
+ }
+ if (lastViewportHeight != 0 && viewportHeight != lastViewportHeight) {
+ if (wasAtBottomBeforeResize) {
+ val totalItems = listState.layoutInfo.totalItemsCount
+ if (totalItems > 0) {
+ isAutoScrolling = true
+ try {
+ listState.scrollToItem(totalItems - 1)
+ } finally {
+ isAutoScrolling = false
+ }
+ }
+ } else if (viewportHeight < lastViewportHeight) {
+ val deltaPx = (lastViewportHeight - viewportHeight).toFloat()
+ if (deltaPx > 0f) {
+ autoScrollEnabled = false
+ isAutoScrolling = true
+ try {
+ listState.scrollBy(deltaPx)
+ } finally {
+ isAutoScrolling = false
+ }
+ }
+ }
}
+ lastViewportHeight = viewportHeight
+ wasAtBottomBeforeResize = atBottom
}
- } else {
- wasAtBottomBeforeIme = false
- }
}
LazyColumn(
@@ -857,7 +902,7 @@ private fun LoadingDotsText() {
Text(
text = phrase + ".".repeat(dotCount),
style = EnsuTypography.message,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textMuted()
)
}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/LaTeXView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/LaTeXView.kt
new file mode 100644
index 0000000000..74946f24c6
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/LaTeXView.kt
@@ -0,0 +1,49 @@
+package io.ente.ensu.chat
+
+import android.view.ViewGroup
+import androidx.compose.foundation.isSystemInDarkTheme
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.viewinterop.AndroidView
+import com.agog.mathdisplay.MTMathView
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuSpacing
+
+@Composable
+fun LaTeXView(latex: String, modifier: Modifier = Modifier) {
+ val isDark = isSystemInDarkTheme()
+ val textColor = if (isDark) EnsuColor.textPrimaryDark else EnsuColor.textPrimaryLight
+ val paddingPx = with(LocalDensity.current) { EnsuSpacing.cardPadding.dp.roundToPx() }
+
+ AndroidView(
+ factory = { context ->
+ MTMathView(context).apply {
+ layoutParams = ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT
+ )
+ setPadding(paddingPx, paddingPx, paddingPx, paddingPx)
+ MathViewCompat.setMathTextAlignment(
+ this,
+ MTMathView.MTTextAlignment.KMTTextAlignmentLeft
+ )
+ this.textColor = textColor.toArgb()
+ this.fontSize = 16f * context.resources.displayMetrics.density
+ this.latex = latex
+ }
+ },
+ update = { view ->
+ view.latex = latex
+ view.textColor = textColor.toArgb()
+ view.setPadding(paddingPx, paddingPx, paddingPx, paddingPx)
+ MathViewCompat.setMathTextAlignment(
+ view,
+ MTMathView.MTTextAlignment.KMTTextAlignmentLeft
+ )
+ },
+ modifier = modifier
+ )
+}
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.kt
index 7e61c4bd10..195ab092f1 100644
--- 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.kt
@@ -70,6 +70,9 @@ fun MarkdownView(markdown: String, enableSelection: Boolean = true) {
is MarkdownBlock.Code -> {
CodeBlockView(code = block.text)
}
+ is MarkdownBlock.Math -> {
+ MathBlockView(text = block.text)
+ }
is MarkdownBlock.ListItems -> {
Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp)) {
block.items.forEach { item ->
@@ -168,6 +171,21 @@ private fun CodeBlockView(code: String) {
}
}
+@Composable
+private fun MathBlockView(text: String) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.codeBlock.dp))
+ .border(1.dp, EnsuColor.border(), RoundedCornerShape(EnsuCornerRadius.codeBlock.dp))
+ ) {
+ LaTeXView(
+ latex = text,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+}
+
private fun headingStyle(level: Int): TextStyle {
val size = when (level) {
1 -> 20.sp
@@ -219,6 +237,7 @@ private sealed class MarkdownBlock {
data class Paragraph(val text: String) : MarkdownBlock()
data class BlockQuote(val text: String) : MarkdownBlock()
data class Code(val text: String) : MarkdownBlock()
+ data class Math(val text: String) : MarkdownBlock()
data class ListItems(val items: List<String>) : MarkdownBlock()
data object Divider : MarkdownBlock()
}
@@ -245,6 +264,8 @@ private object MarkdownParser {
val blocks = mutableListOf<MarkdownBlock>()
val paragraph = mutableListOf<String>()
val listItems = mutableListOf<String>()
+ val mathLines = mutableListOf<String>()
+ var mathEndDelimiter: String? = null
fun flushParagraph() {
if (paragraph.isNotEmpty()) {
@@ -260,8 +281,95 @@ private object MarkdownParser {
}
}
+ fun flushMath() {
+ if (mathEndDelimiter != null) {
+ if (mathLines.isNotEmpty()) {
+ blocks.add(MarkdownBlock.Math(mathLines.joinToString("\n")))
+ }
+ mathLines.clear()
+ mathEndDelimiter = null
+ }
+ }
+
+ fun startMath(endDelimiter: String, initialContent: String? = null) {
+ flushParagraph()
+ flushList()
+ mathEndDelimiter = endDelimiter
+ mathLines.clear()
+ if (!initialContent.isNullOrBlank()) {
+ mathLines.add(initialContent)
+ }
+ }
+
+ fun isBracketMathLine(trimmed: String): Boolean {
+ if (!trimmed.startsWith("[") || !trimmed.endsWith("]") || trimmed.length <= 2) {
+ return false
+ }
+ if (trimmed.contains("](") || trimmed.contains("]:")) {
+ return false
+ }
+ return true
+ }
+
for (line in lines) {
val trimmed = line.trim()
+
+ if (mathEndDelimiter != null) {
+ val endDelimiter = mathEndDelimiter!!
+ if (trimmed == endDelimiter) {
+ flushMath()
+ continue
+ }
+ if (endDelimiter != "]" && trimmed.endsWith(endDelimiter)) {
+ val content = trimmed.removeSuffix(endDelimiter).trimEnd()
+ if (content.isNotEmpty()) {
+ mathLines.add(content)
+ }
+ flushMath()
+ continue
+ }
+ mathLines.add(line)
+ continue
+ }
+
+ if (trimmed == "\\[" || trimmed == "$$" || trimmed == "[") {
+ val endDelimiter = when (trimmed) {
+ "\\[" -> "\\]"
+ "$$" -> "$$"
+ else -> "]"
+ }
+ startMath(endDelimiter)
+ continue
+ }
+
+ if (trimmed.startsWith("\\[")) {
+ val content = trimmed.removePrefix("\\[").trimStart()
+ if (content.endsWith("\\]")) {
+ val inner = content.removeSuffix("\\]").trim()
+ blocks.add(MarkdownBlock.Math(inner))
+ } else {
+ startMath("\\]", content)
+ }
+ continue
+ }
+
+ if (trimmed.startsWith("$$")) {
+ val content = trimmed.removePrefix("$$").trimStart()
+ if (content.endsWith("$$")) {
+ val inner = content.removeSuffix("$$").trim()
+ blocks.add(MarkdownBlock.Math(inner))
+ } else {
+ startMath("$$", content)
+ }
+ continue
+ }
+
+ if (isBracketMathLine(trimmed)) {
+ val inner = trimmed.removePrefix("[").removeSuffix("]").trim()
+ blocks.add(MarkdownBlock.Math(inner))
+ continue
+ }
+
if (trimmed.isEmpty()) {
flushParagraph()
flushList()
@@ -310,6 +418,7 @@ private object MarkdownParser {
flushParagraph()
flushList()
+ flushMath()
return blocks
}
}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MathViewCompat.java b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MathViewCompat.java
new file mode 100644
index 0000000000..b875eb78ae
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MathViewCompat.java
@@ -0,0 +1,12 @@
+package io.ente.ensu.chat;
+
+import com.agog.mathdisplay.MTMathView;
+
+final class MathViewCompat {
+ private MathViewCompat() {
+ }
+
+ static void setMathTextAlignment(MTMathView view, MTMathView.MTTextAlignment alignment) {
+ view.setTextAlignment(alignment);
+ }
+}
diff --git a/mobile/native/android/apps/ensu/crypto-auth-core/build.gradle.kts b/mobile/native/android/apps/ensu/crypto-auth-core/build.gradle.kts
index 47b4ade596..beb22d63d1 100644
--- a/mobile/native/android/apps/ensu/crypto-auth-core/build.gradle.kts
+++ b/mobile/native/android/apps/ensu/crypto-auth-core/build.gradle.kts
@@ -8,7 +8,7 @@ android {
compileSdk = 34
defaultConfig {
- minSdk = 23
+ minSdk = 24
}
sourceSets["main"].jniLibs.srcDir("src/main/jniLibs")
diff --git a/mobile/native/android/apps/ensu/data/build.gradle.kts b/mobile/native/android/apps/ensu/data/build.gradle.kts
index cf505fb46e..27673c539c 100644
--- a/mobile/native/android/apps/ensu/data/build.gradle.kts
+++ b/mobile/native/android/apps/ensu/data/build.gradle.kts
@@ -9,7 +9,7 @@ android {
compileSdk = 34
defaultConfig {
- minSdk = 23
+ minSdk = 24
}
compileOptions {
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.kt
index 69356d48ca..870c98dad8 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt
@@ -127,6 +127,7 @@ class InferenceRsProvider(
onToken: (String) -> Unit
): GenerationSummary = withContext(ioDispatcher) {
val context = contextHandle ?: throw IllegalStateException("Model context not loaded")
+ currentJobId = null
val mmprojPath = if (imageFiles.isEmpty()) null else mmprojPathFor(target)?.absolutePath
val request = GenerateChatRequest(
@@ -185,7 +186,12 @@ class InferenceRsProvider(
}
override fun stopGeneration() {
- currentJobId?.let { cancel(it) }
+ val jobId = currentJobId
+ if (jobId != null) {
+ cancel(jobId)
+ } else {
+ cancel(0)
+ }
}
override fun resetContext() {
@@ -428,8 +434,11 @@ class InferenceRsProvider(
onToken(event.text)
}
}
- is GenerateEvent.Done -> Unit
+ is GenerateEvent.Done -> {
+ currentJobId = null
+ }
is GenerateEvent.Error -> {
+ currentJobId = null
error = InferenceException.Message(event.message)
}
}
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.kt
index 7a14965d26..affa0f81c3 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/AppStore.kt
@@ -63,8 +63,8 @@ class AppStore(
private var pendingSyncSuccessHandler: (() -> Unit)? = null
private val sessionSummarySystemPrompt =
- "You are a title generator. Rewrite the message in 4-5 words for a chat title. Reply with only the title, no quotes."
- private val sessionSummaryMaxWords = 5
+ "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words, no quotes, no emojis, no trailing punctuation, and output only the title."
+ private val sessionSummaryMaxWords = 7
private val attachmentDownloads = mutableMapOf<String, AttachmentDownloadItem>()
private val attachmentDownloadQueue = ArrayDeque<String>()
@@ -287,6 +287,9 @@ class AppStore(
}
fun updateBranchSelection(messageId: String, selectedIndex: Int) {
+ if (_state.value.chat.isGenerating) {
+ stopGeneration()
+ }
val sessionId = _state.value.chat.currentSessionId ?: return
val messages = messageStore[sessionId].orEmpty()
val byId = messages.associateBy { it.id }
@@ -487,6 +490,9 @@ class AppStore(
}
fun retryAssistantMessage(messageId: String) {
+ if (_state.value.chat.isGenerating) {
+ stopGeneration()
+ }
val sessionId = _state.value.chat.currentSessionId ?: return
val message = messageStore[sessionId]?.firstOrNull { it.id == messageId } ?: return
if (message.author != MessageAuthor.Assistant) return
@@ -1485,6 +1491,6 @@ class AppStore(
private const val MEDIA_MARKER = "<__media__>"
private const val DEFAULT_TEMPERATURE = 0.7f
private const val SYSTEM_PROMPT =
- "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points."
+ "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points. For math equations, put \$\$ on its own line (never inline). Example:\n\$\$\nx^2 + y^2 = z^2\n\$\$"
}
}
diff --git a/mobile/native/android/apps/ensu/settings.gradle.kts b/mobile/native/android/apps/ensu/settings.gradle.kts
index 149638d66a..b7473a2b63 100644
--- a/mobile/native/android/apps/ensu/settings.gradle.kts
+++ b/mobile/native/android/apps/ensu/settings.gradle.kts
@@ -11,6 +11,7 @@ dependencyResolutionManagement {
repositories {
google()
mavenCentral()
+ maven { url = uri("https://jitpack.io") }
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj
index 8241902067..137a12bc7f 100644
--- a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj
+++ b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.pbxproj
@@ -14,6 +14,8 @@
DAB0F20E2F5E123400ABCD01 /* InferenceRS in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DAB0F20C2F5E123400ABCD01 /* InferenceRS */; };
DAF584672E61BB8300F8A08F /* ZIPFoundation in Frameworks */ = {isa = PBXBuildFile; productRef = DAF584662E61BB8300F8A08F /* ZIPFoundation */; };
DAF584682E61BB8300F8A08F /* ZIPFoundation in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DAF584662E61BB8300F8A08F /* ZIPFoundation */; };
+ DBA3E91C2F7A6B9000AA11BB /* iosMath in Frameworks */ = {isa = PBXBuildFile; productRef = DBA3E91B2F7A6B9000AA11BB /* iosMath */; };
+ DBA3E91D2F7A6B9000AA11BB /* iosMath in Frameworks (macOS) */ = {isa = PBXBuildFile; productRef = DBA3E91B2F7A6B9000AA11BB /* iosMath */; };
/* End PBXBuildFile section */
@@ -64,6 +66,7 @@
DACC3DC92E618D6A00DAF993 /* EnteNetwork in Frameworks */,
DAB0F20D2F5E123400ABCD01 /* InferenceRS in Frameworks */,
DAF584672E61BB8300F8A08F /* ZIPFoundation in Frameworks */,
+ DBA3E91C2F7A6B9000AA11BB /* iosMath in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -74,6 +77,7 @@
21BBA57867859DAD206D6A46 /* EnteNetwork in Frameworks (macOS) */,
DAB0F20E2F5E123400ABCD01 /* InferenceRS in Frameworks (macOS) */,
DAF584682E61BB8300F8A08F /* ZIPFoundation in Frameworks (macOS) */,
+ DBA3E91D2F7A6B9000AA11BB /* iosMath in Frameworks (macOS) */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -143,6 +147,7 @@
DACC3DC82E618D6A00DAF993 /* EnteNetwork */,
DAB0F20C2F5E123400ABCD01 /* InferenceRS */,
DAF584662E61BB8300F8A08F /* ZIPFoundation */,
+ DBA3E91B2F7A6B9000AA11BB /* iosMath */,
);
productName = ensu;
productReference = DA72BC612E5F87A000D128FF /* ensu.app */;
@@ -169,6 +174,7 @@
DACC3DC82E618D6A00DAF993 /* EnteNetwork */,
DAB0F20C2F5E123400ABCD01 /* InferenceRS */,
DAF584662E61BB8300F8A08F /* ZIPFoundation */,
+ DBA3E91B2F7A6B9000AA11BB /* iosMath */,
);
productName = Ensu;
productReference = 77E1DDDF900AB047CB554122 /* Ensu.app */;
@@ -253,6 +259,7 @@
DA72BCAA2E5F87B000D128FF /* XCRemoteSwiftPackageReference "swift-sodium" */,
DACC3DC62E618D5300DAF993 /* XCLocalSwiftPackageReference "../../Packages/EnteNetwork" */,
DAB0F20B2F5E123400ABCD01 /* XCLocalSwiftPackageReference "../../Packages/Rust" */,
+ DBA3E91A2F7A6B9000AA11BB /* XCLocalSwiftPackageReference "../../Packages/iosMath" */,
DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */,
);
preferredProjectObjectVersion = 77;
@@ -863,6 +870,10 @@
isa = XCLocalSwiftPackageReference;
relativePath = ../../Packages/Rust;
};
+ DBA3E91A2F7A6B9000AA11BB /* XCLocalSwiftPackageReference "../../Packages/iosMath" */ = {
+ isa = XCLocalSwiftPackageReference;
+ relativePath = ../../Packages/iosMath;
+ };
/* End XCLocalSwiftPackageReference section */
/* Begin XCRemoteSwiftPackageReference section */
@@ -898,6 +909,11 @@
isa = XCSwiftPackageProductDependency;
productName = InferenceRS;
};
+ DBA3E91B2F7A6B9000AA11BB /* iosMath */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = DBA3E91A2F7A6B9000AA11BB /* XCLocalSwiftPackageReference "../../Packages/iosMath" */;
+ productName = iosMath;
+ };
DAF584662E61BB8300F8A08F /* ZIPFoundation */ = {
isa = XCSwiftPackageProductDependency;
package = DAF584652E61BB6300F8A08F /* XCRemoteSwiftPackageReference "ZIPFoundation" */;
diff --git a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
index 8c1ef48ca0..e5a90711b8 100644
--- a/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
+++ b/mobile/native/darwin/Apps/ensu/ensu.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -1,13 +1,13 @@
{
- "originHash" : "26a3a7fb21ea1aa09bfc0b9697015a643d8a31bb0c43a8ffd1d764614b60d023",
+ "originHash" : "927afdbad387a731258b2c4708c30c1743c7d2af62c21111bcaf824d096568ae",
"pins" : [
{
"identity" : "swift-log",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-log.git",
"state" : {
- "revision" : "ce592ae52f982c847a4efc0dd881cc9eb32d29f2",
- "version" : "1.6.4"
+ "revision" : "2778fd4e5a12a8aaa30a3ee8285f4ce54c5f3181",
+ "version" : "1.9.1"
}
},
{
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/jedisct1/swift-sodium.git",
"state" : {
- "revision" : "4f9164a0a2c9a6a7ff53a2833d54a5c79c957342",
- "version" : "0.9.1"
+ "revision" : "e7e799cd1eaa4d0f6d3eab56832e7f4b377f4a4f",
+ "version" : "0.10.0"
}
},
{
@@ -33,8 +33,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/weichsel/ZIPFoundation.git",
"state" : {
- "revision" : "02b6abe5f6eef7e3cbd5f247c5cc24e246efcfe0",
- "version" : "0.9.19"
+ "revision" : "22787ffb59de99e5dc1fbfe80b19c97a904ad48d",
+ "version" : "0.9.20"
}
}
],
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift
index d31d42a63e..0d297eb68b 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift
@@ -236,8 +236,9 @@ struct ChatView: View {
insertion: .move(edge: .bottom).combined(with: .opacity),
removal: .move(edge: .top).combined(with: .opacity)
)
+ .animation(.easeInOut(duration: 0.32))
- ZStack(alignment: .top) {
+ ZStack(alignment: .bottom) {
let shouldShowDownloadOnboarding = !viewModel.isModelDownloaded
MessageListView(
@@ -269,70 +270,6 @@ struct ChatView: View {
}
)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
- .overlay(alignment: .bottom) {
- if viewModel.isModelDownloaded {
- let shouldAutoFocus = viewModel.isModelDownloaded
- && !viewModel.isDownloading
- && !viewModel.isGenerating
- && !didAutoFocusInput
- && !isDrawerOpen
- && !didDismissKeyboard
- && !showSettings
- && !showDeveloperSettings
-
- MessageInputView(
- text: $viewModel.draftText,
- attachments: $viewModel.draftAttachments,
- isGenerating: viewModel.isGenerating,
- isDownloading: viewModel.isDownloading,
- editingMessage: editingMessage,
- isProcessingAttachments: viewModel.isProcessingAttachments,
- isAttachmentDownloadBlocked: viewModel.isAttachmentDownloadBlocked,
- onSend: {
- viewModel.sendDraft()
- },
- onStop: {
- viewModel.stopGenerating()
- },
- onCancelEdit: {
- viewModel.cancelEditing()
- },
- onAddImage: { data, name in
- viewModel.addImageAttachment(data: data, fileName: name)
- },
- onAddDocument: { url in
- viewModel.addDocumentAttachment(url: url)
- },
- onRemoveAttachment: { attachment in
- viewModel.removeAttachment(attachment)
- },
- onUserFocus: {
- didDismissKeyboard = false
- },
- onDismissKeyboard: {
- didDismissKeyboard = true
- },
- isFocused: $isInputFocused
- )
- .onPreferenceChange(InputBarHeightKey.self) { newValue in
- inputBarHeight = newValue
- }
- .onAppear {
- if shouldAutoFocus {
- requestInputFocus()
- didAutoFocusInput = true
- didDismissKeyboard = false
- }
- }
- .onChange(of: shouldAutoFocus) { newValue in
- if newValue {
- requestInputFocus()
- didAutoFocusInput = true
- didDismissKeyboard = false
- }
- }
- }
- }
.id(sessionTransitionId)
.transition(sessionTransition)
.onAppear {
@@ -341,6 +278,73 @@ struct ChatView: View {
.onChange(of: viewModel.messages.count) { _ in
viewModel.autoStartModelDownloadIfNeeded()
}
+ .zIndex(0)
+
+ if viewModel.isModelDownloaded {
+ let shouldAutoFocus = viewModel.isModelDownloaded
+ && !viewModel.isDownloading
+ && !viewModel.isGenerating
+ && !didAutoFocusInput
+ && !isDrawerOpen
+ && !didDismissKeyboard
+ && !showSettings
+ && !showDeveloperSettings
+
+ MessageInputView(
+ text: $viewModel.draftText,
+ attachments: $viewModel.draftAttachments,
+ isGenerating: viewModel.isGenerating,
+ isDownloading: viewModel.isDownloading,
+ editingMessage: editingMessage,
+ isProcessingAttachments: viewModel.isProcessingAttachments,
+ isAttachmentDownloadBlocked: viewModel.isAttachmentDownloadBlocked,
+ onSend: {
+ didDismissKeyboard = true
+ isInputFocused = false
+ viewModel.sendDraft()
+ },
+ onStop: {
+ viewModel.stopGenerating()
+ },
+ onCancelEdit: {
+ viewModel.cancelEditing()
+ },
+ onAddImage: { data, name in
+ viewModel.addImageAttachment(data: data, fileName: name)
+ },
+ onAddDocument: { url in
+ viewModel.addDocumentAttachment(url: url)
+ },
+ onRemoveAttachment: { attachment in
+ viewModel.removeAttachment(attachment)
+ },
+ onUserFocus: {
+ didDismissKeyboard = false
+ },
+ onDismissKeyboard: {
+ didDismissKeyboard = true
+ },
+ isFocused: $isInputFocused
+ )
+ .onPreferenceChange(InputBarHeightKey.self) { newValue in
+ inputBarHeight = newValue
+ }
+ .onAppear {
+ if shouldAutoFocus {
+ requestInputFocus()
+ didAutoFocusInput = true
+ didDismissKeyboard = false
+ }
+ }
+ .onChange(of: shouldAutoFocus) { newValue in
+ if newValue {
+ requestInputFocus()
+ didAutoFocusInput = true
+ didDismissKeyboard = false
+ }
+ }
+ .zIndex(1)
+ }
if shouldShowDownloadOnboarding {
DownloadOnboardingView(
@@ -353,14 +357,16 @@ struct ChatView: View {
viewModel.startModelDownload(userInitiated: true)
}
)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
.background(EnsuColor.backgroundBase)
+ .zIndex(2)
}
}
- .animation(.easeOut(duration: 0.25), value: sessionTransitionId)
+ .animation(.easeInOut(duration: 0.32), value: sessionTransitionId)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
.onChange(of: viewModel.currentSessionId) { _ in
- withAnimation(.easeOut(duration: 0.25)) {
+ withAnimation(.easeInOut(duration: 0.32)) {
sessionTransitionId = UUID()
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
index 97d8c5e4a3..583a34eced 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
@@ -261,6 +261,10 @@ final class LlmChatDb {
func createSession(title: String) throws -> LlmChatSession {
LlmChatSession(uuid: UUID().uuidString, title: title, updatedAtUs: Int64(Date().timeIntervalSince1970 * 1_000_000))
}
+
+ func updateSessionTitle(uuid: String, title: String) throws {
+ _ = (uuid, title)
+ }
}
final class LlmChatSync {
@@ -417,11 +421,11 @@ struct DownloadToastState: Identifiable, Equatable {
@MainActor
final class ChatViewModel: ObservableObject {
private static let defaultTemperature: Float = 0.7
- private static let systemPrompt = "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points."
+ private static let systemPrompt = "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points. For math equations, put $$ on its own line (never inline). Example:\n$$\nx^2 + y^2 = z^2\n$$"
private static let sessionTitleMaxLength = 40
- private static let sessionSummaryMaxWords = 5
+ private static let sessionSummaryMaxWords = 7
private static let sessionSummaryStoreKey = "ensu.session_summaries"
- private static let sessionSummarySystemPrompt = "You are a title generator. Rewrite the message in 4-5 words for a chat title. Reply with only the title, no quotes."
+ private static let sessionSummarySystemPrompt = "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words, no quotes, no emojis, no trailing punctuation, and output only the title."
private let logger = EnsuLogging.shared.logger("ChatViewModel")
@@ -1035,6 +1039,9 @@ final class ChatViewModel: ObservableObject {
func retryAssistantResponse(_ message: ChatMessage) {
guard message.role == .assistant else { return }
+ if isGenerating {
+ stopGenerating()
+ }
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 {
@@ -1050,6 +1057,9 @@ final class ChatViewModel: ObservableObject {
}
func changeBranch(for message: ChatMessage, delta: Int) {
+ if isGenerating {
+ stopGenerating()
+ }
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__"
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swift
new file mode 100644
index 0000000000..7387ef3d8a
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swift
@@ -0,0 +1,57 @@
+#if canImport(EnteCore)
+import SwiftUI
+import iosMath
+
+struct LaTeXView: View {
+ let latex: String
+
+ @Environment(\.colorScheme) private var colorScheme
+
+ var body: some View {
+ MathLabelView(
+ latex: latex,
+ textColor: colorScheme == .dark
+ ? PlatformColor(hex: "#E8E4DF")
+ : PlatformColor(hex: "#1A1A1A")
+ )
+ }
+}
+
+#if os(iOS)
+private struct MathLabelView: UIViewRepresentable {
+ let latex: String
+ let textColor: PlatformColor
+
+ func makeUIView(context: Context) -> MTMathUILabel {
+ let label = MTMathUILabel()
+ label.fontSize = 16
+ label.textColor = textColor
+ label.latex = latex
+ return label
+ }
+
+ func updateUIView(_ label: MTMathUILabel, context: Context) {
+ label.latex = latex
+ label.textColor = textColor
+ }
+}
+#elseif os(macOS)
+private struct MathLabelView: NSViewRepresentable {
+ let latex: String
+ let textColor: PlatformColor
+
+ func makeNSView(context: Context) -> MTMathUILabel {
+ let label = MTMathUILabel()
+ label.fontSize = 16
+ label.textColor = textColor
+ label.latex = latex
+ return label
+ }
+
+ func updateNSView(_ label: MTMathUILabel, context: Context) {
+ label.latex = latex
+ label.textColor = textColor
+ }
+}
+#endif
+#endif
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift
index d56ab5abe3..f15445429a 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift
@@ -503,7 +503,7 @@ private struct LoadingDotsView: View {
let phase = Int(context.date.timeIntervalSinceReferenceDate * 2) % 3
Text(phrase + dots(for: phase))
.font(EnsuTypography.message)
- .foregroundStyle(EnsuColor.textPrimary)
+ .foregroundStyle(EnsuColor.textMuted)
}
}
@@ -812,6 +812,8 @@ private struct MarkdownView: View {
BlockQuoteView(text: text)
case .code(let code):
CodeBlockView(code: code)
+ case .math(let text):
+ MathBlockView(text: text)
case .list(let items):
VStack(alignment: .leading, spacing: 6) {
ForEach(items, id: \.self) { item in
@@ -858,6 +860,7 @@ private enum MarkdownBlock: Identifiable {
case paragraph(text: String)
case blockquote(text: String)
case code(text: String)
+ case math(text: String)
case list(items: [String])
case divider
@@ -888,6 +891,8 @@ private enum MarkdownParser {
var blocks: [MarkdownBlock] = []
var paragraph: [String] = []
var listItems: [String] = []
+ var mathLines: [String] = []
+ var mathEndDelimiter: String? = nil
func flushParagraph() {
if !paragraph.isEmpty {
@@ -903,9 +908,90 @@ private enum MarkdownParser {
}
}
+ func flushMath() {
+ if mathEndDelimiter != nil {
+ if !mathLines.isEmpty {
+ blocks.append(.math(text: mathLines.joined(separator: "\n")))
+ }
+ mathLines.removeAll()
+ mathEndDelimiter = nil
+ }
+ }
+
+ func startMath(endDelimiter: String, initialContent: String? = nil) {
+ flushParagraph()
+ flushList()
+ mathEndDelimiter = endDelimiter
+ mathLines.removeAll()
+ if let initial = initialContent?.trimmingCharacters(in: .whitespacesAndNewlines), !initial.isEmpty {
+ mathLines.append(initial)
+ }
+ }
+
+ func isBracketMathLine(_ trimmed: String) -> Bool {
+ guard trimmed.hasPrefix("["), trimmed.hasSuffix("]"), trimmed.count > 2 else {
+ return false
+ }
+ if trimmed.contains("](") || trimmed.contains("]:") {
+ return false
+ }
+ return true
+ }
+
for line in lines {
let trimmed = line.trimmingCharacters(in: .whitespaces)
+ if let endDelimiter = mathEndDelimiter {
+ if trimmed == endDelimiter {
+ flushMath()
+ continue
+ }
+ if endDelimiter != "]" && trimmed.hasSuffix(endDelimiter) {
+ let content = String(trimmed.dropLast(endDelimiter.count)).trimmingCharacters(in: .whitespaces)
+ if !content.isEmpty {
+ mathLines.append(content)
+ }
+ flushMath()
+ continue
+ }
+ mathLines.append(line)
+ continue
+ }
+
+ if trimmed == "\\[" || trimmed == "$$" || trimmed == "[" {
+ let endDelimiter = trimmed == "\\[" ? "\\]" : (trimmed == "$$" ? "$$" : "]")
+ startMath(endDelimiter: endDelimiter)
+ continue
+ }
+
+ if trimmed.hasPrefix("\\[") {
+ let content = String(trimmed.dropFirst(2)).trimmingCharacters(in: .whitespaces)
+ if content.hasSuffix("\\]") {
+ let inner = String(content.dropLast(2)).trimmingCharacters(in: .whitespaces)
+ blocks.append(.math(text: inner))
+ } else {
+ startMath(endDelimiter: "\\]", initialContent: content)
+ }
+ continue
+ }
+
+ if trimmed.hasPrefix("$$") {
+ let content = String(trimmed.dropFirst(2)).trimmingCharacters(in: .whitespaces)
+ if content.hasSuffix("$$") {
+ let inner = String(content.dropLast(2)).trimmingCharacters(in: .whitespaces)
+ blocks.append(.math(text: inner))
+ } else {
+ startMath(endDelimiter: "$$", initialContent: content)
+ }
+ continue
+ }
+
+ if isBracketMathLine(trimmed) {
+ let inner = String(trimmed.dropFirst().dropLast()).trimmingCharacters(in: .whitespaces)
+ blocks.append(.math(text: inner))
+ continue
+ }
+
if trimmed.isEmpty {
flushParagraph()
flushList()
@@ -956,6 +1042,7 @@ private enum MarkdownParser {
flushParagraph()
flushList()
+ flushMath()
return blocks
}
}
@@ -998,6 +1085,21 @@ private struct CodeBlockView: View {
}
}
+private struct MathBlockView: View {
+ let text: String
+
+ var body: some View {
+ LaTeXView(latex: text)
+ .frame(minHeight: 48)
+ .background(EnsuColor.fillFaint)
+ .overlay(
+ RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock)
+ .stroke(EnsuColor.border, lineWidth: 1)
+ )
+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock, style: .continuous))
+ }
+}
+
private struct BlockQuoteView: View {
let text: String
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift
index 4b364b6f30..87e94d7660 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift
@@ -142,6 +142,7 @@ final class InferenceRsProvider {
guard let context = contextHandle else {
throw NSError(domain: "InferenceRsProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "Model not loaded"])
}
+ currentJobId = nil
let nativeMessages = messages.map {
InferenceRS.ChatMessage(role: $0.role.roleString, content: $0.text)
@@ -177,8 +178,9 @@ final class InferenceRsProvider {
self.currentJobId = jobId
onToken(text)
case .done:
- break
+ self.currentJobId = nil
case let .error(_, message):
+ self.currentJobId = nil
lock.lock()
error = NSError(domain: "InferenceRsProvider", code: -2, userInfo: [NSLocalizedDescriptionKey: message])
lock.unlock()
@@ -213,6 +215,8 @@ final class InferenceRsProvider {
func stopGeneration() {
if let jobId = currentJobId {
cancel(jobId: jobId)
+ } else {
+ cancel(jobId: 0)
}
}
diff --git a/rust/inference_rs/src/api.rs b/rust/inference_rs/src/api.rs
index 37512dc62e..02875ecac5 100644
--- a/rust/inference_rs/src/api.rs
+++ b/rust/inference_rs/src/api.rs
@@ -44,6 +44,8 @@ static CANCEL_FLAGS: OnceLock<Mutex<HashMap<JobId, Arc<AtomicBool>>>> = OnceLock
static MTMD_LOG_BUFFER: OnceLock<Mutex<String>> = OnceLock::new();
static MTMD_LOG_HOOK: OnceLock<()> = OnceLock::new();
+const CANCEL_MESSAGE: &str = "Generation cancelled";
+
fn backend() -> Result<&'static LlamaBackend, String> {
match BACKEND.get_or_init(|| LlamaBackend::init().map_err(|err| err.to_string())) {
Ok(backend) => Ok(backend),
@@ -102,6 +104,19 @@ fn register_job() -> (JobId, Arc<AtomicBool>) {
(job_id, flag)
}
+fn cancel_all() {
+ for flag in cancel_flags().lock().values() {
+ flag.store(true, Ordering::Relaxed);
+ }
+}
+
+fn check_cancelled(cancel_flag: &AtomicBool) -> Result<(), String> {
+ if cancel_flag.load(Ordering::Relaxed) {
+ Err(CANCEL_MESSAGE.to_string())
+ } else {
+ Ok(())
+ }
+}
struct JobGuard(JobId);
@@ -826,6 +841,7 @@ pub fn generate_chat_stream(
let mut token_offset = 0usize;
let mut logits_index: i32 = 0;
while token_offset < prompt_tokens.len() {
+ check_cancelled(&cancel_flag)?;
let end = (token_offset + n_batch).min(prompt_tokens.len());
let chunk = &prompt_tokens[token_offset..end];
let mut batch = LlamaBatch::new(chunk.len(), 1);
@@ -899,6 +915,7 @@ pub fn generate_chat_stream(
let mut bitmaps = Vec::with_capacity(image_paths.len());
for image_path in &image_paths {
+ check_cancelled(&cancel_flag)?;
if !Path::new(image_path).exists() {
return Err(format!("Image file not found at {image_path}"));
}
@@ -944,10 +961,12 @@ pub fn generate_chat_stream(
}
ctx.clear_kv_cache();
+ check_cancelled(&cancel_flag)?;
let n_past = chunks
.eval_chunks(&mtmd_ctx, ctx, 0, 0, n_batch, true)
.map_err(|err| format_error("Failed to evaluate multimodal prompt", err))?;
+ check_cancelled(&cancel_flag)?;
let mut sampler = build_sampler(ctx.model, &sampler_request)?;
let mut prompt_tokens = Vec::new();
@@ -1059,6 +1078,7 @@ pub fn generate_stream(
let mut token_offset = 0usize;
let mut logits_index: i32 = 0;
while token_offset < prompt_tokens.len() {
+ check_cancelled(&cancel_flag)?;
let end = (token_offset + n_batch).min(prompt_tokens.len());
let chunk = &prompt_tokens[token_offset..end];
let mut batch = LlamaBatch::new(chunk.len(), 1);
@@ -1124,6 +1144,10 @@ pub fn generate_stream(
}
pub fn cancel(job_id: JobId) -> Result<(), String> {
+ if job_id <= 0 {
+ cancel_all();
+ return Ok(());
+ }
if let Some(flag) = cancel_flags().lock().get(&job_id) {
flag.store(true, Ordering::Relaxed);
}