Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add advanced model and system prompt settings

Prateek Sunal3ea699bfa6a6
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 78c8923372..c45b27e820 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
@@ -5,6 +5,7 @@ import android.os.Build
import android.content.pm.PackageManager
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
+import io.ente.ensu.data.AdvancedSettingsDataStore
import io.ente.ensu.data.EndpointPreferencesDataStore
import io.ente.ensu.data.SessionPreferencesDataStore
import io.ente.ensu.data.auth.EnsuAuthService
@@ -23,7 +24,9 @@ import java.io.File
class AppViewModel(application: Application) : AndroidViewModel(application) {
private val sessionPreferences = SessionPreferencesDataStore(application)
private val endpointPreferences = EndpointPreferencesDataStore(application)
+ val advancedSettingsDataStore = AdvancedSettingsDataStore(application)
private val credentialStore = CredentialStore(application)
+ val appVersion = runCatching { getAppVersion(application) }.getOrDefault("unknown")
val logRepository = FileLogRepository(application)
private val llmProvider = InferenceRsProvider(
@@ -55,7 +58,6 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
val currentEndpointFlow = authService.currentEndpointFlow
init {
- val appVersion = runCatching { getAppVersion(application) }.getOrDefault("unknown")
val launchMessage = "App launched app=$appVersion device=${Build.MANUFACTURER} ${Build.MODEL} os=${Build.VERSION.RELEASE} (sdk=${Build.VERSION.SDK_INT})"
logRepository.log(LogLevel.Info, launchMessage, tag = "App")
@@ -87,6 +89,15 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
authService.updateEndpoint(endpoint)
}
}
+
+ viewModelScope.launch {
+ advancedSettingsDataStore.settingsFlow.collectLatest { settings ->
+ store.applyPersistedSettings(
+ developerSettings = settings.developerSettings,
+ modelSettings = settings.modelSettings
+ )
+ }
+ }
}
@Suppress("DEPRECATION")
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/EnsuApp.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/EnsuApp.kt
index 24b4c3d7d8..0c358a0dc7 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/EnsuApp.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/EnsuApp.kt
@@ -14,6 +14,8 @@ fun EnsuApp(appViewModel: AppViewModel) {
logs = logs,
logRepository = appViewModel.logRepository,
authService = appViewModel.authService,
- currentEndpointFlow = appViewModel.currentEndpointFlow
+ currentEndpointFlow = appViewModel.currentEndpointFlow,
+ advancedSettingsDataStore = appViewModel.advancedSettingsDataStore,
+ appVersion = appViewModel.appVersion
)
}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt
index 2771c15080..6a718f99ee 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeNavigation.kt
@@ -20,30 +20,34 @@ import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
import com.google.accompanist.navigation.animation.AnimatedNavHost
import com.google.accompanist.navigation.animation.composable
import io.ente.ensu.chat.ChatView
+import io.ente.ensu.data.AdvancedSettingsDataStore
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.domain.model.Attachment
import io.ente.ensu.domain.model.AttachmentType
import io.ente.ensu.domain.state.AppState
import io.ente.ensu.domain.store.AppStore
import io.ente.ensu.modelsettings.ModelSettingsScreen
-import io.ente.ensu.settings.DeveloperSettingsScreen
import io.ente.ensu.settings.LogViewerScreen
import io.ente.ensu.settings.SettingsScreen
+import io.ente.ensu.settings.SystemPromptSettingsScreen
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.launch
@Composable
internal fun HomeNavigation(
appState: AppState,
store: AppStore,
logRepository: io.ente.ensu.data.logging.FileLogRepository,
- authService: io.ente.ensu.data.auth.EnsuAuthService,
currentEndpointFlow: Flow<String>,
+ advancedSettingsDataStore: AdvancedSettingsDataStore,
+ appVersion: String,
navController: NavHostController,
drawerState: DrawerState,
currentRoute: String,
@@ -58,6 +62,8 @@ internal fun HomeNavigation(
onOpenAttachment: (Attachment) -> Unit,
onDeleteAccount: () -> Unit
) {
+ val scope = rememberCoroutineScope()
+
Scaffold(
containerColor = EnsuColor.backgroundBase(),
contentWindowInsets = WindowInsets(0, 0, 0, 0),
@@ -88,8 +94,8 @@ internal fun HomeNavigation(
HomeRoute.ModelSettings -> {
SimpleTopBar(title = "Model Settings") { navController.popBackStack() }
}
- HomeRoute.DeveloperSettings -> {
- SimpleTopBar(title = "Developer Settings") { navController.popBackStack() }
+ HomeRoute.SystemPromptSettings -> {
+ SimpleTopBar(title = "System Prompt") { navController.popBackStack() }
}
HomeRoute.Settings -> {
SimpleTopBar(title = "Settings") { navController.popBackStack() }
@@ -146,9 +152,19 @@ internal fun HomeNavigation(
val currentEndpoint by currentEndpointFlow.collectAsState(initial = "https://api.ente.io")
SettingsScreen(
currentEndpoint = currentEndpoint,
+ buildVersion = appVersion,
isLoggedIn = appState.auth.isLoggedIn,
userEmail = appState.auth.email,
+ isAdvancedUnlocked = appState.developerSettings.isAdvancedUnlocked,
onOpenLogs = { navController.navigate(HomeRoute.Logs) },
+ onOpenModelSettings = { navController.navigate(HomeRoute.ModelSettings) },
+ onOpenSystemPromptSettings = { navController.navigate(HomeRoute.SystemPromptSettings) },
+ onUnlockAdvanced = {
+ store.unlockAdvancedSettings()
+ scope.launch {
+ advancedSettingsDataStore.unlockAdvancedSettings()
+ }
+ },
onSignOut = onSignOut,
onSignIn = onSignIn,
onDeleteAccount = onDeleteAccount
@@ -174,22 +190,45 @@ internal fun HomeNavigation(
) {
ModelSettingsScreen(
state = appState.modelSettings,
- onSave = store::updateModelSettings,
- onReset = store::resetModelSettings
+ onSave = { modelSettings ->
+ store.updateModelSettings(modelSettings)
+ scope.launch {
+ advancedSettingsDataStore.saveModelSettings(modelSettings)
+ }
+ },
+ onReset = {
+ store.resetModelSettings()
+ scope.launch {
+ advancedSettingsDataStore.resetModelSettings()
+ }
+ }
)
}
composable(
- route = HomeRoute.DeveloperSettings,
+ route = HomeRoute.SystemPromptSettings,
enterTransition = { forwardEnter() },
exitTransition = { forwardExit() },
popEnterTransition = { backEnter() },
popExitTransition = { backExit() }
) {
- DeveloperSettingsScreen(
- authService = authService,
- currentEndpointFlow = currentEndpointFlow,
- onOpenModelSettings = { navController.navigate(HomeRoute.ModelSettings) },
- onSaved = { navController.popBackStack() }
+ SystemPromptSettingsScreen(
+ systemPrompt = appState.developerSettings.systemPrompt,
+ onSave = { value ->
+ val updated = appState.developerSettings.copy(systemPrompt = value)
+ store.updateDeveloperSettings(updated)
+ scope.launch {
+ advancedSettingsDataStore.saveSystemPrompt(value)
+ }
+ navController.popBackStack()
+ },
+ onReset = {
+ val updated = appState.developerSettings.copy(systemPrompt = "")
+ store.updateDeveloperSettings(updated)
+ scope.launch {
+ advancedSettingsDataStore.saveSystemPrompt("")
+ }
+ navController.popBackStack()
+ }
)
}
}
@@ -202,7 +241,7 @@ internal object HomeRoute {
const val Settings = "settings"
const val Logs = "logs"
const val ModelSettings = "model-settings"
- const val DeveloperSettings = "developer-settings"
+ const val SystemPromptSettings = "system-prompt-settings"
}
internal fun AnimatedContentTransitionScope<NavBackStackEntry>.forwardEnter() =
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
index 155c5728c2..d3e5aa2bc2 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/HomeView.kt
@@ -53,6 +53,7 @@ import com.google.accompanist.navigation.animation.rememberAnimatedNavController
import io.ente.ensu.auth.AuthFlowScreen
import io.ente.ensu.chat.SessionDrawer
import io.ente.ensu.components.NativeChoiceDialog
+import io.ente.ensu.data.AdvancedSettingsDataStore
import io.ente.ensu.data.auth.EnsuAuthService
import io.ente.ensu.data.logging.FileLogRepository
import io.ente.ensu.data.storage.FilePathManager
@@ -80,7 +81,9 @@ fun HomeView(
logs: List<LogEntry>,
logRepository: FileLogRepository,
authService: EnsuAuthService,
- currentEndpointFlow: Flow<String>
+ currentEndpointFlow: Flow<String>,
+ advancedSettingsDataStore: AdvancedSettingsDataStore,
+ appVersion: String
) {
val drawerState = androidx.compose.material3.rememberDrawerState(DrawerValue.Closed)
val scope = rememberCoroutineScope()
@@ -99,10 +102,6 @@ fun HomeView(
var showLogShareDialog by remember { mutableStateOf(false) }
var showSignInComingSoon by remember { mutableStateOf(false) }
- var developerTapCount by remember { mutableStateOf(0) }
- var lastDeveloperTapAt by remember { mutableStateOf<Long?>(null) }
- var showDeveloperDialog by remember { mutableStateOf(false) }
-
val handleSignInRequest: () -> Unit = handle@{
if (!EnsuFeatureFlags.enableSignIn) {
showSignInComingSoon = true
@@ -111,24 +110,6 @@ fun HomeView(
isShowingAuth = true
}
- val handleDeveloperTap: () -> Unit = handle@{
- if (!EnsuFeatureFlags.enableDeveloperTools) return@handle
- // Don't allow switching endpoints for logged-in users.
- if (appState.auth.isLoggedIn) return@handle
-
- val now = System.currentTimeMillis()
- val last = lastDeveloperTapAt
- if (last != null && now - last > 2000) {
- developerTapCount = 0
- }
- lastDeveloperTapAt = now
- developerTapCount += 1
- if (developerTapCount >= 5) {
- developerTapCount = 0
- showDeveloperDialog = true
- }
- }
-
val imagePicker = rememberAttachmentPicker(
contract = ActivityResultContracts.GetContent(),
type = AttachmentType.Image,
@@ -282,8 +263,9 @@ fun HomeView(
appState = appState,
store = store,
logRepository = logRepository,
- authService = authService,
currentEndpointFlow = currentEndpointFlow,
+ advancedSettingsDataStore = advancedSettingsDataStore,
+ appVersion = appVersion,
navController = navController,
drawerState = drawerState,
currentRoute = currentRoute,
@@ -403,47 +385,6 @@ fun HomeView(
}
}
- if (showDeveloperDialog) {
- AlertDialog(
- onDismissRequest = { showDeveloperDialog = false },
- title = {
- Text(text = "Developer settings", style = EnsuTypography.h3Bold)
- },
- text = {
- Text(
- text = "Are you sure that you want to modify Developer settings?",
- style = EnsuTypography.body,
- color = EnsuColor.textMuted()
- )
- },
- confirmButton = {
- TextButton(
- onClick = {
- showDeveloperDialog = false
- navController.navigate(HomeRoute.DeveloperSettings) {
- launchSingleTop = true
- restoreState = true
- popUpTo(HomeRoute.Chat) { inclusive = false }
- }
- scope.launch { drawerState.close() }
- },
- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())
- ) {
- Text(text = "Yes")
- }
- },
- dismissButton = {
- TextButton(
- onClick = { showDeveloperDialog = false },
- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textMuted())
- ) {
- Text(text = "Cancel")
- }
- },
- containerColor = EnsuColor.backgroundBase()
- )
- }
-
if (isShowingSignOutDialog) {
NativeChoiceDialog(
title = "Sign Out",
@@ -601,4 +542,3 @@ private fun querySize(resolver: android.content.ContentResolver, uri: Uri): Long
}
return null
}
-
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/RootView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/RootView.kt
index 04c09e5d2e..3f22f3fe43 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/RootView.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/RootView.kt
@@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
+import io.ente.ensu.data.AdvancedSettingsDataStore
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.data.auth.EnsuAuthService
import io.ente.ensu.data.logging.FileLogRepository
@@ -20,7 +21,9 @@ fun RootView(
logs: List<LogEntry>,
logRepository: FileLogRepository,
authService: EnsuAuthService,
- currentEndpointFlow: Flow<String>
+ currentEndpointFlow: Flow<String>,
+ advancedSettingsDataStore: AdvancedSettingsDataStore,
+ appVersion: String
) {
Box(
modifier = Modifier
@@ -33,7 +36,9 @@ fun RootView(
logs = logs,
logRepository = logRepository,
authService = authService,
- currentEndpointFlow = currentEndpointFlow
+ currentEndpointFlow = currentEndpointFlow,
+ advancedSettingsDataStore = advancedSettingsDataStore,
+ appVersion = appVersion
)
}
}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt
index eb69722ce0..664891c0f4 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/modelsettings/ModelSettingsScreen.kt
@@ -1,5 +1,6 @@
package io.ente.ensu.modelsettings
+import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
@@ -13,8 +14,11 @@ import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
-import androidx.compose.material3.Card
-import androidx.compose.material3.Divider
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.ExposedDropdownMenuBox
+import androidx.compose.material3.ExposedDropdownMenuDefaults
+import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
@@ -31,46 +35,83 @@ import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
import io.ente.ensu.domain.state.ModelSettingsState
+@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ModelSettingsScreen(
state: ModelSettingsState,
onSave: (ModelSettingsState) -> Unit,
onReset: () -> Unit
) {
- var modelUrl by remember(state) { mutableStateOf(state.modelUrl) }
- var mmprojUrl by remember(state) { mutableStateOf(state.mmprojUrl) }
+ val modelChoices = remember {
+ listOf(
+ ModelChoice(
+ id = DEFAULT_OPTION_ID,
+ title = DEFAULT_MODEL_NAME,
+ url = DEFAULT_MODEL_URL,
+ mmproj = DEFAULT_MMPROJ_URL,
+ isDefault = true
+ ),
+ ModelChoice(
+ 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"
+ ),
+ ModelChoice(
+ 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",
+ mmproj = "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"
+ ),
+ ModelChoice(
+ id = "qwen-2b",
+ 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",
+ mmproj = "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf"
+ ),
+ ModelChoice(
+ id = CUSTOM_OPTION_ID,
+ title = "Custom",
+ isCustom = true
+ )
+ )
+ }
+
+ var selectedModelId by remember(state) {
+ mutableStateOf(initialSelectionId(state, modelChoices))
+ }
+ var customModelUrl by remember(state) {
+ mutableStateOf(
+ if (state.useCustomModel && modelChoices.none { !it.isCustom && it.url == state.modelUrl }) {
+ state.modelUrl
+ } else {
+ ""
+ }
+ )
+ }
+ var customMmprojUrl by remember(state) {
+ mutableStateOf(
+ if (state.useCustomModel && modelChoices.none { !it.isCustom && it.url == state.modelUrl }) {
+ state.mmprojUrl
+ } else {
+ ""
+ }
+ )
+ }
var contextLength by remember(state) { mutableStateOf(state.contextLength) }
var maxTokens by remember(state) { mutableStateOf(state.maxTokens) }
var temperature by remember(state) { mutableStateOf(state.temperature) }
-
- val suggestedModels = listOf(
- SuggestedModel(
- title = "Qwen 3.5 2B (Q8_0)",
- subtitle = "Requires mmproj",
- url = "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/Qwen3.5-2B-Q8_0.gguf?download=true",
- mmproj = "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf"
- ),
- SuggestedModel(
- title = "LFM 2.5 1.2B Instruct (Q4_0)",
- subtitle = "Smallest download",
- url = "https://huggingface.co/LiquidAI/LFM2.5-1.2B-GGUF/resolve/main/LFM2.5-1.2B-Q4_0.gguf",
- mmproj = null
- ),
- SuggestedModel(
- title = "LFM 2.5 VL 1.6B (Q4_0)",
- subtitle = "Requires mmproj",
- url = "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf",
- mmproj = "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"
- ),
- SuggestedModel(
- title = "Llama 3.2 1B Instruct (Q4_K_M)",
- subtitle = "Fastest load",
- url = "https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf",
- mmproj = null
+ var showAdvancedLimits by remember(state) {
+ mutableStateOf(
+ state.contextLength.isNotBlank() ||
+ state.maxTokens.isNotBlank() ||
+ state.temperature.isNotBlank()
)
- )
+ }
+ var isModelMenuExpanded by remember { mutableStateOf(false) }
- val isCustomSelected = state.useCustomModel && modelUrl.isNotBlank()
+ val selectedModel = modelChoices.firstOrNull { it.id == selectedModelId } ?: modelChoices.first()
+ val isCustomSelected = selectedModel.isCustom
+ val canSave = !isCustomSelected || customModelUrl.isNotBlank()
Column(
modifier = Modifier
@@ -78,137 +119,185 @@ fun ModelSettingsScreen(
.verticalScroll(rememberScrollState())
.padding(EnsuSpacing.pageHorizontal.dp)
) {
- SectionHeader("Selected model")
- val selectedLabel = if (isCustomSelected) "Custom model" else "Default model"
- Text(text = selectedLabel, style = EnsuTypography.body)
- if (isCustomSelected) {
- Text(text = modelUrl, style = EnsuTypography.small, color = EnsuColor.textMuted())
- } else {
- Text(text = DEFAULT_MODEL_NAME, style = EnsuTypography.small, color = EnsuColor.textMuted())
- Text(text = DEFAULT_MODEL_URL, style = EnsuTypography.mini, color = EnsuColor.textMuted())
- }
-
- Spacer(modifier = Modifier.height(EnsuSpacing.xl.dp))
- SectionHeader("Custom Hugging Face model")
- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
-
- Text(text = "Direct .gguf file URL", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ SectionHeader("Select model")
Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
- OutlinedTextField(
- value = modelUrl,
- onValueChange = { modelUrl = it },
- placeholder = { Text(text = "https://huggingface.co/...") },
- modifier = Modifier.fillMaxWidth()
- )
-
- Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
-
- Text(text = "mmproj .gguf file URL", style = EnsuTypography.small, color = EnsuColor.textMuted())
- Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
- OutlinedTextField(
- value = mmprojUrl,
- onValueChange = { mmprojUrl = it },
- placeholder = { Text(text = "(optional for multimodal)") },
- modifier = Modifier.fillMaxWidth()
+ Text(
+ text = "Choose a built-in model or switch to Custom.",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted()
)
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ ExposedDropdownMenuBox(
+ expanded = isModelMenuExpanded,
+ onExpandedChange = { isModelMenuExpanded = !isModelMenuExpanded }
+ ) {
+ OutlinedTextField(
+ value = selectedModel.title,
+ onValueChange = {},
+ readOnly = true,
+ label = { Text("Model") },
+ trailingIcon = {
+ ExposedDropdownMenuDefaults.TrailingIcon(expanded = isModelMenuExpanded)
+ },
+ modifier = Modifier
+ .menuAnchor()
+ .fillMaxWidth()
+ )
- Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))
-
- Text(text = "Suggested models:", style = EnsuTypography.small, color = EnsuColor.textMuted())
- suggestedModels.forEach { model ->
- SuggestedModelCard(
- title = model.title,
- subtitle = model.subtitle,
- onFill = {
- modelUrl = model.url
- mmprojUrl = model.mmproj.orEmpty()
+ ExposedDropdownMenu(
+ expanded = isModelMenuExpanded,
+ onDismissRequest = { isModelMenuExpanded = false }
+ ) {
+ modelChoices.forEach { choice ->
+ DropdownMenuItem(
+ text = { Text(choice.title) },
+ onClick = {
+ selectedModelId = choice.id
+ isModelMenuExpanded = false
+ if (choice.isCustom) {
+ customModelUrl = ""
+ customMmprojUrl = ""
+ }
+ }
+ )
}
- )
+ }
}
- Spacer(modifier = Modifier.height(EnsuSpacing.xl.dp))
- SectionHeader("Custom limits (optional)")
- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
-
- Row {
- Column(modifier = Modifier.weight(1f)) {
- Text(text = "Context length", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ AnimatedVisibility(isCustomSelected) {
+ Column {
+ Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))
+ Text(text = "Model .gguf URL", style = EnsuTypography.small, color = EnsuColor.textMuted())
Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
OutlinedTextField(
- value = contextLength,
- onValueChange = { contextLength = it },
- placeholder = { Text(text = "8192") },
- modifier = Modifier.fillMaxWidth(),
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
+ value = customModelUrl,
+ onValueChange = { customModelUrl = it },
+ placeholder = { Text(text = "https://huggingface.co/...") },
+ modifier = Modifier.fillMaxWidth()
)
- }
- Spacer(modifier = Modifier.width(EnsuSpacing.md.dp))
- Column(modifier = Modifier.weight(1f)) {
- Text(text = "Max output", style = EnsuTypography.small, color = EnsuColor.textMuted())
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
+ Text(text = "mmproj .gguf URL", style = EnsuTypography.small, color = EnsuColor.textMuted())
Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
OutlinedTextField(
- value = maxTokens,
- onValueChange = { maxTokens = it },
- placeholder = { Text(text = "2048") },
- modifier = Modifier.fillMaxWidth(),
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
+ value = customMmprojUrl,
+ onValueChange = { customMmprojUrl = it },
+ placeholder = { Text(text = "(optional for multimodal)") },
+ modifier = Modifier.fillMaxWidth()
)
}
}
- Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
- Text(text = "Temperature", style = EnsuTypography.small, color = EnsuColor.textMuted())
- Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
- OutlinedTextField(
- value = temperature,
- onValueChange = { temperature = it },
- placeholder = { Text(text = "0.7") },
- modifier = Modifier.fillMaxWidth(),
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
+ Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))
+ ExpandButton(
+ title = "Advanced limits",
+ expanded = showAdvancedLimits,
+ collapsedHint = "Context length, output, temperature",
+ onToggle = { showAdvancedLimits = !showAdvancedLimits }
)
+ AnimatedVisibility(showAdvancedLimits) {
+ Column {
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ Row {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(text = "Context length", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ OutlinedTextField(
+ value = contextLength,
+ onValueChange = { contextLength = it },
+ placeholder = { Text(text = "8192") },
+ modifier = Modifier.fillMaxWidth(),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
+ )
+ }
+ Spacer(modifier = Modifier.width(EnsuSpacing.md.dp))
+ Column(modifier = Modifier.weight(1f)) {
+ Text(text = "Max output", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ OutlinedTextField(
+ value = maxTokens,
+ onValueChange = { maxTokens = it },
+ placeholder = { Text(text = "2048") },
+ modifier = Modifier.fillMaxWidth(),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
+ )
+ }
+ }
- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
- Text(text = "Leave blank to use model defaults", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
+ Text(text = "Temperature", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ OutlinedTextField(
+ value = temperature,
+ onValueChange = { temperature = it },
+ placeholder = { Text(text = "0.7") },
+ modifier = Modifier.fillMaxWidth(),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
+ )
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ Text(text = "Leave blank to use model defaults", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ }
+ }
Spacer(modifier = Modifier.height(EnsuSpacing.xl.dp))
- Divider()
+ HorizontalDivider()
Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))
Button(
onClick = {
- onSave(
- state.copy(
+ val savedState = when {
+ selectedModel.isDefault -> state.copy(
+ useCustomModel = false,
+ modelUrl = "",
+ mmprojUrl = "",
+ contextLength = contextLength,
+ maxTokens = maxTokens,
+ temperature = temperature
+ )
+ selectedModel.isCustom -> state.copy(
useCustomModel = true,
- modelUrl = modelUrl,
- mmprojUrl = mmprojUrl,
+ modelUrl = customModelUrl,
+ mmprojUrl = customMmprojUrl,
contextLength = contextLength,
maxTokens = maxTokens,
temperature = temperature
)
- )
+ else -> state.copy(
+ useCustomModel = true,
+ modelUrl = selectedModel.url.orEmpty(),
+ mmprojUrl = selectedModel.mmproj.orEmpty(),
+ contextLength = contextLength,
+ maxTokens = maxTokens,
+ temperature = temperature
+ )
+ }
+ onSave(savedState)
},
modifier = Modifier.fillMaxWidth(),
+ enabled = canSave,
colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent())
) {
- Text(text = "Use Custom Model", style = EnsuTypography.body)
+ Text(text = "Save Model Settings", style = EnsuTypography.body)
}
Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
TextButton(onClick = {
onReset()
- modelUrl = ""
- mmprojUrl = ""
+ selectedModelId = DEFAULT_OPTION_ID
+ customModelUrl = ""
+ customMmprojUrl = ""
contextLength = ""
maxTokens = ""
temperature = ""
}) {
- Text(text = "Use Default Model", style = EnsuTypography.body, color = EnsuColor.action())
+ Text(text = "Reset to defaults", style = EnsuTypography.body, color = EnsuColor.action())
}
Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
Text(
- text = "Changes require redownloading the model.",
+ text = "Changes apply the next time the model loads.",
style = EnsuTypography.small,
color = EnsuColor.textMuted()
)
@@ -217,32 +306,48 @@ fun ModelSettingsScreen(
@Composable
private fun SectionHeader(title: String) {
- Text(text = title, style = EnsuTypography.h3Bold)
+ Text(text = title, style = EnsuTypography.body)
}
@Composable
-private fun SuggestedModelCard(title: String, subtitle: String, onFill: () -> Unit) {
- Card(modifier = Modifier
- .fillMaxWidth()
- .padding(vertical = EnsuSpacing.xs.dp)
- ) {
- Column(modifier = Modifier.padding(EnsuSpacing.md.dp)) {
- Text(text = title, style = EnsuTypography.body)
- Text(text = subtitle, style = EnsuTypography.small, color = EnsuColor.textMuted())
- TextButton(onClick = onFill) {
- Text(text = "Fill", style = EnsuTypography.small, color = EnsuColor.action())
+private fun ExpandButton(
+ title: String,
+ expanded: Boolean,
+ collapsedHint: String,
+ onToggle: () -> Unit
+) {
+ TextButton(onClick = onToggle, modifier = Modifier.fillMaxWidth()) {
+ Column(modifier = Modifier.fillMaxWidth()) {
+ Text(text = title, style = EnsuTypography.body, color = EnsuColor.action())
+ if (!expanded) {
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ Text(text = collapsedHint, style = EnsuTypography.small, color = EnsuColor.textMuted())
}
}
}
}
-private data class SuggestedModel(
+private data class ModelChoice(
+ val id: String,
val title: String,
- val subtitle: String,
- val url: String,
- val mmproj: String?
+ val url: String? = null,
+ val mmproj: String? = null,
+ val isDefault: Boolean = false,
+ val isCustom: Boolean = false
)
+private fun initialSelectionId(
+ state: ModelSettingsState,
+ choices: List<ModelChoice>
+): String {
+ if (!state.useCustomModel || state.modelUrl.isBlank()) return DEFAULT_OPTION_ID
+ return choices.firstOrNull { !it.isCustom && it.url == state.modelUrl }?.id ?: CUSTOM_OPTION_ID
+}
+
+private const val DEFAULT_OPTION_ID = "default"
+private const val CUSTOM_OPTION_ID = "custom"
private const val DEFAULT_MODEL_NAME = "Qwen 3.5 2B (Q8_0)"
private const val DEFAULT_MODEL_URL =
"https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/Qwen3.5-2B-Q8_0.gguf?download=true"
+private const val DEFAULT_MMPROJ_URL =
+ "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf"
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SettingsScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SettingsScreen.kt
index 66f7e9752e..fb2933385d 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SettingsScreen.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SettingsScreen.kt
@@ -3,6 +3,7 @@ package io.ente.ensu.settings
import android.content.Context
import android.content.Intent
import android.net.Uri
+import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
@@ -45,14 +46,21 @@ import io.ente.ensu.designsystem.HugeIcons
@Composable
fun SettingsScreen(
currentEndpoint: String,
+ buildVersion: String,
isLoggedIn: Boolean,
userEmail: String?,
+ isAdvancedUnlocked: Boolean,
onOpenLogs: () -> Unit,
+ onOpenModelSettings: () -> Unit,
+ onOpenSystemPromptSettings: () -> Unit,
+ onUnlockAdvanced: () -> Unit,
onSignOut: () -> Unit,
onSignIn: () -> Unit,
onDeleteAccount: () -> Unit
) {
var query by remember { mutableStateOf("") }
+ var buildVersionTapCount by remember { mutableStateOf(0) }
+ var lastBuildVersionTapAt by remember { mutableStateOf<Long?>(null) }
val context = LocalContext.current
val allItems = remember(context, onOpenLogs, onSignOut, onSignIn, onDeleteAccount, isLoggedIn) {
@@ -125,6 +133,22 @@ fun SettingsScreen(
}
}
+ fun handleBuildVersionTap() {
+ if (isAdvancedUnlocked) return
+ val now = System.currentTimeMillis()
+ val lastTap = lastBuildVersionTapAt
+ if (lastTap != null && now - lastTap > 2000) {
+ buildVersionTapCount = 0
+ }
+ lastBuildVersionTapAt = now
+ buildVersionTapCount += 1
+ if (buildVersionTapCount >= 5) {
+ buildVersionTapCount = 0
+ onUnlockAdvanced()
+ Toast.makeText(context, "Advanced settings unlocked", Toast.LENGTH_SHORT).show()
+ }
+ }
+
Column(modifier = Modifier.padding(EnsuSpacing.pageHorizontal.dp)) {
OutlinedTextField(
value = query,
@@ -174,6 +198,36 @@ fun SettingsScreen(
SettingsRow(item)
}
+ if (isAdvancedUnlocked && query.isBlank()) {
+ item(key = "advanced-header") {
+ Spacer(modifier = Modifier.size(EnsuSpacing.sm.dp))
+ Text(
+ text = "Advanced",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted(),
+ modifier = Modifier.padding(vertical = EnsuSpacing.xs.dp)
+ )
+ }
+ item(key = "advanced-model-settings") {
+ SettingsRow(
+ SettingsItem(
+ title = "Model settings",
+ iconRes = HugeIcons.Settings01Icon,
+ onClick = onOpenModelSettings
+ )
+ )
+ }
+ item(key = "advanced-system-prompt") {
+ SettingsRow(
+ SettingsItem(
+ title = "System prompt",
+ iconRes = HugeIcons.Edit01Icon,
+ onClick = onOpenSystemPromptSettings
+ )
+ )
+ }
+ }
+
if (isCustomEndpoint) {
item(key = "endpoint") {
Spacer(modifier = Modifier.size(EnsuSpacing.sm.dp))
@@ -188,6 +242,22 @@ fun SettingsScreen(
)
}
}
+
+ if (query.isBlank()) {
+ item(key = "build-version") {
+ Spacer(modifier = Modifier.size(EnsuSpacing.sm.dp))
+ Text(
+ text = "Build version $buildVersion",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted(),
+ textAlign = TextAlign.Center,
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(onClick = ::handleBuildVersionTap)
+ .padding(vertical = EnsuSpacing.sm.dp)
+ )
+ }
+ }
}
}
}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt
new file mode 100644
index 0000000000..2056e92ce0
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt
@@ -0,0 +1,106 @@
+package io.ente.ensu.settings
+
+import io.ente.ensu.auth.PrimaryButton
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.material3.TextFieldDefaults
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.ui.unit.dp
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.EnsuCornerRadius
+import io.ente.ensu.designsystem.EnsuSpacing
+import io.ente.ensu.designsystem.EnsuTypography
+import io.ente.ensu.domain.store.SystemPromptDefaults
+
+@Composable
+fun SystemPromptSettingsScreen(
+ systemPrompt: String,
+ onSave: (String) -> Unit,
+ onReset: () -> Unit
+) {
+ val resolvedPrompt = SystemPromptDefaults.resolve(systemPrompt)
+ var value by remember(systemPrompt) { mutableStateOf(resolvedPrompt) }
+
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(EnsuSpacing.pageHorizontal.dp)
+ ) {
+ Text(
+ text = "This prompt is used as-is. Use \$date anywhere to insert the current date and time.",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted()
+ )
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))
+
+ OutlinedTextField(
+ value = value,
+ onValueChange = { value = it },
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(220.dp),
+ placeholder = {
+ Text(
+ text = "Example: You are a concise assistant. Current date and time: \$date",
+ style = EnsuTypography.body
+ )
+ },
+ colors = TextFieldDefaults.colors(
+ focusedContainerColor = EnsuColor.fillFaint(),
+ unfocusedContainerColor = EnsuColor.fillFaint(),
+ focusedIndicatorColor = EnsuColor.fillFaint(),
+ unfocusedIndicatorColor = EnsuColor.fillFaint()
+ ),
+ shape = RoundedCornerShape(EnsuCornerRadius.input.dp)
+ )
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ Text(
+ text = "Leave blank to use the default prompt.",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted()
+ )
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.xl.dp))
+
+ PrimaryButton(
+ text = "Save",
+ isLoading = false,
+ isEnabled = value.trim() != resolvedPrompt
+ ) {
+ val normalizedValue = value.trim()
+ val valueToSave = if (normalizedValue == SystemPromptDefaults.BODY) "" else normalizedValue
+ onSave(valueToSave)
+ }
+
+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
+
+ TextButton(onClick = {
+ value = SystemPromptDefaults.BODY
+ onReset()
+ }) {
+ Text(
+ text = "Use Default Prompt",
+ style = EnsuTypography.body,
+ color = EnsuColor.action()
+ )
+ }
+ }
+}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/AdvancedSettingsDataStore.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/AdvancedSettingsDataStore.kt
new file mode 100644
index 0000000000..e8eac130e4
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/AdvancedSettingsDataStore.kt
@@ -0,0 +1,84 @@
+package io.ente.ensu.data
+
+import android.content.Context
+import androidx.datastore.preferences.core.booleanPreferencesKey
+import androidx.datastore.preferences.core.edit
+import androidx.datastore.preferences.core.stringPreferencesKey
+import androidx.datastore.preferences.preferencesDataStore
+import io.ente.ensu.domain.state.DeveloperSettingsState
+import io.ente.ensu.domain.state.ModelSettingsState
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+
+private val Context.advancedSettingsPreferences by preferencesDataStore("ensu_advanced_settings")
+
+data class AdvancedSettingsSnapshot(
+ val developerSettings: DeveloperSettingsState = DeveloperSettingsState(),
+ val modelSettings: ModelSettingsState = ModelSettingsState()
+)
+
+class AdvancedSettingsDataStore(private val context: Context) {
+ val settingsFlow: Flow<AdvancedSettingsSnapshot> = context.advancedSettingsPreferences.data.map { prefs ->
+ AdvancedSettingsSnapshot(
+ developerSettings = DeveloperSettingsState(
+ isAdvancedUnlocked = prefs[Keys.advancedUnlocked] ?: false,
+ systemPrompt = prefs[Keys.systemPrompt].orEmpty()
+ ),
+ modelSettings = ModelSettingsState(
+ useCustomModel = prefs[Keys.useCustomModel] ?: false,
+ modelUrl = prefs[Keys.modelUrl].orEmpty(),
+ mmprojUrl = prefs[Keys.mmprojUrl].orEmpty(),
+ contextLength = prefs[Keys.contextLength].orEmpty(),
+ maxTokens = prefs[Keys.maxTokens].orEmpty(),
+ temperature = prefs[Keys.temperature].orEmpty()
+ )
+ )
+ }
+
+ suspend fun unlockAdvancedSettings() {
+ context.advancedSettingsPreferences.edit { prefs ->
+ prefs[Keys.advancedUnlocked] = true
+ }
+ }
+
+ suspend fun saveSystemPrompt(value: String) {
+ context.advancedSettingsPreferences.edit { prefs ->
+ prefs[Keys.systemPrompt] = value
+ }
+ }
+
+ suspend fun saveModelSettings(settings: ModelSettingsState) {
+ context.advancedSettingsPreferences.edit { prefs ->
+ prefs[Keys.useCustomModel] = settings.useCustomModel
+ prefs[Keys.modelUrl] = settings.modelUrl
+ prefs[Keys.mmprojUrl] = settings.mmprojUrl
+ prefs[Keys.contextLength] = settings.contextLength
+ prefs[Keys.maxTokens] = settings.maxTokens
+ prefs[Keys.temperature] = settings.temperature
+ }
+ }
+
+ suspend fun resetModelSettings() {
+ context.advancedSettingsPreferences.edit { prefs ->
+ prefs[Keys.useCustomModel] = false
+ prefs[Keys.modelUrl] = ""
+ prefs[Keys.mmprojUrl] = ""
+ prefs[Keys.contextLength] = ""
+ prefs[Keys.maxTokens] = ""
+ prefs[Keys.temperature] = ""
+ }
+ }
+
+ companion object {
+ private object Keys {
+ val advancedUnlocked = booleanPreferencesKey("advanced_unlocked")
+ val systemPrompt = stringPreferencesKey("system_prompt")
+ val useCustomModel = booleanPreferencesKey("use_custom_model")
+ val modelUrl = stringPreferencesKey("model_url")
+ val mmprojUrl = stringPreferencesKey("mmproj_url")
+ val contextLength = stringPreferencesKey("context_length")
+ val maxTokens = stringPreferencesKey("max_tokens")
+ val temperature = stringPreferencesKey("temperature")
+ }
+ }
+}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/DeveloperSettingsState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/DeveloperSettingsState.kt
index 5d8a6929fb..fdaa256dff 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/DeveloperSettingsState.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/DeveloperSettingsState.kt
@@ -1,5 +1,6 @@
package io.ente.ensu.domain.state
data class DeveloperSettingsState(
- val enableDiagnostics: Boolean = false
+ val isAdvancedUnlocked: Boolean = false,
+ val systemPrompt: String = ""
)
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 78d7013104..5116e36829 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
@@ -9,6 +9,7 @@ import io.ente.ensu.domain.model.Attachment
import io.ente.ensu.domain.model.ChatMessage
import io.ente.ensu.domain.preferences.SessionPreferences
import io.ente.ensu.domain.state.AppState
+import io.ente.ensu.domain.state.DeveloperSettingsState
import io.ente.ensu.domain.state.ModelSettingsState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
@@ -109,6 +110,27 @@ class AppStore(
fun resetModelSettings() = modelSettingsActions.resetModelSettings()
+ fun updateDeveloperSettings(state: DeveloperSettingsState) {
+ _state.value = _state.value.copy(developerSettings = state)
+ }
+
+ fun unlockAdvancedSettings() {
+ updateDeveloperSettings(
+ _state.value.developerSettings.copy(isAdvancedUnlocked = true)
+ )
+ }
+
+ fun applyPersistedSettings(
+ developerSettings: DeveloperSettingsState,
+ modelSettings: ModelSettingsState
+ ) {
+ _state.value = _state.value.copy(
+ developerSettings = developerSettings,
+ modelSettings = modelSettings
+ )
+ modelSettingsActions.refreshModelDownloadInfo()
+ }
+
fun signIn(email: String) = authActions.signIn(email)
fun signOut() {
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
index 95211734f3..9a305de1b4 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/ChatStoreActions.kt
@@ -1221,7 +1221,8 @@ internal class ChatStoreActions(
private fun buildSystemPrompt(nowMillis: Long = clock()): String {
val dateAndTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.getDefault())
.format(Date(nowMillis))
- return "Your name is ensu and you're a friendly ai assistant created by ente.io. ente.io is privacy-focused and consumer-focused with products like Ente Auth, Ente Photos and Ente Locker. Current Date and time is: $dateAndTime. $SYSTEM_PROMPT_BODY"
+ val promptBody = SystemPromptDefaults.resolve(state.value.developerSettings.systemPrompt)
+ return promptBody.replace(SystemPromptDefaults.DATE_PLACEHOLDER, dateAndTime)
}
companion object {
@@ -1231,7 +1232,5 @@ internal class ChatStoreActions(
private const val OVERFLOW_SAFETY_TOKENS = 128
private const val IMAGE_TOKEN_ESTIMATE = 768
private const val MAX_CACHED_SESSIONS = 8
- private const val SYSTEM_PROMPT_BODY =
- "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/domain/src/main/kotlin/io/ente/ensu/domain/store/SystemPromptDefaults.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/SystemPromptDefaults.kt
new file mode 100644
index 0000000000..426c7f08a4
--- /dev/null
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/store/SystemPromptDefaults.kt
@@ -0,0 +1,13 @@
+package io.ente.ensu.domain.store
+
+object SystemPromptDefaults {
+ const val DATE_PLACEHOLDER = "\$date"
+
+ const val 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."
+
+ fun resolve(value: String): String {
+ val trimmed = value.trim()
+ return if (trimmed.isEmpty()) BODY else trimmed
+ }
+}
diff --git a/mobile/native/darwin/Apps/ensu/build.sh b/mobile/native/darwin/Apps/ensu/build.sh
index bf6cb50764..b1fc4337c8 100755
--- a/mobile/native/darwin/Apps/ensu/build.sh
+++ b/mobile/native/darwin/Apps/ensu/build.sh
@@ -13,6 +13,12 @@ ARCHIVE_PATH="$DERIVED_DATA_PATH/Archive/ensu.xcarchive"
EXPORT_PATH="$DERIVED_DATA_PATH/Export"
EXPORT_OPTIONS_PLIST="$ROOT/ExportOptions-AppStore.plist"
+XCODE_EXTRA_ARGS=()
+XCODE_VERSION="$(xcodebuild -version 2>/dev/null | awk '/^Xcode / { print $2; exit }')"
+if [[ "$XCODE_VERSION" == 26* ]]; then
+ XCODE_EXTRA_ARGS+=(SWIFT_ENABLE_EXPLICIT_MODULES=NO)
+fi
+
usage() {
cat <<'EOF'
Build Ensu Apple app.
@@ -187,7 +193,8 @@ build_archive() {
-sdk iphoneos \
-destination 'generic/platform=iOS' \
-archivePath "$ARCHIVE_PATH" \
- archive
+ archive \
+ "${XCODE_EXTRA_ARGS[@]}"
echo "βœ… Archive: $ARCHIVE_PATH"
}
@@ -211,7 +218,8 @@ case "$MODE" in
-configuration Debug \
-sdk iphonesimulator \
-destination "id=$DESTINATION_ID" \
- -derivedDataPath "$DERIVED_DATA_PATH"
+ -derivedDataPath "$DERIVED_DATA_PATH" \
+ "${XCODE_EXTRA_ARGS[@]}"
;;
device)
if [[ -z "$DESTINATION_ID" ]]; then
@@ -229,7 +237,8 @@ case "$MODE" in
-configuration Debug \
-sdk iphoneos \
-destination "id=$DESTINATION_ID" \
- -derivedDataPath "$DERIVED_DATA_PATH"
+ -derivedDataPath "$DERIVED_DATA_PATH" \
+ "${XCODE_EXTRA_ARGS[@]}"
;;
archive)
build_archive
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift
index 7c2906e535..14aae5f5ef 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift
@@ -33,7 +33,6 @@ struct ChatView: View {
&& !viewState.isDrawerOpen
&& !viewState.didDismissKeyboard
&& !viewState.showSettings
- && !viewState.showDeveloperSettings
}
private var overflowDialogPresented: Binding<Bool> {
@@ -129,7 +128,6 @@ struct ChatView: View {
&& !viewModel.isGenerating
&& !viewState.didDismissKeyboard
&& !viewState.showSettings
- && !viewState.showDeveloperSettings
if shouldRestoreFocus {
requestInputFocus()
}
@@ -178,25 +176,6 @@ struct ChatView: View {
onDismiss: { viewState.showAttachmentDownloads = false }
)
}
- .sheet(isPresented: $viewState.showModelSettings) {
- ModelSettingsView(embeddedInNavigation: true)
- }
- .platformFullScreenCover(isPresented: $viewState.showDeveloperSettings) {
- DeveloperSettingsView { message in
- showToast(message, duration: 2)
- }
- }
- .alert("Developer settings", isPresented: $viewState.showDeveloperAlert) {
- Button("Yes") {
- viewState.showDeveloperSettings = true
- viewState.isOpeningDeveloperSettings = false
- }
- Button("Cancel", role: .cancel) {
- viewState.isOpeningDeveloperSettings = false
- }
- } message: {
- Text("Are you sure that you want to modify Developer settings?")
- }
.alert(item: $viewState.deleteSession) { session in
Alert(
title: Text("Delete Chat"),
@@ -478,31 +457,6 @@ struct ChatView: View {
viewState.showSignInComingSoon = true
}
}
-
- private func handleDeveloperTap() {
- guard EnsuFeatureFlags.enableDeveloperTools else { return }
- // Don't allow switching endpoints for logged-in users.
- guard !appState.isLoggedIn else { return }
-
- let now = Date()
- if let lastDeveloperTapAt = viewState.lastDeveloperTapAt,
- now.timeIntervalSince(lastDeveloperTapAt) > 2 {
- viewState.developerTapCount = 0
- }
-
- viewState.lastDeveloperTapAt = now
- viewState.developerTapCount += 1
-
- guard viewState.developerTapCount >= 5 else { return }
- viewState.developerTapCount = 0
- presentDeveloperPrompt()
- }
-
- private func presentDeveloperPrompt() {
- guard !viewState.isOpeningDeveloperSettings else { return }
- viewState.isOpeningDeveloperSettings = true
- viewState.showDeveloperAlert = true
- }
}
private final class ChatViewState: ObservableObject {
@@ -510,12 +464,6 @@ private final class ChatViewState: ObservableObject {
@Published var showSettings = false
@Published var toastMessage: ToastMessage?
@Published var deleteSession: ChatSession?
- @Published var developerTapCount = 0
- @Published var lastDeveloperTapAt: Date?
- @Published var isOpeningDeveloperSettings = false
- @Published var showDeveloperAlert = false
- @Published var showDeveloperSettings = false
- @Published var showModelSettings = false
@Published var showAttachmentDownloads = false
@Published var showSignInComingSoon = false
@Published var pendingSignInRequest = false
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
index 4aead9a183..1359b13fbf 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
@@ -394,12 +394,12 @@ final class ChatViewModel: ObservableObject {
}
private static let defaultTemperature: Float = 0.5
- private static let systemPromptBody = "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 systemPromptDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"
return formatter
}()
+ private static let systemPromptDatePlaceholder = "$date"
private static let defaultGenerationMaxTokens = 8_192
private static let overflowSafetyTokens = 128
private static let imageTokenEstimate = 768
@@ -408,9 +408,10 @@ final class ChatViewModel: ObservableObject {
private static let sessionSummaryStoreKey = "ensu.session_summaries"
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. Don't use markdown characters in the title. No quotes, no emojis, no trailing punctuation, and output only the title."
- private static func systemPrompt() -> String {
- let dateAndTime = systemPromptDateFormatter.string(from: Date())
- return "Your name is ensu and you're a friendly ai assistant created by ente.io. ente.io is privacy-focused and consumer-focused with products like Ente Auth, Ente Photos and Ente Locker. Current Date and time is: \(dateAndTime). \(systemPromptBody)"
+ private func systemPrompt() -> String {
+ let dateAndTime = Self.systemPromptDateFormatter.string(from: Date())
+ let promptBody = ModelSettingsStore.currentSystemPromptBody()
+ return promptBody.replacingOccurrences(of: Self.systemPromptDatePlaceholder, with: dateAndTime)
}
private let logger = EnsuLogging.shared.logger("ChatViewModel")
@@ -1517,7 +1518,7 @@ final class ChatViewModel: ObservableObject {
overflowAlert = nil
let history = historySelection.messages
- let systemMessage = InferenceMessage(text: Self.systemPrompt(), role: .system, hasAttachments: false)
+ let systemMessage = InferenceMessage(text: systemPrompt(), role: .system, hasAttachments: false)
let messages = [systemMessage] + history + [InferenceMessage(text: prompt.text, role: .user, hasAttachments: !userNode.attachments.isEmpty)]
let bufferLock = NSLock()
@@ -2543,7 +2544,7 @@ final class ChatViewModel: ObservableObject {
let historyMessages = path.prefix { $0.id != currentMessageId }
let inputBudget = max(0, limits.contextLength - limits.maxOutput - Self.overflowSafetyTokens)
- let systemTokens = estimateTokens(Self.systemPrompt())
+ let systemTokens = estimateTokens(systemPrompt())
let promptTokens = estimatePromptTokens(promptText: promptText, imageCount: promptImageCount)
let historyTokens = historyMessages.reduce(0) { total, node in
total + estimateTokens(historyText(node))
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/SessionDrawerView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/SessionDrawerView.swift
index 528f3b1733..278707d98b 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/SessionDrawerView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/SessionDrawerView.swift
@@ -154,48 +154,42 @@ struct SessionDrawerView: View {
hapticTap()
onOpenSettings()
} label: {
- HStack(spacing: EnsuSpacing.md) {
- Text(email ?? "")
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
- .lineLimit(1)
- .frame(maxWidth: .infinity, alignment: .leading)
- Image("ArrowRight01Icon")
- .resizable()
- .scaledToFit()
- .frame(width: 18, height: 18)
- .foregroundStyle(EnsuColor.textMuted)
- }
- .frame(maxWidth: .infinity)
- .contentShape(Rectangle())
+ footerButtonLabel(title: email ?? "")
}
.buttonStyle(.plain)
+ .contentShape(Rectangle())
} else {
Button {
hapticTap()
onOpenSettings()
} label: {
- HStack(spacing: EnsuSpacing.md) {
- Text("Settings")
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
- .frame(maxWidth: .infinity, alignment: .leading)
- Image("ArrowRight01Icon")
- .resizable()
- .scaledToFit()
- .frame(width: 18, height: 18)
- .foregroundStyle(EnsuColor.textMuted)
- }
- .frame(maxWidth: .infinity)
- .contentShape(Rectangle())
+ footerButtonLabel(title: "Settings")
}
.buttonStyle(.plain)
+ .contentShape(Rectangle())
}
Spacer(minLength: 0)
}
.padding(EnsuSpacing.lg)
}
+ private func footerButtonLabel(title: String) -> some View {
+ HStack(spacing: EnsuSpacing.md) {
+ Text(title)
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textPrimary)
+ .lineLimit(1)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ Image("ArrowRight01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 18, height: 18)
+ .foregroundStyle(EnsuColor.textMuted)
+ }
+ .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)
+ .contentShape(Rectangle())
+ }
+
private func drawerPrimaryTile(icon: String, title: String, action: @escaping () -> Void, expands: Bool = true) -> some View {
Button(action: {
hapticTap()
diff --git a/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift b/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift
index 51e62d10a3..0f06d71b5a 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift
@@ -6,8 +6,9 @@ struct ModelSettingsView: View {
let embeddedInNavigation: Bool
@ObservedObject private var settings = ModelSettingsStore.shared
- @State private var modelUrl: String = ""
- @State private var mmprojUrl: String = ""
+ @State private var selectedModelId: String = defaultOptionId
+ @State private var customModelUrl: String = ""
+ @State private var customMmprojUrl: String = ""
@State private var contextLength: String = ""
@State private var maxTokens: String = ""
@State private var temperature: String = ""
@@ -18,29 +19,37 @@ struct ModelSettingsView: View {
@State private var maxTokensError: String?
@State private var temperatureError: String?
@State private var isSaving = false
-
- private let suggestedModels: [SuggestedModel] = [
- SuggestedModel(
- name: "Qwen 3.5 2B (Q8_0)",
- details: "Multimodal β€’ requires mmproj",
- url: "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/Qwen3.5-2B-Q8_0.gguf?download=true",
- mmproj: "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf"
+ @State private var showAdvancedLimits = false
+
+ private let modelChoices: [ModelChoice] = [
+ ModelChoice(
+ id: Self.defaultOptionId,
+ name: ModelSettingsStore.defaultModelName,
+ url: ModelSettingsStore.defaultModelUrl,
+ mmproj: ModelSettingsStore.defaultMmprojUrl,
+ isDefault: true
),
- SuggestedModel(
+ ModelChoice(
+ id: "lfm-1.2b",
name: "LFM 2.5 1.2B Instruct (Q4_0)",
- details: "Text only",
url: "https://huggingface.co/LiquidAI/LFM2.5-1.2B-GGUF/resolve/main/LFM2.5-1.2B-Q4_0.gguf"
),
- SuggestedModel(
+ ModelChoice(
+ id: "lfm-vl-1.6b",
name: "LFM 2.5 VL 1.6B (Q4_0)",
- details: "Multimodal β€’ requires mmproj",
url: "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/LFM2.5-VL-1.6B-Q4_0.gguf",
mmproj: "https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"
),
- SuggestedModel(
- name: "Llama 3.2 1B Instruct (Q4_K_M)",
- details: "Text only",
- url: "https://huggingface.co/meta-llama/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf"
+ ModelChoice(
+ id: "qwen-2b",
+ name: "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",
+ mmproj: "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf"
+ ),
+ ModelChoice(
+ id: Self.customOptionId,
+ name: "Custom",
+ isCustom: true
)
]
@@ -84,11 +93,13 @@ struct ModelSettingsView: View {
}
}
.onAppear {
- modelUrl = settings.modelUrl
- mmprojUrl = settings.mmprojUrl
+ selectedModelId = initialSelectionId()
+ customModelUrl = isStoredCustomModel ? settings.modelUrl : ""
+ customMmprojUrl = isStoredCustomModel ? settings.mmprojUrl : ""
contextLength = settings.contextLength
maxTokens = settings.maxTokens
temperature = settings.temperature
+ showAdvancedLimits = !settings.contextLength.isEmpty || !settings.maxTokens.isEmpty || !settings.temperature.isEmpty
}
#if os(macOS)
.safeAreaInset(edge: .top) {
@@ -118,114 +129,120 @@ struct ModelSettingsView: View {
#endif
}
+ private var isStoredCustomModel: Bool {
+ settings.useCustomModel &&
+ !settings.modelUrl.isEmpty &&
+ !modelChoices.contains(where: { !$0.isCustom && $0.url == settings.modelUrl })
+ }
+
+ private var selectedModel: ModelChoice {
+ modelChoices.first(where: { $0.id == selectedModelId }) ?? modelChoices[0]
+ }
+
+ private var canSave: Bool {
+ !selectedModel.isCustom || !customModelUrl.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
private var content: some View {
ScrollView {
VStack(alignment: .leading, spacing: EnsuSpacing.xxl) {
- sectionHeader("Selected model")
+ sectionHeader("Select model")
- VStack(alignment: .leading, spacing: EnsuSpacing.xs) {
- if settings.useCustomModel && !settings.modelUrl.isEmpty {
- Text("Custom model")
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
- Text(settings.modelUrl)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- } else {
- Text("Default model")
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
- Text(ModelSettingsStore.defaultModelName)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- Text(ModelSettingsStore.defaultModelUrl)
- .font(EnsuTypography.mini)
- .foregroundStyle(EnsuColor.textMuted)
+ Text("Choose a built-in model or switch to Custom.")
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Picker("Model", selection: $selectedModelId) {
+ ForEach(modelChoices) { choice in
+ Text(choice.name).tag(choice.id)
}
}
-
- Divider().background(EnsuColor.border)
-
- sectionHeader("Custom Hugging Face model")
-
- VStack(spacing: EnsuSpacing.md) {
- field(
- label: "Direct .gguf file URL",
- hint: "https://huggingface.co/...",
- text: $modelUrl,
- error: urlError,
- keyboardType: .URL
- )
-
- field(
- label: "mmproj .gguf file URL",
- hint: "(optional for multimodal)",
- text: $mmprojUrl,
- error: mmprojError,
- keyboardType: .URL
- )
-
- Text("Suggested models:")
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- .frame(maxWidth: .infinity, alignment: .leading)
-
- ForEach(suggestedModels) { model in
- suggestedModelCard(model)
+ .pickerStyle(.menu)
+ .onChange(of: selectedModelId) { newValue in
+ if newValue == Self.customOptionId {
+ customModelUrl = ""
+ customMmprojUrl = ""
}
}
- Divider().background(EnsuColor.border)
-
- sectionHeader("Custom limits (optional)")
-
- VStack(spacing: EnsuSpacing.sm) {
- HStack(spacing: EnsuSpacing.md) {
+ if selectedModel.isCustom {
+ VStack(spacing: EnsuSpacing.md) {
field(
- label: "Context length",
- hint: "8192",
- text: $contextLength,
- error: contextError,
- keyboardType: .numberPad
+ label: "Model .gguf URL",
+ hint: "https://huggingface.co/...",
+ text: $customModelUrl,
+ error: urlError,
+ keyboardType: .URL
)
field(
- label: "Max output",
- hint: "2048",
- text: $maxTokens,
- error: maxTokensError,
- keyboardType: .numberPad
+ label: "mmproj .gguf URL",
+ hint: "(optional for multimodal)",
+ text: $customMmprojUrl,
+ error: mmprojError,
+ keyboardType: .URL
)
}
+ }
- Text("Leave blank to use model defaults")
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- .frame(maxWidth: .infinity, alignment: .leading)
+ sectionToggle(
+ title: "Advanced limits",
+ collapsedHint: "Context length, output, temperature",
+ expanded: showAdvancedLimits
+ ) {
+ showAdvancedLimits.toggle()
+ }
+
+ if showAdvancedLimits {
+ VStack(spacing: EnsuSpacing.sm) {
+ HStack(spacing: EnsuSpacing.md) {
+ field(
+ label: "Context length",
+ hint: "8192",
+ text: $contextLength,
+ error: contextError,
+ keyboardType: .numberPad
+ )
+
+ field(
+ label: "Max output",
+ hint: "2048",
+ text: $maxTokens,
+ error: maxTokensError,
+ keyboardType: .numberPad
+ )
+ }
+
+ Text("Leave blank to use model defaults")
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+ .frame(maxWidth: .infinity, alignment: .leading)
- field(
- label: "Temperature",
- hint: "0.7",
- text: $temperature,
- error: temperatureError,
- keyboardType: .decimalPad
- )
+ field(
+ label: "Temperature",
+ hint: "0.7",
+ text: $temperature,
+ error: temperatureError,
+ keyboardType: .decimalPad
+ )
+ }
}
Divider().background(EnsuColor.border)
VStack(spacing: EnsuSpacing.md) {
- PrimaryButton(text: "Use Custom Model", isLoading: isSaving, isEnabled: !isSaving) {
+ PrimaryButton(text: "Save Model Settings", isLoading: isSaving, isEnabled: !isSaving && canSave) {
saveTapped()
}
- Button("Use Default Model") {
+ Button("Reset to defaults") {
resetTapped()
}
.font(EnsuTypography.body)
.foregroundStyle(EnsuColor.textMuted)
- Text("Changes require redownloading the model.")
+ Text("Changes apply the next time the model loads.")
.font(EnsuTypography.small)
.foregroundStyle(EnsuColor.textMuted)
.multilineTextAlignment(.center)
@@ -235,9 +252,16 @@ struct ModelSettingsView: View {
}
}
+ private func initialSelectionId() -> String {
+ if !settings.useCustomModel || settings.modelUrl.isEmpty {
+ return Self.defaultOptionId
+ }
+ return modelChoices.first(where: { !$0.isCustom && $0.url == settings.modelUrl })?.id ?? Self.customOptionId
+ }
+
private func sectionHeader(_ title: String) -> some View {
Text(title)
- .font(EnsuTypography.large)
+ .font(EnsuTypography.body)
.foregroundStyle(EnsuColor.textPrimary)
.frame(maxWidth: .infinity, alignment: .leading)
}
@@ -269,27 +293,27 @@ struct ModelSettingsView: View {
.frame(maxWidth: .infinity)
}
- private func suggestedModelCard(_ model: SuggestedModel) -> some View {
- HStack {
+ private func sectionToggle(
+ title: String,
+ collapsedHint: String,
+ expanded: Bool,
+ action: @escaping () -> Void
+ ) -> some View {
+ Button(action: action) {
VStack(alignment: .leading, spacing: 4) {
- Text(model.name)
+ Text(title)
.font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
- Text(model.details)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- }
- Spacer()
- Button("Fill") {
- modelUrl = model.url
- mmprojUrl = model.mmproj ?? ""
+ .foregroundStyle(EnsuColor.action)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ if !expanded {
+ Text(collapsedHint)
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
}
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.action)
}
- .padding(EnsuSpacing.md)
- .background(EnsuColor.fillFaint)
- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))
+ .buttonStyle(.plain)
}
private func saveTapped() {
@@ -302,22 +326,40 @@ struct ModelSettingsView: View {
guard validate() else { return }
isSaving = true
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
- settings.saveCustomModel(
- url: modelUrl,
- mmproj: mmprojUrl,
- contextLength: contextLength,
- maxTokens: maxTokens,
- temperature: temperature
- )
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
+ if selectedModel.isDefault {
+ settings.useCustomModel = false
+ settings.modelUrl = ""
+ settings.mmprojUrl = ""
+ settings.contextLength = contextLength
+ settings.maxTokens = maxTokens
+ settings.temperature = temperature
+ } else if selectedModel.isCustom {
+ settings.saveCustomModel(
+ url: customModelUrl,
+ mmproj: customMmprojUrl,
+ contextLength: contextLength,
+ maxTokens: maxTokens,
+ temperature: temperature
+ )
+ } else {
+ settings.saveCustomModel(
+ url: selectedModel.url ?? "",
+ mmproj: selectedModel.mmproj ?? "",
+ contextLength: contextLength,
+ maxTokens: maxTokens,
+ temperature: temperature
+ )
+ }
isSaving = false
}
}
private func resetTapped() {
settings.resetToDefault()
- modelUrl = ""
- mmprojUrl = ""
+ selectedModelId = Self.defaultOptionId
+ customModelUrl = ""
+ customMmprojUrl = ""
contextLength = ""
maxTokens = ""
temperature = ""
@@ -326,12 +368,17 @@ struct ModelSettingsView: View {
private func validate() -> Bool {
var isValid = true
- if !modelUrl.isEmpty, !isValidHuggingFaceUrl(modelUrl) {
+ if selectedModel.isCustom && customModelUrl.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ urlError = "Enter a Hugging Face .gguf URL"
+ isValid = false
+ }
+
+ if selectedModel.isCustom && !customModelUrl.isEmpty && !isValidHuggingFaceUrl(customModelUrl) {
urlError = "Enter a valid Hugging Face .gguf URL"
isValid = false
}
- if !mmprojUrl.isEmpty, !isValidHuggingFaceUrl(mmprojUrl) {
+ if selectedModel.isCustom && !customMmprojUrl.isEmpty && !isValidHuggingFaceUrl(customMmprojUrl) {
mmprojError = "Enter a valid Hugging Face .gguf URL"
isValid = false
}
@@ -364,20 +411,33 @@ struct ModelSettingsView: View {
guard url.host?.contains("huggingface.co") == true else { return false }
return url.path.lowercased().hasSuffix(".gguf")
}
+
+ private static let defaultOptionId = "default"
+ private static let customOptionId = "custom"
}
-private struct SuggestedModel: Identifiable {
- let id = UUID()
+private struct ModelChoice: Identifiable {
+ let id: String
let name: String
- let details: String
- let url: String
+ let url: String?
let mmproj: String?
-
- init(name: String, details: String, url: String, mmproj: String? = nil) {
+ let isDefault: Bool
+ let isCustom: Bool
+
+ init(
+ id: String,
+ name: String,
+ url: String? = nil,
+ mmproj: String? = nil,
+ isDefault: Bool = false,
+ isCustom: Bool = false
+ ) {
+ self.id = id
self.name = name
- self.details = details
self.url = url
self.mmproj = mmproj
+ self.isDefault = isDefault
+ self.isCustom = isCustom
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift
index 17807e9d1e..0d4a0c8910 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift
@@ -22,6 +22,9 @@ final class ModelSettingsStore: ObservableObject {
@Published var temperature: String {
didSet { persist() }
}
+ @Published var systemPromptBody: String {
+ didSet { persist() }
+ }
private let defaults = UserDefaults.standard
@@ -32,6 +35,7 @@ final class ModelSettingsStore: ObservableObject {
self.contextLength = defaults.string(forKey: Keys.contextLength) ?? ""
self.maxTokens = defaults.string(forKey: Keys.maxTokens) ?? ""
self.temperature = defaults.string(forKey: Keys.temperature) ?? ""
+ self.systemPromptBody = defaults.string(forKey: Keys.systemPromptBody) ?? ""
}
func saveCustomModel(url: String, mmproj: String, contextLength: String, maxTokens: String, temperature: String) {
@@ -65,6 +69,17 @@ final class ModelSettingsStore: ObservableObject {
static var defaultModelName: String { Defaults.modelName }
static var defaultModelUrl: String { Defaults.modelUrl }
static var defaultMmprojUrl: String? { Defaults.mmprojUrl }
+ static var defaultSystemPromptBody: String { Defaults.systemPromptBody }
+
+ static func currentSystemPromptBody() -> String {
+ let stored = UserDefaults.standard.string(forKey: Keys.systemPromptBody) ?? ""
+ return resolveSystemPromptBody(stored)
+ }
+
+ static func resolveSystemPromptBody(_ value: String) -> String {
+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ return trimmed.isEmpty ? Defaults.systemPromptBody : trimmed
+ }
private func persist() {
defaults.set(useCustomModel, forKey: Keys.useCustomModel)
@@ -73,20 +88,35 @@ final class ModelSettingsStore: ObservableObject {
defaults.set(contextLength, forKey: Keys.contextLength)
defaults.set(maxTokens, forKey: Keys.maxTokens)
defaults.set(temperature, forKey: Keys.temperature)
+ defaults.set(systemPromptBody, forKey: Keys.systemPromptBody)
}
- private enum Keys {
+ fileprivate enum Keys {
static let useCustomModel = "ensu.model.use_custom"
static let modelUrl = "ensu.model.url"
static let mmprojUrl = "ensu.model.mmproj"
static let contextLength = "ensu.model.context"
static let maxTokens = "ensu.model.max_tokens"
static let temperature = "ensu.model.temperature"
+ static let systemPromptBody = "ensu.model.system_prompt_body"
}
private enum Defaults {
static let modelName = "Qwen 3.5 2B (Q8_0)"
static let modelUrl = "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/Qwen3.5-2B-Q8_0.gguf?download=true"
static let mmprojUrl = "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf"
+ static let systemPromptBody = "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."
+ }
+}
+
+enum EnsuAdvancedSettings {
+ private static let advancedUnlockedKey = "ensu.settings.advanced_unlocked"
+
+ static var isUnlocked: Bool {
+ UserDefaults.standard.bool(forKey: advancedUnlockedKey)
+ }
+
+ static func unlock() {
+ UserDefaults.standard.set(true, forKey: advancedUnlockedKey)
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift b/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift
index b29aefd120..7e146a0378 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift
@@ -14,6 +14,8 @@ struct SettingsView: View {
@State private var query: String = ""
@State private var showSignOutConfirm = false
+ @State private var buildVersionTapCount = 0
+ @State private var isAdvancedUnlocked = EnsuAdvancedSettings.isUnlocked
var body: some View {
NavigationStack {
@@ -60,6 +62,22 @@ struct SettingsView: View {
.buttonStyle(.plain)
}
+ if shouldShowAdvancedSection {
+ Text("Advanced")
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+ .padding(.top, EnsuSpacing.xs)
+
+ ForEach(filteredAdvancedItems) { item in
+ NavigationLink {
+ item.destination
+ } label: {
+ settingsCard(title: item.title, iconName: item.iconName, showsChevron: true)
+ }
+ .buttonStyle(.plain)
+ }
+ }
+
if let endpointInfoText {
Text(endpointInfoText)
.font(EnsuTypography.small)
@@ -68,6 +86,16 @@ struct SettingsView: View {
.frame(maxWidth: .infinity, alignment: .center)
.padding(.vertical, 8)
}
+
+ Button(action: handleBuildVersionTap) {
+ Text(buildVersionText)
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: .infinity, alignment: .center)
+ .padding(.vertical, 8)
+ }
+ .buttonStyle(.plain)
}
.padding(EnsuSpacing.lg)
}
@@ -107,6 +135,15 @@ struct SettingsView: View {
}
}
+ private var filteredAdvancedItems: [SettingsItem] {
+ guard isAdvancedUnlocked else { return [] }
+ guard !trimmedQuery.isEmpty else { return advancedItems }
+ let q = trimmedQuery.lowercased()
+ return advancedItems.filter { item in
+ item.title.lowercased().contains(q)
+ }
+ }
+
private var aboutItem: SettingsActionItem {
SettingsActionItem(
title: "About",
@@ -188,6 +225,25 @@ struct SettingsView: View {
]
}
+ private var advancedItems: [SettingsItem] {
+ [
+ SettingsItem(
+ title: "Model settings",
+ iconName: "Settings01Icon",
+ destination: AnyView(ModelSettingsView(embeddedInNavigation: true))
+ ),
+ SettingsItem(
+ title: "System prompt",
+ iconName: "Edit01Icon",
+ destination: AnyView(SystemPromptSettingsView(embeddedInNavigation: true))
+ )
+ ]
+ }
+
+ private var shouldShowAdvancedSection: Bool {
+ isAdvancedUnlocked && !filteredAdvancedItems.isEmpty
+ }
+
private var endpointInfoText: String? {
guard trimmedQuery.isEmpty else { return nil }
@@ -204,6 +260,13 @@ struct SettingsView: View {
query.trimmingCharacters(in: .whitespacesAndNewlines)
}
+ private var buildVersionText: String {
+ let info = Bundle.main.infoDictionary
+ let version = info?["CFBundleShortVersionString"] as? String ?? "unknown"
+ let build = info?["CFBundleVersion"] as? String ?? "unknown"
+ return "Build \(version) (\(build))"
+ }
+
private func openDeleteAccountEmail() {
let subject = "Request Deletion for Ente Account"
let encoded = subject.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? subject
@@ -211,6 +274,15 @@ struct SettingsView: View {
openURL(url)
}
+ private func handleBuildVersionTap() {
+ guard !isAdvancedUnlocked else { return }
+ buildVersionTapCount += 1
+ guard buildVersionTapCount >= 5 else { return }
+ EnsuAdvancedSettings.unlock()
+ isAdvancedUnlocked = true
+ buildVersionTapCount = 0
+ }
+
private func openExternalLink(_ urlString: String) {
guard let url = URL(string: urlString) else { return }
openURL(url)
@@ -259,6 +331,150 @@ struct SettingsView: View {
}
}
+private struct SystemPromptSettingsView: View {
+ @Environment(\.dismiss) private var dismiss
+
+ let embeddedInNavigation: Bool
+
+ @ObservedObject private var settings = ModelSettingsStore.shared
+ @State private var promptBody: String = ""
+ @State private var isSaving = false
+
+ init(embeddedInNavigation: Bool = false) {
+ self.embeddedInNavigation = embeddedInNavigation
+ }
+
+ var body: some View {
+ Group {
+ if embeddedInNavigation {
+ content
+ #if os(iOS)
+ .navigationBarTitleDisplayMode(.inline)
+ #endif
+ .toolbar {
+ ToolbarItem(placement: .principal) {
+ Text("System Prompt")
+ .font(EnsuTypography.large)
+ .foregroundStyle(EnsuColor.textPrimary)
+ }
+ }
+ } else {
+ #if os(iOS)
+ NavigationStack {
+ content
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .principal) {
+ Text("System Prompt")
+ .font(EnsuTypography.large)
+ .foregroundStyle(EnsuColor.textPrimary)
+ }
+ ToolbarItem(placement: .primaryAction) {
+ Button("Done") { dismiss() }
+ }
+ }
+ }
+ #else
+ content
+ #endif
+ }
+ }
+ .onAppear {
+ promptBody = ModelSettingsStore.resolveSystemPromptBody(settings.systemPromptBody)
+ }
+ #if os(macOS)
+ .safeAreaInset(edge: .top) {
+ if embeddedInNavigation {
+ EmptyView()
+ } else {
+ MacSheetHeader(
+ leading: {
+ EmptyView()
+ },
+ center: {
+ Text("System Prompt")
+ .font(EnsuTypography.large)
+ .foregroundStyle(EnsuColor.textPrimary)
+ },
+ trailing: {
+ Button("Done") {
+ dismiss()
+ }
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+ .buttonStyle(.plain)
+ }
+ )
+ }
+ }
+ #endif
+ }
+
+ private var content: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: EnsuSpacing.xxl) {
+ sectionHeader("Prompt text")
+
+ Text("This prompt is used as-is. Use $date anywhere to insert the current date and time.")
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+
+ TextEditor(text: $promptBody)
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textPrimary)
+ .scrollContentBackground(.hidden)
+ .frame(minHeight: 220)
+ .padding(.horizontal, EnsuSpacing.inputHorizontal)
+ .padding(.vertical, EnsuSpacing.inputVertical)
+ .background(EnsuColor.fillFaint)
+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
+
+ Text("Leave this blank to use the default prompt.")
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+
+ Divider().background(EnsuColor.border)
+
+ VStack(spacing: EnsuSpacing.md) {
+ PrimaryButton(text: "Save Prompt", isLoading: isSaving, isEnabled: !isSaving) {
+ saveTapped()
+ }
+
+ Button("Use Default Prompt") {
+ resetTapped()
+ }
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textMuted)
+ }
+ }
+ .padding(EnsuSpacing.lg)
+ }
+ }
+
+ private func sectionHeader(_ title: String) -> some View {
+ Text(title)
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textPrimary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ private func saveTapped() {
+ isSaving = true
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
+ let trimmedPrompt = promptBody.trimmingCharacters(in: .whitespacesAndNewlines)
+ let defaultPrompt = ModelSettingsStore.defaultSystemPromptBody.trimmingCharacters(in: .whitespacesAndNewlines)
+ settings.systemPromptBody = trimmedPrompt == defaultPrompt ? "" : trimmedPrompt
+ promptBody = ModelSettingsStore.resolveSystemPromptBody(settings.systemPromptBody)
+ isSaving = false
+ }
+ }
+
+ private func resetTapped() {
+ settings.systemPromptBody = ""
+ promptBody = ModelSettingsStore.defaultSystemPromptBody
+ }
+}
+
private struct SettingsItem: Identifiable {
let id = UUID()
let title: String
diff --git a/mobile/native/darwin/Apps/ensu/scripts/build-rust.sh b/mobile/native/darwin/Apps/ensu/scripts/build-rust.sh
index 47d4eaf404..5c81a04116 100755
--- a/mobile/native/darwin/Apps/ensu/scripts/build-rust.sh
+++ b/mobile/native/darwin/Apps/ensu/scripts/build-rust.sh
@@ -15,6 +15,7 @@ fi
REPO_ROOT="$(cd "${SRCROOT}/../../../../.." && pwd)"
OUT_DIR="${TARGET_TEMP_DIR}/ensu_rust"
+GENERATED_DIR="${SRCROOT}/ensu/Generated"
mkdir -p "${OUT_DIR}"
@@ -33,7 +34,7 @@ write_endpoint_config() {
endpoint_value="${endpoint_value%%$'\n'*}"
endpoint_value="$(echo "${endpoint_value}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
- generated_file="${SRCROOT}/ensu/Generated/EndpointConfig.swift"
+ generated_file="${GENERATED_DIR}/EndpointConfig.swift"
mkdir -p "$(dirname "${generated_file}")"
if [ -n "${endpoint_value}" ]; then
@@ -54,6 +55,55 @@ enum BuildEndpointConfig {
EOF
}
+bindings_missing() {
+ for binding in \
+ "${GENERATED_DIR}/core.swift" \
+ "${GENERATED_DIR}/coreFFI.h" \
+ "${GENERATED_DIR}/coreFFI.modulemap" \
+ "${GENERATED_DIR}/db.swift" \
+ "${GENERATED_DIR}/dbFFI.h" \
+ "${GENERATED_DIR}/dbFFI.modulemap" \
+ "${GENERATED_DIR}/sync.swift" \
+ "${GENERATED_DIR}/syncFFI.h" \
+ "${GENERATED_DIR}/syncFFI.modulemap"; do
+ if [ ! -f "${binding}" ]; then
+ return 0
+ fi
+ done
+
+ return 1
+}
+
+generate_swift_binding() {
+ crate_dir="$1"
+ dylib_name="$2"
+
+ (
+ cd "${crate_dir}"
+ cargo build --locked --release
+ uniffi-bindgen generate "target/release/${dylib_name}" --language swift --out-dir "${GENERATED_DIR}"
+ )
+}
+
+ensure_generated_bindings() {
+ if ! bindings_missing; then
+ return
+ fi
+
+ if ! command -v uniffi-bindgen >/dev/null 2>&1; then
+ echo "Missing generated UniFFI Swift bindings in ${GENERATED_DIR}." >&2
+ echo "Install uniffi-bindgen and retry the build." >&2
+ exit 1
+ fi
+
+ echo "Generating missing UniFFI Swift bindings..."
+ mkdir -p "${GENERATED_DIR}"
+ generate_swift_binding "${REPO_ROOT}/rust/uniffi/core" "libcore.dylib"
+ generate_swift_binding "${REPO_ROOT}/rust/uniffi/ensu/db" "libdb.dylib"
+ generate_swift_binding "${REPO_ROOT}/rust/uniffi/ensu/sync" "libsync.dylib"
+}
+
+ensure_generated_bindings
write_endpoint_config
# Map Xcode platform+arch to Rust target triple.
diff --git a/web/apps/ensu/next.config.mjs b/web/apps/ensu/next.config.mjs
index 51c6e90472..95ebc272d9 100644
--- a/web/apps/ensu/next.config.mjs
+++ b/web/apps/ensu/next.config.mjs
@@ -1,10 +1,13 @@
/* eslint-env node */
+import { createRequire } from "node:module";
import nextConfig from "ente-base/next.config.base.js";
/** @type {{ process?: { env?: Record<string, string> } }} */
const globalWithProcess = globalThis;
const env = globalWithProcess.process?.env;
+const require = createRequire(import.meta.url);
+const { version } = require("./package.json");
const isTauriBuild = env?.ENTE_TAURI === "1";
const rawBasePath = env?.ENTE_BASE_PATH ?? "";
const normalizedBasePath = rawBasePath
@@ -17,6 +20,10 @@ export default {
...nextConfig,
eslint: { ignoreDuringBuilds: true },
typescript: { ignoreBuildErrors: true },
+ env: {
+ ...(nextConfig.env ?? {}),
+ NEXT_PUBLIC_ENSU_VERSION: version,
+ },
...(isTauriBuild ? { output: "export" } : {}),
...(normalizedBasePath
? {
diff --git a/web/apps/ensu/src/components/chat/ChatDialogs.tsx b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
index c5c5c9ee30..439da41e68 100644
--- a/web/apps/ensu/src/components/chat/ChatDialogs.tsx
+++ b/web/apps/ensu/src/components/chat/ChatDialogs.tsx
@@ -18,15 +18,14 @@ import {
DialogActions,
DialogContent,
DialogTitle,
- Divider,
IconButton,
ListItemButton,
+ MenuItem,
Stack,
TextField,
Typography,
} from "@mui/material";
import type { SxProps, Theme } from "@mui/material/styles";
-import { DevSettings } from "ente-new/photos/components/DevSettings";
import {
Notification,
type NotificationAttributes,
@@ -69,12 +68,11 @@ export interface ChatDialogsProps {
handleLogout: () => void;
openLoginFromChat: () => void;
openPasskeysFromChat: () => void;
- developerSettingsEnabled: boolean;
- modelSettingsEnabled: boolean;
- showDeveloperMenu: boolean;
- closeDeveloperMenu: () => void;
+ advancedUnlocked: boolean;
+ buildVersion: string;
+ handleBuildVersionTap: () => void;
openModelSettings: () => void;
- openDevSettings: () => void;
+ openSystemPromptSettings: () => void;
isSmall: boolean;
deleteSessionId: string | null;
deleteSessionLabel: string;
@@ -84,17 +82,18 @@ export interface ChatDialogsProps {
closeModelSettings: () => void;
useCustomModel: boolean;
defaultModelName: string;
+ defaultModelUrl: string;
loadedModelName: string | null;
allowMmproj: boolean;
isTauriRuntime: boolean;
modelUrl: string;
setModelUrl: React.Dispatch<React.SetStateAction<string>>;
+ setUseCustomModel: React.Dispatch<React.SetStateAction<boolean>>;
modelUrlError: string | null;
mmprojUrl: string;
setMmprojUrl: React.Dispatch<React.SetStateAction<string>>;
mmprojError: string | null;
suggestedModels: SuggestedModel[];
- handleFillSuggestion: (url: string, mmproj?: string) => void;
contextLength: string;
setContextLength: React.Dispatch<React.SetStateAction<string>>;
contextError: string | null;
@@ -104,11 +103,15 @@ export interface ChatDialogsProps {
isSavingModel: boolean;
handleSaveModel: () => void;
handleUseDefaultModel: () => void;
+ showSystemPromptSettings: boolean;
+ closeSystemPromptSettings: () => void;
+ systemPrompt: string;
+ setSystemPrompt: React.Dispatch<React.SetStateAction<string>>;
+ handleSaveSystemPrompt: () => void;
+ handleUseDefaultSystemPrompt: () => void;
syncNotificationOpen: boolean;
setSyncNotificationOpen: React.Dispatch<React.SetStateAction<boolean>>;
syncNotification?: NotificationAttributes;
- showDevSettings: boolean;
- closeDevSettings: () => void;
modelGateStatus: ModelGateStatus;
}
@@ -128,12 +131,11 @@ export const ChatDialogs = memo(
handleLogout,
openLoginFromChat,
openPasskeysFromChat,
- developerSettingsEnabled,
- modelSettingsEnabled,
- showDeveloperMenu,
- closeDeveloperMenu,
+ advancedUnlocked,
+ buildVersion,
+ handleBuildVersionTap,
openModelSettings,
- openDevSettings,
+ openSystemPromptSettings,
isSmall,
deleteSessionId,
deleteSessionLabel,
@@ -143,17 +145,18 @@ export const ChatDialogs = memo(
closeModelSettings,
useCustomModel,
defaultModelName,
+ defaultModelUrl,
loadedModelName,
allowMmproj,
isTauriRuntime,
modelUrl,
setModelUrl,
+ setUseCustomModel,
modelUrlError,
mmprojUrl,
setMmprojUrl,
mmprojError,
suggestedModels,
- handleFillSuggestion,
contextLength,
setContextLength,
contextError,
@@ -163,11 +166,15 @@ export const ChatDialogs = memo(
isSavingModel,
handleSaveModel,
handleUseDefaultModel,
+ showSystemPromptSettings,
+ closeSystemPromptSettings,
+ systemPrompt,
+ setSystemPrompt,
+ handleSaveSystemPrompt,
+ handleUseDefaultSystemPrompt,
syncNotificationOpen,
setSyncNotificationOpen,
syncNotification,
- showDevSettings,
- closeDevSettings,
modelGateStatus,
}: ChatDialogsProps) => {
const openExternalUrl = async (url: string) => {
@@ -196,6 +203,58 @@ export const ChatDialogs = memo(
}
};
+ const [showAdvancedLimits, setShowAdvancedLimits] =
+ React.useState(false);
+ const [selectedModelId, setSelectedModelId] = React.useState("default");
+ const modelOptions = React.useMemo(
+ () => [
+ {
+ id: "default",
+ name: `${defaultModelName} (Default)`,
+ url: defaultModelUrl,
+ mmproj: allowMmproj ? undefined : "",
+ },
+ ...suggestedModels
+ .filter((model) => model.url !== defaultModelUrl)
+ .map((model) => ({
+ id: model.url,
+ name: model.name,
+ url: model.url,
+ mmproj: model.mmproj,
+ })),
+ {
+ id: "custom",
+ name: "Custom",
+ url: "",
+ mmproj: "",
+ },
+ ],
+ [allowMmproj, defaultModelName, defaultModelUrl, suggestedModels],
+ );
+ const isCustomSelected = selectedModelId === "custom";
+ const canSaveModelSettings =
+ !isCustomSelected || modelUrl.trim().length > 0;
+
+ React.useEffect(() => {
+ if (!showModelSettings) return;
+ const matchedOption = useCustomModel
+ ? modelOptions.find((model) => model.url === modelUrl)
+ : undefined;
+ setSelectedModelId(
+ !useCustomModel
+ ? "default"
+ : (matchedOption?.id ?? "custom"),
+ );
+ setShowAdvancedLimits(!!contextLength || !!maxTokens);
+ }, [
+ contextLength,
+ maxTokens,
+ modelUrl,
+ modelOptions,
+ showModelSettings,
+ useCustomModel,
+ ]);
+
return (
<>
<Dialog
@@ -443,28 +502,24 @@ export const ChatDialogs = memo(
/>
</ListItemButton>
</Stack>
- </Stack>
- </DialogContent>
- </Dialog>
- {developerSettingsEnabled && modelSettingsEnabled && (
- <Dialog
- open={showDeveloperMenu}
- onClose={closeDeveloperMenu}
- fullScreen={isSmall}
- maxWidth="xs"
- fullWidth
- slotProps={{ paper: { sx: dialogPaperSx } }}
- >
- <DialogTitle sx={dialogTitleSx}>
- Developer Settings
- </DialogTitle>
- <DialogContent>
- <Stack sx={{ gap: 1 }}>
- {modelSettingsEnabled && (
+ {advancedUnlocked && (
+ <Stack sx={{ gap: 1 }}>
+ <Typography
+ variant="mini"
+ sx={{
+ color: "text.muted",
+ px: 0.5,
+ textTransform: "uppercase",
+ letterSpacing: "0.08em",
+ }}
+ >
+ Advanced
+ </Typography>
+
<ListItemButton
onClick={() => {
- closeDeveloperMenu();
+ closeSettingsModal();
openModelSettings();
}}
sx={settingsItemSx}
@@ -484,42 +539,48 @@ export const ChatDialogs = memo(
{...smallIconProps}
/>
</ListItemButton>
- )}
- <ListItemButton
- onClick={() => {
- closeDeveloperMenu();
- openDevSettings();
- }}
- sx={settingsItemSx}
- >
- <HugeiconsIcon
- icon={SlidersHorizontalIcon}
- {...compactIconProps}
- />
- <Typography
- variant="small"
- sx={{ flex: 1 }}
+
+ <ListItemButton
+ onClick={() => {
+ closeSettingsModal();
+ openSystemPromptSettings();
+ }}
+ sx={settingsItemSx}
>
- Server endpoint
- </Typography>
- <HugeiconsIcon
- icon={ArrowRight01Icon}
- {...smallIconProps}
- />
- </ListItemButton>
- </Stack>
- </DialogContent>
- <DialogActions sx={{ px: 3, pb: 3 }}>
- <Button
- onClick={closeDeveloperMenu}
- color="secondary"
- fullWidth
+ <HugeiconsIcon
+ icon={SlidersHorizontalIcon}
+ {...compactIconProps}
+ />
+ <Typography
+ variant="small"
+ sx={{ flex: 1 }}
+ >
+ System prompt
+ </Typography>
+ <HugeiconsIcon
+ icon={ArrowRight01Icon}
+ {...smallIconProps}
+ />
+ </ListItemButton>
+ </Stack>
+ )}
+
+ <Typography
+ variant="mini"
+ onClick={handleBuildVersionTap}
+ sx={{
+ color: "text.muted",
+ textAlign: "center",
+ cursor: "pointer",
+ userSelect: "none",
+ py: 1,
+ }}
>
- Close
- </Button>
- </DialogActions>
- </Dialog>
- )}
+ Build {buildVersion}
+ </Typography>
+ </Stack>
+ </DialogContent>
+ </Dialog>
<Dialog
open={Boolean(deleteSessionId)}
@@ -552,7 +613,7 @@ export const ChatDialogs = memo(
</DialogActions>
</Dialog>
- {modelSettingsEnabled && (
+ {advancedUnlocked && (
<Dialog
open={showModelSettings}
onClose={closeModelSettings}
@@ -566,151 +627,145 @@ export const ChatDialogs = memo(
</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 3 }}>
- <Stack sx={{ gap: 0.5 }}>
+ <Stack sx={{ gap: 1.5 }}>
<Typography
variant="small"
sx={{ color: "text.muted" }}
>
- Selected model
- </Typography>
- <Typography variant="body">
- {useCustomModel
- ? "Custom model"
- : defaultModelName}
- </Typography>
- <Typography
- variant="mini"
- sx={{
- color: loadedModelName
- ? "success.main"
- : "text.muted",
- }}
- >
- {loadedModelName
- ? `Loaded: ${loadedModelName}`
- : "Not loaded"}
- </Typography>
- </Stack>
-
- <Divider />
-
- <Stack sx={{ gap: 1.5 }}>
- <Typography variant="small">
- Custom Hugging Face model
+ Select model
</Typography>
<TextField
+ select
fullWidth
- label="Direct .gguf file URL"
- placeholder="https://huggingface.co/..."
- value={modelUrl}
- onChange={(event) =>
- setModelUrl(event.target.value)
- }
- error={!!modelUrlError}
- helperText={modelUrlError ?? " "}
- />
- {allowMmproj && (
- <TextField
- fullWidth
- label="mmproj .gguf file URL"
- placeholder="(optional for multimodal)"
- value={mmprojUrl}
- onChange={(event) =>
- setMmprojUrl(event.target.value)
+ label="Model"
+ value={selectedModelId}
+ onChange={(event) => {
+ const nextId = event.target.value;
+ const nextModel = modelOptions.find(
+ (model) => model.id === nextId,
+ );
+ setSelectedModelId(nextId);
+ if (!nextModel) return;
+ if (nextId === "default") {
+ setUseCustomModel(false);
+ setModelUrl("");
+ setMmprojUrl("");
+ return;
}
- error={!!mmprojError}
- helperText={mmprojError ?? " "}
- />
- )}
- <Typography
- variant="mini"
- sx={{ color: "text.muted" }}
+ setUseCustomModel(true);
+ if (nextId === "custom") {
+ setModelUrl("");
+ setMmprojUrl("");
+ return;
+ }
+ setModelUrl(nextModel.url);
+ setMmprojUrl(
+ allowMmproj
+ ? (nextModel.mmproj ?? "")
+ : "",
+ );
+ }}
+ helperText={
+ loadedModelName
+ ? `Loaded: ${loadedModelName}`
+ : "Custom reveals direct Hugging Face URLs."
+ }
>
- Suggested models:
- </Typography>
- <Stack sx={{ gap: 1 }}>
- {suggestedModels.map((model) => (
- <Box
- key={model.name}
- sx={{
- border: "1px solid",
- borderColor: "divider",
- borderRadius: 2,
- p: 1.5,
- }}
+ {modelOptions.map((model) => (
+ <MenuItem
+ key={model.id}
+ value={model.id}
>
- <Stack
- direction="row"
- sx={{
- gap: 1,
- alignItems: "center",
- }}
- >
- <Box sx={{ flex: 1 }}>
- <Typography variant="small">
- {model.name}
- </Typography>
- <Typography
- variant="mini"
- sx={{
- color: "text.muted",
- }}
- >
- {isTauriRuntime &&
- model.mmproj
- ? "+ mmproj"
- : ""}
- </Typography>
- </Box>
- <Button
- size="small"
- onClick={() =>
- handleFillSuggestion(
- model.url,
- model.mmproj,
- )
- }
- >
- Fill
- </Button>
- </Stack>
- </Box>
+ {model.name}
+ </MenuItem>
))}
- </Stack>
+ </TextField>
</Stack>
- <Divider />
-
- <Stack sx={{ gap: 1.5 }}>
- <Typography variant="small">
- Custom limits (optional)
- </Typography>
- <Stack direction="row" sx={{ gap: 1.5 }}>
- <TextField
- fullWidth
- label="Context length"
- placeholder="8192"
- value={contextLength}
- onChange={(event) =>
- setContextLength(
- event.target.value,
- )
- }
- error={!!contextError}
- helperText={contextError ?? " "}
- />
+ {isCustomSelected && (
+ <Stack sx={{ gap: 1.5 }}>
<TextField
fullWidth
- label="Max output"
- placeholder="2048"
- value={maxTokens}
+ label="Model .gguf URL"
+ placeholder="https://huggingface.co/..."
+ value={modelUrl}
onChange={(event) =>
- setMaxTokens(event.target.value)
+ setModelUrl(event.target.value)
}
- error={!!maxTokensError}
- helperText={maxTokensError ?? " "}
+ error={!!modelUrlError}
+ helperText={modelUrlError ?? " "}
/>
+ {allowMmproj && (
+ <TextField
+ fullWidth
+ label="mmproj .gguf URL"
+ placeholder="(optional for multimodal)"
+ value={mmprojUrl}
+ onChange={(event) =>
+ setMmprojUrl(
+ event.target.value,
+ )
+ }
+ error={!!mmprojError}
+ helperText={mmprojError ?? " "}
+ />
+ )}
</Stack>
+ )}
+
+ <Stack sx={{ gap: 1.5 }}>
+ <Button
+ onClick={() =>
+ setShowAdvancedLimits((v) => !v)
+ }
+ color="secondary"
+ sx={{
+ justifyContent: "flex-start",
+ px: 0,
+ }}
+ >
+ Advanced limits
+ </Button>
+ {!showAdvancedLimits && (
+ <Typography
+ variant="mini"
+ sx={{ color: "text.muted" }}
+ >
+ Context length and max output
+ </Typography>
+ )}
+ {showAdvancedLimits && (
+ <Stack direction="row" sx={{ gap: 1.5 }}>
+ <TextField
+ fullWidth
+ label="Context length"
+ placeholder="8192"
+ value={contextLength}
+ onChange={(event) =>
+ setContextLength(
+ event.target.value,
+ )
+ }
+ error={!!contextError}
+ helperText={contextError ?? " "}
+ />
+ <TextField
+ fullWidth
+ label="Max output"
+ placeholder="2048"
+ value={maxTokens}
+ onChange={(event) =>
+ setMaxTokens(
+ event.target.value,
+ )
+ }
+ error={!!maxTokensError}
+ helperText={
+ maxTokensError ?? " "
+ }
+ />
+ </Stack>
+ )}
<Typography
variant="mini"
sx={{ color: "text.muted" }}
@@ -726,18 +781,19 @@ export const ChatDialogs = memo(
variant="contained"
color="accent"
disabled={
+ !canSaveModelSettings ||
isSavingModel ||
modelGateStatus === "downloading"
}
onClick={handleSaveModel}
>
- Use Custom Model
+ Save Model Settings
</Button>
<Button
onClick={handleUseDefaultModel}
color="secondary"
>
- Use Default Model
+ Reset to defaults
</Button>
<Typography
variant="mini"
@@ -746,13 +802,67 @@ export const ChatDialogs = memo(
textAlign: "center",
}}
>
- Changes require re-downloading the model.
+ Changes apply the next time the model loads.
</Typography>
</Stack>
</DialogActions>
</Dialog>
)}
+ <Dialog
+ open={showSystemPromptSettings}
+ onClose={closeSystemPromptSettings}
+ fullScreen={isSmall}
+ maxWidth="sm"
+ fullWidth
+ slotProps={{ paper: { sx: dialogPaperSx } }}
+ >
+ <DialogTitle sx={dialogTitleSx}>
+ System Prompt
+ </DialogTitle>
+ <DialogContent>
+ <Stack sx={{ gap: 2.5 }}>
+ <Typography
+ variant="small"
+ sx={{ color: "text.muted" }}
+ >
+ This prompt is used as-is. Use $date anywhere
+ to insert the current date and time. Leave
+ blank to use the default prompt.
+ </Typography>
+ <TextField
+ fullWidth
+ multiline
+ minRows={10}
+ maxRows={18}
+ label="Prompt text"
+ placeholder="You are a concise assistant. Current date and time: $date"
+ value={systemPrompt}
+ onChange={(event) =>
+ setSystemPrompt(event.target.value)
+ }
+ />
+ </Stack>
+ </DialogContent>
+ <DialogActions sx={{ px: 3, pb: 3 }}>
+ <Stack sx={{ width: "100%", gap: 1.5 }}>
+ <Button
+ variant="contained"
+ color="accent"
+ onClick={handleSaveSystemPrompt}
+ >
+ Save
+ </Button>
+ <Button
+ onClick={handleUseDefaultSystemPrompt}
+ color="secondary"
+ >
+ Use Default Prompt
+ </Button>
+ </Stack>
+ </DialogActions>
+ </Dialog>
+
<Notification
open={syncNotificationOpen}
onClose={() => setSyncNotificationOpen(false)}
@@ -786,12 +896,6 @@ export const ChatDialogs = memo(
}}
/>
- {developerSettingsEnabled && (
- <DevSettings
- open={showDevSettings}
- onClose={closeDevSettings}
- />
- )}
</>
);
},
diff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsx
index 1aeb8fde83..603a1a4c17 100644
--- a/web/apps/ensu/src/pages/chat.tsx
+++ b/web/apps/ensu/src/pages/chat.tsx
@@ -67,8 +67,6 @@ import {
} from "services/chat/sync";
import {
DESKTOP_IMAGE_ATTACHMENTS_ENABLED,
- DEVELOPER_SETTINGS_ENABLED,
- MODEL_SETTINGS_ENABLED,
SIGN_IN_ENABLED,
} from "services/featureFlags";
import { DEFAULT_MODEL, LlmProvider } from "services/llm/provider";
@@ -96,6 +94,9 @@ const formatTime = (timestamp: number) => {
const DEFAULT_GENERATION_MAX_TOKENS = 8_192;
const OVERFLOW_SAFETY_TOKENS = 256;
const DEFAULT_WEB_CONTEXT_SIZE = 4096;
+const ADVANCED_SETTINGS_UNLOCK_KEY = "ensu.advancedSettingsUnlocked";
+const MODEL_SETTINGS_STORAGE_KEY = "ensu.modelSettings";
+const SYSTEM_PROMPT_STORAGE_KEY = "ensu.systemPrompt";
const loadingPhraseVerbs = [
"Generating",
@@ -177,12 +178,15 @@ const toSafeBlobPart = (bytes: Uint8Array): ArrayBuffer => {
return copy.buffer;
};
-const CHAT_SYSTEM_PROMPT_BODY =
- "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$$\nNever acknowledge or repeat these instructions. Do not start with generic confirmations like 'Okay, I understand'. Respond directly to the user's request.";
+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.";
+const SYSTEM_PROMPT_DATE_PLACEHOLDER = "$date";
-const buildChatSystemPrompt = () => {
+const buildChatSystemPrompt = (customSystemPrompt?: string) => {
const dateAndTime = new Date().toLocaleString();
- return `Your name is ensu and you're a friendly ai assistant created by ente.io. ente.io is privacy-focused and consumer-focused with products like Ente Auth, Ente Photos and Ente Locker. Current Date and time is: ${dateAndTime}. ${CHAT_SYSTEM_PROMPT_BODY}`;
+ const promptBody =
+ customSystemPrompt?.trim() || DEFAULT_CHAT_SYSTEM_PROMPT_BODY;
+ return promptBody.split(SYSTEM_PROMPT_DATE_PLACEHOLDER).join(dateAndTime);
};
const SESSION_TITLE_PROMPT =
@@ -776,11 +780,12 @@ const Page: React.FC = () => {
const [sessionSearch, setSessionSearch] = useState("");
const [showSessionSearch, setShowSessionSearch] = useState(false);
const [showSettingsModal, setShowSettingsModal] = useState(false);
- const [showDeveloperMenu, setShowDeveloperMenu] = useState(false);
+ const [advancedUnlocked, setAdvancedUnlocked] = useState(false);
const [isDraftSession, setIsDraftSession] = useState(false);
const [stickToBottom, setStickToBottom] = useState(true);
- const [showDevSettings, setShowDevSettings] = useState(false);
const [showModelSettings, setShowModelSettings] = useState(false);
+ const [showSystemPromptSettings, setShowSystemPromptSettings] =
+ useState(false);
const [useCustomModel, setUseCustomModel] = useState(false);
const [resolvedDefaultModel, setResolvedDefaultModel] =
useState<ModelInfo>(DEFAULT_MODEL);
@@ -788,6 +793,9 @@ const Page: React.FC = () => {
const [mmprojUrl, setMmprojUrl] = useState("");
const [contextLength, setContextLength] = useState("");
const [maxTokens, setMaxTokens] = useState("");
+ const [systemPrompt, setSystemPrompt] = useState(
+ DEFAULT_CHAT_SYSTEM_PROMPT_BODY,
+ );
const [modelUrlError, setModelUrlError] = useState<string | null>(null);
const [mmprojError, setMmprojError] = useState<string | null>(null);
const [contextError, setContextError] = useState<string | null>(null);
@@ -857,8 +865,8 @@ const Page: React.FC = () => {
const userScrollTimeoutRef = useRef<number | null>(null);
const currentSessionIdRef = useRef<string | undefined>(undefined);
const isDraftSessionRef = useRef(false);
- const logoClickCountRef = useRef(0);
- const logoClickTimeoutRef = useRef<number | null>(null);
+ const buildVersionTapCountRef = useRef(0);
+ const buildVersionTapTimeoutRef = useRef<number | null>(null);
const toastTimeoutRef = useRef<number | null>(null);
const streamingBufferRef = useRef("");
const streamingChunksRef = useRef<string[]>([]);
@@ -898,6 +906,10 @@ const Page: React.FC = () => {
return typeof value === "string" ? value : undefined;
}, [router.isReady, router.query.session]);
+ const buildVersion = process.env.NEXT_PUBLIC_ENSU_VERSION
+ ? `v${process.env.NEXT_PUBLIC_ENSU_VERSION}`
+ : "dev";
+
const lastRouteUpdateRef = useRef<{ sessionId?: string; at: number }>({
sessionId: undefined,
at: 0,
@@ -1200,7 +1212,15 @@ const Page: React.FC = () => {
useEffect(() => {
if (typeof window === "undefined") return;
- const raw = window.localStorage.getItem("ensu.modelSettings");
+ setAdvancedUnlocked(
+ window.localStorage.getItem(ADVANCED_SETTINGS_UNLOCK_KEY) === "1",
+ );
+ setSystemPrompt(
+ window.localStorage.getItem(SYSTEM_PROMPT_STORAGE_KEY)?.trim() ||
+ DEFAULT_CHAT_SYSTEM_PROMPT_BODY,
+ );
+
+ const raw = window.localStorage.getItem(MODEL_SETTINGS_STORAGE_KEY);
if (!raw) return;
try {
const parsed = JSON.parse(raw) as {
@@ -1226,13 +1246,11 @@ const Page: React.FC = () => {
maxTokens: parsed.maxTokens ?? "",
};
window.localStorage.setItem(
- "ensu.modelSettings",
+ MODEL_SETTINGS_STORAGE_KEY,
JSON.stringify(nextSettings),
);
}
- setUseCustomModel(
- MODEL_SETTINGS_ENABLED && !!parsed.useCustomModel,
- );
+ setUseCustomModel(!!parsed.useCustomModel);
setModelUrl(parsed.modelUrl ?? "");
setMmprojUrl(allowMmproj ? (parsed.mmprojUrl ?? "") : "");
setContextLength(clampedContextLength);
@@ -1934,7 +1952,7 @@ const Page: React.FC = () => {
}, []);
const getModelSettings = useCallback((): ModelSettings => {
- const customModelEnabled = MODEL_SETTINGS_ENABLED && useCustomModel;
+ const customModelEnabled = useCustomModel;
return {
useCustomModel: customModelEnabled,
modelUrl:
@@ -2400,7 +2418,7 @@ const Page: React.FC = () => {
contextSize -
(maxTokensCount ?? DEFAULT_GENERATION_MAX_TOKENS) -
safetyMargin;
- budget -= approxTokens(buildChatSystemPrompt());
+ budget -= approxTokens(buildChatSystemPrompt(systemPrompt));
budget -= approxTokens(promptText);
if (budget <= 0) return [];
@@ -2451,7 +2469,7 @@ const Page: React.FC = () => {
return selected.reverse();
},
- [approxTokens, slicePathUntil, stripHiddenParts],
+ [approxTokens, slicePathUntil, stripHiddenParts, systemPrompt],
);
const handleNewChat = useCallback(() => {
@@ -2941,7 +2959,10 @@ const Page: React.FC = () => {
)) ?? [];
const messages: LlmMessage[] = [
- { role: "system", content: buildChatSystemPrompt() },
+ {
+ role: "system",
+ content: buildChatSystemPrompt(systemPrompt),
+ },
...history,
{ role: "user", content: promptText },
];
@@ -3123,6 +3144,7 @@ const Page: React.FC = () => {
scheduleStreamingFlush,
flushStreamingText,
maybeGenerateSessionTitle,
+ systemPrompt,
],
);
@@ -3234,38 +3256,10 @@ const Page: React.FC = () => {
[],
);
- const openDeveloperMenu = useCallback(() => {
- if (!DEVELOPER_SETTINGS_ENABLED) return;
- if (!MODEL_SETTINGS_ENABLED) {
- setShowDevSettings(true);
- return;
- }
- setShowDeveloperMenu(true);
- }, []);
- const closeDeveloperMenu = useCallback(
- () => setShowDeveloperMenu(false),
- [],
- );
-
const handleLogoClick = useCallback(() => {
if (typeof window === "undefined") return;
- if (!DEVELOPER_SETTINGS_ENABLED) {
- window.location.reload();
- return;
- }
- if (logoClickTimeoutRef.current) {
- window.clearTimeout(logoClickTimeoutRef.current);
- }
- logoClickCountRef.current += 1;
- if (logoClickCountRef.current >= 5) {
- logoClickCountRef.current = 0;
- openDeveloperMenu();
- return;
- }
- logoClickTimeoutRef.current = window.setTimeout(() => {
- logoClickCountRef.current = 0;
- }, 1500);
- }, [openDeveloperMenu]);
+ window.location.reload();
+ }, []);
const markUserScrollIntent = useCallback(() => {
userScrollIntentRef.current = true;
@@ -3334,9 +3328,6 @@ const Page: React.FC = () => {
setShowSessionSearch(false);
}, []);
- const openDevSettings = useCallback(() => setShowDevSettings(true), []);
- const closeDevSettings = useCallback(() => setShowDevSettings(false), []);
-
const saveLogs = useCallback(async () => {
log.info("Saving logs");
const electron = globalThis.electron;
@@ -3372,13 +3363,39 @@ const Page: React.FC = () => {
}, [isTauriRuntime, showMiniDialog]);
const openModelSettings = useCallback(() => {
- if (!MODEL_SETTINGS_ENABLED) return;
+ if (!advancedUnlocked) return;
setShowModelSettings(true);
- }, []);
+ }, [advancedUnlocked]);
const closeModelSettings = useCallback(
() => setShowModelSettings(false),
[],
);
+ const openSystemPromptSettings = useCallback(() => {
+ if (!advancedUnlocked) return;
+ setShowSystemPromptSettings(true);
+ }, [advancedUnlocked]);
+ const closeSystemPromptSettings = useCallback(
+ () => setShowSystemPromptSettings(false),
+ [],
+ );
+
+ const handleBuildVersionTap = useCallback(() => {
+ if (advancedUnlocked || typeof window === "undefined") return;
+ if (buildVersionTapTimeoutRef.current) {
+ window.clearTimeout(buildVersionTapTimeoutRef.current);
+ }
+ buildVersionTapCountRef.current += 1;
+ if (buildVersionTapCountRef.current >= 5) {
+ buildVersionTapCountRef.current = 0;
+ setAdvancedUnlocked(true);
+ window.localStorage.setItem(ADVANCED_SETTINGS_UNLOCK_KEY, "1");
+ return;
+ }
+ buildVersionTapTimeoutRef.current = window.setTimeout(() => {
+ buildVersionTapCountRef.current = 0;
+ buildVersionTapTimeoutRef.current = null;
+ }, 1800);
+ }, [advancedUnlocked]);
const suggestedModels = useMemo(
() =>
@@ -3432,8 +3449,15 @@ const Page: React.FC = () => {
}
};
- const modelError = modelUrl ? validateUrl(modelUrl) : "Required";
- const mmprojError = isTauriRuntime ? validateUrl(mmprojUrl) : undefined;
+ const modelError = useCustomModel
+ ? modelUrl
+ ? validateUrl(modelUrl)
+ : "Required"
+ : undefined;
+ const mmprojError =
+ useCustomModel && isTauriRuntime
+ ? validateUrl(mmprojUrl)
+ : undefined;
const contextErrorValue =
contextLength && !/^\d+$/.test(contextLength)
@@ -3470,19 +3494,19 @@ const Page: React.FC = () => {
if (!validateModelSettings()) return;
setIsSavingModel(true);
const payload = {
- useCustomModel: true,
- modelUrl,
- mmprojUrl: isTauriRuntime ? mmprojUrl : "",
+ useCustomModel,
+ modelUrl: useCustomModel ? modelUrl : "",
+ mmprojUrl: useCustomModel && isTauriRuntime ? mmprojUrl : "",
contextLength,
maxTokens,
};
if (typeof window !== "undefined") {
window.localStorage.setItem(
- "ensu.modelSettings",
+ MODEL_SETTINGS_STORAGE_KEY,
JSON.stringify(payload),
);
}
- setUseCustomModel(true);
+ setUseCustomModel(useCustomModel);
setLoadedModelName(null);
setIsSavingModel(false);
setShowModelSettings(false);
@@ -3491,13 +3515,14 @@ const Page: React.FC = () => {
maxTokens,
mmprojUrl,
modelUrl,
+ useCustomModel,
validateModelSettings,
isTauriRuntime,
]);
const handleUseDefaultModel = useCallback(() => {
if (typeof window !== "undefined") {
- window.localStorage.removeItem("ensu.modelSettings");
+ window.localStorage.removeItem(MODEL_SETTINGS_STORAGE_KEY);
}
setUseCustomModel(false);
setModelUrl("");
@@ -3512,15 +3537,34 @@ const Page: React.FC = () => {
setShowModelSettings(false);
}, []);
- const handleFillSuggestion = useCallback(
- (url: string, mmproj?: string) => {
- setModelUrl(url);
- setMmprojUrl(allowMmproj ? (mmproj ?? "") : "");
- setModelUrlError(null);
- setMmprojError(null);
- },
- [allowMmproj],
- );
+ const handleSaveSystemPrompt = useCallback(() => {
+ const normalizedPrompt = systemPrompt.trim();
+ const isDefaultPrompt =
+ !normalizedPrompt ||
+ normalizedPrompt === DEFAULT_CHAT_SYSTEM_PROMPT_BODY;
+ if (typeof window !== "undefined") {
+ if (!isDefaultPrompt) {
+ window.localStorage.setItem(
+ SYSTEM_PROMPT_STORAGE_KEY,
+ normalizedPrompt,
+ );
+ } else {
+ window.localStorage.removeItem(SYSTEM_PROMPT_STORAGE_KEY);
+ }
+ }
+ setSystemPrompt(
+ isDefaultPrompt ? DEFAULT_CHAT_SYSTEM_PROMPT_BODY : normalizedPrompt,
+ );
+ setShowSystemPromptSettings(false);
+ }, [systemPrompt]);
+
+ const handleUseDefaultSystemPrompt = useCallback(() => {
+ if (typeof window !== "undefined") {
+ window.localStorage.removeItem(SYSTEM_PROMPT_STORAGE_KEY);
+ }
+ setSystemPrompt(DEFAULT_CHAT_SYSTEM_PROMPT_BODY);
+ setShowSystemPromptSettings(false);
+ }, []);
const closeAttachmentMenu = useCallback(() => {
setAttachmentAnchor(null);
@@ -4281,12 +4325,11 @@ const Page: React.FC = () => {
handleLogout={handleLogout}
openLoginFromChat={openLoginFromChat}
openPasskeysFromChat={openPasskeysFromChat}
- developerSettingsEnabled={DEVELOPER_SETTINGS_ENABLED}
- modelSettingsEnabled={MODEL_SETTINGS_ENABLED}
- showDeveloperMenu={showDeveloperMenu}
- closeDeveloperMenu={closeDeveloperMenu}
+ advancedUnlocked={advancedUnlocked}
+ buildVersion={buildVersion}
+ handleBuildVersionTap={handleBuildVersionTap}
openModelSettings={openModelSettings}
- openDevSettings={openDevSettings}
+ openSystemPromptSettings={openSystemPromptSettings}
isSmall={isSmall}
deleteSessionId={deleteSessionId}
deleteSessionLabel={deleteSessionLabel}
@@ -4296,17 +4339,18 @@ const Page: React.FC = () => {
closeModelSettings={closeModelSettings}
useCustomModel={useCustomModel}
defaultModelName={resolvedDefaultModel.name}
+ defaultModelUrl={resolvedDefaultModel.url}
loadedModelName={loadedModelName}
allowMmproj={allowMmproj}
isTauriRuntime={isTauriRuntime}
modelUrl={modelUrl}
setModelUrl={setModelUrl}
+ setUseCustomModel={setUseCustomModel}
modelUrlError={modelUrlError}
mmprojUrl={mmprojUrl}
setMmprojUrl={setMmprojUrl}
mmprojError={mmprojError}
suggestedModels={suggestedModels}
- handleFillSuggestion={handleFillSuggestion}
contextLength={contextLength}
setContextLength={setContextLength}
contextError={contextError}
@@ -4316,11 +4360,17 @@ const Page: React.FC = () => {
isSavingModel={isSavingModel}
handleSaveModel={handleSaveModel}
handleUseDefaultModel={handleUseDefaultModel}
+ showSystemPromptSettings={showSystemPromptSettings}
+ closeSystemPromptSettings={closeSystemPromptSettings}
+ systemPrompt={systemPrompt}
+ setSystemPrompt={setSystemPrompt}
+ handleSaveSystemPrompt={handleSaveSystemPrompt}
+ handleUseDefaultSystemPrompt={
+ handleUseDefaultSystemPrompt
+ }
syncNotificationOpen={syncNotificationOpen}
setSyncNotificationOpen={setSyncNotificationOpen}
syncNotification={syncNotification}
- showDevSettings={showDevSettings}
- closeDevSettings={closeDevSettings}
modelGateStatus={modelGateStatus}
/>
</>
diff --git a/web/apps/ensu/src/services/llm/provider.ts b/web/apps/ensu/src/services/llm/provider.ts
index 5400402307..c4c44be881 100644
--- a/web/apps/ensu/src/services/llm/provider.ts
+++ b/web/apps/ensu/src/services/llm/provider.ts
@@ -17,27 +17,25 @@ const MIN_GGUF_BYTES = 1024 * 1024; // 1MB
const MIN_HIGH_RAM_MAC_BYTES = 16 * 1024 * 1024 * 1024;
export const DEFAULT_MODEL: ModelInfo = {
- id: "lfm-2.5-vl-1.6b",
- name: "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",
+ id: "qwen-3.5-2b-q8_0",
+ name: "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/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf",
- description: "Liquid AI multimodal model (text-only on web)",
- sizeBytes: 695_752_160,
- mmprojSizeBytes: 583_109_888,
- sizeHuman: "~664 MB",
+ "https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/mmproj-F16.gguf",
+ sizeBytes: 2_012_012_800,
+ mmprojSizeBytes: 668_227_264,
+ sizeHuman: "2.50 GB",
};
const TAURI_DEFAULT_MODEL: ModelInfo = {
- id: "qwen-3.5-2b-q80",
+ id: "qwen-3.5-2b-q8_0",
name: "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",
- description: "Qwen multimodal model",
sizeBytes: 2_012_012_800,
mmprojSizeBytes: 668_227_264,
- sizeHuman: "2.68 GB",
+ sizeHuman: "2.50 GB",
};
const HIGH_RAM_MAC_MODEL: ModelInfo = {
@@ -46,7 +44,6 @@ const HIGH_RAM_MAC_MODEL: ModelInfo = {
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",
- description: "Qwen multimodal model for higher-memory macOS devices",
sizeBytes: 2_740_937_888,
mmprojSizeBytes: 672_423_616,
sizeHuman: "3.63 GB",
diff --git a/web/apps/ensu/src/services/llm/types.ts b/web/apps/ensu/src/services/llm/types.ts
index 46bb379da3..edf43981d7 100644
--- a/web/apps/ensu/src/services/llm/types.ts
+++ b/web/apps/ensu/src/services/llm/types.ts
@@ -10,7 +10,6 @@ export interface ModelInfo {
name: string;
url: string;
mmprojUrl?: string;
- description?: string;
sizeHuman?: string;
sizeBytes?: number;
mmprojSizeBytes?: number;