diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 7799664c..64a74b12 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -665,4 +665,45 @@ 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 + + + Confederations + None yet + 1 proposal + %1$d proposals + This device holds no confederation proposals naming this group + Propose a confederation + Open + Every group accepted + Declined + Expired + Withdrawn + Proposed by %1$s + Waiting on %1$d of %2$d groups + %1$d of %2$d groups to act + Name + What the confederation is called + Groups + Group npub + The npub of a group with a public nostr profile + Add group + Remove group + That is not an npub + That group is already on the proposal + Looking for its public profile… + No public profile found, so it cannot take part + This group has no public profile on the relays yet. Broadcast its profile first. + Groups needed to act + %1$d of %2$d groups must take part for the confederation to sign + Fewer groups needed + More groups needed + Open for %1$d days + Shorter + Longer + You will coordinate its key ceremony, and every group that accepts discloses its admins to you. + This group discloses its %1$d admins and its threshold of %2$d to you + Only one of the group's admins can propose a confederation + This group cannot take part: it needs at least as many admins as its threshold, and a threshold of two or more + Propose confederation + Couldn't propose the confederation diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt index 46371999..b11f762d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationDao.kt @@ -40,6 +40,14 @@ abstract class ConfederationDao { ) abstract suspend fun getProposalsNaming(groupPublicKey: HexKey): List + /** Every proposal naming [groupPublicKey] and everything said about each, as it changes. */ + @Query( + "SELECT * FROM ConfederationEvent WHERE proposalId IN " + + "(SELECT proposalId FROM ConfederationInvitee WHERE groupPublicKey = :groupPublicKey) " + + "ORDER BY eventCreatedAt ASC, id ASC" + ) + abstract fun observeEventsNaming(groupPublicKey: HexKey): Flow> + /** Every proposal this device holds, for the relay filter and the coordinator's sweep. */ @Query("SELECT * FROM ConfederationEvent WHERE kind = ${ConfederationKinds.PROPOSAL} ORDER BY eventCreatedAt DESC, id DESC") abstract suspend fun getProposals(): List diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index dab92526..3bea3fe6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -524,6 +524,25 @@ data class ChatMessage( * dispatches on. A type missing from here renders as a chat bubble, * silently, looking exactly like somebody having said it. */ + /** + * What a group said about a confederation, or had said to it (docs/confederation.md, + * Phase 6): a proposal, an acceptance, a rejection, a withdrawal. System lines, + * written by each device from the confederation's own table the first time it files + * the event -- whether a session here signed it or a relay brought it -- so the line + * is written once without a key to dedupe on. + */ + const val TYPE_CONFEDERATION_PROPOSED = "confederationProposed" + const val TYPE_CONFEDERATION_ACCEPTED = "confederationAccepted" + const val TYPE_CONFEDERATION_REJECTED = "confederationRejected" + const val TYPE_CONFEDERATION_WITHDRAWN = "confederationWithdrawn" + + val CONFEDERATION_TYPES = setOf( + TYPE_CONFEDERATION_PROPOSED, + TYPE_CONFEDERATION_ACCEPTED, + TYPE_CONFEDERATION_REJECTED, + TYPE_CONFEDERATION_WITHDRAWN, + ) + val GROUP_IDENTITY_TYPES = setOf( TYPE_GROUP_PROFILE_SIGNED, TYPE_LEGACY_GROUP_RELAYS_SIGNED, @@ -531,7 +550,7 @@ data class ChatMessage( TYPE_LEGACY_GROUP_SCHEMA_SIGNED, TYPE_LEGACY_GROUP_ENTRY_CURATED, TYPE_WALLET_NOT_TAKEN_PART_IN, - ) + ) + CONFEDERATION_TYPES /** * Every subgroup line, for the one check the transcript dispatches on. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 9d6e6da1..5451ae8d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -246,6 +246,9 @@ class DatabaseChatRepository( null } + override suspend fun confederationProposalCount(chatRoomId: String): Int = + database.confederationDao().getProposalsNaming(chatRoomId).size + override suspend fun canSign(chatRoomId: String): Boolean = try { FrostSigningManager.canSign(database, chatRoomId) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt index 37b0b098..89594c1a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseConfederationRepository.kt @@ -10,6 +10,12 @@ import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ConfederationEvent +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.managers.RoomAdmins +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationStatus import mobi.giza.compose.managers.ConfederationManager import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent import mobi.giza.compose.repository.ConfederationRepository @@ -39,4 +45,64 @@ class DatabaseConfederationRepository( override suspend fun relayHintsFor(proposalId: HexKey): List = ConfederationManager.proposal(database, proposalId)?.groups?.mapNotNull { it.relayHint }?.distinct().orEmpty() + + override fun observeStatusesNaming(groupPublicKey: HexKey): Flow> = + database.confederationDao().observeEventsNaming(groupPublicKey).map { rows -> + val now = Clock.System.now().epochSeconds + rows.groupBy { it.proposalId }.values.mapNotNull { events -> + val proposal = events.firstOrNull { it.kind == ConfederationKinds.PROPOSAL && it.id == it.proposalId } + ?.let { ConfederationProposalEvent.parse(it.toEvent()) } ?: return@mapNotNull null + ConfederationManager.statusOf(proposal, events, now) + }.sortedWith(compareByDescending { it.proposal.createdAt }.thenBy { it.proposal.id }) + } + + override fun observeStatus(proposalId: HexKey): Flow = + database.confederationDao().observeEventsForProposal(proposalId).map { rows -> + val proposal = rows.firstOrNull { it.kind == ConfederationKinds.PROPOSAL && it.id == proposalId } + ?.let { ConfederationProposalEvent.parse(it.toEvent()) } ?: return@map null + ConfederationManager.statusOf(proposal, rows) + } + + override suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey): Boolean = + RoomAdmins.of(database, chatRoomId)?.admins?.contains(userPublicKey) == true + + override suspend fun disclosure(chatRoomId: String): ConfederationManager.Disclosure? = + ConfederationManager.disclosureFor(database, chatRoomId) + + override suspend fun nameOf(groupPublicKey: HexKey, inRoom: String?): String = + ConfederationManager.nameOf(database, groupPublicKey, inRoom) + + override suspend fun proposeConfederation( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + invitees: List, + threshold: Int, + name: String, + expiresAt: Long, + ): FrostSigningSession = ConfederationManager.proposeConfederation( + database, localChatRoom, userPublicKey, invitees, threshold, name, expiresAt, + ) + + override suspend fun proposeAcceptance(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey) = + ConfederationManager.proposeAcceptance(database, localChatRoom, userPublicKey, proposalId) + + override suspend fun proposeRejection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey, reason: String) = + ConfederationManager.proposeRejection(database, localChatRoom, userPublicKey, proposalId, reason) + + override suspend fun proposeWithdrawal(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey) = + ConfederationManager.proposeWithdrawal(database, localChatRoom, userPublicKey, proposalId) + + override fun observePendingAnswer(chatRoomId: String, proposalId: HexKey): Flow = + database.frostSigningSessionDao().observeSessionsForChatRoom(chatRoomId).map { sessions -> + sessions.firstOrNull { local -> + local.session.stage != FrostSigningStage.COMPLETE && + local.session.stage != FrostSigningStage.FAILED && + local.items.any { item -> + Event.fromJsonOrNull(item.unsignedEventJson)?.let { event -> + event.kind in ConfederationKinds.ALL && + (event.id == proposalId || event.tags.any { it.size > 1 && it[0] == "e" && it[1] == proposalId }) + } == true + } + }?.session + } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt index 45237880..278d8a63 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt @@ -7,7 +7,11 @@ import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate import com.vitorpamplona.crypto.random.RandomInstance import kotlin.time.Clock import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ChatMessage import mobi.giza.compose.database.model.ConfederationEvent +import mobi.giza.compose.extensions.toNpub +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import kotlin.time.Instant import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex @@ -58,7 +62,7 @@ object ConfederationManager { return false } - return database.confederationDao().record( + val filed = database.confederationDao().record( ConfederationEvent( id = event.id, kind = event.kind, @@ -69,6 +73,64 @@ object ConfederationManager { ), invitees = invitees, ) + // Once per event, by construction: the row above is written once. + if (filed) runCatching { announce(database, event, proposalId) } + .onFailure { logger.w(throwable = it) { "Filed ${event.id.take(8)} but could not write its line" } } + return filed + } + + /** + * A system line in every room on this device that [event] concerns: each group its + * proposal names (docs/confederation.md, Phase 6). An answer whose proposal this device does + * not hold yet gets no line; the proposal's own line says who has answered when it comes. + */ + private suspend fun announce(database: GizaDatabase, event: Event, proposalId: HexKey) { + val proposal = proposal(database, proposalId) ?: return + val rooms = proposal.groupPublicKeys.mapNotNull { database.chatRoomDao().findChatRoomById(it) } + if (rooms.isEmpty()) return + + rooms.forEach { room -> + val roomId = room.chatRoom.id + val who = nameOf(database, event.pubKey, roomId) + val (type, content) = when (event.kind) { + ConfederationKinds.PROPOSAL -> + ChatMessage.TYPE_CONFEDERATION_PROPOSED to if (event.pubKey == roomId) { + "This group proposed a confederation, ${proposal.name}, of ${proposal.groups.size} groups" + } else { + "$who invited this group to a confederation, ${proposal.name}" + } + ConfederationKinds.ACCEPTANCE -> + ChatMessage.TYPE_CONFEDERATION_ACCEPTED to "$who accepted the confederation ${proposal.name}" + ConfederationKinds.REJECTION -> + ChatMessage.TYPE_CONFEDERATION_REJECTED to "$who declined the confederation ${proposal.name}" + ConfederationKinds.WITHDRAWAL -> + ChatMessage.TYPE_CONFEDERATION_WITHDRAWN to "$who withdrew the proposed confederation ${proposal.name}" + else -> return@forEach + } + database.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = event.pubKey, + isUserMessage = false, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = roomId, + content = content, + messageType = type, + createdAt = Instant.fromEpochSeconds(event.createdAt), + ) + ) + } + } + + /** How a line names a group: "This group" in its own room, else its profile's name or its npub. */ + suspend fun nameOf(database: GizaDatabase, group: HexKey, inRoom: String? = null): String { + if (group == inRoom) return "This group" + val profile = database.profileDao().getProfileByPublicKey(group)?.takeIf { it.isResolved() } + return profile?.displayName?.takeIf { it.isNotBlank() } + ?: profile?.userName?.takeIf { it.isNotBlank() } + ?: database.chatRoomDao().findChatRoomById(group)?.chatRoom?.subject?.takeIf { it.isNotBlank() } + ?: (group.hexToByteArray().toNpub().take(14) + "…") } /** @@ -127,6 +189,11 @@ object ConfederationManager { /** The admins and threshold [adminListFor] reads, before there is a proposal id to bind them to. */ class Disclosure(val group: HexKey, val admins: Set, val threshold: Int) { fun listFor(proposalId: HexKey): ConfederationAdminList? = ConfederationAdminList.of(proposalId, group, threshold, admins) + + /** Whether upstream's roster would take this group as it stands: `2 <= t_g <= n_g`. */ + val canTakePart: Boolean + get() = threshold >= ConfederationKinds.MIN_INNER_THRESHOLD && threshold <= admins.size && + admins.all(ConfederationKinds::isPublicKey) } suspend fun disclosureFor(database: GizaDatabase, chatRoomId: String): Disclosure? { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index c205a67f..19c7c415 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -132,6 +132,9 @@ interface ChatRepository { */ suspend fun canSign(chatRoomId: String): Boolean + /** How many confederation proposals naming [chatRoomId] this device holds. docs/confederation.md. */ + suspend fun confederationProposalCount(chatRoomId: String): Int = 0 + /** * Why these members cannot hold a subgroup ceremony together, or null when * they can. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt index 60fae06b..152d86b8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ConfederationRepository.kt @@ -3,8 +3,14 @@ package mobi.giza.compose.repository import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf import kotlin.time.Instant import mobi.giza.compose.database.model.ConfederationEvent +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.managers.ConfederationManager +import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent +import mobi.giza.compose.nostr.confederation.ConfederationStatus /** * The confederation's events on this device, for the relay layer and the screens @@ -24,4 +30,68 @@ interface ConfederationRepository { /** Where to send an event about [proposalId]: the relays the proposal hints at for its groups. */ suspend fun relayHintsFor(proposalId: HexKey): List + + /** Every proposal naming the group [groupPublicKey], newest first, with where each stands. */ + fun observeStatusesNaming(groupPublicKey: HexKey): Flow> + + /** Where [proposalId] stands, as it changes. Null while this device does not hold it. */ + fun observeStatus(proposalId: HexKey): Flow + + /** Whether [userPublicKey] is one of [chatRoomId]'s current admins, and so may coordinate (D4). */ + suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey): Boolean + + /** What an acceptance by [chatRoomId] would disclose, read as its signers will read it. Null when it could not take part. */ + suspend fun disclosure(chatRoomId: String): ConfederationManager.Disclosure? + + /** How a line or a screen names a group. */ + suspend fun nameOf(groupPublicKey: HexKey, inRoom: String? = null): String + + suspend fun proposeConfederation( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + invitees: List, + threshold: Int, + name: String, + expiresAt: Long, + ): FrostSigningSession + + suspend fun proposeAcceptance(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey): FrostSigningSession + + suspend fun proposeRejection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey, reason: String): FrostSigningSession + + suspend fun proposeWithdrawal(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey): FrostSigningSession + + /** A signing session this room has open over an answer to [proposalId], if any: one at a time. */ + fun observePendingAnswer(chatRoomId: String, proposalId: HexKey): Flow + + companion object { + /** Holds nothing and proposes nothing: for screens and tests with no confederation behind them. */ + val NO_OP_CONFEDERATION_REPOSITORY: ConfederationRepository = object : ConfederationRepository { + override suspend fun record(event: Event): Boolean = false + override fun observeUnpublished(): Flow> = flowOf(emptyList()) + override suspend fun markPublished(eventId: HexKey, at: Instant) = Unit + override fun observeOpenProposalIds(): Flow> = flowOf(emptyList()) + override suspend fun relayHintsFor(proposalId: HexKey): List = emptyList() + override fun observeStatusesNaming(groupPublicKey: HexKey): Flow> = flowOf(emptyList()) + override fun observeStatus(proposalId: HexKey): Flow = flowOf(null) + override suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey): Boolean = false + override suspend fun disclosure(chatRoomId: String): ConfederationManager.Disclosure? = null + override suspend fun nameOf(groupPublicKey: HexKey, inRoom: String?): String = groupPublicKey.take(8) + override suspend fun proposeConfederation( + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + invitees: List, + threshold: Int, + name: String, + expiresAt: Long, + ): FrostSigningSession = throw UnsupportedOperationException("No confederation here") + override suspend fun proposeAcceptance(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey): FrostSigningSession = + throw UnsupportedOperationException("No confederation here") + override suspend fun proposeRejection(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey, reason: String): FrostSigningSession = + throw UnsupportedOperationException("No confederation here") + override suspend fun proposeWithdrawal(localChatRoom: LocalChatRoom, userPublicKey: HexKey, proposalId: HexKey): FrostSigningSession = + throw UnsupportedOperationException("No confederation here") + override fun observePendingAnswer(chatRoomId: String, proposalId: HexKey): Flow = flowOf(null) + } + } } 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 b0f025ad..d0f41f97 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 @@ -9,6 +9,13 @@ import mobi.giza.compose.resources.one_post import mobi.giza.compose.resources.no_posts_yet import mobi.giza.compose.resources.posts import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute +import mobi.giza.compose.ExperimentalFeatures +import androidx.compose.material.icons.filled.Hub +import mobi.giza.compose.resources.confederations +import mobi.giza.compose.resources.no_confederations_yet +import mobi.giza.compose.resources.one_confederation_proposal +import mobi.giza.compose.resources.n_confederation_proposals import androidx.compose.material.icons.filled.Campaign import mobi.giza.compose.resources.not_described_yet import mobi.giza.compose.resources.no_name_on_this_profile @@ -705,6 +712,25 @@ fun ChatRoomDetailScreen( ) } + // The confederations naming this group, and the way into + // proposing one (docs/confederation.md). Every member can + // read them; the screen behind it gates proposing. + if (ExperimentalFeatures.confederation) { + item { + ConfederationsRow( + proposalCount = chatRoomDetailUIState.confederationProposalCount, + onClick = { + onNavigateToRoute.invoke( + ConfederationsRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + ) + ) + } + ) + } + } + // 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 @@ -2106,3 +2132,36 @@ private fun GroupPostsRow( ) } } + +/** The row that opens a group's confederations: how many proposals name it. docs/confederation.md. */ +@Composable +private fun ConfederationsRow( + proposalCount: Int, + onClick: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + onClick = onClick + ) { + ListItem( + leadingContent = { + Icon(Icons.Default.Hub, contentDescription = Decorative) + }, + trailingContent = { + Icon(Icons.Default.ChevronRight, contentDescription = Decorative) + }, + headlineContent = { + Text(text = stringResource(Res.string.confederations)) + }, + supportingContent = { + Text( + text = when (proposalCount) { + 0 -> stringResource(Res.string.no_confederations_yet) + 1 -> stringResource(Res.string.one_confederation_proposal) + else -> stringResource(Res.string.n_confederation_proposals, proposalCount) + } + ) + } + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt new file mode 100644 index 00000000..d8411586 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt @@ -0,0 +1,186 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Hub +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.nostr.confederation.ConfederationProposalState +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.confederation_accepted +import mobi.giza.compose.resources.confederation_expired +import mobi.giza.compose.resources.confederation_groups_to_act +import mobi.giza.compose.resources.confederation_open +import mobi.giza.compose.resources.confederation_proposed_by +import mobi.giza.compose.resources.confederation_rejected +import mobi.giza.compose.resources.confederation_waiting_on_groups +import mobi.giza.compose.resources.confederation_withdrawn +import mobi.giza.compose.resources.confederations +import mobi.giza.compose.resources.propose_a_confederation +import mobi.giza.compose.resources.this_device_holds_no_confederation_proposals_for_this_group +import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +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.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.ConfederationsViewModel +import mobi.giza.compose.ui.view.state.ConfederationsUIState +import org.jetbrains.compose.resources.stringResource + +/** + * Every confederation proposal naming a group, its own and the ones inviting it, newest first + * (docs/confederation.md, Phase 6). Watched, so an answer a relay brings shows while the screen + * is open. An admin holding a share finds the way into proposing one here. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ConfederationsScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + initialConfederationsUIState: ConfederationsUIState = ConfederationsUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val confederationsViewModel: ConfederationsViewModel = viewModel( + factory = ConfederationsViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + initialConfederationsUIState = initialConfederationsUIState, + chatRepository = chatRepository, + confederationRepository = confederationRepository, + ) + ) + + LaunchedEffect(true) { + if (initialConfederationsUIState == ConfederationsUIState.Loading) { + confederationsViewModel.initiate() + } + } + + val state = confederationsViewModel.confederationsUIState + val canPropose = (state as? ConfederationsUIState.Loaded)?.canPropose == true && LocalCanSign.current + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.confederations), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) } + ) + }, + floatingActionButton = { + if (canPropose) { + ExtendedFab( + label = stringResource(Res.string.propose_a_confederation), + icon = { Icon(Icons.Default.Hub, contentDescription = Decorative) }, + onClick = { + onNavigateToRoute(ProposeConfederationRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) + } + ) + } + } + ) { padding -> + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + // Nothing to retry: the room came from a navigation argument. + is ConfederationsUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = current.message, onRetry = null) + + ConfederationsUIState.Loading -> Column( + modifier = Modifier.fillMaxWidth().padding(padding).padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + LoadingDataIndicator(fillScreen = false) + } + + is ConfederationsUIState.Loaded -> LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + if (current.proposals.isEmpty()) { + item { + EmptyState( + message = stringResource(Res.string.this_device_holds_no_confederation_proposals_for_this_group), + icon = Icons.Default.Hub, + ) + } + } else { + items(items = current.proposals, key = { it.status.proposal.id }) { item -> + ConfederationProposalCard(item = item) + } + } + } + } + } + } +} + +/** One proposal: what it is called, who made it, how many must act, and where it stands. */ +@Composable +private fun ConfederationProposalCard(item: ConfederationsUIState.Item) { + val status = item.status + val proposal = status.proposal + val groups = proposal.groups.size + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { Icon(Icons.Default.Hub, contentDescription = Decorative) }, + overlineContent = { Text(text = stateLabel(status.state)) }, + headlineContent = { Text(text = proposal.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Column { + Text(text = stringResource(Res.string.confederation_proposed_by, item.proposerName)) + Text(text = stringResource(Res.string.confederation_groups_to_act, proposal.threshold, groups)) + if (status.state == ConfederationProposalState.OPEN) { + Text(text = stringResource(Res.string.confederation_waiting_on_groups, status.waitingOn.size, groups)) + } + } + }, + ) + } +} + +@Composable +internal fun stateLabel(state: ConfederationProposalState): String = stringResource( + when (state) { + ConfederationProposalState.OPEN -> Res.string.confederation_open + ConfederationProposalState.ACCEPTED -> Res.string.confederation_accepted + ConfederationProposalState.REJECTED -> Res.string.confederation_rejected + ConfederationProposalState.EXPIRED -> Res.string.confederation_expired + ConfederationProposalState.WITHDRAWN -> Res.string.confederation_withdrawn + } +) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt new file mode 100644 index 00000000..ebeed1dd --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ProposeConfederationScreen.kt @@ -0,0 +1,336 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.input.clearText +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Hub +import androidx.compose.material.icons.filled.Remove +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilledIconButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import mobi.giza.compose.extensions.toNpub +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.repository.NostrRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.add_group +import mobi.giza.compose.resources.confederation_groups +import mobi.giza.compose.resources.confederation_name +import mobi.giza.compose.resources.confederation_name_supporting +import mobi.giza.compose.resources.could_not_propose_the_confederation +import mobi.giza.compose.resources.fewer_groups_needed +import mobi.giza.compose.resources.group_npub +import mobi.giza.compose.resources.group_npub_supporting +import mobi.giza.compose.resources.groups_needed_to_act +import mobi.giza.compose.resources.groups_needed_to_act_supporting +import mobi.giza.compose.resources.longer +import mobi.giza.compose.resources.looking_for_its_public_profile +import mobi.giza.compose.resources.more_groups_needed +import mobi.giza.compose.resources.no_public_profile_found +import mobi.giza.compose.resources.of +import mobi.giza.compose.resources.only_an_admin_can_propose_a_confederation +import mobi.giza.compose.resources.open_for_days +import mobi.giza.compose.resources.propose_a_confederation +import mobi.giza.compose.resources.propose_confederation +import mobi.giza.compose.resources.remove_group +import mobi.giza.compose.resources.shorter +import mobi.giza.compose.resources.that_group_is_already_on_the_proposal +import mobi.giza.compose.resources.that_is_not_an_npub +import mobi.giza.compose.resources.this_group_cannot_take_part_in_a_confederation +import mobi.giza.compose.resources.this_group_discloses_its_admins +import mobi.giza.compose.resources.this_group_has_no_public_profile +import mobi.giza.compose.resources.you_will_coordinate_the_confederation +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.Decorative +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.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.ProposeConfederationViewModel +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.GroupLookup +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.Lookup +import org.jetbrains.compose.resources.stringResource + +/** + * Proposing that this group and others form a confederation (docs/confederation.md, Phase 6). + * + * Says before anything else what proposing means for the member doing it: they coordinate the + * key ceremony, and every group that accepts discloses its admins to them. Every group is shown + * by the profile the relays returned for it, since only a group with a public profile can take + * part (D2). Proposing opens the group's own signing session, and the screen hands over to it. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ProposeConfederationScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + initialProposeConfederationUIState: ProposeConfederationUIState = ProposeConfederationUIState.Loading, + chatRepository: ChatRepository, + nostrRepository: NostrRepository, + confederationRepository: ConfederationRepository, + onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: ProposeConfederationViewModel = viewModel( + factory = ProposeConfederationViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + initialProposeConfederationUIState = initialProposeConfederationUIState, + chatRepository = chatRepository, + nostrRepository = nostrRepository, + confederationRepository = confederationRepository, + ) + ) + + LaunchedEffect(true) { + if (initialProposeConfederationUIState == ProposeConfederationUIState.Loading) viewModel.initiate() + } + + // Read out here: both are composable and an onClick lambda is not. + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotPropose = stringResource(Res.string.could_not_propose_the_confederation) + val notAnNpub = stringResource(Res.string.that_is_not_an_npub) + val alreadyOnIt = stringResource(Res.string.that_group_is_already_on_the_proposal) + + val nameField = rememberTextFieldState() + val npubField = rememberTextFieldState() + val state by viewModel.uiState.collectAsState() + val identityCanSign = LocalCanSign.current + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.propose_a_confederation), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + floatingActionButton = { + val loaded = state as? ProposeConfederationUIState.Loaded + if (loaded != null) { + ExtendedFab( + label = stringResource(Res.string.propose_confederation), + icon = { Icon(Icons.Default.Hub, contentDescription = Decorative) }, + enabled = identityCanSign && loaded.canPropose(nameField.text.toString()), + onClick = { + viewModel.propose( + name = nameField.text.toString(), + onSuccess = { sessionId -> + // Onto the session: nothing is proposed to anyone until the + // group signs, and the session is where that happens. + onNavigateToRouteAndPopUpInclusive( + FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId) + ) + }, + onFailure = { notify(couldNotPropose) }, + ) + }, + ) + } + }, + ) { padding -> + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + is ProposeConfederationUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = current.message, onRetry = null) + + ProposeConfederationUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) + + is ProposeConfederationUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + Text( + text = stringResource(Res.string.you_will_coordinate_the_confederation), + style = MaterialTheme.typography.bodyMedium, + ) + if (!current.isAdmin) { + Text( + text = stringResource(Res.string.only_an_admin_can_propose_a_confederation), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + if (current.adminCount != null && current.groupThreshold != null) { + Text( + text = stringResource(Res.string.this_group_discloses_its_admins, current.adminCount, current.groupThreshold), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } else { + Text( + text = stringResource(Res.string.this_group_cannot_take_part_in_a_confederation), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = nameField, + label = { Text(stringResource(Res.string.confederation_name)) }, + supportingText = { Text(stringResource(Res.string.confederation_name_supporting)) }, + lineLimits = androidx.compose.foundation.text.input.TextFieldLineLimits.SingleLine, + ) + + Text(text = stringResource(Res.string.confederation_groups), style = MaterialTheme.typography.titleSmall) + GroupLookupRow(group = current.ownGroup, isThisGroup = true, onRemove = null) + if (current.ownGroup.lookup is Lookup.NotFound) { + Text( + text = stringResource(Res.string.this_group_has_no_public_profile), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + current.invitees.forEach { invitee -> + GroupLookupRow(group = invitee, isThisGroup = false, onRemove = { viewModel.removeGroup(invitee.publicKey) }) + } + + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = npubField, + label = { Text(stringResource(Res.string.group_npub)) }, + supportingText = { Text(stringResource(Res.string.group_npub_supporting)) }, + lineLimits = androidx.compose.foundation.text.input.TextFieldLineLimits.SingleLine, + ) + TextButton( + onClick = { + when (viewModel.addGroup(npubField.text.toString())) { + ProposeConfederationViewModel.AddResult.ADDED -> npubField.clearText() + ProposeConfederationViewModel.AddResult.NOT_AN_NPUB -> notify(notAnNpub) + ProposeConfederationViewModel.AddResult.ALREADY_ON_IT -> notify(alreadyOnIt) + } + } + ) { + Icon(Icons.Default.Add, contentDescription = Decorative) + Text(text = stringResource(Res.string.add_group)) + } + + Stepper( + title = stringResource(Res.string.groups_needed_to_act), + value = stringResource(Res.string.of, current.threshold, current.groupCount), + supporting = stringResource(Res.string.groups_needed_to_act_supporting, current.threshold, current.groupCount), + canDecrease = current.threshold > 2, + canIncrease = current.threshold < current.groupCount, + decrease = stringResource(Res.string.fewer_groups_needed), + increase = stringResource(Res.string.more_groups_needed), + onChange = { viewModel.setThreshold(current.threshold + it) }, + ) + + Stepper( + title = stringResource(Res.string.open_for_days, current.expiryDays), + value = current.expiryDays.toString(), + supporting = null, + canDecrease = current.expiryDays > 1, + canIncrease = current.expiryDays < ProposeConfederationViewModel.MAX_EXPIRY_DAYS, + decrease = stringResource(Res.string.shorter), + increase = stringResource(Res.string.longer), + onChange = { viewModel.setExpiryDays(current.expiryDays + it) }, + ) + } + } + } + } +} + +/** A group on the proposal, by the profile the relays returned, or what is still being asked. */ +@Composable +private fun GroupLookupRow(group: GroupLookup, isThisGroup: Boolean, onRemove: (() -> Unit)?) { + val found = group.lookup as? Lookup.Found + val npub = group.publicKey.hexToByteArray().toNpub() + ListItem( + leadingContent = { + ProfileAvatar(size = MaterialTheme.spacing.space500, publicKey = group.publicKey, picture = found?.picture, name = found?.name) + }, + headlineContent = { Text(text = found?.name ?: npub, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + when (group.lookup) { + Lookup.Looking -> Text(stringResource(Res.string.looking_for_its_public_profile)) + Lookup.NotFound -> Text(stringResource(Res.string.no_public_profile_found), color = MaterialTheme.colorScheme.error) + is Lookup.Found -> Text(text = npub, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + }, + trailingContent = if (onRemove != null && !isThisGroup) { + { + IconButton(onClick = onRemove) { + Icon(Icons.Default.Close, contentDescription = stringResource(Res.string.remove_group)) + } + } + } else { + null + }, + ) +} + +@Composable +private fun Stepper( + title: String, + value: String, + supporting: String?, + canDecrease: Boolean, + canIncrease: Boolean, + decrease: String, + increase: String, + onChange: (Int) -> Unit, +) { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text(text = title, style = MaterialTheme.typography.titleSmall) + Row( + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + verticalAlignment = Alignment.CenterVertically, + ) { + FilledIconButton(onClick = { onChange(-1) }, enabled = canDecrease) { + Icon(Icons.Default.Remove, contentDescription = decrease) + } + Text(text = value, style = MaterialTheme.typography.titleMedium) + FilledIconButton(onClick = { onChange(1) }, enabled = canIncrease) { + Icon(Icons.Default.Add, contentDescription = increase) + } + } + if (supporting != null) { + Text(text = supporting, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} 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 29f55d1c..71b91cc8 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 @@ -5,6 +5,10 @@ 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 +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute +import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRoute +import mobi.giza.compose.ui.composable.ConfederationsScreen +import mobi.giza.compose.ui.composable.ProposeConfederationScreen import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute import mobi.giza.compose.ui.composable.AddGroupPostScreen import mobi.giza.compose.ui.composable.GroupPostsScreen @@ -1284,6 +1288,38 @@ fun GizaNavHost( } ) } + // A group's confederations: docs/confederation.md. + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + ConfederationsScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + chatRepository = databaseChatRepository, + confederationRepository = databaseConfederationRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() } + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + ProposeConfederationScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + chatRepository = databaseChatRepository, + nostrRepository = databaseNostrRepository, + confederationRepository = databaseConfederationRepository, + onNavigateToRouteAndPopUpInclusive = { signingRoute -> + // Replace the form: back from the session returns to the list, not + // to a proposal that has already gone out. + navController.navigate(route = signingRoute) { + popUpTo { inclusive = true } + } + }, + onNavigateBack = { navController.popBackStack() } + ) + } // The group's posts: docs/group-nostr-profile-and-posts.md. composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationsRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationsRoute.kt new file mode 100644 index 00000000..7928658d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationsRoute.kt @@ -0,0 +1,10 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** Every confederation proposal naming a group, and the way into proposing one. docs/confederation.md, Phase 6. */ +@Serializable +data class ConfederationsRoute( + val activeUserPublicKey: String, + val chatRoomId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ProposeConfederationRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ProposeConfederationRoute.kt new file mode 100644 index 00000000..64451e0b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ProposeConfederationRoute.kt @@ -0,0 +1,10 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** The form for proposing a confederation of groups. docs/confederation.md, Phase 6. */ +@Serializable +data class ProposeConfederationRoute( + val activeUserPublicKey: String, + val chatRoomId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt index cc4cfb42..94388ca1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -42,9 +42,11 @@ import androidx.compose.material.icons.filled.FactCheck import androidx.compose.material.icons.filled.Draw import androidx.compose.material.icons.filled.Download import androidx.compose.material.icons.filled.History +import androidx.compose.material.icons.filled.Hub import androidx.compose.material.icons.filled.Groups import androidx.compose.material.icons.filled.PanTool import androidx.compose.material.icons.filled.PersonAdd +import androidx.compose.material.icons.filled.Undo import androidx.compose.material.icons.filled.Upload import androidx.compose.material.icons.filled.WorkspacePremium import androidx.compose.material.icons.filled.Info @@ -887,6 +889,11 @@ private fun RitualNotice( ChatMessage.TYPE_ADMIN_OFFERED -> Icons.Default.AdminPanelSettings ChatMessage.TYPE_CHANGE_NOT_APPLIED -> Icons.Default.Block + ChatMessage.TYPE_CONFEDERATION_PROPOSED -> Icons.Default.Hub + ChatMessage.TYPE_CONFEDERATION_ACCEPTED -> Icons.Default.CheckCircle + ChatMessage.TYPE_CONFEDERATION_REJECTED -> Icons.Default.Block + ChatMessage.TYPE_CONFEDERATION_WITHDRAWN -> Icons.Default.Undo + else -> Icons.Default.PanTool } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 036a8462..ad1a7e2e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -132,6 +132,7 @@ class ChatRoomDetailViewModel( canAddSubgroup = canSign && !subgroupsNeedAWallet, groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), groupPosts = chatRepository.groupPosts(chatRoomId), + confederationProposalCount = chatRepository.confederationProposalCount(chatRoomId), canProposeAsGroup = canSign && roomIsOpen, subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, canGovern = canGovern, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt new file mode 100644 index 00000000..aa8a355a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationsViewModel.kt @@ -0,0 +1,81 @@ +package mobi.giza.compose.ui.view.model + +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 com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.launch +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.ui.view.state.ConfederationsUIState + +/** + * Every confederation proposal naming a group, watched rather than read once: an answer + * arrives from a relay while the screen is open, and the screen is where a member waits for it + * (docs/confederation.md, Phase 6). + */ +class ConfederationsViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + initialConfederationsUIState: ConfederationsUIState, + val chatRepository: ChatRepository, + val confederationRepository: ConfederationRepository, +) : ViewModel() { + + var confederationsUIState: ConfederationsUIState by mutableStateOf(initialConfederationsUIState) + private set + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + if (localChatRoom == null) { + confederationsUIState = ConfederationsUIState.Error("Couldn't find the group") + return@launch + } + + val canPropose = GroupStatementCapability.roomIsOpen(localChatRoom) && + chatRepository.canSign(chatRoomId) && + confederationRepository.isAdmin(chatRoomId, activeUserPublicKey) + + confederationRepository.observeStatusesNaming(chatRoomId).collect { statuses -> + confederationsUIState = ConfederationsUIState.Loaded( + localChatRoom = localChatRoom, + proposals = statuses.map { status -> + ConfederationsUIState.Item( + status = status, + proposerName = confederationRepository.nameOf(status.proposal.proposingGroup, chatRoomId), + ) + }, + canPropose = canPropose, + ) + } + } + } + + companion object { + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + initialConfederationsUIState: ConfederationsUIState = ConfederationsUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + ConfederationsViewModel( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + initialConfederationsUIState = initialConfederationsUIState, + chatRepository = chatRepository, + confederationRepository = confederationRepository, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt new file mode 100644 index 00000000..1fb5974c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModel.kt @@ -0,0 +1,221 @@ +package mobi.giza.compose.ui.view.model + +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 com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.identity.CredentialParser +import mobi.giza.compose.nostr.DirectMessagePeerSync +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.repository.NostrRepository +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.GroupLookup +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.Lookup + +/** + * The form a group's admin fills in to propose a confederation (docs/confederation.md, + * Phase 6): the groups, how many must act, a name and how long the proposal stays open. + * + * Every group on it -- this one included -- is looked up on the relays as it is added, and only + * a group whose kind:0 the relays return can take part (D2). A profile this group signed and + * never sent is not public, so this group is looked up the same way. + */ +class ProposeConfederationViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + initialProposeConfederationUIState: ProposeConfederationUIState, + val chatRepository: ChatRepository, + val nostrRepository: NostrRepository, + val confederationRepository: ConfederationRepository, + private val lookupTimeout: Duration = RELAY_LOOKUP_TIMEOUT, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + + /** + * A flow updated atomically rather than a Compose state written in place: profile lookups + * settle on IO threads while the member adds and removes groups on the main one, and a + * read-modify-write from each would lose one of them -- a group left "looking" for good. + */ + private val state = MutableStateFlow(initialProposeConfederationUIState) + val uiState: StateFlow = state.asStateFlow() + + val proposeConfederationUIState: ProposeConfederationUIState get() = state.value + + /** Applies [transform] to the loaded form, atomically; nothing while it is not loaded. */ + private fun updateLoaded(transform: (ProposeConfederationUIState.Loaded) -> ProposeConfederationUIState.Loaded) { + state.update { current -> (current as? ProposeConfederationUIState.Loaded)?.let(transform) ?: current } + } + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + if (localChatRoom == null) { + state.value = ProposeConfederationUIState.Error("Couldn't find the group") + return@launch + } + val disclosure = confederationRepository.disclosure(chatRoomId) + val canTakePart = disclosure?.canTakePart == true + state.value = ProposeConfederationUIState.Loaded( + localChatRoom = localChatRoom, + ownGroup = GroupLookup(chatRoomId, Lookup.Looking), + adminCount = disclosure?.admins?.size?.takeIf { canTakePart }, + groupThreshold = disclosure?.threshold?.takeIf { canTakePart }, + isAdmin = confederationRepository.isAdmin(chatRoomId, activeUserPublicKey), + canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && chatRepository.canSign(chatRoomId), + ) + lookUp(chatRoomId) + } + } + + enum class AddResult { ADDED, NOT_AN_NPUB, ALREADY_ON_IT } + + /** Adds the group [raw] names -- an npub, or its 64-character hex -- and asks the relays for its profile. */ + fun addGroup(raw: String): AddResult { + if (state.value !is ProposeConfederationUIState.Loaded) return AddResult.NOT_AN_NPUB + val token = raw.trim() + val publicKey = CredentialParser.npubOrNull(token) + ?: token.lowercase().takeIf(ConfederationKinds::isPublicKey) + ?: return AddResult.NOT_AN_NPUB + + var result = AddResult.ADDED + updateLoaded { loaded -> + if (publicKey == chatRoomId || loaded.invitees.any { it.publicKey == publicKey } || + loaded.groupCount >= ConfederationKinds.MAX_GROUPS + ) { + result = AddResult.ALREADY_ON_IT + loaded + } else { + result = AddResult.ADDED + loaded.copy( + invitees = loaded.invitees + GroupLookup(publicKey, Lookup.Looking), + // A new group raises the default majority with it, never past what was chosen. + threshold = maxOf(loaded.threshold, defaultThreshold(loaded.groupCount + 1)).coerceAtMost(loaded.groupCount + 1), + ) + } + } + if (result == AddResult.ADDED) lookUp(publicKey) + return result + } + + fun removeGroup(publicKey: HexKey) { + updateLoaded { loaded -> + val invitees = loaded.invitees.filterNot { it.publicKey == publicKey } + loaded.copy( + invitees = invitees, + threshold = loaded.threshold.coerceIn(ConfederationKinds.MIN_GROUPS, maxOf(ConfederationKinds.MIN_GROUPS, invitees.size + 1)), + ) + } + } + + fun setThreshold(threshold: Int) = updateLoaded { loaded -> + loaded.copy(threshold = threshold.coerceIn(ConfederationKinds.MIN_GROUPS, maxOf(ConfederationKinds.MIN_GROUPS, loaded.groupCount))) + } + + fun setExpiryDays(days: Int) = updateLoaded { loaded -> loaded.copy(expiryDays = days.coerceIn(1, MAX_EXPIRY_DAYS)) } + + /** Opens the group's signing session over the proposal and its own acceptance (D3). */ + fun propose(name: String, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + val form = state.value as? ProposeConfederationUIState.Loaded ?: return + if (!form.canPropose(name)) return + updateLoaded { it.copy(isProposing = true) } + + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { + confederationRepository.proposeConfederation( + localChatRoom = form.localChatRoom, + userPublicKey = activeUserPublicKey, + invitees = form.invitees.map { ConfederationProposalEvent.Invitee(it.publicKey) }, + threshold = form.threshold, + name = name.trim(), + expiresAt = Clock.System.now().epochSeconds + form.expiryDays * SECONDS_PER_DAY, + ) + }.onFailure { logger.e("Could not propose a confederation for $chatRoomId", it) }.getOrNull() + + updateLoaded { it.copy(isProposing = false) } + viewModelScope.launch(Dispatchers.Main) { + if (session != null) onSuccess(session.id) else onFailure() + } + } + } + + /** Asks the relays for [publicKey]'s kind:0 and waits a while for it to land (D2). */ + private fun lookUp(publicKey: HexKey) { + // Not cancelled when its group is removed: what it settles then names nobody on the + // form, and is dropped by [settle]. + viewModelScope.launch(Dispatchers.IO) { + runCatching { + nostrRepository.queueSynchronizeNostrEvent(DirectMessagePeerSync.profileRequests(publicKey)) + }.onFailure { logger.w(throwable = it) { "Could not ask the relays about $publicKey" } } + + val profile: Profile? = withTimeoutOrNull(lookupTimeout) { + nostrRepository.observeProfileWithPublicKey(publicKey).first { it?.isResolved() == true } + } + val lookup = profile?.let { + Lookup.Found( + name = it.displayName?.takeIf(String::isNotBlank) ?: it.userName?.takeIf(String::isNotBlank), + picture = it.picture, + ) + } ?: Lookup.NotFound + settle(publicKey, lookup) + } + } + + private fun settle(publicKey: HexKey, lookup: Lookup) = updateLoaded { loaded -> + if (publicKey == chatRoomId) { + loaded.copy(ownGroup = loaded.ownGroup.copy(lookup = lookup)) + } else { + loaded.copy(invitees = loaded.invitees.map { if (it.publicKey == publicKey) it.copy(lookup = lookup) else it }) + } + } + + companion object { + private const val TAG = "ProposeConfederationViewModel" + private const val SECONDS_PER_DAY = 24L * 60 * 60 + val MAX_EXPIRY_DAYS = (ConfederationKinds.MAX_EXPIRY_SECONDS / SECONDS_PER_DAY).toInt() + + /** How long to wait on the relays for a group's profile before saying none was found. */ + val RELAY_LOOKUP_TIMEOUT = 20.seconds + + /** A majority of the groups, never fewer than two: the rule a group's own quorum starts on. */ + fun defaultThreshold(groupCount: Int): Int = maxOf(ConfederationKinds.MIN_GROUPS, groupCount / 2 + 1) + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + initialProposeConfederationUIState: ProposeConfederationUIState = ProposeConfederationUIState.Loading, + chatRepository: ChatRepository, + nostrRepository: NostrRepository, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + ProposeConfederationViewModel( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + initialProposeConfederationUIState = initialProposeConfederationUIState, + chatRepository = chatRepository, + nostrRepository = nostrRepository, + confederationRepository = confederationRepository, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 69b547d3..9790ac1a 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -72,6 +72,8 @@ sealed interface ChatRoomDetailUIState { * device holds. docs/group-nostr-profile-and-posts.md. */ val groupPosts: List = emptyList(), + /** How many confederation proposals naming this group this device holds. docs/confederation.md. */ + val confederationProposalCount: Int = 0, /** * Whether this device could put a profile or a post to the group's quorum: * a Marmot room it has not left, not disbanded, where it holds a share of diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt new file mode 100644 index 00000000..8f5fa118 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationsUIState.kt @@ -0,0 +1,22 @@ +package mobi.giza.compose.ui.view.state + +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.confederation.ConfederationStatus + +/** A group's confederation proposals, as this device holds them (docs/confederation.md, Phase 6). */ +sealed interface ConfederationsUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + /** Every proposal naming this group, its own included, newest first. */ + val proposals: List = emptyList(), + /** Whether this member can propose one: an open keyed room, a share, and an admin (D4). */ + val canPropose: Boolean = false, + ) : ConfederationsUIState + + /** One proposal, and how to name the group that made it. */ + data class Item(val status: ConfederationStatus, val proposerName: String) + + data class Error(val message: String) : ConfederationsUIState + + data object Loading : ConfederationsUIState +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ProposeConfederationUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ProposeConfederationUIState.kt new file mode 100644 index 00000000..2c15e7d3 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ProposeConfederationUIState.kt @@ -0,0 +1,51 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom + +/** The form for proposing a confederation (docs/confederation.md, Phase 6). */ +sealed interface ProposeConfederationUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + /** This group, looked up the way every other is: only a group with a public profile takes part (D2). */ + val ownGroup: GroupLookup, + /** The other groups invited, in the order they were added. */ + val invitees: List = emptyList(), + /** How many groups must take part for the confederation to sign. */ + val threshold: Int = 2, + val expiryDays: Int = 7, + /** What this group's acceptance would disclose, or null if it could not take part as it stands. */ + val adminCount: Int? = null, + val groupThreshold: Int? = null, + /** Whether this member may coordinate: one of the group's current admins (D4). */ + val isAdmin: Boolean = false, + /** Whether this device holds a share of an open room's key. */ + val canSign: Boolean = false, + val isProposing: Boolean = false, + ) : ProposeConfederationUIState { + /** Every group on the proposal, this one first. */ + val groupCount: Int get() = invitees.size + 1 + + val canTakePart: Boolean get() = adminCount != null + + val everyGroupFound: Boolean + get() = ownGroup.lookup is Lookup.Found && invitees.all { it.lookup is Lookup.Found } + + fun canPropose(name: String): Boolean = + canSign && isAdmin && canTakePart && !isProposing && name.isNotBlank() && + invitees.isNotEmpty() && everyGroupFound && threshold in 2..groupCount + } + + /** A group on the proposal, and what the relays said about its profile. */ + data class GroupLookup(val publicKey: HexKey, val lookup: Lookup) + + sealed interface Lookup { + data object Looking : Lookup + data class Found(val name: String?, val picture: String?) : Lookup + data object NotFound : Lookup + } + + data class Error(val message: String) : ProposeConfederationUIState + + data object Loading : ProposeConfederationUIState +} diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt index cdd3176a..b8427194 100644 --- a/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/managers/ConfederationRelayTest.kt @@ -245,7 +245,7 @@ private class ConfederationFakePublisher(var accept: Boolean) : EventPublishTran private class FakeConfederationRepository( openIds: List, private val hints: List = emptyList(), -) : ConfederationRepository { +) : ConfederationRepository by ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY { val openIds = MutableStateFlow(openIds) val owed = MutableStateFlow>(emptyList()) val recorded = mutableListOf() diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt index baece3a9..2b748eea 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt @@ -12,7 +12,11 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile import mobi.giza.compose.database.model.types.FrostSigningSubject import mobi.giza.compose.managers.ConfederationTestGroups.key import mobi.giza.compose.managers.ConfederationTestGroups.npub @@ -114,4 +118,40 @@ class ConfederationStorageJvmTest { assertEquals(proposal.id, db.confederationDao().getEvent(proposal.id)?.id) assertEquals(emptyList(), db.confederationDao().observeUnpublished().first()) } + + private suspend fun room(group: String) { + val eventId = "e".repeat(64) + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = coordinator, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = coordinator, nostrEventId = eventId)) + db.chatRoomDao().upsert(ChatRoom(id = group, userPublicKey = coordinator, subject = "#Polis", description = null, mlsGroupState = "state")) + } + + private suspend fun lines(group: String) = db.chatMessageDao().getChatMessagesByChatRoomId(group) + .map { it.chatMessage } + .filter { it.messageType in ChatMessage.CONFEDERATION_TYPES } + .sortedBy { it.createdAt } + + @Test + fun `an invitation and its answers are lines in the invited room, once each`() = runBlocking { + room(npub(2)) + ConfederationManager.record(db, proposal) + ConfederationManager.record(db, proposal) + ConfederationManager.record(db, ConfederationTestGroups.acceptance(polis, proposal, admins)) + + val written = lines(npub(2)) + assertEquals( + listOf(ChatMessage.TYPE_CONFEDERATION_PROPOSED, ChatMessage.TYPE_CONFEDERATION_ACCEPTED), + written.map { it.messageType }, + "a redelivered proposal writes no second line", + ) + assertTrue(written[0].content.endsWith("invited this group to a confederation, Atlas")) + assertEquals("This group accepted the confederation Atlas", written[1].content) + } + + @Test + fun `a room the proposal does not name gets no line`() = runBlocking { + room(npub(4)) + ConfederationManager.record(db, proposal) + assertEquals(emptyList(), lines(npub(4))) + } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt new file mode 100644 index 00000000..4e764e12 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt @@ -0,0 +1,146 @@ +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.onNodeWithText +import androidx.compose.ui.test.runDesktopComposeUiTest +import kotlin.test.Test +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent +import mobi.giza.compose.nostr.confederation.ConfederationStatus +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.repository.NostrRepository +import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.state.ConfederationsUIState +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.GroupLookup +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.Lookup + +/** The confederation's two screens as a member first meets them (docs/confederation.md, Phase 6). */ +@OptIn(ExperimentalTestApi::class) +class ConfederationScreensJvmTest { + private val roomId = "d4c3b2a1".repeat(8) + private val polis = "a1b2c3d4".repeat(8) + + private val localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = roomId, userPublicKey = "a".repeat(64), subject = "#Agora", description = null, mlsGroupState = "state") + ) + + @Test + fun `the form says who coordinates, what is disclosed, and waits for a name`() = render( + propose = ProposeConfederationUIState.Loaded( + localChatRoom = localChatRoom, + ownGroup = GroupLookup(roomId, Lookup.Found("Agora", null)), + invitees = listOf(GroupLookup(polis, Lookup.Found("Polis", null))), + adminCount = 3, + groupThreshold = 2, + isAdmin = true, + canSign = true, + ) + ) { + onNodeWithText("You will coordinate its key ceremony", substring = true).assertIsDisplayed() + onNodeWithText("This group discloses its 3 admins and its threshold of 2 to you").assertIsDisplayed() + onNodeWithText("Agora").assertIsDisplayed() + onNodeWithText("Polis").assertIsDisplayed() + onNodeWithText("2 of 2 groups must take part for the confederation to sign").assertIsDisplayed() + onNodeWithText("Propose confederation").assertIsNotEnabled() + } + + @Test + fun `a group the relays know nothing of is said to be unable to take part`() = render( + propose = ProposeConfederationUIState.Loaded( + localChatRoom = localChatRoom, + ownGroup = GroupLookup(roomId, Lookup.NotFound), + adminCount = 3, + groupThreshold = 2, + isAdmin = false, + canSign = true, + ) + ) { + onNodeWithText("This group has no public profile on the relays yet", substring = true).assertIsDisplayed() + onNodeWithText("Only one of the group's admins can propose a confederation").assertIsDisplayed() + } + + @Test + fun `a proposal is listed with where it stands`() = renderList( + ConfederationsUIState.Loaded( + localChatRoom = localChatRoom, + proposals = listOf( + ConfederationsUIState.Item( + status = ConfederationStatus.of( + ConfederationProposalEvent.Proposal( + id = "p".padEnd(64, '0'), proposingGroup = polis, createdAt = 1, coordinator = polis, + groups = listOf(ConfederationProposalEvent.Invitee(polis), ConfederationProposalEvent.Invitee(roomId)), + threshold = 2, name = "Atlas", nonce = "0".repeat(64), expiresAt = Long.MAX_VALUE, + ), + emptyList(), now = 2, + ), + proposerName = "Polis", + ) + ), + ) + ) { + onNodeWithText("Atlas").assertIsDisplayed() + onNodeWithText("Open").assertIsDisplayed() + onNodeWithText("Proposed by Polis").assertIsDisplayed() + onNodeWithText("Waiting on 2 of 2 groups").assertIsDisplayed() + } + + @Test + fun `a group with no proposals says this device holds none`() = renderList(ConfederationsUIState.Loaded(localChatRoom = localChatRoom)) { + onNodeWithText("This device holds no confederation proposals naming this group").assertIsDisplayed() + } + + private fun render(propose: ProposeConfederationUIState, assertions: ComposeUiTest.() -> Unit) = + runDesktopComposeUiTest(width = 400, height = 3000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + ProposeConfederationScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = roomId, + initialProposeConfederationUIState = propose, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, + confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateToRouteAndPopUpInclusive = {}, + onNavigateBack = {}, + ) + } + } + } + } + assertions() + } + + private fun renderList(state: ConfederationsUIState, assertions: ComposeUiTest.() -> Unit) = + runDesktopComposeUiTest(width = 400, height = 3000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + ConfederationsScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = roomId, + initialConfederationsUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateToRoute = {}, + onNavigateBack = {}, + ) + } + } + } + } + assertions() + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt new file mode 100644 index 00000000..92a5b5d5 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ProposeConfederationViewModelJvmTest.kt @@ -0,0 +1,225 @@ +package mobi.giza.compose.ui.view.model + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import fr.acinq.bitcoin.PrivateKey +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.Instant +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.ConfederationEvent +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.SynchronizeNostrEventRequest +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.FrostSigningSubject +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.extensions.toNpub +import mobi.giza.compose.managers.ConfederationManager +import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent +import mobi.giza.compose.nostr.confederation.ConfederationStatus +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.repository.NostrRepository +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState +import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.Lookup + +/** + * The form for proposing a confederation (docs/confederation.md, Phase 6): every group, this one + * included, is looked up on the relays and only one with a public profile can be proposed with; + * the button waits on an admin, a share, a name and every group found. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class ProposeConfederationViewModelJvmTest { + private fun npub(n: Int): HexKey = PrivateKey(ByteArray(32).also { it[0] = 0x31; it[31] = n.toByte() }).publicKey().xOnly().value.toHex() + + private val me = npub(9) + private val room = npub(1) + private val polis = npub(2) + private val ekklesia = npub(3) + private val nowhere = npub(4) + + @BeforeTest + fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterTest + fun tearDown() = Dispatchers.resetMain() + + /** Profiles the relays "return", by key. A key absent here is never found. */ + private val relays = mutableMapOf( + room to profile(room, "Agora"), + polis to profile(polis, "Polis"), + ekklesia to profile(ekklesia, "Ekklesia"), + ) + + private fun profile(key: HexKey, name: String) = Profile(publicKey = key, nostrEventId = "e".repeat(64), displayName = name, createdAt = Instant.fromEpochSeconds(1_790_000_000)) + + private val asked = mutableListOf() + + private val nostr = object : NostrRepository by NostrRepository.NO_OP_NOSTR_REPOSITORY { + override suspend fun queueSynchronizeNostrEvent(synchronizeNostrEventRequests: List) { + synchronizeNostrEventRequests.firstOrNull()?.synchronizationFilters?.firstOrNull()?.authors?.firstOrNull()?.let { asked += it } + } + + override suspend fun observeProfileWithPublicKey(publicKey: HexKey): Flow = MutableStateFlow(relays[publicKey]) + } + + private val chat = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom = + LocalChatRoom(ChatRoom(id = id, userPublicKey = me, subject = "#Agora", description = null, mlsGroupState = "state")) + + override suspend fun canSign(chatRoomId: String): Boolean = true + } + + private var proposed: List? = null + private var proposedThreshold: Int? = null + private var admins = setOf(me, npub(10), npub(11)) + + private val confederation = object : ConfederationRepository by ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY { + override suspend fun isAdmin(chatRoomId: String, userPublicKey: HexKey) = userPublicKey in admins + override suspend fun disclosure(chatRoomId: String) = ConfederationManager.Disclosure(chatRoomId, admins, 2) + override suspend fun nameOf(groupPublicKey: HexKey, inRoom: String?) = groupPublicKey.take(8) + override suspend fun proposeConfederation( + localChatRoom: LocalChatRoom, userPublicKey: HexKey, invitees: List, + threshold: Int, name: String, expiresAt: Long, + ): FrostSigningSession { + proposed = invitees + proposedThreshold = threshold + return FrostSigningSession( + id = "s".repeat(64), chatRoomId = localChatRoom.chatRoom.id, coordinatorPublicKey = userPublicKey, + userPublicKey = userPublicKey, dkgSessionId = "k".repeat(64), threshold = 2, participantCount = 3, + signerId = 0, derivationPath = null, subject = FrostSigningSubject.EVENTS, + ) + } + } + + private fun viewModel() = ProposeConfederationViewModel( + activeUserPublicKey = me, + chatRoomId = room, + initialProposeConfederationUIState = ProposeConfederationUIState.Loading, + chatRepository = chat, + nostrRepository = nostr, + confederationRepository = confederation, + lookupTimeout = 300.milliseconds, + ).also { it.initiate() } + + private fun ProposeConfederationViewModel.loaded() = proposeConfederationUIState as ProposeConfederationUIState.Loaded + + private fun eventually(check: () -> Boolean) = runBlocking { + withTimeout(5.seconds) { while (!check()) delay(10) } + } + + @Test + fun `this group is looked up on the relays like any other`() { + val vm = viewModel() + eventually { (vm.proposeConfederationUIState as? ProposeConfederationUIState.Loaded)?.ownGroup?.lookup is Lookup.Found } + assertTrue(room in asked) + assertEquals(3, vm.loaded().adminCount) + } + + @Test + fun `a group added by npub is looked up, and found`() { + val vm = viewModel() + eventually { vm.proposeConfederationUIState is ProposeConfederationUIState.Loaded } + val npub = polis.hexToByteArray().toNpub() + assertEquals(ProposeConfederationViewModel.AddResult.ADDED, vm.addGroup(npub)) + eventually { vm.loaded().invitees.single().lookup is Lookup.Found } + assertEquals("Polis", (vm.loaded().invitees.single().lookup as Lookup.Found).name) + } + + @Test + fun `a group whose profile the relays never return is not found`() { + val vm = viewModel() + eventually { vm.proposeConfederationUIState is ProposeConfederationUIState.Loaded } + vm.addGroup(nowhere) + eventually { vm.loaded().invitees.single().lookup == Lookup.NotFound } + } + + @Test + fun `what is not an npub, this group and a group twice are refused`() { + val vm = viewModel() + eventually { vm.proposeConfederationUIState is ProposeConfederationUIState.Loaded } + assertEquals(ProposeConfederationViewModel.AddResult.NOT_AN_NPUB, vm.addGroup("not a key")) + assertEquals(ProposeConfederationViewModel.AddResult.ALREADY_ON_IT, vm.addGroup(room)) + vm.addGroup(polis) + assertEquals(ProposeConfederationViewModel.AddResult.ALREADY_ON_IT, vm.addGroup(polis)) + } + + @Test + fun `the button waits on a name, every group found, and an admin`() { + val vm = viewModel() + eventually { (vm.proposeConfederationUIState as? ProposeConfederationUIState.Loaded)?.ownGroup?.lookup is Lookup.Found } + assertFalse(vm.loaded().canPropose("Atlas"), "nobody invited yet") + + vm.addGroup(polis) + assertFalse(vm.loaded().canPropose("Atlas"), "still looking") + eventually { vm.loaded().everyGroupFound } + assertFalse(vm.loaded().canPropose(" "), "no name") + assertTrue(vm.loaded().canPropose("Atlas")) + + vm.addGroup(nowhere) + eventually { vm.loaded().invitees.last().lookup == Lookup.NotFound } + assertFalse(vm.loaded().canPropose("Atlas"), "a group without a public profile cannot take part") + } + + @Test + fun `a member who is not an admin cannot propose`() { + admins = setOf(npub(10), npub(11), npub(12)) + val vm = viewModel() + eventually { (vm.proposeConfederationUIState as? ProposeConfederationUIState.Loaded)?.ownGroup?.lookup is Lookup.Found } + vm.addGroup(polis) + eventually { vm.loaded().everyGroupFound } + assertFalse(vm.loaded().isAdmin) + assertFalse(vm.loaded().canPropose("Atlas")) + } + + @Test + fun `the threshold starts at a majority and stays between two and the groups there are`() { + val vm = viewModel() + eventually { vm.proposeConfederationUIState is ProposeConfederationUIState.Loaded } + vm.addGroup(polis) + assertEquals(2, vm.loaded().threshold) + vm.addGroup(ekklesia) + assertEquals(2, vm.loaded().threshold, "a majority of three") + vm.setThreshold(5) + assertEquals(3, vm.loaded().threshold) + vm.removeGroup(ekklesia) + assertEquals(2, vm.loaded().threshold) + vm.setThreshold(1) + assertEquals(2, vm.loaded().threshold) + } + + @Test + fun `proposing hands the groups and the threshold to the group's session`() { + val vm = viewModel() + eventually { (vm.proposeConfederationUIState as? ProposeConfederationUIState.Loaded)?.ownGroup?.lookup is Lookup.Found } + vm.addGroup(polis) + vm.addGroup(ekklesia) + eventually { vm.loaded().everyGroupFound } + vm.setThreshold(3) + + var session: String? = null + vm.propose("Atlas", onSuccess = { session = it }, onFailure = {}) + eventually { session != null } + + assertEquals(listOf(polis, ekklesia), proposed?.map { it.groupPublicKey }) + assertEquals(3, proposedThreshold) + } +} diff --git a/docs/confederation.md b/docs/confederation.md index 27611a82..c443519e 100644 --- a/docs/confederation.md +++ b/docs/confederation.md @@ -48,6 +48,7 @@ wait on upstream (see the next section). | 3 | done. `ConfederationRefusal` in all four places in `FrostSigningManager`: on arrival, again at approval (the admins can change while a member decides), as the decline's reason, and in the resend, which carries the seal again. Two tags ride the FROST proposal: `confederation_seal` and, for an answer, `confederation_proposal`, the signed 9430 it answers, so a signer does not depend on its relays (verified and filed like a relay's copy). `proposeSigningBatch` takes `proposalTags`. `ConfederationManager.proposeConfederation`, `proposeAcceptance`, `proposeRejection` and `proposeWithdrawal` build them. `ProposedEvent` summarises the four kinds. `ConfederationDeclineJvmTest` 16/16 replaces the Phase 1 pin. The warnings half of D6 waits for the approval screen (Phase 7). Full jvmTest 1,569, all passing once `ShippedProfileUpgradeJvmTest` was moved to 43 | | 4 | done, before 3, because the refusals need somewhere to keep the seal and the reason past arrival. Schema 43: `ConfederationEvent` (every kind in one table, keyed by event id, indexed by the proposal it is about), `ConfederationInvitee` (which proposals name a group) and `ConfederationSigning` (per signing session: the seal secret, the carried proposal, the refusal). No `ConfederationGroup` cache: D2's lookups land in the existing `Profile` rows. `ConfederationManager.record` verifies the author's signature and files; `status` computes D8 from the rows. The repository waits for Phase 6, its first caller. `ConfederationStorageJvmTest` 5/5 | | 5 | done. `ExperimentalFeatures.confederation`, on in development builds. `LiveSubscriptionManager` holds `live-confederation` on the publish set while it is on: every confederation kind `#p`-tagged to one of our Marmot rooms, and every answer `#e`-tagged to a proposal not yet expired, re-sent when either changes. What arrives goes to `ConfederationRepository.record`, never `saveNostrEvent`. `FrostSigningManager.complete` calls `ConfederationManager.onSigned`, which files the signed events on every device and, on the coordinator's, marks them owed (`ConfederationEvent.ownSessionId`, `publishedAt`, folded into schema 43 since it has not shipped). `ConfederationPublisher`, run by `SynchronizationViewModel`, sends owed events to the publish set and the proposal's hints and backs off from a minute to half an hour until a relay takes each. `BROADCASTABLE_KINDS` gains 9430–9433. `ChatMessage.applyInnerEvent` draws nothing for these kinds rather than a raw-JSON bubble. `ConfederationRelayTest` 6/6, `ConfederationStorageJvmTest` 7/7 | +| 6 | done. Four system lines (`TYPE_CONFEDERATION_PROPOSED`, `…_ACCEPTED`, `…_REJECTED`, `…_WITHDRAWN`) written by `ConfederationManager.record` in every local room the proposal names, once per event because the event row is written once. No line for an expiry: nothing happens at an expiry to write one from. A "Confederations" row on the group's screen while the flag is on, for every member of a Marmot room. `ConfederationsScreen` watches every proposal naming the group. `ProposeConfederationScreen` looks every group up on the relays, this one included, and its button waits on a name, an admin, a share, a group that can take part and every group found. Relay hints are not written yet: the profile lookup does not say which relay answered. Its view model's state is a `MutableStateFlow` updated atomically, because a lookup settling on an IO thread and a group added on the main one lost updates under the full suite. `ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY` for fakes. `ProposeConfederationViewModelJvmTest` 8/8, `ConfederationScreensJvmTest` 4/4, `ConfederationStorageJvmTest` 9/9. jvmTest 1,591, `m3Audit`, brand and wallet audits clean | ---