From 864bdc6b6e17615cc0908f7d2a2aec8bf32e9186 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaroslav=20Bene=C5=A1?= Date: Thu, 26 Nov 2026 09:55:36 +0000 Subject: [PATCH] Add default instance selection, drawer switcher, and per-instance prefs --- .../java/eu/llembas/android/MainActivity.kt | 38 +++- .../android/assist/AssistController.kt | 65 ++++--- .../java/eu/llembas/android/auth/Instances.kt | 127 ++++++++++++- .../eu/llembas/android/share/ShareActivity.kt | 39 ++-- .../java/eu/llembas/android/ui/home/Drawer.kt | 176 +++++++++++++++++- .../android/ui/settings/SettingsScreen.kt | 95 ++++++++-- .../llembas/android/ui/signin/SignInScreen.kt | 30 ++- app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-hu/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-sk/strings.xml | 1 + app/src/main/res/values/strings.xml | 3 + .../eu/llembas/android/InstanceStoreTest.kt | 80 ++++++++ scripts/strings.py | 3 + 18 files changed, 598 insertions(+), 66 deletions(-) create mode 100644 app/src/test/java/eu/llembas/android/InstanceStoreTest.kt diff --git a/app/src/main/java/eu/llembas/android/MainActivity.kt b/app/src/main/java/eu/llembas/android/MainActivity.kt index 42d3910..7ad02c2 100644 --- a/app/src/main/java/eu/llembas/android/MainActivity.kt +++ b/app/src/main/java/eu/llembas/android/MainActivity.kt @@ -45,6 +45,7 @@ import eu.llembas.android.auth.Prefs import eu.llembas.android.push.Notifications import eu.llembas.android.push.Push import eu.llembas.android.ui.chat.ChatScreen +import eu.llembas.android.ui.files.FileCache import eu.llembas.android.ui.files.FilesScreen import eu.llembas.android.ui.home.ArchivedScreen import eu.llembas.android.ui.home.ChatsViewModel @@ -85,6 +86,9 @@ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) + if (savedInstanceState == null && intent?.getStringExtra(Notifications.EXTRA_INSTANCE).isNullOrBlank()) { + lifecycleScope.launch { lembas.instances.resetToDefault() } + } take(intent) followLanguage() // At most once a day, and only while Settings › About says so (update/ReleaseCheck.kt). @@ -189,6 +193,8 @@ class MainActivity : ComponentActivity() { val scope = rememberCoroutineScope() val chats: ChatsViewModel = viewModel() val list by chats.state.collectAsStateWithLifecycle() + val instances by lembas.instances.instances.collectAsState(initial = emptyList()) + val defaultInstance by lembas.instances.defaultInstance.collectAsState(initial = null) val entry by nav.currentBackStackEntryAsState() val route = entry?.destination?.route val current = entry?.arguments?.getString("id")?.takeIf { route == "chat/{id}" } @@ -206,8 +212,16 @@ class MainActivity : ComponentActivity() { // The account's language, which the app follows unless Settings › Language says // otherwise. Read once per instance in use; kept, so the next start has it at once. LaunchedEffect(instance.id) { + val cached = lembas.instances.prefs.first().forInstance(instance.id).accountLanguage + if (cached.isNotBlank()) { + lembas.instances.savePrefs { it.copy(accountLanguage = cached) } + } runCatching { lembas.instances.clientFor(instance).me() }.onSuccess { me -> - me.accountLanguage?.let { language -> lembas.instances.savePrefs { it.copy(accountLanguage = language) } } + me.accountLanguage?.let { language -> + lembas.instances.savePrefs { p -> + p.withInstance(instance.id) { it.copy(accountLanguage = language) }.copy(accountLanguage = language) + } + } } } // The list is read again each time the drawer opens, so a new title or a finished @@ -276,6 +290,16 @@ class MainActivity : ComponentActivity() { override fun settings() = over("settings") + override fun useInstance(instance: Instance) { + scope.launch { + drawer.close() + lembas.instances.use(instance.id) + FileCache.clear(this@MainActivity) + } + } + + override fun addInstance() = over("add") + override fun more() = chats.more() override fun retry() = chats.load() @@ -292,7 +316,15 @@ class MainActivity : ComponentActivity() { // The drawer opens by a swipe only from a chat: elsewhere the swipe is Back's. gesturesEnabled = drawer.isOpen || route == "new" || route == "new-agent" || route == "chat/{id}", drawerContent = { - DrawerContent(list, current, listOf(instance.name, instance.email).filter { it.isNotBlank() }.joinToString(" · "), actions) + DrawerContent( + list, + current, + listOf(instance.name, instance.email).filter { it.isNotBlank() }.joinToString(" · "), + actions, + instances = instances, + activeInstance = instance, + defaultInstanceId = defaultInstance?.id, + ) }, ) { NavHost(nav, startDestination = "new") { @@ -403,7 +435,7 @@ class MainActivity : ComponentActivity() { } // Signing in to one more instance makes it the one in use, which starts a // fresh navigation for it (the `key` above). - composable("add") { SignInScreen(onDone = { nav.popBackStack() }) } + composable("add") { SignInScreen(onDone = { nav.popBackStack() }, onCancel = { nav.popBackStack() }) } } } } diff --git a/app/src/main/java/eu/llembas/android/assist/AssistController.kt b/app/src/main/java/eu/llembas/android/assist/AssistController.kt index 022f30e..415f3d2 100644 --- a/app/src/main/java/eu/llembas/android/assist/AssistController.kt +++ b/app/src/main/java/eu/llembas/android/assist/AssistController.kt @@ -181,6 +181,9 @@ class AssistController( private var screenText: String? = null private var stt: Boolean? = null + /** The instance this assistant sheet speaks to (the default instance). */ + private var targetId: String? = null + /** The account's own default model, as the instance said it: what "Instance default" means. */ private var accountDefault: String? = null @@ -214,7 +217,7 @@ class AssistController( scope.launch { speaker.playing.collect { on -> _state.update { it.copy(speaking = on) } } } // Settings changed the assistant's model while this sheet lives: the next new chat has it. scope.launch { - context.lembas.instances.prefs.map { it.assistantModel }.distinctUntilChanged().drop(1).collect { chosen -> + context.lembas.instances.prefs.map { it.forInstance(targetId).assistantModel }.distinctUntilChanged().drop(1).collect { chosen -> ready() newChatModel = assistantModelFor(chosen, accountDefault, _state.value.models) ?: chosen.ifBlank { null } _state.update { if (it.chatId == null) it.copy(modelId = newChatModel, modelIsRef = false) else it } @@ -234,34 +237,39 @@ class AssistController( /** The choices kept in Settings, and which instance: nothing here leaves the phone. */ private suspend fun loadLocal() { val store = context.lembas.instances - val instance = store.current() + val instance = store.default() + targetId = instance?.id val prefs = store.prefs.first() + val own = prefs.forInstance(instance?.id) _state.update { it.copy( signedIn = instance != null, instanceName = instance?.name?.ifBlank { instance.base }.orEmpty(), voiceReply = prefs.readAloudSpoken, canReadNotifications = prefs.notificationSummaries && NotificationAccess.granted(context), - last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary } - ?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) }, + last = own.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary } + ?.let { id -> LastAssist(id, own.lastAssistTitle, own.lastAssistAt) }, ) } // Until the instance has said what it has, the choice in Settings stands as it is: a // question asked while the list could not be read still goes to the chosen model. - newChatModel = prefs.assistantModel.ifBlank { null } + newChatModel = own.assistantModel.ifBlank { null } } /** The instance's models and what it offers this account. */ private suspend fun loadRemote() { val store = context.lembas.instances val prefs = store.prefs.first() - val api = store.current()?.let { store.clientFor(it) } ?: return + val instance = store.default() ?: return + targetId = instance.id + val api = store.clientFor(instance) + val own = prefs.forInstance(instance.id) try { val me = api.me() val models = api.models() stt = me.speechToText accountDefault = me.defaultModel - val chosen = assistantModelFor(prefs.assistantModel, me.defaultModel, models) + val chosen = assistantModelFor(own.assistantModel, me.defaultModel, models) newChatModel = chosen _state.update { it.copy( @@ -338,7 +346,7 @@ class AssistController( scope.launch { try { _state.update { it.copy(busy = true, error = null) } - val text = context.lembas.instances.client()?.transcribe(wav, media = mediaFor())?.text.orEmpty() + val text = context.lembas.instances.defaultClient()?.transcribe(wav, media = mediaFor())?.text.orEmpty() _state.update { it.copy(busy = false) } if (text.isNotBlank()) ask(text, spoken = true) } catch (e: CancellationException) { @@ -450,7 +458,7 @@ class AssistController( * while the phone is locked: the recording stays on the phone until it is unlocked. */ private suspend fun writeDownAsSaid() { - val api = context.lembas.instances.client() ?: return + val api = context.lembas.instances.defaultClient() ?: return var sent = 0f while (scope.isActive) { delay(PARTIAL_EVERY_MS) @@ -552,7 +560,7 @@ class AssistController( } try { _state.update { it.copy(busy = true) } - val text = context.lembas.instances.client()?.transcribe(wav, media = mediaFor())?.text.orEmpty() + val text = context.lembas.instances.defaultClient()?.transcribe(wav, media = mediaFor())?.text.orEmpty() _state.update { it.copy(busy = false, heard = "") } if (text.isNotBlank()) askOrStop(text) else endConversation() } catch (e: Exception) { @@ -614,7 +622,9 @@ class AssistController( _state.update { it.copy(conversation = talking) } try { val store = context.lembas.instances - val api = store.client() ?: throw ApiException(401, "Not signed in.") + val instance = store.default() ?: throw ApiException(401, "Not signed in.") + targetId = instance.id + val api = store.clientFor(instance) val prefs = store.prefs.first() // A question typed the moment the sheet opened: the model is known first. ready() @@ -651,8 +661,10 @@ class AssistController( replyId = made.reply?.id ?: return@launch _state.update { it.copy(chatId = inChat) } if (!prefs.assistantTemporary) { - store.savePrefs { - it.copy(lastAssistChat = inChat, lastAssistTitle = question.take(120), lastAssistAt = System.currentTimeMillis()) + store.savePrefs { p -> + p.withInstance(targetId) { + it.copy(lastAssistChat = inChat, lastAssistTitle = question.take(120), lastAssistAt = System.currentTimeMillis()) + } } } } @@ -697,7 +709,13 @@ class AssistController( delay(TITLE_ASK_MS) val title = runCatching { api.chat(chatId).chat.title }.getOrNull().orEmpty() if (title.isNotBlank() && title != provisional) { - context.lembas.instances.savePrefs { if (it.lastAssistChat == chatId) it.copy(lastAssistTitle = title.take(120)) else it } + context.lembas.instances.savePrefs { p -> + if (p.forInstance(targetId).lastAssistChat == chatId) { + p.withInstance(targetId) { it.copy(lastAssistTitle = title.take(120)) } + } else { + p + } + } _state.update { s -> s.copy(last = s.last?.let { l -> if (l.chatId == chatId) l.copy(title = title.take(120)) else l }) } break } @@ -712,7 +730,7 @@ class AssistController( scope.launch { _state.update { it.copy(busy = true, error = null) } try { - val api = context.lembas.instances.client() ?: return@launch + val api = context.lembas.instances.defaultClient() ?: return@launch val detail = api.chat(last.chatId) val question = detail.messages.lastOrNull { it.isUser } val answer = detail.messages.lastOrNull { !it.isUser } @@ -730,7 +748,9 @@ class AssistController( } catch (e: Exception) { // A chat deleted since is simply not offered again. if (e is ApiException && e.status == 404) { - context.lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) } + context.lembas.instances.savePrefs { p -> + p.withInstance(targetId) { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) } + } _state.update { it.copy(last = null) } } else { _state.update { it.copy(error = context.explain(e)) } @@ -746,7 +766,7 @@ class AssistController( val chat = _state.value.chatId ?: return scope.launch { try { - context.lembas.instances.client()?.answer(chat, card.id, answer) + context.lembas.instances.defaultClient()?.answer(chat, card.id, answer) } catch (e: ApiException) { // First answer wins: a 409 is somebody answering elsewhere already. if (e.status != 409) _state.update { it.copy(error = context.explain(e)) } @@ -779,9 +799,9 @@ class AssistController( newChatModel = id _state.update { it.copy(modelId = id, modelIsRef = false) } scope.launch { - context.lembas.instances.savePrefs { it.copy(assistantModel = id) } + context.lembas.instances.savePrefs { p -> p.withInstance(targetId) { it.copy(assistantModel = id) } } val chat = _state.value.chatId ?: return@launch - runCatching { context.lembas.instances.client()?.updateChat(chat, JsonObject(mapOf("model" to JsonPrimitive(id)))) } + runCatching { context.lembas.instances.defaultClient()?.updateChat(chat, JsonObject(mapOf("model" to JsonPrimitive(id)))) } .onFailure { e -> _state.update { it.copy(error = context.explain(e)) } } } } @@ -813,7 +833,7 @@ class AssistController( // Never aloud over the lock screen: an answer is the account's. if (words.isBlank() || locked()) return false return try { - val api = context.lembas.instances.client() ?: return false + val api = context.lembas.instances.defaultClient() ?: return false speaker.playToEnd(api.speech(words, mediaFor()).audio) } catch (e: Exception) { _state.update { it.copy(error = context.explain(e)) } @@ -825,7 +845,10 @@ class AssistController( * start activities differently. */ fun appIntent(): Intent = Intent(context, MainActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) - .apply { _state.value.chatId?.let { putExtra(Notifications.EXTRA_CHAT, it) } } + .apply { + _state.value.chatId?.let { putExtra(Notifications.EXTRA_CHAT, it) } + targetId?.let { putExtra(Notifications.EXTRA_INSTANCE, it) } + } fun close() { following?.cancel() diff --git a/app/src/main/java/eu/llembas/android/auth/Instances.kt b/app/src/main/java/eu/llembas/android/auth/Instances.kt index 7d791b2..39fe6b8 100644 --- a/app/src/main/java/eu/llembas/android/auth/Instances.kt +++ b/app/src/main/java/eu/llembas/android/auth/Instances.kt @@ -65,8 +65,60 @@ object TokenCipher { private val Context.store by preferencesDataStore(name = "instances") private val INSTANCES = stringPreferencesKey("instances") private val ACTIVE = stringPreferencesKey("active") +private val DEFAULT = stringPreferencesKey("default") private val PREFS = stringPreferencesKey("prefs") +/** Choices kept per instance (assistant model, last assistant chat, account language). */ +@Serializable +data class PerInstancePrefs( + val assistantModel: String = "", + val lastAssistChat: String = "", + val lastAssistTitle: String = "", + val lastAssistAt: Long = 0, + val accountLanguage: String = "", +) + +/** + * Pure selection and mutation rules for [InstanceStore]: kept free of Android types so unit + * tests exercise default fallback, multi-account ids and removal directly. + */ +object InstanceLogic { + fun pickDefault(instances: List, defaultId: String?): Instance? = + instances.firstOrNull { it.id == defaultId } ?: instances.firstOrNull() + + fun pickActive(instances: List, activeId: String?, defaultId: String?): Instance? = + instances.firstOrNull { it.id == activeId } ?: pickDefault(instances, defaultId) + + /** Adding [added] replaces any existing entry with the same id, makes it active, and sets it + * as default only when no surviving default exists yet. */ + fun afterAdd( + instances: List, + added: Instance, + currentDefault: String?, + ): Triple, String, String> { + val next = instances.filter { it.id != added.id } + added + val keptDefault = next.firstOrNull { it.id == currentDefault }?.id ?: added.id + return Triple(next, added.id, keptDefault) + } + + /** Removing [removedId] promotes the surviving default (or first) for active, and the + * surviving active (or first) for default, or null when no instance remains. */ + fun afterRemove( + instances: List, + removedId: String, + currentActive: String?, + currentDefault: String?, + ): Triple, String?, String?> { + val remaining = instances.filter { it.id != removedId } + val nextDefault = remaining.firstOrNull { it.id == currentDefault }?.id + ?: remaining.firstOrNull { it.id == currentActive }?.id + ?: remaining.firstOrNull()?.id + val nextActive = remaining.firstOrNull { it.id == currentActive }?.id + ?: nextDefault + return Triple(remaining, nextActive, nextDefault) + } +} + /** * What the person chose in Settings, for this phone. [language]: "" the account's language (the * default), "system" the phone's, or a language's code -- see [eu.llembas.android.AppLanguage]. @@ -115,7 +167,35 @@ data class Prefs( val updateCheckedAt: Long = 0, /** The last version a notification announced, so it is announced once. */ val updateNotified: String = "", + /** Per-instance choices, keyed by [Instance.id]. */ + val perInstance: Map = emptyMap(), ) { + fun forInstance(id: String?): PerInstancePrefs = + id?.let { perInstance[it] } ?: PerInstancePrefs( + assistantModel = assistantModel, + lastAssistChat = lastAssistChat, + lastAssistTitle = lastAssistTitle, + lastAssistAt = lastAssistAt, + accountLanguage = accountLanguage, + ) + + fun withInstance(id: String?, change: (PerInstancePrefs) -> PerInstancePrefs): Prefs { + val updated = change(forInstance(id)) + return if (id == null) { + copy( + assistantModel = updated.assistantModel, + lastAssistChat = updated.lastAssistChat, + lastAssistTitle = updated.lastAssistTitle, + lastAssistAt = updated.lastAssistAt, + accountLanguage = updated.accountLanguage, + ) + } else { + copy(perInstance = perInstance + (id to updated)) + } + } + + fun withoutInstance(id: String): Prefs = if (id in perInstance) copy(perInstance = perInstance - id) else this + companion object { const val VOICE_LEMBAS = "lembas" const val VOICE_PHONE = "phone" @@ -129,9 +209,14 @@ class InstanceStore(private val context: Context) { prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList() } + val defaultInstance: Flow = context.store.data.map { prefs -> + val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList() + InstanceLogic.pickDefault(all, prefs[DEFAULT]) + } + val active: Flow = context.store.data.map { prefs -> val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList() - all.firstOrNull { it.id == prefs[ACTIVE] } ?: all.firstOrNull() + InstanceLogic.pickActive(all, prefs[ACTIVE], prefs[DEFAULT]) } val prefs: Flow = context.store.data.map { p -> @@ -140,8 +225,12 @@ class InstanceStore(private val context: Context) { suspend fun current(): Instance? = active.first() + suspend fun default(): Instance? = defaultInstance.first() + suspend fun client(): ApiClient? = current()?.let { clientFor(it) } + suspend fun defaultClient(): ApiClient? = default()?.let { clientFor(it) } + fun clientFor(instance: Instance): ApiClient = ApiClient(instance.base, TokenCipher.open(instance.sealedToken)) suspend fun add(base: String, name: String, email: String, token: String): Instance { @@ -153,9 +242,11 @@ class InstanceStore(private val context: Context) { sealedToken = TokenCipher.seal(token), ) context.store.edit { prefs -> - val all = prefs[INSTANCES]?.let { LembasJson.decodeFromString(listSerializer, it) } ?: emptyList() - prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, all.filter { it.id != instance.id } + instance) - prefs[ACTIVE] = instance.id + val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList() + val (next, activeId, defaultId) = InstanceLogic.afterAdd(all, instance, prefs[DEFAULT]) + prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, next) + prefs[ACTIVE] = activeId + prefs[DEFAULT] = defaultId } return instance } @@ -164,11 +255,33 @@ class InstanceStore(private val context: Context) { context.store.edit { it[ACTIVE] = id } } + suspend fun setDefault(id: String) { + context.store.edit { prefs -> + val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList() + if (all.any { it.id == id }) prefs[DEFAULT] = id + } + } + + /** On a cold start with no notification target, switch active back to the default instance. */ + suspend fun resetToDefault() { + context.store.edit { prefs -> + val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList() + InstanceLogic.pickDefault(all, prefs[DEFAULT])?.let { prefs[ACTIVE] = it.id } + } + } + suspend fun remove(id: String) { context.store.edit { prefs -> - val all = prefs[INSTANCES]?.let { LembasJson.decodeFromString(listSerializer, it) } ?: emptyList() - prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, all.filter { it.id != id }) - if (prefs[ACTIVE] == id) prefs.remove(ACTIVE) + val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList() + val (remaining, nextActive, nextDefault) = InstanceLogic.afterRemove(all, id, prefs[ACTIVE], prefs[DEFAULT]) + prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, remaining) + if (nextActive != null) prefs[ACTIVE] = nextActive else prefs.remove(ACTIVE) + if (nextDefault != null) prefs[DEFAULT] = nextDefault else prefs.remove(DEFAULT) + prefs[PREFS]?.let { raw -> + runCatching { LembasJson.decodeFromString(Prefs.serializer(), raw) }.getOrNull()?.let { current -> + prefs[PREFS] = LembasJson.encodeToString(Prefs.serializer(), current.withoutInstance(id)) + } + } } } diff --git a/app/src/main/java/eu/llembas/android/share/ShareActivity.kt b/app/src/main/java/eu/llembas/android/share/ShareActivity.kt index 1069625..6b615c6 100644 --- a/app/src/main/java/eu/llembas/android/share/ShareActivity.kt +++ b/app/src/main/java/eu/llembas/android/share/ShareActivity.kt @@ -91,12 +91,14 @@ class ShareActivity : } lifecycleScope.launch { val store = lembas.instances + val instance = store.default() val prefs = store.prefs.first() + val own = prefs.forInstance(instance?.id) state.update { it.copy( - signedIn = store.current() != null, - last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary } - ?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) }, + signedIn = instance != null, + last = own.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary } + ?.let { id -> LastAssist(id, own.lastAssistTitle, own.lastAssistAt) }, ) } } @@ -142,7 +144,7 @@ class ShareActivity : lifecycleScope.launch { try { turn() - val home = lembas.instances.client()?.files("/")?.path ?: return@launch + val home = lembas.instances.defaultClient()?.files("/")?.path ?: return@launch state.update { it.copy(folder = it.folder ?: home) } } catch (e: CancellationException) { throw e @@ -167,7 +169,7 @@ class ShareActivity : state.update { it.copy(sending = true, error = null) } lifecycleScope.launch { try { - val api = lembas.instances.client() ?: run { + val api = lembas.instances.defaultClient() ?: run { startActivity(Intent(this@ShareActivity, MainActivity::class.java)) finish() return@launch @@ -199,11 +201,12 @@ class ShareActivity : lifecycleScope.launch { try { val store = lembas.instances - val api = store.client() ?: run { + val instance = store.default() ?: run { startActivity(Intent(this@ShareActivity, MainActivity::class.java)) finish() return@launch } + val api = store.clientFor(instance) val now = state.value val into = if (toLast) now.last?.chatId else null // What a first try already uploaded for this chat is not uploaded again. @@ -223,23 +226,26 @@ class ShareActivity : val prefs = store.prefs.first() // The assistant's model while the instance still has it; a model that is // gone is not asked for (the instance's default answers instead). - val chosen = prefs.assistantModel + val chosen = prefs.forInstance(instance.id).assistantModel val gone = chosen.isNotBlank() && runCatching { api.models() }.getOrNull()?.let { it.named(chosen) == null } == true turn() val made = api.createChat(message, sent, model = chosen.takeIf { it.isNotBlank() && !gone }) - store.savePrefs { - it.copy( - lastAssistChat = made.chat.id, - lastAssistTitle = ask.ifBlank { now.text.ifBlank { now.files.firstOrNull()?.name.orEmpty() } }.take(120), - lastAssistAt = System.currentTimeMillis(), - ) + store.savePrefs { p -> + p.withInstance(instance.id) { + it.copy( + lastAssistChat = made.chat.id, + lastAssistTitle = ask.ifBlank { now.text.ifBlank { now.files.firstOrNull()?.name.orEmpty() } }.take(120), + lastAssistAt = System.currentTimeMillis(), + ) + } } made.chat.id } startActivity( Intent(this@ShareActivity, MainActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) - .putExtra(Notifications.EXTRA_CHAT, chatId), + .putExtra(Notifications.EXTRA_CHAT, chatId) + .putExtra(Notifications.EXTRA_INSTANCE, instance.id), ) finish() } catch (e: CancellationException) { @@ -247,7 +253,10 @@ class ShareActivity : } catch (e: Exception) { // The last chat deleted since: it is not offered again. if (e is ApiException && e.status == 404 && toLast) { - lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) } + val id = lembas.instances.default()?.id + lembas.instances.savePrefs { p -> + p.withInstance(id) { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) } + } state.update { it.copy(last = null) } } state.update { it.copy(sending = false, error = if (e is SharedRefused) filesSay(e) else explain(e)) } diff --git a/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt b/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt index cfe729e..4074ceb 100644 --- a/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt +++ b/app/src/main/java/eu/llembas/android/ui/home/Drawer.kt @@ -1,3 +1,5 @@ +@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) + package eu.llembas.android.ui.home import android.app.Application @@ -7,6 +9,7 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable 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.fillMaxHeight @@ -22,7 +25,9 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.DriveFileMove +import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Archive +import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.CreateNewFolder import androidx.compose.material.icons.filled.Delete @@ -39,6 +44,7 @@ import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Summarize import androidx.compose.material.icons.filled.Terminal +import androidx.compose.material.icons.filled.UnfoldMore import androidx.compose.material3.AlertDialog import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem @@ -46,6 +52,7 @@ import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface @@ -53,6 +60,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TextField import androidx.compose.material3.TextFieldDefaults +import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -83,6 +91,7 @@ import eu.llembas.android.api.ReplyFrame import eu.llembas.android.api.ReportsFrame import eu.llembas.android.api.SearchHit import eu.llembas.android.api.fit +import eu.llembas.android.auth.Instance import eu.llembas.android.lembas import eu.llembas.android.ui.explain import eu.llembas.android.ui.signin.refusal @@ -490,6 +499,8 @@ interface DrawerActions { fun archived() {} fun memory() {} fun settings() {} + fun useInstance(instance: Instance) {} + fun addInstance() {} fun more() {} fun retry() {} fun search(query: String) {} @@ -511,9 +522,13 @@ fun DrawerContent( today: LocalDate = LocalDate.now(), zone: ZoneId = ZoneId.systemDefault(), initialQuery: String = "", + instances: List = emptyList(), + activeInstance: Instance? = null, + defaultInstanceId: String? = null, ) { val palette = LocalPalette.current var query by rememberSaveable { mutableStateOf(initialQuery) } + var switchingInstance by remember { mutableStateOf(false) } LaunchedEffect(query) { actions.search(query) } val groups = remember(state.chats, state.folders, query, today) { groupChats(state.chats, query, today, zone, state.folders) } // The one dialog open at a time: a chat to file, a folder to name (new or renamed), one to delete. @@ -617,10 +632,74 @@ fun DrawerContent( } } HorizontalDivider(color = palette.border) - DrawerItem(Icons.Filled.Settings, stringResource(R.string.settings), subtitle = account.ifBlank { null }, onClick = actions::settings) + if (instances.isNotEmpty() && activeInstance != null) { + Row( + Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 4.dp) + .clip(RoundedCornerShape(20.dp)) + .clickable { switchingInstance = true } + .heightIn(min = 52.dp) + .padding(horizontal = 14.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Text( + activeInstance.name.ifBlank { activeInstance.base }, + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium, + color = palette.ink, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (activeInstance.email.isNotBlank()) { + Text( + activeInstance.email, + style = MaterialTheme.typography.bodySmall, + color = palette.inkMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + Spacer(Modifier.width(8.dp)) + Icon( + Icons.Filled.UnfoldMore, + contentDescription = stringResource(R.string.instance_switch), + tint = palette.inkMuted, + modifier = Modifier.size(20.dp), + ) + } + } + DrawerItem( + Icons.Filled.Settings, + stringResource(R.string.settings), + subtitle = if (instances.isEmpty()) account.ifBlank { null } else null, + onClick = actions::settings, + ) Spacer(Modifier.size(8.dp)) } } + if (switchingInstance) { + ModalBottomSheet( + onDismissRequest = { switchingInstance = false }, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + ) { + InstanceSwitcherSheet( + instances = instances, + activeId = activeInstance?.id, + defaultId = defaultInstanceId, + onPick = { picked -> + switchingInstance = false + if (picked.id != activeInstance?.id) actions.useInstance(picked) + }, + onAdd = { + switchingInstance = false + actions.addInstance() + }, + ) + } + } moving?.let { chat -> MoveDialog( chat, @@ -700,6 +779,101 @@ private data class FolderNaming(val folder: Folder? = null, val then: Chat? = nu /** What a chat's row can do: open it, and from its long-press menu Pin, Move to folder, Archive. */ private class ChatRowActions(val open: (String) -> Unit, val archive: (Chat) -> Unit, val pin: (Chat, Boolean) -> Unit, val move: (Chat) -> Unit) +@Composable +private fun InstanceSwitcherSheet( + instances: List, + activeId: String?, + defaultId: String?, + onPick: (Instance) -> Unit, + onAdd: () -> Unit, +) { + val palette = LocalPalette.current + LazyColumn(Modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 24.dp)) { + item { + Text( + stringResource(R.string.settings_instances), + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp), + ) + } + items(instances, key = { it.id }) { item -> + val inUse = item.id == activeId + val isDefault = item.id == defaultId + Row( + Modifier + .fillMaxWidth() + .clickable { onPick(item) } + .heightIn(min = 64.dp) + .padding(horizontal = 24.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + item.name.ifBlank { item.base }, + style = MaterialTheme.typography.bodyLarge, + color = palette.ink, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + if (isDefault) { + Spacer(Modifier.width(8.dp)) + Surface(color = palette.accentSoft, shape = RoundedCornerShape(8.dp)) { + Text( + stringResource(R.string.instance_default), + style = MaterialTheme.typography.labelSmall, + color = palette.accent, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + ) + } + } + } + if (item.email.isNotBlank()) { + Text( + item.email, + style = MaterialTheme.typography.bodyMedium, + color = palette.inkMuted, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Text( + item.base, + style = MaterialTheme.typography.bodySmall, + color = palette.inkFaint, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + if (inUse) { + Spacer(Modifier.width(12.dp)) + Icon( + Icons.Filled.CheckCircle, + contentDescription = stringResource(R.string.instance_in_use), + tint = palette.accent, + ) + } + } + } + item { + HorizontalDivider(color = palette.border, modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp)) + Row( + Modifier + .fillMaxWidth() + .clickable(onClick = onAdd) + .heightIn(min = 56.dp) + .padding(horizontal = 24.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Icon(Icons.Filled.Add, contentDescription = null, tint = palette.accent) + Spacer(Modifier.width(16.dp)) + Text(stringResource(R.string.add_instance), style = MaterialTheme.typography.bodyLarge, color = palette.ink) + } + } + } +} + private fun LazyListScope.section(title: Int, chats: List, current: String?, actions: ChatRowActions, key: String = "c") { if (chats.isEmpty()) return item(key = "h$title") { diff --git a/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt b/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt index 3725e71..02f55e4 100644 --- a/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/settings/SettingsScreen.kt @@ -43,6 +43,7 @@ import androidx.compose.material.icons.filled.Hearing import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Mic +import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.MyLocation import androidx.compose.material.icons.filled.Navigation import androidx.compose.material.icons.filled.Notifications @@ -54,11 +55,14 @@ import androidx.compose.material.icons.filled.RecordVoiceOver import androidx.compose.material.icons.filled.Science import androidx.compose.material.icons.filled.ScreenLockPortrait import androidx.compose.material.icons.filled.Security +import androidx.compose.material.icons.filled.Star import androidx.compose.material.icons.filled.SystemUpdate import androidx.compose.material.icons.filled.Timer import androidx.compose.material.icons.filled.Translate import androidx.compose.material.icons.filled.Tune import androidx.compose.material.icons.filled.Update +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -135,6 +139,7 @@ import kotlinx.coroutines.launch /** What the settings page does; every action has a do-nothing default for the screenshots. */ interface SettingsActions { fun use(instance: Instance) {} + fun setDefault(instance: Instance) {} fun add() {} /** The instance's MCP servers and their sign-ins. */ @@ -176,6 +181,7 @@ data class WakeTestShown(val running: Boolean = false, val done: Boolean = false data class SettingsState( val instances: List = emptyList(), val active: Instance? = null, + val defaultInstance: Instance? = null, val prefs: Prefs = Prefs(), val hasDistributor: Boolean = false, val pushNote: String? = null, @@ -217,6 +223,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> U val scope = rememberCoroutineScope() val instances by store.instances.collectAsState(initial = emptyList()) val active by store.active.collectAsState(initial = null) + val defaultInstance by store.defaultInstance.collectAsState(initial = null) val prefs by store.prefs.collectAsState(initial = Prefs()) val wakeState by WakeStatus.state.collectAsState() val assistantConnected by AssistLink.connected.collectAsState() @@ -231,11 +238,12 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> U } clock = SystemClock.elapsedRealtime() } - // The instance's models, for the assistant's: asked for each time Settings opens on an instance. + // The default instance's models, for the assistant's: asked for each time Settings opens on an instance. + val assistInstance = defaultInstance ?: active var models by remember { mutableStateOf(emptyList()) } - LaunchedEffect(active?.id) { + LaunchedEffect(assistInstance?.id) { models = try { - store.client()?.models().orEmpty() + assistInstance?.let { store.clientFor(it).models() }.orEmpty() } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -267,6 +275,10 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> U } } + override fun setDefault(instance: Instance) { + scope.launch { store.setDefault(instance.id) } + } + override fun add() = onAddInstance() override fun mcpServers() = onMcp() @@ -313,7 +325,10 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> U } override fun assistantModel(id: String) { - scope.launch { store.savePrefs { it.copy(assistantModel = id) } } + scope.launch { + val target = (store.default() ?: store.current())?.id + store.savePrefs { p -> p.withInstance(target) { it.copy(assistantModel = id) } } + } } override fun voiceInput(value: String) { @@ -437,6 +452,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> U SettingsState( instances = instances, active = active, + defaultInstance = defaultInstance, prefs = prefs, hasDistributor = distributors.isNotEmpty(), pushNote = pushNote, @@ -517,21 +533,41 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () - state.instances.forEachIndexed { i, instance -> if (i > 0) Rule() val inUse = instance.id == state.active?.id + val isDefault = instance.id == (state.defaultInstance?.id ?: state.instances.firstOrNull()?.id) + var menuOpen by remember(instance.id) { mutableStateOf(false) } Row( - Modifier.fillMaxWidth().clickable { actions.use(instance) }.heightIn(min = 72.dp).padding(horizontal = 16.dp, vertical = 12.dp), + Modifier + .fillMaxWidth() + .clickable { actions.use(instance) } + .heightIn(min = 72.dp) + .padding(start = 16.dp, end = 4.dp, top = 12.dp, bottom = 12.dp), verticalAlignment = Alignment.CenterVertically, ) { Initial(instance.name.ifBlank { instance.base }) Spacer(Modifier.width(16.dp)) Column(Modifier.weight(1f)) { - Text( - instance.name.ifBlank { - instance.base - }, - style = MaterialTheme.typography.bodyLarge, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + instance.name.ifBlank { + instance.base + }, + style = MaterialTheme.typography.bodyLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + if (isDefault) { + Spacer(Modifier.width(8.dp)) + Surface(color = palette.accentSoft, shape = RoundedCornerShape(8.dp)) { + Text( + stringResource(R.string.instance_default), + style = MaterialTheme.typography.labelSmall, + color = palette.accent, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + ) + } + } + } Text( instance.email, style = MaterialTheme.typography.bodyMedium, @@ -548,9 +584,34 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () - ) } if (inUse) { - Spacer(Modifier.width(12.dp)) + Spacer(Modifier.width(8.dp)) Icon(Icons.Filled.CheckCircle, contentDescription = stringResource(R.string.instance_in_use), tint = palette.accent) } + Box { + IconButton(onClick = { menuOpen = true }) { + Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more), tint = palette.inkMuted) + } + DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) { + if (!isDefault) { + DropdownMenuItem( + text = { Text(stringResource(R.string.instance_set_default)) }, + leadingIcon = { Icon(Icons.Filled.Star, contentDescription = null) }, + onClick = { + menuOpen = false + actions.setDefault(instance) + }, + ) + } + DropdownMenuItem( + text = { Text(stringResource(R.string.sign_out), color = palette.danger) }, + leadingIcon = { Icon(Icons.AutoMirrored.Filled.Logout, contentDescription = null, tint = palette.danger) }, + onClick = { + menuOpen = false + actions.signOut(instance) + }, + ) + } + } } } if (state.instances.isNotEmpty()) Rule() @@ -1207,7 +1268,8 @@ fun WakeChoices(which: WakeChoice, prefs: Prefs, onPick: ((SettingsActions) -> U */ @Composable private fun assistantModelLabel(state: SettingsState): String { - val chosen = state.prefs.assistantModel + val target = (state.defaultInstance ?: state.active)?.id + val chosen = state.prefs.forInstance(target).assistantModel val model = state.assistantModels.named(chosen) // While the list is not read yet, or could not be: the choice as it was saved. return when { @@ -1226,7 +1288,8 @@ private fun assistantModelLabel(state: SettingsState): String { @Composable fun AssistantModelChoices(state: SettingsState, onPick: (String) -> Unit) { // A choice saved before models had refs is an id: it still finds its model. - val chosen = state.assistantModels.named(state.prefs.assistantModel)?.key.orEmpty() + val target = (state.defaultInstance ?: state.active)?.id + val chosen = state.assistantModels.named(state.prefs.forInstance(target).assistantModel)?.key.orEmpty() val choices = listOf( Choice(INSTANCE_DEFAULT, stringResource(R.string.assistant_model_default), stringResource(R.string.assistant_model_default_line), chosen.isEmpty()), ) + state.assistantModels.distinctBy { it.key }.map { Choice(it.key, it.titleAmong(state.assistantModels), null, it.key == chosen) } diff --git a/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt b/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt index 078d9e5..54fa521 100644 --- a/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt +++ b/app/src/main/java/eu/llembas/android/ui/signin/SignInScreen.kt @@ -6,14 +6,17 @@ import android.app.Application import android.net.Uri import android.os.Build import androidx.browser.customtabs.CustomTabsIntent +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button @@ -22,8 +25,10 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable @@ -137,11 +142,13 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) { } @Composable -fun SignInScreen(onDone: () -> Unit = {}, model: SignInViewModel = viewModel()) { +fun SignInScreen(onDone: () -> Unit = {}, onCancel: (() -> Unit)? = null, model: SignInViewModel = viewModel()) { val state by model.state.collectAsStateWithLifecycle() LaunchedEffect(state) { if (state == SignInState.Done) onDone() } var address by rememberSaveable { mutableStateOf("") } val context = LocalContext.current + val knownBases by context.lembas.instances.instances.collectAsState(initial = emptyList()) + val distinctBases = knownBases.map { it.base }.distinct() Column( modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding().padding(24.dp), verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically), @@ -166,11 +173,28 @@ fun SignInScreen(onDone: () -> Unit = {}, model: SignInViewModel = viewModel()) keyboardActions = KeyboardActions(onGo = { if (address.isNotBlank()) model.start(address) }), modifier = Modifier.fillMaxWidth().widthIn(max = 420.dp), ) + if (distinctBases.isNotEmpty() && onCancel != null) { + Row( + modifier = Modifier.widthIn(max = 420.dp).horizontalScroll(rememberScrollState()), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + distinctBases.forEach { base -> + OutlinedButton(onClick = { address = base }) { + Text(base.removePrefix("https://").removePrefix("http://")) + } + } + } + } if (s is SignInState.Failed) { Text(s.message, color = MaterialTheme.colorScheme.error, modifier = Modifier.widthIn(max = 420.dp)) } - Button(onClick = { model.start(address) }, enabled = address.isNotBlank()) { - Text(stringResource(R.string.signin_continue)) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) { + if (onCancel != null) { + TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) } + } + Button(onClick = { model.start(address) }, enabled = address.isNotBlank()) { + Text(stringResource(R.string.signin_continue)) + } } } diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index e55adfe..f72b106 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -463,6 +463,7 @@ Instance Odhlásit se Přidat instanci + Výchozí Vzhled Podle systému Moria (temná) diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 6759b73..e8a01c1 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -463,6 +463,7 @@ Instanzen Abmelden Instanz hinzufügen + Standard Design Wie das System Moria (dunkel) diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 6da9d66..dcc2831 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -463,6 +463,7 @@ Instancias Cerrar sesión Añadir una instancia + Predeterminado Tema Como el sistema Moria (oscuro) diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 9a2932b..f7ddb86 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -463,6 +463,7 @@ Instances Se déconnecter Ajouter une instance + Par défaut Thème Comme le système Moria (sombre) diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 93bdae4..119f865 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -463,6 +463,7 @@ Példányok Kijelentkezés Példány hozzáadása + Alapértelmezett Téma A rendszer szerint Moria (sötét) diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index eb06c4c..625ed6f 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -463,6 +463,7 @@ Istanze Esci Aggiungi un\'istanza + Predefinito Tema Come il sistema Moria (scuro) diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 63e71e4..7ff9e86 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -463,6 +463,7 @@ Instancje Wyloguj się Dodaj instancję + Domyślny Motyw Jak system Moria (ciemny) diff --git a/app/src/main/res/values-sk/strings.xml b/app/src/main/res/values-sk/strings.xml index 80640db..760f2cd 100644 --- a/app/src/main/res/values-sk/strings.xml +++ b/app/src/main/res/values-sk/strings.xml @@ -463,6 +463,7 @@ Inštancie Odhlásiť sa Pridať inštanciu + Predvolené Vzhľad Podľa systému Moria (tmavá) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index df57b36..cdf812d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -465,6 +465,9 @@ Instances Sign out Add an instance + Default + Set as default + Switch instance Theme As the system Moria (dark) diff --git a/app/src/test/java/eu/llembas/android/InstanceStoreTest.kt b/app/src/test/java/eu/llembas/android/InstanceStoreTest.kt new file mode 100644 index 0000000..e2502f3 --- /dev/null +++ b/app/src/test/java/eu/llembas/android/InstanceStoreTest.kt @@ -0,0 +1,80 @@ +package eu.llembas.android + +import eu.llembas.android.auth.Instance +import eu.llembas.android.auth.InstanceLogic +import eu.llembas.android.auth.Prefs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class InstanceStoreTest { + private val home = Instance(id = "alice@https://home.example", base = "https://home.example", name = "Home", email = "alice", sealedToken = "t1") + private val work = Instance(id = "bob@https://work.example", base = "https://work.example", name = "Work", email = "bob", sealedToken = "t2") + private val homeAlt = Instance(id = "carol@https://home.example", base = "https://home.example", name = "Home", email = "carol", sealedToken = "t3") + + @Test + fun firstAddedBecomesDefaultAndSecondKeepsIt() { + val (list1, active1, default1) = InstanceLogic.afterAdd(emptyList(), home, null) + assertEquals(listOf(home), list1) + assertEquals(home.id, active1) + assertEquals(home.id, default1) + + val (list2, active2, default2) = InstanceLogic.afterAdd(list1, work, default1) + assertEquals(listOf(home, work), list2) + assertEquals(work.id, active2) + assertEquals(home.id, default2) + + // Two accounts on the same server keep distinct ids. + val (list3, active3, default3) = InstanceLogic.afterAdd(list2, homeAlt, default2) + assertEquals(listOf(home, work, homeAlt), list3) + assertEquals(homeAlt.id, active3) + assertEquals(home.id, default3) + } + + @Test + fun activeFallsBackToDefaultThenFirst() { + val all = listOf(home, work) + assertEquals(work, InstanceLogic.pickActive(all, work.id, home.id)) + assertEquals(work, InstanceLogic.pickActive(all, null, work.id)) + assertEquals(home, InstanceLogic.pickActive(all, "gone", null)) + assertNull(InstanceLogic.pickActive(emptyList(), home.id, home.id)) + } + + @Test + fun removingDefaultOrActivePromotesSurvivingInstance() { + val all = listOf(home, work) + val (rem1, active1, default1) = InstanceLogic.afterRemove(all, home.id, home.id, home.id) + assertEquals(listOf(work), rem1) + assertEquals(work.id, active1) + assertEquals(work.id, default1) + + val (rem2, active2, default2) = InstanceLogic.afterRemove(all, work.id, work.id, home.id) + assertEquals(listOf(home), rem2) + assertEquals(home.id, active2) + assertEquals(home.id, default2) + + val (rem3, active3, default3) = InstanceLogic.afterRemove(listOf(home), home.id, home.id, home.id) + assertEquals(emptyList(), rem3) + assertNull(active3) + assertNull(default3) + } + + @Test + fun perInstancePrefsStayIsolated() { + val base = Prefs(assistantModel = "legacy-model", lastAssistChat = "legacy-chat") + // Unknown instance falls back to legacy flat fields. + assertEquals("legacy-model", base.forInstance(home.id).assistantModel) + + val updated = base + .withInstance(home.id) { it.copy(assistantModel = "fast-home", lastAssistChat = "c-home") } + .withInstance(work.id) { it.copy(assistantModel = "fast-work", lastAssistChat = "c-work") } + assertEquals("fast-home", updated.forInstance(home.id).assistantModel) + assertEquals("c-home", updated.forInstance(home.id).lastAssistChat) + assertEquals("fast-work", updated.forInstance(work.id).assistantModel) + assertEquals("c-work", updated.forInstance(work.id).lastAssistChat) + + val cleaned = updated.withoutInstance(home.id) + assertEquals("fast-work", cleaned.forInstance(work.id).assistantModel) + assertEquals("legacy-model", cleaned.forInstance(home.id).assistantModel) + } +} diff --git a/scripts/strings.py b/scripts/strings.py index 9399635..5ac713e 100755 --- a/scripts/strings.py +++ b/scripts/strings.py @@ -499,6 +499,9 @@ STRINGS: dict[str, str] = { "settings_instances": "Instances", "sign_out": "Sign out", "add_instance": "Add an instance", + "instance_default": "Default", + "instance_set_default": "Set as default", + "instance_switch": "Switch instance", "settings_theme": "Theme", "theme_system": "As the system", "theme_moria": "Moria (dark)",