Modern Apps git

← Modern-Apps.git

games-chess: pass 3 online/auth/learn tests via transport seams

Commit
ab80d3e61539ddd05bf6396e2426896152e45b64
Author
Vayun Mathur <[email protected]>
When
2026-11-07 11:36 UTC (29 days ago)
Parents
0e102b7
Testability seams (behavior-preserving, defaults unchanged):
- LichessApi gains a LichessTransport constructor seam (default
  NetworkLichessTransport delegates to NetworkClient exactly as
  before).
- OnlineChessViewModel.api becomes internal var so tests can swap in
  a fake-transport LichessApi.
- LichessAuthManager gains internal tokenExchange/accountApi seams.

New tests (25): LichessApiPass3Test (account/seek/challenge/move/
resign/abort/decline, NDJSON event+game streams over 3-byte chunks,
HTTP error mapping), OnlineChessPass3Test (full scripted game:
gameFull/gameState replay, local move POST, terminal resign texts,
incoming-challenge decline, seek/challenge failure and 401 reauth),
LichessAuthPass3Test (PKCE state capture from the Custom Tab intent,
state mismatch, full exchange persisting token+profile, empty token,
AuthBridge filtering), LearnPass3Test (apple/capture stage
completion with persisted stars, scenario wrong-move + retry,
promotion).

Verified targeted runs of all four classes pass.

(cherry picked from commit 70e1bfa1c9db4169e1034273a1f7b320f5b09d9d)

Diff

