Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat(ensu): support inline math in native chat

Prateek Sunalbe80bcec6b3d
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.kt
index a03e3c61da..e0ddac8257 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
@@ -150,8 +150,8 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
}
private fun fallbackEnsuDefaults() = io.ente.ensu.domain.model.EnsuDefaults(
- mobileSystemPromptBody = "You are Ensu, an AI assistant built by Ente. Current date and time: \$date\n\nUse 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\$\$\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.",
- desktopSystemPromptBody = "You are Ensu, an AI assistant built by Ente. Current date and time: \$date\n\nUse 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\$\$\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.",
+ mobileSystemPromptBody = "You are Ensu, an AI assistant built by Ente. Current date and time: \$date\n\nUse Markdown **bold** to emphasize important terms and key points.\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.",
+ desktopSystemPromptBody = "You are Ensu, an AI assistant built by Ente. Current date and time: \$date\n\nUse Markdown **bold** to emphasize important terms and key points.\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.",
systemPromptDatePlaceholder = "\$date",
sessionSummarySystemPrompt = "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title.",
mobileDefaultModel = io.ente.ensu.domain.model.EnsuModelPreset(
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
index e32b85d763..8f4aa97a1a 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/LaTeXView.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/LaTeXView.kt
@@ -41,6 +41,85 @@ fun LaTeXView(latex: String, modifier: Modifier = Modifier) {
)
}
+@Composable
+fun InlineLaTeXView(
+ latex: String,
+ modifier: Modifier = Modifier,
+ fontSizeSp: Float = 15f
+) {
+ val isDark = isSystemInDarkTheme()
+ val textColor = if (isDark) EnsuColor.textPrimaryDark else EnsuColor.textPrimaryLight
+ val fontSizePx = fontSizeSp * LocalDensity.current.density
+ val paddingPx = with(LocalDensity.current) { 2.dp.roundToPx() }
+
+ AndroidView(
+ factory = { context ->
+ InlineLatexContainerView(context).apply {
+ layoutParams = ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT
+ )
+ update(latex, textColor.toArgb(), fontSizePx, paddingPx)
+ }
+ },
+ update = { view ->
+ view.update(latex, textColor.toArgb(), fontSizePx, paddingPx)
+ },
+ modifier = modifier
+ )
+}
+
+private class InlineLatexContainerView(context: Context) : FrameLayout(context) {
+ private val mathView = MTMathView(context)
+ private val fallbackView = TextView(context)
+
+ init {
+ addView(
+ mathView,
+ LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT
+ )
+ )
+ addView(
+ fallbackView,
+ LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT
+ )
+ )
+ fallbackView.visibility = View.GONE
+ }
+
+ fun update(latex: String, textColor: Int, fontSizePx: Float, paddingPx: Int) {
+ val sanitizedLatex = latex.replace("\\boxed", "")
+
+ fallbackView.text = latex
+ fallbackView.setTextColor(textColor)
+ fallbackView.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizePx)
+ fallbackView.setPadding(paddingPx, paddingPx, paddingPx, paddingPx)
+
+ mathView.textColor = textColor
+ mathView.fontSize = fontSizePx
+ mathView.setPadding(paddingPx, paddingPx, paddingPx, paddingPx)
+ MathViewCompat.setMathTextAlignment(
+ mathView,
+ MTMathView.MTTextAlignment.KMTTextAlignmentLeft
+ )
+ MathViewCompat.setDisplayErrorInline(mathView, false)
+
+ val shouldRender = latexLooksRenderable(sanitizedLatex)
+ if (shouldRender) {
+ mathView.latex = sanitizedLatex
+ }
+
+ val error = if (shouldRender) MathViewCompat.getError(mathView) else null
+ val useFallback = !shouldRender || !error.isNullOrBlank()
+ mathView.visibility = if (useFallback) View.GONE else View.VISIBLE
+ fallbackView.visibility = if (useFallback) View.VISIBLE else View.GONE
+ }
+}
+
private class LatexContainerView(context: Context) : FrameLayout(context) {
private val mathView = MTMathView(context)
private val fallbackView = TextView(context)
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 8158668426..5664c89aaa 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
@@ -6,6 +6,8 @@ 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.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
@@ -32,6 +34,7 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
@@ -58,17 +61,19 @@ fun MarkdownView(
val appendCursor = trailingCursor && index == blocks.lastIndex
when (block) {
is MarkdownBlock.Heading -> {
- Text(
- text = markdownAnnotatedText(block.text, appendCursor),
+ InlineMarkdownText(
+ text = block.text,
style = headingStyle(block.level),
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
+ appendCursor = appendCursor
)
}
is MarkdownBlock.Paragraph -> {
- Text(
- text = markdownAnnotatedText(block.text, appendCursor),
+ InlineMarkdownText(
+ text = block.text,
style = EnsuTypography.message,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
+ appendCursor = appendCursor
)
}
is MarkdownBlock.BlockQuote -> {
@@ -100,10 +105,11 @@ fun MarkdownView(
style = EnsuTypography.message,
color = EnsuColor.textPrimary()
)
- Text(
- text = markdownAnnotatedText(item, itemCursor),
+ InlineMarkdownText(
+ text = item,
style = EnsuTypography.message,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
+ appendCursor = itemCursor
)
}
}
@@ -147,10 +153,11 @@ private fun BlockQuoteView(text: String, appendCursor: Boolean = false) {
.background(EnsuColor.border())
)
Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
- Text(
- text = markdownAnnotatedText(text, appendCursor),
+ InlineMarkdownText(
+ text = text,
style = EnsuTypography.message,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
+ appendCursor = appendCursor
)
}
}
@@ -231,8 +238,17 @@ private fun headingStyle(level: Int): TextStyle {
return EnsuTypography.message.copy(fontSize = size, fontWeight = FontWeight.SemiBold, lineHeight = (size.value + 6).sp)
}
-private fun markdownAnnotatedText(text: String, appendCursor: Boolean = false): AnnotatedString {
- val pattern = Regex("(\\*\\*[^*]+\\*\\*|`[^`]+`|\\*[^*]+\\*)")
+private data class InlineLinkMatch(
+ val label: String,
+ val endIndexExclusive: Int
+)
+
+private fun markdownAnnotatedText(
+ text: String,
+ linkColor: androidx.compose.ui.graphics.Color,
+ appendCursor: Boolean = false
+): AnnotatedString {
+ val pattern = Regex("""(\[[^\]\n]+\]\([^)]+\)|~~[^~\n]+~~|\*\*[^*\n]+\*\*|`[^`\n]+`|\*[^*\n]+\*)""")
val codeFamily = EnsuTypography.code.fontFamily
return buildAnnotatedString {
var currentIndex = 0
@@ -244,6 +260,26 @@ private fun markdownAnnotatedText(text: String, appendCursor: Boolean = false):
}
val token = match.value
when {
+ token.startsWith("[") -> {
+ val labelEnd = token.indexOf(']')
+ if (labelEnd > 1) {
+ withStyle(
+ SpanStyle(
+ color = linkColor,
+ textDecoration = TextDecoration.Underline
+ )
+ ) {
+ append(token.substring(1, labelEnd))
+ }
+ } else {
+ append(token)
+ }
+ }
+ token.startsWith("~~") -> {
+ withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) {
+ append(token.removePrefix("~~").removeSuffix("~~"))
+ }
+ }
token.startsWith("**") -> {
withStyle(SpanStyle(fontWeight = FontWeight.SemiBold)) {
append(token.removePrefix("**").removeSuffix("**"))
@@ -271,6 +307,387 @@ private fun markdownAnnotatedText(text: String, appendCursor: Boolean = false):
}
}
+private enum class InlineMarkdownStyle {
+ Normal,
+ Bold,
+ Italic,
+ Code,
+ Strikethrough,
+ Link
+}
+
+private sealed class InlineMarkdownSegment {
+ data class Text(val text: String, val style: InlineMarkdownStyle) : InlineMarkdownSegment()
+ data class Math(val latex: String) : InlineMarkdownSegment()
+}
+
+private data class InlineMathMatch(
+ val latex: String,
+ val endIndexExclusive: Int
+)
+
+private val mathTokenPattern = Regex(
+ """(?<!\\)\$(?!\$)(?:[^$\n\\]|\\.)+?(?<!\\)\$(?!\$)|\\\((?:[^\n\\]|\\.)+?\\\)"""
+)
+
+private fun parseInlineMarkdownSegments(text: String): List<InlineMarkdownSegment> {
+ val segments = mutableListOf<InlineMarkdownSegment>()
+ val buffer = StringBuilder()
+ var currentStyle = InlineMarkdownStyle.Normal
+ var index = 0
+
+ fun flushBuffer() {
+ if (buffer.isNotEmpty()) {
+ segments.add(
+ InlineMarkdownSegment.Text(
+ text = buffer.toString(),
+ style = currentStyle
+ )
+ )
+ buffer.clear()
+ }
+ }
+
+ while (index < text.length) {
+ val mathMatch = findInlineMathMatch(text, index)
+ if (mathMatch != null) {
+ flushBuffer()
+ segments.add(InlineMarkdownSegment.Math(latex = mathMatch.latex))
+ index = mathMatch.endIndexExclusive
+ continue
+ }
+
+ when (currentStyle) {
+ InlineMarkdownStyle.Link -> {
+ buffer.append(text[index])
+ index += 1
+ }
+ InlineMarkdownStyle.Code -> {
+ if (text[index] == '`') {
+ flushBuffer()
+ currentStyle = InlineMarkdownStyle.Normal
+ index += 1
+ } else {
+ buffer.append(text[index])
+ index += 1
+ }
+ }
+ InlineMarkdownStyle.Bold -> {
+ if (text.startsWith("**", index)) {
+ flushBuffer()
+ currentStyle = InlineMarkdownStyle.Normal
+ index += 2
+ } else {
+ buffer.append(text[index])
+ index += 1
+ }
+ }
+ InlineMarkdownStyle.Italic -> {
+ if (text[index] == '*' && !text.startsWith("**", index)) {
+ flushBuffer()
+ currentStyle = InlineMarkdownStyle.Normal
+ index += 1
+ } else {
+ buffer.append(text[index])
+ index += 1
+ }
+ }
+ InlineMarkdownStyle.Strikethrough -> {
+ if (text.startsWith("~~", index)) {
+ flushBuffer()
+ currentStyle = InlineMarkdownStyle.Normal
+ index += 2
+ } else {
+ buffer.append(text[index])
+ index += 1
+ }
+ }
+ InlineMarkdownStyle.Normal -> {
+ val linkMatch = findInlineLinkMatch(text, index)
+ when {
+ linkMatch != null -> {
+ flushBuffer()
+ segments.add(
+ InlineMarkdownSegment.Text(
+ text = linkMatch.label,
+ style = InlineMarkdownStyle.Link
+ )
+ )
+ index = linkMatch.endIndexExclusive
+ }
+ text.startsWith("~~", index) && hasClosingDelimiter(text, index + 2, "~~") -> {
+ flushBuffer()
+ currentStyle = InlineMarkdownStyle.Strikethrough
+ index += 2
+ }
+ text.startsWith("**", index) && hasClosingDelimiter(text, index + 2, "**") -> {
+ flushBuffer()
+ currentStyle = InlineMarkdownStyle.Bold
+ index += 2
+ }
+ text[index] == '*' &&
+ !text.startsWith("**", index) &&
+ hasClosingSingleAsterisk(text, index + 1) -> {
+ flushBuffer()
+ currentStyle = InlineMarkdownStyle.Italic
+ index += 1
+ }
+ text[index] == '`' && hasClosingDelimiter(text, index + 1, "`") -> {
+ flushBuffer()
+ currentStyle = InlineMarkdownStyle.Code
+ index += 1
+ }
+ else -> {
+ buffer.append(text[index])
+ index += 1
+ }
+ }
+ }
+ }
+ }
+
+ flushBuffer()
+
+ return segments.filterNot { segment ->
+ segment is InlineMarkdownSegment.Text && segment.text.isEmpty()
+ }
+}
+
+private fun findInlineMathMatch(text: String, startIndex: Int): InlineMathMatch? {
+ if (startIndex >= text.length) {
+ return null
+ }
+
+ if (text.startsWith("\\(", startIndex)) {
+ var index = startIndex + 2
+ while (index < text.length) {
+ if (text[index] == '\n') {
+ return null
+ }
+ if (text[index] == '\\') {
+ if (index + 1 >= text.length) {
+ return null
+ }
+ if (text[index + 1] == ')') {
+ return InlineMathMatch(
+ latex = text.substring(startIndex + 2, index),
+ endIndexExclusive = index + 2
+ )
+ }
+ index += 2
+ continue
+ }
+ index += 1
+ }
+ return null
+ }
+
+ if (text[startIndex] != '$' || (startIndex > 0 && text[startIndex - 1] == '\\')) {
+ return null
+ }
+ if (startIndex + 1 < text.length && text[startIndex + 1] == '$') {
+ return null
+ }
+
+ var index = startIndex + 1
+ while (index < text.length) {
+ if (text[index] == '\n') {
+ return null
+ }
+ if (
+ text[index] == '$' &&
+ text[index - 1] != '\\' &&
+ (index + 1 >= text.length || text[index + 1] != '$')
+ ) {
+ if (index == startIndex + 1) {
+ return null
+ }
+ return InlineMathMatch(
+ latex = text.substring(startIndex + 1, index),
+ endIndexExclusive = index + 1
+ )
+ }
+ index += 1
+ }
+
+ return null
+}
+
+private fun findInlineLinkMatch(text: String, startIndex: Int): InlineLinkMatch? {
+ if (startIndex >= text.length || text[startIndex] != '[') {
+ return null
+ }
+
+ var labelEnd = -1
+ var index = startIndex + 1
+ while (index < text.length) {
+ val char = text[index]
+ if (char == '\n') {
+ return null
+ }
+ if (char == ']' && text.getOrNull(index + 1) == '(') {
+ labelEnd = index
+ break
+ }
+ index += 1
+ }
+
+ if (labelEnd <= startIndex + 1) {
+ return null
+ }
+
+ val label = text.substring(startIndex + 1, labelEnd)
+ if (mathTokenPattern.containsMatchIn(label)) {
+ return null
+ }
+
+ val urlStart = labelEnd + 2
+ index = urlStart
+ while (index < text.length) {
+ val char = text[index]
+ if (char == '\n') {
+ return null
+ }
+ if (char == ')') {
+ return InlineLinkMatch(
+ label = label,
+ endIndexExclusive = index + 1
+ )
+ }
+ index += 1
+ }
+
+ return null
+}
+
+private fun hasClosingDelimiter(text: String, startIndex: Int, delimiter: String): Boolean {
+ var index = startIndex
+ while (index < text.length) {
+ if (text[index] == '\n') {
+ return false
+ }
+ if (text.startsWith(delimiter, index)) {
+ return true
+ }
+ index += 1
+ }
+ return false
+}
+
+private fun hasClosingSingleAsterisk(text: String, startIndex: Int): Boolean {
+ var index = startIndex
+ while (index < text.length) {
+ if (text[index] == '\n') {
+ return false
+ }
+ if (text[index] == '*' && !text.startsWith("**", index)) {
+ return true
+ }
+ index += 1
+ }
+ return false
+}
+
+private fun hasInlineMath(text: String): Boolean =
+ mathTokenPattern.containsMatchIn(text)
+
+private fun splitTextChunks(text: String): List<String> =
+ Regex("""\s+|\S+\s*""").findAll(text).map { it.value }.toList()
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun InlineMarkdownText(
+ text: String,
+ style: TextStyle,
+ color: androidx.compose.ui.graphics.Color,
+ appendCursor: Boolean = false
+) {
+ if (!hasInlineMath(text)) {
+ Text(
+ text = markdownAnnotatedText(
+ text = text,
+ linkColor = EnsuColor.accent(),
+ appendCursor = appendCursor
+ ),
+ style = style,
+ color = color
+ )
+ return
+ }
+
+ val lines = text.split("\n")
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ lines.forEachIndexed { lineIndex, line ->
+ val isLastLine = lineIndex == lines.lastIndex
+ val segments = parseInlineMarkdownSegments(line)
+ val cursorInline = appendCursor &&
+ isLastLine &&
+ segments.lastOrNull() is InlineMarkdownSegment.Text
+ val cursorStandalone = appendCursor &&
+ isLastLine &&
+ segments.lastOrNull() !is InlineMarkdownSegment.Text
+
+ FlowRow(
+ horizontalArrangement = Arrangement.spacedBy(0.dp),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ segments.forEachIndexed { segmentIndex, segment ->
+ when (segment) {
+ is InlineMarkdownSegment.Math -> {
+ InlineLaTeXView(
+ latex = segment.latex,
+ modifier = Modifier.padding(top = 2.dp),
+ fontSizeSp = style.fontSize.value
+ )
+ }
+ is InlineMarkdownSegment.Text -> {
+ val chunks = splitTextChunks(segment.text)
+ chunks.forEachIndexed { chunkIndex, chunk ->
+ val isLastChunk =
+ segmentIndex == segments.lastIndex && chunkIndex == chunks.lastIndex
+ Text(
+ text = if (cursorInline && isLastChunk) "$chunk▍" else chunk,
+ style = styleForInlineSegment(style, segment.style),
+ color = colorForInlineSegment(color, segment.style)
+ )
+ }
+ }
+ }
+ }
+
+ if (cursorStandalone) {
+ Text(
+ text = "▍",
+ style = style,
+ color = color
+ )
+ }
+ }
+ }
+ }
+}
+
+private fun styleForInlineSegment(
+ baseStyle: TextStyle,
+ inlineStyle: InlineMarkdownStyle
+): TextStyle = when (inlineStyle) {
+ InlineMarkdownStyle.Normal -> baseStyle
+ InlineMarkdownStyle.Bold -> baseStyle.copy(fontWeight = FontWeight.SemiBold)
+ InlineMarkdownStyle.Italic -> baseStyle.copy(fontStyle = FontStyle.Italic)
+ InlineMarkdownStyle.Code -> baseStyle.copy(fontFamily = EnsuTypography.code.fontFamily)
+ InlineMarkdownStyle.Strikethrough -> baseStyle.copy(textDecoration = TextDecoration.LineThrough)
+ InlineMarkdownStyle.Link -> baseStyle.copy(textDecoration = TextDecoration.Underline)
+}
+
+@Composable
+private fun colorForInlineSegment(
+ baseColor: androidx.compose.ui.graphics.Color,
+ inlineStyle: InlineMarkdownStyle
+): androidx.compose.ui.graphics.Color = when (inlineStyle) {
+ InlineMarkdownStyle.Link -> EnsuColor.accent()
+ else -> baseColor
+}
+
private sealed class MarkdownBlock {
data class Heading(val level: Int, val text: String) : MarkdownBlock()
data class Paragraph(val text: String) : MarkdownBlock()
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt
index d2a7ed34a0..d23d92f1b6 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ModelSettingsActions.kt
@@ -336,7 +336,7 @@ internal class ModelSettingsActions(
}
val contextLength = settings.contextLength.toIntOrNull()
val maxTokens = settings.maxTokens.toIntOrNull()?.takeIf { it > 0 }
- val id = if (useCustom) "custom:${url.hashCode()}" else "default"
+ val id = if (useCustom) "custom:${url.hashCode()}" else "default:${url.hashCode()}"
return LlmModelTarget(
id = id,
diff --git a/mobile/native/darwin/Apps/ensu/build.sh b/mobile/native/darwin/Apps/ensu/build.sh
index b1fc4337c8..16bd6d8a8f 100755
--- a/mobile/native/darwin/Apps/ensu/build.sh
+++ b/mobile/native/darwin/Apps/ensu/build.sh
@@ -19,6 +19,22 @@ if [[ "$XCODE_VERSION" == 26* ]]; then
XCODE_EXTRA_ARGS+=(SWIFT_ENABLE_EXPLICIT_MODULES=NO)
fi
+# Run xcodebuild, capturing output to a temp log to avoid SIGPIPE with pipefail.
+# On failure, prints the last 30 lines of the log for diagnostics.
+run_xcodebuild() {
+ local log
+ log="$(mktemp)"
+ if xcodebuild "$@" > "$log" 2>&1; then
+ rm -f "$log"
+ else
+ local rc=$?
+ echo "xcodebuild failed (exit $rc). Last 30 lines:" >&2
+ tail -30 "$log" >&2
+ rm -f "$log"
+ exit $rc
+ fi
+}
+
usage() {
cat <<'EOF'
Build Ensu Apple app.
@@ -186,7 +202,7 @@ fi
build_archive() {
mkdir -p "$(dirname "$ARCHIVE_PATH")"
echo "==> Building Release archive"
- xcodebuild \
+ run_xcodebuild \
-project "$PROJECT" \
-scheme "$SCHEME" \
-configuration Release \
@@ -212,7 +228,7 @@ case "$MODE" in
fi
echo "==> Building Debug for simulator (id=$DESTINATION_ID)"
- xcodebuild \
+ run_xcodebuild \
-project "$PROJECT" \
-scheme "$SCHEME" \
-configuration Debug \
@@ -231,7 +247,7 @@ case "$MODE" in
fi
echo "==> Building Debug for device (id=$DESTINATION_ID)"
- xcodebuild \
+ run_xcodebuild \
-project "$PROJECT" \
-scheme "$SCHEME" \
-configuration Debug \
@@ -253,7 +269,7 @@ case "$MODE" in
mkdir -p "$EXPORT_PATH"
echo "==> Exporting IPA"
- xcodebuild \
+ run_xcodebuild \
-exportArchive \
-archivePath "$ARCHIVE_PATH" \
-exportPath "$EXPORT_PATH" \
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swift
index 1a607d5515..51d331692c 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/LaTeXView.swift
@@ -14,7 +14,29 @@ struct LaTeXView: View {
rawLatex: latex,
textColor: colorScheme == .dark
? PlatformColor(hex: "#E8E4DF")
- : PlatformColor(hex: "#1A1A1A")
+ : PlatformColor(hex: "#1A1A1A"),
+ fontSize: 16,
+ isInline: false
+ )
+ }
+}
+
+struct InlineLaTeXView: View {
+ let latex: String
+ let fontSize: CGFloat
+
+ @Environment(\.colorScheme) private var colorScheme
+
+ var body: some View {
+ let sanitizedLatex = latex.replacingOccurrences(of: "\\boxed", with: "")
+ MathLabelView(
+ latex: sanitizedLatex,
+ rawLatex: latex,
+ textColor: colorScheme == .dark
+ ? PlatformColor(hex: "#E8E4DF")
+ : PlatformColor(hex: "#1A1A1A"),
+ fontSize: fontSize,
+ isInline: true
)
}
}
@@ -24,55 +46,76 @@ private struct MathLabelView: UIViewRepresentable {
let latex: String
let rawLatex: String
let textColor: PlatformColor
+ let fontSize: CGFloat
+ let isInline: Bool
func makeUIView(context: Context) -> MathLabelContainerView {
MathLabelContainerView()
}
func updateUIView(_ view: MathLabelContainerView, context: Context) {
- view.update(latex: latex, rawLatex: rawLatex, textColor: textColor)
+ view.update(latex: latex, rawLatex: rawLatex, textColor: textColor, fontSize: fontSize, isInline: isInline)
}
}
private final class MathLabelContainerView: UIView {
private let mathLabel = MTMathUILabel()
private let fallbackLabel = UILabel()
- private let insets = UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)
+ private var currentInsets = UIEdgeInsets.zero
override init(frame: CGRect) {
super.init(frame: frame)
-
- mathLabel.translatesAutoresizingMaskIntoConstraints = false
- fallbackLabel.translatesAutoresizingMaskIntoConstraints = false
fallbackLabel.numberOfLines = 0
-
addSubview(mathLabel)
addSubview(fallbackLabel)
-
- NSLayoutConstraint.activate([
- mathLabel.topAnchor.constraint(equalTo: topAnchor, constant: insets.top),
- mathLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: insets.left),
- mathLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -insets.right),
- mathLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -insets.bottom),
- fallbackLabel.topAnchor.constraint(equalTo: topAnchor, constant: insets.top),
- fallbackLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: insets.left),
- fallbackLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -insets.right),
- fallbackLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -insets.bottom),
- ])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
- func update(latex: String, rawLatex: String, textColor: PlatformColor) {
- mathLabel.fontSize = 16
+ override var intrinsicContentSize: CGSize {
+ if !mathLabel.isHidden {
+ let childSize = mathLabel.intrinsicContentSize
+ return CGSize(
+ width: childSize.width + currentInsets.left + currentInsets.right,
+ height: childSize.height + currentInsets.top + currentInsets.bottom
+ )
+ }
+ let maxLabelWidth = fallbackLabel.preferredMaxLayoutWidth > 0
+ ? fallbackLabel.preferredMaxLayoutWidth
+ : CGFloat.greatestFiniteMagnitude
+ let labelSize = fallbackLabel.sizeThatFits(CGSize(width: maxLabelWidth, height: .greatestFiniteMagnitude))
+ return CGSize(
+ width: labelSize.width + currentInsets.left + currentInsets.right,
+ height: labelSize.height + currentInsets.top + currentInsets.bottom
+ )
+ }
+
+ override func layoutSubviews() {
+ super.layoutSubviews()
+ let insetBounds = bounds.inset(by: currentInsets)
+ mathLabel.frame = insetBounds
+ fallbackLabel.frame = insetBounds
+ let maxWidth = max(0, insetBounds.width)
+ if fallbackLabel.preferredMaxLayoutWidth != maxWidth {
+ fallbackLabel.preferredMaxLayoutWidth = maxWidth
+ invalidateIntrinsicContentSize()
+ }
+ }
+
+ func update(latex: String, rawLatex: String, textColor: PlatformColor, fontSize: CGFloat, isInline: Bool) {
+ currentInsets = isInline
+ ? UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
+ : UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)
+
+ mathLabel.fontSize = fontSize
mathLabel.textColor = textColor
- mathLabel.contentInsets = insets
+ mathLabel.contentInsets = isInline ? .zero : currentInsets
mathLabel.displayErrorInline = false
mathLabel.latex = latex
- fallbackLabel.font = UIFont.systemFont(ofSize: 16)
+ fallbackLabel.font = UIFont.systemFont(ofSize: fontSize)
fallbackLabel.textColor = textColor
fallbackLabel.text = rawLatex
@@ -80,6 +123,8 @@ private final class MathLabelContainerView: UIView {
let shouldFallback = trimmedLatex.isEmpty || mathLabel.error != nil
mathLabel.isHidden = shouldFallback
fallbackLabel.isHidden = !shouldFallback
+
+ invalidateIntrinsicContentSize()
}
}
@@ -88,56 +133,84 @@ private struct MathLabelView: NSViewRepresentable {
let latex: String
let rawLatex: String
let textColor: PlatformColor
+ let fontSize: CGFloat
+ let isInline: Bool
func makeNSView(context: Context) -> MathLabelContainerView {
MathLabelContainerView()
}
func updateNSView(_ view: MathLabelContainerView, context: Context) {
- view.update(latex: latex, rawLatex: rawLatex, textColor: textColor)
+ view.update(latex: latex, rawLatex: rawLatex, textColor: textColor, fontSize: fontSize, isInline: isInline)
}
}
private final class MathLabelContainerView: NSView {
private let mathLabel = MTMathUILabel()
private let fallbackLabel = NSTextField(labelWithString: "")
- private let insets = NSEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)
+ private var currentInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
-
- mathLabel.translatesAutoresizingMaskIntoConstraints = false
- fallbackLabel.translatesAutoresizingMaskIntoConstraints = false
fallbackLabel.lineBreakMode = .byWordWrapping
fallbackLabel.maximumNumberOfLines = 0
-
addSubview(mathLabel)
addSubview(fallbackLabel)
-
- NSLayoutConstraint.activate([
- mathLabel.topAnchor.constraint(equalTo: topAnchor, constant: insets.top),
- mathLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: insets.left),
- mathLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -insets.right),
- mathLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -insets.bottom),
- fallbackLabel.topAnchor.constraint(equalTo: topAnchor, constant: insets.top),
- fallbackLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: insets.left),
- fallbackLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -insets.right),
- fallbackLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -insets.bottom),
- ])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
- func update(latex: String, rawLatex: String, textColor: PlatformColor) {
- mathLabel.fontSize = 16
+ override var intrinsicContentSize: NSSize {
+ if !mathLabel.isHidden {
+ let childSize = mathLabel.intrinsicContentSize
+ return NSSize(
+ width: childSize.width + currentInsets.left + currentInsets.right,
+ height: childSize.height + currentInsets.top + currentInsets.bottom
+ )
+ }
+ let maxWidth = fallbackLabel.preferredMaxLayoutWidth > 0
+ ? fallbackLabel.preferredMaxLayoutWidth
+ : CGFloat.greatestFiniteMagnitude
+ let labelSize = fallbackLabel.sizeThatFits(NSSize(width: maxWidth, height: .greatestFiniteMagnitude))
+ return NSSize(
+ width: labelSize.width + currentInsets.left + currentInsets.right,
+ height: labelSize.height + currentInsets.top + currentInsets.bottom
+ )
+ }
+
+ override func layout() {
+ super.layout()
+ let insetRect = NSRect(
+ x: currentInsets.left,
+ y: currentInsets.bottom,
+ width: max(0, bounds.width - currentInsets.left - currentInsets.right),
+ height: max(0, bounds.height - currentInsets.top - currentInsets.bottom)
+ )
+ mathLabel.frame = insetRect
+ fallbackLabel.frame = insetRect
+ let maxWidth = max(0, insetRect.width)
+ if fallbackLabel.preferredMaxLayoutWidth != maxWidth {
+ fallbackLabel.preferredMaxLayoutWidth = maxWidth
+ invalidateIntrinsicContentSize()
+ }
+ }
+
+ func update(latex: String, rawLatex: String, textColor: PlatformColor, fontSize: CGFloat, isInline: Bool) {
+ currentInsets = isInline
+ ? NSEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
+ : NSEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)
+
+ let nsInsets = isInline ? NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) : currentInsets
+
+ mathLabel.fontSize = fontSize
mathLabel.textColor = textColor
- mathLabel.contentInsets = insets
+ mathLabel.contentInsets = nsInsets
mathLabel.displayErrorInline = false
mathLabel.latex = latex
- fallbackLabel.font = NSFont.systemFont(ofSize: 16)
+ fallbackLabel.font = NSFont.systemFont(ofSize: fontSize)
fallbackLabel.textColor = textColor
fallbackLabel.stringValue = rawLatex
@@ -145,6 +218,8 @@ private final class MathLabelContainerView: NSView {
let shouldFallback = trimmedLatex.isEmpty || mathLabel.error != nil
mathLabel.isHidden = shouldFallback
fallbackLabel.isHidden = !shouldFallback
+
+ invalidateIntrinsicContentSize()
}
}
#endif
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift
index 14fc694240..2465ba7e69 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift
@@ -2,6 +2,9 @@
import SwiftUI
import PhotosUI
import UniformTypeIdentifiers
+#if os(iOS)
+import UIKit
+#endif
struct MessageInputView: View {
@Binding var text: String
@@ -198,7 +201,7 @@ struct MessageInputView: View {
hideKeyboard()
onDismissKeyboard()
} label: {
- Image(systemName: "chevron.down")
+ Image(systemName: keyboardDismissIconName)
.font(.system(size: 14, weight: .semibold))
.foregroundStyle(EnsuColor.textPrimary)
.frame(width: 32, height: 32)
@@ -233,6 +236,14 @@ struct MessageInputView: View {
#endif
}
+ #if os(iOS)
+ private var keyboardDismissIconName: String {
+ UIImage(systemName: "keyboard.chevron.compact.down") != nil
+ ? "keyboard.chevron.compact.down"
+ : "chevron.down"
+ }
+ #endif
+
private var attachmentFlowLayout: some View {
FlowLayout(spacing: EnsuSpacing.sm) {
ForEach(attachments) { attachment in
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swift
index 7ae4cc8e41..2e1f70c5a1 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageList/MessageListComponents.swift
@@ -498,15 +498,35 @@ struct MarkdownView: View {
switch block.kind {
case .heading(let level, let text):
let displayText = showCursor && isLast ? text + StreamingCursor.glyph : text
- markdownText(displayText)
- .font(headingFont(for: level))
- .foregroundStyle(EnsuColor.textPrimary)
+ if containsInlineMath(displayText) {
+ InlineMathTextView(
+ text: displayText,
+ fonts: InlineFontSet(
+ normal: headingFont(for: level),
+ code: EnsuFont.code(size: headingFontSize(for: level), weight: .semibold),
+ mathSize: headingFontSize(for: level)
+ ),
+ textColor: EnsuColor.textPrimary
+ )
+ } else {
+ markdownText(displayText)
+ .font(headingFont(for: level))
+ .foregroundStyle(EnsuColor.textPrimary)
+ }
case .paragraph(let text):
let displayText = showCursor && isLast ? text + StreamingCursor.glyph : text
- markdownText(displayText)
- .font(EnsuTypography.message)
- .foregroundStyle(EnsuColor.textPrimary)
- .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))
+ if containsInlineMath(displayText) {
+ InlineMathTextView(
+ text: displayText,
+ fonts: messageInlineFonts,
+ textColor: EnsuColor.textPrimary
+ )
+ } else {
+ markdownText(displayText)
+ .font(EnsuTypography.message)
+ .foregroundStyle(EnsuColor.textPrimary)
+ .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))
+ }
case .blockquote(let text):
let displayText = showCursor && isLast ? text + StreamingCursor.glyph : text
BlockQuoteView(text: displayText)
@@ -527,9 +547,17 @@ struct MarkdownView: View {
Text("β€’")
.font(EnsuTypography.message)
.foregroundStyle(EnsuColor.textPrimary)
- markdownText(item)
- .font(EnsuTypography.message)
- .foregroundStyle(EnsuColor.textPrimary)
+ if containsInlineMath(item) {
+ InlineMathTextView(
+ text: item,
+ fonts: messageInlineFonts,
+ textColor: EnsuColor.textPrimary
+ )
+ } else {
+ markdownText(item)
+ .font(EnsuTypography.message)
+ .foregroundStyle(EnsuColor.textPrimary)
+ }
}
}
}
@@ -548,16 +576,20 @@ struct MarkdownView: View {
.textSelection(.enabled)
}
- private func headingFont(for level: Int) -> Font {
+ private func headingFontSize(for level: Int) -> CGFloat {
switch level {
case 1:
- return EnsuFont.message(size: 22, weight: .semibold)
+ return 22
case 2:
- return EnsuFont.message(size: 20, weight: .semibold)
+ return 20
default:
- return EnsuFont.message(size: 18, weight: .semibold)
+ return 18
}
}
+
+ private func headingFont(for level: Int) -> Font {
+ EnsuFont.message(size: headingFontSize(for: level), weight: .semibold)
+ }
}
func markdownText(_ text: String) -> SwiftUI.Text {
@@ -567,6 +599,300 @@ func markdownText(_ text: String) -> SwiftUI.Text {
return SwiftUI.Text(text)
}
+private enum InlineMarkdownStyle: Equatable {
+ case normal
+ case bold
+ case italic
+ case code
+}
+
+private enum InlineSegment: Equatable {
+ case text(String, InlineMarkdownStyle)
+ case math(String)
+}
+
+private struct InlineMathMatch {
+ let latex: String
+ let endIndex: Int
+}
+
+private struct InlineFontSet {
+ let normal: Font
+ let code: Font
+ let mathSize: CGFloat
+}
+
+private let messageInlineFonts = InlineFontSet(
+ normal: EnsuTypography.message,
+ code: EnsuFont.code(size: 15, weight: .regular),
+ mathSize: 15
+)
+
+private let inlineMathPattern = try! NSRegularExpression(
+ pattern: #"(?<!\\)\$(?!\$)(?:[^$\n\\]|\\.)+?(?<!\\)\$(?!\$)|\\\((?:[^\n\\]|\\.)+?\\\)"#,
+ options: []
+)
+
+private func parseInlineSegments(_ text: String) -> [InlineSegment] {
+ let characters = Array(text)
+ var segments: [InlineSegment] = []
+ var buffer: [Character] = []
+ var currentStyle: InlineMarkdownStyle = .normal
+ var index = 0
+
+ func flushBuffer() {
+ if !buffer.isEmpty {
+ segments.append(.text(String(buffer), currentStyle))
+ buffer.removeAll(keepingCapacity: true)
+ }
+ }
+
+ while index < characters.count {
+ if let mathMatch = findInlineMathMatch(characters, startIndex: index) {
+ flushBuffer()
+ segments.append(.math(mathMatch.latex))
+ index = mathMatch.endIndex
+ continue
+ }
+
+ switch currentStyle {
+ case .code:
+ if characters[index] == "`" {
+ flushBuffer()
+ currentStyle = .normal
+ index += 1
+ } else {
+ buffer.append(characters[index])
+ index += 1
+ }
+ case .bold:
+ if hasPrefix(characters, at: index, token: ["*", "*"]) {
+ flushBuffer()
+ currentStyle = .normal
+ index += 2
+ } else {
+ buffer.append(characters[index])
+ index += 1
+ }
+ case .italic:
+ if characters[index] == "*" && !hasPrefix(characters, at: index, token: ["*", "*"]) {
+ flushBuffer()
+ currentStyle = .normal
+ index += 1
+ } else {
+ buffer.append(characters[index])
+ index += 1
+ }
+ case .normal:
+ switch true {
+ case hasPrefix(characters, at: index, token: ["*", "*"]) && hasClosingDelimiter(characters, startIndex: index + 2, delimiter: ["*", "*"]):
+ flushBuffer()
+ currentStyle = .bold
+ index += 2
+ case characters[index] == "*" &&
+ !hasPrefix(characters, at: index, token: ["*", "*"]) &&
+ hasClosingSingleAsterisk(characters, startIndex: index + 1):
+ flushBuffer()
+ currentStyle = .italic
+ index += 1
+ case characters[index] == "`" &&
+ hasClosingDelimiter(characters, startIndex: index + 1, delimiter: ["`"]):
+ flushBuffer()
+ currentStyle = .code
+ index += 1
+ default:
+ buffer.append(characters[index])
+ index += 1
+ }
+ }
+ }
+
+ flushBuffer()
+ return segments
+}
+
+private func findInlineMathMatch(_ characters: [Character], startIndex: Int) -> InlineMathMatch? {
+ if startIndex >= characters.count {
+ return nil
+ }
+
+ if hasPrefix(characters, at: startIndex, token: ["\\", "("]) {
+ var index = startIndex + 2
+ while index < characters.count {
+ if characters[index] == "\n" {
+ return nil
+ }
+ if characters[index] == "\\" {
+ if index + 1 >= characters.count {
+ return nil
+ }
+ if characters[index + 1] == ")" {
+ return InlineMathMatch(
+ latex: String(characters[(startIndex + 2)..<index]),
+ endIndex: index + 2
+ )
+ }
+ index += 2
+ continue
+ }
+ index += 1
+ }
+ return nil
+ }
+
+ if characters[startIndex] != "$" || (startIndex > 0 && characters[startIndex - 1] == "\\") {
+ return nil
+ }
+ if startIndex + 1 < characters.count && characters[startIndex + 1] == "$" {
+ return nil
+ }
+
+ var index = startIndex + 1
+ while index < characters.count {
+ if characters[index] == "\n" {
+ return nil
+ }
+ if characters[index] == "$" &&
+ characters[index - 1] != "\\" &&
+ (index + 1 >= characters.count || characters[index + 1] != "$") {
+ if index == startIndex + 1 {
+ return nil
+ }
+ return InlineMathMatch(
+ latex: String(characters[(startIndex + 1)..<index]),
+ endIndex: index + 1
+ )
+ }
+ index += 1
+ }
+
+ return nil
+}
+
+private func hasPrefix(_ characters: [Character], at startIndex: Int, token: [Character]) -> Bool {
+ let endIndex = startIndex + token.count
+ if startIndex < 0 || endIndex > characters.count {
+ return false
+ }
+ return Array(characters[startIndex..<endIndex]) == token
+}
+
+private func hasClosingDelimiter(_ characters: [Character], startIndex: Int, delimiter: [Character]) -> Bool {
+ var index = startIndex
+ while index < characters.count {
+ if characters[index] == "\n" {
+ return false
+ }
+ if hasPrefix(characters, at: index, token: delimiter) {
+ return true
+ }
+ index += 1
+ }
+ return false
+}
+
+private func hasClosingSingleAsterisk(_ characters: [Character], startIndex: Int) -> Bool {
+ var index = startIndex
+ while index < characters.count {
+ if characters[index] == "\n" {
+ return false
+ }
+ if characters[index] == "*" && !hasPrefix(characters, at: index, token: ["*", "*"]) {
+ return true
+ }
+ index += 1
+ }
+ return false
+}
+
+private func containsInlineMath(_ text: String) -> Bool {
+ let nsText = text as NSString
+ return inlineMathPattern.firstMatch(in: text, range: NSRange(location: 0, length: nsText.length)) != nil
+}
+
+private func styledInlineText(
+ _ content: String,
+ style: InlineMarkdownStyle,
+ fonts: InlineFontSet,
+ textColor: Color
+) -> some View {
+ switch style {
+ case .normal:
+ return AnyView(
+ markdownText(content)
+ .font(fonts.normal)
+ .foregroundStyle(textColor)
+ )
+ case .bold:
+ return AnyView(
+ markdownText(content)
+ .font(fonts.normal)
+ .fontWeight(.semibold)
+ .foregroundStyle(textColor)
+ )
+ case .italic:
+ return AnyView(
+ markdownText(content)
+ .font(fonts.normal)
+ .italic()
+ .foregroundStyle(textColor)
+ )
+ case .code:
+ return AnyView(
+ Text(verbatim: content)
+ .font(fonts.code)
+ .foregroundStyle(textColor)
+ )
+ }
+}
+
+private func splitTextChunks(_ text: String) -> [String] {
+ var chunks: [String] = []
+ var current = ""
+ for ch in text {
+ if ch.isWhitespace {
+ current.append(ch)
+ } else {
+ if !current.isEmpty && current.last?.isWhitespace == true {
+ chunks.append(current)
+ current = ""
+ }
+ current.append(ch)
+ }
+ }
+ if !current.isEmpty {
+ chunks.append(current)
+ }
+ return chunks
+}
+
+private struct InlineMathTextView: View {
+ let text: String
+ let fonts: InlineFontSet
+ let textColor: Color
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 2) {
+ ForEach(Array(text.split(separator: "\n", omittingEmptySubsequences: false).enumerated()), id: \.offset) { _, rawLine in
+ let line = String(rawLine)
+ FlowLayout(spacing: 0) {
+ ForEach(Array(parseInlineSegments(line).enumerated()), id: \.offset) { _, segment in
+ switch segment {
+ case .math(let latex):
+ InlineLaTeXView(latex: latex, fontSize: fonts.mathSize)
+ .fixedSize()
+ case .text(let content, let style):
+ ForEach(Array(splitTextChunks(content).enumerated()), id: \.offset) { _, chunk in
+ styledInlineText(chunk, style: style, fonts: fonts, textColor: textColor)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
struct MarkdownBlock: Identifiable, Equatable {
enum Kind: Equatable {
case heading(level: Int, text: String)
@@ -933,18 +1259,28 @@ struct BlockQuoteView: View {
let text: String
var body: some View {
- markdownText(text)
- .font(EnsuTypography.message)
- .foregroundStyle(EnsuColor.textPrimary)
- .padding(EnsuSpacing.cardPadding)
- .background(EnsuColor.fillFaint)
- .overlay(
- Rectangle()
- .fill(EnsuColor.border)
- .frame(width: 3),
- alignment: .leading
- )
- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
+ Group {
+ if containsInlineMath(text) {
+ InlineMathTextView(
+ text: text,
+ fonts: messageInlineFonts,
+ textColor: EnsuColor.textPrimary
+ )
+ } else {
+ markdownText(text)
+ .font(EnsuTypography.message)
+ .foregroundStyle(EnsuColor.textPrimary)
+ }
+ }
+ .padding(EnsuSpacing.cardPadding)
+ .background(EnsuColor.fillFaint)
+ .overlay(
+ Rectangle()
+ .fill(EnsuColor.border)
+ .frame(width: 3),
+ alignment: .leading
+ )
+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/DesignSystem/FlowLayout.swift b/mobile/native/darwin/Apps/ensu/ensu/DesignSystem/FlowLayout.swift
index 3fffa61ce0..76af6975ba 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/DesignSystem/FlowLayout.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/DesignSystem/FlowLayout.swift
@@ -3,6 +3,14 @@ import SwiftUI
struct FlowLayout: Layout {
var spacing: CGFloat = EnsuSpacing.sm
+ private func childSize(for subview: LayoutSubview, maxWidth: CGFloat) -> CGSize {
+ let ideal = subview.sizeThatFits(.unspecified)
+ if ideal.width > maxWidth {
+ return subview.sizeThatFits(ProposedViewSize(width: maxWidth, height: nil))
+ }
+ return ideal
+ }
+
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let maxWidth = proposal.width ?? .infinity
var rowWidth: CGFloat = 0
@@ -11,10 +19,10 @@ struct FlowLayout: Layout {
var maxRowWidth: CGFloat = 0
for subview in subviews {
- let size = subview.sizeThatFits(.unspecified)
+ let size = childSize(for: subview, maxWidth: maxWidth)
let nextWidth = rowWidth == 0 ? size.width : rowWidth + spacing + size.width
- if nextWidth > maxWidth {
+ if nextWidth > maxWidth && rowWidth > 0 {
totalHeight += rowHeight + spacing
maxRowWidth = max(maxRowWidth, rowWidth)
rowWidth = 0
@@ -33,21 +41,42 @@ struct FlowLayout: Layout {
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
- var x = bounds.minX
- var y = bounds.minY
- var rowHeight: CGFloat = 0
+ let sizes = subviews.map { childSize(for: $0, maxWidth: bounds.width) }
- for subview in subviews {
- let size = subview.sizeThatFits(.unspecified)
- if x + size.width > bounds.maxX {
- x = bounds.minX
- y += rowHeight + spacing
- rowHeight = 0
+ struct RowItem {
+ let index: Int
+ let size: CGSize
+ let x: CGFloat
+ }
+ var rows: [[RowItem]] = []
+ var currentRow: [RowItem] = []
+ var x: CGFloat = 0
+
+ for (index, size) in sizes.enumerated() {
+ if x + size.width > bounds.width && !currentRow.isEmpty {
+ rows.append(currentRow)
+ currentRow = []
+ x = 0
}
- subview.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(width: size.width, height: size.height))
+ currentRow.append(RowItem(index: index, size: size, x: x))
x += size.width + spacing
- rowHeight = max(rowHeight, size.height)
+ }
+ if !currentRow.isEmpty {
+ rows.append(currentRow)
+ }
+
+ var y = bounds.minY
+ for row in rows {
+ let rowHeight = row.map(\.size.height).max() ?? 0
+ for item in row {
+ let yOffset = (rowHeight - item.size.height) / 2
+ subviews[item.index].place(
+ at: CGPoint(x: bounds.minX + item.x, y: y + yOffset),
+ proposal: ProposedViewSize(width: item.size.width, height: item.size.height)
+ )
+ }
+ y += rowHeight + spacing
}
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuRustDefaults.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuRustDefaults.swift
index 8acb59ee2f..cd68063009 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuRustDefaults.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuRustDefaults.swift
@@ -39,7 +39,70 @@ enum EnsuRustDefaults {
desktopModelPresets: defaults.desktopModelPresets.map { $0.toLocal() }
)
#else
- fatalError("InferenceRS not available")
+ return EnsuRustDefaultsValue(
+ mobileSystemPromptBody: "You are Ensu, an AI assistant built by Ente. Current date and time: $date\n\nUse Markdown **bold** to emphasize important terms and key points.\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.",
+ desktopSystemPromptBody: "You are Ensu, an AI assistant built by Ente. Current date and time: $date\n\nUse Markdown **bold** to emphasize important terms and key points.\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.",
+ systemPromptDatePlaceholder: "$date",
+ sessionSummarySystemPrompt: "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title.",
+ mobileDefaultModel: EnsuRustModelPreset(
+ id: "lfm-vl-1.6b",
+ title: "LFM 2.5 VL 1.6B (Q4_0)",
+ url: "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf?download=true",
+ mmprojUrl: "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"
+ ),
+ mobileModelPresets: [
+ EnsuRustModelPreset(
+ id: "lfm-1.2b",
+ title: "LFM 2.5 1.2B Instruct (Q4_0)",
+ url: "https://huggingface.co/LiquidAI/LFM2.5-1.2B-GGUF/resolve/main/LFM2.5-1.2B-Q4_0.gguf?download=true",
+ mmprojUrl: nil
+ ),
+ EnsuRustModelPreset(
+ id: "qwen-0.8b",
+ title: "Qwen 3.5 0.8B (Q4_K_M)",
+ url: "https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF/resolve/main/Qwen3.5-0.8B-Q4_K_M.gguf?download=true",
+ mmprojUrl: "https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF/resolve/main/mmproj-F16.gguf"
+ ),
+ EnsuRustModelPreset(
+ id: "qwen-2b-q8",
+ title: "Qwen 3.5 2B (Q8_0)",
+ url: "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/Qwen3.5-2B-Q8_0.gguf?download=true",
+ mmprojUrl: "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf"
+ )
+ ],
+ desktopDefaultModel: EnsuRustModelPreset(
+ id: "qwen-4b-q4km",
+ title: "Qwen 3.5 4B (Q4_K_M)",
+ url: "https://huggingface.co/unsloth/Qwen3.5-4B-GGUF/resolve/main/Qwen3.5-4B-Q4_K_M.gguf?download=true",
+ mmprojUrl: "https://huggingface.co/unsloth/Qwen3.5-4B-GGUF/resolve/main/mmproj-F16.gguf"
+ ),
+ desktopModelPresets: [
+ EnsuRustModelPreset(
+ id: "lfm-vl-1.6b",
+ title: "LFM 2.5 VL 1.6B (Q4_0)",
+ url: "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf?download=true",
+ mmprojUrl: "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"
+ ),
+ EnsuRustModelPreset(
+ id: "lfm-1.2b",
+ title: "LFM 2.5 1.2B Instruct (Q4_0)",
+ url: "https://huggingface.co/LiquidAI/LFM2.5-1.2B-GGUF/resolve/main/LFM2.5-1.2B-Q4_0.gguf?download=true",
+ mmprojUrl: nil
+ ),
+ EnsuRustModelPreset(
+ id: "qwen-0.8b",
+ title: "Qwen 3.5 0.8B (Q4_K_M)",
+ url: "https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF/resolve/main/Qwen3.5-0.8B-Q4_K_M.gguf?download=true",
+ mmprojUrl: "https://huggingface.co/unsloth/Qwen3.5-0.8B-GGUF/resolve/main/mmproj-F16.gguf"
+ ),
+ EnsuRustModelPreset(
+ id: "qwen-2b-q8",
+ title: "Qwen 3.5 2B (Q8_0)",
+ url: "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/Qwen3.5-2B-Q8_0.gguf?download=true",
+ mmprojUrl: "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf"
+ )
+ ]
+ )
#endif
}
}
diff --git a/rust/ensu/inference/src/defaults.rs b/rust/ensu/inference/src/defaults.rs
index f678908ff0..70c67ad143 100644
--- a/rust/ensu/inference/src/defaults.rs
+++ b/rust/ensu/inference/src/defaults.rs
@@ -21,7 +21,7 @@ pub struct EnsuDefaults {
}
const SYSTEM_PROMPT_DATE_PLACEHOLDER: &str = "$date";
-const MOBILE_SYSTEM_PROMPT_BODY: &str = "You are Ensu, an AI assistant built by Ente. Current date and time: $date\n\nUse 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$$\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";
+const MOBILE_SYSTEM_PROMPT_BODY: &str = "You are Ensu, an AI assistant built by Ente. Current date and time: $date\n\nUse Markdown **bold** to emphasize important terms and key points.\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";
const DESKTOP_SYSTEM_PROMPT_BODY: &str = MOBILE_SYSTEM_PROMPT_BODY;
const SESSION_SUMMARY_SYSTEM_PROMPT: &str = "You create concise chat titles. Given the provided message, summarize the user's goal in 5-7 words. Use plain words. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title.";
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index 6424c67adc..d46d0ee38d 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -189,7 +189,7 @@ const toSafeBlobPart = (bytes: Uint8Array): ArrayBuffer => {
};
const DEFAULT_CHAT_SYSTEM_PROMPT_BODY =
- "You are Ensu, an AI assistant built by Ente. Current date and time: $date\n\nUse 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$$\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";
+ "You are Ensu, an AI assistant built by Ente. Current date and time: $date\n\nUse Markdown **bold** to emphasize important terms and key points.\n\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";
const SYSTEM_PROMPT_DATE_PLACEHOLDER = "$date";
const buildChatSystemPrompt = (customSystemPrompt?: string) => {