feat: every group a member creates is robust (remove-convenient-groups, Phase 2)

The group-creation screen no longer offers a group its creator runs alone.
It asks only how many of the members have to agree, then opens the NIP-17
room and its key ceremony. The single-admin Marmot path, its invite round
and its 'couldn't be added' card are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-20 02:08:46 +02:00
1 parent 0a4453da81
commit eb2c8aa090
9 files changed
+186 -492

No files matched your search

@@ -48,7 +48,6 @@
<string name="cloud_backup">Cloud backup</string>
<string name="copy_url">Copy URL</string>
<string name="could_not_unlock_your_phrase_please_try">Could not unlock your phrase. Please try again.</string>
<string name="create_chat">Create chat</string>
<string name="create_new_chat">Create new chat</string>
<string name="create_profile">Create profile</string>
<string name="create_project">Create project</string>
@@ -98,7 +97,6 @@
<string name="invite_a_friend">Invite a friend</string>
<string name="invite_new_member">Invite new member</string>
<string name="it_is_cryptographical_secure_and">It is cryptographical secure, and decentralized, putting you in total control of your digital profile</string>
<string name="just_you_for_now">Just you for now</string>
<string name="keep_the_feed_alive">Keep the feed alive.</string>
<string name="keep_this_phrase_safe_do_not_share_it">Keep this phrase safe.\nDo not share it.</string>
<string name="key">Key</string>
@@ -279,7 +277,6 @@
<string name="the_recovery_phrase_sometimes_called_a_seed">The recovery phrase (sometimes called a seed) is a list of 12 English words. It is the only way back to this profile: the key that signs as you is derived from it.\n\nOnly you have this phrase. Keep it private — nobody from Giza will ever ask you for it.\n\nDo not lose it. Write it down and keep it somewhere safe that is not this phone. If you lose both the phone and the phrase, this profile is gone for good.</string>
<string name="these_are_your_keys_keep_them_safe_so_they">These are your keys. Keep them safe so they can keep unlocking this profile, even when you lose or change your phone.</string>
<string name="this_device_holds_no_phrase_for_the_profile">This device holds no phrase for the profile that is signed in.</string>
<string name="this_decides_who_can_change_the_group_later">This decides who can change the group later. You can't switch afterwards.</string>
<string name="this_group_has_not_been_asked_to_sign">This group has not been asked to sign anything yet.</string>
<string name="this_group_has_not_signed_anything_yet">This group has not signed anything yet.</string>
<string name="this_is_fixed_once_the_ceremony_runs">This is fixed once the ceremony runs. Changing it later means generating a new key.</string>
@@ -322,7 +319,6 @@
<string name="who_will_you_be_passing_the_aux_to">Who will you be passing the aux to?</string>
<string name="you">You</string>
<string name="you_agreed">You agreed.</string>
<string name="you_and_1_other">You and 1 other</string>
<string name="you_are_about_to_create_a_nostr_profile">You are about to create a NOSTR profile.</string>
<string name="you_are_signing">You are signing.</string>
<string name="you_can_still_carry_on_and_invite_people">You can still carry on and invite people later.</string>
@@ -343,7 +339,6 @@
<string name="everyone_has_to_be_online_at_the_same_time">Everyone has to be online at the same time — the ceremony can only finish once all %1$s of you have taken part.</string>
<string name="filter_and_count">%1$s · %2$s</string>
<string name="functionality_coming_soon_2">"%1$s" functionality coming soon</string>
<string name="how_should_be_run">How should %1$s be run?</string>
<string name="invite_2">Invite %1$s</string>
<string name="key_packages">%1$s key packages</string>
<string name="next_with">Next with %1$s</string>
@@ -367,7 +362,6 @@
<string name="shared_key_for">Shared key for %1$s</string>
<string name="to_join_the_chat_room">to join the %1$s chat room.</string>
<string name="unsupported_event_kind_2">Unsupported event kind: %1$s</string>
<string name="was_created_but_couldn_t_be_added_yet_invite">%1$s was created, but %2$s couldn't be added yet. Invite them again from the chat once they've set up encrypted messaging.</string>
<string name="was_created_but_its_shared_key_ceremony">%1$s was created, but its shared key ceremony couldn't be started. Open the chat and start it from the group's details — until then the group has no key of its own.</string>
<string name="word_position">#%1$s</string>
<string name="you_and_others">You and %1$s others</string>
@@ -518,4 +512,11 @@
<string name="founding_members_have_no_key_package">Some of them haven't published a key package yet</string>
<string name="admin_room">Admin room</string>
<string name="every_member_of_this_group_administers_it_there">Every member of this group is an admin there.</string>
<string name="create_group">Create group</string>
<string name="all_of_you_administer_this_group_together">All %1$s of you administer this group together.</string>
<string name="how_many_of_you_have_to_agree">How many of you have to agree to a change?</string>
<string name="fewer_approvals">Fewer approvals</string>
<string name="more_approvals">More approvals</string>
<string name="creating_the_group_starts_a_key_ceremony">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.</string>
<string name="a_group_needs_at_least_people">A group needs at least %1$s people, you included. Go back and pick more.</string>
</resources>
@@ -60,7 +60,7 @@ object MarmotGroupCreation {
private val logger = Logger.withTag(TAG)
/** Matches `SelectChatRoomTypeViewModel`: relays are not always prompt. */
/** How long to wait on the relays for one key package: they are not always prompt. */
const val KEY_PACKAGE_LOOKUP_TIMEOUT: Long = 10_000L
sealed interface Outcome {
@@ -12,10 +12,8 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Groups
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material3.BottomAppBar
import androidx.compose.material3.Card
@@ -26,15 +24,13 @@ import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.material3.TextButton
import mobi.giza.compose.ui.composable.navigation.routes.CreateSharedKeyRoute
import mobi.giza.compose.resources.start_the_key_ceremony
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -42,46 +38,47 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.database.model.types.ChatRoomType
import mobi.giza.compose.identity.Identity
import mobi.giza.compose.managers.Quorum
import mobi.giza.compose.repository.ChatRepository
import mobi.giza.compose.repository.DkgRepository
import mobi.giza.compose.repository.NostrRepository
import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator
import mobi.giza.compose.ui.theme.GizaTheme
import mobi.giza.compose.ui.view.model.SelectChatRoomTypeViewModel
import mobi.giza.compose.ui.view.state.SelectChatRoomTypeUIState
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import mobi.giza.compose.identity.Identity
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import mobi.giza.compose.ui.theme.spacing
import mobi.giza.compose.ui.composable.widgets.Decorative
import mobi.giza.compose.resources.Res
import org.jetbrains.compose.resources.stringResource
import mobi.giza.compose.resources.create_chat
import mobi.giza.compose.resources.how_many_admins_have_to_approve_a_change
import mobi.giza.compose.resources.just_you_for_now
import mobi.giza.compose.resources.open_chat
import mobi.giza.compose.resources.this_decides_who_can_change_the_group_later
import mobi.giza.compose.resources.you_and_1_other
import mobi.giza.compose.resources.how_should_be_run
import mobi.giza.compose.resources.create_group
import mobi.giza.compose.resources.creating_the_group_starts_a_key_ceremony
import mobi.giza.compose.resources.all_of_you_administer_this_group_together
import mobi.giza.compose.resources.fewer_approvals
import mobi.giza.compose.resources.how_many_of_you_have_to_agree
import mobi.giza.compose.resources.more_approvals
import mobi.giza.compose.resources.of
import mobi.giza.compose.resources.was_created_but_couldn_t_be_added_yet_invite
import mobi.giza.compose.resources.open_chat
import mobi.giza.compose.resources.start_the_key_ceremony
import mobi.giza.compose.resources.was_created_but_its_shared_key_ceremony
import mobi.giza.compose.resources.a_group_needs_at_least_people
import mobi.giza.compose.resources.you_and_others
import androidx.compose.material3.SnackbarHost
import mobi.giza.compose.ui.composable.navigation.routes.CreateSharedKeyRoute
import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.composable.widgets.ErrorState
import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator
import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState
import mobi.giza.compose.ui.composable.widgets.NavigateBackButton
import mobi.giza.compose.ui.theme.readableContent
import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition
import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab
import mobi.giza.compose.ui.theme.ConformancePreviews
import mobi.giza.compose.ui.theme.GizaTheme
import mobi.giza.compose.ui.theme.readableContent
import mobi.giza.compose.ui.theme.spacing
import mobi.giza.compose.ui.view.model.SelectChatRoomTypeViewModel
import mobi.giza.compose.ui.view.state.SelectChatRoomTypeUIState
import org.jetbrains.compose.resources.stringResource
/**
* Last step of group creation: convenient (one admin) or robust (everyone
* admins, changes need a threshold to approve), and then build the group.
* Last step of group creation: how many of the group have to agree to a change,
* and then build the group. Every group is robust -- docs/remove-convenient-groups.md.
*/
@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class)
@Composable
@@ -115,27 +112,24 @@ fun SelectChatRoomTypeScreen(
ScreenStateTransition(selectChatRoomTypeViewModel.selectChatRoomTypeUIState) { uiState ->
when (val selectChatRoomTypeUIState = uiState) {
is SelectChatRoomTypeUIState.Error -> {
Column(
modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space250),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(
modifier = Modifier.height(MaterialTheme.spacing.space600)
)
Text(
text = selectChatRoomTypeUIState.message,
textAlign = TextAlign.Center
)
}
ErrorState(
message = selectChatRoomTypeUIState.message,
// Nothing to retry here: the keys could not be read, and going
// back is the way to try again.
onRetry = null,
)
}
SelectChatRoomTypeUIState.TooFewPeople -> {
ErrorState(
message = stringResource(Res.string.a_group_needs_at_least_people, Quorum.MINIMUM_GROUP_SIZE),
// The fix is picking more people, which is the screen behind this one.
onRetry = null,
)
}
is SelectChatRoomTypeUIState.Loaded -> {
val isActionPending = selectChatRoomTypeViewModel.isActionPending.value
val selectedChatRoomType = selectChatRoomTypeViewModel.selectedChatRoomType.value
val membersNotAdded = selectChatRoomTypeViewModel.membersNotAdded
val keyCeremonyNotStarted = selectChatRoomTypeViewModel.keyCeremonyNotStarted.value
val adminCount = selectChatRoomTypeViewModel.adminCount
val isRobustAvailable = selectChatRoomTypeViewModel.isRobustAvailable
val isRobustSelected = selectedChatRoomType == ChatRoomType.ROBUST
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
@@ -143,7 +137,7 @@ fun SelectChatRoomTypeScreen(
TopAppBar(
title = {
Text(
text = stringResource(Res.string.how_should_be_run, name),
text = name,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
@@ -154,21 +148,23 @@ fun SelectChatRoomTypeScreen(
bottomBar = {
BottomAppBar(
floatingActionButton = {
val label = if (selectChatRoomTypeViewModel.createdChatRoomId.value != null) {
stringResource(Res.string.open_chat)
} else {
stringResource(Res.string.create_group)
}
ExtendedFab(
label = if (selectChatRoomTypeViewModel.createdChatRoomId.value != null) {
stringResource(Res.string.open_chat)
} else {
stringResource(Res.string.create_chat)
},
label = label,
icon = {
if (isActionPending) {
CircularProgressIndicator(modifier = Modifier.size(20.dp))
} else {
Icon(Icons.Default.Check, contentDescription = "Create chat")
Icon(Icons.Default.Check, contentDescription = label)
}
},
onClick = {
selectChatRoomTypeViewModel.createChatRoom(
selectChatRoomTypeViewModel.createGroup(
onNavigateToRoute = onNavigateToRoute
)
}
@@ -177,11 +173,7 @@ fun SelectChatRoomTypeScreen(
actions = {
Text(
modifier = Modifier.padding(start = MaterialTheme.spacing.space200),
text = when (selectChatRoomTypeUIState.members.size) {
0 -> stringResource(Res.string.just_you_for_now)
1 -> stringResource(Res.string.you_and_1_other)
else -> stringResource(Res.string.you_and_others, selectChatRoomTypeUIState.members.size)
},
text = stringResource(Res.string.you_and_others, selectChatRoomTypeViewModel.memberPublicKeys.size),
style = MaterialTheme.typography.labelLarge
)
}
@@ -194,25 +186,9 @@ fun SelectChatRoomTypeScreen(
.readableContent()
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(MaterialTheme.spacing.space125),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125)
.padding(MaterialTheme.spacing.containerPadding),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)
) {
if (membersNotAdded.isNotEmpty()) {
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.onErrorContainer
)
) {
Text(
modifier = Modifier.padding(MaterialTheme.spacing.space200),
text = stringResource(Res.string.was_created_but_couldn_t_be_added_yet_invite, name, membersNotAdded.joinToString { selectChatRoomTypeViewModel.displayNameFor(it) }),
style = MaterialTheme.typography.bodyMedium
)
}
}
if (keyCeremonyNotStarted) {
Card(
modifier = Modifier.fillMaxWidth(),
@@ -249,56 +225,27 @@ fun SelectChatRoomTypeScreen(
}
Text(
text = stringResource(Res.string.this_decides_who_can_change_the_group_later),
style = MaterialTheme.typography.labelMedium,
modifier = Modifier.fillMaxWidth().padding(horizontal = MaterialTheme.spacing.space125)
text = stringResource(Res.string.all_of_you_administer_this_group_together, adminCount),
style = MaterialTheme.typography.bodyLarge
)
ChatRoomTypeCard(
icon = Icons.Default.Bolt,
title = "Convenient",
summary = "You are the only admin.",
detail = "You can add or remove people and change the group's name or description on your own, without waiting for anybody.",
footnote = "Nothing about the group can change unless you do it — and nobody else can carry it on if you lose your keys.",
isSelected = selectedChatRoomType == ChatRoomType.CONVENIENT,
onClick = {
selectChatRoomTypeViewModel.selectChatRoomType(ChatRoomType.CONVENIENT)
}
QuorumPicker(
quorum = selectChatRoomTypeViewModel.quorum.value,
adminCount = adminCount,
quorumRange = selectChatRoomTypeViewModel.quorumRange,
explanation = selectChatRoomTypeViewModel.quorumExplanation(),
onQuorumChange = selectChatRoomTypeViewModel::setQuorum
)
ChatRoomTypeCard(
icon = Icons.Default.Groups,
title = "Robust",
summary = "Every member is an admin.",
detail = if (isRobustAvailable) {
"All $adminCount of you administer the group together. Any change — adding or removing someone, renaming the group — has to be approved by a quorum of you before it takes effect."
} else {
"Everyone administers the group together. Any change — adding or removing someone, renaming the group — has to be approved by a quorum of the admins before it takes effect."
},
// Says what tapping create actually does, because it is the one
// thing here that asks something of everybody else: the group's
// first act is a ceremony each member has to approve their way
// through before there is a key.
footnote = "No single admin can change the group alone, and the group outlives any one of you. Creating the group starts a key ceremony every member takes part in.",
isSelected = isRobustSelected,
isEnabled = isRobustAvailable,
disabledReason = selectChatRoomTypeViewModel.robustUnavailableReason,
onClick = {
selectChatRoomTypeViewModel.selectChatRoomType(ChatRoomType.ROBUST)
}
) {
// Ask for the quorum only once robust is the choice — before that
// there is no decision to make.
if (isRobustSelected) {
QuorumPicker(
quorum = selectChatRoomTypeViewModel.quorum.value,
adminCount = adminCount,
quorumRange = selectChatRoomTypeViewModel.quorumRange,
explanation = selectChatRoomTypeViewModel.quorumExplanation(),
onQuorumChange = selectChatRoomTypeViewModel::setQuorum
)
}
}
// Says what tapping create actually does, because it is the one
// thing here that asks something of everybody else: the group's
// first act is a ceremony each member takes part in before there
// is a key. Claims only what the key enforces.
Text(
text = stringResource(Res.string.creating_the_group_starts_a_key_ceremony),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
@@ -316,7 +263,7 @@ fun SelectChatRoomTypeScreen(
)
Text(
text = stringResource(Res.string.how_should_be_run, name),
text = name,
style = MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center
)
@@ -340,87 +287,6 @@ fun SelectChatRoomTypeScreen(
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ChatRoomTypeCard(
icon: androidx.compose.ui.graphics.vector.ImageVector,
title: String,
summary: String,
detail: String,
footnote: String,
isSelected: Boolean,
onClick: () -> Unit,
isEnabled: Boolean = true,
disabledReason: String? = null,
content: @Composable () -> Unit = {},
) {
Card(
modifier = Modifier.fillMaxWidth(),
onClick = onClick,
enabled = isEnabled,
colors = if (isSelected) {
CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
)
} else {
CardDefaults.cardColors()
}
) {
Column(
modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space200),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = isSelected,
onClick = onClick,
enabled = isEnabled
)
Icon(
imageVector = icon,
contentDescription = Decorative
)
Text(
text = title,
style = MaterialTheme.typography.titleMedium
)
}
Text(
text = summary,
style = MaterialTheme.typography.titleSmall
)
Text(
text = detail,
style = MaterialTheme.typography.bodyMedium
)
Text(
text = footnote,
style = MaterialTheme.typography.labelMedium
)
disabledReason?.let {
Text(
text = it,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.error
)
}
content()
}
}
}
/**
* Asks how many admins have to sign off on a change. Stepped rather than typed:
* the range is small, both ends are bounded, and the caption has to keep up.
@@ -434,12 +300,12 @@ private fun QuorumPicker(
onQuorumChange: (Int) -> Unit,
) {
Column(
modifier = Modifier.fillMaxWidth().padding(top = MaterialTheme.spacing.space50),
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space50)
) {
Text(
text = stringResource(Res.string.how_many_admins_have_to_approve_a_change),
style = MaterialTheme.typography.titleSmall
text = stringResource(Res.string.how_many_of_you_have_to_agree),
style = MaterialTheme.typography.titleMedium
)
Row(
@@ -453,7 +319,7 @@ private fun QuorumPicker(
) {
Icon(
Icons.Default.Remove,
contentDescription = "Fewer approvals"
contentDescription = stringResource(Res.string.fewer_approvals)
)
}
@@ -468,7 +334,7 @@ private fun QuorumPicker(
) {
Icon(
Icons.Default.Add,
contentDescription = "More approvals"
contentDescription = stringResource(Res.string.more_approvals)
)
}
}
@@ -489,9 +355,9 @@ private fun SelectChatRoomTypeScreenPreview() {
) {
SelectChatRoomTypeScreen(
activeUserPublicKey = "",
name = "Group discussions",
name = "#group-discussions",
description = "See something... say something.",
memberPublicKeys = listOf("hex", "otherHex"),
memberPublicKeys = listOf("hex", "otherHex", "thirdHex"),
initialSelectChatRoomTypeUIState = SelectChatRoomTypeUIState.Loaded(
members = listOf(
Profile(
@@ -505,6 +371,12 @@ private fun SelectChatRoomTypeScreenPreview() {
displayName = "Woman Of Few Words",
about = "Says it once, says it well.",
nostrEventId = "otherNostrEventId"
),
Profile(
publicKey = "thirdHex",
displayName = "Ada",
about = "Approves things, eventually.",
nostrEventId = "thirdNostrEventId"
)
)
),
@@ -40,6 +40,8 @@ import kotlinx.coroutines.launch
import mobi.giza.compose.resources.Res
import mobi.giza.compose.resources.a_subgroup_needs_at_least_three_admins
import mobi.giza.compose.resources.admin_of_this_group
import mobi.giza.compose.resources.fewer_approvals
import mobi.giza.compose.resources.more_approvals
import mobi.giza.compose.resources.anyone_in_this_group_can_run_a_subgroup
import mobi.giza.compose.resources.has_no_key_package_yet
import mobi.giza.compose.resources.how_many_admins_have_to_approve_a_change
@@ -314,7 +316,7 @@ private fun QuorumStepper(
onClick = { onQuorumChange(quorum - 1) },
enabled = quorum > quorumRange.first
) {
Icon(Icons.Default.Remove, contentDescription = "Fewer approvals")
Icon(Icons.Default.Remove, contentDescription = stringResource(Res.string.fewer_approvals))
}
Text(
@@ -326,7 +328,7 @@ private fun QuorumStepper(
onClick = { onQuorumChange(quorum + 1) },
enabled = quorum < quorumRange.last
) {
Icon(Icons.Default.Add, contentDescription = "More approvals")
Icon(Icons.Default.Add, contentDescription = stringResource(Res.string.more_approvals))
}
}
}
@@ -600,7 +600,7 @@ class DkgRitualViewModel(
companion object {
private const val TAG = "DkgRitualViewModel"
/** Matches SelectChatRoomTypeViewModel: relays are not always prompt. */
/** Matches `MarmotGroupCreation.KEY_PACKAGE_LOOKUP_TIMEOUT`: relays are not always prompt. */
private const val KEY_PACKAGE_LOOKUP_TIMEOUT = 10_000L
fun factory(
@@ -2,7 +2,6 @@ package mobi.giza.compose.ui.view.model
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
@@ -11,31 +10,14 @@ import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import co.touchlab.kermit.Logger
import com.vitorpamplona.crypto.random.RandomInstance
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.database.model.types.ChatRoomType
import mobi.giza.compose.extensions.toHex
import mobi.giza.compose.identity.Identity
import mobi.giza.compose.managers.MarmotGroupFactory
import mobi.giza.compose.managers.MarmotGroupName
import mobi.giza.compose.managers.Quorum
import mobi.giza.compose.nostr.MarmotProfile
import mobi.giza.compose.nostr.Relays
import mobi.giza.compose.repository.ChatRepository
import mobi.giza.compose.repository.DkgRepository
import mobi.giza.compose.repository.NostrRepository
@@ -45,11 +27,13 @@ import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.view.state.SelectChatRoomTypeUIState
/**
* Last step of group creation: how the group should be run, and then actually
* building it.
* Last step of group creation: how many of the group have to agree, and then
* actually building it.
*
* The choice is not cosmetic — it decides who lands in the epoch-0
* `admin_pubkeys` list, so the group can only be minted once it has been made.
* Every group a member makes is robust -- run on a t-of-n key its members
* generate together -- so the only thing left to decide here is `t`. There used
* to be a second kind, run by its creator alone; see
* docs/remove-convenient-groups.md.
*/
class SelectChatRoomTypeViewModel(
val activeUserPublicKey: HexKey,
@@ -70,31 +54,24 @@ class SelectChatRoomTypeViewModel(
val isActionPending: MutableState<Boolean> = mutableStateOf(false)
/** Convenient until the user says otherwise: it is the choice that always works. */
val selectedChatRoomType: MutableState<ChatRoomType> = mutableStateOf(ChatRoomType.CONVENIENT)
/**
* Set as soon as the room exists. Creating a group is not idempotent, so a second
* tap after a partially failed invite round has to reuse this room rather than
* mint another one.
* tap after the ceremony failed to start has to open this room rather than make
* another one.
*/
val createdChatRoomId: MutableState<String?> = mutableStateOf(null)
/** Members the group was created without, because no key package ever showed up. */
val membersNotAdded = mutableStateListOf<HexKey>()
/**
* Set when a [ChatRoomType.ROBUST] room was made but its key ceremony was not.
* Set when the room was made but its key ceremony was not.
*
* The room is real and usable either way -- only the shared key is missing, and
* it can be started again from the group's details. Worth saying rather than
* navigating on, because the key is the whole of what robust means.
* navigating on, because the key is the whole of what makes the group robust.
*/
val keyCeremonyNotStarted: MutableState<Boolean> = mutableStateOf(false)
/**
* Everyone who administers the group under [ChatRoomType.ROBUST]: the picked
* members plus the creator.
* Everyone who administers the group: the picked members plus the creator.
*
* Counted here only to offer a quorum. The admins themselves are read off
* the ceremony this screen opens -- `ChillDkgRitualManager.proposeRitual`
@@ -104,29 +81,29 @@ class SelectChatRoomTypeViewModel(
*/
val adminCount: Int = (memberPublicKeys + activeUserPublicKey).distinct().size
/** Quorums this group can be run on, under [ChatRoomType.ROBUST]. */
val quorumRange: IntRange = Quorum.range(adminCount)
/**
* Whether a group this size can be made at all. The member picker does not
* let a smaller one through, but a route can be built by hand, and the
* ceremony would refuse it later -- this screen is the honest place to say so.
*/
val isPossible: Boolean = Quorum.isPossible(adminCount)
/** Quorums this group can be run on. Empty when it is too small to be made. */
val quorumRange: IntRange = if (isPossible) Quorum.range(adminCount) else IntRange.EMPTY
/**
* How many of [adminCount] admins have to approve a change, under
* [ChatRoomType.ROBUST]. Starts on a simple majority and is the user's to move.
* How many of [adminCount] admins have to approve a change. Starts on a simple
* majority and is the user's to move.
*/
val quorum: MutableState<Int> = mutableStateOf(Quorum.default(adminCount))
/** Whether this group is big enough to be run as [ChatRoomType.ROBUST]. */
val isRobustAvailable: Boolean = Quorum.isPossible(adminCount)
/** Why robust is off the table, or null when it is available. */
val robustUnavailableReason: String? = if (isRobustAvailable) {
null
} else {
val shortfall = Quorum.MINIMUM_GROUP_SIZE - adminCount
val missing = if (shortfall == 1) "1 more person" else "$shortfall more people"
"Needs at least ${Quorum.MINIMUM_GROUP_SIZE} people in the group. Go back and add $missing."
}
fun initiate() {
if (!isPossible) {
logger.w("Asked to make a group of $adminCount; the floor is ${Quorum.MINIMUM_GROUP_SIZE}")
selectChatRoomTypeUIState = SelectChatRoomTypeUIState.TooFewPeople
return
}
viewModelScope.launch(Dispatchers.IO) {
val members = memberPublicKeys.mapNotNull { publicKey ->
nostrRepository.getProfileWithPublicKey(publicKey)
@@ -138,22 +115,10 @@ class SelectChatRoomTypeViewModel(
}
}
fun selectChatRoomType(chatRoomType: ChatRoomType) {
// Once the room exists the choice is baked into its epoch-0 group context and
// re-picking here would change nothing.
if (isActionPending.value || createdChatRoomId.value != null) return
// Belt and braces alongside the disabled card: a group this small cannot carry
// a meaningful threshold, so it never becomes robust.
if (chatRoomType == ChatRoomType.ROBUST && !isRobustAvailable) return
selectedChatRoomType.value = chatRoomType
}
fun setQuorum(value: Int) {
// Same freeze as the type itself: past creation the group's governance is
// already stamped into its epoch-0 context.
if (isActionPending.value || createdChatRoomId.value != null) return
// Past creation the quorum is the ceremony's, already on its way to
// everybody; moving it here would change nothing.
if (isActionPending.value || createdChatRoomId.value != null || !isPossible) return
quorum.value = value.coerceIn(quorumRange)
}
@@ -169,21 +134,43 @@ class SelectChatRoomTypeViewModel(
}
}
/** Names the member behind [publicKey], falling back to the key itself. */
fun displayNameFor(publicKey: HexKey): String {
val members = (selectChatRoomTypeUIState as? SelectChatRoomTypeUIState.Loaded)?.members
return members?.firstOrNull { it.publicKey == publicKey }?.humanReadableNameOrPubkey()
?: publicKey.take(SHORTENED_PUBLIC_KEY_LENGTH)
}
fun createChatRoom(
/**
* Makes the group: a NIP-17 room, and the key ceremony that makes it robust.
*
* NIP-17 has no admin, no privileged member and no MLS group. Membership is simply
* the p-tag set every message carries, which is why there is nothing to invite
* anyone to and no key package to wait on -- everybody picked is in the room the
* moment it exists, and learns about it from the first message.
*
* That first message is the key ceremony, opened here rather than left for somebody
* to find a button for.
*
* NIP-17 itself has nothing for the quorum to govern -- no group state to change, and
* a different member set is simply a different room -- so the only thing that can
* carry it is a key the group generates together and can only sign with t of n of
* them present. Everything that ceremony needs is settled by the time the room
* exists: who is in it, and how many of them have to agree. Waiting would mean
* handing the user the room they asked for minus the thing that makes it robust.
*
* Opening it is also how the rest of the group hears of the room at all. Standing up
* a NIP-17 room sends nothing to anybody; the proposal is the first event out, and
* the inbound path builds the same room on the other side from its p-tags. The
* group's admin room, a Marmot room whose id is derived from the key, follows once
* the ceremony completes -- `CeremonyFollowThrough` makes it.
*/
fun createGroup(
onNavigateToRoute: (Route) -> Unit
) {
if (isActionPending.value) return
// The room survived a partial invite round — the user has read who was left out
// and just wants to get on with the chat.
// A group this small is refused before anything is made; see [isPossible].
if (!isPossible) {
selectChatRoomTypeUIState = SelectChatRoomTypeUIState.TooFewPeople
return
}
// The room exists and its ceremony did not start. The user has read that and
// wants the chat; the ceremony can be started from there.
createdChatRoomId.value?.let { chatRoomId ->
onNavigateToRoute.invoke(
ChatRoomMessagingRoute(
@@ -195,7 +182,9 @@ class SelectChatRoomTypeViewModel(
return
}
val nostrPrivateKey = activeIdentityStateFlow.value?.nostrPrivateKey
// The ceremony needs the secret itself, not a key pair: the ChillDKG host key
// is derived from it rather than being it.
val nostrPrivateKey = activeIdentityStateFlow.value?.nostrPrivateKey?.value?.toByteArray()
if (nostrPrivateKey == null) {
selectChatRoomTypeUIState = SelectChatRoomTypeUIState.Error(
"Couldn't read your keys. Please try again."
@@ -205,130 +194,9 @@ class SelectChatRoomTypeViewModel(
isActionPending.value = true
val nostrPrivateKeyBytes = nostrPrivateKey.value.toByteArray()
val keyPair = KeyPair(
privKey = nostrPrivateKeyBytes
)
when (selectedChatRoomType.value) {
ChatRoomType.CONVENIENT -> createMarmotChatRoom(keyPair, onNavigateToRoute)
// The ceremony needs the secret itself, not the pair: the ChillDKG host
// key is derived from it rather than being it.
ChatRoomType.ROBUST -> createNip17ChatRoom(keyPair, nostrPrivateKeyBytes, onNavigateToRoute)
}
}
/**
* Convenient rooms are Marmot/MLS: one admin, forward secrecy, and members added
* by commit — which is why every invite needs the peer's key package first.
*/
private fun createMarmotChatRoom(
keyPair: KeyPair,
onNavigateToRoute: (Route) -> Unit
) {
val gid = RandomInstance.bytes(32).toHexKey() // TODO: Generate GID through frost...
// Every Marmot room is a `#name`. This one does not go through
// `MarmotGroupCreation` -- its id is random rather than derived, so it has
// no key state to adopt and no admin set to bake in -- which is why the
// convention is applied here as well as there.
val groupName = MarmotGroupName.of(name)
viewModelScope.launch(Dispatchers.IO) {
// The group's initial state is baked into the epoch-0 GroupContext so later
// invitees receive a pre-populated group from the Welcome and never have to
// chase an undecryptable bootstrap commit that predates their membership.
// Which profile that state is on is the factory's decision, not this
// screen's -- see MarmotGroupFactory.
val created = MarmotGroupFactory.create(
creator = keyPair,
roomId = gid,
name = groupName,
description = description,
adminPublicKeys = listOf(keyPair.pubKey.toHexKey()),
relays = Relays.DefaultDMRelayList.map { it.url },
)
val group = created.group
val localChatRoom = chatRepository.getOrCreateChatRoom(
// Key the room on its Marmot id, NOT on `MlsGroup`'s own randomly
// generated groupId — they are unrelated 32-byte values. Every inbound
// path (and the invitee's own join) resolves rooms to this id, through
// the routing address recorded below.
chatRoomId = gid,
activeUserPublicKey = keyPair.pubKey.toHexKey(),
relayHint = null,
defaultSubject = groupName,
description = description,
mlsGroupState = group.saveState().encodeTls().toHex()
)
if (localChatRoom != null) {
chatRepository.recordMarmotRouting(chatRoomId = gid, routingId = created.routingId)
}
if (localChatRoom == null) {
withContext(Dispatchers.Main) {
isActionPending.value = false
onNavigateToRoute.invoke(
ImplementationPendingRoute("Something went wrong")
)
}
return@launch
}
createdChatRoomId.value = localChatRoom.chatRoom.id
val notAdded = inviteMembers(chatRoomId = localChatRoom.chatRoom.id)
withContext(Dispatchers.Main) {
isActionPending.value = false
if (notAdded.isEmpty()) {
onNavigateToRoute.invoke(
ChatRoomMessagingRoute(
activeUserPublicKey = keyPair.pubKey.toHexKey(),
chatRoomId = localChatRoom.chatRoom.id,
relayHint = null
)
)
} else {
// The group is real and usable without them; say who is missing instead
// of dropping the user into a chat that is quietly short a few people.
membersNotAdded.clear()
membersNotAdded.addAll(notAdded)
}
}
}
}
/**
* Robust rooms are NIP-17: no MLS group, no admin, no privileged member. Membership
* is simply the p-tag set every message carries, which is why there is nothing to
* invite anyone to and no key package to wait on — everybody picked is in the room
* the moment it exists, and learns about it from the first message.
*
* That first message is the key ceremony, opened here rather than left for somebody
* to find a button for.
*
* NIP-17 itself has nothing for the quorum to govern — no group state to change, and
* a different member set is simply a different room — so the only thing that can
* carry it is a key the group generates together and can only sign with t of n of
* them present. Everything that ceremony needs is settled by the time the room
* exists: who is in it, and how many of them have to agree. Waiting would mean
* handing the user the room they asked for minus the thing that makes it robust.
*
* Opening it is also how the rest of the group hears of the room at all. Standing up
* a NIP-17 room sends nothing to anybody; the proposal is the first event out, and
* the inbound path builds the same room on the other side from its p-tags.
*/
private fun createNip17ChatRoom(
keyPair: KeyPair,
nostrPrivateKey: ByteArray,
onNavigateToRoute: (Route) -> Unit
) {
viewModelScope.launch(Dispatchers.IO) {
val localChatRoom = chatRepository.createNip17ChatRoom(
userPublicKey = keyPair.pubKey.toHexKey(),
userPublicKey = activeUserPublicKey,
participantPublicKeys = memberPublicKeys,
subject = name,
description = description
@@ -353,7 +221,7 @@ class SelectChatRoomTypeViewModel(
// hands that one back instead of opening a second.
val session = dkgRepository.proposeRitual(
localChatRoom = localChatRoom,
userPublicKey = keyPair.pubKey.toHexKey(),
userPublicKey = activeUserPublicKey,
nostrPrivateKey = nostrPrivateKey,
threshold = quorum.value
)
@@ -373,7 +241,7 @@ class SelectChatRoomTypeViewModel(
onNavigateToRoute.invoke(
ChatRoomMessagingRoute(
activeUserPublicKey = keyPair.pubKey.toHexKey(),
activeUserPublicKey = activeUserPublicKey,
chatRoomId = localChatRoom.chatRoom.id,
relayHint = null
)
@@ -382,64 +250,9 @@ class SelectChatRoomTypeViewModel(
}
}
/**
* Adds every picked member to the freshly created group and returns the ones that
* could not be added.
*/
private suspend fun inviteMembers(chatRoomId: String): List<HexKey> {
if (memberPublicKeys.isEmpty()) return emptyList()
// Resolve the key packages concurrently so the whole batch costs one relay round
// trip rather than one per member.
val keyPackages = coroutineScope {
memberPublicKeys.map { publicKey ->
async {
publicKey to withTimeoutOrNull(KEY_PACKAGE_LOOKUP_TIMEOUT) {
chatRepository.observeMarmotKeyPackageForPublicKey(publicKey, MarmotProfile.DEFAULT_FOR_NEW_ROOMS)
.filterNotNull()
.first()
}
}
}.awaitAll()
}
val withoutKeyPackage = keyPackages.filter { it.second == null }.map { it.first }
withoutKeyPackage.forEach { logger.w("No key package for $it; leaving them out of $chatRoomId") }
val addable = keyPackages.mapNotNull { (publicKey, keyPackage) ->
keyPackage?.let { publicKey to it }
}
if (addable.isEmpty()) return withoutKeyPackage
// One commit for the whole membership rather than one per member. Inviting
// sequentially creates an epoch each, and each commit races the previous
// member's Welcome -- a race MarmotInboundManager resolves by dropping the
// commit outright, leaving that member an epoch behind while this reports
// success. See docs/marmot-membership.md.
val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId)
if (localChatRoom == null) {
logger.e("Chat room $chatRoomId disappeared before its members were added")
return memberPublicKeys
}
val notAdded = runCatching {
chatRepository.addMembers(localChatRoom = localChatRoom, peers = addable)
}.onFailure {
logger.e("Failed to add members to $chatRoomId", it)
}.getOrElse { addable.map { (publicKey, _) -> publicKey } }
return withoutKeyPackage + notAdded
}
companion object {
private const val TAG = "SelectChatRoomTypeViewModel"
/** Shared budget for pulling every picked member's key package off the relays. */
private val KEY_PACKAGE_LOOKUP_TIMEOUT = 20.seconds
/** Enough of a pubkey to tell two members apart when no profile is stored. */
private const val SHORTENED_PUBLIC_KEY_LENGTH = 12
fun factory(
activeUserPublicKey: HexKey,
name: String,
@@ -12,5 +12,11 @@ sealed interface SelectChatRoomTypeUIState {
val message: String
): SelectChatRoomTypeUIState
/**
* Fewer people than a group can be made with. The member picker does not let
* one through, so reaching this is a route somebody built by hand.
*/
data object TooFewPeople: SelectChatRoomTypeUIState
data object Loading: SelectChatRoomTypeUIState
}
@@ -1,7 +1,6 @@
package mobi.giza.compose.managers
import java.io.File
import kotlin.test.Ignore
import kotlin.test.Test
import kotlin.test.assertEquals
@@ -37,7 +36,6 @@ class MarmotRoomEntryPointsJvmTest {
.map { it.nameWithoutExtension }
.toSet()
@Ignore // Phase 2: SelectChatRoomTypeViewModel still mints the convenient group
@Test
fun `a Marmot room is minted in two places and no others`() {
assertEquals(
@@ -45,4 +43,12 @@ class MarmotRoomEntryPointsJvmTest {
callersOf("MarmotGroupFactory.create("),
)
}
@Test
fun `members are added to a room only at its founding`() {
assertEquals(
setOf("MarmotGroupCreation"),
callersOf("chatRepository.addMembers("),
)
}
}
@@ -23,7 +23,6 @@ import mobi.giza.compose.database.model.DkgSession
import mobi.giza.compose.database.model.MarmotKeyPackage
import mobi.giza.compose.database.model.Profile
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.database.model.types.ChatRoomType
import mobi.giza.compose.identity.Identity
import mobi.giza.compose.identity.IdentityKind
import mobi.giza.compose.identity.toWalletId
@@ -34,14 +33,12 @@ import mobi.giza.compose.repository.DkgRepository
import mobi.giza.compose.repository.NostrRepository
import mobi.giza.compose.ui.view.state.SelectChatRoomTypeUIState
import okio.Path.Companion.toPath
import org.junit.Ignore
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertTrue
/**
@@ -171,13 +168,12 @@ class GroupCreationJvmTest {
delay(50)
}
@Ignore("Phase 2: the screen still starts on a convenient group")
@Test
fun `creating a group opens a NIP-17 room and its key ceremony`(): Unit = runBlocking {
val recorder = Recorder()
val viewModel = viewModel(recorder, listOf(bob, cleo, dora))
viewModel.createChatRoom(onNavigateToRoute = {})
viewModel.createGroup(onNavigateToRoute = {})
viewModel.awaitSettled()
assertEquals(listOf(listOf(bob, cleo, dora)), recorder.nip17Rooms)
@@ -191,16 +187,14 @@ class GroupCreationJvmTest {
val recorder = Recorder()
val viewModel = viewModel(recorder, listOf(bob, cleo, dora))
viewModel.selectChatRoomType(ChatRoomType.ROBUST)
viewModel.setQuorum(4)
viewModel.createChatRoom(onNavigateToRoute = {})
viewModel.createGroup(onNavigateToRoute = {})
viewModel.awaitSettled()
assertEquals(listOf(4), recorder.thresholds)
assertTrue(viewModel.keyCeremonyNotStarted.value)
}
@Ignore("Phase 2: a group of two still becomes a convenient one")
@Test
fun `a group below the floor is never created`(): Unit = runBlocking {
val recorder = Recorder()
@@ -210,10 +204,10 @@ class GroupCreationJvmTest {
withTimeout(5_000) {
while (viewModel.selectChatRoomTypeUIState is SelectChatRoomTypeUIState.Loading) delay(10)
}
viewModel.createChatRoom(onNavigateToRoute = {})
viewModel.createGroup(onNavigateToRoute = {})
viewModel.awaitSettled()
assertIs<SelectChatRoomTypeUIState.Error>(viewModel.selectChatRoomTypeUIState)
assertEquals(SelectChatRoomTypeUIState.TooFewPeople, viewModel.selectChatRoomTypeUIState)
assertEquals(emptyList(), recorder.nip17Rooms)
assertEquals(emptyList(), recorder.thresholds)
}