diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index f6128b3a40..3a131ed2d1 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -765,6 +765,9 @@ sealed class MoveToSparkError(message: String, cause: Throwable? = null) : AppEr val feeSats: ULong = 0uL, ) : MoveToSparkError("The move's fee rose after '$movedSats' sats moved") + /** The quote for the update did not finish in time, so nothing moved. */ + class QuoteTimedOut : MoveToSparkError("The update quote did not finish in time") + /** The update moved the balance, but Spark cannot pay with it yet: the move or Spark's balance has not settled. */ class UpdateUnsettled : MoveToSparkError("The update to Spark has not settled yet") diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 347b27ad3b..b70a4938e8 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -600,6 +600,7 @@ fun ContentView( val isRetryingInitialSubscriptionPayment by appViewModel.isRetryingInitialSubscriptionPayment.collectAsStateWithLifecycle() var homeWalletPageRequest by remember { mutableIntStateOf(0) } + var isSendConfirmLocked by remember { mutableStateOf(false) } var homeWidgetsPageRequest by remember { mutableIntStateOf(0) } val navigateToHomeWallet = { homeWalletPageRequest++ @@ -629,6 +630,7 @@ fun ContentView( dismissEnabled = !isCreatingPaymentRequest && !isAcceptingSubscription && !isRetryingInitialSubscriptionPayment && + !isSendConfirmLocked && canDismissSheet, sheetDragHandle = { SheetDragHandle(topPadding = if (usesFlatSheetStyle) 8.dp else 12.dp) }, sheetHandlePlacement = when (currentSheet) { @@ -654,6 +656,7 @@ fun ContentView( hardwareWalletId = sheet.hardwareWalletId, preparingRequest = sheet.preparingRequest, hwSendViewModel = hwSendViewModel, + onConfirmLockChange = { isSendConfirmLocked = it }, ) } } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt index ead537dbc6..fc0435a96d 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendConfirmScreen.kt @@ -1,5 +1,6 @@ package to.bitkit.ui.screens.wallets.send +import androidx.activity.compose.BackHandler import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.tween import androidx.compose.foundation.background @@ -25,6 +26,7 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Icon import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf @@ -110,6 +112,9 @@ import kotlin.time.Duration.Companion.seconds private val EXPIRY_REFRESH_INTERVAL = 60.seconds +/** How long the confirm stays locked after a swipe once nothing runs for it, before it frees the screen. */ +internal val SWIPE_IDLE_RELEASE = 1.seconds + /** Characters of a swap provider's pubky shown on the confirm screen. */ private const val PROVIDER_KEY_LENGTH = 12 const val SEND_CONFIRM_RESET_RESULT_KEY = "SEND_CONFIRM_RESET_RESULT_KEY" @@ -138,6 +143,8 @@ fun SendConfirmScreen( onClickAddTag: () -> Unit, onClickTag: (String) -> Unit, onNavigateToPin: () -> Unit, + isSwipeRunning: Boolean = false, + onLockChange: (Boolean) -> Unit = {}, syncNodeVariant: SyncNodeVariant = SyncNodeVariant.LIGHTNING, autoPayContent: (@Composable () -> Unit)? = null, ) { @@ -199,12 +206,22 @@ fun SendConfirmScreen( if (uiState.isPreparedFeeReview) isLoading = false } + val isLocked = rememberConfirmLock(isLoading, isSwipeRunning, uiState, showBiometrics) + + // A running swipe holds the sheet too, until it moves on or returns here + DisposableEffect(isLocked) { + onLockChange(isLocked) + onDispose { onLockChange(false) } + } + BackHandler(enabled = isLocked) {} + SendConfirmContent( uiState = uiState, isNodeRunning = isNodeRunning, isLoading = isLoading, showBiometrics = showBiometrics, canGoBack = canGoBack, + isLocked = isLocked, syncNodeVariant = syncNodeVariant, initialShowDetails = uiState.isInitialSubscriptionPayment && !uiState.shouldAutomaticallyPay, autoPayContent = autoPayContent, @@ -225,13 +242,40 @@ fun SendConfirmScreen( onEvent(SendEvent.PayConfirmed) }, onBiometricsFailure = { - isLoading = false + // Loading stays on, as on the direct PIN path; the PIN result resets it. showBiometrics = false onNavigateToPin() }, ) } +/** + * Whether the confirm screen is locked: from the swipe until it moves on or returns here. A swipe with nothing + * running for it for [SWIPE_IDLE_RELEASE], such as one stopped before paying, no longer holds it, and neither does + * the amount warning or the biometrics prompt, which the user answers. The review of a prepared fee clears the + * swipe's loading, so it stays leavable until the user swipes again to accept it. + */ +@Composable +internal fun rememberConfirmLock( + isLoading: Boolean, + isSwipeRunning: Boolean, + uiState: SendUiState, + showBiometrics: Boolean = false, +): Boolean { + val isAnswering = showBiometrics || uiState.showSanityWarningDialog != null + // Keyed so a new run, or a closed prompt, locks from its first composition, before the effect resets it. + var isSwipeIdle by remember(isLoading, isSwipeRunning, uiState.shouldConfirmPay, isAnswering) { + mutableStateOf(false) + } + LaunchedEffect(isLoading, isSwipeRunning, uiState.shouldConfirmPay, isAnswering) { + if (!isLoading || isSwipeRunning || uiState.shouldConfirmPay || isAnswering) return@LaunchedEffect + delay(SWIPE_IDLE_RELEASE) + isSwipeIdle = true + } + if (isAnswering) return false + return isLoading && !isSwipeIdle +} + @Composable internal fun AutoPayOverlay( isVisible: Boolean, @@ -257,6 +301,7 @@ internal fun SendConfirmContent( preparingRequest: PaykitPaymentRequest? = null, preparingContact: PubkyProfile? = null, canGoBack: Boolean = true, + isLocked: Boolean = false, initialShowDetails: Boolean = false, syncNodeVariant: SyncNodeVariant = SyncNodeVariant.LIGHTNING, autoPayContent: (@Composable () -> Unit)? = null, @@ -300,7 +345,7 @@ internal fun SendConfirmContent( else -> stringResource(R.string.wallet__send_review) }, contact = if (isPreparing) preparingContact else uiState.contactPaymentProfile, - onBack = onBack.takeIf { canGoBack }, + onBack = onBack.takeIf { canGoBack && !isLocked }, ) Spacer(Modifier.height(16.dp)) @@ -316,9 +361,10 @@ internal fun SendConfirmContent( preparingRequest = preparingRequest, preparingContact = preparingContact, initialShowDetails = initialShowDetails, - onEvent = onEvent, - onClickAddTag = onClickAddTag, - onClickTag = onClickTag, + // The payment's inputs stay as swiped while the swipe runs + onEvent = { if (!isLocked) onEvent(it) }, + onClickAddTag = { if (!isLocked) onClickAddTag() }, + onClickTag = { if (!isLocked) onClickTag(it) }, onSwipeToConfirm = onSwipeToConfirm, ) } else { @@ -448,7 +494,7 @@ private fun ContentRunning( VerticalSpacer(if (isPreparing || uiState.isPaymentRequest) 24.dp else 44.dp) if (isLnurlPay && !uiState.isPaymentRequest) { - LnurlPayDetails(uiState = uiState, onEvent = onEvent) + LnurlPayDetails(uiState = uiState, isLoading = isLoading, onEvent = onEvent) } else if (showDetails && !isPreparing) { when (uiState.payMethod) { SendMethod.ONCHAIN -> { @@ -475,7 +521,7 @@ private fun ContentRunning( ) val lnurlPay = uiState.lnurl as? LnurlParams.LnurlPay if (uiState.paysLnurl && lnurlPay?.data?.commentAllowed() == true) { - LnurlCommentSection(uiState, onEvent) + LnurlCommentSection(uiState, onEvent, enabled = !isLoading) } } } @@ -567,6 +613,7 @@ private fun SendUiState.canSwipeToPay() = isAmountInputValid && private fun LnurlCommentSection( uiState: SendUiState, onEvent: (SendEvent) -> Unit, + enabled: Boolean, ) { Spacer(modifier = Modifier.height(16.dp)) Caption13Up(stringResource(R.string.wallet__lnurl_pay_confirm__comment), color = Colors.White64) @@ -578,6 +625,7 @@ private fun LnurlCommentSection( onValueChange = { onEvent(SendEvent.CommentChange(it)) }, minLines = 3, maxLines = 3, + enabled = enabled, modifier = Modifier .fillMaxWidth() .testTag("CommentInput") @@ -965,6 +1013,7 @@ private val SendUiState.confirmationRequestNote: String? @Composable private fun LnurlPayDetails( uiState: SendUiState, + isLoading: Boolean, onEvent: (SendEvent) -> Unit, modifier: Modifier = Modifier, ) { @@ -1016,7 +1065,7 @@ private fun LnurlPayDetails( UpdateFeeCell(uiState.sparkUpdateQuote?.feeSats) if (lnurlPay.data.commentAllowed()) { - LnurlCommentSection(uiState, onEvent) + LnurlCommentSection(uiState, onEvent, enabled = !isLoading) } } } diff --git a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt index d022f04d4c..c36504ccd3 100644 --- a/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt +++ b/app/src/main/java/to/bitkit/ui/sheets/SendSheet.kt @@ -149,6 +149,14 @@ internal fun NavController.navigateToCoinSelection() { navigateTo(SendRoute.CoinSelection) } +/** Shows [route] after a failed swipe, resetting the confirmation it covers so Back finds it ready to swipe. */ +internal fun NavController.navigateToSendError(route: SendRoute.Error) { + currentBackStackEntry?.takeIf { it.destination.hasRoute() } + ?.savedStateHandle + ?.set(SEND_CONFIRM_RESET_RESULT_KEY, true) + navigateTo(route) +} + internal fun NavController.navigateToSendAmount(startDestination: SendRoute) { if (popBackStack(SendRoute.Amount, inclusive = false)) return navigateTo(SendRoute.Amount) { @@ -172,6 +180,7 @@ fun SendSheet( startDestination: SendRoute = SendRoute.Recipient, hardwareWalletId: String? = null, preparingRequest: PaykitPaymentRequest? = null, + onConfirmLockChange: (Boolean) -> Unit = {}, ) { val context = LocalContext.current val connectivityState by appViewModel.isOnline.collectAsStateWithLifecycle() @@ -376,7 +385,7 @@ fun SendSheet( retryRoute = it.retryRoute, ) ) - is SendEffect.NavigateToError -> navController.navigateTo( + is SendEffect.NavigateToError -> navController.navigateToSendError( SendRoute.errorFromFailure( failure = it.failure, retryRoute = it.retryRoute, @@ -531,6 +540,7 @@ fun SendSheet( } val uiState by appViewModel.sendUiState.collectAsStateWithLifecycle() val lightningState by walletViewModel.lightningState.collectAsStateWithLifecycle() + val isSwipeRunning by appViewModel.isSendSwipeRunning.collectAsStateWithLifecycle() val initialSubscriptionId = uiState.incomingPaymentRequestId ?.takeIf { uiState.isInitialSubscriptionPayment } ?.let { id -> PaykitSubscriptionId(id.paymentRequestId, id.counterparty) } @@ -565,6 +575,8 @@ fun SendSheet( }, onClickTag = { tag -> appViewModel.removeTag(tag) }, onNavigateToPin = { navController.navigateTo(SendRoute.PinCheck) }, + isSwipeRunning = isSwipeRunning, + onLockChange = onConfirmLockChange, autoPayContent = initialSubscription?.let { subscription -> { SubscriptionFirstPaymentProgress( diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index c4fed67217..692761cf58 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -444,8 +444,16 @@ class AppViewModel @Inject constructor( private val sparkUpdateQuoteRun = AtomicLong(0L) /** Bumped only when a new send starts, unlike [sendStateGeneration], which edits within one send also bump. */ + @Volatile private var sendSession = 0L + /** Swipes and payments still running from the confirm screen, by [sendSession]; see [isSendSwipeRunning]. */ + private val sendSwipeRuns = mutableMapOf() + private val _isSendSwipeRunning = MutableStateFlow(false) + + /** True while a swipe of the current send, or the payment it confirmed, runs; the confirm stays locked. */ + val isSendSwipeRunning = _isSendSwipeRunning.asStateFlow() + fun setSendEvent(event: SendEvent) { if ((currentSheet.value as? Sheet.Send)?.preparingRequest != null) return if (preparedFeeReview != null && event.changesReviewedSend()) return @@ -6770,19 +6778,41 @@ class AppViewModel @Inject constructor( if (!_sendUiState.value.isAmountInputValid || !_sendUiState.value.isHardwareFeeReady) return _sendUiState.update { it.copy(approvedSparkUpdateQuote = it.sparkUpdateQuote) } viewModelScope.launch { - val review = preparedFeeReview - if (review == null && !prepareCoinSelection()) return@launch - val amount = _sendUiState.value.amount + whileSendSwipeRuns { + val review = preparedFeeReview + if (review == null && !prepareCoinSelection()) return@whileSendSwipeRuns + val amount = _sendUiState.value.amount - handleSanityChecks(amount, preparedFeeSats = review?.feeSats) - if (_sendUiState.value.showSanityWarningDialog != null) return@launch // await for dialog UI interaction + handleSanityChecks(amount, preparedFeeSats = review?.feeSats) + // await for dialog UI interaction + if (_sendUiState.value.showSanityWarningDialog != null) return@whileSendSwipeRuns - if (preparedFeeReview !== review) return@launch - review?.isSwiped = true - _sendUiState.update { it.copy(shouldConfirmPay = true) } + if (preparedFeeReview !== review) return@whileSendSwipeRuns + review?.isSwiped = true + _sendUiState.update { it.copy(shouldConfirmPay = true) } + } } } + private suspend fun whileSendSwipeRuns(block: suspend () -> Unit) { + val session = sendSession + synchronized(sendSwipeRuns) { sendSwipeRuns[session] = (sendSwipeRuns[session] ?: 0) + 1 } + refreshSendSwipeRunning() + try { + block() + } finally { + synchronized(sendSwipeRuns) { + val runs = (sendSwipeRuns[session] ?: 1) - 1 + if (runs > 0) sendSwipeRuns[session] = runs else sendSwipeRuns.remove(session) + } + refreshSendSwipeRunning() + } + } + + private fun refreshSendSwipeRunning() = synchronized(sendSwipeRuns) { + _isSendSwipeRunning.update { sendSwipeRuns.containsKey(sendSession) } + } + private fun onStartInitialSubscriptionPayment() { val state = _sendUiState.value if (!state.initialSubscriptionPaymentAutoStartPending) return @@ -8114,7 +8144,7 @@ class AppViewModel @Inject constructor( private suspend fun updateSpendingBalanceIfNeeded(bolt11: String, amountSats: ULong): Result { if (!moveToSparkRepo.needsUpdateToSend(amountSats)) return Result.success(Unit) val shown = _sendUiState.value.approvedSparkUpdateQuote - val fresh = moveToSparkRepo.quote().getOrElse { return Result.failure(it) } + val fresh = quoteSparkUpdate().getOrElse { return Result.failure(it) } if (shown == null || fresh.feeSats > shown.feeSats) { _sendUiState.update { it.copy(sparkUpdateQuote = fresh) } return Result.failure(MoveToSparkError.UpdateFeeUnseen()) @@ -8134,12 +8164,14 @@ class AppViewModel @Inject constructor( val state = _sendUiState.value if (!state.needsSparkUpdate()) return true val generation = sendStateGeneration - val fresh = moveToSparkRepo.quote().getOrElse { + val result = quoteSparkUpdate() + // A swipe from a send the user left neither pays nor shows its failure. + if (generation != sendStateGeneration) return false + val fresh = result.getOrElse { val failure = it.toSendFailureDetails(context, state.currentLightningPaymentRequest()) setSendEffect(SendEffect.NavigateToError(failure)) return false } - if (generation != sendStateGeneration) return false val shown = state.approvedSparkUpdateQuote _sendUiState.update { it.copy(sparkUpdateQuote = fresh) } if (shown != null && fresh.feeSats <= shown.feeSats) return true @@ -8148,6 +8180,16 @@ class AppViewModel @Inject constructor( return false } + private suspend fun quoteSparkUpdate(): Result { + // Awaited apart, since the LDK queue finishes its work even after its caller is cancelled + val quote = viewModelScope.async(bgDispatcher) { moveToSparkRepo.quote() } + return withTimeoutOrNull(SPARK_UPDATE_QUOTE_TIMEOUT) { quote.await() } ?: run { + quote.cancel() + Logger.warn("Timed out quoting the update after '$SPARK_UPDATE_QUOTE_TIMEOUT'", context = TAG) + Result.failure(MoveToSparkError.QuoteTimedOut()) + } + } + /** Whether this Lightning payment fits only once the spending balance update moves the channels to Spark. */ private fun SendUiState.needsSparkUpdate(): Boolean { if (payMethod != SendMethod.LIGHTNING || routedPaykitRoute?.serviceLeg != null) return false @@ -9029,6 +9071,7 @@ class AppViewModel @Inject constructor( if (!canPrepareSend(walletGeneration)) return false sendStateGeneration++ sendSession++ + refreshSendSwipeRunning() cancelPreparedFeeReview() addressValidationJob?.cancel() paykitReviewedAmount = null @@ -9304,6 +9347,7 @@ class AppViewModel @Inject constructor( sendStateGeneration++ // A closed send is over: a swap failing for it later gives no contact back to whatever comes next. sendSession++ + refreshSendSwipeRunning() cancelPreparedFeeReview() // A payment still running for the dismissed send, like a slow swap commit, must not block the next. if (confirmedPaymentSubmission != null) releaseConfirmedPaymentSubmission() @@ -9523,11 +9567,10 @@ class AppViewModel @Inject constructor( if (review.isSwiped) review.answer.complete(true) return } - if (isSubmittingPaymentRequest || isSoftwarePaymentSubmissionActive) { + if (isSubmittingPaymentRequest || isSoftwarePaymentSubmissionActive || !_sendUiState.value.isHardwareFeeReady) { _sendUiState.update { it.copy(shouldConfirmPay = false) } return } - if (!_sendUiState.value.isHardwareFeeReady) return val contactPaymentContext = synchronized(contactPaymentContextLock) { activeContactPaymentContext } if (_sendUiState.value.isPaymentRequest && contactPaymentContext?.incomingPaymentRequest == null) { @@ -9547,7 +9590,7 @@ class AppViewModel @Inject constructor( val finishSubmission = beginPaymentSubmission() try { _sendUiState.update { it.copy(shouldConfirmPay = false) } - proceedWithPayment(contactPaymentContext) + whileSendSwipeRuns { proceedWithPayment(contactPaymentContext) } } finally { finishSubmission() if (confirmedPaymentSubmission === submission) releaseConfirmedPaymentSubmission() @@ -10556,6 +10599,9 @@ class AppViewModel @Inject constructor( private const val ADDRESS_VALIDATION_DEBOUNCE_MS = 1000L private const val PAYKIT_CHANNEL_USABILITY_REFRESH_DELAY_MS = 5_000L private val PAYKIT_PAYMENT_REQUEST_REFRESH_INTERVAL = 10.seconds + + /** Bounds the re-quote after the swipe, which keeps Confirm locked while it runs. */ + private val SPARK_UPDATE_QUOTE_TIMEOUT = 60.seconds private val PAYKIT_MAINTENANCE_INTERVALS = listOf(30.seconds, 60.seconds) private val PAYKIT_PAYMENT_REQUEST_PRESENTATION_RETRY_DELAYS = List(14) { 2.seconds } private val PAYKIT_PAYMENT_REQUEST_PRESENTATION_RETRY_INTERVAL = 120.seconds diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmUpdateFeeTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmUpdateFeeTest.kt index 861569ae39..e5b6b201e5 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmUpdateFeeTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendConfirmUpdateFeeTest.kt @@ -1,11 +1,16 @@ package to.bitkit.ui.screens.wallets.send import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo import com.synonym.bitkitcore.LightningInvoice import com.synonym.bitkitcore.NetworkType import org.junit.Rule @@ -13,11 +18,19 @@ import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowSystemClock import to.bitkit.repositories.MoveToSparkQuote import to.bitkit.ui.shared.modifiers.sheetHeight import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.viewmodels.SanityWarning import to.bitkit.viewmodels.SendMethod import to.bitkit.viewmodels.SendUiState +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlin.time.toJavaDuration @RunWith(RobolectricTestRunner::class) class SendConfirmUpdateFeeTest { @@ -52,6 +65,184 @@ class SendConfirmUpdateFeeTest { composeRule.onNodeWithTag("ReviewUpdateFee").assertIsDisplayed() } + @Config(sdk = [34]) + @Test + fun `the amount warning frees the confirm while the user answers it`() { + var isLocked = true + composeRule.setContent { + isLocked = rememberConfirmLock( + isLoading = true, + isSwipeRunning = true, + uiState = SendUiState(showSanityWarningDialog = SanityWarning.OVER_HALF_BALANCE), + ) + } + advanceBy(SWIPE_IDLE_RELEASE / 4) + + assertFalse(isLocked) + } + + @Config(sdk = [34]) + @Test + fun `a swipe accepting a prepared fee locks the confirm`() { + var isLoading by mutableStateOf(false) + var isLocked = true + composeRule.setContent { + isLocked = rememberConfirmLock( + isLoading = isLoading, + isSwipeRunning = true, + uiState = SendUiState(isPreparedFeeReview = true), + ) + } + advanceBy(SWIPE_IDLE_RELEASE / 4) + assertFalse(isLocked) + + composeRule.runOnUiThread { isLoading = true } + advanceBy(SWIPE_IDLE_RELEASE / 4) + + assertTrue(isLocked) + } + + @Config(sdk = [34]) + @Test + fun `a closed biometrics prompt locks again from its first composition`() { + var showBiometrics by mutableStateOf(true) + val composed = mutableListOf() + composeRule.setContent { + composed += rememberConfirmLock( + isLoading = true, + isSwipeRunning = false, + uiState = SendUiState(), + showBiometrics = showBiometrics, + ) + } + advanceBy(SWIPE_IDLE_RELEASE * 2) + assertFalse(composed.last()) + val prompted = composed.size + + composeRule.runOnUiThread { showBiometrics = false } + advanceBy(SWIPE_IDLE_RELEASE / 4) + + val afterClose = composed.drop(prompted) + assertTrue(afterClose.isNotEmpty()) + assertTrue(afterClose.all { it }, "compositions after close: $afterClose") + } + + @Config(sdk = [34], qualifiers = "w411dp-h891dp") + @Test + fun `the lock hides back and blocks edits on its own`() { + val (backs, addTags) = renderConfirm(isLocked = true) + + composeRule.onNodeWithTag("NavigationBack").assertDoesNotExist() + composeRule.onNodeWithTag("TagsAddSend").performScrollTo().performClick() + + assertEquals(0, addTags.size) + assertEquals(0, backs.size) + } + + @Config(sdk = [34], qualifiers = "w411dp-h891dp") + @Test + fun `an unlocked confirm takes edits`() { + val (_, addTags) = renderConfirm(isLocked = false) + + composeRule.onNodeWithTag("TagsAddSend").performScrollTo().performClick() + + assertEquals(1, addTags.size) + } + + private fun renderConfirm(isLocked: Boolean): Pair, List> { + val backs = mutableListOf() + val addTags = mutableListOf() + composeRule.setContent { + CompositionLocalProvider(LocalInspectionMode provides true) { + AppThemeSurface { + SendConfirmContent( + uiState = SendUiState( + amount = 50_000u, + isAmountInputValid = true, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = INVOICE.copy(amountSatoshis = 0u), + sparkUpdateQuote = MoveToSparkQuote("lnbcrt1spark", amountSats = 29_967uL, feeSats = 2uL), + ), + isNodeRunning = true, + // Off, so only the lock gates the rows that loading also disables + isLoading = false, + showBiometrics = false, + isLocked = isLocked, + onBack = { backs += Unit }, + onClickAddTag = { addTags += Unit }, + initialShowDetails = true, + modifier = Modifier.sheetHeight() + ) + } + } + } + // Past the click debounce, which reads the system clock + ShadowSystemClock.advanceBy(1.seconds.toJavaDuration()) + return backs to addTags + } + + @Config(sdk = [34]) + @Test + fun `a swipe with nothing running for it frees the confirm after a second`() { + var isSwipeRunning by mutableStateOf(true) + var isLocked = false + composeRule.setContent { + isLocked = rememberConfirmLock(isLoading = true, isSwipeRunning = isSwipeRunning, uiState = SendUiState()) + } + advanceBy(SWIPE_IDLE_RELEASE * 2) + assertTrue(isLocked) + + composeRule.runOnUiThread { isSwipeRunning = false } + advanceBy(SWIPE_IDLE_RELEASE / 2) + assertTrue(isLocked) + advanceBy(SWIPE_IDLE_RELEASE) + + assertFalse(isLocked) + } + + @Config(sdk = [34]) + @Test + fun `a pending pay confirmation with nothing running stays locked`() { + var isLocked = false + composeRule.setContent { + isLocked = rememberConfirmLock( + isLoading = true, + isSwipeRunning = false, + uiState = SendUiState(shouldConfirmPay = true), + ) + } + advanceBy(5.seconds) + + assertTrue(isLocked) + } + + @Config(sdk = [34]) + @Test + fun `a new run after the idle release locks from its first composition`() { + var isSwipeRunning by mutableStateOf(false) + val composed = mutableListOf>() + composeRule.setContent { + val locked = rememberConfirmLock(isLoading = true, isSwipeRunning = isSwipeRunning, uiState = SendUiState()) + composed += isSwipeRunning to locked + } + advanceBy(SWIPE_IDLE_RELEASE * 2) + assertEquals(false to false, composed.last()) + val released = composed.size + + composeRule.runOnUiThread { isSwipeRunning = true } + advanceBy(SWIPE_IDLE_RELEASE / 4) + + val afterFlip = composed.drop(released) + assertTrue(afterFlip.isNotEmpty()) + assertTrue(afterFlip.all { (running, locked) -> !running || locked }, "compositions after flip: $afterFlip") + } + + private fun advanceBy(duration: Duration) { + composeRule.waitForIdle() + composeRule.mainClock.advanceTimeBy(duration.inWholeMilliseconds) + composeRule.waitForIdle() + } + private companion object { val INVOICE = LightningInvoice( bolt11 = "lnbcrt1p5frwyedq2gf5hg6mfwsnp4qdkkcte90vc7c5z6z72uu5p2schwkmlx9j704tuwm2z59wfgku46xpp56yfmwmfxtl", diff --git a/app/src/test/java/to/bitkit/ui/sheets/SendErrorNavigationTest.kt b/app/src/test/java/to/bitkit/ui/sheets/SendErrorNavigationTest.kt new file mode 100644 index 0000000000..06c7fb1936 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/sheets/SendErrorNavigationTest.kt @@ -0,0 +1,64 @@ +package to.bitkit.ui.sheets + +import android.app.Application +import androidx.activity.ComponentActivity +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule +import androidx.navigation.NavHostController +import androidx.navigation.compose.NavHost +import androidx.navigation.compose.composable +import androidx.navigation.compose.rememberNavController +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.ui.screens.wallets.send.collectConfirmResets +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +@Config(application = Application::class, sdk = [34]) +@RunWith(RobolectricTestRunner::class) +class SendErrorNavigationTest { + @get:Rule + val composeRule = createAndroidComposeRule() + + private lateinit var navController: NavHostController + private var isLoading = false + private var swipe: () -> Unit = {} + + private fun setContent() { + composeRule.setContent { + navController = rememberNavController() + NavHost(navController, startDestination = SendRoute.Confirm) { + composable { entry -> + // Saved like the confirmation's own swipe state + var loading by rememberSaveable { mutableStateOf(false) } + LaunchedEffect(entry) { entry.savedStateHandle.collectConfirmResets { loading = false } } + isLoading = loading + swipe = { loading = true } + } + composable {} + } + } + composeRule.runOnUiThread { swipe() } + composeRule.waitForIdle() + } + + @Test + fun `back from a failed swipe returns to a confirmation that takes a swipe`() { + setContent() + assertTrue(isLoading) + + composeRule.runOnUiThread { navController.navigateToSendError(SendRoute.Error()) } + composeRule.waitForIdle() + composeRule.runOnUiThread { navController.popBackStack() } + composeRule.waitForIdle() + + assertFalse(isLoading) + } +} diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 4a2c1961e9..11b45f7de3 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -21753,6 +21753,146 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) } + @Test + fun `the swipe keeps running while it quotes the update again`() = test { + val bolt11 = "lnbcrt1lockedrequote" + val quoted = CompletableDeferred>() + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).doSuspendableAnswer { quoted.await() } + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + // Short of the update quote's time bound + advanceTimeBy(30.seconds) + assertTrue(sut.isSendSwipeRunning.value) + + quoted.complete(Result.success(UPDATE_QUOTE)) + advanceUntilIdle() + + assertEquals(SendEffect.ResetConfirm, awaitItem()) + } + assertFalse(sut.isSendSwipeRunning.value) + } + + @Test + fun `a swipe of a closed send holds nothing and its failing update quote shows no error`() = test { + val bolt11 = "lnbcrt1closedrequote" + val quoted = CompletableDeferred>() + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).doSuspendableAnswer { quoted.await() } + sut.showSheet(Sheet.Send(SendRoute.Confirm)) + runCurrent() + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, + ), + ) + val effects = mutableListOf() + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { sut.sendEffect.collect { effects += it } } + + sut.setSendEvent(SendEvent.PayConfirmed) + // Short of the update quote's time bound + advanceTimeBy(30.seconds) + assertTrue(sut.isSendSwipeRunning.value) + sut.hideSheet() + // A payment still finishing for the closed send holds no later send's confirm + assertFalse(sut.isSendSwipeRunning.value) + quoted.complete(Result.failure(MoveToSparkError.NothingToMove())) + advanceUntilIdle() + + assertTrue(effects.none { it is SendEffect.NavigateToError }) + assertFalse(sut.isSendSwipeRunning.value) + } + + @Test + fun `a hardware confirm while the fee refreshes clears the pay confirmation`() = test { + setSendState( + SendUiState( + address = "bcrt1qverifyhardware", + amount = 60_000uL, + isAmountInputValid = true, + payMethod = SendMethod.ONCHAIN, + hardwareWalletId = "hardware-wallet", + onchainFeeUi = OnchainFeeUi(sats = 150, isLoading = true), + shouldConfirmPay = true, + ), + ) + + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + + assertFalse(sut.sendUiState.value.shouldConfirmPay) + } + + @Test + fun `a stalled update quote ends the swipe with the payment error`() = test { + val bolt11 = "lnbcrt1stalledrequote" + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + // Ignores cancellation, as LDK queue work does + whenever(moveToSparkRepo.quote()).doSuspendableAnswer { withContext(NonCancellable) { awaitCancellation() } } + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + assertTrue(awaitItem() is SendEffect.NavigateToError) + } + assertFalse(sut.isSendSwipeRunning.value) + verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) + } + + @Test + fun `a stalled update quote at the payment ends it with the payment error`() = test { + val bolt11 = "lnbcrt1stalledpayquote" + var quotes = 0 + whenever(moveToSparkRepo.needsUpdateToSend(60_000uL)).thenReturn(true) + whenever(moveToSparkRepo.quote()).doSuspendableAnswer { + if (++quotes > 1) withContext(NonCancellable) { awaitCancellation() } + Result.success(UPDATE_QUOTE) + } + setSendState( + SendUiState( + address = bolt11, + amount = 60_000uL, + payMethod = SendMethod.LIGHTNING, + decodedInvoice = lightningInvoice(bolt11, 60_000uL), + sparkUpdateQuote = UPDATE_QUOTE, + approvedSparkUpdateQuote = UPDATE_QUOTE, + ), + ) + + sut.sendEffect.test { + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + assertTrue(awaitItem() is SendEffect.NavigateToError) + } + assertEquals(2, quotes) + assertFalse(sut.isSendSwipeRunning.value) + verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) + } + @Test fun `a scan while the node starts decides on QuickPay once the channels are usable`() = test { val bolt11 = "lnbcrt1quickpaystarting" diff --git a/changelog.d/next/2017.fixed.md b/changelog.d/next/2017.fixed.md new file mode 100644 index 0000000000..2b5122ee89 --- /dev/null +++ b/changelog.d/next/2017.fixed.md @@ -0,0 +1 @@ +Keep the payment confirm screen open while a swipe is paying, so leaving can't undo it silently. diff --git a/journeys/README.md b/journeys/README.md index 71872a67b1..326b7e064a 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -172,7 +172,8 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `send/own-invoice-guard.xml` | not ported — iOS has no own-invoice guard | | `send/recovery-pin-system-back.xml` | not ported — iOS has no system Back button, and `SendPinScreen` already answers cancel in `onDisappear` | | `send/retry-original-dialog-style.xml` | not ported — iOS shows the two Retry original payment steps as native alerts | -| `send/update-spending-balance-payment.xml`, `transfer/move-to-spark.xml` | port pending — the iOS Update Spending Balance modal and combined payment are not built yet; port both journeys with it, after synonymdev/bitkit-ios#1355 | +| `send/update-spending-balance-payment.xml` | same file and journey name; the lock step presses system back and drags the sheet here, while iOS opens Confirm from a link as the sheet's root and only drags it | +| `transfer/move-to-spark.xml` | port pending — port it with the iOS Update Spending Balance modal, after synonymdev/bitkit-ios#1355 | | `send/onchain-connecting-view.xml` | ported with another route — on iOS the LDK Debug Restart keeps the node in the running state and a launch shows home only once the node runs, so the iOS journey opens Send while the node is still starting | | `send/prepared-fee-recovery.md` | Same four manual fault cases and file on both platforms; the recipe records original-send versus replacement fee retention and iOS Max/identity-flow adaptations. These faults are not journey capabilities. | | `settings/electrum-server-error-toasts.xml` | not ported — iOS still shows one generic message for every manual Electrum connect failure | diff --git a/journeys/send/update-spending-balance-payment.xml b/journeys/send/update-spending-balance-payment.xml index 677392cd3e..4c4102da5d 100644 --- a/journeys/send/update-spending-balance-payment.xml +++ b/journeys/send/update-spending-balance-payment.xml @@ -5,7 +5,9 @@ and one swipe first moves the channel's balance to Spark, then pays the invoice from Spark. The move shows in Activity as a "Move to Spark" row, and the emptied channel closes in the background. If the payment fails after the move, the funds stay in Spark and the usual payment error shows. QuickPay never sends such a payment; it always - opens the confirm screen. + opens the confirm screen. From the swipe until it moves on or returns to confirm, the confirm screen is locked: no + Back, no sheet dismiss and no edits. Android also checks system back here; on iOS a confirm screen opened from a + link is the sheet's root, so only the sheet's drag applies there. Precondition: dev build pointed at a local Spark regtest (spark-sdk regtest/local), QuickPay off, a wallet with an open channel to that stack's SSP Lightning node that can send about 30 000 sats and a Spark balance of about @@ -17,6 +19,7 @@ Verify the Confirm screen (testTag "SendConfirm") shows 50 000 sats with its details open on their own (Hide Details, testTag "SendConfirmToggleDetails") Verify the fee row shows the payment's own fee and the "Update fee" row (testTag "ReviewUpdateFee") shows an amount, without "up to", and that no "Route" row shows Swipe to pay (testTag "GRAB"); the payment is over half of the Spending balance, so verify the "Are You Sure?" dialog warns about sending over 50% of the balance and tap "Yes, Send" + While the swipe still shows its loading state, press system back and drag the sheet down; verify the Confirm screen stays open Verify the Bitcoin Sent screen (testTag "SendSuccess") shows 50 000 Go back to Home and verify Activity lists a "Move to Spark" transfer row and the 50 000-sat Lightning payment Open Settings › Advanced › Lightning Connections and verify the channel is closing or closed