diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 64a74b12..d9218f1c 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -706,4 +706,19 @@ This group cannot take part: it needs at least as many admins as its threshold, and a threshold of two or more Propose confederation Couldn't propose the confederation + Confederation proposal + Coordinated by %1$s + Open until %1$s + Accepted + Declined + Waiting + Propose accepting + Propose declining + Propose withdrawing + Reason (optional) + Waiting for the group to sign its answer + Open the signing session + Accepting discloses this group's admins and threshold to the coordinator, sealed so that only they can read them. + This device does not hold that proposal + Couldn't ask the group to answer diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt index 3c728e24..70797caf 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseFrostSigningRepository.kt @@ -15,6 +15,7 @@ import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.intermdiate.FrostSignerTally import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.intermdiate.LocalFrostSigningSession +import mobi.giza.compose.managers.ConfederationRefusal import mobi.giza.compose.managers.FrostSigningManager import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents @@ -26,6 +27,9 @@ class DatabaseFrostSigningRepository( ): FrostSigningRepository { private val logger = Logger.withTag(TAG) + override suspend fun confederationNotes(chatRoomId: String, sessionId: String, events: List): List = + runCatching { ConfederationRefusal.notes(database, chatRoomId, sessionId, events) }.getOrDefault(emptyList()) + override fun observeSessionById(sessionId: String): Flow = database.frostSigningSessionDao().observeSessionById(sessionId) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt index 278d8a63..733b8d45 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationManager.kt @@ -73,16 +73,25 @@ object ConfederationManager { ), invitees = invitees, ) - // Once per event, by construction: the row above is written once. - if (filed) runCatching { announce(database, event, proposalId) } - .onFailure { logger.w(throwable = it) { "Filed ${event.id.take(8)} but could not write its line" } } + // Once per event, by construction: the row above is written once. An answer filed + // before its proposal had nothing to name, so the proposal writes its lines now -- + // relays deliver in any order, and a proposal and its proposer's acceptance share a + // second, so which comes first is down to their ids. + if (filed) runCatching { + announce(database, event, proposalId) + if (event.kind == ConfederationKinds.PROPOSAL) { + database.confederationDao().getEventsForProposal(proposalId) + .filter { it.kind in ConfederationKinds.ANSWERS } + .forEach { announce(database, it.toEvent(), proposalId) } + } + }.onFailure { logger.w(throwable = it) { "Filed ${event.id.take(8)} but could not write its line" } } return filed } /** * A system line in every room on this device that [event] concerns: each group its * proposal names (docs/confederation.md, Phase 6). An answer whose proposal this device does - * not hold yet gets no line; the proposal's own line says who has answered when it comes. + * not hold yet gets its line when the proposal is filed. */ private suspend fun announce(database: GizaDatabase, event: Event, proposalId: HexKey) { val proposal = proposal(database, proposalId) ?: return diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt index 34b21aa5..34491e82 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRefusal.kt @@ -189,6 +189,37 @@ object ConfederationRefusal { return null } + /** + * What a member should read before approving a session over a confederation event, beside + * its summary (D6): who it names, what an acceptance discloses, and -- as warnings rather + * than refusals -- each listed group whose public profile this device cannot find. + */ + suspend fun notes(database: GizaDatabase, chatRoomId: String, sessionId: String, events: List): List { + if (!involves(events)) return emptyList() + val carried = Carried.from(database.confederationDao().getSigning(sessionId)) + val proposal = events.firstOrNull { it.kind == ConfederationKinds.PROPOSAL }?.let(ConfederationProposalEvent::parse) + ?: carried.proposalJson?.let { Event.fromJsonOrNull(it) }?.let(ConfederationProposalEvent::parse) + ?: return emptyList() + + val names = proposal.groupPublicKeys.map { ConfederationManager.nameOf(database, it, chatRoomId) } + val notes = mutableListOf( + "Groups: ${names.joinToString()}", + "${proposal.threshold} of ${proposal.groups.size} groups must take part to sign", + "Coordinated by ${ConfederationManager.nameOf(database, proposal.coordinator)}", + ) + if (events.any { it.kind == ConfederationKinds.ACCEPTANCE }) { + ConfederationManager.adminListFor(database, chatRoomId, proposal.id)?.let { list -> + notes += "Discloses this group's ${list.admins.size} admins and its threshold of ${list.threshold} " + + "to the coordinator, sealed so that only they can read them" + } + } + proposal.groupPublicKeys.filter { it != chatRoomId }.forEach { group -> + val found = database.profileDao().getProfileByPublicKey(group)?.isResolved() == true + if (!found) notes += "No public profile found for ${ConfederationManager.nameOf(database, group)} on this device yet" + } + return notes + } + /** Keeps what a session over a confederation event must remember past its proposal (Phase 4's table). */ suspend fun remember(database: GizaDatabase, sessionId: String, carried: Carried, refusal: String?) { database.confederationDao().upsertSigning( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt index 0bfffe8f..8f7e9022 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/FrostSigningRepository.kt @@ -81,6 +81,9 @@ interface FrostSigningRepository { /** Whether this room holds a key it can sign with, so the UI offers nothing that would fail. */ suspend fun canSign(chatRoomId: String): Boolean + /** What to read before approving a confederation event in [sessionId] (docs/confederation.md, D6). */ + suspend fun confederationNotes(chatRoomId: String, sessionId: String, events: List): List = emptyList() + /** * Opens a session asking the group to sign an event with these fields. The * author is the room's own key, not the proposer's, and is filled in here -- diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProposalScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProposalScreen.kt new file mode 100644 index 00000000..f64de9da --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationProposalScreen.kt @@ -0,0 +1,240 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Block +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.HourglassEmpty +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.nostr.confederation.ConfederationAnswer +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.accepting_discloses_admins +import mobi.giza.compose.resources.answer_accepted +import mobi.giza.compose.resources.answer_declined +import mobi.giza.compose.resources.answer_waiting +import mobi.giza.compose.resources.confederation_groups +import mobi.giza.compose.resources.confederation_groups_to_act +import mobi.giza.compose.resources.confederation_proposal +import mobi.giza.compose.resources.confederation_proposed_by +import mobi.giza.compose.resources.coordinated_by +import mobi.giza.compose.resources.could_not_ask_the_group_to_answer +import mobi.giza.compose.resources.open_the_signing_session +import mobi.giza.compose.resources.open_until +import mobi.giza.compose.resources.propose_accepting +import mobi.giza.compose.resources.propose_declining +import mobi.giza.compose.resources.propose_withdrawing +import mobi.giza.compose.resources.reason_optional +import mobi.giza.compose.resources.this_device_does_not_hold_that_proposal +import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_answer +import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.ConfederationProposalViewModel +import mobi.giza.compose.ui.view.state.ConfederationProposalUIState +import org.jetbrains.compose.resources.stringResource + +/** + * One confederation proposal, seen from one of the groups it names (docs/confederation.md, + * Phase 7): what it is, who coordinates, every group's answer, and -- for a member who can put + * one to the group -- this group's answer. Answering is a group signature, so each button opens + * a signing session and the screen goes to it. One answer at a time: while one is being signed + * the buttons give way to it. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ConfederationProposalScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + proposalId: HexKey, + initialConfederationProposalUIState: ConfederationProposalUIState = ConfederationProposalUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: ConfederationProposalViewModel = viewModel( + factory = ConfederationProposalViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + proposalId = proposalId, + initialConfederationProposalUIState = initialConfederationProposalUIState, + chatRepository = chatRepository, + confederationRepository = confederationRepository, + ) + ) + LaunchedEffect(true) { + if (initialConfederationProposalUIState == ConfederationProposalUIState.Loading) viewModel.initiate() + } + + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotAnswer = stringResource(Res.string.could_not_ask_the_group_to_answer) + val identityCanSign = LocalCanSign.current + val reasonField = rememberTextFieldState() + val state by viewModel.uiState.collectAsState() + val toSession: (String) -> Unit = { sessionId -> + onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) + } + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { Text(text = stringResource(Res.string.confederation_proposal), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + }, + ) { padding -> + ScreenStateTransition(state) { uiState -> + when (val current = uiState) { + is ConfederationProposalUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = current.message, onRetry = null) + + ConfederationProposalUIState.Loading -> LoadingDataIndicator(modifier = Modifier.padding(padding)) + + ConfederationProposalUIState.NotHeld -> EmptyState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.this_device_does_not_hold_that_proposal), + ) + + is ConfederationProposalUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + val proposal = current.status.proposal + val nameOf = { key: HexKey -> current.names[key] ?: key.take(12) } + + Text(text = proposal.name, style = MaterialTheme.typography.headlineSmall) + Text(text = stateLabel(current.status.state), style = MaterialTheme.typography.labelLarge) + Text(text = stringResource(Res.string.confederation_proposed_by, nameOf(proposal.proposingGroup))) + Text(text = stringResource(Res.string.coordinated_by, nameOf(proposal.coordinator))) + Text(text = stringResource(Res.string.confederation_groups_to_act, proposal.threshold, proposal.groups.size)) + Text( + text = stringResource(Res.string.open_until, Instant.fromEpochSeconds(proposal.expiresAt).toFormattedTimeAndDateString()), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + HorizontalDivider() + Text(text = stringResource(Res.string.confederation_groups), style = MaterialTheme.typography.titleSmall) + proposal.groupPublicKeys.forEach { group -> + val answer = current.status.answerOf(group) + ListItem( + leadingContent = { + Icon( + imageVector = when (answer) { + ConfederationAnswer.ACCEPTED -> Icons.Default.CheckCircle + ConfederationAnswer.REJECTED -> Icons.Default.Block + ConfederationAnswer.WAITING -> Icons.Default.HourglassEmpty + }, + contentDescription = Decorative, + ) + }, + headlineContent = { Text(text = nameOf(group), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + supportingContent = { + Text( + stringResource( + when (answer) { + ConfederationAnswer.ACCEPTED -> Res.string.answer_accepted + ConfederationAnswer.REJECTED -> Res.string.answer_declined + ConfederationAnswer.WAITING -> Res.string.answer_waiting + } + ) + ) + }, + ) + } + + current.pendingSessionId?.let { sessionId -> + HorizontalDivider() + Text(text = stringResource(Res.string.waiting_for_the_group_to_sign_its_answer)) + TextButton(onClick = { toSession(sessionId) }) { + Text(stringResource(Res.string.open_the_signing_session)) + } + } + + if (current.canAnswer && identityCanSign) { + HorizontalDivider() + Text( + text = stringResource(Res.string.accepting_discloses_admins), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Button( + modifier = Modifier.fillMaxWidth(), + enabled = !current.isActing, + onClick = { viewModel.accept(onSuccess = toSession, onFailure = { notify(couldNotAnswer) }) }, + ) { Text(stringResource(Res.string.propose_accepting)) } + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = reasonField, + label = { Text(stringResource(Res.string.reason_optional)) }, + lineLimits = TextFieldLineLimits.SingleLine, + ) + OutlinedButton( + modifier = Modifier.fillMaxWidth(), + enabled = !current.isActing, + onClick = { + viewModel.reject(reasonField.text.toString(), onSuccess = toSession, onFailure = { notify(couldNotAnswer) }) + }, + ) { Text(stringResource(Res.string.propose_declining)) } + } + + if (current.canWithdraw && identityCanSign) { + HorizontalDivider() + OutlinedButton( + modifier = Modifier.fillMaxWidth(), + enabled = !current.isActing, + onClick = { viewModel.withdraw(onSuccess = toSession, onFailure = { notify(couldNotAnswer) }) }, + ) { Text(stringResource(Res.string.propose_withdrawing)) } + } + } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt index d8411586..7f527b58 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ConfederationsScreen.kt @@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.material.icons.filled.Hub import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api @@ -42,6 +43,7 @@ import mobi.giza.compose.resources.confederation_withdrawn import mobi.giza.compose.resources.confederations import mobi.giza.compose.resources.propose_a_confederation import mobi.giza.compose.resources.this_device_holds_no_confederation_proposals_for_this_group +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.composable.widgets.Decorative @@ -141,7 +143,18 @@ fun ConfederationsScreen( } } else { items(items = current.proposals, key = { it.status.proposal.id }) { item -> - ConfederationProposalCard(item = item) + ConfederationProposalCard( + item = item, + onClick = { + onNavigateToRoute( + ConfederationProposalRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + proposalId = item.status.proposal.id, + ) + ) + }, + ) } } } @@ -151,14 +164,16 @@ fun ConfederationsScreen( } /** One proposal: what it is called, who made it, how many must act, and where it stands. */ +@OptIn(ExperimentalMaterial3Api::class) @Composable -private fun ConfederationProposalCard(item: ConfederationsUIState.Item) { +private fun ConfederationProposalCard(item: ConfederationsUIState.Item, onClick: () -> Unit) { val status = item.status val proposal = status.proposal val groups = proposal.groups.size - Card(modifier = Modifier.fillMaxWidth()) { + Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) { ListItem( leadingContent = { Icon(Icons.Default.Hub, contentDescription = Decorative) }, + trailingContent = { Icon(Icons.Default.ChevronRight, contentDescription = Decorative) }, overlineContent = { Text(text = stateLabel(status.state)) }, headlineContent = { Text(text = proposal.name, maxLines = 1, overflow = TextOverflow.Ellipsis) }, supportingContent = { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt index 446bd673..0a68b174 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/FrostSigningScreen.kt @@ -208,6 +208,12 @@ fun FrostSigningScreen( else -> WhatIsBeingSigned(proposed, state.items.size) } + // A confederation event's terms and what this device could not check + // about it, for the member to weigh. docs/confederation.md, D6. + state.confederationNotes.forEach { note -> + Text(text = note, style = MaterialTheme.typography.bodySmall) + } + HorizontalDivider() Text( 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 71b91cc8..9fd7c2d5 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 @@ -6,6 +6,8 @@ import mobi.giza.compose.ui.composable.navigation.routes.BroadcastGroupSignedEve import mobi.giza.compose.ui.composable.BroadcastGroupSignedEventScreen import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute +import mobi.giza.compose.ui.composable.navigation.routes.ConfederationProposalRoute +import mobi.giza.compose.ui.composable.ConfederationProposalScreen import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRoute import mobi.giza.compose.ui.composable.ConfederationsScreen import mobi.giza.compose.ui.composable.ProposeConfederationScreen @@ -1301,6 +1303,19 @@ fun GizaNavHost( onNavigateBack = { navController.popBackStack() } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + ConfederationProposalScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + proposalId = route.proposalId, + chatRepository = databaseChatRepository, + confederationRepository = databaseConfederationRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationProposalRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationProposalRoute.kt new file mode 100644 index 00000000..d8b3a00a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/ConfederationProposalRoute.kt @@ -0,0 +1,11 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** One confederation proposal, seen from one of the groups it names. docs/confederation.md, Phase 7. */ +@Serializable +data class ConfederationProposalRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val proposalId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProposalViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProposalViewModel.kt new file mode 100644 index 00000000..ffe90dc3 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ConfederationProposalViewModel.kt @@ -0,0 +1,127 @@ +package mobi.giza.compose.ui.view.model + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.ConfederationRepository +import mobi.giza.compose.ui.view.state.ConfederationProposalUIState + +/** + * One confederation proposal from one of the groups it names, and the group's answer to it + * (docs/confederation.md, Phase 7). Watched: the other groups' answers arrive from relays while + * the screen is open, and so does this group's own once its quorum signs. + */ +class ConfederationProposalViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + val proposalId: HexKey, + initialConfederationProposalUIState: ConfederationProposalUIState, + val chatRepository: ChatRepository, + val confederationRepository: ConfederationRepository, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + + private val state = MutableStateFlow(initialConfederationProposalUIState) + val uiState: StateFlow = state.asStateFlow() + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + if (localChatRoom == null) { + state.value = ConfederationProposalUIState.Error("Couldn't find the group") + return@launch + } + val canSign = GroupStatementCapability.roomIsOpen(localChatRoom) && chatRepository.canSign(chatRoomId) + + combine( + confederationRepository.observeStatus(proposalId), + confederationRepository.observePendingAnswer(chatRoomId, proposalId), + ) { status, pending -> status to pending }.collect { (status, pending) -> + if (status == null) { + state.value = ConfederationProposalUIState.NotHeld + return@collect + } + val keys = status.proposal.groupPublicKeys + status.proposal.coordinator + val names = keys.associateWith { confederationRepository.nameOf(it, chatRoomId) } + val acting = (state.value as? ConfederationProposalUIState.Loaded)?.isActing == true + state.value = ConfederationProposalUIState.Loaded( + localChatRoom = localChatRoom, + status = status, + names = names, + pendingSessionId = pending?.id, + canSign = canSign, + isActing = acting, + ) + } + } + } + + fun accept(onSuccess: (String) -> Unit, onFailure: () -> Unit) = act(onSuccess, onFailure) { loaded -> + confederationRepository.proposeAcceptance(loaded.localChatRoom, activeUserPublicKey, proposalId) + } + + fun reject(reason: String, onSuccess: (String) -> Unit, onFailure: () -> Unit) = act(onSuccess, onFailure) { loaded -> + confederationRepository.proposeRejection(loaded.localChatRoom, activeUserPublicKey, proposalId, reason.trim()) + } + + fun withdraw(onSuccess: (String) -> Unit, onFailure: () -> Unit) = act(onSuccess, onFailure) { loaded -> + confederationRepository.proposeWithdrawal(loaded.localChatRoom, activeUserPublicKey, proposalId) + } + + private fun act( + onSuccess: (String) -> Unit, + onFailure: () -> Unit, + propose: suspend (ConfederationProposalUIState.Loaded) -> FrostSigningSession, + ) { + val loaded = state.value as? ConfederationProposalUIState.Loaded ?: return + if (loaded.isActing) return + state.update { (it as? ConfederationProposalUIState.Loaded)?.copy(isActing = true) ?: it } + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { propose(loaded) } + .onFailure { logger.e("Could not ask $chatRoomId to answer $proposalId", it) } + .getOrNull() + state.update { (it as? ConfederationProposalUIState.Loaded)?.copy(isActing = false) ?: it } + viewModelScope.launch(Dispatchers.Main) { + if (session != null) onSuccess(session.id) else onFailure() + } + } + } + + companion object { + private const val TAG = "ConfederationProposalViewModel" + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + proposalId: HexKey, + initialConfederationProposalUIState: ConfederationProposalUIState = ConfederationProposalUIState.Loading, + chatRepository: ChatRepository, + confederationRepository: ConfederationRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + ConfederationProposalViewModel( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + proposalId = proposalId, + initialConfederationProposalUIState = initialConfederationProposalUIState, + chatRepository = chatRepository, + confederationRepository = confederationRepository, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt index d58232c9..ba42a39f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/FrostSigningViewModel.kt @@ -43,6 +43,9 @@ class FrostSigningViewModel( val isActionPending: MutableState = mutableStateOf(false) + /** Read once, when the session's events are first known: they never change. */ + private var notes: List? = null + /** * Loads the room, then watches the session for as long as the screen lives. * @@ -77,6 +80,9 @@ class FrostSigningViewModel( shareHolders ) { session, messages, items, holders -> Observed(session, messages, items, holders) } .collect { (session, messages, items, holders) -> + if (notes == null && items.isNotEmpty()) { + notes = frostSigningRepository.confederationNotes(chatRoomId, sessionId, proposedEvents(items)) + } // Read per emission rather than derived from `messages`: who // the session is waiting on is the manager's rule, and it is // not the same rule at every stage. See @@ -101,6 +107,7 @@ class FrostSigningViewModel( .map { it.signerPublicKey } .toSet(), silent = owed, + confederationNotes = notes.orEmpty(), ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProposalUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProposalUIState.kt new file mode 100644 index 00000000..103f2751 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ConfederationProposalUIState.kt @@ -0,0 +1,39 @@ +package mobi.giza.compose.ui.view.state + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.confederation.ConfederationStatus + +/** One proposal, seen from one of the groups it names (docs/confederation.md, Phase 7). */ +sealed interface ConfederationProposalUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + val status: ConfederationStatus, + /** How to name each group on it, and the coordinator. */ + val names: Map = emptyMap(), + /** A signing session this group has open over an answer, if any: one at a time. */ + val pendingSessionId: String? = null, + /** Whether this device can put an answer to the group: an open room and a share. */ + val canSign: Boolean = false, + val isActing: Boolean = false, + ) : ConfederationProposalUIState { + private val roomId get() = localChatRoom.chatRoom.id + + private val open get() = status.state == mobi.giza.compose.nostr.confederation.ConfederationProposalState.OPEN + + /** This group is invited, has not answered, and nothing is waiting to be signed. */ + val canAnswer: Boolean + get() = canSign && open && pendingSessionId == null && status.proposal.lists(roomId) && + status.proposal.proposingGroup != roomId && !status.hasAnswered(roomId) + + /** This group made it, and it is still open. */ + val canWithdraw: Boolean + get() = canSign && open && pendingSessionId == null && status.proposal.proposingGroup == roomId + } + + data object NotHeld : ConfederationProposalUIState + + data class Error(val message: String) : ConfederationProposalUIState + + data object Loading : ConfederationProposalUIState +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt index b0849f65..4244db04 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/FrostSigningUIState.kt @@ -24,6 +24,9 @@ sealed interface FrostSigningUIState { */ val items: List = emptyList(), + /** For a confederation event: who it names, what it discloses, what could not be checked. docs/confederation.md, D6. */ + val confederationNotes: List = emptyList(), + /** Who has offered a nonce, so the screen can name who it is waiting on. */ val offeredNonce: Set = emptySet(), diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationNetworkJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationNetworkJvmTest.kt new file mode 100644 index 00000000..0ec0e0cd --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationNetworkJvmTest.kt @@ -0,0 +1,227 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.Frost +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgParticipantMessage +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.MarmotInnerEvent +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.types.FrostSigningStage +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.confederation.ConfederationKinds +import mobi.giza.compose.nostr.confederation.ConfederationProposalEvent.Invitee +import mobi.giza.compose.nostr.confederation.ConfederationProposalState +import mobi.giza.compose.nostr.confederation.ConfederationSeal +import mobi.giza.compose.nostr.dkg.DkgRitualEvents +import mobi.giza.compose.nostr.frost.FrostSigningEvents +import kotlin.time.Clock + +/** + * Three groups agreeing, or not, to form a confederation, end to end (docs/confederation.md, + * Phase 7): real FROST signatures by each group's quorum, every device's own refusals, and the + * relays stood in for by copying each signed event to every device. Afterwards every device on + * every group computes the same state, and the coordinator opens each acceptance to the admins + * that group has. + */ +class ConfederationNetworkJvmTest { + private fun key(group: Int, member: Int) = PrivateKey(ByteArray(32).also { it[0] = 0x41; it[30] = group.toByte(); it[31] = member.toByte() }) + + private inner class Group(val index: Int, val name: String) { + val secrets = (1..3).map { key(index, it) } + val members = secrets.map { it.publicKey().xOnly().value.toHex() } + val material: KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey(ByteVector32(("c0" + index.toString().padStart(2, '0')).padEnd(62, '0') + "a1")), + nParticipants = 3, + threshold = 2, + ) + val thresholdPublicKey = material.thresholdPublicKey.value.toHex() + val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + val ceremonyId = "ceremony$index".padEnd(64, '0') + val hostKeys = (0..2).map { "2${('a' + it)}$index".padEnd(66, '0') } + lateinit var devices: List + } + + private inner class Device(val group: Group, val signerIndex: Int, val db: GizaDatabase, val room: LocalChatRoom) { + val publicKey get() = group.members[signerIndex] + val received = mutableSetOf() + } + + private val groups = listOf(Group(1, "Agora"), Group(2, "Polis"), Group(3, "Ekklesia")) + private val agora = groups[0] + private val polis = groups[1] + private val ekklesia = groups[2] + private val everyDevice get() = groups.flatMap { it.devices } + + @BeforeTest + fun network() = runBlocking { + RoomAdmins.override = { id -> groups.firstOrNull { it.roomId == id }?.let { RoomAdmins(it.members.toSet(), governed = false) } } + groups.forEach { group -> group.devices = (0..2).map { device(group, it) } } + } + + @AfterTest + fun close() { + RoomAdmins.override = null + groups.forEach { g -> if (g.isInitialised()) g.devices.forEach { it.db.close() } } + } + + private fun Group.isInitialised() = runCatching { devices }.isSuccess + + private suspend fun device(group: Group, signerIndex: Int): Device { + val db = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + val owner = group.members[signerIndex] + group.members.forEach { member -> + val eventId = "e$member".take(64) + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = member, nostrEventId = eventId)) + } + val chatRoom = ChatRoom( + id = group.roomId, userPublicKey = owner, subject = "#${group.name}", + description = SharedKeyDerivation.describe("Admins of the group."), mlsGroupState = "00", + ) + db.chatRoomDao().upsert(chatRoom) + db.dkgSessionDao().upsert( + DkgSession( + id = group.ceremonyId, chatRoomId = group.roomId, coordinatorPublicKey = group.members[0], userPublicKey = owner, + threshold = 2, participantCount = 3, stage = DkgRitualStage.COMPLETE, hostPublicKey = group.hostKeys[signerIndex], + round1Random = "1".repeat(64), round2AuxRandom = "2".repeat(64), thresholdPublicKey = group.thresholdPublicKey, + secretShare = group.material.secretShares[signerIndex].value.toHex(), + publicShares = group.material.publicShares.joinToString(",") { it.value.toHex() }, + ) + ) + group.members.forEachIndexed { i, member -> + db.dkgSessionDao().upsert(DkgParticipantMessage(sessionId = group.ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = group.hostKeys[i])) + } + return Device(group, signerIndex, db, LocalChatRoom(chatRoom = chatRoom)) + } + + /** Ferries a group's signing messages between its devices until nothing moves. */ + private suspend fun pump(group: Group) { + var moved = true + while (moved) { + moved = false + for (from in group.devices) for (to in group.devices) { + if (from === to) continue + from.db.marmotInnerEventDao().getByChatRoomAndKinds(group.roomId, FrostSigningEvents.ALL.toList()) + .filter { it.publicKey == from.publicKey } + .sortedWith(compareBy({ it.createdAt }, { it.kind })) + .forEach { queued -> + if (!to.received.add(queued.id)) return@forEach + moved = true + to.db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = queued.id, publicKey = queued.publicKey, kind = queued.kind, createdAt = queued.createdAt, + tags = queued.tags, content = queued.content, chatRoomId = group.roomId, + ) + ) + FrostSigningManager.processSigningPayload( + database = to.db, localChatRoom = to.room, + innerEvent = Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, ""), + userPublicKey = to.publicKey, + ) + } + } + } + } + + /** The relays: every event a coordinating device owes goes to every device, and is marked sent. */ + private suspend fun relay() { + everyDevice.forEach { from -> + from.db.confederationDao().observeUnpublished().first().forEach { owed -> + everyDevice.forEach { to -> ConfederationManager.record(to.db, owed.toEvent()) } + from.db.confederationDao().markPublished(owed.id, Clock.System.now()) + } + } + } + + /** [group]'s first member proposes with [propose]; its second approves; the quorum signs; the relays carry it. */ + private suspend fun signed(group: Group, propose: suspend (Device) -> String) { + val sessionId = propose(group.devices[0]) + pump(group) + val second = group.devices[1] + FrostSigningManager.approve(second.db, second.room, sessionId) + pump(group) + group.devices.forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.db.frostSigningSessionDao().getSessionById(sessionId)?.stage, "${group.name} signed on device ${device.signerIndex}") + } + relay() + } + + private suspend fun proposeAtlas(): HexKey { + signed(agora) { device -> + ConfederationManager.proposeConfederation( + device.db, device.room, device.publicKey, + invitees = listOf(Invitee(polis.roomId), Invitee(ekklesia.roomId)), + threshold = 2, name = "Atlas", + expiresAt = Clock.System.now().epochSeconds + ConfederationKinds.DEFAULT_EXPIRY_SECONDS, + ).id + } + return everyDevice.first().db.confederationDao().getProposals().single().id + } + + private suspend fun states(proposalId: HexKey) = everyDevice.map { ConfederationManager.status(it.db, proposalId)?.state }.toSet() + + @Test + fun `one group declining ends it for every device on every group`() = runBlocking { + val proposalId = proposeAtlas() + assertEquals(setOf(ConfederationProposalState.OPEN), states(proposalId)) + + signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).id } + signed(ekklesia) { ConfederationManager.proposeRejection(it.db, it.room, it.publicKey, proposalId, "Not this year").id } + + assertEquals(setOf(ConfederationProposalState.REJECTED), states(proposalId)) + } + + @Test + fun `every group accepting is seen by every device, and the coordinator opens each group's admins`() = runBlocking { + val proposalId = proposeAtlas() + signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).id } + signed(ekklesia) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).id } + + assertEquals(setOf(ConfederationProposalState.ACCEPTED), states(proposalId)) + + val coordinator = agora.devices[0] + val status = assertNotNull(ConfederationManager.status(coordinator.db, proposalId)) + groups.forEach { group -> + val acceptance = assertNotNull(status.acceptances[group.roomId], "${group.name} accepted") + val conversationKey = ConfederationSeal.conversationKey(agora.secrets[0].value.toByteArray(), acceptance.ephemeralPublicKey) + val list = assertNotNull(ConfederationSeal.open(conversationKey, acceptance.content), "the coordinator opens ${group.name}'s") + assertEquals(group.members.sorted(), list.admins) + assertEquals(2, list.threshold) + assertEquals(group.roomId, list.group) + } + } + + @Test + fun `each group's room has a line for the proposal and for every answer`() = runBlocking { + val proposalId = proposeAtlas() + signed(polis) { ConfederationManager.proposeAcceptance(it.db, it.room, it.publicKey, proposalId).id } + + val lines = ekklesia.devices[2].db.chatMessageDao().getChatMessagesByChatRoomId(ekklesia.roomId) + .map { it.chatMessage.messageType } + .filter { it in ChatMessage.CONFEDERATION_TYPES } + // Agora's proposal, Agora's own acceptance signed with it, and Polis's acceptance. + assertEquals( + listOf(ChatMessage.TYPE_CONFEDERATION_PROPOSED, ChatMessage.TYPE_CONFEDERATION_ACCEPTED, ChatMessage.TYPE_CONFEDERATION_ACCEPTED).sorted(), + lines.sorted(), + ) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt index 2b748eea..ce9af1a5 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationStorageJvmTest.kt @@ -154,4 +154,17 @@ class ConfederationStorageJvmTest { ConfederationManager.record(db, proposal) assertEquals(emptyList(), lines(npub(4))) } + + @Test + fun `an answer filed before its proposal gets its line when the proposal comes`() = runBlocking { + room(npub(2)) + ConfederationManager.record(db, ConfederationTestGroups.acceptance(agora, proposal, admins)) + assertEquals(emptyList(), lines(npub(2))) + + ConfederationManager.record(db, proposal) + assertEquals( + listOf(ChatMessage.TYPE_CONFEDERATION_PROPOSED, ChatMessage.TYPE_CONFEDERATION_ACCEPTED), + lines(npub(2)).map { it.messageType }, + ) + } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt index 4e764e12..c10f8055 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/ConfederationScreensJvmTest.kt @@ -6,7 +6,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.test.ComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.runDesktopComposeUiTest import kotlin.test.Test @@ -19,6 +21,7 @@ import mobi.giza.compose.repository.ConfederationRepository import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.state.ConfederationProposalUIState import mobi.giza.compose.ui.view.state.ConfederationsUIState import mobi.giza.compose.ui.view.state.ProposeConfederationUIState import mobi.giza.compose.ui.view.state.ProposeConfederationUIState.GroupLookup @@ -143,4 +146,63 @@ class ConfederationScreensJvmTest { } assertions() } + + private fun status(answers: List = emptyList()) = ConfederationStatus.of( + ConfederationProposalEvent.Proposal( + id = "p".padEnd(64, '0'), proposingGroup = polis, createdAt = 1, coordinator = polis, + groups = listOf(ConfederationProposalEvent.Invitee(polis), ConfederationProposalEvent.Invitee(roomId)), + threshold = 2, name = "Atlas", nonce = "0".repeat(64), expiresAt = 4_000_000_000, + ), + answers, now = 2, + ) + + @Test + fun `an invited group is offered both answers, and told what accepting discloses`() = renderProposal( + ConfederationProposalUIState.Loaded(localChatRoom = localChatRoom, status = status(), names = mapOf(polis to "Polis", roomId to "This group"), canSign = true) + ) { + onNodeWithText("Atlas").assertIsDisplayed() + onNodeWithText("Coordinated by Polis").assertIsDisplayed() + onNodeWithText("Accepting discloses this group's admins", substring = true).assertIsDisplayed() + onNodeWithText("Propose accepting").assertIsDisplayed() + onNodeWithText("Propose declining").assertIsDisplayed() + } + + @Test + fun `while an answer is being signed, the buttons give way to it`() = renderProposal( + ConfederationProposalUIState.Loaded(localChatRoom = localChatRoom, status = status(), pendingSessionId = "s".repeat(64), canSign = true) + ) { + onNodeWithText("Waiting for the group to sign its answer").assertIsDisplayed() + onAllNodesWithText("Propose accepting").assertCountEquals(0) + } + + @Test + fun `a member without a share reads it and is offered nothing`() = renderProposal( + ConfederationProposalUIState.Loaded(localChatRoom = localChatRoom, status = status(), canSign = false) + ) { + onNodeWithText("Atlas").assertIsDisplayed() + onAllNodesWithText("Propose accepting").assertCountEquals(0) + } + + private fun renderProposal(state: ConfederationProposalUIState, assertions: ComposeUiTest.() -> Unit) = + runDesktopComposeUiTest(width = 400, height = 3000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + ConfederationProposalScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = roomId, + proposalId = "p".padEnd(64, '0'), + initialConfederationProposalUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + confederationRepository = ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY, + onNavigateToRoute = {}, + onNavigateBack = {}, + ) + } + } + } + } + assertions() + } } diff --git a/docs/confederation.md b/docs/confederation.md index c443519e..4b6e7997 100644 --- a/docs/confederation.md +++ b/docs/confederation.md @@ -49,6 +49,7 @@ wait on upstream (see the next section). | 4 | done, before 3, because the refusals need somewhere to keep the seal and the reason past arrival. Schema 43: `ConfederationEvent` (every kind in one table, keyed by event id, indexed by the proposal it is about), `ConfederationInvitee` (which proposals name a group) and `ConfederationSigning` (per signing session: the seal secret, the carried proposal, the refusal). No `ConfederationGroup` cache: D2's lookups land in the existing `Profile` rows. `ConfederationManager.record` verifies the author's signature and files; `status` computes D8 from the rows. The repository waits for Phase 6, its first caller. `ConfederationStorageJvmTest` 5/5 | | 5 | done. `ExperimentalFeatures.confederation`, on in development builds. `LiveSubscriptionManager` holds `live-confederation` on the publish set while it is on: every confederation kind `#p`-tagged to one of our Marmot rooms, and every answer `#e`-tagged to a proposal not yet expired, re-sent when either changes. What arrives goes to `ConfederationRepository.record`, never `saveNostrEvent`. `FrostSigningManager.complete` calls `ConfederationManager.onSigned`, which files the signed events on every device and, on the coordinator's, marks them owed (`ConfederationEvent.ownSessionId`, `publishedAt`, folded into schema 43 since it has not shipped). `ConfederationPublisher`, run by `SynchronizationViewModel`, sends owed events to the publish set and the proposal's hints and backs off from a minute to half an hour until a relay takes each. `BROADCASTABLE_KINDS` gains 9430–9433. `ChatMessage.applyInnerEvent` draws nothing for these kinds rather than a raw-JSON bubble. `ConfederationRelayTest` 6/6, `ConfederationStorageJvmTest` 7/7 | | 6 | done. Four system lines (`TYPE_CONFEDERATION_PROPOSED`, `…_ACCEPTED`, `…_REJECTED`, `…_WITHDRAWN`) written by `ConfederationManager.record` in every local room the proposal names, once per event because the event row is written once. No line for an expiry: nothing happens at an expiry to write one from. A "Confederations" row on the group's screen while the flag is on, for every member of a Marmot room. `ConfederationsScreen` watches every proposal naming the group. `ProposeConfederationScreen` looks every group up on the relays, this one included, and its button waits on a name, an admin, a share, a group that can take part and every group found. Relay hints are not written yet: the profile lookup does not say which relay answered. Its view model's state is a `MutableStateFlow` updated atomically, because a lookup settling on an IO thread and a group added on the main one lost updates under the full suite. `ConfederationRepository.NO_OP_CONFEDERATION_REPOSITORY` for fakes. `ProposeConfederationViewModelJvmTest` 8/8, `ConfederationScreensJvmTest` 4/4, `ConfederationStorageJvmTest` 9/9. jvmTest 1,591, `m3Audit`, brand and wallet audits clean | +| 7 | done but for the badge. `ConfederationProposalScreen`, opened from each card: the proposal, its coordinator, every group's answer, and for a member with a share either both answers (in an invited group that has not answered) or withdrawal (in the proposing group), giving way to a pending answer's session. The approval screen shows D6's notes: the groups by name, `T`, the coordinator, what an acceptance discloses, and each listed group with no public profile on this device, as a warning. `ConfederationNetworkJvmTest` 3/3 is the plan's three-group run: real FROST signatures per group, relays as copies, every device on every group agreeing on `REJECTED` and then on `ACCEPTED`, and the coordinator opening each group's admins. It found answers filed before their proposal losing their line, since a proposal and its proposer's acceptance share a second and relay order is by id; a proposal now writes the lines for answers already held. **Not done:** invitations do not feed `observeProposalsAwaitingYou`, which is FROST-session shaped; the transcript line is the notice. jvmTest 1,598 | ---