Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

fix issues

Prateek Sunal88cab95b4dd9
diff --git a/mobile/native/AGENTS.md b/mobile/native/AGENTS.md
new file mode 100644
index 0000000000..6eb6208044
--- /dev/null
+++ b/mobile/native/AGENTS.md
@@ -0,0 +1,34 @@
+# Repository Guidelines
+
+## Project Structure & Module Organization
+- `android/apps/ensu`: Android app workspace (Gradle Kotlin DSL). Key modules include `app-ui`, `domain`, `data`, `crypto-auth-core`, and `rust`.
+- `android/packages/rust`: Shared Rust/Android integration module referenced by the app workspace.
+- `darwin/Apps/ensu` and `darwin/Apps/tv`: Xcode projects for Apple platforms.
+- `darwin/Packages/*`: Swift Package Manager libraries. Source code under `Sources/`, tests under `Tests/`.
+
+## Build, Test, and Development Commands
+Run commands from the module root noted below.
+- Android build (debug): `cd android/apps/ensu && ./gradlew assembleDebug`
+- Android unit tests: `cd android/apps/ensu && ./gradlew test`
+- Apple apps (open in Xcode):
+ - `open darwin/Apps/ensu/ensu.xcodeproj`
+ - `open darwin/darwin.xcworkspace`
+- Swift package tests: `swift test --package-path darwin/Packages/EnteCore`
+
+## Coding Style & Naming Conventions
+- Kotlin: 4-space indentation, `camelCase` for variables/functions, `PascalCase` for types.
+- Swift: 4-space indentation, `camelCase` for members, `PascalCase` for types.
+- Align module/file names with feature or domain (e.g., `app-ui`, `crypto-auth-core`).
+
+## Testing Guidelines
+- Swift packages use `XCTest`; place tests in `darwin/Packages/*/Tests`.
+- Name tests by behavior (e.g., `TokenRefreshTests`, `RefreshTokenSucceedsWhenExpired`).
+- Prefer focused unit tests per module; add integration tests in app targets as needed.
+
+## Commit & Pull Request Guidelines
+- Commit messages: short, imperative subjects, often with tags like `[mob]`, `[web]`, or `fix(scope):`.
+- PRs should include a clear description and reasoning, linked issues, and screenshots for UI changes (Android/iOS/macOS/tvOS).
+
+## Configuration & Security Notes
+- Keep secrets out of the repo; use local `.env` or Xcode/Gradle user-specific config.
+- When adding modules/packages, update Gradle `settings.gradle.kts` or Swift package manifests accordingly.
diff --git a/mobile/native/android/apps/ensu/AGENTS.md b/mobile/native/android/apps/ensu/AGENTS.md
new file mode 100644
index 0000000000..9a4063959a
--- /dev/null
+++ b/mobile/native/android/apps/ensu/AGENTS.md
@@ -0,0 +1,34 @@
+# Repository Guidelines
+
+## Project Structure & Module Organization
+- `app-ui/`: Android UI layer (Compose screens, resources under `src/main/res`).
+- `domain/`: Business logic and use cases.
+- `data/`: Repositories, data sources, and persistence/networking.
+- `crypto-auth-core/`: Shared crypto/auth logic.
+- `rust/` (via `android/packages/rust`): Rust integration module.
+- Gradle configuration lives in `build.gradle.kts`, `settings.gradle.kts`, and `gradle/`.
+
+## Build, Test, and Development Commands
+Run commands from `android/apps/ensu`.
+- `./gradlew assembleDebug`: Build a debug APK.
+- `./gradlew test`: Run unit tests for modules that include tests.
+- `./gradlew lint`: Run Android lint checks (if configured).
+
+## Coding Style & Naming Conventions
+- Kotlin: 4-space indentation, `camelCase` for functions/variables, `PascalCase` for classes/types.
+- Keep file/module names aligned with feature or domain (e.g., `app-ui`, `crypto-auth-core`).
+- Prefer small, focused classes and functions; avoid mixing UI and domain logic.
+
+## Testing Guidelines
+- Use JUnit for JVM unit tests under `src/test` in each module.
+- Name tests after behavior (e.g., `TokenRefreshTest`, `AuthStateReducerTest`).
+- Run tests with `./gradlew test` and keep new logic covered where feasible.
+
+## Commit & Pull Request Guidelines
+- Commit messages are short, imperative, and often tagged (e.g., `[mob] Fix login crash`).
+- PRs should include a clear summary, reasoning, and linked issues.
+- Attach screenshots for UI changes on Android.
+
+## Security & Configuration Tips
+- Do not commit secrets. Use local Gradle properties or environment variables.
+- Store device-specific configs outside the repo when possible.
diff --git a/mobile/native/android/apps/ensu/README.md b/mobile/native/android/apps/ensu/README.md
new file mode 100644
index 0000000000..ff238709a3
--- /dev/null
+++ b/mobile/native/android/apps/ensu/README.md
@@ -0,0 +1,71 @@
+# Ensu Android
+
+## Prerequisites
+
+- Android Studio or command-line tools
+- JDK 17
+- Android SDK with API level 34
+- Rust toolchain (for building native libraries)
+
+## Building
+
+### 1. Build Rust Libraries
+
+Before building the Android app, compile the Rust native libraries:
+
+```bash
+cd mobile/native/android/packages/rust/tool
+./build_android.sh
+```
+
+### 2. Build Debug APK
+
+```bash
+cd mobile/native/android/apps/ensu
+./gradlew :app-ui:assembleDebug
+```
+
+Output: `app-ui/build/outputs/apk/debug/app-ui-debug.apk`
+
+### 3. Build Release APK
+
+```bash
+./gradlew :app-ui:assembleRelease
+```
+
+Output: `app-ui/build/outputs/apk/release/app-ui-release.apk`
+
+Note: Release builds use a debug keystore located at `debug.keystore`. For production releases, configure your own signing keys in `app-ui/build.gradle.kts`.
+
+## Installation
+
+### Install Debug Build
+
+```bash
+./gradlew :app-ui:installDebug
+```
+
+Or via adb:
+
+```bash
+adb install -r app-ui/build/outputs/apk/debug/app-ui-debug.apk
+```
+
+### Install Release Build
+
+```bash
+adb install -r app-ui/build/outputs/apk/release/app-ui-release.apk
+```
+
+Note: If upgrading from a differently signed build, uninstall first:
+
+```bash
+adb uninstall io.ente.ensu
+```
+
+## Project Structure
+
+- `app-ui/` - Main application module (Compose UI)
+- `domain/` - Domain layer (business logic, state management)
+- `data/` - Data layer (repositories, network, storage)
+- `crypto-auth-core/` - Cryptographic authentication utilities
diff --git a/mobile/native/android/apps/ensu/app-ui/build.gradle.kts b/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
index 07fe2804e6..62fa4881a0 100644
--- a/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
+++ b/mobile/native/android/apps/ensu/app-ui/build.gradle.kts
@@ -64,6 +64,7 @@ dependencies {
implementation("androidx.compose.material3:material3")
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-tooling-preview")
+ implementation("androidx.compose.animation:animation")
implementation("androidx.compose.material:material-icons-core")
implementation("androidx.compose.material:material-icons-extended")
implementation("androidx.compose.ui:ui-text")
@@ -71,6 +72,8 @@ dependencies {
implementation("androidx.core:core-ktx:1.12.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0")
+ implementation("androidx.navigation:navigation-compose:2.7.7")
+ implementation("com.google.accompanist:accompanist-navigation-animation:0.34.0")
implementation(project(":domain"))
implementation(project(":data"))
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xml b/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xml
index d8c8bc619b..f2b17bf0e9 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xml
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/AndroidManifest.xml
@@ -12,7 +12,8 @@
<activity
android:name=".MainActivity"
android:exported="true"
- android:windowSoftInputMode="adjustResize">
+ android:windowSoftInputMode="adjustResize"
+ android:enableOnBackInvokedCallback="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/AppViewModel.kt
index 8fef04ae4c..05a0d7c1ab 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
@@ -1,16 +1,19 @@
package io.ente.ensu
import android.app.Application
+import android.os.Build
+import android.content.pm.PackageManager
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import io.ente.ensu.data.EndpointPreferencesDataStore
import io.ente.ensu.data.SessionPreferencesDataStore
import io.ente.ensu.data.auth.EnsuAuthService
-import io.ente.ensu.data.logging.InMemoryLogRepository
+import io.ente.ensu.data.logging.FileLogRepository
import io.ente.ensu.data.storage.CredentialStore
import io.ente.ensu.data.llm.InferenceRsProvider
import io.ente.ensu.data.chat.RustChatRepository
import io.ente.ensu.data.chat.RustChatSyncRepository
+import io.ente.ensu.domain.model.LogLevel
import io.ente.ensu.domain.store.AppStore
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.first
@@ -27,7 +30,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
const val fixedEndpoint = "https://1227635d8108.ngrok-free.app"
}
- val logRepository = InMemoryLogRepository()
+ val logRepository = FileLogRepository(application)
private val llmProvider = InferenceRsProvider(
modelDir = File(application.filesDir, "llm")
)
@@ -55,6 +58,10 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
val currentEndpointFlow = authService.currentEndpointFlow
init {
+ val appVersion = runCatching { getAppVersion(application) }.getOrDefault("unknown")
+ val deviceInfo = "app=$appVersion\ndevice=${Build.MANUFACTURER} ${Build.MODEL}\nos=${Build.VERSION.RELEASE} (sdk=${Build.VERSION.SDK_INT})"
+ logRepository.log(LogLevel.Info, "App launched", details = deviceInfo, tag = "App")
+
runBlocking {
val endpoint = endpointPreferences.endpointFlow.first()
if (endpoint.isNullOrBlank()) {
@@ -74,4 +81,22 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
}
}
}
+
+ @Suppress("DEPRECATION")
+ private fun getAppVersion(application: Application): String {
+ val packageManager = application.packageManager
+ val packageName = application.packageName
+ val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
+ } else {
+ packageManager.getPackageInfo(packageName, 0)
+ }
+ val versionName = packageInfo.versionName ?: "unknown"
+ val versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
+ packageInfo.longVersionCode
+ } else {
+ packageInfo.versionCode.toLong()
+ }
+ return "$versionName+$versionCode"
+ }
}
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 1b9547256d..24b4c3d7d8 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
@@ -12,6 +12,7 @@ fun EnsuApp(appViewModel: AppViewModel) {
appState = appState,
store = appViewModel.store,
logs = logs,
+ logRepository = appViewModel.logRepository,
authService = appViewModel.authService,
currentEndpointFlow = appViewModel.currentEndpointFlow
)
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 3e47698c67..5330135f38 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
@@ -1,55 +1,81 @@
-@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
+@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class, androidx.compose.animation.ExperimentalAnimationApi::class)
package io.ente.ensu
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
+import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import android.content.Intent
import android.webkit.MimeTypeMap
import android.widget.Toast
+import androidx.activity.compose.BackHandler
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInHorizontally
+import androidx.compose.animation.slideOutHorizontally
+import androidx.compose.animation.core.tween
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.outlined.ArrowBack
-import androidx.compose.material.icons.outlined.Download
-import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
+import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
+import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
-import androidx.core.content.FileProvider
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.ui.res.painterResource
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.compose.ui.platform.LocalLifecycleOwner
+import androidx.core.content.FileProvider
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.navigation.NavBackStackEntry
+import androidx.navigation.compose.currentBackStackEntryAsState
+import com.google.accompanist.navigation.animation.AnimatedNavHost
+import com.google.accompanist.navigation.animation.composable
+import com.google.accompanist.navigation.animation.rememberAnimatedNavController
import io.ente.ensu.auth.AuthFlowScreen
import io.ente.ensu.chat.ChatView
import io.ente.ensu.chat.SessionDrawer
-import io.ente.ensu.components.ChoiceDialog
+import io.ente.ensu.components.NativeChoiceDialog
import io.ente.ensu.components.EnsuLogo
import io.ente.ensu.data.auth.EnsuAuthService
+import io.ente.ensu.data.logging.FileLogRepository
import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.designsystem.HugeIcons
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
import io.ente.ensu.domain.model.Attachment
@@ -62,6 +88,7 @@ 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 kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import java.io.File
@@ -73,17 +100,46 @@ fun HomeView(
appState: AppState,
store: AppStore,
logs: List<LogEntry>,
+ logRepository: FileLogRepository,
authService: EnsuAuthService,
currentEndpointFlow: Flow<String>
) {
val drawerState = androidx.compose.material3.rememberDrawerState(DrawerValue.Closed)
val scope = rememberCoroutineScope()
val context = androidx.compose.ui.platform.LocalContext.current
+ val navController = rememberAnimatedNavController()
+ val lifecycleOwner = LocalLifecycleOwner.current
+ val latestChatState by rememberUpdatedState(appState.chat)
+ val latestStore by rememberUpdatedState(store)
+ val navBackStackEntry by navController.currentBackStackEntryAsState()
+ val currentRoute = navBackStackEntry?.destination?.route ?: HomeRoute.Chat
+ val isChatRoute = currentRoute == HomeRoute.Chat
var isShowingAuth by remember { mutableStateOf(false) }
var isShowingSignOutDialog by remember { mutableStateOf(false) }
- var destination by remember { mutableStateOf(HomeDestination.Chat) }
var showAttachmentDownloads by remember { mutableStateOf(false) }
var deleteSessionTarget by remember { mutableStateOf<io.ente.ensu.domain.model.ChatSession?>(null) }
+ var showLogShareDialog by remember { mutableStateOf(false) }
+
+ var developerTapCount by remember { mutableStateOf(0) }
+ var lastDeveloperTapAt by remember { mutableStateOf<Long?>(null) }
+ var showDeveloperDialog by remember { mutableStateOf(false) }
+
+ val handleDeveloperTap: () -> Unit = 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 = androidx.activity.compose.rememberLauncherForActivityResult(
contract = androidx.activity.result.contract.ActivityResultContracts.GetContent()
@@ -121,59 +177,86 @@ fun HomeView(
}
}
+ val exportLogsLauncher = androidx.activity.compose.rememberLauncherForActivityResult(
+ contract = androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/zip")
+ ) { uri ->
+ if (uri == null) return@rememberLauncherForActivityResult
+ scope.launch {
+ try {
+ val zipFile = logRepository.createLogsZip()
+ context.contentResolver.openOutputStream(uri)?.use { out ->
+ zipFile.inputStream().use { input -> input.copyTo(out) }
+ }
+ Toast.makeText(context, "Logs exported", Toast.LENGTH_SHORT).show()
+ } catch (err: Throwable) {
+ Toast.makeText(context, "Export failed: ${err.message ?: "Unknown error"}", Toast.LENGTH_SHORT).show()
+ }
+ }
+ }
+
+ val shareLogs: () -> Unit = {
+ scope.launch {
+ try {
+ val zipFile = logRepository.createLogsZip()
+ val uri = FileProvider.getUriForFile(
+ context,
+ "${context.packageName}.fileprovider",
+ zipFile
+ )
+ val intent = Intent(Intent.ACTION_SEND).apply {
+ type = "application/zip"
+ putExtra(Intent.EXTRA_STREAM, uri)
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+ context.startActivity(Intent.createChooser(intent, "Share logs"))
+ } catch (err: Throwable) {
+ Toast.makeText(context, "Share failed: ${err.message ?: "Unknown error"}", Toast.LENGTH_SHORT).show()
+ }
+ }
+ }
+
+ val exportLogs: () -> Unit = {
+ val name = "ensu-logs-${System.currentTimeMillis()}.zip"
+ exportLogsLauncher.launch(name)
+ }
+
val currentSession = appState.chat.sessions.firstOrNull { it.id == appState.chat.currentSessionId }
- ModalNavigationDrawer(
- drawerState = drawerState,
- drawerContent = {
- SessionDrawer(
- sessions = appState.chat.sessions,
- selectedSessionId = appState.chat.currentSessionId,
- isLoggedIn = appState.auth.isLoggedIn,
- userEmail = appState.auth.email,
- onNewChat = {
- store.startNewSessionDraft()
- store.persistSelectedSession(scope, null)
- destination = HomeDestination.Chat
- scope.launch { drawerState.close() }
- },
- onSelectSession = { session ->
- store.selectSession(session.id)
- store.persistSelectedSession(scope, session.id)
- destination = HomeDestination.Chat
- scope.launch { drawerState.close() }
- },
- onDeleteSession = { session ->
- deleteSessionTarget = session
- },
- onSync = {
- store.syncNow { message ->
- Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
- }
- },
- onOpenLogs = {
- destination = HomeDestination.Logs
- scope.launch { drawerState.close() }
- },
- onOpenModelSettings = {
- destination = HomeDestination.ModelSettings
- scope.launch { drawerState.close() }
- },
- onOpenDeveloperSettings = {
- destination = HomeDestination.DeveloperSettings
- scope.launch { drawerState.close() }
- },
- onSignIn = { isShowingAuth = true },
- onSignOut = { isShowingSignOutDialog = true }
- )
+ BackHandler(enabled = isShowingAuth) {
+ isShowingAuth = false
+ }
+
+ DisposableEffect(lifecycleOwner) {
+ val observer = LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_RESUME) {
+ val chatState = latestChatState
+ if (
+ chatState.hasRequestedModelDownload &&
+ !chatState.isModelDownloaded &&
+ !chatState.isDownloading &&
+ !chatState.isGenerating
+ ) {
+ latestStore.startModelDownload(userInitiated = false)
+ }
+ }
}
- ) {
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
+ }
+
+ androidx.compose.runtime.LaunchedEffect(currentRoute) {
+ if (!isChatRoute) {
+ drawerState.close()
+ }
+ }
+
+ val scaffoldContent: @Composable () -> Unit = {
Scaffold(
containerColor = EnsuColor.backgroundBase(),
contentWindowInsets = WindowInsets(0, 0, 0, 0),
topBar = {
- when (destination) {
- HomeDestination.Chat -> {
+ when (currentRoute) {
+ HomeRoute.Chat -> {
Column {
EnsuTopBar(
sessionTitle = currentSession?.title,
@@ -181,6 +264,8 @@ fun HomeView(
isLoggedIn = appState.auth.isLoggedIn,
attachmentDownloads = appState.chat.attachmentDownloads,
attachmentDownloadProgress = appState.chat.attachmentDownloadProgress,
+ modelDownloadStatus = appState.chat.downloadStatus,
+ modelDownloadPercent = appState.chat.downloadPercent,
onOpenDrawer = { scope.launch { drawerState.open() } },
onSignIn = { isShowingAuth = true },
onAttachmentDownloads = { showAttachmentDownloads = true }
@@ -188,15 +273,22 @@ fun HomeView(
androidx.compose.material3.HorizontalDivider(color = EnsuColor.border())
}
}
- HomeDestination.Logs -> {
- SimpleTopBar(title = "Logs") { destination = HomeDestination.Chat }
+ HomeRoute.Logs -> {
+ LogsTopBar(
+ onBack = { navController.popBackStack() },
+ onShare = { showLogShareDialog = true }
+ )
}
- HomeDestination.ModelSettings -> {
- SimpleTopBar(title = "Model Settings") { destination = HomeDestination.Chat }
+ HomeRoute.ModelSettings -> {
+ SimpleTopBar(title = "Model Settings") { navController.popBackStack() }
}
- HomeDestination.DeveloperSettings -> {
- SimpleTopBar(title = "Developer Settings") { destination = HomeDestination.Chat }
+ HomeRoute.DeveloperSettings -> {
+ SimpleTopBar(title = "Developer Settings") { navController.popBackStack() }
}
+ HomeRoute.Settings -> {
+ SimpleTopBar(title = "Settings") { navController.popBackStack() }
+ }
+ else -> Unit
}
}
) { padding ->
@@ -205,8 +297,18 @@ fun HomeView(
.fillMaxSize()
.padding(padding)
) {
- when (destination) {
- HomeDestination.Chat -> {
+ AnimatedNavHost(
+ navController = navController,
+ startDestination = HomeRoute.Chat,
+ modifier = Modifier.fillMaxSize()
+ ) {
+ composable(
+ route = HomeRoute.Chat,
+ enterTransition = { forwardEnter() },
+ exitTransition = { forwardExit() },
+ popEnterTransition = { backEnter() },
+ popExitTransition = { backExit() }
+ ) {
ChatView(
chatState = appState.chat,
onMessageChange = store::updateMessageText,
@@ -230,24 +332,59 @@ fun HomeView(
onBranchChange = store::updateBranchSelection,
onOpenAttachment = { attachment ->
openAttachment(context, attachment)
- }
+ },
+ onStartDownload = { store.startModelDownload(userInitiated = true) }
+ )
+ }
+ composable(
+ route = HomeRoute.Settings,
+ enterTransition = { forwardEnter() },
+ exitTransition = { forwardExit() },
+ popEnterTransition = { backEnter() },
+ popExitTransition = { backExit() }
+ ) {
+ val currentEndpoint by currentEndpointFlow.collectAsState(initial = "https://api.ente.io")
+ SettingsScreen(
+ currentEndpoint = currentEndpoint,
+ onOpenModelSettings = { navController.navigate(HomeRoute.ModelSettings) },
+ onOpenLogs = { navController.navigate(HomeRoute.Logs) }
)
}
- HomeDestination.Logs -> {
- LogViewerScreen(logs = logs)
+ composable(
+ route = HomeRoute.Logs,
+ enterTransition = { forwardEnter() },
+ exitTransition = { forwardExit() },
+ popEnterTransition = { backEnter() },
+ popExitTransition = { backExit() }
+ ) {
+ LogViewerScreen(
+ logRepository = logRepository
+ )
}
- HomeDestination.ModelSettings -> {
+ composable(
+ route = HomeRoute.ModelSettings,
+ enterTransition = { forwardEnter() },
+ exitTransition = { forwardExit() },
+ popEnterTransition = { backEnter() },
+ popExitTransition = { backExit() }
+ ) {
ModelSettingsScreen(
state = appState.modelSettings,
onSave = store::updateModelSettings,
onReset = store::resetModelSettings
)
}
- HomeDestination.DeveloperSettings -> {
+ composable(
+ route = HomeRoute.DeveloperSettings,
+ enterTransition = { forwardEnter() },
+ exitTransition = { forwardExit() },
+ popEnterTransition = { backEnter() },
+ popExitTransition = { backExit() }
+ ) {
DeveloperSettingsScreen(
authService = authService,
currentEndpointFlow = currentEndpointFlow,
- onSaved = { destination = HomeDestination.Chat }
+ onSaved = { navController.popBackStack() }
)
}
}
@@ -255,6 +392,55 @@ fun HomeView(
}
}
+ ModalNavigationDrawer(
+ drawerState = drawerState,
+ gesturesEnabled = isChatRoute,
+ drawerContent = {
+ if (isChatRoute) {
+ SessionDrawer(
+ sessions = appState.chat.sessions,
+ selectedSessionId = appState.chat.currentSessionId,
+ isLoggedIn = appState.auth.isLoggedIn,
+ userEmail = appState.auth.email,
+ onNewChat = {
+ // We're already on the chat route when the drawer is visible.
+ // Avoid re-navigating to the same destination, which causes an unnecessary transition.
+ store.startNewSessionDraft()
+ store.persistSelectedSession(scope, null)
+ scope.launch { drawerState.close() }
+ },
+ onSelectSession = { session ->
+ // Same reason as above: just swap the session in-place.
+ store.selectSession(session.id)
+ store.persistSelectedSession(scope, session.id)
+ scope.launch { drawerState.close() }
+ },
+ onDeleteSession = { session ->
+ deleteSessionTarget = session
+ },
+ onSync = {
+ store.syncNow { message ->
+ Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
+ }
+ },
+ onOpenSettings = {
+ navController.navigate(HomeRoute.Settings)
+ scope.launch { drawerState.close() }
+ },
+ onDeveloperTap = {
+ handleDeveloperTap()
+ },
+ onSignIn = { isShowingAuth = true },
+ onSignOut = { isShowingSignOutDialog = true }
+ )
+ } else {
+ Box(modifier = Modifier.width(1.dp))
+ }
+ }
+ ) {
+ scaffoldContent()
+ }
+
if (isShowingAuth) {
AuthFlowScreen(
authService = authService,
@@ -275,15 +461,15 @@ fun HomeView(
}
if (deleteSessionTarget != null) {
- ChoiceDialog(
+ NativeChoiceDialog(
title = "Delete Chat",
body = "This will delete the chat and sync the change.",
firstButtonLabel = "Delete",
secondButtonLabel = "Cancel",
- isCritical = true,
onFirst = {
deleteSessionTarget?.let { session ->
store.deleteSession(session.id)
+ store.persistSelectedSession(scope, appState.chat.currentSessionId)
}
deleteSessionTarget = null
},
@@ -292,13 +478,85 @@ fun HomeView(
)
}
+ if (showLogShareDialog) {
+ ModalBottomSheet(
+ onDismissRequest = { showLogShareDialog = false },
+ containerColor = EnsuColor.backgroundBase()
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.md.dp),
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
+ ) {
+ Text(text = "Logs", style = EnsuTypography.h3Bold, color = EnsuColor.textPrimary())
+ Text(text = "Export or share logs for support.", style = EnsuTypography.body, color = EnsuColor.textMuted())
+ Row(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {
+ TextButton(onClick = {
+ showLogShareDialog = false
+ shareLogs()
+ }) {
+ Text(text = "Share")
+ }
+ TextButton(onClick = {
+ showLogShareDialog = false
+ exportLogs()
+ }) {
+ Text(text = "Export")
+ }
+ Spacer(modifier = Modifier.weight(1f))
+ TextButton(onClick = { showLogShareDialog = false }) {
+ Text(text = "Cancel")
+ }
+ }
+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
+ }
+ }
+ }
+
+ 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)
+ scope.launch { drawerState.close() }
+ },
+ colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.accent())
+ ) {
+ Text(text = "Yes")
+ }
+ },
+ dismissButton = {
+ TextButton(
+ onClick = { showDeveloperDialog = false },
+ colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textMuted())
+ ) {
+ Text(text = "Cancel")
+ }
+ },
+ containerColor = EnsuColor.backgroundBase()
+ )
+ }
+
if (isShowingSignOutDialog) {
- ChoiceDialog(
+ NativeChoiceDialog(
title = "Sign Out",
body = "This will stop syncing your sessions.",
firstButtonLabel = "Sign Out",
secondButtonLabel = "Cancel",
- isCritical = false,
onFirst = {
authService.clearCredentials()
store.signOut()
@@ -317,20 +575,22 @@ private fun EnsuTopBar(
isLoggedIn: Boolean,
attachmentDownloads: List<io.ente.ensu.domain.model.AttachmentDownloadItem>,
attachmentDownloadProgress: Int?,
+ modelDownloadStatus: String?,
+ modelDownloadPercent: Int?,
onOpenDrawer: () -> Unit,
onSignIn: () -> Unit,
onAttachmentDownloads: () -> Unit
) {
val titleText = sessionTitle?.takeIf { it.isNotBlank() } ?: "New Chat"
- TopAppBar(
+ CenterAlignedTopAppBar(
title = {
if (showBrand) {
EnsuLogo(height = 20.dp)
} else {
Text(
text = titleText,
- style = EnsuTypography.h3Bold,
+ style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp),
color = EnsuColor.textPrimary(),
maxLines = 1
)
@@ -339,13 +599,23 @@ private fun EnsuTopBar(
navigationIcon = {
IconButton(onClick = onOpenDrawer) {
Icon(
- imageVector = Icons.Outlined.Menu,
+ painter = painterResource(HugeIcons.Menu01Icon),
contentDescription = "Menu"
)
}
},
actions = {
+ val isLoading = modelDownloadStatus?.contains("Loading", ignoreCase = true) == true
+ val showModelProgress = isLoading
+
if (!isLoggedIn) {
+ if (showModelProgress) {
+ ModelProgressIndicator(
+ isLoading = isLoading,
+ progressPercent = modelDownloadPercent
+ )
+ Spacer(modifier = Modifier.width(EnsuSpacing.md.dp))
+ }
TextButton(onClick = onSignIn) {
Text(text = "Sign In", style = EnsuTypography.small, color = EnsuColor.accent())
}
@@ -365,7 +635,7 @@ private fun EnsuTopBar(
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
- imageVector = Icons.Outlined.Download,
+ painter = painterResource(HugeIcons.Upload01Icon),
contentDescription = "Attachment downloads",
tint = EnsuColor.textPrimary()
)
@@ -380,12 +650,48 @@ private fun EnsuTopBar(
}
}
}
+ if (showModelProgress) {
+ if (hasPending) {
+ Spacer(modifier = Modifier.width(EnsuSpacing.md.dp))
+ }
+ ModelProgressIndicator(
+ isLoading = isLoading,
+ progressPercent = modelDownloadPercent,
+ modifier = Modifier.padding(end = EnsuSpacing.sm.dp)
+ )
+ }
}
},
colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())
)
}
+@Composable
+private fun ModelProgressIndicator(
+ isLoading: Boolean,
+ progressPercent: Int?,
+ modifier: Modifier = Modifier
+) {
+ val indicatorModifier = modifier.size(16.dp)
+ val clamped = progressPercent?.coerceIn(0, 100)
+ if (!isLoading && clamped != null) {
+ CircularProgressIndicator(
+ progress = { clamped / 100f },
+ modifier = indicatorModifier,
+ color = EnsuColor.accent(),
+ trackColor = EnsuColor.border(),
+ strokeWidth = 2.dp
+ )
+ } else {
+ CircularProgressIndicator(
+ modifier = indicatorModifier,
+ color = EnsuColor.accent(),
+ trackColor = EnsuColor.border(),
+ strokeWidth = 2.dp
+ )
+ }
+}
+
@Composable
private fun AttachmentDownloadsDialog(
downloads: List<AttachmentDownloadItem>,
@@ -454,23 +760,75 @@ private fun statusLabel(status: AttachmentDownloadStatus): String {
@Composable
private fun SimpleTopBar(title: String, onBack: () -> Unit) {
TopAppBar(
- title = { Text(text = title, style = EnsuTypography.h3Bold) },
+ title = { Text(text = title, style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp)) },
navigationIcon = {
IconButton(onClick = onBack) {
- Icon(imageVector = Icons.Outlined.ArrowBack, contentDescription = "Back")
+ Icon(
+ painter = painterResource(HugeIcons.ArrowLeft01Icon),
+ contentDescription = "Back"
+ )
}
},
colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())
)
}
-private enum class HomeDestination {
- Chat,
- Logs,
- ModelSettings,
- DeveloperSettings
+private object HomeRoute {
+ const val Chat = "chat"
+ const val Settings = "settings"
+ const val Logs = "logs"
+ const val ModelSettings = "model-settings"
+ const val DeveloperSettings = "developer-settings"
+}
+
+@Composable
+private fun LogsTopBar(onBack: () -> Unit, onShare: () -> Unit) {
+ TopAppBar(
+ title = { Text(text = "Logs", style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp)) },
+ navigationIcon = {
+ IconButton(onClick = onBack) {
+ Icon(
+ painter = painterResource(HugeIcons.ArrowLeft01Icon),
+ contentDescription = "Back"
+ )
+ }
+ },
+ actions = {
+ IconButton(onClick = onShare) {
+ Icon(
+ painter = painterResource(HugeIcons.Upload01Icon),
+ contentDescription = "Share"
+ )
+ }
+ },
+ colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())
+ )
}
+private fun androidx.compose.animation.AnimatedContentTransitionScope<NavBackStackEntry>.forwardEnter() =
+ slideInHorizontally(
+ initialOffsetX = { it },
+ animationSpec = tween(220)
+ ) + fadeIn(animationSpec = tween(90))
+
+private fun androidx.compose.animation.AnimatedContentTransitionScope<NavBackStackEntry>.forwardExit() =
+ slideOutHorizontally(
+ targetOffsetX = { -it },
+ animationSpec = tween(220)
+ ) + fadeOut(animationSpec = tween(90))
+
+private fun androidx.compose.animation.AnimatedContentTransitionScope<NavBackStackEntry>.backEnter() =
+ slideInHorizontally(
+ initialOffsetX = { -it },
+ animationSpec = tween(220)
+ ) + fadeIn(animationSpec = tween(90))
+
+private fun androidx.compose.animation.AnimatedContentTransitionScope<NavBackStackEntry>.backExit() =
+ slideOutHorizontally(
+ targetOffsetX = { it },
+ animationSpec = tween(220)
+ ) + fadeOut(animationSpec = tween(90))
+
private fun buildAttachmentFromUri(
context: Context,
uri: Uri,
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 20b6db4f42..04c09e5d2e 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
@@ -7,6 +7,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.data.auth.EnsuAuthService
+import io.ente.ensu.data.logging.FileLogRepository
import io.ente.ensu.domain.model.LogEntry
import io.ente.ensu.domain.state.AppState
import io.ente.ensu.domain.store.AppStore
@@ -17,6 +18,7 @@ fun RootView(
appState: AppState,
store: AppStore,
logs: List<LogEntry>,
+ logRepository: FileLogRepository,
authService: EnsuAuthService,
currentEndpointFlow: Flow<String>
) {
@@ -29,6 +31,7 @@ fun RootView(
appState = appState,
store = store,
logs = logs,
+ logRepository = logRepository,
authService = authService,
currentEndpointFlow = currentEndpointFlow
)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthComponents.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthComponents.kt
index 06937cc142..bf0d2fb415 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthComponents.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthComponents.kt
@@ -17,9 +17,6 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.outlined.Visibility
-import androidx.compose.material.icons.outlined.VisibilityOff
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
@@ -44,8 +41,10 @@ import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
+import androidx.compose.ui.res.painterResource
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuCornerRadius
+import io.ente.ensu.designsystem.HugeIcons
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
@@ -140,7 +139,9 @@ fun PasswordTextField(
trailingIcon = {
IconButton(onClick = onTogglePassword) {
Icon(
- imageVector = if (showPassword) Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility,
+ painter = painterResource(
+ if (showPassword) HugeIcons.ViewOffSlashIcon else HugeIcons.ViewIcon
+ ),
contentDescription = if (showPassword) "Hide password" else "Show password",
tint = EnsuColor.textMuted()
)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt
index 510eb749fd..c0af462e86 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/auth/AuthFlowScreen.kt
@@ -11,8 +11,6 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.height
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.outlined.ArrowBack
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -31,9 +29,11 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import io.ente.ensu.components.EnsuLogo
+import io.ente.ensu.designsystem.HugeIcons
import io.ente.ensu.data.auth.AuthResponsePayload
import io.ente.ensu.data.auth.EnsuAuthService
import io.ente.ensu.data.auth.KeyAttributes
@@ -107,7 +107,10 @@ fun AuthFlowScreen(
onDismiss()
}
}) {
- Icon(imageVector = Icons.Outlined.ArrowBack, contentDescription = "Back")
+ Icon(
+ painter = painterResource(HugeIcons.ArrowLeft01Icon),
+ contentDescription = "Back"
+ )
}
},
actions = {},
@@ -322,6 +325,63 @@ private fun OtpVerificationView(
val scope = rememberCoroutineScope()
val hasValidCode = code.trim().length == 6
+ fun submitOtp() {
+ if (!hasValidCode || isLoading) return
+ scope.launch {
+ if (isLoading) return@launch
+ isLoading = true
+ errorMessage = null
+ try {
+ val payload = authService.verifyOtp(email, code)
+ val keyAttrs = payload.keyAttributes
+ if (keyAttrs == null) {
+ errorMessage = "New user signup not implemented. Please use an existing account."
+ } else if (payload.requiresPasskey) {
+ onNavigate(
+ AuthRoute.Passkey(
+ email = email,
+ srp = srpAttributes,
+ sessionId = payload.passkeySessionId.orEmpty(),
+ accountsUrl = payload.accountsUrl ?: "https://accounts.ente.io",
+ twoFactorSessionId = payload.twoFactorSessionId,
+ password = null
+ )
+ )
+ } else if (payload.requiresTwoFactor) {
+ onNavigate(
+ AuthRoute.TwoFactor(
+ email = email,
+ srp = srpAttributes,
+ sessionId = payload.twoFactorSessionId.orEmpty(),
+ password = null
+ )
+ )
+ } else {
+ onNavigate(
+ AuthRoute.PasswordAfterMfa(
+ email = email,
+ srp = srpAttributes,
+ userId = payload.userId,
+ keyAttributes = keyAttrs,
+ encryptedToken = payload.encryptedToken,
+ token = payload.token
+ )
+ )
+ }
+ } catch (error: Exception) {
+ errorMessage = error.message
+ } finally {
+ isLoading = false
+ }
+ }
+ }
+
+ LaunchedEffect(code) {
+ if (code.trim().length == 6) {
+ submitOtp()
+ }
+ }
+
AuthScreen(
content = {
AuthHeader(title = "Verify email", subtitle = email)
@@ -353,53 +413,7 @@ private fun OtpVerificationView(
isLoading = isLoading,
isEnabled = hasValidCode && !isLoading
) {
- scope.launch {
- if (isLoading) return@launch
- isLoading = true
- errorMessage = null
- try {
- val payload = authService.verifyOtp(email, code)
- val keyAttrs = payload.keyAttributes
- if (keyAttrs == null) {
- errorMessage = "New user signup not implemented. Please use an existing account."
- } else if (payload.requiresPasskey) {
- onNavigate(
- AuthRoute.Passkey(
- email = email,
- srp = srpAttributes,
- sessionId = payload.passkeySessionId.orEmpty(),
- accountsUrl = payload.accountsUrl ?: "https://accounts.ente.io",
- twoFactorSessionId = payload.twoFactorSessionId,
- password = null
- )
- )
- } else if (payload.requiresTwoFactor) {
- onNavigate(
- AuthRoute.TwoFactor(
- email = email,
- srp = srpAttributes,
- sessionId = payload.twoFactorSessionId.orEmpty(),
- password = null
- )
- )
- } else {
- onNavigate(
- AuthRoute.PasswordAfterMfa(
- email = email,
- srp = srpAttributes,
- userId = payload.userId,
- keyAttributes = keyAttrs,
- encryptedToken = payload.encryptedToken,
- token = payload.token
- )
- )
- }
- } catch (error: Exception) {
- errorMessage = error.message
- } finally {
- isLoading = false
- }
- }
+ submitOtp()
}
}
)
@@ -421,6 +435,54 @@ private fun TwoFactorView(
val scope = rememberCoroutineScope()
val hasValidCode = code.trim().length == 6
+ fun submitTwoFactor() {
+ if (!hasValidCode || isLoading) return
+ scope.launch {
+ if (isLoading) return@launch
+ isLoading = true
+ errorMessage = null
+ try {
+ val payload = authService.verifyTwoFactor(sessionId, code)
+ val keyAttrs = payload.keyAttributes
+ if (keyAttrs == null) {
+ errorMessage = "Invalid response"
+ } else if (!password.isNullOrBlank()) {
+ authService.loginAfterChallenge(
+ email = email,
+ password = password,
+ srpAttributes = srpAttributes,
+ userId = payload.userId,
+ keyAttributes = keyAttrs,
+ encryptedToken = payload.encryptedToken,
+ token = payload.token
+ )
+ onLoggedIn()
+ } else {
+ onNavigate(
+ AuthRoute.PasswordAfterMfa(
+ email = email,
+ srp = srpAttributes,
+ userId = payload.userId,
+ keyAttributes = keyAttrs,
+ encryptedToken = payload.encryptedToken,
+ token = payload.token
+ )
+ )
+ }
+ } catch (error: Exception) {
+ errorMessage = error.message
+ } finally {
+ isLoading = false
+ }
+ }
+ }
+
+ LaunchedEffect(code) {
+ if (code.trim().length == 6) {
+ submitTwoFactor()
+ }
+ }
+
AuthScreen(
content = {
AuthHeader(
@@ -449,44 +511,7 @@ private fun TwoFactorView(
isLoading = isLoading,
isEnabled = hasValidCode && !isLoading
) {
- scope.launch {
- if (isLoading) return@launch
- isLoading = true
- errorMessage = null
- try {
- val payload = authService.verifyTwoFactor(sessionId, code)
- val keyAttrs = payload.keyAttributes
- if (keyAttrs == null) {
- errorMessage = "Invalid response"
- } else if (!password.isNullOrBlank()) {
- authService.loginAfterChallenge(
- email = email,
- password = password,
- srpAttributes = srpAttributes,
- userId = payload.userId,
- keyAttributes = keyAttrs,
- encryptedToken = payload.encryptedToken,
- token = payload.token
- )
- onLoggedIn()
- } else {
- onNavigate(
- AuthRoute.PasswordAfterMfa(
- email = email,
- srp = srpAttributes,
- userId = payload.userId,
- keyAttributes = keyAttrs,
- encryptedToken = payload.encryptedToken,
- token = payload.token
- )
- )
- }
- } catch (error: Exception) {
- errorMessage = error.message
- } finally {
- isLoading = false
- }
- }
+ submitTwoFactor()
}
}
)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt
index be4e13a6e1..c96d7b66d8 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/ChatView.kt
@@ -1,6 +1,13 @@
+@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
+
package io.ente.ensu.chat
+import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.focusable
+import androidx.compose.foundation.gestures.detectTapGestures
+import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -9,12 +16,16 @@ import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.WindowInsets
+import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.ime
+import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
@@ -23,49 +34,53 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.automirrored.outlined.ArrowForward
-import androidx.compose.material.icons.outlined.AttachFile
-import androidx.compose.material.icons.outlined.ContentCopy
-import androidx.compose.material.icons.outlined.Edit
-import androidx.compose.material.icons.outlined.StopCircle
-import androidx.compose.material.icons.outlined.Description
-import androidx.compose.material.icons.outlined.Download
-import androidx.compose.material.icons.outlined.Image
-import androidx.compose.material.icons.outlined.Refresh
-import androidx.compose.material.icons.outlined.Close
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.DropdownMenu
+import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
-import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
-import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.draw.shadow
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
-import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.platform.LocalClipboardManager
+import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalHapticFeedback
+import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
-import androidx.compose.ui.platform.LocalClipboardManager
-import io.ente.ensu.components.ActionButton
import io.ente.ensu.components.BranchSwitcher
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuCornerRadius
+import io.ente.ensu.designsystem.HugeIcons
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
import io.ente.ensu.domain.model.Attachment
@@ -76,6 +91,7 @@ import io.ente.ensu.domain.state.ChatState
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
+import kotlin.math.roundToLong
import kotlinx.coroutines.delay
@Composable
@@ -91,63 +107,108 @@ fun ChatView(
onRetryMessage: (ChatMessage) -> Unit,
onCancelEdit: () -> Unit,
onBranchChange: (String, Int) -> Unit,
- onOpenAttachment: (Attachment) -> Unit
+ onOpenAttachment: (Attachment) -> Unit,
+ onStartDownload: () -> Unit
) {
+ val imePadding = WindowInsets.ime.asPaddingValues().calculateBottomPadding()
+ val showDownloadOnboarding = !chatState.isModelDownloaded &&
+ chatState.messages.isEmpty() &&
+ !chatState.isGenerating
+ val hasMessages = chatState.messages.isNotEmpty()
+
+ var didAutoFocusInput by remember { mutableStateOf(false) }
+ val shouldAutoFocusInput = chatState.isModelDownloaded &&
+ !showDownloadOnboarding &&
+ !chatState.isDownloading &&
+ !chatState.isGenerating &&
+ !didAutoFocusInput
+
+ LaunchedEffect(shouldAutoFocusInput) {
+ if (shouldAutoFocusInput) {
+ didAutoFocusInput = true
+ }
+ }
+
+ LaunchedEffect(hasMessages, chatState.isModelDownloaded, chatState.isDownloading, chatState.isGenerating) {
+ if (hasMessages && !chatState.isModelDownloaded && !chatState.isDownloading && !chatState.isGenerating) {
+ onStartDownload()
+ }
+ }
+
+ LaunchedEffect(chatState.isModelDownloaded) {
+ if (chatState.isModelDownloaded && !chatState.isDownloading && !chatState.isGenerating) {
+ onStartDownload()
+ }
+ }
+
Box(modifier = Modifier.fillMaxSize()) {
- Column(modifier = Modifier.fillMaxSize()) {
+ Column(modifier = Modifier.fillMaxSize().imePadding()) {
MessageList(
modifier = Modifier
.weight(1f)
.padding(
start = EnsuSpacing.pageHorizontal.dp,
- end = EnsuSpacing.pageHorizontal.dp,
- top = EnsuSpacing.pageVertical.dp
+ end = EnsuSpacing.pageHorizontal.dp
),
messages = chatState.messages,
streamingResponse = chatState.streamingResponse,
streamingParentId = chatState.streamingParentId,
isGenerating = chatState.isGenerating,
+ isModelDownloaded = chatState.isModelDownloaded,
+ isDownloading = chatState.isDownloading,
+ downloadPercent = chatState.downloadPercent,
+ downloadStatus = chatState.downloadStatus,
+ modelDownloadSizeBytes = chatState.modelDownloadSizeBytes,
branchSelections = chatState.branchSelections,
+ imePadding = imePadding,
onEditMessage = onEditMessage,
onRetryMessage = onRetryMessage,
onBranchChange = onBranchChange,
- onOpenAttachment = onOpenAttachment
+ onOpenAttachment = onOpenAttachment,
+ onStartDownload = onStartDownload
)
val editingMessage = chatState.editingMessageId?.let { editingId ->
chatState.messages.firstOrNull { it.id == editingId }
}
- MessageInput(
- modifier = Modifier
- .fillMaxWidth()
- .navigationBarsPadding()
- .background(EnsuColor.backgroundBase()),
- messageText = chatState.messageText,
- attachments = chatState.attachments,
- editingMessage = editingMessage,
- isProcessingAttachments = chatState.isProcessingAttachments,
- isGenerating = chatState.isGenerating,
- isDownloading = chatState.isDownloading,
- downloadPercent = chatState.downloadPercent,
- isAttachmentDownloadBlocked = chatState.isAttachmentDownloadBlocked,
- attachmentDownloadPercent = chatState.attachmentDownloadProgress,
- onMessageChange = onMessageChange,
- onSend = onSend,
- onStop = onStop,
- onAttachmentSelected = onAttachmentSelected,
- onRemoveAttachment = onRemoveAttachment,
- onCancelEdit = onCancelEdit
- )
+ if (!showDownloadOnboarding) {
+ MessageInput(
+ modifier = Modifier
+ .fillMaxWidth()
+ .navigationBarsPadding()
+ .background(EnsuColor.backgroundBase()),
+ messageText = chatState.messageText,
+ attachments = chatState.attachments,
+ editingMessage = editingMessage,
+ isProcessingAttachments = chatState.isProcessingAttachments,
+ isGenerating = chatState.isGenerating,
+ isDownloading = chatState.isDownloading,
+ downloadPercent = chatState.downloadPercent,
+ isAttachmentDownloadBlocked = chatState.isAttachmentDownloadBlocked,
+ attachmentDownloadPercent = chatState.attachmentDownloadProgress,
+ onMessageChange = onMessageChange,
+ onSend = onSend,
+ onStop = onStop,
+ onAttachmentSelected = onAttachmentSelected,
+ onRemoveAttachment = onRemoveAttachment,
+ onCancelEdit = onCancelEdit,
+ shouldRequestFocus = shouldAutoFocusInput
+ )
+ }
}
val status = chatState.downloadStatus
- val showToast = status != null && (chatState.isDownloading || status.contains("Loading", ignoreCase = true))
+ val isLoading = status?.contains("Loading", ignoreCase = true) == true
+ val showToast = !showDownloadOnboarding &&
+ status != null &&
+ chatState.isDownloading &&
+ !isLoading
if (showToast) {
DownloadToastOverlay(
status = status ?: "",
percent = chatState.downloadPercent ?: 0,
- isLoading = status?.contains("Loading", ignoreCase = true) == true,
+ isLoading = isLoading,
onCancel = onCancelDownload
)
}
@@ -161,14 +222,36 @@ private fun MessageList(
streamingResponse: String,
streamingParentId: String?,
isGenerating: Boolean,
+ isModelDownloaded: Boolean,
+ isDownloading: Boolean,
+ downloadPercent: Int?,
+ downloadStatus: String?,
+ modelDownloadSizeBytes: Long?,
branchSelections: Map<String, Int>,
+ imePadding: androidx.compose.ui.unit.Dp,
onEditMessage: (ChatMessage) -> Unit,
onRetryMessage: (ChatMessage) -> Unit,
onBranchChange: (String, Int) -> Unit,
- onOpenAttachment: (Attachment) -> Unit
+ onOpenAttachment: (Attachment) -> Unit,
+ onStartDownload: () -> Unit
) {
if (messages.isEmpty() && !isGenerating) {
- EmptyState(modifier = modifier)
+ if (!isModelDownloaded) {
+ DownloadOnboarding(
+ modifier = modifier,
+ isDownloading = isDownloading,
+ downloadPercent = downloadPercent,
+ downloadStatus = downloadStatus,
+ modelDownloadSizeBytes = modelDownloadSizeBytes,
+ onDownload = onStartDownload
+ )
+ } else {
+ EmptyState(
+ modifier = modifier,
+ title = "Welcome to ensu",
+ subtitle = "Type a message to start chatting"
+ )
+ }
return
}
@@ -177,6 +260,8 @@ private fun MessageList(
var autoScrollEnabled by remember { mutableStateOf(true) }
var lastHapticLength by remember { mutableStateOf(0) }
var shouldJumpToBottomOnLoad by remember { mutableStateOf(true) }
+ var lastIsAtBottom by remember { mutableStateOf(true) }
+ var wasAtBottomBeforeIme by remember { mutableStateOf(false) }
val isAtBottom by remember {
derivedStateOf {
val layoutInfo = listState.layoutInfo
@@ -210,6 +295,10 @@ private fun MessageList(
}
}
+ LaunchedEffect(isAtBottom) {
+ lastIsAtBottom = isAtBottom
+ }
+
LaunchedEffect(isAtBottom, isGenerating) {
if (isGenerating && isAtBottom) {
autoScrollEnabled = true
@@ -233,10 +322,28 @@ private fun MessageList(
}
}
+ LaunchedEffect(imePadding) {
+ if (imePadding > 0.dp) {
+ wasAtBottomBeforeIme = lastIsAtBottom
+ if (wasAtBottomBeforeIme) {
+ delay(120)
+ val targetIndex = messages.size
+ if (targetIndex >= 0) {
+ listState.scrollToItem(targetIndex)
+ }
+ }
+ } else {
+ wasAtBottomBeforeIme = false
+ }
+ }
+
LazyColumn(
modifier = modifier,
state = listState,
- contentPadding = PaddingValues(bottom = (EnsuSpacing.xxxl + EnsuSpacing.xl).dp),
+ contentPadding = PaddingValues(
+ top = EnsuSpacing.pageVertical.dp,
+ bottom = (EnsuSpacing.xxxl + EnsuSpacing.xl).dp + imePadding
+ ),
verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)
) {
items(messages, key = { it.id }) { message ->
@@ -279,17 +386,113 @@ private fun MessageList(
}
@Composable
-private fun EmptyState(modifier: Modifier) {
+private fun EmptyState(
+ modifier: Modifier,
+ title: String,
+ subtitle: String? = null
+) {
Box(
modifier = modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
- Text(
- text = "Start typing to begin a conversation",
- style = EnsuTypography.body,
- color = EnsuColor.textMuted(),
- textAlign = TextAlign.Center
- )
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text(
+ text = title,
+ style = EnsuTypography.large,
+ color = EnsuColor.textPrimary(),
+ textAlign = TextAlign.Center
+ )
+ if (subtitle != null) {
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ Text(
+ text = subtitle,
+ style = EnsuTypography.body,
+ color = EnsuColor.textMuted(),
+ textAlign = TextAlign.Center
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun DownloadOnboarding(
+ modifier: Modifier,
+ isDownloading: Boolean,
+ downloadPercent: Int?,
+ downloadStatus: String?,
+ modelDownloadSizeBytes: Long?,
+ onDownload: () -> Unit
+) {
+ val haptic = LocalHapticFeedback.current
+ val sizeText = modelDownloadSizeBytes?.let { "Approx. ${formatBytes(it)}" } ?: "Approx. size varies by model"
+ Box(
+ modifier = modifier.fillMaxSize(),
+ contentAlignment = Alignment.Center
+ ) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text(
+ text = "Download to begin using the Chat",
+ style = EnsuTypography.large,
+ color = EnsuColor.textPrimary(),
+ textAlign = TextAlign.Center
+ )
+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
+ if (isDownloading) {
+ val statusText = when {
+ downloadStatus?.contains("Loading", ignoreCase = true) == true -> downloadStatus
+ modelDownloadSizeBytes != null && downloadPercent != null && downloadPercent >= 0 -> {
+ val downloadedBytes = (modelDownloadSizeBytes * (downloadPercent / 100f)).roundToLong()
+ "Downloading... ${formatBytes(downloadedBytes)} / ${formatBytes(modelDownloadSizeBytes)}"
+ }
+ !downloadStatus.isNullOrBlank() -> downloadStatus
+ else -> "Downloading..."
+ }
+ Text(
+ text = statusText ?: "Downloading...",
+ style = EnsuTypography.body,
+ color = EnsuColor.textMuted(),
+ textAlign = TextAlign.Center
+ )
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ val clamped = downloadPercent?.coerceIn(0, 100)
+ if (clamped != null) {
+ LinearProgressIndicator(
+ progress = { clamped / 100f },
+ color = EnsuColor.accent(),
+ trackColor = EnsuColor.border(),
+ modifier = Modifier
+ .fillMaxWidth(0.6f)
+ .height(6.dp)
+ )
+ } else {
+ LinearProgressIndicator(
+ color = EnsuColor.accent(),
+ trackColor = EnsuColor.border(),
+ modifier = Modifier
+ .fillMaxWidth(0.6f)
+ .height(6.dp)
+ )
+ }
+ } else {
+ Button(
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ onDownload()
+ },
+ shape = RoundedCornerShape(EnsuCornerRadius.button.dp),
+ colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent())
+ ) {
+ Text(text = "Download", style = EnsuTypography.body, color = EnsuColor.backgroundBase())
+ }
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ Text(
+ text = sizeText,
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted()
+ )
+ }
+ }
}
}
@@ -303,6 +506,10 @@ private fun UserMessageBubble(
onOpenAttachment: (Attachment) -> Unit
) {
val clipboard = LocalClipboardManager.current
+ val haptic = LocalHapticFeedback.current
+ var showMenu by remember { mutableStateOf(false) }
+ var pressOffset by remember { mutableStateOf(Offset.Zero) }
+ val bubbleShape = RoundedCornerShape(18.dp)
Column(
modifier = Modifier
@@ -310,52 +517,111 @@ private fun UserMessageBubble(
.padding(start = EnsuSpacing.messageBubbleInset.dp),
horizontalAlignment = Alignment.End
) {
- if (message.attachments.isNotEmpty()) {
- FlowRow(
- modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp, Alignment.End),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
+ Box {
+ Column(
+ modifier = Modifier
+ .background(EnsuColor.border().copy(alpha = 0.2f), bubbleShape)
+ .pointerInput(Unit) {
+ detectTapGestures(
+ onLongPress = { offset ->
+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)
+ pressOffset = offset
+ showMenu = true
+ }
+ )
+ }
+ .padding(EnsuSpacing.md.dp)
) {
- message.attachments.forEach { attachment ->
- val icon = when (attachment.type) {
- AttachmentType.Image -> Icons.Outlined.Image
- AttachmentType.Document -> Icons.Outlined.Description
+ if (message.attachments.isNotEmpty()) {
+ FlowRow(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp, Alignment.End),
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
+ ) {
+ message.attachments.forEach { attachment ->
+ io.ente.ensu.components.AttachmentChip(
+ name = attachment.name,
+ size = "${attachment.sizeBytes / 1024} KB",
+ iconRes = HugeIcons.Attachment01Icon,
+ isUploading = attachment.isUploading,
+ onClick = { onOpenAttachment(attachment) }
+ )
+ }
}
- io.ente.ensu.components.AttachmentChip(
- name = attachment.name,
- size = "${attachment.sizeBytes / 1024} KB",
- icon = icon,
- isUploading = attachment.isUploading,
- onClick = { onOpenAttachment(attachment) }
- )
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
}
- }
- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
- }
- Text(
- text = message.text,
- style = EnsuTypography.message,
- color = EnsuColor.userMessageText(),
- textAlign = TextAlign.Right
- )
+ Text(
+ text = message.text,
+ style = EnsuTypography.message,
+ color = EnsuColor.userMessageText(),
+ textAlign = TextAlign.Right
+ )
+ }
- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ val menuOffset = with(LocalDensity.current) {
+ DpOffset(pressOffset.x.toDp(), pressOffset.y.toDp())
+ }
- Row(horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
- ActionButton(
- icon = Icons.Outlined.Edit,
- onTap = onEdit,
- contentDescription = "Edit"
- )
- ActionButton(
- icon = Icons.Outlined.ContentCopy,
- onTap = { clipboard.setText(AnnotatedString(message.text)) },
- contentDescription = "Copy"
+ val menuSurface = if (isSystemInDarkTheme()) Color(0xFF1C1C1E) else Color.White
+ val menuColors = MaterialTheme.colorScheme.copy(
+ surface = menuSurface,
+ surfaceVariant = menuSurface,
+ surfaceTint = Color.Transparent,
+ primary = EnsuColor.textPrimary(),
+ primaryContainer = menuSurface,
+ secondary = EnsuColor.textPrimary(),
+ secondaryContainer = menuSurface,
+ onSurface = EnsuColor.textPrimary(),
+ onSurfaceVariant = EnsuColor.textPrimary()
)
+
+ MaterialTheme(colorScheme = menuColors) {
+ DropdownMenu(
+ expanded = showMenu,
+ onDismissRequest = { showMenu = false },
+ offset = menuOffset,
+ modifier = Modifier
+ .shadow(8.dp, RoundedCornerShape(12.dp))
+ .border(1.dp, EnsuColor.border(), RoundedCornerShape(12.dp))
+ ) {
+ DropdownMenuItem(
+ text = { Text(text = "Edit", style = EnsuTypography.body, color = EnsuColor.textPrimary()) },
+ leadingIcon = {
+ Icon(
+ painter = painterResource(HugeIcons.Edit01Icon),
+ contentDescription = null,
+ modifier = Modifier.size(18.dp),
+ tint = EnsuColor.textPrimary()
+ )
+ },
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ showMenu = false
+ onEdit()
+ }
+ )
+ DropdownMenuItem(
+ text = { Text(text = "Copy", style = EnsuTypography.body, color = EnsuColor.textPrimary()) },
+ leadingIcon = {
+ Icon(
+ painter = painterResource(HugeIcons.Copy01Icon),
+ contentDescription = null,
+ modifier = Modifier.size(18.dp),
+ tint = EnsuColor.textPrimary()
+ )
+ },
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ showMenu = false
+ clipboard.setText(AnnotatedString(message.text))
+ }
+ )
+ }
+ }
}
- Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Spacer(modifier = Modifier.weight(1f))
@@ -387,6 +653,10 @@ private fun AssistantMessageBubble(
onBranchChange: (String, Int) -> Unit
) {
val clipboard = LocalClipboardManager.current
+ val haptic = LocalHapticFeedback.current
+ var showMenu by remember { mutableStateOf(false) }
+ var pressOffset by remember { mutableStateOf(Offset.Zero) }
+ val bubbleShape = RoundedCornerShape(18.dp)
Column(
modifier = Modifier
@@ -394,33 +664,96 @@ private fun AssistantMessageBubble(
.padding(end = EnsuSpacing.messageBubbleInset.dp),
horizontalAlignment = Alignment.Start
) {
- MarkdownView(markdown = message.text)
+ Box {
+ Column(
+ modifier = Modifier
+ .background(EnsuColor.border().copy(alpha = 0.2f), bubbleShape)
+ .pointerInput(Unit) {
+ detectTapGestures(
+ onLongPress = { offset ->
+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)
+ pressOffset = offset
+ showMenu = true
+ }
+ )
+ }
+ .padding(EnsuSpacing.md.dp)
+ ) {
+ MarkdownView(markdown = message.text, enableSelection = false)
- if (message.isInterrupted) {
- Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
- Text(
- text = "Interrupted",
- style = EnsuTypography.small,
- color = EnsuColor.textMuted()
- )
- }
+ if (message.isInterrupted) {
+ Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ Text(
+ text = "Interrupted",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted()
+ )
+ }
+ }
- Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
+ val menuOffset = with(LocalDensity.current) {
+ DpOffset(pressOffset.x.toDp(), pressOffset.y.toDp())
+ }
- Row(verticalAlignment = Alignment.CenterVertically) {
- ActionButton(
- icon = Icons.Outlined.ContentCopy,
- onTap = { clipboard.setText(AnnotatedString(message.text)) },
- contentDescription = "Copy"
- )
- ActionButton(
- icon = Icons.Outlined.Refresh,
- onTap = onRetry,
- contentDescription = "Retry"
+ val menuSurface = if (isSystemInDarkTheme()) Color(0xFF1C1C1E) else Color.White
+ val menuColors = MaterialTheme.colorScheme.copy(
+ surface = menuSurface,
+ surfaceVariant = menuSurface,
+ surfaceTint = Color.Transparent,
+ primary = EnsuColor.textPrimary(),
+ primaryContainer = menuSurface,
+ secondary = EnsuColor.textPrimary(),
+ secondaryContainer = menuSurface,
+ onSurface = EnsuColor.textPrimary(),
+ onSurfaceVariant = EnsuColor.textPrimary()
)
+
+ MaterialTheme(colorScheme = menuColors) {
+ DropdownMenu(
+ expanded = showMenu,
+ onDismissRequest = { showMenu = false },
+ offset = menuOffset,
+ modifier = Modifier
+ .shadow(8.dp, RoundedCornerShape(12.dp))
+ .border(1.dp, EnsuColor.border(), RoundedCornerShape(12.dp))
+ ) {
+ DropdownMenuItem(
+ text = { Text(text = "Copy", style = EnsuTypography.body, color = EnsuColor.textPrimary()) },
+ leadingIcon = {
+ Icon(
+ painter = painterResource(HugeIcons.Copy01Icon),
+ contentDescription = null,
+ modifier = Modifier.size(18.dp),
+ tint = EnsuColor.textPrimary()
+ )
+ },
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ showMenu = false
+ clipboard.setText(AnnotatedString(message.text))
+ }
+ )
+ DropdownMenuItem(
+ text = { Text(text = "Retry", style = EnsuTypography.body, color = EnsuColor.textPrimary()) },
+ leadingIcon = {
+ Icon(
+ painter = painterResource(HugeIcons.RepeatIcon),
+ contentDescription = null,
+ modifier = Modifier.size(18.dp),
+ tint = EnsuColor.textPrimary()
+ )
+ },
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ showMenu = false
+ onRetry()
+ }
+ )
+ }
+ }
}
- Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
Row(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp), verticalAlignment = Alignment.CenterVertically) {
TimestampText(message.timestampMillis)
@@ -444,16 +777,24 @@ private fun AssistantMessageBubble(
@Composable
private fun StreamingMessageBubble(text: String) {
+ val bubbleShape = RoundedCornerShape(18.dp)
+
Column(
modifier = Modifier
.fillMaxWidth()
.padding(end = EnsuSpacing.messageBubbleInset.dp),
horizontalAlignment = Alignment.Start
) {
- if (text.isBlank()) {
- LoadingDotsText()
- } else {
- MarkdownView(markdown = text)
+ Column(
+ modifier = Modifier
+ .background(EnsuColor.border().copy(alpha = 0.2f), bubbleShape)
+ .padding(EnsuSpacing.md.dp)
+ ) {
+ if (text.isBlank()) {
+ LoadingDotsText()
+ } else {
+ MarkdownView(markdown = text, enableSelection = false)
+ }
}
}
}
@@ -461,6 +802,7 @@ private fun StreamingMessageBubble(text: String) {
@Composable
private fun LoadingDotsText() {
var dotCount by remember { mutableStateOf(1) }
+ val phrase = remember { randomLoadingPhrase() }
LaunchedEffect(Unit) {
while (true) {
@@ -470,12 +812,50 @@ private fun LoadingDotsText() {
}
Text(
- text = ".".repeat(dotCount),
+ text = phrase + ".".repeat(dotCount),
style = EnsuTypography.message,
color = EnsuColor.textMuted()
)
}
+private fun randomLoadingPhrase(): String {
+ val verb = loadingPhraseVerbs.random()
+ val target = loadingPhraseTargets.random()
+ return "$verb $target"
+}
+
+private val loadingPhraseVerbs = listOf(
+ "Generating",
+ "Thinking through",
+ "Assembling",
+ "Drafting",
+ "Composing",
+ "Crunching",
+ "Exploring",
+ "Piecing together",
+ "Reviewing",
+ "Organizing",
+ "Synthesizing",
+ "Sketching",
+ "Refining",
+ "Shaping"
+)
+
+private val loadingPhraseTargets = listOf(
+ "your reply",
+ "an answer",
+ "ideas",
+ "context",
+ "details",
+ "the response",
+ "the next steps",
+ "a solution",
+ "the summary",
+ "insights",
+ "the draft",
+ "the explanation"
+)
+
@Composable
private fun DownloadToastOverlay(
status: String,
@@ -483,6 +863,7 @@ private fun DownloadToastOverlay(
isLoading: Boolean,
onCancel: () -> Unit
) {
+ val haptic = LocalHapticFeedback.current
Box(
modifier = Modifier
.fillMaxWidth()
@@ -501,12 +882,26 @@ private fun DownloadToastOverlay(
Row(verticalAlignment = Alignment.CenterVertically) {
Text(text = title, style = EnsuTypography.large, color = EnsuColor.textPrimary())
Spacer(modifier = Modifier.weight(1f))
- IconButton(onClick = onCancel, modifier = Modifier.size(28.dp)) {
- Icon(
- imageVector = Icons.Outlined.StopCircle,
- contentDescription = "Cancel download",
- tint = EnsuColor.stopButton
- )
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)
+ onCancel()
+ },
+ modifier = Modifier.size(28.dp)
+ ) {
+ Box(
+ modifier = Modifier
+ .size(22.dp)
+ .background(EnsuColor.textPrimary(), CircleShape),
+ contentAlignment = Alignment.Center
+ ) {
+ Icon(
+ painter = painterResource(HugeIcons.StopIcon),
+ contentDescription = "Cancel download",
+ modifier = Modifier.size(12.dp),
+ tint = EnsuColor.stopButton
+ )
+ }
}
}
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
@@ -537,6 +932,7 @@ private fun TimestampText(timestampMillis: Long) {
@Composable
private fun EditBanner(message: ChatMessage, onCancelEdit: () -> Unit) {
+ val haptic = LocalHapticFeedback.current
Row(
modifier = Modifier
.fillMaxWidth()
@@ -557,7 +953,7 @@ private fun EditBanner(message: ChatMessage, onCancelEdit: () -> Unit) {
verticalAlignment = Alignment.CenterVertically
) {
Icon(
- imageVector = Icons.Outlined.Edit,
+ painter = painterResource(HugeIcons.Edit01Icon),
contentDescription = null,
tint = EnsuColor.accent(),
modifier = Modifier.size(14.dp)
@@ -577,9 +973,15 @@ private fun EditBanner(message: ChatMessage, onCancelEdit: () -> Unit) {
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f)
)
- IconButton(onClick = onCancelEdit, modifier = Modifier.size(24.dp)) {
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ onCancelEdit()
+ },
+ modifier = Modifier.size(24.dp)
+ ) {
Icon(
- imageVector = Icons.Outlined.Close,
+ painter = painterResource(HugeIcons.Cancel01Icon),
contentDescription = "Cancel edit",
tint = EnsuColor.textMuted()
)
@@ -606,20 +1008,31 @@ private fun MessageInput(
onStop: () -> Unit,
onAttachmentSelected: (AttachmentType) -> Unit,
onRemoveAttachment: (Attachment) -> Unit,
- onCancelEdit: () -> Unit
+ onCancelEdit: () -> Unit,
+ shouldRequestFocus: Boolean
) {
+ val haptic = LocalHapticFeedback.current
val placeholder = when {
- isDownloading -> {
- val percent = downloadPercent?.let { " ($it%)" } ?: ""
- "Downloading model...$percent"
- }
isAttachmentDownloadBlocked -> {
val percent = attachmentDownloadPercent?.let { " ($it%)" } ?: ""
"Downloading attachments...$percent"
}
- else -> "Compose your message..."
+ else -> "Write a message..."
+ }
+
+ val focusRequester = remember { FocusRequester() }
+ LaunchedEffect(shouldRequestFocus) {
+ if (shouldRequestFocus) {
+ // Give the screen a moment to settle so IME shows reliably.
+ delay(120)
+ focusRequester.requestFocus()
+ }
}
+ val hasAttachmentContent = attachments.isNotEmpty() || isProcessingAttachments
+ val inputVerticalPadding = if (hasAttachmentContent) EnsuSpacing.xs.dp else 10.dp
+ val bottomPadding = if (hasAttachmentContent) EnsuSpacing.sm.dp else EnsuSpacing.md.dp
+
Column(
modifier = modifier
.background(EnsuColor.backgroundBase()),
@@ -641,14 +1054,10 @@ private fun MessageInput(
verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
) {
attachments.forEach { attachment ->
- val icon = when (attachment.type) {
- AttachmentType.Image -> Icons.Outlined.Image
- AttachmentType.Document -> Icons.Outlined.Description
- }
io.ente.ensu.components.AttachmentChip(
name = attachment.name,
size = "${attachment.sizeBytes / 1024} KB",
- icon = icon,
+ iconRes = HugeIcons.Attachment01Icon,
isUploading = attachment.isUploading,
onDelete = { onRemoveAttachment(attachment) }
)
@@ -671,11 +1080,11 @@ private fun MessageInput(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- .padding(bottom = EnsuSpacing.sm.dp)
- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp))
+ .padding(bottom = bottomPadding)
+ .background(EnsuColor.fillFaint(), RoundedCornerShape((EnsuCornerRadius.input + 4).dp))
.padding(
horizontal = EnsuSpacing.inputHorizontal.dp,
- vertical = EnsuSpacing.inputVertical.dp
+ vertical = inputVerticalPadding
)
) {
Row(
@@ -685,7 +1094,10 @@ private fun MessageInput(
BasicTextField(
value = messageText,
onValueChange = onMessageChange,
- modifier = Modifier.weight(1f),
+ modifier = Modifier
+ .weight(1f)
+ .focusRequester(focusRequester)
+ .focusable(),
textStyle = EnsuTypography.message.copy(color = EnsuColor.textPrimary()),
minLines = 1,
maxLines = 5,
@@ -708,13 +1120,17 @@ private fun MessageInput(
if (editingMessage == null) {
IconButton(
- onClick = { onAttachmentSelected(AttachmentType.Image) },
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ onAttachmentSelected(AttachmentType.Image)
+ },
enabled = !isGenerating && !isDownloading && !isAttachmentDownloadBlocked,
modifier = Modifier.size(36.dp)
) {
Icon(
- imageVector = Icons.Outlined.AttachFile,
- contentDescription = "Attach"
+ painter = painterResource(HugeIcons.Upload01Icon),
+ contentDescription = "Attach",
+ modifier = Modifier.size(18.dp)
)
}
}
@@ -722,30 +1138,65 @@ private fun MessageInput(
val canSend = messageText.isNotBlank() || attachments.isNotEmpty()
IconButton(
- onClick = if (isGenerating) onStop else onSend,
+ onClick = {
+ if (isGenerating) {
+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)
+ onStop()
+ } else {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ onSend()
+ }
+ },
enabled = isGenerating || (!isDownloading && !isAttachmentDownloadBlocked && canSend),
modifier = Modifier.size(36.dp)
) {
- val icon = when {
- isGenerating -> Icons.Outlined.StopCircle
- isDownloading -> Icons.Outlined.Download
- else -> Icons.AutoMirrored.Outlined.ArrowForward
+ val iconRes = when {
+ isGenerating -> HugeIcons.StopIcon
+ else -> HugeIcons.Navigation06Icon
}
val tint = when {
isGenerating -> EnsuColor.stopButton
- isDownloading -> EnsuColor.textMuted()
+ canSend -> EnsuColor.textPrimary()
else -> EnsuColor.textMuted()
}
- Icon(
- imageVector = icon,
- contentDescription = "Send",
- modifier = Modifier.size(22.dp),
- tint = tint
- )
+ val rotation = if (iconRes == HugeIcons.Navigation06Icon) 90f else 0f
+ if (iconRes == HugeIcons.StopIcon) {
+ Box(
+ modifier = Modifier
+ .size(22.dp)
+ .background(EnsuColor.textPrimary(), CircleShape),
+ contentAlignment = Alignment.Center
+ ) {
+ Icon(
+ painter = painterResource(iconRes),
+ contentDescription = "Send",
+ modifier = Modifier.size(12.dp),
+ tint = EnsuColor.stopButton
+ )
+ }
+ } else {
+ Icon(
+ painter = painterResource(iconRes),
+ contentDescription = "Send",
+ modifier = Modifier.size(18.dp).rotate(rotation),
+ tint = tint
+ )
+ }
}
}
}
}
}
+private fun formatBytes(bytes: Long): String {
+ val units = arrayOf("B", "KB", "MB", "GB")
+ var size = bytes.toDouble()
+ var unitIndex = 0
+ while (size >= 1024 && unitIndex < units.size - 1) {
+ size /= 1024
+ unitIndex++
+ }
+ return String.format(Locale.US, "%.1f %s", size, units[unitIndex])
+}
+
private val timestampFormatter = SimpleDateFormat("h:mm a", Locale.getDefault())
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt
index d03839faec..7e61c4bd10 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt
@@ -18,8 +18,6 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -28,6 +26,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
+import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
@@ -40,13 +39,14 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuCornerRadius
+import io.ente.ensu.designsystem.HugeIcons
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
@Composable
-fun MarkdownView(markdown: String) {
+fun MarkdownView(markdown: String, enableSelection: Boolean = true) {
val blocks = MarkdownParser.parse(markdown)
- SelectionContainer {
+ val content = @Composable {
Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {
blocks.forEach { block ->
when (block) {
@@ -91,6 +91,14 @@ fun MarkdownView(markdown: String) {
}
}
}
+
+ if (enableSelection) {
+ SelectionContainer {
+ content()
+ }
+ } else {
+ content()
+ }
}
@Composable
@@ -151,7 +159,7 @@ private fun CodeBlockView(code: String) {
.size(28.dp)
) {
Icon(
- imageVector = Icons.Outlined.ContentCopy,
+ painter = painterResource(HugeIcons.Copy01Icon),
contentDescription = "Copy code",
tint = EnsuColor.textMuted(),
modifier = Modifier.size(16.dp)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
index e60d5941d6..3a0bf139a8 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
@@ -21,13 +21,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.outlined.Add
-import androidx.compose.material.icons.outlined.BugReport
-import androidx.compose.material.icons.outlined.Build
import androidx.compose.material.icons.outlined.Cloud
-import androidx.compose.material.icons.outlined.Delete
-import androidx.compose.material.icons.outlined.Refresh
-import androidx.compose.material.icons.outlined.Tune
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalDrawerSheet
@@ -36,6 +30,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@@ -43,6 +38,7 @@ import androidx.compose.ui.unit.sp
import io.ente.ensu.components.EnsuLogo
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuCornerRadius
+import io.ente.ensu.designsystem.HugeIcons
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
import io.ente.ensu.domain.model.ChatSession
@@ -58,9 +54,8 @@ fun SessionDrawer(
onSelectSession: (ChatSession) -> Unit,
onDeleteSession: (ChatSession) -> Unit,
onSync: () -> Unit,
- onOpenLogs: () -> Unit,
- onOpenDeveloperSettings: () -> Unit,
- onOpenModelSettings: () -> Unit,
+ onOpenSettings: () -> Unit,
+ onDeveloperTap: () -> Unit,
onSignIn: () -> Unit,
onSignOut: () -> Unit
) {
@@ -76,10 +71,8 @@ fun SessionDrawer(
DrawerHeader(
isLoggedIn = isLoggedIn,
userEmail = userEmail,
- onSync = onSync,
- onOpenLogs = onOpenLogs,
- onOpenDeveloperSettings = onOpenDeveloperSettings,
- onOpenModelSettings = onOpenModelSettings
+ onOpenSettings = onOpenSettings,
+ onDeveloperTap = onDeveloperTap
)
HorizontalDivider(color = EnsuColor.border())
@@ -91,7 +84,11 @@ fun SessionDrawer(
.padding(vertical = EnsuSpacing.lg.dp),
verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)
) {
- DrawerNewChat(onNewChat = onNewChat)
+ DrawerNewChat(
+ onNewChat = onNewChat,
+ onSync = onSync,
+ isLoggedIn = isLoggedIn
+ )
SessionGroups(
sessions = sessions,
selectedSessionId = selectedSessionId,
@@ -115,10 +112,8 @@ fun SessionDrawer(
private fun DrawerHeader(
isLoggedIn: Boolean,
userEmail: String?,
- onSync: () -> Unit,
- onOpenLogs: () -> Unit,
- onOpenDeveloperSettings: () -> Unit,
- onOpenModelSettings: () -> Unit
+ onOpenSettings: () -> Unit,
+ onDeveloperTap: () -> Unit
) {
Column(
modifier = Modifier
@@ -127,19 +122,22 @@ private fun DrawerHeader(
.padding(EnsuSpacing.lg.dp),
verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
) {
- EnsuLogo(height = 28.dp)
Row(
modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
verticalAlignment = Alignment.CenterVertically
) {
- if (isLoggedIn) {
- DrawerIconButton(icon = Icons.Outlined.Refresh, contentDescription = "Sync", onClick = onSync)
+ Box(
+ modifier = Modifier
+ .clickable { onDeveloperTap() }
+ ) {
+ EnsuLogo(height = 28.dp)
}
- DrawerIconButton(icon = Icons.Outlined.BugReport, contentDescription = "Logs", onClick = onOpenLogs)
- DrawerIconButton(icon = Icons.Outlined.Build, contentDescription = "Developer settings", onClick = onOpenDeveloperSettings)
- DrawerIconButton(icon = Icons.Outlined.Tune, contentDescription = "Model settings", onClick = onOpenModelSettings)
Spacer(modifier = Modifier.weight(1f))
+ DrawerIconButton(
+ iconRes = HugeIcons.Settings01Icon,
+ contentDescription = "Settings",
+ onClick = onOpenSettings
+ )
}
if (isLoggedIn && !userEmail.isNullOrBlank()) {
@@ -150,25 +148,56 @@ private fun DrawerHeader(
@Composable
private fun DrawerIconButton(
- icon: androidx.compose.ui.graphics.vector.ImageVector,
+ iconRes: Int,
contentDescription: String,
- onClick: () -> Unit
+ onClick: () -> Unit,
+ isEnabled: Boolean = true
) {
Box(
modifier = Modifier
.size(40.dp)
- .clickable(onClick = onClick),
+ .clickable(enabled = isEnabled, onClick = onClick),
contentAlignment = Alignment.Center
) {
Icon(
- imageVector = icon,
+ painter = painterResource(iconRes),
contentDescription = contentDescription,
modifier = Modifier.size(18.dp),
- tint = EnsuColor.textPrimary()
+ tint = if (isEnabled) EnsuColor.textPrimary() else EnsuColor.textMuted()
)
}
}
+@Composable
+private fun DrawerPrimaryTile(
+ iconRes: Int,
+ label: String,
+ onClick: () -> Unit,
+ isEnabled: Boolean,
+ modifier: Modifier = Modifier
+) {
+ val tint = if (isEnabled) EnsuColor.textPrimary() else EnsuColor.textMuted()
+
+ Row(
+ modifier = modifier
+ .clip(RoundedCornerShape(EnsuCornerRadius.card.dp))
+ .background(EnsuColor.fillFaint())
+ .clickable(enabled = isEnabled, onClick = onClick)
+ .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.md.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.Center
+ ) {
+ Icon(
+ painter = painterResource(iconRes),
+ contentDescription = label,
+ modifier = Modifier.size(18.dp),
+ tint = tint
+ )
+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
+ Text(text = label, style = EnsuTypography.body, color = tint)
+ }
+}
+
@Composable
private fun CloudBadge(email: String) {
Row(
@@ -195,22 +224,34 @@ private fun CloudBadge(email: String) {
}
@Composable
-private fun DrawerNewChat(onNewChat: () -> Unit) {
+private fun DrawerNewChat(
+ onNewChat: () -> Unit,
+ onSync: () -> Unit,
+ isLoggedIn: Boolean
+) {
Row(
modifier = Modifier
.fillMaxWidth()
- .clickable(onClick = onNewChat)
- .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.sm.dp),
- verticalAlignment = Alignment.CenterVertically
+ .padding(horizontal = EnsuSpacing.lg.dp),
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
) {
- Icon(
- imageVector = Icons.Outlined.Add,
- contentDescription = "New chat",
- modifier = Modifier.size(18.dp),
- tint = EnsuColor.textPrimary()
+ DrawerPrimaryTile(
+ iconRes = HugeIcons.PlusSignIcon,
+ label = "New Chat",
+ onClick = onNewChat,
+ isEnabled = true,
+ modifier = Modifier.weight(1f)
)
- Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
- Text(text = "New Chat", style = EnsuTypography.body, color = EnsuColor.textPrimary())
+
+ if (isLoggedIn) {
+ DrawerPrimaryTile(
+ iconRes = HugeIcons.ArrowReloadHorizontalIcon,
+ label = "Sync",
+ onClick = onSync,
+ isEnabled = true,
+ modifier = Modifier.weight(1f)
+ )
+ }
}
}
@@ -279,7 +320,9 @@ private fun SessionTile(
text = session.title,
style = if (isSelected) EnsuTypography.body else EnsuTypography.small,
fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Medium,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
)
val subtitle = session.lastMessagePreview ?: "Nothing here"
Text(
@@ -298,7 +341,7 @@ private fun SessionTile(
contentAlignment = Alignment.Center
) {
Icon(
- imageVector = Icons.Outlined.Delete,
+ painter = painterResource(HugeIcons.Delete01Icon),
contentDescription = "Delete",
modifier = Modifier.size(18.dp),
tint = EnsuColor.textMuted()
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ActionButtons.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ActionButtons.kt
index d38a08ccad..e12fe4b680 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ActionButtons.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ActionButtons.kt
@@ -10,6 +10,9 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
+import androidx.compose.ui.platform.LocalHapticFeedback
+import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuTypography
@@ -21,8 +24,12 @@ fun ActionButton(
contentDescription: String,
color: Color = EnsuColor.textMuted()
) {
+ val haptic = LocalHapticFeedback.current
IconButton(
- onClick = onTap,
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ onTap()
+ },
modifier = Modifier.size(36.dp),
colors = IconButtonDefaults.iconButtonColors(contentColor = color)
) {
@@ -34,12 +41,40 @@ fun ActionButton(
}
}
+@Composable
+fun ActionButton(
+ iconRes: Int,
+ onTap: () -> Unit,
+ contentDescription: String,
+ color: Color = EnsuColor.textMuted()
+) {
+ val haptic = LocalHapticFeedback.current
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ onTap()
+ },
+ modifier = Modifier.size(36.dp),
+ colors = IconButtonDefaults.iconButtonColors(contentColor = color)
+ ) {
+ Icon(
+ painter = painterResource(iconRes),
+ contentDescription = contentDescription,
+ modifier = Modifier.size(16.dp)
+ )
+ }
+}
+
@Composable
fun TextActionButton(
text: String,
onTap: () -> Unit
) {
- TextButton(onClick = onTap) {
+ val haptic = LocalHapticFeedback.current
+ TextButton(onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ onTap()
+ }) {
Text(text = text, style = EnsuTypography.small, color = EnsuColor.textMuted())
}
}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.kt
index eaef0c827f..9d2e77a18b 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/AttachmentChip.kt
@@ -11,8 +11,6 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.material.icons.Icons
-import androidx.compose.material.icons.outlined.Close
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -20,11 +18,14 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
-import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
+import androidx.compose.ui.platform.LocalHapticFeedback
+import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuCornerRadius
+import io.ente.ensu.designsystem.HugeIcons
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
@@ -32,13 +33,17 @@ import io.ente.ensu.designsystem.EnsuTypography
fun AttachmentChip(
name: String,
size: String,
- icon: ImageVector,
+ iconRes: Int,
isUploading: Boolean,
onDelete: (() -> Unit)? = null,
onClick: (() -> Unit)? = null
) {
+ val haptic = LocalHapticFeedback.current
val clickModifier = if (onClick != null) {
- Modifier.clickable(onClick = onClick)
+ Modifier.clickable {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ onClick()
+ }
} else {
Modifier
}
@@ -52,7 +57,7 @@ fun AttachmentChip(
.padding(horizontal = 10.dp, vertical = 6.dp)
) {
Icon(
- imageVector = icon,
+ painter = painterResource(iconRes),
contentDescription = null,
modifier = Modifier.size(14.dp),
tint = EnsuColor.textMuted()
@@ -86,9 +91,15 @@ fun AttachmentChip(
}
if (onDelete != null) {
Spacer(modifier = Modifier.width(EnsuSpacing.xs.dp))
- IconButton(onClick = onDelete, modifier = Modifier.size(24.dp)) {
+ IconButton(
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)
+ onDelete()
+ },
+ modifier = Modifier.size(24.dp)
+ ) {
Icon(
- imageVector = Icons.Outlined.Close,
+ painter = painterResource(HugeIcons.Cancel01Icon),
contentDescription = "Remove attachment",
tint = EnsuColor.textMuted()
)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.kt
index e96349faef..34b0cd71c6 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/BranchSwitcher.kt
@@ -10,6 +10,8 @@ import androidx.compose.material3.ButtonDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
+import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.unit.dp
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuTypography
@@ -23,9 +25,13 @@ fun BranchSwitcher(
) {
if (totalCount <= 1) return
+ val haptic = LocalHapticFeedback.current
Row(verticalAlignment = Alignment.CenterVertically) {
TextButton(
- onClick = onPrevious,
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ onPrevious()
+ },
enabled = currentIndex > 1,
modifier = Modifier.size(36.dp),
contentPadding = ButtonDefaults.TextButtonContentPadding
@@ -40,7 +46,10 @@ fun BranchSwitcher(
)
Spacer(modifier = Modifier.width(4.dp))
TextButton(
- onClick = onNext,
+ onClick = {
+ haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
+ onNext()
+ },
enabled = currentIndex < totalCount,
modifier = Modifier.size(36.dp),
contentPadding = ButtonDefaults.TextButtonContentPadding
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ChoiceDialog.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ChoiceDialog.kt
index 4d83b62f99..d48005bedb 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ChoiceDialog.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/ChoiceDialog.kt
@@ -1,11 +1,13 @@
package io.ente.ensu.components
import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.AlertDialogDefaults
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
+import androidx.compose.ui.unit.dp
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuTypography
@@ -26,13 +28,17 @@ fun ChoiceDialog(
title = { Text(text = title, style = EnsuTypography.h3) },
text = { Text(text = body, style = EnsuTypography.body) },
confirmButton = {
- Button(
- onClick = onFirst,
- colors = ButtonDefaults.buttonColors(
- containerColor = if (isCritical) EnsuColor.error else EnsuColor.accent()
- )
- ) {
- Text(text = firstButtonLabel)
+ if (isCritical) {
+ Button(
+ onClick = onFirst,
+ colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.error)
+ ) {
+ Text(text = firstButtonLabel)
+ }
+ } else {
+ TextButton(onClick = onFirst) {
+ Text(text = firstButtonLabel, color = EnsuColor.textPrimary())
+ }
}
},
dismissButton = {
@@ -41,6 +47,9 @@ fun ChoiceDialog(
Text(text = secondButtonLabel)
}
}
- }
+ },
+ containerColor = EnsuColor.backgroundBase(),
+ tonalElevation = 0.dp,
+ shape = AlertDialogDefaults.shape
)
}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/NativeChoiceDialog.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/NativeChoiceDialog.kt
new file mode 100644
index 0000000000..6e148ceb15
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/components/NativeChoiceDialog.kt
@@ -0,0 +1,51 @@
+package io.ente.ensu.components
+
+import android.app.AlertDialog
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.ui.platform.LocalContext
+
+@Composable
+fun NativeChoiceDialog(
+ title: String,
+ body: String,
+ firstButtonLabel: String,
+ secondButtonLabel: String? = null,
+ isDismissible: Boolean = true,
+ onFirst: () -> Unit,
+ onSecond: (() -> Unit)? = null,
+ onDismiss: () -> Unit
+) {
+ val context = LocalContext.current
+ val currentOnFirst by rememberUpdatedState(onFirst)
+ val currentOnSecond by rememberUpdatedState(onSecond)
+ val currentOnDismiss by rememberUpdatedState(onDismiss)
+
+ DisposableEffect(title, body, firstButtonLabel, secondButtonLabel, isDismissible) {
+ val builder = AlertDialog.Builder(context)
+ .setTitle(title)
+ .setMessage(body)
+ .setPositiveButton(firstButtonLabel) { _, _ ->
+ currentOnFirst()
+ }
+
+ if (secondButtonLabel != null && currentOnSecond != null) {
+ builder.setNegativeButton(secondButtonLabel) { _, _ ->
+ currentOnSecond?.invoke()
+ }
+ }
+
+ val dialog = builder.create()
+ dialog.setCancelable(isDismissible)
+ dialog.setCanceledOnTouchOutside(isDismissible)
+ dialog.setOnDismissListener { currentOnDismiss() }
+ dialog.show()
+
+ onDispose {
+ dialog.setOnDismissListener(null)
+ dialog.dismiss()
+ }
+ }
+}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/designsystem/EnsuTheme.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/designsystem/EnsuTheme.kt
index b1b0031f15..72b9f0e706 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/designsystem/EnsuTheme.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/designsystem/EnsuTheme.kt
@@ -163,25 +163,45 @@ fun EnsuTheme(content: @Composable () -> Unit) {
private fun lightEnsuColorScheme(): ColorScheme = lightColorScheme(
primary = EnsuColor.accentLight,
onPrimary = EnsuColor.backgroundBaseLight,
+
secondary = EnsuColor.fillFaintLight,
onSecondary = EnsuColor.textPrimaryLight,
+
background = EnsuColor.backgroundBaseLight,
onBackground = EnsuColor.textPrimaryLight,
+
surface = EnsuColor.fillFaintLight,
onSurface = EnsuColor.textPrimaryLight,
+
+ // Important for default M3 components (e.g. TextField placeholder/label colors).
+ // If not set, Material uses its default palette (purple-ish).
+ surfaceVariant = EnsuColor.fillFaintLight,
+ onSurfaceVariant = EnsuColor.textMutedLight,
+
outline = EnsuColor.borderLight,
+ outlineVariant = EnsuColor.borderLight,
+
error = EnsuColor.error
)
private fun darkEnsuColorScheme(): ColorScheme = darkColorScheme(
primary = EnsuColor.accentDark,
onPrimary = EnsuColor.backgroundBaseDark,
+
secondary = EnsuColor.fillFaintDark,
onSecondary = EnsuColor.textPrimaryDark,
+
background = EnsuColor.backgroundBaseDark,
onBackground = EnsuColor.textPrimaryDark,
+
surface = EnsuColor.fillFaintDark,
onSurface = EnsuColor.textPrimaryDark,
+
+ surfaceVariant = EnsuColor.fillFaintDark,
+ onSurfaceVariant = EnsuColor.textMutedDark,
+
outline = EnsuColor.borderDark,
+ outlineVariant = EnsuColor.borderDark,
+
error = EnsuColor.error
)
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/designsystem/HugeIcons.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/designsystem/HugeIcons.kt
new file mode 100644
index 0000000000..0e0d85c758
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/designsystem/HugeIcons.kt
@@ -0,0 +1,30 @@
+package io.ente.ensu.designsystem
+
+import io.ente.ensu.R
+
+object HugeIcons {
+ val ArrowDown01Icon = R.drawable.hugeicon_arrow_down01
+ val ArrowLeft01Icon = R.drawable.hugeicon_arrow_left01
+ val ArrowRight01Icon = R.drawable.hugeicon_arrow_right01
+ val ArrowRight02Icon = R.drawable.hugeicon_arrow_right02
+ val ArrowReloadHorizontalIcon = R.drawable.hugeicon_arrow_reload_horizontal
+ val Attachment01Icon = R.drawable.hugeicon_attachment01
+ val Bug01Icon = R.drawable.hugeicon_bug01
+ val Cancel01Icon = R.drawable.hugeicon_cancel01
+ val Copy01Icon = R.drawable.hugeicon_copy01
+ val Delete01Icon = R.drawable.hugeicon_delete01
+ val Edit01Icon = R.drawable.hugeicon_edit01
+ val Menu01Icon = R.drawable.hugeicon_menu01
+ val PlusSignIcon = R.drawable.hugeicon_plus_sign
+ val RefreshIcon = R.drawable.hugeicon_refresh
+ val RepeatIcon = R.drawable.hugeicon_repeat
+ val Search01Icon = R.drawable.hugeicon_search01
+ val Settings01Icon = R.drawable.hugeicon_settings01
+ val SlidersHorizontalIcon = R.drawable.hugeicon_sliders_horizontal
+ val StopCircleIcon = R.drawable.hugeicon_stop_circle
+ val StopIcon = R.drawable.hugeicon_stop
+ val Upload01Icon = R.drawable.hugeicon_upload01
+ val Navigation06Icon = R.drawable.hugeicon_navigation06
+ val ViewIcon = R.drawable.hugeicon_view
+ val ViewOffSlashIcon = R.drawable.hugeicon_view_off_slash
+}
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 fbd73dd7ee..31668a8e28 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
@@ -41,6 +41,7 @@ fun ModelSettingsScreen(
var mmprojUrl by remember(state) { mutableStateOf(state.mmprojUrl) }
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(
@@ -155,6 +156,17 @@ fun ModelSettingsScreen(
}
}
+ 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())
@@ -170,7 +182,8 @@ fun ModelSettingsScreen(
modelUrl = modelUrl,
mmprojUrl = mmprojUrl,
contextLength = contextLength,
- maxTokens = maxTokens
+ maxTokens = maxTokens,
+ temperature = temperature
)
)
},
@@ -188,6 +201,7 @@ fun ModelSettingsScreen(
mmprojUrl = ""
contextLength = ""
maxTokens = ""
+ temperature = ""
}) {
Text(text = "Use Default Model", style = EnsuTypography.body, color = EnsuColor.accent())
}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/LogViewerScreen.kt b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/LogViewerScreen.kt
index 1f9ddfd7cf..0d7f092cec 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/LogViewerScreen.kt
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/LogViewerScreen.kt
@@ -5,24 +5,32 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
+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.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
+import io.ente.ensu.data.logging.FileLogRepository
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.model.LogEntry
@@ -32,19 +40,58 @@ import java.util.Date
import java.util.Locale
@Composable
-fun LogViewerScreen(logs: List<LogEntry>) {
+fun LogViewerScreen(
+ logRepository: FileLogRepository
+) {
+ var entries by remember { mutableStateOf<List<LogEntry>>(emptyList()) }
var selectedLog by remember { mutableStateOf<LogEntry?>(null) }
+ var query by remember { mutableStateOf("") }
+
+ LaunchedEffect(Unit) {
+ entries = logRepository.readTodayEntries()
+ }
+
+ LaunchedEffect(logRepository.logs) {
+ entries = logRepository.readTodayEntries()
+ }
+
+ val filteredLogs = remember(entries, query) {
+ val q = query.trim().lowercase()
+ if (q.isEmpty()) return@remember entries
+ entries.filter { entry ->
+ entry.message.lowercase().contains(q) ||
+ (entry.tag?.lowercase()?.contains(q) == true) ||
+ (entry.details?.lowercase()?.contains(q) == true)
+ }
+ }
Column(
modifier = Modifier
.fillMaxSize()
.padding(EnsuSpacing.pageHorizontal.dp)
) {
- if (logs.isEmpty()) {
+ OutlinedTextField(
+ value = query,
+ onValueChange = { query = it },
+ modifier = Modifier.fillMaxWidth(),
+ placeholder = { Text(text = "Search logs", style = EnsuTypography.body) },
+ singleLine = true,
+ 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.lg.dp))
+
+ if (filteredLogs.isEmpty()) {
Text(text = "No logs available", style = EnsuTypography.body, color = EnsuColor.textMuted())
} else {
LazyColumn(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {
- items(logs, key = { it.id }) { log ->
+ items(filteredLogs, key = { it.id }) { log ->
LogRow(logEntry = log, onOpenDetails = { selectedLog = log })
}
}
@@ -57,6 +104,13 @@ fun LogViewerScreen(logs: List<LogEntry>) {
title = { Text(text = "Log details", style = EnsuTypography.h3) },
text = {
Column {
+ Row(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {
+ Text(text = log.level.name, style = EnsuTypography.small, color = levelColor(log.level))
+ log.tag?.let { tag ->
+ Text(text = tag, style = EnsuTypography.small, color = EnsuColor.textMuted())
+ }
+ }
+ Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
Text(text = log.message, style = EnsuTypography.body)
log.details?.let { details ->
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
@@ -65,9 +119,7 @@ fun LogViewerScreen(logs: List<LogEntry>) {
}
},
confirmButton = {
- TextButton(onClick = { selectedLog = null }) {
- Text(text = "Close")
- }
+ TextButton(onClick = { selectedLog = null }) { Text(text = "Close") }
}
)
}
@@ -78,15 +130,20 @@ private fun LogRow(logEntry: LogEntry, onOpenDetails: () -> Unit) {
Column(
modifier = Modifier
.fillMaxWidth()
+ .clickable(onClick = onOpenDetails)
.padding(vertical = EnsuSpacing.xs.dp)
) {
- Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = logEntry.level.name,
style = EnsuTypography.mini,
color = levelColor(logEntry.level)
)
Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
+ logEntry.tag?.let { tag ->
+ Text(text = tag, style = EnsuTypography.mini, color = EnsuColor.textMuted())
+ Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
+ }
Text(
text = logTimestampFormatter.format(Date(logEntry.timestampMillis)),
style = EnsuTypography.mini,
@@ -95,9 +152,6 @@ private fun LogRow(logEntry: LogEntry, onOpenDetails: () -> Unit) {
}
Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
Text(text = logEntry.message, style = EnsuTypography.body)
- TextButton(onClick = onOpenDetails) {
- Text(text = "Details", style = EnsuTypography.small, color = EnsuColor.accent())
- }
}
}
@@ -108,4 +162,4 @@ private fun levelColor(level: LogLevel): Color = when (level) {
LogLevel.Error -> EnsuColor.error
}
-private val logTimestampFormatter = SimpleDateFormat("h:mm:ss a", Locale.getDefault())
+private val logTimestampFormatter = SimpleDateFormat("MMM d, h:mm:ss a", Locale.getDefault())
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
new file mode 100644
index 0000000000..d584aa6b55
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/java/io/ente/ensu/settings/SettingsScreen.kt
@@ -0,0 +1,142 @@
+package io.ente.ensu.settings
+
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.HorizontalDivider
+import androidx.compose.material3.Icon
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+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.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.painterResource
+import androidx.compose.ui.text.style.TextAlign
+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.designsystem.HugeIcons
+
+@Composable
+fun SettingsScreen(
+ currentEndpoint: String,
+ onOpenModelSettings: () -> Unit,
+ onOpenLogs: () -> Unit
+) {
+ var query by remember { mutableStateOf("") }
+
+ val allItems = remember(onOpenModelSettings, onOpenLogs) {
+ listOf(
+ SettingsItem(
+ title = "Model settings",
+ subtitle = "Model URL, mmproj, context length, max output",
+ onClick = onOpenModelSettings
+ ),
+ SettingsItem(
+ title = "Logs",
+ subtitle = "View, export, and share logs",
+ onClick = onOpenLogs
+ )
+ )
+ }
+
+ val filteredItems = remember(query, allItems) {
+ val q = query.trim().lowercase()
+ if (q.isEmpty()) return@remember allItems
+ allItems.filter { item ->
+ item.title.lowercase().contains(q) ||
+ (item.subtitle?.lowercase()?.contains(q) == true)
+ }
+ }
+
+ Column(modifier = Modifier.padding(EnsuSpacing.pageHorizontal.dp)) {
+ OutlinedTextField(
+ value = query,
+ onValueChange = { query = it },
+ modifier = Modifier.fillMaxWidth(),
+ placeholder = { Text(text = "Search settings", style = EnsuTypography.body) },
+ singleLine = true,
+ colors = TextFieldDefaults.colors(
+ focusedContainerColor = EnsuColor.fillFaint(),
+ unfocusedContainerColor = EnsuColor.fillFaint(),
+ focusedIndicatorColor = EnsuColor.fillFaint(),
+ unfocusedIndicatorColor = EnsuColor.fillFaint()
+ ),
+ shape = RoundedCornerShape(EnsuCornerRadius.input.dp)
+ )
+
+ Spacer(modifier = Modifier.size(EnsuSpacing.lg.dp))
+
+ val normalizedEndpoint = currentEndpoint.trim().trimEnd('/')
+ val defaultEndpoint = "https://api.ente.io"
+ val isCustomEndpoint = query.isBlank() && normalizedEndpoint.isNotBlank() && normalizedEndpoint != defaultEndpoint
+
+ LazyColumn(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {
+ items(filteredItems, key = { it.title }) { item ->
+ SettingsRow(item)
+ HorizontalDivider(color = EnsuColor.border())
+ }
+
+ if (isCustomEndpoint) {
+ item(key = "endpoint") {
+ Spacer(modifier = Modifier.size(EnsuSpacing.sm.dp))
+ Text(
+ text = "Endpoint: $normalizedEndpoint",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted(),
+ textAlign = TextAlign.Center,
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = EnsuSpacing.sm.dp)
+ )
+ }
+ }
+ }
+ }
+}
+
+private data class SettingsItem(
+ val title: String,
+ val subtitle: String? = null,
+ val onClick: () -> Unit
+)
+
+@Composable
+private fun SettingsRow(item: SettingsItem) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable(onClick = item.onClick)
+ .padding(vertical = EnsuSpacing.sm.dp),
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(text = item.title, style = EnsuTypography.body, color = EnsuColor.textPrimary())
+ if (!item.subtitle.isNullOrBlank()) {
+ Text(text = item.subtitle, style = EnsuTypography.small, color = EnsuColor.textMuted())
+ }
+ }
+ Icon(
+ painter = painterResource(HugeIcons.ArrowRight01Icon),
+ contentDescription = null,
+ tint = EnsuColor.textMuted(),
+ modifier = Modifier.size(18.dp)
+ )
+ }
+}
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_down01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_down01.xml
new file mode 100644
index 0000000000..65b2659446
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_down01.xml
@@ -0,0 +1,13 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M18 9.00005C18 9.00005 13.5811 15 12 15C10.4188 15 6 9 6 9" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_left01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_left01.xml
new file mode 100644
index 0000000000..c895f5029d
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_left01.xml
@@ -0,0 +1,13 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M15 6C15 6 9.00001 10.4189 9 12C8.99999 13.5812 15 18 15 18" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_reload_horizontal.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_reload_horizontal.xml
new file mode 100644
index 0000000000..ac3bf2b51e
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_reload_horizontal.xml
@@ -0,0 +1,34 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M20.5 5.5H9.5C5.78672 5.5 3 8.18503 3 12" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M3.5 18.5H14.5C18.2133 18.5 21 15.815 21 12" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M18.5 3C18.5 3 21 4.84122 21 5.50002C21 6.15882 18.5 8 18.5 8" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M5.49998 16C5.49998 16 3.00001 17.8412 3 18.5C2.99999 19.1588 5.5 21 5.5 21" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_right01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_right01.xml
new file mode 100644
index 0000000000..81bdbf5904
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_right01.xml
@@ -0,0 +1,13 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M9.00005 6C9.00005 6 15 10.4189 15 12C15 13.5812 9 18 9 18" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_right02.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_right02.xml
new file mode 100644
index 0000000000..b897474e42
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_arrow_right02.xml
@@ -0,0 +1,20 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M18.5 12L4.99997 12" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M13 18C13 18 19 13.5811 19 12C19 10.4188 13 6 13 6" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_attachment01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_attachment01.xml
new file mode 100644
index 0000000000..1de153d170
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_attachment01.xml
@@ -0,0 +1,13 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M5.82338 12L4.27922 10.4558C2.57359 8.75022 2.57359 5.98485 4.27922 4.27922C5.98485 2.57359 8.75022 2.57359 10.4558 4.27922L19.7208 13.5442C21.4264 15.2498 21.4264 18.0152 19.7208 19.7208C18.0152 21.4264 15.2498 21.4264 13.5442 19.7208L10.0698 16.2464C9.00379 15.1804 9.00379 13.4521 10.0698 12.386C11.1358 11.32 12.8642 11.32 13.9302 12.386L15.8604 14.3162" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_bug01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_bug01.xml
new file mode 100644
index 0000000000..63037c2b71
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_bug01.xml
@@ -0,0 +1,53 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M3.01309 4.99084C2.89323 6.05084 3.55249 8.42285 6.48923 8.42285" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M17.5951 8.38081C18.8357 8.57881 21.1132 7.49881 20.9957 5.00281" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M20.9928 20.9989C21.0528 19.9429 20.1777 17.5549 17.599 17.4229" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M6.45163 17.4708C5.65013 17.2308 3.01306 18.3348 3.01306 20.9988" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:pathData="M9.3299 6.11884C9.35388 5.09884 9.84533 2.99884 12.0029 2.99884C13.9208 2.99884 14.5861 4.61884 14.676 6.11884M6.26131 9.41884C6.38118 8.63884 7.29216 6.81484 9.36586 6.63484C11.4635 6.55564 14.3403 6.58684 14.8797 6.67084C15.5869 6.73377 17.2951 7.43884 17.7506 9.41884C17.9124 10.4388 17.8285 11.8788 17.8524 12.7188C17.8165 13.5588 17.9207 15.2623 17.7565 16.1388C17.6367 17.0988 16.9894 18.4668 16.1024 19.3068C14.7838 20.7228 11.1639 22.2108 8.03534 19.4508C6.41713 17.8908 6.30925 16.3788 6.18939 15.7788C6.15725 15.4571 6.15875 13.8763 6.16541 12.3588C6.14144 11.046 6.17235 9.78063 6.26131 9.41884Z" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M3.01306 12.8988H5.9498" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M20.9929 12.8988L18.1161 12.8988" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M12.0033 16.4988L12.0033 20.2788" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_cancel01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_cancel01.xml
new file mode 100644
index 0000000000..db7ffaf65e
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_cancel01.xml
@@ -0,0 +1,13 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M18 6L6.00081 17.9992M17.9992 18L6 6.00085" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_copy01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_copy01.xml
new file mode 100644
index 0000000000..d5410422f4
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_copy01.xml
@@ -0,0 +1,20 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M9 15C9 12.1716 9 10.7574 9.87868 9.87868C10.7574 9 12.1716 9 15 9L16 9C18.8284 9 20.2426 9 21.1213 9.87868C22 10.7574 22 12.1716 22 15V16C22 18.8284 22 20.2426 21.1213 21.1213C20.2426 22 18.8284 22 16 22H15C12.1716 22 10.7574 22 9.87868 21.1213C9 20.2426 9 18.8284 9 16L9 15Z" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M16.9999 9C16.9975 6.04291 16.9528 4.51121 16.092 3.46243C15.9258 3.25989 15.7401 3.07418 15.5376 2.90796C14.4312 2 12.7875 2 9.5 2C6.21252 2 4.56878 2 3.46243 2.90796C3.25989 3.07417 3.07418 3.25989 2.90796 3.46243C2 4.56878 2 6.21252 2 9.5C2 12.7875 2 14.4312 2.90796 15.5376C3.07417 15.7401 3.25989 15.9258 3.46243 16.092C4.51121 16.9528 6.04291 16.9975 9 16.9999" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_delete01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_delete01.xml
new file mode 100644
index 0000000000..01a1399662
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_delete01.xml
@@ -0,0 +1,18 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M19.5 5.5L18.8803 15.5251C18.7219 18.0864 18.6428 19.3671 18.0008 20.2879C17.6833 20.7431 17.2747 21.1273 16.8007 21.416C15.8421 22 14.559 22 11.9927 22C9.42312 22 8.1383 22 7.17905 21.4149C6.7048 21.1257 6.296 20.7408 5.97868 20.2848C5.33688 19.3626 5.25945 18.0801 5.10461 15.5152L4.5 5.5" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M3 5.5H21M16.0557 5.5L15.3731 4.09173C14.9196 3.15626 14.6928 2.68852 14.3017 2.39681C14.215 2.3321 14.1231 2.27454 14.027 2.2247C13.5939 2 13.0741 2 12.0345 2C10.9688 2 10.436 2 9.99568 2.23412C9.8981 2.28601 9.80498 2.3459 9.71729 2.41317C9.32164 2.7167 9.10063 3.20155 8.65861 4.17126L8.05292 5.5" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_edit01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_edit01.xml
new file mode 100644
index 0000000000..ff85780bf4
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_edit01.xml
@@ -0,0 +1,19 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineJoin="round"
+ android:pathData="M16.9459 3.17305C17.5332 2.58578 17.8268 2.29215 18.1521 2.15173C18.6208 1.94942 19.1521 1.94942 19.6208 2.15173C19.946 2.29215 20.2397 2.58578 20.8269 3.17305C21.4142 3.76032 21.7079 4.05395 21.8483 4.37925C22.0506 4.8479 22.0506 5.37924 21.8483 5.84789C21.7079 6.17319 21.4142 6.46682 20.8269 7.05409L15.8054 12.0757C14.5682 13.3129 13.9496 13.9315 13.1748 14.298C12.4 14.6645 11.5294 14.7504 9.78823 14.9222L9 15L9.07778 14.2118C9.24958 12.4706 9.33549 11.6 9.70201 10.8252C10.0685 10.0504 10.6871 9.43183 11.9243 8.19464L16.9459 3.17305Z" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M6 15H3.75C2.7835 15 2 15.7835 2 16.75C2 17.7165 2.7835 18.5 3.75 18.5H13.25C14.2165 18.5 15 19.2835 15 20.25C15 21.2165 14.2165 22 13.25 22H11" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_menu01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_menu01.xml
new file mode 100644
index 0000000000..1167a3964d
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_menu01.xml
@@ -0,0 +1,27 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M4 5L20 5" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M4 12L20 12" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M4 19L20 19" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_navigation06.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_navigation06.xml
new file mode 100644
index 0000000000..72bfd9b329
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_navigation06.xml
@@ -0,0 +1,12 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineJoin="round"
+ android:pathData="M6.73726 10.4584C9.00955 5.81947 10.1457 3.5 12 3.5C13.8543 3.5 14.9904 5.81946 17.2627 10.4584L18.8101 13.6174C20.5552 17.18 21.4277 18.9613 20.7934 19.8178C20.6228 20.0481 20.398 20.238 20.1366 20.3729C19.1643 20.8743 17.3794 19.8641 13.8096 17.8436C13.0178 17.3954 12.6219 17.1713 12.1889 17.1312C12.0633 17.1196 11.9367 17.1196 11.8111 17.1312C11.3781 17.1713 10.9822 17.3954 10.1904 17.8436C6.62059 19.8641 4.83571 20.8743 3.86337 20.3729C3.60196 20.238 3.37719 20.0481 3.20664 19.8178C2.57226 18.9613 3.44481 17.18 5.1899 13.6174L6.73726 10.4584Z" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_plus_sign.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_plus_sign.xml
new file mode 100644
index 0000000000..3058d0feb0
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_plus_sign.xml
@@ -0,0 +1,13 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M12 4V20M20 12H4" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_refresh.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_refresh.xml
new file mode 100644
index 0000000000..f5b6125a1e
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_refresh.xml
@@ -0,0 +1,13 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M20.0092 2V5.13219C20.0092 5.42605 19.6418 5.55908 19.4537 5.33333C17.6226 3.2875 14.9617 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_repeat.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_repeat.xml
new file mode 100644
index 0000000000..8c103964bd
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_repeat.xml
@@ -0,0 +1,20 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M16.3884 3L17.3913 3.97574C17.8393 4.41165 18.0633 4.62961 17.9844 4.81481C17.9056 5 17.5888 5 16.9552 5H9.19422C5.22096 5 2 8.13401 2 12C2 13.4872 2.47668 14.8662 3.2895 16" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M7.61156 21L6.60875 20.0243C6.16074 19.5883 5.93673 19.3704 6.01557 19.1852C6.09441 19 6.4112 19 7.04478 19H14.8058C18.779 19 22 15.866 22 12C22 10.5128 21.5233 9.13383 20.7105 8" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_search01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_search01.xml
new file mode 100644
index 0000000000..789d0d04a7
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_search01.xml
@@ -0,0 +1,20 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M17 17L21 21" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M19 11C19 6.58172 15.4183 3 11 3C6.58172 3 3 6.58172 3 11C3 15.4183 6.58172 19 11 19C15.4183 19 19 15.4183 19 11Z" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_settings01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_settings01.xml
new file mode 100644
index 0000000000..e899e8f7dd
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_settings01.xml
@@ -0,0 +1,17 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M21.3175 7.14139L20.8239 6.28479C20.4506 5.63696 20.264 5.31305 19.9464 5.18388C19.6288 5.05472 19.2696 5.15664 18.5513 5.36048L17.3311 5.70418C16.8725 5.80994 16.3913 5.74994 15.9726 5.53479L15.6357 5.34042C15.2766 5.11043 15.0004 4.77133 14.8475 4.37274L14.5136 3.37536C14.294 2.71534 14.1842 2.38533 13.9228 2.19657C13.6615 2.00781 13.3143 2.00781 12.6199 2.00781H11.5051C10.8108 2.00781 10.4636 2.00781 10.2022 2.19657C9.94085 2.38533 9.83106 2.71534 9.61149 3.37536L9.27753 4.37274C9.12465 4.77133 8.84845 5.11043 8.48937 5.34042L8.15249 5.53479C7.73374 5.74994 7.25259 5.80994 6.79398 5.70418L5.57375 5.36048C4.85541 5.15664 4.49625 5.05472 4.17867 5.18388C3.86109 5.31305 3.67445 5.63696 3.30115 6.28479L2.80757 7.14139C2.45766 7.74864 2.2827 8.05227 2.31666 8.37549C2.35061 8.69871 2.58483 8.95918 3.05326 9.48012L4.0843 10.6328C4.3363 10.9518 4.51521 11.5078 4.51521 12.0077C4.51521 12.5078 4.33636 13.0636 4.08433 13.3827L3.05326 14.5354C2.58483 15.0564 2.35062 15.3168 2.31666 15.6401C2.2827 15.9633 2.45766 16.2669 2.80757 16.8741L3.30114 17.7307C3.67443 18.3785 3.86109 18.7025 4.17867 18.8316C4.49625 18.9608 4.85542 18.8589 5.57377 18.655L6.79394 18.3113C7.25263 18.2055 7.73387 18.2656 8.15267 18.4808L8.4895 18.6752C8.84851 18.9052 9.12464 19.2442 9.2775 19.6428L9.61149 20.6403C9.83106 21.3003 9.94085 21.6303 10.2022 21.8191C10.4636 22.0078 10.8108 22.0078 11.5051 22.0078H12.6199C13.3143 22.0078 13.6615 22.0078 13.9228 21.8191C14.1842 21.6303 14.294 21.3003 14.5136 20.6403L14.8476 19.6428C15.0004 19.2442 15.2765 18.9052 15.6356 18.6752L15.9724 18.4808C16.3912 18.2656 16.8724 18.2055 17.3311 18.3113L18.5513 18.655C19.2696 18.8589 19.6288 18.9608 19.9464 18.8316C20.264 18.7025 20.4506 18.3785 20.8239 17.7307L21.3175 16.8741C21.6674 16.2669 21.8423 15.9633 21.8084 15.6401C21.7744 15.3168 21.5402 15.0564 21.0718 14.5354L20.0407 13.3827C19.7887 13.0636 19.6098 12.5078 19.6098 12.0077C19.6098 11.5078 19.7888 10.9518 20.0407 10.6328L21.0718 9.48012C21.5402 8.95918 21.7744 8.69871 21.8084 8.37549C21.8423 8.05227 21.6674 7.74864 21.3175 7.14139Z" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:pathData="M15.5195 12C15.5195 13.933 13.9525 15.5 12.0195 15.5C10.0865 15.5 8.51953 13.933 8.51953 12C8.51953 10.067 10.0865 8.5 12.0195 8.5C13.9525 8.5 15.5195 10.067 15.5195 12Z" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_sliders_horizontal.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_sliders_horizontal.xml
new file mode 100644
index 0000000000..1a949b0e38
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_sliders_horizontal.xml
@@ -0,0 +1,60 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M3.99963 5.00055L9.99963 5.00031" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M12.9996 5.00031L19.9996 5.00031" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M15.9996 9.00031L15.9996 15.0003" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M9.99963 2.00031L9.99963 8.00031" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M11.9996 16.0003L11.9996 22.0003" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M15.9996 12.0001L19.9996 12.0003" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M3.99963 12.0005L12.9996 12.0003" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M11.9996 19.0003L19.9996 19.0003" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M3.99963 19.0005L8.99963 19.0003" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_stop.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_stop.xml
new file mode 100644
index 0000000000..93cefd4565
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_stop.xml
@@ -0,0 +1,9 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#FF000000"
+ android:pathData="M4 12C4 8.72077 4 7.08116 4.81382 5.91891C5.1149 5.48891 5.48891 5.1149 5.91891 4.81382C7.08116 4 8.72077 4 12 4C15.2792 4 16.9188 4 18.0811 4.81382C18.5111 5.1149 18.8851 5.48891 19.1862 5.91891C20 7.08116 20 8.72077 20 12C20 15.2792 20 16.9188 19.1862 18.0811C18.8851 18.5111 18.5111 18.8851 18.0811 19.1862C16.9188 20 15.2792 20 12 20C8.72077 20 7.08116 20 5.91891 19.1862C5.48891 18.8851 5.1149 18.5111 4.81382 18.0811C4 16.9188 4 15.2792 4 12Z" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_stop_circle.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_stop_circle.xml
new file mode 100644
index 0000000000..4742fe9ae7
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_stop_circle.xml
@@ -0,0 +1,18 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:pathData="M 12.0 2.0 A 10.0 10.0 0 1 0 12.0 22.0 A 10.0 10.0 0 1 0 12.0 2.0" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M9.38886 15.1629C9.89331 15.5 10.5955 15.5 12 15.5C13.4045 15.5 14.1067 15.5 14.6111 15.1629C14.8295 15.017 15.017 14.8295 15.1629 14.6111C15.5 14.1067 15.5 13.4045 15.5 12C15.5 10.5955 15.5 9.89331 15.1629 9.38886C15.017 9.17048 14.8295 8.98298 14.6111 8.83706C14.1067 8.5 13.4045 8.5 12 8.5C10.5955 8.5 9.89331 8.5 9.38886 8.83706C9.17048 8.98298 8.98298 9.17048 8.83706 9.38886C8.5 9.89331 8.5 10.5955 8.5 12C8.5 13.4045 8.5 14.1067 8.83706 14.6111C8.98298 14.8295 9.17048 15.017 9.38886 15.1629Z" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_upload01.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_upload01.xml
new file mode 100644
index 0000000000..e0eb16b609
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_upload01.xml
@@ -0,0 +1,20 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M2.99995 17C2.99995 17.93 2.99995 18.395 3.10217 18.7765C3.37957 19.8117 4.18821 20.6204 5.22349 20.8978C5.60499 21 6.06997 21 6.99995 21L16.9999 21C17.9299 21 18.3949 21 18.7764 20.8978C19.8117 20.6204 20.6203 19.8117 20.8977 18.7765C20.9999 18.395 20.9999 17.93 20.9999 17" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M16.5 7.49993C16.5 7.49993 13.1858 2.99997 12 2.99996C10.8142 2.99995 7.50002 7.49996 7.50002 7.49996M12 3.99996V16" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_view.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_view.xml
new file mode 100644
index 0000000000..ba3594d58e
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_view.xml
@@ -0,0 +1,16 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:pathData="M21.544 11.045C21.848 11.4713 22 11.6845 22 12C22 12.3155 21.848 12.5287 21.544 12.955C20.1779 14.8706 16.6892 19 12 19C7.31078 19 3.8221 14.8706 2.45604 12.955C2.15201 12.5287 2 12.3155 2 12C2 11.6845 2.15201 11.4713 2.45604 11.045C3.8221 9.12944 7.31078 5 12 5C16.6892 5 20.1779 9.12944 21.544 11.045Z" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:pathData="M15 12C15 10.3431 13.6569 9 12 9C10.3431 9 9 10.3431 9 12C9 13.6569 10.3431 15 12 15C13.6569 15 15 13.6569 15 12Z" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_view_off_slash.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_view_off_slash.xml
new file mode 100644
index 0000000000..1408dbb73c
--- /dev/null
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/drawable/hugeicon_view_off_slash.xml
@@ -0,0 +1,26 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M19.439 15.439C20.3636 14.5212 21.0775 13.6091 21.544 12.955C21.848 12.5287 22 12.3155 22 12C22 11.6845 21.848 11.4713 21.544 11.045C20.1779 9.12944 16.6892 5 12 5C11.0922 5 10.2294 5.15476 9.41827 5.41827M6.74742 6.74742C4.73118 8.1072 3.24215 9.94266 2.45604 11.045C2.15201 11.4713 2 11.6845 2 12C2 12.3155 2.15201 12.5287 2.45604 12.955C3.8221 14.8706 7.31078 19 12 19C13.9908 19 15.7651 18.2557 17.2526 17.2526" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:pathData="M9.85786 10C9.32783 10.53 9 11.2623 9 12.0711C9 13.6887 10.3113 15 11.9289 15C12.7377 15 13.47 14.6722 14 14.1421" />
+ <path
+ android:fillColor="#00000000"
+ android:strokeColor="#FF000000"
+ android:strokeWidth="2"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round"
+ android:pathData="M3 3L21 21" />
+</vector>
\ No newline at end of file
diff --git a/mobile/native/android/apps/ensu/app-ui/src/main/res/xml/file_paths.xml b/mobile/native/android/apps/ensu/app-ui/src/main/res/xml/file_paths.xml
index bb5b4fbc11..8ec9c398b9 100644
--- a/mobile/native/android/apps/ensu/app-ui/src/main/res/xml/file_paths.xml
+++ b/mobile/native/android/apps/ensu/app-ui/src/main/res/xml/file_paths.xml
@@ -3,4 +3,12 @@
<files-path
name="attachments"
path="attachments/" />
+
+ <files-path
+ name="logs"
+ path="logs/" />
+
+ <cache-path
+ name="cache"
+ path="." />
</paths>
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesDataStore.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesDataStore.kt
index a04512e714..61e09bcfd0 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesDataStore.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesDataStore.kt
@@ -10,6 +10,7 @@ import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import io.ente.ensu.domain.preferences.SessionPreferences
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
+import org.json.JSONObject
class SessionPreferencesDataStore(context: Context) : SessionPreferences {
private val dataStore: DataStore<Preferences> = PreferenceDataStoreFactory.create {
@@ -20,6 +21,10 @@ class SessionPreferencesDataStore(context: Context) : SessionPreferences {
preferences[Keys.SELECTED_SESSION_ID]
}
+ override val sessionSummaries: Flow<Map<String, String>> = dataStore.data.map { preferences ->
+ decodeSessionSummaries(preferences[Keys.SESSION_SUMMARIES])
+ }
+
override suspend fun setSelectedSessionId(sessionId: String?) {
dataStore.edit { preferences ->
if (sessionId == null) {
@@ -30,7 +35,45 @@ class SessionPreferencesDataStore(context: Context) : SessionPreferences {
}
}
+ override suspend fun setSessionSummary(sessionId: String, summary: String?) {
+ dataStore.edit { preferences ->
+ val summaries = decodeSessionSummaries(preferences[Keys.SESSION_SUMMARIES]).toMutableMap()
+ if (summary.isNullOrBlank()) {
+ summaries.remove(sessionId)
+ } else {
+ summaries[sessionId] = summary
+ }
+ preferences[Keys.SESSION_SUMMARIES] = encodeSessionSummaries(summaries)
+ }
+ }
+
+ private fun decodeSessionSummaries(raw: String?): Map<String, String> {
+ if (raw.isNullOrBlank()) return emptyMap()
+ return runCatching {
+ val json = JSONObject(raw)
+ val map = mutableMapOf<String, String>()
+ val keys = json.keys()
+ while (keys.hasNext()) {
+ val key = keys.next()
+ val value = json.optString(key)
+ if (value.isNotBlank()) {
+ map[key] = value
+ }
+ }
+ map
+ }.getOrDefault(emptyMap())
+ }
+
+ private fun encodeSessionSummaries(summaries: Map<String, String>): String {
+ val json = JSONObject()
+ summaries.forEach { (key, value) ->
+ json.put(key, value)
+ }
+ return json.toString()
+ }
+
private object Keys {
val SELECTED_SESSION_ID = stringPreferencesKey("selected_session_id")
+ val SESSION_SUMMARIES = stringPreferencesKey("session_summaries")
}
}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesExt.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesExt.kt
index d869823198..ff7340120b 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesExt.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/SessionPreferencesExt.kt
@@ -11,3 +11,7 @@ import kotlinx.coroutines.runBlocking
fun SessionPreferences.getSelectedSessionIdSync(): String? = runBlocking {
selectedSessionId.first()
}
+
+fun SessionPreferences.getSessionSummariesSync(): Map<String, String> = runBlocking {
+ sessionSummaries.first()
+}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt
index a4d0e4f73d..4edc52ec2c 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/auth/EnsuAuthService.kt
@@ -53,7 +53,9 @@ class EnsuAuthService(
logRepository.log(
LogLevel.Error,
"Crypto init failed",
- error.message ?: "Unknown error"
+ details = error.message,
+ tag = "Auth",
+ throwable = error
)
}
.getOrThrow()
@@ -90,10 +92,16 @@ class EnsuAuthService(
pingEndpoint(url)
endpointPreferences.setEndpoint(normalized)
updateEndpointUrl(url)
- logRepository.log(LogLevel.Info, "Updated endpoint", normalized)
+ logRepository.log(LogLevel.Info, "Updated endpoint", details = normalized, tag = "Auth")
Result.success(normalized)
} catch (error: Exception) {
- logRepository.log(LogLevel.Error, "Endpoint update failed", error.message ?: "Unknown error")
+ logRepository.log(
+ LogLevel.Error,
+ "Endpoint update failed",
+ details = error.message,
+ tag = "Auth",
+ throwable = error
+ )
Result.failure(error)
}
}
@@ -137,7 +145,7 @@ class EnsuAuthService(
suspend fun loginWithSrp(email: String, password: String, srpAttributes: SrpAttributes): SrpLoginResult {
try {
- logRepository.log(LogLevel.Info, "SRP login started")
+ logRepository.log(LogLevel.Info, "SRP login started", tag = "Auth")
val start = withContext(Dispatchers.Default) {
EnsuCryptoBridge.srpStart(password, srpAttributes.toCrypto())
}
@@ -179,7 +187,7 @@ class EnsuAuthService(
}
storeSecrets(email, payload.userId, secrets)
- logRepository.log(LogLevel.Info, "SRP login success")
+ logRepository.log(LogLevel.Info, "SRP login success", tag = "Auth")
return SrpLoginResult(null, null, null)
} finally {
EnsuCryptoBridge.srpClear()
@@ -219,7 +227,7 @@ class EnsuAuthService(
}
storeSecrets(email, userId, secrets)
- logRepository.log(LogLevel.Info, "Login after challenge success")
+ logRepository.log(LogLevel.Info, "Login after challenge success", tag = "Auth")
}
fun clearCredentials() {
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt
index e026828b03..d0822f134d 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/chat/RustChatRepository.kt
@@ -8,6 +8,7 @@ import io.ente.ensu.domain.model.AttachmentType
import io.ente.ensu.domain.model.ChatMessage
import io.ente.ensu.domain.model.ChatSession
import io.ente.ensu.domain.model.MessageAuthor
+import io.ente.ensu.domain.model.sessionTitleFromText
import io.ente.labs.llmchat_db.AttachmentKind
import io.ente.labs.llmchat_db.AttachmentMeta
import io.ente.labs.llmchat_db.DbException
@@ -34,10 +35,12 @@ class RustChatRepository(
override fun listSessions(): List<ChatSession> = withDbRecovery {
val sessions = db.listSessions()
sessions.map { session ->
- val lastMessage = runCatching { db.getMessages(session.uuid) }.getOrNull()?.lastOrNull()?.text
+ val messages = runCatching { db.getMessages(session.uuid) }.getOrNull().orEmpty()
+ val firstMessage = messages.firstOrNull()?.text.orEmpty()
+ val lastMessage = messages.lastOrNull()?.text
ChatSession(
id = session.uuid,
- title = session.title,
+ title = sessionTitleFromText(firstMessage, fallback = session.title),
lastMessagePreview = lastMessage,
updatedAtMillis = session.updatedAtUs / 1000
)
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt
index ce3026af55..a4069664b8 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/llm/InferenceRsProvider.kt
@@ -131,7 +131,7 @@ class InferenceRsProvider(
val request = GenerateChatRequest(
messages = messages.map { msg ->
- io.ente.labs.inference_rs.ChatMessage(msg.isUserRole(), msg.text)
+ io.ente.labs.inference_rs.ChatMessage(msg.roleString(), msg.text)
},
templateOverride = null,
addAssistant = true,
@@ -154,6 +154,36 @@ class InferenceRsProvider(
GenerationSummary(summary.jobId, summary.generatedTokens ?: 0, summary.totalTimeMs)
}
+ override fun isModelDownloaded(target: LlmModelTarget): Boolean {
+ val modelFile = modelPathFor(target)
+ if (!modelFile.exists()) return false
+ val mmprojFile = mmprojPathFor(target)
+ if (mmprojFile != null && !mmprojFile.exists()) return false
+ return true
+ }
+
+ override suspend fun estimateModelDownloadSize(target: LlmModelTarget): Long? = withContext(ioDispatcher) {
+ val modelFile = modelPathFor(target)
+ val mmprojFile = mmprojPathFor(target)
+ val mmprojUrl = target.mmprojUrl
+ val modelSize = if (modelFile.exists()) {
+ modelFile.length().takeIf { it > 0 }
+ } else {
+ fetchContentLength(target.url)
+ }
+ val mmprojSize = if (mmprojFile != null && !mmprojUrl.isNullOrBlank()) {
+ if (mmprojFile.exists()) {
+ mmprojFile.length().takeIf { it > 0 }
+ } else {
+ fetchContentLength(mmprojUrl)
+ }
+ } else {
+ null
+ }
+ val sizes = listOfNotNull(modelSize, mmprojSize)
+ if (sizes.isEmpty()) null else sizes.sum()
+ }
+
override fun stopGeneration() {
currentJobId?.let { cancel(it) }
}
@@ -174,8 +204,12 @@ class InferenceRsProvider(
downloadCall?.cancel()
}
- private fun LlmMessage.isUserRole(): String {
- return if (isUser) "user" else "assistant"
+ private fun LlmMessage.roleString(): String {
+ return when (role) {
+ io.ente.ensu.domain.llm.LlmMessageRole.User -> "user"
+ io.ente.ensu.domain.llm.LlmMessageRole.Assistant -> "assistant"
+ io.ente.ensu.domain.llm.LlmMessageRole.System -> "system"
+ }
}
private fun unloadModel() {
@@ -227,48 +261,88 @@ class InferenceRsProvider(
onProgress: (Long, Long?) -> Unit
) {
val tmp = File(dest.absolutePath + ".tmp")
- if (tmp.exists()) tmp.delete()
+ var existing = if (tmp.exists()) tmp.length() else 0L
+ if (existing > 0 && !looksLikeGguf(tmp)) {
+ tmp.delete()
+ existing = 0L
+ }
- val request = Request.Builder().url(url).build()
- val call = httpClient.newCall(request)
- downloadCall = call
+ while (true) {
+ val requestBuilder = Request.Builder().url(url)
+ if (existing > 0) {
+ requestBuilder.header("Range", "bytes=$existing-")
+ }
+ val call = httpClient.newCall(requestBuilder.build())
+ downloadCall = call
- val response = call.execute()
- if (!response.isSuccessful) {
- response.close()
- throw IOException("Download failed: HTTP ${response.code}")
- }
+ val response = call.execute()
+ if (!response.isSuccessful) {
+ response.close()
+ throw IOException("Download failed: HTTP ${response.code}")
+ }
+
+ if (existing > 0 && response.code == 200) {
+ response.close()
+ tmp.delete()
+ existing = 0L
+ continue
+ }
- val body = response.body ?: throw IOException("Empty response body")
- val totalBytes = body.contentLength().takeIf { it > 0 }
- var downloaded = 0L
-
- FileOutputStream(tmp).use { out ->
- body.byteStream().use { input ->
- val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
- while (true) {
- if (downloadCancelled.get()) {
- call.cancel()
- response.close()
- tmp.delete()
- throw IOException("Download cancelled")
+ val body = response.body ?: throw IOException("Empty response body")
+ val totalBytes = resolveTotalBytes(response, existing, body.contentLength())
+ if (totalBytes != null && totalBytes <= existing) {
+ response.close()
+ tmp.delete()
+ existing = 0L
+ continue
+ }
+
+ val append = existing > 0 && response.code == 206
+ var downloaded = existing
+
+ FileOutputStream(tmp, append).use { out ->
+ body.byteStream().use { input ->
+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
+ while (true) {
+ if (downloadCancelled.get()) {
+ call.cancel()
+ response.close()
+ tmp.delete()
+ throw IOException("Download cancelled")
+ }
+ val read = input.read(buffer)
+ if (read == -1) break
+ out.write(buffer, 0, read)
+ downloaded += read
+ onProgress(downloaded, totalBytes)
}
- val read = input.read(buffer)
- if (read == -1) break
- out.write(buffer, 0, read)
- downloaded += read
- onProgress(downloaded, totalBytes)
}
}
+ response.close()
+
+ if (totalBytes != null && downloaded < totalBytes) {
+ tmp.delete()
+ throw IOException("Download incomplete")
+ }
+
+ if (!looksLikeGguf(tmp)) {
+ tmp.delete()
+ throw IOException("Downloaded file is not GGUF")
+ }
+ if (dest.exists()) dest.delete()
+ tmp.renameTo(dest)
+ return
}
- response.close()
+ }
- if (!looksLikeGguf(tmp)) {
- tmp.delete()
- throw IOException("Downloaded file is not GGUF")
+ private fun resolveTotalBytes(response: okhttp3.Response, existing: Long, remainingLength: Long): Long? {
+ val contentLength = remainingLength.takeIf { it > 0 }
+ if (existing > 0 && response.code == 206) {
+ val contentRange = response.header("Content-Range")
+ val totalFromRange = contentRange?.substringAfter('/')?.toLongOrNull()
+ return totalFromRange ?: contentLength?.let { existing + it }
}
- if (dest.exists()) dest.delete()
- tmp.renameTo(dest)
+ return contentLength
}
private fun fetchContentLength(url: String): Long? {
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.kt
new file mode 100644
index 0000000000..150f7e227d
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/FileLogRepository.kt
@@ -0,0 +1,273 @@
+package io.ente.ensu.data.logging
+
+import android.content.Context
+import android.util.Log
+import io.ente.ensu.domain.logging.LogRepository
+import io.ente.ensu.domain.model.LogEntry
+import io.ente.ensu.domain.model.LogLevel
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import java.io.BufferedInputStream
+import java.io.BufferedOutputStream
+import java.io.File
+import java.io.FileInputStream
+import java.io.FileOutputStream
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.UUID
+import java.util.zip.ZipEntry
+import java.util.zip.ZipOutputStream
+
+class FileLogRepository(
+ private val context: Context,
+ private val maxLogFiles: Int = 5,
+ private val maxEntriesInMemory: Int = 500
+) : LogRepository {
+
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val writeMutex = Mutex()
+
+ private val dateFormatter = SimpleDateFormat("yyyy-MM-dd", Locale.US)
+ private val lineTimestampFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US)
+
+ private val logsDir: File = File(context.filesDir, "logs")
+
+ private val _logs = MutableStateFlow<List<LogEntry>>(emptyList())
+ override val logs: StateFlow<List<LogEntry>> = _logs.asStateFlow()
+
+ init {
+ ensureLogDir()
+ pruneOldLogFiles()
+ }
+
+ override fun log(level: LogLevel, message: String, details: String?, tag: String?, throwable: Throwable?) {
+ val resolvedTag = tag ?: "ensu"
+ val combinedDetails = buildString {
+ if (!details.isNullOrBlank()) {
+ append(details)
+ }
+ if (throwable != null) {
+ if (isNotEmpty()) append("\n")
+ append(throwable.stackTraceToString())
+ }
+ }.ifBlank { null }
+
+ val safeMessage = LogSanitizer.sanitize(message).orEmpty()
+ val safeDetails = LogSanitizer.sanitize(combinedDetails)
+
+ val entry = LogEntry(
+ id = UUID.randomUUID().toString(),
+ timestampMillis = System.currentTimeMillis(),
+ level = level,
+ tag = resolvedTag,
+ message = safeMessage,
+ details = safeDetails
+ )
+
+ _logs.update { (listOf(entry) + it).take(maxEntriesInMemory) }
+
+ // Also mirror to Logcat.
+ when (level) {
+ LogLevel.Info -> Log.i(resolvedTag, safeMessage)
+ LogLevel.Warning -> Log.w(resolvedTag, safeMessage)
+ LogLevel.Error -> {
+ if (throwable != null) {
+ Log.e(resolvedTag, safeMessage, throwable)
+ } else {
+ Log.e(resolvedTag, safeMessage)
+ }
+ }
+ }
+
+ val line = formatLine(entry)
+ ioScope.launch {
+ writeMutex.withLock {
+ val file = todayLogFile()
+ file.parentFile?.mkdirs()
+ file.appendText(line)
+ }
+ }
+ }
+
+ fun logDirectory(): File = logsDir
+
+ fun listLogFiles(): List<File> {
+ ensureLogDir()
+ return logsDir.listFiles()
+ ?.filter { it.isFile && it.name.endsWith(".txt") }
+ ?.sortedBy { it.name }
+ .orEmpty()
+ }
+
+ suspend fun readLogText(file: File): String = withContext(Dispatchers.IO) {
+ writeMutex.withLock {
+ if (!file.exists()) return@withLock ""
+ runCatching { file.readText() }.getOrDefault("")
+ }
+ }
+
+ fun todayLogFile(): File {
+ val name = "${dateFormatter.format(Date())}.txt"
+ return File(logsDir, name)
+ }
+
+ suspend fun readTodayLogText(): String = withContext(Dispatchers.IO) {
+ writeMutex.withLock {
+ val file = todayLogFile()
+ if (!file.exists()) return@withLock ""
+ runCatching { file.readText() }.getOrDefault("")
+ }
+ }
+
+ suspend fun readTodayEntries(): List<LogEntry> = withContext(Dispatchers.IO) {
+ parseLogEntries(readTodayLogText()).reversed()
+ }
+
+ suspend fun createLogsZip(outputDir: File = context.cacheDir): File = withContext(Dispatchers.IO) {
+ ensureLogDir()
+ pruneOldLogFiles()
+
+ val now = Date()
+ val out = File(outputDir, "ensu-logs-${dateFormatter.format(now)}-${System.currentTimeMillis()}.zip")
+ if (out.exists()) out.delete()
+
+ ZipOutputStream(BufferedOutputStream(FileOutputStream(out))).use { zipOut ->
+ logsDir.listFiles()?.sortedBy { it.name }?.forEach { file ->
+ if (!file.isFile) return@forEach
+ val entry = ZipEntry(file.name)
+ zipOut.putNextEntry(entry)
+ BufferedInputStream(FileInputStream(file)).use { input ->
+ input.copyTo(zipOut)
+ }
+ zipOut.closeEntry()
+ }
+ }
+ out
+ }
+
+ private fun ensureLogDir() {
+ if (!logsDir.exists()) {
+ logsDir.mkdirs()
+ }
+ }
+
+ private fun pruneOldLogFiles() {
+ val files = logsDir.listFiles()?.toList().orEmpty()
+ .filter { it.isFile && it.name.endsWith(".txt") }
+ .mapNotNull { file ->
+ val name = file.name.removeSuffix(".txt")
+ val date = runCatching { dateFormatter.parse(name) }.getOrNull() ?: return@mapNotNull null
+ file to date.time
+ }
+ .sortedBy { it.second }
+ .map { it.first }
+
+ if (files.size <= maxLogFiles) return
+ val toDelete = files.take(files.size - maxLogFiles)
+ toDelete.forEach { runCatching { it.delete() } }
+ }
+
+ private fun formatLine(entry: LogEntry): String {
+ val timestamp = lineTimestampFormatter.format(Date(entry.timestampMillis))
+ val header = "[${entry.tag}][${entry.level.name.uppercase()}] [$timestamp]"
+ var out = "$header ${entry.message}".trimEnd() + "\n"
+
+ entry.details?.takeIf { it.isNotBlank() }?.let { details ->
+ details.lines().forEach { line ->
+ out += "$header ⤷ $line\n"
+ }
+ }
+ return out
+ }
+
+ private fun parseLogEntries(text: String): List<LogEntry> {
+ if (text.isBlank()) return emptyList()
+
+ val entries = mutableListOf<LogEntry>()
+ var current: LogEntry? = null
+ var details = mutableListOf<String>()
+
+ text.lineSequence().forEach { line ->
+ val trimmed = line.trimEnd()
+ if (trimmed.isBlank()) return@forEach
+
+ val match = logLineRegex.matchEntire(trimmed)
+ if (match == null) {
+ if (current != null) {
+ details.add(trimmed)
+ } else {
+ entries.add(
+ LogEntry(
+ id = UUID.randomUUID().toString(),
+ timestampMillis = System.currentTimeMillis(),
+ level = LogLevel.Info,
+ tag = "Log",
+ message = trimmed,
+ details = null
+ )
+ )
+ }
+ return@forEach
+ }
+
+ val tag = match.groupValues[1]
+ val levelValue = match.groupValues[2]
+ val timestampValue = match.groupValues[3]
+ val message = match.groupValues[4]
+
+ val isDetail = message.trimStart().startsWith("⤷")
+ if (isDetail && current != null) {
+ details.add(message.replaceFirst("⤷", "").trim())
+ return@forEach
+ }
+
+ current?.let {
+ val detailText = details.takeIf { it.isNotEmpty() }?.joinToString("\n")
+ entries.add(it.copy(details = detailText))
+ }
+
+ val level = parseLevel(levelValue) ?: LogLevel.Info
+ val timestamp = runCatching {
+ lineTimestampFormatter.parse(timestampValue)?.time
+ }.getOrNull() ?: System.currentTimeMillis()
+
+ current = LogEntry(
+ id = UUID.randomUUID().toString(),
+ timestampMillis = timestamp,
+ level = level,
+ tag = tag,
+ message = message,
+ details = null
+ )
+ details = mutableListOf()
+ }
+
+ current?.let {
+ val detailText = details.takeIf { it.isNotEmpty() }?.joinToString("\n")
+ entries.add(it.copy(details = detailText))
+ }
+
+ return entries
+ }
+
+ private fun parseLevel(value: String): LogLevel? = when (value.uppercase()) {
+ "INFO" -> LogLevel.Info
+ "WARNING", "WARN" -> LogLevel.Warning
+ "ERROR" -> LogLevel.Error
+ else -> null
+ }
+
+ companion object {
+ private val logLineRegex = Regex("\\[(.+?)]\\[(.+?)] \\[(.+?)]\\] (.*)")
+ }
+}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/InMemoryLogRepository.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/InMemoryLogRepository.kt
index cd03a26514..15bfc29250 100644
--- a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/InMemoryLogRepository.kt
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/InMemoryLogRepository.kt
@@ -13,14 +13,28 @@ class InMemoryLogRepository : LogRepository {
private val _logs = MutableStateFlow<List<LogEntry>>(emptyList())
override val logs: StateFlow<List<LogEntry>> = _logs.asStateFlow()
- override fun log(level: LogLevel, message: String, details: String?) {
+ override fun log(level: LogLevel, message: String, details: String?, tag: String?, throwable: Throwable?) {
+ val combinedDetails = buildString {
+ if (!details.isNullOrBlank()) {
+ append(details)
+ }
+ if (throwable != null) {
+ if (isNotEmpty()) append("\n")
+ append(throwable.stackTraceToString())
+ }
+ }.ifBlank { null }
+
+ val safeMessage = LogSanitizer.sanitize(message).orEmpty()
+ val safeDetails = LogSanitizer.sanitize(combinedDetails)
+
val entry = LogEntry(
id = UUID.randomUUID().toString(),
timestampMillis = System.currentTimeMillis(),
level = level,
- message = message,
- details = details
+ tag = tag,
+ message = safeMessage,
+ details = safeDetails
)
- _logs.update { listOf(entry) + it }
+ _logs.update { (listOf(entry) + it).take(500) }
}
}
diff --git a/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/LogSanitizer.kt b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/LogSanitizer.kt
new file mode 100644
index 0000000000..17890990a2
--- /dev/null
+++ b/mobile/native/android/apps/ensu/data/src/main/java/io/ente/ensu/data/logging/LogSanitizer.kt
@@ -0,0 +1,36 @@
+package io.ente.ensu.data.logging
+
+object LogSanitizer {
+ private val emailRegex = Regex("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}")
+ private val bearerRegex = Regex("(?i)bearer\\s+[A-Za-z0-9._-]+")
+
+ // key=value style secrets
+ private val keyValueSecretRegex = Regex(
+ "(?i)(token|authToken|accessToken|refreshToken|authorization|password|otp|secret|secretKey|masterKey|encryptedToken|srpA|srpB|srpM1|srpM2|kek)\\s*[:=]\\s*([^\\s,;]+)"
+ )
+
+ // query params in URLs
+ private val querySecretRegex = Regex("(?i)(token|key|sig|signature|auth|session|passkey|otp)=([^&\\s]+)")
+
+ // Very long base64-ish blobs
+ private val longBlobRegex = Regex("[A-Za-z0-9+/=]{40,}")
+
+ fun sanitize(input: String?): String? {
+ if (input.isNullOrBlank()) return input
+ var out = input
+
+ out = bearerRegex.replace(out) { "Bearer <redacted>" }
+ out = keyValueSecretRegex.replace(out) { match ->
+ val key = match.groups[1]?.value ?: "secret"
+ "$key=<redacted>"
+ }
+ out = querySecretRegex.replace(out) { match ->
+ val key = match.groups[1]?.value ?: "param"
+ "$key=<redacted>"
+ }
+ out = emailRegex.replace(out) { "<redacted-email>" }
+ out = longBlobRegex.replace(out) { "<redacted-blob>" }
+
+ return out
+ }
+}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt
index a80c09980c..c23b54343f 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/llm/LlmProvider.kt
@@ -16,9 +16,15 @@ data class DownloadProgress(
val status: String
)
+enum class LlmMessageRole {
+ User,
+ Assistant,
+ System
+}
+
data class LlmMessage(
val text: String,
- val isUser: Boolean,
+ val role: LlmMessageRole,
val hasAttachments: Boolean = false
)
@@ -43,6 +49,9 @@ interface LlmProvider {
onToken: (String) -> Unit
): GenerationSummary
+ fun isModelDownloaded(target: LlmModelTarget): Boolean
+ suspend fun estimateModelDownloadSize(target: LlmModelTarget): Long?
+
fun stopGeneration()
fun resetContext()
fun cancelDownload()
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/logging/LogRepository.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/logging/LogRepository.kt
index eee9b7da9e..dd47c4f1c7 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/logging/LogRepository.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/logging/LogRepository.kt
@@ -7,12 +7,18 @@ import kotlinx.coroutines.flow.StateFlow
interface LogRepository {
val logs: StateFlow<List<LogEntry>>
- fun log(level: LogLevel, message: String, details: String? = null)
+ fun log(
+ level: LogLevel,
+ message: String,
+ details: String? = null,
+ tag: String? = null,
+ throwable: Throwable? = null
+ )
}
object NoOpLogRepository : LogRepository {
private val emptyFlow = MutableStateFlow<List<LogEntry>>(emptyList())
override val logs: StateFlow<List<LogEntry>> = emptyFlow
- override fun log(level: LogLevel, message: String, details: String?) = Unit
+ override fun log(level: LogLevel, message: String, details: String?, tag: String?, throwable: Throwable?) = Unit
}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/ChatModels.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/ChatModels.kt
index aba8370946..c854bbb99f 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/ChatModels.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/ChatModels.kt
@@ -40,3 +40,15 @@ data class Attachment(
val localPath: String? = null,
val isUploading: Boolean = false
)
+
+const val SessionTitleMaxLength = 50
+
+fun sessionTitleFromText(text: String, fallback: String = "New Chat"): String {
+ val trimmed = text.trim()
+ if (trimmed.isBlank()) return fallback
+ return if (trimmed.length <= SessionTitleMaxLength) {
+ trimmed
+ } else {
+ trimmed.take(SessionTitleMaxLength).trimEnd() + "…"
+ }
+}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/LogEntry.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/LogEntry.kt
index 2af7e959c6..87f3d37df0 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/LogEntry.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/model/LogEntry.kt
@@ -4,6 +4,7 @@ data class LogEntry(
val id: String,
val timestampMillis: Long,
val level: LogLevel,
+ val tag: String? = null,
val message: String,
val details: String? = null
)
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.kt
index 9d628e09ac..1c8a6c3e57 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/preferences/SessionPreferences.kt
@@ -4,5 +4,7 @@ import kotlinx.coroutines.flow.Flow
interface SessionPreferences {
val selectedSessionId: Flow<String?>
+ val sessionSummaries: Flow<Map<String, String>>
suspend fun setSelectedSessionId(sessionId: String?)
+ suspend fun setSessionSummary(sessionId: String, summary: String?)
}
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt
index 0bcf4e2d7b..22c165d621 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ChatState.kt
@@ -24,5 +24,8 @@ data class ChatState(
val attachmentDownloadProgress: Int? = null,
val isAttachmentDownloadBlocked: Boolean = false,
val transientAssistantError: String? = null,
- val transientAssistantParentId: String? = null
+ val transientAssistantParentId: String? = null,
+ val isModelDownloaded: Boolean = false,
+ val modelDownloadSizeBytes: Long? = null,
+ val hasRequestedModelDownload: Boolean = false
)
diff --git a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ModelSettingsState.kt b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ModelSettingsState.kt
index fdbe117fcd..331777e7d3 100644
--- a/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ModelSettingsState.kt
+++ b/mobile/native/android/apps/ensu/domain/src/main/kotlin/io/ente/ensu/domain/state/ModelSettingsState.kt
@@ -6,5 +6,6 @@ data class ModelSettingsState(
val mmprojUrl: String = "",
val contextLength: String = "",
val maxTokens: String = "",
+ val temperature: String = "",
val isSaving: Boolean = false
)
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 6c76f866a2..208787342f 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
@@ -2,6 +2,7 @@ package io.ente.ensu.domain.store
import io.ente.ensu.domain.chat.ChatSyncRepository
import io.ente.ensu.domain.llm.LlmMessage
+import io.ente.ensu.domain.llm.LlmMessageRole
import io.ente.ensu.domain.llm.LlmModelTarget
import io.ente.ensu.domain.llm.LlmProvider
import io.ente.ensu.domain.model.Attachment
@@ -13,6 +14,7 @@ import io.ente.ensu.domain.model.ChatMessage
import io.ente.ensu.domain.model.ChatSession
import io.ente.ensu.domain.model.LogLevel
import io.ente.ensu.domain.model.MessageAuthor
+import io.ente.ensu.domain.model.sessionTitleFromText
import io.ente.ensu.domain.preferences.SessionPreferences
import io.ente.ensu.domain.state.AppState
import io.ente.ensu.domain.state.ModelSettingsState
@@ -27,6 +29,7 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
@@ -47,10 +50,14 @@ class AppStore(
private val messageStore = mutableMapOf<String, MutableList<ChatMessage>>()
private val branchSelections = mutableMapOf<String, MutableMap<String, String>>()
+ private val sessionSummaries = mutableMapOf<String, String>()
private var scope: CoroutineScope? = null
private var generationJob: Job? = null
+ private var modelDownloadJob: Job? = null
+ private var sessionSummaryJob: Job? = null
private var stopRequested = false
private var streamingParentId: String? = null
+ private var activeGenerationToken = 0L
private var pendingSyncRequested = false
private var pendingSyncErrorHandler: ((String) -> Unit)? = null
@@ -61,24 +68,44 @@ class AppStore(
fun bootstrap(scope: CoroutineScope) {
this.scope = scope
- logRepository.log(LogLevel.Info, "Ensū started")
+
+ sessionSummaries.clear()
+ sessionSummaries.putAll(runBlocking { sessionPreferences.sessionSummaries.first() })
if (_state.value.chat.sessions.isEmpty()) {
loadSessionsFromDb()
}
+ refreshModelDownloadInfo()
+
scope.launch {
- sessionPreferences.selectedSessionId.collectLatest { storedId ->
- if (storedId != null) {
- _state.update { appState ->
- if (appState.chat.sessions.any { it.id == storedId }) {
- appState.copy(chat = appState.chat.copy(currentSessionId = storedId))
- } else {
- appState
- }
- }
- loadMessagesFromDb(storedId)
- rebuildChatState(storedId)
+ sessionPreferences.sessionSummaries.collectLatest { summaries ->
+ sessionSummaries.clear()
+ sessionSummaries.putAll(summaries)
+ applySessionSummariesToState()
+ }
+ }
+
+ }
+
+ private fun refreshModelDownloadInfo() {
+ val target = resolveTarget(_state.value.modelSettings)
+ val isDownloaded = llmProvider.isModelDownloaded(target)
+ _state.update { appState ->
+ appState.copy(
+ chat = appState.chat.copy(
+ isModelDownloaded = isDownloaded,
+ modelDownloadSizeBytes = if (isDownloaded) null else appState.chat.modelDownloadSizeBytes
+ )
+ )
+ }
+
+ if (!isDownloaded) {
+ val scope = scope ?: return
+ scope.launch {
+ val size = llmProvider.estimateModelDownloadSize(target)
+ _state.update { appState ->
+ appState.copy(chat = appState.chat.copy(modelDownloadSizeBytes = size))
}
}
}
@@ -87,6 +114,7 @@ class AppStore(
fun createNewSession(): String {
generationJob?.cancel()
llmProvider.stopGeneration()
+ invalidateGenerationToken()
streamingParentId = null
_state.update { appState ->
appState.copy(
@@ -120,13 +148,14 @@ class AppStore(
// Session is empty, no DB load needed.
rebuildChatState(session.id)
updateAttachmentDownloadState()
- logRepository.log(LogLevel.Info, "Created new session")
+ logRepository.log(LogLevel.Info, "Session created", tag = "Chat")
return session.id
}
fun startNewSessionDraft() {
generationJob?.cancel()
llmProvider.stopGeneration()
+ invalidateGenerationToken()
streamingParentId = null
_state.update { appState ->
appState.copy(
@@ -147,12 +176,12 @@ class AppStore(
)
}
updateAttachmentDownloadState()
- logRepository.log(LogLevel.Info, "Started new session draft")
}
fun selectSession(sessionId: String) {
generationJob?.cancel()
llmProvider.stopGeneration()
+ invalidateGenerationToken()
streamingParentId = null
_state.update { appState ->
appState.copy(
@@ -170,7 +199,6 @@ class AppStore(
loadMessagesFromDb(sessionId)
rebuildChatState(sessionId)
ensureAttachmentsAvailable(sessionId)
- logRepository.log(LogLevel.Info, "Selected session", sessionId)
}
fun deleteSession(sessionId: String) {
@@ -180,6 +208,7 @@ class AppStore(
if (isCurrent) {
generationJob?.cancel()
llmProvider.stopGeneration()
+ invalidateGenerationToken()
streamingParentId = null
}
@@ -187,6 +216,8 @@ class AppStore(
messageStore.remove(sessionId)
branchSelections.remove(sessionId)
purgeAttachmentDownloads(sessionId)
+ sessionSummaries.remove(sessionId)
+ scope?.launch { sessionPreferences.setSessionSummary(sessionId, null) }
val remaining = currentState.chat.sessions.filterNot { it.id == sessionId }
val sessions = remaining
@@ -234,7 +265,7 @@ class AppStore(
scope?.launch { sessionPreferences.setSelectedSessionId(newCurrent) }
syncNow()
- logRepository.log(LogLevel.Info, "Deleted session", sessionId)
+ logRepository.log(LogLevel.Info, "Session deleted", tag = "Chat")
}
fun persistSelectedSession(scope: CoroutineScope, sessionId: String?) {
@@ -325,9 +356,111 @@ class AppStore(
llmProvider.stopGeneration()
}
+ fun startModelDownload(userInitiated: Boolean = true) {
+ val scope = scope ?: return
+ val currentState = _state.value
+ if (currentState.chat.isDownloading || currentState.chat.isGenerating) return
+
+ val target = resolveTarget(currentState.modelSettings)
+ val isDownloaded = llmProvider.isModelDownloaded(target)
+ if (isDownloaded) {
+ _state.update { appState ->
+ appState.copy(
+ chat = appState.chat.copy(
+ isModelDownloaded = true,
+ modelDownloadSizeBytes = null,
+ hasRequestedModelDownload = if (userInitiated) true else appState.chat.hasRequestedModelDownload
+ )
+ )
+ }
+ }
+
+ modelDownloadJob?.cancel()
+ if (!isDownloaded) {
+ logRepository.log(
+ LogLevel.Info,
+ "Model download started",
+ details = "model=${target.id}",
+ tag = "Model"
+ )
+ _state.update { appState ->
+ appState.copy(
+ chat = appState.chat.copy(
+ isDownloading = true,
+ downloadPercent = 0,
+ downloadStatus = "Starting download...",
+ hasRequestedModelDownload = if (userInitiated) true else appState.chat.hasRequestedModelDownload
+ )
+ )
+ }
+ }
+
+ modelDownloadJob = scope.launch {
+ var loggedComplete = false
+ try {
+ llmProvider.ensureModelReady(target) { progress ->
+ val downloading = (progress.percent in 0..99) || progress.status.contains("Loading", ignoreCase = true)
+ val finished = progress.status.contains("Ready", ignoreCase = true)
+ if (!isDownloaded && finished && !loggedComplete) {
+ loggedComplete = true
+ logRepository.log(
+ LogLevel.Info,
+ "Model download complete",
+ details = "model=${target.id}",
+ tag = "Model"
+ )
+ }
+ _state.update { appState ->
+ appState.copy(
+ chat = appState.chat.copy(
+ isDownloading = downloading && !finished,
+ downloadPercent = progress.percent.takeIf { it >= 0 },
+ downloadStatus = progress.status,
+ isModelDownloaded = if (finished) true else appState.chat.isModelDownloaded,
+ modelDownloadSizeBytes = if (finished) null else appState.chat.modelDownloadSizeBytes
+ )
+ )
+ }
+ }
+ } catch (err: Throwable) {
+ val cancelled = err is kotlinx.coroutines.CancellationException ||
+ err.message?.contains("cancel", ignoreCase = true) == true
+ _state.update { appState ->
+ appState.copy(
+ chat = appState.chat.copy(
+ isDownloading = false,
+ downloadPercent = null,
+ downloadStatus = if (cancelled) "Download cancelled" else "Download failed",
+ hasRequestedModelDownload = if (cancelled) false else appState.chat.hasRequestedModelDownload
+ )
+ )
+ }
+ if (cancelled) {
+ if (!isDownloaded) {
+ logRepository.log(LogLevel.Info, "Model download cancelled", tag = "Model")
+ }
+ } else {
+ logRepository.log(
+ LogLevel.Error,
+ if (isDownloaded) "Model load failed" else "Model download failed",
+ details = err.message,
+ tag = "Model",
+ throwable = err
+ )
+ }
+ } finally {
+ modelDownloadJob = null
+ refreshModelDownloadInfo()
+ }
+ }
+ }
+
fun cancelDownload() {
generationJob?.cancel()
+ modelDownloadJob?.cancel()
+ modelDownloadJob = null
llmProvider.cancelDownload()
+ invalidateGenerationToken()
streamingParentId = null
_state.update { appState ->
appState.copy(
@@ -337,10 +470,12 @@ class AppStore(
streamingResponse = "",
streamingParentId = null,
downloadPercent = null,
- downloadStatus = "Download cancelled"
+ downloadStatus = "Download cancelled",
+ hasRequestedModelDownload = false
)
)
}
+ refreshModelDownloadInfo()
}
fun retryAssistantMessage(messageId: String) {
@@ -406,26 +541,34 @@ class AppStore(
rebuildChatState(sessionId)
startGeneration(sessionId, userMessage)
requestSync()
- logRepository.log(LogLevel.Info, "Sent message", text)
+ logRepository.log(
+ LogLevel.Info,
+ "Message sent",
+ details = "len=${text.length} attachments=${attachments.size} edited=${editingMessageId != null}",
+ tag = "Chat"
+ )
}
fun updateModelSettings(state: ModelSettingsState) {
_state.update { appState ->
appState.copy(modelSettings = state)
}
+ refreshModelDownloadInfo()
}
fun resetModelSettings() {
_state.update { appState ->
appState.copy(modelSettings = ModelSettingsState())
}
+ refreshModelDownloadInfo()
}
fun signIn(email: String) {
_state.update { appState ->
appState.copy(auth = AuthState(isLoggedIn = true, email = email))
}
- logRepository.log(LogLevel.Info, "Signed in", email)
+ // Do not log PII like user email.
+ logRepository.log(LogLevel.Info, "Signed in", tag = "Auth")
syncNow()
}
@@ -433,7 +576,7 @@ class AppStore(
_state.update { appState ->
appState.copy(auth = AuthState())
}
- logRepository.log(LogLevel.Info, "Signed out")
+ logRepository.log(LogLevel.Info, "Signed out", tag = "Auth")
}
fun syncNow(onError: ((String) -> Unit)? = null) {
@@ -476,13 +619,21 @@ class AppStore(
val scope = scope ?: return
scope.launch {
try {
+ logRepository.log(LogLevel.Info, "Sync started", tag = "Sync")
withContext(Dispatchers.IO) {
chatSyncRepository?.sync()
}
loadSessionsFromDb()
+ logRepository.log(LogLevel.Info, "Sync success", tag = "Sync")
} catch (err: Throwable) {
val message = syncErrorMessage(err)
- logRepository.log(LogLevel.Error, "Sync failed", message)
+ logRepository.log(
+ LogLevel.Error,
+ "Sync failed",
+ details = message,
+ tag = "Sync",
+ throwable = err
+ )
if (onError != null) {
withContext(Dispatchers.Main) {
onError("Sync failed: $message")
@@ -653,10 +804,25 @@ class AppStore(
}
}
+ private fun nextGenerationToken(): Long {
+ activeGenerationToken += 1
+ return activeGenerationToken
+ }
+
+ private fun invalidateGenerationToken() {
+ activeGenerationToken += 1
+ }
+
+ private fun isGenerationActive(token: Long, sessionId: String): Boolean {
+ return token == activeGenerationToken && _state.value.chat.currentSessionId == sessionId
+ }
+
private fun startGeneration(sessionId: String, userMessage: ChatMessage) {
val scope = scope ?: return
generationJob?.cancel()
+ sessionSummaryJob?.cancel()
stopRequested = false
+ val generationToken = nextGenerationToken()
streamingParentId = userMessage.id
_state.update { appState ->
@@ -676,8 +842,10 @@ class AppStore(
generationJob = scope.launch {
val settings = _state.value.modelSettings
val target = resolveTarget(settings)
+ val isActive = { isGenerationActive(generationToken, sessionId) }
try {
llmProvider.ensureModelReady(target) { progress ->
+ if (!isActive()) return@ensureModelReady
val downloading = (progress.percent in 0..99) || progress.status.contains("Loading", ignoreCase = true)
val finished = progress.status.contains("Ready", ignoreCase = true)
_state.update { appState ->
@@ -685,7 +853,9 @@ class AppStore(
chat = appState.chat.copy(
isDownloading = downloading && !finished,
downloadPercent = progress.percent.takeIf { it >= 0 },
- downloadStatus = progress.status
+ downloadStatus = progress.status,
+ isModelDownloaded = if (finished) true else appState.chat.isModelDownloaded,
+ modelDownloadSizeBytes = if (finished) null else appState.chat.modelDownloadSizeBytes
)
)
}
@@ -693,6 +863,7 @@ class AppStore(
} catch (err: Throwable) {
val cancelled = err is kotlinx.coroutines.CancellationException ||
err.message?.contains("cancel", ignoreCase = true) == true
+ if (!isActive()) return@launch
streamingParentId = null
_state.update { appState ->
appState.copy(
@@ -701,22 +872,35 @@ class AppStore(
isDownloading = false,
streamingParentId = null,
downloadPercent = null,
- downloadStatus = if (cancelled) "Download cancelled" else null
+ downloadStatus = if (cancelled) "Download cancelled" else null,
+ hasRequestedModelDownload = if (cancelled) false else appState.chat.hasRequestedModelDownload
)
)
}
if (!cancelled) {
- logRepository.log(LogLevel.Error, "Model load failed", err.message ?: "")
+ logRepository.log(
+ LogLevel.Error,
+ "Model load failed",
+ details = err.message,
+ tag = "Model",
+ throwable = err
+ )
}
syncAfterGeneration()
return@launch
}
+ if (!isActive()) return@launch
+
val prompt = buildPrompt(userMessage.text, userMessage.attachments)
val history = buildHistory(sessionId, prompt.text, userMessage.id)
- val llmMessages = history + LlmMessage(
+ val systemMessage = LlmMessage(
+ text = SYSTEM_PROMPT,
+ role = LlmMessageRole.System
+ )
+ val llmMessages = listOf(systemMessage) + history + LlmMessage(
text = prompt.text,
- isUser = true,
+ role = LlmMessageRole.User,
hasAttachments = userMessage.attachments.isNotEmpty()
)
@@ -728,22 +912,46 @@ class AppStore(
target = target,
messages = llmMessages,
imageFiles = prompt.imageFiles,
- temperature = 0.7f,
+ temperature = resolveTemperature(settings),
maxTokens = target.maxTokens ?: 1024
) { token ->
buffer.append(token)
tokenCount += estimateTokens(token)
- _state.update { appState ->
- appState.copy(chat = appState.chat.copy(streamingResponse = buffer.toString()))
+ if (isActive()) {
+ _state.update { appState ->
+ appState.copy(chat = appState.chat.copy(streamingResponse = buffer.toString()))
+ }
}
}
- finishGeneration(sessionId, userMessage, buffer, tokenCount, summary.totalTimeMs, false)
+ finishGeneration(
+ sessionId,
+ userMessage,
+ buffer,
+ tokenCount,
+ summary.totalTimeMs,
+ interrupted = false,
+ shouldUpdateUi = isActive()
+ )
} catch (err: Throwable) {
val interrupted = stopRequested || err.message?.contains("cancel", ignoreCase = true) == true
- finishGeneration(sessionId, userMessage, buffer, tokenCount, null, interrupted)
+ finishGeneration(
+ sessionId,
+ userMessage,
+ buffer,
+ tokenCount,
+ totalTimeMs = null,
+ interrupted = interrupted,
+ shouldUpdateUi = isActive()
+ )
if (!interrupted) {
- logRepository.log(LogLevel.Error, "Generation failed", err.message ?: "")
+ logRepository.log(
+ LogLevel.Error,
+ "Generation failed",
+ details = err.message,
+ tag = "LLM",
+ throwable = err
+ )
}
}
}
@@ -755,7 +963,8 @@ class AppStore(
buffer: StringBuilder,
tokenCount: Int,
totalTimeMs: Long?,
- interrupted: Boolean
+ interrupted: Boolean,
+ shouldUpdateUi: Boolean
) {
val finalText = buffer.toString().trim()
if (finalText.isNotEmpty()) {
@@ -781,28 +990,41 @@ class AppStore(
updateCurrentSessionPreview(sessionId, finalText, assistantMessage.timestampMillis)
}
- streamingParentId = null
- _state.update { appState ->
- appState.copy(
- chat = appState.chat.copy(
- isGenerating = false,
- isDownloading = false,
- streamingResponse = "",
- streamingParentId = null,
- downloadPercent = null,
- downloadStatus = null
+ if (shouldUpdateUi) {
+ streamingParentId = null
+ _state.update { appState ->
+ appState.copy(
+ chat = appState.chat.copy(
+ isGenerating = false,
+ isDownloading = false,
+ streamingResponse = "",
+ streamingParentId = null,
+ downloadPercent = null,
+ downloadStatus = null
+ )
)
- )
+ }
+ rebuildChatState(sessionId)
+ syncAfterGeneration()
}
- rebuildChatState(sessionId)
- syncAfterGeneration()
+ scheduleSessionSummary(sessionId)
}
private fun updateCurrentSessionPreview(sessionId: String, preview: String, timestamp: Long) {
_state.update { appState ->
val updatedSessions = appState.chat.sessions.map { session ->
if (session.id == sessionId) {
- session.copy(lastMessagePreview = preview, updatedAtMillis = timestamp)
+ val shouldUpdateTitle = session.title.isBlank() || session.title.equals("New Chat", ignoreCase = true)
+ val updatedTitle = if (shouldUpdateTitle) {
+ sessionTitleFromText(preview, fallback = session.title)
+ } else {
+ session.title
+ }
+ session.copy(
+ title = updatedTitle,
+ lastMessagePreview = preview,
+ updatedAtMillis = timestamp
+ )
} else {
session
}
@@ -811,6 +1033,76 @@ class AppStore(
}
}
+ private fun applySessionSummariesToState() {
+ _state.update { appState ->
+ val updatedSessions = appState.chat.sessions.map { session ->
+ val summary = sessionSummaries[session.id]
+ if (!summary.isNullOrBlank() && summary != session.title) {
+ session.copy(title = summary)
+ } else {
+ session
+ }
+ }
+ appState.copy(chat = appState.chat.copy(sessions = updatedSessions))
+ }
+ }
+
+ private fun scheduleSessionSummary(sessionId: String) {
+ val scope = scope ?: return
+ sessionSummaryJob?.cancel()
+ sessionSummaryJob = scope.launch(Dispatchers.Default) {
+ val summary = buildSessionSummary(sessionId) ?: return@launch
+ if (!isActive) return@launch
+ withContext(Dispatchers.Main) {
+ applySessionSummary(sessionId, summary)
+ }
+ }
+ }
+
+ private fun buildSessionSummary(sessionId: String): String? {
+ val firstUserMessage = messageStore[sessionId]
+ ?.asSequence()
+ ?.filter { it.author == MessageAuthor.User }
+ ?.minByOrNull { it.timestampMillis }
+ ?: return null
+ val summary = summarizeQuestion(firstUserMessage.text)
+ if (summary.isBlank()) return null
+ val existing = sessionSummaries[sessionId]
+ if (!existing.isNullOrBlank() && existing == summary) return null
+ return summary
+ }
+
+ private fun applySessionSummary(sessionId: String, summary: String) {
+ if (summary.isBlank()) return
+ if (sessionSummaries[sessionId] == summary) return
+ sessionSummaries[sessionId] = summary
+ scope?.launch { sessionPreferences.setSessionSummary(sessionId, summary) }
+ _state.update { appState ->
+ val updatedSessions = appState.chat.sessions.map { session ->
+ if (session.id == sessionId) {
+ session.copy(title = summary)
+ } else {
+ session
+ }
+ }
+ appState.copy(chat = appState.chat.copy(sessions = updatedSessions))
+ }
+ }
+
+ private fun summarizeQuestion(text: String): String {
+ val cleaned = text
+ .replace(Regex("[\r\n]+"), " ")
+ .replace(Regex("\\s+"), " ")
+ .trim()
+ if (cleaned.isBlank()) return ""
+ val words = cleaned.split(" ")
+ .map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }
+ .filter { it.isNotBlank() }
+ if (words.isEmpty()) return ""
+ val summaryWords = words.take(6)
+ return summaryWords.joinToString(" ")
+ }
+
private fun loadMessagesFromDb(sessionId: String) {
val messages = chatRepository.getMessages(sessionId)
messageStore[sessionId] = messages.toMutableList()
@@ -979,10 +1271,22 @@ class AppStore(
val text = historyText(message)
val cost = estimateTokens(text)
if (cost <= remaining) {
- selected.add(LlmMessage(text, message.author == MessageAuthor.User, message.attachments.isNotEmpty()))
+ selected.add(
+ LlmMessage(
+ text = text,
+ role = if (message.author == MessageAuthor.User) LlmMessageRole.User else LlmMessageRole.Assistant,
+ hasAttachments = message.attachments.isNotEmpty()
+ )
+ )
remaining -= cost
} else if (selected.isEmpty()) {
- selected.add(LlmMessage(trimToBudget(text, remaining), message.author == MessageAuthor.User, message.attachments.isNotEmpty()))
+ selected.add(
+ LlmMessage(
+ text = trimToBudget(text, remaining),
+ role = if (message.author == MessageAuthor.User) LlmMessageRole.User else LlmMessageRole.Assistant,
+ hasAttachments = message.attachments.isNotEmpty()
+ )
+ )
break
} else {
break
@@ -1013,6 +1317,11 @@ class AppStore(
return max(1, text.length / 4)
}
+ private fun resolveTemperature(settings: ModelSettingsState): Float {
+ val temperature = settings.temperature.trim().toFloatOrNull()
+ return temperature?.takeIf { it >= 0f } ?: DEFAULT_TEMPERATURE
+ }
+
private fun resolveTarget(settings: ModelSettingsState): LlmModelTarget {
val useCustom = settings.useCustomModel && settings.modelUrl.isNotBlank()
val url = if (useCustom) settings.modelUrl else DEFAULT_MODEL_URL
@@ -1031,36 +1340,35 @@ class AppStore(
}
private fun loadSessionsFromDb() {
- val sessions = chatRepository.listSessions()
+ val sessions = chatRepository.listSessions().map { session ->
+ val summary = sessionSummaries[session.id]
+ if (!summary.isNullOrBlank()) {
+ session.copy(title = summary)
+ } else {
+ session
+ }
+ }
sessions.forEach { session ->
messageStore.getOrPut(session.id) { mutableListOf() }
branchSelections.getOrPut(session.id) { mutableMapOf() }
}
- val stored = runBlocking { sessionPreferences.selectedSessionId.first() }
- val resolvedStored = stored?.takeIf { id -> sessions.any { it.id == id } }
- val shouldKeepDraft = resolvedStored == null &&
- stored == null &&
- _state.value.chat.currentSessionId == null &&
- _state.value.chat.sessions.isNotEmpty()
- val current = if (shouldKeepDraft) null else resolvedStored ?: sessions.firstOrNull()?.id
+ val currentSessionId = _state.value.chat.currentSessionId
+ val sessionStillExists = currentSessionId != null && sessions.any { it.id == currentSessionId }
_state.update { appState ->
appState.copy(
chat = appState.chat.copy(
sessions = sessions,
- currentSessionId = current,
- messages = if (current == null) emptyList() else appState.chat.messages,
- branchSelections = if (current == null) emptyMap() else appState.chat.branchSelections
+ currentSessionId = if (sessionStillExists) currentSessionId else null
)
)
}
- if (current != null) {
- loadMessagesFromDb(current)
- rebuildChatState(current)
- ensureAttachmentsAvailable(current)
+ if (sessionStillExists && currentSessionId != null) {
+ loadMessagesFromDb(currentSessionId)
+ rebuildChatState(currentSessionId)
} else {
updateAttachmentDownloadState()
}
@@ -1077,5 +1385,8 @@ class AppStore(
private const val DEFAULT_MMPROJ_URL =
"https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-GGUF/resolve/main/mmproj-LFM2.5-VL-1.6b-Q8_0.gguf"
private const val MEDIA_MARKER = "<__media__>"
+ private const val DEFAULT_TEMPERATURE = 0.7f
+ private const val SYSTEM_PROMPT =
+ "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points."
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/ArrowReloadHorizontalIcon.imageset/ArrowReloadHorizontalIcon.svg b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/ArrowReloadHorizontalIcon.imageset/ArrowReloadHorizontalIcon.svg
new file mode 100644
index 0000000000..a82b8a7391
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/ArrowReloadHorizontalIcon.imageset/ArrowReloadHorizontalIcon.svg
@@ -0,0 +1,6 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
+ <path d="M20.5 5.5H9.5C5.78672 5.5 3 8.18503 3 12" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" />
+ <path d="M3.5 18.5H14.5C18.2133 18.5 21 15.815 21 12" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" />
+ <path d="M18.5 3C18.5 3 21 4.84122 21 5.50002C21 6.15882 18.5 8 18.5 8" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" />
+ <path d="M5.49998 16C5.49998 16 3.00001 17.8412 3 18.5C2.99999 19.1588 5.5 21 5.5 21" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" />
+</svg>
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/ArrowReloadHorizontalIcon.imageset/Contents.json b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/ArrowReloadHorizontalIcon.imageset/Contents.json
new file mode 100644
index 0000000000..f5d17d2f0f
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/ArrowReloadHorizontalIcon.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "ArrowReloadHorizontalIcon.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Navigation06Icon.imageset/Contents.json b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Navigation06Icon.imageset/Contents.json
new file mode 100644
index 0000000000..0901738099
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Navigation06Icon.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "Navigation06Icon.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Navigation06Icon.imageset/Navigation06Icon.svg b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Navigation06Icon.imageset/Navigation06Icon.svg
new file mode 100644
index 0000000000..f9cfbf0f01
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Navigation06Icon.imageset/Navigation06Icon.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
+ <path d="M6.73726 10.4584C9.00955 5.81947 10.1457 3.5 12 3.5C13.8543 3.5 14.9904 5.81946 17.2627 10.4584L18.8101 13.6174C20.5552 17.18 21.4277 18.9613 20.7934 19.8178C20.6228 20.0481 20.398 20.238 20.1366 20.3729C19.1643 20.8743 17.3794 19.8641 13.8096 17.8436C13.0178 17.3954 12.6219 17.1713 12.1889 17.1312C12.0633 17.1196 11.9367 17.1196 11.8111 17.1312C11.3781 17.1713 10.9822 17.3954 10.1904 17.8436C6.62059 19.8641 4.83571 20.8743 3.86337 20.3729C3.60196 20.238 3.37719 20.0481 3.20664 19.8178C2.57226 18.9613 3.44481 17.18 5.1899 13.6174L6.73726 10.4584Z" stroke="currentColor" stroke-linejoin="round" stroke-width="2" />
+</svg>
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/StopIcon.imageset/Contents.json b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/StopIcon.imageset/Contents.json
new file mode 100644
index 0000000000..ef539e8e05
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/StopIcon.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "StopIcon.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/StopIcon.imageset/StopIcon.svg b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/StopIcon.imageset/StopIcon.svg
new file mode 100644
index 0000000000..dc2bf00e8c
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/StopIcon.imageset/StopIcon.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
+ <path d="M4 12C4 8.72077 4 7.08116 4.81382 5.91891C5.1149 5.48891 5.48891 5.1149 5.91891 4.81382C7.08116 4 8.72077 4 12 4C15.2792 4 16.9188 4 18.0811 4.81382C18.5111 5.1149 18.8851 5.48891 19.1862 5.91891C20 7.08116 20 8.72077 20 12C20 15.2792 20 16.9188 19.1862 18.0811C18.8851 18.5111 18.5111 18.8851 18.0811 19.1862C16.9188 20 15.2792 20 12 20C8.72077 20 7.08116 20 5.91891 19.1862C5.48891 18.8851 5.1149 18.5111 4.81382 18.0811C4 16.9188 4 15.2792 4 12Z" />
+</svg>
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Upload01Icon.imageset/Contents.json b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Upload01Icon.imageset/Contents.json
new file mode 100644
index 0000000000..5540d0ffae
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Upload01Icon.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "Upload01Icon.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Upload01Icon.imageset/Upload01Icon.svg b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Upload01Icon.imageset/Upload01Icon.svg
new file mode 100644
index 0000000000..2ea944e86b
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Assets.xcassets/Upload01Icon.imageset/Upload01Icon.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
+ <path d="M2.99995 17C2.99995 17.93 2.99995 18.395 3.10217 18.7765C3.37957 19.8117 4.18821 20.6204 5.22349 20.8978C5.60499 21 6.06997 21 6.99995 21L16.9999 21C17.9299 21 18.3949 21 18.7764 20.8978C19.8117 20.6204 20.6203 19.8117 20.8977 18.7765C20.9999 18.395 20.9999 17.93 20.9999 17" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" />
+ <path d="M16.5 7.49993C16.5 7.49993 13.1858 2.99997 12 2.99996C10.8142 2.99995 7.50002 7.49996 7.50002 7.49996M12 3.99996V16" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" />
+</svg>
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Auth/AuthFlowView.swift b/mobile/native/darwin/Apps/ensu/ensu/Auth/AuthFlowView.swift
index 1c95a5918b..71cbf71948 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Auth/AuthFlowView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Auth/AuthFlowView.swift
@@ -58,8 +58,10 @@ struct AuthFlowView: View {
path.removeLast()
} label: {
HStack(spacing: 4) {
- Image(systemName: "chevron.left")
- .font(.system(size: 14, weight: .semibold))
+ Image("ArrowLeft01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 14, height: 14)
Text("Back")
}
.font(EnsuTypography.small)
@@ -201,8 +203,10 @@ struct AuthFlowView: View {
path.removeLast()
} label: {
HStack(spacing: 4) {
- Image(systemName: "chevron.left")
- .font(.system(size: 14, weight: .semibold))
+ Image("ArrowLeft01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 14, height: 14)
Text("Back")
}
.font(EnsuTypography.small)
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift
index 09f2c8df50..c6f53de25b 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatView.swift
@@ -1,3 +1,4 @@
+#if canImport(EnteCore)
import SwiftUI
struct ChatView: View {
@@ -5,10 +6,14 @@ struct ChatView: View {
@Binding var isShowingAuth: Bool
@EnvironmentObject private var appState: EnsuAppState
+ @ObservedObject private var modelSettings = ModelSettingsStore.shared
@State private var isDrawerOpen = false
+ @State private var showSettings = false
@State private var showModelSettings = false
+ @State private var showLogs = false
@State private var toastMessage: ToastMessage?
+ @StateObject private var keyboard = KeyboardObserver()
@State private var deleteSession: ChatSession?
@State private var developerTapCount = 0
@State private var lastDeveloperTapAt: Date?
@@ -17,6 +22,7 @@ struct ChatView: View {
@State private var showDeveloperSettings = false
@State private var showSignOutAlert = false
@State private var showAttachmentDownloads = false
+ @State private var didAutoFocusInput = false
private var editingMessage: ChatMessage? {
guard let editingId = viewModel.editingMessageId else { return nil }
@@ -67,10 +73,32 @@ struct ChatView: View {
showToast(message, duration: 2)
viewModel.syncErrorMessage = nil
}
+ .onChange(of: modelSettings.useCustomModel) { _ in
+ viewModel.refreshModelDownloadInfo()
+ }
+ .onChange(of: modelSettings.modelUrl) { _ in
+ viewModel.refreshModelDownloadInfo()
+ }
+ .onChange(of: modelSettings.mmprojUrl) { _ in
+ viewModel.refreshModelDownloadInfo()
+ }
+ }
+ .sheet(isPresented: $showSettings) {
+ SettingsView(
+ onOpenModelSettings: {
+ showModelSettings = true
+ },
+ onOpenLogs: {
+ showLogs = true
+ }
+ )
}
.sheet(isPresented: $showModelSettings) {
ModelSettingsView()
}
+ .sheet(isPresented: $showLogs) {
+ LogsView()
+ }
.sheet(isPresented: $showAttachmentDownloads) {
AttachmentDownloadsSheet(
downloads: viewModel.attachmentDownloads,
@@ -134,6 +162,7 @@ struct ChatView: View {
showSignIn: !appState.isLoggedIn,
showsMenuButton: showsMenuButton,
attachmentDownloadSummary: viewModel.attachmentDownloadSummary,
+ modelDownloadState: viewModel.downloadToast,
onMenu: { isDrawerOpen.toggle() },
onSignIn: { isShowingAuth = true },
onAttachmentDownloads: {
@@ -144,58 +173,92 @@ struct ChatView: View {
Divider()
.background(EnsuColor.border)
+ let showDownloadOnboarding = viewModel.messages.isEmpty && !viewModel.isGenerating && !viewModel.isModelDownloaded
+
ZStack(alignment: .top) {
VStack(spacing: 0) {
- MessageListView(
- messages: viewModel.messages,
- streamingResponse: viewModel.displayedStreamingResponse,
- streamingParentId: viewModel.displayedStreamingParentId,
- isGenerating: viewModel.isGenerating,
- onEdit: { message in
- viewModel.beginEditing(message: message)
- },
- onCopy: { message in
- copyToPasteboard(message.text)
- showToast("Copied to clipboard", duration: 1)
- },
- onRetry: { message in
- viewModel.retryAssistantResponse(message)
- },
- onBranchChange: { message, delta in
- viewModel.changeBranch(for: message, delta: delta)
- }
- )
-
- MessageInputView(
- text: $viewModel.draftText,
- attachments: $viewModel.draftAttachments,
- isGenerating: viewModel.isGenerating,
- isDownloading: viewModel.isDownloading,
- editingMessage: editingMessage,
- isProcessingAttachments: viewModel.isProcessingAttachments,
- isAttachmentDownloadBlocked: viewModel.isAttachmentDownloadBlocked,
- onSend: {
- viewModel.sendDraft()
- },
- onStop: {
- viewModel.stopGenerating()
- },
- onCancelEdit: {
- viewModel.cancelEditing()
- },
- onAddImage: { data, name in
- viewModel.addImageAttachment(data: data, fileName: name)
- },
- onAddDocument: { url in
- viewModel.addDocumentAttachment(url: url)
- },
- onRemoveAttachment: { attachment in
- viewModel.removeAttachment(attachment)
+ if showDownloadOnboarding {
+ DownloadOnboardingView(
+ isDownloading: viewModel.isDownloading,
+ downloadPercent: viewModel.downloadToast?.percent,
+ statusText: viewModel.downloadToast?.status,
+ totalBytes: viewModel.modelDownloadSizeBytes,
+ sizeText: viewModel.modelDownloadSizeText,
+ onDownload: {
+ viewModel.startModelDownload()
+ }
+ )
+ } else {
+ MessageListView(
+ messages: viewModel.messages,
+ streamingResponse: viewModel.displayedStreamingResponse,
+ streamingParentId: viewModel.displayedStreamingParentId,
+ isGenerating: viewModel.isGenerating,
+ keyboardHeight: keyboard.height,
+ emptyStateTitle: "Welcome to ensu",
+ emptyStateSubtitle: "Start typing to begin a conversation",
+ onEdit: { message in
+ viewModel.beginEditing(message: message)
+ },
+ onCopy: { message in
+ copyToPasteboard(message.text)
+ showToast("Copied to clipboard", duration: 1)
+ },
+ onRetry: { message in
+ viewModel.retryAssistantResponse(message)
+ },
+ onBranchChange: { message, delta in
+ viewModel.changeBranch(for: message, delta: delta)
+ }
+ )
+ }
+
+ if !showDownloadOnboarding {
+ let shouldAutoFocus = viewModel.isModelDownloaded && !viewModel.isDownloading && !viewModel.isGenerating && !didAutoFocusInput
+
+ MessageInputView(
+ text: $viewModel.draftText,
+ attachments: $viewModel.draftAttachments,
+ isGenerating: viewModel.isGenerating,
+ isDownloading: viewModel.isDownloading,
+ editingMessage: editingMessage,
+ isProcessingAttachments: viewModel.isProcessingAttachments,
+ isAttachmentDownloadBlocked: viewModel.isAttachmentDownloadBlocked,
+ autoFocus: shouldAutoFocus,
+ onSend: {
+ viewModel.sendDraft()
+ },
+ onStop: {
+ viewModel.stopGenerating()
+ },
+ onCancelEdit: {
+ viewModel.cancelEditing()
+ },
+ onAddImage: { data, name in
+ viewModel.addImageAttachment(data: data, fileName: name)
+ },
+ onAddDocument: { url in
+ viewModel.addDocumentAttachment(url: url)
+ },
+ onRemoveAttachment: { attachment in
+ viewModel.removeAttachment(attachment)
+ }
+ )
+ .onAppear {
+ if shouldAutoFocus {
+ didAutoFocusInput = true
+ }
}
- )
+ }
+ }
+ .onAppear {
+ viewModel.autoStartModelDownloadIfNeeded()
+ }
+ .onChange(of: viewModel.messages.count) { _ in
+ viewModel.autoStartModelDownloadIfNeeded()
}
- if let downloadToast = viewModel.downloadToast {
+ if let downloadToast = viewModel.downloadToast, !showDownloadOnboarding, downloadToast.phase != .loading {
DownloadToastView(state: downloadToast) {
viewModel.downloadToast = nil
} onRetry: {
@@ -231,18 +294,13 @@ struct ChatView: View {
onSync: {
viewModel.syncNow()
},
- onShowLogs: {
- showToast("Logs are not available yet.", duration: 2)
- },
- onShowModelSettings: {
- showModelSettings = true
+ onOpenSettings: {
+ isDrawerOpen = false
+ showSettings = true
},
onDeveloperTap: {
handleDeveloperTap()
},
- onDeveloperSettings: {
- presentDeveloperPrompt()
- },
onSignOut: {
showSignOutAlert = true
},
@@ -274,6 +332,9 @@ struct ChatView: View {
}
private func handleDeveloperTap() {
+ // Don't allow switching endpoints for logged-in users.
+ guard !appState.isLoggedIn else { return }
+
let now = Date()
if let lastDeveloperTapAt,
now.timeIntervalSince(lastDeveloperTapAt) > 2 {
@@ -295,6 +356,83 @@ struct ChatView: View {
}
}
+private struct DownloadOnboardingView: View {
+ let isDownloading: Bool
+ let downloadPercent: Int?
+ let statusText: String?
+ let totalBytes: Int64?
+ let sizeText: String
+ let onDownload: () -> Void
+
+ var body: some View {
+ VStack(spacing: EnsuSpacing.md) {
+ Text("Download to begin using the Chat")
+ .font(EnsuTypography.large)
+ .foregroundStyle(EnsuColor.textPrimary)
+ .multilineTextAlignment(.center)
+
+ if isDownloading {
+ let statusLine: String = {
+ if let statusText, statusText.localizedCaseInsensitiveContains("loading") {
+ return statusText
+ }
+ if let totalBytes, let percent = downloadPercent, percent >= 0 {
+ let clamped = min(max(percent, 0), 100)
+ let downloaded = Int64(Double(totalBytes) * Double(clamped) / 100.0)
+ return "Downloading... \(formatBytes(downloaded)) / \(formatBytes(totalBytes))"
+ }
+ if let statusText, !statusText.isEmpty {
+ return statusText
+ }
+ return "Downloading..."
+ }()
+
+ Text(statusLine)
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textMuted)
+ .multilineTextAlignment(.center)
+
+ progressView
+ } else {
+ Button("Download") {
+ hapticMedium()
+ onDownload()
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(EnsuColor.accent)
+
+ Text(sizeText)
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .padding(.horizontal, EnsuSpacing.pageHorizontal)
+ }
+
+ @ViewBuilder
+ private var progressView: some View {
+ if let percent = downloadPercent, percent >= 0 {
+ let clamped = min(max(percent, 0), 100)
+ ProgressView(value: Double(clamped), total: 100)
+ .progressViewStyle(.linear)
+ .tint(EnsuColor.accent)
+ .frame(maxWidth: 240)
+ } else {
+ ProgressView()
+ .progressViewStyle(.linear)
+ .tint(EnsuColor.accent)
+ .frame(maxWidth: 240)
+ }
+ }
+
+ private func formatBytes(_ bytes: Int64) -> String {
+ let formatter = ByteCountFormatter()
+ formatter.countStyle = .file
+ return formatter.string(fromByteCount: bytes)
+ }
+}
+
private struct ToastMessage: Identifiable {
let id = UUID()
let text: String
@@ -354,8 +492,14 @@ private struct AttachmentDownloadsSheet: View {
.foregroundStyle(EnsuColor.textMuted)
if item.status == .queued || item.status == .downloading {
- Button(action: { onCancel(item.id) }) {
- Image(systemName: "xmark.circle.fill")
+ Button(action: {
+ hapticWarning()
+ onCancel(item.id)
+ }) {
+ Image("Cancel01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 18, height: 18)
.foregroundStyle(EnsuColor.textMuted)
}
.buttonStyle(.plain)
@@ -392,19 +536,35 @@ private struct ChatAppBar: View {
let showSignIn: Bool
let showsMenuButton: Bool
let attachmentDownloadSummary: (completed: Int, total: Int)?
+ let modelDownloadState: DownloadToastState?
let onMenu: () -> Void
let onSignIn: () -> Void
let onAttachmentDownloads: () -> Void
private let centerInset: CGFloat = 72
+ private var modelProgressState: DownloadToastState? {
+ guard let modelDownloadState else { return nil }
+ switch modelDownloadState.phase {
+ case .loading:
+ return modelDownloadState
+ default:
+ return nil
+ }
+ }
+
var body: some View {
ZStack {
HStack(spacing: EnsuSpacing.md) {
if showsMenuButton {
- Button(action: onMenu) {
- Image(systemName: "line.3.horizontal")
- .font(.system(size: 18, weight: .semibold))
+ Button(action: {
+ hapticTap()
+ onMenu()
+ }) {
+ Image("Menu01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 18, height: 18)
.frame(width: 40, height: 40)
}
.buttonStyle(.plain)
@@ -415,29 +575,47 @@ private struct ChatAppBar: View {
Spacer()
- if showSignIn {
- Button(action: onSignIn) {
- Text("Sign In")
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.accent)
- }
- .buttonStyle(.plain)
- } else if let summary = attachmentDownloadSummary {
- Button(action: onAttachmentDownloads) {
- HStack(spacing: 6) {
- Image(systemName: "arrow.down.circle")
- .font(.system(size: 14, weight: .semibold))
- .foregroundStyle(EnsuColor.textPrimary)
- Text("\(summary.completed)/\(summary.total)")
- .font(EnsuTypography.mini)
- .foregroundStyle(EnsuColor.textMuted)
+ HStack(spacing: EnsuSpacing.md) {
+ if showSignIn {
+ if let progress = modelProgressState {
+ ModelProgressIndicator(state: progress)
+ }
+ Button(action: {
+ hapticTap()
+ onSignIn()
+ }) {
+ Text("Sign In")
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.accent)
+ }
+ .buttonStyle(.plain)
+ } else {
+ if let summary = attachmentDownloadSummary {
+ Button(action: {
+ hapticTap()
+ onAttachmentDownloads()
+ }) {
+ HStack(spacing: 6) {
+ Image("Upload01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 14, height: 14)
+ .foregroundStyle(EnsuColor.textPrimary)
+ Text("\(summary.completed)/\(summary.total)")
+ .font(EnsuTypography.mini)
+ .foregroundStyle(EnsuColor.textMuted)
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 6)
+ .background(EnsuColor.fillFaint)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ }
+ .buttonStyle(.plain)
+ }
+ if let progress = modelProgressState {
+ ModelProgressIndicator(state: progress)
}
- .padding(.horizontal, 8)
- .padding(.vertical, 6)
- .background(EnsuColor.fillFaint)
- .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
}
- .buttonStyle(.plain)
}
}
@@ -458,3 +636,31 @@ private struct ChatAppBar: View {
.background(EnsuColor.backgroundBase)
}
}
+
+private struct ModelProgressIndicator: View {
+ let state: DownloadToastState
+
+ var body: some View {
+ let clamped = min(max(state.percent, 0), 100)
+ if state.phase == .downloading {
+ ProgressView(value: Double(clamped), total: 100)
+ .progressViewStyle(.circular)
+ .tint(EnsuColor.accent)
+ .frame(width: 16, height: 16)
+ } else {
+ ProgressView()
+ .progressViewStyle(.circular)
+ .tint(EnsuColor.accent)
+ .frame(width: 16, height: 16)
+ }
+ }
+}
+#else
+import SwiftUI
+
+struct ChatView: View {
+ var body: some View {
+ Text("Chat unavailable")
+ }
+}
+#endif
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
index 0f13bd3285..5e3df541a3 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/ChatViewModel.swift
@@ -1,5 +1,292 @@
import Foundation
+#if canImport(EnteCore)
import EnteCore
+#else
+struct SyncAuth {
+ let baseUrl: String
+ let authToken: String
+ let masterKey: Data
+ let userAgent: String
+ let clientPackage: String
+ let clientVersion: String?
+}
+
+enum SyncError: Error {
+ case Message(String)
+}
+
+final class CredentialStore {
+ static let shared = CredentialStore()
+ var hasConfiguredAccount: Bool { false }
+ var token: String? { nil }
+ var masterKey: Data? { nil }
+
+ func getOrCreateChatDbKey() -> Data {
+ Data()
+ }
+}
+
+struct EntePlatform {
+ static let current = EntePlatform()
+ var userAgent: String { "ensu" }
+}
+
+enum EnteApp {
+ case ensu
+
+ var packageIdentifier: String {
+ "ensu"
+ }
+}
+
+enum EnsuLogLevel: String {
+ case info
+ case warning
+ case error
+}
+
+struct EnsuLogger {
+ let tag: String
+
+ func info(_ message: String, details: String? = nil) {}
+ func warning(_ message: String, details: String? = nil) {}
+ func error(_ message: String, _ error: Error? = nil, details: String? = nil) {}
+}
+
+final class EnsuLogging {
+ static let shared = EnsuLogging()
+
+ func start() {}
+
+ func logger(_ tag: String) -> EnsuLogger {
+ EnsuLogger(tag: tag)
+ }
+
+ func log(level: EnsuLogLevel, tag: String, message: String, details: String? = nil, error: Error? = nil) {}
+
+ func todayLogFileURL() -> URL { URL(fileURLWithPath: "") }
+ func listLogFiles() -> [URL] { [] }
+ func readLogText(fileURL: URL) -> String { "" }
+ func createLogsArchive() throws -> URL { URL(fileURLWithPath: "") }
+}
+
+struct NetworkConfiguration {
+ let apiEndpoint: URL
+
+ static var `default`: NetworkConfiguration {
+ NetworkConfiguration(apiEndpoint: URL(string: "https://api.ente.io")!)
+ }
+}
+
+enum EnsuDeveloperSettings {
+ static var networkConfiguration: NetworkConfiguration {
+ .default
+ }
+}
+
+struct InferenceModelTarget: Equatable {
+ let id: String
+ let url: String
+ let mmprojUrl: String?
+ let contextLength: Int?
+ let maxTokens: Int?
+}
+
+struct InferenceDownloadProgress: Equatable {
+ let percent: Int
+ let status: String
+}
+
+enum InferenceMessageRole {
+ case user
+ case assistant
+ case system
+
+ var roleString: String {
+ switch self {
+ case .user:
+ return "user"
+ case .assistant:
+ return "assistant"
+ case .system:
+ return "system"
+ }
+ }
+}
+
+struct InferenceMessage {
+ let text: String
+ let role: InferenceMessageRole
+ let hasAttachments: Bool
+}
+
+struct InferenceGenerationSummary {
+ let jobId: Int64
+ let generatedTokens: Int
+ let totalTimeMs: Int64?
+}
+
+final class InferenceRsProvider {
+ init(modelDir: URL) {
+ _ = modelDir
+ }
+
+ func ensureModelReady(
+ target: InferenceModelTarget,
+ onProgress: @escaping (InferenceDownloadProgress) -> Void
+ ) async throws {
+ _ = (target, onProgress)
+ }
+
+ func generateChat(
+ target: InferenceModelTarget,
+ messages: [InferenceMessage],
+ imageFiles: [URL],
+ temperature: Float,
+ maxTokens: Int,
+ onToken: @escaping (String) -> Void
+ ) async throws -> InferenceGenerationSummary {
+ _ = (target, messages, imageFiles, temperature, maxTokens, onToken)
+ return InferenceGenerationSummary(jobId: 0, generatedTokens: 0, totalTimeMs: nil)
+ }
+
+ func isModelDownloaded(target: InferenceModelTarget) -> Bool {
+ _ = target
+ return true
+ }
+
+ func estimatedDownloadSize(target: InferenceModelTarget) async -> Int64? {
+ _ = target
+ return nil
+ }
+
+ func stopGeneration() {}
+
+ func resetContext() {}
+
+ func cancelDownload() {}
+}
+
+@MainActor
+final class ModelSettingsStore: ObservableObject {
+ static let shared = ModelSettingsStore()
+
+ var temperature: String = ""
+ var contextLength: String = ""
+ var maxTokens: String = ""
+ var useCustomModel: Bool = false
+ var modelUrl: String = ""
+ var mmprojUrl: String = ""
+
+ func currentTarget() -> InferenceModelTarget {
+ let context = Int(contextLength)
+ let maxOutput = Int(maxTokens)
+ return InferenceModelTarget(
+ id: "default",
+ url: "",
+ mmprojUrl: nil,
+ contextLength: context,
+ maxTokens: maxOutput
+ )
+ }
+}
+
+enum MessageSender {
+ case selfUser
+ case other
+}
+
+enum AttachmentKind {
+ case image
+ case document
+}
+
+struct AttachmentMeta {
+ let id: String
+ let kind: AttachmentKind
+ let size: Int64
+ let name: String
+}
+
+struct LlmChatSession {
+ let uuid: String
+ let title: String
+ let updatedAtUs: Int64
+}
+
+struct LlmChatMessage {
+ let uuid: String
+ let sender: MessageSender
+ let createdAtUs: Int64
+ let text: String
+ let parentMessageUuid: String?
+ let attachments: [AttachmentMeta]
+}
+
+final class LlmChatDb {
+ static func open(mainDbPath: String, attachmentsDbPath: String, key: Data) throws -> LlmChatDb {
+ _ = (mainDbPath, attachmentsDbPath, key)
+ return LlmChatDb()
+ }
+
+ func listSessions() throws -> [LlmChatSession] { [] }
+
+ func getMessages(sessionUuid: String) throws -> [LlmChatMessage] {
+ _ = sessionUuid
+ return []
+ }
+
+ func deleteSession(uuid: String) throws {
+ _ = uuid
+ }
+
+ func insertMessage(
+ sessionUuid: String,
+ sender: MessageSender,
+ text: String,
+ parentMessageUuid: String?,
+ attachments: [AttachmentMeta]
+ ) throws -> LlmChatMessage {
+ _ = (sessionUuid, sender, text, parentMessageUuid, attachments)
+ return LlmChatMessage(
+ uuid: UUID().uuidString,
+ sender: sender,
+ createdAtUs: Int64(Date().timeIntervalSince1970 * 1_000_000),
+ text: text,
+ parentMessageUuid: parentMessageUuid,
+ attachments: attachments
+ )
+ }
+
+ func createSession(title: String) throws -> LlmChatSession {
+ LlmChatSession(uuid: UUID().uuidString, title: title, updatedAtUs: Int64(Date().timeIntervalSince1970 * 1_000_000))
+ }
+}
+
+final class LlmChatSync {
+ static func open(
+ mainDbPath: String,
+ attachmentsDbPath: String,
+ dbKey: Data,
+ attachmentsDir: String,
+ metaDir: String,
+ plaintextDir: String
+ ) throws -> LlmChatSync {
+ _ = (mainDbPath, attachmentsDbPath, dbKey, attachmentsDir, metaDir, plaintextDir)
+ return LlmChatSync()
+ }
+
+ func sync(auth: SyncAuth) throws -> Bool {
+ _ = auth
+ return true
+ }
+
+ func downloadAttachment(attachmentId: String, sessionUuid: String, auth: SyncAuth) throws -> Bool {
+ _ = (attachmentId, sessionUuid, auth)
+ return true
+ }
+}
+#endif
struct ChatAttachment: Identifiable, Equatable {
enum Kind {
@@ -30,9 +317,9 @@ struct ChatAttachment: Identifiable, Equatable {
var iconName: String {
switch kind {
case .image:
- return "photo"
+ return "Attachment01Icon"
case .document:
- return "doc.text"
+ return "Attachment01Icon"
}
}
}
@@ -129,6 +416,13 @@ struct DownloadToastState: Identifiable, Equatable {
@MainActor
final class ChatViewModel: ObservableObject {
+ private static let defaultTemperature: Float = 0.7
+ private static let systemPrompt = "You are a helpful assistant. Use Markdown **bold** to emphasize important terms and key points."
+ private static let sessionTitleMaxLength = 50
+ private static let sessionSummaryStoreKey = "ensu.session_summaries"
+
+ private let logger = EnsuLogging.shared.logger("ChatViewModel")
+
@Published var sessions: [ChatSession]
@Published var currentSessionId: UUID?
@Published var messages: [ChatMessage]
@@ -159,6 +453,8 @@ final class ChatViewModel: ObservableObject {
@Published var draftAttachments: [ChatAttachment] = []
@Published var editingMessageId: UUID?
@Published var downloadToast: DownloadToastState?
+ @Published var isModelDownloaded: Bool = false
+ @Published var modelDownloadSizeBytes: Int64?
@Published var attachmentDownloads: [AttachmentDownloadItem] = []
@Published var currentSessionMissingAttachments: [AttachmentDownloadItem] = []
@Published var syncErrorMessage: String?
@@ -171,19 +467,25 @@ final class ChatViewModel: ObservableObject {
private var messageStore: [UUID: [MessageNode]] = [:]
private var branchSelections: [UUID: [String: UUID]] = [:]
+ private var sessionSummaries: [String: String] = [:]
+ private var sessionSummaryTask: Task<Void, Never>?
private let rootId = UUID(uuidString: "00000000-0000-0000-0000-000000000000")!
private var generationTask: Task<Void, Never>?
+ private var modelDownloadTask: Task<Void, Never>?
private var stopRequested = false
private var activeGenerationId: UUID?
private var activeGenerationSessionId: UUID?
private var pendingSyncRequested = false
private var pendingSyncShowErrors = false
+ private var modelDownloadLoggedStart = false
private var attachmentDownloadQueue: [String] = []
private var attachmentDownloadTasks: [String: Task<Void, Never>] = [:]
private let maxAttachmentDownloads = 2
init() {
+ logger.info("Initializing")
+ let summaries = Self.loadSessionSummaries()
let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
?? FileManager.default.temporaryDirectory
@@ -231,10 +533,14 @@ final class ChatViewModel: ObservableObject {
let loaded = (try? chatDb.listSessions()) ?? []
let sessions: [ChatSession] = loaded.compactMap { session in
guard let id = UUID(uuidString: session.uuid) else { return nil }
- let lastMessage = (try? chatDb.getMessages(sessionUuid: session.uuid))?.last?.text ?? ""
+ let messages = (try? chatDb.getMessages(sessionUuid: session.uuid)) ?? []
+ let firstMessage = messages.first?.text ?? ""
+ let lastMessage = messages.last?.text ?? ""
+ let summary = summaries[session.uuid]
+ let title = summary ?? Self.sessionTitle(from: firstMessage, fallback: session.title)
return ChatSession(
id: id,
- title: session.title,
+ title: title,
lastMessage: lastMessage,
updatedAt: Date(timeIntervalSince1970: Double(session.updatedAtUs) / 1_000_000.0)
)
@@ -245,9 +551,10 @@ final class ChatViewModel: ObservableObject {
self.chatDb = chatDb
self.syncEngine = syncEngine
self.attachmentsDir = attachmentsDir
+ self.sessionSummaries = summaries
self.sessions = sessions
- self.currentSessionId = sessions.first?.id
+ self.currentSessionId = nil
self.messages = []
for session in sessions {
@@ -262,6 +569,8 @@ final class ChatViewModel: ObservableObject {
} else {
refreshAttachmentDownloadState()
}
+
+ refreshModelDownloadInfo()
}
var currentSession: ChatSession? {
@@ -295,6 +604,13 @@ final class ChatViewModel: ObservableObject {
return (completed, total)
}
+ var modelDownloadSizeText: String {
+ guard let bytes = modelDownloadSizeBytes else { return "Approx. size varies by model" }
+ let formatter = ByteCountFormatter()
+ formatter.countStyle = .file
+ return "Approx. \(formatter.string(fromByteCount: bytes))"
+ }
+
func sessionTitle(for sessionId: UUID) -> String {
sessions.first { $0.id == sessionId }?.title ?? "Chat"
}
@@ -350,6 +666,8 @@ final class ChatViewModel: ObservableObject {
downloadToast = nil
}
try? chatDb.deleteSession(uuid: session.id.uuidString)
+ sessionSummaries.removeValue(forKey: session.id.uuidString)
+ persistSessionSummaries()
sessions.removeAll { $0.id == session.id }
messageStore[session.id] = nil
@@ -385,22 +703,28 @@ final class ChatViewModel: ObservableObject {
}
private func performSync(showErrors: Bool) {
+ let log = logger
guard let auth = buildSyncAuth() else {
+ log.warning("Sync skipped", details: "not logged in")
if showErrors {
syncErrorMessage = "Sync failed: Sign in to sync"
}
return
}
- Task.detached { [weak self] in
+ log.info("Sync started")
+
+ Task.detached { [weak self, log] in
guard let self else { return }
do {
_ = try self.syncEngine.sync(auth: auth)
+ log.info("Sync success")
await MainActor.run {
self.reloadFromDb()
}
} catch {
let message = syncErrorMessage(from: error)
+ log.error("Sync failed", error, details: message)
await MainActor.run {
if showErrors {
self.syncErrorMessage = "Sync failed: \(message)"
@@ -487,6 +811,11 @@ final class ChatViewModel: ObservableObject {
let attachments = draftAttachments
guard !trimmed.isEmpty || !attachments.isEmpty else { return }
+ logger.info(
+ "Sent message",
+ details: "len=\(trimmed.count) attachments=\(attachments.count) edited=\(editingMessageId != nil)"
+ )
+
let sessionId = currentSessionId ?? createSessionForDraft()
if !missingAttachments(for: sessionId).isEmpty {
@@ -553,9 +882,85 @@ final class ChatViewModel: ObservableObject {
provider.stopGeneration()
}
+ func refreshModelDownloadInfo() {
+ let target = modelSettings.currentTarget()
+ isModelDownloaded = provider.isModelDownloaded(target: target)
+ if isModelDownloaded {
+ modelDownloadSizeBytes = nil
+ return
+ }
+
+ Task { [weak self] in
+ guard let self else { return }
+ let size = await provider.estimatedDownloadSize(target: target)
+ await MainActor.run {
+ self.modelDownloadSizeBytes = size
+ }
+ }
+ }
+
+ func startModelDownload() {
+ guard !isDownloading && !isGenerating else { return }
+ let target = modelSettings.currentTarget()
+ let isDownloaded = provider.isModelDownloaded(target: target)
+ if isDownloaded {
+ isModelDownloaded = true
+ modelDownloadSizeBytes = nil
+ } else {
+ modelDownloadLoggedStart = true
+ logger.info("Model download started", details: "model=\(target.id)")
+ }
+
+ modelDownloadTask?.cancel()
+ modelDownloadTask = Task {
+ do {
+ try await provider.ensureModelReady(target: target) { progress in
+ Task { @MainActor in
+ self.handleProgress(progress)
+ }
+ }
+ } catch {
+ if isCancellation(error) {
+ return
+ }
+ if self.modelDownloadLoggedStart {
+ self.logger.error("Model download failed", error)
+ self.modelDownloadLoggedStart = false
+ } else {
+ self.logger.error("Model load failed", error)
+ }
+ await MainActor.run {
+ self.downloadToast = DownloadToastState(
+ phase: .errorDownload,
+ percent: -1,
+ status: error.localizedDescription,
+ offerRetryDownload: true
+ )
+ self.isDownloading = false
+ }
+ }
+ }
+ }
+
+ func autoStartModelDownloadIfNeeded() {
+ guard !isDownloading && !isGenerating else { return }
+ if isModelDownloaded {
+ startModelDownload()
+ return
+ }
+ guard !messages.isEmpty else { return }
+ startModelDownload()
+ }
+
func cancelDownload() {
generationTask?.cancel()
+ modelDownloadTask?.cancel()
+ modelDownloadTask = nil
provider.cancelDownload()
+ if modelDownloadLoggedStart {
+ logger.info("Model download cancelled")
+ modelDownloadLoggedStart = false
+ }
stopRequested = true
activeGenerationId = nil
activeGenerationSessionId = nil
@@ -564,11 +969,13 @@ final class ChatViewModel: ObservableObject {
streamingResponse = ""
streamingParentId = nil
downloadToast = nil
+ refreshModelDownloadInfo()
}
func retryDownload() {
let target = modelSettings.currentTarget()
- Task {
+ modelDownloadTask?.cancel()
+ modelDownloadTask = Task {
do {
try await provider.ensureModelReady(target: target) { progress in
Task { @MainActor in
@@ -579,7 +986,14 @@ final class ChatViewModel: ObservableObject {
if isCancellation(error) {
return
}
- downloadToast = DownloadToastState(phase: .errorDownload, percent: -1, status: error.localizedDescription, offerRetryDownload: true)
+ await MainActor.run {
+ self.downloadToast = DownloadToastState(
+ phase: .errorDownload,
+ percent: -1,
+ status: error.localizedDescription,
+ offerRetryDownload: true
+ )
+ }
}
}
}
@@ -631,6 +1045,7 @@ final class ChatViewModel: ObservableObject {
private func startGeneration(for userNode: MessageNode) {
generationTask?.cancel()
+ sessionSummaryTask?.cancel()
stopRequested = false
let generationId = UUID()
activeGenerationId = generationId
@@ -679,7 +1094,8 @@ final class ChatViewModel: ObservableObject {
let prompt = buildPrompt(text: userNode.text, attachments: userNode.attachments)
let history = buildHistory(sessionId: userNode.sessionId, promptText: prompt.text, currentMessageId: userNode.id)
- let messages = history + [InferenceMessage(text: prompt.text, isUser: true, hasAttachments: !userNode.attachments.isEmpty)]
+ let systemMessage = InferenceMessage(text: Self.systemPrompt, role: .system, hasAttachments: false)
+ let messages = [systemMessage] + history + [InferenceMessage(text: prompt.text, role: .user, hasAttachments: !userNode.attachments.isEmpty)]
let bufferLock = NSLock()
var buffer = ""
@@ -690,7 +1106,7 @@ final class ChatViewModel: ObservableObject {
target: target,
messages: messages,
imageFiles: prompt.imageFiles,
- temperature: 0.7,
+ temperature: resolveTemperature(),
maxTokens: target.maxTokens ?? 1024
) { token in
bufferLock.lock()
@@ -762,10 +1178,15 @@ final class ChatViewModel: ObservableObject {
rebuildMessages(for: parent.sessionId)
}
syncNow(showErrors: false)
+ scheduleSessionSummary(for: parent.sessionId)
}
private func handleProgress(_ progress: InferenceDownloadProgress) {
if progress.percent == -1 {
+ if modelDownloadLoggedStart {
+ logger.error("Model download failed", details: progress.status)
+ modelDownloadLoggedStart = false
+ }
downloadToast = DownloadToastState(phase: .errorDownload, percent: -1, status: progress.status, offerRetryDownload: true)
isDownloading = false
return
@@ -781,8 +1202,14 @@ final class ChatViewModel: ObservableObject {
}
if isReady {
+ if modelDownloadLoggedStart {
+ logger.info("Model download complete", details: progress.status)
+ modelDownloadLoggedStart = false
+ }
downloadToast = DownloadToastState(phase: .complete, percent: 100, status: progress.status, offerRetryDownload: false)
isDownloading = false
+ isModelDownloaded = true
+ modelDownloadSizeBytes = nil
Task { @MainActor in
try? await Task.sleep(nanoseconds: 1_500_000_000)
if self.downloadToast?.phase == .complete {
@@ -982,9 +1409,10 @@ final class ChatViewModel: ObservableObject {
let refreshed: [ChatSession] = loaded.compactMap { session in
guard let id = UUID(uuidString: session.uuid) else { return nil }
let lastMessage = (try? chatDb.getMessages(sessionUuid: session.uuid))?.last?.text ?? ""
+ let summary = sessionSummaries[session.uuid]
return ChatSession(
id: id,
- title: session.title,
+ title: summary ?? session.title,
lastMessage: lastMessage,
updatedAt: Date(timeIntervalSince1970: Double(session.updatedAtUs) / 1_000_000.0)
)
@@ -1175,12 +1603,84 @@ final class ChatViewModel: ObservableObject {
sessions = sessions.map { session in
guard session.id == sessionId else { return session }
var updated = session
+ let isPlaceholderTitle = session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||
+ session.title.caseInsensitiveCompare("New chat") == .orderedSame
+ if isPlaceholderTitle {
+ updated.title = Self.sessionTitle(from: preview, fallback: session.title)
+ }
updated.lastMessage = preview
updated.updatedAt = date
return updated
}
}
+ private func scheduleSessionSummary(for sessionId: UUID) {
+ sessionSummaryTask?.cancel()
+ sessionSummaryTask = Task(priority: .utility) { [weak self] in
+ guard let self else { return }
+ do {
+ try await Task.sleep(nanoseconds: 200_000_000)
+ } catch {
+ return
+ }
+ guard !Task.isCancelled else { return }
+ await self.generateSessionSummaryIfNeeded(sessionId: sessionId)
+ }
+ }
+
+ @MainActor
+ private func generateSessionSummaryIfNeeded(sessionId: UUID) {
+ guard let nodes = messageStore[sessionId], !nodes.isEmpty else { return }
+ guard let firstUser = nodes.sorted(by: { $0.timestamp < $1.timestamp }).first(where: { $0.role == .user }) else {
+ return
+ }
+ let summary = Self.summarizeQuestion(firstUser.text)
+ guard !summary.isEmpty else { return }
+ if sessionSummaries[sessionId.uuidString] == summary { return }
+ sessionSummaries[sessionId.uuidString] = summary
+ persistSessionSummaries()
+ sessions = sessions.map { session in
+ guard session.id == sessionId else { return session }
+ var updated = session
+ updated.title = summary
+ return updated
+ }
+ }
+
+ private func persistSessionSummaries() {
+ guard let data = try? JSONEncoder().encode(sessionSummaries) else { return }
+ UserDefaults.standard.set(data, forKey: Self.sessionSummaryStoreKey)
+ }
+
+ private static func loadSessionSummaries() -> [String: String] {
+ guard let data = UserDefaults.standard.data(forKey: Self.sessionSummaryStoreKey) else { return [:] }
+ return (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]
+ }
+
+ private static func summarizeQuestion(_ text: String) -> String {
+ let cleaned = text
+ .replacingOccurrences(of: "[\\r\\n]+", with: " ", options: .regularExpression)
+ .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !cleaned.isEmpty else { return "" }
+ let words = cleaned.split(separator: " ").map {
+ String($0).trimmingCharacters(in: .punctuationCharacters)
+ }.filter { !$0.isEmpty }
+ guard !words.isEmpty else { return "" }
+ let summaryWords = words.prefix(6)
+ return summaryWords.joined(separator: " ")
+ }
+
+ private static func sessionTitle(from text: String, fallback: String = "New chat") -> String {
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return fallback }
+ if trimmed.count <= Self.sessionTitleMaxLength {
+ return trimmed
+ }
+ let prefix = trimmed.prefix(Self.sessionTitleMaxLength)
+ return String(prefix).trimmingCharacters(in: .whitespacesAndNewlines) + "…"
+ }
+
private func isCancellation(_ error: Error) -> Bool {
if error is CancellationError { return true }
return error.localizedDescription.localizedCaseInsensitiveContains("cancel")
@@ -1251,9 +1751,9 @@ final class ChatViewModel: ObservableObject {
if history.isEmpty { return [] }
let target = modelSettings.currentTarget()
- let contextSize = target.contextLength ?? 4096
- let maxTokens = target.maxTokens ?? 1024
- var budget = contextSize - maxTokens - 256
+ let contextSize: Int = target.contextLength ?? 4096
+ let maxTokens: Int = target.maxTokens ?? 1024
+ var budget: Int = contextSize - maxTokens - 256
budget -= estimateTokens(promptText)
if budget <= 0 { return [] }
@@ -1262,10 +1762,10 @@ final class ChatViewModel: ObservableObject {
let text = historyText(node)
let cost = estimateTokens(text)
if cost <= budget {
- selected.append(InferenceMessage(text: text, isUser: node.role == .user, hasAttachments: !node.attachments.isEmpty))
+ selected.append(InferenceMessage(text: text, role: node.role == .user ? .user : .assistant, hasAttachments: !node.attachments.isEmpty))
budget -= cost
} else if selected.isEmpty {
- selected.append(InferenceMessage(text: trimToBudget(text, budget: budget), isUser: node.role == .user, hasAttachments: !node.attachments.isEmpty))
+ selected.append(InferenceMessage(text: trimToBudget(text, budget: budget), role: node.role == .user ? .user : .assistant, hasAttachments: !node.attachments.isEmpty))
break
} else {
break
@@ -1282,7 +1782,7 @@ final class ChatViewModel: ObservableObject {
} else if !node.attachments.isEmpty {
text += "\n\n[\(node.attachments.count) attachments attached]"
}
- return text.trimmingCharacters(in: .whitespacesAndNewlines)
+ return text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
private func trimToBudget(_ text: String, budget: Int) -> String {
@@ -1296,6 +1796,11 @@ final class ChatViewModel: ObservableObject {
max(1, text.count / 4)
}
+ private func resolveTemperature() -> Float {
+ let value = Float(modelSettings.temperature.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))
+ return value.map { max(0, $0) } ?? Self.defaultTemperature
+ }
+
private struct MessageNode: Identifiable {
let id: UUID
let sessionId: UUID
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/DownloadToastView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/DownloadToastView.swift
index e735864bda..7a1c14bf73 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/DownloadToastView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/DownloadToastView.swift
@@ -32,7 +32,7 @@ struct DownloadToastView: View {
private var iconName: String {
switch state.phase {
case .downloading:
- return "arrow.down.circle"
+ return "Upload01Icon"
case .loading:
return "cpu"
case .complete:
@@ -56,9 +56,17 @@ struct DownloadToastView: View {
var body: some View {
VStack(alignment: .leading, spacing: EnsuSpacing.sm) {
HStack(spacing: EnsuSpacing.md) {
- Image(systemName: iconName)
- .font(.system(size: 20, weight: .semibold))
- .foregroundStyle(iconColor)
+ if iconName.hasSuffix("Icon") {
+ Image(iconName)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 20, height: 20)
+ .foregroundStyle(iconColor)
+ } else {
+ Image(systemName: iconName)
+ .font(.system(size: 20, weight: .semibold))
+ .foregroundStyle(iconColor)
+ }
Text(title)
.font(EnsuTypography.large)
@@ -67,9 +75,14 @@ struct DownloadToastView: View {
Spacer()
if !isComplete && !hasError {
- Button(action: onCancel) {
- Image(systemName: "xmark")
- .font(.system(size: 12, weight: .semibold))
+ Button(action: {
+ hapticWarning()
+ onCancel()
+ }) {
+ Image("Cancel01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 12, height: 12)
}
.buttonStyle(.plain)
.foregroundStyle(EnsuColor.textMuted)
@@ -102,12 +115,19 @@ struct DownloadToastView: View {
if hasError {
HStack {
Spacer()
- Button("Dismiss", action: onDismiss)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.textMuted)
- Button(state.offerRetryDownload ? "Retry download" : "Retry", action: onRetry)
- .font(EnsuTypography.small)
- .foregroundStyle(EnsuColor.accent)
+ Button("Dismiss") {
+ hapticTap()
+ onDismiss()
+ }
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+
+ Button(state.offerRetryDownload ? "Retry download" : "Retry") {
+ hapticMedium()
+ onRetry()
+ }
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.accent)
}
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift
index eff3b03728..93f49cd2e3 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageInputView.swift
@@ -1,7 +1,7 @@
+#if canImport(EnteCore)
import SwiftUI
import PhotosUI
import UniformTypeIdentifiers
-import UIKit
struct MessageInputView: View {
@Binding var text: String
@@ -11,6 +11,7 @@ struct MessageInputView: View {
let editingMessage: ChatMessage?
let isProcessingAttachments: Bool
let isAttachmentDownloadBlocked: Bool
+ let autoFocus: Bool
let onSend: () -> Void
let onStop: () -> Void
let onCancelEdit: () -> Void
@@ -20,16 +21,14 @@ struct MessageInputView: View {
@StateObject private var keyboard = KeyboardObserver()
@FocusState private var isFocused: Bool
- @State private var isImagePickerPresented = false
+
+ @State private var selectedPhotoItem: PhotosPickerItem?
private var placeholder: String {
- if isDownloading {
- return "Downloading model... (queue messages)"
- }
if isAttachmentDownloadBlocked {
return "Downloading attachments..."
}
- return "Compose your message..."
+ return "Write a message..."
}
private var canSend: Bool {
@@ -37,6 +36,11 @@ struct MessageInputView: View {
return hasContent && !isGenerating && !isDownloading && !isAttachmentDownloadBlocked
}
+ private var isSendEnabled: Bool {
+ let hasContent = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty
+ return hasContent && !isDownloading && !isAttachmentDownloadBlocked
+ }
+
var body: some View {
ZStack(alignment: .bottomTrailing) {
VStack(alignment: .leading, spacing: EnsuSpacing.sm) {
@@ -45,9 +49,14 @@ struct MessageInputView: View {
}
let hasAttachmentContent = !attachments.isEmpty || isProcessingAttachments
- let inputVerticalPadding: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : EnsuSpacing.inputVertical
- let textFieldPadding: CGFloat = hasAttachmentContent ? 2 : 8
- let bottomPadding: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : EnsuSpacing.sm
+
+ // Make the input bar a bit more compact when showing "Write a message..."
+ let inputVerticalPadding: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : 10
+ let textFieldPadding: CGFloat = hasAttachmentContent ? 2 : 6
+
+ // Lift the bar slightly off the bottom edge.
+ let bottomPadding: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : EnsuSpacing.md
+
let inputStackSpacing: CGFloat = hasAttachmentContent ? EnsuSpacing.xs : EnsuSpacing.sm
VStack(alignment: .leading, spacing: inputStackSpacing) {
@@ -96,43 +105,66 @@ struct MessageInputView: View {
}
if editingMessage == nil {
- Button {
- isImagePickerPresented = true
- } label: {
- Image(systemName: "paperclip")
- .font(attachmentIconFont)
+ PhotosPicker(selection: $selectedPhotoItem, matching: .images) {
+ Image("Upload01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: attachmentIconSize, height: attachmentIconSize)
.frame(width: 32, height: 32, alignment: .center)
}
.disabled(isGenerating || isDownloading || isAttachmentDownloadBlocked)
.foregroundStyle(EnsuColor.textMuted)
+ .simultaneousGesture(TapGesture().onEnded {
+ hapticTap()
+ })
#if os(macOS)
.buttonStyle(.plain)
.frame(width: 32, height: 32, alignment: .center)
#endif
- .sheet(isPresented: $isImagePickerPresented) {
- ImagePicker(
- onPick: { data, name in
- onAddImage(data, name)
- isImagePickerPresented = false
- },
- onCancel: {
- isImagePickerPresented = false
+ .onChange(of: selectedPhotoItem) { newItem in
+ guard let newItem else { return }
+ Task {
+ let data = try? await newItem.loadTransferable(type: Data.self)
+ await MainActor.run {
+ if let data {
+ onAddImage(data, nil)
+ }
+ selectedPhotoItem = nil
}
- )
+ }
}
}
Button {
if isGenerating {
+ hapticWarning()
onStop()
- } else if canSend {
+ } else if isSendEnabled {
+ hapticMedium()
onSend()
}
} label: {
- Image(systemName: sendIcon)
- .font(.system(size: 22, weight: .semibold))
- .foregroundStyle(sendColor)
+ if sendIcon == "StopIcon" {
+ ZStack {
+ Circle()
+ .fill(EnsuColor.textPrimary)
+ .frame(width: attachmentIconSize + 6, height: attachmentIconSize + 6)
+ Image(sendIcon)
+ .resizable()
+ .scaledToFit()
+ .frame(width: attachmentIconSize - 4, height: attachmentIconSize - 4)
+ .foregroundStyle(EnsuColor.stopButton)
+ }
.frame(width: 32, height: 32)
+ } else {
+ Image(sendIcon)
+ .resizable()
+ .scaledToFit()
+ .frame(width: attachmentIconSize, height: attachmentIconSize)
+ .rotationEffect(sendIcon == "Navigation06Icon" ? .degrees(90) : .zero)
+ .foregroundStyle(sendColor)
+ .frame(width: 32, height: 32)
+ }
}
.disabled(isDownloading || (!canSend && !isGenerating))
}
@@ -140,7 +172,7 @@ struct MessageInputView: View {
.padding(.vertical, inputVerticalPadding)
.frame(maxWidth: .infinity)
.background(EnsuColor.fillFaint)
- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input + 4, style: .continuous))
.padding(.horizontal, EnsuSpacing.pageHorizontal)
.padding(.bottom, bottomPadding)
}
@@ -149,6 +181,7 @@ struct MessageInputView: View {
if keyboard.isVisible {
Button {
+ hapticTap()
isFocused = false
hideKeyboard()
} label: {
@@ -166,11 +199,11 @@ struct MessageInputView: View {
.background(EnsuColor.backgroundBase)
}
- private var attachmentIconFont: Font {
+ private var attachmentIconSize: CGFloat {
#if os(macOS)
- return .system(size: 22, weight: .semibold)
+ return 18
#else
- return .system(size: 18, weight: .regular)
+ return 16
#endif
}
@@ -192,28 +225,24 @@ struct MessageInputView: View {
private var sendIcon: String {
if isGenerating {
- return "stop.fill"
- }
- if isDownloading {
- return "arrow.down"
+ return "StopIcon"
}
- return "paperplane"
+ return "Navigation06Icon"
}
private var sendColor: Color {
if isGenerating {
return EnsuColor.stopButton
}
- if isDownloading {
- return EnsuColor.textMuted
- }
- return EnsuColor.textMuted
+ return isSendEnabled ? EnsuColor.textPrimary : EnsuColor.textMuted
}
private func editBanner(for message: ChatMessage) -> some View {
HStack(spacing: EnsuSpacing.sm) {
- Image(systemName: "pencil")
- .font(.system(size: 14))
+ Image("Edit01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 14, height: 14)
.foregroundStyle(EnsuColor.accent)
Text("Editing:")
@@ -227,9 +256,14 @@ struct MessageInputView: View {
Spacer()
- Button(action: onCancelEdit) {
- Image(systemName: "xmark")
- .font(.system(size: 12, weight: .semibold))
+ Button(action: {
+ hapticTap()
+ onCancelEdit()
+ }) {
+ Image("Cancel01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 12, height: 12)
.foregroundStyle(EnsuColor.textMuted)
}
.buttonStyle(.plain)
@@ -249,91 +283,13 @@ struct MessageInputView: View {
.padding(.horizontal, EnsuSpacing.pageHorizontal)
}
}
+#else
+import SwiftUI
-private struct ImagePicker: UIViewControllerRepresentable {
- let onPick: (Data, String?) -> Void
- let onCancel: () -> Void
-
- func makeCoordinator() -> Coordinator {
- Coordinator(onPick: onPick, onCancel: onCancel)
- }
-
- func makeUIViewController(context: Context) -> PHPickerViewController {
- var config = PHPickerConfiguration(photoLibrary: .shared())
- config.filter = .images
- config.selectionLimit = 1
- let picker = PHPickerViewController(configuration: config)
- picker.delegate = context.coordinator
- return picker
- }
-
- func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {}
-
- final class Coordinator: NSObject, PHPickerViewControllerDelegate {
- private let onPick: (Data, String?) -> Void
- private let onCancel: () -> Void
-
- init(onPick: @escaping (Data, String?) -> Void, onCancel: @escaping () -> Void) {
- self.onPick = onPick
- self.onCancel = onCancel
- }
-
- func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
- guard let result = results.first else {
- onCancel()
- return
- }
- let provider = result.itemProvider
- let typeIdentifier = UTType.image.identifier
- provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, _ in
- DispatchQueue.main.async {
- guard let data else {
- self.onCancel()
- return
- }
- self.onPick(data, provider.suggestedName)
- }
- }
- }
+struct MessageInputView: View {
+ var body: some View {
+ Text("Input unavailable")
}
}
+#endif
-private struct DocumentPicker: UIViewControllerRepresentable {
- let onPick: (URL) -> Void
- let onCancel: () -> Void
-
- func makeCoordinator() -> Coordinator {
- Coordinator(onPick: onPick, onCancel: onCancel)
- }
-
- func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
- let picker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.data], asCopy: true)
- picker.delegate = context.coordinator
- picker.allowsMultipleSelection = false
- return picker
- }
-
- func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {}
-
- final class Coordinator: NSObject, UIDocumentPickerDelegate {
- private let onPick: (URL) -> Void
- private let onCancel: () -> Void
-
- init(onPick: @escaping (URL) -> Void, onCancel: @escaping () -> Void) {
- self.onPick = onPick
- self.onCancel = onCancel
- }
-
- func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
- guard let url = urls.first else {
- onCancel()
- return
- }
- onPick(url)
- }
-
- func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
- onCancel()
- }
- }
-}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift
index 56b85febe6..267366ec91 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/MessageListView.swift
@@ -1,3 +1,4 @@
+#if canImport(EnteCore)
import SwiftUI
import QuickLook
#if os(iOS)
@@ -9,6 +10,9 @@ struct MessageListView: View {
let streamingResponse: String
let streamingParentId: UUID?
let isGenerating: Bool
+ let keyboardHeight: CGFloat
+ let emptyStateTitle: String
+ let emptyStateSubtitle: String?
let onEdit: (ChatMessage) -> Void
let onCopy: (ChatMessage) -> Void
let onRetry: (ChatMessage) -> Void
@@ -18,6 +22,7 @@ struct MessageListView: View {
@State private var autoScrollEnabled = true
@State private var previewItem: AttachmentPreviewItem?
@State private var lastHapticLength = 0
+ @State private var wasAtBottomBeforeKeyboard = false
#if os(iOS)
@State private var haptic = UIImpactFeedbackGenerator(style: .medium)
#endif
@@ -28,10 +33,18 @@ struct MessageListView: View {
ScrollView {
LazyVStack(alignment: .leading, spacing: EnsuSpacing.lg) {
if messages.isEmpty && !isGenerating {
- Text("Start typing to begin a conversation")
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textMuted)
- .frame(maxWidth: .infinity, minHeight: proxy.size.height * 0.6)
+ VStack(spacing: EnsuSpacing.sm) {
+ Text(emptyStateTitle)
+ .font(EnsuTypography.large)
+ .foregroundStyle(EnsuColor.textPrimary)
+ if let emptyStateSubtitle {
+ Text(emptyStateSubtitle)
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textMuted)
+ }
+ }
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: .infinity, minHeight: proxy.size.height * 0.6)
}
ForEach(messages) { message in
@@ -105,6 +118,18 @@ struct MessageListView: View {
#endif
scrollToBottom(scrollProxy)
}
+ .onChange(of: keyboardHeight) { newValue in
+ if newValue > 0 {
+ wasAtBottomBeforeKeyboard = isAtBottom
+ }
+ if wasAtBottomBeforeKeyboard {
+ autoScrollEnabled = true
+ scrollToBottom(scrollProxy, force: true)
+ }
+ if newValue == 0 {
+ wasAtBottomBeforeKeyboard = false
+ }
+ }
.onChange(of: isGenerating) { newValue in
if newValue {
autoScrollEnabled = true
@@ -161,6 +186,7 @@ private struct AttachmentPreviewItem: Identifiable {
var id: String { url.path }
}
+#if os(iOS)
private struct QuickLookPreview: UIViewControllerRepresentable {
let url: URL
@@ -195,6 +221,22 @@ private struct QuickLookPreview: UIViewControllerRepresentable {
}
}
}
+#elseif os(macOS)
+private struct QuickLookPreview: NSViewRepresentable {
+ let url: URL
+
+ func makeNSView(context: Context) -> QLPreviewView {
+ let view = QLPreviewView(frame: .zero, style: .normal)
+ view.autostarts = true
+ view.previewItem = url as NSURL
+ return view
+ }
+
+ func updateNSView(_ nsView: QLPreviewView, context: Context) {
+ nsView.previewItem = url as NSURL
+ }
+}
+#endif
private struct UserMessageBubbleView: View {
let message: ChatMessage
@@ -204,38 +246,53 @@ private struct UserMessageBubbleView: View {
let onOpenAttachment: (ChatAttachment) -> Void
var body: some View {
+ let bubbleShape = RoundedRectangle(cornerRadius: 18, style: .continuous)
+
HStack(alignment: .bottom) {
Spacer(minLength: EnsuSpacing.messageBubbleInset)
VStack(alignment: .trailing, spacing: EnsuSpacing.sm) {
- if !message.attachments.isEmpty {
- FlowLayout(spacing: EnsuSpacing.sm) {
- ForEach(message.attachments) { attachment in
- AttachmentChip(
- name: attachment.name,
- size: attachment.formattedSize,
- icon: attachment.iconName,
- isUploading: attachment.isUploading
- )
- .onTapGesture {
- onOpenAttachment(attachment)
+ VStack(alignment: .trailing, spacing: EnsuSpacing.sm) {
+ if !message.attachments.isEmpty {
+ FlowLayout(spacing: EnsuSpacing.sm) {
+ ForEach(message.attachments) { attachment in
+ AttachmentChip(
+ name: attachment.name,
+ size: attachment.formattedSize,
+ icon: attachment.iconName,
+ isUploading: attachment.isUploading
+ )
+ .onTapGesture {
+ hapticTap()
+ onOpenAttachment(attachment)
+ }
}
}
+ .frame(maxWidth: .infinity, alignment: .trailing)
}
- .frame(maxWidth: .infinity, alignment: .trailing)
- }
- Text(message.text)
- .font(EnsuTypography.message)
- .foregroundStyle(EnsuColor.userMessageText)
- .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))
- .multilineTextAlignment(.trailing)
- .textSelection(.enabled)
-
- HStack(spacing: EnsuSpacing.xs) {
- ActionButton(icon: "pencil", action: onEdit)
- ActionButton(icon: "doc.on.doc", action: onCopy)
+ Text(message.text)
+ .font(EnsuTypography.message)
+ .foregroundStyle(EnsuColor.userMessageText)
+ .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))
+ .multilineTextAlignment(.trailing)
+ .textSelection(.enabled)
+ }
+ .padding(EnsuSpacing.md)
+ .background(EnsuColor.border.opacity(0.2))
+ .clipShape(bubbleShape)
+ #if os(iOS)
+ .contextMenu {
+ Button("Edit") {
+ hapticTap()
+ onEdit()
+ }
+ Button("Copy") {
+ hapticTap()
+ onCopy()
+ }
}
+ #endif
HStack(spacing: EnsuSpacing.sm) {
Spacer()
@@ -262,21 +319,35 @@ private struct AssistantMessageBubbleView: View {
let onOpenAttachment: (ChatAttachment) -> Void
var body: some View {
+ let bubbleShape = RoundedRectangle(cornerRadius: 18, style: .continuous)
+
HStack(alignment: .bottom) {
VStack(alignment: .leading, spacing: EnsuSpacing.sm) {
- AssistantMessageRenderer(text: message.text, isStreaming: false, storageId: message.id.uuidString)
-
- if message.isInterrupted {
- Text("Interrupted")
- .font(EnsuTypography.small)
- .italic()
- .foregroundStyle(EnsuColor.textMuted)
+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {
+ AssistantMessageRenderer(text: message.text, isStreaming: false, storageId: message.id.uuidString)
+
+ if message.isInterrupted {
+ Text("Interrupted")
+ .font(EnsuTypography.small)
+ .italic()
+ .foregroundStyle(EnsuColor.textMuted)
+ }
}
-
- HStack(spacing: EnsuSpacing.xs) {
- ActionButton(icon: "doc.on.doc", action: onCopy)
- ActionButton(icon: "arrow.clockwise", action: onRetry)
+ .padding(EnsuSpacing.md)
+ .background(EnsuColor.border.opacity(0.2))
+ .clipShape(bubbleShape)
+ #if os(iOS)
+ .contextMenu {
+ Button("Copy") {
+ hapticTap()
+ onCopy()
+ }
+ Button("Retry") {
+ hapticMedium()
+ onRetry()
+ }
}
+ #endif
HStack(spacing: EnsuSpacing.sm) {
TimestampView(date: message.timestamp)
@@ -302,24 +373,31 @@ private struct StreamingBubbleView: View {
@State private var cursorOpacity: Double = 1
var body: some View {
+ let bubbleShape = RoundedRectangle(cornerRadius: 18, style: .continuous)
+
HStack(alignment: .bottom) {
VStack(alignment: .leading, spacing: EnsuSpacing.sm) {
- if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
- LoadingDotsView()
- } else {
- HStack(alignment: .bottom, spacing: 4) {
- AssistantMessageRenderer(text: text, isStreaming: true, storageId: UUID().uuidString)
- Rectangle()
- .fill(EnsuColor.accent)
- .frame(width: 2, height: 18)
- .opacity(cursorOpacity)
- .onAppear {
- withAnimation(.easeInOut(duration: 0.53).repeatForever(autoreverses: true)) {
- cursorOpacity = 0
+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {
+ if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ LoadingDotsView()
+ } else {
+ HStack(alignment: .bottom, spacing: 4) {
+ AssistantMessageRenderer(text: text, isStreaming: true, storageId: UUID().uuidString)
+ Rectangle()
+ .fill(EnsuColor.accent)
+ .frame(width: 2, height: 18)
+ .opacity(cursorOpacity)
+ .onAppear {
+ withAnimation(.easeInOut(duration: 0.53).repeatForever(autoreverses: true)) {
+ cursorOpacity = 0
+ }
}
- }
+ }
}
}
+ .padding(EnsuSpacing.md)
+ .background(EnsuColor.border.opacity(0.2))
+ .clipShape(bubbleShape)
}
Spacer(minLength: EnsuSpacing.messageBubbleInset)
@@ -328,19 +406,59 @@ private struct StreamingBubbleView: View {
}
private struct LoadingDotsView: View {
+ @State private var phrase: String = LoadingDotsView.randomPhrase()
+
var body: some View {
TimelineView(.periodic(from: .now, by: 0.5)) { context in
let phase = Int(context.date.timeIntervalSinceReferenceDate * 2) % 3
- Text(dots(for: phase))
+ Text(phrase + dots(for: phase))
.font(EnsuTypography.message)
.foregroundStyle(EnsuColor.textMuted)
}
}
+ private static let loadingPhraseVerbs = [
+ "Generating",
+ "Thinking through",
+ "Assembling",
+ "Drafting",
+ "Composing",
+ "Crunching",
+ "Exploring",
+ "Piecing together",
+ "Reviewing",
+ "Organizing",
+ "Synthesizing",
+ "Sketching",
+ "Refining",
+ "Shaping"
+ ]
+
+ private static let loadingPhraseTargets = [
+ "your reply",
+ "an answer",
+ "ideas",
+ "context",
+ "details",
+ "the response",
+ "the next steps",
+ "a solution",
+ "the summary",
+ "insights",
+ "the draft",
+ "the explanation"
+ ]
+
+ private static func randomPhrase() -> String {
+ let verb = loadingPhraseVerbs.randomElement() ?? "Generating"
+ let target = loadingPhraseTargets.randomElement() ?? "your reply"
+ return "\(verb) \(target)"
+ }
+
private func dots(for phase: Int) -> String {
switch phase {
- case 0: return ". "
- case 1: return ".. "
+ case 0: return "."
+ case 1: return ".."
default: return "..."
}
}
@@ -767,10 +885,13 @@ private struct CodeBlockView: View {
}
Button {
+ hapticTap()
copyToPasteboard(code)
} label: {
- Image(systemName: "doc.on.doc")
- .font(.system(size: 14))
+ Image("Copy01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 14, height: 14)
.padding(6)
.background(EnsuColor.fillFaint.opacity(0.8))
.clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))
@@ -805,4 +926,13 @@ private struct BlockQuoteView: View {
.clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))
}
}
+#else
+import SwiftUI
+
+struct MessageListView: View {
+ var body: some View {
+ Text("Messages unavailable")
+ }
+}
+#endif
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Chat/SessionDrawerView.swift b/mobile/native/darwin/Apps/ensu/ensu/Chat/SessionDrawerView.swift
index 2c4f0be340..db71c951cf 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Chat/SessionDrawerView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Chat/SessionDrawerView.swift
@@ -1,3 +1,4 @@
+#if canImport(EnteCore)
import SwiftUI
struct SessionDrawerView: View {
@@ -9,10 +10,8 @@ struct SessionDrawerView: View {
let onSelectSession: (ChatSession) -> Void
let onDeleteSession: (ChatSession) -> Void
let onSync: () -> Void
- let onShowLogs: () -> Void
- let onShowModelSettings: () -> Void
+ let onOpenSettings: () -> Void
let onDeveloperTap: () -> Void
- let onDeveloperSettings: () -> Void
let onSignOut: () -> Void
let onSignIn: () -> Void
@@ -58,17 +57,10 @@ struct SessionDrawerView: View {
.onTapGesture {
onDeveloperTap()
}
- Spacer()
- }
- HStack(spacing: EnsuSpacing.sm) {
- if isLoggedIn {
- iconButton(symbol: "arrow.clockwise", action: onSync)
- }
- iconButton(symbol: "ladybug", action: onShowLogs)
- iconButton(symbol: "wrench.and.screwdriver", action: onDeveloperSettings)
- iconButton(symbol: "slider.horizontal.3", action: onShowModelSettings)
Spacer()
+
+ iconButton(symbol: "Settings01Icon", action: onOpenSettings)
}
if isLoggedIn, let email {
@@ -96,17 +88,23 @@ struct SessionDrawerView: View {
}
private var newChatTile: some View {
- Button(action: onNewChat) {
- HStack(spacing: EnsuSpacing.sm) {
- Image(systemName: "plus")
- Text("New Chat")
- .font(EnsuTypography.body)
+ HStack(spacing: EnsuSpacing.sm) {
+ drawerPrimaryTile(
+ icon: "PlusSignIcon",
+ title: "New Chat",
+ action: onNewChat
+ )
+
+ if isLoggedIn {
+ drawerPrimaryTile(
+ icon: "ArrowReloadHorizontalIcon",
+ title: "Sync",
+ action: onSync
+ )
}
- .foregroundStyle(EnsuColor.textPrimary)
- .padding(.horizontal, EnsuSpacing.lg)
- .padding(.vertical, EnsuSpacing.sm)
}
- .buttonStyle(.plain)
+ // Make the tiles take equal width (50/50) and keep some space between.
+ .padding(.horizontal, EnsuSpacing.lg)
}
private func sessionTile(_ session: ChatSession) -> some View {
@@ -121,7 +119,7 @@ struct SessionDrawerView: View {
.lineLimit(1)
}
Spacer()
- ActionButton(icon: "trash", color: EnsuColor.textMuted) {
+ ActionButton(icon: "Delete01Icon", color: EnsuColor.textMuted) {
onDeleteSession(session)
}
}
@@ -129,6 +127,7 @@ struct SessionDrawerView: View {
.padding(.vertical, EnsuSpacing.sm)
.contentShape(Rectangle())
.onTapGesture {
+ hapticTap()
onSelectSession(session)
}
}
@@ -136,13 +135,19 @@ struct SessionDrawerView: View {
private var footer: some View {
HStack {
if isLoggedIn {
- Button("Sign Out", action: onSignOut)
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
+ Button("Sign Out") {
+ hapticWarning()
+ onSignOut()
+ }
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textPrimary)
} else {
- Button("Sign In to Backup", action: onSignIn)
- .font(EnsuTypography.body)
- .foregroundStyle(EnsuColor.textPrimary)
+ Button("Sign In to Backup") {
+ hapticTap()
+ onSignIn()
+ }
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textPrimary)
}
Spacer()
}
@@ -150,15 +155,45 @@ struct SessionDrawerView: View {
}
private func iconButton(symbol: String, action: @escaping () -> Void) -> some View {
- Button(action: action) {
- Image(systemName: symbol)
- .font(.system(size: 18))
+ Button(action: {
+ hapticTap()
+ action()
+ }) {
+ Image(symbol)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 18, height: 18)
.frame(width: 40, height: 40)
.foregroundStyle(EnsuColor.textPrimary)
}
.buttonStyle(.plain)
}
+ private func drawerPrimaryTile(icon: String, title: String, action: @escaping () -> Void) -> some View {
+ Button(action: {
+ hapticTap()
+ action()
+ }) {
+ HStack(spacing: EnsuSpacing.sm) {
+ Image(icon)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 18, height: 18)
+
+ Text(title)
+ .font(EnsuTypography.body)
+ }
+ .foregroundStyle(EnsuColor.textPrimary)
+ .frame(maxWidth: .infinity)
+ .padding(.horizontal, EnsuSpacing.lg)
+ .padding(.vertical, EnsuSpacing.md)
+ .background(EnsuColor.fillFaint)
+ .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))
+ }
+ .buttonStyle(.plain)
+ .frame(maxWidth: .infinity)
+ }
+
private var sectionedSessions: [SessionSection] {
let grouped = Dictionary(grouping: sessions) { session in
sectionTitle(for: session.updatedAt)
@@ -189,3 +224,12 @@ private struct SessionSection: Identifiable {
let title: String
let sessions: [ChatSession]
}
+#else
+import SwiftUI
+
+struct SessionDrawerView: View {
+ var body: some View {
+ Text("Sessions unavailable")
+ }
+}
+#endif
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Components/AuthComponents.swift b/mobile/native/darwin/Apps/ensu/ensu/Components/AuthComponents.swift
index a559408e77..df51827f5b 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Components/AuthComponents.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Components/AuthComponents.swift
@@ -115,7 +115,10 @@ struct PasswordTextField: View {
Button {
showPassword.toggle()
} label: {
- Image(systemName: showPassword ? "eye.slash" : "eye")
+ Image(showPassword ? "ViewOffSlashIcon" : "ViewIcon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 18, height: 18)
.foregroundStyle(EnsuColor.textMuted)
}
}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Components/EnsuComponents.swift b/mobile/native/darwin/Apps/ensu/ensu/Components/EnsuComponents.swift
index f695f10859..834629077b 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Components/EnsuComponents.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Components/EnsuComponents.swift
@@ -7,7 +7,10 @@ struct PrimaryButton: View {
let action: () -> Void
var body: some View {
- Button(action: action) {
+ Button(action: {
+ hapticMedium()
+ action()
+ }) {
ZStack {
if isLoading {
ProgressView()
@@ -35,7 +38,10 @@ struct TextLink: View {
let action: () -> Void
var body: some View {
- Button(action: action) {
+ Button(action: {
+ hapticTap()
+ action()
+ }) {
Text(text)
.font(EnsuFont.ui(size: 14, weight: .semibold))
.underline()
@@ -47,15 +53,28 @@ struct TextLink: View {
struct ActionButton: View {
let icon: String
+ var isSystemSymbol: Bool = false
var tooltip: String? = nil
var color: Color = EnsuColor.textMuted
let action: () -> Void
var body: some View {
- Button(action: action) {
- Image(systemName: icon)
- .font(.system(size: 16, weight: .regular))
- .frame(width: 36, height: 36)
+ Button(action: {
+ hapticTap()
+ action()
+ }) {
+ Group {
+ if isSystemSymbol {
+ Image(systemName: icon)
+ .font(.system(size: 16, weight: .regular))
+ } else {
+ Image(icon)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 16, height: 16)
+ }
+ }
+ .frame(width: 36, height: 36)
}
.buttonStyle(ActionButtonStyle(color: color))
.accessibilityLabel(tooltip ?? "")
@@ -69,7 +88,10 @@ struct TextActionButton: View {
@Environment(\.isEnabled) private var isEnabled
var body: some View {
- Button(action: action) {
+ Button(action: {
+ hapticTap()
+ action()
+ }) {
Text(text)
.font(EnsuTypography.small)
.foregroundStyle(isEnabled ? EnsuColor.textMuted : EnsuColor.textMuted.opacity(0.4))
@@ -102,8 +124,10 @@ struct AttachmentChip: View {
var body: some View {
HStack(spacing: 8) {
- Image(systemName: icon)
- .font(.system(size: 14))
+ Image(icon)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 14, height: 14)
.foregroundStyle(EnsuColor.textMuted)
VStack(alignment: .leading, spacing: 2) {
@@ -124,9 +148,14 @@ struct AttachmentChip: View {
}
if let onDelete {
- Button(action: onDelete) {
- Image(systemName: "xmark")
- .font(.system(size: 10, weight: .semibold))
+ Button(action: {
+ hapticTap()
+ onDelete()
+ }) {
+ Image("Cancel01Icon")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 10, height: 10)
.padding(4)
}
.buttonStyle(.plain)
diff --git a/mobile/native/darwin/Apps/ensu/ensu/EnsuApp.swift b/mobile/native/darwin/Apps/ensu/ensu/EnsuApp.swift
index 4a2fdf2fdf..6ad9c91054 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/EnsuApp.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/EnsuApp.swift
@@ -5,6 +5,10 @@ struct EnsuApp: App {
@StateObject private var appState = EnsuAppState()
@StateObject private var deepLinkRouter = DeepLinkRouter()
+ init() {
+ EnsuLogging.shared.start()
+ }
+
var body: some Scene {
WindowGroup {
RootView()
diff --git a/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift b/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift
index 1c8842c04d..f71911039c 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/ModelSettings/ModelSettingsView.swift
@@ -8,11 +8,13 @@ struct ModelSettingsView: View {
@State private var mmprojUrl: String = ""
@State private var contextLength: String = ""
@State private var maxTokens: String = ""
+ @State private var temperature: String = ""
@State private var urlError: String?
@State private var mmprojError: String?
@State private var contextError: String?
@State private var maxTokensError: String?
+ @State private var temperatureError: String?
@State private var isSaving = false
private let suggestedModels: [SuggestedModel] = [
@@ -61,6 +63,7 @@ struct ModelSettingsView: View {
mmprojUrl = settings.mmprojUrl
contextLength = settings.contextLength
maxTokens = settings.maxTokens
+ temperature = settings.temperature
}
#if os(macOS)
.safeAreaInset(edge: .top) {
@@ -170,6 +173,14 @@ struct ModelSettingsView: View {
.font(EnsuTypography.small)
.foregroundStyle(EnsuColor.textMuted)
.frame(maxWidth: .infinity, alignment: .leading)
+
+ field(
+ label: "Temperature",
+ hint: "0.7",
+ text: $temperature,
+ error: temperatureError,
+ keyboardType: .decimalPad
+ )
}
Divider().background(EnsuColor.border)
@@ -262,6 +273,7 @@ struct ModelSettingsView: View {
mmprojError = nil
contextError = nil
maxTokensError = nil
+ temperatureError = nil
guard validate() else { return }
@@ -271,7 +283,8 @@ struct ModelSettingsView: View {
url: modelUrl,
mmproj: mmprojUrl,
contextLength: contextLength,
- maxTokens: maxTokens
+ maxTokens: maxTokens,
+ temperature: temperature
)
isSaving = false
}
@@ -283,6 +296,7 @@ struct ModelSettingsView: View {
mmprojUrl = ""
contextLength = ""
maxTokens = ""
+ temperature = ""
}
private func validate() -> Bool {
@@ -308,6 +322,11 @@ struct ModelSettingsView: View {
isValid = false
}
+ if !temperature.isEmpty, Float(temperature) == nil {
+ temperatureError = "Enter a valid number"
+ isValid = false
+ }
+
if let contextValue = Int(contextLength), let maxValue = Int(maxTokens), maxValue > contextValue {
maxTokensError = "Must be <= context length"
isValid = false
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAuthService.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAuthService.swift
index 84c77a2d5a..cdb22f0f85 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAuthService.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/EnsuAuthService.swift
@@ -27,6 +27,7 @@ struct AuthResponsePayload: Hashable {
final class EnsuAuthService {
static let shared = EnsuAuthService()
+ private let logger = EnsuLogging.shared.logger("EnsuAuthService")
private let tokenProvider = EnsuAuthTokenProvider()
private var networkFactory: NetworkFactory
@@ -43,13 +44,17 @@ final class EnsuAuthService {
)
// Initialise Rust crypto backend once (no-op for pure Rust, but keeps parity).
- // Ignore errors here and surface them when actually used.
- try? initCrypto()
+ do {
+ try initCrypto()
+ } catch {
+ logger.error("Crypto init failed", error)
+ }
}
// MARK: - Network
func updateEndpoint(_ endpoint: URL?) {
+ logger.info("Updated endpoint", details: endpoint?.absoluteString ?? "default")
EnsuDeveloperSettings.setEndpoint(endpoint)
networkFactory = NetworkFactory(
configuration: EnsuDeveloperSettings.networkConfiguration,
@@ -103,73 +108,84 @@ final class EnsuAuthService {
// MARK: - SRP Login
func loginWithSrp(email: String, password: String, srpAttributes: SrpAttributes) async throws -> SrpLoginResult {
+ logger.info("SRP login started")
defer { srpClear() }
- // 1) Start SRP (heavy crypto)
- let start = try await Task.detached(priority: .userInitiated) {
- try srpStart(password: password, srpAttrs: srpAttributes)
- }.value
-
- // 2) Create SRP session
- let session = try await networkFactory.authentication.createSRPSession(
- srpUserID: srpAttributes.srpUserId,
- clientPub: start.srpA
- )
-
- // 3) Finish SRP
- let verify = try await Task.detached(priority: .userInitiated) {
- try srpFinish(srpB: session.srpB)
- }.value
+ do {
+ // 1) Start SRP (heavy crypto)
+ let start = try await Task.detached(priority: .userInitiated) {
+ try srpStart(password: password, srpAttrs: srpAttributes)
+ }.value
+
+ // 2) Create SRP session
+ let session = try await networkFactory.authentication.createSRPSession(
+ srpUserID: srpAttributes.srpUserId,
+ clientPub: start.srpA
+ )
- // 4) Verify SRP session
- let authResponse = try await networkFactory.authentication.verifySRPSession(
- srpUserID: srpAttributes.srpUserId,
- sessionID: session.sessionID,
- clientM1: verify.srpM1
- )
+ // 3) Finish SRP
+ let verify = try await Task.detached(priority: .userInitiated) {
+ try srpFinish(srpB: session.srpB)
+ }.value
- // If additional auth factors are required, return the session IDs.
- let passkeySessionId = (authResponse.passkeySessionID?.isEmpty == false) ? authResponse.passkeySessionID : nil
- let twoFactorSessionId = (authResponse.effectiveTwoFactorSessionID?.isEmpty == false) ? authResponse.effectiveTwoFactorSessionID : nil
- if passkeySessionId != nil || twoFactorSessionId != nil {
- return SrpLoginResult(
- twoFactorSessionId: twoFactorSessionId,
- passkeySessionId: passkeySessionId,
- accountsUrl: (authResponse.accountsUrl?.isEmpty == false) ? authResponse.accountsUrl : accountsUrlFallback
+ // 4) Verify SRP session
+ let authResponse = try await networkFactory.authentication.verifySRPSession(
+ srpUserID: srpAttributes.srpUserId,
+ sessionID: session.sessionID,
+ clientM1: verify.srpM1
)
- }
- // 5) Decrypt secrets using the KEK derived in srpStart
- guard let keyAttrsNet = authResponse.keyAttributes else {
- throw EnteError.invalidResponse
- }
+ // If additional auth factors are required, return the session IDs.
+ let passkeySessionId = (authResponse.passkeySessionID?.isEmpty == false) ? authResponse.passkeySessionID : nil
+ let twoFactorSessionId = (authResponse.effectiveTwoFactorSessionID?.isEmpty == false) ? authResponse.effectiveTwoFactorSessionID : nil
+ if passkeySessionId != nil || twoFactorSessionId != nil {
+ logger.info(
+ "SRP login requires additional auth",
+ details: "2fa=\(twoFactorSessionId != nil) passkey=\(passkeySessionId != nil)"
+ )
+ return SrpLoginResult(
+ twoFactorSessionId: twoFactorSessionId,
+ passkeySessionId: passkeySessionId,
+ accountsUrl: (authResponse.accountsUrl?.isEmpty == false) ? authResponse.accountsUrl : accountsUrlFallback
+ )
+ }
- let keyAttrs = KeyAttributes(
- kekSalt: keyAttrsNet.kekSalt,
- encryptedKey: keyAttrsNet.encryptedKey,
- keyDecryptionNonce: keyAttrsNet.keyDecryptionNonce,
- publicKey: keyAttrsNet.publicKey,
- encryptedSecretKey: keyAttrsNet.encryptedSecretKey,
- secretKeyDecryptionNonce: keyAttrsNet.secretKeyDecryptionNonce,
- memLimit: UInt32(keyAttrsNet.memLimit),
- opsLimit: UInt32(keyAttrsNet.opsLimit)
- )
+ // 5) Decrypt secrets using the KEK derived in srpStart
+ guard let keyAttrsNet = authResponse.keyAttributes else {
+ throw EnteError.invalidResponse
+ }
- let secrets = try await Task.detached(priority: .userInitiated) {
- try srpDecryptSecrets(
- keyAttrs: keyAttrs,
- encryptedToken: authResponse.encryptedToken,
- plainToken: authResponse.token
+ let keyAttrs = KeyAttributes(
+ kekSalt: keyAttrsNet.kekSalt,
+ encryptedKey: keyAttrsNet.encryptedKey,
+ keyDecryptionNonce: keyAttrsNet.keyDecryptionNonce,
+ publicKey: keyAttrsNet.publicKey,
+ encryptedSecretKey: keyAttrsNet.encryptedSecretKey,
+ secretKeyDecryptionNonce: keyAttrsNet.secretKeyDecryptionNonce,
+ memLimit: UInt32(keyAttrsNet.memLimit),
+ opsLimit: UInt32(keyAttrsNet.opsLimit)
)
- }.value
- try storeSecrets(
- email: email,
- userId: authResponse.id.rawValue,
- secrets: secrets
- )
+ let secrets = try await Task.detached(priority: .userInitiated) {
+ try srpDecryptSecrets(
+ keyAttrs: keyAttrs,
+ encryptedToken: authResponse.encryptedToken,
+ plainToken: authResponse.token
+ )
+ }.value
+
+ try storeSecrets(
+ email: email,
+ userId: authResponse.id.rawValue,
+ secrets: secrets
+ )
- return SrpLoginResult(twoFactorSessionId: nil, passkeySessionId: nil, accountsUrl: nil)
+ logger.info("SRP login success")
+ return SrpLoginResult(twoFactorSessionId: nil, passkeySessionId: nil, accountsUrl: nil)
+ } catch {
+ logger.error("SRP login failed", error)
+ throw error
+ }
}
// MARK: - Continuation (email MFA / 2FA / passkeys)
@@ -183,6 +199,7 @@ final class EnsuAuthService {
encryptedToken: String?,
token: String?
) async throws {
+ logger.info("Login after challenge started")
var kek = try await Task.detached(priority: .userInitiated) {
try deriveKekForLogin(
password: password,
@@ -206,6 +223,7 @@ final class EnsuAuthService {
}.value
try storeSecrets(email: email, userId: userId, secrets: secrets)
+ logger.info("Login after challenge success")
}
// MARK: - Storage
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift
index 09ac410ff6..ccd5e5e985 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceRsProvider.swift
@@ -1,4 +1,48 @@
import Foundation
+
+struct InferenceModelTarget: Equatable {
+ let id: String
+ let url: String
+ let mmprojUrl: String?
+ let contextLength: Int?
+ let maxTokens: Int?
+}
+
+struct InferenceDownloadProgress: Equatable {
+ let percent: Int
+ let status: String
+}
+
+enum InferenceMessageRole {
+ case user
+ case assistant
+ case system
+
+ var roleString: String {
+ switch self {
+ case .user:
+ return "user"
+ case .assistant:
+ return "assistant"
+ case .system:
+ return "system"
+ }
+ }
+}
+
+struct InferenceMessage {
+ let text: String
+ let role: InferenceMessageRole
+ let hasAttachments: Bool
+}
+
+struct InferenceGenerationSummary {
+ let jobId: Int64
+ let generatedTokens: Int
+ let totalTimeMs: Int64?
+}
+
+#if canImport(InferenceRS)
import CryptoKit
import InferenceRS
@@ -100,7 +144,7 @@ final class InferenceRsProvider {
}
let nativeMessages = messages.map {
- InferenceRS.ChatMessage(role: $0.isUser ? "user" : "assistant", content: $0.text)
+ InferenceRS.ChatMessage(role: $0.role.roleString, content: $0.text)
}
let mmprojPath = imageFiles.isEmpty ? nil : mmprojPathFor(target: target)?.path
@@ -184,6 +228,48 @@ final class InferenceRsProvider {
currentDownloadTask?.cancel()
}
+ func isModelDownloaded(target: InferenceModelTarget) -> Bool {
+ let modelPath = modelPathFor(target: target)
+ if !FileManager.default.fileExists(atPath: modelPath.path) {
+ return false
+ }
+ if let mmprojPath = mmprojPathFor(target: target),
+ let mmprojUrl = target.mmprojUrl,
+ !mmprojUrl.isEmpty,
+ !FileManager.default.fileExists(atPath: mmprojPath.path) {
+ return false
+ }
+ return true
+ }
+
+ func estimatedDownloadSize(target: InferenceModelTarget) async -> Int64? {
+ let modelPath = modelPathFor(target: target)
+ let mmprojPath = mmprojPathFor(target: target)
+ let modelSize: Int64?
+ if FileManager.default.fileExists(atPath: modelPath.path) {
+ modelSize = fileSize(modelPath)
+ } else {
+ modelSize = await fetchContentLength(for: target.url)
+ }
+
+ let mmprojSize: Int64?
+ if let mmprojUrl = target.mmprojUrl, !mmprojUrl.isEmpty, let mmprojPath {
+ if FileManager.default.fileExists(atPath: mmprojPath.path) {
+ mmprojSize = fileSize(mmprojPath)
+ } else {
+ mmprojSize = await fetchContentLength(for: mmprojUrl)
+ }
+ } else {
+ mmprojSize = nil
+ }
+
+ let sizes = [modelSize, mmprojSize].compactMap { $0 }.filter { $0 > 0 }
+ if sizes.isEmpty {
+ return nil
+ }
+ return sizes.reduce(0, +)
+ }
+
private func unloadModel() {
contextHandle = nil
modelHandle = nil
@@ -221,81 +307,134 @@ final class InferenceRsProvider {
throw NSError(domain: "InferenceRsProvider", code: -7, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])
}
- var request = URLRequest(url: url)
- request.httpMethod = "GET"
+ let tmp = destination.appendingPathExtension("tmp")
+ var existing = fileSize(tmp)
+ if existing > 0, !looksLikeGguf(file: tmp) {
+ try? FileManager.default.removeItem(at: tmp)
+ existing = 0
+ }
- let (bytes, response) = try await URLSession.shared.bytes(for: request)
- currentDownloadTask = bytes.task
+ var shouldResume = existing > 0
- if let http = response as? HTTPURLResponse, !(200...299).contains(http.statusCode) {
- throw NSError(
- domain: "InferenceRsProvider",
- code: -9,
- userInfo: [NSLocalizedDescriptionKey: "Download failed (HTTP \(http.statusCode))"]
- )
- }
+ while true {
+ var request = URLRequest(url: url)
+ request.httpMethod = "GET"
+ if shouldResume {
+ request.setValue("bytes=\(existing)-", forHTTPHeaderField: "Range")
+ }
- var totalBytes: Int64? = response.expectedContentLength > 0 ? response.expectedContentLength : nil
- if totalBytes == nil, let http = response as? HTTPURLResponse,
- let lengthHeader = http.value(forHTTPHeaderField: "Content-Length"),
- let length = Int64(lengthHeader) {
- totalBytes = length
- }
+ let (bytes, response) = try await URLSession.shared.bytes(for: request)
+ currentDownloadTask = bytes.task
- try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)
- let tmp = destination.appendingPathExtension("tmp")
- if FileManager.default.fileExists(atPath: tmp.path) {
- try FileManager.default.removeItem(at: tmp)
- }
- FileManager.default.createFile(atPath: tmp.path, contents: nil)
- let handle = try FileHandle(forWritingTo: tmp)
+ let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
+ if shouldResume, statusCode == 200 {
+ try? FileManager.default.removeItem(at: tmp)
+ existing = 0
+ shouldResume = false
+ continue
+ }
- var buffer = [UInt8]()
- buffer.reserveCapacity(64 * 1024)
- var downloaded: Int64 = 0
- var lastProgressUpdate: Int64 = 0
- let updateThreshold: Int64 = 512 * 1024
+ if !(200...299).contains(statusCode) {
+ throw NSError(
+ domain: "InferenceRsProvider",
+ code: -9,
+ userInfo: [NSLocalizedDescriptionKey: "Download failed (HTTP \(statusCode))"]
+ )
+ }
- defer {
- currentDownloadTask = nil
- }
+ var totalBytes: Int64?
+ if shouldResume, statusCode == 206,
+ let contentRange = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Range") {
+ totalBytes = parseTotalBytes(from: contentRange)
+ }
+
+ if totalBytes == nil {
+ let expected = response.expectedContentLength
+ if expected > 0 {
+ totalBytes = shouldResume && statusCode == 206 ? expected + existing : expected
+ }
+ }
- for try await byte in bytes {
- if downloadCancelled {
- try? handle.close()
+ if let totalBytes, totalBytes <= existing {
try? FileManager.default.removeItem(at: tmp)
- throw CancellationError()
+ existing = 0
+ shouldResume = false
+ continue
+ }
+
+ try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)
+
+ let handle: FileHandle
+ if shouldResume, statusCode == 206, FileManager.default.fileExists(atPath: tmp.path) {
+ handle = try FileHandle(forWritingTo: tmp)
+ try handle.seekToEnd()
+ } else {
+ if FileManager.default.fileExists(atPath: tmp.path) {
+ try FileManager.default.removeItem(at: tmp)
+ }
+ FileManager.default.createFile(atPath: tmp.path, contents: nil)
+ handle = try FileHandle(forWritingTo: tmp)
}
- buffer.append(byte)
- downloaded += 1
+ var buffer = [UInt8]()
+ buffer.reserveCapacity(64 * 1024)
+ var downloaded: Int64 = existing
+ var lastProgressUpdate: Int64 = existing
+ let updateThreshold: Int64 = 512 * 1024
+
+ defer {
+ currentDownloadTask = nil
+ }
+
+ for try await byte in bytes {
+ if downloadCancelled {
+ try? handle.close()
+ try? FileManager.default.removeItem(at: tmp)
+ throw CancellationError()
+ }
+
+ buffer.append(byte)
+ downloaded += 1
+
+ if buffer.count >= 64 * 1024 {
+ handle.write(Data(buffer))
+ buffer.removeAll(keepingCapacity: true)
+ }
+
+ if downloaded - lastProgressUpdate >= updateThreshold {
+ lastProgressUpdate = downloaded
+ onProgress(downloaded, totalBytes)
+ }
+ }
- if buffer.count >= 64 * 1024 {
+ if !buffer.isEmpty {
handle.write(Data(buffer))
- buffer.removeAll(keepingCapacity: true)
}
+ try handle.close()
+ onProgress(downloaded, totalBytes)
- if downloaded - lastProgressUpdate >= updateThreshold {
- lastProgressUpdate = downloaded
- onProgress(downloaded, totalBytes)
+ if let totalBytes, downloaded < totalBytes {
+ try? FileManager.default.removeItem(at: tmp)
+ throw NSError(domain: "InferenceRsProvider", code: -10, userInfo: [NSLocalizedDescriptionKey: "Download incomplete"])
}
- }
- if !buffer.isEmpty {
- handle.write(Data(buffer))
- }
- try handle.close()
- onProgress(downloaded, totalBytes)
+ if !looksLikeGguf(file: tmp) {
+ try? FileManager.default.removeItem(at: tmp)
+ throw NSError(domain: "InferenceRsProvider", code: -6, userInfo: [NSLocalizedDescriptionKey: "Downloaded file is not GGUF"])
+ }
- if !looksLikeGguf(file: tmp) {
- try? FileManager.default.removeItem(at: tmp)
- throw NSError(domain: "InferenceRsProvider", code: -6, userInfo: [NSLocalizedDescriptionKey: "Downloaded file is not GGUF"])
+ if FileManager.default.fileExists(atPath: destination.path) {
+ try FileManager.default.removeItem(at: destination)
+ }
+ try FileManager.default.moveItem(at: tmp, to: destination)
+ return
}
+ }
- if FileManager.default.fileExists(atPath: destination.path) {
- try FileManager.default.removeItem(at: destination)
- }
- try FileManager.default.moveItem(at: tmp, to: destination)
+ private func parseTotalBytes(from contentRange: String) -> Int64? {
+ let parts = contentRange.split(separator: "/")
+ guard parts.count == 2 else { return nil }
+ return Int64(parts[1])
}
private func fetchContentLength(for urlString: String) async -> Int64? {
@@ -387,3 +526,52 @@ private final class CallbackSink: GenerateEventCallback, @unchecked Sendable {
handler(event)
}
}
+#else
+final class InferenceRsProvider {
+ init(modelDir: URL) {
+ _ = modelDir
+ }
+
+ func ensureModelReady(
+ target: InferenceModelTarget,
+ onProgress: @escaping (InferenceDownloadProgress) -> Void
+ ) async throws {
+ _ = target
+ _ = onProgress
+ throw NSError(domain: "InferenceRsProvider", code: -100, userInfo: [NSLocalizedDescriptionKey: "InferenceRS not available"])
+ }
+
+ func generateChat(
+ target: InferenceModelTarget,
+ messages: [InferenceMessage],
+ imageFiles: [URL],
+ temperature: Float,
+ maxTokens: Int,
+ onToken: @escaping (String) -> Void
+ ) async throws -> InferenceGenerationSummary {
+ _ = target
+ _ = messages
+ _ = imageFiles
+ _ = temperature
+ _ = maxTokens
+ _ = onToken
+ throw NSError(domain: "InferenceRsProvider", code: -101, userInfo: [NSLocalizedDescriptionKey: "InferenceRS not available"])
+ }
+
+ func stopGeneration() {}
+
+ func resetContext() {}
+
+ func cancelDownload() {}
+
+ func isModelDownloaded(target: InferenceModelTarget) -> Bool {
+ _ = target
+ return false
+ }
+
+ func estimatedDownloadSize(target: InferenceModelTarget) async -> Int64? {
+ _ = target
+ return nil
+ }
+}
+#endif
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceTypes.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceTypes.swift
index 36a3ff5381..b45a73a015 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceTypes.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/InferenceTypes.swift
@@ -1,26 +1 @@
-import Foundation
-
-struct InferenceModelTarget: Equatable {
- let id: String
- let url: String
- let mmprojUrl: String?
- let contextLength: Int?
- let maxTokens: Int?
-}
-
-struct InferenceDownloadProgress: Equatable {
- let percent: Int
- let status: String
-}
-
-struct InferenceMessage {
- let text: String
- let isUser: Bool
- let hasAttachments: Bool
-}
-
-struct InferenceGenerationSummary {
- let jobId: Int64
- let generatedTokens: Int
- let totalTimeMs: Int64?
-}
+// Types live in InferenceRsProvider.swift to support fallback builds.
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/Logging/EnsuLogging.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/Logging/EnsuLogging.swift
new file mode 100644
index 0000000000..73e91eb8ab
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/Logging/EnsuLogging.swift
@@ -0,0 +1,270 @@
+import Foundation
+
+enum EnsuLogLevel: String {
+ case info = "INFO"
+ case warning = "WARN"
+ case error = "ERROR"
+}
+
+struct EnsuLogEntry: Identifiable, Hashable {
+ let id = UUID()
+ let timestamp: Date
+ let level: EnsuLogLevel
+ let tag: String
+ let message: String
+ let details: String?
+}
+
+@MainActor
+final class EnsuLogStore: ObservableObject {
+ static let shared = EnsuLogStore()
+
+ @Published private(set) var entries: [EnsuLogEntry] = []
+
+ private init() {}
+
+ func add(_ entry: EnsuLogEntry, maxEntries: Int) {
+ entries.insert(entry, at: 0)
+ if entries.count > maxEntries {
+ entries = Array(entries.prefix(maxEntries))
+ }
+ }
+}
+
+final class EnsuLogging {
+ static let shared = EnsuLogging()
+
+ private let queue = DispatchQueue(label: "io.ente.ensu.logging")
+
+ private let dayFormatter: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.dateFormat = "yyyy-MM-dd"
+ return formatter
+ }()
+
+ private let lineFormatter: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
+ return formatter
+ }()
+
+ private var isStarted = false
+ private(set) var logsDirectory: URL!
+
+ private let maxLogFiles: Int
+ private let maxEntriesInMemory: Int
+
+ private init(maxLogFiles: Int = 5, maxEntriesInMemory: Int = 500) {
+ self.maxLogFiles = maxLogFiles
+ self.maxEntriesInMemory = maxEntriesInMemory
+ }
+
+ func start() {
+ guard !isStarted else { return }
+ isStarted = true
+
+ let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
+ let base = support ?? FileManager.default.temporaryDirectory
+ logsDirectory = base.appendingPathComponent("logs", isDirectory: true)
+
+ queue.async {
+ do {
+ try FileManager.default.createDirectory(at: self.logsDirectory, withIntermediateDirectories: true)
+ self.pruneOldLogFiles()
+ } catch {
+ // Best-effort: fallback to temp.
+ self.logsDirectory = FileManager.default.temporaryDirectory.appendingPathComponent("logs", isDirectory: true)
+ try? FileManager.default.createDirectory(at: self.logsDirectory, withIntermediateDirectories: true)
+ }
+
+ let details = self.buildSystemInfo()
+ self.log(level: .info, tag: "App", message: "Ensū started", details: details, error: nil)
+ }
+ }
+
+ func logger(_ tag: String) -> EnsuLogger {
+ EnsuLogger(tag: tag)
+ }
+
+ func log(level: EnsuLogLevel, tag: String, message: String, details: String? = nil, error: Error? = nil) {
+ start()
+
+ let safeMessage = EnsuLogSanitizer.sanitize(message) ?? ""
+ let safeDetails = EnsuLogSanitizer.sanitize(combineDetails(details: details, error: error))
+
+ let entry = EnsuLogEntry(
+ timestamp: Date(),
+ level: level,
+ tag: tag,
+ message: safeMessage,
+ details: safeDetails
+ )
+
+ Task { @MainActor in
+ EnsuLogStore.shared.add(entry, maxEntries: maxEntriesInMemory)
+ }
+
+ queue.async {
+ let line = self.formatLine(entry)
+ self.appendToFile(line)
+ }
+ }
+
+ func todayLogFileURL() -> URL {
+ start()
+ let name = "\(dayFormatter.string(from: Date())).txt"
+ return logsDirectory.appendingPathComponent(name)
+ }
+
+ func listLogFiles() -> [URL] {
+ start()
+ let urls = (try? FileManager.default.contentsOfDirectory(at: logsDirectory, includingPropertiesForKeys: nil)) ?? []
+ return urls
+ .filter { $0.pathExtension.lowercased() == "txt" }
+ .sorted { $0.lastPathComponent < $1.lastPathComponent }
+ }
+
+ func readLogText(fileURL: URL? = nil) -> String {
+ start()
+ let url = fileURL ?? todayLogFileURL()
+ return (try? String(contentsOf: url, encoding: .utf8)) ?? ""
+ }
+
+ func createLogsArchive() throws -> URL {
+ start()
+ let name = "ensu-logs-\(dayFormatter.string(from: Date()))-\(Int(Date().timeIntervalSince1970)).zip"
+ let dest = FileManager.default.temporaryDirectory.appendingPathComponent(name)
+ if FileManager.default.fileExists(atPath: dest.path) {
+ try? FileManager.default.removeItem(at: dest)
+ }
+
+ if #available(iOS 16.0, macOS 13.0, *) {
+ try FileManager.default.zipItem(at: logsDirectory, to: dest, shouldKeepParent: true)
+ return dest
+ }
+
+ // Fallback: concatenate logs into a single text file.
+ let fallback = dest.deletingPathExtension().appendingPathExtension("txt")
+ var combined = ""
+ for file in listLogFiles() {
+ combined += "\n===== \(file.lastPathComponent) =====\n"
+ combined += readLogText(fileURL: file)
+ }
+ try combined.write(to: fallback, atomically: true, encoding: .utf8)
+ return fallback
+ }
+
+ private func appendToFile(_ text: String) {
+ let url = todayLogFileURL()
+ if !FileManager.default.fileExists(atPath: url.path) {
+ FileManager.default.createFile(atPath: url.path, contents: nil)
+ }
+
+ do {
+ let handle = try FileHandle(forWritingTo: url)
+ try handle.seekToEnd()
+ if let data = text.data(using: .utf8) {
+ try handle.write(contentsOf: data)
+ }
+ try handle.close()
+ } catch {
+ // Best-effort: ignore.
+ }
+ }
+
+ private func pruneOldLogFiles() {
+ let files = listLogFiles()
+ guard files.count > maxLogFiles else { return }
+ let toDelete = files.prefix(files.count - maxLogFiles)
+ for file in toDelete {
+ try? FileManager.default.removeItem(at: file)
+ }
+ }
+
+ private func formatLine(_ entry: EnsuLogEntry) -> String {
+ let ts = lineFormatter.string(from: entry.timestamp)
+ let header = "[\(entry.tag)][\(entry.level.rawValue)] [\(ts)]"
+ var out = "\(header) \(entry.message)\n"
+ if let details = entry.details, !details.isEmpty {
+ for line in details.split(separator: "\n", omittingEmptySubsequences: false) {
+ out += "\(header) ⤷ \(line)\n"
+ }
+ }
+ return out
+ }
+
+ private func combineDetails(details: String?, error: Error?) -> String? {
+ var parts: [String] = []
+ if let details, !details.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ parts.append(details)
+ }
+ if let error {
+ parts.append("type: \(String(describing: type(of: error)))")
+ parts.append("error: \(error)")
+ parts.append("trace: \(Thread.callStackSymbols.joined(separator: "\n"))")
+ }
+ return parts.isEmpty ? nil : parts.joined(separator: "\n")
+ }
+
+ private func buildSystemInfo() -> String {
+ var lines: [String] = []
+
+ #if os(iOS)
+ let device = "\(ProcessInfo.processInfo.operatingSystemVersionString)"
+ lines.append("os: \(device)")
+ #elseif os(macOS)
+ lines.append("os: \(ProcessInfo.processInfo.operatingSystemVersionString)")
+ #endif
+
+ if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String,
+ let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
+ lines.append("app: \(version)+\(build)")
+ }
+ return lines.joined(separator: "\n")
+ }
+}
+
+struct EnsuLogger {
+ let tag: String
+
+ func info(_ message: String, details: String? = nil) {
+ EnsuLogging.shared.log(level: .info, tag: tag, message: message, details: details)
+ }
+
+ func warning(_ message: String, details: String? = nil) {
+ EnsuLogging.shared.log(level: .warning, tag: tag, message: message, details: details)
+ }
+
+ func error(_ message: String, _ error: Error? = nil, details: String? = nil) {
+ EnsuLogging.shared.log(level: .error, tag: tag, message: message, details: details, error: error)
+ }
+}
+
+private enum EnsuLogSanitizer {
+ private static let emailPattern = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
+ private static let bearerPattern = "(?i)bearer\\s+[A-Za-z0-9._-]+"
+ private static let keyValuePattern = "(?i)(token|authToken|accessToken|refreshToken|authorization|password|otp|secret|secretKey|masterKey|encryptedToken|srpA|srpB|srpM1|srpM2|kek)\\s*[:=]\\s*([^\\s,;]+)"
+ private static let queryPattern = "(?i)(token|key|sig|signature|auth|session|passkey|otp)=([^&\\s]+)"
+ private static let longBlobPattern = "[A-Za-z0-9+/=]{40,}"
+
+ static func sanitize(_ input: String?) -> String? {
+ guard let input, !input.isEmpty else { return input }
+ var out = input
+ out = out.replacingRegex(bearerPattern, with: "Bearer <redacted>")
+ out = out.replacingRegex(keyValuePattern, with: "$1=<redacted>")
+ out = out.replacingRegex(queryPattern, with: "$1=<redacted>")
+ out = out.replacingRegex(emailPattern, with: "<redacted-email>")
+ out = out.replacingRegex(longBlobPattern, with: "<redacted-blob>")
+ return out
+ }
+}
+
+private extension String {
+ func replacingRegex(_ pattern: String, with replacement: String) -> String {
+ guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return self }
+ let range = NSRange(startIndex..<endIndex, in: self)
+ return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replacement)
+ }
+}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift
index e25aa5ffc6..d8bae492f8 100644
--- a/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift
+++ b/mobile/native/darwin/Apps/ensu/ensu/Services/ModelSettingsStore.swift
@@ -19,6 +19,9 @@ final class ModelSettingsStore: ObservableObject {
@Published var maxTokens: String {
didSet { persist() }
}
+ @Published var temperature: String {
+ didSet { persist() }
+ }
private let defaults = UserDefaults.standard
@@ -28,14 +31,16 @@ final class ModelSettingsStore: ObservableObject {
self.mmprojUrl = defaults.string(forKey: Keys.mmprojUrl) ?? ""
self.contextLength = defaults.string(forKey: Keys.contextLength) ?? ""
self.maxTokens = defaults.string(forKey: Keys.maxTokens) ?? ""
+ self.temperature = defaults.string(forKey: Keys.temperature) ?? ""
}
- func saveCustomModel(url: String, mmproj: String, contextLength: String, maxTokens: String) {
+ func saveCustomModel(url: String, mmproj: String, contextLength: String, maxTokens: String, temperature: String) {
useCustomModel = true
modelUrl = url
mmprojUrl = mmproj
self.contextLength = contextLength
self.maxTokens = maxTokens
+ self.temperature = temperature
}
func resetToDefault() {
@@ -44,6 +49,7 @@ final class ModelSettingsStore: ObservableObject {
mmprojUrl = ""
contextLength = ""
maxTokens = ""
+ temperature = ""
}
func currentTarget() -> InferenceModelTarget {
@@ -66,6 +72,7 @@ final class ModelSettingsStore: ObservableObject {
defaults.set(mmprojUrl, forKey: Keys.mmprojUrl)
defaults.set(contextLength, forKey: Keys.contextLength)
defaults.set(maxTokens, forKey: Keys.maxTokens)
+ defaults.set(temperature, forKey: Keys.temperature)
}
private enum Keys {
@@ -74,6 +81,7 @@ final class ModelSettingsStore: ObservableObject {
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"
}
private enum Defaults {
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Settings/LogsView.swift b/mobile/native/darwin/Apps/ensu/ensu/Settings/LogsView.swift
new file mode 100644
index 0000000000..d141fb7c03
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Settings/LogsView.swift
@@ -0,0 +1,165 @@
+import SwiftUI
+
+struct LogsView: View {
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var selectedFile: URL?
+ @State private var logText: String = ""
+
+ @State private var presentingShare = false
+ @State private var presentingExport = false
+ @State private var archiveURL: URL?
+
+ private let logger = EnsuLogging.shared.logger("LogsView")
+
+ var body: some View {
+ NavigationStack {
+ VStack(spacing: 0) {
+ content
+ }
+ .background(EnsuColor.backgroundBase)
+ .navigationTitle("Logs")
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button("Close") { dismiss() }
+ }
+ ToolbarItem(placement: .primaryAction) {
+ Menu {
+ Button("Share") { shareTapped() }
+ Button("Export") { exportTapped() }
+ } label: {
+ Image(systemName: "square.and.arrow.up")
+ }
+ }
+ }
+ }
+ .task {
+ selectedFile = EnsuLogging.shared.todayLogFileURL()
+ loadSelectedFile()
+ }
+ #if os(iOS)
+ .sheet(isPresented: $presentingShare) {
+ if let archiveURL {
+ ActivityView(activityItems: [archiveURL])
+ }
+ }
+ .sheet(isPresented: $presentingExport) {
+ if let archiveURL {
+ ExportDocumentPicker(urls: [archiveURL])
+ }
+ }
+ #endif
+ }
+
+ private var content: some View {
+ ScrollView {
+ Text(logText.isEmpty ? "No logs available" : logText)
+ .font(.system(size: 12, weight: .regular, design: .monospaced))
+ .foregroundStyle(logText.isEmpty ? EnsuColor.textMuted : EnsuColor.textPrimary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(EnsuSpacing.lg)
+ .textSelection(.enabled)
+ }
+ }
+
+ private func loadSelectedFile() {
+ let url = selectedFile
+ logText = EnsuLogging.shared.readLogText(fileURL: url)
+ }
+
+ private func shareTapped() {
+ do {
+ archiveURL = try EnsuLogging.shared.createLogsArchive()
+ } catch {
+ logger.error("Failed to create logs archive", error)
+ return
+ }
+
+ #if os(iOS)
+ presentingShare = true
+ #elseif os(macOS)
+ if let archiveURL {
+ MacShareSheet(items: [archiveURL]).present()
+ }
+ #endif
+ }
+
+ private func exportTapped() {
+ do {
+ archiveURL = try EnsuLogging.shared.createLogsArchive()
+ } catch {
+ logger.error("Failed to create logs archive", error)
+ return
+ }
+
+ #if os(iOS)
+ presentingExport = true
+ #elseif os(macOS)
+ exportOnMac()
+ #endif
+ }
+
+ #if os(macOS)
+ private func exportOnMac() {
+ guard let archiveURL else { return }
+ let panel = NSSavePanel()
+ panel.nameFieldStringValue = archiveURL.lastPathComponent
+ panel.begin { response in
+ guard response == .OK, let dest = panel.url else { return }
+ do {
+ if FileManager.default.fileExists(atPath: dest.path) {
+ try FileManager.default.removeItem(at: dest)
+ }
+ try FileManager.default.copyItem(at: archiveURL, to: dest)
+ } catch {
+ logger.error("Failed to export logs", error)
+ }
+ }
+ }
+ #endif
+}
+
+#if os(iOS)
+import UIKit
+
+struct ActivityView: UIViewControllerRepresentable {
+ let activityItems: [Any]
+
+ func makeUIViewController(context: Context) -> UIActivityViewController {
+ UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
+ }
+
+ func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
+}
+
+struct ExportDocumentPicker: UIViewControllerRepresentable {
+ let urls: [URL]
+
+ func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
+ let picker = UIDocumentPickerViewController(forExporting: urls, asCopy: true)
+ picker.allowsMultipleSelection = false
+ return picker
+ }
+
+ func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {}
+}
+#endif
+
+#if os(macOS)
+import AppKit
+
+private final class MacShareSheet: NSObject {
+ private let items: [Any]
+
+ init(items: [Any]) {
+ self.items = items
+ }
+
+ func present() {
+ guard let keyWindow = NSApplication.shared.keyWindow,
+ let contentView = keyWindow.contentView else { return }
+ let picker = NSSharingServicePicker(items: items)
+ picker.show(relativeTo: .zero, of: contentView, preferredEdge: .minY)
+ }
+}
+#endif
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift b/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift
new file mode 100644
index 0000000000..e8635ca191
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Settings/SettingsView.swift
@@ -0,0 +1,99 @@
+import SwiftUI
+
+struct SettingsView: View {
+ @Environment(\.dismiss) private var dismiss
+
+ let onOpenModelSettings: () -> Void
+ let onOpenLogs: () -> Void
+
+ @State private var query: String = ""
+
+ var body: some View {
+ NavigationStack {
+ List {
+ ForEach(filteredItems) { item in
+ Button {
+ item.action()
+ dismiss()
+ } label: {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(item.title)
+ .font(EnsuTypography.body)
+ .foregroundStyle(EnsuColor.textPrimary)
+ if let subtitle = item.subtitle {
+ Text(subtitle)
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+ }
+ }
+ .padding(.vertical, 6)
+ }
+ .buttonStyle(.plain)
+ }
+
+ if let endpointInfoText {
+ Text(endpointInfoText)
+ .font(EnsuTypography.small)
+ .foregroundStyle(EnsuColor.textMuted)
+ .multilineTextAlignment(.center)
+ .frame(maxWidth: .infinity, alignment: .center)
+ .padding(.vertical, 8)
+ .listRowBackground(EnsuColor.backgroundBase)
+ }
+ }
+ .scrollContentBackground(.hidden)
+ .background(EnsuColor.backgroundBase)
+ .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
+ .navigationTitle("Settings")
+ .toolbar {
+ ToolbarItem(placement: .primaryAction) {
+ Button("Close") { dismiss() }
+ }
+ }
+ }
+ }
+
+ private var filteredItems: [SettingsItem] {
+ let trimmed = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return allItems }
+ let q = trimmed.lowercased()
+ return allItems.filter { item in
+ item.title.lowercased().contains(q) || (item.subtitle?.lowercased().contains(q) == true)
+ }
+ }
+
+ private var allItems: [SettingsItem] {
+ [
+ SettingsItem(
+ title: "Model settings",
+ subtitle: "Model URL, mmproj, context length",
+ action: onOpenModelSettings
+ ),
+ SettingsItem(
+ title: "Logs",
+ subtitle: "View, export, and share logs",
+ action: onOpenLogs
+ )
+ ]
+ }
+
+ private var endpointInfoText: String? {
+ let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard trimmedQuery.isEmpty else { return nil }
+
+ let defaultEndpoint = "https://api.ente.io"
+ let endpoint = EnsuDeveloperSettings.currentEndpointString
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ .trimmingCharacters(in: CharacterSet(charactersIn: "/"))
+
+ guard !endpoint.isEmpty, endpoint != defaultEndpoint else { return nil }
+ return "Endpoint: \(endpoint)"
+ }
+}
+
+private struct SettingsItem: Identifiable {
+ let id = UUID()
+ let title: String
+ let subtitle: String?
+ let action: () -> Void
+}
diff --git a/mobile/native/darwin/Apps/ensu/ensu/Utils/Haptics.swift b/mobile/native/darwin/Apps/ensu/ensu/Utils/Haptics.swift
new file mode 100644
index 0000000000..445469d740
--- /dev/null
+++ b/mobile/native/darwin/Apps/ensu/ensu/Utils/Haptics.swift
@@ -0,0 +1,56 @@
+import Foundation
+
+#if canImport(UIKit)
+import UIKit
+
+func hapticTap() {
+ UIImpactFeedbackGenerator(style: .light).impactOccurred()
+}
+
+func hapticMedium() {
+ UIImpactFeedbackGenerator(style: .medium).impactOccurred()
+}
+
+func hapticHeavy() {
+ UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
+}
+
+func hapticSuccess() {
+ UINotificationFeedbackGenerator().notificationOccurred(.success)
+}
+
+func hapticWarning() {
+ UINotificationFeedbackGenerator().notificationOccurred(.warning)
+}
+
+func hapticError() {
+ UINotificationFeedbackGenerator().notificationOccurred(.error)
+}
+
+#elseif canImport(AppKit)
+import AppKit
+
+func hapticTap() {
+ NSHapticFeedbackManager.defaultPerformer.perform(.generic, performanceTime: .now)
+}
+
+func hapticMedium() {
+ NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .now)
+}
+
+func hapticHeavy() {
+ NSHapticFeedbackManager.defaultPerformer.perform(.levelChange, performanceTime: .now)
+}
+
+func hapticSuccess() {
+ hapticTap()
+}
+
+func hapticWarning() {
+ hapticMedium()
+}
+
+func hapticError() {
+ hapticHeavy()
+}
+#endif