From 7ae536e80dcd729d2d562ef5c5434aa9e3e509d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 8 Apr 2026 12:47:23 +0000 Subject: [PATCH 01/10] feat: add AI writing help to new post screen Add on-device AI writing assistance using ML Kit GenAI APIs (Rewriting, Proofreading) powered by Gemini Nano via Android AICore. Users can tap the sparkle button in the compose toolbar to access tone chips (Correct, Rephrase, Shorter, Elaborate, Friendly, Professional, More Direct, Punchy, + Emoji) that transform their post text. Results appear in a card with Use/Dismiss actions. - Play flavor: MLKitWritingAssistant using on-device Gemini Nano - F-Droid flavor: NoOpWritingAssistant stub (returns unavailable) - WritingAssistant interface for future DVM/NIP90 integration - AI button hidden on unsupported devices Also fixes pre-existing exhaustive when expression in DecryptAndIndexProcessor for GroupEventResult.Duplicate. https://claude.ai/code/session_01RbCYGrbbapRMike8WQy41F --- amethyst/build.gradle | 5 + .../service/ai/NoOpWritingAssistant.kt | 32 ++++ .../service/ai/WritingAssistantFactory.kt | 28 +++ .../amethyst/service/ai/WritingAssistant.kt | 61 ++++++ .../marmot/MarmotGroupEventsEoseManager.kt | 3 +- .../creators/aihelp/AiWritingHelpButton.kt | 55 ++++++ .../creators/aihelp/AiWritingHelpPanel.kt | 176 ++++++++++++++++++ .../loggedIn/DecryptAndIndexProcessor.kt | 4 + .../loggedIn/home/ShortNotePostScreen.kt | 22 +++ .../loggedIn/home/ShortNotePostViewModel.kt | 54 ++++++ amethyst/src/main/res/values/strings.xml | 13 ++ .../service/ai/MLKitWritingAssistant.kt | 156 ++++++++++++++++ .../service/ai/WritingAssistantFactory.kt | 27 +++ gradle/libs.versions.toml | 6 + 14 files changed, 641 insertions(+), 1 deletion(-) create mode 100644 amethyst/src/fdroid/java/com/vitorpamplona/amethyst/service/ai/NoOpWritingAssistant.kt create mode 100644 amethyst/src/fdroid/java/com/vitorpamplona/amethyst/service/ai/WritingAssistantFactory.kt create mode 100644 amethyst/src/main/java/com/vitorpamplona/amethyst/service/ai/WritingAssistant.kt create mode 100644 amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpButton.kt create mode 100644 amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt create mode 100644 amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/MLKitWritingAssistant.kt create mode 100644 amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/WritingAssistantFactory.kt diff --git a/amethyst/build.gradle b/amethyst/build.gradle index 57630fc71..f52cb777c 100644 --- a/amethyst/build.gradle +++ b/amethyst/build.gradle @@ -338,6 +338,11 @@ dependencies { // Google services model the translate text playImplementation libs.google.mlkit.translate + // On-device AI writing assistance (Gemini Nano via AICore) + playImplementation libs.google.mlkit.genai.proofreading + playImplementation libs.google.mlkit.genai.prompt + playImplementation libs.google.mlkit.genai.rewriting + // PushNotifications playImplementation platform(libs.firebase.bom) playImplementation libs.firebase.messaging diff --git a/amethyst/src/fdroid/java/com/vitorpamplona/amethyst/service/ai/NoOpWritingAssistant.kt b/amethyst/src/fdroid/java/com/vitorpamplona/amethyst/service/ai/NoOpWritingAssistant.kt new file mode 100644 index 000000000..665cce0c3 --- /dev/null +++ b/amethyst/src/fdroid/java/com/vitorpamplona/amethyst/service/ai/NoOpWritingAssistant.kt @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2025 Vitor Pamplona + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the + * Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.vitorpamplona.amethyst.service.ai + +class NoOpWritingAssistant : WritingAssistant { + override suspend fun checkAvailability(): WritingAssistantStatus = WritingAssistantStatus.Unavailable + + override suspend fun transform( + text: String, + tone: WritingTone, + ): WritingResult = WritingResult(text, text, tone) + + override fun close() {} +} diff --git a/amethyst/src/fdroid/java/com/vitorpamplona/amethyst/service/ai/WritingAssistantFactory.kt b/amethyst/src/fdroid/java/com/vitorpamplona/amethyst/service/ai/WritingAssistantFactory.kt new file mode 100644 index 000000000..bc5e51758 --- /dev/null +++ b/amethyst/src/fdroid/java/com/vitorpamplona/amethyst/service/ai/WritingAssistantFactory.kt @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Vitor Pamplona + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the + * Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.vitorpamplona.amethyst.service.ai + +import android.content.Context + +object WritingAssistantFactory { + @Suppress("UNUSED_PARAMETER") + fun create(context: Context): WritingAssistant = NoOpWritingAssistant() +} diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/ai/WritingAssistant.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/ai/WritingAssistant.kt new file mode 100644 index 000000000..e136ecba1 --- /dev/null +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/ai/WritingAssistant.kt @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Vitor Pamplona + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the + * Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.vitorpamplona.amethyst.service.ai + +import androidx.compose.runtime.Immutable + +interface WritingAssistant { + suspend fun checkAvailability(): WritingAssistantStatus + + suspend fun transform( + text: String, + tone: WritingTone, + ): WritingResult + + fun close() +} + +enum class WritingTone { + CORRECT, + REPHRASE, + SHORTER, + ELABORATE, + FRIENDLY, + PROFESSIONAL, + MORE_DIRECT, + PUNCHY, + EMOJIFY, +} + +sealed class WritingAssistantStatus { + data object Available : WritingAssistantStatus() + + data object Unavailable : WritingAssistantStatus() + + data object Downloading : WritingAssistantStatus() +} + +@Immutable +data class WritingResult( + val originalText: String, + val transformedText: String, + val tone: WritingTone, +) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/relayClient/reqCommand/account/marmot/MarmotGroupEventsEoseManager.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/relayClient/reqCommand/account/marmot/MarmotGroupEventsEoseManager.kt index 94a5248af..8647f9c01 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/relayClient/reqCommand/account/marmot/MarmotGroupEventsEoseManager.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/relayClient/reqCommand/account/marmot/MarmotGroupEventsEoseManager.kt @@ -73,7 +73,8 @@ class MarmotGroupEventsEoseManager( metadata ?.relays ?.mapNotNull { - com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer.normalizeOrNull(it) + com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer + .normalizeOrNull(it) }?.toSet() val relaysForGroup = if (!groupRelays.isNullOrEmpty()) groupRelays else fallbackRelays for (relay in relaysForGroup) { diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpButton.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpButton.kt new file mode 100644 index 000000000..c2e2a7b61 --- /dev/null +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpButton.kt @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2025 Vitor Pamplona + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the + * Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.vitorpamplona.amethyst.ui.note.creators.aihelp + +import androidx.compose.foundation.layout.height +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.AutoAwesome +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.vitorpamplona.amethyst.R +import com.vitorpamplona.amethyst.ui.stringRes + +@Composable +fun AiWritingHelpButton( + isActive: Boolean, + onClick: () -> Unit, +) { + IconButton( + onClick = { onClick() }, + ) { + Icon( + imageVector = Icons.Outlined.AutoAwesome, + contentDescription = stringRes(R.string.ai_writing_help), + modifier = Modifier.height(22.dp), + tint = + if (isActive) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onBackground + }, + ) + } +} diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt new file mode 100644 index 000000000..1d93cc6ed --- /dev/null +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2025 Vitor Pamplona + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the + * Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.vitorpamplona.amethyst.ui.note.creators.aihelp + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.expandVertically +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +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.draw.clip +import androidx.compose.ui.unit.dp +import com.vitorpamplona.amethyst.R +import com.vitorpamplona.amethyst.service.ai.WritingResult +import com.vitorpamplona.amethyst.service.ai.WritingTone +import com.vitorpamplona.amethyst.ui.stringRes + +@Composable +fun AiWritingHelpPanel( + isVisible: Boolean, + isProcessing: Boolean, + result: WritingResult?, + onToneSelected: (WritingTone) -> Unit, + onApply: () -> Unit, + onDismiss: () -> Unit, +) { + AnimatedVisibility( + visible = isVisible, + enter = expandVertically(), + exit = shrinkVertically(), + ) { + Column( + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 8.dp), + ) { + if (isProcessing) { + Box( + modifier = + Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), + contentAlignment = Alignment.Center, + ) { + CircularProgressIndicator(modifier = Modifier.size(24.dp)) + } + } + + result?.let { + AiResultCard( + result = it, + onApply = onApply, + onDismiss = onDismiss, + ) + } + + ToneChipRow(onToneSelected = onToneSelected) + } + } +} + +@Composable +private fun AiResultCard( + result: WritingResult, + onApply: () -> Unit, + onDismiss: () -> Unit, +) { + Column( + modifier = + Modifier + .fillMaxWidth() + .padding(vertical = 4.dp) + .clip(RoundedCornerShape(12.dp)) + .background(MaterialTheme.colorScheme.surfaceVariant) + .padding(12.dp), + ) { + Text( + text = result.transformedText, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = + Modifier + .fillMaxWidth() + .heightIn(max = 150.dp) + .verticalScroll(rememberScrollState()), + ) + + Row( + modifier = + Modifier + .fillMaxWidth() + .padding(top = 8.dp), + horizontalArrangement = Arrangement.End, + ) { + TextButton(onClick = onDismiss) { + Text(stringRes(R.string.ai_writing_dismiss)) + } + OutlinedButton(onClick = onApply) { + Text(stringRes(R.string.ai_writing_use_this)) + } + } + } +} + +@Composable +private fun ToneChipRow(onToneSelected: (WritingTone) -> Unit) { + val scrollState = rememberScrollState() + Row( + modifier = + Modifier + .horizontalScroll(scrollState) + .fillMaxWidth() + .padding(vertical = 4.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + WritingTone.entries.forEach { tone -> + FilterChip( + selected = false, + onClick = { onToneSelected(tone) }, + label = { Text(toneDisplayName(tone)) }, + ) + } + } +} + +@Composable +private fun toneDisplayName(tone: WritingTone): String = + when (tone) { + WritingTone.CORRECT -> stringRes(R.string.ai_tone_correct) + WritingTone.REPHRASE -> stringRes(R.string.ai_tone_rephrase) + WritingTone.SHORTER -> stringRes(R.string.ai_tone_shorter) + WritingTone.ELABORATE -> stringRes(R.string.ai_tone_elaborate) + WritingTone.FRIENDLY -> stringRes(R.string.ai_tone_friendly) + WritingTone.PROFESSIONAL -> stringRes(R.string.ai_tone_professional) + WritingTone.MORE_DIRECT -> stringRes(R.string.ai_tone_more_direct) + WritingTone.PUNCHY -> stringRes(R.string.ai_tone_punchy) + WritingTone.EMOJIFY -> stringRes(R.string.ai_tone_emojify) + } diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/DecryptAndIndexProcessor.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/DecryptAndIndexProcessor.kt index 8791601c1..c6f8fbf35 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/DecryptAndIndexProcessor.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/DecryptAndIndexProcessor.kt @@ -496,6 +496,10 @@ class GroupEventHandler( Log.d("GroupEventHandler", "Commit pending for group ${result.groupId}, epoch=${result.epoch}") } + is GroupEventResult.Duplicate -> { + Log.d("GroupEventHandler") { "Duplicate event for group ${result.groupId}" } + } + is GroupEventResult.Error -> { Log.w("GroupEventHandler") { "Error processing GroupEvent: ${result.message}" } } diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt index eed62305a..c0a116dfe 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt @@ -65,6 +65,7 @@ import androidx.core.net.toUri import androidx.core.util.Consumer import androidx.lifecycle.viewmodel.compose.viewModel import com.vitorpamplona.amethyst.R +import com.vitorpamplona.amethyst.service.ai.WritingAssistantStatus import com.vitorpamplona.amethyst.ui.actions.StrippingFailureDialog import com.vitorpamplona.amethyst.ui.actions.mediaServers.FileServerSelectionRow import com.vitorpamplona.amethyst.ui.actions.uploads.MAX_VOICE_RECORD_SECONDS @@ -82,6 +83,8 @@ import com.vitorpamplona.amethyst.ui.navigation.navs.Nav import com.vitorpamplona.amethyst.ui.navigation.topbars.PostingTopBar import com.vitorpamplona.amethyst.ui.note.BaseUserPicture import com.vitorpamplona.amethyst.ui.note.NoteCompose +import com.vitorpamplona.amethyst.ui.note.creators.aihelp.AiWritingHelpButton +import com.vitorpamplona.amethyst.ui.note.creators.aihelp.AiWritingHelpPanel import com.vitorpamplona.amethyst.ui.note.creators.contentWarning.ContentSensitivityExplainer import com.vitorpamplona.amethyst.ui.note.creators.contentWarning.MarkAsSensitiveButton import com.vitorpamplona.amethyst.ui.note.creators.emojiSuggestions.ShowEmojiSuggestionList @@ -144,6 +147,10 @@ fun ShortNotePostScreen( val context = LocalContext.current val activity = context.getActivity() + LaunchedEffect(Unit) { + postViewModel.initWritingAssistant(context) + } + LaunchedEffect(postViewModel, accountViewModel) { val baseReplyTo = baseReplyToId?.let { accountViewModel.getNoteIfExists(it) } val quote = quoteId?.let { accountViewModel.getNoteIfExists(it) } @@ -556,6 +563,15 @@ private fun NewPostScreenBody( ) } + AiWritingHelpPanel( + isVisible = postViewModel.wantsAiHelp, + isProcessing = postViewModel.isAiProcessing, + result = postViewModel.aiResult, + onToneSelected = postViewModel::requestAiTransform, + onApply = postViewModel::applyAiResult, + onDismiss = postViewModel::dismissAiResult, + ) + BottomRowActions(postViewModel) } } @@ -651,6 +667,12 @@ private fun BottomRowActions(postViewModel: ShortNotePostViewModel) { postViewModel.wantsInvoice = !postViewModel.wantsInvoice } } + + if (postViewModel.aiStatus is WritingAssistantStatus.Available) { + AiWritingHelpButton(postViewModel.wantsAiHelp) { + postViewModel.wantsAiHelp = !postViewModel.wantsAiHelp + } + } } } diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt index 6adf94284..2ec52b771 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt @@ -44,6 +44,11 @@ import com.vitorpamplona.amethyst.model.Account import com.vitorpamplona.amethyst.model.LocalCache import com.vitorpamplona.amethyst.model.Note import com.vitorpamplona.amethyst.model.User +import com.vitorpamplona.amethyst.service.ai.WritingAssistant +import com.vitorpamplona.amethyst.service.ai.WritingAssistantFactory +import com.vitorpamplona.amethyst.service.ai.WritingAssistantStatus +import com.vitorpamplona.amethyst.service.ai.WritingResult +import com.vitorpamplona.amethyst.service.ai.WritingTone import com.vitorpamplona.amethyst.service.location.LocationState import com.vitorpamplona.amethyst.service.uploads.CompressorQuality import com.vitorpamplona.amethyst.service.uploads.MediaCompressor @@ -291,6 +296,53 @@ open class ShortNotePostViewModel : // Anonymous Reply var wantsAnonymousPost by mutableStateOf(false) + // AI Writing Help + var wantsAiHelp by mutableStateOf(false) + var aiResult by mutableStateOf(null) + var aiStatus by mutableStateOf(WritingAssistantStatus.Unavailable) + var isAiProcessing by mutableStateOf(false) + private var writingAssistant: WritingAssistant? = null + + fun initWritingAssistant(context: android.content.Context) { + if (writingAssistant == null) { + writingAssistant = WritingAssistantFactory.create(context) + viewModelScope.launch(Dispatchers.IO) { + aiStatus = writingAssistant?.checkAvailability() ?: WritingAssistantStatus.Unavailable + } + } + } + + fun requestAiTransform(tone: WritingTone) { + val text = message.text.toString() + if (text.isBlank() || isAiProcessing) return + + isAiProcessing = true + aiResult = null + viewModelScope.launch(Dispatchers.IO) { + try { + val result = writingAssistant?.transform(text, tone) + aiResult = result + } catch (e: Exception) { + if (e is kotlinx.coroutines.CancellationException) throw e + aiResult = null + } finally { + isAiProcessing = false + } + } + } + + fun applyAiResult() { + aiResult?.let { + message.setTextAndPlaceCursorAtEnd(it.transformedText) + aiResult = null + draftTag.newVersion() + } + } + + fun dismissAiResult() { + aiResult = null + } + fun lnAddress(): String? = account.userProfile().lnAddress() fun hasLnAddress(): Boolean = account.userProfile().lnAddress() != null @@ -1372,6 +1424,8 @@ open class ShortNotePostViewModel : override fun onCleared() { super.onCleared() + writingAssistant?.close() + writingAssistant = null Log.d("Init") { "OnCleared: ${this.javaClass.simpleName}" } } diff --git a/amethyst/src/main/res/values/strings.xml b/amethyst/src/main/res/values/strings.xml index 985b4f915..3548f1e30 100644 --- a/amethyst/src/main/res/values/strings.xml +++ b/amethyst/src/main/res/values/strings.xml @@ -2199,4 +2199,17 @@ %1$d members removed from relay Relay join request Relay leave request + + AI Writing Help + Use This + Dismiss + Correct + Rephrase + Shorter + Elaborate + Friendly + Professional + More Direct + Punchy + + Emoji diff --git a/amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/MLKitWritingAssistant.kt b/amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/MLKitWritingAssistant.kt new file mode 100644 index 000000000..00d04436d --- /dev/null +++ b/amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/MLKitWritingAssistant.kt @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2025 Vitor Pamplona + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the + * Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.vitorpamplona.amethyst.service.ai + +import android.content.Context +import com.google.mlkit.genai.common.FeatureStatus +import com.google.mlkit.genai.proofreading.ProofreaderOptions +import com.google.mlkit.genai.proofreading.Proofreading +import com.google.mlkit.genai.proofreading.ProofreadingRequest +import com.google.mlkit.genai.rewriting.Rewriter +import com.google.mlkit.genai.rewriting.RewriterOptions +import com.google.mlkit.genai.rewriting.Rewriting +import com.google.mlkit.genai.rewriting.RewritingRequest +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +class MLKitWritingAssistant( + private val context: Context, +) : WritingAssistant { + private var rewriters = mutableMapOf() + private var proofreader = + Proofreading.getClient( + ProofreaderOptions + .builder(context) + .setInputType(ProofreaderOptions.InputType.KEYBOARD) + .setLanguage(ProofreaderOptions.Language.ENGLISH) + .build(), + ) + + private fun getRewriter( + @RewriterOptions.OutputType outputType: Int, + ): Rewriter = + rewriters.getOrPut(outputType) { + Rewriting.getClient( + RewriterOptions + .builder(context) + .setOutputType(outputType) + .setLanguage(RewriterOptions.Language.ENGLISH) + .build(), + ) + } + + override suspend fun checkAvailability(): WritingAssistantStatus = + withContext(Dispatchers.IO) { + try { + val status = getRewriter(RewriterOptions.OutputType.REPHRASE).checkFeatureStatus().get() + when (status) { + FeatureStatus.AVAILABLE -> { + WritingAssistantStatus.Available + } + + FeatureStatus.DOWNLOADING -> { + WritingAssistantStatus.Downloading + } + + else -> { + WritingAssistantStatus.Unavailable + } + } + } catch (e: Exception) { + WritingAssistantStatus.Unavailable + } + } + + override suspend fun transform( + text: String, + tone: WritingTone, + ): WritingResult { + val transformedText = + when (tone) { + WritingTone.CORRECT -> { + proofread(text) + } + + WritingTone.REPHRASE -> { + rewrite(text, RewriterOptions.OutputType.REPHRASE) + } + + WritingTone.SHORTER -> { + rewrite(text, RewriterOptions.OutputType.SHORTEN) + } + + WritingTone.ELABORATE -> { + rewrite(text, RewriterOptions.OutputType.ELABORATE) + } + + WritingTone.FRIENDLY -> { + rewrite(text, RewriterOptions.OutputType.FRIENDLY) + } + + WritingTone.PROFESSIONAL -> { + rewrite(text, RewriterOptions.OutputType.PROFESSIONAL) + } + + WritingTone.EMOJIFY -> { + rewrite(text, RewriterOptions.OutputType.EMOJIFY) + } + + WritingTone.MORE_DIRECT -> { + rewrite(text, RewriterOptions.OutputType.PROFESSIONAL) + } + + WritingTone.PUNCHY -> { + rewrite(text, RewriterOptions.OutputType.SHORTEN) + } + } + + return WritingResult( + originalText = text, + transformedText = transformedText, + tone = tone, + ) + } + + private suspend fun rewrite( + text: String, + @RewriterOptions.OutputType outputType: Int, + ): String = + withContext(Dispatchers.IO) { + val rewriter = getRewriter(outputType) + val request = RewritingRequest.builder(text).build() + val result = rewriter.runInference(request).get() + result.results.firstOrNull()?.text ?: text + } + + private suspend fun proofread(text: String): String = + withContext(Dispatchers.IO) { + val request = ProofreadingRequest.builder(text).build() + val result = proofreader.runInference(request).get() + result.results.firstOrNull()?.text ?: text + } + + override fun close() { + rewriters.values.forEach { it.close() } + rewriters.clear() + proofreader.close() + } +} diff --git a/amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/WritingAssistantFactory.kt b/amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/WritingAssistantFactory.kt new file mode 100644 index 000000000..86525c2d9 --- /dev/null +++ b/amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/WritingAssistantFactory.kt @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Vitor Pamplona + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the + * Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.vitorpamplona.amethyst.service.ai + +import android.content.Context + +object WritingAssistantFactory { + fun create(context: Context): WritingAssistant = MLKitWritingAssistant(context) +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 60485652c..0c0cc62f9 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -30,6 +30,9 @@ kotlin = "2.3.20" kotlinxCollectionsImmutable = "0.4.0" kotlinxCoroutinesCore = "1.10.2" kotlinxSerialization = "1.10.0" +genaiProofreading = "1.0.0-beta1" +genaiPrompt = "1.0.0-beta2" +genaiRewriting = "1.0.0-beta1" languageId = "17.0.6" lifecycleRuntimeKtx = "2.10.0" lightcompressor-enhanced = "1.8.1" @@ -134,6 +137,9 @@ jetbrains-compose-runtime = { module = "org.jetbrains.compose.runtime:runtime", jetbrains-compose-ui = { module = "org.jetbrains.compose.ui:ui", version.ref = "jetbrainsCompose" } jetbrains-compose-ui-tooling = { module = "org.jetbrains.compose.ui:ui-tooling", version.ref = "jetbrainsCompose" } jetbrains-compose-ui-tooling-preview = { module = "org.jetbrains.compose.ui:ui-tooling-preview", version.ref = "jetbrainsCompose" } +google-mlkit-genai-proofreading = { group = "com.google.mlkit", name = "genai-proofreading", version.ref = "genaiProofreading" } +google-mlkit-genai-prompt = { group = "com.google.mlkit", name = "genai-prompt", version.ref = "genaiPrompt" } +google-mlkit-genai-rewriting = { group = "com.google.mlkit", name = "genai-rewriting", version.ref = "genaiRewriting" } google-mlkit-language-id = { group = "com.google.mlkit", name = "language-id", version.ref = "languageId" } google-mlkit-translate = { group = "com.google.mlkit", name = "translate", version.ref = "translate" } jackson-module-kotlin = { group = "com.fasterxml.jackson.module", name = "jackson-module-kotlin", version.ref = "jacksonModuleKotlin" } From 5ed66fd6992a39bd7adee6fda1c7c35d7005a1ed Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 8 Apr 2026 14:42:03 +0000 Subject: [PATCH 02/10] feat: auto-detect language for AI writing help Use ML Kit language identification to detect the post's language before transforming. Maps detected BCP-47 tags to the 7 supported languages (English, Japanese, Korean, German, French, Italian, Spanish). Falls back to English for unsupported languages. Rewriter and proofreader clients are cached per language+outputType combination. https://claude.ai/code/session_01RbCYGrbbapRMike8WQy41F --- .../service/ai/MLKitWritingAssistant.kt | 135 ++++++++++-------- 1 file changed, 74 insertions(+), 61 deletions(-) diff --git a/amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/MLKitWritingAssistant.kt b/amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/MLKitWritingAssistant.kt index 00d04436d..fec041625 100644 --- a/amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/MLKitWritingAssistant.kt +++ b/amethyst/src/play/java/com/vitorpamplona/amethyst/service/ai/MLKitWritingAssistant.kt @@ -21,7 +21,9 @@ package com.vitorpamplona.amethyst.service.ai import android.content.Context +import com.google.android.gms.tasks.Tasks import com.google.mlkit.genai.common.FeatureStatus +import com.google.mlkit.genai.proofreading.Proofreader import com.google.mlkit.genai.proofreading.ProofreaderOptions import com.google.mlkit.genai.proofreading.Proofreading import com.google.mlkit.genai.proofreading.ProofreadingRequest @@ -29,31 +31,44 @@ import com.google.mlkit.genai.rewriting.Rewriter import com.google.mlkit.genai.rewriting.RewriterOptions import com.google.mlkit.genai.rewriting.Rewriting import com.google.mlkit.genai.rewriting.RewritingRequest +import com.vitorpamplona.amethyst.service.lang.LanguageTranslatorService import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class MLKitWritingAssistant( private val context: Context, ) : WritingAssistant { - private var rewriters = mutableMapOf() - private var proofreader = - Proofreading.getClient( - ProofreaderOptions - .builder(context) - .setInputType(ProofreaderOptions.InputType.KEYBOARD) - .setLanguage(ProofreaderOptions.Language.ENGLISH) - .build(), - ) + private var rewriters = mutableMapOf() + private var proofreaders = mutableMapOf() + + private fun rewriterCacheKey( + @RewriterOptions.OutputType outputType: Int, + @RewriterOptions.Language language: Int, + ): Long = (outputType.toLong() shl 32) or language.toLong() private fun getRewriter( @RewriterOptions.OutputType outputType: Int, + @RewriterOptions.Language language: Int, ): Rewriter = - rewriters.getOrPut(outputType) { + rewriters.getOrPut(rewriterCacheKey(outputType, language)) { Rewriting.getClient( RewriterOptions .builder(context) .setOutputType(outputType) - .setLanguage(RewriterOptions.Language.ENGLISH) + .setLanguage(language) + .build(), + ) + } + + private fun getProofreader( + @ProofreaderOptions.Language language: Int, + ): Proofreader = + proofreaders.getOrPut(language) { + Proofreading.getClient( + ProofreaderOptions + .builder(context) + .setInputType(ProofreaderOptions.InputType.KEYBOARD) + .setLanguage(language) .build(), ) } @@ -61,19 +76,12 @@ class MLKitWritingAssistant( override suspend fun checkAvailability(): WritingAssistantStatus = withContext(Dispatchers.IO) { try { - val status = getRewriter(RewriterOptions.OutputType.REPHRASE).checkFeatureStatus().get() + val rewriter = getRewriter(RewriterOptions.OutputType.REPHRASE, RewriterOptions.Language.ENGLISH) + val status = rewriter.checkFeatureStatus().get() when (status) { - FeatureStatus.AVAILABLE -> { - WritingAssistantStatus.Available - } - - FeatureStatus.DOWNLOADING -> { - WritingAssistantStatus.Downloading - } - - else -> { - WritingAssistantStatus.Unavailable - } + FeatureStatus.AVAILABLE -> WritingAssistantStatus.Available + FeatureStatus.DOWNLOADING -> WritingAssistantStatus.Downloading + else -> WritingAssistantStatus.Unavailable } } catch (e: Exception) { WritingAssistantStatus.Unavailable @@ -84,43 +92,18 @@ class MLKitWritingAssistant( text: String, tone: WritingTone, ): WritingResult { + val language = detectLanguage(text) val transformedText = when (tone) { - WritingTone.CORRECT -> { - proofread(text) - } - - WritingTone.REPHRASE -> { - rewrite(text, RewriterOptions.OutputType.REPHRASE) - } - - WritingTone.SHORTER -> { - rewrite(text, RewriterOptions.OutputType.SHORTEN) - } - - WritingTone.ELABORATE -> { - rewrite(text, RewriterOptions.OutputType.ELABORATE) - } - - WritingTone.FRIENDLY -> { - rewrite(text, RewriterOptions.OutputType.FRIENDLY) - } - - WritingTone.PROFESSIONAL -> { - rewrite(text, RewriterOptions.OutputType.PROFESSIONAL) - } - - WritingTone.EMOJIFY -> { - rewrite(text, RewriterOptions.OutputType.EMOJIFY) - } - - WritingTone.MORE_DIRECT -> { - rewrite(text, RewriterOptions.OutputType.PROFESSIONAL) - } - - WritingTone.PUNCHY -> { - rewrite(text, RewriterOptions.OutputType.SHORTEN) - } + WritingTone.CORRECT -> proofread(text, language) + WritingTone.REPHRASE -> rewrite(text, RewriterOptions.OutputType.REPHRASE, language) + WritingTone.SHORTER -> rewrite(text, RewriterOptions.OutputType.SHORTEN, language) + WritingTone.ELABORATE -> rewrite(text, RewriterOptions.OutputType.ELABORATE, language) + WritingTone.FRIENDLY -> rewrite(text, RewriterOptions.OutputType.FRIENDLY, language) + WritingTone.PROFESSIONAL -> rewrite(text, RewriterOptions.OutputType.PROFESSIONAL, language) + WritingTone.EMOJIFY -> rewrite(text, RewriterOptions.OutputType.EMOJIFY, language) + WritingTone.MORE_DIRECT -> rewrite(text, RewriterOptions.OutputType.PROFESSIONAL, language) + WritingTone.PUNCHY -> rewrite(text, RewriterOptions.OutputType.SHORTEN, language) } return WritingResult( @@ -130,19 +113,34 @@ class MLKitWritingAssistant( ) } + private suspend fun detectLanguage(text: String): Int = + withContext(Dispatchers.IO) { + try { + val langTag = Tasks.await(LanguageTranslatorService.identifyLanguage(text)) + mapLanguageTag(langTag) + } catch (e: Exception) { + RewriterOptions.Language.ENGLISH + } + } + private suspend fun rewrite( text: String, @RewriterOptions.OutputType outputType: Int, + @RewriterOptions.Language language: Int, ): String = withContext(Dispatchers.IO) { - val rewriter = getRewriter(outputType) + val rewriter = getRewriter(outputType, language) val request = RewritingRequest.builder(text).build() val result = rewriter.runInference(request).get() result.results.firstOrNull()?.text ?: text } - private suspend fun proofread(text: String): String = + private suspend fun proofread( + text: String, + @ProofreaderOptions.Language language: Int, + ): String = withContext(Dispatchers.IO) { + val proofreader = getProofreader(language) val request = ProofreadingRequest.builder(text).build() val result = proofreader.runInference(request).get() result.results.firstOrNull()?.text ?: text @@ -151,6 +149,21 @@ class MLKitWritingAssistant( override fun close() { rewriters.values.forEach { it.close() } rewriters.clear() - proofreader.close() + proofreaders.values.forEach { it.close() } + proofreaders.clear() + } + + companion object { + fun mapLanguageTag(tag: String?): Int = + when (tag?.lowercase()?.take(2)) { + "en" -> RewriterOptions.Language.ENGLISH + "ja" -> RewriterOptions.Language.JAPANESE + "ko" -> RewriterOptions.Language.KOREAN + "de" -> RewriterOptions.Language.GERMAN + "fr" -> RewriterOptions.Language.FRENCH + "it" -> RewriterOptions.Language.ITALIAN + "es" -> RewriterOptions.Language.SPANISH + else -> RewriterOptions.Language.ENGLISH + } } } From e6741410546a0dc8a974c669de0c883083b87b70 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 8 Apr 2026 15:52:18 +0000 Subject: [PATCH 03/10] feat: add mock writing assistant for UI testing Temporary MockWritingAssistant that returns fake transformed text after a short delay. Enabled via useMockAi flag in ShortNotePostViewModel. Allows testing the AI writing help UI on devices without Gemini Nano. TODO: Set useMockAi = false before shipping. https://claude.ai/code/session_01RbCYGrbbapRMike8WQy41F --- .../service/ai/MockWritingAssistant.kt | 97 +++++++++++++++++++ .../loggedIn/home/ShortNotePostViewModel.kt | 11 ++- 2 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 amethyst/src/main/java/com/vitorpamplona/amethyst/service/ai/MockWritingAssistant.kt diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/service/ai/MockWritingAssistant.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/ai/MockWritingAssistant.kt new file mode 100644 index 000000000..8945613fe --- /dev/null +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/service/ai/MockWritingAssistant.kt @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2025 Vitor Pamplona + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the + * Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +package com.vitorpamplona.amethyst.service.ai + +import kotlinx.coroutines.delay + +/** + * TODO: Remove before shipping. Debug-only mock for testing the AI writing help UI + * on devices without Gemini Nano / AICore support. + */ +class MockWritingAssistant : WritingAssistant { + override suspend fun checkAvailability(): WritingAssistantStatus = WritingAssistantStatus.Available + + override suspend fun transform( + text: String, + tone: WritingTone, + ): WritingResult { + delay(800) + + val transformed = + when (tone) { + WritingTone.CORRECT -> { + correctMock(text) + } + + WritingTone.REPHRASE -> { + "Here's another way to put it: $text" + } + + WritingTone.SHORTER -> { + text + .split(".") + .firstOrNull() + ?.trim() + ?.plus(".") ?: text + } + + WritingTone.ELABORATE -> { + "$text Furthermore, this point deserves deeper consideration and nuance." + } + + WritingTone.FRIENDLY -> { + "Hey! $text Hope that makes sense! :)" + } + + WritingTone.PROFESSIONAL -> { + "I would like to bring to your attention the following: $text" + } + + WritingTone.MORE_DIRECT -> { + text.replace("I think ", "").replace("maybe ", "").replace("perhaps ", "") + } + + WritingTone.PUNCHY -> { + text.uppercase().replace(".", "!") + } + + WritingTone.EMOJIFY -> { + "$text \uD83D\uDE80\uD83D\uDD25\u2728" + } + } + + return WritingResult( + originalText = text, + transformedText = transformed, + tone = tone, + ) + } + + private fun correctMock(text: String): String = + text + .replace("teh ", "the ") + .replace("dont ", "don't ") + .replace("cant ", "can't ") + .replace("wont ", "won't ") + .replace("i ", "I ") + + override fun close() {} +} diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt index 2ec52b771..cb892662c 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt @@ -44,6 +44,7 @@ import com.vitorpamplona.amethyst.model.Account import com.vitorpamplona.amethyst.model.LocalCache import com.vitorpamplona.amethyst.model.Note import com.vitorpamplona.amethyst.model.User +import com.vitorpamplona.amethyst.service.ai.MockWritingAssistant import com.vitorpamplona.amethyst.service.ai.WritingAssistant import com.vitorpamplona.amethyst.service.ai.WritingAssistantFactory import com.vitorpamplona.amethyst.service.ai.WritingAssistantStatus @@ -297,6 +298,9 @@ open class ShortNotePostViewModel : var wantsAnonymousPost by mutableStateOf(false) // AI Writing Help + // TODO: Remove useMockAi before shipping. Set to true to test UI without Gemini Nano. + private val useMockAi = true + var wantsAiHelp by mutableStateOf(false) var aiResult by mutableStateOf(null) var aiStatus by mutableStateOf(WritingAssistantStatus.Unavailable) @@ -305,7 +309,12 @@ open class ShortNotePostViewModel : fun initWritingAssistant(context: android.content.Context) { if (writingAssistant == null) { - writingAssistant = WritingAssistantFactory.create(context) + writingAssistant = + if (useMockAi) { + MockWritingAssistant() + } else { + WritingAssistantFactory.create(context) + } viewModelScope.launch(Dispatchers.IO) { aiStatus = writingAssistant?.checkAvailability() ?: WritingAssistantStatus.Unavailable } From 60d817b0c01b4bf8193fc8e34306b9344561ccc7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 8 Apr 2026 16:24:48 +0000 Subject: [PATCH 04/10] feat: move AI writing help to Application Preferences Replace the sparkle toggle button in the compose toolbar with a persistent setting in UI/Application Preferences. The new "Propose AI text improvements" setting (Always/Never) controls whether the tone chip row appears in the compose screen. When enabled and the device supports on-device AI, the tone chips show automatically below the text field. Removes the per-session toggle button from BottomRowActions. https://claude.ai/code/session_01RbCYGrbbapRMike8WQy41F --- .../amethyst/model/UiSettings.kt | 1 + .../amethyst/model/UiSettingsFlow.kt | 9 ++++++++ .../model/preferences/UISharedPreferences.kt | 3 +++ .../loggedIn/home/ShortNotePostScreen.kt | 10 +-------- .../loggedIn/home/ShortNotePostViewModel.kt | 10 ++++++++- .../loggedIn/settings/AppSettingsScreen.kt | 21 +++++++++++++++++++ amethyst/src/main/res/values/strings.xml | 2 ++ 7 files changed, 46 insertions(+), 10 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettings.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettings.kt index b0e6aae20..5b1b09323 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettings.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettings.kt @@ -38,6 +38,7 @@ data class UiSettings( val dontAskForNotificationPermissions: Boolean = false, val featureSet: FeatureSetType = FeatureSetType.SIMPLIFIED, val gallerySet: ProfileGalleryType = ProfileGalleryType.CLASSIC, + val automaticallyProposeAiImprovements: BooleanType = BooleanType.NEVER, ) enum class ThemeType( diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettingsFlow.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettingsFlow.kt index 467663f7e..3e0ec3222 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettingsFlow.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettingsFlow.kt @@ -38,6 +38,7 @@ class UiSettingsFlow( val dontAskForNotificationPermissions: MutableStateFlow = MutableStateFlow(false), val featureSet: MutableStateFlow = MutableStateFlow(FeatureSetType.SIMPLIFIED), val gallerySet: MutableStateFlow = MutableStateFlow(ProfileGalleryType.CLASSIC), + val automaticallyProposeAiImprovements: MutableStateFlow = MutableStateFlow(BooleanType.NEVER), ) { val listOfFlows: List> = listOf>( @@ -52,6 +53,7 @@ class UiSettingsFlow( dontAskForNotificationPermissions, featureSet, gallerySet, + automaticallyProposeAiImprovements, ) // emits at every change in any of the propertyes. @@ -69,6 +71,7 @@ class UiSettingsFlow( flows[8] as Boolean, flows[9] as FeatureSetType, flows[10] as ProfileGalleryType, + flows[11] as BooleanType, ) } @@ -85,6 +88,7 @@ class UiSettingsFlow( dontAskForNotificationPermissions.value, featureSet.value, gallerySet.value, + automaticallyProposeAiImprovements.value, ) fun update(torSettings: UiSettings): Boolean { @@ -134,6 +138,10 @@ class UiSettingsFlow( gallerySet.tryEmit(torSettings.gallerySet) any = true } + if (automaticallyProposeAiImprovements.value != torSettings.automaticallyProposeAiImprovements) { + automaticallyProposeAiImprovements.tryEmit(torSettings.automaticallyProposeAiImprovements) + any = true + } return any } @@ -164,6 +172,7 @@ class UiSettingsFlow( MutableStateFlow(uiSettings.dontAskForNotificationPermissions), MutableStateFlow(uiSettings.featureSet), MutableStateFlow(uiSettings.gallerySet), + MutableStateFlow(uiSettings.automaticallyProposeAiImprovements), ) } } diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/UISharedPreferences.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/UISharedPreferences.kt index 2b673eb36..5dfe07df3 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/UISharedPreferences.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/UISharedPreferences.kt @@ -102,6 +102,7 @@ class UiSharedPreferences( val UI_DONT_ASK_FOR_NOTIFICATION_PERMISSIONS = booleanPreferencesKey("ui.dont_ask_for_notification_permissions") val UI_FEATURE_SET = stringPreferencesKey("ui.feature_set") val UI_GALLERY_SET = stringPreferencesKey("ui.gallery_set") + val UI_PROPOSE_AI_IMPROVEMENTS = stringPreferencesKey("ui.propose_ai_improvements") suspend fun uiPreferences(context: Context): UiSettings? = try { @@ -120,6 +121,7 @@ class UiSharedPreferences( dontAskForNotificationPermissions = preferences[UI_DONT_ASK_FOR_NOTIFICATION_PERMISSIONS] ?: false, featureSet = preferences[UI_FEATURE_SET]?.let { FeatureSetType.valueOf(it) } ?: FeatureSetType.SIMPLIFIED, gallerySet = preferences[UI_GALLERY_SET]?.let { ProfileGalleryType.valueOf(it) } ?: ProfileGalleryType.CLASSIC, + automaticallyProposeAiImprovements = preferences[UI_PROPOSE_AI_IMPROVEMENTS]?.let { BooleanType.valueOf(it) } ?: BooleanType.NEVER, ) } catch (e: Exception) { if (e is CancellationException) throw e @@ -155,6 +157,7 @@ class UiSharedPreferences( preferences[UI_DONT_ASK_FOR_NOTIFICATION_PERMISSIONS] = sharedSettings.dontAskForNotificationPermissions preferences[UI_FEATURE_SET] = sharedSettings.featureSet.name preferences[UI_GALLERY_SET] = sharedSettings.gallerySet.name + preferences[UI_PROPOSE_AI_IMPROVEMENTS] = sharedSettings.automaticallyProposeAiImprovements.name } } catch (e: Exception) { if (e is CancellationException) throw e diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt index c0a116dfe..3758b8d01 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt @@ -65,7 +65,6 @@ import androidx.core.net.toUri import androidx.core.util.Consumer import androidx.lifecycle.viewmodel.compose.viewModel import com.vitorpamplona.amethyst.R -import com.vitorpamplona.amethyst.service.ai.WritingAssistantStatus import com.vitorpamplona.amethyst.ui.actions.StrippingFailureDialog import com.vitorpamplona.amethyst.ui.actions.mediaServers.FileServerSelectionRow import com.vitorpamplona.amethyst.ui.actions.uploads.MAX_VOICE_RECORD_SECONDS @@ -83,7 +82,6 @@ import com.vitorpamplona.amethyst.ui.navigation.navs.Nav import com.vitorpamplona.amethyst.ui.navigation.topbars.PostingTopBar import com.vitorpamplona.amethyst.ui.note.BaseUserPicture import com.vitorpamplona.amethyst.ui.note.NoteCompose -import com.vitorpamplona.amethyst.ui.note.creators.aihelp.AiWritingHelpButton import com.vitorpamplona.amethyst.ui.note.creators.aihelp.AiWritingHelpPanel import com.vitorpamplona.amethyst.ui.note.creators.contentWarning.ContentSensitivityExplainer import com.vitorpamplona.amethyst.ui.note.creators.contentWarning.MarkAsSensitiveButton @@ -564,7 +562,7 @@ private fun NewPostScreenBody( } AiWritingHelpPanel( - isVisible = postViewModel.wantsAiHelp, + isVisible = postViewModel.showAiPanel, isProcessing = postViewModel.isAiProcessing, result = postViewModel.aiResult, onToneSelected = postViewModel::requestAiTransform, @@ -667,12 +665,6 @@ private fun BottomRowActions(postViewModel: ShortNotePostViewModel) { postViewModel.wantsInvoice = !postViewModel.wantsInvoice } } - - if (postViewModel.aiStatus is WritingAssistantStatus.Available) { - AiWritingHelpButton(postViewModel.wantsAiHelp) { - postViewModel.wantsAiHelp = !postViewModel.wantsAiHelp - } - } } } diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt index cb892662c..fd0a25e32 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt @@ -41,6 +41,7 @@ import com.vitorpamplona.amethyst.commons.compose.replaceCurrentWord import com.vitorpamplona.amethyst.commons.compose.setTextAndPlaceCursorAtBeginning import com.vitorpamplona.amethyst.commons.model.nip30CustomEmojis.EmojiPackState.EmojiMedia import com.vitorpamplona.amethyst.model.Account +import com.vitorpamplona.amethyst.model.BooleanType import com.vitorpamplona.amethyst.model.LocalCache import com.vitorpamplona.amethyst.model.Note import com.vitorpamplona.amethyst.model.User @@ -301,12 +302,19 @@ open class ShortNotePostViewModel : // TODO: Remove useMockAi before shipping. Set to true to test UI without Gemini Nano. private val useMockAi = true - var wantsAiHelp by mutableStateOf(false) var aiResult by mutableStateOf(null) var aiStatus by mutableStateOf(WritingAssistantStatus.Unavailable) var isAiProcessing by mutableStateOf(false) private var writingAssistant: WritingAssistant? = null + val showAiPanel: Boolean + get() { + val prefEnabled = + accountViewModel.settings.uiSettingsFlow.automaticallyProposeAiImprovements.value == + BooleanType.ALWAYS + return prefEnabled && aiStatus is WritingAssistantStatus.Available + } + fun initWritingAssistant(context: android.content.Context) { if (writingAssistant == null) { writingAssistant = diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/AppSettingsScreen.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/AppSettingsScreen.kt index fc799a4a0..ace4f154d 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/AppSettingsScreen.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/settings/AppSettingsScreen.kt @@ -121,6 +121,7 @@ fun SettingsScreen(sharedPrefs: UiSettingsFlow) { ImmersiveScrollingChoice(sharedPrefs) FeatureSetChoice(sharedPrefs) GalleryChoice(sharedPrefs) + AiWritingHelpChoice(sharedPrefs) PushNotificationSettingsRow(sharedPrefs) } } @@ -366,6 +367,26 @@ fun GalleryChoice(sharedPrefs: UiSettingsFlow) { } } +@Composable +fun AiWritingHelpChoice(sharedPrefs: UiSettingsFlow) { + val aiIndex by sharedPrefs.automaticallyProposeAiImprovements.collectAsState() + + val booleanItems = + persistentListOf( + TitleExplainer(stringRes(ConnectivityType.ALWAYS.resourceId)), + TitleExplainer(stringRes(ConnectivityType.NEVER.resourceId)), + ) + + SettingsRow( + R.string.ai_writing_setting_title, + R.string.ai_writing_setting_description, + booleanItems, + aiIndex.screenCode, + ) { + sharedPrefs.automaticallyProposeAiImprovements.tryEmit(parseBooleanType(it)) + } +} + @Composable fun SettingsRow( name: Int, diff --git a/amethyst/src/main/res/values/strings.xml b/amethyst/src/main/res/values/strings.xml index 3548f1e30..b3ba42afb 100644 --- a/amethyst/src/main/res/values/strings.xml +++ b/amethyst/src/main/res/values/strings.xml @@ -2201,6 +2201,8 @@ Relay leave request AI Writing Help + Propose AI text improvements + Show AI writing help options when composing posts (on-device, requires supported hardware) Use This Dismiss Correct From 6f6e8761585f04d31c46f828a373e001a3f6fb7a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 8 Apr 2026 16:33:06 +0000 Subject: [PATCH 05/10] feat: precompute all AI tone results in parallel Instead of computing on-tap, all 9 tones are precomputed in parallel after a 1-second debounce when the user stops typing. Tone chips only appear once results are ready. Tapping a chip instantly shows the precomputed result. Text changes cancel and restart the computation. https://claude.ai/code/session_01RbCYGrbbapRMike8WQy41F --- .../creators/aihelp/AiWritingHelpPanel.kt | 46 +++++------ .../loggedIn/home/ShortNotePostScreen.kt | 6 +- .../loggedIn/home/ShortNotePostViewModel.kt | 76 ++++++++++++++----- 3 files changed, 78 insertions(+), 50 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt index 1d93cc6ed..6c37b1ecb 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt @@ -26,24 +26,20 @@ import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.background import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.FilterChip import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton 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.draw.clip import androidx.compose.ui.unit.dp @@ -55,8 +51,8 @@ import com.vitorpamplona.amethyst.ui.stringRes @Composable fun AiWritingHelpPanel( isVisible: Boolean, - isProcessing: Boolean, - result: WritingResult?, + readyResults: Map, + selectedResult: WritingResult?, onToneSelected: (WritingTone) -> Unit, onApply: () -> Unit, onDismiss: () -> Unit, @@ -72,19 +68,7 @@ fun AiWritingHelpPanel( .fillMaxWidth() .padding(horizontal = 8.dp), ) { - if (isProcessing) { - Box( - modifier = - Modifier - .fillMaxWidth() - .padding(vertical = 12.dp), - contentAlignment = Alignment.Center, - ) { - CircularProgressIndicator(modifier = Modifier.size(24.dp)) - } - } - - result?.let { + selectedResult?.let { AiResultCard( result = it, onApply = onApply, @@ -92,7 +76,11 @@ fun AiWritingHelpPanel( ) } - ToneChipRow(onToneSelected = onToneSelected) + ToneChipRow( + readyTones = readyResults.keys, + selectedTone = selectedResult?.tone, + onToneSelected = onToneSelected, + ) } } } @@ -141,7 +129,11 @@ private fun AiResultCard( } @Composable -private fun ToneChipRow(onToneSelected: (WritingTone) -> Unit) { +private fun ToneChipRow( + readyTones: Set, + selectedTone: WritingTone?, + onToneSelected: (WritingTone) -> Unit, +) { val scrollState = rememberScrollState() Row( modifier = @@ -152,11 +144,13 @@ private fun ToneChipRow(onToneSelected: (WritingTone) -> Unit) { horizontalArrangement = Arrangement.spacedBy(6.dp), ) { WritingTone.entries.forEach { tone -> - FilterChip( - selected = false, - onClick = { onToneSelected(tone) }, - label = { Text(toneDisplayName(tone)) }, - ) + if (tone in readyTones) { + FilterChip( + selected = tone == selectedTone, + onClick = { onToneSelected(tone) }, + label = { Text(toneDisplayName(tone)) }, + ) + } } } } diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt index 3758b8d01..4816efd86 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostScreen.kt @@ -563,9 +563,9 @@ private fun NewPostScreenBody( AiWritingHelpPanel( isVisible = postViewModel.showAiPanel, - isProcessing = postViewModel.isAiProcessing, - result = postViewModel.aiResult, - onToneSelected = postViewModel::requestAiTransform, + readyResults = postViewModel.aiResults, + selectedResult = postViewModel.aiSelectedResult, + onToneSelected = postViewModel::selectAiResult, onApply = postViewModel::applyAiResult, onDismiss = postViewModel::dismissAiResult, ) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt index fd0a25e32..9ce53a7ea 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt @@ -147,7 +147,12 @@ import com.vitorpamplona.quartz.utils.Log import com.vitorpamplona.quartz.utils.RandomInstance import com.vitorpamplona.quartz.utils.TimeUtils import kotlinx.collections.immutable.ImmutableList +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch @@ -302,17 +307,19 @@ open class ShortNotePostViewModel : // TODO: Remove useMockAi before shipping. Set to true to test UI without Gemini Nano. private val useMockAi = true - var aiResult by mutableStateOf(null) + var aiResults by mutableStateOf>(emptyMap()) + var aiSelectedResult by mutableStateOf(null) var aiStatus by mutableStateOf(WritingAssistantStatus.Unavailable) - var isAiProcessing by mutableStateOf(false) private var writingAssistant: WritingAssistant? = null + private var aiComputeJob: Job? = null + private var lastComputedText: String = "" val showAiPanel: Boolean get() { val prefEnabled = accountViewModel.settings.uiSettingsFlow.automaticallyProposeAiImprovements.value == BooleanType.ALWAYS - return prefEnabled && aiStatus is WritingAssistantStatus.Available + return prefEnabled && aiStatus is WritingAssistantStatus.Available && aiResults.isNotEmpty() } fun initWritingAssistant(context: android.content.Context) { @@ -329,35 +336,61 @@ open class ShortNotePostViewModel : } } - fun requestAiTransform(tone: WritingTone) { - val text = message.text.toString() - if (text.isBlank() || isAiProcessing) return + fun precomputeAiResults() { + val assistant = writingAssistant ?: return + if (aiStatus !is WritingAssistantStatus.Available) return + val prefEnabled = + accountViewModel.settings.uiSettingsFlow.automaticallyProposeAiImprovements.value == + BooleanType.ALWAYS + if (!prefEnabled) return - isAiProcessing = true - aiResult = null - viewModelScope.launch(Dispatchers.IO) { - try { - val result = writingAssistant?.transform(text, tone) - aiResult = result - } catch (e: Exception) { - if (e is kotlinx.coroutines.CancellationException) throw e - aiResult = null - } finally { - isAiProcessing = false + val text = message.text.toString().trim() + if (text.isBlank() || text == lastComputedText) return + + aiComputeJob?.cancel() + aiResults = emptyMap() + aiSelectedResult = null + + aiComputeJob = + viewModelScope.launch(Dispatchers.IO) { + delay(1000) + lastComputedText = text + + coroutineScope { + WritingTone.entries + .map { tone -> + async { + try { + assistant.transform(text, tone) + } catch (e: Exception) { + if (e is CancellationException) throw e + null + } + } + }.forEach { deferred -> + val result = deferred.await() ?: return@forEach + aiResults = aiResults + (result.tone to result) + } + } } - } + } + + fun selectAiResult(tone: WritingTone) { + aiSelectedResult = aiResults[tone] } fun applyAiResult() { - aiResult?.let { + aiSelectedResult?.let { message.setTextAndPlaceCursorAtEnd(it.transformedText) - aiResult = null + aiSelectedResult = null + aiResults = emptyMap() + lastComputedText = "" draftTag.newVersion() } } fun dismissAiResult() { - aiResult = null + aiSelectedResult = null } fun lnAddress(): String? = account.userProfile().lnAddress() @@ -1200,6 +1233,7 @@ open class ShortNotePostViewModel : emojiSuggestions?.processCurrentWord(lastWord) } + precomputeAiResults() draftTag.newVersion() } From 9f40d14a23ac0c1e0f0654b9823b10adadb55b02 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 8 Apr 2026 16:39:44 +0000 Subject: [PATCH 06/10] fix: show all AI tone chips at once instead of progressively Use awaitAll() to collect all tone results before updating the map, so all chips appear simultaneously when computation finishes. https://claude.ai/code/session_01RbCYGrbbapRMike8WQy41F --- .../loggedIn/home/ShortNotePostViewModel.kt | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt index 9ce53a7ea..92e1f0ad7 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt @@ -151,6 +151,7 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.StateFlow @@ -356,22 +357,23 @@ open class ShortNotePostViewModel : delay(1000) lastComputedText = text - coroutineScope { - WritingTone.entries - .map { tone -> - async { - try { - assistant.transform(text, tone) - } catch (e: Exception) { - if (e is CancellationException) throw e - null + val results = + coroutineScope { + WritingTone.entries + .map { tone -> + async { + try { + assistant.transform(text, tone) + } catch (e: Exception) { + if (e is CancellationException) throw e + null + } } - } - }.forEach { deferred -> - val result = deferred.await() ?: return@forEach - aiResults = aiResults + (result.tone to result) - } - } + }.awaitAll() + .filterNotNull() + .associateBy { it.tone } + } + aiResults = results } } From 7d9d8eda1105cdbaab0cae14215a38d8756b091d Mon Sep 17 00:00:00 2001 From: Vitor Pamplona Date: Wed, 8 Apr 2026 13:13:37 -0400 Subject: [PATCH 07/10] reducing borders in the chip row --- .../amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt index 6c37b1ecb..7eb2e6cbb 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/note/creators/aihelp/AiWritingHelpPanel.kt @@ -139,8 +139,7 @@ private fun ToneChipRow( modifier = Modifier .horizontalScroll(scrollState) - .fillMaxWidth() - .padding(vertical = 4.dp), + .fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp), ) { WritingTone.entries.forEach { tone -> From f71d9df9223f9214728d296b721b4a15f028b25e Mon Sep 17 00:00:00 2001 From: Vitor Pamplona Date: Wed, 8 Apr 2026 13:14:57 -0400 Subject: [PATCH 08/10] Remove the mock --- .../ui/screen/loggedIn/home/ShortNotePostViewModel.kt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt index 92e1f0ad7..d3c960e10 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/ui/screen/loggedIn/home/ShortNotePostViewModel.kt @@ -304,9 +304,8 @@ open class ShortNotePostViewModel : // Anonymous Reply var wantsAnonymousPost by mutableStateOf(false) - // AI Writing Help - // TODO: Remove useMockAi before shipping. Set to true to test UI without Gemini Nano. - private val useMockAi = true + // AI Writing Help for testing + private val useMockAi = false var aiResults by mutableStateOf>(emptyMap()) var aiSelectedResult by mutableStateOf(null) From 59457579fbb5e0022cf50e739dcba2abdcf063bb Mon Sep 17 00:00:00 2001 From: Vitor Pamplona Date: Wed, 8 Apr 2026 13:16:21 -0400 Subject: [PATCH 09/10] Simplify text for new settings --- amethyst/src/main/res/values/strings.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/amethyst/src/main/res/values/strings.xml b/amethyst/src/main/res/values/strings.xml index b3ba42afb..260126063 100644 --- a/amethyst/src/main/res/values/strings.xml +++ b/amethyst/src/main/res/values/strings.xml @@ -2202,7 +2202,7 @@ AI Writing Help Propose AI text improvements - Show AI writing help options when composing posts (on-device, requires supported hardware) + Show writing recommendations (on-device) Use This Dismiss Correct From 542d9520e18b20e7512519b74177df049a37e8c3 Mon Sep 17 00:00:00 2001 From: Vitor Pamplona Date: Wed, 8 Apr 2026 13:22:53 -0400 Subject: [PATCH 10/10] AI text improvements is active by default --- .../main/java/com/vitorpamplona/amethyst/model/UiSettings.kt | 2 +- .../java/com/vitorpamplona/amethyst/model/UiSettingsFlow.kt | 2 +- .../amethyst/model/preferences/UISharedPreferences.kt | 2 +- amethyst/src/main/res/values/strings.xml | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettings.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettings.kt index 5b1b09323..002b2935f 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettings.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettings.kt @@ -38,7 +38,7 @@ data class UiSettings( val dontAskForNotificationPermissions: Boolean = false, val featureSet: FeatureSetType = FeatureSetType.SIMPLIFIED, val gallerySet: ProfileGalleryType = ProfileGalleryType.CLASSIC, - val automaticallyProposeAiImprovements: BooleanType = BooleanType.NEVER, + val automaticallyProposeAiImprovements: BooleanType = BooleanType.ALWAYS, ) enum class ThemeType( diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettingsFlow.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettingsFlow.kt index 3e0ec3222..37cb82cc3 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettingsFlow.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/UiSettingsFlow.kt @@ -38,7 +38,7 @@ class UiSettingsFlow( val dontAskForNotificationPermissions: MutableStateFlow = MutableStateFlow(false), val featureSet: MutableStateFlow = MutableStateFlow(FeatureSetType.SIMPLIFIED), val gallerySet: MutableStateFlow = MutableStateFlow(ProfileGalleryType.CLASSIC), - val automaticallyProposeAiImprovements: MutableStateFlow = MutableStateFlow(BooleanType.NEVER), + val automaticallyProposeAiImprovements: MutableStateFlow = MutableStateFlow(BooleanType.ALWAYS), ) { val listOfFlows: List> = listOf>( diff --git a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/UISharedPreferences.kt b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/UISharedPreferences.kt index 5dfe07df3..c2f573f41 100644 --- a/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/UISharedPreferences.kt +++ b/amethyst/src/main/java/com/vitorpamplona/amethyst/model/preferences/UISharedPreferences.kt @@ -121,7 +121,7 @@ class UiSharedPreferences( dontAskForNotificationPermissions = preferences[UI_DONT_ASK_FOR_NOTIFICATION_PERMISSIONS] ?: false, featureSet = preferences[UI_FEATURE_SET]?.let { FeatureSetType.valueOf(it) } ?: FeatureSetType.SIMPLIFIED, gallerySet = preferences[UI_GALLERY_SET]?.let { ProfileGalleryType.valueOf(it) } ?: ProfileGalleryType.CLASSIC, - automaticallyProposeAiImprovements = preferences[UI_PROPOSE_AI_IMPROVEMENTS]?.let { BooleanType.valueOf(it) } ?: BooleanType.NEVER, + automaticallyProposeAiImprovements = preferences[UI_PROPOSE_AI_IMPROVEMENTS]?.let { BooleanType.valueOf(it) } ?: BooleanType.ALWAYS, ) } catch (e: Exception) { if (e is CancellationException) throw e diff --git a/amethyst/src/main/res/values/strings.xml b/amethyst/src/main/res/values/strings.xml index 260126063..22e265c34 100644 --- a/amethyst/src/main/res/values/strings.xml +++ b/amethyst/src/main/res/values/strings.xml @@ -2201,8 +2201,8 @@ Relay leave request AI Writing Help - Propose AI text improvements - Show writing recommendations (on-device) + Propose text improvements + Uses an on-device AI model to propose text corrections and tone changes. Use This Dismiss Correct