Merge branch 'claude/proposal-state-filters-8cc06c' into curated

A filter on the proposal list, over the four states a proposal can be in from
the reader's side: needs you, in progress, signed, abandoned. "Needs you" is
not a FrostSigningStage -- an open session waiting on this member and one
waiting on everybody else are both COLLECTING_NONCES -- so the classification
is derived once and the four places that used to work it out for themselves
read it.

The transcript's notice opens on the queue rather than the whole history, and
its other entrance turns out to be two that wanted different lists.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5 committed 2026-10-08 13:52:11 -05:00
commit 62d5336bcb
15 files changed
+1834 -123

No files matched your search

@@ -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."
-->
<string name="abandoned">Abandoned</string>
<string name="filter_all">All</string>
<string name="app_name">Curare</string>
<string name="add_a_dialect_the_group_can_translate_into">Add a dialect the group can translate into</string>
<string name="add_artifact_to_library">Add artifact to library</string>
@@ -108,6 +110,7 @@
<string name="i_have_saved_my_recovery_phrase_somewhere">I have saved my recovery phrase somewhere safe.</string>
<string name="i_understand_that_if_i_lose_this_phone_and">I understand that if I lose this phone and my recovery phrase, I lose this profile and the funds in its wallet.</string>
<string name="if_you_are_new_to_torch_or_just_want_to">If you are new to Curare or just want to create a fresh profile</string>
<string name="in_progress">In progress</string>
<string name="initial_version_label">Initial version label</string>
<string name="input_npub_or_nip05">Input npub... or nip05</string>
<string name="introduce_yourself">Introduce yourself</string>
@@ -151,6 +154,7 @@
<string name="name_eg_alan_turing">Name (eg. Alan Turing)</string>
<string name="name_eg_group_discussions">Name (eg. Group Discussions)</string>
<string name="name_of_artifact">Name of artifact</string>
<string name="needs_you">Needs you</string>
<string name="network_relays">Network relays</string>
<string name="no_wallet_is_open_on_this_device_so_there">No wallet is open on this device, so there is no phrase to show.</string>
<string name="not_backed_up_yet">Not backed up yet</string>
@@ -167,9 +171,12 @@
<string name="no_one_selected_yet">No one selected yet</string>
<string name="no_one_to_add_yet">No one to add yet.</string>
<string name="no_projects_exists_in_this_group">No projects exists in this group.</string>
<string name="no_proposal_has_been_abandoned">No proposal has been abandoned.</string>
<string name="no_proposal_is_in_progress">No proposal is in progress.</string>
<string name="no_translations_yet">No translations yet.</string>
<string name="no_versions">No versions.</string>
<string name="not_now">Not now</string>
<string name="nothing_is_waiting_for_your_signature">Nothing is waiting for your signature.</string>
<string name="nothing_was_created_and_no_key_exists_it_is">Nothing was created and no key exists. It is safe to run it again.</string>
<string name="open_chat">Open chat</string>
<string name="original">Original</string>
@@ -221,6 +228,7 @@
<string name="send_message">Send message</string>
<string name="share_profile">Share profile</string>
<string name="shared_key">Shared key</string>
<string name="signed">Signed</string>
<string name="signing_key">Signing key</string>
<string name="the_key_this_room_signs_as">The key this room signs as, and the ceremony it came from.</string>
<string name="what_the_group_signed">What the group signed</string>
@@ -265,6 +273,7 @@
<string name="this_decides_who_can_change_the_group_later">This decides who can change the group later. You can't switch afterwards.</string>
<string name="this_group_has_no_shared_key_so_it_cannot">This group has no shared key, so it cannot sign them in.</string>
<string name="this_group_has_not_been_asked_to_sign">This group has not been asked to sign anything yet.</string>
<string name="this_group_has_not_signed_anything_yet">This group has not signed anything yet.</string>
<string name="this_is_fixed_once_the_ceremony_runs">This is fixed once the ceremony runs. Changing it later means generating a new key.</string>
<string name="this_is_the_last_thing_the_ceremony_needs">This is the last thing the ceremony needs from you.</string>
<string name="this_will_be_shown_when_people_open_the_chat">This will be shown when people open the chat for more details.</string>
@@ -334,6 +343,7 @@
<string name="event_s_still_unreadable">%1$s event(s) still unreadable%2$s</string>
<string name="events_signed_together">%1$s events, signed together</string>
<string name="everyone_has_to_be_online_at_the_same_time">Everyone has to be online at the same time — the ceremony can only finish once all %1$s of you have taken part.</string>
<string name="filter_and_count">%1$s · %2$s</string>
<string name="functionality_coming_soon_2">"%1$s" functionality coming soon</string>
<string name="how_should_be_run">How should %1$s be run?</string>
<string name="invite_2">Invite %1$s</string>
@@ -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
)
)
}
@@ -1,25 +1,26 @@
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.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 +34,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 +51,34 @@ 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.in_progress
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_in_progress
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.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 +108,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 +141,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 +197,164 @@ 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.IN_PROGRESS -> stringResource(Res.string.no_proposal_is_in_progress)
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<ProposalState, Int>,
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.IN_PROGRESS -> stringResource(Res.string.in_progress)
ProposalFilter.SIGNED -> stringResource(Res.string.signed)
ProposalFilter.ABANDONED -> stringResource(Res.string.abandoned)
}
/**
* One proposal, named after the first thing it signs.
*
@@ -269,29 +417,28 @@ 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
ProposalState.IN_PROGRESS -> 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.IN_PROGRESS -> "Waiting on others"
},
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 +517,16 @@ 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 has to: the
* three things it says about an open session -- you agreed, you declined, you
* were picked to sign -- are exactly the distinctions [ProposalState.IN_PROGRESS]
* collapses. The classification picks the arm; the stage writes the sentence.
*/
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 +595,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 +614,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")
)
)
)
),
@@ -1497,7 +1497,8 @@ fun CurareNavHost(
},
onNavigateToRoute = { signingRoute ->
navController.navigate(route = signingRoute)
}
},
initialFilter = route.filter
)
}
composable<ArtifactDetailRoute> { backStackEntry ->
@@ -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
)
}
@@ -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()
@@ -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
)
}
}
@@ -0,0 +1,27 @@
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),
IN_PROGRESS(ProposalState.IN_PROGRESS),
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 }
}
}
@@ -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<Proposal> = 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<Proposal> = proposals.filter { it.awaitsYou }
val waitingForYou: List<Proposal> = proposals.filter { it.state == ProposalState.NEEDS_YOU }
val rest: List<Proposal> = proposals.filterNot { it.awaitsYou }
val rest: List<Proposal> = 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<Proposal> = 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, Int> = ProposalState.entries.associateWith { state ->
proposals.count { it.state == state }
}
}
/**
@@ -59,6 +96,37 @@ 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 [ProposalState.IN_PROGRESS], because whether it
* is an ending is the one thing this file cannot guess.
*/
val state: ProposalState get() = when {
awaitsYou -> ProposalState.NEEDS_YOU
else -> when (session.stage) {
FrostSigningStage.COLLECTING_NONCES,
FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES -> ProposalState.IN_PROGRESS
FrostSigningStage.COMPLETE -> ProposalState.SIGNED
FrostSigningStage.FAILED -> ProposalState.ABANDONED
}
}
}
data class Error(
@@ -0,0 +1,43 @@
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].
* The stage is how far the protocol has run; this is what there is to do about
* it, and the two part company on the only state anybody comes to this screen
* looking for: 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 ordered by how much it asks of the reader, 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, and this member has already said their piece -- or was never needed.
*
* Covers more than it looks like: agreed and waiting on others, refused and
* left the others to it, picked to sign, not picked and watching. All of them
* are the same thing to a reader deciding where to look, which is "not here",
* and the row's own status line says which one it is.
*/
IN_PROGRESS,
/** Aggregated and verified. The group signed it. */
SIGNED,
/** Abandoned. `FrostSigningSession.failureReason` says why, when it knows. */
ABANDONED,
}
@@ -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<String> = 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<ProposalListRoute>().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<ProposalListRoute>(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")
}
}
@@ -0,0 +1,200 @@
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 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, signed, abandoned),
filter = filter,
)
@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)
}
}
@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.IN_PROGRESS).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(5, 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(3, 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.IN_PROGRESS 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)
}
}
}
@@ -0,0 +1,237 @@
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.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<FrostSigningItem> = 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 without closing it`() {
val agreed = session().copy(signApprovedAt = Clock.System.now())
assertEquals(ProposalState.IN_PROGRESS, 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.IN_PROGRESS, proposal(declined).state)
}
@Test
fun `a session gathering signatures is in progress whether or not you were picked`() {
val collecting = session(stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES)
.copy(signApprovedAt = Clock.System.now())
assertEquals(ProposalState.IN_PROGRESS, proposal(collecting.copy(signerIds = "1,2")).state)
assertEquals(ProposalState.IN_PROGRESS, proposal(collecting.copy(signerIds = "1,3")).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 this is in progress -- which is also
* what the row says: "enough members took part without you".
*/
@Test
fun `a fully signed batch is in progress until advance closes it`() {
val signed = session(stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES)
val items = listOf(item(signature = "ab".repeat(32)))
assertEquals(ProposalState.IN_PROGRESS, 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 = "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(3, loaded.rest.size)
assertEquals(proposals.size, loaded.waitingForYou.size + loaded.rest.size)
assertEquals(
setOf(
ProposalState.NEEDS_YOU,
ProposalState.IN_PROGRESS,
ProposalState.SIGNED,
ProposalState.ABANDONED,
),
proposals.map { it.state }.toSet()
)
}
/** 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 })
}
}
@@ -0,0 +1,292 @@
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,
) = ProposalListUIState.Proposal(
session = session.copy(
id = id,
stage = stage,
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 signed = proposal("signed", "New post", "A note", stage = FrostSigningStage.COMPLETE)
private val mixed = listOf(needsYou, alsoNeedsYou, open, 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 in progress, one signed -- and nothing abandoned,
// which still gets a chip rather than vanishing.
chip("All")
chip("Needs you · 2")
chip("In progress · 1")
chip("Signed · 1")
chip("Abandoned · 0")
}
@Test
fun `the chips are offered above the rows, in the order the states run`() =
render(loaded(mixed)) {
val chips = listOf("All", "Needs you · 2", "In progress · 1", "Signed · 1", "Abandoned · 0")
.map { onNodeWithText(it).getBoundsInRoot().left }
assertTrue(
chips.zipWithNext().all { (left, right) -> left < right },
"the chips were drawn out of order: $chips"
)
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("A note").assertIsDisplayed()
}
@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)
}
@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("In progress · 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("In progress · 1")
chip("Signed · 1")
}
@Test
fun `each filter has its own words for being empty`() {
render(loaded(listOf(needsYou))) {
chip("In progress · 0").performClick()
onNodeWithText("No proposal is in progress.").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("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.Proposal>) =
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()
}
}
@@ -0,0 +1,352 @@
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<List<LocalFrostSigningSession>>) =
object : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY {
override fun observeSessionsForChatRoom(
chatRoomId: String
): Flow<List<LocalFrostSigningSession>> = sessions
}
private fun session(
id: String,
stage: FrostSigningStage = FrostSigningStage.COLLECTING_NONCES,
approved: Boolean = false,
) = FrostSigningSession(
id = id,
chatRoomId = chatRoomId,
coordinatorPublicKey = ada,
userPublicKey = bob,
dkgSessionId = "ceremony",
threshold = 2,
participantCount = 3,
signerId = 2,
stage = stage,
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,
) = LocalFrostSigningSession(
session = session(id, stage, approved),
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("signed", stage = FrostSigningStage.COMPLETE),
local("gone", stage = FrostSigningStage.FAILED),
)
private fun viewModel(
sessions: Flow<List<LocalFrostSigningSession>>,
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<List<LocalFrostSigningSession>>(replay = 1)
flow.emit(mixed)
val model = viewModel(flow)
model.initiate()
val loaded = model.awaitLoaded()
assertEquals(ProposalFilter.ALL, loaded.filter)
assertEquals(4, loaded.visible.size)
assertEquals(
listOf(
ProposalState.NEEDS_YOU,
ProposalState.IN_PROGRESS,
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<List<LocalFrostSigningSession>>(replay = 1)
flow.emit(mixed)
val model = viewModel(flow)
model.initiate()
model.awaitLoaded()
model.select(ProposalFilter.SIGNED)
val loaded = assertIs<ProposalListUIState.Loaded>(model.proposalListUIState)
assertEquals(ProposalFilter.SIGNED, loaded.filter)
assertEquals(listOf("signed"), loaded.visible.map { it.session.id })
assertEquals(4, 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<List<LocalFrostSigningSession>>(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 })
// Somebody else signs the open one, and a fresh proposal arrives.
flow.emit(
mixed.map { if (it.session.id == "open") local("open", FrostSigningStage.COMPLETE) else it } +
local("fresh")
)
model.await("the new proposal") {
it is ProposalListUIState.Loaded && it.proposals.size == 5
}
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(2, after.counts[ProposalState.SIGNED], "the counts did not follow the room")
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<List<LocalFrostSigningSession>>(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.IN_PROGRESS])
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<List<LocalFrostSigningSession>>(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<List<LocalFrostSigningSession>>(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<List<LocalFrostSigningSession>>(replay = 1)
flow.emit(mixed)
val model = viewModel(flow, room = null)
model.initiate()
model.await("the error") { it is ProposalListUIState.Error }
assertIs<ProposalListUIState.Error>(model.proposalListUIState)
model.viewModelScope.cancel()
}
private fun ProposalListViewModel.loaded(): ProposalListUIState.Loaded =
assertIs<ProposalListUIState.Loaded>(proposalListUIState)
}