Modern Apps git

← Modern-Apps.git

email: publish viewer state on Main; make composer test deterministic

Commit
4dd2924c598fa67bc667e4086813705083df3c71
Author
Vayun Mathur <[email protected]>
When
2026-11-21 15:42 UTC (14 days ago)
Parents
e461136
EmlViewerSuccessTest timed out ~1 in 3 full-suite runs with
every thread idle: the parse result, error and loading states
were written from IO/Default threads on independent
schedules, and the loading clear could fail to invalidate
recomposition entirely. The screen now parses on IO and
publishes all three states together on Main (the same pattern
as EmailViewModel). The shared awaitSemantics helper also ran
only the frame clock, never the composition scheduler's queued
work - it now runs due scheduler tasks and steps the virtual
clock in a bounded way, which several debounce-driven screens
depend on. ComposerLaunchersW5Test raced database close
against a fire-and-forget delete on a viewModelScope nothing
ever cleared; autosave completion is now awaited as the
terminal signal and the harness drains the scope against the
still-open database before closing.

Verified: email suite green 8/8 consecutive full runs (was
failing 5/5 and ~1/3), nonogram awaitSemantics suite passes.

Diff

build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt
diff --git a/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt b/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.ktindex 0163767d02..6e447dae24 100644--- a/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt+++ b/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt@@ -2,6 +2,7 @@ package com.vayunmathur.testsupport  import android.os.Looper import androidx.compose.ui.test.junit4.ComposeContentTestRule+import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking@@ -24,7 +25,8 @@ import org.robolectric.Shadows  *   terminal condition holds. Idling the looper is what lets a coroutine  *   resumed on Main actually run; sleeping would only bet on load.  * - [awaitSemantics] is a Compose semantics wait on a terminal node state,- *   idling the main looper on every check for the same reason.+ *   pumping the looper *and* the composition's test scheduler on every+ *   check for the same reason (see its doc).  *  * None of these sleep, burn CPU, or read `System.currentTimeMillis`.  */@@ -77,12 +79,39 @@ fun awaitWithMainIdle(description: String, maxSteps: Int = 10_000, condition: ()  * re-checks [condition] after every idle, and each check first pumps the  * main looper so a parse/load resumed on Main can land and compose.  * The timeout is the framework's failure bound, not the mechanism.+ *+ * The pump has three parts, and all are needed. Idling Robolectric's paused+ * looper runs work posted to the Android main thread. But the composition's+ * own coroutines — the recomposer and its [androidx.compose.runtime.LaunchedEffect]s+ * — live on the Compose test environment's scheduler (the one behind+ * [androidx.compose.ui.test.MainTestClock]), and `waitUntil` only *advances+ * that scheduler's frame clock* between checks; it never *runs* the tasks+ * queued on the scheduler. A state write landing from an IO thread therefore+ * invalidated the tree (the scaffold title flipped to the parsed subject)+ * while the recomposition that would compose the new branch sat queued past+ * the whole 15s wait, and a debounced autosave's timer sat in the+ * scheduler's future. So each check also (a) runs the scheduler's due tasks+ * and (b) steps its virtual clock forward a bounded window, executing the+ * timers and delayed resumes queued there. Stepping virtual time is the+ * mechanism, not a timing bet: it runs the actual queued work.  */ fun ComposeContentTestRule.awaitSemantics(description: String, condition: () -> Boolean) {     waitUntil(15_000) {+        idleMainLooper()+        mainClock.scheduler.runCurrent()+        mainClock.scheduler.advanceTimeBy(SCHEDULER_ADVANCE_SECONDS.seconds)         idleMainLooper()         condition()     }     idleMainLooper()+    mainClock.scheduler.advanceUntilIdle()+    idleMainLooper()     check(condition()) { "terminal semantics state not reached: $description" } }++/**+ * Virtual seconds [awaitSemantics] steps the composition scheduler per+ * check: past an 800ms debounce or a sharing timeout (5s), far short of any+ * point where virtual time itself becomes the thing being tested.+ */+private const val SCHEDULER_ADVANCE_SECONDS = 60
email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.ktindex 6cc3ab1dba..0c51e5f5f1 100644--- a/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/EmlViewerScreen.kt@@ -82,12 +82,25 @@ fun EmlViewerScreen(         loading = true         error = null         parsed = null-        withContext(Dispatchers.IO) {+        // Parse on IO, publish on Main — explicitly. Assigning `parsed`/`error`+        // inside the withContext(IO) block wrote Compose state from the IO+        // thread, and returning to this effect's own context is not a+        // guarantee either: the composition's dispatcher resumes wherever the+        // async work completed in some environments, so the three writes+        // still landed off the main thread on their own schedules — the+        // title could flip to the parsed subject (a background snapshot write+        // the recomposer observed) while `loading = false` never invalidated+        // a recomposition at all, leaving a torn subject + spinner state.+        // Hopping to Dispatchers.Main makes all three writes land together,+        // on the main thread, in one resume.+        val result = withContext(Dispatchers.IO) {             runCatching { EmlUtils.parseEml(context, uriString.toUri()) }-                .onSuccess { parsed = it }-                .onFailure { error = it.message ?: it.javaClass.simpleName }         }-        loading = false+        withContext(Dispatchers.Main) {+            result.onSuccess { parsed = it }+            result.onFailure { error = it.message ?: it.javaClass.simpleName }+            loading = false+        }     }      AppScaffold(@@ -121,12 +134,16 @@ fun EmlViewerScreen(                         OutlinedButton(onClick = {                             scope.launch {                                 loading = true; error = null; parsed = null-                                withContext(Dispatchers.IO) {+                                // Same publication rule as the initial load: parse on+                                // IO, publish all state together on Main.+                                val result = withContext(Dispatchers.IO) {                                     runCatching { EmlUtils.parseEml(context, uriString.toUri()) }-                                        .onSuccess { parsed = it }-                                        .onFailure { error = it.message ?: it.javaClass.simpleName }                                 }-                                loading = false+                                withContext(Dispatchers.Main) {+                                    result.onSuccess { parsed = it }+                                    result.onFailure { error = it.message ?: it.javaClass.simpleName }+                                    loading = false+                                }                             }                         }) { Text(stringResource(R.string.retry)) }                     }
email/src/test/java/com/vayunmathur/email/ui/ComposerLaunchersW5Test.kt
diff --git a/email/src/test/java/com/vayunmathur/email/ui/ComposerLaunchersW5Test.kt b/email/src/test/java/com/vayunmathur/email/ui/ComposerLaunchersW5Test.ktindex f6bee6183f..04292c6ceb 100644--- a/email/src/test/java/com/vayunmathur/email/ui/ComposerLaunchersW5Test.kt+++ b/email/src/test/java/com/vayunmathur/email/ui/ComposerLaunchersW5Test.kt@@ -20,6 +20,7 @@ import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.performClick import androidx.core.app.ActivityOptionsCompat+import androidx.lifecycle.viewModelScope import androidx.room3.Room import androidx.test.core.app.ApplicationProvider import androidx.work.Configuration@@ -28,11 +29,15 @@ import com.vayunmathur.email.data.EmailAccount import com.vayunmathur.email.data.EmailDatabase import com.vayunmathur.email.data.EmailRepository import com.vayunmathur.email.platform.EmailViewModel+import com.vayunmathur.testsupport.awaitSemantics+import com.vayunmathur.testsupport.awaitWithMainIdle import java.io.File import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertTrue+import kotlinx.coroutines.Job+import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.Rule@@ -106,16 +111,29 @@ class ComposerLaunchersW5Test {             .allowMainThreadQueries().build()         resetRepositorySingleton()         com.vayunmathur.library.util.databases[EmailDatabase::class] = db-        vm = EmailViewModel(context)         runBlocking {             db.accountDao().insertAccount(                 EmailAccount(email = "[email protected]", signature = "Sent from W5")             )         }+        vm = EmailViewModel(context)     }      @AfterTest     fun close() {+        // Quiesce before closing: EmailDraftActions.save/delete fire-and-forget+        // into viewModelScope. The ViewModel here is hand-built (no+        // ViewModelStore ever clears it), so without cancelling the scope, a+        // save/delete still queued on the paused main looper — or tails of the+        // accounts/drafts StateFlows — runs during compose-rule teardown,+        // after db.close(), and dies with "connection is closed". Cancel the+        // scope, pump the looper until its children have drained against the+        // still-open database, and only then close.+        vm.viewModelScope.cancel()+        val scopeJob = vm.viewModelScope.coroutineContext[Job]+        awaitWithMainIdle("viewModel scope drained", maxSteps = 2_000) {+            scopeJob?.children?.none { it.isActive } ?: true+        }         com.vayunmathur.library.util.databases.remove(EmailDatabase::class)         resetRepositorySingleton()         db.close()@@ -153,7 +171,7 @@ class ComposerLaunchersW5Test {                 )             }         }-        rule.waitUntil(20_000) { exists("Launchers W5") }+        rule.awaitSemantics("composer subject") { exists("Launchers W5") }         // Toolbar actions only (attach + inline image), identified by their         // position in the top bar - clicking Send would start a real SMTP         // attempt and wedge the screen in "sending".@@ -162,35 +180,24 @@ class ComposerLaunchersW5Test {             .filter { (_, n) -> n.boundsInRoot.top < 120f && n.boundsInRoot.left > 100f }         for ((i, _) in toolbar.take(2)) {             runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }-            Thread.sleep(300)+            rule.waitForIdle()         }         // The attachment chip for the picked file should be listed.         assertTrue(exists("w5-inline.png") || exists("Launchers W5"))-        // Draft autosave (800ms debounce) should persist a draft row.-        val deadline = System.currentTimeMillis() + 20_000-        var saved = false-        while (System.currentTimeMillis() < deadline) {-            runCatching { rule.waitForIdle() }-            Thread.sleep(200)-            saved = runBlocking { db.outboxDao().getDraftsFlow().first().isNotEmpty() }-            if (saved) break-        }-        // The composer's own autosave is debounce-driven; assert the draft-        // store directly as well so the save/load/delete path is pinned.-        if (!saved) {-            val idRef = java.util.concurrent.atomic.AtomicLong(0)-            vm.draftsActions.save(null, "[email protected]", "[email protected]", "", "", "Launchers W5", "Hello") {-                idRef.set(it)-            }-            val deadline2 = System.currentTimeMillis() + 10_000-            while (idRef.get() == 0L && System.currentTimeMillis() < deadline2) {-                runCatching { rule.waitForIdle() }-                Thread.sleep(50)-            }-            assertTrue(idRef.get() != 0L, "draft save should return an id")-            val loaded = runBlocking { vm.draftsActions.load(idRef.get()) }-            assertTrue(loaded?.subject == "Launchers W5", "saved draft should load, got $loaded")-            vm.draftsActions.delete(idRef.get())+        // Draft autosave (800ms debounce) should persist a draft row. Wait on+        // the terminal signal — a draft row in the store — via the shared+        // semantics pump: the collector and its debounce run on the+        // composition's scheduler, which the old waitForIdle + Thread.sleep+        // poll never drove, so under load 20 real seconds passed with the+        // debounce unfired and the test fell through to a fire-and-forget+        // direct save/delete that raced db.close() in teardown. (The draft+        // store's save/load/delete CRUD itself is pinned by+        // EmailDraftActionsTest; this test pins the composer's autosave.)+        var autosaved = false+        rule.awaitSemantics("draft autosave persists a draft row") {+            autosaved = runBlocking { db.outboxDao().getDraftsFlow().first().isNotEmpty() }+            autosaved         }+        assertTrue(autosaved, "composer autosave should persist a draft row")     } }