From 4baf5d8f2e1c2f151aa0ef79917d083ae4163410 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 22:43:34 +0200 Subject: [PATCH] feat: nothing asks a NIP-17 room for its one ceremony (nip17-multiple-ceremonies, Phase 3) Six reads took a room's newest ceremony to mean the room's group. With the same people able to make several groups in one room, each was ambiguous or wrong: - The shared-key screen handed over to any ceremony that had not failed. It now offers another group, which has to be named once the room has one, and lists what the members already have. - A retry of a failed group's ceremony now starts from that ceremony's name and quorum (CreateSharedKeyRoute.retrying), not the room's. - adminRoomOf became adminRoomsOf: the details screen and the member-action explanation offer every group's admin room, by name. - completedKey's last fallback answers only when the room holds exactly one key of its own. Nothing asks it of a NIP-17 room today (Phase 0, P5). - The repository's two newest-ceremony reads, and the DAO queries only they used, are gone. CeremonyLookupsJvmTest now expects none. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 3 + .../compose/database/dao/DkgSessionDao.kt | 33 ------ .../repository/DatabaseChatRepository.kt | 28 +++-- .../repository/DatabaseDkgRepository.kt | 8 -- .../compose/managers/FrostSigningManager.kt | 18 ++- .../mobi/giza/compose/repository/AdminRoom.kt | 17 +++ .../giza/compose/repository/ChatRepository.kt | 15 ++- .../giza/compose/repository/DkgRepository.kt | 22 ---- .../ui/composable/ChatRoomDetailScreen.kt | 10 +- .../ui/composable/CreateSharedKeyScreen.kt | 81 ++++++++++--- .../compose/ui/composable/DkgRitualScreen.kt | 6 +- .../MemberActionUnavailableScreen.kt | 36 ++++-- .../ui/composable/navigation/GizaNavHost.kt | 6 +- .../navigation/routes/CreateSharedKeyRoute.kt | 21 ++-- .../ui/view/model/ChatRoomDetailViewModel.kt | 2 +- .../ui/view/model/CreateSharedKeyViewModel.kt | 73 +++++++++--- .../model/MemberActionUnavailableViewModel.kt | 2 +- .../ui/view/state/ChatRoomDetailUIState.kt | 11 +- .../ui/view/state/CreateSharedKeyUIState.kt | 27 +++-- .../state/MemberActionUnavailableUIState.kt | 8 +- .../managers/CeremonyLookupsJvmTest.kt | 25 ++-- .../managers/GroupsInOneRoomJvmTest.kt | 108 +++++++++++++++++ .../MemberActionUnavailableScreenJvmTest.kt | 28 ++++- .../model/CreateSharedKeyViewModelJvmTest.kt | 112 ++++++++++++++---- .../view/model/DkgRitualViewModelJvmTest.kt | 7 +- 25 files changed, 501 insertions(+), 206 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/AdminRoom.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupsInOneRoomJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 3c845be7..5cfe51f9 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -551,6 +551,9 @@ You already have groups with these people: %1$s. This will be a separate group with the same name, with a key and room of its own. an unnamed group + Open %1$s + New group with these members + The new group and its room are called this. Nothing is signed for the group without a quorum of you, and the group outlives any one of you. Creating it starts a key ceremony every member takes part in. A group needs at least %1$s people, you included. Go back and pick more. Pick at least %1$s people diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt index b53e7294..7201b5f0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt @@ -27,31 +27,6 @@ interface DkgSessionDao { @Query("SELECT * FROM DkgSession WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC LIMIT 1") suspend fun getLatestSessionForChatRoom(chatRoomId: String): DkgSession? - /** - * The room's newest ceremony **of its own**, newest first -- never one it is - * only hosting on a subgroup's behalf. - * - * The distinction did not exist while every ceremony ran in a NIP-17 room of - * its own. It does now: a subgroup's ChillDKG runs in the parent's Marmot - * room, so that room holds a completed ceremony whose key is the *child's*, - * and a caller asking "what key does this room sign with" must not be handed - * it. That is `FrostSigningManager.completedKey`'s last fallback, which is - * reached by every parent member who holds no key-state row -- which is - * every member welcomed after the parent's own ceremony. - * - * A ceremony run to make a subgroup is never the room's own key, and - * `parentChatRoomId` is the only thing that has to be read to know it. It is - * an unverified claim, but not a dangerous one here: the direction it can be - * abused in is a member *excluding* a ceremony from this answer, and a - * ceremony they can exclude is one they proposed, whose key they would - * simply not have proposed at all. - */ - @Query( - "SELECT * FROM DkgSession WHERE chatRoomId = :chatRoomId AND parentChatRoomId IS NULL " + - "ORDER BY createdAt DESC LIMIT 1" - ) - suspend fun getLatestOwnSessionForChatRoom(chatRoomId: String): DkgSession? - /** * Every ceremony the room holds **of its own**, newest first -- never one it is * only hosting on a subgroup's behalf. @@ -109,14 +84,6 @@ interface DkgSessionDao { ) suspend fun getLatestSessionFor(chatRoomId: String, parentChatRoomId: String?): DkgSession? - @Query( - "SELECT * FROM DkgSession WHERE chatRoomId = :chatRoomId AND " + - "(parentChatRoomId = :parentChatRoomId OR " + - "(:parentChatRoomId IS NULL AND parentChatRoomId IS NULL)) " + - "ORDER BY createdAt DESC LIMIT 1" - ) - fun observeLatestSessionFor(chatRoomId: String, parentChatRoomId: String?): Flow - /** * The newest ceremony making a subgroup of [parentChatRoomId] over exactly * these admins, or null if this device knows of none. 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 af5c9c28..d8351c8d 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 @@ -1,5 +1,6 @@ package mobi.giza.compose.database.repository +import mobi.giza.compose.repository.AdminRoom import mobi.giza.compose.nostr.GroupPost import mobi.giza.compose.nostr.GroupNostrProfile import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent @@ -148,17 +149,24 @@ class DatabaseChatRepository( emptySet() } - override suspend fun adminRoomOf(chatRoomId: String): String? = try { - // The room's own ceremony, not a subgroup's it hosted: a subgroup's key - // makes the subgroup's room, which is not this group's admin room. - database.dkgSessionDao().getLatestSessionFor(chatRoomId, parentChatRoomId = null) - ?.takeIf { it.stage == DkgRitualStage.COMPLETE } - ?.thresholdPublicKey - ?.let { SharedKeyDerivation.marmotGroupId(it) } - ?.takeIf { it != chatRoomId && database.chatRoomDao().findChatRoomById(it) != null } + override suspend fun adminRoomsOf(chatRoomId: String): List = try { + // The room's own ceremonies, not a subgroup's it hosted: a subgroup's key + // makes the subgroup's room, which is not one of this room's groups. Every + // one that finished, since the same people may have made several groups here. + database.dkgSessionDao().getOwnSessionsForChatRoom(chatRoomId) + .filter { it.stage == DkgRitualStage.COMPLETE } + .mapNotNull { ceremony -> + val roomId = ceremony.thresholdPublicKey + ?.let { SharedKeyDerivation.marmotGroupId(it) } + ?.takeIf { it != chatRoomId } + ?: return@mapNotNull null + val room = database.chatRoomDao().findChatRoomById(roomId) ?: return@mapNotNull null + AdminRoom(name = room.chatRoom.subject ?: ceremony.subject, chatRoomId = roomId) + } + .distinctBy { it.chatRoomId } } catch (e: Throwable) { - logger.e("Error finding the admin room of $chatRoomId", e) - null + logger.e("Error finding the admin rooms of $chatRoomId", e) + emptyList() } override suspend fun reconcileAdminFlags(): Int = AdminFlags.reconcileAll(database) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseDkgRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseDkgRepository.kt index 767083e9..79a8ea7f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseDkgRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseDkgRepository.kt @@ -46,18 +46,10 @@ class DatabaseDkgRepository( return roomId.takeIf { database.chatRoomDao().findChatRoomById(it) == null } } - override fun observeLatestSessionForChatRoom( - chatRoomId: String, - parentChatRoomId: String?, - ): Flow = - database.dkgSessionDao().observeLatestSessionFor(chatRoomId, parentChatRoomId) override fun observeMessages(sessionId: String): Flow> = database.dkgSessionDao().observeMessages(sessionId) - override suspend fun getLatestSessionForChatRoom(chatRoomId: String): DkgSession? = - database.dkgSessionDao().getLatestSessionForChatRoom(chatRoomId) - override fun observeOwnSessionsForChatRoom(chatRoomId: String): Flow> = database.dkgSessionDao().observeOwnSessionsForChatRoom(chatRoomId) .map { sessions -> sessions.filter { it.stage != DkgRitualStage.FAILED } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt index 4fba3a0e..24222fac 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -1925,6 +1925,14 @@ object FrostSigningManager { * naming a parent is never the room's own key, and that is all it takes to * tell them apart. * + * And it answers only when there is one answer. A NIP-17 room holds a ceremony + * for every group its members have made there -- the same people always share + * one, since its id is derived from them -- so with two finished keys "the key + * this room signs with" has none, and guessing the newest would sign as a group + * the proposer never meant. Nothing that runs today asks it of a NIP-17 room: + * the one signing there is the key state, which names its key + * (docs/nip17-multiple-ceremonies.md, P5). Anything that comes to must do the same. + * * They are not only for rooms that predate the table. A room's key state is * signed before the room exists and filed as the room is created, so a * device that missed that session -- a member invited later, a reinstall -- @@ -1951,9 +1959,13 @@ object FrostSigningManager { ShareGenerations.canSign(database, session) }?.let { return it } - return database.dkgSessionDao() - .getLatestOwnSessionForChatRoom(chatRoomId) - ?.takeIf { it.stage == DkgRitualStage.COMPLETE && ShareGenerations.canSign(database, it) } + val own = database.dkgSessionDao() + .getOwnSessionsForChatRoom(chatRoomId) + .filter { it.stage == DkgRitualStage.COMPLETE && ShareGenerations.canSign(database, it) } + if (own.size > 1) { + logger.w("$chatRoomId holds ${own.size} keys of its own; a signature there has to name one") + } + return own.singleOrNull() } /** Whether this group can sign at all, read by the UI so it offers nothing that would fail. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/AdminRoom.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/AdminRoom.kt new file mode 100644 index 00000000..0c60d5ae --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/AdminRoom.kt @@ -0,0 +1,17 @@ +package mobi.giza.compose.repository + +/** + * A room a group's ceremony made, as a NIP-17 room's members find it: where they are + * admins of one of the groups they have made together. + * + * The same people share one NIP-17 room however many groups they make -- its id is + * derived from them -- so a room can have any number of these + * (docs/nip17-multiple-ceremonies.md). + * + * [name] is the admin room's own, as this device holds it, or the name its ceremony + * was opened under when the room has none. + */ +data class AdminRoom( + val name: String?, + val chatRoomId: String, +) 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 c35d8f9f..f30c7b3e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -316,12 +316,15 @@ interface ChatRepository { suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set /** - * The admin room [chatRoomId]'s own key ceremony made, if this device holds - * it: where the members of a robust group's NIP-17 room are admins. Null for - * a room with no finished ceremony of its own, and for one whose admin room - * this device does not hold. + * The admin rooms [chatRoomId]'s own key ceremonies made that this device holds, + * newest first: where the members of a NIP-17 room are admins, one room per group + * they have made there. Empty for a room with no finished ceremony of its own. + * + * A list because the same people share one NIP-17 room however many groups they + * make; picking the newest used to hide every group but the last + * (docs/nip17-multiple-ceremonies.md). */ - suspend fun adminRoomOf(chatRoomId: String): String? + suspend fun adminRoomsOf(chatRoomId: String): List /** * Brings every Marmot room's admin flags in line with its group's policy, for @@ -657,7 +660,7 @@ interface ChatRepository { override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = emptySet() - override suspend fun adminRoomOf(chatRoomId: String): String? = null + override suspend fun adminRoomsOf(chatRoomId: String): List = emptyList() override suspend fun reconcileAdminFlags(): Int = 0 diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/DkgRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/DkgRepository.kt index 916c4b57..f24d5491 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/DkgRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/DkgRepository.kt @@ -20,19 +20,6 @@ import kotlinx.coroutines.flow.flowOf * not publish on their behalf until they say so. */ interface DkgRepository { - /** - * The room's current ritual for one purpose — the group's own when - * [parentChatRoomId] is null, or that parent's subgroup when it is not. - * Abandoned attempts are superseded by the newest. - * - * A room routinely holds several: a parent's room hosts the ceremony of every - * subgroup the group makes. See `DkgSessionDao.getLatestSessionFor`. - */ - fun observeLatestSessionForChatRoom( - chatRoomId: String, - parentChatRoomId: String? = null, - ): Flow - fun observeMessages(sessionId: String): Flow> /** @@ -63,8 +50,6 @@ interface DkgRepository { */ suspend fun roomAwaitingCreation(session: DkgSession): String? - suspend fun getLatestSessionForChatRoom(chatRoomId: String): DkgSession? - /** * Every group of its own [chatRoomId] holds, newest first, failed ones left * out: in a NIP-17 room, the groups its members have made there. @@ -223,11 +208,6 @@ interface DkgRepository { companion object { val NO_OP_DKG_REPOSITORY: DkgRepository = object : DkgRepository { - override fun observeLatestSessionForChatRoom( - chatRoomId: String, - parentChatRoomId: String?, - ): Flow = flowOf(null) - override fun observeMessages(sessionId: String): Flow> = flowOf(emptyList()) override fun observeSessionById(sessionId: String): Flow = flowOf(null) @@ -237,8 +217,6 @@ interface DkgRepository { override suspend fun roomAwaitingCreation(session: DkgSession): String? = null - override suspend fun getLatestSessionForChatRoom(chatRoomId: String): DkgSession? = null - override fun observeOwnSessionsForChatRoom(chatRoomId: String): Flow> = flowOf(emptyList()) 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 c0900421..02ecd69f 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 @@ -681,9 +681,11 @@ fun ChatRoomDetailScreen( } // A robust group's NIP-17 room has no admins of its own; - // its members are admins of the room its key made. - chatRoomDetailUIState.adminRoomId?.let { adminRoomId -> - item { + // its members are admins of the rooms its keys made, one + // per group they have made here. + chatRoomDetailUIState.adminRooms.forEach { adminRoom -> + val adminRoomId = adminRoom.chatRoomId + item(key = "admin-room-$adminRoomId") { Card( modifier = Modifier.fillMaxWidth(), onClick = { @@ -704,7 +706,7 @@ fun ChatRoomDetailScreen( Icon(Icons.Default.ChevronRight, contentDescription = Decorative) }, headlineContent = { - Text(text = stringResource(Res.string.admin_room)) + Text(text = adminRoom.name ?: stringResource(Res.string.admin_room)) }, supportingContent = { Text(text = stringResource(Res.string.every_member_of_this_group_administers_it_there)) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/CreateSharedKeyScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/CreateSharedKeyScreen.kt index b5776cb7..7425a6b2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/CreateSharedKeyScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/CreateSharedKeyScreen.kt @@ -19,6 +19,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilledIconButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.Surface @@ -32,6 +33,12 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.new_group_with_these_members +import mobi.giza.compose.resources.an_unnamed_group +import mobi.giza.compose.resources.you_already_have_a_group_with_these_people +import mobi.giza.compose.resources.you_already_have_groups_with_these_people +import mobi.giza.compose.resources.name +import mobi.giza.compose.resources.the_new_group_and_its_room_are_called_this import mobi.giza.compose.resources.a_shared_key_needs_at_least_members import mobi.giza.compose.resources.couldn_t_load_this_group import mobi.giza.compose.resources.couldn_t_read_your_keys @@ -70,7 +77,9 @@ import mobi.giza.compose.ui.view.model.CreateSharedKeyViewModel import mobi.giza.compose.ui.view.state.CreateSharedKeyUIState /** - * Starts a NIP-17 group's own key ceremony: the quorum, and one button. + * Starts a group's key ceremony in a NIP-17 room: its name, the quorum, and one + * button. The room's first group, or another made by the same people beside the + * ones they have (docs/nip17-multiple-ceremonies.md). * * The only screen that does. The ceremony screen it hands over to shows a * ceremony and never offers to start one, because doing both from one button @@ -78,8 +87,9 @@ import mobi.giza.compose.ui.view.state.CreateSharedKeyUIState * one in the parent's room. See docs/ceremony-creation.md. * * [onCeremonyOpened] is called with the ceremony to show, whether this screen - * opened it or found one already there. The caller replaces this screen with it, - * so back from the ceremony goes wherever the member came from. + * opened it or a repeated ask was folded into one already running under the same + * name. The caller replaces this screen with it, so back from the ceremony goes + * wherever the member came from. */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -92,6 +102,7 @@ fun CreateSharedKeyScreen( dkgRepository: DkgRepository, onCeremonyOpened: (dkgSessionId: String) -> Unit, onNavigateBack: () -> Unit, + retrying: String? = null, ) { val viewModel: CreateSharedKeyViewModel = viewModel( factory = CreateSharedKeyViewModel.factory( @@ -101,6 +112,7 @@ fun CreateSharedKeyScreen( activeIdentityStateFlow = activeIdentityStateFlow, chatRepository = chatRepository, dkgRepository = dkgRepository, + retrying = retrying, ) ) @@ -112,23 +124,24 @@ fun CreateSharedKeyScreen( val state = viewModel.uiState - LaunchedEffect(state) { - if (state is CreateSharedKeyUIState.Existing) onCeremonyOpened(state.dkgSessionId) - } - Scaffold( snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, topBar = { TopAppBar( title = { - // The room's name only once it is loaded; before that, and on a - // refusal, the plain title rather than "Shared key for " and - // nothing. - val subject = (state as? CreateSharedKeyUIState.Loaded)?.localChatRoom?.chatRoom?.subject + // The room's name only once it is loaded and only for its first + // group, which it was named for; before that, and on a refusal, + // the plain title rather than "Shared key for " and nothing. A + // room that already has a group is making another, and its name + // is the first group's, not this one's. + val loaded = state as? CreateSharedKeyUIState.Loaded + val subject = loaded?.takeIf { !it.needsName }?.localChatRoom?.chatRoom?.subject Text( - text = subject - ?.let { stringResource(Res.string.shared_key_for, it) } - ?: stringResource(Res.string.shared_key), + text = when { + loaded?.needsName == true -> stringResource(Res.string.new_group_with_these_members) + subject != null -> stringResource(Res.string.shared_key_for, subject) + else -> stringResource(Res.string.shared_key) + }, maxLines = 1, overflow = TextOverflow.Ellipsis ) @@ -139,9 +152,7 @@ fun CreateSharedKeyScreen( ) { innerPadding -> ScreenStateTransition(state) { uiState -> when (uiState) { - // Existing is a hand-over in flight: nothing to draw but the wait. - CreateSharedKeyUIState.Loading, - is CreateSharedKeyUIState.Existing -> LoadingDataIndicator( + CreateSharedKeyUIState.Loading -> LoadingDataIndicator( modifier = Modifier.padding(innerPadding).fillMaxSize() ) @@ -184,11 +195,45 @@ fun CreateSharedKeyScreen( .padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) ) { + if (uiState.groups.isNotEmpty()) { + val unnamed = stringResource(Res.string.an_unnamed_group) + val roomSubject = uiState.localChatRoom.chatRoom.subject + val names = uiState.groups.joinToString(", ") { + it.subject ?: roomSubject ?: unnamed + } + Text( + text = if (uiState.groups.size == 1) { + stringResource(Res.string.you_already_have_a_group_with_these_people, names) + } else { + stringResource(Res.string.you_already_have_groups_with_these_people, names) + }, + style = MaterialTheme.typography.bodyMedium + ) + } + Text( text = stringResource(Res.string.the_group_can_hold_one_key_together_split_so), style = MaterialTheme.typography.bodyMedium ) + // The name the group's room will carry. A room that already + // has a group has to name this one: the room keeps its first + // group's name, and falling back to it would make that + // group's namesake. docs/nip17-multiple-ceremonies.md, D2. + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + value = viewModel.name.value, + onValueChange = viewModel::setName, + enabled = !isActionPending, + singleLine = true, + label = { Text(stringResource(Res.string.name)) }, + supportingText = if (uiState.needsName) { + { Text(stringResource(Res.string.the_new_group_and_its_room_are_called_this)) } + } else { + null + }, + ) + Text( text = stringResource( Res.string.everyone_has_to_be_online_at_the_same_time, @@ -206,7 +251,7 @@ fun CreateSharedKeyScreen( Button( modifier = Modifier.fillMaxWidth(), - enabled = !isActionPending, + enabled = !isActionPending && viewModel.canCreate(), onClick = { viewModel.create(onCreated = onCeremonyOpened) } ) { if (isActionPending) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgRitualScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgRitualScreen.kt index 65d914f7..e45bcd52 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgRitualScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgRitualScreen.kt @@ -387,7 +387,9 @@ fun DkgRitualScreen( /** * Where a failed ceremony is tried again: the screen that starts that kind. * - * A group's own goes back to `CreateSharedKeyScreen`. A subgroup's goes back to + * A group's own goes back to `CreateSharedKeyScreen`, filled in from the one that + * failed -- its name above all, since the room may hold other groups and its own + * name is the first one's (docs/nip17-multiple-ceremonies.md). A subgroup's goes back to * the picker, filled in from the ceremony that failed, because trying again is a * new ceremony over choices the member may want to change -- an admin who never * showed up, say. @@ -401,7 +403,7 @@ internal fun retryRoute(activeUserPublicKey: HexKey, chatRoomId: String, session retrying = session.id, ) } - ?: CreateSharedKeyRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId) + ?: CreateSharedKeyRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, retrying = session.id) /** The ladder, and the members it is climbing. */ /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreen.kt index 8562b84c..99cbfabc 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreen.kt @@ -35,6 +35,7 @@ import androidx.compose.ui.text.TextStyle import androidx.lifecycle.viewmodel.compose.viewModel import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.open_room_named import mobi.giza.compose.resources.also_in_the_way import mobi.giza.compose.resources.back_to_the_group import mobi.giza.compose.resources.make_admin @@ -175,20 +176,31 @@ fun MemberActionUnavailableScreen( titleStyle = MaterialTheme.typography.headlineSmall, ) - // The one reason with something to do about it from here. - if (lead == MemberActionBlocker.NoAdminsInThisRoom && state.adminRoomId != null) { - Button( - onClick = { - onNavigateToRoute( - ChatRoomDetailRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = state.adminRoomId, - relayHint = null, + // The one reason with something to do about it from here. The same + // people may run several groups from this room, each from a room of + // its own, and which one the member meant is theirs to say, so each + // is offered by name (docs/nip17-multiple-ceremonies.md). + if (lead == MemberActionBlocker.NoAdminsInThisRoom) { + state.adminRooms.forEach { adminRoom -> + Button( + onClick = { + onNavigateToRoute( + ChatRoomDetailRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = adminRoom.chatRoomId, + relayHint = null, + ) ) + }, + ) { + Text( + if (state.adminRooms.size == 1 || adminRoom.name == null) { + stringResource(Res.string.open_the_admin_room) + } else { + stringResource(Res.string.open_room_named, adminRoom.name) + } ) - }, - ) { - Text(stringResource(Res.string.open_the_admin_room)) + } } } 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 0e226c81..0780d0af 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 @@ -588,7 +588,8 @@ fun GizaNavHost( chatRepository = databaseChatRepository, dkgRepository = databaseDkgRepository, // Replaces this screen with the ceremony, whether it was just - // opened or was already there, so back from the ceremony goes + // opened or one running under the same name was handed back, so + // back from the ceremony goes // wherever the member came from rather than to a second offer. onCeremonyOpened = { dkgSessionId -> navController.navigate( @@ -601,7 +602,8 @@ fun GizaNavHost( popUpTo { inclusive = true } } }, - onNavigateBack = { navController.popBackStack() } + onNavigateBack = { navController.popBackStack() }, + retrying = route.retrying, ) } composable { backStackEntry -> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/CreateSharedKeyRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/CreateSharedKeyRoute.kt index bd2da105..c60bbd28 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/CreateSharedKeyRoute.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/CreateSharedKeyRoute.kt @@ -3,17 +3,24 @@ package mobi.giza.compose.ui.composable.navigation.routes import kotlinx.serialization.Serializable /** - * Starting a NIP-17 group's own key ceremony, and nothing else. + * Starting a group's key ceremony in a NIP-17 room, and nothing else. * - * The one place a group that has no key yet asks for one. Group creation and - * the subgroup picker start their own ceremonies because they already know what - * each is for; this is for a group that exists and has none. The ceremony screen - * that follows only ever shows a ceremony -- it used to offer to start one too, - * from the same button the approvals used, which is how a member joining a - * subgroup's ceremony opened a second. See docs/ceremony-creation.md. + * The one place a room's members ask for a key outside group creation. Group + * creation and the subgroup picker start their own ceremonies because they already + * know what each is for; this is for a room whose members want one -- their first + * group, or another beside the ones they have (docs/nip17-multiple-ceremonies.md). + * The ceremony screen that follows only ever shows a ceremony -- it used to offer + * to start one too, from the same button the approvals used, which is how a member + * joining a subgroup's ceremony opened a second. See docs/ceremony-creation.md. */ @Serializable data class CreateSharedKeyRoute( val activeUserPublicKey: String, val chatRoomId: String, + /** + * The failed ceremony this is a second try at, whose name and quorum the screen + * starts from -- or null for a new group. Without it a retry of the room's + * second group would come back under the room's first group's name. + */ + val retrying: String? = null, ): Route() 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 f71ca546..865a58cd 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 @@ -174,7 +174,7 @@ class ChatRoomDetailViewModel( nostrRepository.getProfileWithPublicKey(publicKey)?.humanReadableNameOrPubkey() ?: publicKey.take(SHORTENED_PUBLIC_KEY_LENGTH) }, - adminRoomId = if (localChatRoom.chatRoom.mlsGroupState == null) chatRepository.adminRoomOf(chatRoomId) else null, + adminRooms = if (localChatRoom.chatRoom.mlsGroupState == null) chatRepository.adminRoomsOf(chatRoomId) else emptyList(), soleAdminName = soleAdminOf(localChatRoom, hasKey = groupKeyState != null)?.let { publicKey -> nostrRepository.getProfileWithPublicKey(publicKey)?.humanReadableNameOrPubkey() ?: publicKey.take(SHORTENED_PUBLIC_KEY_LENGTH) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModel.kt index 3d21d73a..6db34ccb 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModel.kt @@ -18,7 +18,6 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import mobi.giza.compose.managers.Quorum -import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.identity.Identity import mobi.giza.compose.managers.ChillDkgRitualManager import mobi.giza.compose.repository.ChatRepository @@ -27,11 +26,13 @@ import mobi.giza.compose.ui.view.state.CreateSharedKeyUIState import mobi.giza.compose.ui.view.state.CreateSharedKeyUIState.Refused.Reason /** - * Starts a NIP-17 group's own key ceremony. + * Starts a group's key ceremony in a NIP-17 room: the room's first group, or + * another beside the ones its members have already made there + * (docs/nip17-multiple-ceremonies.md). * * Everything about *starting* that the ceremony screen used to carry: the - * quorum, the size check, and the proposal. The ceremony screen only shows one - * now, so nothing it draws can be mistaken for a way to open another. + * quorum, the name, the size check, and the proposal. The ceremony screen only + * shows one now, so nothing it draws can be mistaken for a way to open another. * * The refusals are made here rather than by hiding a button, so the screen can * say why, and `ChillDkgRitualManager.proposeRitual` makes the Marmot one again @@ -44,6 +45,8 @@ class CreateSharedKeyViewModel( val activeIdentityStateFlow: StateFlow, val chatRepository: ChatRepository, val dkgRepository: DkgRepository, + /** The failed ceremony this is a second try at, if it is one. See `CreateSharedKeyRoute.retrying`. */ + val retrying: String? = null, ) : ViewModel() { var uiState: CreateSharedKeyUIState by mutableStateOf(initialUIState) @@ -59,6 +62,13 @@ class CreateSharedKeyViewModel( */ val threshold: MutableState = mutableStateOf(Quorum.MINIMUM) + /** + * What the group being made is called, and so the room its key makes. Starts as + * the room's name for the room's first group -- the room was named for it -- and + * empty for any after it, which have to be named (D2). + */ + val name: MutableState = mutableStateOf("") + fun initiate() { uiState = CreateSharedKeyUIState.Loading @@ -79,24 +89,30 @@ class CreateSharedKeyViewModel( return@launch } - // The room's own, which in a NIP-17 room is every ceremony it holds: - // subgroups run in their parent's Marmot room. A finished one counts -- - // the group has its key, and the ceremony screen is where the next step - // after it is offered. - val own = dkgRepository.observeLatestSessionForChatRoom(chatRoomId, parentChatRoomId = null) - .first() - if (own != null && own.stage != DkgRitualStage.FAILED) { - uiState = CreateSharedKeyUIState.Existing(own.id) - return@launch - } + // The groups the room's members have already made here, which in a + // NIP-17 room is every ceremony it holds of its own: subgroups run in + // their parent's Marmot room. None of them is a reason not to make + // another; they are what the screen says these people already have, and + // why the next one needs a name of its own. + val groups = dkgRepository.observeOwnSessionsForChatRoom(chatRoomId).first() + + // A second try starts where the first left off: its name and quorum. + val failed = retrying + ?.let { dkgRepository.observeSessionById(it).first() } + ?.takeIf { it.chatRoomId == chatRoomId && it.parentChatRoomId == null } val participantCount = ChillDkgRitualManager.memberPublicKeys(localChatRoom).size - threshold.value = Quorum.default(participantCount) + threshold.value = (failed?.threshold ?: Quorum.default(participantCount)) .coerceIn(quorumRange(participantCount)) + name.value = failed?.subject + ?: localChatRoom.chatRoom.subject?.takeIf { groups.isEmpty() } + ?: "" + uiState = CreateSharedKeyUIState.Loaded( localChatRoom = localChatRoom, participantCount = participantCount, + groups = groups, ) } } @@ -119,6 +135,22 @@ class CreateSharedKeyViewModel( threshold.value = value.coerceIn(quorumRange()) } + fun setName(value: String) { + if (isActionPending.value) return + + name.value = value + } + + /** + * Whether the ceremony can be opened as filled in: always for the room's first + * group, which the room names if nobody does, and only once named for any + * after it. + */ + fun canCreate(): Boolean { + val loaded = uiState as? CreateSharedKeyUIState.Loaded ?: return false + return !loaded.needsName || name.value.isNotBlank() + } + /** * Opens the ceremony, making this device its coordinator, and hands over to * the screen that shows it. @@ -127,6 +159,7 @@ class CreateSharedKeyViewModel( if (isActionPending.value) return val loaded = uiState as? CreateSharedKeyUIState.Loaded ?: return + if (!canCreate()) return val nostrPrivateKey = activeIdentityStateFlow.value?.nostrPrivateKey if (nostrPrivateKey == null) { @@ -137,13 +170,15 @@ class CreateSharedKeyViewModel( isActionPending.value = true viewModelScope.launch(Dispatchers.IO) { - // A ceremony somebody else opened since this screen loaded comes back - // here rather than a second one -- `proposeRitual` checks again. + // A ceremony still running under this name comes back here rather than + // a second one -- `proposeRitual` folds a repeated ask into it -- and the + // screen hands over to it the same way. val session = dkgRepository.proposeRitual( localChatRoom = loaded.localChatRoom, userPublicKey = activeUserPublicKey, nostrPrivateKey = nostrPrivateKey.value.toByteArray(), - threshold = threshold.value + threshold = threshold.value, + subject = name.value.trim().takeIf { it.isNotEmpty() }, ) isActionPending.value = false @@ -168,6 +203,7 @@ class CreateSharedKeyViewModel( activeIdentityStateFlow: StateFlow, chatRepository: ChatRepository, dkgRepository: DkgRepository, + retrying: String? = null, ): ViewModelProvider.Factory = viewModelFactory { initializer { CreateSharedKeyViewModel( @@ -177,6 +213,7 @@ class CreateSharedKeyViewModel( activeIdentityStateFlow = activeIdentityStateFlow, chatRepository = chatRepository, dkgRepository = dkgRepository, + retrying = retrying, ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberActionUnavailableViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberActionUnavailableViewModel.kt index b5b11b48..428305f6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberActionUnavailableViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/MemberActionUnavailableViewModel.kt @@ -86,7 +86,7 @@ class MemberActionUnavailableViewModel( action = action, blockers = option.blockers, names = named.associateWith { nameOf(it) }, - adminRoomId = if (MemberActionBlocker.NoAdminsInThisRoom in option.blockers) chatRepository.adminRoomOf(chatRoomId) else null, + adminRooms = if (MemberActionBlocker.NoAdminsInThisRoom in option.blockers) chatRepository.adminRoomsOf(chatRoomId) else emptyList(), ) } 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 b833998d..efc96840 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 @@ -1,5 +1,6 @@ package mobi.giza.compose.ui.view.state +import mobi.giza.compose.repository.AdminRoom import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.database.model.GroupKeyState import mobi.giza.compose.managers.SubgroupManager @@ -165,12 +166,12 @@ sealed interface ChatRoomDetailUIState { */ val founderNames: Map = emptyMap(), /** - * The admin room this group's ceremony made, when this is the group's - * NIP-17 room and this device holds it. A NIP-17 room has no admins of its - * own; this is where its members are admins. docs/robust-group-admins.md, - * Phase 5. + * The admin rooms this room's ceremonies made, when this is a NIP-17 room + * and this device holds them. A NIP-17 room has no admins of its own; these + * are where its members are admins, one per group they have made here. + * docs/robust-group-admins.md, Phase 5, and docs/nip17-multiple-ceremonies.md. */ - val adminRoomId: String? = null, + val adminRooms: List = emptyList(), /** * Who runs this group alone, when it is one: a Marmot room with no key * behind it, more than two members and one admin -- a group made before diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/CreateSharedKeyUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/CreateSharedKeyUIState.kt index 51c540a9..ea33fd7e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/CreateSharedKeyUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/CreateSharedKeyUIState.kt @@ -1,21 +1,28 @@ package mobi.giza.compose.ui.view.state +import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.intermdiate.LocalChatRoom sealed interface CreateSharedKeyUIState { - /** The room, and how many people a ceremony in it would be split across. */ + /** + * The room, how many people a ceremony in it would be split across, and the + * groups its members have already made there. + * + * [groups] is every own ceremony the room holds that has not failed, newest + * first. A room with any has to name the next one: it keeps its first group's + * name, and a second group named by it would be that one's namesake + * (docs/nip17-multiple-ceremonies.md, D2). It used to be the reason to hand over + * to the room's ceremony instead of offering one; the same people may make as + * many groups as they like now, so it is what the screen tells them they have. + */ data class Loaded( val localChatRoom: LocalChatRoom, val participantCount: Int, - ) : CreateSharedKeyUIState - - /** - * The group already has a ceremony that has not failed -- running, or finished - * with a key. The screen hands over to it rather than offering a second: a - * second is another participant set for every member to reconcile, and the key - * the first produced would be left with nothing pointing at it. - */ - data class Existing(val dkgSessionId: String) : CreateSharedKeyUIState + val groups: List = emptyList(), + ) : CreateSharedKeyUIState { + /** Whether the group being made has to be given a name of its own. */ + val needsName: Boolean get() = groups.isNotEmpty() + } /** This room cannot hold a ceremony of its own, and the screen says why. */ data class Refused(val reason: Reason) : CreateSharedKeyUIState { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberActionUnavailableUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberActionUnavailableUIState.kt index bcfcb070..12df5064 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberActionUnavailableUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/MemberActionUnavailableUIState.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.ui.view.state +import mobi.giza.compose.repository.AdminRoom import com.vitorpamplona.quartz.nip01Core.core.HexKey /** @@ -25,8 +26,11 @@ sealed interface MemberActionUnavailableUIState { val blockers: List, /** What to call everyone a blocker names: admins to ask, devices waited on. */ val names: Map = emptyMap(), - /** The admin room a NIP-17 room's members run the group from, when known. */ - val adminRoomId: String? = null, + /** + * The admin rooms a NIP-17 room's members run their groups from, when known: + * one per group the same people have made there. + */ + val adminRooms: List = emptyList(), ) : MemberActionUnavailableUIState /** Nothing stands in the way any more: the blocker cleared while the screen was open. */ diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyLookupsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyLookupsJvmTest.kt index 2512c588..3e32f281 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyLookupsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyLookupsJvmTest.kt @@ -8,9 +8,9 @@ import kotlin.test.assertEquals * Every place that asks a room for "its ceremony" and takes the newest one. * * In a NIP-17 room that question has no single answer once the same people have made - * a second group there (docs/nip17-multiple-ceremonies.md). Each of these reads was - * written while it did, and each one either has to stop asking or has to be right - * because the room it asks is never a NIP-17 room. + * a second group there (docs/nip17-multiple-ceremonies.md). Phase 0 found six such + * reads in the app; Phase 3 took every one of them out. What is left of the queries + * serves tests of the DAO itself. * * Like `CeremonyEntryPointsJvmTest`, this counts rather than proves: it fails the day * a new caller appears, so that adding one is a decision somebody makes here. @@ -32,7 +32,7 @@ class CeremonyLookupsJvmTest { ) @Test - fun `the reads that take a room's newest ceremony are these and no others`() { + fun `nothing in the app takes a room's newest ceremony`() { val found = source.resolve("commonMain/kotlin").walkTopDown() .filter { it.isFile && it.extension == "kt" } .flatMap { file -> @@ -44,19 +44,8 @@ class CeremonyLookupsJvmTest { } .toMap() - assertEquals( - mapOf( - // The one admin room a NIP-17 room's details link to. - "DatabaseChatRepository: dkgSessionDao().getLatestSessionFor(" to 1, - // The repository's pass-throughs. - "DatabaseDkgRepository: dkgSessionDao().observeLatestSessionFor(" to 1, - "DatabaseDkgRepository: dkgSessionDao().getLatestSessionForChatRoom(" to 1, - // The key a room signs with, last fallback. - "FrostSigningManager: dkgSessionDao().getLatestOwnSessionForChatRoom(" to 1, - // The shared-key screen handing over to the room's ceremony. - "CreateSharedKeyViewModel: dkgRepository.observeLatestSessionForChatRoom(" to 1, - ), - found, - ) + // None, since docs/nip17-multiple-ceremonies.md, Phase 3. Every screen and + // manager names the ceremony it means, or asks for all of a room's. + assertEquals(emptyMap(), found) } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupsInOneRoomJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupsInOneRoomJvmTest.kt new file mode 100644 index 00000000..96cfc445 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupsInOneRoomJvmTest.kt @@ -0,0 +1,108 @@ +package mobi.giza.compose.managers + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.types.DkgApprovalStep +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.repository.AdminRoom +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * What a NIP-17 room answers once the same people have made more than one group in + * it: every group's admin room, and no single key of its own. + * docs/nip17-multiple-ceremonies.md, Phase 3. + * + * Two real ceremonies, run to the end on [CeremonyNetwork], so the keys and shares + * are the ones a device would hold. + */ +class GroupsInOneRoomJvmTest { + + private suspend fun completed(network: CeremonyNetwork, subject: String?, threshold: Int = 2): DkgSession { + val session = network.propose(threshold = threshold, subject = subject) + network.deliverUntilQuiet() + network.devices.forEach { device -> + if (network.pendingApproval(device, session.id) == DkgApprovalStep.HOST_KEY) { + network.approve(device, session.id, DkgApprovalStep.HOST_KEY) + } + } + network.deliverUntilQuiet() + return assertNotNull(network.session(network.coordinator, session.id)).also { + assertEquals(DkgRitualStage.COMPLETE, it.stage, it.failureReason) + } + } + + /** The room [ceremony]'s key makes, as `MarmotGroupCreation` would have filed it. */ + private suspend fun standUpRoom(network: CeremonyNetwork, ceremony: DkgSession, name: String): String { + val roomId = SharedKeyDerivation.marmotGroupId(assertNotNull(ceremony.thresholdPublicKey)) + network.coordinator.db.chatRoomDao().upsert( + ChatRoom( + id = roomId, + userPublicKey = network.coordinator.publicKey, + subject = name, + description = null, + mlsGroupState = "00", + ) + ) + return roomId + } + + @Test + fun `a room's members are admins of every group they made in it`(): Unit = runBlocking { + CeremonyNetwork.nip17(size = 3, subject = "Ekklesia").use { network -> + val repository = DatabaseChatRepository(network.coordinator.db, CoroutineScope(Dispatchers.Default)) + + val ekklesia = completed(network, subject = null) + assertEquals(emptyList(), repository.adminRoomsOf(network.roomId), "no room made yet, none to offer") + + val ekklesiaRoom = standUpRoom(network, ekklesia, "#Ekklesia") + assertEquals(listOf(AdminRoom("#Ekklesia", ekklesiaRoom)), repository.adminRoomsOf(network.roomId)) + + // A second group, by the same people, in the same room. While its ceremony + // runs it has no room to offer; the first group's is still there. + val agora = network.propose(threshold = 3, subject = "Agora") + assertEquals(listOf(AdminRoom("#Ekklesia", ekklesiaRoom)), repository.adminRoomsOf(network.roomId)) + + network.deliverUntilQuiet() + network.devices.forEach { device -> + if (network.pendingApproval(device, agora.id) == DkgApprovalStep.HOST_KEY) { + network.approve(device, agora.id, DkgApprovalStep.HOST_KEY) + } + } + network.deliverUntilQuiet() + val agoraDone = assertNotNull(network.session(network.coordinator, agora.id)) + assertEquals(DkgRitualStage.COMPLETE, agoraDone.stage, agoraDone.failureReason) + + val agoraRoom = standUpRoom(network, agoraDone, "#Agora") + assertEquals( + setOf(AdminRoom("#Ekklesia", ekklesiaRoom), AdminRoom("#Agora", agoraRoom)), + repository.adminRoomsOf(network.roomId).toSet(), + "both groups, not the newest alone", + ) + } + } + + /** + * "The key this room signs with" has no answer in a NIP-17 room holding two, and + * guessing the newest would sign as a group nobody named. Nothing asks it of a + * NIP-17 room today; this is what keeps a future caller from being handed one. + */ + @Test + fun `a room holding two keys of its own has no one key to sign with`(): Unit = runBlocking { + CeremonyNetwork.nip17(size = 3, subject = "Ekklesia").use { network -> + val db = network.coordinator.db + + val ekklesia = completed(network, subject = null) + assertEquals(ekklesia.id, FrostSigningManager.completedKey(db, network.roomId)?.id, "one key is the answer") + + completed(network, subject = "Agora", threshold = 3) + assertNull(FrostSigningManager.completedKey(db, network.roomId), "two keys are not one") + } + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreenJvmTest.kt index 4e8f462a..dc523e97 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreenJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/MemberActionUnavailableScreenJvmTest.kt @@ -1,5 +1,6 @@ package mobi.giza.compose.ui.composable +import mobi.giza.compose.repository.AdminRoom import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Text @@ -46,12 +47,15 @@ class MemberActionUnavailableScreenJvmTest { private val nomvula = "b".repeat(64) private val thabo = "c".repeat(64) - private fun blocked(vararg blockers: MemberActionBlocker, adminRoomId: String? = null) = MemberActionUnavailableUIState.Blocked( + private fun blocked(vararg blockers: MemberActionBlocker, adminRoomId: String? = null) = + blocked(*blockers, adminRooms = listOfNotNull(adminRoomId?.let { AdminRoom(name = "#Checkers", chatRoomId = it) })) + + private fun blocked(vararg blockers: MemberActionBlocker, adminRooms: List) = MemberActionUnavailableUIState.Blocked( memberName = "Nomvula", action = MemberAction.MAKE_ADMIN, blockers = blockers.toList(), names = mapOf(thabo to "Thabo"), - adminRoomId = adminRoomId, + adminRooms = adminRooms, ) @Test @@ -112,6 +116,26 @@ class MemberActionUnavailableScreenJvmTest { } } + /** + * The same people may run several groups from one NIP-17 room, each from an admin + * room of its own; which one the member meant is theirs to say. + * docs/nip17-multiple-ceremonies.md, Phase 3. + */ + @Test + fun `a room whose members run several groups offers each admin room by name`() { + val rooms = listOf( + AdminRoom(name = "#Checkers", chatRoomId = "8".repeat(64)), + AdminRoom(name = "#Chess", chatRoomId = "9".repeat(64)), + ) + var opened: Route? = null + render(blocked(MemberActionBlocker.NoAdminsInThisRoom, adminRooms = rooms), onNavigateToRoute = { opened = it }) { + onNodeWithText("Open the admin room").assertDoesNotExist() + onNodeWithText("Open #Checkers").assertExists() + onNodeWithText("Open #Chess").performClick() + } + assertEquals(ChatRoomDetailRoute(activeUserPublicKey, "9".repeat(64), null), opened) + } + @Test fun `a reason that cleared says so, and goes back to the group`() { var wentBack = false diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt index b06c8ff3..ed822cae 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/CreateSharedKeyViewModelJvmTest.kt @@ -33,6 +33,8 @@ import mobi.giza.compose.identity.toWalletId import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.DkgRepository import mobi.giza.compose.ui.view.state.CreateSharedKeyUIState +import kotlin.test.assertTrue +import kotlin.test.assertFalse import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test @@ -41,12 +43,14 @@ import kotlin.test.assertIs import kotlin.test.assertNull /** - * The one screen that starts a group's own key ceremony. + * The one screen that starts a group's key ceremony in a NIP-17 room. * * What it must decide before it draws a button: whether the room can hold a - * ceremony of its own at all, and whether it already has one. A Marmot room - * cannot, and the ceremony screen offering it one anyway is how a second - * ceremony opened beside a subgroup's -- see docs/ceremony-creation.md. + * ceremony of its own at all, and what the group is to be called. A Marmot room + * cannot hold one, and the ceremony screen offering it one anyway is how a second + * ceremony opened beside a subgroup's -- see docs/ceremony-creation.md. A NIP-17 + * room that already has a group can hold another, which has to be named: + * docs/nip17-multiple-ceremonies.md. */ @OptIn(ExperimentalCoroutinesApi::class) class CreateSharedKeyViewModelJvmTest { @@ -86,14 +90,15 @@ class CreateSharedKeyViewModelJvmTest { }, ) - private fun session(id: String, stage: DkgRitualStage) = DkgSession( + private fun session(id: String, stage: DkgRitualStage, subject: String? = null, threshold: Int = 2) = DkgSession( id = id, chatRoomId = chatRoomId, coordinatorPublicKey = bob, userPublicKey = ada, - threshold = 2, + threshold = threshold, participantCount = 3, stage = stage, + subject = subject, hostPublicKey = ada, round1Random = "aa".repeat(32), round2AuxRandom = "bb".repeat(32), @@ -102,12 +107,19 @@ class CreateSharedKeyViewModelJvmTest { /** What `proposeRitual` was asked for, one entry per call. */ private val proposed = mutableListOf() - private fun dkgRepository(own: DkgSession? = null) = + /** And under what name. */ + private val subjects = mutableListOf() + + /** What `proposeRitual` hands back: a new ceremony unless a test says otherwise. */ + private var answer: DkgSession = session("new".padEnd(64, '0'), DkgRitualStage.COLLECTING_HOST_KEYS) + + private fun dkgRepository(groups: List = emptyList(), byId: List = emptyList()) = object : DkgRepository by DkgRepository.NO_OP_DKG_REPOSITORY { - override fun observeLatestSessionForChatRoom( - chatRoomId: String, - parentChatRoomId: String?, - ): Flow = flowOf(own.takeIf { parentChatRoomId == null }) + override fun observeOwnSessionsForChatRoom(chatRoomId: String): Flow> = + flowOf(groups) + + override fun observeSessionById(sessionId: String): Flow = + flowOf(byId.firstOrNull { it.id == sessionId }) override suspend fun proposeRitual( localChatRoom: LocalChatRoom, @@ -119,7 +131,8 @@ class CreateSharedKeyViewModelJvmTest { subject: String?, ): DkgSession? { proposed += threshold - return session("new".padEnd(64, '0'), DkgRitualStage.COLLECTING_HOST_KEYS) + subjects += subject + return answer } } @@ -133,7 +146,11 @@ class CreateSharedKeyViewModelJvmTest { temporaryFolder.newFolder().resolve("$name.preferences_pb").path.toPath() } - private fun viewModel(room: LocalChatRoom?, own: DkgSession? = null) = CreateSharedKeyViewModel( + private fun viewModel( + room: LocalChatRoom?, + groups: List = emptyList(), + retrying: DkgSession? = null, + ) = CreateSharedKeyViewModel( chatRoomId = chatRoomId, activeUserPublicKey = ada, initialUIState = CreateSharedKeyUIState.Loading, @@ -147,7 +164,8 @@ class CreateSharedKeyViewModelJvmTest { ) ), chatRepository = chatRepository(room), - dkgRepository = dkgRepository(own), + dkgRepository = dkgRepository(groups, listOfNotNull(retrying)), + retrying = retrying?.id, ) private suspend fun CreateSharedKeyViewModel.awaitSettled(): CreateSharedKeyUIState = @@ -170,25 +188,77 @@ class CreateSharedKeyViewModelJvmTest { assertEquals("new".padEnd(64, '0'), withTimeout(5_000) { opened.await() }) assertEquals(listOf(2), proposed) + assertEquals(listOf("Checkers"), subjects, "the room's first group is named for the room") } + /** + * The same people may make another group. It is not handed over to the first, + * as it was, and it has to be named: the room keeps its first group's name. + */ @Test - fun `a group with a ceremony already is handed to it`(): Unit = runBlocking { - val running = session("run".padEnd(64, '0'), DkgRitualStage.COLLECTING_ROUND_1) - val viewModel = viewModel(room(), own = running) + fun `a room that already has a group is offered another, under a name of its own`(): Unit = runBlocking { + val made = session("one".padEnd(64, '0'), DkgRitualStage.COMPLETE, subject = "Checkers") + val viewModel = viewModel(room(), groups = listOf(made)) viewModel.initiate() - assertEquals(CreateSharedKeyUIState.Existing(running.id), viewModel.awaitSettled()) - assertEquals(emptyList(), proposed, "and nothing is proposed") + val loaded = assertIs(viewModel.awaitSettled()) + assertEquals(listOf(made), loaded.groups) + assertTrue(loaded.needsName) + assertEquals("", viewModel.name.value, "not the room's name, which is the first group's") + assertFalse(viewModel.canCreate(), "nothing opens without a name") + + viewModel.create { error("an unnamed second group opens nothing") } + delay(50) + assertEquals(emptyList(), proposed) + + viewModel.setName(" Chess ") + assertTrue(viewModel.canCreate()) + + val opened = CompletableDeferred() + viewModel.create { opened.complete(it) } + assertEquals(answer.id, withTimeout(5_000) { opened.await() }) + assertEquals(listOf("Chess"), subjects) + } + + /** A name already running is the same ask, and the screen hands over to it. */ + @Test + fun `asking under a running group's name opens that group`(): Unit = runBlocking { + val running = session("run".padEnd(64, '0'), DkgRitualStage.COLLECTING_ROUND_1, subject = "Chess") + answer = running + val viewModel = viewModel(room(), groups = listOf(running)) + viewModel.initiate() + viewModel.awaitSettled() + viewModel.setName("Chess") + + val opened = CompletableDeferred() + viewModel.create { opened.complete(it) } + assertEquals(running.id, withTimeout(5_000) { opened.await() }) } @Test fun `a failed ceremony is there to be replaced`(): Unit = runBlocking { - val failed = session("bad".padEnd(64, '0'), DkgRitualStage.FAILED) - val viewModel = viewModel(room(), own = failed) + // The repository leaves failed ceremonies out of a room's groups. + val viewModel = viewModel(room(), groups = emptyList()) viewModel.initiate() assertIs(viewModel.awaitSettled()) + assertEquals("Checkers", viewModel.name.value) + } + + /** + * A retry of a room's second group comes back as that group, not as the room's + * first: the room's name is the first group's. + */ + @Test + fun `a retry starts from the name and quorum of the ceremony that failed`(): Unit = runBlocking { + val made = session("one".padEnd(64, '0'), DkgRitualStage.COMPLETE, subject = "Checkers") + val failed = session("bad".padEnd(64, '0'), DkgRitualStage.FAILED, subject = "Chess", threshold = 3) + val viewModel = viewModel(room(), groups = listOf(made), retrying = failed) + viewModel.initiate() + + assertIs(viewModel.awaitSettled()) + assertEquals("Chess", viewModel.name.value) + assertEquals(3, viewModel.threshold.value) } @Test diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModelJvmTest.kt index bff196ee..702f2c6d 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModelJvmTest.kt @@ -289,7 +289,12 @@ class DkgRitualViewModelJvmTest { val parent = "9a7e".repeat(16) val group = retryRoute(ada, chatRoomId, session(DkgRitualStage.FAILED)) - assertEquals(CreateSharedKeyRoute(activeUserPublicKey = ada, chatRoomId = chatRoomId), group) + assertEquals( + CreateSharedKeyRoute(activeUserPublicKey = ada, chatRoomId = chatRoomId, retrying = sessionId), + group, + "a group's own goes back to the creation screen, filled in from the one that failed: " + + "the room may hold other groups, and its name is the first one's", + ) val subgroup = retryRoute( ada,