Skip to content

armgit / ente

Public Imported from GitHub
0

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

Format Ensu Android with ktfmt

Manav Rathi8fd032f189c9
diff --git a/android/apps/ensu/app/build.gradle.kts b/android/apps/ensu/app/build.gradle.kts
index c281f72cef..d6f14a8e11 100644
--- a/android/apps/ensu/app/build.gradle.kts
+++ b/android/apps/ensu/app/build.gradle.kts
@@ -9,13 +9,12 @@ plugins {
id("org.jetbrains.kotlin.plugin.serialization")
}
-configurations.configureEach {
- exclude(group = "com.google.guava", module = "listenablefuture")
-}
+configurations.configureEach { exclude(group = "com.google.guava", module = "listenablefuture") }
val keystorePropsFile = file("../key.properties")
val keystoreProps = Properties()
val hasReleaseKeystore = keystorePropsFile.exists()
+
if (hasReleaseKeystore) {
keystorePropsFile.inputStream().use { keystoreProps.load(it) }
}
@@ -30,27 +29,35 @@ fun capture(vararg cmd: String): String? = runCatching {
errorOutput = ByteArrayOutputStream()
}
out.toString().trim()
-}.getOrNull()
+}
+ .getOrNull()
fun connectedDeviceAbi(): String? {
val sdkRoot = System.getenv("ANDROID_HOME") ?: System.getenv("ANDROID_SDK_ROOT")
val adb = sdkRoot?.let { "$it/platform-tools/adb" } ?: "adb"
- val serial = System.getenv("ANDROID_SERIAL")?.takeIf { it.isNotBlank() }
- ?: capture(adb, "devices")?.lines()?.drop(1)
- ?.mapNotNull { line ->
- line.trim().takeIf { it.endsWith("\tdevice") }?.substringBefore('\t')
- }
- ?.singleOrNull()
- ?: return null
- return capture(adb, "-s", serial, "shell", "getprop", "ro.product.cpu.abi")
- ?.takeIf { it in knownAbis }
+ val serial =
+ System.getenv("ANDROID_SERIAL")?.takeIf { it.isNotBlank() }
+ ?: capture(adb, "devices")
+ ?.lines()
+ ?.drop(1)
+ ?.mapNotNull { line ->
+ line.trim().takeIf { it.endsWith("\tdevice") }?.substringBefore('\t')
+ }
+ ?.singleOrNull()
+ ?: return null
+ return capture(adb, "-s", serial, "shell", "getprop", "ro.product.cpu.abi")?.takeIf {
+ it in knownAbis
+ }
}
-fun hostAbi(): String = when (System.getProperty("os.arch")) {
- "aarch64", "arm64" -> "arm64-v8a"
- "x86_64", "amd64" -> "x86_64"
- else -> error("Unsupported host architecture: ${System.getProperty("os.arch")}")
-}
+fun hostAbi(): String =
+ when (System.getProperty("os.arch")) {
+ "aarch64",
+ "arm64" -> "arm64-v8a"
+ "x86_64",
+ "amd64" -> "x86_64"
+ else -> error("Unsupported host architecture: ${System.getProperty("os.arch")}")
+ }
val debugAbis = listOf(connectedDeviceAbi() ?: hostAbi())
@@ -86,33 +93,26 @@ android {
debug {
applicationIdSuffix = ".debug"
versionNameSuffix = "-debug"
- ndk {
- abiFilters += debugAbis
- }
+ ndk { abiFilters += debugAbis }
}
release {
signingConfig = signingConfigs.getByName("release")
- ndk {
- abiFilters += knownAbis
- }
+ ndk { abiFilters += knownAbis }
}
}
- buildFeatures {
- compose = true
- }
+ buildFeatures { compose = true }
packaging {
- resources {
- excludes += "/META-INF/{AL2.0,LGPL2.1}"
- }
+ resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" }
jniLibs {
- pickFirsts += setOf(
- "lib/arm64-v8a/libc++_shared.so",
- "lib/armeabi-v7a/libc++_shared.so",
- "lib/x86/libc++_shared.so",
- "lib/x86_64/libc++_shared.so"
- )
+ pickFirsts +=
+ setOf(
+ "lib/arm64-v8a/libc++_shared.so",
+ "lib/armeabi-v7a/libc++_shared.so",
+ "lib/x86/libc++_shared.so",
+ "lib/x86_64/libc++_shared.so",
+ )
}
}
@@ -122,11 +122,7 @@ android {
}
}
-kotlin {
- compilerOptions {
- jvmTarget.set(JvmTarget.JVM_17)
- }
-}
+kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } }
dependencies {
val composeBom = platform("androidx.compose:compose-bom:2024.02.02")
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/App.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/App.kt
index 92fbb235b6..c35ce376d6 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/App.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/App.kt
@@ -22,11 +22,9 @@ fun App(appViewModel: AppViewModel) {
val isReady by appViewModel.isReady.collectAsState()
if (!isReady) {
Column(
- modifier = Modifier
- .fillMaxSize()
- .background(EnsuColor.backgroundBase()),
+ modifier = Modifier.fillMaxSize().background(EnsuColor.backgroundBase()),
horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.Center
+ verticalArrangement = Arrangement.Center,
) {
CircularProgressIndicator(color = EnsuColor.action())
Spacer(Modifier.height(16.dp))
@@ -40,6 +38,6 @@ fun App(appViewModel: AppViewModel) {
logRepository = appViewModel.logRepository,
advancedSettingsDataStore = appViewModel.advancedSettingsDataStore,
appVersion = appViewModel.appVersion,
- configDefaults = appViewModel.configDefaults
+ configDefaults = appViewModel.configDefaults,
)
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/AppState.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/AppState.kt
index e2680a04d2..6d4a765c95 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/AppState.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/AppState.kt
@@ -1,12 +1,13 @@
package io.ente.ensu
-import io.ente.ensu.llm.ModelSettingsState
-import io.ente.ensu.settings.DeveloperSettingsState
+
import io.ente.ensu.chat.ChatState
import io.ente.ensu.knowledge.KnowledgeState
+import io.ente.ensu.llm.ModelSettingsState
+import io.ente.ensu.settings.DeveloperSettingsState
data class AppState(
val chat: ChatState = ChatState(),
val knowledge: KnowledgeState = KnowledgeState(),
val developerSettings: DeveloperSettingsState = DeveloperSettingsState(),
- val modelSettings: ModelSettingsState = ModelSettingsState()
+ val modelSettings: ModelSettingsState = ModelSettingsState(),
)
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt
index 1573ed113c..5e83d8aaa0 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/AppStore.kt
@@ -1,29 +1,27 @@
package io.ente.ensu
import android.content.Context
-import io.ente.ensu.llm.ModelSettingsActions
+import io.ente.ensu.assets.AssetStore
+import io.ente.ensu.bindings.ConfigDefaults
+import io.ente.ensu.bindings.Transcriber
+import io.ente.ensu.chat.Attachment
import io.ente.ensu.chat.AttachmentStoreActions
-import io.ente.ensu.chat.ChatStoreActions
-
+import io.ente.ensu.chat.ChatMessage
import io.ente.ensu.chat.ChatRepository
-import io.ente.ensu.device.ChatDeviceCapability
-import io.ente.ensu.bindings.Transcriber
+import io.ente.ensu.chat.ChatStoreActions
import io.ente.ensu.device.AndroidDeviceCapabilityProvider
+import io.ente.ensu.device.ChatDeviceCapability
+import io.ente.ensu.knowledge.KnowledgeProvider
+import io.ente.ensu.knowledge.KnowledgeStore
import io.ente.ensu.llm.DownloadPhase
import io.ente.ensu.llm.LlmProvider
-import io.ente.ensu.assets.AssetStore
+import io.ente.ensu.llm.ModelSettingsActions
+import io.ente.ensu.llm.ModelSettingsState
import io.ente.ensu.logging.FileLogRepository
-import io.ente.ensu.chat.Attachment
-import io.ente.ensu.chat.ChatMessage
-import io.ente.ensu.bindings.ConfigDefaults
import io.ente.ensu.logging.LogLevel
import io.ente.ensu.notes.NotesStore
-import io.ente.ensu.settings.SessionPreferencesDataStore
-import io.ente.ensu.AppState
import io.ente.ensu.settings.DeveloperSettingsState
-import io.ente.ensu.llm.ModelSettingsState
-import io.ente.ensu.knowledge.KnowledgeProvider
-import io.ente.ensu.knowledge.KnowledgeStore
+import io.ente.ensu.settings.SessionPreferencesDataStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -41,39 +39,43 @@ class AppStore(
private val deviceCapabilityProvider: AndroidDeviceCapabilityProvider,
val configDefaults: ConfigDefaults,
private val logRepository: FileLogRepository,
- clock: () -> Long = { System.currentTimeMillis() }
+ clock: () -> Long = { System.currentTimeMillis() },
) {
private val _state = MutableStateFlow(AppState())
val state: StateFlow<AppState> = _state.asStateFlow()
- val notesStore = NotesStore(context, llmProvider, logRepository).also { llmProvider.modelMaintenance = it }
+ val notesStore =
+ NotesStore(context, llmProvider, logRepository).also { llmProvider.modelMaintenance = it }
private val messageStore = mutableMapOf<String, MutableList<ChatMessage>>()
private val attachmentActions = AttachmentStoreActions(_state, messageStore)
- private val knowledgeStore = KnowledgeStore(
- context = context,
- state = _state,
- provider = knowledgeProvider,
- datasets = configDefaults.knowledgeDatasets,
- logRepository = logRepository
- )
+ private val knowledgeStore =
+ KnowledgeStore(
+ context = context,
+ state = _state,
+ provider = knowledgeProvider,
+ datasets = configDefaults.knowledgeDatasets,
+ logRepository = logRepository,
+ )
private val modelSettingsActions =
ModelSettingsActions(_state, sessionPreferences, llmProvider, logRepository)
- private val chatActions = ChatStoreActions(
- state = _state,
- sessionPreferences = sessionPreferences,
- chatRepository = chatRepository,
- llmProvider = llmProvider,
- knowledgeProvider = knowledgeProvider,
- clock = clock,
- logRepository = logRepository,
- messageStore = messageStore,
- attachmentActions = attachmentActions,
- modelSettingsActions = modelSettingsActions,
- configDefaults = configDefaults,
- notesStore = notesStore,
- awaitKnowledgeReady = knowledgeStore::awaitEnabledPacksReady
- )
+ private val chatActions =
+ ChatStoreActions(
+ state = _state,
+ sessionPreferences = sessionPreferences,
+ chatRepository = chatRepository,
+ llmProvider = llmProvider,
+ knowledgeProvider = knowledgeProvider,
+ clock = clock,
+ logRepository = logRepository,
+ messageStore = messageStore,
+ attachmentActions = attachmentActions,
+ modelSettingsActions = modelSettingsActions,
+ configDefaults = configDefaults,
+ notesStore = notesStore,
+ awaitKnowledgeReady = knowledgeStore::awaitEnabledPacksReady,
+ )
+
fun bootstrap(scope: CoroutineScope) {
notesStore.bootstrap(scope)
chatActions.setScope(scope)
@@ -82,59 +84,64 @@ class AppStore(
chatActions.bootstrap(scope)
modelSettingsActions.refreshModelDownloadInfo()
knowledgeStore.bootstrap(scope)
- _state.value = _state.value.copy(
- chat = _state.value.chat.copy(isModelStateKnown = true)
- )
+ _state.value = _state.value.copy(chat = _state.value.chat.copy(isModelStateKnown = true))
}
fun refreshDeviceCapability(scope: CoroutineScope? = null) {
val capability = deviceCapabilityProvider.chatCapability()
val unsupported = capability is ChatDeviceCapability.UnsupportedLowMemory
- _state.value = _state.value.copy(
- chat = _state.value.chat.copy(
- deviceCapability = capability,
- showUnsupportedDeviceDialog = unsupported || _state.value.chat.showUnsupportedDeviceDialog,
- isDownloading = if (unsupported) false else _state.value.chat.isDownloading,
- downloadPercent = if (unsupported) null else _state.value.chat.downloadPercent,
- downloadStatus = if (unsupported) null else _state.value.chat.downloadStatus,
- downloadPhase = if (unsupported) null else _state.value.chat.downloadPhase,
- hasRequestedModelDownload = if (unsupported) false else _state.value.chat.hasRequestedModelDownload,
- editingMessageId = if (unsupported) null else _state.value.chat.editingMessageId,
- messageText = if (unsupported) "" else _state.value.chat.messageText,
- attachments = if (unsupported) emptyList() else _state.value.chat.attachments
+ _state.value =
+ _state.value.copy(
+ chat =
+ _state.value.chat.copy(
+ deviceCapability = capability,
+ showUnsupportedDeviceDialog =
+ unsupported || _state.value.chat.showUnsupportedDeviceDialog,
+ isDownloading = if (unsupported) false else _state.value.chat.isDownloading,
+ downloadPercent =
+ if (unsupported) null else _state.value.chat.downloadPercent,
+ downloadStatus =
+ if (unsupported) null else _state.value.chat.downloadStatus,
+ downloadPhase = if (unsupported) null else _state.value.chat.downloadPhase,
+ hasRequestedModelDownload =
+ if (unsupported) false else _state.value.chat.hasRequestedModelDownload,
+ editingMessageId =
+ if (unsupported) null else _state.value.chat.editingMessageId,
+ messageText = if (unsupported) "" else _state.value.chat.messageText,
+ attachments =
+ if (unsupported) emptyList() else _state.value.chat.attachments,
+ )
)
- )
if (unsupported) {
scope?.let { coroutineScope ->
- coroutineScope.launch {
- sessionPreferences.setModelDownloadRequested(false)
- }
+ coroutineScope.launch { sessionPreferences.setModelDownloadRequested(false) }
}
}
logRepository.log(
LogLevel.Info,
"Chat device capability evaluated",
details = "capability=$capability",
- tag = "App"
+ tag = "App",
)
}
fun dismissUnsupportedDeviceDialog() {
- _state.value = _state.value.copy(
- chat = _state.value.chat.copy(showUnsupportedDeviceDialog = false)
- )
+ _state.value =
+ _state.value.copy(chat = _state.value.chat.copy(showUnsupportedDeviceDialog = false))
}
fun hydrateModelDownloadRequested(requested: Boolean) {
if (!requested) return
- _state.value = _state.value.copy(
- chat = _state.value.chat.copy(
- hasRequestedModelDownload = true,
- isDownloading = true,
- downloadStatus = "Resuming download...",
- downloadPhase = DownloadPhase.Downloading
+ _state.value =
+ _state.value.copy(
+ chat =
+ _state.value.chat.copy(
+ hasRequestedModelDownload = true,
+ isDownloading = true,
+ downloadStatus = "Resuming download...",
+ downloadPhase = DownloadPhase.Downloading,
+ )
)
- )
}
fun createNewSession(): String = chatActions.createNewSession()
@@ -178,7 +185,8 @@ class AppStore(
fun cancelKnowledgePackDownload(stableId: String) = knowledgeStore.cancel(stableId)
- fun setKnowledgePackEnabled(stableId: String, enabled: Boolean) = knowledgeStore.setEnabled(stableId, enabled)
+ fun setKnowledgePackEnabled(stableId: String, enabled: Boolean) =
+ knowledgeStore.setEnabled(stableId, enabled)
fun cancelDownload() {
chatActions.cancelGenerationForDownload()
@@ -203,17 +211,14 @@ class AppStore(
}
fun unlockAdvancedSettings() {
- updateDeveloperSettings(
- _state.value.developerSettings.copy(isAdvancedUnlocked = true)
- )
+ updateDeveloperSettings(_state.value.developerSettings.copy(isAdvancedUnlocked = true))
}
fun applyPersistedSettings(
developerSettings: DeveloperSettingsState,
- modelSettings: ModelSettingsState
+ modelSettings: ModelSettingsState,
) {
_state.value = _state.value.copy(developerSettings = developerSettings)
modelSettingsActions.hydratePersistedModelSettings(modelSettings)
}
-
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt
index e752ff3f82..67752eb987 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/AppViewModel.kt
@@ -5,24 +5,21 @@ import android.content.pm.PackageManager
import android.os.Build
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
-import io.ente.ensu.settings.AdvancedSettingsDataStore
-import io.ente.ensu.settings.AdvancedSettingsSnapshot
-import io.ente.ensu.device.AndroidDeviceCapabilityProvider
-import io.ente.ensu.settings.SessionPreferencesDataStore
import io.ente.ensu.chat.ChatRepository
import io.ente.ensu.config.loadConfigDefaults
+import io.ente.ensu.device.AndroidDeviceCapabilityProvider
import io.ente.ensu.llm.LlmProvider
-import io.ente.ensu.assets.AssetStore
-import io.ente.ensu.llm.ModelSettingsState
-import io.ente.ensu.storage.CredentialStore
import io.ente.ensu.logging.LogLevel
-import io.ente.ensu.AppStore
+import io.ente.ensu.settings.AdvancedSettingsDataStore
+import io.ente.ensu.settings.AdvancedSettingsSnapshot
+import io.ente.ensu.settings.SessionPreferencesDataStore
+import io.ente.ensu.storage.CredentialStore
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -39,48 +36,52 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
private val assetStore = (application as EnsuApplication).assetStore
private val _isReady = MutableStateFlow(!assetStore.needsMigration())
val isReady = _isReady.asStateFlow()
- private val llmProvider = LlmProvider(
- assetStore = assetStore,
- transcriber = transcriber,
- deviceCapabilityProvider = deviceCapabilityProvider,
- knowledgeEmbedding = configDefaults.knowledgeEmbedding
- )
+ private val llmProvider =
+ LlmProvider(
+ assetStore = assetStore,
+ transcriber = transcriber,
+ deviceCapabilityProvider = deviceCapabilityProvider,
+ knowledgeEmbedding = configDefaults.knowledgeEmbedding,
+ )
private val chatRepository = ChatRepository(application, credentialStore)
private val knowledgeProvider = (application as EnsuApplication).knowledgeProvider
- val store = AppStore(
- context = application,
- sessionPreferences = sessionPreferences,
- chatRepository = chatRepository,
- llmProvider = llmProvider,
- knowledgeProvider = knowledgeProvider,
- assetStore = assetStore,
- transcriber = transcriber,
- deviceCapabilityProvider = deviceCapabilityProvider,
- configDefaults = configDefaults,
- logRepository = logRepository
- )
+ val store =
+ AppStore(
+ context = application,
+ sessionPreferences = sessionPreferences,
+ chatRepository = chatRepository,
+ llmProvider = llmProvider,
+ knowledgeProvider = knowledgeProvider,
+ assetStore = assetStore,
+ transcriber = transcriber,
+ deviceCapabilityProvider = deviceCapabilityProvider,
+ configDefaults = configDefaults,
+ logRepository = logRepository,
+ )
+
init {
- val launchMessage = "App launched app=$appVersion device=${Build.MANUFACTURER} ${Build.MODEL} os=${Build.VERSION.RELEASE} (sdk=${Build.VERSION.SDK_INT})"
+ val launchMessage =
+ "App launched app=$appVersion device=${Build.MANUFACTURER} ${Build.MODEL} os=${Build.VERSION.RELEASE} (sdk=${Build.VERSION.SDK_INT})"
logRepository.log(LogLevel.Info, launchMessage, tag = "App")
viewModelScope.launch {
runCatching {
advancedSettingsDataStore.migrateLegacyModelSelection { url, mmproj ->
- withContext(Dispatchers.IO) {
- assetStore.migrate(url, mmproj)
- }
+ withContext(Dispatchers.IO) { assetStore.migrate(url, mmproj) }
}
}
val initialSettings = runCatching {
advancedSettingsDataStore.settingsFlow.first()
- }.getOrDefault(AdvancedSettingsSnapshot())
+ }
+ .getOrDefault(AdvancedSettingsSnapshot())
store.applyPersistedSettings(
developerSettings = initialSettings.developerSettings,
- modelSettings = initialSettings.modelSettings
+ modelSettings = initialSettings.modelSettings,
)
store.hydrateModelDownloadRequested(
- runCatching { sessionPreferences.modelDownloadRequested.first() }.getOrDefault(false)
+ runCatching { sessionPreferences.modelDownloadRequested.first() }
+ .getOrDefault(false)
)
store.bootstrap(viewModelScope)
_isReady.value = true
@@ -88,7 +89,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
advancedSettingsDataStore.settingsFlow.drop(1).collectLatest { settings ->
store.applyPersistedSettings(
developerSettings = settings.developerSettings,
- modelSettings = settings.modelSettings
+ modelSettings = settings.modelSettings,
)
}
}
@@ -98,18 +99,19 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
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 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()
- }
+ val versionCode =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
+ packageInfo.longVersionCode
+ } else {
+ packageInfo.versionCode.toLong()
+ }
return "$versionName+$versionCode"
}
-
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/EnsuApplication.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/EnsuApplication.kt
index acb8b34063..b1d7b33041 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/EnsuApplication.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/EnsuApplication.kt
@@ -1,12 +1,12 @@
package io.ente.ensu
import android.app.Application
+import io.ente.ensu.assets.AssetStore
import io.ente.ensu.bindings.RustLogLevel
import io.ente.ensu.bindings.RustLogSink
import io.ente.ensu.bindings.Transcriber
import io.ente.ensu.bindings.initRustLogging
import io.ente.ensu.bindings.transcriptionModelAsset
-import io.ente.ensu.assets.AssetStore
import io.ente.ensu.knowledge.KnowledgeProvider
import io.ente.ensu.logging.FileLogRepository
import io.ente.ensu.logging.LogLevel
@@ -20,7 +20,7 @@ class EnsuApplication : Application() {
val transcription = transcriptionModelAsset()
Transcriber(
store.assetDir(transcription).absolutePath,
- store.voiceActivityModelPath().absolutePath
+ store.voiceActivityModelPath().absolutePath,
)
}
@@ -30,15 +30,14 @@ class EnsuApplication : Application() {
}
}
-private class EnsuRustLogSink(
- private val logRepository: FileLogRepository
-) : RustLogSink {
+private class EnsuRustLogSink(private val logRepository: FileLogRepository) : RustLogSink {
override fun log(level: RustLogLevel, target: String, message: String) {
- val mappedLevel = when (level) {
- RustLogLevel.ERROR -> LogLevel.Error
- RustLogLevel.WARN -> LogLevel.Warning
- RustLogLevel.INFO -> LogLevel.Info
- }
+ val mappedLevel =
+ when (level) {
+ RustLogLevel.ERROR -> LogLevel.Error
+ RustLogLevel.WARN -> LogLevel.Warning
+ RustLogLevel.INFO -> LogLevel.Info
+ }
logRepository.log(mappedLevel, "[$target] $message", tag = "rust")
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeDialogs.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeDialogs.kt
index bc2e83b0fd..13d111ae58 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeDialogs.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeDialogs.kt
@@ -1,39 +1,26 @@
package io.ente.ensu
-import androidx.compose.foundation.background
-import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Box
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.Image
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.rememberScrollState
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.foundation.verticalScroll
-import androidx.compose.foundation.Image
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
-import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
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
@Composable
internal fun ComingSoonDialog(
title: String,
message: String,
- onDismiss: () -> Unit
+ onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
@@ -42,7 +29,7 @@ internal fun ComingSoonDialog(
painter = painterResource(id = R.drawable.ensu_ducky),
contentDescription = null,
modifier = Modifier.height(108.dp),
- contentScale = ContentScale.Fit
+ contentScale = ContentScale.Fit,
)
},
title = {
@@ -50,7 +37,7 @@ internal fun ComingSoonDialog(
text = title,
style = EnsuTypography.h3Bold,
modifier = Modifier.fillMaxWidth(),
- textAlign = TextAlign.Center
+ textAlign = TextAlign.Center,
)
},
text = {
@@ -59,17 +46,17 @@ internal fun ComingSoonDialog(
style = EnsuTypography.body,
color = EnsuColor.textMuted(),
modifier = Modifier.fillMaxWidth(),
- textAlign = TextAlign.Center
+ textAlign = TextAlign.Center,
)
},
confirmButton = {
TextButton(
onClick = onDismiss,
- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())
+ colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary()),
) {
Text(text = "Got it")
}
},
- containerColor = EnsuColor.backgroundBase()
+ containerColor = EnsuColor.backgroundBase(),
)
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeNavigation.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeNavigation.kt
index 089995b98b..8a15c355a9 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeNavigation.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeNavigation.kt
@@ -1,11 +1,11 @@
package io.ente.ensu
import androidx.compose.animation.AnimatedContentTransitionScope
+import androidx.compose.animation.core.tween
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.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets
@@ -15,28 +15,25 @@ import androidx.compose.material3.DrawerState
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
-import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
-import io.ente.ensu.chat.ChatView
-import io.ente.ensu.notes.NotesSettingsScreen
-import io.ente.ensu.settings.AdvancedSettingsDataStore
-import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.bindings.ConfigDefaults
import io.ente.ensu.chat.Attachment
import io.ente.ensu.chat.AttachmentType
-import io.ente.ensu.bindings.ConfigDefaults
-import io.ente.ensu.AppState
-import io.ente.ensu.AppStore
+import io.ente.ensu.chat.ChatView
+import io.ente.ensu.designsystem.EnsuColor
+import io.ente.ensu.device.isChatSupported
import io.ente.ensu.llm.ModelSettingsScreen
import io.ente.ensu.logging.LogViewerScreen
+import io.ente.ensu.notes.NotesSettingsScreen
+import io.ente.ensu.settings.AdvancedSettingsDataStore
+import io.ente.ensu.settings.KnowledgeSettingsScreen
import io.ente.ensu.settings.SettingsScreen
import io.ente.ensu.settings.SystemPromptSettingsScreen
-import io.ente.ensu.settings.KnowledgeSettingsScreen
-import io.ente.ensu.device.isChatSupported
@Composable
internal fun HomeNavigation(
@@ -55,7 +52,7 @@ internal fun HomeNavigation(
onNewChat: () -> Unit,
onShowLogShareDialog: () -> Unit,
onAttachmentSelected: (AttachmentType) -> Unit,
- onOpenAttachment: (Attachment) -> Unit
+ onOpenAttachment: (Attachment) -> Unit,
) {
Scaffold(
containerColor = EnsuColor.backgroundBase(),
@@ -70,7 +67,7 @@ internal fun HomeNavigation(
modelDownloadStatus = appState.chat.downloadStatus,
modelDownloadPercent = appState.chat.downloadPercent,
onOpenDrawer = onOpenDrawer,
- onNewChat = onNewChat
+ onNewChat = onNewChat,
)
androidx.compose.material3.HorizontalDivider(color = EnsuColor.border())
}
@@ -78,7 +75,7 @@ internal fun HomeNavigation(
HomeRoute.Logs -> {
LogsTopBar(
onBack = { navController.popBackStack() },
- onShare = onShowLogShareDialog
+ onShare = onShowLogShareDialog,
)
}
HomeRoute.ModelSettings -> {
@@ -98,24 +95,20 @@ internal fun HomeNavigation(
}
else -> Unit
}
- }
+ },
) { padding ->
- Box(
- modifier = Modifier
- .fillMaxSize()
- .padding(padding)
- ) {
+ Box(modifier = Modifier.fillMaxSize().padding(padding)) {
NavHost(
navController = navController,
startDestination = HomeRoute.Chat,
- modifier = Modifier.fillMaxSize()
+ modifier = Modifier.fillMaxSize(),
) {
composable(
route = HomeRoute.Chat,
enterTransition = { forwardEnter() },
exitTransition = { forwardExit() },
popEnterTransition = { backEnter() },
- popExitTransition = { backExit() }
+ popExitTransition = { backExit() },
) {
ChatView(
chatState = appState.chat,
@@ -138,7 +131,7 @@ internal fun HomeNavigation(
},
onDismissUnsupportedDeviceDialog = store::dismissUnsupportedDeviceDialog,
onOverflowTrim = store::confirmOverflowTrim,
- onOverflowCancel = store::cancelOverflowDialog
+ onOverflowCancel = store::cancelOverflowDialog,
)
}
composable(
@@ -146,7 +139,7 @@ internal fun HomeNavigation(
enterTransition = { forwardEnter() },
exitTransition = { forwardExit() },
popEnterTransition = { backEnter() },
- popExitTransition = { backExit() }
+ popExitTransition = { backExit() },
) {
SettingsScreen(
buildVersion = appVersion,
@@ -155,12 +148,14 @@ internal fun HomeNavigation(
onOpenKnowledge = { navController.navigate(HomeRoute.Knowledge) },
onOpenNotes = { navController.navigate(HomeRoute.Notes) },
onOpenModelSettings = { navController.navigate(HomeRoute.ModelSettings) },
- onOpenSystemPromptSettings = { navController.navigate(HomeRoute.SystemPromptSettings) },
+ onOpenSystemPromptSettings = {
+ navController.navigate(HomeRoute.SystemPromptSettings)
+ },
onUnlockAdvanced = {
store.unlockAdvancedSettings()
advancedSettingsDataStore.persistUnlockAdvancedSettings()
},
- onSignIn = onSignIn
+ onSignIn = onSignIn,
)
}
composable(
@@ -168,7 +163,7 @@ internal fun HomeNavigation(
enterTransition = { forwardEnter() },
exitTransition = { forwardExit() },
popEnterTransition = { backEnter() },
- popExitTransition = { backExit() }
+ popExitTransition = { backExit() },
) {
NotesSettingsScreen(store.notesStore)
}
@@ -177,14 +172,14 @@ internal fun HomeNavigation(
enterTransition = { forwardEnter() },
exitTransition = { forwardExit() },
popEnterTransition = { backEnter() },
- popExitTransition = { backExit() }
+ popExitTransition = { backExit() },
) {
KnowledgeSettingsScreen(
state = appState.knowledge,
packDownloadsAllowed = appState.chat.deviceCapability.isChatSupported(),
onDownloadOrUpdate = store::downloadOrUpdateKnowledgePack,
onCancel = store::cancelKnowledgePackDownload,
- onSetEnabled = store::setKnowledgePackEnabled
+ onSetEnabled = store::setKnowledgePackEnabled,
)
}
composable(
@@ -192,18 +187,16 @@ internal fun HomeNavigation(
enterTransition = { forwardEnter() },
exitTransition = { forwardExit() },
popEnterTransition = { backEnter() },
- popExitTransition = { backExit() }
+ popExitTransition = { backExit() },
) {
- LogViewerScreen(
- logRepository = logRepository
- )
+ LogViewerScreen(logRepository = logRepository)
}
composable(
route = HomeRoute.ModelSettings,
enterTransition = { forwardEnter() },
exitTransition = { forwardExit() },
popEnterTransition = { backEnter() },
- popExitTransition = { backExit() }
+ popExitTransition = { backExit() },
) {
ModelSettingsScreen(
totalMemoryBytes = appState.chat.deviceCapability.totalMemoryBytes,
@@ -215,7 +208,7 @@ internal fun HomeNavigation(
onReset = {
store.resetModelSettings()
advancedSettingsDataStore.persistResetModelSettings()
- }
+ },
)
}
composable(
@@ -223,7 +216,7 @@ internal fun HomeNavigation(
enterTransition = { forwardEnter() },
exitTransition = { forwardExit() },
popEnterTransition = { backEnter() },
- popExitTransition = { backExit() }
+ popExitTransition = { backExit() },
) {
SystemPromptSettingsScreen(
defaultPromptBody = configDefaults.mobileSystemPromptBody,
@@ -240,7 +233,7 @@ internal fun HomeNavigation(
store.updateDeveloperSettings(updated)
advancedSettingsDataStore.persistSystemPrompt("")
navController.popBackStack()
- }
+ },
)
}
}
@@ -261,23 +254,23 @@ internal object HomeRoute {
internal fun AnimatedContentTransitionScope<NavBackStackEntry>.forwardEnter() =
slideInHorizontally(
initialOffsetX = { it },
- animationSpec = tween(220)
+ animationSpec = tween(220),
) + fadeIn(animationSpec = tween(90))
internal fun AnimatedContentTransitionScope<NavBackStackEntry>.forwardExit() =
slideOutHorizontally(
targetOffsetX = { -it },
- animationSpec = tween(220)
+ animationSpec = tween(220),
) + fadeOut(animationSpec = tween(90))
internal fun AnimatedContentTransitionScope<NavBackStackEntry>.backEnter() =
slideInHorizontally(
initialOffsetX = { -it },
- animationSpec = tween(220)
+ animationSpec = tween(220),
) + fadeIn(animationSpec = tween(90))
internal fun AnimatedContentTransitionScope<NavBackStackEntry>.backExit() =
slideOutHorizontally(
targetOffsetX = { it },
- animationSpec = tween(220)
+ animationSpec = tween(220),
) + fadeOut(animationSpec = tween(90))
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeTopBars.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeTopBars.kt
index 9aa454e4d7..2bcfbe3067 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeTopBars.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeTopBars.kt
@@ -6,13 +6,13 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
+import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
-import androidx.compose.material3.CenterAlignedTopAppBar
-import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@@ -32,7 +32,7 @@ internal fun TopBar(
modelDownloadStatus: String?,
modelDownloadPercent: Int?,
onOpenDrawer: () -> Unit,
- onNewChat: () -> Unit
+ onNewChat: () -> Unit,
) {
val titleText = sessionTitle?.takeIf { it.isNotBlank() } ?: "New Chat"
@@ -45,7 +45,7 @@ internal fun TopBar(
text = titleText,
style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp),
color = EnsuColor.textPrimary(),
- maxLines = 1
+ maxLines = 1,
)
}
},
@@ -53,7 +53,7 @@ internal fun TopBar(
IconButton(onClick = onOpenDrawer) {
Icon(
painter = painterResource(HugeIcons.Menu01Icon),
- contentDescription = "Menu"
+ contentDescription = "Menu",
)
}
},
@@ -64,7 +64,7 @@ internal fun TopBar(
if (showModelProgress) {
ModelProgressIndicator(
isLoading = isLoading,
- progressPercent = modelDownloadPercent
+ progressPercent = modelDownloadPercent,
)
}
@@ -74,15 +74,15 @@ internal fun TopBar(
IconButton(
onClick = onNewChat,
- modifier = Modifier.padding(end = EnsuSpacing.sm.dp)
+ modifier = Modifier.padding(end = EnsuSpacing.sm.dp),
) {
Icon(
painter = painterResource(HugeIcons.PlusSignIcon),
- contentDescription = "New chat"
+ contentDescription = "New chat",
)
}
},
- colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())
+ colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase()),
)
}
@@ -90,7 +90,7 @@ internal fun TopBar(
private fun ModelProgressIndicator(
isLoading: Boolean,
progressPercent: Int?,
- modifier: Modifier = Modifier
+ modifier: Modifier = Modifier,
) {
val indicatorModifier = modifier.size(16.dp)
val clamped = progressPercent?.coerceIn(0, 100)
@@ -100,14 +100,14 @@ private fun ModelProgressIndicator(
modifier = indicatorModifier,
color = EnsuColor.action(),
trackColor = EnsuColor.border(),
- strokeWidth = 2.dp
+ strokeWidth = 2.dp,
)
} else {
CircularProgressIndicator(
modifier = indicatorModifier,
color = EnsuColor.action(),
trackColor = EnsuColor.border(),
- strokeWidth = 2.dp
+ strokeWidth = 2.dp,
)
}
}
@@ -115,28 +115,38 @@ private fun ModelProgressIndicator(
@Composable
internal fun SimpleTopBar(title: String, onBack: () -> Unit) {
TopAppBar(
- title = { Text(text = title, style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp)) },
+ title = {
+ Text(
+ text = title,
+ style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp),
+ )
+ },
navigationIcon = {
IconButton(onClick = onBack) {
Icon(
painter = painterResource(HugeIcons.ArrowLeft01Icon),
- contentDescription = "Back"
+ contentDescription = "Back",
)
}
},
- colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())
+ colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase()),
)
}
@Composable
internal fun LogsTopBar(onBack: () -> Unit, onShare: () -> Unit) {
TopAppBar(
- title = { Text(text = "Logs", style = EnsuTypography.h3Bold.copy(fontSize = 20.sp, lineHeight = 24.sp)) },
+ 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"
+ contentDescription = "Back",
)
}
},
@@ -145,10 +155,10 @@ internal fun LogsTopBar(onBack: () -> Unit, onShare: () -> Unit) {
Icon(
painter = painterResource(HugeIcons.Upload01Icon),
contentDescription = "Share",
- modifier = Modifier.size(18.dp)
+ modifier = Modifier.size(18.dp),
)
}
},
- colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase())
+ colors = TopAppBarDefaults.topAppBarColors(containerColor = EnsuColor.backgroundBase()),
)
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeView.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeView.kt
index 9ae0526913..24838f36db 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeView.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/HomeView.kt
@@ -45,33 +45,31 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
+import io.ente.ensu.bindings.ConfigDefaults
+import io.ente.ensu.bindings.compressAttachmentImage
+import io.ente.ensu.chat.Attachment
+import io.ente.ensu.chat.AttachmentType
+import io.ente.ensu.chat.MaxImageAttachmentsPerMessage
import io.ente.ensu.chat.SessionDrawer
import io.ente.ensu.components.ImageAttachmentPreviewDialog
import io.ente.ensu.components.NativeChoiceDialog
-import io.ente.ensu.notes.LocalNotesStore
-import io.ente.ensu.settings.AdvancedSettingsDataStore
-import io.ente.ensu.logging.FileLogRepository
-import io.ente.ensu.storage.FilePathManager
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
-import io.ente.ensu.chat.Attachment
-import io.ente.ensu.chat.AttachmentType
-import io.ente.ensu.bindings.ConfigDefaults
-import io.ente.ensu.chat.MaxImageAttachmentsPerMessage
-import io.ente.ensu.AppState
-import io.ente.ensu.AppStore
+import io.ente.ensu.logging.FileLogRepository
+import io.ente.ensu.notes.LocalNotesStore
+import io.ente.ensu.settings.AdvancedSettingsDataStore
+import io.ente.ensu.storage.FilePathManager
import io.ente.ensu.whatsnew.PendingWhatsNew
import io.ente.ensu.whatsnew.WhatsNewDialog
import io.ente.ensu.whatsnew.WhatsNewService
-import io.ente.ensu.bindings.compressAttachmentImage
+import java.io.File
+import java.io.FileOutputStream
+import java.util.UUID
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
-import java.io.File
-import java.io.FileOutputStream
-import java.util.UUID
@Composable
fun HomeView(
@@ -80,293 +78,329 @@ fun HomeView(
logRepository: FileLogRepository,
advancedSettingsDataStore: AdvancedSettingsDataStore,
appVersion: String,
- configDefaults: ConfigDefaults
-) = CompositionLocalProvider(LocalNotesStore provides store.notesStore) {
- val drawerState = androidx.compose.material3.rememberDrawerState(DrawerValue.Closed)
- val scope = rememberCoroutineScope()
- val context = androidx.compose.ui.platform.LocalContext.current
- val navController = rememberNavController()
- val lifecycleOwner = LocalLifecycleOwner.current
- val latestStore by rememberUpdatedState(store)
- val navBackStackEntry by navController.currentBackStackEntryAsState()
- val currentRoute = navBackStackEntry?.destination?.route ?: HomeRoute.Chat
- val isChatRoute = currentRoute == HomeRoute.Chat
- var deleteSessionTarget by remember { mutableStateOf<io.ente.ensu.chat.ChatSession?>(null) }
- var showLogShareDialog by remember { mutableStateOf(false) }
- var showSignInComingSoon by remember { mutableStateOf(false) }
- var imagePreviewAttachment by remember { mutableStateOf<Attachment?>(null) }
- val whatsNewService = remember(context) { WhatsNewService(context.applicationContext) }
- var pendingWhatsNew by remember { mutableStateOf<PendingWhatsNew?>(null) }
-
- val handleSignInRequest: () -> Unit = { showSignInComingSoon = true }
-
- val imagePicker = rememberAttachmentPicker(
- contract = ActivityResultContracts.GetContent(),
- type = AttachmentType.Image,
- store = store,
- context = context
- )
-
- val documentPicker = rememberAttachmentPicker(
- contract = ActivityResultContracts.OpenDocument(),
- type = AttachmentType.Document,
- store = store,
- context = context
- )
-
- 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) }
+ configDefaults: ConfigDefaults,
+) =
+ CompositionLocalProvider(LocalNotesStore provides store.notesStore) {
+ val drawerState = androidx.compose.material3.rememberDrawerState(DrawerValue.Closed)
+ val scope = rememberCoroutineScope()
+ val context = androidx.compose.ui.platform.LocalContext.current
+ val navController = rememberNavController()
+ val lifecycleOwner = LocalLifecycleOwner.current
+ val latestStore by rememberUpdatedState(store)
+ val navBackStackEntry by navController.currentBackStackEntryAsState()
+ val currentRoute = navBackStackEntry?.destination?.route ?: HomeRoute.Chat
+ val isChatRoute = currentRoute == HomeRoute.Chat
+ var deleteSessionTarget by remember { mutableStateOf<io.ente.ensu.chat.ChatSession?>(null) }
+ var showLogShareDialog by remember { mutableStateOf(false) }
+ var showSignInComingSoon by remember { mutableStateOf(false) }
+ var imagePreviewAttachment by remember { mutableStateOf<Attachment?>(null) }
+ val whatsNewService = remember(context) { WhatsNewService(context.applicationContext) }
+ var pendingWhatsNew by remember { mutableStateOf<PendingWhatsNew?>(null) }
+
+ val handleSignInRequest: () -> Unit = { showSignInComingSoon = true }
+
+ val imagePicker =
+ rememberAttachmentPicker(
+ contract = ActivityResultContracts.GetContent(),
+ type = AttachmentType.Image,
+ store = store,
+ context = context,
+ )
+
+ val documentPicker =
+ rememberAttachmentPicker(
+ contract = ActivityResultContracts.OpenDocument(),
+ type = AttachmentType.Document,
+ store = store,
+ context = context,
+ )
+
+ 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()
+ }
}
- 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)
+ 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()
}
- 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 by remember(appState.chat.sessions, appState.chat.currentSessionId) {
- derivedStateOf {
- appState.chat.sessions.firstOrNull { it.id == appState.chat.currentSessionId }
+ val exportLogs: () -> Unit = {
+ val name = "ensu-logs-${System.currentTimeMillis()}.zip"
+ exportLogsLauncher.launch(name)
}
- }
- BackHandler(enabled = !isChatRoute) {
- if (!navController.popBackStack()) {
- navController.navigate(HomeRoute.Chat) { launchSingleTop = true }
+ val currentSession by
+ remember(appState.chat.sessions, appState.chat.currentSessionId) {
+ derivedStateOf {
+ appState.chat.sessions.firstOrNull { it.id == appState.chat.currentSessionId }
+ }
+ }
+
+ BackHandler(enabled = !isChatRoute) {
+ if (!navController.popBackStack()) {
+ navController.navigate(HomeRoute.Chat) { launchSingleTop = true }
+ }
}
- }
- BackHandler(enabled = drawerState.currentValue == DrawerValue.Open) {
- scope.launch { drawerState.close() }
- }
+ BackHandler(enabled = drawerState.currentValue == DrawerValue.Open) {
+ scope.launch { drawerState.close() }
+ }
- DisposableEffect(lifecycleOwner) {
- val observer = LifecycleEventObserver { _, event ->
- if (event == Lifecycle.Event.ON_RESUME) {
- latestStore.notesStore.setForeground(true)
- latestStore.refreshModelDownloadInfo()
- } else if (event == Lifecycle.Event.ON_STOP) {
- latestStore.notesStore.setForeground(false)
+ DisposableEffect(lifecycleOwner) {
+ val observer = LifecycleEventObserver { _, event ->
+ if (event == Lifecycle.Event.ON_RESUME) {
+ latestStore.notesStore.setForeground(true)
+ latestStore.refreshModelDownloadInfo()
+ } else if (event == Lifecycle.Event.ON_STOP) {
+ latestStore.notesStore.setForeground(false)
+ }
}
+ latestStore.notesStore.setForeground(
+ lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
+ )
+ lifecycleOwner.lifecycle.addObserver(observer)
+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
- latestStore.notesStore.setForeground(lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED))
- lifecycleOwner.lifecycle.addObserver(observer)
- onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
- }
- LaunchedEffect(whatsNewService) {
- delay(600)
- pendingWhatsNew = whatsNewService.getPendingWhatsNew()
- }
+ LaunchedEffect(whatsNewService) {
+ delay(600)
+ pendingWhatsNew = whatsNewService.getPendingWhatsNew()
+ }
- // Note: Drawer close is handled in navigation callbacks (onOpenSettings, onAccount, etc.)
- // to avoid race conditions with route changes during navigation transitions.
+ // Note: Drawer close is handled in navigation callbacks (onOpenSettings, onAccount, etc.)
+ // to avoid race conditions with route changes during navigation transitions.
- val openDrawer: () -> Unit = { scope.launch { drawerState.open() } }
+ val openDrawer: () -> Unit = { scope.launch { drawerState.open() } }
- val handleAttachmentSelected: (AttachmentType) -> Unit = handle@{ type ->
- when (type) {
- AttachmentType.Image -> {
- val imageCount = appState.chat.attachments.count {
- it.type == AttachmentType.Image
+ val handleAttachmentSelected: (AttachmentType) -> Unit = handle@{ type ->
+ when (type) {
+ AttachmentType.Image -> {
+ val imageCount =
+ appState.chat.attachments.count { it.type == AttachmentType.Image }
+ if (imageCount >= MaxImageAttachmentsPerMessage) return@handle
+ imagePicker.launch("image/*")
+ }
+ AttachmentType.Document -> {
+ documentPicker.launch(arrayOf("*/*"))
}
- if (imageCount >= MaxImageAttachmentsPerMessage) return@handle
- imagePicker.launch("image/*")
- }
- AttachmentType.Document -> {
- documentPicker.launch(arrayOf("*/*"))
}
}
- }
- ModalNavigationDrawer(
- drawerState = drawerState,
- gesturesEnabled = isChatRoute,
- drawerContent = {
- // Always render SessionDrawer - don't conditionally swap content based on route.
- // Changing drawer content while navigating can cause race conditions with the
- // navigation back stack. The drawer is already hidden via gesturesEnabled.
- SessionDrawer(
- sessions = appState.chat.sessions,
- selectedSessionId = appState.chat.currentSessionId,
- 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
+ ModalNavigationDrawer(
+ drawerState = drawerState,
+ gesturesEnabled = isChatRoute,
+ drawerContent = {
+ // Always render SessionDrawer - don't conditionally swap content based on route.
+ // Changing drawer content while navigating can cause race conditions with the
+ // navigation back stack. The drawer is already hidden via gesturesEnabled.
+ SessionDrawer(
+ sessions = appState.chat.sessions,
+ selectedSessionId = appState.chat.currentSessionId,
+ 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 },
+ onOpenSettings = {
+ navController.navigate(HomeRoute.Settings) {
+ launchSingleTop = true
+ restoreState = true
+ popUpTo(HomeRoute.Chat) { inclusive = false }
+ }
+ scope.launch { drawerState.close() }
+ },
+ )
+ },
+ ) {
+ HomeNavigation(
+ appState = appState,
+ store = store,
+ logRepository = logRepository,
+ advancedSettingsDataStore = advancedSettingsDataStore,
+ appVersion = appVersion,
+ configDefaults = configDefaults,
+ navController = navController,
+ drawerState = drawerState,
+ currentRoute = currentRoute,
+ currentSession = currentSession,
+ onSignIn = handleSignInRequest,
+ onOpenDrawer = openDrawer,
+ onNewChat = {
+ store.startNewSessionDraft()
+ store.persistSelectedSession(scope, null)
},
- onOpenSettings = {
- navController.navigate(HomeRoute.Settings) {
- launchSingleTop = true
- restoreState = true
- popUpTo(HomeRoute.Chat) { inclusive = false }
+ onShowLogShareDialog = { showLogShareDialog = true },
+ onAttachmentSelected = handleAttachmentSelected,
+ onOpenAttachment = { attachment ->
+ if (attachment.type == AttachmentType.Image) {
+ imagePreviewAttachment = attachment
+ } else {
+ openAttachment(context, attachment)
}
- scope.launch { drawerState.close() }
- }
+ },
)
}
- ) {
- HomeNavigation(
- appState = appState,
- store = store,
- logRepository = logRepository,
- advancedSettingsDataStore = advancedSettingsDataStore,
- appVersion = appVersion,
- configDefaults = configDefaults,
- navController = navController,
- drawerState = drawerState,
- currentRoute = currentRoute,
- currentSession = currentSession,
- onSignIn = handleSignInRequest,
- onOpenDrawer = openDrawer,
- onNewChat = {
- store.startNewSessionDraft()
- store.persistSelectedSession(scope, null)
- },
- onShowLogShareDialog = { showLogShareDialog = true },
- onAttachmentSelected = handleAttachmentSelected,
- onOpenAttachment = { attachment ->
- if (attachment.type == AttachmentType.Image) {
- imagePreviewAttachment = attachment
- } else {
- openAttachment(context, attachment)
- }
- }
- )
- }
- imagePreviewAttachment?.let { attachment ->
- ImageAttachmentPreviewDialog(
- path = attachment.localPath,
- contentDescription = attachment.name,
- onDismiss = { imagePreviewAttachment = null }
- )
- }
+ imagePreviewAttachment?.let { attachment ->
+ ImageAttachmentPreviewDialog(
+ path = attachment.localPath,
+ contentDescription = attachment.name,
+ onDismiss = { imagePreviewAttachment = null },
+ )
+ }
- if (showSignInComingSoon) {
- ComingSoonDialog(
- title = "Coming soon",
- message = "Sign in and cloud backup will be available in a future update.",
- onDismiss = { showSignInComingSoon = false }
- )
- }
+ if (showSignInComingSoon) {
+ ComingSoonDialog(
+ title = "Coming soon",
+ message = "Sign in and cloud backup will be available in a future update.",
+ onDismiss = { showSignInComingSoon = false },
+ )
+ }
- pendingWhatsNew?.let { pending ->
- WhatsNewDialog(
- entries = pending.entries,
- onDismiss = {
- whatsNewService.markSeen()
- pendingWhatsNew = null
- }
- )
- }
+ pendingWhatsNew?.let { pending ->
+ WhatsNewDialog(
+ entries = pending.entries,
+ onDismiss = {
+ whatsNewService.markSeen()
+ pendingWhatsNew = null
+ },
+ )
+ }
- if (deleteSessionTarget != null) {
- NativeChoiceDialog(
- title = "Delete Chat",
- body = "This will delete the chat from this device.",
- firstButtonLabel = "Delete",
- secondButtonLabel = "Cancel",
- onFirst = {
- deleteSessionTarget?.let { session ->
- store.deleteSession(session.id)
- store.persistSelectedSession(scope, appState.chat.currentSessionId)
- }
- deleteSessionTarget = null
- },
- onSecond = { deleteSessionTarget = null },
- onDismiss = { deleteSessionTarget = null }
- )
- }
+ if (deleteSessionTarget != null) {
+ NativeChoiceDialog(
+ title = "Delete Chat",
+ body = "This will delete the chat from this device.",
+ firstButtonLabel = "Delete",
+ secondButtonLabel = "Cancel",
+ onFirst = {
+ deleteSessionTarget?.let { session ->
+ store.deleteSession(session.id)
+ store.persistSelectedSession(scope, appState.chat.currentSessionId)
+ }
+ deleteSessionTarget = null
+ },
+ onSecond = { deleteSessionTarget = null },
+ onDismiss = { deleteSessionTarget = null },
+ )
+ }
- 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)
+ if (showLogShareDialog) {
+ ModalBottomSheet(
+ onDismissRequest = { showLogShareDialog = false },
+ containerColor = EnsuColor.backgroundBase(),
) {
- 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()
- },
- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())
- ) {
- Text(text = "Share")
- }
- TextButton(
- onClick = {
- showLogShareDialog = false
- exportLogs()
- },
- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())
- ) {
- Text(text = "Export")
- }
- Spacer(modifier = Modifier.weight(1f))
- TextButton(
- onClick = { showLogShareDialog = false },
- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textMuted())
- ) {
- Text(text = "Cancel")
+ 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()
+ },
+ colors =
+ ButtonDefaults.textButtonColors(
+ contentColor = EnsuColor.textPrimary()
+ ),
+ ) {
+ Text(text = "Share")
+ }
+ TextButton(
+ onClick = {
+ showLogShareDialog = false
+ exportLogs()
+ },
+ colors =
+ ButtonDefaults.textButtonColors(
+ contentColor = EnsuColor.textPrimary()
+ ),
+ ) {
+ Text(text = "Export")
+ }
+ Spacer(modifier = Modifier.weight(1f))
+ TextButton(
+ onClick = { showLogShareDialog = false },
+ colors =
+ ButtonDefaults.textButtonColors(
+ contentColor = EnsuColor.textMuted()
+ ),
+ ) {
+ Text(text = "Cancel")
+ }
}
+ Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
}
- Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
}
}
}
-}
@Composable
private fun <I> rememberAttachmentPicker(
contract: ActivityResultContract<I, Uri?>,
type: AttachmentType,
store: AppStore,
- context: Context
+ context: Context,
): ManagedActivityResultLauncher<I, Uri?> {
val scope = rememberCoroutineScope()
val latestStore by rememberUpdatedState(store)
@@ -375,9 +409,8 @@ private fun <I> rememberAttachmentPicker(
if (uri != null) {
latestStore.setAttachmentProcessing(true)
scope.launch {
- val attachment = withContext(Dispatchers.IO) {
- buildAttachmentFromUri(context, uri, type)
- }
+ val attachment =
+ withContext(Dispatchers.IO) { buildAttachmentFromUri(context, uri, type) }
if (attachment != null) {
latestStore.addAttachment(attachment)
if (type == AttachmentType.Image) {
@@ -394,15 +427,17 @@ private fun <I> rememberAttachmentPicker(
private fun buildAttachmentFromUri(
context: Context,
uri: Uri,
- type: AttachmentType
+ type: AttachmentType,
): Attachment? {
val resolver = context.contentResolver
val name = queryDisplayName(resolver, uri)
val size = querySize(resolver, uri)
- val rawName = name ?: when (type) {
- AttachmentType.Image -> "image"
- AttachmentType.Document -> "document"
- }
+ val rawName =
+ name
+ ?: when (type) {
+ AttachmentType.Image -> "image"
+ AttachmentType.Document -> "document"
+ }
val safeName = rawName.replace("/", "_")
val attachmentsDir = FilePathManager(context).attachmentsDir
@@ -416,16 +451,12 @@ private fun buildAttachmentFromUri(
val inputStream = resolver.openInputStream(uri) ?: return@runCatching null
val originalBytes = inputStream.use { input -> input.readAttachmentImageBytes() }
val compressedBytes = compressAttachmentImage(originalBytes)
- FileOutputStream(destination).use { output ->
- output.write(compressedBytes)
- }
+ FileOutputStream(destination).use { output -> output.write(compressedBytes) }
finalName = normalizedJpegAttachmentName(name ?: safeName)
} else {
val inputStream = resolver.openInputStream(uri) ?: return@runCatching null
inputStream.use { input ->
- FileOutputStream(destination).use { output ->
- input.copyTo(output)
- }
+ FileOutputStream(destination).use { output -> input.copyTo(output) }
}
finalName = name ?: safeName
}
@@ -438,19 +469,17 @@ private fun buildAttachmentFromUri(
sizeBytes = finalSize,
type = type,
localPath = destination.absolutePath,
- isUploading = false
+ isUploading = false,
)
- }.getOrNull()
+ }
+ .getOrNull()
}
private fun normalizedJpegAttachmentName(name: String?): String {
- val raw = name
- ?.replace("\u0000", "")
- ?.replace("\\", "/")
- ?.substringAfterLast("/")
- ?.trim()
- ?.takeIf { it.isNotBlank() }
- ?: "image"
+ val raw =
+ name?.replace("\u0000", "")?.replace("\\", "/")?.substringAfterLast("/")?.trim()?.takeIf {
+ it.isNotBlank()
+ } ?: "image"
val base = raw.substringBeforeLast(".", raw).ifBlank { "image" }
return "$base.jpg"
}
@@ -468,24 +497,28 @@ private fun openAttachment(context: Context, attachment: Attachment) {
}
val extension = file.extension.lowercase()
- val mimeFromExtension = if (extension.isNotBlank()) {
- MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
- } else {
- null
- }
- val mime = when {
- attachment.type == AttachmentType.Image -> mimeFromExtension ?: "image/*"
- else -> mimeFromExtension ?: "*/*"
- }
+ val mimeFromExtension =
+ if (extension.isNotBlank()) {
+ MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
+ } else {
+ null
+ }
+ val mime =
+ when {
+ attachment.type == AttachmentType.Image -> mimeFromExtension ?: "image/*"
+ else -> mimeFromExtension ?: "*/*"
+ }
- val uri = FileProvider.getUriForFile(
- context,
- "${context.packageName}.fileprovider",
- file
- )
- val intent = Intent(Intent.ACTION_VIEW)
- .setDataAndType(uri, mime)
- .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ val uri =
+ FileProvider.getUriForFile(
+ context,
+ "${context.packageName}.fileprovider",
+ file,
+ )
+ val intent =
+ Intent(Intent.ACTION_VIEW)
+ .setDataAndType(uri, mime)
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val chooser = Intent.createChooser(intent, "Open attachment")
val resolved = intent.resolveActivity(context.packageManager)
if (resolved != null) {
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/MainActivity.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/MainActivity.kt
index 811f6d47d1..121e59c916 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/MainActivity.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/MainActivity.kt
@@ -20,10 +20,11 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge(
- navigationBarStyle = SystemBarStyle.auto(
- EnsuColor.backgroundBaseLight.toArgb(),
- EnsuColor.backgroundBaseDark.toArgb()
- )
+ navigationBarStyle =
+ SystemBarStyle.auto(
+ EnsuColor.backgroundBaseLight.toArgb(),
+ EnsuColor.backgroundBaseDark.toArgb(),
+ )
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
window.isNavigationBarContrastEnforced = false
@@ -32,10 +33,10 @@ class MainActivity : ComponentActivity() {
Theme {
val appViewModel: AppViewModel = viewModel()
Box(
- modifier = Modifier
- .fillMaxSize()
- .background(EnsuColor.backgroundBase())
- .safeDrawingPadding()
+ modifier =
+ Modifier.fillMaxSize()
+ .background(EnsuColor.backgroundBase())
+ .safeDrawingPadding()
) {
App(appViewModel = appViewModel)
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/RootView.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/RootView.kt
index 8ad8a0c38d..11435c4745 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/RootView.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/RootView.kt
@@ -5,12 +5,10 @@ import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
-import io.ente.ensu.settings.AdvancedSettingsDataStore
+import io.ente.ensu.bindings.ConfigDefaults
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.logging.FileLogRepository
-import io.ente.ensu.bindings.ConfigDefaults
-import io.ente.ensu.AppState
-import io.ente.ensu.AppStore
+import io.ente.ensu.settings.AdvancedSettingsDataStore
@Composable
fun RootView(
@@ -19,20 +17,16 @@ fun RootView(
logRepository: FileLogRepository,
advancedSettingsDataStore: AdvancedSettingsDataStore,
appVersion: String,
- configDefaults: ConfigDefaults
+ configDefaults: ConfigDefaults,
) {
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(EnsuColor.backgroundBase())
- ) {
+ Box(modifier = Modifier.fillMaxSize().background(EnsuColor.backgroundBase())) {
HomeView(
appState = appState,
store = store,
logRepository = logRepository,
advancedSettingsDataStore = advancedSettingsDataStore,
appVersion = appVersion,
- configDefaults = configDefaults
+ configDefaults = configDefaults,
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetDownloadJobService.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetDownloadJobService.kt
index b410b1a09f..ebe31487c1 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetDownloadJobService.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetDownloadJobService.kt
@@ -27,20 +27,21 @@ class AssetDownloadJobService : JobService() {
params,
NOTIFICATION_ID,
buildNotification(this, 0, true),
- JOB_END_NOTIFICATION_POLICY_REMOVE
+ JOB_END_NOTIFICATION_POLICY_REMOVE,
)
return true
}
override fun onStopJob(params: JobParameters): Boolean {
- val callbacks = synchronized(lock) {
- if (runningParams !== params) return false
- runningJob = null
- runningParams = null
- val callbacks = cancellations.values.toList()
- cancellations.clear()
- callbacks
- }
+ val callbacks =
+ synchronized(lock) {
+ if (runningParams !== params) return false
+ runningJob = null
+ runningParams = null
+ val callbacks = cancellations.values.toList()
+ cancellations.clear()
+ callbacks
+ }
callbacks.forEach { it() }
return false
}
@@ -65,13 +66,14 @@ class AssetDownloadJobService : JobService() {
}
fun begin(onCancelled: () -> Unit): Long {
- val (id, first) = synchronized(lock) {
- val id = nextId++
- val first = cancellations.isEmpty()
- cancellations[id] = onCancelled
- if (first) lastNotifyMs = 0L
- id to first
- }
+ val (id, first) =
+ synchronized(lock) {
+ val id = nextId++
+ val first = cancellations.isEmpty()
+ cancellations[id] = onCancelled
+ if (first) lastNotifyMs = 0L
+ id to first
+ }
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return id
if (!first) return id
val scheduler = appContext.getSystemService(JobScheduler::class.java)
@@ -79,14 +81,21 @@ class AssetDownloadJobService : JobService() {
Log.w(TAG, "JobScheduler unavailable")
return id
}
- val job = JobInfo.Builder(JOB_ID, ComponentName(appContext, AssetDownloadJobService::class.java))
- .setUserInitiated(true)
- .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
- .build()
- val result = runCatching { scheduler.schedule(job) }.getOrElse { error ->
- Log.w(TAG, "Download job schedule failed", error)
- return id
+ val job =
+ JobInfo.Builder(
+ JOB_ID,
+ ComponentName(appContext, AssetDownloadJobService::class.java),
+ )
+ .setUserInitiated(true)
+ .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
+ .build()
+ val result = runCatching {
+ scheduler.schedule(job)
}
+ .getOrElse { error ->
+ Log.w(TAG, "Download job schedule failed", error)
+ return id
+ }
if (result != JobScheduler.RESULT_SUCCESS) {
Log.w(TAG, "Download job not scheduled")
}
@@ -113,20 +122,21 @@ class AssetDownloadJobService : JobService() {
params,
NOTIFICATION_ID,
buildNotification(appContext, shownPercent, shownIndeterminate),
- JOB_END_NOTIFICATION_POLICY_REMOVE
+ JOB_END_NOTIFICATION_POLICY_REMOVE,
)
}
fun end(id: Long) {
- val state = synchronized(lock) {
- if (cancellations.remove(id) == null) return
- if (cancellations.isNotEmpty()) return
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return
- val state = runningJob to runningParams
- runningJob = null
- runningParams = null
- state
- }
+ val state =
+ synchronized(lock) {
+ if (cancellations.remove(id) == null) return
+ if (cancellations.isNotEmpty()) return
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return
+ val state = runningJob to runningParams
+ runningJob = null
+ runningParams = null
+ state
+ }
val (job, params) = state
if (job != null && params != null) {
job.jobFinished(params, false)
@@ -136,13 +146,17 @@ class AssetDownloadJobService : JobService() {
private fun buildNotification(
context: Context,
percent: Int,
- indeterminate: Boolean
+ indeterminate: Boolean,
): Notification {
- NotificationManagerCompat.from(context).createNotificationChannel(
- NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManagerCompat.IMPORTANCE_LOW)
- .setName("Asset downloads")
- .build()
- )
+ NotificationManagerCompat.from(context)
+ .createNotificationChannel(
+ NotificationChannelCompat.Builder(
+ CHANNEL_ID,
+ NotificationManagerCompat.IMPORTANCE_LOW,
+ )
+ .setName("Asset downloads")
+ .build()
+ )
return NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle("Downloading assets")
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetStore.kt
index 9d179485b0..e4a8a80823 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetStore.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/assets/AssetStore.kt
@@ -3,13 +3,13 @@ package io.ente.ensu.assets
import android.content.Context
import android.os.Environment
import android.util.Log
+import io.ente.ensu.bindings.Asset
import io.ente.ensu.bindings.AssetDownloadCallback
import io.ente.ensu.bindings.AssetDownloadProgress
-import io.ente.ensu.bindings.Asset
import io.ente.ensu.bindings.AssetStoreCore
import io.ente.ensu.bindings.CancellationToken
-import io.ente.ensu.bindings.LegacyAssets
import io.ente.ensu.bindings.KnowledgeReconciliation
+import io.ente.ensu.bindings.LegacyAssets
import io.ente.ensu.bindings.cleanupObsoleteKnowledgePackRevisions
import io.ente.ensu.bindings.migrateEnsuAssets
import io.ente.ensu.bindings.needsAssetMigration
@@ -23,8 +23,8 @@ import kotlinx.coroutines.withContext
class AssetStore(context: Context) {
private val appContext = context.applicationContext
private val assetsDir = File(appContext.noBackupFilesDir, "assets")
- private val legacyLlmDir = appContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
- ?.let { File(it, "llm") }
+ private val legacyLlmDir =
+ appContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.let { File(it, "llm") }
private val legacyTranscriptionDir = File(appContext.dataDir, "app_ensu_transcription_models")
private val core: AssetStoreCore
@@ -40,24 +40,23 @@ class AssetStore(context: Context) {
File(appContext.filesDir, "llm").deleteRecursively()
return migrateEnsuAssets(
assetsDir.absolutePath,
- legacyAssets(legacyModelUrl, legacyMmprojUrl)
+ legacyAssets(legacyModelUrl, legacyMmprojUrl),
)
}
- private fun legacyAssets(modelUrl: String?, mmprojUrl: String?) = LegacyAssets(
- llmDir = legacyLlmDir?.absolutePath,
- transcriptionDir = legacyTranscriptionDir.absolutePath,
- modelUrl = modelUrl,
- mmprojUrl = mmprojUrl
- )
+ private fun legacyAssets(modelUrl: String?, mmprojUrl: String?) =
+ LegacyAssets(
+ llmDir = legacyLlmDir?.absolutePath,
+ transcriptionDir = legacyTranscriptionDir.absolutePath,
+ modelUrl = modelUrl,
+ mmprojUrl = mmprojUrl,
+ )
fun assetDir(asset: Asset): File = File(core.assetDir(asset))
- fun llmModelPath(asset: Asset): File? =
- core.llmModelPath(asset)?.let(::File)
+ fun llmModelPath(asset: Asset): File? = core.llmModelPath(asset)?.let(::File)
- fun llmMmprojPath(asset: Asset): File? =
- core.llmMmprojPath(asset)?.let(::File)
+ fun llmMmprojPath(asset: Asset): File? = core.llmMmprojPath(asset)?.let(::File)
fun voiceActivityModelPath(): File = File(core.voiceActivityModelPath())
@@ -71,39 +70,39 @@ class AssetStore(context: Context) {
internal fun cleanupKnowledgeRevisions(stableId: String, activeIdentity: String) =
cleanupObsoleteKnowledgePackRevisions(core, stableId, activeIdentity)
- suspend fun estimateDownloadSize(asset: Asset): Long? = withContext(Dispatchers.IO) {
- core.estimatedDownloadSize(asset)
- }
+ suspend fun estimateDownloadSize(asset: Asset): Long? =
+ withContext(Dispatchers.IO) { core.estimatedDownloadSize(asset) }
suspend fun download(
assets: List<Asset>,
- onProgress: (AssetDownloadProgress) -> Unit
- ) = withContext(Dispatchers.IO) {
- if (assets.all { core.isDownloaded(it) }) return@withContext
-
- val token = CancellationToken()
- val lease = AssetDownloadJobService.begin { token.cancel() }
- try {
- core.download(
- assets,
- object : AssetDownloadCallback {
- override fun onProgress(progress: AssetDownloadProgress) {
- progress.logLine?.let { Log.i("AssetStore", it) }
- AssetDownloadJobService.update(
- lease,
- progress.percentage.toInt(),
- progress.totalBytes == null
- )
- onProgress(progress)
- }
- },
- token
- )
- } catch (e: CancellationException) {
- token.cancel()
- throw e
- } finally {
- AssetDownloadJobService.end(lease)
+ onProgress: (AssetDownloadProgress) -> Unit,
+ ) =
+ withContext(Dispatchers.IO) {
+ if (assets.all { core.isDownloaded(it) }) return@withContext
+
+ val token = CancellationToken()
+ val lease = AssetDownloadJobService.begin { token.cancel() }
+ try {
+ core.download(
+ assets,
+ object : AssetDownloadCallback {
+ override fun onProgress(progress: AssetDownloadProgress) {
+ progress.logLine?.let { Log.i("AssetStore", it) }
+ AssetDownloadJobService.update(
+ lease,
+ progress.percentage.toInt(),
+ progress.totalBytes == null,
+ )
+ onProgress(progress)
+ }
+ },
+ token,
+ )
+ } catch (e: CancellationException) {
+ token.cancel()
+ throw e
+ } finally {
+ AssetDownloadJobService.end(lease)
+ }
}
- }
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/AttachmentStoreActions.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/AttachmentStoreActions.kt
index 3129566bcb..02a8bd3ed3 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/AttachmentStoreActions.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/AttachmentStoreActions.kt
@@ -1,17 +1,13 @@
package io.ente.ensu.chat
-import io.ente.ensu.chat.Attachment
-import io.ente.ensu.chat.AttachmentType
-import io.ente.ensu.chat.ChatMessage
-import io.ente.ensu.chat.MaxImageAttachmentsPerMessage
import io.ente.ensu.AppState
+import java.io.File
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
-import java.io.File
internal class AttachmentStoreActions(
private val state: MutableStateFlow<AppState>,
- private val messageStore: MutableMap<String, MutableList<ChatMessage>>
+ private val messageStore: MutableMap<String, MutableList<ChatMessage>>,
) {
fun setAttachmentProcessing(isProcessing: Boolean) {
state.update { appState ->
@@ -23,23 +19,20 @@ internal class AttachmentStoreActions(
var accepted = false
state.update { appState ->
val chat = appState.chat
- val imageLimitReached = attachment.type == AttachmentType.Image &&
- chat.attachments.count { it.type == AttachmentType.Image } >=
- MaxImageAttachmentsPerMessage
- if (chat.isGenerating ||
- chat.isDownloading ||
- imageLimitReached
- ) {
- appState.copy(
- chat = chat.copy(isProcessingAttachments = false)
- )
+ val imageLimitReached =
+ attachment.type == AttachmentType.Image &&
+ chat.attachments.count { it.type == AttachmentType.Image } >=
+ MaxImageAttachmentsPerMessage
+ if (chat.isGenerating || chat.isDownloading || imageLimitReached) {
+ appState.copy(chat = chat.copy(isProcessingAttachments = false))
} else {
accepted = true
appState.copy(
- chat = chat.copy(
- attachments = chat.attachments + attachment,
- isProcessingAttachments = false
- )
+ chat =
+ chat.copy(
+ attachments = chat.attachments + attachment,
+ isProcessingAttachments = false,
+ )
)
}
}
@@ -49,9 +42,10 @@ internal class AttachmentStoreActions(
fun removeAttachment(attachment: Attachment) {
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- attachments = appState.chat.attachments.filterNot { it.id == attachment.id }
- )
+ chat =
+ appState.chat.copy(
+ attachments = appState.chat.attachments.filterNot { it.id == attachment.id }
+ )
)
}
deleteIfUnstored(attachment)
@@ -62,9 +56,10 @@ internal class AttachmentStoreActions(
}
private fun deleteIfUnstored(attachment: Attachment) {
- val stored = messageStore.values.any { messages ->
- messages.any { message -> message.attachments.any { it.id == attachment.id } }
- }
+ val stored =
+ messageStore.values.any { messages ->
+ messages.any { message -> message.attachments.any { it.id == attachment.id } }
+ }
if (!stored) attachment.localPath?.let { File(it).delete() }
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt
index 7c0f73dc0f..01ac3508e1 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatInputBar.kt
@@ -1,11 +1,11 @@
package io.ente.ensu.chat
-import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
@@ -48,16 +48,12 @@ import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
+import io.ente.ensu.components.ImageAttachmentThumbnail
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
-import io.ente.ensu.components.ImageAttachmentThumbnail
-import io.ente.ensu.chat.Attachment
-import io.ente.ensu.chat.AttachmentType
-import io.ente.ensu.chat.ChatMessage
-import io.ente.ensu.chat.MaxImageAttachmentsPerMessage
import io.ente.ensu.format.formattedFileSize
import io.ente.ensu.platform.rememberHaptics
import kotlinx.coroutines.delay
@@ -80,7 +76,7 @@ internal fun MessageInput(
onCancelEdit: () -> Unit,
voiceInputState: VoiceInputState,
onVoiceInput: () -> Unit,
- focusRequestId: Int
+ focusRequestId: Int,
) {
val haptic = rememberHaptics()
val placeholder = "Write a message..."
@@ -90,17 +86,18 @@ internal fun MessageInput(
mutableStateOf(
TextFieldValue(
text = messageText,
- selection = TextRange(messageText.length)
+ selection = TextRange(messageText.length),
)
)
}
LaunchedEffect(messageText) {
if (messageText != fieldValue.text) {
- fieldValue = TextFieldValue(
- text = messageText,
- selection = TextRange(messageText.length)
- )
+ fieldValue =
+ TextFieldValue(
+ text = messageText,
+ selection = TextRange(messageText.length),
+ )
}
}
@@ -119,9 +116,8 @@ internal fun MessageInput(
attachments.count { it.type == AttachmentType.Image } >= MaxImageAttachmentsPerMessage
Column(
- modifier = modifier
- .background(EnsuColor.backgroundBase()),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
+ modifier = modifier.background(EnsuColor.backgroundBase()),
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
) {
if (editingMessage != null) {
EditBanner(message = editingMessage, onCancelEdit = onCancelEdit)
@@ -130,13 +126,13 @@ internal fun MessageInput(
if (attachments.isNotEmpty()) {
val maxAttachmentHeight = 140.dp
FlowRow(
- modifier = Modifier
- .fillMaxWidth()
- .heightIn(max = maxAttachmentHeight)
- .verticalScroll(rememberScrollState())
- .padding(horizontal = EnsuSpacing.pageHorizontal.dp),
+ modifier =
+ Modifier.fillMaxWidth()
+ .heightIn(max = maxAttachmentHeight)
+ .verticalScroll(rememberScrollState())
+ .padding(horizontal = EnsuSpacing.pageHorizontal.dp),
horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
) {
attachments.forEach { attachment ->
if (attachment.type == AttachmentType.Image && attachment.localPath != null) {
@@ -146,7 +142,7 @@ internal fun MessageInput(
width = 76.dp,
height = 76.dp,
isUploading = attachment.isUploading,
- onDelete = { onRemoveAttachment(attachment) }
+ onDelete = { onRemoveAttachment(attachment) },
)
} else {
io.ente.ensu.components.AttachmentChip(
@@ -154,7 +150,7 @@ internal fun MessageInput(
size = attachment.sizeBytes.formattedFileSize(),
iconRes = HugeIcons.Attachment01Icon,
isUploading = attachment.isUploading,
- onDelete = { onRemoveAttachment(attachment) }
+ onDelete = { onRemoveAttachment(attachment) },
)
}
}
@@ -164,7 +160,7 @@ internal fun MessageInput(
if (isProcessingAttachments) {
Row(
modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
@@ -175,19 +171,22 @@ internal fun MessageInput(
voiceInputState.statusText()?.let { status ->
Row(
modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
when (voiceInputState) {
is VoiceInputState.Downloading,
VoiceInputState.Transcribing -> {
- CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
+ CircularProgressIndicator(
+ modifier = Modifier.size(16.dp),
+ strokeWidth = 2.dp,
+ )
}
VoiceInputState.Recording -> {
Icon(
painter = painterResource(HugeIcons.Mic02Icon),
contentDescription = null,
modifier = Modifier.size(16.dp),
- tint = EnsuColor.stopButton
+ tint = EnsuColor.stopButton,
)
}
is VoiceInputState.Error -> {
@@ -195,7 +194,7 @@ internal fun MessageInput(
imageVector = Icons.Rounded.ErrorOutline,
contentDescription = null,
modifier = Modifier.size(16.dp),
- tint = EnsuColor.stopButton
+ tint = EnsuColor.stopButton,
)
}
VoiceInputState.Idle -> Unit
@@ -204,29 +203,33 @@ internal fun MessageInput(
Text(
text = status,
style = EnsuTypography.small,
- color = if (voiceInputState is VoiceInputState.Error) {
- EnsuColor.stopButton
- } else {
- EnsuColor.textMuted()
- }
+ color =
+ if (voiceInputState is VoiceInputState.Error) {
+ EnsuColor.stopButton
+ } else {
+ EnsuColor.textMuted()
+ },
)
}
}
Box(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- .padding(bottom = bottomPadding)
- .background(EnsuColor.fillFaint(), RoundedCornerShape((EnsuCornerRadius.input + 4).dp))
- .padding(
- horizontal = EnsuSpacing.inputHorizontal.dp,
- vertical = inputVerticalPadding
- )
+ modifier =
+ Modifier.fillMaxWidth()
+ .padding(horizontal = EnsuSpacing.pageHorizontal.dp)
+ .padding(bottom = bottomPadding)
+ .background(
+ EnsuColor.fillFaint(),
+ RoundedCornerShape((EnsuCornerRadius.input + 4).dp),
+ )
+ .padding(
+ horizontal = EnsuSpacing.inputHorizontal.dp,
+ vertical = inputVerticalPadding,
+ )
) {
Row(
modifier = Modifier.fillMaxWidth(),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
BasicTextField(
value = fieldValue,
@@ -234,22 +237,23 @@ internal fun MessageInput(
fieldValue = newValue
onMessageChange(newValue.text)
},
- modifier = Modifier
- .weight(1f)
- .focusRequester(focusRequester)
- .focusable(),
+ modifier = Modifier.weight(1f).focusRequester(focusRequester).focusable(),
textStyle = EnsuTypography.message.copy(color = EnsuColor.textPrimary()),
minLines = 1,
maxLines = 5,
- keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),
- cursorBrush = SolidColor(EnsuColor.accent())
+ keyboardOptions =
+ KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),
+ cursorBrush = SolidColor(EnsuColor.accent()),
) { innerTextField ->
- Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterStart) {
+ Box(
+ modifier = Modifier.fillMaxWidth(),
+ contentAlignment = Alignment.CenterStart,
+ ) {
if (fieldValue.text.isBlank()) {
Text(
text = placeholder,
style = EnsuTypography.message,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
innerTextField()
@@ -259,32 +263,31 @@ internal fun MessageInput(
Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
if (editingMessage == null) {
- val canAddImageAttachment = !isGenerating &&
- !isDownloading &&
- !isImageAttachmentLimitReached
+ val canAddImageAttachment =
+ !isGenerating && !isDownloading && !isImageAttachmentLimitReached
IconButton(
onClick = {
haptic.perform(HapticFeedbackType.TextHandleMove)
onAttachmentSelected(AttachmentType.Image)
},
enabled = canAddImageAttachment,
- modifier = Modifier.size(36.dp)
+ modifier = Modifier.size(36.dp),
) {
Icon(
painter = painterResource(HugeIcons.Upload01Icon),
contentDescription = "Attach",
- modifier = Modifier.size(18.dp)
+ modifier = Modifier.size(18.dp),
)
}
}
if (editingMessage == null) {
- val isVoiceBusy = voiceInputState is VoiceInputState.Downloading ||
- voiceInputState is VoiceInputState.Transcribing
- val canUseVoice = voiceInputState.isRecording ||
- (!isGenerating &&
- !isDownloading &&
- !isVoiceBusy)
+ val isVoiceBusy =
+ voiceInputState is VoiceInputState.Downloading ||
+ voiceInputState is VoiceInputState.Transcribing
+ val canUseVoice =
+ voiceInputState.isRecording ||
+ (!isGenerating && !isDownloading && !isVoiceBusy)
IconButton(
onClick = {
@@ -298,29 +301,33 @@ internal fun MessageInput(
onVoiceInput()
},
enabled = canUseVoice,
- modifier = Modifier.size(36.dp)
+ modifier = Modifier.size(36.dp),
) {
if (isVoiceBusy) {
- CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
+ CircularProgressIndicator(
+ modifier = Modifier.size(16.dp),
+ strokeWidth = 2.dp,
+ )
} else if (voiceInputState.isRecording) {
Icon(
painter = painterResource(HugeIcons.StopIcon),
contentDescription = "Stop dictation",
modifier = Modifier.size(18.dp),
- tint = EnsuColor.stopButton
+ tint = EnsuColor.stopButton,
)
} else {
Icon(
painter = painterResource(HugeIcons.Mic02Icon),
contentDescription = "Dictate",
- modifier = Modifier.size(18.dp)
+ modifier = Modifier.size(18.dp),
)
}
}
}
- val canSend = (messageText.isNotBlank() || attachments.isNotEmpty()) &&
- !voiceInputState.blocksSend
+ val canSend =
+ (messageText.isNotBlank() || attachments.isNotEmpty()) &&
+ !voiceInputState.blocksSend
IconButton(
onClick = {
@@ -333,30 +340,30 @@ internal fun MessageInput(
}
},
enabled = isGenerating || (!isDownloading && canSend),
- modifier = Modifier.size(36.dp)
+ modifier = Modifier.size(36.dp),
) {
- val iconRes = when {
- isGenerating -> HugeIcons.StopIcon
- else -> HugeIcons.Navigation06Icon
- }
- val tint = when {
- isGenerating -> EnsuColor.stopButton
- canSend -> EnsuColor.textPrimary()
- else -> EnsuColor.textMuted()
- }
+ val iconRes =
+ when {
+ isGenerating -> HugeIcons.StopIcon
+ else -> HugeIcons.Navigation06Icon
+ }
+ val tint =
+ when {
+ isGenerating -> EnsuColor.stopButton
+ canSend -> EnsuColor.textPrimary()
+ else -> EnsuColor.textMuted()
+ }
val rotation = if (iconRes == HugeIcons.Navigation06Icon) 90f else 0f
if (iconRes == HugeIcons.StopIcon) {
Box(
- modifier = Modifier
- .size(22.dp)
- .background(Color.White, CircleShape),
- contentAlignment = Alignment.Center
+ modifier = Modifier.size(22.dp).background(Color.White, CircleShape),
+ contentAlignment = Alignment.Center,
) {
Icon(
painter = painterResource(iconRes),
contentDescription = "Send",
modifier = Modifier.size(12.dp),
- tint = EnsuColor.stopButton
+ tint = EnsuColor.stopButton,
)
}
} else {
@@ -364,7 +371,7 @@ internal fun MessageInput(
painter = painterResource(iconRes),
contentDescription = "Send",
modifier = Modifier.size(18.dp).rotate(rotation),
- tint = tint
+ tint = tint,
)
}
}
@@ -377,35 +384,30 @@ internal fun MessageInput(
private fun EditBanner(message: ChatMessage, onCancelEdit: () -> Unit) {
val haptic = rememberHaptics()
Row(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = EnsuSpacing.pageHorizontal.dp)
- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp))
- .height(IntrinsicSize.Min)
+ modifier =
+ Modifier.fillMaxWidth()
+ .padding(horizontal = EnsuSpacing.pageHorizontal.dp)
+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp))
+ .height(IntrinsicSize.Min)
) {
- Box(
- modifier = Modifier
- .fillMaxHeight()
- .width(3.dp)
- .background(EnsuColor.accent())
- )
+ Box(modifier = Modifier.fillMaxHeight().width(3.dp).background(EnsuColor.accent()))
Row(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = EnsuSpacing.md.dp, vertical = EnsuSpacing.sm.dp),
- verticalAlignment = Alignment.CenterVertically
+ modifier =
+ Modifier.fillMaxWidth()
+ .padding(horizontal = EnsuSpacing.md.dp, vertical = EnsuSpacing.sm.dp),
+ verticalAlignment = Alignment.CenterVertically,
) {
Icon(
painter = painterResource(HugeIcons.Edit01Icon),
contentDescription = null,
tint = EnsuColor.action(),
- modifier = Modifier.size(14.dp)
+ modifier = Modifier.size(14.dp),
)
Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
Text(
text = "Editing:",
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
Spacer(modifier = Modifier.width(EnsuSpacing.xs.dp))
Text(
@@ -414,19 +416,19 @@ private fun EditBanner(message: ChatMessage, onCancelEdit: () -> Unit) {
color = EnsuColor.textPrimary(),
maxLines = 1,
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
- modifier = Modifier.weight(1f)
+ modifier = Modifier.weight(1f),
)
IconButton(
onClick = {
haptic.perform(HapticFeedbackType.TextHandleMove)
onCancelEdit()
},
- modifier = Modifier.size(24.dp)
+ modifier = Modifier.size(24.dp),
) {
Icon(
painter = painterResource(HugeIcons.Cancel01Icon),
contentDescription = "Cancel edit",
- tint = EnsuColor.textMuted()
+ tint = EnsuColor.textMuted(),
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatMessages.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatMessages.kt
index 85d9b38411..6fecb316d3 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatMessages.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatMessages.kt
@@ -1,16 +1,13 @@
package io.ente.ensu.chat
import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
-import androidx.compose.animation.scaleIn
-import androidx.compose.animation.shrinkVertically
-import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.isSystemInDarkTheme
-import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -23,15 +20,15 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
-import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
-import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenuItem
@@ -40,9 +37,9 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
-import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -64,35 +61,31 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
+import io.ente.ensu.bindings.GroundedSource
+import io.ente.ensu.bindings.parseGroundedAssistantText
import io.ente.ensu.components.AttributionDialog
import io.ente.ensu.components.AttributionLink
-import io.ente.ensu.components.KnowledgeCard
import io.ente.ensu.components.BranchSwitcher
import io.ente.ensu.components.ImageAttachmentThumbnail
+import io.ente.ensu.components.KnowledgeCard
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
-import io.ente.ensu.chat.Attachment
-import io.ente.ensu.chat.AttachmentType
-import io.ente.ensu.chat.ChatMessage
-import io.ente.ensu.chat.MessageAuthor
import io.ente.ensu.format.formatBytes
import io.ente.ensu.format.formattedFileSize
+import io.ente.ensu.llm.DownloadPhase
import io.ente.ensu.notes.LocalNotesStore
import io.ente.ensu.platform.rememberHaptics
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.flow.collect
-import kotlinx.coroutines.flow.distinctUntilChanged
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.roundToInt
import kotlin.math.roundToLong
-import io.ente.ensu.llm.DownloadPhase
-import io.ente.ensu.bindings.GroundedSource
-import io.ente.ensu.bindings.parseGroundedAssistantText
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.flow.distinctUntilChanged
@Composable
internal fun MessageList(
@@ -114,7 +107,7 @@ internal fun MessageList(
onRetryMessage: (ChatMessage) -> Unit,
onBranchChange: (String, Int) -> Unit,
onOpenAttachment: (Attachment) -> Unit,
- onStartDownload: (Boolean) -> Unit
+ onStartDownload: (Boolean) -> Unit,
) {
if (isModelStateKnown && !isModelDownloaded && !isChatUnsupported) {
DownloadOnboarding(
@@ -124,7 +117,7 @@ internal fun MessageList(
downloadStatus = downloadStatus,
downloadPhase = downloadPhase,
modelDownloadSizeBytes = modelDownloadSizeBytes,
- onDownload = { onStartDownload(true) }
+ onDownload = { onStartDownload(true) },
)
return
}
@@ -135,14 +128,15 @@ internal fun MessageList(
EmptyState(
modifier = modifier,
title = "Welcome",
- subtitle = "Type a message to start chatting"
+ subtitle = "Type a message to start chatting",
)
return
}
- val listState = rememberLazyListState(
- initialFirstVisibleItemIndex = if (messages.isNotEmpty()) messages.size else 0
- )
+ val listState =
+ rememberLazyListState(
+ initialFirstVisibleItemIndex = if (messages.isNotEmpty()) messages.size else 0
+ )
val haptic = rememberHaptics()
var autoScrollEnabled by remember { mutableStateOf(true) }
var isAutoScrolling by remember { mutableStateOf(false) }
@@ -153,18 +147,13 @@ internal fun MessageList(
var lastUserMessageId by remember { mutableStateOf<String?>(null) }
var previousScrollIndex by remember { mutableStateOf(listState.firstVisibleItemIndex) }
var previousScrollOffset by remember { mutableStateOf(listState.firstVisibleItemScrollOffset) }
- val isAtBottom by remember {
- derivedStateOf {
- !listState.canScrollForward
- }
- }
- val bottomItemIndex by remember(messages.size, isGenerating) {
- derivedStateOf {
- messages.size +
- (if (isGenerating) 1 else 0) +
- (if (messages.isNotEmpty()) 1 else 0)
+ val isAtBottom by remember { derivedStateOf { !listState.canScrollForward } }
+ val bottomItemIndex by
+ remember(messages.size, isGenerating) {
+ derivedStateOf {
+ messages.size + (if (isGenerating) 1 else 0) + (if (messages.isNotEmpty()) 1 else 0)
+ }
}
- }
val streamingAnchorId = if (isGenerating) streamingParentId else null
@@ -179,7 +168,9 @@ internal fun MessageList(
LaunchedEffect(lastMessage?.id) {
if (lastMessage == null) {
lastUserMessageId = null
- } else if (lastMessage.author == MessageAuthor.User && lastMessage.id != lastUserMessageId) {
+ } else if (
+ lastMessage.author == MessageAuthor.User && lastMessage.id != lastUserMessageId
+ ) {
lastUserMessageId = lastMessage.id
if (!listState.isScrollInProgress || isAtBottom) {
autoScrollEnabled = true
@@ -201,19 +192,21 @@ internal fun MessageList(
Triple(
listState.firstVisibleItemIndex,
listState.firstVisibleItemScrollOffset,
- listState.isScrollInProgress
+ listState.isScrollInProgress,
)
- }.collect { (index, offset, isScrolling) ->
- if (isScrolling && !isAutoScrolling && !isAtBottom) {
- val movedTowardTop = index < previousScrollIndex ||
- (index == previousScrollIndex && offset < previousScrollOffset)
- if (movedTowardTop) {
- autoScrollEnabled = false
+ }
+ .collect { (index, offset, isScrolling) ->
+ if (isScrolling && !isAutoScrolling && !isAtBottom) {
+ val movedTowardTop =
+ index < previousScrollIndex ||
+ (index == previousScrollIndex && offset < previousScrollOffset)
+ if (movedTowardTop) {
+ autoScrollEnabled = false
+ }
}
+ previousScrollIndex = index
+ previousScrollOffset = offset
}
- previousScrollIndex = index
- previousScrollOffset = offset
- }
}
LaunchedEffect(isAtBottom) {
@@ -230,7 +223,13 @@ internal fun MessageList(
}
}
- LaunchedEffect(messages.size, streamingResponse, streamingParentId, isGenerating, autoScrollEnabled) {
+ LaunchedEffect(
+ messages.size,
+ streamingResponse,
+ streamingParentId,
+ isGenerating,
+ autoScrollEnabled,
+ ) {
if (!autoScrollEnabled) return@LaunchedEffect
if (listState.isScrollInProgress && !isAutoScrolling) return@LaunchedEffect
val targetIndex = bottomItemIndex
@@ -291,11 +290,12 @@ internal fun MessageList(
LazyColumn(
modifier = modifier,
state = listState,
- contentPadding = PaddingValues(
- top = EnsuSpacing.pageVertical.dp,
- bottom = (EnsuSpacing.xxxl + EnsuSpacing.xl).dp
- ),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)
+ contentPadding =
+ PaddingValues(
+ top = EnsuSpacing.pageVertical.dp,
+ bottom = (EnsuSpacing.xxxl + EnsuSpacing.xl).dp,
+ ),
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp),
) {
messages.forEach { message ->
item(key = message.id) {
@@ -306,7 +306,7 @@ internal fun MessageList(
branchSelections = branchSelections,
onEdit = { onEditMessage(message) },
onBranchChange = onBranchChange,
- onOpenAttachment = onOpenAttachment
+ onOpenAttachment = onOpenAttachment,
)
}
MessageAuthor.Assistant -> {
@@ -316,7 +316,7 @@ internal fun MessageList(
branchSelections = branchSelections,
onRetry = { onRetryMessage(message) },
onBranchChange = onBranchChange,
- showsMetadata = true
+ showsMetadata = true,
)
}
}
@@ -326,7 +326,7 @@ internal fun MessageList(
item(key = "streaming") {
StreamingMessageBubble(
text = streamingResponse,
- isGenerating = true
+ isGenerating = true,
)
}
}
@@ -336,20 +336,16 @@ internal fun MessageList(
item(key = "streaming") {
StreamingMessageBubble(
text = streamingResponse,
- isGenerating = true
+ isGenerating = true,
)
}
}
if (messages.isNotEmpty()) {
- item(key = "ai-safety-footer") {
- AiSafetyFooter()
- }
+ item(key = "ai-safety-footer") { AiSafetyFooter() }
}
- item(key = "bottom") {
- Spacer(modifier = Modifier.height(1.dp))
- }
+ item(key = "bottom") { Spacer(modifier = Modifier.height(1.dp)) }
}
}
@@ -357,18 +353,18 @@ internal fun MessageList(
private fun EmptyState(
modifier: Modifier,
title: String,
- subtitle: String? = null
+ subtitle: String? = null,
) {
Box(
modifier = modifier.fillMaxSize(),
- contentAlignment = Alignment.Center
+ contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = title,
style = EnsuTypography.h2,
color = EnsuColor.textPrimary(),
- textAlign = TextAlign.Center
+ textAlign = TextAlign.Center,
)
if (subtitle != null) {
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
@@ -376,7 +372,7 @@ private fun EmptyState(
text = subtitle,
style = EnsuTypography.body,
color = EnsuColor.textMuted(),
- textAlign = TextAlign.Center
+ textAlign = TextAlign.Center,
)
}
}
@@ -390,9 +386,7 @@ private fun AiSafetyFooter() {
style = EnsuTypography.small.copy(fontSize = 12.sp),
color = EnsuColor.textMuted(),
textAlign = TextAlign.Center,
- modifier = Modifier
- .fillMaxWidth()
- .padding(top = EnsuSpacing.sm.dp)
+ modifier = Modifier.fillMaxWidth().padding(top = EnsuSpacing.sm.dp),
)
}
@@ -404,41 +398,47 @@ private fun DownloadOnboarding(
downloadStatus: String?,
downloadPhase: DownloadPhase?,
modelDownloadSizeBytes: Long?,
- onDownload: () -> Unit
+ onDownload: () -> Unit,
) {
val haptic = rememberHaptics()
val downloadAccent = EnsuColor.accentDark
val downloadButtonTextColor = Color.Black
- val sizeText = modelDownloadSizeBytes?.let { "Approx. ${formatBytes(it)}" } ?: "Approx. size varies by model"
+ val sizeText =
+ modelDownloadSizeBytes?.let { "Approx. ${formatBytes(it)}" }
+ ?: "Approx. size varies by model"
Box(
modifier = modifier.fillMaxSize(),
- contentAlignment = Alignment.Center
+ contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Download to begin using the Chat",
style = EnsuTypography.large,
color = EnsuColor.textPrimary(),
- textAlign = TextAlign.Center
+ textAlign = TextAlign.Center,
)
Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
if (isDownloading) {
val isLoadingModel = downloadPhase == DownloadPhase.Loading
val showProgress = downloadPercent != null || isLoadingModel
- val statusText = when {
- isLoadingModel -> downloadStatus
- modelDownloadSizeBytes != null && downloadPercent != null && downloadPercent >= 0 -> {
- val downloadedBytes = (modelDownloadSizeBytes * (downloadPercent / 100f)).roundToLong()
- "Downloading... ${formatBytes(downloadedBytes)} / ${formatBytes(modelDownloadSizeBytes)}"
+ val statusText =
+ when {
+ isLoadingModel -> downloadStatus
+ modelDownloadSizeBytes != null &&
+ downloadPercent != null &&
+ downloadPercent >= 0 -> {
+ val downloadedBytes =
+ (modelDownloadSizeBytes * (downloadPercent / 100f)).roundToLong()
+ "Downloading... ${formatBytes(downloadedBytes)} / ${formatBytes(modelDownloadSizeBytes)}"
+ }
+ !downloadStatus.isNullOrBlank() -> downloadStatus
+ else -> "Downloading..."
}
- !downloadStatus.isNullOrBlank() -> downloadStatus
- else -> "Downloading..."
- }
Text(
text = statusText ?: "Downloading...",
style = EnsuTypography.body.copy(fontFeatureSettings = "tnum"),
color = EnsuColor.textMuted(),
- textAlign = TextAlign.Center
+ textAlign = TextAlign.Center,
)
if (showProgress) {
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
@@ -448,17 +448,13 @@ private fun DownloadOnboarding(
progress = { clamped / 100f },
color = downloadAccent,
trackColor = EnsuColor.border(),
- modifier = Modifier
- .fillMaxWidth(0.6f)
- .height(6.dp)
+ modifier = Modifier.fillMaxWidth(0.6f).height(6.dp),
)
} else {
LinearProgressIndicator(
color = downloadAccent,
trackColor = EnsuColor.border(),
- modifier = Modifier
- .fillMaxWidth(0.6f)
- .height(6.dp)
+ modifier = Modifier.fillMaxWidth(0.6f).height(6.dp),
)
}
}
@@ -467,12 +463,13 @@ private fun DownloadOnboarding(
Text(
text = downloadStatus,
style = EnsuTypography.body,
- color = if (downloadPhase == DownloadPhase.Failed) {
- EnsuColor.error
- } else {
- EnsuColor.textMuted()
- },
- textAlign = TextAlign.Center
+ color =
+ if (downloadPhase == DownloadPhase.Failed) {
+ EnsuColor.error
+ } else {
+ EnsuColor.textMuted()
+ },
+ textAlign = TextAlign.Center,
)
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
}
@@ -482,15 +479,19 @@ private fun DownloadOnboarding(
onDownload()
},
shape = RoundedCornerShape(EnsuCornerRadius.button.dp),
- colors = ButtonDefaults.buttonColors(containerColor = downloadAccent)
+ colors = ButtonDefaults.buttonColors(containerColor = downloadAccent),
) {
- Text(text = "Download", style = EnsuTypography.body, color = downloadButtonTextColor)
+ Text(
+ text = "Download",
+ style = EnsuTypography.body,
+ color = downloadButtonTextColor,
+ )
}
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
Text(
text = sizeText,
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
}
@@ -504,26 +505,25 @@ private fun UserMessageBubble(
branchSelections: Map<String, Int>,
onEdit: () -> Unit,
onBranchChange: (String, Int) -> Unit,
- onOpenAttachment: (Attachment) -> Unit
+ onOpenAttachment: (Attachment) -> Unit,
) {
val clipboard = LocalClipboardManager.current
val haptic = rememberHaptics()
var showMenu by remember { mutableStateOf(false) }
var pressOffset by remember { mutableStateOf(Offset.Zero) }
val bubbleShape = RoundedCornerShape(18.dp)
- val bubbleFill = if (isSystemInDarkTheme()) EnsuColor.fillFaint() else EnsuColor.border().copy(alpha = 0.2f)
+ val bubbleFill =
+ if (isSystemInDarkTheme()) EnsuColor.fillFaint() else EnsuColor.border().copy(alpha = 0.2f)
Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(start = EnsuSpacing.messageBubbleInset.dp),
- horizontalAlignment = Alignment.End
+ modifier = Modifier.fillMaxWidth().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)
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
) {
message.attachments.forEach { attachment ->
if (attachment.type == AttachmentType.Image && attachment.localPath != null) {
@@ -536,21 +536,24 @@ private fun UserMessageBubble(
portraitHeight = 164.dp,
squareSize = 140.dp,
isUploading = attachment.isUploading,
- onClick = { onOpenAttachment(attachment) }
+ onClick = { onOpenAttachment(attachment) },
)
} else {
io.ente.ensu.components.AttachmentChip(
name = attachment.name,
- size = if (attachment.localPath == null) {
- "Unavailable on this device"
- } else {
- attachment.sizeBytes.formattedFileSize()
- },
+ size =
+ if (attachment.localPath == null) {
+ "Unavailable on this device"
+ } else {
+ attachment.sizeBytes.formattedFileSize()
+ },
iconRes = HugeIcons.Attachment01Icon,
isUploading = attachment.isUploading,
- onClick = if (attachment.localPath == null) null else {
- { onOpenAttachment(attachment) }
- }
+ onClick =
+ if (attachment.localPath == null) null
+ else {
+ { onOpenAttachment(attachment) }
+ },
)
}
}
@@ -560,24 +563,24 @@ private fun UserMessageBubble(
Box {
Column(
- modifier = Modifier
- .background(bubbleFill, bubbleShape)
- .pointerInput(Unit) {
- detectTapGestures(
- onLongPress = { offset ->
- haptic.perform(HapticFeedbackType.LongPress)
- pressOffset = offset
- showMenu = true
- }
- )
- }
- .padding(EnsuSpacing.md.dp)
+ modifier =
+ Modifier.background(bubbleFill, bubbleShape)
+ .pointerInput(Unit) {
+ detectTapGestures(
+ onLongPress = { offset ->
+ haptic.perform(HapticFeedbackType.LongPress)
+ pressOffset = offset
+ showMenu = true
+ }
+ )
+ }
+ .padding(EnsuSpacing.md.dp)
) {
Text(
text = message.text,
style = EnsuTypography.message,
color = EnsuColor.userMessageText(),
- textAlign = TextAlign.Start
+ textAlign = TextAlign.Start,
)
}
@@ -585,16 +588,17 @@ private fun UserMessageBubble(
showMenu = showMenu,
pressOffset = pressOffset,
onDismiss = { showMenu = false },
- actions = listOf(
- MessageAction("Edit", HugeIcons.Edit01Icon) {
- haptic.perform(HapticFeedbackType.TextHandleMove)
- onEdit()
- },
- MessageAction("Copy", HugeIcons.Copy01Icon) {
- haptic.perform(HapticFeedbackType.TextHandleMove)
- clipboard.setText(AnnotatedString(message.text))
- }
- )
+ actions =
+ listOf(
+ MessageAction("Edit", HugeIcons.Edit01Icon) {
+ haptic.perform(HapticFeedbackType.TextHandleMove)
+ onEdit()
+ },
+ MessageAction("Copy", HugeIcons.Copy01Icon) {
+ haptic.perform(HapticFeedbackType.TextHandleMove)
+ clipboard.setText(AnnotatedString(message.text))
+ },
+ ),
)
}
@@ -613,7 +617,7 @@ private fun UserMessageBubble(
onNext = {
val current = branchSelections[message.id] ?: 1
onBranchChange(message.id, (current + 1).coerceAtMost(message.branchCount))
- }
+ },
)
Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
}
@@ -630,7 +634,7 @@ private fun AssistantMessageBubble(
branchSelections: Map<String, Int>,
onRetry: () -> Unit,
onBranchChange: (String, Int) -> Unit,
- showsMetadata: Boolean
+ showsMetadata: Boolean,
) {
val clipboard = LocalClipboardManager.current
val parsed = remember(message.text) { parseGroundedAssistantText(message.text) }
@@ -640,64 +644,69 @@ private fun AssistantMessageBubble(
var pressOffset by remember { mutableStateOf(Offset.Zero) }
Column(
modifier = Modifier.fillMaxWidth(),
- horizontalAlignment = Alignment.Start
+ horizontalAlignment = Alignment.Start,
) {
val actions = buildList {
if (!message.isSynthetic) {
- add(MessageAction("Copy", HugeIcons.Copy01Icon) {
- haptic.perform(HapticFeedbackType.TextHandleMove)
- clipboard.setText(AnnotatedString(stripHiddenMessageParts(parsed.text)))
- })
+ add(
+ MessageAction("Copy", HugeIcons.Copy01Icon) {
+ haptic.perform(HapticFeedbackType.TextHandleMove)
+ clipboard.setText(AnnotatedString(stripHiddenMessageParts(parsed.text)))
+ }
+ )
}
if (!message.isSynthetic || isLastMessage) {
- add(MessageAction("Retry", HugeIcons.RepeatIcon) {
- haptic.perform(HapticFeedbackType.TextHandleMove)
- onRetry()
- })
+ add(
+ MessageAction("Retry", HugeIcons.RepeatIcon) {
+ haptic.perform(HapticFeedbackType.TextHandleMove)
+ onRetry()
+ }
+ )
}
}
Box {
Column(
- modifier = Modifier
- .fillMaxWidth()
- .pointerInput(message.id, message.isSynthetic, isLastMessage) {
- detectTapGestures(
- onLongPress = { offset ->
- if (actions.isEmpty()) return@detectTapGestures
- haptic.perform(HapticFeedbackType.LongPress)
- pressOffset = offset
- showMenu = true
- }
- )
- }
- .padding(horizontal = EnsuSpacing.sm.dp, vertical = EnsuSpacing.md.dp)
+ modifier =
+ Modifier.fillMaxWidth()
+ .pointerInput(message.id, message.isSynthetic, isLastMessage) {
+ detectTapGestures(
+ onLongPress = { offset ->
+ if (actions.isEmpty()) return@detectTapGestures
+ haptic.perform(HapticFeedbackType.LongPress)
+ pressOffset = offset
+ showMenu = true
+ }
+ )
+ }
+ .padding(horizontal = EnsuSpacing.sm.dp, vertical = EnsuSpacing.md.dp)
) {
MarkdownView(
markdown = stripHiddenMessageParts(parsed.text),
- enableSelection = false
+ enableSelection = false,
)
if (parsed.sourceLabels.isNotEmpty()) {
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp)
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp),
) {
parsed.sourceLabels.forEach { label ->
Surface(
onClick = { showSources = true },
color = EnsuColor.fillFaint(),
- shape = RoundedCornerShape(EnsuCornerRadius.button.dp)
+ shape = RoundedCornerShape(EnsuCornerRadius.button.dp),
) {
Text(
text = label,
style = EnsuTypography.small,
color = EnsuColor.textPrimary(),
- modifier = Modifier.padding(
- horizontal = EnsuSpacing.md.dp,
- vertical = EnsuSpacing.sm.dp
- )
+ modifier =
+ Modifier.padding(
+ horizontal = EnsuSpacing.md.dp,
+ vertical = EnsuSpacing.sm.dp,
+ ),
)
}
}
@@ -709,7 +718,7 @@ private fun AssistantMessageBubble(
Text(
text = "Interrupted",
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
}
@@ -718,18 +727,21 @@ private fun AssistantMessageBubble(
showMenu = showMenu,
pressOffset = pressOffset,
onDismiss = { showMenu = false },
- actions = actions
+ actions = actions,
)
}
AnimatedVisibility(
visible = showsMetadata,
enter = fadeIn(animationSpec = tween(durationMillis = 300)),
- exit = fadeOut(animationSpec = tween(durationMillis = 150))
+ exit = fadeOut(animationSpec = tween(durationMillis = 150)),
) {
Column {
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
- Row(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp), verticalAlignment = Alignment.CenterVertically) {
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
TimestampText(message.timestampMillis)
if (message.branchCount > 1) {
BranchSwitcher(
@@ -741,8 +753,11 @@ private fun AssistantMessageBubble(
},
onNext = {
val current = branchSelections[message.id] ?: 1
- onBranchChange(message.id, (current + 1).coerceAtMost(message.branchCount))
- }
+ onBranchChange(
+ message.id,
+ (current + 1).coerceAtMost(message.branchCount),
+ )
+ },
)
}
}
@@ -752,7 +767,7 @@ private fun AssistantMessageBubble(
if (showSources) {
KnowledgeSourcesDialog(
citations = parsed.sources,
- onDismiss = { showSources = false }
+ onDismiss = { showSources = false },
)
}
}
@@ -762,11 +777,13 @@ private fun AssistantMessageBubble(
@Composable
private fun KnowledgeSourcesDialog(
citations: List<GroundedSource>,
- onDismiss: () -> Unit
+ onDismiss: () -> Unit,
) {
val uriHandler = LocalUriHandler.current
val notes = LocalNotesStore.current
- val notesState = if (citations.any { it is GroundedSource.LocalNote }) notes?.state?.collectAsState()?.value else null
+ val notesState =
+ if (citations.any { it is GroundedSource.LocalNote }) notes?.state?.collectAsState()?.value
+ else null
AttributionDialog(title = "Sources", onDismiss = onDismiss) {
notesState?.error?.let { error ->
Text(error, style = EnsuTypography.small, color = EnsuColor.error)
@@ -776,38 +793,42 @@ private fun KnowledgeSourcesDialog(
val citation = (source as? GroundedSource.EnsuPack)?.citation
KnowledgeCard(padding = EnsuSpacing.md.dp, spacing = EnsuSpacing.sm.dp) {
Text(
- text = buildString {
- append("SOURCE ${index + 1} Β· ")
- if (note != null) {
- append("YOUR NOTES")
- note.collectionLabel?.let { append(" Β· ${it.uppercase()}") }
- } else if (citation != null) {
- append("ENSU PACK Β· ${citation.datasetLabel.uppercase()}")
- }
- },
+ text =
+ buildString {
+ append("SOURCE ${index + 1} Β· ")
+ if (note != null) {
+ append("YOUR NOTES")
+ note.collectionLabel?.let { append(" Β· ${it.uppercase()}") }
+ } else if (citation != null) {
+ append("ENSU PACK Β· ${citation.datasetLabel.uppercase()}")
+ }
+ },
style = EnsuTypography.mini,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
Text(
text = note?.title ?: citation?.title.orEmpty(),
style = EnsuTypography.large,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
- note?.section?.takeIf { it.isNotBlank() }?.let {
- Text(it, style = EnsuTypography.small, color = EnsuColor.textMuted())
- }
+ note
+ ?.section
+ ?.takeIf { it.isNotBlank() }
+ ?.let { Text(it, style = EnsuTypography.small, color = EnsuColor.textMuted()) }
HorizontalDivider(color = EnsuColor.border())
Text(
text = note?.documentId ?: citation?.credit.orEmpty(),
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
FlowRow(horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)) {
if (note != null) {
AttributionLink("Open note β†—") { notes?.open(note) }
} else if (citation != null) {
AttributionLink("Open source β†—") { uriHandler.openUri(citation.sourceUrl) }
- AttributionLink("${citation.licenseLabel} β†—") { uriHandler.openUri(citation.licenseUrl) }
+ AttributionLink("${citation.licenseLabel} β†—") {
+ uriHandler.openUri(citation.licenseUrl)
+ }
}
}
}
@@ -818,7 +839,7 @@ private fun KnowledgeSourcesDialog(
private data class MessageAction(
val label: String,
val iconRes: Int,
- val onClick: () -> Unit
+ val onClick: () -> Unit,
)
@Composable
@@ -826,7 +847,7 @@ private fun MessageActionsMenu(
showMenu: Boolean,
pressOffset: Offset,
onDismiss: () -> Unit,
- actions: List<MessageAction>
+ actions: List<MessageAction>,
) {
if (!showMenu || actions.isEmpty()) return
val menuSurface = if (isSystemInDarkTheme()) Color(0xFF1C1C1E) else Color.White
@@ -836,18 +857,16 @@ private fun MessageActionsMenu(
alignment = Alignment.TopStart,
offset = offset,
onDismissRequest = onDismiss,
- properties = PopupProperties(focusable = true)
+ properties = PopupProperties(focusable = true),
) {
Surface(
modifier = Modifier.wrapContentSize(),
color = menuSurface,
shadowElevation = 4.dp,
- shape = RoundedCornerShape(12.dp)
+ shape = RoundedCornerShape(12.dp),
) {
Column(
- modifier = Modifier
- .width(IntrinsicSize.Min)
- .padding(vertical = EnsuSpacing.xs.dp)
+ modifier = Modifier.width(IntrinsicSize.Min).padding(vertical = EnsuSpacing.xs.dp)
) {
actions.forEach { action ->
DropdownMenuItem(
@@ -855,7 +874,7 @@ private fun MessageActionsMenu(
Text(
text = action.label,
style = EnsuTypography.body,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
},
leadingIcon = {
@@ -863,13 +882,13 @@ private fun MessageActionsMenu(
painter = androidx.compose.ui.res.painterResource(action.iconRes),
contentDescription = null,
modifier = Modifier.size(18.dp),
- tint = EnsuColor.textPrimary()
+ tint = EnsuColor.textPrimary(),
)
},
onClick = {
onDismiss()
action.onClick()
- }
+ },
)
}
}
@@ -880,7 +899,7 @@ private fun MessageActionsMenu(
@Composable
private fun StreamingMessageBubble(
text: String,
- isGenerating: Boolean
+ isGenerating: Boolean,
) {
var renderedText by remember { mutableStateOf(text) }
var showCursor by remember { mutableStateOf(true) }
@@ -915,15 +934,19 @@ private fun StreamingMessageBubble(
if (!isGenerating) return
Column(
- modifier = Modifier
- .fillMaxWidth()
- .padding(horizontal = EnsuSpacing.sm.dp)
- .padding(vertical = if (hasText) EnsuSpacing.md.dp else 0.dp),
+ modifier =
+ Modifier.fillMaxWidth()
+ .padding(horizontal = EnsuSpacing.sm.dp)
+ .padding(vertical = if (hasText) EnsuSpacing.md.dp else 0.dp),
horizontalAlignment = Alignment.Start,
- verticalArrangement = Arrangement.spacedBy(if (hasText) EnsuSpacing.sm.dp else 0.dp)
+ verticalArrangement = Arrangement.spacedBy(if (hasText) EnsuSpacing.sm.dp else 0.dp),
) {
if (hasText) {
- MarkdownView(markdown = renderedText, enableSelection = false, trailingCursor = showCursor)
+ MarkdownView(
+ markdown = renderedText,
+ enableSelection = false,
+ trailingCursor = showCursor,
+ )
}
generatingDotsIndicator()
@@ -945,7 +968,7 @@ private fun generatingDotsIndicator() {
text = ".".repeat(dotCount),
style = EnsuTypography.message,
color = EnsuColor.textMuted(),
- modifier = Modifier.widthIn(min = 24.dp)
+ modifier = Modifier.widthIn(min = 24.dp),
)
}
@@ -968,7 +991,7 @@ private fun TimestampText(timestampMillis: Long) {
Text(
text = timestampFormatter.format(Date(timestampMillis)),
style = EnsuTypography.mini,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatModels.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatModels.kt
index 38c6bf6445..12c7ba5940 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatModels.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatModels.kt
@@ -4,7 +4,7 @@ import java.util.UUID
enum class MessageAuthor {
User,
- Assistant
+ Assistant,
}
data class ChatMessage(
@@ -18,19 +18,19 @@ data class ChatMessage(
val isInterrupted: Boolean = false,
val isSynthetic: Boolean = false,
val tokensPerSecond: Double? = null,
- val branchCount: Int = 1
+ val branchCount: Int = 1,
)
data class ChatSession(
val id: String = UUID.randomUUID().toString(),
val title: String,
val lastMessagePreview: String? = null,
- val updatedAtMillis: Long
+ val updatedAtMillis: Long,
)
enum class AttachmentType {
Image,
- Document
+ Document,
}
const val MaxImageAttachmentsPerMessage = 2
@@ -41,7 +41,7 @@ data class Attachment(
val sizeBytes: Long,
val type: AttachmentType,
val localPath: String? = null,
- val isUploading: Boolean = false
+ val isUploading: Boolean = false,
)
const val SessionTitleMaxLength = 40
@@ -60,8 +60,5 @@ private val TitleLineBreakRegex = Regex("[\r\n\t]+")
private val TitleWhitespaceRegex = Regex("\\s+")
internal fun sanitizeTitleText(text: String): String {
- return text
- .replace(TitleLineBreakRegex, " ")
- .replace(TitleWhitespaceRegex, " ")
- .trim()
+ return text.replace(TitleLineBreakRegex, " ").replace(TitleWhitespaceRegex, " ").trim()
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatOverlays.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatOverlays.kt
index eff8ce90cf..aa3f6ec563 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatOverlays.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatOverlays.kt
@@ -36,9 +36,10 @@ import kotlin.math.roundToLong
@Composable
internal fun OverflowDialog(
onTrim: () -> Unit,
- onCancel: () -> Unit
+ onCancel: () -> Unit,
) {
- val overflowMessage = "This conversation is too long for the model to process. Some older messages will be dropped to make room."
+ val overflowMessage =
+ "This conversation is too long for the model to process. Some older messages will be dropped to make room."
AlertDialog(
onDismissRequest = onCancel,
@@ -47,7 +48,7 @@ internal fun OverflowDialog(
Text(
text = overflowMessage,
style = EnsuTypography.body,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
},
confirmButton = {
@@ -56,11 +57,9 @@ internal fun OverflowDialog(
}
},
dismissButton = {
- TextButton(onClick = onCancel) {
- Text(text = "Cancel", color = EnsuColor.textMuted())
- }
+ TextButton(onClick = onCancel) { Text(text = "Cancel", color = EnsuColor.textMuted()) }
},
- containerColor = EnsuColor.backgroundBase()
+ containerColor = EnsuColor.backgroundBase(),
)
}
@@ -69,9 +68,7 @@ private const val UNSUPPORTED_DEVICE_MESSAGE =
"You can view existing chats, but can't send new messages."
@Composable
-internal fun UnsupportedDeviceDialog(
- onDismiss: () -> Unit
-) {
+internal fun UnsupportedDeviceDialog(onDismiss: () -> Unit) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(text = "Chat unavailable on this device", style = EnsuTypography.h3) },
@@ -79,7 +76,7 @@ internal fun UnsupportedDeviceDialog(
Text(
text = UNSUPPORTED_DEVICE_MESSAGE,
style = EnsuTypography.body,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
},
confirmButton = {
@@ -87,30 +84,29 @@ internal fun UnsupportedDeviceDialog(
Text(text = "Got it", color = EnsuColor.textPrimary())
}
},
- containerColor = EnsuColor.backgroundBase()
+ containerColor = EnsuColor.backgroundBase(),
)
}
@Composable
-internal fun UnsupportedChatInputNotice(
- modifier: Modifier = Modifier
-) {
+internal fun UnsupportedChatInputNotice(modifier: Modifier = Modifier) {
Column(
- modifier = modifier
- .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.md.dp)
- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.card.dp))
- .padding(EnsuSpacing.md.dp)
+ modifier =
+ modifier
+ .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.md.dp)
+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.card.dp))
+ .padding(EnsuSpacing.md.dp)
) {
Text(
text = "Chat unavailable on this device",
style = EnsuTypography.large,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
Text(
text = UNSUPPORTED_DEVICE_MESSAGE,
style = EnsuTypography.body,
color = EnsuColor.textMuted(),
- modifier = Modifier.padding(top = EnsuSpacing.xs.dp)
+ modifier = Modifier.padding(top = EnsuSpacing.xs.dp),
)
}
}
@@ -121,31 +117,33 @@ internal fun DownloadToastOverlay(
percent: Int,
totalBytes: Long?,
isLoading: Boolean,
- onCancel: () -> Unit
+ onCancel: () -> Unit,
) {
val haptic = rememberHaptics()
Box(
- modifier = Modifier
- .fillMaxWidth()
- .padding(top = EnsuSpacing.lg.dp),
- contentAlignment = Alignment.TopCenter
+ modifier = Modifier.fillMaxWidth().padding(top = EnsuSpacing.lg.dp),
+ contentAlignment = Alignment.TopCenter,
) {
val title = if (isLoading) "Loading model" else "Downloading model"
val clamped = percent.coerceIn(0, 100)
- val statusText = when {
- isLoading -> status
- totalBytes != null -> {
- val downloadedBytes = (totalBytes * (clamped / 100f)).roundToLong()
- "Downloading... ${formatBytes(downloadedBytes)} / ${formatBytes(totalBytes)}"
+ val statusText =
+ when {
+ isLoading -> status
+ totalBytes != null -> {
+ val downloadedBytes = (totalBytes * (clamped / 100f)).roundToLong()
+ "Downloading... ${formatBytes(downloadedBytes)} / ${formatBytes(totalBytes)}"
+ }
+ else -> status
}
- else -> status
- }
Column(
- modifier = Modifier
- .padding(horizontal = EnsuSpacing.lg.dp)
- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.toast.dp))
- .padding(EnsuSpacing.lg.dp)
- .fillMaxWidth()
+ modifier =
+ Modifier.padding(horizontal = EnsuSpacing.lg.dp)
+ .background(
+ EnsuColor.fillFaint(),
+ RoundedCornerShape(EnsuCornerRadius.toast.dp),
+ )
+ .padding(EnsuSpacing.lg.dp)
+ .fillMaxWidth()
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(text = title, style = EnsuTypography.large, color = EnsuColor.textPrimary())
@@ -155,19 +153,17 @@ internal fun DownloadToastOverlay(
haptic.perform(HapticFeedbackType.LongPress)
onCancel()
},
- modifier = Modifier.size(28.dp)
+ modifier = Modifier.size(28.dp),
) {
Box(
- modifier = Modifier
- .size(22.dp)
- .background(Color.White, CircleShape),
- contentAlignment = Alignment.Center
+ modifier = Modifier.size(22.dp).background(Color.White, CircleShape),
+ contentAlignment = Alignment.Center,
) {
Icon(
painter = painterResource(HugeIcons.StopIcon),
contentDescription = "Cancel download",
modifier = Modifier.size(12.dp),
- tint = EnsuColor.stopButton
+ tint = EnsuColor.stopButton,
)
}
}
@@ -177,14 +173,14 @@ internal fun DownloadToastOverlay(
progress = { clamped / 100f },
color = if (isLoading) EnsuColor.accent() else EnsuColor.accent(),
trackColor = EnsuColor.border(),
- modifier = Modifier.fillMaxWidth()
+ modifier = Modifier.fillMaxWidth(),
)
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = statusText,
style = EnsuTypography.small.copy(fontFeatureSettings = "tnum"),
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
Spacer(modifier = Modifier.weight(1f))
Text(text = "$clamped%", style = EnsuTypography.mini, color = EnsuColor.textMuted())
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt
index eda34aa4a6..d64d31fb91 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatRepository.kt
@@ -1,25 +1,19 @@
package io.ente.ensu.chat
import android.content.Context
-import io.ente.ensu.storage.CredentialStore
-import io.ente.ensu.storage.FilePathManager
-import io.ente.ensu.chat.Attachment
-import io.ente.ensu.chat.AttachmentType
-import io.ente.ensu.chat.ChatMessage
-import io.ente.ensu.chat.ChatSession
-import io.ente.ensu.chat.MessageAuthor
-import io.ente.ensu.chat.sessionTitleFromText
import io.ente.ensu.bindings.DbAttachmentKind
import io.ente.ensu.bindings.DbAttachmentMeta
+import io.ente.ensu.bindings.DbException
import io.ente.ensu.bindings.DbSender
import io.ente.ensu.bindings.EnsuDb
-import io.ente.ensu.bindings.DbException
import io.ente.ensu.bindings.cleanAssistantText
+import io.ente.ensu.storage.CredentialStore
+import io.ente.ensu.storage.FilePathManager
import java.io.File
class ChatRepository(
context: Context,
- credentialStore: CredentialStore
+ credentialStore: CredentialStore,
) {
private val filePaths = FilePathManager(context)
@@ -36,19 +30,27 @@ class ChatRepository(
val sessions = db.listSessions()
sessions.map { session ->
val messages = runCatching { db.getMessages(session.uuid) }.getOrNull().orEmpty()
- val firstMessage = messages.firstOrNull()?.let { message ->
- if (message.sender == DbSender.OTHER) cleanAssistantText(message.text) else message.text
- }.orEmpty()
- val lastMessage = messages.lastOrNull()?.let { message ->
- if (message.sender == DbSender.OTHER) cleanAssistantText(message.text) else message.text
- }
- val isPlaceholder = session.title.isBlank() || session.title.equals("New Chat", ignoreCase = true)
+ val firstMessage =
+ messages
+ .firstOrNull()
+ ?.let { message ->
+ if (message.sender == DbSender.OTHER) cleanAssistantText(message.text)
+ else message.text
+ }
+ .orEmpty()
+ val lastMessage =
+ messages.lastOrNull()?.let { message ->
+ if (message.sender == DbSender.OTHER) cleanAssistantText(message.text)
+ else message.text
+ }
+ val isPlaceholder =
+ session.title.isBlank() || session.title.equals("New Chat", ignoreCase = true)
val seedTitle = if (isPlaceholder) firstMessage else session.title
ChatSession(
id = session.uuid,
title = sessionTitleFromText(seedTitle, fallback = session.title),
lastMessagePreview = lastMessage,
- updatedAtMillis = session.updatedAtUs / 1000
+ updatedAtMillis = session.updatedAtUs / 1000,
)
}
}
@@ -59,14 +61,12 @@ class ChatRepository(
id = session.uuid,
title = session.title,
lastMessagePreview = null,
- updatedAtMillis = session.updatedAtUs / 1000
+ updatedAtMillis = session.updatedAtUs / 1000,
)
}
fun deleteSession(sessionId: String) = withDbRecovery {
- db.deleteSession(sessionId).forEach { id ->
- File(attachmentsDir, id).delete()
- }
+ db.deleteSession(sessionId).forEach { id -> File(attachmentsDir, id).delete() }
}
fun getMessages(sessionId: String): List<ChatMessage> = withDbRecovery {
@@ -75,26 +75,29 @@ class ChatRepository(
id = message.uuid,
sessionId = message.sessionUuid,
parentId = message.parentMessageUuid,
- author = when (message.sender) {
- DbSender.SELF_USER -> MessageAuthor.User
- DbSender.OTHER -> MessageAuthor.Assistant
- },
+ author =
+ when (message.sender) {
+ DbSender.SELF_USER -> MessageAuthor.User
+ DbSender.OTHER -> MessageAuthor.Assistant
+ },
text = message.text,
timestampMillis = message.createdAtUs / 1000,
- attachments = message.attachments.map { meta ->
- val file = File(attachmentsDir, meta.id)
- Attachment(
- id = meta.id,
- name = meta.name,
- sizeBytes = meta.size,
- type = when (meta.kind) {
- DbAttachmentKind.IMAGE -> AttachmentType.Image
- DbAttachmentKind.DOCUMENT -> AttachmentType.Document
- },
- localPath = file.takeIf { it.exists() }?.absolutePath,
- isUploading = false
- )
- }
+ attachments =
+ message.attachments.map { meta ->
+ val file = File(attachmentsDir, meta.id)
+ Attachment(
+ id = meta.id,
+ name = meta.name,
+ sizeBytes = meta.size,
+ type =
+ when (meta.kind) {
+ DbAttachmentKind.IMAGE -> AttachmentType.Image
+ DbAttachmentKind.DOCUMENT -> AttachmentType.Document
+ },
+ localPath = file.takeIf { it.exists() }?.absolutePath,
+ isUploading = false,
+ )
+ },
)
}
}
@@ -104,31 +107,34 @@ class ChatRepository(
parentId: String?,
author: MessageAuthor,
text: String,
- attachments: List<Attachment>
+ attachments: List<Attachment>,
): ChatMessage = withDbRecovery {
val meta = attachments.map { att ->
DbAttachmentMeta(
id = att.id,
- kind = when (att.type) {
- AttachmentType.Image -> DbAttachmentKind.IMAGE
- AttachmentType.Document -> DbAttachmentKind.DOCUMENT
- },
+ kind =
+ when (att.type) {
+ AttachmentType.Image -> DbAttachmentKind.IMAGE
+ AttachmentType.Document -> DbAttachmentKind.DOCUMENT
+ },
size = att.sizeBytes,
- name = att.name
+ name = att.name,
)
}
- val message = db.insertMessage(
- sessionUuid = sessionId,
- sender = if (author == MessageAuthor.User) {
- DbSender.SELF_USER
- } else {
- DbSender.OTHER
- },
- text = text,
- parentMessageUuid = parentId,
- attachments = meta
- )
+ val message =
+ db.insertMessage(
+ sessionUuid = sessionId,
+ sender =
+ if (author == MessageAuthor.User) {
+ DbSender.SELF_USER
+ } else {
+ DbSender.OTHER
+ },
+ text = text,
+ parentMessageUuid = parentId,
+ attachments = meta,
+ )
ChatMessage(
id = message.uuid,
@@ -137,7 +143,7 @@ class ChatRepository(
author = author,
text = message.text,
timestampMillis = message.createdAtUs / 1000,
- attachments = attachments
+ attachments = attachments,
)
}
@@ -152,7 +158,7 @@ class ChatRepository(
private fun openDb(dbFile: File, key: ByteArray): EnsuDb {
return EnsuDb.open(
dbFile.absolutePath,
- key
+ key,
)
}
@@ -178,13 +184,15 @@ class ChatRepository(
}
private fun pruneOrphanedAttachments() {
- val referenced = try {
- db.listSessions().flatMap { session -> db.getMessages(session.uuid) }
- .flatMap { message -> message.attachments }
- .mapTo(mutableSetOf()) { attachment -> attachment.id }
- } catch (_: DbException) {
- return
- }
+ val referenced =
+ try {
+ db.listSessions()
+ .flatMap { session -> db.getMessages(session.uuid) }
+ .flatMap { message -> message.attachments }
+ .mapTo(mutableSetOf()) { attachment -> attachment.id }
+ } catch (_: DbException) {
+ return
+ }
attachmentsDir.listFiles()?.forEach { file ->
if (file.isFile && file.name !in referenced) file.delete()
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt
index f5405ed8f5..cef1550264 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatState.kt
@@ -2,10 +2,6 @@ package io.ente.ensu.chat
import io.ente.ensu.device.ChatDeviceCapability
import io.ente.ensu.llm.DownloadPhase
-import io.ente.ensu.chat.Attachment
-import io.ente.ensu.chat.ChatMessage
-import io.ente.ensu.chat.ChatSession
-
data class ChatState(
val sessions: List<ChatSession> = emptyList(),
@@ -31,12 +27,12 @@ data class ChatState(
val hasRequestedModelDownload: Boolean = false,
val deviceCapability: ChatDeviceCapability = ChatDeviceCapability.Unknown,
val showUnsupportedDeviceDialog: Boolean = false,
- val overflowDialog: OverflowDialogState? = null
+ val overflowDialog: OverflowDialogState? = null,
)
data class OverflowDialogState(
val inputTokens: Int,
val inputBudget: Int,
val contextLength: Int,
- val maxOutput: Int
+ val maxOutput: Int,
)
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt
index da818433b1..c396c061cc 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatStoreActions.kt
@@ -1,37 +1,33 @@
package io.ente.ensu.chat
-import io.ente.ensu.llm.DownloadProgressTracker
-import io.ente.ensu.llm.ModelSettingsActions
-import io.ente.ensu.chat.ChatRepository
+import io.ente.ensu.AppState
+import io.ente.ensu.bindings.AssetDownloadException
+import io.ente.ensu.bindings.ConfigDefaults
+import io.ente.ensu.bindings.DbException
+import io.ente.ensu.bindings.GroundedSource
+import io.ente.ensu.bindings.LlmException
+import io.ente.ensu.bindings.buildGroundedPromptContext
+import io.ente.ensu.bindings.cleanAssistantText
+import io.ente.ensu.bindings.finalizeGroundedAssistantText
+import io.ente.ensu.bindings.selectMixedGroundingCandidates
import io.ente.ensu.device.isChatSupported
-import io.ente.ensu.logging.FileLogRepository
-import io.ente.ensu.llm.DownloadPhase
+import io.ente.ensu.knowledge.KnowledgeProvider
+import io.ente.ensu.llm.DownloadProgressTracker
import io.ente.ensu.llm.LlmMessage
import io.ente.ensu.llm.LlmMessageRole
import io.ente.ensu.llm.LlmModelSelection
import io.ente.ensu.llm.LlmProvider
-import io.ente.ensu.chat.Attachment
-import io.ente.ensu.chat.ChatMessage
-import io.ente.ensu.chat.ChatSession
-import io.ente.ensu.bindings.AssetDownloadException
-import io.ente.ensu.bindings.DbException
-import io.ente.ensu.bindings.LlmException
-import io.ente.ensu.bindings.ConfigDefaults
+import io.ente.ensu.llm.ModelSettingsActions
+import io.ente.ensu.logging.FileLogRepository
import io.ente.ensu.logging.LogLevel
-import io.ente.ensu.chat.MessageAuthor
-import io.ente.ensu.chat.sessionTitleFromText
import io.ente.ensu.notes.NotesStore
import io.ente.ensu.settings.SessionPreferencesDataStore
-import io.ente.ensu.AppState
-import io.ente.ensu.bindings.GroundedSource
-import io.ente.ensu.bindings.selectMixedGroundingCandidates
-import io.ente.ensu.bindings.buildGroundedPromptContext
-import io.ente.ensu.bindings.cleanAssistantText
-import io.ente.ensu.bindings.finalizeGroundedAssistantText
-import io.ente.ensu.knowledge.KnowledgeProvider
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
+import kotlin.math.abs
+import kotlin.math.max
+import kotlin.math.min
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -42,9 +38,6 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
-import kotlin.math.abs
-import kotlin.math.max
-import kotlin.math.min
internal class ChatStoreActions(
private val state: MutableStateFlow<AppState>,
@@ -59,7 +52,7 @@ internal class ChatStoreActions(
private val modelSettingsActions: ModelSettingsActions,
private val configDefaults: ConfigDefaults,
private val notesStore: NotesStore,
- private val awaitKnowledgeReady: suspend () -> Unit
+ private val awaitKnowledgeReady: suspend () -> Unit,
) {
private val branchSelections = mutableMapOf<String, MutableMap<String, String>>()
private val sessionSummaries = mutableMapOf<String, String>()
@@ -114,13 +107,14 @@ internal class ChatStoreActions(
state.update { appState ->
val updatedSessions = listOf(session) + appState.chat.sessions
appState.copy(
- chat = appState.chat.copy(
- sessions = updatedSessions,
- currentSessionId = session.id,
- messageText = "",
- attachments = emptyList(),
- editingMessageId = null
- )
+ chat =
+ appState.chat.copy(
+ sessions = updatedSessions,
+ currentSessionId = session.id,
+ messageText = "",
+ attachments = emptyList(),
+ editingMessageId = null,
+ )
)
}
markSessionAccess(session.id)
@@ -137,14 +131,15 @@ internal class ChatStoreActions(
attachmentActions.discardAttachments(state.value.chat.attachments)
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- currentSessionId = null,
- messages = emptyList(),
- branchSelections = emptyMap(),
- messageText = "",
- attachments = emptyList(),
- editingMessageId = null
- )
+ chat =
+ appState.chat.copy(
+ currentSessionId = null,
+ messages = emptyList(),
+ branchSelections = emptyMap(),
+ messageText = "",
+ attachments = emptyList(),
+ editingMessageId = null,
+ )
)
}
}
@@ -152,11 +147,7 @@ internal class ChatStoreActions(
fun selectSession(sessionId: String) {
resetGenerationState()
state.update { appState ->
- appState.copy(
- chat = appState.chat.copy(
- currentSessionId = sessionId
- )
- )
+ appState.copy(chat = appState.chat.copy(currentSessionId = sessionId))
}
val scope = scope ?: return
scope.launch(Dispatchers.IO) {
@@ -181,30 +172,35 @@ internal class ChatStoreActions(
val sessions = currentState.chat.sessions.filterNot { it.id == sessionId }
- val newCurrent = if (isCurrent) {
- sessions.firstOrNull()?.id
- } else {
- currentState.chat.currentSessionId?.takeIf { id -> sessions.any { it.id == id } }
- ?: sessions.firstOrNull()?.id
- }
+ val newCurrent =
+ if (isCurrent) {
+ sessions.firstOrNull()?.id
+ } else {
+ currentState.chat.currentSessionId?.takeIf { id -> sessions.any { it.id == id } }
+ ?: sessions.firstOrNull()?.id
+ }
state.update { appState ->
val resetCurrent = isCurrent
appState.copy(
- chat = appState.chat.copy(
- sessions = sessions,
- currentSessionId = newCurrent,
- isGenerating = if (resetCurrent) false else appState.chat.isGenerating,
- isDownloading = if (resetCurrent) false else appState.chat.isDownloading,
- streamingResponse = if (resetCurrent) "" else appState.chat.streamingResponse,
- streamingParentId = if (resetCurrent) null else appState.chat.streamingParentId,
- downloadPercent = if (resetCurrent) null else appState.chat.downloadPercent,
- downloadStatus = if (resetCurrent) null else appState.chat.downloadStatus,
- downloadPhase = if (resetCurrent) null else appState.chat.downloadPhase,
- messageText = if (resetCurrent) "" else appState.chat.messageText,
- attachments = if (resetCurrent) emptyList() else appState.chat.attachments,
- editingMessageId = if (resetCurrent) null else appState.chat.editingMessageId
- )
+ chat =
+ appState.chat.copy(
+ sessions = sessions,
+ currentSessionId = newCurrent,
+ isGenerating = if (resetCurrent) false else appState.chat.isGenerating,
+ isDownloading = if (resetCurrent) false else appState.chat.isDownloading,
+ streamingResponse =
+ if (resetCurrent) "" else appState.chat.streamingResponse,
+ streamingParentId =
+ if (resetCurrent) null else appState.chat.streamingParentId,
+ downloadPercent = if (resetCurrent) null else appState.chat.downloadPercent,
+ downloadStatus = if (resetCurrent) null else appState.chat.downloadStatus,
+ downloadPhase = if (resetCurrent) null else appState.chat.downloadPhase,
+ messageText = if (resetCurrent) "" else appState.chat.messageText,
+ attachments = if (resetCurrent) emptyList() else appState.chat.attachments,
+ editingMessageId =
+ if (resetCurrent) null else appState.chat.editingMessageId,
+ )
)
}
@@ -217,12 +213,20 @@ internal class ChatStoreActions(
}
} else {
state.update { appState ->
- appState.copy(chat = appState.chat.copy(messages = emptyList(), branchSelections = emptyMap()))
+ appState.copy(
+ chat =
+ appState.chat.copy(
+ messages = emptyList(),
+ branchSelections = emptyMap(),
+ )
+ )
}
}
} else {
state.update { appState ->
- appState.copy(chat = appState.chat.copy(messages = emptyList(), branchSelections = emptyMap()))
+ appState.copy(
+ chat = appState.chat.copy(messages = emptyList(), branchSelections = emptyMap())
+ )
}
}
trimSessionCaches(sessions.map { it.id }.toSet())
@@ -232,15 +236,11 @@ internal class ChatStoreActions(
}
fun persistSelectedSession(scope: CoroutineScope, sessionId: String?) {
- scope.launch {
- sessionPreferences.setSelectedSessionId(sessionId)
- }
+ scope.launch { sessionPreferences.setSelectedSessionId(sessionId) }
}
fun updateMessageText(value: String) {
- state.update { appState ->
- appState.copy(chat = appState.chat.copy(messageText = value))
- }
+ state.update { appState -> appState.copy(chat = appState.chat.copy(messageText = value)) }
}
fun updateBranchSelection(messageId: String, selectedIndex: Int) {
@@ -269,11 +269,12 @@ internal class ChatStoreActions(
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- editingMessageId = message.id,
- messageText = message.text,
- attachments = message.attachments
- )
+ chat =
+ appState.chat.copy(
+ editingMessageId = message.id,
+ messageText = message.text,
+ attachments = message.attachments,
+ )
)
}
}
@@ -282,11 +283,12 @@ internal class ChatStoreActions(
attachmentActions.discardAttachments(state.value.chat.attachments)
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- editingMessageId = null,
- messageText = "",
- attachments = emptyList()
- )
+ chat =
+ appState.chat.copy(
+ editingMessageId = null,
+ messageText = "",
+ attachments = emptyList(),
+ )
)
}
}
@@ -307,15 +309,16 @@ internal class ChatStoreActions(
val sessionId = state.value.chat.currentSessionId ?: return
// For synthetic interrupted placeholders, find the parent user message directly
- val parent = if (messageId.startsWith("interrupted-placeholder-")) {
- val parentUserId = messageId.removePrefix("interrupted-placeholder-")
- messageStore[sessionId]?.firstOrNull { it.id == parentUserId }
- } else {
- val message = messageStore[sessionId]?.firstOrNull { it.id == messageId } ?: return
- if (message.author != MessageAuthor.Assistant) return
- val parentId = message.parentId ?: return
- messageStore[sessionId]?.firstOrNull { it.id == parentId }
- } ?: return
+ val parent =
+ if (messageId.startsWith("interrupted-placeholder-")) {
+ val parentUserId = messageId.removePrefix("interrupted-placeholder-")
+ messageStore[sessionId]?.firstOrNull { it.id == parentUserId }
+ } else {
+ val message = messageStore[sessionId]?.firstOrNull { it.id == messageId } ?: return
+ if (message.author != MessageAuthor.Assistant) return
+ val parentId = message.parentId ?: return
+ messageStore[sessionId]?.firstOrNull { it.id == parentId }
+ } ?: return
priorGeneration?.cancel()
priorSummary?.cancel()
@@ -341,31 +344,34 @@ internal class ChatStoreActions(
val timestamp = clock()
val editingMessageId = currentState.chat.editingMessageId
- val parentId = if (editingMessageId != null) {
- val existing = messageStore[sessionId]?.firstOrNull { it.id == editingMessageId }
- existing?.parentId
- } else {
- buildSelectedPath(sessionId).lastOrNull()?.id
- }
+ val parentId =
+ if (editingMessageId != null) {
+ val existing = messageStore[sessionId]?.firstOrNull { it.id == editingMessageId }
+ existing?.parentId
+ } else {
+ buildSelectedPath(sessionId).lastOrNull()?.id
+ }
- val userMessage = chatRepository.insertMessage(
- sessionId = sessionId,
- parentId = parentId,
- author = MessageAuthor.User,
- text = text,
- attachments = attachments
- )
+ val userMessage =
+ chatRepository.insertMessage(
+ sessionId = sessionId,
+ parentId = parentId,
+ author = MessageAuthor.User,
+ text = text,
+ attachments = attachments,
+ )
messageStore.getOrPut(sessionId) { mutableListOf() }.add(userMessage)
updateSelectionForParent(sessionId, parentId, userMessage.id)
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- messageText = "",
- attachments = emptyList(),
- editingMessageId = null
- )
+ chat =
+ appState.chat.copy(
+ messageText = "",
+ attachments = emptyList(),
+ editingMessageId = null,
+ )
)
}
@@ -375,8 +381,9 @@ internal class ChatStoreActions(
logRepository.log(
LogLevel.Info,
"Message sent",
- details = "len=${text.length} attachments=${attachments.size} edited=${editingMessageId != null}",
- tag = "Chat"
+ details =
+ "len=${text.length} attachments=${attachments.size} edited=${editingMessageId != null}",
+ tag = "Chat",
)
}
@@ -408,18 +415,19 @@ internal class ChatStoreActions(
fun loadSessionsFromDb() {
val scope = scope ?: return
scope.launch(Dispatchers.IO) {
- val loaded = try {
- chatRepository.listSessions()
- } catch (error: DbException) {
- logRepository.log(
- LogLevel.Error,
- "Failed to load sessions",
- details = error.message,
- tag = "Chat",
- throwable = error
- )
- return@launch
- }
+ val loaded =
+ try {
+ chatRepository.listSessions()
+ } catch (error: DbException) {
+ logRepository.log(
+ LogLevel.Error,
+ "Failed to load sessions",
+ details = error.message,
+ tag = "Chat",
+ throwable = error,
+ )
+ return@launch
+ }
val sessions = loaded.map { session ->
val summary = sessionSummaries[sessionKey(session.id)]
if (!summary.isNullOrBlank()) {
@@ -430,14 +438,16 @@ internal class ChatStoreActions(
}
val currentSessionId = state.value.chat.currentSessionId
- val sessionStillExists = currentSessionId != null && sessions.any { it.id == currentSessionId }
+ val sessionStillExists =
+ currentSessionId != null && sessions.any { it.id == currentSessionId }
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- sessions = sessions,
- currentSessionId = if (sessionStillExists) currentSessionId else null
- )
+ chat =
+ appState.chat.copy(
+ sessions = sessions,
+ currentSessionId = if (sessionStillExists) currentSessionId else null,
+ )
)
}
@@ -467,16 +477,17 @@ internal class ChatStoreActions(
streamingParentId = userMessage.id
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isGenerating = true,
- isDownloading = false,
- streamingResponse = "",
- streamingParentId = userMessage.id,
- downloadPercent = null,
- downloadStatus = null,
- downloadPhase = null,
- hasRequestedModelDownload = true
- )
+ chat =
+ appState.chat.copy(
+ isGenerating = true,
+ isDownloading = false,
+ streamingResponse = "",
+ streamingParentId = userMessage.id,
+ downloadPercent = null,
+ downloadStatus = null,
+ downloadPhase = null,
+ hasRequestedModelDownload = true,
+ )
)
}
rebuildChatState(sessionId)
@@ -494,33 +505,38 @@ internal class ChatStoreActions(
val progressTracker = DownloadProgressTracker()
var embeddingAssetInvalid = false
val enabledDatasets = state.value.knowledge.enabledReadyDatasets
- val knowledgeHits = if (
- userMessage.text.isNotBlank() &&
- (enabledDatasets.isNotEmpty() || notesStore.state.value.collections.any { it.eligible })
- ) {
- try {
- val hits = llmProvider.withChatModelReleasedForRetrieval { embed ->
- if (!isActive()) throw kotlinx.coroutines.CancellationException()
- val query = embed(userMessage.text.trim())
- if (!isActive()) throw kotlinx.coroutines.CancellationException()
- val packs = knowledgeProvider.search(
- datasets = enabledDatasets,
- query = query,
- maxHits = configDefaults.knowledgeEmbedding.maxHits
- )
- val notes = notesStore.retrieve(query)
- notesStore.verify(selectMixedGroundingCandidates(packs, notes, notes.size.toUInt()))
+ val knowledgeHits =
+ if (
+ userMessage.text.isNotBlank() &&
+ (enabledDatasets.isNotEmpty() ||
+ notesStore.state.value.collections.any { it.eligible })
+ ) {
+ try {
+ val hits = llmProvider.withChatModelReleasedForRetrieval { embed ->
+ if (!isActive()) throw kotlinx.coroutines.CancellationException()
+ val query = embed(userMessage.text.trim())
+ if (!isActive()) throw kotlinx.coroutines.CancellationException()
+ val packs =
+ knowledgeProvider.search(
+ datasets = enabledDatasets,
+ query = query,
+ maxHits = configDefaults.knowledgeEmbedding.maxHits,
+ )
+ val notes = notesStore.retrieve(query)
+ notesStore.verify(
+ selectMixedGroundingCandidates(packs, notes, notes.size.toUInt())
+ )
+ }
+ if (!isActive()) return@launch
+ hits
+ } catch (error: Throwable) {
+ if (error is kotlinx.coroutines.CancellationException) return@launch
+ embeddingAssetInvalid = error is LlmProvider.EmbeddingAssetInvalid
+ emptyList()
}
- if (!isActive()) return@launch
- hits
- } catch (error: Throwable) {
- if (error is kotlinx.coroutines.CancellationException) return@launch
- embeddingAssetInvalid = error is LlmProvider.EmbeddingAssetInvalid
+ } else {
emptyList()
}
- } else {
- emptyList()
- }
if (!isActive()) return@launch
try {
@@ -529,33 +545,40 @@ internal class ChatStoreActions(
val resolvedProgress = progressTracker.resolve(progress)
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isDownloading = resolvedProgress.isDownloading,
- downloadPercent = resolvedProgress.percent,
- downloadStatus = resolvedProgress.status,
- downloadPhase = resolvedProgress.phase,
- modelDownloadSizeBytes = if (resolvedProgress.isFinished) null else appState.chat.modelDownloadSizeBytes
- )
+ chat =
+ appState.chat.copy(
+ isDownloading = resolvedProgress.isDownloading,
+ downloadPercent = resolvedProgress.percent,
+ downloadStatus = resolvedProgress.status,
+ downloadPhase = resolvedProgress.phase,
+ modelDownloadSizeBytes =
+ if (resolvedProgress.isFinished) null
+ else appState.chat.modelDownloadSizeBytes,
+ )
)
}
}
} catch (err: Throwable) {
- val cancelled = err is kotlinx.coroutines.CancellationException ||
- err is LlmException.Cancelled ||
- err is AssetDownloadException.Cancelled
+ val cancelled =
+ err is kotlinx.coroutines.CancellationException ||
+ err is LlmException.Cancelled ||
+ err is AssetDownloadException.Cancelled
if (!isActive()) return@launch
streamingParentId = null
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isGenerating = false,
- isDownloading = false,
- streamingParentId = null,
- downloadPercent = null,
- downloadStatus = if (cancelled) "Download cancelled" else null,
- downloadPhase = null,
- hasRequestedModelDownload = if (cancelled) false else appState.chat.hasRequestedModelDownload
- )
+ chat =
+ appState.chat.copy(
+ isGenerating = false,
+ isDownloading = false,
+ streamingParentId = null,
+ downloadPercent = null,
+ downloadStatus = if (cancelled) "Download cancelled" else null,
+ downloadPhase = null,
+ hasRequestedModelDownload =
+ if (cancelled) false
+ else appState.chat.hasRequestedModelDownload,
+ )
)
}
modelSettingsActions.refreshModelDownloadInfo()
@@ -565,7 +588,7 @@ internal class ChatStoreActions(
"Model load failed",
details = err.message,
tag = "Model",
- throwable = err
+ throwable = err,
)
}
return@launch
@@ -575,14 +598,15 @@ internal class ChatStoreActions(
val generationLimits = resolveGenerationLimits(selection)
val normalSystemPrompt = buildSystemPrompt()
- val normalHistorySelection = buildHistorySelection(
- sessionId = sessionId,
- promptText = prompt.text,
- promptImageCount = prompt.imageFiles.size,
- currentMessageId = userMessage.id,
- limits = generationLimits,
- systemPrompt = normalSystemPrompt
- )
+ val normalHistorySelection =
+ buildHistorySelection(
+ sessionId = sessionId,
+ promptText = prompt.text,
+ promptImageCount = prompt.imageFiles.size,
+ currentMessageId = userMessage.id,
+ limits = generationLimits,
+ systemPrompt = normalSystemPrompt,
+ )
if (normalHistorySelection.wasTrimmed && overflowBypassMessageId != userMessage.id) {
overflowBypassMessageId = null
@@ -590,15 +614,16 @@ internal class ChatStoreActions(
streamingParentId = null
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isGenerating = false,
- isDownloading = false,
- streamingResponse = "",
- streamingParentId = null,
- downloadPercent = null,
- downloadStatus = null,
- downloadPhase = null
- )
+ chat =
+ appState.chat.copy(
+ isGenerating = false,
+ isDownloading = false,
+ streamingResponse = "",
+ streamingParentId = null,
+ downloadPercent = null,
+ downloadStatus = null,
+ downloadPhase = null,
+ )
)
}
showOverflowDialog(normalHistorySelection, generationLimits)
@@ -611,19 +636,22 @@ internal class ChatStoreActions(
pendingOverflow = null
clearOverflowDialog()
- val remainingKnowledgeBytes = (
- (normalHistorySelection.inputBudget - normalHistorySelection.inputTokens)
- .coerceAtLeast(0) * 4 - 2
- ).coerceAtLeast(0)
+ val remainingKnowledgeBytes =
+ ((normalHistorySelection.inputBudget - normalHistorySelection.inputTokens)
+ .coerceAtLeast(0) * 4 - 2)
+ .coerceAtLeast(0)
val knowledgeContext = runCatching {
buildGroundedPromptContext(
excerpts = knowledgeHits,
- maxUtf8Bytes = min(
- configDefaults.knowledgeEmbedding.maxContextUtf8Bytes.toInt(),
- remainingKnowledgeBytes
- ).toUInt()
+ maxUtf8Bytes =
+ min(
+ configDefaults.knowledgeEmbedding.maxContextUtf8Bytes.toInt(),
+ remainingKnowledgeBytes,
+ )
+ .toUInt(),
)
- }.getOrNull()
+ }
+ .getOrNull()
val candidateSystemPrompt = knowledgeContext?.let {
"$normalSystemPrompt\n\n${it.text}"
}
@@ -634,26 +662,31 @@ internal class ChatStoreActions(
promptImageCount = prompt.imageFiles.size,
currentMessageId = userMessage.id,
limits = generationLimits,
- systemPrompt = it
+ systemPrompt = it,
)
}
val useKnowledge = knowledgeHistorySelection?.wasTrimmed == false
- val historySelection = if (useKnowledge) {
- knowledgeHistorySelection
- } else {
- normalHistorySelection
- }
+ val historySelection =
+ if (useKnowledge) {
+ knowledgeHistorySelection
+ } else {
+ normalHistorySelection
+ }
var activeCitations = if (useKnowledge) knowledgeContext.sources else emptyList()
val systemPrompt = if (useKnowledge) candidateSystemPrompt else normalSystemPrompt
- val systemMessage = LlmMessage(
- text = systemPrompt,
- role = LlmMessageRole.System
- )
- var llmMessages = listOf(systemMessage) + historySelection.messages + LlmMessage(
- text = prompt.text,
- role = LlmMessageRole.User,
- hasAttachments = userMessage.attachments.isNotEmpty()
- )
+ val systemMessage =
+ LlmMessage(
+ text = systemPrompt,
+ role = LlmMessageRole.System,
+ )
+ var llmMessages =
+ listOf(systemMessage) +
+ historySelection.messages +
+ LlmMessage(
+ text = prompt.text,
+ role = LlmMessageRole.User,
+ hasAttachments = userMessage.attachments.isNotEmpty(),
+ )
val buffer = StringBuilder()
var tokenCount = 0
@@ -665,37 +698,42 @@ internal class ChatStoreActions(
messages = llmMessages,
imageFiles = prompt.imageFiles,
temperature = modelSettingsActions.resolveTemperature(settings),
- maxTokens = generationLimits.maxOutput
+ maxTokens = generationLimits.maxOutput,
) { token ->
buffer.append(token)
tokenCount += estimateTokens(token)
if (isActive()) {
state.update { appState ->
- appState.copy(chat = appState.chat.copy(streamingResponse = buffer.toString()))
+ appState.copy(
+ chat = appState.chat.copy(streamingResponse = buffer.toString())
+ )
}
}
}
}
- val summary = try {
- generate()
- } catch (error: Throwable) {
- if (error is LlmException.PromptTooLong &&
- buffer.isEmpty() &&
- activeCitations.isNotEmpty()
- ) {
- activeCitations = emptyList()
- llmMessages = listOf(
- LlmMessage(normalSystemPrompt, LlmMessageRole.System)
- ) + normalHistorySelection.messages + LlmMessage(
- text = prompt.text,
- role = LlmMessageRole.User,
- hasAttachments = userMessage.attachments.isNotEmpty()
- )
+ val summary =
+ try {
generate()
- } else {
- throw error
+ } catch (error: Throwable) {
+ if (
+ error is LlmException.PromptTooLong &&
+ buffer.isEmpty() &&
+ activeCitations.isNotEmpty()
+ ) {
+ activeCitations = emptyList()
+ llmMessages =
+ listOf(LlmMessage(normalSystemPrompt, LlmMessageRole.System)) +
+ normalHistorySelection.messages +
+ LlmMessage(
+ text = prompt.text,
+ role = LlmMessageRole.User,
+ hasAttachments = userMessage.attachments.isNotEmpty(),
+ )
+ generate()
+ } else {
+ throw error
+ }
}
- }
finishGeneration(
sessionId,
@@ -705,7 +743,7 @@ internal class ChatStoreActions(
summary.totalTimeMs,
interrupted = false,
shouldUpdateUi = isActive(),
- citations = activeCitations
+ citations = activeCitations,
)
} catch (err: Throwable) {
val interrupted = stopRequested || err is LlmException.Cancelled
@@ -717,7 +755,7 @@ internal class ChatStoreActions(
totalTimeMs = null,
interrupted = interrupted,
shouldUpdateUi = isActive(),
- citations = activeCitations
+ citations = activeCitations,
)
if (!interrupted) {
logRepository.log(
@@ -725,7 +763,7 @@ internal class ChatStoreActions(
"Generation failed",
details = err.message,
tag = "LLM",
- throwable = err
+ throwable = err,
)
}
}
@@ -734,9 +772,7 @@ internal class ChatStoreActions(
generationJob = activeJob
activeJob.invokeOnCompletion {
notesScope.close()
- scope.launch {
- settleGenerationIfActive(generationToken, sessionId)
- }
+ scope.launch { settleGenerationIfActive(generationToken, sessionId) }
}
}
@@ -748,27 +784,31 @@ internal class ChatStoreActions(
totalTimeMs: Long?,
interrupted: Boolean,
shouldUpdateUi: Boolean,
- citations: List<GroundedSource> = emptyList()
+ citations: List<GroundedSource> = emptyList(),
) {
val rawText = buffer.toString().trim()
- val finalText = if (rawText.isNotEmpty()) {
- runCatching { finalizeGroundedAssistantText(rawText, citations) }.getOrElse { error ->
- logRepository.log(
- LogLevel.Warning,
- "Assistant source finalization failed",
- details = "session=$sessionId parent=${parentMessage.id}",
- tag = "Chat",
- throwable = error
- )
- runCatching { finalizeGroundedAssistantText(rawText, emptyList()) }.getOrDefault("")
+ val finalText =
+ if (rawText.isNotEmpty()) {
+ runCatching { finalizeGroundedAssistantText(rawText, citations) }
+ .getOrElse { error ->
+ logRepository.log(
+ LogLevel.Warning,
+ "Assistant source finalization failed",
+ details = "session=$sessionId parent=${parentMessage.id}",
+ tag = "Chat",
+ throwable = error,
+ )
+ runCatching { finalizeGroundedAssistantText(rawText, emptyList()) }
+ .getOrDefault("")
+ }
+ } else {
+ rawText
}
- } else {
- rawText
- }
if (finalText.isNotEmpty()) {
- val tokensPerSecond = if (totalTimeMs != null && totalTimeMs > 0) {
- tokenCount.toDouble() / (totalTimeMs / 1000.0)
- } else null
+ val tokensPerSecond =
+ if (totalTimeMs != null && totalTimeMs > 0) {
+ tokenCount.toDouble() / (totalTimeMs / 1000.0)
+ } else null
if (shouldUpdateUi) {
val inserted = runCatching {
@@ -777,59 +817,65 @@ internal class ChatStoreActions(
parentId = parentMessage.id,
author = MessageAuthor.Assistant,
text = finalText,
- attachments = emptyList()
- )
- }.getOrElse { error ->
- logRepository.log(
- LogLevel.Warning,
- "Skipping assistant message persistence",
- details = "session=$sessionId parent=${parentMessage.id} interrupted=$interrupted",
- tag = "Chat",
- throwable = error
+ attachments = emptyList(),
)
- null
}
+ .getOrElse { error ->
+ logRepository.log(
+ LogLevel.Warning,
+ "Skipping assistant message persistence",
+ details =
+ "session=$sessionId parent=${parentMessage.id} interrupted=$interrupted",
+ tag = "Chat",
+ throwable = error,
+ )
+ null
+ }
if (inserted != null) {
- val assistantMessage = inserted.copy(
- isInterrupted = interrupted,
- tokensPerSecond = tokensPerSecond
- )
+ val assistantMessage =
+ inserted.copy(
+ isInterrupted = interrupted,
+ tokensPerSecond = tokensPerSecond,
+ )
messageStore.getOrPut(sessionId) { mutableListOf() }.add(assistantMessage)
updateSelectionForParent(sessionId, parentMessage.id, assistantMessage.id)
updateCurrentSessionPreview(
sessionId,
cleanAssistantText(finalText),
- assistantMessage.timestampMillis
+ assistantMessage.timestampMillis,
)
}
} else {
logRepository.log(
LogLevel.Info,
"Dropped stale generation response",
- details = "session=$sessionId parent=${parentMessage.id} interrupted=$interrupted",
- tag = "Chat"
+ details =
+ "session=$sessionId parent=${parentMessage.id} interrupted=$interrupted",
+ tag = "Chat",
)
}
}
if (shouldUpdateUi) {
streamingParentId = null
- val (displayMessages, branchSelectionIndices) = buildDisplayMessagesAndSelections(sessionId)
+ val (displayMessages, branchSelectionIndices) =
+ buildDisplayMessagesAndSelections(sessionId)
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isGenerating = false,
- isDownloading = false,
- streamingResponse = "",
- streamingParentId = null,
- downloadPercent = null,
- downloadStatus = null,
- downloadPhase = null,
- messages = displayMessages,
- branchSelections = branchSelectionIndices
- )
+ chat =
+ appState.chat.copy(
+ isGenerating = false,
+ isDownloading = false,
+ streamingResponse = "",
+ streamingParentId = null,
+ downloadPercent = null,
+ downloadStatus = null,
+ downloadPhase = null,
+ messages = displayMessages,
+ branchSelections = branchSelectionIndices,
+ )
)
}
}
@@ -840,40 +886,45 @@ internal class ChatStoreActions(
private fun updateCurrentSessionPreview(sessionId: String, preview: String, timestamp: Long) {
state.update { appState ->
- val updatedSessions = appState.chat.sessions.map { session ->
- if (session.id == sessionId) {
- val shouldUpdateTitle = session.title.isBlank() || session.title.equals("New Chat", ignoreCase = true)
- val updatedTitle = if (shouldUpdateTitle) {
- sessionTitleFromText(preview, fallback = session.title)
+ val updatedSessions =
+ appState.chat.sessions.map { session ->
+ if (session.id == sessionId) {
+ val shouldUpdateTitle =
+ session.title.isBlank() ||
+ session.title.equals("New Chat", ignoreCase = true)
+ val updatedTitle =
+ if (shouldUpdateTitle) {
+ sessionTitleFromText(preview, fallback = session.title)
+ } else {
+ session.title
+ }
+ if (updatedTitle != session.title) {
+ chatRepository.updateSessionTitle(sessionId, updatedTitle)
+ }
+ session.copy(
+ title = updatedTitle,
+ lastMessagePreview = preview,
+ updatedAtMillis = timestamp,
+ )
} else {
- session.title
+ session
}
- if (updatedTitle != session.title) {
- chatRepository.updateSessionTitle(sessionId, updatedTitle)
- }
- session.copy(
- title = updatedTitle,
- lastMessagePreview = preview,
- updatedAtMillis = timestamp
- )
- } else {
- session
}
- }
appState.copy(chat = appState.chat.copy(sessions = updatedSessions))
}
}
private fun applySessionSummariesToState() {
state.update { appState ->
- val updatedSessions = appState.chat.sessions.map { session ->
- val summary = sessionSummaries[sessionKey(session.id)]
- if (!summary.isNullOrBlank() && summary != session.title) {
- session.copy(title = summary)
- } else {
- session
+ val updatedSessions =
+ appState.chat.sessions.map { session ->
+ val summary = sessionSummaries[sessionKey(session.id)]
+ if (!summary.isNullOrBlank() && summary != session.title) {
+ session.copy(title = summary)
+ } else {
+ session
+ }
}
- }
appState.copy(chat = appState.chat.copy(sessions = updatedSessions))
}
}
@@ -886,18 +937,20 @@ internal class ChatStoreActions(
val selection = modelSettingsActions.resolveSelection(state.value.modelSettings)
val notesScope = notesStore.suspendMaintenance()
- sessionSummaryJob = scope.launch(Dispatchers.Default) {
- notesStore.awaitMaintenance()
- val summary = generateSessionSummary(
- input = summaryInput.text,
- fallback = summaryInput.fallback,
- selection = selection
- ) ?: return@launch
- if (!isActive) return@launch
- withContext(Dispatchers.Main) {
- applySessionSummary(sessionId, summary)
- }
- }.also { it.invokeOnCompletion { notesScope.close() } }
+ sessionSummaryJob =
+ scope
+ .launch(Dispatchers.Default) {
+ notesStore.awaitMaintenance()
+ val summary =
+ generateSessionSummary(
+ input = summaryInput.text,
+ fallback = summaryInput.fallback,
+ selection = selection,
+ ) ?: return@launch
+ if (!isActive) return@launch
+ withContext(Dispatchers.Main) { applySessionSummary(sessionId, summary) }
+ }
+ .also { it.invokeOnCompletion { notesScope.close() } }
}
private data class SessionSummaryInput(val text: String, val fallback: String)
@@ -905,9 +958,9 @@ internal class ChatStoreActions(
private fun buildSessionSummaryInput(sessionId: String): SessionSummaryInput? {
val messages = messageStore[sessionId].orEmpty()
if (messages.isEmpty()) return null
- val firstUser = messages.filter { it.author == MessageAuthor.User }
- .minByOrNull { it.timestampMillis }
- ?: return null
+ val firstUser =
+ messages.filter { it.author == MessageAuthor.User }.minByOrNull { it.timestampMillis }
+ ?: return null
val assistants = messages.filter { it.author == MessageAuthor.Assistant }
if (assistants.size != 1) return null
val firstAssistant = assistants.first()
@@ -922,7 +975,7 @@ internal class ChatStoreActions(
private suspend fun generateSessionSummary(
input: String,
fallback: String,
- selection: LlmModelSelection
+ selection: LlmModelSelection,
): String? {
if (!state.value.chat.deviceCapability.isChatSupported()) {
return sessionTitleFromText(fallback, fallback = fallback)
@@ -933,10 +986,11 @@ internal class ChatStoreActions(
val cleanedInput = sanitizeTitleText(input)
if (cleanedInput.isBlank()) return sessionTitleFromText(fallback, fallback = fallback)
- val messages = listOf(
- LlmMessage(text = sessionSummarySystemPrompt, role = LlmMessageRole.System),
- LlmMessage(text = cleanedInput, role = LlmMessageRole.User)
- )
+ val messages =
+ listOf(
+ LlmMessage(text = sessionSummarySystemPrompt, role = LlmMessageRole.System),
+ LlmMessage(text = cleanedInput, role = LlmMessageRole.User),
+ )
val buffer = StringBuilder()
try {
@@ -946,22 +1000,24 @@ internal class ChatStoreActions(
messages = messages,
imageFiles = emptyList(),
temperature = 0.2f,
- maxTokens = 64
+ maxTokens = 64,
) { token ->
buffer.append(token)
}
} catch (err: Throwable) {
val fallbackSummary = summarizeQuestion(fallback)
- return if (fallbackSummary.isBlank()) null else sessionTitleFromText(fallbackSummary, fallback = fallback)
+ return if (fallbackSummary.isBlank()) null
+ else sessionTitleFromText(fallbackSummary, fallback = fallback)
}
val raw = sanitizeTitleText(buffer.toString())
if (raw.isBlank()) {
return sessionTitleFromText(fallback, fallback = fallback)
}
- val words = raw.split(" ")
- .map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }
- .filter { it.isNotBlank() }
+ val words =
+ raw.split(" ")
+ .map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }
+ .filter { it.isNotBlank() }
if (words.isEmpty()) return null
val summary = words.take(sessionSummaryMaxWords).joinToString(" ")
return sessionTitleFromText(summary, fallback = fallback)
@@ -976,13 +1032,14 @@ internal class ChatStoreActions(
scope?.launch { sessionPreferences.setSessionSummary(sessionId, sanitized) }
chatRepository.updateSessionTitle(sessionId, sanitized)
state.update { appState ->
- val updatedSessions = appState.chat.sessions.map { session ->
- if (session.id == sessionId) {
- session.copy(title = sanitized)
- } else {
- session
+ val updatedSessions =
+ appState.chat.sessions.map { session ->
+ if (session.id == sessionId) {
+ session.copy(title = sanitized)
+ } else {
+ session
+ }
}
- }
appState.copy(chat = appState.chat.copy(sessions = updatedSessions))
}
}
@@ -990,18 +1047,18 @@ internal class ChatStoreActions(
private fun summarizeQuestion(text: String): String {
val cleaned = sanitizeTitleText(text)
if (cleaned.isBlank()) return ""
- val words = cleaned.split(" ")
- .map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }
- .filter { it.isNotBlank() }
+ val words =
+ cleaned
+ .split(" ")
+ .map { word -> word.trim { ch -> !ch.isLetterOrDigit() } }
+ .filter { it.isNotBlank() }
if (words.isEmpty()) return ""
val summaryWords = words.take(sessionSummaryMaxWords)
return summaryWords.joinToString(" ")
}
private suspend fun loadMessagesFromDb(sessionId: String) {
- val messages = withContext(Dispatchers.IO) {
- chatRepository.getMessages(sessionId)
- }
+ val messages = withContext(Dispatchers.IO) { chatRepository.getMessages(sessionId) }
messageStore[sessionId] = messages.toMutableList()
branchSelections.getOrPut(sessionId) { mutableMapOf() }.clear()
markSessionAccess(sessionId)
@@ -1012,7 +1069,9 @@ internal class ChatStoreActions(
sessionAccessTimes[sessionId] = clock()
}
- private fun trimSessionCaches(availableSessions: Set<String> = state.value.chat.sessions.map { it.id }.toSet()) {
+ private fun trimSessionCaches(
+ availableSessions: Set<String> = state.value.chat.sessions.map { it.id }.toSet()
+ ) {
val availableKeys = availableSessions.map(::sessionKey).toSet()
sessionSummaries.keys.retainAll(availableKeys)
@@ -1021,10 +1080,11 @@ internal class ChatStoreActions(
if (currentSessionId != null && currentSessionId in availableSessions) {
keepIds.add(currentSessionId)
}
- val ordered = sessionAccessTimes.entries
- .filter { it.key in availableSessions }
- .sortedByDescending { it.value }
- .map { it.key }
+ val ordered =
+ sessionAccessTimes.entries
+ .filter { it.key in availableSessions }
+ .sortedByDescending { it.value }
+ .map { it.key }
for (id in ordered) {
if (keepIds.size >= MAX_CACHED_SESSIONS) break
keepIds.add(id)
@@ -1048,15 +1108,18 @@ internal class ChatStoreActions(
val (displayMessages, branchSelectionIndices) = buildDisplayMessagesAndSelections(sessionId)
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- messages = displayMessages,
- branchSelections = branchSelectionIndices
- )
+ chat =
+ appState.chat.copy(
+ messages = displayMessages,
+ branchSelections = branchSelectionIndices,
+ )
)
}
}
- private fun buildDisplayMessagesAndSelections(sessionId: String?): Pair<List<ChatMessage>, Map<String, Int>> {
+ private fun buildDisplayMessagesAndSelections(
+ sessionId: String?
+ ): Pair<List<ChatMessage>, Map<String, Int>> {
if (sessionId == null) {
return emptyList<ChatMessage>() to emptyMap()
}
@@ -1088,16 +1151,18 @@ internal class ChatStoreActions(
val next = displayMessages.getOrNull(i + 1)
val isLastAndGenerating = i == displayMessages.lastIndex && isGenerating
if (next?.author != MessageAuthor.Assistant && !isLastAndGenerating) {
- add(ChatMessage(
- id = "interrupted-placeholder-${msg.id}",
- sessionId = sessionId,
- parentId = msg.id,
- author = MessageAuthor.Assistant,
- text = "Response was interrupted",
- timestampMillis = msg.timestampMillis,
- isInterrupted = true,
- isSynthetic = true
- ))
+ add(
+ ChatMessage(
+ id = "interrupted-placeholder-${msg.id}",
+ sessionId = sessionId,
+ parentId = msg.id,
+ author = MessageAuthor.Assistant,
+ text = "Response was interrupted",
+ timestampMillis = msg.timestampMillis,
+ isInterrupted = true,
+ isSynthetic = true,
+ )
+ )
}
}
}
@@ -1112,10 +1177,13 @@ internal class ChatStoreActions(
val byId = messages.associateBy { it.id }
val childrenMap = buildChildrenMap(messages)
- val roots = dedupeSiblings(messages.filter { message ->
- val parentId = message.parentId
- parentId == null || byId[parentId] == null
- })
+ val roots =
+ dedupeSiblings(
+ messages.filter { message ->
+ val parentId = message.parentId
+ parentId == null || byId[parentId] == null
+ }
+ )
if (roots.isEmpty()) return emptyList()
val selectionMap = branchSelections.getOrPut(sessionId) { mutableMapOf() }
@@ -1136,7 +1204,7 @@ internal class ChatStoreActions(
private fun selectChild(
selectionMap: MutableMap<String, String>,
selectionKey: String,
- candidates: List<ChatMessage>
+ candidates: List<ChatMessage>,
): ChatMessage? {
if (candidates.isEmpty()) return null
val selectedId = selectionMap[selectionKey]
@@ -1171,7 +1239,11 @@ internal class ChatStoreActions(
private fun isDuplicate(left: ChatMessage, right: ChatMessage): Boolean {
if (left.author != right.author) return false
if (left.text != right.text) return false
- if (!attachmentsSignature(left.attachments).contentEquals(attachmentsSignature(right.attachments))) return false
+ if (
+ !attachmentsSignature(left.attachments)
+ .contentEquals(attachmentsSignature(right.attachments))
+ )
+ return false
return abs(left.timestampMillis - right.timestampMillis) <= 2_000
}
@@ -1189,17 +1261,17 @@ internal class ChatStoreActions(
val messages: List<LlmMessage>,
val inputTokens: Int,
val inputBudget: Int,
- val wasTrimmed: Boolean
+ val wasTrimmed: Boolean,
)
private data class GenerationLimits(
val contextLength: Int,
- val maxOutput: Int
+ val maxOutput: Int,
)
private data class PendingOverflow(
val sessionId: String,
- val messageId: String
+ val messageId: String,
)
private fun buildPrompt(text: String, attachments: List<Attachment>): PromptResult {
@@ -1239,7 +1311,7 @@ internal class ChatStoreActions(
promptImageCount: Int,
currentMessageId: String,
limits: GenerationLimits,
- systemPrompt: String
+ systemPrompt: String,
): HistorySelection {
val path = buildSelectedPath(sessionId)
val historyMessages = path.takeWhile { it.id != currentMessageId }
@@ -1251,7 +1323,12 @@ internal class ChatStoreActions(
val remaining = inputBudget - systemTokens - promptTokens
if (remaining <= 0 || historyMessages.isEmpty()) {
- return HistorySelection(emptyList(), inputTokens, inputBudget, inputTokens > inputBudget)
+ return HistorySelection(
+ emptyList(),
+ inputTokens,
+ inputBudget,
+ inputTokens > inputBudget,
+ )
}
val quantum = max(1, inputBudget / 4)
@@ -1265,16 +1342,19 @@ internal class ChatStoreActions(
startIndex++
}
- val retained = historyMessages.drop(startIndex).ifEmpty {
- historyMessages.takeLast(1).filter { estimateTokens(historyText(it)) <= remaining }
- }
+ val retained =
+ historyMessages.drop(startIndex).ifEmpty {
+ historyMessages.takeLast(1).filter { estimateTokens(historyText(it)) <= remaining }
+ }
val selected = retained.map { message ->
val text = historyText(message)
LlmMessage(
text = text,
- role = if (message.author == MessageAuthor.User) LlmMessageRole.User else LlmMessageRole.Assistant,
- hasAttachments = message.attachments.isNotEmpty()
+ role =
+ if (message.author == MessageAuthor.User) LlmMessageRole.User
+ else LlmMessageRole.Assistant,
+ hasAttachments = message.attachments.isNotEmpty(),
)
}
@@ -1282,9 +1362,10 @@ internal class ChatStoreActions(
}
private fun resolveGenerationLimits(selection: LlmModelSelection): GenerationLimits {
- val contextLength = llmProvider.loadedContextLength(selection)
- ?: selection.contextLength
- ?: DEFAULT_CONTEXT_LENGTH
+ val contextLength =
+ llmProvider.loadedContextLength(selection)
+ ?: selection.contextLength
+ ?: DEFAULT_CONTEXT_LENGTH
val maxOutput = resolveMaxOutputTokens(selection.maxTokens, contextLength)
return GenerationLimits(contextLength = contextLength, maxOutput = maxOutput)
}
@@ -1298,22 +1379,22 @@ internal class ChatStoreActions(
private fun showOverflowDialog(selection: HistorySelection, limits: GenerationLimits) {
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- overflowDialog = io.ente.ensu.chat.OverflowDialogState(
- inputTokens = selection.inputTokens,
- inputBudget = selection.inputBudget,
- contextLength = limits.contextLength,
- maxOutput = limits.maxOutput
+ chat =
+ appState.chat.copy(
+ overflowDialog =
+ io.ente.ensu.chat.OverflowDialogState(
+ inputTokens = selection.inputTokens,
+ inputBudget = selection.inputBudget,
+ contextLength = limits.contextLength,
+ maxOutput = limits.maxOutput,
+ )
)
- )
)
}
}
private fun clearOverflowDialog() {
- state.update { appState ->
- appState.copy(chat = appState.chat.copy(overflowDialog = null))
- }
+ state.update { appState -> appState.copy(chat = appState.chat.copy(overflowDialog = null)) }
}
private fun historyText(message: ChatMessage): String {
@@ -1353,15 +1434,16 @@ internal class ChatStoreActions(
streamingParentId = null
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isGenerating = false,
- isDownloading = false,
- streamingResponse = "",
- streamingParentId = null,
- downloadPercent = null,
- downloadStatus = null,
- downloadPhase = null
- )
+ chat =
+ appState.chat.copy(
+ isGenerating = false,
+ isDownloading = false,
+ streamingResponse = "",
+ streamingParentId = null,
+ downloadPercent = null,
+ downloadStatus = null,
+ downloadPhase = null,
+ )
)
}
rebuildChatState(sessionId)
@@ -1371,15 +1453,16 @@ internal class ChatStoreActions(
cancelGeneration()
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isGenerating = false,
- isDownloading = false,
- streamingResponse = "",
- streamingParentId = null,
- downloadPercent = null,
- downloadStatus = null,
- downloadPhase = null
- )
+ chat =
+ appState.chat.copy(
+ isGenerating = false,
+ isDownloading = false,
+ streamingResponse = "",
+ streamingParentId = null,
+ downloadPercent = null,
+ downloadStatus = null,
+ downloadPhase = null,
+ )
)
}
}
@@ -1399,14 +1482,15 @@ internal class ChatStoreActions(
private data class PromptResult(
val text: String,
- val imageFiles: List<java.io.File>
+ val imageFiles: List<java.io.File>,
)
private fun buildSystemPrompt(nowMillis: Long = clock()): String {
- val date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
- .format(Date(nowMillis))
- val promptBody = state.value.developerSettings.systemPrompt.trim()
- .ifEmpty { configDefaults.mobileSystemPromptBody }
+ val date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date(nowMillis))
+ val promptBody =
+ state.value.developerSettings.systemPrompt.trim().ifEmpty {
+ configDefaults.mobileSystemPromptBody
+ }
return promptBody.replace(configDefaults.systemPromptDatePlaceholder, date)
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt
index b5f45a9a34..652a40aba3 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/ChatView.kt
@@ -40,21 +40,16 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onGloballyPositioned
-import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
-import io.ente.ensu.bindings.Transcriber
import io.ente.ensu.assets.AssetStore
+import io.ente.ensu.bindings.Transcriber
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.device.ChatDeviceCapability
-import io.ente.ensu.chat.Attachment
-import io.ente.ensu.chat.AttachmentType
-import io.ente.ensu.chat.ChatMessage
-import io.ente.ensu.chat.ChatState
-import kotlinx.coroutines.delay
@Composable
fun ChatView(
@@ -76,7 +71,7 @@ fun ChatView(
onStartDownload: (Boolean) -> Unit,
onDismissUnsupportedDeviceDialog: () -> Unit,
onOverflowTrim: () -> Unit,
- onOverflowCancel: () -> Unit
+ onOverflowCancel: () -> Unit,
) {
val density = LocalDensity.current
val context = LocalContext.current
@@ -85,73 +80,79 @@ fun ChatView(
val latestOnMessageChange by rememberUpdatedState(onMessageChange)
val sessionKey = chatState.currentSessionId ?: "new-session"
val latestSessionKey by rememberUpdatedState(sessionKey)
- val unsupportedCapability = chatState.deviceCapability as? ChatDeviceCapability.UnsupportedLowMemory
+ val unsupportedCapability =
+ chatState.deviceCapability as? ChatDeviceCapability.UnsupportedLowMemory
val isChatUnsupported = unsupportedCapability != null
var pendingVoiceSessionKey by remember { mutableStateOf<String?>(null) }
- val voiceController = rememberVoiceTranscriptionController(
- assetStore = assetStore,
- transcriber = transcriber,
- onTranscript = { transcript ->
- latestOnMessageChange(appendVoiceTranscript(latestMessageText, transcript))
- }
- )
+ val voiceController =
+ rememberVoiceTranscriptionController(
+ assetStore = assetStore,
+ transcriber = transcriber,
+ onTranscript = { transcript ->
+ latestOnMessageChange(appendVoiceTranscript(latestMessageText, transcript))
+ },
+ )
- val editingMessage by remember(chatState.editingMessageId, chatState.messages) {
- derivedStateOf {
- chatState.editingMessageId?.let { editingId ->
- chatState.messages.firstOrNull { it.id == editingId }
+ val editingMessage by
+ remember(chatState.editingMessageId, chatState.messages) {
+ derivedStateOf {
+ chatState.editingMessageId?.let { editingId ->
+ chatState.messages.firstOrNull { it.id == editingId }
+ }
}
}
- }
- val canStartVoiceInput = !chatState.isGenerating &&
- !chatState.isDownloading &&
- chatState.isModelDownloaded &&
- !isChatUnsupported &&
- editingMessage == null
+ val canStartVoiceInput =
+ !chatState.isGenerating &&
+ !chatState.isDownloading &&
+ chatState.isModelDownloaded &&
+ !isChatUnsupported &&
+ editingMessage == null
val latestCanStartVoiceInput by rememberUpdatedState(canStartVoiceInput)
- val microphonePermissionLauncher = rememberLauncherForActivityResult(
- contract = ActivityResultContracts.RequestPermission()
- ) { granted ->
- val requestedSessionKey = pendingVoiceSessionKey
- pendingVoiceSessionKey = null
- if (granted) {
- if (requestedSessionKey != null) {
- voiceController.startRecording {
- latestSessionKey == requestedSessionKey && latestCanStartVoiceInput
+ val microphonePermissionLauncher =
+ rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestPermission()) {
+ granted ->
+ val requestedSessionKey = pendingVoiceSessionKey
+ pendingVoiceSessionKey = null
+ if (granted) {
+ if (requestedSessionKey != null) {
+ voiceController.startRecording {
+ latestSessionKey == requestedSessionKey && latestCanStartVoiceInput
+ }
}
+ } else {
+ voiceController.onPermissionDenied()
}
- } else {
- voiceController.onPermissionDenied()
}
- }
- val showDownloadOnboarding by remember(
- chatState.isModelDownloaded,
- chatState.isModelStateKnown,
- chatState.isGenerating,
- isChatUnsupported
- ) {
- derivedStateOf {
- chatState.isModelStateKnown &&
- !chatState.isModelDownloaded &&
- !chatState.isGenerating &&
- !isChatUnsupported
+ val showDownloadOnboarding by
+ remember(
+ chatState.isModelDownloaded,
+ chatState.isModelStateKnown,
+ chatState.isGenerating,
+ isChatUnsupported,
+ ) {
+ derivedStateOf {
+ chatState.isModelStateKnown &&
+ !chatState.isModelDownloaded &&
+ !chatState.isGenerating &&
+ !isChatUnsupported
+ }
}
- }
val focusManager = LocalFocusManager.current
var didAutoFocusInput by remember { mutableStateOf(false) }
var focusRequestId by remember { mutableStateOf(0) }
var wasDrawerOpen by remember { mutableStateOf(false) }
- val shouldAutoFocusInput = chatState.isModelDownloaded &&
- !showDownloadOnboarding &&
- !isChatUnsupported &&
- !chatState.isDownloading &&
- !chatState.isGenerating &&
- !didAutoFocusInput &&
- !isDrawerOpen
+ val shouldAutoFocusInput =
+ chatState.isModelDownloaded &&
+ !showDownloadOnboarding &&
+ !isChatUnsupported &&
+ !chatState.isDownloading &&
+ !chatState.isGenerating &&
+ !didAutoFocusInput &&
+ !isDrawerOpen
LaunchedEffect(shouldAutoFocusInput, isDrawerOpen) {
if (isDrawerOpen) {
@@ -168,11 +169,12 @@ fun ChatView(
}
if (wasDrawerOpen) {
- val shouldRestoreFocus = chatState.isModelDownloaded &&
- !showDownloadOnboarding &&
- !isChatUnsupported &&
- !chatState.isDownloading &&
- !chatState.isGenerating
+ val shouldRestoreFocus =
+ chatState.isModelDownloaded &&
+ !showDownloadOnboarding &&
+ !isChatUnsupported &&
+ !chatState.isDownloading &&
+ !chatState.isGenerating
if (shouldRestoreFocus) {
focusRequestId += 1
}
@@ -186,36 +188,37 @@ fun ChatView(
}
Box(modifier = Modifier.fillMaxSize()) {
- Column(
- modifier = Modifier
- .fillMaxSize()
- .imePadding()
- ) {
+ Column(modifier = Modifier.fillMaxSize().imePadding()) {
AnimatedContent(
targetState = sessionKey,
- modifier = Modifier
- .weight(1f),
+ modifier = Modifier.weight(1f),
transitionSpec = {
- val enter = fadeIn(animationSpec = tween(220, easing = FastOutSlowInEasing)) +
- slideInVertically(animationSpec = tween(320, easing = FastOutSlowInEasing)) {
- it / 12
- }
- val exit = fadeOut(animationSpec = tween(220, easing = FastOutSlowInEasing)) +
- slideOutVertically(animationSpec = tween(320, easing = FastOutSlowInEasing)) {
- -it / 12
- }
+ val enter =
+ fadeIn(animationSpec = tween(220, easing = FastOutSlowInEasing)) +
+ slideInVertically(
+ animationSpec = tween(320, easing = FastOutSlowInEasing)
+ ) {
+ it / 12
+ }
+ val exit =
+ fadeOut(animationSpec = tween(220, easing = FastOutSlowInEasing)) +
+ slideOutVertically(
+ animationSpec = tween(320, easing = FastOutSlowInEasing)
+ ) {
+ -it / 12
+ }
enter.togetherWith(exit)
},
- label = "session-change"
+ label = "session-change",
) { targetSessionKey ->
key(targetSessionKey) {
MessageList(
- modifier = Modifier
- .fillMaxSize()
- .padding(
- start = EnsuSpacing.pageHorizontal.dp,
- end = EnsuSpacing.pageHorizontal.dp
- ),
+ modifier =
+ Modifier.fillMaxSize()
+ .padding(
+ start = EnsuSpacing.pageHorizontal.dp,
+ end = EnsuSpacing.pageHorizontal.dp,
+ ),
messages = chatState.messages,
streamingResponse = chatState.streamingResponse,
streamingParentId = chatState.streamingParentId,
@@ -233,7 +236,7 @@ fun ChatView(
onRetryMessage = onRetryMessage,
onBranchChange = onBranchChange,
onOpenAttachment = onOpenAttachment,
- onStartDownload = onStartDownload
+ onStartDownload = onStartDownload,
)
}
}
@@ -241,29 +244,29 @@ fun ChatView(
if (chatState.overflowDialog != null) {
OverflowDialog(
onTrim = onOverflowTrim,
- onCancel = onOverflowCancel
+ onCancel = onOverflowCancel,
)
}
if (unsupportedCapability != null) {
UnsupportedChatInputNotice(
- modifier = Modifier
- .fillMaxWidth()
- .navigationBarsPadding()
- .background(EnsuColor.backgroundBase())
- .onGloballyPositioned { coords ->
- inputBarHeightDp = with(density) { coords.size.height.toDp() }
- }
+ modifier =
+ Modifier.fillMaxWidth()
+ .navigationBarsPadding()
+ .background(EnsuColor.backgroundBase())
+ .onGloballyPositioned { coords ->
+ inputBarHeightDp = with(density) { coords.size.height.toDp() }
+ }
)
} else if (chatState.isModelStateKnown && !showDownloadOnboarding) {
MessageInput(
- modifier = Modifier
- .fillMaxWidth()
- .navigationBarsPadding()
- .background(EnsuColor.backgroundBase())
- .onGloballyPositioned { coords ->
- inputBarHeightDp = with(density) { coords.size.height.toDp() }
- },
+ modifier =
+ Modifier.fillMaxWidth()
+ .navigationBarsPadding()
+ .background(EnsuColor.backgroundBase())
+ .onGloballyPositioned { coords ->
+ inputBarHeightDp = with(density) { coords.size.height.toDp() }
+ },
messageText = chatState.messageText,
attachments = chatState.attachments,
editingMessage = editingMessage,
@@ -284,74 +287,77 @@ fun ChatView(
if (voiceController.state.isRecording) {
voiceController.stopAndTranscribe()
} else {
- val hasMicrophonePermission = ContextCompat.checkSelfPermission(
- context,
- Manifest.permission.RECORD_AUDIO
- ) == PackageManager.PERMISSION_GRANTED
+ val hasMicrophonePermission =
+ ContextCompat.checkSelfPermission(
+ context,
+ Manifest.permission.RECORD_AUDIO,
+ ) == PackageManager.PERMISSION_GRANTED
if (canStartVoiceInput && hasMicrophonePermission) {
val requestedSessionKey = sessionKey
voiceController.startRecording {
- latestSessionKey == requestedSessionKey && latestCanStartVoiceInput
+ latestSessionKey == requestedSessionKey &&
+ latestCanStartVoiceInput
}
} else if (canStartVoiceInput) {
pendingVoiceSessionKey = sessionKey
- microphonePermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
+ microphonePermissionLauncher.launch(
+ Manifest.permission.RECORD_AUDIO
+ )
}
}
},
- focusRequestId = focusRequestId
+ focusRequestId = focusRequestId,
)
}
}
if (chatState.showUnsupportedDeviceDialog && unsupportedCapability != null) {
- UnsupportedDeviceDialog(
- onDismiss = onDismissUnsupportedDeviceDialog
- )
+ UnsupportedDeviceDialog(onDismiss = onDismissUnsupportedDeviceDialog)
}
val imeVisible = WindowInsets.ime.getBottom(density) > 0
if (imeVisible && inputBarHeightDp > 0.dp) {
IconButton(
onClick = { focusManager.clearFocus() },
- modifier = Modifier
- .align(Alignment.BottomEnd)
- .imePadding()
- .padding(
- end = EnsuSpacing.pageHorizontal.dp,
- bottom = inputBarHeightDp + EnsuSpacing.sm.dp
- )
- .background(
- color = EnsuColor.fillFaint(),
- shape = CircleShape
- )
+ modifier =
+ Modifier.align(Alignment.BottomEnd)
+ .imePadding()
+ .padding(
+ end = EnsuSpacing.pageHorizontal.dp,
+ bottom = inputBarHeightDp + EnsuSpacing.sm.dp,
+ )
+ .background(
+ color = EnsuColor.fillFaint(),
+ shape = CircleShape,
+ ),
) {
Icon(
imageVector = Icons.Rounded.KeyboardArrowDown,
contentDescription = "Dismiss keyboard",
modifier = Modifier.padding(7.dp),
- tint = EnsuColor.textPrimary()
+ tint = EnsuColor.textPrimary(),
)
}
}
val status = chatState.downloadStatus
val isLoading = status?.contains("Loading", ignoreCase = true) == true
- val showToast by remember(status, chatState.isDownloading, showDownloadOnboarding, isLoading) {
- derivedStateOf {
- !showDownloadOnboarding &&
- status != null &&
- chatState.isDownloading &&
- !isLoading
+ val showToast by
+ remember(status, chatState.isDownloading, showDownloadOnboarding, isLoading) {
+ derivedStateOf {
+ !showDownloadOnboarding &&
+ status != null &&
+ chatState.isDownloading &&
+ !isLoading
+ }
}
- }
if (showToast) {
DownloadToastOverlay(
status = status ?: "",
percent = chatState.downloadPercent ?: 0,
totalBytes = chatState.modelDownloadSizeBytes,
isLoading = isLoading,
- onCancel = onCancelDownload
+ onCancel = onCancelDownload,
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LaTeXView.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LaTeXView.kt
index 8f4aa97a1a..4c93505462 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LaTeXView.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LaTeXView.kt
@@ -27,17 +27,16 @@ fun LaTeXView(latex: String, modifier: Modifier = Modifier) {
AndroidView(
factory = { context ->
LatexContainerView(context).apply {
- layoutParams = ViewGroup.LayoutParams(
- ViewGroup.LayoutParams.MATCH_PARENT,
- ViewGroup.LayoutParams.WRAP_CONTENT
- )
+ layoutParams =
+ ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ )
update(latex, textColor.toArgb(), fontSizePx, paddingPx)
}
},
- update = { view ->
- view.update(latex, textColor.toArgb(), fontSizePx, paddingPx)
- },
- modifier = modifier
+ update = { view -> view.update(latex, textColor.toArgb(), fontSizePx, paddingPx) },
+ modifier = modifier,
)
}
@@ -45,7 +44,7 @@ fun LaTeXView(latex: String, modifier: Modifier = Modifier) {
fun InlineLaTeXView(
latex: String,
modifier: Modifier = Modifier,
- fontSizeSp: Float = 15f
+ fontSizeSp: Float = 15f,
) {
val isDark = isSystemInDarkTheme()
val textColor = if (isDark) EnsuColor.textPrimaryDark else EnsuColor.textPrimaryLight
@@ -55,17 +54,16 @@ fun InlineLaTeXView(
AndroidView(
factory = { context ->
InlineLatexContainerView(context).apply {
- layoutParams = ViewGroup.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT
- )
+ layoutParams =
+ ViewGroup.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ )
update(latex, textColor.toArgb(), fontSizePx, paddingPx)
}
},
- update = { view ->
- view.update(latex, textColor.toArgb(), fontSizePx, paddingPx)
- },
- modifier = modifier
+ update = { view -> view.update(latex, textColor.toArgb(), fontSizePx, paddingPx) },
+ modifier = modifier,
)
}
@@ -78,15 +76,15 @@ private class InlineLatexContainerView(context: Context) : FrameLayout(context)
mathView,
LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT
- )
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ),
)
addView(
fallbackView,
LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT
- )
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ),
)
fallbackView.visibility = View.GONE
}
@@ -104,7 +102,7 @@ private class InlineLatexContainerView(context: Context) : FrameLayout(context)
mathView.setPadding(paddingPx, paddingPx, paddingPx, paddingPx)
MathViewCompat.setMathTextAlignment(
mathView,
- MTMathView.MTTextAlignment.KMTTextAlignmentLeft
+ MTMathView.MTTextAlignment.KMTTextAlignmentLeft,
)
MathViewCompat.setDisplayErrorInline(mathView, false)
@@ -129,15 +127,15 @@ private class LatexContainerView(context: Context) : FrameLayout(context) {
mathView,
LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
- ViewGroup.LayoutParams.WRAP_CONTENT
- )
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ),
)
addView(
fallbackView,
LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
- ViewGroup.LayoutParams.WRAP_CONTENT
- )
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ),
)
fallbackView.visibility = View.GONE
}
@@ -155,7 +153,7 @@ private class LatexContainerView(context: Context) : FrameLayout(context) {
mathView.setPadding(paddingPx, paddingPx, paddingPx, paddingPx)
MathViewCompat.setMathTextAlignment(
mathView,
- MTMathView.MTTextAlignment.KMTTextAlignmentLeft
+ MTMathView.MTTextAlignment.KMTTextAlignmentLeft,
)
MathViewCompat.setDisplayErrorInline(mathView, false)
@@ -222,17 +220,17 @@ private fun countMatches(text: String, regex: Regex): Int {
private fun environmentsBalanced(text: String): Boolean {
val beginMatches = runCatching {
- LatexRegex.beginEnvironment
- .findAll(text)
- .map { it.groupValues[1] }
- .toList()
- }.getOrElse { return false }
+ LatexRegex.beginEnvironment.findAll(text).map { it.groupValues[1] }.toList()
+ }
+ .getOrElse {
+ return false
+ }
val endMatches = runCatching {
- LatexRegex.endEnvironment
- .findAll(text)
- .map { it.groupValues[1] }
- .toList()
- }.getOrElse { return false }
+ LatexRegex.endEnvironment.findAll(text).map { it.groupValues[1] }.toList()
+ }
+ .getOrElse {
+ return false
+ }
if (beginMatches.size != endMatches.size) {
return false
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt
index 2c45065035..249a467e44 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt
@@ -34,104 +34,107 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
-import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuCornerRadius
-import io.ente.ensu.designsystem.HugeIcons
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
+import io.ente.ensu.designsystem.HugeIcons
@Composable
fun MarkdownView(
markdown: String,
enableSelection: Boolean = true,
- trailingCursor: Boolean = false
+ trailingCursor: Boolean = false,
) {
val blocks = remember(markdown) { MarkdownParser.parse(markdown) }
- val content = @Composable {
- Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {
- blocks.forEachIndexed { index, block ->
- key(index) {
- val appendCursor = trailingCursor && index == blocks.lastIndex
- when (block) {
- is MarkdownBlock.Heading -> {
- InlineMarkdownText(
- text = block.text,
- style = headingStyle(block.level),
- color = EnsuColor.textPrimary(),
- appendCursor = appendCursor
- )
- }
- is MarkdownBlock.Paragraph -> {
- InlineMarkdownText(
- text = block.text,
- style = EnsuTypography.message,
- color = EnsuColor.textPrimary(),
- appendCursor = appendCursor
- )
- }
- is MarkdownBlock.BlockQuote -> {
- BlockQuoteView(text = block.text, appendCursor = appendCursor)
- }
- is MarkdownBlock.Code -> {
- CodeBlockView(code = block.text)
- if (appendCursor) {
- TrailingCursor()
+ val content =
+ @Composable {
+ Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {
+ blocks.forEachIndexed { index, block ->
+ key(index) {
+ val appendCursor = trailingCursor && index == blocks.lastIndex
+ when (block) {
+ is MarkdownBlock.Heading -> {
+ InlineMarkdownText(
+ text = block.text,
+ style = headingStyle(block.level),
+ color = EnsuColor.textPrimary(),
+ appendCursor = appendCursor,
+ )
}
- }
- is MarkdownBlock.Math -> {
- MathBlockView(text = block.text)
- if (appendCursor) {
- TrailingCursor()
+ is MarkdownBlock.Paragraph -> {
+ InlineMarkdownText(
+ text = block.text,
+ style = EnsuTypography.message,
+ color = EnsuColor.textPrimary(),
+ appendCursor = appendCursor,
+ )
}
- }
- is MarkdownBlock.ListItems -> {
- Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp)) {
- block.items.forEachIndexed { itemIndex, item ->
- key(itemIndex) {
- val itemCursor = appendCursor && itemIndex == block.items.lastIndex
- Row(
- verticalAlignment = Alignment.Top,
- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
- ) {
- Text(
- text = "β€’",
- style = EnsuTypography.message,
- color = EnsuColor.textPrimary()
- )
- InlineMarkdownText(
- text = item,
- style = EnsuTypography.message,
- color = EnsuColor.textPrimary(),
- appendCursor = itemCursor
- )
+ is MarkdownBlock.BlockQuote -> {
+ BlockQuoteView(text = block.text, appendCursor = appendCursor)
+ }
+ is MarkdownBlock.Code -> {
+ CodeBlockView(code = block.text)
+ if (appendCursor) {
+ TrailingCursor()
+ }
+ }
+ is MarkdownBlock.Math -> {
+ MathBlockView(text = block.text)
+ if (appendCursor) {
+ TrailingCursor()
+ }
+ }
+ is MarkdownBlock.ListItems -> {
+ Column(
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp)
+ ) {
+ block.items.forEachIndexed { itemIndex, item ->
+ key(itemIndex) {
+ val itemCursor =
+ appendCursor && itemIndex == block.items.lastIndex
+ Row(
+ verticalAlignment = Alignment.Top,
+ horizontalArrangement =
+ Arrangement.spacedBy(EnsuSpacing.sm.dp),
+ ) {
+ Text(
+ text = "β€’",
+ style = EnsuTypography.message,
+ color = EnsuColor.textPrimary(),
+ )
+ InlineMarkdownText(
+ text = item,
+ style = EnsuTypography.message,
+ color = EnsuColor.textPrimary(),
+ appendCursor = itemCursor,
+ )
+ }
}
}
}
}
- }
- MarkdownBlock.Divider -> {
- HorizontalDivider(color = EnsuColor.border())
- if (appendCursor) {
- TrailingCursor()
+ MarkdownBlock.Divider -> {
+ HorizontalDivider(color = EnsuColor.border())
+ if (appendCursor) {
+ TrailingCursor()
+ }
}
}
}
}
}
}
- }
if (enableSelection) {
- SelectionContainer {
- content()
- }
+ SelectionContainer { content() }
} else {
content()
}
@@ -140,24 +143,19 @@ fun MarkdownView(
@Composable
private fun BlockQuoteView(text: String, appendCursor: Boolean = false) {
Row(
- modifier = Modifier
- .fillMaxWidth()
- .height(IntrinsicSize.Min)
- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.card.dp))
- .padding(EnsuSpacing.cardPadding.dp)
+ modifier =
+ Modifier.fillMaxWidth()
+ .height(IntrinsicSize.Min)
+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.card.dp))
+ .padding(EnsuSpacing.cardPadding.dp)
) {
- Box(
- modifier = Modifier
- .fillMaxHeight()
- .width(3.dp)
- .background(EnsuColor.border())
- )
+ Box(modifier = Modifier.fillMaxHeight().width(3.dp).background(EnsuColor.border()))
Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
InlineMarkdownText(
text = text,
style = EnsuTypography.message,
color = EnsuColor.textPrimary(),
- appendCursor = appendCursor
+ appendCursor = appendCursor,
)
}
}
@@ -166,40 +164,40 @@ private fun BlockQuoteView(text: String, appendCursor: Boolean = false) {
private fun CodeBlockView(code: String) {
val clipboard = LocalClipboardManager.current
Box(
- modifier = Modifier
- .fillMaxWidth()
- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.codeBlock.dp))
- .border(1.dp, EnsuColor.border(), RoundedCornerShape(EnsuCornerRadius.codeBlock.dp))
+ modifier =
+ Modifier.fillMaxWidth()
+ .background(
+ EnsuColor.fillFaint(),
+ RoundedCornerShape(EnsuCornerRadius.codeBlock.dp),
+ )
+ .border(1.dp, EnsuColor.border(), RoundedCornerShape(EnsuCornerRadius.codeBlock.dp))
) {
Row(
- modifier = Modifier
- .horizontalScroll(rememberScrollState())
- .padding(
- start = EnsuSpacing.cardPadding.dp,
- end = (EnsuSpacing.cardPadding + 32).dp,
- top = EnsuSpacing.cardPadding.dp,
- bottom = (EnsuSpacing.cardPadding + 32).dp
- )
+ modifier =
+ Modifier.horizontalScroll(rememberScrollState())
+ .padding(
+ start = EnsuSpacing.cardPadding.dp,
+ end = (EnsuSpacing.cardPadding + 32).dp,
+ top = EnsuSpacing.cardPadding.dp,
+ bottom = (EnsuSpacing.cardPadding + 32).dp,
+ )
) {
Text(
text = code,
style = EnsuTypography.code,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
}
IconButton(
onClick = { clipboard.setText(AnnotatedString(code)) },
- modifier = Modifier
- .align(Alignment.BottomEnd)
- .padding(EnsuSpacing.xs.dp)
- .size(28.dp)
+ modifier = Modifier.align(Alignment.BottomEnd).padding(EnsuSpacing.xs.dp).size(28.dp),
) {
Icon(
painter = painterResource(HugeIcons.Copy01Icon),
contentDescription = "Copy code",
tint = EnsuColor.textMuted(),
- modifier = Modifier.size(16.dp)
+ modifier = Modifier.size(16.dp),
)
}
}
@@ -208,14 +206,17 @@ private fun CodeBlockView(code: String) {
@Composable
private fun MathBlockView(text: String) {
Box(
- modifier = Modifier
- .fillMaxWidth()
- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.codeBlock.dp))
- .border(1.dp, EnsuColor.border(), RoundedCornerShape(EnsuCornerRadius.codeBlock.dp))
+ modifier =
+ Modifier.fillMaxWidth()
+ .background(
+ EnsuColor.fillFaint(),
+ RoundedCornerShape(EnsuCornerRadius.codeBlock.dp),
+ )
+ .border(1.dp, EnsuColor.border(), RoundedCornerShape(EnsuCornerRadius.codeBlock.dp))
) {
LaTeXView(
latex = text,
- modifier = Modifier.fillMaxWidth()
+ modifier = Modifier.fillMaxWidth(),
)
}
}
@@ -225,30 +226,36 @@ private fun TrailingCursor() {
Text(
text = "▍",
style = EnsuTypography.message,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
}
private fun headingStyle(level: Int): TextStyle {
- val size = when (level) {
- 1 -> 20.sp
- 2 -> 18.sp
- else -> 16.sp
- }
- return EnsuTypography.message.copy(fontSize = size, fontWeight = FontWeight.SemiBold, lineHeight = (size.value + 6).sp)
+ val size =
+ when (level) {
+ 1 -> 20.sp
+ 2 -> 18.sp
+ else -> 16.sp
+ }
+ return EnsuTypography.message.copy(
+ fontSize = size,
+ fontWeight = FontWeight.SemiBold,
+ lineHeight = (size.value + 6).sp,
+ )
}
private data class InlineLinkMatch(
val label: String,
- val endIndexExclusive: Int
+ val endIndexExclusive: Int,
)
private fun markdownAnnotatedText(
text: String,
linkColor: androidx.compose.ui.graphics.Color,
- appendCursor: Boolean = false
+ appendCursor: Boolean = false,
): AnnotatedString {
- val pattern = Regex("""(\[[^\]\n]+\]\([^)]+\)|~~[^~\n]+~~|\*\*[^*\n]+\*\*|`[^`\n]+`|\*[^*\n]+\*)""")
+ val pattern =
+ Regex("""(\[[^\]\n]+\]\([^)]+\)|~~[^~\n]+~~|\*\*[^*\n]+\*\*|`[^`\n]+`|\*[^*\n]+\*)""")
val codeFamily = EnsuTypography.code.fontFamily
return buildAnnotatedString {
var currentIndex = 0
@@ -266,7 +273,7 @@ private fun markdownAnnotatedText(
withStyle(
SpanStyle(
color = linkColor,
- textDecoration = TextDecoration.Underline
+ textDecoration = TextDecoration.Underline,
)
) {
append(token.substring(1, labelEnd))
@@ -313,22 +320,22 @@ private enum class InlineMarkdownStyle {
Italic,
Code,
Strikethrough,
- Link
+ Link,
}
private sealed interface InlineMarkdownSegment {
data class Text(val text: String, val style: InlineMarkdownStyle) : InlineMarkdownSegment
+
data class Math(val latex: String) : InlineMarkdownSegment
}
private data class InlineMathMatch(
val latex: String,
- val endIndexExclusive: Int
+ val endIndexExclusive: Int,
)
-private val mathTokenPattern = Regex(
- """(?<!\\)\$(?!\$)(?:[^$\n\\]|\\.)+?(?<!\\)\$(?!\$)|\\\((?:[^\n\\]|\\.)+?\\\)"""
-)
+private val mathTokenPattern =
+ Regex("""(?<!\\)\$(?!\$)(?:[^$\n\\]|\\.)+?(?<!\\)\$(?!\$)|\\\((?:[^\n\\]|\\.)+?\\\)""")
private fun parseInlineMarkdownSegments(text: String): List<InlineMarkdownSegment> {
val segments = mutableListOf<InlineMarkdownSegment>()
@@ -341,7 +348,7 @@ private fun parseInlineMarkdownSegments(text: String): List<InlineMarkdownSegmen
segments.add(
InlineMarkdownSegment.Text(
text = buffer.toString(),
- style = currentStyle
+ style = currentStyle,
)
)
buffer.clear()
@@ -410,7 +417,7 @@ private fun parseInlineMarkdownSegments(text: String): List<InlineMarkdownSegmen
segments.add(
InlineMarkdownSegment.Text(
text = linkMatch.label,
- style = InlineMarkdownStyle.Link
+ style = InlineMarkdownStyle.Link,
)
)
index = linkMatch.endIndexExclusive
@@ -471,7 +478,7 @@ private fun findInlineMathMatch(text: String, startIndex: Int): InlineMathMatch?
if (text[index + 1] == ')') {
return InlineMathMatch(
latex = text.substring(startIndex + 2, index),
- endIndexExclusive = index + 2
+ endIndexExclusive = index + 2,
)
}
index += 2
@@ -496,15 +503,15 @@ private fun findInlineMathMatch(text: String, startIndex: Int): InlineMathMatch?
}
if (
text[index] == '$' &&
- text[index - 1] != '\\' &&
- (index + 1 >= text.length || text[index + 1] != '$')
+ text[index - 1] != '\\' &&
+ (index + 1 >= text.length || text[index + 1] != '$')
) {
if (index == startIndex + 1) {
return null
}
return InlineMathMatch(
latex = text.substring(startIndex + 1, index),
- endIndexExclusive = index + 1
+ endIndexExclusive = index + 1,
)
}
index += 1
@@ -551,7 +558,7 @@ private fun findInlineLinkMatch(text: String, startIndex: Int): InlineLinkMatch?
if (char == ')') {
return InlineLinkMatch(
label = label,
- endIndexExclusive = index + 1
+ endIndexExclusive = index + 1,
)
}
index += 1
@@ -588,8 +595,7 @@ private fun hasClosingSingleAsterisk(text: String, startIndex: Int): Boolean {
return false
}
-private fun hasInlineMath(text: String): Boolean =
- mathTokenPattern.containsMatchIn(text)
+private fun hasInlineMath(text: String): Boolean = mathTokenPattern.containsMatchIn(text)
private fun splitTextChunks(text: String): List<String> =
Regex("""\s+|\S+\s*""").findAll(text).map { it.value }.toList()
@@ -600,17 +606,18 @@ private fun InlineMarkdownText(
text: String,
style: TextStyle,
color: androidx.compose.ui.graphics.Color,
- appendCursor: Boolean = false
+ appendCursor: Boolean = false,
) {
if (!hasInlineMath(text)) {
Text(
- text = markdownAnnotatedText(
- text = text,
- linkColor = EnsuColor.accent(),
- appendCursor = appendCursor
- ),
+ text =
+ markdownAnnotatedText(
+ text = text,
+ linkColor = EnsuColor.accent(),
+ appendCursor = appendCursor,
+ ),
style = style,
- color = color
+ color = color,
)
return
}
@@ -620,16 +627,14 @@ private fun InlineMarkdownText(
lines.forEachIndexed { lineIndex, line ->
val isLastLine = lineIndex == lines.lastIndex
val segments = parseInlineMarkdownSegments(line)
- val cursorInline = appendCursor &&
- isLastLine &&
- segments.lastOrNull() is InlineMarkdownSegment.Text
- val cursorStandalone = appendCursor &&
- isLastLine &&
- segments.lastOrNull() !is InlineMarkdownSegment.Text
+ val cursorInline =
+ appendCursor && isLastLine && segments.lastOrNull() is InlineMarkdownSegment.Text
+ val cursorStandalone =
+ appendCursor && isLastLine && segments.lastOrNull() !is InlineMarkdownSegment.Text
FlowRow(
horizontalArrangement = Arrangement.spacedBy(0.dp),
- verticalArrangement = Arrangement.spacedBy(2.dp)
+ verticalArrangement = Arrangement.spacedBy(2.dp),
) {
segments.forEachIndexed { segmentIndex, segment ->
when (segment) {
@@ -637,18 +642,19 @@ private fun InlineMarkdownText(
InlineLaTeXView(
latex = segment.latex,
modifier = Modifier.padding(top = 2.dp),
- fontSizeSp = style.fontSize.value
+ fontSizeSp = style.fontSize.value,
)
}
is InlineMarkdownSegment.Text -> {
val chunks = splitTextChunks(segment.text)
chunks.forEachIndexed { chunkIndex, chunk ->
val isLastChunk =
- segmentIndex == segments.lastIndex && chunkIndex == chunks.lastIndex
+ segmentIndex == segments.lastIndex &&
+ chunkIndex == chunks.lastIndex
Text(
text = if (cursorInline && isLastChunk) "$chunk▍" else chunk,
style = styleForInlineSegment(style, segment.style),
- color = colorForInlineSegment(color, segment.style)
+ color = colorForInlineSegment(color, segment.style),
)
}
}
@@ -659,7 +665,7 @@ private fun InlineMarkdownText(
Text(
text = "▍",
style = style,
- color = color
+ color = color,
)
}
}
@@ -669,29 +675,38 @@ private fun InlineMarkdownText(
private fun styleForInlineSegment(
baseStyle: TextStyle,
- inlineStyle: InlineMarkdownStyle
-): TextStyle = when (inlineStyle) {
- InlineMarkdownStyle.Normal -> baseStyle
- InlineMarkdownStyle.Bold -> baseStyle.copy(fontWeight = FontWeight.SemiBold)
- InlineMarkdownStyle.Italic -> baseStyle.copy(fontStyle = FontStyle.Italic)
- InlineMarkdownStyle.Code -> baseStyle.copy(fontFamily = EnsuTypography.code.fontFamily)
- InlineMarkdownStyle.Strikethrough -> baseStyle.copy(textDecoration = TextDecoration.LineThrough)
- InlineMarkdownStyle.Link -> baseStyle.copy(textDecoration = TextDecoration.Underline)
-}
+ inlineStyle: InlineMarkdownStyle,
+): TextStyle =
+ when (inlineStyle) {
+ InlineMarkdownStyle.Normal -> baseStyle
+ InlineMarkdownStyle.Bold -> baseStyle.copy(fontWeight = FontWeight.SemiBold)
+ InlineMarkdownStyle.Italic -> baseStyle.copy(fontStyle = FontStyle.Italic)
+ InlineMarkdownStyle.Code -> baseStyle.copy(fontFamily = EnsuTypography.code.fontFamily)
+ InlineMarkdownStyle.Strikethrough ->
+ baseStyle.copy(textDecoration = TextDecoration.LineThrough)
+ InlineMarkdownStyle.Link -> baseStyle.copy(textDecoration = TextDecoration.Underline)
+ }
@Composable
private fun colorForInlineSegment(
baseColor: androidx.compose.ui.graphics.Color,
- inlineStyle: InlineMarkdownStyle
-): androidx.compose.ui.graphics.Color = if (inlineStyle == InlineMarkdownStyle.Link) EnsuColor.accent() else baseColor
+ inlineStyle: InlineMarkdownStyle,
+): androidx.compose.ui.graphics.Color =
+ if (inlineStyle == InlineMarkdownStyle.Link) EnsuColor.accent() else baseColor
private sealed interface MarkdownBlock {
data class Heading(val level: Int, val text: String) : MarkdownBlock
+
data class Paragraph(val text: String) : MarkdownBlock
+
data class BlockQuote(val text: String) : MarkdownBlock
+
data class Code(val text: String) : MarkdownBlock
+
data class Math(val text: String) : MarkdownBlock
+
data class ListItems(val items: List<String>) : MarkdownBlock
+
data object Divider : MarkdownBlock
}
@@ -786,11 +801,12 @@ private object MarkdownParser {
}
if (trimmed == "\\[" || trimmed == "$$" || trimmed == "[") {
- val endDelimiter = when (trimmed) {
- "\\[" -> "\\]"
- "$$" -> "$$"
- else -> "]"
- }
+ val endDelimiter =
+ when (trimmed) {
+ "\\[" -> "\\]"
+ "$$" -> "$$"
+ else -> "]"
+ }
startMath(endDelimiter)
continue
}
@@ -836,7 +852,9 @@ private object MarkdownParser {
continue
}
- if (trimmed.startsWith("# ") || trimmed.startsWith("## ") || trimmed.startsWith("### ")) {
+ if (
+ trimmed.startsWith("# ") || trimmed.startsWith("## ") || trimmed.startsWith("### ")
+ ) {
flushParagraph()
flushList()
val level = trimmed.takeWhile { it == '#' }.length.coerceIn(1, 3)
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/SessionDrawer.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
index 9cc4004639..89c5bb8caf 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/SessionDrawer.kt
@@ -5,6 +5,7 @@ import androidx.compose.foundation.clickable
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
@@ -14,15 +15,11 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
-import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
-import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.ui.graphics.RectangleShape
-
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -38,6 +35,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
@@ -45,10 +43,9 @@ 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
-import io.ente.ensu.chat.ChatSession
+import io.ente.ensu.designsystem.HugeIcons
import kotlin.math.absoluteValue
@Composable
@@ -57,34 +54,31 @@ fun SessionDrawer(
selectedSessionId: String?,
onSelectSession: (ChatSession) -> Unit,
onDeleteSession: (ChatSession) -> Unit,
- onOpenSettings: () -> Unit
+ onOpenSettings: () -> Unit,
) {
var searchQuery by remember { mutableStateOf("") }
- val filteredSessions = remember(searchQuery, sessions) {
- val query = searchQuery.trim()
- if (query.isEmpty()) {
- sessions
- } else {
- val lower = query.lowercase()
- sessions.filter { session ->
- session.title.lowercase().contains(lower) ||
- (session.lastMessagePreview?.lowercase()?.contains(lower) == true)
+ val filteredSessions =
+ remember(searchQuery, sessions) {
+ val query = searchQuery.trim()
+ if (query.isEmpty()) {
+ sessions
+ } else {
+ val lower = query.lowercase()
+ sessions.filter { session ->
+ session.title.lowercase().contains(lower) ||
+ (session.lastMessagePreview?.lowercase()?.contains(lower) == true)
+ }
}
}
- }
ModalDrawerSheet(
drawerContainerColor = EnsuColor.backgroundBase(),
- drawerShape = RectangleShape
+ drawerShape = RectangleShape,
) {
- Column(
- modifier = Modifier
- .fillMaxSize()
- .windowInsetsPadding(WindowInsets.systemBars)
- ) {
+ Column(modifier = Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.systemBars)) {
DrawerHeader(
searchQuery = searchQuery,
- onSearchChange = { searchQuery = it }
+ onSearchChange = { searchQuery = it },
)
HorizontalDivider(color = EnsuColor.border())
@@ -94,14 +88,12 @@ fun SessionDrawer(
selectedSessionId = selectedSessionId,
onSelectSession = onSelectSession,
onDeleteSession = onDeleteSession,
- modifier = Modifier.weight(1f)
+ modifier = Modifier.weight(1f),
)
HorizontalDivider(color = EnsuColor.border())
- DrawerFooter(
- onOpenSettings = onOpenSettings
- )
+ DrawerFooter(onOpenSettings = onOpenSettings)
}
}
}
@@ -109,19 +101,19 @@ fun SessionDrawer(
@Composable
private fun DrawerHeader(
searchQuery: String,
- onSearchChange: (String) -> Unit
+ onSearchChange: (String) -> Unit,
) {
Column(
- modifier = Modifier
- .fillMaxWidth()
- .background(EnsuColor.backgroundBase())
- .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.md.dp)
+ modifier =
+ Modifier.fillMaxWidth()
+ .background(EnsuColor.backgroundBase())
+ .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.md.dp)
) {
DrawerSearchControls(
query = searchQuery,
onQueryChange = onSearchChange,
onClearSearch = { onSearchChange("") },
- modifier = Modifier.fillMaxWidth()
+ modifier = Modifier.fillMaxWidth(),
)
}
}
@@ -131,26 +123,26 @@ private fun DrawerSearchControls(
query: String,
onQueryChange: (String) -> Unit,
onClearSearch: () -> Unit,
- modifier: Modifier = Modifier
+ modifier: Modifier = Modifier,
) {
val hasQuery = query.isNotBlank()
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
DrawerSearchField(
query = query,
onQueryChange = onQueryChange,
- modifier = Modifier.weight(1f)
+ modifier = Modifier.weight(1f),
)
if (hasQuery) {
DrawerSearchActionButton(
iconRes = HugeIcons.Cancel01Icon,
contentDescription = "Clear search",
- onClick = onClearSearch
+ onClick = onClearSearch,
)
}
}
@@ -160,7 +152,7 @@ private fun DrawerSearchControls(
private fun DrawerSearchField(
query: String,
onQueryChange: (String) -> Unit,
- modifier: Modifier = Modifier
+ modifier: Modifier = Modifier,
) {
OutlinedTextField(
value = query,
@@ -170,7 +162,7 @@ private fun DrawerSearchField(
Text(
text = "Search chats",
style = EnsuTypography.body,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
},
leadingIcon = {
@@ -178,18 +170,19 @@ private fun DrawerSearchField(
painter = painterResource(HugeIcons.Search01Icon),
contentDescription = "Search",
modifier = Modifier.size(18.dp),
- tint = EnsuColor.textMuted()
+ tint = EnsuColor.textMuted(),
)
},
singleLine = true,
textStyle = EnsuTypography.body,
- colors = TextFieldDefaults.colors(
- focusedContainerColor = EnsuColor.fillFaint(),
- unfocusedContainerColor = EnsuColor.fillFaint(),
- focusedIndicatorColor = EnsuColor.fillFaint(),
- unfocusedIndicatorColor = EnsuColor.fillFaint()
- ),
- shape = RoundedCornerShape(EnsuCornerRadius.card.dp)
+ colors =
+ TextFieldDefaults.colors(
+ focusedContainerColor = EnsuColor.fillFaint(),
+ unfocusedContainerColor = EnsuColor.fillFaint(),
+ focusedIndicatorColor = EnsuColor.fillFaint(),
+ unfocusedIndicatorColor = EnsuColor.fillFaint(),
+ ),
+ shape = RoundedCornerShape(EnsuCornerRadius.card.dp),
)
}
@@ -197,19 +190,17 @@ private fun DrawerSearchField(
private fun DrawerSearchActionButton(
iconRes: Int,
contentDescription: String,
- onClick: () -> Unit
+ onClick: () -> Unit,
) {
IconButton(
onClick = onClick,
- modifier = Modifier
- .size(36.dp)
- .clip(CircleShape)
+ modifier = Modifier.size(36.dp).clip(CircleShape),
) {
Icon(
painter = painterResource(iconRes),
contentDescription = contentDescription,
modifier = Modifier.size(18.dp),
- tint = EnsuColor.textPrimary()
+ tint = EnsuColor.textPrimary(),
)
}
}
@@ -220,20 +211,21 @@ private fun SessionGroups(
selectedSessionId: String?,
onSelectSession: (ChatSession) -> Unit,
onDeleteSession: (ChatSession) -> Unit,
- modifier: Modifier = Modifier
+ modifier: Modifier = Modifier,
) {
val grouped = remember(sessions) { sessions.groupBy { sessionGroupLabel(it.updatedAtMillis) } }
val order = listOf("TODAY", "YESTERDAY", "THIS WEEK", "LAST WEEK", "THIS MONTH", "OLDER")
- val orderedGroups = remember(grouped) {
- order.mapNotNull { label ->
- grouped[label]?.takeIf { it.isNotEmpty() }?.let { label to it }
+ val orderedGroups =
+ remember(grouped) {
+ order.mapNotNull { label ->
+ grouped[label]?.takeIf { it.isNotEmpty() }?.let { label to it }
+ }
}
- }
LazyColumn(
modifier = modifier.fillMaxWidth(),
contentPadding = PaddingValues(vertical = EnsuSpacing.lg.dp),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
) {
orderedGroups.forEachIndexed { index, (label, groupSessions) ->
item(key = "header_$label") {
@@ -245,7 +237,7 @@ private fun SessionGroups(
text = label,
style = EnsuTypography.tiny.copy(letterSpacing = 1.sp),
color = EnsuColor.textMuted(),
- modifier = Modifier.padding(horizontal = EnsuSpacing.lg.dp)
+ modifier = Modifier.padding(horizontal = EnsuSpacing.lg.dp),
)
}
}
@@ -255,7 +247,7 @@ private fun SessionGroups(
session = session,
isSelected = session.id == selectedSessionId,
onSelect = { onSelectSession(session) },
- onDelete = { onDeleteSession(session) }
+ onDelete = { onDeleteSession(session) },
)
}
}
@@ -267,21 +259,21 @@ private fun SessionTile(
session: ChatSession,
isSelected: Boolean,
onSelect: () -> Unit,
- onDelete: () -> Unit
+ onDelete: () -> Unit,
) {
Column(
- modifier = Modifier
- .fillMaxWidth()
- .clickable(onClick = onSelect)
- .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.sm.dp)
+ modifier =
+ Modifier.fillMaxWidth()
+ .clickable(onClick = onSelect)
+ .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.sm.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
) {
Column(
modifier = Modifier.weight(1f),
- verticalArrangement = Arrangement.spacedBy(4.dp)
+ verticalArrangement = Arrangement.spacedBy(4.dp),
) {
Text(
text = session.title,
@@ -289,7 +281,7 @@ private fun SessionTile(
fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Medium,
color = EnsuColor.textPrimary(),
maxLines = 1,
- overflow = TextOverflow.Ellipsis
+ overflow = TextOverflow.Ellipsis,
)
val subtitle = session.lastMessagePreview ?: "Nothing here"
Text(
@@ -297,21 +289,21 @@ private fun SessionTile(
style = EnsuTypography.mini,
color = EnsuColor.textMuted(),
maxLines = 1,
- overflow = TextOverflow.Ellipsis
+ overflow = TextOverflow.Ellipsis,
)
}
Box(
- modifier = Modifier
- .size(36.dp)
- .clip(RoundedCornerShape(4.dp))
- .clickable(onClick = onDelete),
- contentAlignment = Alignment.Center
+ modifier =
+ Modifier.size(36.dp)
+ .clip(RoundedCornerShape(4.dp))
+ .clickable(onClick = onDelete),
+ contentAlignment = Alignment.Center,
) {
Icon(
painter = painterResource(HugeIcons.Delete01Icon),
contentDescription = "Delete",
modifier = Modifier.size(18.dp),
- tint = EnsuColor.textMuted()
+ tint = EnsuColor.textMuted(),
)
}
}
@@ -319,28 +311,24 @@ private fun SessionTile(
}
@Composable
-private fun DrawerFooter(
- onOpenSettings: () -> Unit
-) {
+private fun DrawerFooter(onOpenSettings: () -> Unit) {
Row(
- modifier = Modifier
- .fillMaxWidth()
- .clickable(onClick = onOpenSettings)
- .padding(EnsuSpacing.lg.dp),
+ modifier =
+ Modifier.fillMaxWidth().clickable(onClick = onOpenSettings).padding(EnsuSpacing.lg.dp),
verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp),
) {
Text(
text = "Settings",
style = EnsuTypography.body,
color = EnsuColor.textPrimary(),
- modifier = Modifier.weight(1f)
+ modifier = Modifier.weight(1f),
)
Icon(
painter = painterResource(HugeIcons.ArrowRight01Icon),
contentDescription = "Settings",
modifier = Modifier.size(18.dp),
- tint = EnsuColor.textMuted()
+ tint = EnsuColor.textMuted(),
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/VoiceInput.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/VoiceInput.kt
index 4579639007..fccbf2f75e 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/VoiceInput.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/VoiceInput.kt
@@ -14,16 +14,19 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
+import io.ente.ensu.assets.AssetStore
import io.ente.ensu.bindings.AssetDownloadException
import io.ente.ensu.bindings.LlmException
import io.ente.ensu.bindings.Transcriber
import io.ente.ensu.bindings.TranscriptionException
import io.ente.ensu.bindings.transcriptionModelAsset
import io.ente.ensu.bindings.voiceActivityModelAsset
-import io.ente.ensu.assets.AssetStore
-import io.ente.ensu.notes.LocalNotesStore
import io.ente.ensu.llm.ModelMaintenance
import io.ente.ensu.llm.withMaintenanceSuspended
+import io.ente.ensu.notes.LocalNotesStore
+import java.io.ByteArrayOutputStream
+import java.io.IOException
+import kotlin.coroutines.coroutineContext
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -35,15 +38,16 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
-import java.io.ByteArrayOutputStream
-import java.io.IOException
-import kotlin.coroutines.coroutineContext
internal sealed interface VoiceInputState {
data object Idle : VoiceInputState
+
data object Recording : VoiceInputState
+
data class Downloading(val percent: Int?) : VoiceInputState
+
data object Transcribing : VoiceInputState
+
data class Error(val message: String) : VoiceInputState
}
@@ -51,36 +55,38 @@ internal val VoiceInputState.isRecording: Boolean
get() = this is VoiceInputState.Recording
internal val VoiceInputState.isWorking: Boolean
- get() = this is VoiceInputState.Recording ||
- this is VoiceInputState.Downloading ||
- this is VoiceInputState.Transcribing
+ get() =
+ this is VoiceInputState.Recording ||
+ this is VoiceInputState.Downloading ||
+ this is VoiceInputState.Transcribing
internal val VoiceInputState.blocksSend: Boolean
- get() = this is VoiceInputState.Recording ||
- this is VoiceInputState.Transcribing
-
-internal fun VoiceInputState.statusText(): String? = when (this) {
- VoiceInputState.Idle -> null
- VoiceInputState.Recording -> "Listening..."
- is VoiceInputState.Downloading -> {
- val suffix = percent?.let { " ($it%)" }.orEmpty()
- "Downloading voice model...$suffix"
+ get() = this is VoiceInputState.Recording || this is VoiceInputState.Transcribing
+
+internal fun VoiceInputState.statusText(): String? =
+ when (this) {
+ VoiceInputState.Idle -> null
+ VoiceInputState.Recording -> "Listening..."
+ is VoiceInputState.Downloading -> {
+ val suffix = percent?.let { " ($it%)" }.orEmpty()
+ "Downloading voice model...$suffix"
+ }
+ VoiceInputState.Transcribing -> null
+ is VoiceInputState.Error -> message
}
- VoiceInputState.Transcribing -> null
- is VoiceInputState.Error -> message
-}
@Composable
internal fun rememberVoiceTranscriptionController(
assetStore: AssetStore,
transcriber: Transcriber,
- onTranscript: (String) -> Unit
+ onTranscript: (String) -> Unit,
): VoiceTranscriptionController {
val lifecycleOwner = LocalLifecycleOwner.current
val notes = LocalNotesStore.current
- val controller = remember(transcriber, notes) {
- VoiceTranscriptionController(assetStore, transcriber, onTranscript, notes)
- }
+ val controller =
+ remember(transcriber, notes) {
+ VoiceTranscriptionController(assetStore, transcriber, onTranscript, notes)
+ }
DisposableEffect(controller, lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_PAUSE) {
@@ -88,13 +94,9 @@ internal fun rememberVoiceTranscriptionController(
}
}
lifecycleOwner.lifecycle.addObserver(observer)
- onDispose {
- lifecycleOwner.lifecycle.removeObserver(observer)
- }
- }
- DisposableEffect(controller) {
- onDispose { controller.dispose() }
+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
+ DisposableEffect(controller) { onDispose { controller.dispose() } }
return controller
}
@@ -102,12 +104,13 @@ internal class VoiceTranscriptionController(
private val assetStore: AssetStore,
private val transcriber: Transcriber,
private val onTranscript: (String) -> Unit,
- private val maintenance: ModelMaintenance?
+ private val maintenance: ModelMaintenance?,
) {
- private val modelAssets = listOf(
- transcriptionModelAsset(),
- voiceActivityModelAsset()
- )
+ private val modelAssets =
+ listOf(
+ transcriptionModelAsset(),
+ voiceActivityModelAsset(),
+ )
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private val bufferLock = Any()
@@ -149,7 +152,8 @@ internal class VoiceTranscriptionController(
throw error
} catch (error: UnsatisfiedLinkError) {
Log.w(TAG, "Voice transcription is not available on this device", error)
- state = VoiceInputState.Error("Voice transcription is not available on this device.")
+ state =
+ VoiceInputState.Error("Voice transcription is not available on this device.")
} catch (error: TranscriptionException) {
Log.w(TAG, "Voice model preparation failed: ${error.message}", error)
state = VoiceInputState.Error(transcriptionErrorMessage(error))
@@ -171,7 +175,7 @@ internal class VoiceTranscriptionController(
Log.w(
TAG,
"Voice model preparation failed: ${error.javaClass.simpleName}: ${error.message}",
- error
+ error,
)
state = VoiceInputState.Error("Could not transcribe voice input.")
}
@@ -184,52 +188,51 @@ internal class VoiceTranscriptionController(
return
}
- synchronized(bufferLock) {
- recordedPcm = ByteArrayOutputStream()
- }
+ synchronized(bufferLock) { recordedPcm = ByteArrayOutputStream() }
recordingSampleRate = preferredSampleRate
state = VoiceInputState.Recording
- recordingJob = scope.launch(Dispatchers.IO) {
- var recorder: AudioRecord? = null
- try {
- val activeRecorder = createRecorder(recordingSampleRate)
- recorder = activeRecorder
- audioRecord = activeRecorder
- recordingSampleRate = activeRecorder.sampleRate.takeIf { it > 0 } ?: preferredSampleRate
- activeRecorder.startRecording()
- val buffer = ByteArray(readBufferSize(recordingSampleRate))
- while (coroutineContext.isActive) {
- val read = activeRecorder.read(buffer, 0, buffer.size)
- when {
- read > 0 -> synchronized(bufferLock) {
- recordedPcm.write(buffer, 0, read)
+ recordingJob =
+ scope.launch(Dispatchers.IO) {
+ var recorder: AudioRecord? = null
+ try {
+ val activeRecorder = createRecorder(recordingSampleRate)
+ recorder = activeRecorder
+ audioRecord = activeRecorder
+ recordingSampleRate =
+ activeRecorder.sampleRate.takeIf { it > 0 } ?: preferredSampleRate
+ activeRecorder.startRecording()
+ val buffer = ByteArray(readBufferSize(recordingSampleRate))
+ while (coroutineContext.isActive) {
+ val read = activeRecorder.read(buffer, 0, buffer.size)
+ when {
+ read > 0 ->
+ synchronized(bufferLock) { recordedPcm.write(buffer, 0, read) }
+ read < 0 -> throw IOException("Audio recorder failed with code $read")
}
- read < 0 -> throw IOException("Audio recorder failed with code $read")
}
- }
- } catch (error: Throwable) {
- if (error is CancellationException) {
- throw error
- }
- Log.w(TAG, "Could not record microphone audio", error)
- withContext(Dispatchers.Main.immediate) {
- if (state is VoiceInputState.Recording) {
- state = VoiceInputState.Error("Could not record microphone audio.")
+ } catch (error: Throwable) {
+ if (error is CancellationException) {
+ throw error
}
- }
- } finally {
- runCatching {
- if (recorder?.recordingState == AudioRecord.RECORDSTATE_RECORDING) {
- recorder.stop()
+ Log.w(TAG, "Could not record microphone audio", error)
+ withContext(Dispatchers.Main.immediate) {
+ if (state is VoiceInputState.Recording) {
+ state = VoiceInputState.Error("Could not record microphone audio.")
+ }
+ }
+ } finally {
+ runCatching {
+ if (recorder?.recordingState == AudioRecord.RECORDSTATE_RECORDING) {
+ recorder.stop()
+ }
+ }
+ recorder?.release()
+ if (audioRecord === recorder) {
+ audioRecord = null
}
- }
- recorder?.release()
- if (audioRecord === recorder) {
- audioRecord = null
}
}
- }
}
fun stopAndTranscribe() {
@@ -270,84 +273,85 @@ internal class VoiceTranscriptionController(
recordingJob?.cancel()
recordingJob = null
stopActiveRecorder()
- synchronized(bufferLock) {
- recordedPcm.reset()
- }
+ synchronized(bufferLock) { recordedPcm.reset() }
}
fun dispose() {
transientErrorJob?.cancel()
preparingRecordingJob?.cancel()
scope.cancel()
- runCatching {
- audioRecord?.release()
- }
+ runCatching { audioRecord?.release() }
audioRecord = null
}
- private suspend fun transcribeRecording(pcm: ByteArray, sampleRate: Int) = maintenance.withMaintenanceSuspended {
- try {
- ensureTranscriptionModelDownloaded()
- awaitTranscriptionModelPreload()
- val transcript = withContext(Dispatchers.IO) {
- withContext(Dispatchers.Main.immediate) {
- state = VoiceInputState.Transcribing
+ private suspend fun transcribeRecording(pcm: ByteArray, sampleRate: Int) =
+ maintenance.withMaintenanceSuspended {
+ try {
+ ensureTranscriptionModelDownloaded()
+ awaitTranscriptionModelPreload()
+ val transcript =
+ withContext(Dispatchers.IO) {
+ withContext(Dispatchers.Main.immediate) {
+ state = VoiceInputState.Transcribing
+ }
+ transcriber.transcribe(
+ sampleRate.toUInt(),
+ pcm,
+ )
+ }
+ .trim()
+
+ if (transcript.isBlank()) {
+ showTransientError("No speech detected.")
+ } else {
+ onTranscript(transcript)
+ state = VoiceInputState.Idle
}
- transcriber.transcribe(
- sampleRate.toUInt(),
- pcm
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: UnsatisfiedLinkError) {
+ Log.w(TAG, "Voice transcription is not available on this device", error)
+ state =
+ VoiceInputState.Error("Voice transcription is not available on this device.")
+ } catch (error: TranscriptionException) {
+ Log.w(TAG, "Voice transcription failed: ${error.message}", error)
+ state = VoiceInputState.Error(transcriptionErrorMessage(error))
+ } catch (error: AssetDownloadException) {
+ if (error is AssetDownloadException.Cancelled) {
+ state = VoiceInputState.Idle
+ return@withMaintenanceSuspended
+ }
+ Log.w(TAG, "Voice model download failed: ${error.message}", error)
+ state = VoiceInputState.Error(downloadErrorMessage)
+ } catch (error: LlmException) {
+ if (error is LlmException.Cancelled) {
+ state = VoiceInputState.Idle
+ return@withMaintenanceSuspended
+ }
+ Log.w(TAG, "Voice model download failed: ${error.message}", error)
+ state = VoiceInputState.Error(downloadErrorMessage)
+ } catch (error: Throwable) {
+ Log.w(
+ TAG,
+ "Voice transcription failed: ${error.javaClass.simpleName}: ${error.message}",
+ error,
)
- }.trim()
-
- if (transcript.isBlank()) {
- showTransientError("No speech detected.")
- } else {
- onTranscript(transcript)
- state = VoiceInputState.Idle
- }
- } catch (error: CancellationException) {
- throw error
- } catch (error: UnsatisfiedLinkError) {
- Log.w(TAG, "Voice transcription is not available on this device", error)
- state = VoiceInputState.Error("Voice transcription is not available on this device.")
- } catch (error: TranscriptionException) {
- Log.w(TAG, "Voice transcription failed: ${error.message}", error)
- state = VoiceInputState.Error(transcriptionErrorMessage(error))
- } catch (error: AssetDownloadException) {
- if (error is AssetDownloadException.Cancelled) {
- state = VoiceInputState.Idle
- return@withMaintenanceSuspended
- }
- Log.w(TAG, "Voice model download failed: ${error.message}", error)
- state = VoiceInputState.Error(downloadErrorMessage)
- } catch (error: LlmException) {
- if (error is LlmException.Cancelled) {
- state = VoiceInputState.Idle
- return@withMaintenanceSuspended
+ state = VoiceInputState.Error("Could not transcribe voice input.")
}
- Log.w(TAG, "Voice model download failed: ${error.message}", error)
- state = VoiceInputState.Error(downloadErrorMessage)
- } catch (error: Throwable) {
- Log.w(
- TAG,
- "Voice transcription failed: ${error.javaClass.simpleName}: ${error.message}",
- error
- )
- state = VoiceInputState.Error("Could not transcribe voice input.")
}
- }
private fun preloadTranscriptionModel() {
transcriptionPreloadJob?.cancel()
- transcriptionPreloadJob = scope.launch(Dispatchers.IO) {
- try {
- maintenance.withMaintenanceSuspended { transcriber.loadModel() }
- } catch (error: CancellationException) {
- throw error
- } catch (error: Throwable) {
- Log.w(TAG, "Voice model preload failed", error)
+ transcriptionPreloadJob =
+ scope.launch(Dispatchers.IO) {
+ try {
+ maintenance.withMaintenanceSuspended { transcriber.loadModel() }
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: Throwable) {
+ Log.w(TAG, "Voice model preload failed", error)
+ }
}
- }
}
private suspend fun awaitTranscriptionModelPreload() {
@@ -372,7 +376,7 @@ internal class VoiceTranscriptionController(
assetStore.download(modelAssets) { progress ->
postStateIfJobActive(
activeJob,
- VoiceInputState.Downloading(progress.percentage.toInt().coerceIn(0, 100))
+ VoiceInputState.Downloading(progress.percentage.toInt().coerceIn(0, 100)),
)
}
}
@@ -410,11 +414,12 @@ internal class VoiceTranscriptionController(
@SuppressLint("MissingPermission")
private fun createRecorder(sampleRate: Int): AudioRecord {
- val minBufferSize = AudioRecord.getMinBufferSize(
- sampleRate,
- AudioFormat.CHANNEL_IN_MONO,
- AudioFormat.ENCODING_PCM_16BIT
- )
+ val minBufferSize =
+ AudioRecord.getMinBufferSize(
+ sampleRate,
+ AudioFormat.CHANNEL_IN_MONO,
+ AudioFormat.ENCODING_PCM_16BIT,
+ )
if (minBufferSize <= 0) {
throw IOException("Audio recorder buffer unavailable")
}
@@ -439,11 +444,12 @@ internal class VoiceTranscriptionController(
}
private fun readBufferSize(sampleRate: Int): Int {
- val minBufferSize = AudioRecord.getMinBufferSize(
- sampleRate,
- AudioFormat.CHANNEL_IN_MONO,
- AudioFormat.ENCODING_PCM_16BIT
- )
+ val minBufferSize =
+ AudioRecord.getMinBufferSize(
+ sampleRate,
+ AudioFormat.CHANNEL_IN_MONO,
+ AudioFormat.ENCODING_PCM_16BIT,
+ )
return maxOf(minBufferSize, 4096)
}
@@ -452,15 +458,16 @@ internal class VoiceTranscriptionController(
private val downloadErrorMessage =
"Voice model download failed. Check your connection and try again."
- private fun transcriptionErrorMessage(error: TranscriptionException): String = when (error) {
- is TranscriptionException.NotDownloaded,
- is TranscriptionException.VadNotDownloaded,
- is TranscriptionException.Transcribe -> "Voice model could not be loaded."
- is TranscriptionException.InvalidAudio -> "Could not detect speech in this recording."
- is TranscriptionException.StorageFull ->
- "Not enough storage space. Please free up space and try again."
- is TranscriptionException.Io -> "Could not transcribe voice input."
- }
+ private fun transcriptionErrorMessage(error: TranscriptionException): String =
+ when (error) {
+ is TranscriptionException.NotDownloaded,
+ is TranscriptionException.VadNotDownloaded,
+ is TranscriptionException.Transcribe -> "Voice model could not be loaded."
+ is TranscriptionException.InvalidAudio -> "Could not detect speech in this recording."
+ is TranscriptionException.StorageFull ->
+ "Not enough storage space. Please free up space and try again."
+ is TranscriptionException.Io -> "Could not transcribe voice input."
+ }
private fun showTransientError(message: String) {
val errorState = VoiceInputState.Error(message)
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ActionButtons.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ActionButtons.kt
index b56933a992..1b0b6692e9 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ActionButtons.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ActionButtons.kt
@@ -33,7 +33,7 @@ fun ActionButton(
icon: ImageVector,
onTap: () -> Unit,
contentDescription: String,
- color: Color = EnsuColor.textMuted()
+ color: Color = EnsuColor.textMuted(),
) {
val haptic = rememberHaptics()
IconButton(
@@ -42,12 +42,12 @@ fun ActionButton(
onTap()
},
modifier = Modifier.size(36.dp),
- colors = IconButtonDefaults.iconButtonColors(contentColor = color)
+ colors = IconButtonDefaults.iconButtonColors(contentColor = color),
) {
Icon(
imageVector = icon,
contentDescription = contentDescription,
- modifier = Modifier.size(16.dp)
+ modifier = Modifier.size(16.dp),
)
}
}
@@ -57,7 +57,7 @@ fun ActionButton(
iconRes: Int,
onTap: () -> Unit,
contentDescription: String,
- color: Color = EnsuColor.textMuted()
+ color: Color = EnsuColor.textMuted(),
) {
val haptic = rememberHaptics()
IconButton(
@@ -66,12 +66,12 @@ fun ActionButton(
onTap()
},
modifier = Modifier.size(36.dp),
- colors = IconButtonDefaults.iconButtonColors(contentColor = color)
+ colors = IconButtonDefaults.iconButtonColors(contentColor = color),
) {
Icon(
painter = painterResource(iconRes),
contentDescription = contentDescription,
- modifier = Modifier.size(16.dp)
+ modifier = Modifier.size(16.dp),
)
}
}
@@ -79,13 +79,15 @@ fun ActionButton(
@Composable
fun TextActionButton(
text: String,
- onTap: () -> Unit
+ onTap: () -> Unit,
) {
val haptic = rememberHaptics()
- TextButton(onClick = {
- haptic.perform(HapticFeedbackType.TextHandleMove)
- onTap()
- }) {
+ TextButton(
+ onClick = {
+ haptic.perform(HapticFeedbackType.TextHandleMove)
+ onTap()
+ }
+ ) {
Text(text = text, style = EnsuTypography.small, color = EnsuColor.textMuted())
}
}
@@ -95,10 +97,11 @@ fun CompactButton(label: String, onClick: () -> Unit) {
Button(
onClick = onClick,
colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent()),
- contentPadding = PaddingValues(
- horizontal = EnsuSpacing.md.dp,
- vertical = EnsuSpacing.xs.dp
- )
+ contentPadding =
+ PaddingValues(
+ horizontal = EnsuSpacing.md.dp,
+ vertical = EnsuSpacing.xs.dp,
+ ),
) {
Text(label, style = EnsuTypography.mini)
}
@@ -109,7 +112,7 @@ fun PrimaryButton(
text: String,
isLoading: Boolean,
isEnabled: Boolean,
- onClick: () -> Unit
+ onClick: () -> Unit,
) {
Button(
onClick = onClick,
@@ -117,19 +120,20 @@ fun PrimaryButton(
enabled = isEnabled,
colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent()),
contentPadding = PaddingValues(vertical = EnsuSpacing.buttonVertical.dp),
- shape = RoundedCornerShape(EnsuCornerRadius.button.dp)
+ shape = RoundedCornerShape(EnsuCornerRadius.button.dp),
) {
if (isLoading) {
CircularProgressIndicator(
modifier = Modifier.size(18.dp),
color = MaterialTheme.colorScheme.onPrimary,
- strokeWidth = 2.dp
+ strokeWidth = 2.dp,
)
} else {
Text(
text = text,
- style = EnsuTypography.body.copy(fontSize = 18.sp, fontWeight = FontWeight.SemiBold),
- color = MaterialTheme.colorScheme.onPrimary
+ style =
+ EnsuTypography.body.copy(fontSize = 18.sp, fontWeight = FontWeight.SemiBold),
+ color = MaterialTheme.colorScheme.onPrimary,
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/AttachmentChip.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/AttachmentChip.kt
index f3bd287e91..8b0b7f497d 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/AttachmentChip.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/AttachmentChip.kt
@@ -24,9 +24,9 @@ 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
+import io.ente.ensu.designsystem.HugeIcons
import io.ente.ensu.platform.rememberHaptics
@Composable
@@ -36,57 +36,58 @@ fun AttachmentChip(
iconRes: Int,
isUploading: Boolean,
onDelete: (() -> Unit)? = null,
- onClick: (() -> Unit)? = null
+ onClick: (() -> Unit)? = null,
) {
val haptic = rememberHaptics()
- val clickModifier = if (onClick != null) {
- Modifier.clickable {
- haptic.perform(HapticFeedbackType.TextHandleMove)
- onClick()
+ val clickModifier =
+ if (onClick != null) {
+ Modifier.clickable {
+ haptic.perform(HapticFeedbackType.TextHandleMove)
+ onClick()
+ }
+ } else {
+ Modifier
}
- } else {
- Modifier
- }
Row(
verticalAlignment = Alignment.CenterVertically,
- modifier = Modifier
- .widthIn(max = 220.dp)
- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp))
- .then(clickModifier)
- .padding(horizontal = 10.dp, vertical = 6.dp)
+ modifier =
+ Modifier.widthIn(max = 220.dp)
+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.input.dp))
+ .then(clickModifier)
+ .padding(horizontal = 10.dp, vertical = 6.dp),
) {
Icon(
painter = painterResource(iconRes),
contentDescription = null,
modifier = Modifier.size(14.dp),
- tint = EnsuColor.textMuted()
+ tint = EnsuColor.textMuted(),
)
Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
Column(
modifier = Modifier.widthIn(max = 160.dp),
- verticalArrangement = Arrangement.Center
+ verticalArrangement = Arrangement.Center,
) {
Text(
text = name,
style = EnsuTypography.small,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
Text(
text = size,
style = EnsuTypography.mini,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
if (isUploading) {
Spacer(modifier = Modifier.width(EnsuSpacing.xs.dp))
CircularProgressIndicator(
modifier = Modifier.size(12.dp),
- strokeWidth = 2.dp
+ strokeWidth = 2.dp,
)
}
if (onDelete != null) {
@@ -96,12 +97,12 @@ fun AttachmentChip(
haptic.perform(HapticFeedbackType.LongPress)
onDelete()
},
- modifier = Modifier.size(24.dp)
+ modifier = Modifier.size(24.dp),
) {
Icon(
painter = painterResource(HugeIcons.Cancel01Icon),
contentDescription = "Remove attachment",
- tint = EnsuColor.textMuted()
+ tint = EnsuColor.textMuted(),
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/BranchSwitcher.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/BranchSwitcher.kt
index 3ef524c3d3..bddc68c5fa 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/BranchSwitcher.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/BranchSwitcher.kt
@@ -2,11 +2,11 @@ package io.ente.ensu.components
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
-import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
-import androidx.compose.material3.ButtonDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -21,7 +21,7 @@ fun BranchSwitcher(
currentIndex: Int,
totalCount: Int,
onPrevious: () -> Unit,
- onNext: () -> Unit
+ onNext: () -> Unit,
) {
if (totalCount <= 1) return
@@ -34,7 +34,7 @@ fun BranchSwitcher(
},
enabled = currentIndex > 1,
modifier = Modifier.size(36.dp),
- contentPadding = ButtonDefaults.TextButtonContentPadding
+ contentPadding = ButtonDefaults.TextButtonContentPadding,
) {
Text(text = "<", style = EnsuTypography.small, color = EnsuColor.textMuted())
}
@@ -42,7 +42,7 @@ fun BranchSwitcher(
Text(
text = "${currentIndex}/${totalCount}",
style = EnsuTypography.small.copy(fontFeatureSettings = "tnum"),
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
Spacer(modifier = Modifier.width(4.dp))
TextButton(
@@ -52,7 +52,7 @@ fun BranchSwitcher(
},
enabled = currentIndex < totalCount,
modifier = Modifier.size(36.dp),
- contentPadding = ButtonDefaults.TextButtonContentPadding
+ contentPadding = ButtonDefaults.TextButtonContentPadding,
) {
Text(text = ">", style = EnsuTypography.small, color = EnsuColor.textMuted())
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ChoiceDialog.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ChoiceDialog.kt
index d2743f1e44..adff37a86e 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ChoiceDialog.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ChoiceDialog.kt
@@ -21,7 +21,7 @@ fun ChoiceDialog(
isDismissible: Boolean = true,
onFirst: () -> Unit,
onSecond: (() -> Unit)? = null,
- onDismiss: () -> Unit
+ onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = { if (isDismissible) onDismiss() },
@@ -31,7 +31,7 @@ fun ChoiceDialog(
if (isCritical) {
Button(
onClick = onFirst,
- colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.error)
+ colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.error),
) {
Text(text = firstButtonLabel)
}
@@ -45,7 +45,7 @@ fun ChoiceDialog(
if (secondButtonLabel != null && onSecond != null) {
TextButton(
onClick = onSecond,
- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textMuted())
+ colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textMuted()),
) {
Text(text = secondButtonLabel)
}
@@ -53,6 +53,6 @@ fun ChoiceDialog(
},
containerColor = EnsuColor.backgroundBase(),
tonalElevation = 0.dp,
- shape = AlertDialogDefaults.shape
+ shape = AlertDialogDefaults.shape,
)
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ImageAttachmentThumbnail.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ImageAttachmentThumbnail.kt
index 335a75ed41..04f18d4831 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ImageAttachmentThumbnail.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/ImageAttachmentThumbnail.kt
@@ -34,8 +34,8 @@ import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
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.HugeIcons
import io.ente.ensu.platform.rememberHaptics
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -52,94 +52,98 @@ fun ImageAttachmentThumbnail(
squareSize: Dp? = null,
isUploading: Boolean = false,
onDelete: (() -> Unit)? = null,
- onClick: (() -> Unit)? = null
+ onClick: (() -> Unit)? = null,
) {
val density = LocalDensity.current
val maxWidth = maxOf(width, portraitWidth ?: width, squareSize ?: width)
val maxHeight = maxOf(height, portraitHeight ?: height, squareSize ?: height)
val targetWidthPx = with(density) { maxWidth.roundToPx() }
val targetHeightPx = with(density) { maxHeight.roundToPx() }
- val image = produceState<DecodedImage?>(initialValue = null, path, targetWidthPx, targetHeightPx) {
- value = decodeSampledImage(path, targetWidthPx, targetHeightPx)
- }.value
+ val image =
+ produceState<DecodedImage?>(initialValue = null, path, targetWidthPx, targetHeightPx) {
+ value = decodeSampledImage(path, targetWidthPx, targetHeightPx)
+ }
+ .value
val haptic = rememberHaptics()
val shape = RoundedCornerShape(EnsuCornerRadius.card.dp)
- val resolvedWidth = when {
- image?.isPortrait == true && portraitWidth != null -> portraitWidth
- image?.isSquare == true && squareSize != null -> squareSize
- else -> width
- }
- val resolvedHeight = when {
- image?.isPortrait == true && portraitHeight != null -> portraitHeight
- image?.isSquare == true && squareSize != null -> squareSize
- else -> height
- }
- val clickModifier = if (onClick != null) {
- Modifier.clickable {
- haptic.perform(HapticFeedbackType.TextHandleMove)
- onClick()
+ val resolvedWidth =
+ when {
+ image?.isPortrait == true && portraitWidth != null -> portraitWidth
+ image?.isSquare == true && squareSize != null -> squareSize
+ else -> width
+ }
+ val resolvedHeight =
+ when {
+ image?.isPortrait == true && portraitHeight != null -> portraitHeight
+ image?.isSquare == true && squareSize != null -> squareSize
+ else -> height
+ }
+ val clickModifier =
+ if (onClick != null) {
+ Modifier.clickable {
+ haptic.perform(HapticFeedbackType.TextHandleMove)
+ onClick()
+ }
+ } else {
+ Modifier
}
- } else {
- Modifier
- }
Box(
- modifier = modifier
- .size(width = resolvedWidth, height = resolvedHeight)
- .clip(shape)
- .background(EnsuColor.fillFaint(), shape)
- .then(clickModifier),
- contentAlignment = Alignment.Center
+ modifier =
+ modifier
+ .size(width = resolvedWidth, height = resolvedHeight)
+ .clip(shape)
+ .background(EnsuColor.fillFaint(), shape)
+ .then(clickModifier),
+ contentAlignment = Alignment.Center,
) {
if (image != null) {
Image(
bitmap = image.bitmap,
contentDescription = contentDescription,
modifier = Modifier.fillMaxSize(),
- contentScale = ContentScale.Crop
+ contentScale = ContentScale.Crop,
)
} else {
Icon(
painter = painterResource(HugeIcons.Attachment01Icon),
contentDescription = contentDescription,
modifier = Modifier.size(24.dp),
- tint = EnsuColor.textMuted()
+ tint = EnsuColor.textMuted(),
)
}
if (isUploading) {
Box(
- modifier = Modifier
- .fillMaxSize()
- .background(Color.Black.copy(alpha = 0.18f)),
- contentAlignment = Alignment.Center
+ modifier = Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.18f)),
+ contentAlignment = Alignment.Center,
) {
CircularProgressIndicator(
modifier = Modifier.size(22.dp),
strokeWidth = 2.dp,
- color = Color.White
+ color = Color.White,
)
}
}
if (onDelete != null) {
Box(
- modifier = Modifier
- .align(Alignment.TopEnd)
- .padding(4.dp)
- .size(20.dp)
- .background(Color.Black.copy(alpha = 0.42f), CircleShape)
- .clickable {
- haptic.perform(HapticFeedbackType.LongPress)
- onDelete()
- },
- contentAlignment = Alignment.Center
+ modifier =
+ Modifier.align(Alignment.TopEnd)
+ .padding(4.dp)
+ .size(20.dp)
+ .background(Color.Black.copy(alpha = 0.42f), CircleShape)
+ .clickable {
+ haptic.perform(HapticFeedbackType.LongPress)
+ onDelete()
+ },
+ contentAlignment = Alignment.Center,
) {
Icon(
painter = painterResource(HugeIcons.Cancel01Icon),
contentDescription = "Remove image",
modifier = Modifier.size(9.dp),
- tint = Color.White
+ tint = Color.White,
)
}
}
@@ -150,85 +154,89 @@ fun ImageAttachmentThumbnail(
fun ImageAttachmentPreviewDialog(
path: String?,
contentDescription: String?,
- onDismiss: () -> Unit
+ onDismiss: () -> Unit,
) {
val density = LocalDensity.current
Dialog(
onDismissRequest = onDismiss,
- properties = DialogProperties(usePlatformDefaultWidth = false)
+ properties = DialogProperties(usePlatformDefaultWidth = false),
) {
BoxWithConstraints(
- modifier = Modifier
- .fillMaxSize()
- .background(Color.Black.copy(alpha = 0.94f))
- .clickable(
- interactionSource = remember { MutableInteractionSource() },
- indication = null,
- onClick = onDismiss
- )
+ modifier =
+ Modifier.fillMaxSize()
+ .background(Color.Black.copy(alpha = 0.94f))
+ .clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null,
+ onClick = onDismiss,
+ )
) {
val targetWidthPx = with(density) { maxWidth.roundToPx() }
val targetHeightPx = with(density) { maxHeight.roundToPx() }
- val image = produceState<DecodedImage?>(initialValue = null, path, targetWidthPx, targetHeightPx) {
- value = decodeSampledImage(path, targetWidthPx, targetHeightPx)
- }.value
+ val image =
+ produceState<DecodedImage?>(
+ initialValue = null,
+ path,
+ targetWidthPx,
+ targetHeightPx,
+ ) {
+ value = decodeSampledImage(path, targetWidthPx, targetHeightPx)
+ }
+ .value
if (image != null) {
val previewPadding = EnsuSpacing.md.dp
val availableWidth = maxOf(0.dp, maxWidth - previewPadding - previewPadding)
val availableHeight = maxOf(0.dp, maxHeight - previewPadding - previewPadding)
- val (displayWidth, displayHeight) = fittedImageSize(
- bitmapWidth = image.bitmap.width,
- bitmapHeight = image.bitmap.height,
- availableWidth = availableWidth,
- availableHeight = availableHeight
- )
+ val (displayWidth, displayHeight) =
+ fittedImageSize(
+ bitmapWidth = image.bitmap.width,
+ bitmapHeight = image.bitmap.height,
+ availableWidth = availableWidth,
+ availableHeight = availableHeight,
+ )
Image(
bitmap = image.bitmap,
contentDescription = contentDescription,
- modifier = Modifier
- .align(Alignment.Center)
- .size(width = displayWidth, height = displayHeight)
- .clickable(
- interactionSource = remember { MutableInteractionSource() },
- indication = null,
- onClick = {}
- ),
- contentScale = ContentScale.Fit
+ modifier =
+ Modifier.align(Alignment.Center)
+ .size(width = displayWidth, height = displayHeight)
+ .clickable(
+ interactionSource = remember { MutableInteractionSource() },
+ indication = null,
+ onClick = {},
+ ),
+ contentScale = ContentScale.Fit,
)
} else {
Icon(
painter = painterResource(HugeIcons.Attachment01Icon),
contentDescription = contentDescription,
- modifier = Modifier
- .align(Alignment.Center)
- .size(32.dp),
- tint = Color.White.copy(alpha = 0.7f)
+ modifier = Modifier.align(Alignment.Center).size(32.dp),
+ tint = Color.White.copy(alpha = 0.7f),
)
}
IconButton(
onClick = onDismiss,
- modifier = Modifier
- .align(Alignment.TopEnd)
- .padding(EnsuSpacing.lg.dp)
- .size(32.dp)
- .background(Color.Black.copy(alpha = 0.35f), CircleShape)
+ modifier =
+ Modifier.align(Alignment.TopEnd)
+ .padding(EnsuSpacing.lg.dp)
+ .size(32.dp)
+ .background(Color.Black.copy(alpha = 0.35f), CircleShape),
) {
Icon(
painter = painterResource(HugeIcons.Cancel01Icon),
contentDescription = "Close image preview",
modifier = Modifier.size(14.dp),
- tint = Color.White
+ tint = Color.White,
)
}
}
}
}
-private data class DecodedImage(
- val bitmap: ImageBitmap
-) {
+private data class DecodedImage(val bitmap: ImageBitmap) {
val isPortrait: Boolean = bitmap.height > bitmap.width
val isSquare: Boolean = bitmap.height == bitmap.width
}
@@ -237,13 +245,10 @@ private fun fittedImageSize(
bitmapWidth: Int,
bitmapHeight: Int,
availableWidth: Dp,
- availableHeight: Dp
+ availableHeight: Dp,
): Pair<Dp, Dp> {
if (
- bitmapWidth <= 0 ||
- bitmapHeight <= 0 ||
- availableWidth <= 0.dp ||
- availableHeight <= 0.dp
+ bitmapWidth <= 0 || bitmapHeight <= 0 || availableWidth <= 0.dp || availableHeight <= 0.dp
) {
return 0.dp to 0.dp
}
@@ -260,43 +265,46 @@ private fun fittedImageSize(
private suspend fun decodeSampledImage(
path: String?,
targetWidthPx: Int,
- targetHeightPx: Int
-): DecodedImage? = withContext(Dispatchers.IO) {
- if (path.isNullOrBlank() || targetWidthPx <= 0 || targetHeightPx <= 0) {
- return@withContext null
- }
+ targetHeightPx: Int,
+): DecodedImage? =
+ withContext(Dispatchers.IO) {
+ if (path.isNullOrBlank() || targetWidthPx <= 0 || targetHeightPx <= 0) {
+ return@withContext null
+ }
- val bounds = BitmapFactory.Options().apply {
- inJustDecodeBounds = true
- }
- BitmapFactory.decodeFile(path, bounds)
- if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
- return@withContext null
- }
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeFile(path, bounds)
+ if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
+ return@withContext null
+ }
- val options = BitmapFactory.Options().apply {
- inSampleSize = calculateInSampleSize(
- width = bounds.outWidth,
- height = bounds.outHeight,
- targetWidth = targetWidthPx,
- targetHeight = targetHeightPx
- )
- }
+ val options =
+ BitmapFactory.Options().apply {
+ inSampleSize =
+ calculateInSampleSize(
+ width = bounds.outWidth,
+ height = bounds.outHeight,
+ targetWidth = targetWidthPx,
+ targetHeight = targetHeightPx,
+ )
+ }
- BitmapFactory.decodeFile(path, options)?.asImageBitmap()?.let(::DecodedImage)
-}
+ BitmapFactory.decodeFile(path, options)?.asImageBitmap()?.let(::DecodedImage)
+ }
private fun calculateInSampleSize(
width: Int,
height: Int,
targetWidth: Int,
- targetHeight: Int
+ targetHeight: Int,
): Int {
var inSampleSize = 1
if (height > targetHeight || width > targetWidth) {
val halfHeight = height / 2
val halfWidth = width / 2
- while (halfHeight / inSampleSize >= targetHeight && halfWidth / inSampleSize >= targetWidth) {
+ while (
+ halfHeight / inSampleSize >= targetHeight && halfWidth / inSampleSize >= targetWidth
+ ) {
inSampleSize *= 2
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/KnowledgeComponents.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/KnowledgeComponents.kt
index a292399a8e..9bce53d973 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/KnowledgeComponents.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/KnowledgeComponents.kt
@@ -26,15 +26,15 @@ import io.ente.ensu.designsystem.EnsuTypography
internal fun KnowledgeCard(
padding: Dp = EnsuSpacing.lg.dp,
spacing: Dp = 0.dp,
- content: @Composable ColumnScope.() -> Unit
+ content: @Composable ColumnScope.() -> Unit,
) {
Column(
- modifier = Modifier
- .fillMaxWidth()
- .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.card.dp))
- .padding(padding),
+ modifier =
+ Modifier.fillMaxWidth()
+ .background(EnsuColor.fillFaint(), RoundedCornerShape(EnsuCornerRadius.card.dp))
+ .padding(padding),
verticalArrangement = Arrangement.spacedBy(spacing),
- content = content
+ content = content,
)
}
@@ -42,7 +42,7 @@ internal fun KnowledgeCard(
internal fun AttributionDialog(
title: String,
onDismiss: () -> Unit,
- content: @Composable ColumnScope.() -> Unit
+ content: @Composable ColumnScope.() -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
@@ -51,11 +51,11 @@ internal fun AttributionDialog(
Column(
modifier = Modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp),
- content = content
+ content = content,
)
},
confirmButton = { TextButton(onClick = onDismiss) { Text("Done") } },
- containerColor = EnsuColor.backgroundBase()
+ containerColor = EnsuColor.backgroundBase(),
)
}
@@ -63,7 +63,7 @@ internal fun AttributionDialog(
internal fun AttributionLink(label: String, onClick: () -> Unit) {
TextButton(
onClick = onClick,
- contentPadding = PaddingValues(vertical = EnsuSpacing.xs.dp)
+ contentPadding = PaddingValues(vertical = EnsuSpacing.xs.dp),
) {
Text(label, style = EnsuTypography.mini, color = EnsuColor.accent())
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/Logo.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/Logo.kt
index 6113b354a9..abf538ae1e 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/Logo.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/Logo.kt
@@ -23,23 +23,22 @@ fun Logo(
height: Dp = 24.dp,
horizontalPadding: Dp = 4.dp,
verticalPadding: Dp = 2.dp,
- tint: Color = EnsuColor.textPrimary()
+ tint: Color = EnsuColor.textPrimary(),
) {
val imageHeight = height - verticalPadding * 2
Box(
- modifier = modifier
- .height(height)
- .padding(horizontal = horizontalPadding, vertical = verticalPadding),
- contentAlignment = Alignment.Center
+ modifier =
+ modifier
+ .height(height)
+ .padding(horizontal = horizontalPadding, vertical = verticalPadding),
+ contentAlignment = Alignment.Center,
) {
Image(
painter = painterResource(R.drawable.ensu_logo),
contentDescription = "Ensu",
- modifier = Modifier
- .height(imageHeight)
- .aspectRatio(906f / 255f),
+ modifier = Modifier.height(imageHeight).aspectRatio(906f / 255f),
contentScale = ContentScale.Fit,
- colorFilter = ColorFilter.tint(tint)
+ colorFilter = ColorFilter.tint(tint),
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/NativeChoiceDialog.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/NativeChoiceDialog.kt
index 6e148ceb15..6c784fb788 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/components/NativeChoiceDialog.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/components/NativeChoiceDialog.kt
@@ -16,7 +16,7 @@ fun NativeChoiceDialog(
isDismissible: Boolean = true,
onFirst: () -> Unit,
onSecond: (() -> Unit)? = null,
- onDismiss: () -> Unit
+ onDismiss: () -> Unit,
) {
val context = LocalContext.current
val currentOnFirst by rememberUpdatedState(onFirst)
@@ -24,17 +24,15 @@ fun NativeChoiceDialog(
val currentOnDismiss by rememberUpdatedState(onDismiss)
DisposableEffect(title, body, firstButtonLabel, secondButtonLabel, isDismissible) {
- val builder = AlertDialog.Builder(context)
- .setTitle(title)
- .setMessage(body)
- .setPositiveButton(firstButtonLabel) { _, _ ->
+ val builder =
+ AlertDialog.Builder(context).setTitle(title).setMessage(body).setPositiveButton(
+ firstButtonLabel
+ ) { _, _ ->
currentOnFirst()
}
if (secondButtonLabel != null && currentOnSecond != null) {
- builder.setNegativeButton(secondButtonLabel) { _, _ ->
- currentOnSecond?.invoke()
- }
+ builder.setNegativeButton(secondButtonLabel) { _, _ -> currentOnSecond?.invoke() }
}
val dialog = builder.create()
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.kt
index 86afa453fd..8fe06fae1f 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.kt
@@ -51,7 +51,8 @@ object EnsuColor {
val toastTextDark = Color(0xFF1A1A1A)
@Composable
- fun backgroundBase(): Color = if (isSystemInDarkTheme()) backgroundBaseDark else backgroundBaseLight
+ fun backgroundBase(): Color =
+ if (isSystemInDarkTheme()) backgroundBaseDark else backgroundBaseLight
@Composable
fun textPrimary(): Color = if (isSystemInDarkTheme()) textPrimaryDark else textPrimaryLight
@@ -59,23 +60,22 @@ object EnsuColor {
@Composable
fun textMuted(): Color = if (isSystemInDarkTheme()) textMutedDark else textMutedLight
- @Composable
- fun border(): Color = if (isSystemInDarkTheme()) borderDark else borderLight
+ @Composable fun border(): Color = if (isSystemInDarkTheme()) borderDark else borderLight
@Composable
fun fillFaint(): Color = if (isSystemInDarkTheme()) fillFaintDark else fillFaintLight
- @Composable
- fun accent(): Color = if (isSystemInDarkTheme()) accentDark else accentLight
+ @Composable fun accent(): Color = if (isSystemInDarkTheme()) accentDark else accentLight
- @Composable
- fun action(): Color = if (isSystemInDarkTheme()) actionDark else actionLight
+ @Composable fun action(): Color = if (isSystemInDarkTheme()) actionDark else actionLight
@Composable
- fun userMessageText(): Color = if (isSystemInDarkTheme()) userMessageTextDark else userMessageTextLight
+ fun userMessageText(): Color =
+ if (isSystemInDarkTheme()) userMessageTextDark else userMessageTextLight
@Composable
- fun toastBackground(): Color = if (isSystemInDarkTheme()) toastBackgroundDark else toastBackgroundLight
+ fun toastBackground(): Color =
+ if (isSystemInDarkTheme()) toastBackgroundDark else toastBackgroundLight
@Composable
fun toastText(): Color = if (isSystemInDarkTheme()) toastTextDark else toastTextLight
@@ -108,52 +108,131 @@ object EnsuCornerRadius {
}
object EnsuTypography {
- private val serifFamily = FontFamily(
- Font(R.font.dm_serif_text_regular, FontWeight.Medium),
- Font(R.font.dm_serif_text_regular, FontWeight.SemiBold)
- )
-
- private val uiFamily = FontFamily(
- Font(R.font.inter_regular, FontWeight.Normal),
- Font(R.font.inter_medium, FontWeight.Medium),
- Font(R.font.inter_semibold, FontWeight.SemiBold),
- Font(R.font.inter_bold, FontWeight.Bold)
- )
+ private val serifFamily =
+ FontFamily(
+ Font(R.font.dm_serif_text_regular, FontWeight.Medium),
+ Font(R.font.dm_serif_text_regular, FontWeight.SemiBold),
+ )
+
+ private val uiFamily =
+ FontFamily(
+ Font(R.font.inter_regular, FontWeight.Normal),
+ Font(R.font.inter_medium, FontWeight.Medium),
+ Font(R.font.inter_semibold, FontWeight.SemiBold),
+ Font(R.font.inter_bold, FontWeight.Bold),
+ )
private val messageFamily = uiFamily
- private val codeFamily = FontFamily(
- Font(R.font.jetbrainsmono_regular, FontWeight.Normal)
- )
-
- val h1 = TextStyle(fontFamily = serifFamily, fontSize = 48.sp, fontWeight = FontWeight.Medium, lineHeight = 82.sp)
- val h2 = TextStyle(fontFamily = serifFamily, fontSize = 32.sp, fontWeight = FontWeight.Medium, lineHeight = 39.sp)
- val h3 = TextStyle(fontFamily = serifFamily, fontSize = 24.sp, fontWeight = FontWeight.Medium, lineHeight = 29.sp)
- val large = TextStyle(fontFamily = serifFamily, fontSize = 18.sp, fontWeight = FontWeight.Medium, lineHeight = 22.sp)
-
- val h1Bold = TextStyle(fontFamily = serifFamily, fontSize = 48.sp, fontWeight = FontWeight.SemiBold, lineHeight = 82.sp)
- val h2Bold = TextStyle(fontFamily = serifFamily, fontSize = 32.sp, fontWeight = FontWeight.SemiBold, lineHeight = 39.sp)
- val h3Bold = TextStyle(fontFamily = serifFamily, fontSize = 24.sp, fontWeight = FontWeight.SemiBold, lineHeight = 29.sp)
-
- val body = TextStyle(fontFamily = uiFamily, fontSize = 16.sp, fontWeight = FontWeight.Medium, lineHeight = 20.sp)
- val small = TextStyle(fontFamily = uiFamily, fontSize = 14.sp, fontWeight = FontWeight.Medium, lineHeight = 17.sp)
- val mini = TextStyle(fontFamily = uiFamily, fontSize = 12.sp, fontWeight = FontWeight.Medium, lineHeight = 15.sp)
- val tiny = TextStyle(fontFamily = uiFamily, fontSize = 10.sp, fontWeight = FontWeight.Medium, lineHeight = 12.sp)
-
- val message = TextStyle(fontFamily = messageFamily, fontSize = 15.sp, fontWeight = FontWeight.Normal, lineHeight = 26.sp)
- val code = TextStyle(fontFamily = codeFamily, fontSize = 13.sp, fontWeight = FontWeight.Normal, lineHeight = 19.sp)
-
- val material = Typography(
- bodyLarge = body,
- bodyMedium = body,
- bodySmall = small,
- titleLarge = h2,
- titleMedium = h3,
- titleSmall = large,
- labelLarge = small,
- labelMedium = mini,
- labelSmall = tiny
- )
+ private val codeFamily = FontFamily(Font(R.font.jetbrainsmono_regular, FontWeight.Normal))
+
+ val h1 =
+ TextStyle(
+ fontFamily = serifFamily,
+ fontSize = 48.sp,
+ fontWeight = FontWeight.Medium,
+ lineHeight = 82.sp,
+ )
+ val h2 =
+ TextStyle(
+ fontFamily = serifFamily,
+ fontSize = 32.sp,
+ fontWeight = FontWeight.Medium,
+ lineHeight = 39.sp,
+ )
+ val h3 =
+ TextStyle(
+ fontFamily = serifFamily,
+ fontSize = 24.sp,
+ fontWeight = FontWeight.Medium,
+ lineHeight = 29.sp,
+ )
+ val large =
+ TextStyle(
+ fontFamily = serifFamily,
+ fontSize = 18.sp,
+ fontWeight = FontWeight.Medium,
+ lineHeight = 22.sp,
+ )
+
+ val h1Bold =
+ TextStyle(
+ fontFamily = serifFamily,
+ fontSize = 48.sp,
+ fontWeight = FontWeight.SemiBold,
+ lineHeight = 82.sp,
+ )
+ val h2Bold =
+ TextStyle(
+ fontFamily = serifFamily,
+ fontSize = 32.sp,
+ fontWeight = FontWeight.SemiBold,
+ lineHeight = 39.sp,
+ )
+ val h3Bold =
+ TextStyle(
+ fontFamily = serifFamily,
+ fontSize = 24.sp,
+ fontWeight = FontWeight.SemiBold,
+ lineHeight = 29.sp,
+ )
+
+ val body =
+ TextStyle(
+ fontFamily = uiFamily,
+ fontSize = 16.sp,
+ fontWeight = FontWeight.Medium,
+ lineHeight = 20.sp,
+ )
+ val small =
+ TextStyle(
+ fontFamily = uiFamily,
+ fontSize = 14.sp,
+ fontWeight = FontWeight.Medium,
+ lineHeight = 17.sp,
+ )
+ val mini =
+ TextStyle(
+ fontFamily = uiFamily,
+ fontSize = 12.sp,
+ fontWeight = FontWeight.Medium,
+ lineHeight = 15.sp,
+ )
+ val tiny =
+ TextStyle(
+ fontFamily = uiFamily,
+ fontSize = 10.sp,
+ fontWeight = FontWeight.Medium,
+ lineHeight = 12.sp,
+ )
+
+ val message =
+ TextStyle(
+ fontFamily = messageFamily,
+ fontSize = 15.sp,
+ fontWeight = FontWeight.Normal,
+ lineHeight = 26.sp,
+ )
+ val code =
+ TextStyle(
+ fontFamily = codeFamily,
+ fontSize = 13.sp,
+ fontWeight = FontWeight.Normal,
+ lineHeight = 19.sp,
+ )
+
+ val material =
+ Typography(
+ bodyLarge = body,
+ bodyMedium = body,
+ bodySmall = small,
+ titleLarge = h2,
+ titleMedium = h3,
+ titleSmall = large,
+ labelLarge = small,
+ labelMedium = mini,
+ labelSmall = tiny,
+ )
}
@Composable
@@ -162,52 +241,43 @@ fun Theme(content: @Composable () -> Unit) {
MaterialTheme(
colorScheme = if (isDark) darkEnsuColorScheme() else lightEnsuColorScheme(),
typography = EnsuTypography.material,
- content = content
+ content = content,
)
}
-private fun lightEnsuColorScheme(): ColorScheme = lightColorScheme(
- primary = EnsuColor.accentLight,
- onPrimary = Color.Black,
-
- 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 = Color.Black,
-
- 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,
+private fun lightEnsuColorScheme(): ColorScheme =
+ lightColorScheme(
+ primary = EnsuColor.accentLight,
+ onPrimary = Color.Black,
+ 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,
+ )
- error = EnsuColor.error
-)
+private fun darkEnsuColorScheme(): ColorScheme =
+ darkColorScheme(
+ primary = EnsuColor.accentDark,
+ onPrimary = Color.Black,
+ 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/android/apps/ensu/app/src/main/java/io/ente/ensu/device/AndroidDeviceCapabilityProvider.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/device/AndroidDeviceCapabilityProvider.kt
index 297e495b5f..e60d0d6242 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/device/AndroidDeviceCapabilityProvider.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/device/AndroidDeviceCapabilityProvider.kt
@@ -2,15 +2,14 @@ package io.ente.ensu.device
import android.app.ActivityManager
import android.content.Context
-import io.ente.ensu.device.CHAT_MIN_RAM_BYTES
-import io.ente.ensu.device.ChatDeviceCapability
class AndroidDeviceCapabilityProvider(context: Context) {
private val appContext = context.applicationContext
fun chatCapability(): ChatDeviceCapability {
- val activityManager = appContext.getSystemService(ActivityManager::class.java)
- ?: return ChatDeviceCapability.Unknown
+ val activityManager =
+ appContext.getSystemService(ActivityManager::class.java)
+ ?: return ChatDeviceCapability.Unknown
val memoryInfo = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(memoryInfo)
val totalMemoryBytes = memoryInfo.totalMem
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/device/ChatDeviceCapability.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/device/ChatDeviceCapability.kt
index 937e890b27..c0e0f587e1 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/device/ChatDeviceCapability.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/device/ChatDeviceCapability.kt
@@ -8,13 +8,11 @@ const val CHAT_MIN_RAM_BYTES: Long = 3_200_000_000L
sealed interface ChatDeviceCapability {
val totalMemoryBytes: Long?
- data class Supported(
- override val totalMemoryBytes: Long?
- ) : ChatDeviceCapability
+ data class Supported(override val totalMemoryBytes: Long?) : ChatDeviceCapability
data class UnsupportedLowMemory(
override val totalMemoryBytes: Long,
- val requiredMemoryBytes: Long = CHAT_MIN_RAM_BYTES
+ val requiredMemoryBytes: Long = CHAT_MIN_RAM_BYTES,
) : ChatDeviceCapability
object Unknown : ChatDeviceCapability {
@@ -22,10 +20,8 @@ sealed interface ChatDeviceCapability {
}
}
-
-class UnsupportedDeviceMemoryException(
- val capability: ChatDeviceCapability.UnsupportedLowMemory
-) : IllegalStateException("Device does not have enough RAM for local chat")
+class UnsupportedDeviceMemoryException(val capability: ChatDeviceCapability.UnsupportedLowMemory) :
+ IllegalStateException("Device does not have enough RAM for local chat")
fun ChatDeviceCapability.isChatSupported(): Boolean =
this !is ChatDeviceCapability.UnsupportedLowMemory
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeProvider.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeProvider.kt
index f490c07af8..c359f02832 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeProvider.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeProvider.kt
@@ -18,16 +18,12 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
-class KnowledgeProvider(
- private val assetStore: AssetStore
-) {
- private data class ActiveMutation(
- val task: Deferred<KnowledgeReconciliation>
- )
+class KnowledgeProvider(private val assetStore: AssetStore) {
+ private data class ActiveMutation(val task: Deferred<KnowledgeReconciliation>)
private data class OpenIndex(
val directory: String,
- val index: RetrievalIndex
+ val index: RetrievalIndex,
)
private val mutationGate = Mutex()
@@ -44,57 +40,63 @@ class KnowledgeProvider(
mutationGate.withLock {
if (
mutations[dataset.stableId] === activeMutation &&
- activeMutation.task.isCompleted
+ activeMutation.task.isCompleted
) {
mutations.remove(dataset.stableId)
}
}
- result.getOrNull()?.let { return@withLock it }
- currentCoroutineContext().ensureActive()
- }
- withContext(Dispatchers.IO) {
- indexGate.withLock {
- reconcileAndOpenLocked(dataset)
+ result.getOrNull()?.let {
+ return@withLock it
}
+ currentCoroutineContext().ensureActive()
}
+ withContext(Dispatchers.IO) { indexGate.withLock { reconcileAndOpenLocked(dataset) } }
}
suspend fun download(
dataset: KnowledgeDatasetConfig,
- onProgress: (KnowledgeDownloadProgress) -> Unit
+ onProgress: (KnowledgeDownloadProgress) -> Unit,
): KnowledgeReconciliation = coroutineScope {
var ownsMutation = false
- val mutation = lifecycleGate(dataset.stableId).withLock {
- mutationGate.withLock {
- mutations[dataset.stableId] ?: run {
- ownsMutation = true
- val task = async(Dispatchers.IO) {
- try {
- assetStore.download(listOf(knowledgePackAsset(dataset.stableId))) {
- onProgress(KnowledgeDownloadProgress(it.label, it.percentage))
- }
- indexGate.withLock {
- val result = reconcileAndOpenLocked(dataset)
- check(result.activeIdentity == dataset.currentDownloadIdentity) {
- "Downloaded knowledge pack failed current revision validation"
- }
- result
- }
- } catch (error: Throwable) {
- withContext(NonCancellable) {
- indexGate.withLock {
- runCatching { reconcileAndOpenLocked(dataset) }
+ val mutation =
+ lifecycleGate(dataset.stableId).withLock {
+ mutationGate.withLock {
+ mutations[dataset.stableId]
+ ?: run {
+ ownsMutation = true
+ val task =
+ async(Dispatchers.IO) {
+ try {
+ assetStore.download(
+ listOf(knowledgePackAsset(dataset.stableId))
+ ) {
+ onProgress(
+ KnowledgeDownloadProgress(it.label, it.percentage)
+ )
+ }
+ indexGate.withLock {
+ val result = reconcileAndOpenLocked(dataset)
+ check(
+ result.activeIdentity ==
+ dataset.currentDownloadIdentity
+ ) {
+ "Downloaded knowledge pack failed current revision validation"
+ }
+ result
+ }
+ } catch (error: Throwable) {
+ withContext(NonCancellable) {
+ indexGate.withLock {
+ runCatching { reconcileAndOpenLocked(dataset) }
+ }
+ }
+ throw error
+ }
}
- }
- throw error
+ ActiveMutation(task).also { mutations[dataset.stableId] = it }
}
- }
- ActiveMutation(task).also {
- mutations[dataset.stableId] = it
- }
}
}
- }
try {
mutation.task.await()
@@ -130,24 +132,26 @@ class KnowledgeProvider(
suspend fun search(
datasets: List<KnowledgeDatasetConfig>,
query: List<Float>,
- maxHits: UInt
- ): List<KnowledgePromptHit> = withContext(Dispatchers.IO) {
- indexGate.withLock {
- val merged = mutableListOf<KnowledgePromptHit>()
- for (dataset in datasets) {
- currentCoroutineContext().ensureActive()
- val open = indexes[dataset.stableId] ?: continue
- val hits = try {
- open.index.search(query, maxHits, dataset.relevanceThreshold)
- } catch (_: Throwable) {
- continue
+ maxHits: UInt,
+ ): List<KnowledgePromptHit> =
+ withContext(Dispatchers.IO) {
+ indexGate.withLock {
+ val merged = mutableListOf<KnowledgePromptHit>()
+ for (dataset in datasets) {
+ currentCoroutineContext().ensureActive()
+ val open = indexes[dataset.stableId] ?: continue
+ val hits =
+ try {
+ open.index.search(query, maxHits, dataset.relevanceThreshold)
+ } catch (_: Throwable) {
+ continue
+ }
+ currentCoroutineContext().ensureActive()
+ merged += hits.map { hit -> KnowledgePromptHit(dataset.stableId, hit) }
}
- currentCoroutineContext().ensureActive()
- merged += hits.map { hit -> KnowledgePromptHit(dataset.stableId, hit) }
+ merged.sortedByDescending { it.hit.score }.take(maxHits.toInt())
}
- merged.sortedByDescending { it.hit.score }.take(maxHits.toInt())
}
- }
private fun reconcileAndOpenLocked(dataset: KnowledgeDatasetConfig): KnowledgeReconciliation {
val previous = indexes[dataset.stableId]
@@ -162,18 +166,17 @@ class KnowledgeProvider(
previous?.index?.destroy()
}
result.activeIdentity?.let { activeIdentity ->
- runCatching {
- assetStore.cleanupKnowledgeRevisions(dataset.stableId, activeIdentity)
- }
+ runCatching { assetStore.cleanupKnowledgeRevisions(dataset.stableId, activeIdentity) }
}
return result
}
- private suspend fun lifecycleGate(stableId: String): Mutex =
- mutationGate.withLock { lifecycleGates.getOrPut(stableId) { Mutex() } }
+ private suspend fun lifecycleGate(stableId: String): Mutex = mutationGate.withLock {
+ lifecycleGates.getOrPut(stableId) { Mutex() }
+ }
}
data class KnowledgeDownloadProgress(
val label: String,
- val percentage: Double
+ val percentage: Double,
)
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt
index 92e3a78d38..5861b11e21 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt
@@ -31,22 +31,22 @@ data class KnowledgePackState(
val activeIdentity: String? = null,
val enabled: Boolean = false,
val mutationProgress: KnowledgeDownloadProgress? = null,
- val errorMessage: String? = null
+ val errorMessage: String? = null,
) {
- val isMutating: Boolean get() = mutationProgress != null
+ val isMutating: Boolean
+ get() = mutationProgress != null
}
-data class KnowledgeState(
- val packs: Map<String, KnowledgePackState> = emptyMap()
-) {
+data class KnowledgeState(val packs: Map<String, KnowledgePackState> = emptyMap()) {
val enabledReadyDatasets: List<KnowledgeDatasetConfig>
- get() = packs.values
- .filter { pack ->
- pack.enabled &&
- (pack.status == KnowledgeReconciliationStatus.READY ||
- pack.status == KnowledgeReconciliationStatus.UPDATE_AVAILABLE)
- }
- .map { it.config }
+ get() =
+ packs.values
+ .filter { pack ->
+ pack.enabled &&
+ (pack.status == KnowledgeReconciliationStatus.READY ||
+ pack.status == KnowledgeReconciliationStatus.UPDATE_AVAILABLE)
+ }
+ .map { it.config }
}
class KnowledgeStore(
@@ -54,7 +54,7 @@ class KnowledgeStore(
private val state: MutableStateFlow<AppState>,
private val provider: KnowledgeProvider,
datasets: List<KnowledgeDatasetConfig>,
- private val logRepository: FileLogRepository
+ private val logRepository: FileLogRepository,
) {
private val preferences = KnowledgePreferences(context)
private val catalog = datasets.associateBy { it.stableId }
@@ -68,28 +68,24 @@ class KnowledgeStore(
if (bootstrapJob != null) return
state.update { appState ->
appState.copy(
- knowledge = KnowledgeState(
- packs = catalog.mapValues { (_, config) -> KnowledgePackState(config) }
- )
+ knowledge =
+ KnowledgeState(
+ packs = catalog.mapValues { (_, config) -> KnowledgePackState(config) }
+ )
)
}
bootstrapJob = scope.launch {
val requestedEnabled = runCatching {
preferences.enabledDatasetIds.first()
- }.getOrDefault(emptySet())
- val (enabled, disabled) = catalog.values.partition {
- it.stableId in requestedEnabled
}
+ .getOrDefault(emptySet())
+ val (enabled, disabled) = catalog.values.partition { it.stableId in requestedEnabled }
try {
- enabled.forEach { dataset ->
- reconcileAndUpdate(dataset, enabled = true)
- }
+ enabled.forEach { dataset -> reconcileAndUpdate(dataset, enabled = true) }
} finally {
enabledPacksReady.complete(Unit)
}
- disabled.forEach { dataset ->
- reconcileAndUpdate(dataset, enabled = false)
- }
+ disabled.forEach { dataset -> reconcileAndUpdate(dataset, enabled = false) }
}
}
@@ -106,48 +102,47 @@ class KnowledgeStore(
updatePack(stableId) {
it.copy(
mutationProgress = KnowledgeDownloadProgress("Starting download...", 0.0),
- errorMessage = null
+ errorMessage = null,
)
}
jobs[stableId] = ownerScope.launch {
try {
- val reconciliation = provider.download(dataset) { progress ->
- updatePack(stableId) { current ->
- current.copy(mutationProgress = progress)
+ val reconciliation =
+ provider.download(dataset) { progress ->
+ updatePack(stableId) { current ->
+ current.copy(mutationProgress = progress)
+ }
}
- }
- val shouldEnable = !wasInstalled &&
- reconciliation.status == KnowledgeReconciliationStatus.READY
+ val shouldEnable =
+ !wasInstalled && reconciliation.status == KnowledgeReconciliationStatus.READY
if (shouldEnable) {
preferences.setDatasetEnabled(stableId, true)
}
- val enabled = if (wasInstalled) {
- state.value.knowledge.packs[stableId]?.enabled == true
- } else {
- shouldEnable
- }
+ val enabled =
+ if (wasInstalled) {
+ state.value.knowledge.packs[stableId]?.enabled == true
+ } else {
+ shouldEnable
+ }
updatePack(stableId) {
- it.fromReconciliation(reconciliation, enabled).copy(
- mutationProgress = null
- )
+ it.fromReconciliation(reconciliation, enabled).copy(mutationProgress = null)
}
} catch (error: CancellationException) {
throw error
} catch (error: Throwable) {
val reconciled = runCatching { provider.reconcile(dataset) }.getOrNull()
updatePack(stableId) { current ->
- (reconciled?.let {
- current.fromReconciliation(it, current.enabled)
- } ?: current).copy(
- mutationProgress = null,
- errorMessage = userFacingKnowledgeError(error)
- )
+ (reconciled?.let { current.fromReconciliation(it, current.enabled) } ?: current)
+ .copy(
+ mutationProgress = null,
+ errorMessage = userFacingKnowledgeError(error),
+ )
}
logRepository.log(
LogLevel.Error,
"Knowledge pack setup failed",
details = "pack=$stableId error=${error.message}",
- tag = "Knowledge"
+ tag = "Knowledge",
)
} finally {
jobs.remove(stableId)
@@ -176,28 +171,27 @@ class KnowledgeStore(
if (pack.activeIdentity == null || pack.isMutating) return
val ownerScope = scope ?: return
updatePack(stableId) { it.copy(enabled = enabled) }
- ownerScope.launch {
- preferences.setDatasetEnabled(stableId, enabled)
- }
+ ownerScope.launch { preferences.setDatasetEnabled(stableId, enabled) }
}
private fun updatePack(
stableId: String,
- transform: (KnowledgePackState) -> KnowledgePackState
+ transform: (KnowledgePackState) -> KnowledgePackState,
) {
state.update { appState ->
val current = appState.knowledge.packs[stableId] ?: return@update appState
appState.copy(
- knowledge = appState.knowledge.copy(
- packs = appState.knowledge.packs + (stableId to transform(current))
- )
+ knowledge =
+ appState.knowledge.copy(
+ packs = appState.knowledge.packs + (stableId to transform(current))
+ )
)
}
}
private suspend fun reconcileAndUpdate(
dataset: KnowledgeDatasetConfig,
- enabled: Boolean
+ enabled: Boolean,
) {
val result = runCatching { provider.reconcile(dataset) }
updatePack(dataset.stableId) { current ->
@@ -209,22 +203,23 @@ class KnowledgeStore(
current.copy(
status = KnowledgeReconciliationStatus.DOWNLOAD,
enabled = false,
- errorMessage = userFacingKnowledgeError(error)
+ errorMessage = userFacingKnowledgeError(error),
)
- }
+ },
)
}
}
private fun KnowledgePackState.fromReconciliation(
result: KnowledgeReconciliation,
- enabled: Boolean
- ): KnowledgePackState = copy(
- status = result.status,
- activeIdentity = result.activeIdentity,
- enabled = enabled && result.activeIdentity != null,
- errorMessage = null
- )
+ enabled: Boolean,
+ ): KnowledgePackState =
+ copy(
+ status = result.status,
+ activeIdentity = result.activeIdentity,
+ enabled = enabled && result.activeIdentity != null,
+ errorMessage = null,
+ )
private fun userFacingKnowledgeError(error: Throwable): String {
return when (error) {
@@ -238,8 +233,7 @@ class KnowledgeStore(
is AssetDownloadException.Validation,
is AssetDownloadException.InvalidDownload ->
"The knowledge pack couldn't be verified. Please try again."
- is AssetDownloadException.Io ->
- "Couldn't save the knowledge pack. Please try again."
+ is AssetDownloadException.Io -> "Couldn't save the knowledge pack. Please try again."
else -> "Knowledge pack setup failed. Please try again."
}
}
@@ -248,9 +242,8 @@ class KnowledgeStore(
private class KnowledgePreferences(context: Context) {
private val preferences = context.applicationContext.knowledgePreferences
- val enabledDatasetIds: Flow<Set<String>> = preferences.data.map { values ->
- values[Keys.enabledDatasetIds].orEmpty()
- }
+ val enabledDatasetIds: Flow<Set<String>> =
+ preferences.data.map { values -> values[Keys.enabledDatasetIds].orEmpty() }
suspend fun setDatasetEnabled(stableId: String, enabled: Boolean) {
preferences.edit { values ->
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/DownloadProgressTracker.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/DownloadProgressTracker.kt
index 2f4342b742..b3efcbfb59 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/DownloadProgressTracker.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/DownloadProgressTracker.kt
@@ -1,18 +1,16 @@
package io.ente.ensu.llm
-import io.ente.ensu.llm.DownloadProgress
-
internal data class ResolvedDownloadProgress(
val percent: Int?,
val status: String,
val phase: DownloadPhase,
val isDownloading: Boolean,
- val isFinished: Boolean
+ val isFinished: Boolean,
)
internal class DownloadProgressTracker(
initialPercent: Int? = 0,
- initialStatus: String? = "Starting download..."
+ initialStatus: String? = "Starting download...",
) {
private var lastVisiblePercent: Int? = initialPercent
private var lastVisibleStatus: String? = initialStatus
@@ -24,21 +22,22 @@ internal class DownloadProgressTracker(
val previousPercent = lastVisiblePercent
val previousStatus = lastVisibleStatus
- val resolvedPercent = when {
- isFinished -> 100
- rawPercent == null -> previousPercent
- previousPercent == null -> rawPercent
- rawPercent >= previousPercent -> rawPercent
- else -> previousPercent
- }
- val regressed = rawPercent != null &&
- previousPercent != null &&
- rawPercent < previousPercent
- val resolvedStatus = when {
- isFinished || isLoading -> progress.status
- regressed -> previousStatus ?: progress.status
- else -> progress.status
- }
+ val resolvedPercent =
+ when {
+ isFinished -> 100
+ rawPercent == null -> previousPercent
+ previousPercent == null -> rawPercent
+ rawPercent >= previousPercent -> rawPercent
+ else -> previousPercent
+ }
+ val regressed =
+ rawPercent != null && previousPercent != null && rawPercent < previousPercent
+ val resolvedStatus =
+ when {
+ isFinished || isLoading -> progress.status
+ regressed -> previousStatus ?: progress.status
+ else -> progress.status
+ }
if (!isFinished) {
lastVisiblePercent = resolvedPercent
@@ -50,7 +49,7 @@ internal class DownloadProgressTracker(
status = resolvedStatus,
phase = progress.phase,
isDownloading = progress.phase != DownloadPhase.Failed && !isFinished,
- isFinished = isFinished
+ isFinished = isFinished,
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmModels.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmModels.kt
index ed478e9941..e6cae66950 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmModels.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmModels.kt
@@ -3,36 +3,36 @@ package io.ente.ensu.llm
data class LlmModelSelection(
val id: String,
val contextLength: Int? = null,
- val maxTokens: Int? = null
+ val maxTokens: Int? = null,
)
data class DownloadProgress(
val percent: Int?,
val status: String,
- val phase: DownloadPhase = DownloadPhase.Downloading
+ val phase: DownloadPhase = DownloadPhase.Downloading,
)
enum class DownloadPhase {
Downloading,
Loading,
Ready,
- Failed
+ Failed,
}
enum class LlmMessageRole {
User,
Assistant,
- System
+ System,
}
data class LlmMessage(
val text: String,
val role: LlmMessageRole,
- val hasAttachments: Boolean = false
+ val hasAttachments: Boolean = false,
)
data class GenerationSummary(
val jobId: Long,
val generatedTokens: Int,
- val totalTimeMs: Long?
+ val totalTimeMs: Long?,
)
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt
index 5e90fda840..e28803e8df 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/LlmProvider.kt
@@ -3,6 +3,7 @@ package io.ente.ensu.llm
import android.util.Log
import io.ente.ensu.assets.AssetStore
import io.ente.ensu.bindings.Asset
+import io.ente.ensu.bindings.KnowledgeEmbeddingConfig
import io.ente.ensu.bindings.LlmChatMessage as NativeChatMessage
import io.ente.ensu.bindings.LlmChatRequest
import io.ente.ensu.bindings.LlmContext
@@ -12,7 +13,6 @@ import io.ente.ensu.bindings.LlmGenerationEventCallback
import io.ente.ensu.bindings.LlmGenerationSummary as NativeSummary
import io.ente.ensu.bindings.LlmModel
import io.ente.ensu.bindings.LlmModelLoadParams
-import io.ente.ensu.bindings.KnowledgeEmbeddingConfig
import io.ente.ensu.bindings.Transcriber
import io.ente.ensu.bindings.knowledgeEmbeddingModelAsset
import io.ente.ensu.bindings.llmAsset
@@ -29,20 +29,19 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
-class RequiredModelValidationError(
- val modelId: String
-) : Exception("Downloaded model failed validation: $modelId")
+class RequiredModelValidationError(val modelId: String) :
+ Exception("Downloaded model failed validation: $modelId")
class LlmProvider(
private val assetStore: AssetStore,
private val transcriber: Transcriber,
private val deviceCapabilityProvider: AndroidDeviceCapabilityProvider,
private val knowledgeEmbedding: KnowledgeEmbeddingConfig,
- private val ioDispatcher: kotlinx.coroutines.CoroutineDispatcher = Dispatchers.IO
+ private val ioDispatcher: kotlinx.coroutines.CoroutineDispatcher = Dispatchers.IO,
) {
private data class LoadedModelKey(
val id: String,
- val requestedContextLength: Int?
+ val requestedContextLength: Int?,
)
@Volatile private var loadedModel: LlmModel? = null
@@ -56,17 +55,17 @@ class LlmProvider(
private val embeddingAsset = knowledgeEmbeddingModelAsset()
internal var modelMaintenance: ModelMaintenance? = null
- private suspend fun <T> withModelContext(block: suspend () -> T): T = modelMaintenance.withMaintenanceSuspended {
- withContext(ioDispatcher) { block() }
- }
+ private suspend fun <T> withModelContext(block: suspend () -> T): T =
+ modelMaintenance.withMaintenanceSuspended {
+ withContext(ioDispatcher) { block() }
+ }
class EmbeddingAssetInvalid : Exception("Embedding model asset is invalid")
fun isChatModelReady(selection: LlmModelSelection): Boolean =
assetStore.isDownloaded(chatAsset(selection))
- fun isEmbeddingModelReady(): Boolean =
- assetStore.isDownloaded(embeddingAsset)
+ fun isEmbeddingModelReady(): Boolean = assetStore.isDownloaded(embeddingAsset)
suspend fun estimateEmbeddingDownloadSize(): Long? =
assetStore.estimateDownloadSize(embeddingAsset)
@@ -79,18 +78,16 @@ class LlmProvider(
suspend fun ensureModelReady(
selection: LlmModelSelection,
- onProgress: (DownloadProgress) -> Unit
+ onProgress: (DownloadProgress) -> Unit,
) {
withModelContext {
- modelLoadMutex.withLock {
- ensureModelReadyLocked(selection, onProgress)
- }
+ modelLoadMutex.withLock { ensureModelReadyLocked(selection, onProgress) }
}
}
suspend fun ensureRequiredModelsReady(
selection: LlmModelSelection,
- onProgress: (DownloadProgress) -> Unit
+ onProgress: (DownloadProgress) -> Unit,
) {
withModelContext {
deviceCapabilityProvider.chatCapability().requireChatSupported()
@@ -124,7 +121,7 @@ class LlmProvider(
selection,
onProgress,
allowRecovery = false,
- shouldDownload = false
+ shouldDownload = false,
)
}
}
@@ -136,39 +133,40 @@ class LlmProvider(
imageFiles: List<File>,
temperature: Float,
maxTokens: Int?,
- onToken: (String) -> Unit
+ onToken: (String) -> Unit,
): GenerationSummary = withModelContext {
modelLoadMutex.withLock {
deviceCapabilityProvider.chatCapability().requireChatSupported()
val context = loadedContext ?: throw IllegalStateException("Model context not loaded")
currentJobId = null
- val mmprojPath = if (imageFiles.isEmpty()) {
- null
- } else {
- assetStore.llmMmprojPath(chatAsset(selection))?.absolutePath
- }
+ val mmprojPath =
+ if (imageFiles.isEmpty()) {
+ null
+ } else {
+ assetStore.llmMmprojPath(chatAsset(selection))?.absolutePath
+ }
val clampedTemperature = temperature.coerceIn(0.35f, 0.7f)
- val request = LlmChatRequest(
- messages = messages.map { msg ->
- NativeChatMessage(msg.roleString(), msg.text)
- },
- templateOverride = null,
- addAssistant = true,
- imagePaths = imageFiles.map { it.absolutePath },
- mmprojPath = mmprojPath,
- mediaMarker = null,
- maxTokens = maxTokens,
- temperature = clampedTemperature,
- topP = 0.9f,
- topK = 50,
- repeatPenalty = 1.18f,
- frequencyPenalty = 0f,
- presencePenalty = 0f,
- seed = null,
- stopSequences = null,
- grammar = null
- )
+ val request =
+ LlmChatRequest(
+ messages =
+ messages.map { msg -> NativeChatMessage(msg.roleString(), msg.text) },
+ templateOverride = null,
+ addAssistant = true,
+ imagePaths = imageFiles.map { it.absolutePath },
+ mmprojPath = mmprojPath,
+ mediaMarker = null,
+ maxTokens = maxTokens,
+ temperature = clampedTemperature,
+ topP = 0.9f,
+ topK = 50,
+ repeatPenalty = 1.18f,
+ frequencyPenalty = 0f,
+ presencePenalty = 0f,
+ seed = null,
+ stopSequences = null,
+ grammar = null,
+ )
unloadTranscriptionModelIfLoaded()
val summary = generateStreamWithCallback(context, request, onToken)
@@ -178,44 +176,46 @@ class LlmProvider(
suspend fun <T> withChatModelReleasedForRetrieval(
block: suspend (embed: (String) -> List<Float>) -> T
- ): T = withModelContext {
- withEmbeddingContext { embedding -> block(embedding::embed) }
- }
+ ): T = withModelContext { withEmbeddingContext { embedding -> block(embedding::embed) } }
internal suspend fun <T> withEmbeddingContext(
checkCancellation: () -> Unit = {},
- block: suspend (LlmContext) -> T
- ): T = withContext(ioDispatcher) {
- modelLoadMutex.withLock {
- checkCancellation()
- deviceCapabilityProvider.chatCapability().requireChatSupported()
- if (!isEmbeddingModelReady()) throw EmbeddingAssetInvalid()
- unloadTranscriptionModelIfLoaded()
- unloadModel()
- if (!backendInitialized) {
- llmInitBackend()
- backendInitialized = true
- }
+ block: suspend (LlmContext) -> T,
+ ): T =
+ withContext(ioDispatcher) {
+ modelLoadMutex.withLock {
+ checkCancellation()
+ deviceCapabilityProvider.chatCapability().requireChatSupported()
+ if (!isEmbeddingModelReady()) throw EmbeddingAssetInvalid()
+ unloadTranscriptionModelIfLoaded()
+ unloadModel()
+ if (!backendInitialized) {
+ llmInitBackend()
+ backendInitialized = true
+ }
- val embeddingModel = LlmModel.load(
- LlmModelLoadParams(
- modelPath = requireNotNull(assetStore.llmModelPath(embeddingAsset)).absolutePath,
- nGpuLayers = 0,
- useMmap = true,
- useMlock = false
- )
- )
- var embeddingContext: LlmContext? = null
- try {
- val threads = max(1, Runtime.getRuntime().availableProcessors() - 1)
- embeddingContext = embeddingModel.newEmbeddingContext(threads)
- block(embeddingContext)
- } finally {
- embeddingContext?.destroy()
- embeddingModel.destroy()
+ val embeddingModel =
+ LlmModel.load(
+ LlmModelLoadParams(
+ modelPath =
+ requireNotNull(assetStore.llmModelPath(embeddingAsset))
+ .absolutePath,
+ nGpuLayers = 0,
+ useMmap = true,
+ useMlock = false,
+ )
+ )
+ var embeddingContext: LlmContext? = null
+ try {
+ val threads = max(1, Runtime.getRuntime().availableProcessors() - 1)
+ embeddingContext = embeddingModel.newEmbeddingContext(threads)
+ block(embeddingContext)
+ } finally {
+ embeddingContext?.destroy()
+ embeddingModel.destroy()
+ }
}
}
- }
suspend fun prewarmImageInference(selection: LlmModelSelection) {
withModelContext {
@@ -224,17 +224,17 @@ class LlmProvider(
val asset = chatAsset(selection)
if (!assetStore.isDownloaded(asset)) return@withLock
val mmprojPath =
- assetStore.llmMmprojPath(asset)?.absolutePath
- ?.takeIf { File(it).exists() }
- ?: return@withLock
+ assetStore.llmMmprojPath(asset)?.absolutePath?.takeIf { File(it).exists() }
+ ?: return@withLock
ensureModelReadyLocked(selection, onProgress = {})
val context = loadedContext ?: return@withLock
unloadTranscriptionModelIfLoaded()
context.prewarmMultimodal(mmprojPath, null)
}
- }.onFailure { error ->
- Log.d("LlmProvider", "Image inference prewarm skipped", error)
}
+ .onFailure { error ->
+ Log.d("LlmProvider", "Image inference prewarm skipped", error)
+ }
}
}
@@ -260,11 +260,12 @@ class LlmProvider(
withModelContext {
modelLoadMutex.withLock {
val model = loadedModel ?: return@withLock
- val contextParams = LlmContextParams(
- contextSize = currentContextLength,
- nThreads = null,
- nBatch = null
- )
+ val contextParams =
+ LlmContextParams(
+ contextSize = currentContextLength,
+ nThreads = null,
+ nBatch = null,
+ )
loadedContext?.destroy()
loadedContext = model.newContext(contextParams)
}
@@ -291,16 +292,17 @@ class LlmProvider(
private fun unloadTranscriptionModelIfLoaded() {
runCatching {
transcriber.unloadModel()
- }.onFailure { error ->
- Log.d("LlmProvider", "Transcription model unload skipped", error)
}
+ .onFailure { error ->
+ Log.d("LlmProvider", "Transcription model unload skipped", error)
+ }
}
private suspend fun ensureModelReadyLocked(
selection: LlmModelSelection,
onProgress: (DownloadProgress) -> Unit,
allowRecovery: Boolean = true,
- shouldDownload: Boolean = true
+ shouldDownload: Boolean = true,
) {
deviceCapabilityProvider.chatCapability().requireChatSupported()
val modelKey = LoadedModelKey(selection.id, selection.contextLength)
@@ -325,11 +327,13 @@ class LlmProvider(
try {
loadWithFallbacks(
selection,
- requireNotNull(assetStore.llmModelPath(asset))
+ requireNotNull(assetStore.llmModelPath(asset)),
)
} catch (error: Throwable) {
if (allowRecovery && wasAlreadyDownloaded && assetStore.removeDownloaded(asset)) {
- onProgress(DownloadProgress(0, "Starting download...", phase = DownloadPhase.Downloading))
+ onProgress(
+ DownloadProgress(0, "Starting download...", phase = DownloadPhase.Downloading)
+ )
ensureModelReadyLocked(selection, onProgress, allowRecovery = false)
return
}
@@ -340,7 +344,7 @@ class LlmProvider(
private suspend fun downloadAssets(
assets: List<Asset>,
- onProgress: (DownloadProgress) -> Unit
+ onProgress: (DownloadProgress) -> Unit,
) {
activeDownloads.incrementAndGet()
try {
@@ -348,7 +352,7 @@ class LlmProvider(
onProgress(
DownloadProgress(
progress.percentage.toInt().coerceIn(0, 99),
- progress.status
+ progress.status,
)
)
}
@@ -361,16 +365,18 @@ class LlmProvider(
private fun loadWithFallbacks(selection: LlmModelSelection, modelFile: File) {
val desiredCtx = selection.contextLength ?: 12000
- val contexts = listOf(desiredCtx, 12000, 8192, 4096, 2048, 1024).distinct().filter { it > 0 }
+ val contexts =
+ listOf(desiredCtx, 12000, 8192, 4096, 2048, 1024).distinct().filter { it > 0 }
val threads = max(1, Runtime.getRuntime().availableProcessors() - 1)
val batch = 512
- val modelParams = LlmModelLoadParams(
- modelPath = modelFile.absolutePath,
- nGpuLayers = 0,
- useMmap = true,
- useMlock = false
- )
+ val modelParams =
+ LlmModelLoadParams(
+ modelPath = modelFile.absolutePath,
+ nGpuLayers = 0,
+ useMmap = true,
+ useMlock = false,
+ )
val model = LlmModel.load(modelParams)
loadedModel = model
@@ -378,11 +384,12 @@ class LlmProvider(
var lastError: Throwable? = null
for (ctx in contexts) {
try {
- val contextParams = LlmContextParams(
- contextSize = ctx,
- nThreads = threads,
- nBatch = batch
- )
+ val contextParams =
+ LlmContextParams(
+ contextSize = ctx,
+ nThreads = threads,
+ nBatch = batch,
+ )
loadedContext = model.newContext(contextParams)
currentModelKey = LoadedModelKey(selection.id, selection.contextLength)
currentContextLength = ctx
@@ -398,23 +405,24 @@ class LlmProvider(
private fun generateStreamWithCallback(
context: LlmContext,
request: LlmChatRequest,
- onToken: (String) -> Unit
+ onToken: (String) -> Unit,
): NativeSummary {
- val callback = object : LlmGenerationEventCallback {
- override fun onEvent(event: LlmGenerationEvent) {
- when (event) {
- is LlmGenerationEvent.Text -> {
- currentJobId = event.jobId
- if (event.text.isNotEmpty()) {
- onToken(event.text)
+ val callback =
+ object : LlmGenerationEventCallback {
+ override fun onEvent(event: LlmGenerationEvent) {
+ when (event) {
+ is LlmGenerationEvent.Text -> {
+ currentJobId = event.jobId
+ if (event.text.isNotEmpty()) {
+ onToken(event.text)
+ }
+ }
+ is LlmGenerationEvent.Done -> {
+ currentJobId = null
}
- }
- is LlmGenerationEvent.Done -> {
- currentJobId = null
}
}
}
- }
try {
return context.generateChatStream(request, callback)
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelMaintenance.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelMaintenance.kt
index c1030d750a..2d0bfd993d 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelMaintenance.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelMaintenance.kt
@@ -2,7 +2,9 @@ package io.ente.ensu.llm
interface ModelMaintenance {
fun suspendMaintenance(): AutoCloseable
+
suspend fun awaitMaintenance()
+
fun modelReadinessChanged()
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt
index 598fb40920..d387ed5a2e 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsActions.kt
@@ -23,7 +23,7 @@ internal class ModelSettingsActions(
private val state: MutableStateFlow<AppState>,
private val sessionPreferences: SessionPreferencesDataStore,
private val llmProvider: LlmProvider,
- private val logRepository: FileLogRepository
+ private val logRepository: FileLogRepository,
) {
private var scope: CoroutineScope? = null
private var modelDownloadJob: Job? = null
@@ -35,9 +35,7 @@ internal class ModelSettingsActions(
fun updateModelSettings(settings: ModelSettingsState) {
val oldSelection = resolveSelection(state.value.modelSettings)
val newSelection = resolveSelection(settings)
- state.update { appState ->
- appState.copy(modelSettings = settings)
- }
+ state.update { appState -> appState.copy(modelSettings = settings) }
if (downloadIdentityChanged(oldSelection, newSelection)) {
modelDownloadJob?.cancel()
modelDownloadJob = null
@@ -46,16 +44,12 @@ internal class ModelSettingsActions(
}
fun hydratePersistedModelSettings(settings: ModelSettingsState) {
- state.update { appState ->
- appState.copy(modelSettings = settings)
- }
+ state.update { appState -> appState.copy(modelSettings = settings) }
refreshModelDownloadInfo()
}
fun resetModelSettings() {
- state.update { appState ->
- appState.copy(modelSettings = ModelSettingsState())
- }
+ state.update { appState -> appState.copy(modelSettings = ModelSettingsState()) }
refreshModelDownloadInfo()
}
@@ -66,14 +60,15 @@ internal class ModelSettingsActions(
persistModelDownloadRequested(false)
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isDownloading = false,
- downloadPercent = null,
- downloadStatus = null,
- downloadPhase = null,
- modelDownloadSizeBytes = null,
- hasRequestedModelDownload = false
- )
+ chat =
+ appState.chat.copy(
+ isDownloading = false,
+ downloadPercent = null,
+ downloadStatus = null,
+ downloadPhase = null,
+ modelDownloadSizeBytes = null,
+ hasRequestedModelDownload = false,
+ )
)
}
return
@@ -87,15 +82,18 @@ internal class ModelSettingsActions(
}
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isModelDownloaded = isDownloaded,
- isDownloading = if (isDownloaded) false else appState.chat.isDownloading,
- downloadPercent = if (isDownloaded) null else appState.chat.downloadPercent,
- downloadStatus = if (isDownloaded) null else appState.chat.downloadStatus,
- downloadPhase = if (isDownloaded) null else appState.chat.downloadPhase,
- modelDownloadSizeBytes = if (isDownloaded) null else appState.chat.modelDownloadSizeBytes,
- hasRequestedModelDownload = appState.chat.hasRequestedModelDownload || isDownloaded
- )
+ chat =
+ appState.chat.copy(
+ isModelDownloaded = isDownloaded,
+ isDownloading = if (isDownloaded) false else appState.chat.isDownloading,
+ downloadPercent = if (isDownloaded) null else appState.chat.downloadPercent,
+ downloadStatus = if (isDownloaded) null else appState.chat.downloadStatus,
+ downloadPhase = if (isDownloaded) null else appState.chat.downloadPhase,
+ modelDownloadSizeBytes =
+ if (isDownloaded) null else appState.chat.modelDownloadSizeBytes,
+ hasRequestedModelDownload =
+ appState.chat.hasRequestedModelDownload || isDownloaded,
+ )
)
}
@@ -107,33 +105,38 @@ internal class ModelSettingsActions(
persistModelDownloadRequested(false)
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isDownloading = false,
- downloadPercent = null,
- downloadStatus = null,
- downloadPhase = null,
- hasRequestedModelDownload = false
- )
+ chat =
+ appState.chat.copy(
+ isDownloading = false,
+ downloadPercent = null,
+ downloadStatus = null,
+ downloadPhase = null,
+ hasRequestedModelDownload = false,
+ )
)
}
}
- val chatSize = if (chatReady) 0L else llmProvider.estimateChatModelDownloadSize(selection)
- val embeddingSize = if (!IS_ENSU_PACKS_ENABLED || embeddingReady) {
- 0L
- } else {
- llmProvider.estimateEmbeddingDownloadSize()
- }
- val size = if (chatSize == null || embeddingSize == null) {
- null
- } else {
- chatSize + embeddingSize
- }
+ val chatSize =
+ if (chatReady) 0L else llmProvider.estimateChatModelDownloadSize(selection)
+ val embeddingSize =
+ if (!IS_ENSU_PACKS_ENABLED || embeddingReady) {
+ 0L
+ } else {
+ llmProvider.estimateEmbeddingDownloadSize()
+ }
+ val size =
+ if (chatSize == null || embeddingSize == null) {
+ null
+ } else {
+ chatSize + embeddingSize
+ }
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- modelDownloadSizeBytes = size ?: appState.chat.modelDownloadSizeBytes
- )
+ chat =
+ appState.chat.copy(
+ modelDownloadSizeBytes = size ?: appState.chat.modelDownloadSizeBytes
+ )
)
}
}
@@ -148,16 +151,20 @@ internal class ModelSettingsActions(
if (!userInitiated && !currentState.chat.hasRequestedModelDownload) return
val selection = resolveSelection(currentState.modelSettings)
- val isDownloaded = llmProvider.isChatModelReady(selection) &&
- (!IS_ENSU_PACKS_ENABLED || llmProvider.isEmbeddingModelReady())
+ val isDownloaded =
+ llmProvider.isChatModelReady(selection) &&
+ (!IS_ENSU_PACKS_ENABLED || llmProvider.isEmbeddingModelReady())
if (isDownloaded) {
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isModelDownloaded = true,
- modelDownloadSizeBytes = null,
- hasRequestedModelDownload = if (userInitiated) true else appState.chat.hasRequestedModelDownload
- )
+ chat =
+ appState.chat.copy(
+ isModelDownloaded = true,
+ modelDownloadSizeBytes = null,
+ hasRequestedModelDownload =
+ if (userInitiated) true
+ else appState.chat.hasRequestedModelDownload,
+ )
)
}
}
@@ -169,27 +176,31 @@ internal class ModelSettingsActions(
LogLevel.Info,
"Model download started",
details = "model=${selection.id}",
- tag = "Model"
+ tag = "Model",
)
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isDownloading = true,
- downloadPercent = 0,
- downloadStatus = "Starting download...",
- downloadPhase = DownloadPhase.Downloading,
- hasRequestedModelDownload = if (userInitiated) true else appState.chat.hasRequestedModelDownload
- )
+ chat =
+ appState.chat.copy(
+ isDownloading = true,
+ downloadPercent = 0,
+ downloadStatus = "Starting download...",
+ downloadPhase = DownloadPhase.Downloading,
+ hasRequestedModelDownload =
+ if (userInitiated) true
+ else appState.chat.hasRequestedModelDownload,
+ )
)
}
}
modelDownloadJob = scope.launch {
var loggedComplete = false
- val progressTracker = DownloadProgressTracker(
- initialPercent = if (isDownloaded) null else 0,
- initialStatus = if (isDownloaded) null else "Starting download..."
- )
+ val progressTracker =
+ DownloadProgressTracker(
+ initialPercent = if (isDownloaded) null else 0,
+ initialStatus = if (isDownloaded) null else "Starting download...",
+ )
try {
var retryCount = 0
while (true) {
@@ -202,19 +213,24 @@ internal class ModelSettingsActions(
LogLevel.Info,
"Model download complete",
details = "model=${selection.id}",
- tag = "Model"
+ tag = "Model",
)
}
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isDownloading = resolvedProgress.isDownloading,
- downloadPercent = resolvedProgress.percent,
- downloadStatus = resolvedProgress.status,
- downloadPhase = resolvedProgress.phase,
- isModelDownloaded = if (resolvedProgress.isFinished) true else appState.chat.isModelDownloaded,
- modelDownloadSizeBytes = if (resolvedProgress.isFinished) null else appState.chat.modelDownloadSizeBytes
- )
+ chat =
+ appState.chat.copy(
+ isDownloading = resolvedProgress.isDownloading,
+ downloadPercent = resolvedProgress.percent,
+ downloadStatus = resolvedProgress.status,
+ downloadPhase = resolvedProgress.phase,
+ isModelDownloaded =
+ if (resolvedProgress.isFinished) true
+ else appState.chat.isModelDownloaded,
+ modelDownloadSizeBytes =
+ if (resolvedProgress.isFinished) null
+ else appState.chat.modelDownloadSizeBytes,
+ )
)
}
}
@@ -229,23 +245,26 @@ internal class ModelSettingsActions(
}
}
} catch (err: Throwable) {
- val cancelled = err is kotlinx.coroutines.CancellationException ||
- err is LlmException.Cancelled ||
- err is AssetDownloadException.Cancelled
- val failureMessage = if (cancelled) {
- "Download cancelled"
- } else {
- userFacingDownloadError(err, isDownloaded)
- }
+ val cancelled =
+ err is kotlinx.coroutines.CancellationException ||
+ err is LlmException.Cancelled ||
+ err is AssetDownloadException.Cancelled
+ val failureMessage =
+ if (cancelled) {
+ "Download cancelled"
+ } else {
+ userFacingDownloadError(err, isDownloaded)
+ }
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isDownloading = false,
- downloadPercent = null,
- downloadStatus = failureMessage,
- downloadPhase = if (cancelled) null else DownloadPhase.Failed,
- hasRequestedModelDownload = false
- )
+ chat =
+ appState.chat.copy(
+ isDownloading = false,
+ downloadPercent = null,
+ downloadStatus = failureMessage,
+ downloadPhase = if (cancelled) null else DownloadPhase.Failed,
+ hasRequestedModelDownload = false,
+ )
)
}
persistModelDownloadRequested(false)
@@ -259,7 +278,7 @@ internal class ModelSettingsActions(
if (isDownloaded) "Model load failed" else "Model download failed",
details = err.message,
tag = "Model",
- throwable = err
+ throwable = err,
)
}
} finally {
@@ -286,7 +305,7 @@ internal class ModelSettingsActions(
LogLevel.Warning,
"Image inference prewarm skipped",
details = err.message,
- tag = "Model"
+ tag = "Model",
)
}
}
@@ -298,13 +317,14 @@ internal class ModelSettingsActions(
persistModelDownloadRequested(false)
state.update { appState ->
appState.copy(
- chat = appState.chat.copy(
- isDownloading = false,
- downloadPercent = null,
- downloadStatus = "Download cancelled",
- downloadPhase = null,
- hasRequestedModelDownload = false
- )
+ chat =
+ appState.chat.copy(
+ isDownloading = false,
+ downloadPercent = null,
+ downloadStatus = "Download cancelled",
+ downloadPhase = null,
+ hasRequestedModelDownload = false,
+ )
)
}
refreshModelDownloadInfo()
@@ -314,31 +334,33 @@ internal class ModelSettingsActions(
scope?.launch {
runCatching {
sessionPreferences.setModelDownloadRequested(requested)
- }.onFailure { error ->
- logRepository.log(
- LogLevel.Error,
- "Failed to persist model download state",
- details = error.message,
- tag = "Model",
- throwable = error
- )
}
+ .onFailure { error ->
+ logRepository.log(
+ LogLevel.Error,
+ "Failed to persist model download state",
+ details = error.message,
+ tag = "Model",
+ throwable = error,
+ )
+ }
}
}
fun resolveSelection(settings: ModelSettingsState): LlmModelSelection {
- val modelId = resolveEffectiveModelId(
- surface = ModelRuntimeSurface.ANDROID,
- totalMemoryBytes = state.value.chat.deviceCapability.totalMemoryBytes?.toULong(),
- preferredModelId = settings.modelId.takeIf { it.isNotEmpty() }
- )
+ val modelId =
+ resolveEffectiveModelId(
+ surface = ModelRuntimeSurface.ANDROID,
+ totalMemoryBytes = state.value.chat.deviceCapability.totalMemoryBytes?.toULong(),
+ preferredModelId = settings.modelId.takeIf { it.isNotEmpty() },
+ )
val contextLength = settings.contextLength.toIntOrNull()
val maxTokens = settings.maxTokens.toIntOrNull()?.takeIf { it > 0 }
return LlmModelSelection(
id = modelId,
contextLength = contextLength,
- maxTokens = maxTokens
+ maxTokens = maxTokens,
)
}
@@ -350,7 +372,7 @@ internal class ModelSettingsActions(
private fun downloadIdentityChanged(
oldSelection: LlmModelSelection,
- newSelection: LlmModelSelection
+ newSelection: LlmModelSelection,
): Boolean {
return oldSelection.id != newSelection.id
}
@@ -386,7 +408,8 @@ internal class ModelSettingsActions(
if (isOutOfStorageError(err)) {
return "Not enough storage space to download the model. Please free up space and try again."
}
- return if (wasAlreadyDownloaded) "Model load failed" else "Download failed. Please try again."
+ return if (wasAlreadyDownloaded) "Model load failed"
+ else "Download failed. Please try again."
}
private fun isOutOfStorageError(err: Throwable): Boolean {
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsScreen.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsScreen.kt
index 94300c506c..41dc8d5494 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsScreen.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsScreen.kt
@@ -32,11 +32,11 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
+import io.ente.ensu.bindings.ModelRuntimeSurface
+import io.ente.ensu.bindings.resolveModelPolicy
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
-import io.ente.ensu.bindings.ModelRuntimeSurface
-import io.ente.ensu.bindings.resolveModelPolicy
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -44,64 +44,68 @@ fun ModelSettingsScreen(
totalMemoryBytes: Long?,
state: ModelSettingsState,
onSave: (ModelSettingsState) -> Unit,
- onReset: () -> Unit
+ onReset: () -> Unit,
) {
val context = LocalContext.current
- val modelChoices = remember(totalMemoryBytes) {
- val modelPolicy = resolveModelPolicy(
- surface = ModelRuntimeSurface.ANDROID,
- totalMemoryBytes = totalMemoryBytes?.toULong()
- )
- listOf(
- ModelChoice(
- id = DEFAULT_OPTION_ID,
- title = modelPolicy.defaultModel.title,
- isDefault = true
- )
- ) + modelPolicy.visibleModels
- .filter { it.id != modelPolicy.defaultModel.id }
- .map { preset ->
+ val modelChoices =
+ remember(totalMemoryBytes) {
+ val modelPolicy =
+ resolveModelPolicy(
+ surface = ModelRuntimeSurface.ANDROID,
+ totalMemoryBytes = totalMemoryBytes?.toULong(),
+ )
+ listOf(
ModelChoice(
- id = preset.id,
- title = preset.title
+ id = DEFAULT_OPTION_ID,
+ title = modelPolicy.defaultModel.title,
+ isDefault = true,
)
- }
- }
+ ) +
+ modelPolicy.visibleModels
+ .filter { it.id != modelPolicy.defaultModel.id }
+ .map { preset ->
+ ModelChoice(
+ id = preset.id,
+ title = preset.title,
+ )
+ }
+ }
- var selectedModelId by remember(state) {
- mutableStateOf(initialSelectionId(state, modelChoices))
- }
+ var selectedModelId by
+ remember(state) { mutableStateOf(initialSelectionId(state, modelChoices)) }
var contextLength by remember(state) { mutableStateOf(state.contextLength) }
var maxTokens by remember(state) { mutableStateOf(state.maxTokens) }
var temperature by remember(state) { mutableStateOf(state.temperature) }
- var showAdvancedLimits by remember(state) {
- mutableStateOf(
- state.contextLength.isNotBlank() ||
- state.maxTokens.isNotBlank() ||
- state.temperature.isNotBlank()
- )
- }
+ var showAdvancedLimits by
+ remember(state) {
+ mutableStateOf(
+ state.contextLength.isNotBlank() ||
+ state.maxTokens.isNotBlank() ||
+ state.temperature.isNotBlank()
+ )
+ }
var isModelMenuExpanded by remember { mutableStateOf(false) }
- val selectedModel = modelChoices.firstOrNull { it.id == selectedModelId } ?: modelChoices.first()
+ val selectedModel =
+ modelChoices.firstOrNull { it.id == selectedModelId } ?: modelChoices.first()
Column(
- modifier = Modifier
- .fillMaxSize()
- .verticalScroll(rememberScrollState())
- .padding(EnsuSpacing.pageHorizontal.dp)
+ modifier =
+ Modifier.fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(EnsuSpacing.pageHorizontal.dp)
) {
SectionHeader("Select model")
Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
Text(
text = "Choose a built-in model.",
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
ExposedDropdownMenuBox(
expanded = isModelMenuExpanded,
- onExpandedChange = { isModelMenuExpanded = !isModelMenuExpanded }
+ onExpandedChange = { isModelMenuExpanded = !isModelMenuExpanded },
) {
OutlinedTextField(
value = selectedModel.title,
@@ -111,14 +115,12 @@ fun ModelSettingsScreen(
trailingIcon = {
ExposedDropdownMenuDefaults.TrailingIcon(expanded = isModelMenuExpanded)
},
- modifier = Modifier
- .menuAnchor()
- .fillMaxWidth()
+ modifier = Modifier.menuAnchor().fillMaxWidth(),
)
ExposedDropdownMenu(
expanded = isModelMenuExpanded,
- onDismissRequest = { isModelMenuExpanded = false }
+ onDismissRequest = { isModelMenuExpanded = false },
) {
modelChoices.forEach { choice ->
DropdownMenuItem(
@@ -126,7 +128,7 @@ fun ModelSettingsScreen(
onClick = {
selectedModelId = choice.id
isModelMenuExpanded = false
- }
+ },
)
}
}
@@ -137,55 +139,71 @@ fun ModelSettingsScreen(
title = "Advanced limits",
expanded = showAdvancedLimits,
collapsedHint = "Context length, output, temperature",
- onToggle = { showAdvancedLimits = !showAdvancedLimits }
+ onToggle = { showAdvancedLimits = !showAdvancedLimits },
)
AnimatedVisibility(showAdvancedLimits) {
Column {
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
Row {
Column(modifier = Modifier.weight(1f)) {
- Text(text = "Context length", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Text(
+ text = "Context length",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted(),
+ )
Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
OutlinedTextField(
value = contextLength,
onValueChange = { contextLength = it },
placeholder = { Text(text = "8192") },
modifier = Modifier.fillMaxWidth(),
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
)
}
Spacer(modifier = Modifier.width(EnsuSpacing.md.dp))
Column(modifier = Modifier.weight(1f)) {
- Text(text = "Max output", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Text(
+ text = "Max output",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted(),
+ )
Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
OutlinedTextField(
value = maxTokens,
onValueChange = { maxTokens = it },
placeholder = { Text(text = "2048") },
modifier = Modifier.fillMaxWidth(),
- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
)
}
}
Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
- Text(text = "Temperature", style = EnsuTypography.small, color = EnsuColor.textMuted())
+ 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)
+ 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())
+ Text(
+ text = "Leave blank to use model defaults",
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted(),
+ )
Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
Text(
text = "Values below 0.35 or above 0.7 are clamped automatically.",
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
}
@@ -196,39 +214,46 @@ fun ModelSettingsScreen(
Button(
onClick = {
- val savedState = state.copy(
- modelId = selectedModel.id.takeUnless { selectedModel.isDefault }.orEmpty(),
- contextLength = contextLength,
- maxTokens = maxTokens,
- temperature = temperature
- )
+ val savedState =
+ state.copy(
+ modelId = selectedModel.id.takeUnless { selectedModel.isDefault }.orEmpty(),
+ contextLength = contextLength,
+ maxTokens = maxTokens,
+ temperature = temperature,
+ )
onSave(savedState)
Toast.makeText(context, "Model settings saved", Toast.LENGTH_SHORT).show()
},
modifier = Modifier.fillMaxWidth(),
- colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent())
+ colors = ButtonDefaults.buttonColors(containerColor = EnsuColor.accent()),
) {
Text(text = "Save Model Settings", style = EnsuTypography.body)
}
Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
- TextButton(onClick = {
- onReset()
- selectedModelId = DEFAULT_OPTION_ID
- contextLength = ""
- maxTokens = ""
- temperature = ""
- Toast.makeText(context, "Model settings reset", Toast.LENGTH_SHORT).show()
- }) {
- Text(text = "Reset to defaults", style = EnsuTypography.body, color = EnsuColor.action())
+ TextButton(
+ onClick = {
+ onReset()
+ selectedModelId = DEFAULT_OPTION_ID
+ contextLength = ""
+ maxTokens = ""
+ temperature = ""
+ Toast.makeText(context, "Model settings reset", Toast.LENGTH_SHORT).show()
+ }
+ ) {
+ Text(
+ text = "Reset to defaults",
+ style = EnsuTypography.body,
+ color = EnsuColor.action(),
+ )
}
Spacer(modifier = Modifier.height(EnsuSpacing.md.dp))
Text(
text = "Changes apply the next time the model loads.",
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
}
@@ -243,14 +268,18 @@ private fun ExpandButton(
title: String,
expanded: Boolean,
collapsedHint: String,
- onToggle: () -> Unit
+ onToggle: () -> Unit,
) {
TextButton(onClick = onToggle, modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.fillMaxWidth()) {
Text(text = title, style = EnsuTypography.body, color = EnsuColor.action())
if (!expanded) {
Spacer(modifier = Modifier.height(EnsuSpacing.xs.dp))
- Text(text = collapsedHint, style = EnsuTypography.small, color = EnsuColor.textMuted())
+ Text(
+ text = collapsedHint,
+ style = EnsuTypography.small,
+ color = EnsuColor.textMuted(),
+ )
}
}
}
@@ -259,12 +288,12 @@ private fun ExpandButton(
private data class ModelChoice(
val id: String,
val title: String,
- val isDefault: Boolean = false
+ val isDefault: Boolean = false,
)
private fun initialSelectionId(
state: ModelSettingsState,
- choices: List<ModelChoice>
+ choices: List<ModelChoice>,
): String {
return choices.firstOrNull { it.id == state.modelId }?.id ?: DEFAULT_OPTION_ID
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsState.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsState.kt
index 8278e1b0e1..0d716081f6 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsState.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/llm/ModelSettingsState.kt
@@ -5,5 +5,5 @@ data class ModelSettingsState(
val contextLength: String = "",
val maxTokens: String = "",
val temperature: String = "",
- val isSaving: Boolean = false
+ val isSaving: Boolean = false,
)
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/FileLogRepository.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/FileLogRepository.kt
index 7305395ba9..5112d92802 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/FileLogRepository.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/FileLogRepository.kt
@@ -2,13 +2,6 @@ package io.ente.ensu.logging
import android.content.Context
import android.util.Log
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.SupervisorJob
-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
@@ -20,10 +13,17 @@ import java.util.Locale
import java.util.UUID
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
class FileLogRepository(
private val context: Context,
- private val maxLogFiles: Int = 5
+ private val maxLogFiles: Int = 5,
) {
private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -39,15 +39,22 @@ class FileLogRepository(
pruneOldLogFiles()
}
- fun log(level: LogLevel, message: String, details: String? = null, tag: String? = null, throwable: Throwable? = null) {
+ fun log(
+ level: LogLevel,
+ message: String,
+ details: String? = null,
+ tag: String? = null,
+ throwable: Throwable? = null,
+ ) {
val resolvedTag = tag ?: "ensu"
- val entry = buildLogEntry(
- level = level,
- message = message,
- details = details,
- tag = resolvedTag,
- throwable = throwable
- )
+ val entry =
+ buildLogEntry(
+ level = level,
+ message = message,
+ details = details,
+ tag = resolvedTag,
+ throwable = throwable,
+ )
// Also mirror to Logcat.
when (level) {
@@ -76,57 +83,67 @@ class FileLogRepository(
fun listLogFiles(): List<File> {
ensureLogDir()
- return logsDir.listFiles()
+ 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("")
+ 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 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 readTodayEntries(): List<LogEntry> =
+ withContext(Dispatchers.IO) { parseLogEntries(readTodayLogText()).reversed() }
- suspend fun createLogsZip(outputDir: File = context.cacheDir): File = withContext(Dispatchers.IO) {
- ensureLogDir()
- pruneOldLogFiles()
+ 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()
+ 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
}
- out
- }
private fun ensureLogDir() {
if (!logsDir.exists()) {
@@ -135,15 +152,21 @@ class FileLogRepository(
}
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 }
+ 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)
@@ -168,11 +191,12 @@ class FileLogRepository(
entries.add(
LogEntry(
id = UUID.randomUUID().toString(),
- timestampMillis = runCatching { lineTimestampFormatter.parse(timestamp)?.time }
- .getOrNull() ?: System.currentTimeMillis(),
+ timestampMillis =
+ runCatching { lineTimestampFormatter.parse(timestamp)?.time }
+ .getOrNull() ?: System.currentTimeMillis(),
level = parseLevel(level),
tag = tag,
- message = message
+ message = message,
)
)
} else {
@@ -187,7 +211,7 @@ class FileLogRepository(
timestampMillis = System.currentTimeMillis(),
level = LogLevel.Info,
tag = "Log",
- message = line
+ message = line,
)
)
}
@@ -196,17 +220,20 @@ class FileLogRepository(
return entries
}
- private fun levelToken(level: LogLevel): String = when (level) {
- LogLevel.Info -> "INFO"
- LogLevel.Warning -> "WARN"
- LogLevel.Error -> "ERROR"
- }
+ private fun levelToken(level: LogLevel): String =
+ when (level) {
+ LogLevel.Info -> "INFO"
+ LogLevel.Warning -> "WARN"
+ LogLevel.Error -> "ERROR"
+ }
- private fun parseLevel(token: String): LogLevel = when (token.uppercase()) {
- "WARN", "WARNING" -> LogLevel.Warning
- "ERROR" -> LogLevel.Error
- else -> LogLevel.Info
- }
+ private fun parseLevel(token: String): LogLevel =
+ when (token.uppercase()) {
+ "WARN",
+ "WARNING" -> LogLevel.Warning
+ "ERROR" -> LogLevel.Error
+ else -> LogLevel.Info
+ }
companion object {
private val logLineRegex = Regex("\\[(.+?)]\\[(.+?)] \\[(.+?)] (.*)")
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogEntry.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogEntry.kt
index b2960640aa..83ba3e22c5 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogEntry.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogEntry.kt
@@ -8,13 +8,13 @@ data class LogEntry(
val level: LogLevel,
val tag: String? = null,
val message: String,
- val details: String? = null
+ val details: String? = null,
)
enum class LogLevel {
Info,
Warning,
- Error
+ Error,
}
internal fun buildLogEntry(
@@ -24,7 +24,7 @@ internal fun buildLogEntry(
tag: String?,
throwable: Throwable?,
idProvider: () -> String = { UUID.randomUUID().toString() },
- nowProvider: () -> Long = { System.currentTimeMillis() }
+ nowProvider: () -> Long = { System.currentTimeMillis() },
): LogEntry {
val combinedDetails = buildString {
if (!details.isNullOrBlank()) {
@@ -34,7 +34,8 @@ internal fun buildLogEntry(
if (isNotEmpty()) append("\n")
append(throwable.stackTraceToString())
}
- }.ifBlank { null }
+ }
+ .ifBlank { null }
val safeMessage = sanitizeLog(message).orEmpty()
val safeDetails = sanitizeLog(combinedDetails)
@@ -45,6 +46,6 @@ internal fun buildLogEntry(
level = level,
tag = tag,
message = safeMessage,
- details = safeDetails
+ details = safeDetails,
)
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogSanitizer.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogSanitizer.kt
index 097bca6f0b..554f86fd79 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogSanitizer.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogSanitizer.kt
@@ -4,12 +4,14 @@ 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,;]+)"
-)
+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]+)")
+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,}")
@@ -19,14 +21,16 @@ internal fun sanitizeLog(input: String?): String? {
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 =
+ 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>" }
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogViewerScreen.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogViewerScreen.kt
index c78d59fb15..d35530cab5 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogViewerScreen.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/logging/LogViewerScreen.kt
@@ -1,13 +1,18 @@
package io.ente.ensu.logging
+import android.app.AlertDialog
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.os.Build
+import android.widget.Toast
import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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
@@ -17,11 +22,6 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
-import android.app.AlertDialog
-import android.content.ClipData
-import android.content.ClipboardManager
-import android.os.Build
-import android.widget.Toast
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
@@ -40,65 +40,60 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
-import io.ente.ensu.logging.FileLogRepository
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuCornerRadius
import io.ente.ensu.designsystem.EnsuIcon
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
import io.ente.ensu.designsystem.HugeIcons
-import io.ente.ensu.logging.LogEntry
-import io.ente.ensu.logging.LogLevel
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@Composable
-fun LogViewerScreen(
- logRepository: FileLogRepository
-) {
+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(Unit) { 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)
+ 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)
- ) {
+ Column(modifier = Modifier.fillMaxSize().padding(EnsuSpacing.pageHorizontal.dp)) {
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)
+ 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())
+ Text(
+ text = "No logs available",
+ style = EnsuTypography.body,
+ color = EnsuColor.textMuted(),
+ )
} else {
LazyColumn(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {
items(filteredLogs, key = { it.id }) { log ->
@@ -116,39 +111,42 @@ fun LogViewerScreen(
@Composable
private fun NativeLogDetailsDialog(logEntry: LogEntry, onDismiss: () -> Unit) {
val context = LocalContext.current
- val message = remember(logEntry) {
- buildString {
- append("Level: ")
- append(logEntry.level.name)
- logEntry.tag?.let { tag ->
- append("\nTag: ")
- append(tag)
- }
- append("\n\n")
- append(logEntry.message)
- logEntry.details?.let { details ->
- if (details.isNotBlank()) {
- append("\n\nDetails:\n")
- append(details)
+ val message =
+ remember(logEntry) {
+ buildString {
+ append("Level: ")
+ append(logEntry.level.name)
+ logEntry.tag?.let { tag ->
+ append("\nTag: ")
+ append(tag)
+ }
+ append("\n\n")
+ append(logEntry.message)
+ logEntry.details?.let { details ->
+ if (details.isNotBlank()) {
+ append("\n\nDetails:\n")
+ append(details)
+ }
}
}
}
- }
DisposableEffect(logEntry) {
- val dialog = AlertDialog.Builder(context)
- .setTitle("Log details")
- .setMessage(message)
- .setNeutralButton("Copy") { _, _ ->
- context.getSystemService(ClipboardManager::class.java)
- .setPrimaryClip(ClipData.newPlainText("log", message))
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
- Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
+ val dialog =
+ AlertDialog.Builder(context)
+ .setTitle("Log details")
+ .setMessage(message)
+ .setNeutralButton("Copy") { _, _ ->
+ context
+ .getSystemService(ClipboardManager::class.java)
+ .setPrimaryClip(ClipData.newPlainText("log", message))
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
+ Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
+ }
}
- }
- .setPositiveButton("Close") { _, _ -> onDismiss() }
- .setOnDismissListener { onDismiss() }
- .create()
+ .setPositiveButton("Close") { _, _ -> onDismiss() }
+ .setOnDismissListener { onDismiss() }
+ .create()
dialog.show()
onDispose { dialog.dismiss() }
@@ -160,23 +158,22 @@ private fun LogRow(logEntry: LogEntry, onOpenDetails: () -> Unit) {
val hasDetails = !logEntry.details.isNullOrBlank()
Column(
- modifier = Modifier
- .fillMaxWidth()
- .clickable(onClick = onOpenDetails)
- .padding(vertical = EnsuSpacing.xs.dp)
+ modifier =
+ Modifier.fillMaxWidth()
+ .clickable(onClick = onOpenDetails)
+ .padding(vertical = EnsuSpacing.xs.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
Row(
modifier = Modifier.weight(1f),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
Box(
- modifier = Modifier
- .size(7.dp)
- .background(levelColor(logEntry.level), CircleShape)
+ modifier =
+ Modifier.size(7.dp).background(levelColor(logEntry.level), CircleShape)
)
Spacer(modifier = Modifier.width(EnsuSpacing.sm.dp))
logEntry.tag?.let { tag ->
@@ -185,7 +182,7 @@ private fun LogRow(logEntry: LogEntry, onOpenDetails: () -> Unit) {
style = EnsuTypography.mini,
color = EnsuColor.textMuted(),
maxLines = 1,
- overflow = TextOverflow.Ellipsis
+ overflow = TextOverflow.Ellipsis,
)
}
}
@@ -193,7 +190,7 @@ private fun LogRow(logEntry: LogEntry, onOpenDetails: () -> Unit) {
Text(
text = logTimestampFormatter.format(Date(logEntry.timestampMillis)),
style = EnsuTypography.mini,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
Box(modifier = Modifier.size(EnsuIcon.tiny)) {
if (hasDetails) {
@@ -201,7 +198,7 @@ private fun LogRow(logEntry: LogEntry, onOpenDetails: () -> Unit) {
painter = painterResource(HugeIcons.ArrowRight01Icon),
contentDescription = null,
tint = EnsuColor.textMuted(),
- modifier = Modifier.size(EnsuIcon.tiny)
+ modifier = Modifier.size(EnsuIcon.tiny),
)
}
}
@@ -212,10 +209,11 @@ private fun LogRow(logEntry: LogEntry, onOpenDetails: () -> Unit) {
}
@Composable
-private fun levelColor(level: LogLevel): Color = when (level) {
- LogLevel.Info -> EnsuColor.textMuted()
- LogLevel.Warning -> EnsuColor.accent()
- LogLevel.Error -> EnsuColor.error
-}
+private fun levelColor(level: LogLevel): Color =
+ when (level) {
+ LogLevel.Info -> EnsuColor.textMuted()
+ LogLevel.Warning -> EnsuColor.accent()
+ LogLevel.Error -> EnsuColor.error
+ }
private val logTimestampFormatter = SimpleDateFormat("MMM d, h:mm:ss a", Locale.getDefault())
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/AndroidNotesSource.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/AndroidNotesSource.kt
index 1ffa613c3f..ec77313165 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/AndroidNotesSource.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/AndroidNotesSource.kt
@@ -23,7 +23,7 @@ private const val MAX_SCAN_ENTRIES = 250_000
internal class AndroidNotesSource(
private val resolver: ContentResolver,
private val tree: Uri,
- private val cancellation: NotesCancellationInterface
+ private val cancellation: NotesCancellationInterface,
) : NotesSource {
@Volatile private var signal: CancellationSignal? = null
private val activeRead = AtomicReference<FileChannel?>()
@@ -38,7 +38,7 @@ internal class AndroidNotesSource(
val directory: Boolean,
val size: Long?,
val modified: Long?,
- val virtual: Boolean
+ val virtual: Boolean,
)
fun cancel() {
@@ -53,33 +53,45 @@ internal class AndroidNotesSource(
private fun uri(id: String) = DocumentsContract.buildDocumentUriUsingTree(tree, id)
private fun query(target: Uri): List<Entry> = access { request ->
- val columns = arrayOf(
- DocumentsContract.Document.COLUMN_DOCUMENT_ID,
- DocumentsContract.Document.COLUMN_DISPLAY_NAME,
- DocumentsContract.Document.COLUMN_MIME_TYPE,
- DocumentsContract.Document.COLUMN_SIZE,
- DocumentsContract.Document.COLUMN_LAST_MODIFIED,
- DocumentsContract.Document.COLUMN_FLAGS
- )
+ val columns =
+ arrayOf(
+ DocumentsContract.Document.COLUMN_DOCUMENT_ID,
+ DocumentsContract.Document.COLUMN_DISPLAY_NAME,
+ DocumentsContract.Document.COLUMN_MIME_TYPE,
+ DocumentsContract.Document.COLUMN_SIZE,
+ DocumentsContract.Document.COLUMN_LAST_MODIFIED,
+ DocumentsContract.Document.COLUMN_FLAGS,
+ )
resolver.query(target, columns, null, null, null, request)?.use { cursor ->
val entries = mutableListOf<Entry>()
while (cursor.moveToNext()) {
request.throwIfCanceled()
if (entries.size % 64 == 0) cancellation.check()
- if (entries.size >= MAX_SCAN_ENTRIES) throw NotesException.InvalidInput("The Notes folder contains too many entries")
- val id = cursor.getString(0) ?: throw NotesException.SourceRead("Missing document identity")
- val name = cursor.getString(1) ?: throw NotesException.SourceRead("Missing document name")
- entries += Entry(
- id = id,
- name = name,
- directory = cursor.getString(2) == DocumentsContract.Document.MIME_TYPE_DIR,
- size = if (cursor.isNull(3)) null else cursor.getLong(3).takeIf { it >= 0 },
- modified = if (cursor.isNull(4)) null else cursor.getLong(4).takeIf { it > 0 },
- virtual = !cursor.isNull(5) && cursor.getInt(5) and DocumentsContract.Document.FLAG_VIRTUAL_DOCUMENT != 0
- )
+ if (entries.size >= MAX_SCAN_ENTRIES)
+ throw NotesException.InvalidInput("The Notes folder contains too many entries")
+ val id =
+ cursor.getString(0)
+ ?: throw NotesException.SourceRead("Missing document identity")
+ val name =
+ cursor.getString(1) ?: throw NotesException.SourceRead("Missing document name")
+ entries +=
+ Entry(
+ id = id,
+ name = name,
+ directory = cursor.getString(2) == DocumentsContract.Document.MIME_TYPE_DIR,
+ size = if (cursor.isNull(3)) null else cursor.getLong(3).takeIf { it >= 0 },
+ modified =
+ if (cursor.isNull(4)) null else cursor.getLong(4).takeIf { it > 0 },
+ virtual =
+ !cursor.isNull(5) &&
+ cursor.getInt(5) and
+ DocumentsContract.Document.FLAG_VIRTUAL_DOCUMENT != 0,
+ )
}
if (cursor.extras.containsKey(DocumentsContract.EXTRA_ERROR)) {
- throw NotesException.SourceRead("Could not load the complete Notes folder. Please try again.")
+ throw NotesException.SourceRead(
+ "Could not load the complete Notes folder. Please try again."
+ )
}
if (cursor.extras.getBoolean(DocumentsContract.EXTRA_LOADING, false)) {
throw NotesException.SourceRead("The folder is still loading. Please try again.")
@@ -88,9 +100,8 @@ internal class AndroidNotesSource(
} ?: throw NotesException.SourceRead("Could not read the Notes folder")
}
- private fun children(id: String): Map<String, Entry> = directories.getOrPut(id) {
- queryChildren(id)
- }
+ private fun children(id: String): Map<String, Entry> =
+ directories.getOrPut(id) { queryChildren(id) }
private fun queryChildren(id: String): Map<String, Entry> {
val entries = query(DocumentsContract.buildChildDocumentsUriUsingTree(tree, id))
@@ -105,7 +116,8 @@ internal class AndroidNotesSource(
tree.authority == other.tree.authority && rootId == other.rootId
fun root(): Entry =
- query(uri(rootId)).singleOrNull()?.takeIf { it.directory } ?: throw NotesException.Unavailable()
+ query(uri(rootId)).singleOrNull()?.takeIf { it.directory }
+ ?: throw NotesException.Unavailable()
fun contains(other: AndroidNotesSource): Boolean {
if (tree.authority != other.tree.authority) return false
@@ -119,7 +131,8 @@ internal class AndroidNotesSource(
if (id == other.rootId) return true
if (!seen.add(id)) throw NotesException.SourceRead("Ambiguous directory structure")
for (child in children(id).values) {
- if (++count > MAX_SCAN_ENTRIES) throw NotesException.InvalidInput("The Notes folder contains too many entries")
+ if (++count > MAX_SCAN_ENTRIES)
+ throw NotesException.InvalidInput("The Notes folder contains too many entries")
if (child.id == other.rootId) return true
if (child.directory) pending.add(child.id)
}
@@ -138,9 +151,11 @@ internal class AndroidNotesSource(
while (pending.isNotEmpty()) {
cancellation.check()
val (directory, prefix) = pending.removeFirst()
- if (!seen.add(directory)) throw NotesException.SourceRead("Ambiguous directory structure")
+ if (!seen.add(directory))
+ throw NotesException.SourceRead("Ambiguous directory structure")
for (child in children(directory).values) {
- if (++entries > MAX_SCAN_ENTRIES) throw NotesException.InvalidInput("The Notes folder contains too many entries")
+ if (++entries > MAX_SCAN_ENTRIES)
+ throw NotesException.InvalidInput("The Notes folder contains too many entries")
if (child.name.startsWith(".")) continue
if (!child.directory && (child.virtual || !supported(child.name))) continue
if (child.name.contains("/")) continue
@@ -154,13 +169,18 @@ internal class AndroidNotesSource(
pending.add(child.id to "$id/")
} else {
if (child.size != null && child.size > limits.maxSourceBytes.toLong()) continue
- val size = child.size ?: try {
- bytes(child.id).size.toLong()
- } catch (_: TooLarge) {
- continue
- }
+ val size =
+ child.size
+ ?: try {
+ bytes(child.id).size.toLong()
+ } catch (_: TooLarge) {
+ continue
+ }
total += size
- if (documents.size.toULong() >= limits.maxCollectionDocuments || total.toULong() > limits.maxCollectionSourceBytes) {
+ if (
+ documents.size.toULong() >= limits.maxCollectionDocuments ||
+ total.toULong() > limits.maxCollectionSourceBytes
+ ) {
throw NotesException.InvalidInput("The Notes folder is too large to index")
}
documents += NotesDocument(id, size.toULong(), child.modified)
@@ -179,13 +199,19 @@ internal class AndroidNotesSource(
for ((index, name) in parts.withIndex()) {
if (name.startsWith(".")) throw NotesException.SourceChanged()
val expected = children(directory)[name] ?: throw NotesException.SourceChanged()
- val entry = query(uri(expected.id)).singleOrNull() ?: throw NotesException.SourceChanged()
- if (entry.id != expected.id || entry.name != expected.name || entry.directory != expected.directory) {
+ val entry =
+ query(uri(expected.id)).singleOrNull() ?: throw NotesException.SourceChanged()
+ if (
+ entry.id != expected.id ||
+ entry.name != expected.name ||
+ entry.directory != expected.directory
+ ) {
throw NotesException.SourceChanged()
}
expectedPath += entry.id
if (index == parts.lastIndex) {
- if (entry.directory || entry.virtual || !supported(name)) throw NotesException.SourceChanged()
+ if (entry.directory || entry.virtual || !supported(name))
+ throw NotesException.SourceChanged()
if (!verifyPath(entry.id, expectedPath)) {
verifyListedPath(expectedPath, parts)
}
@@ -201,8 +227,11 @@ internal class AndroidNotesSource(
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O || !supportsPath) return false
return access {
try {
- val path = DocumentsContract.findDocumentPath(resolver, uri(id))
- ?: throw NotesException.SourceRead("Could not verify the note location. Please try again.")
+ val path =
+ DocumentsContract.findDocumentPath(resolver, uri(id))
+ ?: throw NotesException.SourceRead(
+ "Could not verify the note location. Please try again."
+ )
if (path.path != expected) throw NotesException.SourceChanged()
true
} catch (_: UnsupportedOperationException) {
@@ -221,11 +250,12 @@ internal class AndroidNotesSource(
override fun readDocument(documentId: String): NotesRead {
val before = resolve(documentId)
- val bytes = try {
- bytes(before.id)
- } catch (_: TooLarge) {
- throw NotesException.SourceChanged()
- }
+ val bytes =
+ try {
+ bytes(before.id)
+ } catch (_: TooLarge) {
+ throw NotesException.SourceChanged()
+ }
val after = resolve(documentId)
if (before != after || (after.size != null && after.size != bytes.size.toLong())) {
throw NotesException.SourceChanged()
@@ -234,8 +264,9 @@ internal class AndroidNotesSource(
}
private fun bytes(id: String): ByteArray = access { request ->
- val descriptor = resolver.openAssetFileDescriptor(uri(id), "r", request)
- ?: throw NotesException.SourceRead("Could not read the note")
+ val descriptor =
+ resolver.openAssetFileDescriptor(uri(id), "r", request)
+ ?: throw NotesException.SourceRead("Could not read the note")
descriptor.use {
cancellation.check()
it.createInputStream().use { input ->
@@ -246,7 +277,8 @@ internal class AndroidNotesSource(
val output = ByteArrayOutputStream()
val buffer = ByteArray(8192)
val destination = ByteBuffer.wrap(buffer)
- var remaining = descriptor.declaredLength.takeIf { length -> length >= 0 } ?: Long.MAX_VALUE
+ var remaining =
+ descriptor.declaredLength.takeIf { length -> length >= 0 } ?: Long.MAX_VALUE
while (remaining > 0) {
cancellation.check()
destination.clear()
@@ -295,5 +327,7 @@ internal class AndroidNotesSource(
}
private class TooLarge : Exception()
- private fun supported(name: String) = name.endsWith(".md", true) || name.endsWith(".markdown", true)
+
+ private fun supported(name: String) =
+ name.endsWith(".md", true) || name.endsWith(".markdown", true)
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesMaintenanceGate.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesMaintenanceGate.kt
index 803ae190c3..27680472c4 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesMaintenanceGate.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesMaintenanceGate.kt
@@ -2,28 +2,33 @@ package io.ente.ensu.notes
internal class NotesMaintenanceGate<T> {
private var suspensions = 0
- @Volatile var active: T? = null
+ @Volatile
+ var active: T? = null
private set
val available: Boolean
@Synchronized get() = suspensions == 0 && active == null
- @Synchronized fun admit(run: T): Boolean {
+ @Synchronized
+ fun admit(run: T): Boolean {
if (!available) return false
active = run
return true
}
- @Synchronized fun suspend(): T? {
+ @Synchronized
+ fun suspend(): T? {
suspensions++
return active
}
- @Synchronized fun resume() {
+ @Synchronized
+ fun resume() {
suspensions--
}
- @Synchronized fun finish(run: T) {
+ @Synchronized
+ fun finish(run: T) {
if (active === run) active = null
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesProvider.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesProvider.kt
index ad56218c60..2ad389a93e 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesProvider.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesProvider.kt
@@ -14,19 +14,19 @@ import io.ente.ensu.bindings.NotesException
import io.ente.ensu.bindings.NotesIndexOptions
import io.ente.ensu.bindings.NotesProgressCallback
import io.ente.ensu.bindings.notesContentRevision
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.util.UUID
import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
-import java.io.ByteArrayOutputStream
-import java.io.File
-import java.util.UUID
internal data class NotesRegistration(
val id: String,
- val label: String
+ val label: String,
)
class NotesProvider(private val context: Context) {
@@ -39,9 +39,8 @@ class NotesProvider(private val context: Context) {
private val registry = AtomicFile(File(root, "collections.json"))
private val diskGate = Mutex()
- private suspend fun <T> withAccess(block: suspend () -> T): T = withContext(Dispatchers.IO) {
- diskGate.withLock { block() }
- }
+ private suspend fun <T> withAccess(block: suspend () -> T): T =
+ withContext(Dispatchers.IO) { diskGate.withLock { block() } }
internal suspend fun load(): List<NotesRegistration> = withAccess {
val records = loadRegistry()
@@ -56,26 +55,40 @@ class NotesProvider(private val context: Context) {
}
internal suspend fun add(tree: Uri): NotesRegistration = withAccess {
- val alreadyGranted = context.contentResolver.persistedUriPermissions.any {
- it.uri == tree && it.isReadPermission
- }
+ val alreadyGranted =
+ context.contentResolver.persistedUriPermissions.any {
+ it.uri == tree && it.isReadPermission
+ }
var committed = false
try {
- context.contentResolver.takePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ context.contentResolver.takePersistableUriPermission(
+ tree,
+ Intent.FLAG_GRANT_READ_URI_PERMISSION,
+ )
NotesCancellation().use { token ->
val source = AndroidNotesSource(context.contentResolver, tree, token)
val label = source.root().name
for (registered in registrations.values) {
- val other = AndroidNotesSource(context.contentResolver, Uri.parse(registered.tree), token)
- val overlaps = source.sameRoot(other) || source.contains(other) || try {
- other.contains(source)
- } catch (_: NotesException.Unavailable) {
- false
- } catch (_: NotesException.SourceRead) {
- false
- }
+ val other =
+ AndroidNotesSource(
+ context.contentResolver,
+ Uri.parse(registered.tree),
+ token,
+ )
+ val overlaps =
+ source.sameRoot(other) ||
+ source.contains(other) ||
+ try {
+ other.contains(source)
+ } catch (_: NotesException.Unavailable) {
+ false
+ } catch (_: NotesException.SourceRead) {
+ false
+ }
if (overlaps) {
- throw NotesException.InvalidInput("This folder overlaps a folder already added to Your Notes.")
+ throw NotesException.InvalidInput(
+ "This folder overlaps a folder already added to Your Notes."
+ )
}
}
val record = Registration(UUID.randomUUID().toString(), label, tree.toString())
@@ -87,7 +100,10 @@ class NotesProvider(private val context: Context) {
} catch (error: Exception) {
if (!committed && !alreadyGranted) {
runCatching {
- context.contentResolver.releasePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ context.contentResolver.releasePersistableUriPermission(
+ tree,
+ Intent.FLAG_GRANT_READ_URI_PERMISSION,
+ )
}
}
throw error
@@ -103,7 +119,8 @@ class NotesProvider(private val context: Context) {
if (remaining.none { it.tree == record.tree }) {
runCatching {
context.contentResolver.releasePersistableUriPermission(
- Uri.parse(record.tree), Intent.FLAG_GRANT_READ_URI_PERMISSION
+ Uri.parse(record.tree),
+ Intent.FLAG_GRANT_READ_URI_PERMISSION,
)
}
}
@@ -125,7 +142,7 @@ class NotesProvider(private val context: Context) {
embedding: LlmContext,
cancel: NotesCancellation,
progress: NotesProgressCallback,
- options: NotesIndexOptions
+ options: NotesIndexOptions,
) = withAccess {
withSource(registration(id), cancel) { source ->
handle(id).use { it.index(source, embedding, cancel, progress, options) }
@@ -135,7 +152,7 @@ class NotesProvider(private val context: Context) {
private suspend fun <T> withSource(
record: Registration,
cancel: NotesCancellation,
- block: (AndroidNotesSource) -> T
+ block: (AndroidNotesSource) -> T,
): T {
val source = AndroidNotesSource(context.contentResolver, Uri.parse(record.tree), cancel)
return runNotesRead(source::cancel) { block(source) }
@@ -146,20 +163,27 @@ class NotesProvider(private val context: Context) {
Unit
}
- private suspend fun readVerified(record: Registration, reference: NoteSourceReference): ByteArray =
+ private suspend fun readVerified(
+ record: Registration,
+ reference: NoteSourceReference,
+ ): ByteArray =
NotesCancellation().use { cancel ->
val bytes = withSource(record, cancel) { it.readDocument(reference.documentId) }.bytes
- if (notesContentRevision(bytes) != reference.indexedRevision) throw NotesException.SourceChanged()
+ if (notesContentRevision(bytes) != reference.indexedRevision)
+ throw NotesException.SourceChanged()
bytes
}
internal suspend fun preview(reference: NoteSourceReference): Uri = withAccess {
val bytes = readVerified(registration(reference.collectionId), reference)
val previews = File(context.cacheDir, "note-previews").apply { mkdirs() }
- previews.listFiles()?.filter { it.lastModified() < System.currentTimeMillis() - 86_400_000L }
+ previews
+ .listFiles()
+ ?.filter { it.lastModified() < System.currentTimeMillis() - 86_400_000L }
?.forEach { it.deleteRecursively() }
val folder = File(previews, UUID.randomUUID().toString()).apply { mkdirs() }
- val file = File(folder, reference.documentId.substringAfterLast('/')).apply { writeBytes(bytes) }
+ val file =
+ File(folder, reference.documentId.substringAfterLast('/')).apply { writeBytes(bytes) }
FileProvider.getUriForFile(context, context.packageName + ".fileprovider", file)
}
@@ -169,34 +193,41 @@ class NotesProvider(private val context: Context) {
private fun handle(id: String) = NotesCollection(root.absolutePath, id)
private fun loadRegistry(): List<Registration> {
- if (!registry.baseFile.exists() && !File(registry.baseFile.path + ".bak").exists()) return emptyList()
- val bytes = registry.openRead().use { input ->
- val output = ByteArrayOutputStream()
- val buffer = ByteArray(8192)
- while (true) {
- val count = input.read(buffer)
- if (count < 0) break
- require(output.size() + count <= 1024 * 1024)
- output.write(buffer, 0, count)
+ if (!registry.baseFile.exists() && !File(registry.baseFile.path + ".bak").exists())
+ return emptyList()
+ val bytes =
+ registry.openRead().use { input ->
+ val output = ByteArrayOutputStream()
+ val buffer = ByteArray(8192)
+ while (true) {
+ val count = input.read(buffer)
+ if (count < 0) break
+ require(output.size() + count <= 1024 * 1024)
+ output.write(buffer, 0, count)
+ }
+ output.toByteArray()
}
- output.toByteArray()
- }
val json = JSONObject(bytes.toString(Charsets.UTF_8))
require(json.getInt("schemaVersion") == 1)
val records = json.getJSONArray("collections")
- val result = (0 until records.length()).map { i ->
- val row = records.getJSONObject(i)
- val id = row.getString("id")
- require(UUID.fromString(id).toString() == id)
- val tree = row.getString("tree")
- val uri = Uri.parse(tree)
- require(uri.scheme == "content" && DocumentsContract.isTreeUri(uri))
- Registration(id, row.getString("label"), tree)
- }
+ val result =
+ (0 until records.length()).map { i ->
+ val row = records.getJSONObject(i)
+ val id = row.getString("id")
+ require(UUID.fromString(id).toString() == id)
+ val tree = row.getString("tree")
+ val uri = Uri.parse(tree)
+ require(uri.scheme == "content" && DocumentsContract.isTreeUri(uri))
+ Registration(id, row.getString("label"), tree)
+ }
val registeredIds = result.map { it.id }.toSet()
require(registeredIds.size == result.size)
root.listFiles()?.forEach { child ->
- if (child.name !in registeredIds && runCatching { UUID.fromString(child.name).toString() == child.name }.getOrDefault(false)) {
+ if (
+ child.name !in registeredIds &&
+ runCatching { UUID.fromString(child.name).toString() == child.name }
+ .getOrDefault(false)
+ ) {
runCatching { handle(child.name).use { it.remove() } }
}
}
@@ -205,11 +236,22 @@ class NotesProvider(private val context: Context) {
private fun save(records: List<Registration>) {
root.mkdirs()
- val json = JSONObject().put("schemaVersion", 1).put("collections", JSONArray().apply {
- records.forEach {
- put(JSONObject().put("id", it.id).put("label", it.label).put("tree", it.tree))
- }
- })
+ val json =
+ JSONObject()
+ .put("schemaVersion", 1)
+ .put(
+ "collections",
+ JSONArray().apply {
+ records.forEach {
+ put(
+ JSONObject()
+ .put("id", it.id)
+ .put("label", it.label)
+ .put("tree", it.tree)
+ )
+ }
+ },
+ )
val bytes = json.toString().toByteArray()
require(bytes.size <= 1024 * 1024)
val stream = registry.startWrite()
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesRead.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesRead.kt
index f2b9c35f12..09d2cd1408 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesRead.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesRead.kt
@@ -9,14 +9,15 @@ import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
internal suspend fun <T> runNotesRead(cancel: () -> Unit, read: () -> T): T = coroutineScope {
- val worker = async(Dispatchers.IO) {
- try {
- read()
- } catch (error: Exception) {
- currentCoroutineContext().ensureActive()
- throw error
+ val worker =
+ async(Dispatchers.IO) {
+ try {
+ read()
+ } catch (error: Exception) {
+ currentCoroutineContext().ensureActive()
+ throw error
+ }
}
- }
try {
worker.await()
} finally {
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesSettingsScreen.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesSettingsScreen.kt
index 49ec53a693..6c4e0c574b 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesSettingsScreen.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesSettingsScreen.kt
@@ -25,8 +25,8 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
-import io.ente.ensu.components.KnowledgeCard
import io.ente.ensu.components.CompactButton
+import io.ente.ensu.components.KnowledgeCard
import io.ente.ensu.designsystem.EnsuColor
import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
@@ -38,65 +38,90 @@ import java.util.Date
fun NotesSettingsScreen(store: NotesStore) {
val state by store.state.collectAsState()
var removing by remember { mutableStateOf<NoteCollectionState?>(null) }
- val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
- uri?.let(store::add)
- }
+ val picker =
+ rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
+ uri?.let(store::add)
+ }
LazyColumn(
modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp),
) {
items(state.collections, key = { it.id }) { collection ->
KnowledgeCard(spacing = EnsuSpacing.sm.dp) {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(
modifier = Modifier.weight(1f),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp)
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp),
) {
- Text(collection.label, style = EnsuTypography.large, color = EnsuColor.textPrimary())
Text(
- text = buildString {
- if (collection.documentCount == 0L && (collection.status == NotesStatus.Pending || collection.status == NotesStatus.Indexing)) {
- append("Preparing notes…")
- } else {
- append("${collection.documentCount} ${if (collection.documentCount == 1L) "note indexed" else "notes indexed"}")
- }
- collection.lastUpdatedAtMs?.let {
- append(" Β· Updated at ")
- append(DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(it)))
- }
- },
+ collection.label,
+ style = EnsuTypography.large,
+ color = EnsuColor.textPrimary(),
+ )
+ Text(
+ text =
+ buildString {
+ if (
+ collection.documentCount == 0L &&
+ (collection.status == NotesStatus.Pending ||
+ collection.status == NotesStatus.Indexing)
+ ) {
+ append("Preparing notes…")
+ } else {
+ append(
+ "${collection.documentCount} ${if (collection.documentCount == 1L) "note indexed" else "notes indexed"}"
+ )
+ }
+ collection.lastUpdatedAtMs?.let {
+ append(" Β· Updated at ")
+ append(
+ DateFormat.getDateTimeInstance(
+ DateFormat.MEDIUM,
+ DateFormat.SHORT,
+ )
+ .format(Date(it))
+ )
+ }
+ },
style = EnsuTypography.mini,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
- IconButton(onClick = { removing = collection }, modifier = Modifier.size(48.dp)) {
+ IconButton(
+ onClick = { removing = collection },
+ modifier = Modifier.size(48.dp),
+ ) {
Icon(
painter = painterResource(HugeIcons.Delete01Icon),
contentDescription = "Remove ${collection.label}",
modifier = Modifier.size(18.dp),
- tint = EnsuColor.textMuted()
+ tint = EnsuColor.textMuted(),
)
}
}
collection.progress?.let { progress ->
Row(
horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
LinearProgressIndicator(
progress = { progress.coerceIn(0, 100) / 100f },
modifier = Modifier.weight(1f),
color = EnsuColor.action(),
- trackColor = EnsuColor.border()
+ trackColor = EnsuColor.border(),
+ )
+ Text(
+ "$progress%",
+ style = EnsuTypography.mini,
+ color = EnsuColor.textMuted(),
)
- Text("$progress%", style = EnsuTypography.mini, color = EnsuColor.textMuted())
}
}
if (collection.status == NotesStatus.Pending) {
Text(
"Indexing will continue when the app and model are ready.",
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
collection.error?.let {
@@ -108,14 +133,14 @@ fun NotesSettingsScreen(store: NotesStore) {
item {
CompactButton(
label = "Add notes folder",
- onClick = { picker.launch(null) }
+ onClick = { picker.launch(null) },
)
}
item {
Text(
"Ensu reads and indexes markdown files in the selected folder. Source files are never modified.",
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
state.error?.let { error ->
@@ -126,17 +151,21 @@ fun NotesSettingsScreen(store: NotesStore) {
AlertDialog(
onDismissRequest = { removing = null },
title = { Text("Remove ${collection.label}?") },
- text = { Text("Remove this folder from Your Notes? Your original files will be kept.") },
+ text = {
+ Text("Remove this folder from Your Notes? Your original files will be kept.")
+ },
confirmButton = {
- TextButton(onClick = {
- store.remove(collection.id)
- removing = null
- }) {
+ TextButton(
+ onClick = {
+ store.remove(collection.id)
+ removing = null
+ }
+ ) {
Text("Remove")
}
},
dismissButton = { TextButton(onClick = { removing = null }) { Text("Cancel") } },
- containerColor = EnsuColor.backgroundBase()
+ containerColor = EnsuColor.backgroundBase(),
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesStore.kt
index 6f860369d1..1be69ee2ef 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesStore.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/notes/NotesStore.kt
@@ -21,6 +21,7 @@ import io.ente.ensu.llm.ModelMaintenance
import io.ente.ensu.llm.withMaintenanceSuspended
import io.ente.ensu.logging.FileLogRepository
import io.ente.ensu.logging.LogLevel
+import java.util.concurrent.atomic.AtomicBoolean
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
@@ -30,16 +31,22 @@ import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
-import kotlinx.coroutines.isActive
-import kotlinx.coroutines.launch
-import kotlinx.coroutines.withContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
-import java.util.concurrent.atomic.AtomicBoolean
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
-enum class NotesStatus { Pending, Indexing, Updating, Ready, Unavailable, Error }
+enum class NotesStatus {
+ Pending,
+ Indexing,
+ Updating,
+ Ready,
+ Unavailable,
+ Error,
+}
data class NoteCollectionState(
val id: String,
@@ -50,7 +57,7 @@ data class NoteCollectionState(
val progress: Int? = null,
val error: String? = null,
val completedEmpty: Boolean = false,
- val lastUpdatedAtMs: Long? = null
+ val lastUpdatedAtMs: Long? = null,
) {
val eligible: Boolean
get() = indexAvailable && status != NotesStatus.Error && status != NotesStatus.Unavailable
@@ -58,7 +65,7 @@ data class NoteCollectionState(
data class NotesState(
val collections: List<NoteCollectionState> = emptyList(),
- val error: String? = null
+ val error: String? = null,
)
val LocalNotesStore = staticCompositionLocalOf<NotesStore?> { null }
@@ -67,17 +74,17 @@ class NotesStore(
private val context: Context,
private val llm: LlmProvider,
private val logRepository: FileLogRepository,
- private val provider: NotesProvider = NotesProvider(context)
+ private val provider: NotesProvider = NotesProvider(context),
) : ModelMaintenance {
private data class Pending(
val forced: Set<String>,
val rebuild: Boolean,
- val due: Long
+ val due: Long,
)
private class Run(
val cancel: NotesCancellation,
- val job: Job
+ val job: Job,
)
private val limits = notesLimits()
@@ -88,7 +95,9 @@ class NotesStore(
private val maintenance = NotesMaintenanceGate<Run>()
private var scope: CoroutineScope? = null
private var bootstrapJob: Job? = null
- private val active get() = maintenance.active
+ private val active
+ get() = maintenance.active
+
private var wake: Job? = null
private var foreground = false
private var loaded = false
@@ -112,17 +121,35 @@ class NotesStore(
enqueue(record.id, rebuild = true, immediate = true)
NoteCollectionState(record.id, record.label)
} catch (e: Exception) {
- logRepository.log(LogLevel.Error, "Checkpoint load failed collection=${record.id}", tag = "Notes", throwable = e)
- NoteCollectionState(record.id, record.label, NotesStatus.Error, error = message(e))
+ logRepository.log(
+ LogLevel.Error,
+ "Checkpoint load failed collection=${record.id}",
+ tag = "Notes",
+ throwable = e,
+ )
+ NoteCollectionState(
+ record.id,
+ record.label,
+ NotesStatus.Error,
+ error = message(e),
+ )
}
}
_state.value = NotesState(states)
loaded = true
scans.addAll(registrations.keys)
} catch (e: Exception) {
- logRepository.log(LogLevel.Error, "Collection registry load failed", tag = "Notes", throwable = e)
+ logRepository.log(
+ LogLevel.Error,
+ "Collection registry load failed",
+ tag = "Notes",
+ throwable = e,
+ )
disabled = true
- _state.value = NotesState(error = "Could not load Your Notes. Existing indexes have been preserved.")
+ _state.value =
+ NotesState(
+ error = "Could not load Your Notes. Existing indexes have been preserved."
+ )
}
pump()
}
@@ -173,7 +200,11 @@ class NotesStore(
val record = provider.add(tree)
registrations[record.id] = record
_state.update {
- it.copy(collections = it.collections + NoteCollectionState(record.id, record.label), error = null)
+ it.copy(
+ collections =
+ it.collections + NoteCollectionState(record.id, record.label),
+ error = null,
+ )
}
enqueue(record.id, immediate = true)
} catch (error: CancellationException) {
@@ -196,7 +227,10 @@ class NotesStore(
scans.remove(id)
failed.remove(id)
_state.update {
- it.copy(collections = it.collections.filter { row -> row.id != id }, error = null)
+ it.copy(
+ collections = it.collections.filter { row -> row.id != id },
+ error = null,
+ )
}
} catch (error: CancellationException) {
throw error
@@ -220,24 +254,28 @@ class NotesStore(
_state.update { it.copy(error = null) }
}
- suspend fun retrieve(query: List<Float>): List<NotesHit> = withContext(Dispatchers.Main.immediate) {
- val records = _state.value.collections.filter { it.eligible }.mapNotNull { registrations[it.id] }
- val hits = mutableListOf<NotesHit>()
- for (record in records) {
- currentCoroutineContext().ensureActive()
- try {
- hits += provider.search(record.id, query)
- } catch (error: CancellationException) {
- throw error
- } catch (error: NotesException.RebuildRequired) {
- enqueue(record.id, rebuild = true, immediate = true)
- update(record.id) { it.copy(status = NotesStatus.Pending, indexAvailable = false) }
- } catch (error: Exception) {
- fail(record.id, error)
+ suspend fun retrieve(query: List<Float>): List<NotesHit> =
+ withContext(Dispatchers.Main.immediate) {
+ val records =
+ _state.value.collections.filter { it.eligible }.mapNotNull { registrations[it.id] }
+ val hits = mutableListOf<NotesHit>()
+ for (record in records) {
+ currentCoroutineContext().ensureActive()
+ try {
+ hits += provider.search(record.id, query)
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: NotesException.RebuildRequired) {
+ enqueue(record.id, rebuild = true, immediate = true)
+ update(record.id) {
+ it.copy(status = NotesStatus.Pending, indexAvailable = false)
+ }
+ } catch (error: Exception) {
+ fail(record.id, error)
+ }
}
+ hits
}
- hits
- }
suspend fun verify(excerpts: List<GroundedExcerpt>): List<GroundedExcerpt> =
withContext(Dispatchers.Main.immediate) {
@@ -255,7 +293,13 @@ class NotesStore(
val record = records[note.collectionId] ?: continue
try {
provider.verify(note)
- result += excerpt.copy(source = GroundedSource.LocalNote(withNotesCollectionLabel(note, record.label)))
+ result +=
+ excerpt.copy(
+ source =
+ GroundedSource.LocalNote(
+ withNotesCollectionLabel(note, record.label)
+ )
+ )
accepted++
} catch (error: CancellationException) {
throw error
@@ -272,20 +316,25 @@ class NotesStore(
scope?.launch {
clearError()
try {
- val uri = withMaintenanceSuspended {
- provider.preview(reference)
- }
- context.startActivity(Intent(Intent.ACTION_VIEW).apply {
- setDataAndType(uri, "text/plain")
- addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
- })
+ val uri = withMaintenanceSuspended { provider.preview(reference) }
+ context.startActivity(
+ Intent(Intent.ACTION_VIEW).apply {
+ setDataAndType(uri, "text/plain")
+ addFlags(
+ Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK
+ )
+ }
+ )
clearError()
} catch (e: Exception) {
- val error = when (e) {
- is NotesException.SourceChanged -> "This note changed after the answer was generated."
- is NotesException.Unavailable -> "This note is unavailable."
- else -> "Could not open this note. Check folder access and that a text viewer is installed."
- }
+ val error =
+ when (e) {
+ is NotesException.SourceChanged ->
+ "This note changed after the answer was generated."
+ is NotesException.Unavailable -> "This note is unavailable."
+ else ->
+ "Could not open this note. Check folder access and that a text viewer is installed."
+ }
_state.update { it.copy(error = error) }
}
}
@@ -295,15 +344,18 @@ class NotesStore(
id: String,
rebuild: Boolean = false,
forced: Set<String> = emptySet(),
- immediate: Boolean = false
+ immediate: Boolean = false,
) {
if (id !in registrations) return
val old = pending[id]
- pending[id] = Pending(
- forced = old?.forced.orEmpty() + forced,
- rebuild = rebuild || old?.rebuild == true,
- due = if (immediate) 0 else old?.due ?: (System.currentTimeMillis() + SCAN_INTERVAL_MS)
- )
+ pending[id] =
+ Pending(
+ forced = old?.forced.orEmpty() + forced,
+ rebuild = rebuild || old?.rebuild == true,
+ due =
+ if (immediate) 0
+ else old?.due ?: (System.currentTimeMillis() + SCAN_INTERVAL_MS),
+ )
}
private fun pump() {
@@ -312,115 +364,161 @@ class NotesStore(
wake?.cancel()
val now = System.currentTimeMillis()
val embeddingReady = llm.isEmbeddingModelReady()
- val request = if (embeddingReady) {
- pending.entries.firstOrNull { it.key !in failed && it.value.due <= now }
- } else null
+ val request =
+ if (embeddingReady) {
+ pending.entries.firstOrNull { it.key !in failed && it.value.due <= now }
+ } else null
val id = request?.key ?: scans.firstOrNull { it !in pending && it !in failed }
if (id == null) {
- val due = if (embeddingReady) {
- pending.asSequence().filter { it.key !in failed }.minOfOrNull { it.value.due }
- } else null
+ val due =
+ if (embeddingReady) {
+ pending.asSequence().filter { it.key !in failed }.minOfOrNull { it.value.due }
+ } else null
wake = owner.launch {
- delay(minOf(SCAN_INTERVAL_MS, due?.minus(now)?.coerceAtLeast(1) ?: SCAN_INTERVAL_MS))
- scans.addAll(_state.value.collections.filter {
- it.status != NotesStatus.Unavailable && (it.status != NotesStatus.Error || it.completedEmpty)
- }.map { it.id })
+ delay(
+ minOf(SCAN_INTERVAL_MS, due?.minus(now)?.coerceAtLeast(1) ?: SCAN_INTERVAL_MS)
+ )
+ scans.addAll(
+ _state.value.collections
+ .filter {
+ it.status != NotesStatus.Unavailable &&
+ (it.status != NotesStatus.Error || it.completedEmpty)
+ }
+ .map { it.id }
+ )
pump()
}
return
}
- val record = registrations[id] ?: run {
- pending.remove(id)
- scans.remove(id)
- pump()
- return
- }
+ val record =
+ registrations[id]
+ ?: run {
+ pending.remove(id)
+ scans.remove(id)
+ pump()
+ return
+ }
val snapshot = request?.value
val cancel = NotesCancellation()
val hadIndex = _state.value.collections.firstOrNull { it.id == id }?.indexAvailable == true
- val job = owner.launch(start = CoroutineStart.LAZY) {
- scans.remove(id)
- try {
- cancel.check()
- if (snapshot == null) {
- val result = provider.inspectFreshness(id, cancel)
- update(id) { fromSummary(record, result.summary).copy(progress = if (result.summary.initialComplete) null else it.progress) }
- if (result.changed) {
- enqueue(id, forced = result.forcedDocumentIds.toSet(), immediate = !result.summary.initialComplete)
- update(id) { it.copy(status = NotesStatus.Pending, error = null) }
- }
- } else {
- update(id) { it.copy(status = if (hadIndex) NotesStatus.Updating else NotesStatus.Indexing, error = null) }
- val result = llm.withEmbeddingContext(checkCancellation = cancel::check) { embedding ->
- provider.index(
- id,
- embedding,
- cancel,
- object : NotesProgressCallback {
- override fun onProgress(progress: NotesProgress) {
- owner.launch {
- if (active?.cancel === cancel) {
- update(id) {
- it.copy(progress = progress.percentage.toInt(), documentCount = progress.indexedDocumentCount.toLong())
- }
- }
- }
- }
- },
- NotesIndexOptions(snapshot.forced.toList(), snapshot.rebuild)
- )
- }
- val changedId = result.changedDocumentId
- if (pending[id] === snapshot) {
- if (changedId == null) {
- pending.remove(id)
- } else {
- pending[id] = snapshot.copy(
- forced = result.uncheckedDocumentIds.toSet() + changedId,
- rebuild = false,
- due = System.currentTimeMillis() + SCAN_INTERVAL_MS
+ val job =
+ owner.launch(start = CoroutineStart.LAZY) {
+ scans.remove(id)
+ try {
+ cancel.check()
+ if (snapshot == null) {
+ val result = provider.inspectFreshness(id, cancel)
+ update(id) {
+ fromSummary(record, result.summary)
+ .copy(
+ progress =
+ if (result.summary.initialComplete) null else it.progress
+ )
+ }
+ if (result.changed) {
+ enqueue(
+ id,
+ forced = result.forcedDocumentIds.toSet(),
+ immediate = !result.summary.initialComplete,
)
+ update(id) { it.copy(status = NotesStatus.Pending, error = null) }
}
- } else if (changedId != null) {
- enqueue(id, forced = result.uncheckedDocumentIds.toSet() + changedId)
- }
- update(id) {
- if (id !in pending) {
- fromSummary(record, result.summary)
- } else {
+ } else {
+ update(id) {
it.copy(
- status = NotesStatus.Pending,
- documentCount = result.summary.documentCount.toLong(),
- indexAvailable = hadIndex && result.summary.initialComplete && result.summary.documentCount > 0uL
+ status =
+ if (hadIndex) NotesStatus.Updating else NotesStatus.Indexing,
+ error = null,
)
}
- }
- }
- } catch (e: Exception) {
- when (e) {
- is NotesException.Cancelled, is CancellationException -> {
- if (snapshot == null) scans.add(id)
- val saved = withContext(NonCancellable) {
- runCatching { provider.inspect(id) }.getOrNull()
+ val result =
+ llm.withEmbeddingContext(checkCancellation = cancel::check) { embedding
+ ->
+ provider.index(
+ id,
+ embedding,
+ cancel,
+ object : NotesProgressCallback {
+ override fun onProgress(progress: NotesProgress) {
+ owner.launch {
+ if (active?.cancel === cancel) {
+ update(id) {
+ it.copy(
+ progress = progress.percentage.toInt(),
+ documentCount =
+ progress.indexedDocumentCount
+ .toLong(),
+ )
+ }
+ }
+ }
+ }
+ },
+ NotesIndexOptions(snapshot.forced.toList(), snapshot.rebuild),
+ )
+ }
+ val changedId = result.changedDocumentId
+ if (pending[id] === snapshot) {
+ if (changedId == null) {
+ pending.remove(id)
+ } else {
+ pending[id] =
+ snapshot.copy(
+ forced = result.uncheckedDocumentIds.toSet() + changedId,
+ rebuild = false,
+ due = System.currentTimeMillis() + SCAN_INTERVAL_MS,
+ )
+ }
+ } else if (changedId != null) {
+ enqueue(id, forced = result.uncheckedDocumentIds.toSet() + changedId)
}
update(id) {
- it.copy(
- status = NotesStatus.Pending,
- indexAvailable = hadIndex && saved?.initialComplete == true && saved.documentCount > 0uL
- )
+ if (id !in pending) {
+ fromSummary(record, result.summary)
+ } else {
+ it.copy(
+ status = NotesStatus.Pending,
+ documentCount = result.summary.documentCount.toLong(),
+ indexAvailable =
+ hadIndex &&
+ result.summary.initialComplete &&
+ result.summary.documentCount > 0uL,
+ )
+ }
}
- if (e is CancellationException) throw e
}
- is NotesException.RebuildRequired -> {
- if (snapshot == null) {
- enqueue(id, rebuild = true, immediate = true)
- update(id) { it.copy(status = NotesStatus.Pending, indexAvailable = false) }
- } else fail(id, e)
+ } catch (e: Exception) {
+ when (e) {
+ is NotesException.Cancelled,
+ is CancellationException -> {
+ if (snapshot == null) scans.add(id)
+ val saved =
+ withContext(NonCancellable) {
+ runCatching { provider.inspect(id) }.getOrNull()
+ }
+ update(id) {
+ it.copy(
+ status = NotesStatus.Pending,
+ indexAvailable =
+ hadIndex &&
+ saved?.initialComplete == true &&
+ saved.documentCount > 0uL,
+ )
+ }
+ if (e is CancellationException) throw e
+ }
+ is NotesException.RebuildRequired -> {
+ if (snapshot == null) {
+ enqueue(id, rebuild = true, immediate = true)
+ update(id) {
+ it.copy(status = NotesStatus.Pending, indexAvailable = false)
+ }
+ } else fail(id, e)
+ }
+ else -> fail(id, e)
}
- else -> fail(id, e)
}
}
- }
val run = Run(cancel, job)
val admitted = maintenance.admit(run)
job.invokeOnCompletion {
@@ -433,21 +531,33 @@ class NotesStore(
private fun fail(id: String, e: Exception) {
if (id !in registrations) return
- logRepository.log(LogLevel.Error, "Notes update failed collection=$id", tag = "Notes", throwable = e)
+ logRepository.log(
+ LogLevel.Error,
+ "Notes update failed collection=$id",
+ tag = "Notes",
+ throwable = e,
+ )
failed.add(id)
scans.remove(id)
update(id) {
it.copy(
- status = if (e is NotesException.Unavailable) NotesStatus.Unavailable else NotesStatus.Error,
+ status =
+ if (e is NotesException.Unavailable) NotesStatus.Unavailable
+ else NotesStatus.Error,
progress = null,
error = message(e),
- completedEmpty = false
+ completedEmpty = false,
)
}
}
private fun update(id: String, transform: (NoteCollectionState) -> NoteCollectionState) {
- _state.update { it.copy(collections = it.collections.map { row -> if (row.id == id) transform(row) else row }) }
+ _state.update {
+ it.copy(
+ collections =
+ it.collections.map { row -> if (row.id == id) transform(row) else row }
+ )
+ }
}
private fun fromSummary(record: NotesRegistration, summary: NotesSummary): NoteCollectionState {
@@ -456,28 +566,33 @@ class NotesStore(
return NoteCollectionState(
id = record.id,
label = record.label,
- status = when {
- ready -> NotesStatus.Ready
- empty -> NotesStatus.Error
- else -> NotesStatus.Pending
- },
+ status =
+ when {
+ ready -> NotesStatus.Ready
+ empty -> NotesStatus.Error
+ else -> NotesStatus.Pending
+ },
documentCount = summary.documentCount.toLong(),
indexAvailable = ready,
error = if (empty) EMPTY_NOTES else null,
completedEmpty = empty,
- lastUpdatedAtMs = summary.lastUpdatedAtMs
+ lastUpdatedAtMs = summary.lastUpdatedAtMs,
)
}
- private fun message(e: Exception): String = when (e) {
- is NotesException.Unavailable -> "This Notes folder is unavailable. Check access and try again."
- is NotesException.SourceChanged -> "The folder changed. Try again after it finishes updating."
- is NotesException.SourceRead -> e.detail
- is NotesException.InvalidInput -> e.detail
- is NotesException.Storage -> "Could not save the Notes index. Check storage and try again."
- is NotesException.RebuildRequired -> "The Notes index needs rebuilding."
- else -> "Could not update Your Notes. Please try again."
- }
+ private fun message(e: Exception): String =
+ when (e) {
+ is NotesException.Unavailable ->
+ "This Notes folder is unavailable. Check access and try again."
+ is NotesException.SourceChanged ->
+ "The folder changed. Try again after it finishes updating."
+ is NotesException.SourceRead -> e.detail
+ is NotesException.InvalidInput -> e.detail
+ is NotesException.Storage ->
+ "Could not save the Notes index. Check storage and try again."
+ is NotesException.RebuildRequired -> "The Notes index needs rebuilding."
+ else -> "Could not update Your Notes. Please try again."
+ }
companion object {
private const val SCAN_INTERVAL_MS = 300_000L
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/platform/Haptics.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/platform/Haptics.kt
index 4d91e3fcc8..caf54b415d 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/platform/Haptics.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/platform/Haptics.kt
@@ -15,7 +15,7 @@ import androidx.compose.ui.platform.LocalView
class Haptics(
private val context: Context,
- private val view: View
+ private val view: View,
) {
fun perform(type: HapticFeedbackType) {
val feedback = mapToHapticConstant(type)
@@ -28,14 +28,16 @@ class Haptics(
if (!shouldForceVibrationFallback() && view.performHapticFeedback(feedback)) return
- val vibrator = context.getSystemService(VibratorManager::class.java)?.defaultVibrator ?: return
- val effect = when (type) {
- HapticFeedbackType.LongPress -> VibrationEffect.EFFECT_HEAVY_CLICK
- else -> VibrationEffect.EFFECT_TICK
- }
+ val vibrator =
+ context.getSystemService(VibratorManager::class.java)?.defaultVibrator ?: return
+ val effect =
+ when (type) {
+ HapticFeedbackType.LongPress -> VibrationEffect.EFFECT_HEAVY_CLICK
+ else -> VibrationEffect.EFFECT_TICK
+ }
vibrator.vibrate(
VibrationEffect.createPredefined(effect),
- VibrationAttributes.createForUsage(VibrationAttributes.USAGE_TOUCH)
+ VibrationAttributes.createForUsage(VibrationAttributes.USAGE_TOUCH),
)
}
@@ -64,7 +66,5 @@ class Haptics(
fun rememberHaptics(): Haptics {
val context = LocalContext.current
val view = LocalView.current
- return remember(context, view) {
- Haptics(context, view)
- }
+ return remember(context, view) { Haptics(context, view) }
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/AdvancedSettingsDataStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/AdvancedSettingsDataStore.kt
index 2bc79dfb76..caf3af88a0 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/AdvancedSettingsDataStore.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/AdvancedSettingsDataStore.kt
@@ -5,13 +5,12 @@ import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
-import io.ente.ensu.settings.DeveloperSettingsState
import io.ente.ensu.llm.ModelSettingsState
import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.flow.first
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
@@ -19,26 +18,29 @@ private val Context.advancedSettingsPreferences by preferencesDataStore("ensu_ad
data class AdvancedSettingsSnapshot(
val developerSettings: DeveloperSettingsState = DeveloperSettingsState(),
- val modelSettings: ModelSettingsState = ModelSettingsState()
+ val modelSettings: ModelSettingsState = ModelSettingsState(),
)
class AdvancedSettingsDataStore(private val context: Context) {
private val persistenceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
- val settingsFlow: Flow<AdvancedSettingsSnapshot> = context.advancedSettingsPreferences.data.map { prefs ->
- AdvancedSettingsSnapshot(
- developerSettings = DeveloperSettingsState(
- isAdvancedUnlocked = prefs[Keys.advancedUnlocked] ?: false,
- systemPrompt = prefs[Keys.systemPrompt].orEmpty()
- ),
- modelSettings = ModelSettingsState(
- modelId = prefs[Keys.modelId].orEmpty(),
- contextLength = prefs[Keys.contextLength].orEmpty(),
- maxTokens = prefs[Keys.maxTokens].orEmpty(),
- temperature = prefs[Keys.temperature].orEmpty()
+ val settingsFlow: Flow<AdvancedSettingsSnapshot> =
+ context.advancedSettingsPreferences.data.map { prefs ->
+ AdvancedSettingsSnapshot(
+ developerSettings =
+ DeveloperSettingsState(
+ isAdvancedUnlocked = prefs[Keys.advancedUnlocked] ?: false,
+ systemPrompt = prefs[Keys.systemPrompt].orEmpty(),
+ ),
+ modelSettings =
+ ModelSettingsState(
+ modelId = prefs[Keys.modelId].orEmpty(),
+ contextLength = prefs[Keys.contextLength].orEmpty(),
+ maxTokens = prefs[Keys.maxTokens].orEmpty(),
+ temperature = prefs[Keys.temperature].orEmpty(),
+ ),
)
- )
- }
+ }
suspend fun migrateLegacyModelSelection(
migrate: suspend (legacyModelUrl: String?, legacyMmprojUrl: String?) -> String?
@@ -61,27 +63,19 @@ class AdvancedSettingsDataStore(private val context: Context) {
}
suspend fun unlockAdvancedSettings() {
- context.advancedSettingsPreferences.edit { prefs ->
- prefs[Keys.advancedUnlocked] = true
- }
+ context.advancedSettingsPreferences.edit { prefs -> prefs[Keys.advancedUnlocked] = true }
}
fun persistUnlockAdvancedSettings() {
- persistenceScope.launch {
- unlockAdvancedSettings()
- }
+ persistenceScope.launch { unlockAdvancedSettings() }
}
suspend fun saveSystemPrompt(value: String) {
- context.advancedSettingsPreferences.edit { prefs ->
- prefs[Keys.systemPrompt] = value
- }
+ context.advancedSettingsPreferences.edit { prefs -> prefs[Keys.systemPrompt] = value }
}
fun persistSystemPrompt(value: String) {
- persistenceScope.launch {
- saveSystemPrompt(value)
- }
+ persistenceScope.launch { saveSystemPrompt(value) }
}
suspend fun saveModelSettings(settings: ModelSettingsState) {
@@ -94,9 +88,7 @@ class AdvancedSettingsDataStore(private val context: Context) {
}
fun persistModelSettings(settings: ModelSettingsState) {
- persistenceScope.launch {
- saveModelSettings(settings)
- }
+ persistenceScope.launch { saveModelSettings(settings) }
}
suspend fun resetModelSettings() {
@@ -109,9 +101,7 @@ class AdvancedSettingsDataStore(private val context: Context) {
}
fun persistResetModelSettings() {
- persistenceScope.launch {
- resetModelSettings()
- }
+ persistenceScope.launch { resetModelSettings() }
}
companion object {
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/DeveloperSettingsState.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/DeveloperSettingsState.kt
index be16bcd348..4bd1452a3a 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/DeveloperSettingsState.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/DeveloperSettingsState.kt
@@ -2,5 +2,5 @@ package io.ente.ensu.settings
data class DeveloperSettingsState(
val isAdvancedUnlocked: Boolean = false,
- val systemPrompt: String = ""
+ val systemPrompt: String = "",
)
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/KnowledgeSettingsScreen.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/KnowledgeSettingsScreen.kt
index 72d969fe02..ec831c9c3b 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/KnowledgeSettingsScreen.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/KnowledgeSettingsScreen.kt
@@ -11,9 +11,9 @@ 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.material3.HorizontalDivider
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Info
+import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
@@ -29,6 +29,8 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
+import io.ente.ensu.bindings.KnowledgeDatasetConfig
+import io.ente.ensu.bindings.KnowledgeReconciliationStatus
import io.ente.ensu.components.AttributionDialog
import io.ente.ensu.components.AttributionLink
import io.ente.ensu.components.CompactButton
@@ -38,8 +40,6 @@ import io.ente.ensu.designsystem.EnsuSpacing
import io.ente.ensu.designsystem.EnsuTypography
import io.ente.ensu.designsystem.HugeIcons
import io.ente.ensu.format.formatBytes
-import io.ente.ensu.bindings.KnowledgeDatasetConfig
-import io.ente.ensu.bindings.KnowledgeReconciliationStatus
import io.ente.ensu.knowledge.KnowledgePackState
import io.ente.ensu.knowledge.KnowledgeState
@@ -49,13 +49,13 @@ fun KnowledgeSettingsScreen(
packDownloadsAllowed: Boolean,
onDownloadOrUpdate: (String) -> Unit,
onCancel: (String) -> Unit,
- onSetEnabled: (String, Boolean) -> Unit
+ onSetEnabled: (String, Boolean) -> Unit,
) {
var attributionConfig by remember { mutableStateOf<KnowledgeDatasetConfig?>(null) }
LazyColumn(
modifier = Modifier.padding(horizontal = EnsuSpacing.pageHorizontal.dp),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp),
) {
items(state.packs.values.toList(), key = { it.config.stableId }) { pack ->
KnowledgePackCard(
@@ -64,7 +64,7 @@ fun KnowledgeSettingsScreen(
onDownloadOrUpdate = { onDownloadOrUpdate(pack.config.stableId) },
onCancel = { onCancel(pack.config.stableId) },
onSetEnabled = { enabled -> onSetEnabled(pack.config.stableId, enabled) },
- onOpenAttribution = { attributionConfig = pack.config }
+ onOpenAttribution = { attributionConfig = pack.config },
)
}
}
@@ -72,7 +72,7 @@ fun KnowledgeSettingsScreen(
attributionConfig?.let { config ->
PackAttributionDialog(
config = config,
- onDismiss = { attributionConfig = null }
+ onDismiss = { attributionConfig = null },
)
}
}
@@ -84,23 +84,27 @@ private fun KnowledgePackCard(
onDownloadOrUpdate: () -> Unit,
onCancel: () -> Unit,
onSetEnabled: (Boolean) -> Unit,
- onOpenAttribution: () -> Unit
+ onOpenAttribution: () -> Unit,
) {
KnowledgeCard {
Row(verticalAlignment = Alignment.CenterVertically) {
Column(
modifier = Modifier.weight(1f),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp)
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp),
) {
- Text(pack.config.label, style = EnsuTypography.large, color = EnsuColor.textPrimary())
+ Text(
+ pack.config.label,
+ style = EnsuTypography.large,
+ color = EnsuColor.textPrimary(),
+ )
PackMetadataLine(pack = pack, onOpenAttribution = onOpenAttribution)
}
if (pack.activeIdentity != null && !pack.isMutating) {
Switch(checked = pack.enabled, onCheckedChange = onSetEnabled)
} else if (
packDownloadsAllowed &&
- pack.status == KnowledgeReconciliationStatus.DOWNLOAD &&
- !pack.isMutating
+ pack.status == KnowledgeReconciliationStatus.DOWNLOAD &&
+ !pack.isMutating
) {
CompactButton(label = "Download", onClick = onDownloadOrUpdate)
}
@@ -111,71 +115,71 @@ private fun KnowledgePackCard(
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
LinearProgressIndicator(
- progress = { (pack.mutationProgress?.percentage ?: 0.0).coerceIn(0.0, 100.0).toFloat() / 100f },
+ progress = {
+ (pack.mutationProgress?.percentage ?: 0.0).coerceIn(0.0, 100.0).toFloat() /
+ 100f
+ },
modifier = Modifier.weight(1f),
color = EnsuColor.action(),
- trackColor = EnsuColor.border()
+ trackColor = EnsuColor.border(),
)
IconButton(
onClick = onCancel,
- modifier = Modifier.size(32.dp)
+ modifier = Modifier.size(32.dp),
) {
Icon(
painter = painterResource(HugeIcons.Cancel01Icon),
contentDescription = "Cancel download",
modifier = Modifier.size(14.dp),
- tint = EnsuColor.textMuted()
+ tint = EnsuColor.textMuted(),
)
}
}
} else if (
- packDownloadsAllowed &&
- pack.status == KnowledgeReconciliationStatus.UPDATE_AVAILABLE
+ packDownloadsAllowed && pack.status == KnowledgeReconciliationStatus.UPDATE_AVAILABLE
) {
Spacer(Modifier.height(EnsuSpacing.md.dp))
CompactButton(label = "Update", onClick = onDownloadOrUpdate)
}
- pack.errorMessage?.let {
- Text(it, style = EnsuTypography.small, color = EnsuColor.error)
- }
+ pack.errorMessage?.let { Text(it, style = EnsuTypography.small, color = EnsuColor.error) }
}
}
@Composable
private fun PackMetadataLine(
pack: KnowledgePackState,
- onOpenAttribution: () -> Unit
+ onOpenAttribution: () -> Unit,
) {
val attribution = pack.config.attribution
Row(
horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = formatBytes(pack.config.downloadSizeBytes),
style = EnsuTypography.mini,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
Text("Β·", style = EnsuTypography.mini, color = EnsuColor.textMuted())
Row(
modifier = Modifier.clickable(onClick = onOpenAttribution),
horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = attribution.licenseLabel,
style = EnsuTypography.mini,
- color = EnsuColor.accent()
+ color = EnsuColor.accent(),
)
Icon(
imageVector = Icons.Outlined.Info,
contentDescription = "View attribution for ${pack.config.label}",
tint = EnsuColor.accent(),
- modifier = Modifier.size(14.dp)
+ modifier = Modifier.size(14.dp),
)
}
}
@@ -184,7 +188,7 @@ private fun PackMetadataLine(
@Composable
private fun PackAttributionDialog(
config: KnowledgeDatasetConfig,
- onDismiss: () -> Unit
+ onDismiss: () -> Unit,
) {
val attribution = config.attribution
val uriHandler = LocalUriHandler.current
@@ -194,35 +198,32 @@ private fun PackAttributionDialog(
Text(
text = config.label,
style = EnsuTypography.large,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
HorizontalDivider(color = EnsuColor.border())
Text(
text = "From ${attribution.credit}",
style = EnsuTypography.small,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
Text(
text = attribution.modificationNotice,
style = EnsuTypography.small,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
Row(
modifier = Modifier.fillMaxWidth(),
- horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)
+ horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp),
) {
- AttributionLink("Source β†—") {
- uriHandler.openUri(attribution.publicPackUrl)
- }
- AttributionLink("License β†—") {
- uriHandler.openUri(attribution.licenseUrl)
- }
+ AttributionLink("Source β†—") { uriHandler.openUri(attribution.publicPackUrl) }
+ AttributionLink("License β†—") { uriHandler.openUri(attribution.licenseUrl) }
}
HorizontalDivider(color = EnsuColor.border())
Text(
- text = "Wikimedia and Ensu are not affiliated. Wikimedia project names identify the source material only.",
+ text =
+ "Wikimedia and Ensu are not affiliated. Wikimedia project names identify the source material only.",
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SessionPreferencesDataStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SessionPreferencesDataStore.kt
index 14707f4495..5ce56c2f63 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SessionPreferencesDataStore.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SessionPreferencesDataStore.kt
@@ -2,12 +2,12 @@ package io.ente.ensu.settings
import android.content.Context
import androidx.datastore.core.DataStore
+import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStoreFile
-import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import org.json.JSONObject
@@ -15,17 +15,16 @@ import org.json.JSONObject
class SessionPreferencesDataStore(context: Context) {
private val dataStore: DataStore<Preferences> = getDataStore(context.applicationContext)
- val selectedSessionId: Flow<String?> = dataStore.data.map { preferences ->
- preferences[Keys.SELECTED_SESSION_ID]
- }
+ val selectedSessionId: Flow<String?> =
+ dataStore.data.map { preferences -> preferences[Keys.SELECTED_SESSION_ID] }
- val sessionSummaries: Flow<Map<String, String>> = dataStore.data.map { preferences ->
- decodeSessionSummaries(preferences[Keys.SESSION_SUMMARIES])
- }
+ val sessionSummaries: Flow<Map<String, String>> =
+ dataStore.data.map { preferences ->
+ decodeSessionSummaries(preferences[Keys.SESSION_SUMMARIES])
+ }
- val modelDownloadRequested: Flow<Boolean> = dataStore.data.map { preferences ->
- preferences[Keys.MODEL_DOWNLOAD_REQUESTED] ?: false
- }
+ val modelDownloadRequested: Flow<Boolean> =
+ dataStore.data.map { preferences -> preferences[Keys.MODEL_DOWNLOAD_REQUESTED] ?: false }
suspend fun setSelectedSessionId(sessionId: String?) {
dataStore.edit { preferences ->
@@ -39,7 +38,8 @@ class SessionPreferencesDataStore(context: Context) {
suspend fun setSessionSummary(sessionId: String, summary: String?) {
dataStore.edit { preferences ->
- val summaries = decodeSessionSummaries(preferences[Keys.SESSION_SUMMARIES]).toMutableMap()
+ val summaries =
+ decodeSessionSummaries(preferences[Keys.SESSION_SUMMARIES]).toMutableMap()
if (summary.isNullOrBlank()) {
summaries.remove(sessionId)
} else {
@@ -50,33 +50,30 @@ class SessionPreferencesDataStore(context: Context) {
}
suspend fun setModelDownloadRequested(requested: Boolean) {
- dataStore.edit { preferences ->
- preferences[Keys.MODEL_DOWNLOAD_REQUESTED] = requested
- }
+ dataStore.edit { preferences -> preferences[Keys.MODEL_DOWNLOAD_REQUESTED] = requested }
}
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
+ 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
}
- map
- }.getOrDefault(emptyMap())
+ .getOrDefault(emptyMap())
}
private fun encodeSessionSummaries(summaries: Map<String, String>): String {
val json = JSONObject()
- summaries.forEach { (key, value) ->
- json.put(key, value)
- }
+ summaries.forEach { (key, value) -> json.put(key, value) }
return json.toString()
}
@@ -87,17 +84,17 @@ class SessionPreferencesDataStore(context: Context) {
}
companion object {
- @Volatile
- private var instance: DataStore<Preferences>? = null
+ @Volatile private var instance: DataStore<Preferences>? = null
private fun getDataStore(context: Context): DataStore<Preferences> {
- return instance ?: synchronized(this) {
- instance ?: PreferenceDataStoreFactory.create {
- context.preferencesDataStoreFile("ensu_session_prefs")
- }.also { created ->
- instance = created
+ return instance
+ ?: synchronized(this) {
+ instance
+ ?: PreferenceDataStoreFactory.create {
+ context.preferencesDataStoreFile("ensu_session_prefs")
+ }
+ .also { created -> instance = created }
}
- }
}
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SettingsScreen.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SettingsScreen.kt
index 48a562103e..b9800f46f8 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SettingsScreen.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SettingsScreen.kt
@@ -55,75 +55,81 @@ fun SettingsScreen(
onOpenModelSettings: () -> Unit,
onOpenSystemPromptSettings: () -> Unit,
onUnlockAdvanced: () -> Unit,
- onSignIn: () -> Unit
+ onSignIn: () -> Unit,
) {
var query by remember { mutableStateOf("") }
var buildVersionTapCount by remember { mutableStateOf(0) }
var lastBuildVersionTapAt by remember { mutableStateOf<Long?>(null) }
val context = LocalContext.current
- val allItems = remember(context, onOpenLogs, onOpenKnowledge, onOpenNotes, onSignIn) {
- buildList {
- add(
- SettingsItem(
- title = "About",
- iconVector = Icons.Outlined.Info,
- onClick = { context.openExternalLink("https://ente.com/blog/ensu/") }
+ val allItems =
+ remember(context, onOpenLogs, onOpenKnowledge, onOpenNotes, onSignIn) {
+ buildList {
+ add(
+ SettingsItem(
+ title = "About",
+ iconVector = Icons.Outlined.Info,
+ onClick = { context.openExternalLink("https://ente.com/blog/ensu/") },
+ )
)
- )
-
- add(SettingsItem(title = "Your Notes", iconRes = HugeIcons.Folder01Icon, onClick = onOpenNotes))
- if (IS_ENSU_PACKS_ENABLED) {
add(
SettingsItem(
- title = "Ensu Packs",
- iconRes = HugeIcons.PackageIcon,
- onClick = onOpenKnowledge
+ title = "Your Notes",
+ iconRes = HugeIcons.Folder01Icon,
+ onClick = onOpenNotes,
)
)
- }
- add(
- SettingsItem(
- title = "Logs",
- iconRes = HugeIcons.Bug01Icon,
- onClick = onOpenLogs
+ if (IS_ENSU_PACKS_ENABLED) {
+ add(
+ SettingsItem(
+ title = "Ensu Packs",
+ iconRes = HugeIcons.PackageIcon,
+ onClick = onOpenKnowledge,
+ )
+ )
+ }
+
+ add(
+ SettingsItem(
+ title = "Logs",
+ iconRes = HugeIcons.Bug01Icon,
+ onClick = onOpenLogs,
+ )
)
- )
- add(
- SettingsItem(
- title = "Sign In to Backup",
- iconRes = HugeIcons.Upload01Icon,
- onClick = onSignIn
+ add(
+ SettingsItem(
+ title = "Sign In to Backup",
+ iconRes = HugeIcons.Upload01Icon,
+ onClick = onSignIn,
+ )
)
- )
- add(
- SettingsItem(
- title = "Privacy Policy",
- iconRes = HugeIcons.ViewIcon,
- onClick = { context.openExternalLink("https://ente.com/privacy") }
+ add(
+ SettingsItem(
+ title = "Privacy Policy",
+ iconRes = HugeIcons.ViewIcon,
+ onClick = { context.openExternalLink("https://ente.com/privacy") },
+ )
)
- )
- add(
- SettingsItem(
- title = "Terms of Service",
- iconVector = Icons.Outlined.Description,
- onClick = { context.openExternalLink("https://ente.com/terms") }
+ add(
+ SettingsItem(
+ title = "Terms of Service",
+ iconVector = Icons.Outlined.Description,
+ onClick = { context.openExternalLink("https://ente.com/terms") },
+ )
)
- )
+ }
}
- }
- val filteredItems = remember(query, allItems) {
- val q = query.trim().lowercase()
- if (q.isEmpty()) return@remember allItems
- allItems.filter { item ->
- item.title.lowercase().contains(q)
+ val filteredItems =
+ remember(query, allItems) {
+ val q = query.trim().lowercase()
+ if (q.isEmpty()) return@remember allItems
+ allItems.filter { item -> item.title.lowercase().contains(q) }
}
- }
fun handleBuildVersionTap() {
if (isAdvancedUnlocked) return
@@ -148,21 +154,20 @@ fun SettingsScreen(
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)
+ 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))
LazyColumn(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.sm.dp)) {
- items(filteredItems, key = { it.title }) { item ->
- SettingsRow(item)
- }
+ items(filteredItems, key = { it.title }) { item -> SettingsRow(item) }
if (isAdvancedUnlocked && query.isBlank()) {
item(key = "advanced-header") {
@@ -171,7 +176,7 @@ fun SettingsScreen(
text = "Advanced",
style = EnsuTypography.small,
color = EnsuColor.textMuted(),
- modifier = Modifier.padding(vertical = EnsuSpacing.xs.dp)
+ modifier = Modifier.padding(vertical = EnsuSpacing.xs.dp),
)
}
item(key = "advanced-model-settings") {
@@ -179,7 +184,7 @@ fun SettingsScreen(
SettingsItem(
title = "Model settings",
iconRes = HugeIcons.Settings01Icon,
- onClick = onOpenModelSettings
+ onClick = onOpenModelSettings,
)
)
}
@@ -188,7 +193,7 @@ fun SettingsScreen(
SettingsItem(
title = "System prompt",
iconRes = HugeIcons.Edit01Icon,
- onClick = onOpenSystemPromptSettings
+ onClick = onOpenSystemPromptSettings,
)
)
}
@@ -202,10 +207,10 @@ fun SettingsScreen(
style = EnsuTypography.small,
color = EnsuColor.textMuted(),
textAlign = TextAlign.Center,
- modifier = Modifier
- .fillMaxWidth()
- .clickable(onClick = ::handleBuildVersionTap)
- .padding(vertical = EnsuSpacing.sm.dp)
+ modifier =
+ Modifier.fillMaxWidth()
+ .clickable(onClick = ::handleBuildVersionTap)
+ .padding(vertical = EnsuSpacing.sm.dp),
)
}
}
@@ -218,7 +223,7 @@ private data class SettingsItem(
val iconRes: Int? = null,
val iconVector: ImageVector? = null,
val onClick: () -> Unit,
- val isDestructive: Boolean = false
+ val isDestructive: Boolean = false,
)
@Composable
@@ -226,30 +231,31 @@ private fun SettingsRow(item: SettingsItem) {
val iconAndTextColor = if (item.isDestructive) EnsuColor.error else EnsuColor.textPrimary()
Row(
- modifier = Modifier
- .fillMaxWidth()
- .clip(RoundedCornerShape(EnsuCornerRadius.card.dp))
- .background(EnsuColor.fillFaint())
- .clickable(onClick = item.onClick)
- .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.lg.dp),
+ modifier =
+ Modifier.fillMaxWidth()
+ .clip(RoundedCornerShape(EnsuCornerRadius.card.dp))
+ .background(EnsuColor.fillFaint())
+ .clickable(onClick = item.onClick)
+ .padding(horizontal = EnsuSpacing.lg.dp, vertical = EnsuSpacing.lg.dp),
horizontalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp),
- verticalAlignment = Alignment.CenterVertically
+ verticalAlignment = Alignment.CenterVertically,
) {
item.iconVector?.let { iconVector ->
Icon(
imageVector = iconVector,
contentDescription = null,
tint = iconAndTextColor,
- modifier = Modifier.size(18.dp)
- )
- } ?: item.iconRes?.let { iconRes ->
- Icon(
- painter = painterResource(iconRes),
- contentDescription = null,
- tint = iconAndTextColor,
- modifier = Modifier.size(18.dp)
+ modifier = Modifier.size(18.dp),
)
}
+ ?: item.iconRes?.let { iconRes ->
+ Icon(
+ painter = painterResource(iconRes),
+ contentDescription = null,
+ tint = iconAndTextColor,
+ modifier = Modifier.size(18.dp),
+ )
+ }
Column(modifier = Modifier.weight(1f)) {
Text(text = item.title, style = EnsuTypography.body, color = iconAndTextColor)
}
@@ -257,16 +263,17 @@ private fun SettingsRow(item: SettingsItem) {
painter = painterResource(HugeIcons.ArrowRight01Icon),
contentDescription = null,
tint = EnsuColor.textMuted(),
- modifier = Modifier.size(18.dp)
+ modifier = Modifier.size(18.dp),
)
}
}
private fun Context.openExternalLink(url: String) {
runCatching {
- val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- }
+ val intent =
+ Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
ContextCompat.startActivity(this, intent, null)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt
index 835af058ad..7017b0f127 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/settings/SystemPromptSettingsScreen.kt
@@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
@@ -18,7 +19,6 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
-import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.unit.dp
import io.ente.ensu.components.PrimaryButton
import io.ente.ensu.designsystem.EnsuColor
@@ -32,21 +32,22 @@ fun SystemPromptSettingsScreen(
datePlaceholder: String,
systemPrompt: String,
onSave: (String) -> Unit,
- onReset: () -> Unit
+ onReset: () -> Unit,
) {
val resolvedPrompt = systemPrompt.trim().ifEmpty { defaultPromptBody }
var value by remember(systemPrompt) { mutableStateOf(resolvedPrompt) }
Column(
- modifier = Modifier
- .fillMaxSize()
- .verticalScroll(rememberScrollState())
- .padding(EnsuSpacing.pageHorizontal.dp)
+ modifier =
+ Modifier.fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(EnsuSpacing.pageHorizontal.dp)
) {
Text(
- text = "This prompt is used as-is. Use $datePlaceholder anywhere to insert the current date.",
+ text =
+ "This prompt is used as-is. Use $datePlaceholder anywhere to insert the current date.",
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
Spacer(modifier = Modifier.height(EnsuSpacing.lg.dp))
@@ -54,29 +55,28 @@ fun SystemPromptSettingsScreen(
OutlinedTextField(
value = value,
onValueChange = { value = it },
- modifier = Modifier
- .fillMaxWidth()
- .height(220.dp),
+ modifier = Modifier.fillMaxWidth().height(220.dp),
placeholder = {
Text(
text = "Example: You are a concise assistant. Current date: $datePlaceholder",
- style = EnsuTypography.body
+ style = EnsuTypography.body,
)
},
- colors = TextFieldDefaults.colors(
- focusedContainerColor = EnsuColor.fillFaint(),
- unfocusedContainerColor = EnsuColor.fillFaint(),
- focusedIndicatorColor = EnsuColor.fillFaint(),
- unfocusedIndicatorColor = EnsuColor.fillFaint()
- ),
- shape = RoundedCornerShape(EnsuCornerRadius.input.dp)
+ colors =
+ TextFieldDefaults.colors(
+ focusedContainerColor = EnsuColor.fillFaint(),
+ unfocusedContainerColor = EnsuColor.fillFaint(),
+ focusedIndicatorColor = EnsuColor.fillFaint(),
+ unfocusedIndicatorColor = EnsuColor.fillFaint(),
+ ),
+ shape = RoundedCornerShape(EnsuCornerRadius.input.dp),
)
Spacer(modifier = Modifier.height(EnsuSpacing.sm.dp))
Text(
text = "Leave blank to use the default prompt.",
style = EnsuTypography.small,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
Spacer(modifier = Modifier.height(EnsuSpacing.xl.dp))
@@ -84,7 +84,7 @@ fun SystemPromptSettingsScreen(
PrimaryButton(
text = "Save",
isLoading = false,
- isEnabled = value.trim() != resolvedPrompt
+ isEnabled = value.trim() != resolvedPrompt,
) {
val normalizedValue = value.trim()
val valueToSave = if (normalizedValue == defaultPromptBody) "" else normalizedValue
@@ -97,7 +97,7 @@ fun SystemPromptSettingsScreen(
Text(
text = "Use Default Prompt",
style = EnsuTypography.body,
- color = EnsuColor.action()
+ color = EnsuColor.action(),
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt
index 98ad1f4d95..2043a6fa57 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/storage/CredentialStore.kt
@@ -6,17 +6,17 @@ import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
class CredentialStore(context: Context) {
- private val masterKey = MasterKey.Builder(context)
- .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
- .build()
-
- private val prefs = EncryptedSharedPreferences.create(
- context,
- "ensu_credentials",
- masterKey,
- EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
- EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
- )
+ private val masterKey =
+ MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build()
+
+ private val prefs =
+ EncryptedSharedPreferences.create(
+ context,
+ "ensu_credentials",
+ masterKey,
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
+ )
fun getOrCreateChatDbKey(hasChatData: Boolean): ByteArray {
prefs.getString(KEY_CHAT_DB_KEY, null)?.let { encoded ->
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewContent.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewContent.kt
index 691dfbf4da..dfd97ea3cc 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewContent.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewContent.kt
@@ -2,24 +2,27 @@ package io.ente.ensu.whatsnew
data class WhatsNewEntry(
val title: String,
- val description: String
+ val description: String,
)
object WhatsNewContent {
const val VERSION: Int = 2
- val entries: List<WhatsNewEntry> = listOf(
- WhatsNewEntry(
- title = "Ensu Packs",
- description = "Add knowledge from wikipedia and wikibooks to get more accurate answers."
- ),
- WhatsNewEntry(
- title = "Chat with Your Notes",
- description = "Add your markdown notes folder, and chat with your notes. Ask questions or discuss the thoughts you put down."
- ),
- WhatsNewEntry(
- title = "Gemma for high RAM phones",
- description = "For phones with >8GB RAM, Gemma 4 is the new default model."
+ val entries: List<WhatsNewEntry> =
+ listOf(
+ WhatsNewEntry(
+ title = "Ensu Packs",
+ description =
+ "Add knowledge from wikipedia and wikibooks to get more accurate answers.",
+ ),
+ WhatsNewEntry(
+ title = "Chat with Your Notes",
+ description =
+ "Add your markdown notes folder, and chat with your notes. Ask questions or discuss the thoughts you put down.",
+ ),
+ WhatsNewEntry(
+ title = "Gemma for high RAM phones",
+ description = "For phones with >8GB RAM, Gemma 4 is the new default model.",
+ ),
)
- )
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewDialog.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewDialog.kt
index bdc5c626ff..53c7c5d5f4 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewDialog.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewDialog.kt
@@ -20,7 +20,7 @@ import io.ente.ensu.designsystem.EnsuTypography
@Composable
fun WhatsNewDialog(
entries: List<WhatsNewEntry>,
- onDismiss: () -> Unit
+ onDismiss: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
@@ -28,31 +28,29 @@ fun WhatsNewDialog(
Text(
text = "What's new",
style = EnsuTypography.h3Bold,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
},
text = {
Column(
- modifier = Modifier
- .fillMaxWidth()
- .heightIn(max = 360.dp)
- .verticalScroll(rememberScrollState()),
- verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp)
+ modifier =
+ Modifier.fillMaxWidth()
+ .heightIn(max = 360.dp)
+ .verticalScroll(rememberScrollState()),
+ verticalArrangement = Arrangement.spacedBy(EnsuSpacing.lg.dp),
) {
- entries.forEach { entry ->
- WhatsNewEntryContent(entry)
- }
+ entries.forEach { entry -> WhatsNewEntryContent(entry) }
}
},
confirmButton = {
TextButton(
onClick = onDismiss,
- colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary())
+ colors = ButtonDefaults.textButtonColors(contentColor = EnsuColor.textPrimary()),
) {
Text(text = "Continue", style = EnsuTypography.body)
}
},
- containerColor = EnsuColor.backgroundBase()
+ containerColor = EnsuColor.backgroundBase(),
)
}
@@ -62,12 +60,12 @@ private fun WhatsNewEntryContent(entry: WhatsNewEntry) {
Text(
text = entry.title,
style = EnsuTypography.large,
- color = EnsuColor.textPrimary()
+ color = EnsuColor.textPrimary(),
)
Text(
text = entry.description,
style = EnsuTypography.body,
- color = EnsuColor.textMuted()
+ color = EnsuColor.textMuted(),
)
}
}
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewService.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewService.kt
index bb510eb386..911252c6f7 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewService.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/whatsnew/WhatsNewService.kt
@@ -4,14 +4,15 @@ import android.content.Context
data class PendingWhatsNew(
val version: Int,
- val entries: List<WhatsNewEntry>
+ val entries: List<WhatsNewEntry>,
)
class WhatsNewService(context: Context) {
- private val preferences = context.getSharedPreferences(
- PREFERENCES_NAME,
- Context.MODE_PRIVATE
- )
+ private val preferences =
+ context.getSharedPreferences(
+ PREFERENCES_NAME,
+ Context.MODE_PRIVATE,
+ )
fun getPendingWhatsNew(): PendingWhatsNew? {
if (!preferences.contains(KEY_SEEN_VERSION)) {
@@ -29,14 +30,12 @@ class WhatsNewService(context: Context) {
return PendingWhatsNew(
version = WhatsNewContent.VERSION,
- entries = WhatsNewContent.entries
+ entries = WhatsNewContent.entries,
)
}
fun markSeen() {
- preferences.edit()
- .putInt(KEY_SEEN_VERSION, WhatsNewContent.VERSION)
- .apply()
+ preferences.edit().putInt(KEY_SEEN_VERSION, WhatsNewContent.VERSION).apply()
}
private companion object {
diff --git a/android/apps/ensu/app/src/test/java/io/ente/ensu/AttachmentInputTest.kt b/android/apps/ensu/app/src/test/java/io/ente/ensu/AttachmentInputTest.kt
index 965da64994..1c60d2c25e 100644
--- a/android/apps/ensu/app/src/test/java/io/ente/ensu/AttachmentInputTest.kt
+++ b/android/apps/ensu/app/src/test/java/io/ente/ensu/AttachmentInputTest.kt
@@ -21,24 +21,21 @@ class AttachmentInputTest {
fun rejectsInputPastTheLimit() {
val input = ByteArrayInputStream(byteArrayOf(1, 2, 3, 4, 5))
- assertThrows(IOException::class.java) {
- input.readAttachmentImageBytes(maxBytes = 4)
- }
+ assertThrows(IOException::class.java) { input.readAttachmentImageBytes(maxBytes = 4) }
}
@Test
fun stopsReadingAStreamThatDoesNotEnd() {
- val input = object : InputStream() {
- override fun read(): Int = 0
-
- override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
- buffer.fill(0, offset, offset + length)
- return length
+ val input =
+ object : InputStream() {
+ override fun read(): Int = 0
+
+ override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
+ buffer.fill(0, offset, offset + length)
+ return length
+ }
}
- }
- assertThrows(IOException::class.java) {
- input.readAttachmentImageBytes(maxBytes = 16)
- }
+ assertThrows(IOException::class.java) { input.readAttachmentImageBytes(maxBytes = 16) }
}
}
diff --git a/android/apps/ensu/rust/build.gradle.kts b/android/apps/ensu/rust/build.gradle.kts
index 85b278464b..69e00a7b50 100644
--- a/android/apps/ensu/rust/build.gradle.kts
+++ b/android/apps/ensu/rust/build.gradle.kts
@@ -19,83 +19,96 @@ fun capture(vararg cmd: String): String? = runCatching {
errorOutput = ByteArrayOutputStream()
}
out.toString().trim()
-}.getOrNull()
+}
+ .getOrNull()
fun connectedDeviceAbi(): String? {
val sdkRoot = System.getenv("ANDROID_HOME") ?: System.getenv("ANDROID_SDK_ROOT")
val adb = sdkRoot?.let { "$it/platform-tools/adb" } ?: "adb"
- val serial = System.getenv("ANDROID_SERIAL")?.takeIf { it.isNotBlank() }
- ?: capture(adb, "devices")?.lines()?.drop(1)
- ?.mapNotNull { l -> l.trim().takeIf { it.endsWith("\tdevice") }?.substringBefore('\t') }
- ?.singleOrNull()
- ?: return null
- return capture(adb, "-s", serial, "shell", "getprop", "ro.product.cpu.abi")
- ?.takeIf { it in knownAbis }
+ val serial =
+ System.getenv("ANDROID_SERIAL")?.takeIf { it.isNotBlank() }
+ ?: capture(adb, "devices")
+ ?.lines()
+ ?.drop(1)
+ ?.mapNotNull { l ->
+ l.trim().takeIf { it.endsWith("\tdevice") }?.substringBefore('\t')
+ }
+ ?.singleOrNull()
+ ?: return null
+ return capture(adb, "-s", serial, "shell", "getprop", "ro.product.cpu.abi")?.takeIf {
+ it in knownAbis
+ }
}
-fun hostAbi(): String = when (System.getProperty("os.arch")) {
- "aarch64", "arm64" -> "arm64-v8a"
- "x86_64", "amd64" -> "x86_64"
- else -> error("Unsupported host architecture: ${System.getProperty("os.arch")}")
-}
+fun hostAbi(): String =
+ when (System.getProperty("os.arch")) {
+ "aarch64",
+ "arm64" -> "arm64-v8a"
+ "x86_64",
+ "amd64" -> "x86_64"
+ else -> error("Unsupported host architecture: ${System.getProperty("os.arch")}")
+ }
fun ndkToolchain(ndkDir: java.io.File): java.io.File =
- ndkDir.resolve("toolchains/llvm/prebuilt")
- .listFiles { f -> f.isDirectory }
- ?.singleOrNull()
+ ndkDir.resolve("toolchains/llvm/prebuilt").listFiles { f -> f.isDirectory }?.singleOrNull()
?: error("Expected exactly one NDK host toolchain in $ndkDir/toolchains/llvm/prebuilt")
fun registerBuildRustJni(
taskName: String,
outputDir: Provider<Directory>,
resolveAbis: () -> List<String>,
-) = tasks.register(taskName) {
- val abis = resolveAbis()
-
- inputs.files(fileTree(file("../../../../rust")) { exclude("**/target/**") })
- inputs.file(file("scripts/build-rust.sh"))
- inputs.property("abis", abis)
- inputs.property("ndk", providers.provider { android.ndkVersion })
- outputs.dir(outputDir)
-
- doLast {
- val version = android.ndkVersion
- val ndkDir = runCatching { android.ndkDirectory }.getOrElse {
- error("NDK $version is not installed. Run: sdkmanager \"ndk;$version\"")
- }
- val toolchain = ndkToolchain(ndkDir)
-
- val outDir = outputDir.get().asFile
- outDir.deleteRecursively()
- outDir.mkdirs()
-
- exec {
- workingDir = file("scripts")
- commandLine(
- "bash",
- "./build-rust.sh",
- "--toolchain", toolchain.absolutePath,
- "--out-dir", outDir.absolutePath,
- *abis.toTypedArray(),
- )
- environment("ANDROID_NDK", ndkDir.absolutePath)
- environment("ANDROID_NDK_ROOT", ndkDir.absolutePath)
- environment("NDK_ROOT", ndkDir.absolutePath)
+) =
+ tasks.register(taskName) {
+ val abis = resolveAbis()
+
+ inputs.files(fileTree(file("../../../../rust")) { exclude("**/target/**") })
+ inputs.file(file("scripts/build-rust.sh"))
+ inputs.property("abis", abis)
+ inputs.property("ndk", providers.provider { android.ndkVersion })
+ outputs.dir(outputDir)
+
+ doLast {
+ val version = android.ndkVersion
+ val ndkDir = runCatching {
+ android.ndkDirectory
+ }.getOrElse { error("NDK $version is not installed. Run: sdkmanager \"ndk;$version\"") }
+ val toolchain = ndkToolchain(ndkDir)
+
+ val outDir = outputDir.get().asFile
+ outDir.deleteRecursively()
+ outDir.mkdirs()
+
+ exec {
+ workingDir = file("scripts")
+ commandLine(
+ "bash",
+ "./build-rust.sh",
+ "--toolchain",
+ toolchain.absolutePath,
+ "--out-dir",
+ outDir.absolutePath,
+ *abis.toTypedArray(),
+ )
+ environment("ANDROID_NDK", ndkDir.absolutePath)
+ environment("ANDROID_NDK_ROOT", ndkDir.absolutePath)
+ environment("NDK_ROOT", ndkDir.absolutePath)
+ }
}
}
-}
-val buildRustJniDebug = registerBuildRustJni(
- taskName = "buildRustJniDebug",
- outputDir = debugJniLibsDir,
- resolveAbis = { listOf(connectedDeviceAbi() ?: hostAbi()) },
-)
+val buildRustJniDebug =
+ registerBuildRustJni(
+ taskName = "buildRustJniDebug",
+ outputDir = debugJniLibsDir,
+ resolveAbis = { listOf(connectedDeviceAbi() ?: hostAbi()) },
+ )
-val buildRustJniRelease = registerBuildRustJni(
- taskName = "buildRustJniRelease",
- outputDir = releaseJniLibsDir,
- resolveAbis = { knownAbis },
-)
+val buildRustJniRelease =
+ registerBuildRustJni(
+ taskName = "buildRustJniRelease",
+ outputDir = releaseJniLibsDir,
+ resolveAbis = { knownAbis },
+ )
android {
namespace = "io.ente.ensu.rust"
@@ -105,9 +118,7 @@ android {
// the requirement explicit for local builds too.
ndkVersion = "27.3.13750724"
- defaultConfig {
- minSdk = 24
- }
+ defaultConfig { minSdk = 24 }
sourceSets["debug"].jniLibs.setSrcDirs(listOf(debugJniLibsDir))
sourceSets["release"].jniLibs.setSrcDirs(listOf(releaseJniLibsDir))
@@ -126,12 +137,9 @@ kotlin {
}
}
-tasks.matching { it.name == "preDebugBuild" }.configureEach {
- dependsOn(buildRustJniDebug)
-}
-tasks.matching { it.name == "preReleaseBuild" }.configureEach {
- dependsOn(buildRustJniRelease)
-}
+tasks.matching { it.name == "preDebugBuild" }.configureEach { dependsOn(buildRustJniDebug) }
+
+tasks.matching { it.name == "preReleaseBuild" }.configureEach { dependsOn(buildRustJniRelease) }
dependencies {
api("net.java.dev.jna:jna:5.18.1@aar")
diff --git a/android/build.gradle.kts b/android/build.gradle.kts
index 34e489efe8..c5ac95925e 100644
--- a/android/build.gradle.kts
+++ b/android/build.gradle.kts
@@ -27,12 +27,8 @@ allprojects {
ignoredBuildTypes.set(listOf("release"))
}
- tasks.withType<KtfmtBaseTask>().configureEach {
- exclude("**/io/ente/ensu/bindings/ensu.kt")
- }
- tasks.withType<Detekt>().configureEach {
- exclude("**/io/ente/ensu/bindings/ensu.kt")
- }
+ tasks.withType<KtfmtBaseTask>().configureEach { exclude("**/io/ente/ensu/bindings/ensu.kt") }
+ tasks.withType<Detekt>().configureEach { exclude("**/io/ente/ensu/bindings/ensu.kt") }
listOf("com.android.application", "com.android.library").forEach { id ->
pluginManager.withPlugin(id) {
diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts
index 7bbf84c681..7dab0f6a8d 100644
--- a/android/settings.gradle.kts
+++ b/android/settings.gradle.kts
@@ -20,9 +20,7 @@ dependencyResolutionManagement {
ivy {
name = "enteOnnxRuntimePackaging"
url = uri("https://github.com/ente/ort-packaging/releases/download")
- patternLayout {
- artifact("ort-[revision]/[artifact]-[revision].[ext]")
- }
+ patternLayout { artifact("ort-[revision]/[artifact]-[revision].[ext]") }
metadataSources { artifact() }
}
}
@@ -34,5 +32,7 @@ dependencyResolutionManagement {
rootProject.name = "android"
include(":ensu")
+
project(":ensu").projectDir = file("apps/ensu")
+
include(":ensu:app", ":ensu:rust")