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 22f85e47..064a7d26 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 @@ -3,7 +3,10 @@ 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.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding @@ -11,6 +14,7 @@ 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.Campaign import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.ChevronRight import androidx.compose.material.icons.filled.Draw @@ -22,6 +26,7 @@ import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FilterChip +import androidx.compose.material3.TextButton import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults @@ -32,6 +37,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color @@ -59,6 +65,11 @@ 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.everyone_has_signed_this_session +import curare.composeapp.generated.resources.asked_again_to_sign +import curare.composeapp.generated.resources.asked_again_recently +import curare.composeapp.generated.resources.asked_again +import curare.composeapp.generated.resources.ask_again import curare.composeapp.generated.resources.you_declined import curare.composeapp.generated.resources.you_are_signing import curare.composeapp.generated.resources.you_agreed @@ -91,7 +102,9 @@ 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.Decorative import to.curare.compose.ui.composable.widgets.NavigateBackButton +import to.curare.compose.ui.composable.widgets.rememberNotifier import to.curare.compose.ui.theme.readableContent import to.curare.compose.ui.theme.ConformancePreviews @@ -168,6 +181,32 @@ fun ProposalListScreen( ) is ProposalListUIState.Loaded -> { + // Read above the handlers, because `rememberNotifier` and + // `stringResource` are composable and an onClick is not. The + // notifier takes this screen's scope on purpose: a resend is + // often the last thing a coordinator does before leaving. + val notify = rememberNotifier(rememberCoroutineScope()) + val asked = stringResource(Res.string.asked_again) + val askedToSign = stringResource(Res.string.asked_again_to_sign) + val nobodyLeft = stringResource(Res.string.everyone_has_signed_this_session) + + val askAgain: (ProposalListUIState.Proposal) -> Unit = { proposal -> + val signing = proposal.state == ProposalState.BEING_SIGNED + + proposalListViewModel.askAgain(proposal.session.id) { sent -> + notify( + when { + sent && signing -> askedToSign + sent -> asked + // Nothing went out. The row cannot tell a + // cooldown from an empty queue, so it says + // the one the button is only offered under. + else -> nobodyLeft + } + ) + } + } + val open: (ProposalListUIState.Proposal) -> Unit = { proposal -> onNavigateToRoute.invoke( FrostSigningRoute( @@ -200,6 +239,8 @@ fun ProposalListScreen( ProposalList( state = state, onOpen = open, + onAskAgain = askAgain, + isAsking = proposalListViewModel::isAsking, modifier = Modifier.weight(1f) ) } @@ -224,6 +265,8 @@ fun ProposalListScreen( private fun ProposalList( state: ProposalListUIState.Loaded, onOpen: (ProposalListUIState.Proposal) -> Unit, + onAskAgain: (ProposalListUIState.Proposal) -> Unit, + isAsking: (String) -> Boolean, modifier: Modifier = Modifier, ) { // Said rather than defaulted, because five different absences used to say one @@ -259,7 +302,12 @@ private fun ProposalList( ) { if (state.filter != ProposalFilter.ALL) { items(items = state.visible, key = { it.session.id }) { proposal -> - ProposalCard(proposal = proposal, onClick = { onOpen(proposal) }) + ProposalCard( + proposal = proposal, + onClick = { onOpen(proposal) }, + onAskAgain = { onAskAgain(proposal) }, + asking = isAsking(proposal.session.id) + ) } return@LazyColumn @@ -278,7 +326,12 @@ private fun ProposalList( items = state.waitingForYou, key = { it.session.id } ) { proposal -> - ProposalCard(proposal = proposal, onClick = { onOpen(proposal) }) + ProposalCard( + proposal = proposal, + onClick = { onOpen(proposal) }, + onAskAgain = { onAskAgain(proposal) }, + asking = isAsking(proposal.session.id) + ) } } @@ -299,7 +352,12 @@ private fun ProposalList( items = state.rest, key = { it.session.id } ) { proposal -> - ProposalCard(proposal = proposal, onClick = { onOpen(proposal) }) + ProposalCard( + proposal = proposal, + onClick = { onOpen(proposal) }, + onAskAgain = { onAskAgain(proposal) }, + asking = isAsking(proposal.session.id) + ) } } } @@ -381,6 +439,8 @@ private fun labelOf(filter: ProposalFilter): String = when (filter) { private fun ProposalCard( proposal: ProposalListUIState.Proposal, onClick: () -> Unit, + onAskAgain: (() -> Unit)? = null, + asking: Boolean = false, ) { val lead = proposal.signs.firstOrNull() @@ -529,12 +589,64 @@ private fun ProposalCard( style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) + + if (onAskAgain != null && proposal.canAskAgain) { + AskAgainButton( + proposal = proposal, + asking = asking, + onAskAgain = onAskAgain + ) + } } } ) } } +/** + * Asks the members a proposal is still waiting on to take another look. + * + * The same offer the signing screen makes, and deliberately the same words: a + * coordinator who went looking for it there and found it here should not have + * to work out that "re-broadcast" and "ask again" are one button. What the list + * adds is reach -- the one proposal that has stalled is found by filtering to + * it, rather than by opening each in turn. + * + * Disabled rather than hidden while the cooldown runs. A control that vanishes + * after a tap reads as one that failed, and what happened is that it worked. + */ +@Composable +private fun AskAgainButton( + proposal: ProposalListUIState.Proposal, + asking: Boolean, + onAskAgain: () -> Unit, +) { + val waiting = proposal.askAgainAt != null + + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space25)) { + if (waiting) { + Text( + text = stringResource(Res.string.asked_again_recently), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + TextButton( + enabled = !waiting && !asking, + onClick = onAskAgain, + contentPadding = PaddingValues( + horizontal = MaterialTheme.spacing.compactPadding, + vertical = MaterialTheme.spacing.space25, + ) + ) { + Icon(Icons.Default.Campaign, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) + Text(stringResource(Res.string.ask_again)) + } + } +} + /** * Who the reader is in this proposal, in a line. * 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 32e357f5..b794e633 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 @@ -2,6 +2,7 @@ package to.curare.compose.ui.view.model import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.mutableStateSetOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider @@ -17,6 +18,7 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch import to.curare.compose.database.model.intermdiate.FrostSignerTally import to.curare.compose.database.model.intermdiate.LocalFrostSigningSession +import to.curare.compose.database.model.types.FrostSigningStage import to.curare.compose.extensions.shortened import to.curare.compose.managers.FrostSigningManager import to.curare.compose.nostr.frost.FrostSigningEvents @@ -61,6 +63,12 @@ class ProposalListViewModel( */ private var filter: ProposalFilter = initialFilter + /** + * The sessions whose "ask again" is in flight, so a second tap on one row + * does not publish twice while the first is still going out. + */ + private val pending = mutableStateSetOf() + private val logger = Logger.withTag(TAG) init { @@ -135,7 +143,7 @@ class ProposalListViewModel( * worked out here, so the list and the signing screen cannot disagree about * which proposals still have a decision in them. */ - private fun asProposal( + private suspend fun asProposal( local: LocalFrostSigningSession, tallies: List, ): ProposalListUIState.Proposal { @@ -157,10 +165,72 @@ class ProposalListViewModel( unreadable = items.size - events.size, awaitsYou = FrostSigningManager.isAwaitingApproval(local.session, items), noncesOffered = counted(FrostSigningEvents.NONCE), - partialSignatures = counted(FrostSigningEvents.PARTIAL_SIGNATURE) + partialSignatures = counted(FrostSigningEvents.PARTIAL_SIGNATURE), + owing = owingFor(local) ) } + /** + * How many members a session is still waiting on, when asking them again is + * this device's to offer. + * + * A query per row, and the only one on this screen -- so it is asked for as + * few rows as possible. Not ours to send, nothing to send, or already ended: + * all three answer null without touching the database. + * + * An ended session is left out although `FrostSigningManager.resend` would + * take it: a completed one can be re-sent to deliver the signature to a + * member who never applied it, and that is worth a button on the one + * proposal's screen rather than on every row of a list that only grows. The + * signing screen still offers it. + */ + private suspend fun owingFor(local: LocalFrostSigningSession): Int? { + val session = local.session + + if (!session.isCoordinator() || local.items.isEmpty()) return null + + return when (session.stage) { + FrostSigningStage.COLLECTING_NONCES, + FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES -> + frostSigningRepository.membersOwing(session).size + + FrostSigningStage.COMPLETE, FrostSigningStage.FAILED -> null + } + } + + /** + * Asks the members a proposal is still waiting on to take another look. + * + * Guarded per session rather than by one flag for the screen, because the + * rooms this screen is for have several proposals open at once and a + * coordinator working down the list should not be locked out of the second + * by the first still publishing. + * + * [onResult] is told whether anything went out. `resend` answers false for + * a cooldown that has not run out, a session waiting on nobody and a stage + * that cannot be resent, and the row that offered the button has no way to + * know which -- so what it says afterwards comes from here. + */ + fun askAgain(sessionId: String, onResult: (sent: Boolean) -> Unit) { + val state = proposalListUIState as? ProposalListUIState.Loaded ?: return + + if (!pending.add(sessionId)) return + + viewModelScope.launch(Dispatchers.IO) { + val sent = frostSigningRepository.resend( + localChatRoom = state.localChatRoom, + sessionId = sessionId + ) + + pending.remove(sessionId) + + viewModelScope.launch(Dispatchers.Main) { onResult.invoke(sent) } + } + } + + /** Whether an ask for this session is still in flight. */ + fun isAsking(sessionId: String): Boolean = sessionId in pending + companion object { private const val TAG = "ProposalListViewModel" 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 d8be898a..944ec75c 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 @@ -1,8 +1,11 @@ package to.curare.compose.ui.view.state +import kotlin.time.Clock +import kotlin.time.Instant 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 import to.curare.compose.text.ProposedEvent sealed interface ProposalListUIState { @@ -104,6 +107,24 @@ sealed interface ProposalListUIState { */ val noncesOffered: Int = 0, val partialSignatures: Int = 0, + + /** + * How many share holders the session is still waiting on, or null when + * asking them again is not this device's to offer. + * + * Asked of `FrostSigningManager.membersOwing` rather than worked out + * from the counts above, because the two are not the same question and + * the difference is a button that does nothing. Past the nonces a signer + * who refused has answered and is owed nothing, while the signature + * count is still short by one -- so a row reading `have < need` would + * offer to knock on a door that has already been shut. + * + * Null rather than zero for a session this device did not propose: a + * resend from anybody else would have a member who was missing the + * session believe the resender coordinates. Zero means it is ours to + * send and there is nobody left to send it to. + */ + val owing: Int? = null, ) { /** The batch's size, readable or not. */ val eventCount: Int get() = signs.size + unreadable @@ -172,6 +193,30 @@ sealed interface ProposalListUIState { FrostSigningStage.COMPLETE, FrostSigningStage.FAILED -> null } + + /** + * Whether to offer asking the quiet members to take another look. + * + * The same offer the signing screen makes, reached from the row rather + * than from a tap into it -- a coordinator scanning a list for the one + * that has stalled should not have to open each to find the button. It + * is offered only when there is somebody to ask, because a control that + * publishes nothing is worse than no control. + */ + val canAskAgain: Boolean get() = (owing ?: 0) > 0 + + /** + * When the next ask may go out, or null when one may go out now. + * + * Read at composition rather than ticked, exactly as the signing screen + * reads it. The cooldown is five minutes and every message the room + * exchanges recomposes this screen, so a button left disabled a little + * past its time is the worst this costs -- and that is the safe + * direction for a control that publishes. + */ + val askAgainAt: Instant? get() = session.resentAt + ?.plus(FrostSigningManager.RESEND_COOLDOWN) + ?.takeIf { it > Clock.System.now() } } /** diff --git a/composeApp/src/commonTest/kotlin/to/curare/compose/ui/view/state/ProposalAskAgainTest.kt b/composeApp/src/commonTest/kotlin/to/curare/compose/ui/view/state/ProposalAskAgainTest.kt new file mode 100644 index 00000000..64f815c6 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/to/curare/compose/ui/view/state/ProposalAskAgainTest.kt @@ -0,0 +1,132 @@ +package to.curare.compose.ui.view.state + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import to.curare.compose.database.model.FrostSigningSession +import to.curare.compose.database.model.types.FrostSigningStage +import to.curare.compose.managers.FrostSigningManager + +/** + * When a row offers to ask the quiet members again, and when it only looks like + * it could. + * + * The offer is the coordinator's and nobody else's -- `acceptProposal` takes a + * session's coordinator from the author of the proposal that opened it, so a + * resend from anybody else would have a member who was missing the session + * believe the resender coordinates, and then drop the real coordinator's signer + * set. The row expresses that as a null rather than a zero: not ours to send is + * a different fact from nobody left to send to, and only one of them could ever + * become a button. + */ +class ProposalAskAgainTest { + private val roomId = "11".repeat(32) + private val me = "a".repeat(64) + private val somebodyElse = "b".repeat(64) + + private fun session( + coordinator: String = me, + stage: FrostSigningStage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + resentAt: kotlin.time.Instant? = null, + ) = FrostSigningSession( + id = "session", + chatRoomId = roomId, + coordinatorPublicKey = coordinator, + userPublicKey = me, + dkgSessionId = "ceremony", + threshold = 2, + participantCount = 3, + signerId = 1, + stage = stage, + resentAt = resentAt, + ) + + private fun proposal( + session: FrostSigningSession = session(), + owing: Int? = null, + ) = ProposalListUIState.Proposal( + session = session, + proposerName = "You", + owing = owing, + ) + + @Test + fun `a session waiting on somebody offers the ask`() { + assertTrue(proposal(owing = 1).canAskAgain) + assertTrue(proposal(owing = 3).canAskAgain) + } + + @Test + fun `a session waiting on nobody offers nothing, because there is nobody to ask`() { + assertFalse(proposal(owing = 0).canAskAgain) + } + + /** + * Null is what the view model answers for a session this device did not + * propose, and it must not read as "waiting on nobody" turning into a button + * by some later arithmetic. + */ + @Test + fun `a session that is not ours to send offers nothing`() { + assertFalse(proposal(session(coordinator = somebodyElse), owing = null).canAskAgain) + assertNull(proposal(session(coordinator = somebodyElse)).owing) + } + + @Test + fun `a proposal says nothing about the cooldown until one has been sent`() { + assertNull(proposal(owing = 1).askAgainAt) + } + + @Test + fun `an ask sent just now is still cooling down`() { + val justNow = proposal(session(resentAt = Clock.System.now()), owing = 1) + + assertNotNull(justNow.askAgainAt, "the cooldown should still be running") + assertTrue( + justNow.canAskAgain, + "the offer stays and the button goes quiet; a control that vanishes reads as one that failed" + ) + } + + @Test + fun `an ask sent longer ago than the cooldown may go again`() { + val old = Clock.System.now() - FrostSigningManager.RESEND_COOLDOWN - kotlin.time.Duration.parse("1s") + + assertNull(proposal(session(resentAt = old), owing = 1).askAgainAt) + } + + /** The boundary belongs to the manager, so the row reads it rather than guessing. */ + @Test + fun `the cooldown the row honours is the one the manager enforces`() { + val sentAt = Clock.System.now() - FrostSigningManager.RESEND_COOLDOWN / 2 + val halfway = proposal(session(resentAt = sentAt), owing = 1) + + assertEquals( + sentAt + FrostSigningManager.RESEND_COOLDOWN, + halfway.askAgainAt, + "the row's cooldown drifted from the manager's" + ) + } + + /** + * The offer does not depend on the stage here, because the view model has + * already decided which stages it asks about -- see `owingFor`. A row only + * ever receives a count for a session that could be resent. + */ + @Test + fun `a count on any stage the view model asks about becomes an offer`() { + for (stage in listOf( + FrostSigningStage.COLLECTING_NONCES, + FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + )) { + assertTrue( + proposal(session(stage = stage), owing = 1).canAskAgain, + "$stage should be askable" + ) + } + } +} 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 index 2c9ff1a3..73da8771 100644 --- a/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ProposalListScreenJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/ui/composable/ProposalListScreenJvmTest.kt @@ -7,6 +7,8 @@ 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.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.getBoundsInRoot import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithContentDescription @@ -17,6 +19,7 @@ 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.database.model.intermdiate.LocalChatRoom import to.curare.compose.repository.FrostSigningRepository import to.curare.compose.text.ProposedEvent import to.curare.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey @@ -27,6 +30,8 @@ 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.assertEquals +import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock @@ -74,11 +79,14 @@ class ProposalListScreenJvmTest { signerIds: String? = null, nonces: Int = 0, signatures: Int = 0, + owing: Int? = null, + resentAt: kotlin.time.Instant? = null, ) = ProposalListUIState.Proposal( session = session.copy( id = id, stage = stage, signerIds = signerIds, + resentAt = resentAt, signApprovedAt = Clock.System.now().takeIf { approved }, ), proposerName = "Ada", @@ -86,6 +94,7 @@ class ProposalListScreenJvmTest { awaitsYou = awaitsYou, noncesOffered = nonces, partialSignatures = signatures, + owing = owing, ) private val needsYou = proposal("needs", "New chapter", "Genesis 1", awaitsYou = true) @@ -362,6 +371,144 @@ class ProposalListScreenJvmTest { onAllNodesWithText("Waiting on the rest", substring = true).assertCountEquals(0) } + // --- asking the quiet members again --------------------------------------------- + + /** + * The button a coordinator came to the list for. + * + * It says what the signing screen's says, deliberately: somebody who found + * it there and then found this should not have to work out that two labels + * are one button. What the list adds is that filtering to "being signed" + * puts every stalled proposal in front of them at once, rather than one tap + * into each. + */ + @Test + fun `a stalled proposal we coordinate offers the ask, on the being signed chip`() { + val stalled = proposal( + "signing", "New chapter", "Genesis 4", + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + approved = true, signerIds = "1,2", signatures = 1, owing = 1, + ) + + render(loaded(listOf(stalled, signed))) { + chip("Being signed ยท 1").performClick() + + onNodeWithText("Genesis 4").assertIsDisplayed() + onNodeWithText("Ask again").assertIsDisplayed().assertIsEnabled() + } + } + + @Test + fun `tapping it asks for that proposal and no other`() { + val stalled = proposal( + "signing", "New chapter", "Genesis 4", + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + approved = true, signerIds = "1,2", owing = 1, + ) + val other = proposal( + "also", "New chapter", "Genesis 5", + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + approved = true, signerIds = "1,2", owing = 1, + ) + + render(loaded(listOf(stalled, other))) { + onAllNodesWithText("Ask again")[0].performClick() + waitUntil { resent.isNotEmpty() } + } + + assertEquals(listOf("signing"), resent) + } + + /** Opening the proposal and asking again are different taps on one row. */ + @Test + fun `asking again does not open the proposal`() { + var opened: Route? = null + val stalled = proposal( + "signing", "New chapter", "Genesis 4", + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + approved = true, signerIds = "1,2", owing = 1, + ) + + render(loaded(listOf(stalled)), onNavigateToRoute = { opened = it }) { + onNodeWithText("Ask again").performClick() + waitUntil { resent.isNotEmpty() } + } + + assertEquals(listOf("signing"), resent) + assertNull(opened, "the card behind the button took the tap too") + } + + /** + * The offer is the coordinator's and nobody else's: a resend from anybody + * else would have a member who was missing the session believe the resender + * coordinates, and then drop the real coordinator's signer set. + */ + @Test + fun `a proposal that is not ours to send offers no button`() { + val theirs = proposal( + "signing", "New chapter", "Genesis 4", + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + approved = true, signerIds = "1,2", owing = null, + ) + + render(loaded(listOf(theirs))) { + onNodeWithText("Genesis 4").assertIsDisplayed() + onAllNodesWithText("Ask again").assertCountEquals(0) + } + } + + @Test + fun `a proposal waiting on nobody offers no button`() { + val settled = proposal( + "signing", "New chapter", "Genesis 4", + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + approved = true, signerIds = "1,2", owing = 0, + ) + + render(loaded(listOf(settled))) { + onAllNodesWithText("Ask again").assertCountEquals(0) + } + } + + /** + * Disabled rather than hidden while the cooldown runs. A control that + * vanishes after a tap reads as one that failed, and what happened is that + * it worked -- so the button stays and says why it is quiet. + */ + @Test + fun `an ask sent just now leaves the button in place, disabled, and says why`() { + val justAsked = proposal( + "signing", "New chapter", "Genesis 4", + stage = FrostSigningStage.COLLECTING_PARTIAL_SIGNATURES, + approved = true, signerIds = "1,2", owing = 1, + resentAt = Clock.System.now(), + ) + + render(loaded(listOf(justAsked))) { + onNodeWithText("Ask again").assertIsDisplayed().assertIsNotEnabled() + onNodeWithText("Asked again just now. You can ask again in a few minutes.") + .assertIsDisplayed() + } + } + + /** It is offered on the earlier stage too, where the knock is for the quiet. */ + @Test + fun `a proposal still short of members offers it as well`() { + val short = proposal( + "open", "New translation", "isiZulu", + approved = true, nonces = 1, owing = 2, + ) + + render(loaded(listOf(short))) { + onNodeWithText("Ask again").assertIsDisplayed().assertIsEnabled() + } + } + + @Test + fun `a signed proposal offers nothing to ask about`() = render(loaded(listOf(signed))) { + onAllNodesWithText("Ask again").assertCountEquals(0) + } + @Test fun `a pushed screen keeps its way back, chips or no chips`() { render(loaded(mixed)) { onNodeWithContentDescription("Back").assertIsDisplayed() } @@ -384,6 +531,26 @@ class ProposalListScreenJvmTest { proposals = proposals, ) + /** + * The sessions a render asked again for, in order. + * + * Recorded through the repository the screen is given rather than through a + * callback added for the test, so what these assert is the path the app + * takes: the button, the view model's guard, and the repository call. + */ + private val resent = mutableListOf() + + private fun recordingRepository() = + object : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { + override suspend fun resend( + localChatRoom: LocalChatRoom, + sessionId: String + ): Boolean { + resent += sessionId + return true + } + } + private fun render( uiState: ProposalListUIState, onNavigateToRoute: (Route) -> Unit = {}, @@ -399,8 +566,7 @@ class ProposalListScreenJvmTest { chatRoomId = chatRoomId, initialProposalListUIState = uiState, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = - FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, + frostSigningRepository = recordingRepository(), onNavigateBack = {}, onNavigateToRoute = onNavigateToRoute, initialFilter = initialFilter, 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 index 37b8cad1..1c1ed765 100644 --- 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 @@ -5,6 +5,7 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow @@ -32,7 +33,9 @@ import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.test.fail import kotlin.time.Clock @@ -86,6 +89,13 @@ class ProposalListViewModelJvmTest { room.takeIf { id == chatRoomId } } + /** Who each session is still waiting on, and which sessions were resent. */ + private val owed = mutableMapOf>() + private val resent = mutableListOf() + + /** Held open so a test can watch a resend that has not finished yet. */ + private var resendGate: CompletableDeferred? = null + private fun frostRepository( sessions: Flow>, tallies: Flow> = flowOf(emptyList()), @@ -97,6 +107,14 @@ class ProposalListViewModelJvmTest { override fun observeSignerTalliesForChatRoom( chatRoomId: String ): Flow> = tallies + + override suspend fun membersOwing(session: FrostSigningSession): Set = + owed[session.id].orEmpty() + + override suspend fun resend(localChatRoom: LocalChatRoom, sessionId: String): Boolean { + resent += sessionId + return resendGate?.await() ?: true + } } private fun nonces(sessionId: String, members: Int) = @@ -110,10 +128,11 @@ class ProposalListViewModelJvmTest { stage: FrostSigningStage = FrostSigningStage.COLLECTING_NONCES, approved: Boolean = false, signerIds: String? = null, + coordinator: String = ada, ) = FrostSigningSession( id = id, chatRoomId = chatRoomId, - coordinatorPublicKey = ada, + coordinatorPublicKey = coordinator, userPublicKey = bob, dkgSessionId = "ceremony", threshold = 2, @@ -124,26 +143,27 @@ class ProposalListViewModelJvmTest { signApprovedAt = Clock.System.now().takeIf { approved }, ) - /** One session with one readable event in it, as the repository hands it over. */ + /** One event of a session's batch, readable so the row can name it. */ + private fun item(sessionId: String, itemIndex: Int) = FrostSigningItem( + sessionId = sessionId, + itemIndex = itemIndex, + unsignedEventJson = """{"id":"${"e".repeat(64)}","pubkey":"$chatRoomId",""" + + """"created_at":1700000000,"kind":1,"tags":[],"content":"a chapter","sig":""}""", + eventId = "e".repeat(64), + nonceRandom = "00".repeat(32), + ) + + /** One session as the repository hands it over, with [items] events in it. */ private fun local( id: String, stage: FrostSigningStage = FrostSigningStage.COLLECTING_NONCES, approved: Boolean = false, signerIds: String? = null, + coordinator: String = ada, + items: Int = 1, ) = 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), - ) - ), + session = session(id, stage, approved, signerIds, coordinator), + unorderedItems = (0 until items).map { index -> item(id, index) }, ) /** A room with one of each state in it. */ @@ -507,6 +527,193 @@ class ProposalListViewModelJvmTest { model.viewModelScope.cancel() } + // --- asking the quiet members again --------------------------------------------- + + /** + * The one the signing screen gates its button on, reached from the row. + * + * Not ours to send and nobody left to send to are different facts, and only + * the second could ever become a button later. The row keeps them apart as + * null against zero so no arithmetic can turn one into the other. + */ + @Test + fun `only a session this device proposed is ours to ask again for`() = runBlocking { + val sessions = MutableSharedFlow>(replay = 1) + owed["mine"] = setOf(bob) + owed["theirs"] = setOf(bob) + sessions.emit( + listOf( + local("mine", approved = true, coordinator = bob), + local("theirs", approved = true, coordinator = ada), + ) + ) + + val model = viewModel(sessions) + model.initiate() + + val byId = model.awaitLoaded().proposals.associateBy { it.session.id } + + // `local` builds the row as bob's device sees it -- userPublicKey is bob + // -- so the one bob coordinates is the one with an offer on it. + assertEquals(1, byId.getValue("mine").owing) + assertTrue(byId.getValue("mine").canAskAgain) + + assertNull(byId.getValue("theirs").owing, "a session we do not coordinate was costed") + assertFalse(byId.getValue("theirs").canAskAgain) + + model.viewModelScope.cancel() + } + + @Test + fun `a session waiting on nobody is ours but has nobody to ask`() = runBlocking { + val sessions = MutableSharedFlow>(replay = 1) + owed["mine"] = emptySet() + sessions.emit(listOf(local("mine", approved = true, coordinator = bob))) + + val model = viewModel(sessions) + model.initiate() + + val proposal = model.awaitLoaded().proposals.single() + + assertEquals(0, proposal.owing, "ours to send is not the same as nothing to send") + assertFalse(proposal.canAskAgain) + + model.viewModelScope.cancel() + } + + /** + * An ended session is left out although the manager would resend it: a + * completed one can be re-sent to deliver the signature to a member who + * never applied it, which is worth a button on the one proposal's screen + * rather than a query per row on a list that only grows. + */ + @Test + fun `an ended session is not costed, so a growing history stays one query`() = runBlocking { + val sessions = MutableSharedFlow>(replay = 1) + owed["done"] = setOf(bob) + owed["gone"] = setOf(bob) + sessions.emit( + listOf( + local("done", stage = FrostSigningStage.COMPLETE, coordinator = bob), + local("gone", stage = FrostSigningStage.FAILED, coordinator = bob), + ) + ) + + val model = viewModel(sessions) + model.initiate() + + assertTrue(model.awaitLoaded().proposals.all { it.owing == null }) + + model.viewModelScope.cancel() + } + + /** Nothing to resend: a session whose proposal has not landed has no events to send. */ + @Test + fun `a session holding no events is not offered an ask`() = runBlocking { + val sessions = MutableSharedFlow>(replay = 1) + owed["empty"] = setOf(bob) + sessions.emit(listOf(local("empty", coordinator = bob, items = 0))) + + val model = viewModel(sessions) + model.initiate() + + assertNull(model.awaitLoaded().proposals.single().owing) + + model.viewModelScope.cancel() + } + + @Test + fun `asking again resends that session and says whether anything went out`() = runBlocking { + val sessions = MutableSharedFlow>(replay = 1) + owed["mine"] = setOf(bob) + sessions.emit(listOf(local("mine", approved = true, coordinator = bob))) + + val model = viewModel(sessions) + model.initiate() + model.awaitLoaded() + + var sent: Boolean? = null + model.askAgain("mine") { sent = it } + + withTimeout(5_000) { while (sent == null) delay(10) } + + assertEquals(listOf("mine"), resent) + assertEquals(true, sent) + + model.viewModelScope.cancel() + } + + /** + * Guarded per session rather than by one flag for the screen. These rooms + * have several proposals open at once, and a coordinator working down the + * list should not be locked out of the second by the first still publishing. + */ + @Test + fun `a second tap on the same row publishes nothing, while another row still may`() = + runBlocking { + val sessions = MutableSharedFlow>(replay = 1) + owed["one"] = setOf(bob) + owed["two"] = setOf(bob) + sessions.emit( + listOf( + local("one", approved = true, coordinator = bob), + local("two", approved = true, coordinator = bob), + ) + ) + + val model = viewModel(sessions) + model.initiate() + model.awaitLoaded() + + val gate = CompletableDeferred() + resendGate = gate + + model.askAgain("one") {} + withTimeout(5_000) { while (!model.isAsking("one")) delay(10) } + + // The same row again, while the first is still going out. + model.askAgain("one") {} + delay(50) + assertEquals(listOf("one"), resent, "a second tap published again") + + // A different row is not locked out by it. + model.askAgain("two") {} + withTimeout(5_000) { while (resent.size < 2) delay(10) } + assertEquals(listOf("one", "two"), resent) + + gate.complete(true) + withTimeout(5_000) { while (model.isAsking("one")) delay(10) } + + // And once it has finished, the row may be asked again. + resendGate = null + model.askAgain("one") {} + withTimeout(5_000) { while (resent.size < 3) delay(10) } + assertEquals(listOf("one", "two", "one"), resent) + + model.viewModelScope.cancel() + } + + @Test + fun `a resend that published nothing is reported as such`() = runBlocking { + val sessions = MutableSharedFlow>(replay = 1) + owed["mine"] = setOf(bob) + sessions.emit(listOf(local("mine", approved = true, coordinator = bob))) + + val model = viewModel(sessions) + model.initiate() + model.awaitLoaded() + + resendGate = CompletableDeferred().also { it.complete(false) } + + var sent: Boolean? = null + model.askAgain("mine") { sent = it } + withTimeout(5_000) { while (sent == null) delay(10) } + + assertEquals(false, sent) + + model.viewModelScope.cancel() + } + private fun ProposalListViewModel.loaded(): ProposalListUIState.Loaded = assertIs(proposalListUIState) }