diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 9322683b..67c81bc2 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -20,6 +20,8 @@ an em dash or a comma. The compose resources plugin reports that only as "XML file ... is not valid. Check the file content." --> + Abandoned + All Curare Add a dialect the group can translate into Add artifact to library @@ -38,6 +40,7 @@ Backup confirmation Be sure to keep this nsec safe. Be the first to comment. + Being signed Bio BIP39 seed with the standard BIP84 derivation path. The profile\'s nostr key comes off the same seed, so these 12 words restore both. Block user @@ -151,7 +154,10 @@ Name (eg. Alan Turing) Name (eg. Group Discussions) Name of artifact + Needs you Network relays + No proposal is being signed. + No proposal is waiting on members. No wallet is open on this device, so there is no phrase to show. Not backed up yet New chat @@ -167,9 +173,11 @@ No one selected yet No one to add yet. No projects exists in this group. + No proposal has been abandoned. No translations yet. No versions. Not now + Nothing is waiting for your signature. Nothing was created and no key exists. It is safe to run it again. Open chat Original @@ -225,6 +233,7 @@ Send message Share profile Shared key + Signed Signing key The key this room signs as, and the ceremony it came from. What the group signed @@ -269,6 +278,7 @@ This decides who can change the group later. You can't switch afterwards. This group has no shared key, so it cannot sign them in. This group has not been asked to sign anything yet. + This group has not signed anything yet. This is fixed once the ceremony runs. Changing it later means generating a new key. This is the last thing the ceremony needs from you. This will be shown when people open the chat for more details. @@ -305,6 +315,7 @@ View invites Waiting for you Waiting for your signature + Waiting on members We are looking for your profile on as many relays as possible. Nostr aims to be decentralized by distributing data to multiple nodse. We are searching the internet to find your profile and complete sign in. We couldn't find the local profile. Please try again later. @@ -338,6 +349,7 @@ %1$s event(s) still unreadable%2$s %1$s events, signed together Everyone has to be online at the same time — the ceremony can only finish once all %1$s of you have taken part. + %1$s · %2$s "%1$s" functionality coming soon How should %1$s be run? Invite %1$s diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ChatRoomMessagingScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ChatRoomMessagingScreen.kt index 6572158a..7bd8229c 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ChatRoomMessagingScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ChatRoomMessagingScreen.kt @@ -50,11 +50,13 @@ import to.curare.compose.ui.composable.navigation.routes.ChatRoomDetailRoute import to.curare.compose.ui.composable.navigation.routes.DkgRitualRoute import to.curare.compose.ui.composable.navigation.routes.FrostSigningRoute import to.curare.compose.ui.composable.navigation.routes.ProposalListRoute +import to.curare.compose.ui.composable.navigation.routes.proposalDestination import to.curare.compose.ui.composable.navigation.routes.Route import to.curare.compose.ui.composable.widgets.LoadingDataIndicator import to.curare.compose.ui.theme.CurareTheme import to.curare.compose.ui.view.model.ChatRoomMessagingViewModel import to.curare.compose.ui.view.state.ChatRoomMessagingUIState +import to.curare.compose.ui.view.state.ProposalFilter import com.vitorpamplona.quartz.nip01Core.core.HexKey import to.curare.compose.ui.composable.widgets.chat.ChatTranscript import to.curare.compose.ui.theme.spacing @@ -185,39 +187,27 @@ fun ChatRoomMessagingScreen( ) }, onOpenSigning = { sessionId -> - // Two reasons to open the queue instead of the one - // proposal. A line written before chat rows named - // their session cannot say which proposal it is - // about, and the room may have several -- the list - // is the honest answer there, showing all of them - // with their own state rather than guessing at one. - // - // The other is that the proposal they tapped is - // not the only one waiting on them, in which case - // it is not the whole of what is being asked and a - // screen showing only it would say it was. onNavigateToRoute.invoke( - if (sessionId == null || - chatMessageListViewModel.hidesOtherDecisions(sessionId) - ) { - ProposalListRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId - ) - } else { - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - } + proposalDestination( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId, + hasOtherDecisionsWaiting = + chatMessageListViewModel::hidesOtherDecisions + ) ) }, + // The notice has just counted the proposals + // waiting on this member and said so. Opening + // the room's whole signing history from it + // would have the reader look for the three it + // named, so the chip is set on the way in. onOpenProposals = { onNavigateToRoute.invoke( ProposalListRoute( activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId + chatRoomId = chatRoomId, + filter = ProposalFilter.NEEDS_YOU ) ) } diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ProposalListScreen.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ProposalListScreen.kt index 9454d315..ae2d738e 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ProposalListScreen.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/ProposalListScreen.kt @@ -1,25 +1,27 @@ package to.curare.compose.ui.composable +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.material.icons.filled.Draw import androidx.compose.material.icons.filled.ErrorOutline +import androidx.compose.material.icons.filled.Groups import androidx.compose.material.icons.filled.HourglassEmpty +import androidx.compose.material.icons.filled.Inbox import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults -import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults @@ -33,10 +35,10 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color -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 kotlin.time.Clock import com.vitorpamplona.quartz.nip01Core.core.HexKey import to.curare.compose.database.model.ChatRoom import to.curare.compose.database.model.FrostSigningSession @@ -50,18 +52,36 @@ import to.curare.compose.ui.composable.navigation.routes.FrostSigningRoute import to.curare.compose.ui.composable.navigation.routes.Route import to.curare.compose.ui.theme.CurareTheme import to.curare.compose.ui.view.model.ProposalListViewModel +import to.curare.compose.ui.view.state.ProposalFilter import to.curare.compose.ui.view.state.ProposalListUIState +import to.curare.compose.ui.view.state.ProposalState import to.curare.compose.ui.theme.spacing import curare.composeapp.generated.resources.Res import org.jetbrains.compose.resources.stringResource +import curare.composeapp.generated.resources.abandoned import curare.composeapp.generated.resources.everything_else +import curare.composeapp.generated.resources.filter_all +import curare.composeapp.generated.resources.filter_and_count +import curare.composeapp.generated.resources.being_signed +import curare.composeapp.generated.resources.needs_you +import curare.composeapp.generated.resources.no_proposal_has_been_abandoned +import curare.composeapp.generated.resources.no_proposal_is_being_signed +import curare.composeapp.generated.resources.no_proposal_is_waiting_on_members +import curare.composeapp.generated.resources.nothing_is_waiting_for_your_signature +import curare.composeapp.generated.resources.signed +import curare.composeapp.generated.resources.this_group_has_not_signed_anything_yet +import curare.composeapp.generated.resources.waiting_on_members import curare.composeapp.generated.resources.proposals import curare.composeapp.generated.resources.review import curare.composeapp.generated.resources.this_group_has_not_been_asked_to_sign import curare.composeapp.generated.resources.waiting_for_you import curare.composeapp.generated.resources.of_them_could_not_be_read import androidx.compose.material3.SnackbarHost +import to.curare.compose.ui.composable.widgets.EmptyState +import to.curare.compose.ui.composable.widgets.ErrorState +import to.curare.compose.ui.composable.widgets.LoadingDataIndicator import to.curare.compose.ui.composable.widgets.LocalSnackbarHostState +import to.curare.compose.ui.composable.widgets.ScreenStateTransition import to.curare.compose.ui.composable.widgets.NavigateBackButton import to.curare.compose.ui.theme.readableContent import to.curare.compose.ui.theme.ConformancePreviews @@ -91,13 +111,15 @@ fun ProposalListScreen( frostSigningRepository: FrostSigningRepository, onNavigateBack: () -> Unit, onNavigateToRoute: (Route) -> Unit, + initialFilter: ProposalFilter = ProposalFilter.ALL, ) { val proposalListViewModel: ProposalListViewModel = viewModel( factory = ProposalListViewModel.factory( chatRoomId = chatRoomId, initialProposalListUIState = initialProposalListUIState, chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository + frostSigningRepository = frostSigningRepository, + initialFilter = initialFilter ) ) @@ -122,84 +144,55 @@ fun ProposalListScreen( ) } ) { padding -> - when (val state = proposalListViewModel.proposalListUIState) { - is ProposalListUIState.Loading -> Column( - modifier = Modifier.fillMaxWidth().padding(padding).readableContent().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - CircularProgressIndicator() - } + ScreenStateTransition(proposalListViewModel.proposalListUIState) { uiState -> + when (val state = uiState) { + is ProposalListUIState.Loading -> LoadingDataIndicator( + modifier = Modifier.fillMaxSize().padding(padding).readableContent() + ) - is ProposalListUIState.Error -> Column( - modifier = Modifier.fillMaxWidth().padding(padding).readableContent().padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.space600)) - Text(text = state.message, textAlign = TextAlign.Center) - } + is ProposalListUIState.Error -> ErrorState( + message = state.message, + // Nothing to retry: the room either exists on this device or + // it does not, and looking again will not change that. + onRetry = null, + modifier = Modifier.fillMaxSize().padding(padding).readableContent() + ) - is ProposalListUIState.Loaded -> { - val open: (ProposalListUIState.Proposal) -> Unit = { proposal -> - onNavigateToRoute.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = proposal.session.id + is ProposalListUIState.Loaded -> { + val open: (ProposalListUIState.Proposal) -> Unit = { proposal -> + onNavigateToRoute.invoke( + FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = proposal.session.id + ) ) - ) - } - - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.space250), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (state.proposals.isEmpty()) { - item { - Text( - modifier = Modifier.fillMaxWidth().padding(top = MaterialTheme.spacing.space600), - text = stringResource(Res.string.this_group_has_not_been_asked_to_sign), - textAlign = TextAlign.Center - ) - } } - if (state.waitingForYou.isNotEmpty()) { - item { - Text( - text = stringResource(Res.string.waiting_for_you), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.primary + Column( + modifier = Modifier.fillMaxSize().padding(padding).readableContent() + ) { + // Outside the list rather than its first item, because a + // control that scrolls away is a control the reader has to + // scroll back for -- and the list it filters is as long as + // the group's whole signing history. + // + // A room with nothing in it has nothing to filter, and five + // chips reading 0 over an empty screen would be five ways of + // saying what the empty state says once. + if (state.proposals.isNotEmpty()) { + ProposalFilterRow( + selected = state.filter, + counts = state.counts, + onSelect = proposalListViewModel::select ) } - items( - items = state.waitingForYou, - key = { it.session.id } - ) { proposal -> - ProposalCard(proposal = proposal, onClick = { open(proposal) }) - } - } - - if (state.rest.isNotEmpty()) { - // Headed only when there is a section above to tell it - // apart from; on its own it is the whole screen, which - // the title already says. - if (state.waitingForYou.isNotEmpty()) { - item { - Text( - text = stringResource(Res.string.everything_else), - style = MaterialTheme.typography.labelMedium - ) - } - } - - items( - items = state.rest, - key = { it.session.id } - ) { proposal -> - ProposalCard(proposal = proposal, onClick = { open(proposal) }) - } + ProposalList( + state = state, + onOpen = open, + modifier = Modifier.weight(1f) + ) } } } @@ -207,6 +200,167 @@ fun ProposalListScreen( } } +/** + * The rows the current filter asks for. + * + * Two layouts behind one list, and which one is drawn is the filter's doing. + * Unfiltered, the sections stay: what is waiting on the reader is a different + * kind of thing to read from what the group has done, and burying the first in + * the second is what this screen was written to stop. Filtered, the sections go + * -- "waiting for you" against "everything else" is a distinction the reader has + * already made by tapping a chip, and heading a single-state list with it would + * be answering a question nobody asked. + */ +@Composable +private fun ProposalList( + state: ProposalListUIState.Loaded, + onOpen: (ProposalListUIState.Proposal) -> Unit, + modifier: Modifier = Modifier, +) { + // Said rather than defaulted, because five different absences used to say one + // thing here. A filter with nothing in it is not the same fact as a group that + // has never been asked to sign, and the queue running dry is not an absence at + // all -- it is the reader having finished. + if (state.visible.isEmpty()) { + EmptyState( + message = when (state.filter) { + ProposalFilter.ALL -> stringResource(Res.string.this_group_has_not_been_asked_to_sign) + ProposalFilter.NEEDS_YOU -> stringResource(Res.string.nothing_is_waiting_for_your_signature) + ProposalFilter.WAITING_ON_MEMBERS -> + stringResource(Res.string.no_proposal_is_waiting_on_members) + ProposalFilter.BEING_SIGNED -> stringResource(Res.string.no_proposal_is_being_signed) + ProposalFilter.SIGNED -> stringResource(Res.string.this_group_has_not_signed_anything_yet) + ProposalFilter.ABANDONED -> stringResource(Res.string.no_proposal_has_been_abandoned) + }, + icon = when (state.filter) { + // The queue emptying is the end of the work, not a blank screen, + // so it keeps the icon the rows it replaced were carrying. + ProposalFilter.NEEDS_YOU -> Icons.Default.Draw + else -> Icons.Default.Inbox + }, + modifier = modifier.fillMaxSize() + ) + + return + } + + LazyColumn( + modifier = modifier.fillMaxSize().padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + if (state.filter != ProposalFilter.ALL) { + items(items = state.visible, key = { it.session.id }) { proposal -> + ProposalCard(proposal = proposal, onClick = { onOpen(proposal) }) + } + + return@LazyColumn + } + + if (state.waitingForYou.isNotEmpty()) { + item { + Text( + text = stringResource(Res.string.waiting_for_you), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary + ) + } + + items( + items = state.waitingForYou, + key = { it.session.id } + ) { proposal -> + ProposalCard(proposal = proposal, onClick = { onOpen(proposal) }) + } + } + + if (state.rest.isNotEmpty()) { + // Headed only when there is a section above to tell it + // apart from; on its own it is the whole screen, which + // the title already says. + if (state.waitingForYou.isNotEmpty()) { + item { + Text( + text = stringResource(Res.string.everything_else), + style = MaterialTheme.typography.labelMedium + ) + } + } + + items( + items = state.rest, + key = { it.session.id } + ) { proposal -> + ProposalCard(proposal = proposal, onClick = { onOpen(proposal) }) + } + } + } +} + +/** + * One chip per state, and one for all of them. + * + * Scrolls sideways rather than wrapping. Five chips carrying counts will not fit + * 360dp at the largest text size the reader can ask for, and a row that reflows + * to a second line moves the list under the thumb that was about to tap it. The + * first chip is [ProposalFilter.NEEDS_YOU]'s neighbour on purpose: the reason to + * arrive here with a filter in mind is almost always that one. + * + * Every chip is present even at zero, which is the same reasoning from the other + * side -- chips that come and go as sessions advance move the row, and sessions + * advance while this screen is open. + */ +@Composable +private fun ProposalFilterRow( + selected: ProposalFilter, + counts: Map, + onSelect: (ProposalFilter) -> Unit, +) { + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()) + .padding( + horizontal = MaterialTheme.spacing.containerPadding, + vertical = MaterialTheme.spacing.compactPadding + ), + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + for (filter in ProposalFilter.entries) { + val label = labelOf(filter) + + FilterChip( + selected = filter == selected, + onClick = { onSelect(filter) }, + label = { + Text( + text = when (val state = filter.state) { + // "All" carries no number: it is every chip's counts + // added up, which the chips beside it already say. + null -> label + else -> stringResource( + Res.string.filter_and_count, + label, + counts[state] ?: 0 + ) + } + ) + } + ) + } + } +} + +/** What a chip calls its state, in sentence case because M3 says so. */ +@Composable +private fun labelOf(filter: ProposalFilter): String = when (filter) { + ProposalFilter.ALL -> stringResource(Res.string.filter_all) + ProposalFilter.NEEDS_YOU -> stringResource(Res.string.needs_you) + ProposalFilter.WAITING_ON_MEMBERS -> stringResource(Res.string.waiting_on_members) + ProposalFilter.BEING_SIGNED -> stringResource(Res.string.being_signed) + ProposalFilter.SIGNED -> stringResource(Res.string.signed) + ProposalFilter.ABANDONED -> stringResource(Res.string.abandoned) +} + /** * One proposal, named after the first thing it signs. * @@ -269,29 +423,34 @@ private fun ProposalCard( ), leadingContent = { Icon( - imageVector = when { - proposal.awaitsYou -> Icons.Default.Draw - proposal.session.stage == FrostSigningStage.COMPLETE -> - Icons.Default.CheckCircle - proposal.session.stage == FrostSigningStage.FAILED -> - Icons.Default.ErrorOutline - else -> Icons.Default.HourglassEmpty + imageVector = when (proposal.state) { + ProposalState.NEEDS_YOU -> Icons.Default.Draw + ProposalState.SIGNED -> Icons.Default.CheckCircle + ProposalState.ABANDONED -> Icons.Default.ErrorOutline + // People against machinery: one is short of members + // willing to sign, the other is the chosen ones + // finishing. The shapes say which without the colour, + // which is the only signal a monochrome display has. + ProposalState.WAITING_ON_MEMBERS -> Icons.Default.Groups + ProposalState.BEING_SIGNED -> Icons.Default.HourglassEmpty }, // Carries the stage on its own, and carries it alone on the // highlighted card where the failure state has no colour to spare. - contentDescription = when { - proposal.awaitsYou -> "Awaiting your signature" - proposal.session.stage == FrostSigningStage.COMPLETE -> "Signed" - proposal.session.stage == FrostSigningStage.FAILED -> "Failed" - else -> "Waiting on others" + contentDescription = when (proposal.state) { + ProposalState.NEEDS_YOU -> "Awaiting your signature" + ProposalState.SIGNED -> "Signed" + ProposalState.ABANDONED -> "Failed" + ProposalState.WAITING_ON_MEMBERS -> "Waiting on members" + ProposalState.BEING_SIGNED -> "Being signed" }, - tint = when { + tint = when (proposal.state) { // `error` is 2.67:1 on the highlighted card, so on that one the // failure is carried by the icon shape and the supporting line // rather than by colour -- which is the more robust signal // anyway, and the only one available to a monochrome display. - proposal.session.stage == FrostSigningStage.FAILED && - !proposal.awaitsYou -> MaterialTheme.colorScheme.error + // A failed session is never NEEDS_YOU, so that card is never + // the highlighted one and the exception no longer needs stating. + ProposalState.ABANDONED -> MaterialTheme.colorScheme.error else -> cardContentColor } ) @@ -370,11 +529,19 @@ private fun ProposalCard( * be: this is one row of a list somebody is scanning, not the page they are * deciding on. What it must never do is call a session finished when it is not, * or waiting when the decision has gone. + * + * Still switches on the stage rather than on `Proposal.state`, and still has to, + * though for less than it used to. What is left collapsed inside a state is who + * the reader was in it: whether they agreed or declined, under + * [ProposalState.WAITING_ON_MEMBERS], and whether they were picked to sign, + * under [ProposalState.BEING_SIGNED]. Those are facts about the reader rather + * than about the proposal, which is why they are a sentence on the row and not a + * chip above it. */ private fun statusOf(proposal: ProposalListUIState.Proposal): String { val session = proposal.session - if (proposal.awaitsYou) return "Needs your review" + if (proposal.state == ProposalState.NEEDS_YOU) return "Needs your review" return when (session.stage) { // Not awaiting the reader and still collecting means they answered, one @@ -443,6 +610,16 @@ private fun ProposalListScreenPreview() { ), awaitsYou = true ), + ProposalListUIState.Proposal( + session = session.copy( + id = "openSessionId", + signApprovedAt = Clock.System.now() + ), + proposerName = "Grace", + signs = listOf( + ProposedEvent.Summary("New chapter", "Genesis 2 · 641 words · 24 chunks") + ) + ), ProposalListUIState.Proposal( session = session.copy( id = "olderSessionId", @@ -452,6 +629,20 @@ private fun ProposalListScreenPreview() { signs = listOf( ProposedEvent.Summary("New translation", "isiZulu · public · CC BY-SA") ) + ), + // One of each state, so the conformance sweep renders every + // icon, every status line and -- from phase 3 -- every chip + // with something behind it, in all six schemes. + ProposalListUIState.Proposal( + session = session.copy( + id = "abandonedSessionId", + stage = FrostSigningStage.FAILED, + failureReason = "The group could not agree in time." + ), + proposerName = "Ada", + signs = listOf( + ProposedEvent.Summary("New chapter", "Genesis 3 · 512 words · 19 chunks") + ) ) ) ), diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt index cf787d52..ed571eb4 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/CurareNavHost.kt @@ -1497,7 +1497,8 @@ fun CurareNavHost( }, onNavigateToRoute = { signingRoute -> navController.navigate(route = signingRoute) - } + }, + initialFilter = route.filter ) } composable { backStackEntry -> diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/routes/ProposalDestination.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/routes/ProposalDestination.kt new file mode 100644 index 00000000..f0118b93 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/routes/ProposalDestination.kt @@ -0,0 +1,53 @@ +package to.curare.compose.ui.composable.navigation.routes + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import to.curare.compose.ui.view.state.ProposalFilter + +/** + * Where tapping a proposal in the transcript goes. + * + * Three answers, and they are three because the tap means three different + * things. Pulled out of the screen so each can be stated once and checked: the + * decision is made from two facts and a null, and a `when` buried in a lambda + * nested nine deep inside a `LazyColumn` is not a thing anybody can hold to it. + * + * @param sessionId the proposal the tapped line names, or null when it predates + * chat rows naming their session at all. + * @param hasOtherDecisionsWaiting whether opening that proposal by itself would + * hide other decisions the room is waiting on this member for -- see + * `ChatMessageListViewModel.hidesOtherDecisions`, which is what the screen + * passes. + */ +fun proposalDestination( + activeUserPublicKey: HexKey, + chatRoomId: String, + sessionId: String?, + hasOtherDecisionsWaiting: (String) -> Boolean, +): Route = when { + // A line too old to say which proposal it is about. The list is the honest + // answer -- every proposal with its own state, rather than a guess at one -- + // and it is the room's list, unfiltered, because a line like this could be + // about anything the group has ever signed. + sessionId == null -> ProposalListRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId + ) + + // Several decisions are waiting and this is one of them. Opening the one they + // tapped would have answering it look like being done, so they get the queue + // -- and the queue is what the filter is for. Showing the room's whole + // history here would be the same mistake in the other direction: it was the + // other decisions, not the history, that the one proposal was held back for. + hasOtherDecisionsWaiting(sessionId) -> ProposalListRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + filter = ProposalFilter.NEEDS_YOU + ) + + // One proposal, named, and nothing else being asked. Open it. + else -> FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId + ) +} diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/routes/ProposalListRoute.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/routes/ProposalListRoute.kt index dcf10aa6..1c6b768b 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/routes/ProposalListRoute.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/composable/navigation/routes/ProposalListRoute.kt @@ -1,6 +1,7 @@ package to.curare.compose.ui.composable.navigation.routes import kotlinx.serialization.Serializable +import to.curare.compose.ui.view.state.ProposalFilter /** * Everything a group has asked its shared key to sign. @@ -12,5 +13,19 @@ import kotlinx.serialization.Serializable @Serializable data class ProposalListRoute( val activeUserPublicKey: String, - val chatRoomId: String + val chatRoomId: String, + + /** + * Which of them to open on, for the callers that already know. + * + * The transcript's notice counts the proposals waiting on this member and + * says so; a tap on it that then showed the room's whole history would have + * the reader find the three it just named for themselves. So the notice asks + * for [ProposalFilter.NEEDS_YOU] and arrives with the chip already set. + * + * [ProposalFilter.ALL] is the honest default, and is what the ways in that + * mean "show me the room" pass -- the group's own Proposals row, and the + * transcript lines that cannot say which proposal they are about. + */ + val filter: ProposalFilter = ProposalFilter.ALL, ): Route() diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/ProposalListViewModel.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/ProposalListViewModel.kt index 0eb7c6c9..5c740e82 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/ProposalListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/model/ProposalListViewModel.kt @@ -19,6 +19,7 @@ import to.curare.compose.managers.FrostSigningManager import to.curare.compose.repository.ChatRepository import to.curare.compose.repository.FrostSigningRepository import to.curare.compose.text.ProposedEvent +import to.curare.compose.ui.view.state.ProposalFilter import to.curare.compose.ui.view.state.ProposalListUIState /** @@ -35,13 +36,37 @@ class ProposalListViewModel( initialProposalListUIState: ProposalListUIState, val chatRepository: ChatRepository, val frostSigningRepository: FrostSigningRepository, + initialFilter: ProposalFilter = ProposalFilter.ALL, ): ViewModel() { var proposalListUIState: ProposalListUIState by mutableStateOf(initialProposalListUIState) private set + /** + * Which proposals the reader asked for, kept here rather than only on the + * state it is drawn from. + * + * This is the load-bearing part. [initiate] rebuilds a whole + * [ProposalListUIState.Loaded] on every emission, and the flow emits + * whenever any member's message advances any session in the room -- which is + * precisely when somebody is sitting on this screen watching. A `Loaded` + * built with the field's default would snap the chips back to + * [ProposalFilter.ALL] mid-scroll, and would do it most often in the busiest + * rooms. So the selection outlives the state it appears on, and every + * emission reads it. + */ + private var filter: ProposalFilter = initialFilter + private val logger = Logger.withTag(TAG) + init { + // A `Loaded` handed straight in -- a preview, a screen test -- carries a + // filter of its own, and [initialFilter] is the caller's. The caller's + // wins, so no screen can open with its chips saying one thing and its + // rows showing another. + select(initialFilter) + } + /** * Loads the room, then watches its proposals for as long as the screen lives. * @@ -62,12 +87,31 @@ class ProposalListViewModel( proposalListUIState = ProposalListUIState.Loaded( localChatRoom = localChatRoom, - proposals = sessions.map { asProposal(it) } + proposals = sessions.map { asProposal(it) }, + filter = filter ) } } } + /** + * Shows only the proposals in one state, or all of them again. + * + * Applied to the state in hand as well as remembered for the next emission, + * so the chips answer the tap rather than waiting for a session somewhere in + * the room to move. A tap arriving while the screen is still loading is not + * lost either -- it is remembered, and [initiate]'s first emission is + * already filtered, which is what a deep link into a filter relies on. + */ + fun select(filter: ProposalFilter) { + this.filter = filter + + val current = proposalListUIState + if (current is ProposalListUIState.Loaded) { + proposalListUIState = current.copy(filter = filter) + } + } + /** * One session as a row. * @@ -100,13 +144,15 @@ class ProposalListViewModel( initialProposalListUIState: ProposalListUIState = ProposalListUIState.Loading, chatRepository: ChatRepository, frostSigningRepository: FrostSigningRepository, + initialFilter: ProposalFilter = ProposalFilter.ALL, ): ViewModelProvider.Factory = viewModelFactory { initializer { ProposalListViewModel( chatRoomId = chatRoomId, initialProposalListUIState = initialProposalListUIState, chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository + frostSigningRepository = frostSigningRepository, + initialFilter = initialFilter ) } } diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/ProposalFilter.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/ProposalFilter.kt new file mode 100644 index 00000000..03f61d4e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/ProposalFilter.kt @@ -0,0 +1,28 @@ +package to.curare.compose.ui.view.state + +/** + * Which proposals the reader has asked to see. + * + * A flat enum rather than `All` plus a [ProposalState], because every filter + * this screen has is a state and the wrapper would be a type to unwrap at every + * call site for no fact it could hold. [state] is null on [ALL] and that is the + * whole of the difference. + * + * Offered in this order, which is [ProposalState]'s order behind [ALL]: most + * asked of the reader first, because the reason to come here with a filter in + * mind is almost always [NEEDS_YOU]. + */ +enum class ProposalFilter(val state: ProposalState?) { + ALL(null), + NEEDS_YOU(ProposalState.NEEDS_YOU), + WAITING_ON_MEMBERS(ProposalState.WAITING_ON_MEMBERS), + BEING_SIGNED(ProposalState.BEING_SIGNED), + SIGNED(ProposalState.SIGNED), + ABANDONED(ProposalState.ABANDONED), + ; + + companion object { + /** The filter showing exactly one state, for deep links and tests. */ + fun of(state: ProposalState): ProposalFilter = entries.first { it.state == state } + } +} diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/ProposalListUIState.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/ProposalListUIState.kt index 18af4659..95a13d8c 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/ProposalListUIState.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/ProposalListUIState.kt @@ -2,6 +2,7 @@ package to.curare.compose.ui.view.state import to.curare.compose.database.model.FrostSigningSession import to.curare.compose.database.model.intermdiate.LocalChatRoom +import to.curare.compose.database.model.types.FrostSigningStage import to.curare.compose.text.ProposedEvent sealed interface ProposalListUIState { @@ -10,6 +11,16 @@ sealed interface ProposalListUIState { /** Every proposal the room has made, newest first. */ val proposals: List = emptyList(), + + /** + * Which of them the reader has asked to see. + * + * Held on the state and not only on the view model, because the chips + * have to draw the current selection and the counts beside it in the + * same pass that draws the rows it selected -- a selection the row list + * disagreed with would be a chip marked for a filter that is not applied. + */ + val filter: ProposalFilter = ProposalFilter.ALL, ): ProposalListUIState { /** * The ones that cannot move until this member answers them. @@ -21,9 +32,35 @@ sealed interface ProposalListUIState { * the second one under the first one's history is the whole reason this * screen exists. */ - val waitingForYou: List = proposals.filter { it.awaitsYou } + val waitingForYou: List = proposals.filter { it.state == ProposalState.NEEDS_YOU } - val rest: List = proposals.filterNot { it.awaitsYou } + val rest: List = proposals.filterNot { it.state == ProposalState.NEEDS_YOU } + + /** + * The rows [filter] actually asks for. + * + * [proposals] is left whole beside it, because the counts on the chips + * are counts of the room and not of the selection -- a chip that read + * its own number off the filtered list would say 0 for every filter but + * the chosen one. + */ + val visible: List = when (val only = filter.state) { + null -> proposals + else -> proposals.filter { it.state == only } + } + + /** + * How many proposals are in each state, for the number on each chip. + * + * Every state is present, zero included: a room that has never + * abandoned a proposal still gets an "abandoned" chip reading 0, because + * a chip row that gains and loses chips as sessions advance moves under + * the thumb of the person reading it -- and sessions advance while this + * screen is open, which is the whole reason the screen exists. + */ + val counts: Map = ProposalState.entries.associateWith { state -> + proposals.count { it.state == state } + } } /** @@ -59,6 +96,36 @@ sealed interface ProposalListUIState { ) { /** The batch's size, readable or not. */ val eventCount: Int get() = signs.size + unreadable + + /** + * Where it has got to, in the terms the screen reads it in. + * + * Asked once here rather than at each of the four places that used to + * work it out for themselves -- the section split, the row's icon, that + * icon's description, and the status line. They were four `when` chains + * over the same two facts, and the chips would have been a fifth; the + * way a chip comes to count a proposal the row beneath it describes + * differently is by asking the question again. + * + * [awaitsYou] is tried first and wins, because it is the one state that + * is not a stage: an open session waiting on this member and an open + * session waiting on everybody else are both `COLLECTING_NONCES`. + * + * The inner `when` is exhaustive on purpose, with no `else`. A stage + * added to `FrostSigningStage` later should fail to compile here rather + * than quietly land in whichever arm happened to be last, because what + * the reader is waiting on is the one thing this file cannot guess. + */ + val state: ProposalState get() = when { + awaitsYou -> ProposalState.NEEDS_YOU + + else -> when (session.stage) { + FrostSigningStage.COLLECTING_NONCES -> ProposalState.WAITING_ON_MEMBERS + FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES -> ProposalState.BEING_SIGNED + FrostSigningStage.COMPLETE -> ProposalState.SIGNED + FrostSigningStage.FAILED -> ProposalState.ABANDONED + } + } } data class Error( diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/ProposalState.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/ProposalState.kt new file mode 100644 index 00000000..b1358f3e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/ui/view/state/ProposalState.kt @@ -0,0 +1,60 @@ +package to.curare.compose.ui.view.state + +/** + * Where a proposal has got to, as a reader scanning a list of them cares. + * + * Deliberately not [to.curare.compose.database.model.types.FrostSigningStage], + * although it has come to be the stage plus one. The one is the point: a + * proposal waiting on *this* member is `COLLECTING_NONCES` like every other open + * one, and what sets it apart is `FrostSigningSession.signApprovedAt` and + * `signDeclinedAt` being null. So [NEEDS_YOU] cannot be read off the stage at + * all, and a filter keyed on the enum would be a filter missing its reason to + * exist. + * + * Exhaustive and in lifecycle order, which is the order the chips are offered + * in. + */ +enum class ProposalState { + /** + * Waiting on this member to agree or refuse, and going nowhere until they do. + * + * The same question the signing screen gates its buttons on -- see + * `ProposalListUIState.Proposal.awaitsYou`, which is + * `FrostSigningManager.isAwaitingApproval` and not a second opinion of it. + */ + NEEDS_YOU, + + /** + * Open, answered by this member, and short of members willing to sign it. + * + * The stage where a proposal can still die of indifference. Refusals are + * counted against `FrostSigningSession.declinesThatAbandon`, so one more may + * end it; and a member who is simply offline is indistinguishable from one + * who has not looked. It is also the only stage the coordinator's resend is + * for, which is the practical reason this is not merged with + * [BEING_SIGNED]: these are the proposals somebody may have to do something + * about. + */ + WAITING_ON_MEMBERS, + + /** + * The signer set is fixed, and the chosen signers are producing signatures. + * + * Nothing anybody can be asked here. `signerIds` is written once and never + * revised, so no further refusal is counted against it -- what is left is + * the signers' devices finishing arithmetic they have already committed to. + * Where [WAITING_ON_MEMBERS] asks whether this will happen, this one says it + * is happening. + * + * Whether *this* device was among the chosen is not a state of the proposal + * but a fact about the reader, and the row's status line says it. Splitting + * on it would be splitting every state by who is looking. + */ + BEING_SIGNED, + + /** Aggregated and verified. The group signed it. */ + SIGNED, + + /** Abandoned. `FrostSigningSession.failureReason` says why, when it knows. */ + ABANDONED, +} diff --git a/composeApp/src/commonTest/kotlin/to/curare/compose/ui/composable/navigation/routes/ProposalDestinationTest.kt b/composeApp/src/commonTest/kotlin/to/curare/compose/ui/composable/navigation/routes/ProposalDestinationTest.kt new file mode 100644 index 00000000..489d7a97 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/to/curare/compose/ui/composable/navigation/routes/ProposalDestinationTest.kt @@ -0,0 +1,201 @@ +package to.curare.compose.ui.composable.navigation.routes + +import kotlinx.serialization.descriptors.SerialKind +import kotlinx.serialization.json.Json +import kotlinx.serialization.serializer +import to.curare.compose.ui.view.state.ProposalFilter +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Where a tap on a proposal in the transcript lands, and which list it opens on. + * + * Three answers from two facts and a null, and they used to be a condition + * inside a lambda nine levels down a `LazyColumn`. The decision matters more + * than its depth suggested: one of the three is a member being handed their + * queue instead of the proposal they asked for, which is only right because + * answering the one they tapped and leaving would look exactly like being done. + * + * The filter is the new part. A tap held back *because other decisions are + * waiting* should open on those decisions -- opening on the room's whole signing + * history would be the same mistake in the other direction, since it was the + * other decisions and not the history that the one proposal was withheld for. + * An unnamed line gets the room, because it could be about anything. + */ +class ProposalDestinationTest { + private val me = "a".repeat(64) + private val roomId = "d4c3b2a1".repeat(8) + + private fun destination( + sessionId: String?, + waiting: Set = emptySet(), + ) = proposalDestination( + activeUserPublicKey = me, + chatRoomId = roomId, + sessionId = sessionId, + hasOtherDecisionsWaiting = { it in waiting }, + ) + + @Test + fun `a line too old to name its proposal opens the room, unfiltered`() { + assertEquals( + ProposalListRoute(activeUserPublicKey = me, chatRoomId = roomId), + destination(sessionId = null) + ) + assertEquals( + ProposalFilter.ALL, + (destination(sessionId = null) as ProposalListRoute).filter + ) + } + + /** Even when the room is busy: an unnamed line is not a claim about the queue. */ + @Test + fun `an unnamed line opens the room even with decisions waiting`() { + assertEquals( + ProposalListRoute(activeUserPublicKey = me, chatRoomId = roomId), + destination(sessionId = null, waiting = setOf("one", "two")) + ) + } + + @Test + fun `one named proposal and nothing else being asked opens that proposal`() { + assertEquals( + FrostSigningRoute( + activeUserPublicKey = me, + chatRoomId = roomId, + sessionId = "one" + ), + destination(sessionId = "one") + ) + } + + @Test + fun `a proposal held back for the others opens on the queue, not the history`() { + val route = destination(sessionId = "one", waiting = setOf("one")) + + assertEquals( + ProposalListRoute( + activeUserPublicKey = me, + chatRoomId = roomId, + filter = ProposalFilter.NEEDS_YOU + ), + route + ) + } + + /** + * The decision is asked of the session that was tapped, and of no other. + * + * `hidesOtherDecisions` only answers true for a proposal that is itself + * waiting on this member -- a line about something already signed is + * history, and a reader who taps one is asking to see that rather than to be + * handed the queue. Passing the wrong id here would quietly invert that. + */ + @Test + fun `the queue is offered only for the proposal that was tapped`() { + assertEquals( + FrostSigningRoute( + activeUserPublicKey = me, + chatRoomId = roomId, + sessionId = "settled" + ), + destination(sessionId = "settled", waiting = setOf("one", "two")) + ) + } + + @Test + fun `the route carries the room and the reader through every branch`() { + for (route in listOf( + destination(sessionId = null), + destination(sessionId = "one", waiting = setOf("one")), + destination(sessionId = "one"), + )) { + when (route) { + is ProposalListRoute -> { + assertEquals(me, route.activeUserPublicKey) + assertEquals(roomId, route.chatRoomId) + } + + is FrostSigningRoute -> { + assertEquals(me, route.activeUserPublicKey) + assertEquals(roomId, route.chatRoomId) + } + + else -> error("unexpected destination $route") + } + } + } + + // --- the filter as a navigation argument ----------------------------------------- + + /** + * The filter rides on a type-safe navigation route, which means the route's + * serializer has to describe it. + * + * Navigation derives an argument's `NavType` from the serial descriptor, and + * takes an [SerialKind.ENUM] as a string. The round trip below is what that + * rests on; it fails if the enum is ever replaced by something navigation + * cannot place -- a sealed hierarchy, say -- which is the shape a filter + * carrying more than a state would want. + */ + @Test + fun `the filter survives the route's serializer, which is what navigation reads`() { + val descriptor = serializer().descriptor + val filterIndex = descriptor.getElementIndex("filter") + + assertTrue(filterIndex >= 0, "the route stopped carrying a filter") + assertEquals( + SerialKind.ENUM, + descriptor.getElementDescriptor(filterIndex).kind, + "navigation takes an enum argument as a string; this is no longer an enum" + ) + + for (filter in ProposalFilter.entries) { + val route = ProposalListRoute( + activeUserPublicKey = me, + chatRoomId = roomId, + filter = filter, + ) + + assertEquals(route, Json.decodeFromString(Json.encodeToString(route))) + } + } + + /** + * A route built without one shows the room. + * + * The default is what the group's own Proposals row relies on, and what every + * caller predating the argument reads back as -- which is what they all were. + */ + @Test + fun `a route that names no filter means all of them`() { + assertEquals( + ProposalFilter.ALL, + ProposalListRoute(activeUserPublicKey = me, chatRoomId = roomId).filter + ) + + // And an encoding that omits it, which is what a saved back stack from + // before the argument existed looks like. + val withoutFilter = """{"activeUserPublicKey":"$me","chatRoomId":"$roomId"}""" + + assertEquals( + ProposalFilter.ALL, + Json.decodeFromString(withoutFilter).filter + ) + } + + /** Named so a stored route reads as the state it means, not as an ordinal. */ + @Test + fun `the filter is stored by name`() { + val encoded = Json.encodeToString( + ProposalListRoute( + activeUserPublicKey = me, + chatRoomId = roomId, + filter = ProposalFilter.NEEDS_YOU, + ) + ) + + assertTrue(encoded.contains("NEEDS_YOU"), "the filter was not stored by name: $encoded") + } +} diff --git a/composeApp/src/commonTest/kotlin/to/curare/compose/ui/view/state/ProposalFilterTest.kt b/composeApp/src/commonTest/kotlin/to/curare/compose/ui/view/state/ProposalFilterTest.kt new file mode 100644 index 00000000..3d848dca --- /dev/null +++ b/composeApp/src/commonTest/kotlin/to/curare/compose/ui/view/state/ProposalFilterTest.kt @@ -0,0 +1,258 @@ +package to.curare.compose.ui.view.state + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue +import kotlin.time.Clock +import to.curare.compose.database.model.ChatRoom +import to.curare.compose.database.model.FrostSigningSession +import to.curare.compose.database.model.intermdiate.LocalChatRoom +import to.curare.compose.database.model.types.FrostSigningStage + +/** + * What a filter selects, and what the chips count. + * + * The two are deliberately different lists: the rows come from the selection, + * the numbers come from the room. A chip reading its own count off the filtered + * list would say 0 for every filter but the one already chosen, which is the + * one number the reader does not need. + */ +class ProposalFilterTest { + private val roomId = "11".repeat(32) + private val ada = "a".repeat(64) + private val bob = "b".repeat(64) + + private val room = LocalChatRoom( + chatRoom = ChatRoom( + id = roomId, + userPublicKey = bob, + subject = "#Ekklesia", + description = null, + mlsGroupState = null, + ) + ) + + private fun session(id: String, stage: FrostSigningStage = FrostSigningStage.COLLECTING_NONCES) = + FrostSigningSession( + id = id, + chatRoomId = roomId, + coordinatorPublicKey = ada, + userPublicKey = bob, + dkgSessionId = "ceremony", + threshold = 2, + participantCount = 3, + signerId = 2, + stage = stage, + ) + + /** + * `awaitsYou` is passed rather than derived here. + * + * `ProposalStateTest` is where it is held to `isAwaitingApproval`; this file + * is about what the filter does with a classification once it has one, and + * building each state through the manager would make every case here depend + * on the protocol's rules for no extra coverage. + */ + private fun proposal( + id: String, + stage: FrostSigningStage = FrostSigningStage.COLLECTING_NONCES, + awaitsYou: Boolean = false, + ) = ProposalListUIState.Proposal( + session = session(id, stage), + proposerName = "Ada", + awaitsYou = awaitsYou, + ) + + private val needsYou = proposal("needs", awaitsYou = true) + private val alsoNeedsYou = proposal("also", awaitsYou = true) + private val open = proposal("open").copy( + session = session("open").copy(signApprovedAt = Clock.System.now()) + ) + private val beingSigned = proposal( + "signing", + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + ).copy( + session = session("signing", FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES) + .copy(signApprovedAt = Clock.System.now(), signerIds = "1,2") + ) + private val signed = proposal("signed", stage = FrostSigningStage.COMPLETE) + private val abandoned = proposal("abandoned", stage = FrostSigningStage.FAILED) + + private fun loaded(filter: ProposalFilter = ProposalFilter.ALL) = ProposalListUIState.Loaded( + localChatRoom = room, + proposals = listOf(needsYou, alsoNeedsYou, open, beingSigned, signed, abandoned), + filter = filter, + ) + + /** + * The chips run in lifecycle order behind "all", which is the order a reader + * scans them in and the order the states actually happen in. + * + * Pinned here rather than on the screen: the row scrolls, so a chip past the + * right edge has no measurable position, and the order is a property of the + * enum anyway. + */ + @Test + fun `the chips run in lifecycle order, with all of them first`() { + assertEquals( + listOf( + ProposalFilter.ALL, + ProposalFilter.NEEDS_YOU, + ProposalFilter.WAITING_ON_MEMBERS, + ProposalFilter.BEING_SIGNED, + ProposalFilter.SIGNED, + ProposalFilter.ABANDONED, + ), + ProposalFilter.entries + ) + + // And the states they select are in their own declaration order, so the + // two enums cannot drift into disagreeing about what follows what. + assertEquals( + ProposalState.entries, + ProposalFilter.entries.mapNotNull { it.state } + ) + } + + @Test + fun `every filter but ALL names exactly one state, and ALL names none`() { + assertEquals(null, ProposalFilter.ALL.state) + + assertEquals( + ProposalState.entries.toSet(), + ProposalFilter.entries.mapNotNull { it.state }.toSet(), + "every state should be reachable by a chip" + ) + assertEquals( + ProposalFilter.entries.size - 1, + ProposalFilter.entries.mapNotNull { it.state }.distinct().size, + "no two chips should select the same state" + ) + + for (state in ProposalState.entries) { + assertEquals(state, ProposalFilter.of(state).state) + } + } + + /** + * The two open stages are two chips. + * + * Short of members, a proposal can still die of indifference and the + * coordinator's resend is the lever for it; once the signer set is fixed + * there is nothing to do but wait. One chip over both would file "somebody + * may have to chase this" with "nothing to do". + */ + @Test + fun `an open proposal is filed by whether it is still short of members`() { + assertEquals(ProposalState.WAITING_ON_MEMBERS, open.state) + assertEquals(ProposalState.BEING_SIGNED, beingSigned.state) + + assertEquals( + listOf(ProposalFilter.WAITING_ON_MEMBERS, ProposalFilter.BEING_SIGNED), + ProposalFilter.entries.filter { it.state in setOf(open.state, beingSigned.state) } + ) + } + + @Test + fun `the default shows everything, in the order it arrived`() { + val state = loaded() + + assertEquals(ProposalFilter.ALL, state.filter) + assertEquals(state.proposals, state.visible) + } + + @Test + fun `a filter narrows the rows to its own state`() { + assertEquals(listOf(needsYou, alsoNeedsYou), loaded(ProposalFilter.NEEDS_YOU).visible) + assertEquals(listOf(open), loaded(ProposalFilter.WAITING_ON_MEMBERS).visible) + assertEquals(listOf(beingSigned), loaded(ProposalFilter.BEING_SIGNED).visible) + assertEquals(listOf(signed), loaded(ProposalFilter.SIGNED).visible) + assertEquals(listOf(abandoned), loaded(ProposalFilter.ABANDONED).visible) + } + + @Test + fun `filtering narrows the rows without narrowing the room`() { + val state = loaded(ProposalFilter.SIGNED) + + assertEquals(1, state.visible.size) + assertEquals(6, state.proposals.size) + + // The split is the room's, not the selection's: it is what ALL renders, + // and a filtered screen does not draw it at all. + assertEquals(2, state.waitingForYou.size) + assertEquals(4, state.rest.size) + } + + @Test + fun `the counts are of the room, so they do not move when the filter does`() { + val expected = mapOf( + ProposalState.NEEDS_YOU to 2, + ProposalState.WAITING_ON_MEMBERS to 1, + ProposalState.BEING_SIGNED to 1, + ProposalState.SIGNED to 1, + ProposalState.ABANDONED to 1, + ) + + for (filter in ProposalFilter.entries) { + assertEquals(expected, loaded(filter).counts, "counts changed under $filter") + } + } + + @Test + fun `the counts sum to the room, so no proposal is counted twice or lost`() { + val state = loaded() + + assertEquals(state.proposals.size, state.counts.values.sum()) + + for (each in ProposalState.entries) { + assertEquals( + state.counts[each], + state.proposals.count { it.state == each }, + "$each was miscounted" + ) + } + } + + /** + * A chip is offered for a state the room has none of, reading 0. + * + * Deliberate: the alternative is a chip row that gains and loses chips as + * sessions advance, and sessions advance while this screen is open -- + * someone else signing is exactly when the reader is looking at it. A row + * that reflows under the thumb is worse than an honest zero. + */ + @Test + fun `every state gets a count, including the ones the room has never been in`() { + val quiet = ProposalListUIState.Loaded( + localChatRoom = room, + proposals = listOf(needsYou), + ) + + assertEquals(ProposalState.entries.toSet(), quiet.counts.keys) + assertEquals(0, quiet.counts[ProposalState.ABANDONED]) + assertEquals(1, quiet.counts[ProposalState.NEEDS_YOU]) + } + + @Test + fun `a filter the room has nothing for selects nothing rather than everything`() { + val quiet = ProposalListUIState.Loaded( + localChatRoom = room, + proposals = listOf(needsYou, open), + filter = ProposalFilter.ABANDONED, + ) + + assertTrue(quiet.visible.isEmpty()) + assertEquals(2, quiet.proposals.size, "the room is still there to go back to") + } + + @Test + fun `an empty room has an empty everything, under any filter`() { + for (filter in ProposalFilter.entries) { + val empty = ProposalListUIState.Loaded(localChatRoom = room, filter = filter) + + assertTrue(empty.visible.isEmpty()) + assertEquals(0, empty.counts.values.sum()) + assertEquals(ProposalState.entries.toSet(), empty.counts.keys) + } + } +} diff --git a/composeApp/src/commonTest/kotlin/to/curare/compose/ui/view/state/ProposalStateTest.kt b/composeApp/src/commonTest/kotlin/to/curare/compose/ui/view/state/ProposalStateTest.kt new file mode 100644 index 00000000..2dcb1eb8 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/to/curare/compose/ui/view/state/ProposalStateTest.kt @@ -0,0 +1,277 @@ +package to.curare.compose.ui.view.state + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlin.time.Clock +import to.curare.compose.database.model.ChatRoom +import to.curare.compose.database.model.FrostSigningItem +import to.curare.compose.database.model.FrostSigningSession +import to.curare.compose.database.model.intermdiate.LocalChatRoom +import to.curare.compose.database.model.types.FrostSigningStage +import to.curare.compose.managers.FrostSigningManager + +/** + * How a proposal is classified for the list, and what the classification is + * allowed to disagree with. + * + * The screen asks this question in four places -- the section split, the row's + * icon, that icon's description and its status line -- and the filter chips make + * five. They used to each work it out from the stage and the approval + * timestamps, which is how a chip comes to count a proposal the row beneath it + * describes differently. So the classification is pinned here, before anything + * renders it. + * + * What it must agree with is `FrostSigningManager.isAwaitingApproval`. That is + * what the signing screen gates its two buttons on, so a list calling a + * proposal settled while the screen behind it still offers a decision would be + * hiding a decision rather than filtering one. [awaitsYou] is fed from it here + * exactly as the view model feeds it, rather than being asserted by hand. + */ +class ProposalStateTest { + private val roomId = "11".repeat(32) + private val ada = "a".repeat(64) + private val bob = "b".repeat(64) + + /** A 2-of-3 session as the proposer's second member sees it, before they answer. */ + private fun session( + id: String = "session", + stage: FrostSigningStage = FrostSigningStage.COLLECTING_NONCES, + ) = FrostSigningSession( + id = id, + chatRoomId = roomId, + coordinatorPublicKey = ada, + userPublicKey = bob, + dkgSessionId = "ceremony", + threshold = 2, + participantCount = 3, + signerId = 2, + stage = stage, + ) + + /** The room the proposals belong to. Nothing here reads anything off it. */ + private fun room() = LocalChatRoom( + chatRoom = ChatRoom( + id = roomId, + userPublicKey = bob, + subject = "#Ekklesia", + description = null, + mlsGroupState = null, + ) + ) + + private fun item( + sessionId: String = "session", + itemIndex: Int = 0, + eventId: String = "e".repeat(64), + signature: String? = null, + ) = FrostSigningItem( + sessionId = sessionId, + itemIndex = itemIndex, + eventId = eventId, + unsignedEventJson = """{"id":"$eventId"}""", + nonceRandom = "00".repeat(32), + signature = signature, + ) + + /** + * One proposal, built the way the view model builds it. + * + * [awaitsYou] through the manager rather than passed in, so a change to what + * the signing screen considers answered lands in these expectations too. + */ + private fun proposal( + session: FrostSigningSession, + items: List = listOf(item(sessionId = session.id)), + ) = ProposalListUIState.Proposal( + session = session, + proposerName = "Ada", + awaitsYou = FrostSigningManager.isAwaitingApproval(session, items), + ) + + @Test + fun `an open session nobody has answered needs you`() { + assertEquals(ProposalState.NEEDS_YOU, proposal(session()).state) + } + + @Test + fun `agreeing moves it out of your queue, still short of members`() { + val agreed = session().copy(signApprovedAt = Clock.System.now()) + + assertEquals(ProposalState.WAITING_ON_MEMBERS, proposal(agreed).state) + } + + @Test + fun `refusing moves it out of your queue too, because either answer is an answer`() { + val declined = session().copy(signDeclinedAt = Clock.System.now()) + + assertEquals(ProposalState.WAITING_ON_MEMBERS, proposal(declined).state) + } + + /** + * The two open stages are two states, and this is the pair that carries the + * distinction. + * + * Short of members, the proposal can still die of indifference: refusals are + * counted against `declinesThatAbandon`, and an offline member is + * indistinguishable from one who has not looked. It is also the only stage + * the coordinator's resend is for. Once the signer set is written neither is + * true -- `signerIds` is written once and never revised -- so what is left is + * arithmetic the chosen devices have already committed to. + * + * Collapsing the two would file "somebody may have to chase this" and + * "nothing to do but wait" under one chip. + */ + @Test + fun `fixing the signer set is what moves it from waiting on members to being signed`() { + val answered = session().copy(signApprovedAt = Clock.System.now()) + + assertEquals(ProposalState.WAITING_ON_MEMBERS, proposal(answered).state) + + val fixed = answered.copy( + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + signerIds = "1,2", + ) + + assertEquals(ProposalState.BEING_SIGNED, proposal(fixed).state) + } + + /** + * Whether this device was picked is a fact about the reader, not a state of + * the proposal, so it does not move it between chips. The row's status line + * says which it is -- "you are signing" against "enough members took part + * without you" -- and that is where a fact about the reader belongs. + */ + @Test + fun `being signed does not depend on whether you were picked to sign it`() { + val collecting = session(stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES) + .copy(signApprovedAt = Clock.System.now()) + + val picked = collecting.copy(signerIds = "1,2") + val passedOver = collecting.copy(signerIds = "1,3") + + assertTrue(picked.isSigner(), "the fixture should have this device signing") + assertFalse(passedOver.isSigner(), "the fixture should have this device passed over") + + assertEquals(ProposalState.BEING_SIGNED, proposal(picked).state) + assertEquals(ProposalState.BEING_SIGNED, proposal(passedOver).state) + } + + @Test + fun `a complete session is signed`() { + assertEquals( + ProposalState.SIGNED, + proposal(session(stage = FrostSigningStage.COMPLETE)).state + ) + } + + @Test + fun `a failed session is abandoned`() { + assertEquals( + ProposalState.ABANDONED, + proposal(session(stage = FrostSigningStage.FAILED)).state + ) + } + + /** + * An ended session is never in the reader's queue, whatever they did or did + * not answer. This is the rule that lets the row's failure colour be chosen + * by the classification alone: `error` is 2.67:1 on the highlighted card, and + * the highlighted card is [ProposalState.NEEDS_YOU] -- so the two can never + * meet. + */ + @Test + fun `an ended session never needs you, even unanswered`() { + for (stage in listOf(FrostSigningStage.COMPLETE, FrostSigningStage.FAILED)) { + val ended = proposal(session(stage = stage)) + + assertEquals(false, ended.awaitsYou, "$stage should not await an answer") + assertTrue( + ended.state != ProposalState.NEEDS_YOU, + "$stage should not be in the reader's queue" + ) + } + } + + /** + * The group signed it without needing this member. + * + * `isAwaitingApproval` stops asking once every item carries a signature, + * because `advance` closes the session on its next pass and the only answers + * left to give are a nonce nobody is waiting for or a refusal nobody counts. + * The stage has not caught up yet, so it is still being signed -- which is + * also what the row says: "enough members took part without you". + */ + @Test + fun `a fully signed batch is still being signed until advance closes it`() { + val signed = session(stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES) + val items = listOf(item(signature = "ab".repeat(32))) + + assertEquals(ProposalState.BEING_SIGNED, proposal(signed, items).state) + } + + /** + * A session that exists before its proposal has arrived. + * + * It classifies [ProposalState.NEEDS_YOU] although there is nothing in it to + * read -- the card says "nothing has arrived to sign yet" -- and that is + * deliberate parity rather than an oversight: `isAwaitingApproval` only + * short-circuits on a *non-empty* batch that is fully signed, so the signing + * screen still offers the decision. A filter that classified it any other way + * would hide a row that screen would act on. + */ + @Test + fun `a session with nothing in it yet still needs you, matching the signing screen`() { + val empty = proposal(session(), items = emptyList()) + + assertEquals(0, empty.eventCount) + assertEquals(ProposalState.NEEDS_YOU, empty.state) + } + + /** Every proposal lands in exactly one state, so counting them cannot double. */ + @Test + fun `the split covers every proposal exactly once`() { + val proposals = listOf( + proposal(session(id = "needs")), + proposal(session(id = "open").copy(signApprovedAt = Clock.System.now())), + proposal( + session(id = "signing", stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES) + .copy(signApprovedAt = Clock.System.now(), signerIds = "1,2") + ), + proposal(session(id = "done", stage = FrostSigningStage.COMPLETE)), + proposal(session(id = "gone", stage = FrostSigningStage.FAILED)), + ) + + val loaded = ProposalListUIState.Loaded( + localChatRoom = room(), + proposals = proposals, + ) + + assertEquals(1, loaded.waitingForYou.size) + assertEquals(4, loaded.rest.size) + assertEquals(proposals.size, loaded.waitingForYou.size + loaded.rest.size) + + // One of each, and every state reached: five proposals, five states. + assertEquals(ProposalState.entries.toSet(), proposals.map { it.state }.toSet()) + assertEquals(proposals.size, proposals.map { it.state }.distinct().size) + } + + /** The split is the classification, not a second reading of `awaitsYou`. */ + @Test + fun `the waiting section is exactly the proposals in your queue`() { + val proposals = listOf( + proposal(session(id = "needs")), + proposal(session(id = "also")), + proposal(session(id = "done", stage = FrostSigningStage.COMPLETE)), + ) + + val loaded = ProposalListUIState.Loaded(localChatRoom = room(), proposals = proposals) + + assertEquals( + proposals.filter { it.state == ProposalState.NEEDS_YOU }, + loaded.waitingForYou + ) + assertTrue(loaded.rest.none { it.state == ProposalState.NEEDS_YOU }) + } +} diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ProposalListScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ProposalListScreenJvmTest.kt new file mode 100644 index 00000000..fe2db71e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ProposalListScreenJvmTest.kt @@ -0,0 +1,338 @@ +package to.curare.compose.ui.composable + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.getBoundsInRoot +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.runDesktopComposeUiTest +import to.curare.compose.database.model.FrostSigningSession +import to.curare.compose.database.model.types.FrostSigningStage +import to.curare.compose.repository.ChatRepository +import to.curare.compose.repository.FrostSigningRepository +import to.curare.compose.text.ProposedEvent +import to.curare.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey +import to.curare.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId +import to.curare.compose.ui.composable.navigation.routes.Route +import to.curare.compose.ui.composable.widgets.ProvideSnackbarHost +import to.curare.compose.ui.theme.CurareTheme +import to.curare.compose.ui.view.state.ProposalFilter +import to.curare.compose.ui.view.state.ProposalListUIState +import kotlin.test.Test +import kotlin.test.assertTrue +import kotlin.time.Clock + +/** + * The chip row over the proposal list: what it offers, what it counts, and what + * tapping one does to the rows beneath it. + * + * **Every state is offered, with its own number.** A chip is present at zero + * too, which is the decision worth testing rather than the obvious one: the + * alternative is a row that gains and loses chips as sessions advance, and + * sessions advance while this screen is open -- somebody else signing is exactly + * when a member comes to look at it. + * + * **A filter flattens the screen.** Unfiltered, the two sections stay, because + * what is waiting on the reader reads differently from what the group has done. + * Filtered, the headings go: the reader has already said which they want by + * tapping, and heading a single-state list with "waiting for you" would answer a + * question nobody asked. + * + * **An empty filter says which emptiness it is.** One shared "nothing found" is + * how five different absences here came to say one thing. A group never asked to + * sign and a queue the reader has worked through are not the same fact, and the + * second is not an absence at all. + */ +@OptIn(ExperimentalTestApi::class) +class ProposalListScreenJvmTest { + private val session = FrostSigningSession( + id = "needs", + chatRoomId = chatRoomId, + coordinatorPublicKey = "c".repeat(64), + userPublicKey = activeUserPublicKey, + dkgSessionId = "ceremony", + threshold = 2, + participantCount = 3, + signerId = 2, + ) + + private fun proposal( + id: String, + label: String, + detail: String, + stage: FrostSigningStage = FrostSigningStage.COLLECTING_NONCES, + awaitsYou: Boolean = false, + approved: Boolean = false, + signerIds: String? = null, + ) = ProposalListUIState.Proposal( + session = session.copy( + id = id, + stage = stage, + signerIds = signerIds, + signApprovedAt = Clock.System.now().takeIf { approved }, + ), + proposerName = "Ada", + signs = listOf(ProposedEvent.Summary(label, detail)), + awaitsYou = awaitsYou, + ) + + private val needsYou = proposal("needs", "New chapter", "Genesis 1", awaitsYou = true) + private val alsoNeedsYou = proposal("also", "New chapter", "Genesis 2", awaitsYou = true) + private val open = proposal("open", "New translation", "isiZulu", approved = true) + private val beingSigned = proposal( + "signing", "New chapter", "Genesis 4", + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + approved = true, + signerIds = "1,2", + ) + private val signed = proposal("signed", "New post", "A note", stage = FrostSigningStage.COMPLETE) + + private val mixed = listOf(needsYou, alsoNeedsYou, open, beingSigned, signed) + + /** + * Scrolls a chip into view and returns it. + * + * The row scrolls sideways by design -- five counted chips do not fit the + * sixty characters `readableContent` holds the column to -- so reaching the + * last one is what the reader does as well. + */ + private fun ComposeUiTest.chip(label: String) = + onNodeWithText(label).performScrollTo().assertIsDisplayed() + + @Test + fun `every state is offered with its own count, zero included`() = render(loaded(mixed)) { + // Two in the queue, one short of members, one being signed, one signed -- + // and nothing abandoned, which still gets a chip rather than vanishing. + chip("All") + chip("Needs you · 2") + chip("Waiting on members · 1") + chip("Being signed · 1") + chip("Signed · 1") + chip("Abandoned · 0") + } + + /** + * Order is asserted on the chips the viewport actually lays out. + * + * The row scrolls, and a chip entirely past the right edge reports zero + * bounds rather than an off-screen position -- so the ones beyond the fold + * cannot be measured here and are not what this test is for. That the six + * run in lifecycle order is `ProposalFilterTest`'s to say, where it is a + * property of the enum and no viewport is involved. + */ + @Test + fun `the chips are offered above the rows, in the order the states run`() = + render(loaded(mixed)) { + val laidOut = listOf("All", "Needs you · 2", "Waiting on members · 1") + .map { onNodeWithText(it).assertIsDisplayed().getBoundsInRoot().left } + + assertTrue( + laidOut.zipWithNext().all { (left, right) -> left < right }, + "the chips were drawn out of order: $laidOut" + ) + + val chipBottom = onNodeWithText("All").getBoundsInRoot().bottom + val firstRow = onNodeWithText("Genesis 1").getBoundsInRoot().top + assertTrue(chipBottom <= firstRow, "the chips were drawn over the rows") + } + + @Test + fun `unfiltered, the sections stay and every proposal is drawn`() = render(loaded(mixed)) { + onNodeWithText("Waiting for you").assertIsDisplayed() + onNodeWithText("Everything else").assertIsDisplayed() + + onNodeWithText("Genesis 1").assertIsDisplayed() + onNodeWithText("Genesis 2").assertIsDisplayed() + onNodeWithText("isiZulu").assertIsDisplayed() + onNodeWithText("Genesis 4").assertIsDisplayed() + onNodeWithText("A note").assertIsDisplayed() + } + + /** + * The two open stages are two chips, and they hold different proposals. + * + * Short of members, somebody may have to chase it -- refusals can still end + * it, and the coordinator's resend is for exactly this. Once the signer set + * is fixed there is nothing to do but wait. One chip over both would file + * those together. + */ + @Test + fun `the two open stages are told apart`() = render(loaded(mixed)) { + chip("Waiting on members · 1").performClick() + onNodeWithText("isiZulu").assertIsDisplayed() + onAllNodesWithText("Genesis 4").assertCountEquals(0) + + chip("Being signed · 1").performClick() + onNodeWithText("Genesis 4").assertIsDisplayed() + onAllNodesWithText("isiZulu").assertCountEquals(0) + } + + @Test + fun `tapping a chip narrows the rows to its state`() = render(loaded(mixed)) { + chip("Signed · 1").performClick() + + onNodeWithText("A note").assertIsDisplayed() + onAllNodesWithText("Genesis 1").assertCountEquals(0) + onAllNodesWithText("Genesis 2").assertCountEquals(0) + onAllNodesWithText("isiZulu").assertCountEquals(0) + onAllNodesWithText("Genesis 4").assertCountEquals(0) + } + + @Test + fun `a filtered list drops the section headings`() = render(loaded(mixed)) { + chip("Needs you · 2").performClick() + + onNodeWithText("Genesis 1").assertIsDisplayed() + onNodeWithText("Genesis 2").assertIsDisplayed() + onAllNodesWithText("Waiting for you").assertCountEquals(0) + onAllNodesWithText("Everything else").assertCountEquals(0) + } + + @Test + fun `going back to all restores the sections and the rest of the rows`() = + render(loaded(mixed)) { + chip("Signed · 1").performClick() + onAllNodesWithText("Genesis 1").assertCountEquals(0) + + chip("All").performClick() + + onNodeWithText("Waiting for you").assertIsDisplayed() + onNodeWithText("Genesis 1").assertIsDisplayed() + onNodeWithText("A note").assertIsDisplayed() + } + + /** The counts are the room's, so narrowing the rows must not narrow them. */ + @Test + fun `the counts stay put when the filter moves`() = render(loaded(mixed)) { + chip("Signed · 1").performClick() + + chip("Needs you · 2") + chip("Waiting on members · 1") + chip("Being signed · 1") + chip("Abandoned · 0") + } + + @Test + fun `a filter with nothing in it says which emptiness it is`() = render(loaded(mixed)) { + chip("Abandoned · 0").performClick() + + onNodeWithText("No proposal has been abandoned.").assertIsDisplayed() + // Not the whole-screen message, which would be a different and false claim. + onAllNodesWithText("This group has not been asked to sign anything yet.") + .assertCountEquals(0) + } + + /** + * The queue running dry is the end of the reader's work, not a blank screen, + * and the chips behind it still say where everything went. + */ + @Test + fun `a worked-through queue reads as finished rather than as missing`() = + render(loaded(listOf(open, signed))) { + chip("Needs you · 0").performClick() + + onNodeWithText("Nothing is waiting for your signature.").assertIsDisplayed() + chip("Waiting on members · 1") + chip("Signed · 1") + } + + @Test + fun `each filter has its own words for being empty`() { + render(loaded(listOf(needsYou))) { + chip("Waiting on members · 0").performClick() + onNodeWithText("No proposal is waiting on members.").assertIsDisplayed() + } + + render(loaded(listOf(needsYou))) { + chip("Being signed · 0").performClick() + onNodeWithText("No proposal is being signed.").assertIsDisplayed() + } + + render(loaded(listOf(needsYou))) { + chip("Signed · 0").performClick() + onNodeWithText("This group has not signed anything yet.").assertIsDisplayed() + } + } + + /** + * A room with nothing in it has nothing to filter, and five chips reading 0 + * would be five ways of saying what the empty state says once. + */ + @Test + fun `an untouched room offers no chips at all, only the reason`() = render(loaded(emptyList())) { + onNodeWithText("This group has not been asked to sign anything yet.").assertIsDisplayed() + + onAllNodesWithText("All").assertCountEquals(0) + onAllNodesWithText("Needs you · 0").assertCountEquals(0) + onAllNodesWithText("Abandoned · 0").assertCountEquals(0) + } + + @Test + fun `an initial filter is the one selected when the screen opens`() = + render(loaded(mixed), initialFilter = ProposalFilter.NEEDS_YOU) { + onNodeWithText("Genesis 1").assertIsDisplayed() + onNodeWithText("Genesis 2").assertIsDisplayed() + onAllNodesWithText("A note").assertCountEquals(0) + onAllNodesWithText("Genesis 4").assertCountEquals(0) + onAllNodesWithText("Waiting for you").assertCountEquals(0) + } + + @Test + fun `a pushed screen keeps its way back, chips or no chips`() { + render(loaded(mixed)) { onNodeWithContentDescription("Back").assertIsDisplayed() } + render(loaded(emptyList())) { onNodeWithContentDescription("Back").assertIsDisplayed() } + } + + @Test + fun `the room that could not be found says so, with nothing to filter`() { + render(ProposalListUIState.Error("Couldn't find the group")) { + onNodeWithText("Couldn't find the group").assertIsDisplayed() + onAllNodesWithText("All").assertCountEquals(0) + // Nothing to retry, so nothing offering to. + onAllNodesWithText("Try again").assertCountEquals(0) + } + } + + private fun loaded(proposals: List) = + ProposalListUIState.Loaded( + localChatRoom = GroupSignedWorkFixtures.localChatRoom(), + proposals = proposals, + ) + + private fun render( + uiState: ProposalListUIState, + onNavigateToRoute: (Route) -> Unit = {}, + initialFilter: ProposalFilter = ProposalFilter.ALL, + assertions: ComposeUiTest.() -> Unit + ) = runDesktopComposeUiTest(width = 500, height = 1600) { + setContent { + CurareTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + ProposalListScreen( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + initialProposalListUIState = uiState, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + frostSigningRepository = + FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, + onNavigateBack = {}, + onNavigateToRoute = onNavigateToRoute, + initialFilter = initialFilter, + ) + } + } + } + } + + assertions() + } +} diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/ProposalListViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/ProposalListViewModelJvmTest.kt new file mode 100644 index 00000000..ceea09c6 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/view/model/ProposalListViewModelJvmTest.kt @@ -0,0 +1,379 @@ +package to.curare.compose.ui.view.model + +import androidx.lifecycle.viewModelScope +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import to.curare.compose.database.model.ChatRoom +import to.curare.compose.database.model.FrostSigningItem +import to.curare.compose.database.model.FrostSigningSession +import to.curare.compose.database.model.intermdiate.LocalChatRoom +import to.curare.compose.database.model.intermdiate.LocalFrostSigningSession +import to.curare.compose.database.model.types.FrostSigningStage +import to.curare.compose.repository.ChatRepository +import to.curare.compose.repository.FrostSigningRepository +import to.curare.compose.ui.view.state.ProposalFilter +import to.curare.compose.ui.view.state.ProposalListUIState +import to.curare.compose.ui.view.state.ProposalState +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue +import kotlin.test.fail +import kotlin.time.Clock + +/** + * What the proposal list's view model decides that nothing else can check. + * + * One thing above all, and it is the reason this file exists: the selected + * filter has to outlive the state it is drawn on. `observeSessionsForChatRoom` + * re-emits whenever any member's message advances any session in the room, and + * the view model builds a whole new `Loaded` each time. A `Loaded` built with + * the field's default would snap the chips back to "all" -- and would do it + * exactly when somebody else signs, which is exactly when a member is sitting + * on this screen watching. The bug is invisible in a static list and certain in + * a busy room, so it is pinned here rather than left to be noticed. + * + * The rest is the ordinary shape of the screen: the room is looked up once, a + * missing room is an error rather than an empty list, and a tap that lands + * before the first emission is remembered rather than lost. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class ProposalListViewModelJvmTest { + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + private val chatRoomId = "d4c3b2a1".repeat(8) + private val ada = "a".repeat(64) + private val bob = "b".repeat(64) + + private val localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = chatRoomId, + userPublicKey = bob, + subject = "Translation room", + description = null, + initialGiftWrapPayloadId = "sdfaer", + mlsGroupState = "state", + ) + ) + + private fun chatRepository(room: LocalChatRoom? = localChatRoom) = + object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = + room.takeIf { id == chatRoomId } + } + + private fun frostRepository(sessions: Flow>) = + object : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { + override fun observeSessionsForChatRoom( + chatRoomId: String + ): Flow> = sessions + } + + private fun session( + id: String, + stage: FrostSigningStage = FrostSigningStage.COLLECTING_NONCES, + approved: Boolean = false, + signerIds: String? = null, + ) = FrostSigningSession( + id = id, + chatRoomId = chatRoomId, + coordinatorPublicKey = ada, + userPublicKey = bob, + dkgSessionId = "ceremony", + threshold = 2, + participantCount = 3, + signerId = 2, + stage = stage, + signerIds = signerIds, + signApprovedAt = Clock.System.now().takeIf { approved }, + ) + + /** One session with one readable event in it, as the repository hands it over. */ + private fun local( + id: String, + stage: FrostSigningStage = FrostSigningStage.COLLECTING_NONCES, + approved: Boolean = false, + signerIds: String? = null, + ) = LocalFrostSigningSession( + session = session(id, stage, approved, signerIds), + unorderedItems = listOf( + FrostSigningItem( + sessionId = id, + itemIndex = 0, + unsignedEventJson = """ + {"id":"${"e".repeat(64)}","pubkey":"$chatRoomId","created_at":1700000000, + "kind":1,"tags":[],"content":"a chapter","sig":""} + """.trimIndent().replace("\n", ""), + eventId = "e".repeat(64), + nonceRandom = "00".repeat(32), + ) + ), + ) + + /** A room with one of each state in it. */ + private val mixed = listOf( + local("needs"), + local("open", approved = true), + local( + "signing", + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + approved = true, + signerIds = "1,2", + ), + local("signed", stage = FrostSigningStage.COMPLETE), + local("gone", stage = FrostSigningStage.FAILED), + ) + + private fun viewModel( + sessions: Flow>, + room: LocalChatRoom? = localChatRoom, + initialFilter: ProposalFilter = ProposalFilter.ALL, + ) = ProposalListViewModel( + chatRoomId = chatRoomId, + initialProposalListUIState = ProposalListUIState.Loading, + chatRepository = chatRepository(room), + frostSigningRepository = frostRepository(sessions), + initialFilter = initialFilter, + ) + + /** + * Waits for the state to satisfy [predicate], or says what it was waiting for. + * + * `initiate` collects on `Dispatchers.IO`, so the wait is a real one rather + * than a virtual-time one -- the same shape the other view-model tests use. + */ + private suspend fun ProposalListViewModel.await( + what: String, + predicate: (ProposalListUIState) -> Boolean, + ) { + try { + withTimeout(5_000) { + while (!predicate(proposalListUIState)) delay(10) + } + } catch (_: TimeoutCancellationException) { + fail("timed out waiting for $what; the state was $proposalListUIState") + } + } + + private suspend fun ProposalListViewModel.awaitLoaded(): ProposalListUIState.Loaded { + await("the room to load") { it is ProposalListUIState.Loaded } + return loaded() + } + + @Test + fun `the room's proposals arrive classified, unfiltered by default`() = runBlocking { + val flow = MutableSharedFlow>(replay = 1) + flow.emit(mixed) + + val model = viewModel(flow) + model.initiate() + + val loaded = model.awaitLoaded() + + assertEquals(ProposalFilter.ALL, loaded.filter) + assertEquals(5, loaded.visible.size) + assertEquals( + listOf( + ProposalState.NEEDS_YOU, + ProposalState.WAITING_ON_MEMBERS, + ProposalState.BEING_SIGNED, + ProposalState.SIGNED, + ProposalState.ABANDONED, + ), + loaded.proposals.map { it.state } + ) + assertEquals(1, loaded.counts[ProposalState.NEEDS_YOU]) + + model.viewModelScope.cancel() + } + + @Test + fun `selecting a filter narrows the rows at once, without waiting for the room to move`() = + runBlocking { + val flow = MutableSharedFlow>(replay = 1) + flow.emit(mixed) + + val model = viewModel(flow) + model.initiate() + model.awaitLoaded() + + model.select(ProposalFilter.SIGNED) + + val loaded = assertIs(model.proposalListUIState) + assertEquals(ProposalFilter.SIGNED, loaded.filter) + assertEquals(listOf("signed"), loaded.visible.map { it.session.id }) + assertEquals(5, loaded.proposals.size, "the room is still whole behind the filter") + + model.viewModelScope.cancel() + } + + /** + * The one this file is for. + * + * A second emission is what happens when somebody else in the room signs, + * declines or proposes. It must not take the reader's filter with it. + */ + @Test + fun `a session advancing elsewhere in the room does not reset the filter`() = runBlocking { + val flow = MutableSharedFlow>(replay = 1) + flow.emit(mixed) + + val model = viewModel(flow) + model.initiate() + model.awaitLoaded() + + model.select(ProposalFilter.NEEDS_YOU) + assertEquals(listOf("needs"), model.loaded().visible.map { it.session.id }) + + // The coordinator fixes the signer set on the open one, and a fresh + // proposal arrives. The first is a move between two chips, which is the + // emission most likely to arrive while somebody is reading. + flow.emit( + mixed.map { + if (it.session.id == "open") { + local( + "open", + FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + approved = true, + signerIds = "1,2", + ) + } else { + it + } + } + local("fresh") + ) + + model.await("the new proposal") { + it is ProposalListUIState.Loaded && it.proposals.size == 6 + } + + val after = model.loaded() + assertEquals(ProposalFilter.NEEDS_YOU, after.filter, "the filter was reset by an emission") + assertEquals( + listOf("needs", "fresh"), + after.visible.map { it.session.id }, + "the filter was kept but not applied to the new rows" + ) + assertEquals( + 0, + after.counts[ProposalState.WAITING_ON_MEMBERS], + "the counts did not follow the room" + ) + assertEquals(2, after.counts[ProposalState.BEING_SIGNED]) + + model.viewModelScope.cancel() + } + + /** + * Working through the queue empties the filter under the reader, and that is + * the intended end of it: the rows go as they are answered and what is left + * is the empty state saying nothing is waiting. The counts behind it still + * show where everything went. + */ + @Test + fun `answering the last proposal in a filter empties it rather than widening it`() = + runBlocking { + val flow = MutableSharedFlow>(replay = 1) + flow.emit(listOf(local("needs"))) + + val model = viewModel(flow) + model.initiate() + model.awaitLoaded() + + model.select(ProposalFilter.NEEDS_YOU) + assertEquals(1, model.loaded().visible.size) + + flow.emit(listOf(local("needs", approved = true))) + + model.await("the answer to land") { + it is ProposalListUIState.Loaded && + it.counts[ProposalState.NEEDS_YOU] == 0 + } + + val after = model.loaded() + assertEquals(ProposalFilter.NEEDS_YOU, after.filter) + assertTrue(after.visible.isEmpty()) + assertEquals(1, after.proposals.size) + assertEquals(1, after.counts[ProposalState.WAITING_ON_MEMBERS]) + + model.viewModelScope.cancel() + } + + /** + * A filter chosen before the screen has loaded, which is what a deep link + * into the queue is: the first emission is already filtered, so the reader + * never sees the unfiltered list flash past. + */ + @Test + fun `an initial filter applies to the very first emission`() = runBlocking { + val flow = MutableSharedFlow>(replay = 1) + flow.emit(mixed) + + val model = viewModel(flow, initialFilter = ProposalFilter.NEEDS_YOU) + model.initiate() + + val loaded = model.awaitLoaded() + + assertEquals(ProposalFilter.NEEDS_YOU, loaded.filter) + assertEquals(listOf("needs"), loaded.visible.map { it.session.id }) + + model.viewModelScope.cancel() + } + + /** A tap that lands while the room is still being looked up is remembered. */ + @Test + fun `selecting before the first emission is not lost`() = runBlocking { + val flow = MutableSharedFlow>(replay = 1) + + val model = viewModel(flow) + model.initiate() + + model.select(ProposalFilter.ABANDONED) + flow.emit(mixed) + + val loaded = model.awaitLoaded() + + assertEquals(ProposalFilter.ABANDONED, loaded.filter) + assertEquals(listOf("gone"), loaded.visible.map { it.session.id }) + + model.viewModelScope.cancel() + } + + @Test + fun `a room that cannot be found is an error, not an empty list`() = runBlocking { + val flow = MutableSharedFlow>(replay = 1) + flow.emit(mixed) + + val model = viewModel(flow, room = null) + model.initiate() + + model.await("the error") { it is ProposalListUIState.Error } + assertIs(model.proposalListUIState) + + model.viewModelScope.cancel() + } + + private fun ProposalListViewModel.loaded(): ProposalListUIState.Loaded = + assertIs(proposalListUIState) +}