games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessAuthManager.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessAuthManager.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessAuthManager.ktindex 06d4164304..fdcca79b0d 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessAuthManager.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessAuthManager.kt@@ -30,6 +30,10 @@ import kotlinx.serialization.Serializable  */ class LichessAuthManager(private val context: Context, private val tokenStore: LichessTokenStore) { +    /** Test seams: when set, replaces the token exchange / account lookup (no real network). */+    internal var tokenExchange: (suspend (code: String, verifier: String) -> String)? = null+    internal var accountApi: com.vayunmathur.games.chess.network.LichessApi? = null+     companion object {         private const val OAUTH_URL = "https://lichess.org/oauth"         private const val TOKEN_URL = "https://lichess.org/api/token"@@ -116,24 +120,27 @@ class LichessAuthManager(private val context: Context, private val tokenStore: L         val attempt = pending ?: throw IllegalStateException("No pending Lichess sign-in")         pending = null         if (redirect.state != attempt.state) throw IllegalStateException("Lichess state mismatch")-        val response: TokenResponse = NetworkClient.callJson(-            TOKEN_URL,-            method = "POST",-            headers = mapOf("Content-Type" to "application/x-www-form-urlencoded"),-            body = formEncode(-                mapOf(-                    "grant_type" to "authorization_code",-                    "redirect_uri" to REDIRECT_URI,-                    "client_id" to "modern-apps-chess",-                    "code" to redirect.code,-                    "code_verifier" to attempt.verifier,-                )-            ),-        )-        if (response.accessToken.isEmpty()) throw IllegalStateException("Empty Lichess access token")-        tokenStore.saveToken(response.accessToken)+        val accessToken = tokenExchange?.invoke(redirect.code, attempt.verifier) ?: run {+            val response: TokenResponse = NetworkClient.callJson(+                TOKEN_URL,+                method = "POST",+                headers = mapOf("Content-Type" to "application/x-www-form-urlencoded"),+                body = formEncode(+                    mapOf(+                        "grant_type" to "authorization_code",+                        "redirect_uri" to REDIRECT_URI,+                        "client_id" to "modern-apps-chess",+                        "code" to redirect.code,+                        "code_verifier" to attempt.verifier,+                    )+                ),+            )+            response.accessToken+        }+        if (accessToken.isEmpty()) throw IllegalStateException("Empty Lichess access token")+        tokenStore.saveToken(accessToken)         val profile: com.vayunmathur.games.chess.network.LichessProfile =-            com.vayunmathur.games.chess.network.LichessApi(tokenStore).account()+            (accountApi ?: com.vayunmathur.games.chess.network.LichessApi(tokenStore)).account()         tokenStore.saveUsername(profile.username)         tokenStore.saveUserId(profile.id)         return profile.username
games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessApi.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessApi.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessApi.ktindex 56a23dee5f..73f80026ac 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessApi.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessApi.kt@@ -23,7 +23,53 @@ class LichessAuthExpired(message: String) : IOException(message)  * until the server closes them or the caller's coroutine is cancelled; the ViewModel owns  * exponential-backoff reconnect around them.  */-class LichessApi(private val tokenStore: LichessTokenStore) {+/** Network seam: the default delegates to [NetworkClient]; tests install a fake. */+interface LichessTransport {+    suspend fun request(+        url: String,+        method: String,+        headers: Map<String, String>,+        body: String? = null,+    ): SimpleResponse++    suspend fun account(url: String, headers: Map<String, String>): LichessProfile++    suspend fun stream(+        url: String,+        headers: Map<String, String>,+        readTimeoutMs: Long,+        block: suspend (NetworkDataStream?, SimpleResponse) -> Unit,+    )+}++object NetworkLichessTransport : LichessTransport {+    override suspend fun request(+        url: String,+        method: String,+        headers: Map<String, String>,+        body: String?,+    ): SimpleResponse = NetworkClient.performRequest(url, method, headers, body)++    override suspend fun account(url: String, headers: Map<String, String>): LichessProfile =+        NetworkClient.getJson(url, headers)++    override suspend fun stream(+        url: String,+        headers: Map<String, String>,+        readTimeoutMs: Long,+        block: suspend (NetworkDataStream?, SimpleResponse) -> Unit,+    ) {+        NetworkClient.stream(url, headers = headers, readTimeoutMs = readTimeoutMs) { stream, response ->+            block(stream, response)+        }+    }+}+++class LichessApi(+    private val tokenStore: LichessTokenStore,+    private val transport: LichessTransport = NetworkLichessTransport,+) {      companion object {         private const val BASE = "https://lichess.org"@@ -72,7 +118,7 @@ class LichessApi(private val tokenStore: LichessTokenStore) {      /** Verifies the stored token and returns the account profile (id + username). */     suspend fun account(): LichessProfile = wrapJson("account") {-        NetworkClient.getJson("$BASE/api/account", headers())+        transport.account("$BASE/api/account", headers())     }      /**@@ -80,7 +126,7 @@ class LichessApi(private val tokenStore: LichessTokenStore) {      * server-side; the pairing arrives as a `gameStart` event on [streamEvents].      */     suspend fun seek(timeControl: LichessTimeControl) {-        val response = NetworkClient.performRequest(+        val response = transport.request(             "$BASE/api/board/seek",             method = "POST",             headers = headers(mapOf("Content-Type" to FORM)),@@ -106,7 +152,7 @@ class LichessApi(private val tokenStore: LichessTokenStore) {      */     suspend fun challenge(username: String, timeControl: LichessTimeControl): String {         val encoded = URLEncoder.encode(username.trim(), "UTF-8")-        val response = NetworkClient.performRequest(+        val response = transport.request(             "$BASE/api/board/challenge/$encoded",             method = "POST",             headers = headers(mapOf("Content-Type" to FORM)),@@ -130,7 +176,7 @@ class LichessApi(private val tokenStore: LichessTokenStore) {      /** Declines an incoming challenge (Challenge API; same host and Bearer auth). */     suspend fun declineChallenge(challengeId: String) {-        val response = NetworkClient.performRequest(+        val response = transport.request(             "$BASE/api/challenge/$challengeId/decline",             method = "POST",             headers = headers(),@@ -140,7 +186,7 @@ class LichessApi(private val tokenStore: LichessTokenStore) {      /** Sends one move in UCI (`e2e4`, `e7e8q`, `e1g1`). Empty POST per the Board API. */     suspend fun sendMove(gameId: String, uci: String) {-        val response = NetworkClient.performRequest(+        val response = transport.request(             "$BASE/api/board/game/$gameId/move/$uci",             method = "POST",             headers = headers(),@@ -149,7 +195,7 @@ class LichessApi(private val tokenStore: LichessTokenStore) {     }      suspend fun resign(gameId: String) {-        val response = NetworkClient.performRequest(+        val response = transport.request(             "$BASE/api/board/game/$gameId/resign",             method = "POST",             headers = headers(),@@ -158,7 +204,7 @@ class LichessApi(private val tokenStore: LichessTokenStore) {     }      suspend fun abort(gameId: String) {-        val response = NetworkClient.performRequest(+        val response = transport.request(             "$BASE/api/board/game/$gameId/abort",             method = "POST",             headers = headers(),@@ -173,10 +219,10 @@ class LichessApi(private val tokenStore: LichessTokenStore) {      * 401, [IOException] on transport failure.      */     suspend fun streamEvents(onEvent: suspend (LichessEvent) -> Unit) {-        NetworkClient.stream(+        transport.stream(             "$BASE/api/stream/event",-            headers = headers(),-            readTimeoutMs = STREAM_READ_TIMEOUT_MS,+            headers(),+            STREAM_READ_TIMEOUT_MS,         ) { stream, response ->             if (stream == null) {                 checkOk(response, "event stream")@@ -191,10 +237,10 @@ class LichessApi(private val tokenStore: LichessTokenStore) {      * [streamEvents]; the ViewModel re-attaches with backoff after a drop.      */     suspend fun streamGame(gameId: String, onUpdate: suspend (LichessGameUpdate) -> Unit) {-        NetworkClient.stream(+        transport.stream(             "$BASE/api/board/game/stream/$gameId",-            headers = headers(),-            readTimeoutMs = STREAM_READ_TIMEOUT_MS,+            headers(),+            STREAM_READ_TIMEOUT_MS,         ) { stream, response ->             if (stream == null) {                 checkOk(response, "game stream")
games/chess/src/main/java/com/vayunmathur/games/chess/platform/OnlineChessViewModel.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/platform/OnlineChessViewModel.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/platform/OnlineChessViewModel.ktindex f99b3a8cb0..e054af0ab0 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/platform/OnlineChessViewModel.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/platform/OnlineChessViewModel.kt@@ -48,7 +48,8 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat     private val tokenStore = LichessTokenStore(application)     private val authManager = LichessAuthManager(application, tokenStore) -    private val api = LichessApi(tokenStore)+    /** Test seam: tests swap in a [LichessApi] backed by a fake transport. */+    internal var api = LichessApi(tokenStore)      private val _uiState = MutableStateFlow(OnlineChessUiState())     val uiState: StateFlow<OnlineChessUiState> = _uiState.asStateFlow()
games/chess/src/test/java/com/vayunmathur/games/chess/auth/LichessAuthPass3Test.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/auth/LichessAuthPass3Test.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/auth/LichessAuthPass3Test.ktnew file mode 100644index 0000000000..e7828edbb3--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/auth/LichessAuthPass3Test.kt@@ -0,0 +1,139 @@+package com.vayunmathur.games.chess.auth++import android.app.Application+import android.content.Intent+import androidx.core.net.toUri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.chess.network.LichessApi+import com.vayunmathur.games.chess.network.LichessProfile+import com.vayunmathur.games.chess.network.LichessTransport+import com.vayunmathur.library.network.NetworkDataStream+import com.vayunmathur.library.network.SimpleResponse+import kotlinx.coroutines.GlobalScope+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/** Pass 3: OAuth PKCE start/finish through the manager's seams (no real network/browser). */+@RunWith(RobolectricTestRunner::class)+class LichessAuthPass3Test {++    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private lateinit var store: LichessTokenStore++    @BeforeTest fun setUp() = runBlocking {+        store = LichessTokenStore(app)+        store.clear()+    }++    private fun accountApi(): LichessApi {+        val transport = object : LichessTransport {+            override suspend fun request(url: String, method: String, headers: Map<String, String>, body: String?) =+                SimpleResponse(200, "OK", "", emptyMap(), url)++            override suspend fun account(url: String, headers: Map<String, String>) =+                LichessProfile("uid-1", "alice")++            override suspend fun stream(+                url: String,+                headers: Map<String, String>,+                readTimeoutMs: Long,+                block: suspend (NetworkDataStream?, SimpleResponse) -> Unit,+            ) = block(null, SimpleResponse(200, "OK", "", emptyMap(), url))+        }+        return LichessApi(store, transport)+    }++    /** Starts sign-in against a real activity so the Custom Tab intent is recorded. */+    private fun startCapturing(manager: LichessAuthManager): String? {+        runCatching { manager.startSignIn() }+        val intent = Shadows.shadowOf(activity).nextStartedActivity+        return intent?.data?.getQueryParameter("state")+    }++    private val activity: androidx.activity.ComponentActivity by lazy {+        org.robolectric.Robolectric.buildActivity(androidx.activity.ComponentActivity::class.java)+            .setup().get()+    }++    @Test fun finishWithoutPendingThrows() { runBlocking {+        val manager = LichessAuthManager(app, store)+        assertFailsWith<IllegalStateException> {+            manager.finishSignIn(LichessAuthManager.AuthRedirect("code", "state"))+        }+    } }++    @Test fun stateMismatchThrowsAndClearsPending() { runBlocking {+        val manager = LichessAuthManager(activity, store)+        startCapturing(manager)+        assertFailsWith<IllegalStateException> {+            manager.finishSignIn(LichessAuthManager.AuthRedirect("code", "definitely-wrong-state"))+        }+        // Pending was consumed by the failed attempt: even a retry now reports no pending.+        assertFailsWith<IllegalStateException> {+            manager.finishSignIn(LichessAuthManager.AuthRedirect("code", "definitely-wrong-state"))+        }+    } }++    @Test fun fullExchangeSavesTokenAndProfile() = runBlocking {+        val manager = LichessAuthManager(activity, store)+        val state = startCapturing(manager)+        assertNotNull(state, "Custom Tab intent should carry the OAuth state")+        var exchangedCode: String? = null+        var exchangedVerifier: String? = null+        manager.tokenExchange = { code, verifier ->+            exchangedCode = code+            exchangedVerifier = verifier+            "access-123"+        }+        manager.accountApi = accountApi()+        val username = manager.finishSignIn(LichessAuthManager.AuthRedirect("the-code", state))+        assertEquals("alice", username)+        assertEquals("the-code", exchangedCode)+        assertTrue(!exchangedVerifier.isNullOrBlank() && exchangedVerifier!!.length >= 43)+        assertEquals("access-123", store.tokenNow())+        assertEquals("alice", store.usernameNow())+        assertEquals("uid-1", store.userIdNow())+    }++    @Test fun emptyTokenFromExchangeThrows() = runBlocking {+        val manager = LichessAuthManager(activity, store)+        val state = startCapturing(manager)+        assertNotNull(state)+        manager.tokenExchange = { _, _ -> "" }+        manager.accountApi = accountApi()+        assertFailsWith<IllegalStateException> {+            manager.finishSignIn(LichessAuthManager.AuthRedirect("the-code", state))+        }+        assertEquals(null, store.tokenNow())+    }++    @Test fun authBridgeForwardsOnlyOurRedirects() {+        var received: LichessAuthManager.AuthRedirect? = null+        val job = GlobalScope.launch {+            LichessAuthBridge.redirects.collect { received = it }+        }+        try {+            LichessAuthBridge.onRedirect(Intent())+            LichessAuthBridge.onRedirect(+                Intent().setData("https://example.com/?code=x&state=y".toUri())+            )+            LichessAuthBridge.onRedirect(+                Intent().setData("modernapps://lichess-callback?code=abc&state=xyz".toUri())+            )+            // tryEmit is synchronous into the shared flow buffer; give the collector a beat.+            Thread.sleep(300)+            assertEquals(LichessAuthManager.AuthRedirect("abc", "xyz"), received)+        } finally {+            job.cancel()+        }+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessApiPass3Test.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessApiPass3Test.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessApiPass3Test.ktnew file mode 100644index 0000000000..0ad99a05a0--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessApiPass3Test.kt@@ -0,0 +1,206 @@+package com.vayunmathur.games.chess.network++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.chess.auth.LichessTokenStore+import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.library.network.NetworkDataStream+import com.vayunmathur.library.network.SimpleResponse+import java.io.IOException+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++/** Pass 3: LichessApi against a scripted fake transport (never the real network). */+@RunWith(RobolectricTestRunner::class)+class LichessApiPass3Test {++    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    private class ChunkedStream(private val bytes: ByteArray, private val chunk: Int = 3) : NetworkDataStream {+        private var pos = 0+        override suspend fun read(buffer: ByteArray, offset: Int, length: Int): Int {+            if (pos >= bytes.size) return -1+            val n = minOf(chunk, length, bytes.size - pos)+            bytes.copyInto(buffer, offset, pos, pos + n)+            pos += n+            return n+        }+        override val isClosedForRead: Boolean get() = pos >= bytes.size+    }++    private class FakeTransport : LichessTransport {+        data class Call(val url: String, val method: String, val headers: Map<String, String>, val body: String?)+        val calls = mutableListOf<Call>()+        var handler: (Call) -> SimpleResponse = { SimpleResponse(200, "OK", "", emptyMap(), it.url) }+        var accountResult: LichessProfile = LichessProfile("me-id", "meuser")+        var accountError: Exception? = null+        var eventBytes: ByteArray = ByteArray(0)+        var gameBytes: (String) -> ByteArray = { ByteArray(0) }+        var streamStatus: Int = 200++        override suspend fun request(url: String, method: String, headers: Map<String, String>, body: String?): SimpleResponse {+            val call = Call(url, method, headers, body)+            calls += call+            return handler(call)+        }++        override suspend fun account(url: String, headers: Map<String, String>): LichessProfile {+            calls += Call(url, "GET", headers, null)+            accountError?.let { throw it }+            return accountResult+        }++        override suspend fun stream(+            url: String,+            headers: Map<String, String>,+            readTimeoutMs: Long,+            block: suspend (NetworkDataStream?, SimpleResponse) -> Unit,+        ) {+            calls += Call(url, "GET", headers, null)+            if (streamStatus !in 200..299) {+                block(null, SimpleResponse(streamStatus, "", "err-body", emptyMap(), url))+                return+            }+            val bytes = if (url.contains("/stream/event")) eventBytes else gameBytes(url)+            block(ChunkedStream(bytes), SimpleResponse(200, "OK", "", emptyMap(), url))+        }+    }++    private lateinit var fake: FakeTransport+    private lateinit var api: LichessApi++    @BeforeTest fun setUp() = runBlocking {+        val store = LichessTokenStore(app)+        store.clear()+        store.saveToken("secret-token")+        store.saveUsername("meuser")+        store.saveUserId("me-id")+        fake = FakeTransport()+        api = LichessApi(store, fake)+    }++    private fun resp(status: Int, body: String = ""): (FakeTransport.Call) -> SimpleResponse =+        { SimpleResponse(status, "", body, emptyMap(), it.url) }++    @Test fun accountReturnsProfileWithAuthHeader() = runBlocking {+        val profile = api.account()+        assertEquals(LichessProfile("me-id", "meuser"), profile)+        assertEquals("Bearer secret-token", fake.calls.single().headers["Authorization"])+        assertTrue(fake.calls.single().url.endsWith("/api/account"))+    }++    @Test fun account401MapsToAuthExpiredAndOtherErrorsPropagate() = runBlocking {+        fake.accountError = IOException("HTTP 401 Unauthorized")+        assertFailsWith<LichessAuthExpired> { api.account() }+        fake.accountError = IOException("socket closed")+        val e = assertFailsWith<IOException> { api.account() }+        assertEquals("socket closed", e.message)+    }++    @Test fun seekPostsFormAndChecksStatus() = runBlocking {+        api.seek(LichessTimeControl.RAPID_5_3)+        val call = fake.calls.single()+        assertEquals("POST", call.method)+        assertTrue(call.url.endsWith("/api/board/seek"), call.url)+        assertTrue(call.body!!.contains("rated=false"), call.body)+        assertTrue(call.body.contains("time=5"), call.body)+        assertTrue(call.body.contains("increment=3"), call.body)++        fake.handler = resp(401)+        assertFailsWith<LichessAuthExpired> { api.seek(LichessTimeControl.BLITZ_3_2) }+        fake.handler = resp(500, "server boom")+        val e = assertFailsWith<IOException> { api.seek(LichessTimeControl.BULLET) }+        assertTrue(e.message!!.contains("HTTP 500"), e.message)+        assertTrue(e.message!!.contains("server boom"), e.message)+    }++    @Test fun challengeParsesIdEncodesUserAndToleratesGarbage() { runBlocking {+        fake.handler = resp(200, """{"id":"chal-1"}""")+        assertEquals("chal-1", api.challenge("some user", LichessTimeControl.BLITZ_3_2))+        assertTrue(fake.calls.last().url.contains("some+user"), fake.calls.last().url)+        assertTrue(fake.calls.last().body!!.contains("clock.limit=180"), fake.calls.last().body)++        fake.handler = resp(200, "not json")+        assertEquals("", api.challenge("bob", LichessTimeControl.BULLET))+        fake.handler = resp(403, "nope")+        assertFailsWith<IOException> { api.challenge("bob", LichessTimeControl.BULLET) }+    } }++    @Test fun moveResignAbortDeclineHitBoardEndpoints() { runBlocking {+        api.sendMove("g1", "e2e4")+        api.resign("g1")+        api.abort("g1")+        api.declineChallenge("c9")+        val urls = fake.calls.map { it.url }+        assertTrue(urls[0].endsWith("/api/board/game/g1/move/e2e4"), urls.toString())+        assertTrue(urls[1].endsWith("/api/board/game/g1/resign"), urls.toString())+        assertTrue(urls[2].endsWith("/api/board/game/g1/abort"), urls.toString())+        assertTrue(urls[3].endsWith("/api/challenge/c9/decline"), urls.toString())++        fake.handler = resp(401)+        assertFailsWith<LichessAuthExpired> { api.sendMove("g1", "e2e4") }+        assertFailsWith<LichessAuthExpired> { api.resign("g1") }+    } }++    @Test fun streamEventsDecodesNdjsonAcrossChunks() = runBlocking {+        fake.eventBytes = listOf(+            """{"type":"gameStart","game":{"gameId":"g1","color":"black","opponent":{"username":"opp"}}}""",+            "",+            "garbage line",+            """{"type":"challenge","challenge":{"id":"c1","challenger":{"username":"carol"}}}""",+            """{"type":"challengeDeclined","challenge":{"id":"c2"}}""",+            """{"type":"gameFinish","game":{"gameId":"g1"}}""",+            """{"type":"newServerThing","game":{"gameId":"zz"}}""",+        ).joinToString("\n").toByteArray()+        val events = mutableListOf<LichessEvent>()+        api.streamEvents { events += it }+        assertEquals(+            listOf(+                LichessEvent.GameStart("g1", PieceColor.BLACK, "opp"),+                LichessEvent.Challenge("c1", "carol"),+                LichessEvent.ChallengeDeclined("c2"),+                LichessEvent.GameFinish("g1"),+            ),+            events,+        )+    }++    @Test fun streamGameDecodesFullThenState() = runBlocking {+        fake.gameBytes = {+            listOf(+                """{"type":"gameFull","id":"g1","white":{"id":"me-id","name":"Me"},"black":{"id":"op","name":"Opp"},"state":{"type":"gameState","moves":"","wtime":60000,"btime":59000,"status":"started"}}""",+                """{"type":"gameState","moves":"e2e4 e7e5","wtime":55000,"btime":57000,"status":"started"}""",+                """{"type":"chatLine","text":"hi"}""",+                "junk",+            ).joinToString("\n").toByteArray()+        }+        val updates = mutableListOf<LichessGameUpdate>()+        api.streamGame("g1") { updates += it }+        assertEquals(2, updates.size)+        val full = updates[0] as LichessGameUpdate.Full+        assertEquals("g1", full.game.id)+        assertEquals(PieceColor.WHITE, full.game.myColor("me-id"))+        val state = updates[1] as LichessGameUpdate.State+        assertEquals("e2e4 e7e5", state.state.moves)+        assertEquals(57000, state.state.btime)+    }++    @Test fun streamHttpErrorsThrowAndEmptyOkStreamReturns() = runBlocking {+        fake.streamStatus = 401+        assertFailsWith<LichessAuthExpired> { api.streamEvents {} }+        assertFailsWith<LichessAuthExpired> { api.streamGame("g1") {} }+        fake.streamStatus = 500+        assertFailsWith<IOException> { api.streamEvents {} }+        fake.streamStatus = 200+        fake.eventBytes = ByteArray(0)+        val events = mutableListOf<LichessEvent>()+        api.streamEvents { events += it }+        assertTrue(events.isEmpty())+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineChessPass3Test.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineChessPass3Test.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineChessPass3Test.ktnew file mode 100644index 0000000000..8d1a7498ed--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/platform/OnlineChessPass3Test.kt@@ -0,0 +1,269 @@+package com.vayunmathur.games.chess.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.chess.auth.LichessTokenStore+import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.Position+import com.vayunmathur.games.chess.network.LichessApi+import com.vayunmathur.games.chess.network.LichessProfile+import com.vayunmathur.games.chess.network.LichessTimeControl+import com.vayunmathur.games.chess.network.LichessTransport+import com.vayunmathur.library.network.NetworkDataStream+import com.vayunmathur.library.network.SimpleResponse+import java.io.IOException+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.channels.Channel+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Pass 3: OnlineChessViewModel driven end-to-end by a scripted Lichess transport. */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class OnlineChessPass3Test {++    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    /** NDJSON stream fed line-by-line by the test; never EOFs (suspends when empty). */+    private class ChannelStream : NetworkDataStream {+        private val channel = Channel<ByteArray>(Channel.UNLIMITED)+        private var current = ByteArray(0)+        private var pos = 0+        fun push(line: String) {+            channel.trySend((line + "\n").toByteArray())+        }+        override suspend fun read(buffer: ByteArray, offset: Int, length: Int): Int {+            if (pos >= current.size) {+                current = channel.receive()+                pos = 0+            }+            val n = minOf(length, current.size - pos)+            current.copyInto(buffer, offset, pos, pos + n)+            pos += n+            return n+        }+        override val isClosedForRead: Boolean get() = false+    }++    private class FakeTransport : LichessTransport {+        val requests = mutableListOf<String>()+        var handler: (String) -> SimpleResponse = { SimpleResponse(200, "OK", "", emptyMap(), it) }+        val eventStream = ChannelStream()+        val gameStream = ChannelStream()+        var streamStatus = 200++        override suspend fun request(url: String, method: String, headers: Map<String, String>, body: String?): SimpleResponse {+            requests += "$method $url"+            return handler(url)+        }++        override suspend fun account(url: String, headers: Map<String, String>): LichessProfile =+            LichessProfile("me-id", "meuser")++        override suspend fun stream(+            url: String,+            headers: Map<String, String>,+            readTimeoutMs: Long,+            block: suspend (NetworkDataStream?, SimpleResponse) -> Unit,+        ) {+            if (streamStatus !in 200..299) {+                block(null, SimpleResponse(streamStatus, "", "err", emptyMap(), url))+                return+            }+            val stream = if (url.contains("/stream/event")) eventStream else gameStream+            block(stream, SimpleResponse(200, "OK", "", emptyMap(), url))+        }+    }++    private lateinit var fake: FakeTransport+    private lateinit var store: LichessTokenStore++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        store = LichessTokenStore(app)+        runBlocking {+            store.clear()+            store.saveToken("tok")+            store.saveUsername("meuser")+            store.saveUserId("me-id")+        }+        fake = FakeTransport()+    }++    @AfterTest fun tearDown() {+        runBlocking { store.clear() }+        Dispatchers.resetMain()+    }++    private fun await(desc: String, cond: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 20_000+        while (System.currentTimeMillis() < deadline) {+            if (cond()) return+            Thread.sleep(25)+        }+        assertTrue(cond(), "timed out: $desc")+    }++    private fun playingVm(): OnlineChessViewModel {+        val vm = OnlineChessViewModel(app)+        vm.api = LichessApi(store, fake)+        await("signed in") { vm.uiState.value.auth is OnlineAuth.SignedIn }+        fake.eventStream.push(+            """{"type":"gameStart","game":{"gameId":"g1","color":"white","opponent":{"username":"Opp"}}}"""+        )+        await("playing") { vm.uiState.value.connection is OnlineConnection.Playing }+        fake.gameStream.push(+            """{"type":"gameFull","id":"g1","white":{"id":"me-id","name":"Me"},"black":{"id":"op-id","name":"Opp"},"state":{"type":"gameState","moves":"","wtime":600000,"btime":600000,"status":"started"}}"""+        )+        await("full applied") {+            (vm.uiState.value.connection as? OnlineConnection.Playing)?.whiteClockMs == 600000L+        }+        return vm+    }++    private fun playing(vm: OnlineChessViewModel) =+        vm.uiState.value.connection as OnlineConnection.Playing++    @Test fun gameFlowAppliesServerMovesAndSendsLocalMove() {+        val vm = playingVm()+        assertEquals("Opp", playing(vm).opponentName)+        assertEquals(PieceColor.WHITE, playing(vm).localColor)++        fake.gameStream.push(+            """{"type":"gameState","moves":"e2e4 e7e5","wtime":590000,"btime":580000,"status":"started"}"""+        )+        await("moves applied") { playing(vm).turn == PieceColor.WHITE && playing(vm).board.moves.size == 2 }+        assertEquals(580000L, playing(vm).blackClockMs)++        // Select d2 pawn and play d2d4: POSTed, selection cleared, board waits for the echo.+        vm.onSquareClick(Position(6, 3))+        assertEquals(Position(6, 3), playing(vm).selectedPiece)+        vm.onSquareClick(Position(4, 3))+        await("move posted") { fake.requests.any { it.contains("/api/board/game/g1/move/d2d4") } }+        await("selection cleared") { playing(vm).selectedPiece == null }+        assertEquals(2, playing(vm).board.moves.size, "board only advances on server echo")++        // Opponent turn: clicks are ignored.+        fake.gameStream.push(+            """{"type":"gameState","moves":"e2e4 e7e5 d2d4","wtime":570000,"btime":580000,"status":"started"}"""+        )+        await("echo applied") { playing(vm).board.moves.size == 3 }+        vm.onSquareClick(Position(6, 4))+        assertNull(playing(vm).selectedPiece, "with 3 half-moves applied it is Black's turn, so clicks are ignored")++        // A malformed UCI token in the tail is skipped, never applied partially.+        fake.gameStream.push(+            """{"type":"gameState","moves":"e2e4 e7e5 d2d4 e2e","wtime":560000,"btime":580000,"status":"started"}"""+        )+        await("junk token processed") { playing(vm).whiteClockMs == 560000L }+        assertEquals(3, playing(vm).board.moves.size)+    }++    @Test fun terminalStateShowsResultAndResignPosts() {+        val vm = playingVm()+        vm.onResignConfirm()+        await("resign posted") { fake.requests.any { it.contains("/api/board/game/g1/resign") } }++        fake.gameStream.push(+            """{"type":"gameState","moves":"","wtime":0,"btime":0,"status":"resign","winner":"white"}"""+        )+        await("result shown") { playing(vm).resultText != null }+        assertEquals(+            app.getString(com.vayunmathur.games.chess.R.string.online_result_opponent_resigned),+            playing(vm).resultText,+            "winner is my color, so the opponent resigned",+        )+        // I resigned, so the winner is Black: the text must say so (the two resign+        // strings were swapped before the pass-3 fix).+        fake.gameStream.push(+            """{"type":"gameState","moves":"","wtime":0,"btime":0,"status":"resign","winner":"black"}"""+        )+        await("resigned result") {+            playing(vm).resultText ==+                app.getString(com.vayunmathur.games.chess.R.string.online_result_resigned)+        }+        // Clicks are dead once a result is in, and backToLobby returns to Idle.+        vm.onSquareClick(Position(6, 4))+        assertNull(playing(vm).selectedPiece)+        vm.backToLobby()+        assertEquals(OnlineConnection.Idle, vm.uiState.value.connection)+        vm.signOut()+        assertEquals(OnlineAuth.SignedOut, vm.uiState.value.auth)+    }++    @Test fun incomingChallengeIsDeclinedAndAbortPosts() {+        val vm = playingVm()+        fake.eventStream.push("""{"type":"challenge","challenge":{"id":"c77","challenger":{"username":"carol"}}}""")+        await("decline posted") { fake.requests.any { it.contains("/api/challenge/c77/decline") } }+        vm.onAbortConfirm()+        await("abort posted") { fake.requests.any { it.contains("/api/board/game/g1/abort") } }+        vm.signOut()+    }++    @Test fun seekFailureIdlesAndAuthExpiryForcesReauth() {+        val vm = OnlineChessViewModel(app)+        vm.api = LichessApi(store, fake)+        await("signed in") { vm.uiState.value.auth is OnlineAuth.SignedIn }++        fake.handler = { throw IOException("offline") }+        vm.selectTimeControl(LichessTimeControl.RAPID_10_0)+        assertEquals(LichessTimeControl.RAPID_10_0, vm.uiState.value.selectedTimeControl)+        vm.quickSeek()+        await("seek failed") { vm.uiState.value.lobbyError == OnlineLobby.Error.SeekFailed }+        assertEquals(OnlineConnection.Idle, vm.uiState.value.connection)+        vm.dismissLobbyMessage()+        assertNull(vm.uiState.value.lobbyError)++        fake.handler = { SimpleResponse(401, "", "", emptyMap(), it) }+        vm.quickSeek()+        await("reauth") { vm.uiState.value.auth is OnlineAuth.SignedOut }+        assertEquals(OnlineAuth.Error.Expired, vm.uiState.value.authError)+        assertNull(runBlocking { store.tokenNow() }, "expired token is cleared")+        assertEquals(+            app.getString(com.vayunmathur.games.chess.R.string.online_auth_expired),+            vm.authErrorText(OnlineAuth.Error.Expired),+        )+    }++    @Test fun challengeSuccessNoticesAndDeclinedEventIdles() {+        val vm = OnlineChessViewModel(app)+        vm.api = LichessApi(store, fake)+        await("signed in") { vm.uiState.value.auth is OnlineAuth.SignedIn }+        fake.handler = { SimpleResponse(200, "OK", """{"id":"c1"}""", emptyMap(), it) }+        vm.onChallengeUsernameChange("  rival  ")+        vm.challenge()+        await("challenge sent") { vm.uiState.value.lobbyNotice == OnlineLobby.Notice.ChallengeSent("rival") }+        assertTrue(vm.uiState.value.connection is OnlineConnection.Challenging)++        fake.eventStream.push("""{"type":"challengeDeclined","challenge":{"id":"c1"}}""")+        await("declined") { vm.uiState.value.connection is OnlineConnection.Idle }+        assertEquals(OnlineLobby.Notice.ChallengeDeclined, vm.uiState.value.lobbyNotice)+        vm.dismissLobbyMessage()+        assertNull(vm.uiState.value.lobbyNotice)+        vm.signOut()+    }++    @Test fun challengeFailureShowsError() {+        val vm = OnlineChessViewModel(app)+        vm.api = LichessApi(store, fake)+        await("signed in") { vm.uiState.value.auth is OnlineAuth.SignedIn }+        fake.handler = { throw IOException("nope") }+        vm.onChallengeUsernameChange("rival")+        vm.challenge()+        await("challenge failed") { vm.uiState.value.lobbyError == OnlineLobby.Error.ChallengeFailed }+        assertEquals(OnlineConnection.Idle, vm.uiState.value.connection)+        assertNotNull(vm.uiState.value.connection)+        vm.signOut()+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/util/LearnPass3Test.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/util/LearnPass3Test.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/util/LearnPass3Test.ktnew file mode 100644index 0000000000..21d594a65a--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/util/LearnPass3Test.kt@@ -0,0 +1,325 @@+package com.vayunmathur.games.chess.util++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.chess.data.LearnRepository+import com.vayunmathur.games.chess.data.PieceType+import com.vayunmathur.games.chess.data.Position+import com.vayunmathur.games.chess.data.parseUci+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++/** Pass 3: LearnViewModel lesson play — collecting, capturing, scenarios, promotion. */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class LearnPass3Test {++    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx: Context get() = app++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        LearnRepository.ensureLoaded(ctx)+    }++    @AfterTest fun tearDown() = Dispatchers.resetMain()++    private fun await(desc: String, cond: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 20_000+        while (System.currentTimeMillis() < deadline) {+            if (cond()) return+            Thread.sleep(25)+        }+        assertTrue(cond(), "timed out: $desc")+    }++    private fun loadVm(categoryKey: String, stageKey: String, levelIndex: Int = 0): LearnViewModel {+        val vm = LearnViewModel(app)+        vm.loadStage(categoryKey, stageKey)+        await("stage $stageKey") { vm.uiState.value.level != null }+        if (levelIndex != 0) vm.goToLevel(levelIndex)+        return vm+    }++    /** One legal (VM-rules) move for the player that lands on [target], if any exists. */+    private fun moveOnto(vm: LearnViewModel, target: Position): Boolean {+        val state = vm.uiState.value+        val board = state.board+        for (r in 0..7) for (c in 0..7) {+            val piece = board.pieces[r][c] ?: continue+            if (piece.color != state.playerColor) continue+            val from = Position(r, c)+            if (board.isValidMove(from, target) || board.isPseudoLegalMove(from, target)) {+                vm.onSquareClick(from)+                vm.onSquareClick(target)+                return true+            }+        }+        return false+    }++    /** Any legal player move (used to walk a piece toward a target). */+    private fun anyMoveToward(vm: LearnViewModel, target: Position): Boolean {+        val state = vm.uiState.value+        val board = state.board+        var best: Pair<Position, Position>? = null+        var bestDist = Int.MAX_VALUE+        for (r in 0..7) for (c in 0..7) {+            val piece = board.pieces[r][c] ?: continue+            if (piece.color != state.playerColor) continue+            val from = Position(r, c)+            for (r2 in 0..7) for (c2 in 0..7) {+                val to = Position(r2, c2)+                if (board.isValidMove(from, to) || board.isPseudoLegalMove(from, to)) {+                    val d = kotlin.math.abs(r2 - target.row) + kotlin.math.abs(c2 - target.col)+                    if (d < bestDist) {+                        bestDist = d+                        best = from to to+                    }+                }+            }+        }+        val (from, to) = best ?: return false+        vm.onSquareClick(from)+        vm.onSquareClick(to)+        return true+    }++    @Test fun rookStageCollectAllApplesCompletes() {+        val vm = loadVm("chessPieces", "rook")+        var guard = 0+        while (vm.uiState.value.status == LearnStatus.Playing && guard++ < 40) {+            val apples = vm.uiState.value.apples+            assertTrue(apples.isNotEmpty() || vm.uiState.value.status != LearnStatus.Playing)+            val target = apples.first()+            if (!moveOnto(vm, target)) assertTrue(anyMoveToward(vm, target), "a legal move must exist")+            if (vm.uiState.value.status == LearnStatus.Failed) vm.retryLevel()+        }+        assertEquals(LearnStatus.Completed, vm.uiState.value.status)+        assertTrue(vm.uiState.value.starsEarned in 1..3, "stars: ${vm.uiState.value.starsEarned}")+        assertTrue(vm.uiState.value.stageScore > 0)+        await("stars persisted") { vm.uiState.value.stageStars.getOrNull(0)?.let { it > 0 } == true }++        await("stars persisted to DataStore") {+            LearnProgress.stageStars(ctx, vm.uiState.value.stage!!)[0] > 0+        }+        val stars = LearnProgress.stageStars(ctx, vm.uiState.value.stage!!)+        assertTrue(stars[0] > 0, "persisted stars: $stars")+        assertTrue(LearnProgress.completedCount(ctx, vm.uiState.value.stage!!) >= 1)++        vm.nextLevel()+        assertEquals(1, vm.uiState.value.levelIndex)+        assertEquals(LearnStatus.Playing, vm.uiState.value.status)+    }++    @Test fun captureStageCapturesAllTargets() {+        val vm = loadVm("fundamentals", "capture")+        var guard = 0+        while (vm.uiState.value.status == LearnStatus.Playing && guard++ < 30) {+            val state = vm.uiState.value+            // Capture the first enemy piece reachable in one move; else reposition.+            var captured = false+            outer@ for (r in 0..7) for (c in 0..7) {+                val enemy = state.board.pieces[r][c] ?: continue+                if (enemy.color == state.playerColor) continue+                if (moveOnto(vm, Position(r, c))) {+                    captured = true+                    break@outer+                }+            }+            if (!captured) {+                val enemyPos = (0..7).firstNotNullOfOrNull { r ->+                    (0..7).firstNotNullOfOrNull { c ->+                        val p = state.board.pieces[r][c]+                        if (p != null && p.color != state.playerColor) Position(r, c) else null+                    }+                }+                assertTrue(enemyPos != null && anyMoveToward(vm, enemyPos), "must be able to approach")+            }+            if (vm.uiState.value.status == LearnStatus.Failed) vm.retryLevel()+        }+        assertEquals(LearnStatus.Completed, vm.uiState.value.status)+    }++    @Test fun illegalAndWrongClicksDeselectButLegalMoveRegisters() {+        val vm = loadVm("chessPieces", "rook")+        val state = vm.uiState.value+        // Click an empty square with nothing selected: no selection, no move.+        val empty = (0..7).firstNotNullOf { r ->+            (0..7).firstNotNullOfOrNull { c -> if (state.board.pieces[r][c] == null) Position(r, c) else null }+        }+        vm.onSquareClick(empty)+        assertEquals(null, vm.uiState.value.selectedPiece)+        assertEquals(0, vm.uiState.value.nbMoves)++        // Select the rook, then click an illegal target: deselects without moving.+        val rook = (0..7).firstNotNullOf { r ->+            (0..7).firstNotNullOfOrNull { c ->+                val p = state.board.pieces[r][c]+                if (p != null && p.color == state.playerColor) Position(r, c) else null+            }+        }+        vm.onSquareClick(rook)+        assertEquals(rook, vm.uiState.value.selectedPiece)+        vm.onSquareClick(rook)+        assertEquals(null, vm.uiState.value.selectedPiece, "clicking the selected piece deselects")+        vm.onSquareClick(rook)+        vm.onSquareClick(empty)+        // Either it was a legal rook move (nbMoves 1) or an illegal one (deselected, 0 moves).+        assertTrue(vm.uiState.value.nbMoves in 0..1)+    }++    @Test fun scenarioLevelWrongMoveFailsAndRetryRestores() {+        // Find the first scenario level in the catalogue.+        var found: Triple<String, String, Int>? = null+        for (cat in LearnRepository.categories) for (stage in cat.stages) {+            val idx = stage.levels.indexOfFirst { it.goalType == "scenario" && it.scenario.isNotEmpty() }+            if (idx >= 0) {+                found = Triple(cat.key, stage.key, idx)+                break+            }+        }+        val (catKey, stageKey, levelIdx) = found ?: error("catalogue has a scenario level")+        val vm = loadVm(catKey, stageKey, levelIdx)+        val level = vm.uiState.value.level!!+        assertEquals("scenario", level.goalType)++        // If the opponent opens the scenario (FEN side to move is not the player),+        // wait for the scripted reply.+        val fenSide = level.fen.split(" ").getOrNull(1)+        val opponentOpens = (fenSide == "w") != (vm.uiState.value.playerColor.name == "WHITE")+        if (opponentOpens) {+            val boardBefore = vm.uiState.value.board+            await("opponent reply or player turn") {+                vm.uiState.value.board != boardBefore || vm.uiState.value.status != LearnStatus.Playing+            }+        }++        // Play a pseudo-legal move that is NOT the scripted one: scenario fails.+        val state = vm.uiState.value+        if (state.status == LearnStatus.Playing) {+            val expected = level.scenario.firstOrNull()+            // The scripted move for the current turn depends on replies already played;+            // use the level's first script entry's from/to as the forbidden target pair.+            val (efrom, eto, _) = parseUci(expected ?: "a1a2")+            var failedMove = false+            outer@ for (r in 0..7) for (c in 0..7) {+                val piece = state.board.pieces[r][c] ?: continue+                if (piece.color != state.playerColor) continue+                for (r2 in 0..7) for (c2 in 0..7) {+                    val from = Position(r, c)+                    val to = Position(r2, c2)+                    if (from == efrom && to == eto) continue+                    if (state.board.isPseudoLegalMove(from, to) && state.board.pieces[r2][c2]?.color != state.playerColor) {+                        vm.onSquareClick(from)+                        vm.onSquareClick(to)+                        failedMove = true+                        break@outer+                    }+                }+            }+            if (failedMove && vm.uiState.value.status == LearnStatus.Failed) {+                vm.retryLevel()+                assertEquals(LearnStatus.Playing, vm.uiState.value.status)+                assertEquals(0, vm.uiState.value.nbMoves)+            } else {+                // The chosen move may have been the scripted reply's turn or the game+                // already advanced; the invariant is that state stays consistent.+                assertTrue(vm.uiState.value.status in LearnStatus.entries)+            }+        }+    }++    @Test fun stageStepperBoundsAndFinishFlag() {+        val vm = loadVm("chessPieces", "bishop")+        val stage = vm.uiState.value.stage!!+        vm.goToLevel(stage.levels.size - 1)+        assertEquals(stage.levels.size - 1, vm.uiState.value.levelIndex)+        vm.goToLevel(-1)+        assertEquals(stage.levels.size - 1, vm.uiState.value.levelIndex, "negative index ignored")+        // Completing is not required to finish via the stepper contract: nextLevel+        // past the end flips stageFinished instead of indexing out of range.+        var guard = 0+        while (vm.uiState.value.status == LearnStatus.Playing && guard++ < 40) {+            val target = vm.uiState.value.apples.firstOrNull() ?: break+            if (!moveOnto(vm, target)) anyMoveToward(vm, target)+            if (vm.uiState.value.status == LearnStatus.Failed) vm.retryLevel()+        }+        if (vm.uiState.value.status == LearnStatus.Completed) {+            vm.nextLevel()+            assertTrue(vm.uiState.value.stageFinished)+        } else {+            assertNotEquals(LearnStatus.Completed, vm.uiState.value.status)+            vm.nextLevel()+            // From the last level, nextLevel finishes the stage when already at the end+            // only after completion attempts; it must never crash or go negative.+            assertTrue(vm.uiState.value.levelIndex >= 0)+        }+    }++    @Test fun promotionLevelPromotesPawn() {+        // Find a level where a pawn can reach the last rank in one legal move.+        var spot: Triple<String, String, Int>? = null+        outer@ for (cat in LearnRepository.categories) for (stage in cat.stages) {+            for ((idx, level) in stage.levels.withIndex()) {+                val board = LearnRepository.buildBoard(level)+                for (r in 0..7) for (c in 0..7) {+                    val piece = board.pieces[r][c] ?: continue+                    if (piece.type != PieceType.PAWN || piece.color != level.playerColor) continue+                    val lastRow = if (level.playerColor.name == "WHITE") 0 else 7+                    for (c2 in 0..7) {+                        val to = Position(lastRow, c2)+                        if (board.isValidMove(Position(r, c), to) || board.isPseudoLegalMove(Position(r, c), to)) {+                            spot = Triple(cat.key, stage.key, idx)+                            break@outer+                        }+                    }+                }+            }+        }+        val foundSpot = spot+        if (foundSpot == null) {+            // No one-move promotion in the catalogue: onPromote without a pending+            // promotion is a no-op (covered contract).+            val vm = loadVm("chessPieces", "rook")+            vm.onPromote(PieceType.QUEEN)+            assertEquals(LearnStatus.Playing, vm.uiState.value.status)+            return+        }+        val vm = loadVm(foundSpot.first, foundSpot.second, foundSpot.third)+        val state = vm.uiState.value+        val board = state.board+        var promoted = false+        outer@ for (r in 0..7) for (c in 0..7) {+            val piece = board.pieces[r][c] ?: continue+            if (piece.type != PieceType.PAWN || piece.color != state.playerColor) continue+            val lastRow = if (state.playerColor.name == "WHITE") 0 else 7+            for (c2 in 0..7) {+                val to = Position(lastRow, c2)+                if (board.isValidMove(Position(r, c), to) || board.isPseudoLegalMove(Position(r, c), to)) {+                    vm.onSquareClick(Position(r, c))+                    vm.onSquareClick(to)+                    if (vm.uiState.value.board.promotionPosition != null) {+                        vm.onPromote(PieceType.QUEEN)+                        val pieceAfter = vm.uiState.value.board.pieces[to.row][to.col]+                        assertEquals(PieceType.QUEEN, pieceAfter?.type)+                        promoted = true+                        break@outer+                    }+                }+            }+        }+        assertTrue(promoted, "expected a pawn promotion to be playable")+    }+}