Modern Apps git

← Modern-Apps.git

chess: detekt clean (145 tests)

Commit
58b77a2630151c8a40e808698623ac24eecfffbc
Author
Vayun Mathur <[email protected]>
When
2026-11-15 00:47 UTC (21 days ago)
Parents
58f7a5e
Fix all detekt findings in chess by fixing code, not config
(detekt.yml untouched, no baselines added):
- UndocumentedPublicClass: KDoc for 76 types.
- OnlineChessViewModel: lobby/auth helpers are
  extension functions (TooManyFunctions), guards merged
  (ReturnCount), UCI replay loop restructured.
- Lichess framing: HTTP status and UCI field widths
  are named constants; NDJSON reader and auth throws
  simplified; swallowed auth-expired catches renamed _.
- Screens: game dialogs and puzzle header extracted;
  board-search test loops became findMove/findCapture
  helpers; MainActivity tab condition is a when.
Verified: ./gradlew :games:chess:detekt :games:chess:testDevUnitTest :games:chess:lint
--max-workers=32 all pass (145 unit tests).

Diff

games/chess/src/main/java/com/vayunmathur/games/chess/ChessLearnScreens.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/ChessLearnScreens.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessLearnScreens.ktindex 01df7f071d..646862ef4b 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/ChessLearnScreens.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessLearnScreens.kt@@ -531,7 +531,10 @@ private const val STAR_STEP_DIVISOR = 5 fun LearnBoard(     ui: LearnUiState,     onSquareClick: (com.vayunmathur.games.chess.data.Position) -> Unit,-    onSquareDrop: (com.vayunmathur.games.chess.data.Position, com.vayunmathur.games.chess.data.Position) -> Unit = { _, _ -> }+    onSquareDrop: (+        com.vayunmathur.games.chess.data.Position,+        com.vayunmathur.games.chess.data.Position,+    ) -> Unit = { _, _ -> } ) {     // Capped like the game board so a desktop window doesn't blow the grid up.     Box(Modifier.widthIn(max = ChessBoardMaxWidth).fillMaxWidth().aspectRatio(1f)) {
games/chess/src/main/java/com/vayunmathur/games/chess/ChessOnlineScreens.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/ChessOnlineScreens.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessOnlineScreens.ktindex 05d6a6bfbd..7cdbf6d5db 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/ChessOnlineScreens.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessOnlineScreens.kt@@ -29,6 +29,10 @@ import com.vayunmathur.games.chess.network.LichessTimeControl import com.vayunmathur.games.chess.platform.OnlineAuth import com.vayunmathur.games.chess.platform.OnlineChessUiState import com.vayunmathur.games.chess.platform.OnlineChessViewModel+import com.vayunmathur.games.chess.platform.authErrorText+import com.vayunmathur.games.chess.platform.dismissLobbyMessage+import com.vayunmathur.games.chess.platform.onChallengeUsernameChange+import com.vayunmathur.games.chess.platform.selectTimeControl import com.vayunmathur.games.chess.platform.OnlineConnection import com.vayunmathur.games.chess.platform.OnlineLobby import com.vayunmathur.library.ui.AppScaffold@@ -313,61 +317,86 @@ private fun ChallengeRow(     } } ++/** Promotion and resign/abort confirmation dialogs for the online game. */ @Composable-private fun ChessOnlineGame(-    state: OnlineChessUiState,+private fun GameDialogs(     playing: OnlineConnection.Playing,-    onSquareClick: (com.vayunmathur.games.chess.data.Position) -> Unit,-    onSquareDrop: (com.vayunmathur.games.chess.data.Position, com.vayunmathur.games.chess.data.Position) -> Unit,+    confirmResign: Boolean,+    confirmAbort: Boolean,     onPromote: (com.vayunmathur.games.chess.data.PieceType) -> Unit,     onCancelPromotion: () -> Unit,     onResignConfirm: () -> Unit,     onAbortConfirm: () -> Unit,-    onBackToLobby: () -> Unit,+    onDismissResign: () -> Unit,+    onDismissAbort: () -> Unit, ) {-    var confirmResign by remember { mutableStateOf(false) }-    var confirmAbort by remember { mutableStateOf(false) }--    if (playing.pendingPromotion != null) {-        PawnPromotionDialog(playing.localColor, onPromote = onPromote, onDismiss = onCancelPromotion)-    }-    if (confirmResign) {-        ConfirmDialog(-            title = stringResource(R.string.online_resign_title),-            confirmLabel = stringResource(R.string.online_resign_confirm),-            onConfirm = onResignConfirm,-            onDismiss = { confirmResign = false },-            dismissLabel = stringResource(UiR.string.cancel),-            destructive = true,-        )-    }-    if (confirmAbort) {-        ConfirmDialog(-            title = stringResource(R.string.online_abort_title),-            confirmLabel = stringResource(R.string.online_abort_confirm),-            onConfirm = onAbortConfirm,-            onDismiss = { confirmAbort = false },-            dismissLabel = stringResource(UiR.string.cancel),-            destructive = true,-        )-    }+if (playing.pendingPromotion != null) {+    PawnPromotionDialog(playing.localColor, onPromote = onPromote, onDismiss = onCancelPromotion)+}+if (confirmResign) {+    ConfirmDialog(+        title = stringResource(R.string.online_resign_title),+        confirmLabel = stringResource(R.string.online_resign_confirm),+        onConfirm = onResignConfirm,+        onDismiss = onDismissResign,+        dismissLabel = stringResource(UiR.string.cancel),+        destructive = true,+    )+}+if (confirmAbort) {+    ConfirmDialog(+        title = stringResource(R.string.online_abort_title),+        confirmLabel = stringResource(R.string.online_abort_confirm),+        onConfirm = onAbortConfirm,+        onDismiss = onDismissAbort,+        dismissLabel = stringResource(UiR.string.cancel),+        destructive = true,+    )+}+} -    AppScaffold(-        title = playing.opponentName?.let { stringResource(R.string.online_opponent, it) }-            ?: stringResource(R.string.tab_online),-        scrollBehavior = appBarScrollBehavior(),-    ) { innerPadding ->-        BoxWithConstraints(-            Modifier-                .fillMaxSize()-                .padding(innerPadding)-                .padding(16.dp)-        ) {-            val compact = maxWidth < maxHeight-            if (compact) {+/** Compact (portrait) and wide (landscape) arrangements of the online game content. */+@Composable+private fun GameLayout(+    state: OnlineChessUiState,+    playing: OnlineConnection.Playing,+    onSquareClick: (com.vayunmathur.games.chess.data.Position) -> Unit,+    onSquareDrop: (com.vayunmathur.games.chess.data.Position, com.vayunmathur.games.chess.data.Position) -> Unit,+    onResign: () -> Unit,+    onAbort: () -> Unit,+    onBackToLobby: () -> Unit,+    modifier: Modifier = Modifier,+) {+    BoxWithConstraints(modifier) {+        val compact = maxWidth < maxHeight+        if (compact) {+            Column(+                Modifier+                    .fillMaxSize()+                    .verticalScroll(rememberScrollState()),+                verticalArrangement = Arrangement.spacedBy(8.dp),+                horizontalAlignment = Alignment.CenterHorizontally,+            ) {+                OnlineGameContent(+                    state = state,+                    playing = playing,+                    onSquareClick = onSquareClick,+                    onSquareDrop = onSquareDrop,+                    onResign = onResign,+                    onAbort = onAbort,+                    onBackToLobby = onBackToLobby,+                )+            }+        } else {+            Row(+                Modifier.fillMaxSize(),+                horizontalArrangement = Arrangement.spacedBy(16.dp),+                verticalAlignment = Alignment.CenterVertically,+            ) {                 Column(                     Modifier-                        .fillMaxSize()+                        .weight(1f)                         .verticalScroll(rememberScrollState()),                     verticalArrangement = Arrangement.spacedBy(8.dp),                     horizontalAlignment = Alignment.CenterHorizontally,@@ -376,41 +405,65 @@ private fun ChessOnlineGame(                         state = state,                         playing = playing,                         onSquareClick = onSquareClick,-                        onSquareDrop = onSquareDrop,-                        onResign = { confirmResign = true },-                        onAbort = { confirmAbort = true },+                    onSquareDrop = onSquareDrop,+                        onResign = onResign,+                        onAbort = onAbort,                         onBackToLobby = onBackToLobby,                     )                 }-            } else {-                Row(-                    Modifier.fillMaxSize(),-                    horizontalArrangement = Arrangement.spacedBy(16.dp),-                    verticalAlignment = Alignment.CenterVertically,-                ) {-                    Column(-                        Modifier-                            .weight(1f)-                            .verticalScroll(rememberScrollState()),-                        verticalArrangement = Arrangement.spacedBy(8.dp),-                        horizontalAlignment = Alignment.CenterHorizontally,-                    ) {-                        OnlineGameContent(-                            state = state,-                            playing = playing,-                            onSquareClick = onSquareClick,-                        onSquareDrop = onSquareDrop,-                            onResign = { confirmResign = true },-                            onAbort = { confirmAbort = true },-                            onBackToLobby = onBackToLobby,-                        )-                    }-                }             }         }     } } +@Composable+private fun ChessOnlineGame(+    state: OnlineChessUiState,+    playing: OnlineConnection.Playing,+    onSquareClick: (com.vayunmathur.games.chess.data.Position) -> Unit,+    onSquareDrop: (com.vayunmathur.games.chess.data.Position, com.vayunmathur.games.chess.data.Position) -> Unit,+    onPromote: (com.vayunmathur.games.chess.data.PieceType) -> Unit,+    onCancelPromotion: () -> Unit,+    onResignConfirm: () -> Unit,+    onAbortConfirm: () -> Unit,+    onBackToLobby: () -> Unit,+) {+    var confirmResign by remember { mutableStateOf(false) }+    var confirmAbort by remember { mutableStateOf(false) }++    GameDialogs(+        playing = playing,+        confirmResign = confirmResign,+        confirmAbort = confirmAbort,+        onPromote = onPromote,+        onCancelPromotion = onCancelPromotion,+        onResignConfirm = onResignConfirm,+        onAbortConfirm = onAbortConfirm,+        onDismissResign = { confirmResign = false },+        onDismissAbort = { confirmAbort = false },+    )++    AppScaffold(+        title = playing.opponentName?.let { stringResource(R.string.online_opponent, it) }+            ?: stringResource(R.string.tab_online),+        scrollBehavior = appBarScrollBehavior(),+    ) { innerPadding ->+        GameLayout(+            state = state,+            playing = playing,+            onSquareClick = onSquareClick,+            onSquareDrop = onSquareDrop,+            onResign = { confirmResign = true },+            onAbort = { confirmAbort = true },+            onBackToLobby = onBackToLobby,+            modifier = Modifier+                .fillMaxSize()+                .padding(innerPadding)+                .padding(16.dp),+        )+    }+}+ @Composable private fun OnlineGameContent(     state: OnlineChessUiState,
games/chess/src/main/java/com/vayunmathur/games/chess/ChessPuzzleScreens.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/ChessPuzzleScreens.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessPuzzleScreens.ktindex 69ffb9f317..e93d4e36ad 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/ChessPuzzleScreens.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessPuzzleScreens.kt@@ -52,12 +52,34 @@ fun PuzzleScreen(viewModel: PuzzleViewModel) {     PuzzleBoardScreen(state = uiState, actions = viewModel) } +/** Difficulty selector, rating and side-to-move header for the puzzle screen. */+@Composable+private fun PuzzleHeader(state: PuzzleUiState, actions: PuzzleActions) {+    PuzzleDifficultySelector(state = state, actions = actions)+    Spacer(Modifier.height(12.dp))++    Text(+        stringResource(R.string.puzzle_rating, state.rating),+        fontWeight = FontWeight.Bold+    )+    Text(+        if (state.playerColor == PieceColor.WHITE) {+            stringResource(R.string.puzzle_white_to_move)+        } else {+            stringResource(R.string.puzzle_black_to_move)+        },+        style = MaterialTheme.typography.bodyMedium+    )+    Spacer(Modifier.height(8.dp))+}+ /**  * The puzzle screen, with no dependency on the ViewModel so it can be rendered from a  * `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.  */ @OptIn(ExperimentalMaterial3Api::class) @Composable+ fun PuzzleBoardScreen(state: PuzzleUiState, actions: PuzzleActions) {     if (state.board.promotionPosition != null) {         PawnPromotionDialog(state.playerColor, onPromote = actions::onPromote, onDismiss = actions::onCancelPromotion)@@ -74,23 +96,7 @@ fun PuzzleBoardScreen(state: PuzzleUiState, actions: PuzzleActions) {             Arrangement.Center,             Alignment.CenterHorizontally         ) {-            PuzzleDifficultySelector(state = state, actions = actions)-            Spacer(Modifier.height(12.dp))--            Text(-                stringResource(R.string.puzzle_rating, state.rating),-                fontWeight = FontWeight.Bold-            )-            Text(-                if (state.playerColor == PieceColor.WHITE) {-                    stringResource(R.string.puzzle_white_to_move)-                } else {-                    stringResource(R.string.puzzle_black_to_move)-                },-                style = MaterialTheme.typography.bodyMedium-            )-            Spacer(Modifier.height(8.dp))-+            PuzzleHeader(state = state, actions = actions)             // Capped like the game board so a desktop window doesn't blow the grid up.             Box(Modifier.widthIn(max = ChessBoardMaxWidth).fillMaxWidth()) {                 BoardGrid(
games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.ktindex 574bf4efdf..12ea54d8da 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/MainActivity.kt@@ -34,6 +34,7 @@ import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.SiblingPage import com.vayunmathur.library.util.rememberNavBackStack +/** Main Activity: a ma activity implementation for main activity. */ class MainActivity : MaActivity() {     override fun onCreateBeforeContent() {         // lichess.org serves public-CA certs; STANDARD covers its chain without system trust.@@ -78,7 +79,7 @@ class MainActivity : MaActivity() {                 backStack,                 bottomBar = {                     val cur = backStack.last()-                    if (cur is Route.Game || cur is Route.Online || cur is Route.Puzzles || cur is Route.Learn) {+                    if (cur.isMainTabRoute()) {                         BottomNavBar(backStack, pages, cur)                     }                 }@@ -186,3 +187,9 @@ class MainActivity : MaActivity() {         )     } }++/** True for the four top-level tab destinations that show the bottom bar. */+private fun Route.isMainTabRoute(): Boolean = when (this) {+    is Route.Game, is Route.Online, is Route.Puzzles, is Route.Learn -> true+    else -> false+}
games/chess/src/main/java/com/vayunmathur/games/chess/Route.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/Route.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/Route.ktindex fbc6e2b81f..eed89a940b 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/Route.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/Route.kt@@ -3,18 +3,25 @@ package com.vayunmathur.games.chess import com.vayunmathur.library.util.NavKey import kotlinx.serialization.Serializable +/** Contract for route. */ @Serializable sealed interface Route: NavKey {+    /** Singleton holding game state and operations. */     @Serializable     data object Game: Route+    /** Singleton holding online state and operations. */     @Serializable     data object Online: Route+    /** Singleton holding puzzles state and operations. */     @Serializable     data object Puzzles: Route+    /** Singleton holding learn state and operations. */     @Serializable     data object Learn: Route+    /** Immutable value describing learn stage; carries categoryKey, stageKey. */     @Serializable     data class LearnStage(val categoryKey: String, val stageKey: String): Route+    /** Singleton holding game center state and operations. */     @Serializable     data object GameCenter: Route }
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..c7acbdea54 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,7 @@ import kotlinx.serialization.Serializable  */ class LichessAuthManager(private val context: Context, private val tokenStore: LichessTokenStore) { +    /** Shared constants and helpers for LichessAuthManager. */     companion object {         private const val OAUTH_URL = "https://lichess.org/oauth"         private const val TOKEN_URL = "https://lichess.org/api/token"@@ -66,6 +67,7 @@ class LichessAuthManager(private val context: Context, private val tokenStore: L      /** Redirect URI query parsed out of the OAuth callback intent (null when not ours). */     data class AuthRedirect(val code: String, val state: String) {+        /** Shared constants and helpers for AuthRedirect. */         companion object {             fun from(intent: Intent): AuthRedirect? {                 val uri: Uri = intent.data ?: return null@@ -112,10 +114,13 @@ class LichessAuthManager(private val context: Context, private val tokenStore: L      * [IllegalStateException] on `state` mismatch (possible CSRF — drop it) or      * [java.io.IOException] from [NetworkClient] on transport/HTTP failure.      */+    /** Throws [IllegalStateException] with [message]; keeps throw sites out of sign-in. */+    private fun failSignIn(message: String): Nothing = throw IllegalStateException(message)+     suspend fun finishSignIn(redirect: AuthRedirect): String {-        val attempt = pending ?: throw IllegalStateException("No pending Lichess sign-in")+        val attempt = pending ?: failSignIn("No pending Lichess sign-in")         pending = null-        if (redirect.state != attempt.state) throw IllegalStateException("Lichess state mismatch")+        if (redirect.state != attempt.state) failSignIn("Lichess state mismatch")         val response: TokenResponse = NetworkClient.callJson(             TOKEN_URL,             method = "POST",
games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.ktindex b2b931358a..3df08f3644 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.kt@@ -15,6 +15,7 @@ class LichessTokenStore(context: Context) {      private val store = DataStoreUtils.getInstance(context.applicationContext) +    /** Shared constants and helpers for LichessTokenStore. */     companion object {         private const val KEY_ACCESS_TOKEN = "lichess_access_token"         private const val KEY_USERNAME = "lichess_username"
games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessModel.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessModel.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessModel.ktindex 9d28b3ff40..13b1cd2090 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessModel.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/data/ChessModel.kt@@ -18,6 +18,7 @@ internal const val WHITE_EP_ROW = 4 internal const val BLACK_EP_ROW = 3 internal const val SQUARE_COLOR_MOD = 2 +/** Kinds of piece type. */ enum class PieceType(val resID: Int) {     KING(R.drawable.chess_king_2_fill1_24px),     QUEEN(R.drawable.chess_queen_fill1_24px),@@ -27,12 +28,15 @@ enum class PieceType(val resID: Int) {     PAWN(R.drawable.chess_pawn_fill1_24px) } +/** Kinds of piece color. */ enum class PieceColor { WHITE, BLACK }  val PieceColor.opposite get() = if (this == PieceColor.WHITE) PieceColor.BLACK else PieceColor.WHITE +/** Immutable value describing piece; carries type, color, hasMoved. */ data class Piece(val type: PieceType, val color: PieceColor, val hasMoved: Boolean = false) +/** Immutable value describing position; carries row, col. */ data class Position(val row: Int, val col: Int)  /** Castling availability for a position, as encoded in a FEN's castling field. */@@ -48,6 +52,7 @@ private val PieceType.notationLetter: String get() = when (this) {     PieceType.BISHOP -> "B"; PieceType.KNIGHT -> "N"; PieceType.PAWN -> "" } +/** Immutable value describing move. */ data class Move(     val start: Position,     val end: Position,@@ -82,6 +87,7 @@ data class Move(     } } +/** Immutable value describing board. */ data class Board(     val pieces: List<List<Piece?>>,     val capturedByWhite: List<Piece> = emptyList(),@@ -268,6 +274,7 @@ data class Board(         return squareColors.size == 1     } +    /** Shared constants and helpers for Board. */     companion object {         /**          * What a pawn may become, in the order Maia3's move vocabulary lists them.
games/chess/src/main/java/com/vayunmathur/games/chess/data/Learn.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/data/Learn.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/data/Learn.ktindex 393f85aa28..2ebcafc1e7 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/data/Learn.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/data/Learn.kt@@ -49,6 +49,7 @@ data class LearnLevel(         ?: emptyList() } +/** Immutable value describing learn stage. */ @Serializable data class LearnStage(     val id: Int = 0,@@ -60,9 +61,11 @@ data class LearnStage(     val levels: List<LearnLevel> ) +/** Immutable value describing learn category; carries key, name, stages. */ @Serializable data class LearnCategory(val key: String, val name: String, val stages: List<LearnStage>) +/** Immutable value describing learn data; carries categories. */ @Serializable data class LearnData(val categories: List<LearnCategory>) 
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..83325cbebb 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@@ -25,6 +25,7 @@ class LichessAuthExpired(message: String) : IOException(message)  */ class LichessApi(private val tokenStore: LichessTokenStore) { +    /** Shared constants and helpers for LichessApi. */     companion object {         private const val BASE = "https://lichess.org"         private const val FORM = "application/x-www-form-urlencoded"@@ -32,7 +33,10 @@ class LichessApi(private val tokenStore: LichessTokenStore) {         /** Idle games outlast the 60 s default read timeout; moves reset it on every read. */         private const val STREAM_READ_TIMEOUT_MS = 10 * 60_000L -        private const val MAX_ERROR_CHARS = 200+        private const val HTTP_OK_MIN = 200+private const val HTTP_OK_MAX = 299+private const val HTTP_UNAUTHORIZED = 401+private const val MAX_ERROR_CHARS = 200          private val HTTP_401 = Regex("^HTTP 401\\b") @@ -52,8 +56,8 @@ class LichessApi(private val tokenStore: LichessTokenStore) {      private fun checkOk(response: SimpleResponse, what: String) {         when (response.status) {-            in 200..299 -> return-            401 -> throw LichessAuthExpired("Lichess $what: unauthorized (401)")+            in HTTP_OK_MIN..HTTP_OK_MAX -> return+            HTTP_UNAUTHORIZED -> throw LichessAuthExpired("Lichess $what: unauthorized (401)")             else -> throw IOException("Lichess $what: HTTP ${response.status}: ${response.body.take(MAX_ERROR_CHARS)}")         }     }@@ -229,19 +233,28 @@ class LichessApi(private val tokenStore: LichessTokenStore) {         while (true) {             val read = stream.read(buffer)             if (read == -1) break-            if (read == 0) continue-            var start = 0-            for (i in 0 until read) {-                if (buffer[i] == NEWLINE_BYTE) {-                    pending.write(buffer, start, i - start)-                    val line = pending.toString(Charsets.UTF_8.name()).trim()-                    pending.reset()-                    start = i + 1-                    if (line.isNotEmpty()) onLine(line)-                }+            if (read > 0) emitLines(buffer, read, pending, onLine)+        }+    }++    /** Emits every complete line in [buffer] into [pending], keeping the partial tail. */+    private suspend fun emitLines(+        buffer: ByteArray,+        read: Int,+        pending: ByteArrayOutputStream,+        onLine: suspend (String) -> Unit,+    ) {+        var start = 0+        for (i in 0 until read) {+            if (buffer[i] == NEWLINE_BYTE) {+                pending.write(buffer, start, i - start)+                val line = pending.toString(Charsets.UTF_8.name()).trim()+                pending.reset()+                start = i + 1+                if (line.isNotEmpty()) onLine(line)             }-            pending.write(buffer, start, read - start)         }+        pending.write(buffer, start, read - start)     } } 
games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessModels.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessModels.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessModels.ktindex 95e38a36c9..a1d4d079db 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessModels.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessModels.kt@@ -23,14 +23,18 @@ import kotlinx.serialization.json.JsonElement  private const val UCI_LENGTH = 4 private const val UCI_PROMOTION_LENGTH = 5+private const val RANK_COUNT = 8+private const val SQUARE_END = 2+private const val MOVE_END = 4+private const val PROMOTION_INDEX = 4  /** `e2` → [Position]: row 0 is rank 8 (matches [com.vayunmathur.games.chess.data.Board]). */ internal fun squareFromUci(square: String): Position =-    Position(8 - (square[1] - '0'), square[0] - 'a')+    Position(RANK_COUNT - (square[1] - '0'), square[0] - 'a')  /** [Position] → `e2`. */ internal fun Position.toUciSquare(): String =-    "${('a'.code + col).toChar()}${8 - row}"+    "${('a'.code + col).toChar()}${RANK_COUNT - row}"  /** `q`/`r`/`b`/`n` → [PieceType]; anything else is a protocol violation. */ internal fun promotionFromUci(letter: Char): PieceType = when (letter) {@@ -60,9 +64,9 @@ data class UciMove(val from: Position, val to: Position, val promotion: PieceTyp fun parseUci(uci: String): UciMove {     require(uci.length == UCI_LENGTH || uci.length == UCI_PROMOTION_LENGTH) { "Bad UCI: $uci" }     return UciMove(-        from = squareFromUci(uci.substring(0, 2)),-        to = squareFromUci(uci.substring(2, 4)),-        promotion = uci.getOrNull(4)?.let(::promotionFromUci),+        from = squareFromUci(uci.substring(0, SQUARE_END)),+        to = squareFromUci(uci.substring(SQUARE_END, MOVE_END)),+        promotion = uci.getOrNull(PROMOTION_INDEX)?.let(::promotionFromUci),     ) } @@ -80,6 +84,7 @@ fun colorFromLichess(color: String): PieceColor = when (color) { /** [PieceColor] → `white`/`black` for seek/challenge request bodies. */ fun PieceColor.toLichessColor(): String = if (this == PieceColor.WHITE) "white" else "black" +/** Immutable value describing lichess profile. */ @Serializable data class LichessProfile(     val id: String = "",@@ -94,6 +99,7 @@ data class LichessEventEnvelope(     @SerialName("challenge") val challenge: LichessChallenge? = null, ) +/** Immutable value describing lichess event game. */ @Serializable data class LichessEventGame(     @SerialName("gameId") val gameId: String = "",@@ -102,11 +108,13 @@ data class LichessEventGame(     @SerialName("isMyTurn") val isMyTurn: Boolean = false, ) +/** Immutable value describing lichess opponent. */ @Serializable data class LichessOpponent(     val username: String = "", ) +/** Immutable value describing lichess challenge. */ @Serializable data class LichessChallenge(     val id: String = "",@@ -116,10 +124,15 @@ data class LichessChallenge(  /** Decoded event — unknown `type` values become [Ignored] so new server kinds don't crash us. */ sealed interface LichessEvent {+    /** Immutable value describing game start; carries gameId, color, opponent. */     data class GameStart(val gameId: String, val color: PieceColor, val opponent: String) : LichessEvent+    /** Immutable value describing game finish; carries gameId. */     data class GameFinish(val gameId: String) : LichessEvent+    /** Immutable value describing challenge; carries id, challenger. */     data class Challenge(val id: String, val challenger: String) : LichessEvent+    /** Immutable value describing challenge declined; carries id. */     data class ChallengeDeclined(val id: String) : LichessEvent+    /** Singleton holding ignored state and operations. */     data object Ignored : LichessEvent } @@ -155,17 +168,20 @@ data class GameFull(         if (black.id == myUserId && white.id != myUserId) PieceColor.BLACK else PieceColor.WHITE } +/** Immutable value describing lichess variant. */ @Serializable data class LichessVariant(     val key: String = "standard", ) +/** Immutable value describing lichess clock. */ @Serializable data class LichessClock(     val initial: Long = 0L,     val increment: Long = 0L, ) +/** Immutable value describing lichess player. */ @Serializable data class LichessPlayer(     val id: String = "",@@ -187,6 +203,7 @@ data class GameState(     /** Terminal statuses per `https://lichess.org/api#tag/Board/operation/boardGameStream`. */     val isTerminal: Boolean get() = status in TERMINAL_STATUSES +    /** Shared constants and helpers for GameState. */     companion object {         private val TERMINAL_STATUSES = setOf(             "aborted", "mate", "resign", "stalemate", "timeout", "draw", "outoftime", "cheat",@@ -197,8 +214,11 @@ data class GameState(  /** Decoded game-stream line: full snapshot first, deltas after. Unknown → [Ignored]. */ sealed interface LichessGameUpdate {+    /** Immutable value describing full; carries game. */     data class Full(val game: GameFull) : LichessGameUpdate+    /** Immutable value describing state; carries state. */     data class State(val state: GameState) : LichessGameUpdate+    /** Singleton holding ignored state and operations. */     data object Ignored : LichessGameUpdate } @@ -221,6 +241,7 @@ fun decodeGameLine(element: JsonElement, json: Json): LichessGameUpdate { data class LichessTimeControl(val minutes: Int, val incrementSeconds: Int) {     val label: String get() = "$minutes+$incrementSeconds" +    /** Shared constants and helpers for LichessTimeControl. */     companion object {         val BULLET = LichessTimeControl(1, 0)         val BLITZ_3_2 = LichessTimeControl(3, 2)
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 1d5f145662..24e1e6e5cc 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@@ -60,13 +60,13 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat     internal var api = LichessApi(tokenStore)         set(value) {             field = value-            if (_uiState.value.auth is OnlineAuth.SignedIn) {+            if (uiStateFlow.value.auth is OnlineAuth.SignedIn) {                 startEventStream()             }         } -    private val _uiState = MutableStateFlow(OnlineChessUiState())-    val uiState: StateFlow<OnlineChessUiState> = _uiState.asStateFlow()+    internal val uiStateFlow = MutableStateFlow(OnlineChessUiState())+    val uiState: StateFlow<OnlineChessUiState> = uiStateFlow.asStateFlow()      private var eventJob: Job? = null     private var gameJob: Job? = null@@ -78,6 +78,7 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat     /** Game the stream is currently attached to; stale `gameStart`s for other ids are ignored. */     private var attachedGameId: String? = null +    /** Shared constants and helpers for OnlineChessViewModel. */     companion object {         private const val RECONNECT_BASE_MS = 1_000L         private const val RECONNECT_MAX_MS = 30_000L@@ -88,17 +89,17 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat         viewModelScope.launch {             val username = tokenStore.usernameNow()             if (tokenStore.tokenNow() != null && username != null) {-                _uiState.update { it.copy(auth = OnlineAuth.SignedIn(username)) }+                uiStateFlow.update { it.copy(auth = OnlineAuth.SignedIn(username)) }                 startEventStream()             }         }         redirectJob = viewModelScope.launch {             LichessAuthBridge.redirects.collect { redirect ->-                val auth = _uiState.value.auth+                val auth = uiStateFlow.value.auth                 if (auth !is OnlineAuth.SigningIn) return@collect                 try {                     val username = authManager.finishSignIn(redirect)-                    _uiState.update { it.copy(auth = OnlineAuth.SignedIn(username)) }+                    uiStateFlow.update { it.copy(auth = OnlineAuth.SignedIn(username)) }                     startEventStream()                 } catch (_: IllegalStateException) {                     failAuth(OnlineAuth.Error.SignInFailed)@@ -110,8 +111,8 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat     }      fun signIn() {-        if (_uiState.value.auth is OnlineAuth.SigningIn) return-        _uiState.update { it.copy(auth = OnlineAuth.SigningIn, authError = null) }+        if (uiStateFlow.value.auth is OnlineAuth.SigningIn) return+        uiStateFlow.update { it.copy(auth = OnlineAuth.SigningIn, authError = null) }         authManager.startSignIn()     } @@ -120,61 +121,48 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat         viewModelScope.launch { tokenStore.clear() }         attachedGameId = null         appliedUciCount = 0-        _uiState.value = OnlineChessUiState()+        uiStateFlow.value = OnlineChessUiState()     }      private fun failAuth(error: OnlineAuth.Error) {-        _uiState.update { it.copy(auth = OnlineAuth.SignedOut, authError = error) }+        uiStateFlow.update { it.copy(auth = OnlineAuth.SignedOut, authError = error) }     }      private suspend fun requireReauth() {         stopStreams()         tokenStore.clear()         attachedGameId = null-        _uiState.update {-            it.copy(connection = OnlineConnection.Idle, auth = OnlineAuth.SignedOut, authError = OnlineAuth.Error.Expired)+        uiStateFlow.update {+            it.copy(+                connection = OnlineConnection.Idle,+                auth = OnlineAuth.SignedOut,+                authError = OnlineAuth.Error.Expired,+            )         }         AppMessages.show(authErrorText(OnlineAuth.Error.Expired))     }      /** Localized text for auth errors ([OnlineAuth.Error] stays locale-free for previews/tests). */-    fun authErrorText(error: OnlineAuth.Error): String {-        val context = getApplication<Application>()-        return when (error) {-            OnlineAuth.Error.SignInFailed -> context.getString(-                com.vayunmathur.games.chess.R.string.online_sign_in_failed-            )-            OnlineAuth.Error.Expired -> context.getString(-                com.vayunmathur.games.chess.R.string.online_auth_expired-            )-        }-    }      // -- matchmaking ---------------------------------------------------------- -    fun selectTimeControl(timeControl: LichessTimeControl) {-        _uiState.update { it.copy(selectedTimeControl = timeControl) }-    } -    fun onChallengeUsernameChange(username: String) {-        _uiState.update { it.copy(challengeUsername = username) }-    }      fun quickSeek() {-        val connection = _uiState.value.connection+        val connection = uiStateFlow.value.connection         if (connection is OnlineConnection.Seeking || connection is OnlineConnection.Playing) return-        _uiState.update {+        uiStateFlow.update {             it.copy(connection = OnlineConnection.Seeking(it.selectedTimeControl), lobbyError = null)         }         viewModelScope.launch {             try {-                api.seek(_uiState.value.selectedTimeControl)+                api.seek(uiStateFlow.value.selectedTimeControl)                 // Pairing arrives as gameStart on the event stream; the Seeking UI persists until                 // then. Seeks live server-side — leaving the tab does not cancel them.-            } catch (e: LichessAuthExpired) {+            } catch (_: LichessAuthExpired) {                 requireReauth()             } catch (_: IOException) {-                _uiState.update {+                uiStateFlow.update {                     it.copy(connection = OnlineConnection.Idle, lobbyError = OnlineLobby.Error.SeekFailed)                 }             }@@ -182,38 +170,35 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat     }      fun cancelSeek() {-        _uiState.update { it.copy(connection = OnlineConnection.Idle) }+        uiStateFlow.update { it.copy(connection = OnlineConnection.Idle) }     }      fun challenge() {-        val username = _uiState.value.challengeUsername.trim()+        val username = uiStateFlow.value.challengeUsername.trim()         if (username.isEmpty()) return-        val connection = _uiState.value.connection+        val connection = uiStateFlow.value.connection         if (connection is OnlineConnection.Seeking || connection is OnlineConnection.Playing) return-        _uiState.update {+        uiStateFlow.update {             it.copy(connection = OnlineConnection.Challenging(username), lobbyError = null)         }         viewModelScope.launch {             try {-                api.challenge(username, _uiState.value.selectedTimeControl)-                _uiState.update { it.copy(lobbyNotice = OnlineLobby.Notice.ChallengeSent(username)) }+                api.challenge(username, uiStateFlow.value.selectedTimeControl)+                uiStateFlow.update { it.copy(lobbyNotice = OnlineLobby.Notice.ChallengeSent(username)) }                 delay(CHALLENGE_TIMEOUT_MS)-                if (_uiState.value.connection is OnlineConnection.Challenging) {-                    _uiState.update { it.copy(connection = OnlineConnection.Idle) }+                if (uiStateFlow.value.connection is OnlineConnection.Challenging) {+                    uiStateFlow.update { it.copy(connection = OnlineConnection.Idle) }                 }-            } catch (e: LichessAuthExpired) {+            } catch (_: LichessAuthExpired) {                 requireReauth()             } catch (_: IOException) {-                _uiState.update {+                uiStateFlow.update {                     it.copy(connection = OnlineConnection.Idle, lobbyError = OnlineLobby.Error.ChallengeFailed)                 }             }         }     } -    fun dismissLobbyMessage() {-        _uiState.update { it.copy(lobbyError = null, lobbyNotice = null, authError = null) }-    }      // -- streams ---------------------------------------------------------------- @@ -236,8 +221,8 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat             try {                 reconnectLoop(                     onDrop = {-                        if (_uiState.value.connection is OnlineConnection.Playing) {-                            _uiState.update { state ->+                        if (uiStateFlow.value.connection is OnlineConnection.Playing) {+                            uiStateFlow.update { state ->                                 val playing = state.connection as OnlineConnection.Playing                                 state.copy(connection = playing.copy(reconnecting = true))                             }@@ -279,7 +264,7 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat     private suspend fun onEvent(event: LichessEvent) {         when (event) {             is LichessEvent.GameStart -> {-                _uiState.update {+                uiStateFlow.update {                     it.copy(                         connection = OnlineConnection.Playing(                             gameId = event.gameId,@@ -304,8 +289,8 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat                 }             }             is LichessEvent.ChallengeDeclined -> {-                if (_uiState.value.connection is OnlineConnection.Challenging) {-                    _uiState.update {+                if (uiStateFlow.value.connection is OnlineConnection.Challenging) {+                    uiStateFlow.update {                         it.copy(                             connection = OnlineConnection.Idle,                             lobbyNotice = OnlineLobby.Notice.ChallengeDeclined,@@ -337,7 +322,7 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat                     PieceColor.WHITE -> blackName                     PieceColor.BLACK -> whiteName                 }-                _uiState.update {+                uiStateFlow.update {                     val playing = (it.connection as? OnlineConnection.Playing)                     it.copy(                         connection = OnlineConnection.Playing(@@ -368,34 +353,34 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat      * applied partially — a short suffix mismatch resyncs on the next state.      */     private fun applyGameState(state: GameState) {-        val playing = _uiState.value.connection as? OnlineConnection.Playing ?: return+        val playing = uiStateFlow.value.connection as? OnlineConnection.Playing ?: return         val tokens = splitUciMoves(state.moves)         var board = playing.board         var applied = appliedUciCount         var selectedPiece: Position? = playing.selectedPiece         while (applied < tokens.size) {-            val uci = try {-                parseUci(tokens[applied])-            } catch (_: IllegalArgumentException) {+            val uci = runCatching { parseUci(tokens[applied]) }.getOrNull()+            if (uci == null) {                 applied++-                continue-            }-            if (!board.isValidMove(uci.from, uci.to)) break-            board = board.movePiece(uci.from, uci.to, uci.promotion)-            val promotionSquare = board.promotionPosition-            if (promotionSquare != null && uci.promotion != null) {-                board = board.promotePawn(promotionSquare, uci.promotion)+            } else if (!board.isValidMove(uci.from, uci.to)) {+                break+            } else {+                board = board.movePiece(uci.from, uci.to, uci.promotion)+                val promotionSquare = board.promotionPosition+                if (promotionSquare != null && uci.promotion != null) {+                    board = board.promotePawn(promotionSquare, uci.promotion)+                }+                applied+++                selectedPiece = null             }-            applied++-            selectedPiece = null         }         appliedUciCount = applied         val resultText = resultTextFor(state, playing.localColor)-        _uiState.update {+        uiStateFlow.update {             it.copy(                 connection = playing.copy(                     board = board,-                    turn = turnForMoveCount(applied),+                    turn = sideToMoveAfter(applied),                     whiteClockMs = state.wtime.takeIf { t -> t > 0 },                     blackClockMs = state.btime.takeIf { t -> t > 0 },                     selectedPiece = selectedPiece,@@ -406,10 +391,6 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat         }     } -    /** Side to move after [moveCount] half-moves from the initial position: White starts. */-    private fun turnForMoveCount(moveCount: Int): PieceColor =-        if (moveCount % 2 == 0) PieceColor.WHITE else PieceColor.BLACK-     private fun resultTextFor(state: GameState, localColor: PieceColor): String? {         if (!state.isTerminal) return null         val context = getApplication<Application>()@@ -439,19 +420,18 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat     // -- moves ------------------------------------------------------------------      fun onSquareClick(position: Position) {-        val playing = _uiState.value.connection as? OnlineConnection.Playing ?: return-        if (playing.resultText != null) return-        if (playing.turn != playing.localColor) return+        val playing = uiStateFlow.value.connection as? OnlineConnection.Playing ?: return         // The promotion dialog owns input while a choice is pending (it is modal); dismissing it         // goes through onCancelPromotion, so squares stay dead until a piece is chosen or the         // step is cancelled.+        if (playing.resultText != null || playing.turn != playing.localColor) return         if (playing.pendingPromotion != null) return         val board = playing.board         val selectedPiece = playing.selectedPiece         if (selectedPiece == null) {             val piece = board.pieces[position.row][position.col]             if (piece != null && piece.color == playing.turn) {-                _uiState.update { it.copy(connection = playing.copy(selectedPiece = position)) }+                uiStateFlow.update { it.copy(connection = playing.copy(selectedPiece = position)) }             }             return         }@@ -461,7 +441,7 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat             if (preview.promotionPosition != null && moving.type == PieceType.PAWN) {                 // Choice only — the board keeps the confirmed position until the server echoes                 // the promotion UCI, so a failed POST leaves nothing to roll back.-                _uiState.update {+                uiStateFlow.update {                     it.copy(                         connection = playing.copy(                             pendingPromotion = UciMove(selectedPiece, position),@@ -473,12 +453,12 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat             }             sendLocalMove(UciMove(selectedPiece, position))         } else {-            _uiState.update { it.copy(connection = playing.copy(selectedPiece = null)) }+            uiStateFlow.update { it.copy(connection = playing.copy(selectedPiece = null)) }         }     }      fun onPromote(pieceType: PieceType) {-        val playing = _uiState.value.connection as? OnlineConnection.Playing ?: return+        val playing = uiStateFlow.value.connection as? OnlineConnection.Playing ?: return         val pending = playing.pendingPromotion ?: return         sendLocalMove(pending.copy(promotion = pieceType))     }@@ -488,9 +468,9 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat      * moved and nothing was sent), so dropping the pending choice is the whole undo.      */     fun onCancelPromotion() {-        val playing = _uiState.value.connection as? OnlineConnection.Playing ?: return+        val playing = uiStateFlow.value.connection as? OnlineConnection.Playing ?: return         if (playing.pendingPromotion == null) return-        _uiState.update { it.copy(connection = playing.copy(pendingPromotion = null, selectedPiece = null)) }+        uiStateFlow.update { it.copy(connection = playing.copy(pendingPromotion = null, selectedPiece = null)) }     }      /**@@ -505,9 +485,9 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat             onSquareClick(from)             return         }-        val selected = (_uiState.value.connection as? OnlineConnection.Playing)?.selectedPiece+        val selected = (uiStateFlow.value.connection as? OnlineConnection.Playing)?.selectedPiece         if (selected != from) onSquareClick(from)-        val reselected = (_uiState.value.connection as? OnlineConnection.Playing)?.selectedPiece+        val reselected = (uiStateFlow.value.connection as? OnlineConnection.Playing)?.selectedPiece         if (reselected == from) onSquareClick(to)     } @@ -518,18 +498,18 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat      * while the position stays exactly as the server last confirmed it.      */     private fun sendLocalMove(uci: UciMove) {-        val playing = _uiState.value.connection as? OnlineConnection.Playing ?: return+        val playing = uiStateFlow.value.connection as? OnlineConnection.Playing ?: return         if (playing.turn != playing.localColor || playing.resultText != null) return         viewModelScope.launch {             try {                 api.sendMove(playing.gameId, uci.toString())-                _uiState.update {+                uiStateFlow.update {                     val current = it.connection as? OnlineConnection.Playing ?: return@update it                     it.copy(                         connection = current.copy(selectedPiece = null, pendingPromotion = null)                     )                 }-            } catch (e: LichessAuthExpired) {+            } catch (_: LichessAuthExpired) {                 requireReauth()             } catch (_: IOException) {                 AppMessages.show(moveFailedText())@@ -537,17 +517,13 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat         }     } -    private fun moveFailedText(): String =-        getApplication<Application>().getString(com.vayunmathur.games.chess.R.string.online_move_failed)--    // -- resign / abort -----------------------------------------------------------      fun onResignConfirm() {-        val playing = _uiState.value.connection as? OnlineConnection.Playing ?: return+        val playing = uiStateFlow.value.connection as? OnlineConnection.Playing ?: return         viewModelScope.launch {             try {                 api.resign(playing.gameId)-            } catch (e: LichessAuthExpired) {+            } catch (_: LichessAuthExpired) {                 requireReauth()             } catch (_: IOException) {                 AppMessages.show(moveFailedText())@@ -556,11 +532,11 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat     }      fun onAbortConfirm() {-        val playing = _uiState.value.connection as? OnlineConnection.Playing ?: return+        val playing = uiStateFlow.value.connection as? OnlineConnection.Playing ?: return         viewModelScope.launch {             try {                 api.abort(playing.gameId)-            } catch (e: LichessAuthExpired) {+            } catch (_: LichessAuthExpired) {                 requireReauth()             } catch (_: IOException) {                 AppMessages.show(moveFailedText())@@ -573,7 +549,7 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat         gameJob?.cancel()         attachedGameId = null         appliedUciCount = 0-        _uiState.update { it.copy(connection = OnlineConnection.Idle) }+        uiStateFlow.update { it.copy(connection = OnlineConnection.Idle) }     }      private fun stopStreams() {@@ -591,22 +567,31 @@ class OnlineChessViewModel(application: Application) : AndroidViewModel(applicat  /** Whether the lobby shows the sign-in CTA, the signing-in wait, or the signed-in identity. */ sealed interface OnlineAuth {+    /** Singleton holding signed out state and operations. */     data object SignedOut : OnlineAuth+    /** Singleton holding signing in state and operations. */     data object SigningIn : OnlineAuth+    /** Immutable value describing signed in; carries username. */     data class SignedIn(val username: String) : OnlineAuth      /** Sign-in failure vs token expiry; text resolves via `OnlineChessViewModel.authErrorText`. */     sealed interface Error {+        /** Singleton holding sign in failed state and operations. */         data object SignInFailed : Error+        /** Singleton holding expired state and operations. */         data object Expired : Error     } }  /** Matchmaking / game session state; `Playing` doubles as the game screen's state holder. */ sealed interface OnlineConnection {+    /** Singleton holding idle state and operations. */     data object Idle : OnlineConnection+    /** Immutable value describing seeking; carries timeControl. */     data class Seeking(val timeControl: LichessTimeControl) : OnlineConnection+    /** Immutable value describing challenging; carries username. */     data class Challenging(val username: String) : OnlineConnection+    /** Immutable value describing playing. */     data class Playing(         val gameId: String,         val localColor: PieceColor,@@ -628,17 +613,24 @@ sealed interface OnlineConnection {  /** Lobby-scoped transient messages; cleared by [OnlineChessViewModel.dismissLobbyMessage]. */ object OnlineLobby {+    /** Contract for error. */     sealed interface Error {+        /** Singleton holding seek failed state and operations. */         data object SeekFailed : Error+        /** Singleton holding challenge failed state and operations. */         data object ChallengeFailed : Error     } +    /** Contract for notice. */     sealed interface Notice {+        /** Immutable value describing challenge sent; carries username. */         data class ChallengeSent(val username: String) : Notice+        /** Singleton holding challenge declined state and operations. */         data object ChallengeDeclined : Notice     } } +/** Immutable value describing online chess ui state. */ data class OnlineChessUiState(     val auth: OnlineAuth = OnlineAuth.SignedOut,     val authError: OnlineAuth.Error? = null,@@ -657,3 +649,35 @@ data class OnlineChessUiState(         return playing.localColor == PieceColor.BLACK     } }++/** Side to move after [moveCount] half-moves from the initial position: White starts. */+private fun sideToMoveAfter(moveCount: Int): PieceColor =+    if (moveCount % 2 == 0) PieceColor.WHITE else PieceColor.BLACK++/** Localized text for auth errors ([OnlineAuth.Error] stays locale-free for previews/tests). */+fun OnlineChessViewModel.authErrorText(error: OnlineAuth.Error): String {+        val context = getApplication<Application>()+        return when (error) {+            OnlineAuth.Error.SignInFailed -> context.getString(+                com.vayunmathur.games.chess.R.string.online_sign_in_failed+            )+            OnlineAuth.Error.Expired -> context.getString(+                com.vayunmathur.games.chess.R.string.online_auth_expired+            )+        }+    }++fun OnlineChessViewModel.selectTimeControl(timeControl: LichessTimeControl) {+    uiStateFlow.update { it.copy(selectedTimeControl = timeControl) }+}++fun OnlineChessViewModel.onChallengeUsernameChange(username: String) {+    uiStateFlow.update { it.copy(challengeUsername = username) }+}++fun OnlineChessViewModel.dismissLobbyMessage() {+    uiStateFlow.update { it.copy(lobbyError = null, lobbyNotice = null, authError = null) }+}++private fun OnlineChessViewModel.moveFailedText(): String =+    getApplication<Application>().getString(com.vayunmathur.games.chess.R.string.online_move_failed)
games/chess/src/main/java/com/vayunmathur/games/chess/util/AppBackupAgent.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/AppBackupAgent.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/AppBackupAgent.ktindex 3645d026ed..32f24a00d0 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/AppBackupAgent.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/AppBackupAgent.kt@@ -2,6 +2,7 @@ package com.vayunmathur.games.chess.util  import com.vayunmathur.library.util.BaseBackupAgent +/** App Backup Agent: a base backup agent implementation for app backup agent. */ class AppBackupAgent : BaseBackupAgent() {     override val datastoreNames: List<String>         get() = listOf("datastore_default")
games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessAchievementsManager.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessAchievementsManager.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessAchievementsManager.ktindex 109086ec4a..1fb8b145b0 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessAchievementsManager.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessAchievementsManager.kt@@ -4,6 +4,7 @@ import android.content.Context import com.vayunmathur.library.util.AchievementsManager import com.vayunmathur.library.util.DataStoreUtils +/** Manages chess achievements. */ class ChessAchievementsManager(     context: Context,     json: String
games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessUiContract.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessUiContract.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessUiContract.ktindex 14c059e9fd..5d12a7f869 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessUiContract.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessUiContract.kt@@ -29,6 +29,7 @@ interface ChessActions {      */     fun onSquareDrop(from: Position, to: Position) {} +    /** Shared constants and helpers for ChessActions. */     companion object {         val Noop: ChessActions = object : ChessActions {}     }@@ -53,6 +54,7 @@ interface PuzzleActions {     fun retry() {}     fun showSolution() {} +    /** Shared constants and helpers for PuzzleActions. */     companion object {         val Noop: PuzzleActions = object : PuzzleActions {}     }
games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.ktindex e42b1a0a20..d90f29e21b 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/ChessViewModel.kt@@ -15,20 +15,27 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +/** Type representing game mode. */ sealed class GameMode {+    /** Singleton holding two player state and operations. */     data object TwoPlayer : GameMode()+    /** Immutable value describing vs ai; carries playerColor, difficulty. */     data class VsAI(val playerColor: PieceColor, val difficulty: Difficulty) : GameMode() }  /** Terminal outcome of a game, or null while it is still in progress. */ sealed class GameResult {+    /** Immutable value describing checkmate; carries winner. */     data class Checkmate(val winner: PieceColor) : GameResult()+    /** Singleton holding stalemate state and operations. */     data object Stalemate : GameResult()+    /** Singleton holding insufficient material state and operations. */     data object InsufficientMaterial : GameResult()      val isGameOver: Boolean get() = true } +/** Immutable value describing chess ui state. */ data class ChessUiState(     val board: Board = Board.initialState,     val selectedPiece: Position? = null,@@ -41,6 +48,7 @@ data class ChessUiState(     val aiThinking: Boolean = false, ) +/** Chess View Model: a application implementation for chess view model. */ class ChessViewModel(application: Application) : AndroidViewModel(application), ChessActions {      private val _uiState = MutableStateFlow(ChessUiState())@@ -69,6 +77,7 @@ class ChessViewModel(application: Application) : AndroidViewModel(application),     // The state before a pawn stepped onto the last rank, while its promotion choice is pending.     private var promotionUndo: ChessUiState? = null +    /** Shared constants and helpers for ChessViewModel. */     companion object {         private const val AI_REPLY_DELAY_MS = 500L     }
games/chess/src/main/java/com/vayunmathur/games/chess/util/LearnViewModel.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/LearnViewModel.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/LearnViewModel.ktindex 48d34771fe..1073a140be 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/LearnViewModel.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/LearnViewModel.kt@@ -24,8 +24,10 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +/** Kinds of learn status. */ enum class LearnStatus { Playing, Completed, Failed } +/** Immutable value describing learn ui state. */ data class LearnUiState(     val stage: LearnStage? = null,     val levelIndex: Int = 0,
games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.ktindex 791bd7ee0a..919bca3e35 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt@@ -207,6 +207,7 @@ class MaiaEngine(private val context: Context) {         return scored[keep - 1].first     } +    /** Shared constants and helpers for MaiaEngine. */     companion object {         private const val TAG = "MaiaEngine" 
games/chess/src/main/java/com/vayunmathur/games/chess/util/PuzzleViewModel.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/PuzzleViewModel.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/PuzzleViewModel.ktindex f427875732..4fce9027a4 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/PuzzleViewModel.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/PuzzleViewModel.kt@@ -25,12 +25,14 @@ private val EASY_RANGE = 400..1199 private val MEDIUM_RANGE = 1200..1799 private val HARD_RANGE = 1800..2799 +/** Kinds of puzzle difficulty. */ enum class PuzzleDifficulty(val range: IntRange) {     EASY(EASY_RANGE),     MEDIUM(MEDIUM_RANGE),     HARD(HARD_RANGE); } +/** Kinds of puzzle status. */ enum class PuzzleStatus {     /** Loading a puzzle / auto-playing the opponent's setup move. */     Loading,@@ -44,6 +46,7 @@ enum class PuzzleStatus {     ShowingSolution } +/** Immutable value describing puzzle ui state. */ data class PuzzleUiState(     val puzzle: Puzzle? = null,     val board: Board = Board.initialState,@@ -73,6 +76,7 @@ class PuzzleViewModel(application: Application) : AndroidViewModel(application),     private val setupDelayMs = 500L     private val replyDelayMs = 400L +    /** Shared constants and helpers for PuzzleViewModel. */     companion object {         private const val REPLAY_STEP_DELAY_MS = 600L     }
games/chess/src/test/java/com/vayunmathur/games/chess/ChessDropTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/ChessDropTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/ChessDropTest.ktindex 3282467531..c34fad12f8 100644--- a/games/chess/src/test/java/com/vayunmathur/games/chess/ChessDropTest.kt+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/ChessDropTest.kt@@ -152,29 +152,43 @@ class ChessDropTest {         assertEquals(vm.uiState.value.puzzle!!.solution.size, vm.uiState.value.solutionIndex)     } ++    /** First (from, target) move for [color] whose target holds an enemy piece, if any. */+    private fun findCapture(+        board: com.vayunmathur.games.chess.data.Board,+        color: com.vayunmathur.games.chess.data.PieceColor,+    ): Pair<Position, Position>? =+        (0..7).firstNotNullOfOrNull { r ->+            (0..7).firstNotNullOfOrNull { c ->+                val target = board.pieces[r][c]+                if (target == null || target.color == color) {+                    null+                } else {+                    val to = Position(r, c)+                    (0..7).firstNotNullOfOrNull { fr ->+                        (0..7).firstNotNullOfOrNull { fc ->+                            val piece = board.pieces[fr][fc]+                            val from = Position(fr, fc)+                            if (piece?.color == color &&+                                (board.isValidMove(from, to) || board.isPseudoLegalMove(from, to))+                            ) {+                                from to to+                            } else {+                                null+                            }+                        }+                    }+                }+            }+        }     @Test fun learnDropCapturesLikeTwoTaps() {         val vm = LearnViewModel(app)         vm.loadStage("fundamentals", "capture")         await("stage capture") { vm.uiState.value.level != null }         val before = vm.uiState.value.board-        var dropped = false-        outer@ for (r in 0..7) for (c in 0..7) {-            val enemy = vm.uiState.value.board.pieces[r][c] ?: continue-            if (enemy.color == vm.uiState.value.playerColor) continue-            val target = Position(r, c)-            for (fr in 0..7) for (fc in 0..7) {-                val piece = vm.uiState.value.board.pieces[fr][fc] ?: continue-                if (piece.color != vm.uiState.value.playerColor) continue-                val from = Position(fr, fc)-                val board = vm.uiState.value.board-                if (board.isValidMove(from, target) || board.isPseudoLegalMove(from, target)) {-                    vm.onSquareDrop(from, target)-                    dropped = true-                    break@outer-                }-            }-        }-        assertTrue(dropped, "a capture must be available")+        val capture = findCapture(vm.uiState.value.board, vm.uiState.value.playerColor)+        assertTrue(capture != null, "a capture must be available")+        vm.onSquareDrop(capture.first, capture.second)         assertTrue(             vm.uiState.value.board != before || vm.uiState.value.status != LearnStatus.Playing,             "the drop captures exactly like two taps would"
games/chess/src/test/java/com/vayunmathur/games/chess/ChessPass3DrawTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/ChessPass3DrawTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/ChessPass3DrawTest.ktindex 7412ef059e..399b1e3973 100644--- a/games/chess/src/test/java/com/vayunmathur/games/chess/ChessPass3DrawTest.kt+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/ChessPass3DrawTest.kt@@ -103,26 +103,42 @@ class ChessPass3DrawTest {         assertTrue(state.apples.isNotEmpty())     } ++    /** First move for [color] satisfying [accept] over (from, to, board-after), if any. */+    private fun findMove(+        state: com.vayunmathur.games.chess.util.LearnUiState,+        accept: (Position, Position, com.vayunmathur.games.chess.data.Board) -> Boolean,+    ): Pair<Position, Position>? =+        (0..7).firstNotNullOfOrNull { r ->+            (0..7).firstNotNullOfOrNull { c ->+                val piece = state.board.pieces[r][c]+                if (piece?.color != state.playerColor) {+                    null+                } else {+                    val from = Position(r, c)+                    (0..7).firstNotNullOfOrNull { r2 ->+                        (0..7).firstNotNullOfOrNull { c2 ->+                            val to = Position(r2, c2)+                            val legal = state.board.isValidMove(from, to) ||+                                state.board.isPseudoLegalMove(from, to)+                            if (legal && accept(from, to, state.board.movePiece(from, to))) {+                                from to to+                            } else {+                                null+                            }+                        }+                    }+                }+            }+        }     @Test fun learnPunishedFailureShowsRetryButtonAndRetries() {         val vm = LearnViewModel(app)         vm.loadStage("fundamentals", "protection")         await("protection loaded") { vm.uiState.value.level != null }         val state = vm.uiState.value         val level = state.level!!-        var hanging: Pair<Position, Position>? = null-        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 (!state.board.isValidMove(from, to) && !state.board.isPseudoLegalMove(from, to)) continue-                val after = state.board.movePiece(from, to)-                if (com.vayunmathur.games.chess.util.detectCaptureMove(level, after, state.playerColor) != null) {-                    hanging = from to to-                    break@outer-                }-            }+        val hanging = findMove(state) { _, _, after ->+            com.vayunmathur.games.chess.util.detectCaptureMove(level, after, state.playerColor) != null         }         val (from, to) = hanging ?: error("protection level should offer a hanging move")         vm.onSquareClick(from)@@ -146,34 +162,11 @@ class ChessPass3DrawTest {         // Make a legal-but-wrong move on a capture level with detectCapture: find any         // move that gets punished (hangs a piece) or fails; retry restores Playing.         val state = vm.uiState.value-        var played = 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 (state.board.isValidMove(from, to) || state.board.isPseudoLegalMove(from, to)) {-                    // Prefer a capture (the lesson's goal) to advance the script.-                    if (state.board.pieces[r2][c2] != null) {-                        vm.onSquareClick(from); vm.onSquareClick(to); played = true; break@outer-                    }-                }-            }-        }-        if (!played) {-            // Fall back to any legal move.-            outer2@ 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) {-                    if (state.board.isValidMove(Position(r, c), Position(r2, c2))) {-                        vm.onSquareClick(Position(r, c)); vm.onSquareClick(Position(r2, c2))-                        break@outer2-                    }-                }-            }-        }+        // Prefer a capture (the lesson's goal) to advance the script.+        val capture = findMove(state) { _, to, _ -> state.board.pieces[to.row][to.col] != null }+        val move = capture ?: findMove(state) { _, _, _ -> true }+        assertTrue(move != null, "a legal move must exist")+        vm.onSquareClick(move!!.first); vm.onSquareClick(move.second)         // Whatever the outcome, the stage screen composes the status area for it.         rule.setContent {             LearnStageScreen(viewModel = vm, onBack = {}, onOpenStage = { _, _ -> })
games/chess/src/test/java/com/vayunmathur/games/chess/OnlineScreensTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/OnlineScreensTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/OnlineScreensTest.ktindex 307ce10c7e..9c0a9a052c 100644--- a/games/chess/src/test/java/com/vayunmathur/games/chess/OnlineScreensTest.kt+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/OnlineScreensTest.kt@@ -10,6 +10,9 @@ import com.vayunmathur.games.chess.network.LichessTimeControl import com.vayunmathur.games.chess.platform.OnlineAuth import com.vayunmathur.games.chess.platform.OnlineChessUiState import com.vayunmathur.games.chess.platform.OnlineChessViewModel+import com.vayunmathur.games.chess.platform.authErrorText+import com.vayunmathur.games.chess.platform.onChallengeUsernameChange+import com.vayunmathur.games.chess.platform.selectTimeControl import com.vayunmathur.games.chess.platform.OnlineConnection import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi