diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index c404f03c..7799664c 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -648,4 +648,21 @@ That isn't a relay address. Relays start with wss:// and cannot be on this device. That relay is already in this list. The app's own publishing relays are filled in. Add or remove relays before sending. + + An event is a JSON object with a kind, tags and content. + An event needs a kind. + Content must be text. + Couldn't ask the group to sign this event. + {"kind": 1, "tags": [], "content": "…"} + Kind %1$s + Kind %1$s has nowhere to go on the group's screen. It can file kinds %2$s. + Paste an unsigned Nostr event for the group to sign. It is filed by kind: a profile (kind 0) or a post (kind 1). + Propose event + Tags must be a list of lists of strings. + That isn't JSON. + The content isn't a profile. A kind 0 carries a JSON object of profile fields. + The group signs it, so it takes a quorum. The author is the group and the time is now, whatever the paste says about either. + This group has no shared key, so it cannot sign an event. Run a shared key ceremony first. + Unsigned event + What the group would sign diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/GroupEventProposal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/GroupEventProposal.kt new file mode 100644 index 00000000..e7c05be2 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/GroupEventProposal.kt @@ -0,0 +1,170 @@ +package mobi.giza.compose.nostr + +import mobi.giza.compose.managers.GroupStatementRefusal +import mobi.giza.compose.network.serialization.CommonJson +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.intOrNull + +/** + * An unsigned event a member pasted for the group to sign, read and checked + * before a quorum is asked for it. + * + * The typed editors -- the profile form and the post composer -- each build one + * kind of event and know what it needs. This is the untyped way in: the event as + * JSON, the way another tool prints it, pasted whole. What comes out is the same + * thing the editors produce, a kind, tags and content for + * `FrostSigningRepository.proposeSigning`, and it is filed the same way when the + * quorum signs: `FrostSigningManager.complete` records it as a `GroupSignedEvent` + * and the group's screen reads its profile and posts straight off those by kind. + * docs/group-nostr-profile-and-posts.md, D9. + * + * ### What is ignored + * + * `id`, `pubkey`, `sig` and `created_at`. The group is the author -- the + * session resolves the room's key and hashes the id over it -- and the time is + * when the session opens, which is what every typed editor does too. A pasted + * `created_at` in particular has to go: the kinds here are replaceable or + * addressable, so a stale one would make the new event *older* than the last and + * the proposal would look as though it did nothing. The screen says so. + * + * ### What is refused, and why before rather than after + * + * Only kinds the group's screen has a place for, and only events that place + * would accept. A signature is the most expensive thing this app does, and the + * readers refuse rather than repair: a kind 0 whose content is not a profile or + * a blank post would be signed, filed and shown nowhere, with nothing to tell + * the member their quorum was spent on nothing. So every check a reader makes is + * made here first, on the paste -- with the predicates every member's device + * declines on (`GroupStatementRefusal`), so the proposer and the signer draw the + * same line. + */ +object GroupEventProposal { + /** + * The kinds a pasted event may be: exactly the ones the group's screen reads. + * + * Not the kinds `ChatMessage.applyInnerEvent` has an arm for. A subgroup + * certificate or a key state event has invariants a paste cannot be trusted + * to meet and a place in the room's life that a form is not. The line is "has + * a section on the group's screen", because that is where a member goes to see + * it landed -- Curare's line, less the relay lists Giza did not bring back + * (D1) and Curare's schemas. + */ + val ACCEPTED_KINDS: Set = setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + + sealed interface Reading + + /** An event the group could sign and the screen could show. */ + class Ready( + val kind: Kind, + val tags: Array>, + val content: String, + ) : Reading { + /** + * The event as the signing screen will describe it, for a preview before + * the button is pressed. The id, author and signature are placeholders: + * `ProposedEvent.summarize` reads none of them. + */ + fun preview(): Event = Event( + id = "", + pubKey = "", + createdAt = 0, + kind = kind, + tags = tags, + content = content, + sig = "", + ) + } + + /** Why the paste cannot be proposed as it is. */ + sealed interface Refused : Reading { + data object NotJson : Refused + + /** JSON, but an array, a string, a number -- anything but an object. */ + data object NotAnObject : Refused + + data object NoKind : Refused + + data class KindNotAccepted(val kind: Kind) : Refused + + /** `tags` present but not a list of lists of strings. */ + data object TagsMalformed : Refused + + /** `content` present but not a string. */ + data object ContentNotText : Refused + + /** A kind 0 whose content will not parse as a profile. */ + data object ProfileUnreadable : Refused + + /** A kind 1 with nothing to say, which the posts reader would drop. */ + data object PostBlank : Refused + } + + private const val KEY_KIND = "kind" + private const val KEY_TAGS = "tags" + private const val KEY_CONTENT = "content" + + /** The paste as something the group could sign, or the reason it is not. */ + fun read(json: String): Reading { + val element = runCatching { CommonJson.parseToJsonElement(json) }.getOrNull() + ?: return Refused.NotJson + + val obj = element as? JsonObject ?: return Refused.NotAnObject + + // A number or a numeric string: relays write the former and a hand + // types either, and there is nothing to be gained by refusing "1". + val kind = (obj[KEY_KIND] as? JsonPrimitive)?.intOrNull ?: return Refused.NoKind + if (kind !in ACCEPTED_KINDS) return Refused.KindNotAccepted(kind) + + val tags = when (val raw = obj[KEY_TAGS]) { + null -> emptyArray() + else -> readTags(raw) ?: return Refused.TagsMalformed + } + + val content = when (val raw = obj[KEY_CONTENT]) { + null -> "" + else -> (raw as? JsonPrimitive)?.takeIf { it.isString }?.content + ?: return Refused.ContentNotText + } + + return when (kind) { + // An empty kind 0 is a profile the group has wiped, which it is + // entitled to do; content that is not JSON is not a profile at all. + // The same line `GroupNostrProfile.of` draws. + MetadataEvent.KIND -> if (GroupStatementRefusal.isUnreadableProfile(tags, content)) { + Refused.ProfileUnreadable + } else { + Ready(kind, tags, content) + } + + // The line `AddGroupPostViewModel.proposePost` draws, for the reason + // it gives: a blank post cannot be told from a broken one and, kind:1 + // not being replaceable, cannot be un-said. + TextNoteEvent.KIND -> if (GroupStatementRefusal.isBlankPost(content)) { + Refused.PostBlank + } else { + Ready(kind, tags, content) + } + + else -> Refused.KindNotAccepted(kind) + } + } + + private fun readTags(raw: JsonElement): Array>? { + val outer = raw as? JsonArray ?: return null + + return outer.map { tag -> + val inner = tag as? JsonArray ?: return null + inner.map { value -> + (value as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull ?: return null + }.toTypedArray() + }.toTypedArray() + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index fee5952e..b0f025ad 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -1,5 +1,9 @@ package mobi.giza.compose.ui.composable +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.resources.propose_event +import mobi.giza.compose.ui.composable.navigation.routes.ProposeGroupEventRoute +import androidx.compose.material.icons.filled.DataObject import mobi.giza.compose.resources.n_posts import mobi.giza.compose.resources.one_post import mobi.giza.compose.resources.no_posts_yet @@ -255,6 +259,10 @@ fun ChatRoomDetailScreen( // Read outside the click handlers: stringResource and rememberNotifier are both // composable, and a lambda passed to onClick is not. + // Read here rather than in the list's DSL, which is not composable: whether the + // identity can sign at all, for the one write entrance below that is not its own + // screen. docs/npub-sign-in.md. + val identityCanSign = LocalCanSign.current val notify = rememberNotifier(rememberCoroutineScope()) val removalRequested = stringResource(Res.string.member_removal_requested) val couldNotLeave = stringResource(Res.string.couldn_t_leave_the_group) @@ -697,6 +705,40 @@ fun ChatRoomDetailScreen( ) } + // The untyped way in: an unsigned event, pasted. It + // lands on its kind's screen above once the quorum + // signs. Behind the same gate as the editors, and the + // identity's: an npub-only profile cannot propose. + // docs/group-nostr-profile-and-posts.md, D9. + if (chatRoomDetailUIState.canProposeAsGroup && identityCanSign) { + item { + TextButton( + onClick = { + onNavigateToRoute.invoke( + ProposeGroupEventRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint + ) + ) + } + ) { + Icon( + Icons.Default.DataObject, + contentDescription = Decorative + ) + + Spacer( + modifier = Modifier.width( + MaterialTheme.spacing.space125 + ) + ) + + Text(stringResource(Res.string.propose_event)) + } + } + } + item { HorizontalDivider() } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeGroupEventScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeGroupEventScreen.kt new file mode 100644 index 00000000..fdd40117 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeGroupEventScreen.kt @@ -0,0 +1,431 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Draw +import androidx.compose.material3.BottomAppBar +import androidx.compose.material3.BottomAppBarDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.GroupEventProposal +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.text.ProposedEvent +import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab +import mobi.giza.compose.ui.composable.widgets.profile.ProfileAvatar +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.theme.ConformancePreviews +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.ProposeGroupEventViewModel +import mobi.giza.compose.ui.view.state.ProposeGroupEventUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.a_post_needs_something_to_say +import mobi.giza.compose.resources.an_event_is_a_json_object +import mobi.giza.compose.resources.an_event_needs_a_kind +import mobi.giza.compose.resources.content_must_be_text +import mobi.giza.compose.resources.could_not_ask_the_group_to_sign_this_event +import mobi.giza.compose.resources.eg_kind_1_tags_content +import mobi.giza.compose.resources.kind_n +import mobi.giza.compose.resources.kind_n_has_nowhere_to_go_on_this_screen +import mobi.giza.compose.resources.paste_an_unsigned_event_for_the_group_to_sign +import mobi.giza.compose.resources.propose_event +import mobi.giza.compose.resources.tags_must_be_a_list_of_lists_of_strings +import mobi.giza.compose.resources.that_is_not_json +import mobi.giza.compose.resources.the_content_is_not_a_profile +import mobi.giza.compose.resources.the_group_signs_an_event_so_it_takes_a_quorum +import mobi.giza.compose.resources.this_group_has_no_shared_key_to_sign_an_event +import mobi.giza.compose.resources.unsigned_event +import mobi.giza.compose.resources.what_the_group_would_sign +import org.jetbrains.compose.resources.stringResource + +/** + * An unsigned event, pasted, for the group to sign. + * + * The typed editors each build one kind of statement; this takes any of the + * kinds the group's screen can show, as JSON, the way another tool prints one. + * Above the paste is what the group would be signing, read back the way the + * signing screen will describe it, so a member sees "Nostr profile · Translation + * collective" rather than a wall of brackets before deciding -- and sees why the group will + * not be asked when the paste is something it could never show. + * + * The byline is the group's, as on the post composer and for the same reason: + * whatever is pasted goes out in the group's name, and a paste that names some + * other `pubkey` goes out in the group's name anyway. The explanatory line says + * so, because a paste with a `pubkey` in it is the one case where a member could + * reasonably expect otherwise. + */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) +@Composable +fun ProposeGroupEventScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialProposeGroupEventUIState: ProposeGroupEventUIState = ProposeGroupEventUIState.Loading, + chatRepository: ChatRepository, + frostSigningRepository: FrostSigningRepository, + onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val proposeGroupEventViewModel: ProposeGroupEventViewModel = viewModel( + factory = ProposeGroupEventViewModel.factory( + chatRoomId = chatRoomId, + relayHint = relayHint, + initialProposeGroupEventUIState = initialProposeGroupEventUIState, + activeUserPublicKey = activeUserPublicKey, + chatRepository = chatRepository, + frostSigningRepository = frostSigningRepository + ) + ) + + // Read out here rather than in the click handler: both are composable and an + // onClick lambda is not. The scope is the caller's so a message survives this + // screen being replaced by the signing session. + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_event) + + ScreenStateTransition(proposeGroupEventViewModel.proposeGroupEventUIState) { uiState -> + when (val proposeGroupEventUIState = uiState) { + is ProposeGroupEventUIState.Error -> { + // Nothing to retry: the room came from a navigation argument, and + // reading it again with the same one fails the same way. + ErrorState(message = proposeGroupEventUIState.message, onRetry = null) + } + + is ProposeGroupEventUIState.Loaded -> { + val eventFieldState = rememberTextFieldState() + // The room and this device's share, and the identity: an npub-only + // profile cannot send the proposal at all. docs/npub-sign-in.md. + val canSign = proposeGroupEventUIState.canSign && LocalCanSign.current + + // Read on every change. A paste is a few kilobytes at most and the + // reading is one JSON parse, so this is cheaper than the debounce + // that would hide the answer for a beat after the paste. + val json = eventFieldState.text.toString() + val reading = remember(json) { + json.takeIf { it.isNotBlank() }?.let(GroupEventProposal::read) + } + + // imePadding: this screen is a text field the size of the screen, + // and without it the software keyboard covers what is being pasted. + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.propose_event)) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + bottomBar = { + BottomAppBar( + actions = {}, + floatingActionButton = { + ExtendedFab( + label = stringResource(Res.string.propose_event), + icon = { Icon(Icons.Default.Draw, contentDescription = "Propose event") }, + enabled = canSign, + onClick = { + proposeGroupEventViewModel.proposeEvent( + localChatRoom = proposeGroupEventUIState.localChatRoom, + json = eventFieldState.text.toString(), + onSuccess = { sessionId -> + // Onto the session rather than back + // to the group. Nothing has been + // signed yet -- the event lands when + // a quorum signs -- so landing on a + // screen that does not show it would + // read as a failure. + onNavigateToRouteAndPopUpInclusive.invoke( + FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId + ) + ) + }, + // The reason is already under the paste; + // pressing the button anyway is answered + // rather than ignored, and the paste + // stays. Same on a failure to propose. + onRefused = {}, + onFailure = { notify(couldNotPropose) } + ) + } + ) + } + ) + } + ) { innerPadding -> + Column( + modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize(), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + horizontalAlignment = Alignment.CenterHorizontally + ) { + // Whose name this goes out in, said before anything is + // pasted. It is the group's, whatever the paste says. + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + ProfileAvatar( + size = MaterialTheme.spacing.space500, + publicKey = chatRoomId, + picture = proposeGroupEventUIState.groupNostrProfile?.picture(), + name = proposeGroupEventUIState.groupNostrProfile?.name() + ) + + Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) + + Text( + text = proposeGroupEventUIState.groupNostrProfile?.name() + ?: proposeGroupEventUIState.localChatRoom.chatRoom.subject + ?: chatRoomId.take(16), + style = MaterialTheme.typography.titleSmall, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + + Text( + text = stringResource( + Res.string.paste_an_unsigned_event_for_the_group_to_sign + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center + ) + + Text( + text = stringResource( + Res.string.the_group_signs_an_event_so_it_takes_a_quorum + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center + ) + + if (!proposeGroupEventUIState.canSign) { + Text( + text = stringResource( + Res.string.this_group_has_no_shared_key_to_sign_an_event + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + textAlign = TextAlign.Center + ) + } + + when (reading) { + null -> Unit + is GroupEventProposal.Ready -> ProposalPreview(reading) + is GroupEventProposal.Refused -> RefusalNotice(reading) + } + + OutlinedTextField( + modifier = Modifier.fillMaxWidth().weight(1f) + .background(BottomAppBarDefaults.containerColor), + state = eventFieldState, + // The paste grows into the screen rather than scrolling + // inside three lines, and is set in a monospace face: + // it is JSON, and a bracket that does not line up is + // the kind of thing a member is looking for in it. + lineLimits = TextFieldLineLimits.MultiLine(), + textStyle = TextStyle(fontFamily = FontFamily.Monospace), + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = Color.Transparent, + unfocusedBorderColor = Color.Transparent, + disabledBorderColor = Color.Transparent + ), + label = { Text(stringResource(Res.string.unsigned_event)) }, + placeholder = { + Text( + text = stringResource(Res.string.eg_kind_1_tags_content), + fontFamily = FontFamily.Monospace + ) + }, + isError = reading is GroupEventProposal.Refused + ) + } + } + } + + ProposeGroupEventUIState.Loading -> { + Column( + modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + + Text( + text = stringResource(Res.string.propose_event), + style = MaterialTheme.typography.bodyLarge, + textAlign = TextAlign.Center + ) + + LoadingDataIndicator(fillScreen = false) + } + } + } + } + + LaunchedEffect(true) { + if (initialProposeGroupEventUIState == ProposeGroupEventUIState.Loading) { + proposeGroupEventViewModel.initiateProposeGroupEvent() + } + } +} + +/** + * What the group would sign, said the way the signing screen will say it. + * + * `ProposedEvent.summarize` rather than a description of this screen's own, so + * that what a member reads here before proposing is word for word what every + * other member reads before signing. Two descriptions of one event would drift. + */ +@Composable +private fun ProposalPreview(ready: GroupEventProposal.Ready) { + val summary = ProposedEvent.summarize(ready.preview()) + + Card(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + Text( + text = stringResource(Res.string.what_the_group_would_sign), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Text( + text = stringResource(Res.string.kind_n, ready.kind.toString()) + " · " + summary.label, + style = MaterialTheme.typography.titleSmall + ) + + // Capped, because a kind:1's detail is the whole post and the paste + // under this card is the thing the screen is for. + Text( + text = summary.detail, + style = MaterialTheme.typography.bodyMedium, + maxLines = 6, + overflow = TextOverflow.Ellipsis + ) + } + } +} + +/** + * Why the group will not be asked, under the paste it is about. + * + * Named rather than silent: a button that does nothing for a paste it refuses is + * indistinguishable from a missed tap. + */ +@Composable +private fun RefusalNotice(refused: GroupEventProposal.Refused) { + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + Text( + text = when (refused) { + GroupEventProposal.Refused.NotJson -> stringResource(Res.string.that_is_not_json) + GroupEventProposal.Refused.NotAnObject -> stringResource(Res.string.an_event_is_a_json_object) + GroupEventProposal.Refused.NoKind -> stringResource(Res.string.an_event_needs_a_kind) + is GroupEventProposal.Refused.KindNotAccepted -> stringResource( + Res.string.kind_n_has_nowhere_to_go_on_this_screen, + refused.kind.toString(), + GroupEventProposal.ACCEPTED_KINDS.sorted().joinToString() + ) + GroupEventProposal.Refused.TagsMalformed -> + stringResource(Res.string.tags_must_be_a_list_of_lists_of_strings) + GroupEventProposal.Refused.ContentNotText -> stringResource(Res.string.content_must_be_text) + GroupEventProposal.Refused.ProfileUnreadable -> + stringResource(Res.string.the_content_is_not_a_profile) + GroupEventProposal.Refused.PostBlank -> stringResource(Res.string.a_post_needs_something_to_say) + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + } +} + +@ConformancePreviews +@Composable +private fun ProposeGroupEventScreenPreview() { + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + ProposeGroupEventScreen( + activeUserPublicKey = "", + chatRoomId = "publicKey", + relayHint = null, + initialProposeGroupEventUIState = ProposeGroupEventUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = "publicKey", + userPublicKey = "", + subject = "Translation room", + description = "A group translating hard books.", + initialGiftWrapPayloadId = "sdfaer", + mlsGroupState = "state" + ), + ), + // A group that can sign, so the screen renders in the state a + // member actually meets it in rather than greyed out. + canSign = true + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, + onNavigateToRouteAndPopUpInclusive = {}, + onNavigateBack = {}, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index b11ca0d0..b065d94a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -1,5 +1,7 @@ package mobi.giza.compose.ui.composable.navigation +import mobi.giza.compose.ui.composable.navigation.routes.ProposeGroupEventRoute +import mobi.giza.compose.ui.composable.ProposeGroupEventScreen import mobi.giza.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute import mobi.giza.compose.ui.composable.BroadcastGroupSignedEventScreen import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute @@ -1334,6 +1336,31 @@ fun GizaNavHost( } ) } + // An unsigned event, pasted for the group to sign: D9 of + // docs/group-nostr-profile-and-posts.md. + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + ProposeGroupEventScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + chatRepository = databaseChatRepository, + frostSigningRepository = databaseFrostSigningRepository, + onNavigateToRouteAndPopUpInclusive = { signingRoute -> + // Replace the paste so back returns to the group rather + // than to an event whose proposal has already gone out. + navController.navigate(route = signingRoute) { + popUpTo { + inclusive = true + } + } + }, + onNavigateBack = { + navController.popBackStack() + } + ) + } composable { backStackEntry -> val route: ImplementationPendingRoute = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ProposeGroupEventRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ProposeGroupEventRoute.kt new file mode 100644 index 00000000..45f1d499 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ProposeGroupEventRoute.kt @@ -0,0 +1,11 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** The untyped way into a group's signed statements: an unsigned event, pasted. */ +@Serializable +data class ProposeGroupEventRoute( + val activeUserPublicKey: String, + val chatRoomId: String, // TODO: have this as a publicKey + val relayHint: String? +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeGroupEventViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeGroupEventViewModel.kt new file mode 100644 index 00000000..4f6c06c0 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeGroupEventViewModel.kt @@ -0,0 +1,157 @@ +package mobi.giza.compose.ui.view.model + +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import co.touchlab.kermit.Logger +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.GroupEventProposal +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.ui.view.state.ProposeGroupEventUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.launch + +/** + * Asks the group to sign an event a member pasted. + * + * Nothing is built here; the paste is the event. What this decides is whether + * the group should be asked at all -- `GroupEventProposal.read` refuses a paste + * the group's screen could never show, so a quorum is not spent on an event that + * would be signed, filed and seen by nobody -- and it hands the kind, tags and + * content to the same `proposeSigning` every typed editor uses. The author and + * the time are the session's to fill in, which is how a pasted `pubkey` or + * `created_at` comes to be ignored: they are never passed along. + * + * Where the event lands is decided by nothing here. `FrostSigningManager.complete` + * files every signed event as a `GroupSignedEvent`, and the group's screen reads + * its profile and posts off those by kind. A pasted kind 0 + * becomes the profile the same way a kind 0 from the profile form does, because + * by the time either is signed there is no telling them apart. + */ +class ProposeGroupEventViewModel( + val chatRoomId: String, + val activeUserPublicKey: HexKey, + val relayHint: String?, + initialProposeGroupEventUIState: ProposeGroupEventUIState, + val chatRepository: ChatRepository, + val frostSigningRepository: FrostSigningRepository, +): ViewModel() { + + var proposeGroupEventUIState: ProposeGroupEventUIState by mutableStateOf( + initialProposeGroupEventUIState + ) + private set + + private val logger = Logger.withTag(TAG) + + val isActionPending: MutableState = mutableStateOf(false) + + fun initiateProposeGroupEvent() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + + proposeGroupEventUIState = if (localChatRoom == null) { + ProposeGroupEventUIState.Error("Couldn't find the chat room") + } else { + ProposeGroupEventUIState.Loaded( + localChatRoom = localChatRoom, + groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), + // The same condition the group detail screen gates the entry + // point on. + canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && + frostSigningRepository.canSign(chatRoomId), + ) + } + } + } + + /** + * Opens a session over the pasted event, or says why not. + * + * [onRefused] carries the reading's own reason, which the screen has been + * showing under the paste all along; it is repeated here so pressing the + * button on a refused paste is answered rather than ignored. Both refusals + * and a failed proposal stay on the paste: the JSON is the thing worth + * keeping. + */ + fun proposeEvent( + localChatRoom: LocalChatRoom, + json: String, + onSuccess: (sessionId: String) -> Unit, + onRefused: (GroupEventProposal.Refused) -> Unit, + onFailure: () -> Unit + ) { + // Guard against double submits. A pasted kind:1 accumulates like any + // other post, so a second session over the same paste is a second post + // on the record forever. + if (isActionPending.value) return + + val ready = when (val reading = GroupEventProposal.read(json)) { + is GroupEventProposal.Ready -> reading + is GroupEventProposal.Refused -> { + onRefused.invoke(reading) + return + } + } + + isActionPending.value = true + + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { + frostSigningRepository.proposeSigning( + localChatRoom = localChatRoom, + userPublicKey = activeUserPublicKey, + kind = ready.kind, + tags = ready.tags, + content = ready.content, + ) + }.onFailure { error -> + logger.e("Failed to propose a pasted kind ${ready.kind} event for $chatRoomId", error) + }.getOrNull() + + viewModelScope.launch(Dispatchers.Main) { + if (session != null) { + onSuccess.invoke(session.id) + } else { + onFailure.invoke() + } + } + + isActionPending.value = false + } + } + + companion object { + private const val TAG = "ProposeGroupEventViewModel" + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialProposeGroupEventUIState: ProposeGroupEventUIState = + ProposeGroupEventUIState.Loading, + chatRepository: ChatRepository, + frostSigningRepository: FrostSigningRepository + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + ProposeGroupEventViewModel( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint, + initialProposeGroupEventUIState = initialProposeGroupEventUIState, + chatRepository = chatRepository, + frostSigningRepository = frostSigningRepository + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ProposeGroupEventUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ProposeGroupEventUIState.kt new file mode 100644 index 00000000..8de97079 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ProposeGroupEventUIState.kt @@ -0,0 +1,32 @@ +package mobi.giza.compose.ui.view.state + +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.GroupNostrProfile + +sealed interface ProposeGroupEventUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + /** + * Who the group says it is, for the byline over the paste. + * + * Whatever is pasted goes out signed by the group and read as the group, + * so the screen shows whose name it will carry -- which is not the + * member pasting it, and not whatever `pubkey` the paste may name. + */ + val groupNostrProfile: GroupNostrProfile? = null, + /** + * Whether this device holds a share of the group's key. + * + * False leaves the paste writable and the button inert, for the same + * reason the typed editors do: reading and checking cost nothing, and + * only a share-holder can open the session that would sign it. + */ + val canSign: Boolean = false, + ): ProposeGroupEventUIState + + data class Error( + val message: String + ): ProposeGroupEventUIState + + data object Loading: ProposeGroupEventUIState +} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/GroupEventProposalTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/GroupEventProposalTest.kt new file mode 100644 index 00000000..ffe7592d --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/nostr/GroupEventProposalTest.kt @@ -0,0 +1,280 @@ +package mobi.giza.compose.nostr + +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.managers.SharedKeyDerivation +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.Frost +import fr.acinq.bitcoin.crypto.frost.IndividualNonce +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import fr.acinq.bitcoin.crypto.frost.SecretNonce +import fr.acinq.bitcoin.crypto.frost.Session +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * What a pasted event may become, and where it goes once the group has signed it. + * + * Two halves. The first is the reading: which pastes are refused and why, and + * that what is refused is exactly what a reader would refuse -- the point of + * checking before proposing is that a quorum is never asked to sign something + * that will be filed and shown nowhere. + * + * The second is the promise the feature makes: a pasted kind 0 becomes the + * profile and a kind 1 a post (docs/group-nostr-profile-and-posts.md, D9). That + * is not this module's doing -- `FrostSigningManager.complete` files every signed + * event and the group's screen reads each section off those by kind -- so the + * test is the whole chain: the paste read here, signed by a real quorum through + * the same shape `FrostSigningManager.advance` runs, and read back by the reader + * that section uses. + */ +class GroupEventProposalTest { + private val participants = 3 + private val threshold = 2 + + private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey( + ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") + ), + nParticipants = participants, + threshold = threshold + ) + + private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH + + private val chatRoomId = + SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) + + /** + * A profile as another client prints a signed event: id, author, signature and + * time included, none of which the paste is allowed to decide. + */ + private val pastedProfile = """ + { + "id": "b2f8c7a7b4d5e6f70123456789abcdef0123456789abcdef0123456789abcdef", + "pubkey": "7c965d8c2acdfd635562da3bcb82596b595be28b008d8b54ec702ed4c67d9d25", + "created_at": 1735689600, + "kind": 0, + "tags": [ + ["alt", "The group's profile"], + ["i", "github:translation-collective", "{\"proof\":\"x\"}"] + ], + "content": "{\"name\":\"Translation collective\",\"about\":\"Hard books\"}", + "sig": "c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00" + } + """.trimIndent() + + @Test + fun `a pasted event is read as its kind tags and content and nothing else`() { + val ready = assertIs(GroupEventProposal.read(pastedProfile)) + + assertEquals(0, ready.kind) + assertEquals("""{"name":"Translation collective","about":"Hard books"}""", ready.content) + assertEquals(2, ready.tags.size) + assertEquals(listOf("alt", "The group's profile"), ready.tags.first().toList()) + // A tag's JSON comes through verbatim, escapes and all. + assertEquals("{\"proof\":\"x\"}", ready.tags[1][2]) + + // The id, author, signature and time are not the paste's to decide, and + // there is nowhere on a reading for them to go: the session hashes the id + // over the room's key and the time it opens at. + val preview = ready.preview() + assertEquals("", preview.pubKey) + assertEquals(0L, preview.createdAt) + } + + @Test + fun `a bare template with no tags or content still reads`() { + val ready = assertIs( + GroupEventProposal.read("""{"kind": 0, "content": "{}"}""") + ) + assertEquals(0, ready.kind) + assertEquals(0, ready.tags.size) + + // A numeric string for the kind is what a hand types; a relay writes a number. + assertIs( + GroupEventProposal.read("""{"kind": "1", "content": "Hello"}""") + ) + } + + @Test + fun `what is not an event is refused and named`() { + assertEquals(GroupEventProposal.Refused.NotJson, GroupEventProposal.read("not json at all")) + assertEquals(GroupEventProposal.Refused.NotJson, GroupEventProposal.read("{\"kind\": 1,")) + assertEquals(GroupEventProposal.Refused.NotAnObject, GroupEventProposal.read("[1, 2, 3]")) + assertEquals(GroupEventProposal.Refused.NotAnObject, GroupEventProposal.read("\"a string\"")) + assertEquals(GroupEventProposal.Refused.NoKind, GroupEventProposal.read("""{"content": "Hello"}""")) + assertEquals(GroupEventProposal.Refused.NoKind, GroupEventProposal.read("""{"kind": "one"}""")) + assertEquals( + GroupEventProposal.Refused.TagsMalformed, + GroupEventProposal.read("""{"kind": 1, "tags": "e", "content": "Hello"}""") + ) + assertEquals( + GroupEventProposal.Refused.TagsMalformed, + GroupEventProposal.read("""{"kind": 1, "tags": [["e", 1]], "content": "Hello"}""") + ) + assertEquals( + GroupEventProposal.Refused.ContentNotText, + GroupEventProposal.read("""{"kind": 1, "content": {"note": "Hello"}}""") + ) + } + + @Test + fun `a kind the group's screen has no place for is refused whatever else it says`() { + // A long-form article is a perfectly good nostr event and the group could + // sign it. It would then be filed and shown nowhere, with nothing to tell + // the member their quorum was spent on it. + assertEquals( + GroupEventProposal.Refused.KindNotAccepted(30023), + GroupEventProposal.read("""{"kind": 30023, "tags": [["d", "x"]], "content": "An article"}""") + ) + + // A relay list has no section here: Giza did not bring the group's relay + // lists back (D1). + assertEquals( + GroupEventProposal.Refused.KindNotAccepted(10002), + GroupEventProposal.read("""{"kind": 10002, "tags": [["r", "wss://relay.example.com"]]}""") + ) + + // The kinds with a section: the profile and the posts. A subgroup + // certificate is deliberately not among them. + assertEquals(setOf(0, 1), GroupEventProposal.ACCEPTED_KINDS) + } + + @Test + fun `a kind zero whose content is not a profile is refused and an empty one is not`() { + assertEquals( + GroupEventProposal.Refused.ProfileUnreadable, + GroupEventProposal.read("""{"kind": 0, "content": "not a profile"}""") + ) + + // Wiping a profile is a thing groups are entitled to do -- the same line + // `GroupNostrProfile.of` draws. + assertIs(GroupEventProposal.read("""{"kind": 0, "content": ""}""")) + assertIs( + GroupEventProposal.read("""{"kind": 0, "content": "{\"name\":\"Translation collective\"}"}""") + ) + } + + @Test + fun `a blank post is refused the way the composer refuses one`() { + listOf("", " ", "\\n\\n").forEach { blank -> + assertEquals( + GroupEventProposal.Refused.PostBlank, + GroupEventProposal.read("""{"kind": 1, "content": "$blank"}"""), + "a post saying \"$blank\" was accepted" + ) + } + } + + @Test + fun `a pasted kind zero once signed is the group's profile`() { + val ready = assertIs( + GroupEventProposal.read( + """{"kind": 0, "pubkey": "not the group", "content": "{\"name\":\"Translation collective\",\"about\":\"We translate hard books.\"}"}""" + ) + ) + + val profile = assertNotNull(GroupNostrProfile.of(signed(ready), chatRoomId)) + + assertEquals("Translation collective", profile.name()) + assertEquals("We translate hard books.", profile.about()) + assertEquals(chatRoomId, profile.publicKey) + } + + @Test + fun `a pasted kind one once signed is one of the group's posts`() { + val ready = assertIs( + GroupEventProposal.read("""{"kind": 1, "tags": [], "content": "We have finished the first chapter."}""") + ) + + val posts = GroupPost.newestFirstAmong(listOf(signed(ready)), chatRoomId) + + assertEquals(listOf("We have finished the first chapter."), posts.map { it.content }) + assertTrue(posts.single().isNewThread()) + } + + /** + * A reading as `FrostSigningManager.complete` would file it: authored by the + * room's key at its path, the id hashed over that, a real quorum's signature + * on it, and the time the session opened at rather than anything pasted. + */ + private fun signed(ready: GroupEventProposal.Ready, createdAt: Long = 1_700_000_000): GroupSignedEvent { + val groupPubKey = SharedKeyDerivation + .derive(groupMaterial.thresholdPublicKey.value.toHex(), path) + .hex + + val id = EventHasher.hashId( + pubKey = groupPubKey, + createdAt = createdAt, + kind = ready.kind, + tags = ready.tags, + content = ready.content + ) + + return GroupSignedEvent.fromEvent( + event = Event( + id = id, + pubKey = groupPubKey, + createdAt = createdAt, + kind = ready.kind, + tags = ready.tags, + content = ready.content, + sig = groupSignature(groupMaterial, id) + ), + chatRoomId = chatRoomId, + derivationPath = SharedKeyDerivation.formatPath(path) + ) + } + + /** + * A real FROST signature by [material]'s quorum over [eventId], through the + * same shape `FrostSigningManager.advance` runs. + */ + private fun groupSignature(material: KeyMaterial, eventId: String): String { + val cache = SharedKeyDerivation + .derive(material.thresholdPublicKey.value.toHex(), path) + .cache + val message = ByteVector(eventId.hexToByteArray()) + val signerIds = listOf(0, 1) + + val nonces = signerIds.map { signerId -> + SecretNonce.generate( + sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), + secretShare = material.secretShares[signerId], + publicShare = material.publicShares[signerId], + tweakedThresholdPublicKey = cache.tweakedPublicKey, + message = message, + extraInput = null + ) + } + + val signingSession = Session.create( + aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, + signerIds = signerIds.map { it.toUInt() }, + signerPublicShares = signerIds.map { material.publicShares[it] }, + nParticipants = participants, + threshold = threshold, + tweakCache = cache, + message = message + ) + + val partials = signerIds.mapIndexed { position, signerId -> + signingSession.sign( + nonces[position].first, + material.secretShares[signerId], + signerId.toUInt() + ).right!! + } + + return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt index a6ec8d94..28e2adce 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt @@ -2,6 +2,7 @@ package mobi.giza.compose.ui.composable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.Modifier import androidx.compose.ui.test.ComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi @@ -19,7 +20,9 @@ import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.post import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.profile import mobi.giza.compose.ui.composable.navigation.routes.GroupNostrProfileRoute import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute +import mobi.giza.compose.ui.composable.navigation.routes.ProposeGroupEventRoute import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.LocalCanSign import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost import mobi.giza.compose.ui.theme.GizaTheme import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState @@ -28,7 +31,7 @@ import kotlin.test.assertEquals /** * The rows on the group's screen that lead to what the group says as itself on - * nostr: its profile and its posts (docs/group-nostr-profile-and-posts.md). + * nostr: its profile, its posts, and the paste (docs/group-nostr-profile-and-posts.md). * * The relay lists were not brought back with them (D1), so their row stays absent. */ @@ -99,6 +102,33 @@ class GroupSignedWorkRowsJvmTest { onNodeWithText("Posts").assertDoesNotExist() } + @Test + fun `a member who can propose is offered the paste, and it opens`() { + var opened: Route? = null + + render(state(groupNostrProfile = profile), onNavigateToRoute = { opened = it }) { + onNodeWithText("Propose event").assertIsDisplayed().performClick() + } + + assertEquals(ProposeGroupEventRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) + } + + @Test + fun `a member who cannot propose is not offered the paste`() = render( + state(groupNostrProfile = profile, canProposeAsGroup = false) + ) { + onNodeWithText("Nostr profile").assertIsDisplayed() + onNodeWithText("Propose event").assertDoesNotExist() + } + + @Test + fun `an identity that cannot sign is not offered the paste`() = render( + state(groupNostrProfile = profile), + identityCanSign = false, + ) { + onNodeWithText("Propose event").assertDoesNotExist() + } + @Test fun `there is no relays row`() = render(state(groupNostrProfile = profile)) { onNodeWithText("Relays").assertDoesNotExist() @@ -125,11 +155,13 @@ class GroupSignedWorkRowsJvmTest { private fun render( uiState: ChatRoomDetailUIState, onNavigateToRoute: (Route) -> Unit = {}, + identityCanSign: Boolean = true, assertions: ComposeUiTest.() -> Unit ) = runDesktopComposeUiTest(width = 400, height = 4000) { setContent { GizaTheme { ProvideSnackbarHost { + CompositionLocalProvider(LocalCanSign provides identityCanSign) { Box(modifier = Modifier.fillMaxSize()) { ChatRoomDetailScreen( activeUserPublicKey = activeUserPublicKey, @@ -143,6 +175,7 @@ class GroupSignedWorkRowsJvmTest { onNavigateBack = {}, ) } + } } } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt new file mode 100644 index 00000000..44971ba4 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt @@ -0,0 +1,131 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.runDesktopComposeUiTest +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.FrostSigningRepository +import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.state.ProposeGroupEventUIState +import kotlin.test.Test + +/** + * What the paste screen says back as an event is typed into it. + * + * The screen's one job beyond a text field is to tell a member, before a quorum + * is asked, what the group would be signing or why it will not be asked. Both + * are read live off the paste, so both are tested by typing: a profile reads back + * as the signing screen would describe it, junk is named as junk, and a kind + * with no section to land in is refused with the kinds that have one. + */ +@OptIn(ExperimentalTestApi::class) +class ProposeGroupEventScreenJvmTest { + + private val chatRoomId = "d4c3b2a1".repeat(8) + + private val profile = """{"kind":0,"created_at":1735689600,"tags":[],""" + + """"content":"{\"name\":\"Translation collective\",\"about\":\"Hard books\"}"}""" + + @Test + fun `a pasted profile is read back as the signing screen would say it`() = render(state()) { + onNodeWithText("Unsigned event").performTextInput(profile) + + onNodeWithText("What the group would sign").assertIsDisplayed() + onNodeWithText("Kind 0 · Nostr profile").assertIsDisplayed() + onNodeWithText("Translation collective · Hard books").assertIsDisplayed() + } + + @Test + fun `a pasted post is read back by its words`() = render(state()) { + onNodeWithText("Unsigned event").performTextInput("""{"kind": 1, "content": "We meet on Thursday"}""") + + onNodeWithText("Kind 1 · Post").assertIsDisplayed() + onNodeWithText("We meet on Thursday").assertIsDisplayed() + } + + @Test + fun `junk is named as junk`() = + render(state()) { + onNodeWithText("Unsigned event").performTextInput("this is not an event") + onNodeWithText("That isn't JSON.").assertIsDisplayed() + onNodeWithText("What the group would sign").assertDoesNotExist() + } + + @Test + fun `a kind the screen cannot file is refused with the kinds it can`() = render(state()) { + onNodeWithText("Unsigned event").performTextInput("""{"kind": 30023, "content": "An article"}""") + + onNodeWithText("Kind 30023 has nowhere to go on the group's screen.", substring = true) + .assertIsDisplayed() + onNodeWithText("It can file kinds 0, 1.", substring = true).assertIsDisplayed() + } + + @Test + fun `a relay list is refused, since the group's relay lists did not come back`() = render(state()) { + onNodeWithText("Unsigned event").performTextInput("""{"kind": 10002, "tags": []}""") + + onNodeWithText("Kind 10002 has nowhere to go on the group's screen.", substring = true) + .assertIsDisplayed() + } + + @Test + fun `a member holding no share of the key is told so and the button is inert`() = render( + state(canSign = false) + ) { + onNodeWithText("This group has no shared key, so it cannot sign an event.", substring = true) + .assertIsDisplayed() + onNodeWithContentDescription("Propose event").assertIsNotEnabled() + } + + private fun state(canSign: Boolean = true) = ProposeGroupEventUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = chatRoomId, + userPublicKey = "a".repeat(64), + subject = "Translation room", + description = "A group translating hard books.", + initialGiftWrapPayloadId = "sdfaer", + mlsGroupState = "state" + ) + ), + canSign = canSign, + ) + + private fun render( + uiState: ProposeGroupEventUIState, + assertions: ComposeUiTest.() -> Unit + ) = runDesktopComposeUiTest(width = 400, height = 1200) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + ProposeGroupEventScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = chatRoomId, + relayHint = null, + initialProposeGroupEventUIState = uiState, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + frostSigningRepository = + FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, + onNavigateToRouteAndPopUpInclusive = {}, + onNavigateBack = {}, + ) + } + } + } + } + + assertions() + } +}