Modern Apps git

← Modern-Apps.git

chess: online play via Lichess (OAuth PKCE, seek, challenges)

Commit
b31d637dce33f18585f831136201689ce9480264
Author
vayun-mathur <[email protected]>
When
2026-10-17 19:57 UTC (1 month ago)
Parents
505f1d3

Diff

games/chess/build.gradle.kts
diff --git a/games/chess/build.gradle.kts b/games/chess/build.gradle.ktsindex 7963be58e7..79def735a3 100644--- a/games/chess/build.gradle.kts+++ b/games/chess/build.gradle.kts@@ -24,4 +24,6 @@ android { dependencies {     implementation(project(":sdk:games"))     implementation(project(":library:ml"))+    implementation(project(":library:network"))+    implementation(libs.androidx.browser) }
games/chess/src/main/AndroidManifest.xml
diff --git a/games/chess/src/main/AndroidManifest.xml b/games/chess/src/main/AndroidManifest.xmlindex 2e7095f918..d280bd9bbc 100644--- a/games/chess/src/main/AndroidManifest.xml+++ b/games/chess/src/main/AndroidManifest.xml@@ -3,6 +3,8 @@      <uses-permission android:name="com.vayunmathur.games.hub.permission.READ_GAME_DATA" />     <uses-permission android:name="com.vayunmathur.games.hub.permission.WRITE_GAME_DATA" />+    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />      <application         android:allowBackup="true"@@ -17,12 +19,22 @@             android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"             android:name=".MainActivity"             android:exported="true"+            android:launchMode="singleTop"             android:theme="@style/Theme.General">             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>+            <!-- Lichess OAuth (PKCE) redirect: modernapps://lichess-callback?code=…&state=… -->+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />++                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />++                <data android:scheme="modernapps" android:host="lichess-callback" />+            </intent-filter>         </activity>     </application> 
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.ktnew file mode 100644index 0000000000..d4ab91f4fa--- /dev/null+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/ChessOnlineScreens.kt@@ -0,0 +1,530 @@+package com.vayunmathur.games.chess++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.games.chess.data.PieceColor+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.OnlineConnection+import com.vayunmathur.games.chess.platform.OnlineLobby+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.ConfirmDialog+import com.vayunmathur.library.ui.IconClock+import com.vayunmathur.library.ui.IconFlag+import com.vayunmathur.library.ui.Messenger+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.library.util.OfflineAware+import com.vayunmathur.library.util.rememberIsOnline+import com.vayunmathur.library.ui.R as UiR++private const val MILLIS_PER_SECOND = 1_000L+private const val SECONDS_PER_MINUTE = 60L++/**+ * The online play tab: Lichess sign-in → lobby (quick seek + challenge) → live game.+ *+ * The game board reuses [BoardGrid], [MovesList] and [PawnPromotionDialog] from+ * [ChessGameScreens.kt] — no second board renderer. State comes from [OnlineChessViewModel]:+ * the lobby reads `auth` + `connection`, the game reads the `Playing` connection. Errors+ * surface on the shared snackbar via [rememberMessenger]; the offline banner comes from+ * [OfflineAware]. Preview entry: [ChessOnlineScreen] (stateless).+ */+@Composable+fun ChessOnlineScreens(viewModel: OnlineChessViewModel) {+    val state by viewModel.uiState.collectAsState()+    val online by rememberIsOnline()+    val messenger = rememberMessenger()+    OfflineAware {+        when (val connection = state.connection) {+            is OnlineConnection.Playing -> ChessOnlineGame(+                state = state,+                playing = connection,+                onSquareClick = viewModel::onSquareClick,+                onPromote = viewModel::onPromote,+                onResignConfirm = viewModel::onResignConfirm,+                onAbortConfirm = viewModel::onAbortConfirm,+                onBackToLobby = viewModel::backToLobby,+            )+            else -> {+                LobbyMessages(state = state, viewModel = viewModel, messenger = messenger)+                ChessOnlineLobbyScreen(+                    state = state,+                    online = online,+                    onSignIn = viewModel::signIn,+                    onSignOut = viewModel::signOut,+                    onSelectTimeControl = viewModel::selectTimeControl,+                    onQuickSeek = viewModel::quickSeek,+                    onCancelSeek = viewModel::cancelSeek,+                    onChallengeUsernameChange = viewModel::onChallengeUsernameChange,+                    onChallenge = viewModel::challenge,+                )+            }+        }+    }+}++@Composable+private fun ChessOnlineLobbyScreen(+    state: OnlineChessUiState,+    online: Boolean,+    onSignIn: () -> Unit,+    onSignOut: () -> Unit,+    onSelectTimeControl: (LichessTimeControl) -> Unit,+    onQuickSeek: () -> Unit,+    onCancelSeek: () -> Unit,+    onChallengeUsernameChange: (String) -> Unit,+    onChallenge: () -> Unit,+) {+    val seeking = state.connection as? OnlineConnection.Seeking+    val challenging = state.connection as? OnlineConnection.Challenging++    AppScaffold(+        title = stringResource(R.string.tab_online),+        scrollBehavior = appBarScrollBehavior(),+    ) { innerPadding ->+        Column(+            Modifier+                .fillMaxSize()+                .padding(innerPadding)+                .padding(16.dp)+                .verticalScroll(rememberScrollState()),+            verticalArrangement = Arrangement.spacedBy(16.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+        ) {+            when (val auth = state.auth) {+                is OnlineAuth.SignedIn -> SignedInHeader(+                    username = auth.username,+                    onSignOut = onSignOut,+                )+                OnlineAuth.SigningIn -> SigningInRow()+                OnlineAuth.SignedOut -> SignInCta(+                    enabled = online,+                    onSignIn = onSignIn,+                )+            }+            if (state.auth is OnlineAuth.SignedIn) {+                TimeControlRow(+                    selected = state.selectedTimeControl,+                    enabled = online && seeking == null && challenging == null,+                    onSelect = onSelectTimeControl,+                )+                SeekRow(+                    seeking = seeking,+                    enabled = online,+                    onSeek = onQuickSeek,+                    onCancel = onCancelSeek,+                )+                ChallengeRow(+                    username = state.challengeUsername,+                    challenging = challenging,+                    enabled = online,+                    onUsernameChange = onChallengeUsernameChange,+                    onChallenge = onChallenge,+                )+            }+        }+    }+}++/**+ * Posts lobby-scoped transient messages (challenge sent/declined, seek failures) to the shared+ * snackbar and clears them so a recomposition never reposts.+ */+@Composable+private fun LobbyMessages(+    state: OnlineChessUiState,+    viewModel: OnlineChessViewModel,+    messenger: Messenger,+) {+    val matchmakingFailed = stringResource(R.string.online_matchmaking_failed)+    val challengeSentFmt = stringResource(R.string.online_challenge_sent)+    val challengeDeclined = stringResource(R.string.online_challenge_declined)+    val authErrorText = state.authError?.let { viewModel.authErrorText(it) }+    val lobbyError = state.lobbyError+    val lobbyNotice = state.lobbyNotice+    LaunchedEffect(lobbyError, lobbyNotice, authErrorText) {+        val text = when {+            authErrorText != null -> authErrorText+            lobbyError != null -> matchmakingFailed+            lobbyNotice is OnlineLobby.Notice.ChallengeSent ->+                challengeSentFmt.format(lobbyNotice.username)+            lobbyNotice is OnlineLobby.Notice.ChallengeDeclined -> challengeDeclined+            else -> null+        }+        if (text != null) {+            messenger.show(text)+            viewModel.dismissLobbyMessage()+        }+    }+}++@Composable+private fun SignedInHeader(username: String, onSignOut: () -> Unit) {+    Row(+        Modifier.fillMaxWidth(),+        horizontalArrangement = Arrangement.SpaceBetween,+        verticalAlignment = Alignment.CenterVertically,+    ) {+        Text(+            stringResource(R.string.online_signed_in_as, username),+            fontWeight = FontWeight.Bold,+        )+        OutlinedButton(onClick = onSignOut) {+            Text(stringResource(R.string.online_sign_out))+        }+    }+}++@Composable+private fun SigningInRow() {+    Row(+        horizontalArrangement = Arrangement.spacedBy(12.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        CircularProgressIndicator()+        Text(stringResource(R.string.online_signing_in))+    }+}++@Composable+private fun SignInCta(enabled: Boolean, onSignIn: () -> Unit) {+    Button(onClick = onSignIn, enabled = enabled) {+        Text(stringResource(R.string.online_sign_in))+    }+}++@Composable+private fun TimeControlRow(+    selected: LichessTimeControl,+    enabled: Boolean,+    onSelect: (LichessTimeControl) -> Unit,+) {+    val labels = listOf(+        stringResource(R.string.online_tc_1_0) to LichessTimeControl.BULLET,+        stringResource(R.string.online_tc_3_2) to LichessTimeControl.BLITZ_3_2,+        stringResource(R.string.online_tc_5_3) to LichessTimeControl.RAPID_5_3,+        stringResource(R.string.online_tc_10_0) to LichessTimeControl.RAPID_10_0,+    )+    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+        labels.forEach { (label, control) ->+            if (control == selected) {+                Button(onClick = { onSelect(control) }, enabled = enabled) {+                    Text(label)+                }+            } else {+                OutlinedButton(onClick = { onSelect(control) }, enabled = enabled) {+                    Text(label)+                }+            }+        }+    }+}++@Composable+private fun SeekRow(+    seeking: OnlineConnection.Seeking?,+    enabled: Boolean,+    onSeek: () -> Unit,+    onCancel: () -> Unit,+) {+    if (seeking != null) {+        Row(+            horizontalArrangement = Arrangement.spacedBy(12.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            CircularProgressIndicator()+            Text(stringResource(R.string.online_seeking, seeking.timeControl.label))+            OutlinedButton(onClick = onCancel) {+                Text(stringResource(UiR.string.cancel))+            }+        }+    } else {+        Button(onClick = onSeek, enabled = enabled) {+            Text(stringResource(R.string.online_quick_seek))+        }+    }+}++@Composable+private fun ChallengeRow(+    username: String,+    challenging: OnlineConnection.Challenging?,+    enabled: Boolean,+    onUsernameChange: (String) -> Unit,+    onChallenge: () -> Unit,+) {+    Column(+        verticalArrangement = Arrangement.spacedBy(8.dp),+        horizontalAlignment = Alignment.CenterHorizontally,+    ) {+        OutlinedTextField(+            value = username,+            onValueChange = onUsernameChange,+            enabled = challenging == null,+            singleLine = true,+            label = { Text(stringResource(R.string.online_challenge_username)) },+        )+        if (challenging != null) {+            Row(+                horizontalArrangement = Arrangement.spacedBy(12.dp),+                verticalAlignment = Alignment.CenterVertically,+            ) {+                CircularProgressIndicator()+                Text(stringResource(R.string.online_challenge_sent, challenging.username))+            }+        } else {+            Button(onClick = onChallenge, enabled = enabled && username.isNotBlank()) {+                Text(stringResource(R.string.online_challenge))+            }+        }+    }+}++@Composable+private fun ChessOnlineGame(+    state: OnlineChessUiState,+    playing: OnlineConnection.Playing,+    onSquareClick: (com.vayunmathur.games.chess.data.Position) -> Unit,+    onPromote: (com.vayunmathur.games.chess.data.PieceType) -> Unit,+    onResignConfirm: () -> Unit,+    onAbortConfirm: () -> Unit,+    onBackToLobby: () -> Unit,+) {+    var confirmResign by remember { mutableStateOf(false) }+    var confirmAbort by remember { mutableStateOf(false) }++    if (playing.pendingPromotion != null) {+        PawnPromotionDialog(playing.localColor, onPromote = onPromote)+    }+    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,+        )+    }++    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) {+                Column(+                    Modifier+                        .fillMaxSize()+                        .verticalScroll(rememberScrollState()),+                    verticalArrangement = Arrangement.spacedBy(8.dp),+                    horizontalAlignment = Alignment.CenterHorizontally,+                ) {+                    OnlineGameContent(+                        state = state,+                        playing = playing,+                        onSquareClick = onSquareClick,+                        onResign = { confirmResign = true },+                        onAbort = { confirmAbort = true },+                        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,+                            onResign = { confirmResign = true },+                            onAbort = { confirmAbort = true },+                            onBackToLobby = onBackToLobby,+                        )+                    }+                }+            }+        }+    }+}++@Composable+private fun OnlineGameContent(+    state: OnlineChessUiState,+    playing: OnlineConnection.Playing,+    onSquareClick: (com.vayunmathur.games.chess.data.Position) -> Unit,+    onResign: () -> Unit,+    onAbort: () -> Unit,+    onBackToLobby: () -> Unit,+) {+    if (playing.reconnecting) {+        Text(+            stringResource(R.string.online_reconnecting),+            fontWeight = FontWeight.Bold,+        )+    }+    ClockRow(playing = playing)+    BoardGrid(+        board = playing.board,+        selectedPiece = playing.selectedPiece,+        isFlipped = state.isBoardFlipped,+        turn = playing.turn,+        onSquareClick = onSquareClick,+        showLastMove = true,+    )+    MovesList(moves = playing.board.moves, turn = playing.turn)+    playing.resultText?.let {+        Text(it, fontSize = 24.sp, fontWeight = FontWeight.Bold)+        Button(onClick = onBackToLobby) {+            Text(stringResource(R.string.online_back_to_lobby))+        }+    } ?: GameEndBar(+        canAbort = playing.canAbort,+        onResign = onResign,+        onAbort = onAbort,+    )+}++/** Display-only clocks (v1): no local ticking, values come from the last `gameState`. */+@Composable+private fun ClockRow(playing: OnlineConnection.Playing) {+    val white = playing.whiteClockMs+    val black = playing.blackClockMs+    if (white == null && black == null) return+    Row(+        Modifier.fillMaxWidth(),+        horizontalArrangement = Arrangement.SpaceEvenly,+        verticalAlignment = Alignment.CenterVertically,+    ) {+        ClockCell(+            label = stringResource(R.string.color_white),+            millis = white,+            active = playing.turn == PieceColor.WHITE,+        )+        IconClock()+        ClockCell(+            label = stringResource(R.string.color_black),+            millis = black,+            active = playing.turn == PieceColor.BLACK,+        )+    }+}++@Composable+private fun ClockCell(label: String, millis: Long?, active: Boolean) {+    Text(+        "$label ${millis?.let(::formatClock) ?: "--:--"}",+        fontWeight = if (active) FontWeight.Bold else FontWeight.Normal,+    )+}++/** `m:ss`, prefixing `0:` urgency under 10 s. `null`/negative never reach here (row hides). */+private fun formatClock(millis: Long): String {+    val totalSeconds = millis / MILLIS_PER_SECOND+    val minutes = totalSeconds / SECONDS_PER_MINUTE+    val seconds = totalSeconds % SECONDS_PER_MINUTE+    return "$minutes:${seconds.toString().padStart(2, '0')}"+}++@Composable+private fun GameEndBar(canAbort: Boolean, onResign: () -> Unit, onAbort: () -> Unit) {+    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+        if (canAbort) {+            OutlinedButton(onClick = onAbort) {+                Text(stringResource(R.string.online_abort_confirm))+            }+        }+        OutlinedButton(onClick = onResign) {+            IconFlag()+            Text(stringResource(R.string.online_resign_confirm))+        }+    }+}++/**+ * Stateless online screen for previews: lobby vs game is driven by [OnlineChessUiState]+ * (same shape the ViewModel exposes) with no-op actions. No ViewModel, no network.+ */+@Composable+fun ChessOnlineScreen(state: OnlineChessUiState) {+    val online = true+    OfflineAware {+        when (val connection = state.connection) {+            is OnlineConnection.Playing -> ChessOnlineGame(+                state = state,+                playing = connection,+                onSquareClick = {},+                onPromote = {},+                onResignConfirm = {},+                onAbortConfirm = {},+                onBackToLobby = {},+            )+            else -> ChessOnlineLobbyScreen(+                state = state,+                online = online,+                onSignIn = {},+                onSignOut = {},+                onSelectTimeControl = {},+                onQuickSeek = {},+                onCancelSeek = {},+                onChallengeUsernameChange = {},+                onChallenge = {},+            )+        }+    }+}+
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 ff1ed09887..574bf4efdf 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@@ -1,5 +1,6 @@ package com.vayunmathur.games.chess +import android.content.Intent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable@@ -13,15 +14,19 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.games.chess.auth.LichessAuthBridge+import com.vayunmathur.games.chess.platform.OnlineChessViewModel import com.vayunmathur.games.chess.util.ChessViewModel import com.vayunmathur.games.chess.util.LearnViewModel import com.vayunmathur.games.chess.util.PuzzleViewModel+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.ui.AchievementNotification import com.vayunmathur.library.ui.GameCenterScreen import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.IconOnline import com.vayunmathur.library.ui.IconPlay import com.vayunmathur.library.ui.MaActivity-import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.util.BottomBarItem import com.vayunmathur.library.util.BottomNavBar import com.vayunmathur.library.util.GameHubComposeHook@@ -30,6 +35,20 @@ import com.vayunmathur.library.util.SiblingPage import com.vayunmathur.library.util.rememberNavBackStack  class MainActivity : MaActivity() {+    override fun onCreateBeforeContent() {+        // lichess.org serves public-CA certs; STANDARD covers its chain without system trust.+        NetworkClient.init(this, TrustBundle.STANDARD)+        // Cold start straight into the OAuth redirect (process died mid-sign-in): forward it like+        // onNewIntent would. Sign-in can't complete without the in-memory verifier, but the+        // attempt clears instead of hanging on "waiting for approval".+        intent?.let(LichessAuthBridge::onRedirect)+    }++    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        LichessAuthBridge.onRedirect(intent)+    }+     @Composable     override fun Content() {         val backStack = rememberNavBackStack<Route>(Route.Game)@@ -59,7 +78,7 @@ class MainActivity : MaActivity() {                 backStack,                 bottomBar = {                     val cur = backStack.last()-                    if (cur is Route.Game || cur is Route.Puzzles || cur is Route.Learn) {+                    if (cur is Route.Game || cur is Route.Online || cur is Route.Puzzles || cur is Route.Learn) {                         BottomNavBar(backStack, pages, cur)                     }                 }@@ -67,6 +86,10 @@ class MainActivity : MaActivity() {                 entry<Route.Game>(metadata = SiblingPage()) {                     GameEntry(backStack, achievementsManager)                 }+                entry<Route.Online>(metadata = SiblingPage()) {+                    val onlineViewModel: OnlineChessViewModel = viewModel()+                    ChessOnlineScreens(onlineViewModel)+                }                 entry<Route.Puzzles>(metadata = SiblingPage()) {                     val puzzleViewModel: PuzzleViewModel = viewModel()                     PuzzleScreen(puzzleViewModel)@@ -100,9 +123,13 @@ class MainActivity : MaActivity() {     @Composable     private fun bottomBarPages(): List<BottomBarItem<out Route>> = listOf(         BottomBarItem(-            stringResource(UiR.string.play),+            stringResource(R.string.tab_offline),             Route.Game,         ) { IconPlay() },+        BottomBarItem(+            stringResource(R.string.tab_online),+            Route.Online,+        ) { IconOnline() },         BottomBarItem(             stringResource(R.string.tab_puzzles),             Route.Puzzles,
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 d0dafff31f..fbc6e2b81f 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@@ -8,6 +8,8 @@ sealed interface Route: NavKey {     @Serializable     data object Game: Route     @Serializable+    data object Online: Route+    @Serializable     data object Puzzles: Route     @Serializable     data object Learn: 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.ktnew file mode 100644index 0000000000..06d4164304--- /dev/null+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessAuthManager.kt@@ -0,0 +1,159 @@+package com.vayunmathur.games.chess.auth++import android.content.Context+import android.content.Intent+import android.net.Uri+import android.util.Base64+import androidx.browser.customtabs.CustomTabsIntent+import androidx.core.net.toUri+import com.vayunmathur.library.network.NetworkClient+import java.net.URLEncoder+import java.security.MessageDigest+import java.security.SecureRandom+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.asSharedFlow+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Lichess OAuth with PKCE (public client, no secret).+ *+ * Flow: [startSignIn] builds `https://lichess.org/oauth?...&scope=board:play` and opens it in a+ * Custom Tab; the `modernapps://lichess-callback?code=…&state=…` redirect re-enters the app+ * through `MainActivity.onNewIntent` → [LichessAuthBridge.onRedirect] → [LichessAuthBridge.redirects];+ * the online ViewModel validates `state` and calls [finishSignIn] (`POST /api/token`) via+ * [NetworkClient], persisting the access token in [LichessTokenStore].+ *+ * The verifier lives in memory only (never DataStore): a redirect that arrives after a process+ * death has no verifier to complete with, so it is dropped and the user signs in again.+ */+class LichessAuthManager(private val context: Context, private val tokenStore: LichessTokenStore) {++    companion object {+        private const val OAUTH_URL = "https://lichess.org/oauth"+        private const val TOKEN_URL = "https://lichess.org/api/token"+        private const val REDIRECT_URI = "modernapps://lichess-callback"+        private const val SCOPE = "board:play"++        /** PKCE verifier entropy (RFC 7636: 32 octets; 43–128 chars after base64url). */+        private const val VERIFIER_BYTES = 32++        /** `state` entropy: 16 bytes is unguessable and fits comfortably in a URL. */+        private const val STATE_BYTES = 16++        private val secureRandom = SecureRandom()++        private fun base64Url(bytes: ByteArray): String =+            Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)++        /** RFC 7636 `S256`: `BASE64URL(SHA256(verifier))`. */+        private fun codeChallenge(verifier: String): String {+            val digest = MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray(Charsets.US_ASCII))+            return base64Url(digest)+        }++        private fun formEncode(params: Map<String, String>): String =+            params.entries.joinToString("&") { (k, v) ->+                URLEncoder.encode(k, "UTF-8") + "=" + URLEncoder.encode(v, "UTF-8")+            }+    }++    /** One pending sign-in attempt; cleared on [startSignIn] and on completion. */+    private var pending: PendingAuth? = null++    private data class PendingAuth(val verifier: String, val state: String)++    /** Redirect URI query parsed out of the OAuth callback intent (null when not ours). */+    data class AuthRedirect(val code: String, val state: String) {+        companion object {+            fun from(intent: Intent): AuthRedirect? {+                val uri: Uri = intent.data ?: return null+                if (uri.scheme != "modernapps" || uri.host != "lichess-callback") return null+                val code = uri.getQueryParameter("code") ?: return null+                val state = uri.getQueryParameter("state") ?: return null+                return AuthRedirect(code, state)+            }+        }+    }++    @Serializable+    private data class TokenResponse(+        @SerialName("access_token") val accessToken: String = "",+        @SerialName("token_type") val tokenType: String = "",+        @SerialName("expires_in") val expiresIn: Long = 0L,+    )++    /**+     * Opens the Lichess authorize page. Any earlier incomplete attempt is abandoned — the user+     * tapped sign-in again, so only the newest `state` may complete.+     */+    fun startSignIn() {+        val verifier = base64Url(ByteArray(VERIFIER_BYTES).also { secureRandom.nextBytes(it) })+        val state = base64Url(ByteArray(STATE_BYTES).also { secureRandom.nextBytes(it) })+        pending = PendingAuth(verifier, state)+        val url = OAUTH_URL + "?" + formEncode(+            mapOf(+                "response_type" to "code",+                "client_id" to "modern-apps-chess",+                "redirect_uri" to REDIRECT_URI,+                "scope" to SCOPE,+                "code_challenge_method" to "S256",+                "code_challenge" to codeChallenge(verifier),+                "state" to state,+            )+        )+        CustomTabsIntent.Builder().build().launchUrl(context, url.toUri())+    }++    /**+     * Completes sign-in after the redirect: validates `state`, exchanges the code, persists the+     * token. Returns the username verified via `GET /api/account`, or throws:+     * [IllegalStateException] on `state` mismatch (possible CSRF — drop it) or+     * [java.io.IOException] from [NetworkClient] on transport/HTTP failure.+     */+    suspend fun finishSignIn(redirect: AuthRedirect): String {+        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 profile: com.vayunmathur.games.chess.network.LichessProfile =+            com.vayunmathur.games.chess.network.LichessApi(tokenStore).account()+        tokenStore.saveUsername(profile.username)+        tokenStore.saveUserId(profile.id)+        return profile.username+    }+}++/**+ * Forwards the OAuth redirect intent to whoever is collecting it.+ *+ * The redirect re-enters [MainActivity] (singleTop → `onNewIntent`) outside composition, but the+ * completion logic lives in the online ViewModel; a repository-scoped channel would outlive the+ * screen, so the bridge is a process-scoped flow with no replay — a redirect with nothing+ * collecting (user left the Online tab mid-sign-in) is dropped.+ */+object LichessAuthBridge {+    private val _redirects = MutableSharedFlow<LichessAuthManager.AuthRedirect>(extraBufferCapacity = 1)+    val redirects: SharedFlow<LichessAuthManager.AuthRedirect> = _redirects.asSharedFlow()++    fun onRedirect(intent: Intent) {+        val redirect = LichessAuthManager.AuthRedirect.from(intent) ?: return+        _redirects.tryEmit(redirect)+    }+}
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.ktnew file mode 100644index 0000000000..b2b931358a--- /dev/null+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/auth/LichessTokenStore.kt@@ -0,0 +1,65 @@+package com.vayunmathur.games.chess.auth++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.flow.Flow++/**+ * Persists the Lichess OAuth access token in the app's DataStore.+ *+ * The token authenticates every Board API call as a Bearer header via [authHeaders]; [clear]+ * drops it on sign-out or on [LichessAuthExpired] (HTTP 401). The lobby reads [usernameNow] for+ * its signed-in header without a network round-trip.+ */+class LichessTokenStore(context: Context) {++    private val store = DataStoreUtils.getInstance(context.applicationContext)++    companion object {+        private const val KEY_ACCESS_TOKEN = "lichess_access_token"+        private const val KEY_USERNAME = "lichess_username"+        private const val KEY_USER_ID = "lichess_user_id"++        private const val AUTH_SCHEME = "Bearer "+    }++    /** Emits the stored access token when set; silent before sign-in / after [clear]. */+    val token: Flow<String> = store.stringFlow(KEY_ACCESS_TOKEN)++    /** Emits the verified Lichess username from the last `/api/account` check. */+    val username: Flow<String> = store.stringFlow(KEY_USERNAME)++    /** Snapshot for one-shot reads (sign-in finish, API header build, VM init). */+    suspend fun tokenNow(): String? = store.getStringAwait(KEY_ACCESS_TOKEN)?.takeIf { it.isNotEmpty() }++    /** Snapshot of the stored username (lobby header without a network round-trip). */+    suspend fun usernameNow(): String? = store.getStringAwait(KEY_USERNAME)?.takeIf { it.isNotEmpty() }++    /** Authorization header for Lichess API calls; empty when signed out. */+    suspend fun authHeaders(): Map<String, String> {+        val token = tokenNow() ?: return emptyMap()+        return mapOf("Authorization" to AUTH_SCHEME + token)+    }++    suspend fun saveToken(token: String) {+        store.setString(KEY_ACCESS_TOKEN, token)+    }++    suspend fun saveUsername(username: String) {+        store.setString(KEY_USERNAME, username)+    }++    suspend fun saveUserId(userId: String) {+        store.setString(KEY_USER_ID, userId)+    }++    /** Snapshot of the stored Lichess user id (resolves my color in `gameFull`). */+    suspend fun userIdNow(): String? = store.getStringAwait(KEY_USER_ID)?.takeIf { it.isNotEmpty() }++    /** Drops the token and username; the lobby returns to the signed-out state. */+    suspend fun clear() {+        store.setString(KEY_ACCESS_TOKEN, "")+        store.setString(KEY_USERNAME, "")+        store.setString(KEY_USER_ID, "")+    }+}
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.ktnew file mode 100644index 0000000000..56a23dee5f--- /dev/null+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessApi.kt@@ -0,0 +1,249 @@+package com.vayunmathur.games.chess.network++import com.vayunmathur.games.chess.auth.LichessTokenStore+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.NetworkDataStream+import com.vayunmathur.library.network.SimpleResponse+import java.io.ByteArrayOutputStream+import java.io.IOException+import java.net.URLEncoder+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/** Thrown when Lichess answers HTTP 401 — the token was revoked or expired. */+class LichessAuthExpired(message: String) : IOException(message)++/**+ * Lichess Board API client (`https://lichess.org/api#tag/Board`), built only on [NetworkClient]+ * primitives (`getJson` / `performRequest` / `stream`) with `TrustBundle.STANDARD` (set once in+ * `MainActivity.onCreateBeforeContent`). No raw OkHttp/Retrofit/`HttpURLConnection`.+ *+ * Mutating calls use [NetworkClient.performRequest] (which never throws on HTTP status) so a 401+ * maps to [LichessAuthExpired] while other failures keep their status + body prefix. Streams run+ * 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) {++    companion object {+        private const val BASE = "https://lichess.org"+        private const val FORM = "application/x-www-form-urlencoded"++        /** 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 val HTTP_401 = Regex("^HTTP 401\\b")++        private val ndjson = Json {+            ignoreUnknownKeys = true+            isLenient = true+        }++        private fun form(params: Map<String, String>): String =+            params.entries.joinToString("&") { (k, v) ->+                URLEncoder.encode(k, "UTF-8") + "=" + URLEncoder.encode(v, "UTF-8")+            }+    }++    private suspend fun headers(extra: Map<String, String> = emptyMap()): Map<String, String> =+        tokenStore.authHeaders() + extra++    private fun checkOk(response: SimpleResponse, what: String) {+        when (response.status) {+            in 200..299 -> return+            401 -> throw LichessAuthExpired("Lichess $what: unauthorized (401)")+            else -> throw IOException("Lichess $what: HTTP ${response.status}: ${response.body.take(MAX_ERROR_CHARS)}")+        }+    }++    /** Maps [NetworkClient.callJson]/[getJson] transport failures: 401 → [LichessAuthExpired]. */+    private suspend fun <T> wrapJson(what: String, block: suspend () -> T): T {+        try {+            return block()+        } catch (e: IOException) {+            if (e is LichessAuthExpired || e.message?.let(HTTP_401::containsMatchIn) == true) {+                throw LichessAuthExpired("Lichess $what: unauthorized (401)")+            }+            throw e+        }+    }++    /** Verifies the stored token and returns the account profile (id + username). */+    suspend fun account(): LichessProfile = wrapJson("account") {+        NetworkClient.getJson("$BASE/api/account", headers())+    }++    /**+     * Opens a public seek (`rated=false`, random color, standard variant). Matchmaking happens+     * server-side; the pairing arrives as a `gameStart` event on [streamEvents].+     */+    suspend fun seek(timeControl: LichessTimeControl) {+        val response = NetworkClient.performRequest(+            "$BASE/api/board/seek",+            method = "POST",+            headers = headers(mapOf("Content-Type" to FORM)),+            body = form(+                mapOf(+                    "rated" to "false",+                    "time" to timeControl.minutes.toString(),+                    "increment" to timeControl.incrementSeconds.toString(),+                    "color" to "random",+                    "variant" to "standard",+                )+            ),+        )+        checkOk(response, "seek")+    }++    @Serializable+    private data class ChallengeCreated(val id: String = "")++    /**+     * Challenges `username` to an unrated standard game. Returns the challenge id; acceptance+     * arrives as `gameStart`, refusal as `challengeDeclined` on [streamEvents].+     */+    suspend fun challenge(username: String, timeControl: LichessTimeControl): String {+        val encoded = URLEncoder.encode(username.trim(), "UTF-8")+        val response = NetworkClient.performRequest(+            "$BASE/api/board/challenge/$encoded",+            method = "POST",+            headers = headers(mapOf("Content-Type" to FORM)),+            body = form(+                mapOf(+                    "rated" to "false",+                    "clock.limit" to (timeControl.minutes * 60).toString(),+                    "clock.increment" to timeControl.incrementSeconds.toString(),+                    "color" to "random",+                    "variant.key" to "standard",+                )+            ),+        )+        checkOk(response, "challenge")+        return try {+            ndjson.decodeFromString(ChallengeCreated.serializer(), response.body).id+        } catch (_: IllegalArgumentException) {+            ""+        }+    }++    /** Declines an incoming challenge (Challenge API; same host and Bearer auth). */+    suspend fun declineChallenge(challengeId: String) {+        val response = NetworkClient.performRequest(+            "$BASE/api/challenge/$challengeId/decline",+            method = "POST",+            headers = headers(),+        )+        checkOk(response, "decline challenge")+    }++    /** 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(+            "$BASE/api/board/game/$gameId/move/$uci",+            method = "POST",+            headers = headers(),+        )+        checkOk(response, "move $uci")+    }++    suspend fun resign(gameId: String) {+        val response = NetworkClient.performRequest(+            "$BASE/api/board/game/$gameId/resign",+            method = "POST",+            headers = headers(),+        )+        checkOk(response, "resign")+    }++    suspend fun abort(gameId: String) {+        val response = NetworkClient.performRequest(+            "$BASE/api/board/game/$gameId/abort",+            method = "POST",+            headers = headers(),+        )+        checkOk(response, "abort")+    }++    /**+     * Follows the account event stream (`gameStart` / `gameFinish` / `challenge` /+     * `challengeDeclined`), invoking [onEvent] per NDJSON line. Returns only when the server+     * closes the stream or the caller's coroutine is cancelled; throws [LichessAuthExpired] on+     * 401, [IOException] on transport failure.+     */+    suspend fun streamEvents(onEvent: suspend (LichessEvent) -> Unit) {+        NetworkClient.stream(+            "$BASE/api/stream/event",+            headers = headers(),+            readTimeoutMs = STREAM_READ_TIMEOUT_MS,+        ) { stream, response ->+            if (stream == null) {+                checkOk(response, "event stream")+                return@stream+            }+            readLines(stream) { line -> parseEvent(line)?.let { onEvent(it) } }+        }+    }++    /**+     * Follows one game's stream (`gameFull` then `gameState` deltas). Same lifecycle as+     * [streamEvents]; the ViewModel re-attaches with backoff after a drop.+     */+    suspend fun streamGame(gameId: String, onUpdate: suspend (LichessGameUpdate) -> Unit) {+        NetworkClient.stream(+            "$BASE/api/board/game/stream/$gameId",+            headers = headers(),+            readTimeoutMs = STREAM_READ_TIMEOUT_MS,+        ) { stream, response ->+            if (stream == null) {+                checkOk(response, "game stream")+                return@stream+            }+            readLines(stream) { line -> parseGameLine(line)?.let { onUpdate(it) } }+        }+    }++    private fun parseEvent(line: String): LichessEvent? = try {+        ndjson.decodeFromString(LichessEventEnvelope.serializer(), line).toEvent()+            .takeIf { it != LichessEvent.Ignored }+    } catch (_: IllegalArgumentException) {+        null+    }++    private fun parseGameLine(line: String): LichessGameUpdate? = try {+        decodeGameLine(ndjson.parseToJsonElement(line), ndjson)+            .takeIf { it != LichessGameUpdate.Ignored }+    } catch (_: IllegalArgumentException) {+        null+    }++    /**+     * Splits a [NetworkDataStream] into lines at `\n`, invoking [onLine] per non-blank line.+     * Lichess NDJSON is `\n`-delimited with no escapes spanning lines, so a byte scan suffices.+     * A transport failure surfaces as end-of-stream (`-1`); reconnect is the caller's job.+     */+    private suspend fun readLines(stream: NetworkDataStream, onLine: suspend (String) -> Unit) {+        val buffer = ByteArray(READ_BUFFER_SIZE)+        val pending = ByteArrayOutputStream()+        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)+                }+            }+            pending.write(buffer, start, read - start)+        }+    }+}++private const val READ_BUFFER_SIZE = 8 * 1024+private const val NEWLINE_BYTE: Byte = '\n'.code.toByte()
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.ktnew file mode 100644index 0000000000..95e38a36c9--- /dev/null+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/network/LichessModels.kt@@ -0,0 +1,232 @@+package com.vayunmathur.games.chess.network++import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.PieceType+import com.vayunmathur.games.chess.data.Position+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonElement++/**+ * Lichess Board API DTOs (`https://lichess.org/api#tag/Board`) plus UCI helpers.+ *+ * UCI moves are coordinate strings: `e2e4`, promotion `e7e8q`, castling `e1g1`. The server sends+ * `gameState.moves` as a space-separated suffix of every move so far; the ViewModel diff-applies+ * only the unseen tail onto [com.vayunmathur.games.chess.data.Board].+ *+ * Event envelopes are polymorphic (`type`: `gameStart`/`gameFinish`/`challenge`/…), so the+ * client decodes NDJSON lines as [LichessEventEnvelope] and switches on [type]; game payloads+ * arrive as [GameFull] (first line) then [GameState] deltas. Unknown `type` values decode via+ * [IgnoredEvent] rather than failing — Lichess adds event kinds without versioning.+ */++private const val UCI_LENGTH = 4+private const val UCI_PROMOTION_LENGTH = 5++/** `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] → `e2`. */+internal fun Position.toUciSquare(): String =+    "${('a'.code + col).toChar()}${8 - row}"++/** `q`/`r`/`b`/`n` → [PieceType]; anything else is a protocol violation. */+internal fun promotionFromUci(letter: Char): PieceType = when (letter) {+    'q' -> PieceType.QUEEN+    'r' -> PieceType.ROOK+    'b' -> PieceType.BISHOP+    'n', 'k' -> PieceType.KNIGHT // 'k' never occurs; mapped defensively, never emitted+    else -> throw IllegalArgumentException("Bad promotion letter: $letter")+}++/** [PieceType] → `q`/`r`/`b`/`n` (king/pawn never promote; map to queen defensively). */+internal fun PieceType.toUciPromotion(): Char = when (this) {+    PieceType.QUEEN -> 'q'+    PieceType.ROOK -> 'r'+    PieceType.BISHOP -> 'b'+    PieceType.KNIGHT -> 'n'+    PieceType.KING, PieceType.PAWN -> 'q'+}++/** A parsed UCI move: from/to squares plus the optional promotion choice. */+data class UciMove(val from: Position, val to: Position, val promotion: PieceType? = null) {+    override fun toString(): String =+        from.toUciSquare() + to.toUciSquare() + (promotion?.toUciPromotion()?.toString() ?: "")+}++/** Parses `e2e4` / `e7e8q` / `e1g1`; throws [IllegalArgumentException] on malformed input. */+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),+    )+}++/** Splits a `gameState.moves` payload into UCI tokens (empty string → no moves). */+fun splitUciMoves(moves: String): List<String> =+    if (moves.isBlank()) emptyList() else moves.trim().split(' ')++/** `white`/`black` → [PieceColor]; anything else is a protocol violation. */+fun colorFromLichess(color: String): PieceColor = when (color) {+    "white" -> PieceColor.WHITE+    "black" -> PieceColor.BLACK+    else -> throw IllegalArgumentException("Bad color: $color")+}++/** [PieceColor] → `white`/`black` for seek/challenge request bodies. */+fun PieceColor.toLichessColor(): String = if (this == PieceColor.WHITE) "white" else "black"++@Serializable+data class LichessProfile(+    val id: String = "",+    val username: String = "",+)++/** Polymorphic event-stream envelope; [payload] is decoded per [type]. */+@Serializable+data class LichessEventEnvelope(+    val type: String = "",+    @SerialName("game") val game: LichessEventGame? = null,+    @SerialName("challenge") val challenge: LichessChallenge? = null,+)++@Serializable+data class LichessEventGame(+    @SerialName("gameId") val gameId: String = "",+    val color: String = "",+    val opponent: LichessOpponent? = null,+    @SerialName("isMyTurn") val isMyTurn: Boolean = false,+)++@Serializable+data class LichessOpponent(+    val username: String = "",+)++@Serializable+data class LichessChallenge(+    val id: String = "",+    val challenger: LichessOpponent? = null,+    val destUser: LichessOpponent? = null,+)++/** Decoded event — unknown `type` values become [Ignored] so new server kinds don't crash us. */+sealed interface LichessEvent {+    data class GameStart(val gameId: String, val color: PieceColor, val opponent: String) : LichessEvent+    data class GameFinish(val gameId: String) : LichessEvent+    data class Challenge(val id: String, val challenger: String) : LichessEvent+    data class ChallengeDeclined(val id: String) : LichessEvent+    data object Ignored : LichessEvent+}++fun LichessEventEnvelope.toEvent(): LichessEvent = when (type) {+    "gameStart" -> LichessEvent.GameStart(+        gameId = game?.gameId ?: "",+        color = game?.color?.let(::colorFromLichess) ?: PieceColor.WHITE,+        opponent = game?.opponent?.username ?: "",+    )+    "gameFinish" -> LichessEvent.GameFinish(gameId = game?.gameId ?: "")+    "challenge" -> LichessEvent.Challenge(+        id = challenge?.id ?: "",+        challenger = challenge?.challenger?.username ?: "",+    )+    "challengeDeclined" -> LichessEvent.ChallengeDeclined(id = challenge?.id ?: "")+    else -> LichessEvent.Ignored+}++/** First line of the game stream: full position plus clock and side to move. */+@Serializable+data class GameFull(+    val id: String = "",+    val rated: Boolean = false,+    val variant: LichessVariant = LichessVariant(),+    val clock: LichessClock? = null,+    val white: LichessPlayer = LichessPlayer(),+    val black: LichessPlayer = LichessPlayer(),+    @SerialName("initialFen") val initialFen: String = "startpos",+    val state: GameState = GameState(),+) {+    /** My color, resolved from the account id Lichess echoes on both player objects. */+    fun myColor(myUserId: String): PieceColor =+        if (black.id == myUserId && white.id != myUserId) PieceColor.BLACK else PieceColor.WHITE+}++@Serializable+data class LichessVariant(+    val key: String = "standard",+)++@Serializable+data class LichessClock(+    val initial: Long = 0L,+    val increment: Long = 0L,+)++@Serializable+data class LichessPlayer(+    val id: String = "",+    val name: String = "",+)++/** `gameFull.state` and every `gameState` line: authoritative move list, clocks, status. */+@Serializable+data class GameState(+    val type: String = "",+    val moves: String = "",+    val wtime: Long = 0L,+    val btime: Long = 0L,+    val winc: Long = 0L,+    val binc: Long = 0L,+    val status: String = "started",+    val winner: String? = null,+) {+    /** Terminal statuses per `https://lichess.org/api#tag/Board/operation/boardGameStream`. */+    val isTerminal: Boolean get() = status in TERMINAL_STATUSES++    companion object {+        private val TERMINAL_STATUSES = setOf(+            "aborted", "mate", "resign", "stalemate", "timeout", "draw", "outoftime", "cheat",+            "noStart", "variantEnd",+        )+    }+}++/** Decoded game-stream line: full snapshot first, deltas after. Unknown → [Ignored]. */+sealed interface LichessGameUpdate {+    data class Full(val game: GameFull) : LichessGameUpdate+    data class State(val state: GameState) : LichessGameUpdate+    data object Ignored : LichessGameUpdate+}++private const val GAME_FULL_TYPE = "gameFull"+private const val GAME_STATE_TYPE = "gameState"++/** Decodes one NDJSON line by its `type` field; never throws on unknown shapes. */+fun decodeGameLine(element: JsonElement, json: Json): LichessGameUpdate {+    val type = (element as? kotlinx.serialization.json.JsonObject)?.get("type")+        ?.let { it as? kotlinx.serialization.json.JsonPrimitive }+        ?.takeIf { it.isString }?.content ?: ""+    return when (type) {+        GAME_FULL_TYPE -> LichessGameUpdate.Full(json.decodeFromJsonElement(GameFull.serializer(), element))+        GAME_STATE_TYPE -> LichessGameUpdate.State(json.decodeFromJsonElement(GameState.serializer(), element))+        else -> LichessGameUpdate.Ignored+    }+}++/** Time control for seek/challenge: minutes + increment seconds (Lichess `clock.limit/inc`). */+data class LichessTimeControl(val minutes: Int, val incrementSeconds: Int) {+    val label: String get() = "$minutes+$incrementSeconds"++    companion object {+        val BULLET = LichessTimeControl(1, 0)+        val BLITZ_3_2 = LichessTimeControl(3, 2)+        val RAPID_5_3 = LichessTimeControl(5, 3)+        val RAPID_10_0 = LichessTimeControl(10, 0)++        val PRESETS = listOf(BULLET, BLITZ_3_2, RAPID_5_3, RAPID_10_0)+    }+}
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.ktnew file mode 100644index 0000000000..ef0f9bcf9d--- /dev/null+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/platform/OnlineChessViewModel.kt@@ -0,0 +1,614 @@+package com.vayunmathur.games.chess.platform++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.games.chess.auth.LichessAuthBridge+import com.vayunmathur.games.chess.auth.LichessAuthManager+import com.vayunmathur.games.chess.auth.LichessTokenStore+import com.vayunmathur.games.chess.data.Board+import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.PieceType+import com.vayunmathur.games.chess.data.Position+import com.vayunmathur.games.chess.data.opposite+import com.vayunmathur.games.chess.network.GameState+import com.vayunmathur.games.chess.network.LichessApi+import com.vayunmathur.games.chess.network.LichessAuthExpired+import com.vayunmathur.games.chess.network.LichessEvent+import com.vayunmathur.games.chess.network.LichessGameUpdate+import com.vayunmathur.games.chess.network.LichessTimeControl+import com.vayunmathur.games.chess.network.UciMove+import com.vayunmathur.games.chess.network.parseUci+import com.vayunmathur.games.chess.network.splitUciMoves+import com.vayunmathur.games.chess.network.toUciSquare+import com.vayunmathur.library.util.AppMessages+import java.io.IOException+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch++/**+ * Online (Lichess) chess session: sign-in, matchmaking, and one live game at a time.+ *+ * The move path mirrors `ChessViewModel.onSquareClick` — guard `turn == localColor` plus+ * `board.isValidMove`, show `PawnPromotionDialog` for last-rank pawn steps, then `POST` the UCI+ * (`e2e4`, `e7e8q`, `e1g1`) — but the board only advances on the server's next `gameState`: the+ * client replays the unseen UCI tail via `Board.movePiece` / `promotePawn` (which already cover+ * castling, en passant and promotion), so a rejected or reordered move can never fork the+ * position. The promotion choice is held in `pendingPromotion` without touching the board, so a+ * failed POST leaves nothing to roll back. Server `status` (resign/draw/abort/outoftime/…) wins+ * over local rules on conflict. Clocks are display-only for v1.+ */+class OnlineChessViewModel(application: Application) : AndroidViewModel(application) {++    private val tokenStore = LichessTokenStore(application)+    private val authManager = LichessAuthManager(application, tokenStore)+    private val api = LichessApi(tokenStore)++    private val _uiState = MutableStateFlow(OnlineChessUiState())+    val uiState: StateFlow<OnlineChessUiState> = _uiState.asStateFlow()++    private var eventJob: Job? = null+    private var gameJob: Job? = null+    private var redirectJob: Job? = null++    /** UCI tokens already applied to [OnlineChessUiState.board]; the tail past this is new. */+    private var appliedUciCount: Int = 0++    /** Game the stream is currently attached to; stale `gameStart`s for other ids are ignored. */+    private var attachedGameId: String? = null++    companion object {+        private const val RECONNECT_BASE_MS = 1_000L+        private const val RECONNECT_MAX_MS = 30_000L+        private const val CHALLENGE_TIMEOUT_MS = 60_000L+    }++    init {+        viewModelScope.launch {+            val username = tokenStore.usernameNow()+            if (tokenStore.tokenNow() != null && username != null) {+                _uiState.update { it.copy(auth = OnlineAuth.SignedIn(username)) }+                startEventStream()+            }+        }+        redirectJob = viewModelScope.launch {+            LichessAuthBridge.redirects.collect { redirect ->+                val auth = _uiState.value.auth+                if (auth !is OnlineAuth.SigningIn) return@collect+                try {+                    val username = authManager.finishSignIn(redirect)+                    _uiState.update { it.copy(auth = OnlineAuth.SignedIn(username)) }+                    startEventStream()+                } catch (_: IllegalStateException) {+                    failAuth(OnlineAuth.Error.SignInFailed)+                } catch (_: IOException) {+                    failAuth(OnlineAuth.Error.SignInFailed)+                }+            }+        }+    }++    fun signIn() {+        if (_uiState.value.auth is OnlineAuth.SigningIn) return+        _uiState.update { it.copy(auth = OnlineAuth.SigningIn, authError = null) }+        authManager.startSignIn()+    }++    fun signOut() {+        stopStreams()+        viewModelScope.launch { tokenStore.clear() }+        attachedGameId = null+        appliedUciCount = 0+        _uiState.value = OnlineChessUiState()+    }++    private fun failAuth(error: OnlineAuth.Error) {+        _uiState.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)+        }+        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+        if (connection is OnlineConnection.Seeking || connection is OnlineConnection.Playing) return+        _uiState.update {+            it.copy(connection = OnlineConnection.Seeking(it.selectedTimeControl), lobbyError = null)+        }+        viewModelScope.launch {+            try {+                api.seek(_uiState.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) {+                requireReauth()+            } catch (_: IOException) {+                _uiState.update {+                    it.copy(connection = OnlineConnection.Idle, lobbyError = OnlineLobby.Error.SeekFailed)+                }+            }+        }+    }++    fun cancelSeek() {+        _uiState.update { it.copy(connection = OnlineConnection.Idle) }+    }++    fun challenge() {+        val username = _uiState.value.challengeUsername.trim()+        if (username.isEmpty()) return+        val connection = _uiState.value.connection+        if (connection is OnlineConnection.Seeking || connection is OnlineConnection.Playing) return+        _uiState.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)) }+                delay(CHALLENGE_TIMEOUT_MS)+                if (_uiState.value.connection is OnlineConnection.Challenging) {+                    _uiState.update { it.copy(connection = OnlineConnection.Idle) }+                }+            } catch (e: LichessAuthExpired) {+                requireReauth()+            } catch (_: IOException) {+                _uiState.update {+                    it.copy(connection = OnlineConnection.Idle, lobbyError = OnlineLobby.Error.ChallengeFailed)+                }+            }+        }+    }++    fun dismissLobbyMessage() {+        _uiState.update { it.copy(lobbyError = null, lobbyNotice = null, authError = null) }+    }++    // -- streams ----------------------------------------------------------------++    private fun startEventStream() {+        eventJob?.cancel()+        eventJob = viewModelScope.launch {+            try {+                reconnectLoop { api.streamEvents(::onEvent) }+            } catch (_: LichessAuthExpired) {+                requireReauth()+            }+        }+    }++    private fun attachGame(gameId: String) {+        if (attachedGameId == gameId && gameJob?.isActive == true) return+        attachedGameId = gameId+        gameJob?.cancel()+        gameJob = viewModelScope.launch {+            try {+                reconnectLoop(+                    onDrop = {+                        if (_uiState.value.connection is OnlineConnection.Playing) {+                            _uiState.update { state ->+                                val playing = state.connection as OnlineConnection.Playing+                                state.copy(connection = playing.copy(reconnecting = true))+                            }+                        }+                    }+                ) {+                    api.streamGame(gameId, ::onGameUpdate)+                }+            } catch (_: LichessAuthExpired) {+                requireReauth()+            }+        }+    }++    /**+     * Holds [block]'s stream open across drops: both a transport failure and a clean EOF (the+     * server closed an ostensibly infinite push stream) back off and re-attach, because a sync+     * gap heals by resuming from the next `gameState`. Only job cancellation (sign-out,+     * game end, ViewModel clear) and [LichessAuthExpired] escape: re-auth restarts the streams+     * from a clean state. [onDrop] marks the UI reconnecting before each retry so a mid-game+     * drop shows the banner.+     */+    private suspend fun reconnectLoop(onDrop: suspend () -> Unit = {}, block: suspend () -> Unit) {+        var backoff = RECONNECT_BASE_MS+        while (true) {+            try {+                block()+            } catch (e: LichessAuthExpired) {+                throw e+            } catch (_: IOException) {+                // Fall through to the shared backoff below.+            }+            onDrop()+            delay(backoff)+            backoff = (backoff * 2).coerceAtMost(RECONNECT_MAX_MS)+        }+    }++    private suspend fun onEvent(event: LichessEvent) {+        when (event) {+            is LichessEvent.GameStart -> {+                _uiState.update {+                    it.copy(+                        connection = OnlineConnection.Playing(+                            gameId = event.gameId,+                            localColor = event.color,+                            opponentName = event.opponent,+                            board = Board.initialState,+                            turn = PieceColor.WHITE,+                            selectedPiece = null,+                            resultText = null,+                        ),+                        lobbyError = null,+                        lobbyNotice = null,+                    )+                }+                appliedUciCount = 0+                attachGame(event.gameId)+            }+            is LichessEvent.GameFinish -> {+                if (attachedGameId == event.gameId) {+                    gameJob?.cancel()+                    attachedGameId = null+                }+            }+            is LichessEvent.ChallengeDeclined -> {+                if (_uiState.value.connection is OnlineConnection.Challenging) {+                    _uiState.update {+                        it.copy(+                            connection = OnlineConnection.Idle,+                            lobbyNotice = OnlineLobby.Notice.ChallengeDeclined,+                        )+                    }+                }+            }+            is LichessEvent.Challenge -> {+                // v1 scope is outgoing challenges only; incoming ones stay on lichess.org.+                viewModelScope.launch {+                    try {+                        api.declineChallenge(event.id)+                    } catch (_: IOException) {+                    }+                }+            }+            LichessEvent.Ignored -> Unit+        }+    }++    private suspend fun onGameUpdate(update: LichessGameUpdate) {+        when (update) {+            is LichessGameUpdate.Full -> {+                val myId = tokenStore.userIdNow() ?: return+                val localColor = update.game.myColor(myId)+                val whiteName = update.game.white.name.ifEmpty { null }+                val blackName = update.game.black.name.ifEmpty { null }+                val opponent = when (localColor) {+                    PieceColor.WHITE -> blackName+                    PieceColor.BLACK -> whiteName+                }+                _uiState.update {+                    val playing = (it.connection as? OnlineConnection.Playing)+                    it.copy(+                        connection = OnlineConnection.Playing(+                            gameId = update.game.id,+                            localColor = localColor,+                            opponentName = opponent ?: playing?.opponentName,+                            board = Board.initialState,+                            turn = PieceColor.WHITE,+                            whiteClockMs = update.game.state.wtime.takeIf { t -> t > 0 },+                            blackClockMs = update.game.state.btime.takeIf { t -> t > 0 },+                            selectedPiece = null,+                            resultText = null,+                            reconnecting = false,+                        )+                    )+                }+                appliedUciCount = 0+                applyGameState(update.game.state)+            }+            is LichessGameUpdate.State -> applyGameState(update.state)+            LichessGameUpdate.Ignored -> Unit+        }+    }++    /**+     * Applies the authoritative [GameState]: replays the unseen UCI tail onto the board and+     * adopts the server turn, clocks, and terminal status. Unknown UCI tokens are skipped, never+     * 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 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) {+                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)+            }+            applied+++            selectedPiece = null+        }+        appliedUciCount = applied+        val resultText = resultTextFor(state, playing.localColor)+        _uiState.update {+            it.copy(+                connection = playing.copy(+                    board = board,+                    turn = turnForMoveCount(applied),+                    whiteClockMs = state.wtime.takeIf { t -> t > 0 },+                    blackClockMs = state.btime.takeIf { t -> t > 0 },+                    selectedPiece = selectedPiece,+                    resultText = resultText,+                    reconnecting = false,+                )+            )+        }+    }++    /** 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>()+        val iWon = state.winner?.let {+            (it == "white") == (localColor == PieceColor.WHITE)+        }+        return when (state.status) {+            "draw", "stalemate" -> context.getString(+                com.vayunmathur.games.chess.R.string.online_result_draw+            )+            // `winner` is the color that won: present → the other side resigned; absent → I resigned+            // (my resign POST raced the state, or the server reports it without a winner).+            "resign" ->+                if (iWon == false) context.getString(+                    com.vayunmathur.games.chess.R.string.online_result_opponent_resigned+                ) else context.getString(+                    com.vayunmathur.games.chess.R.string.online_result_resigned+                )+            "aborted" -> context.getString(com.vayunmathur.games.chess.R.string.online_result_draw)+            else -> {+                if (iWon == true) context.getString(com.vayunmathur.games.chess.R.string.online_result_win)+                else context.getString(com.vayunmathur.games.chess.R.string.online_result_loss)+            }+        }+    }++    // -- 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+        // The promotion dialog owns input while a choice is pending; the dialog has no dismiss+        // affordance (mirrors offline PawnPromotionDialog), so squares stay dead until then.+        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)) }+            }+            return+        }+        if (board.isValidMove(selectedPiece, position)) {+            val moving = board.pieces[selectedPiece.row][selectedPiece.col] ?: return+            val preview = board.movePiece(selectedPiece, position)+            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 {+                    it.copy(+                        connection = playing.copy(+                            pendingPromotion = UciMove(selectedPiece, position),+                            selectedPiece = null,+                        )+                    )+                }+                return+            }+            sendLocalMove(UciMove(selectedPiece, position))+        } else {+            _uiState.update { it.copy(connection = playing.copy(selectedPiece = null)) }+        }+    }++    fun onPromote(pieceType: PieceType) {+        val playing = _uiState.value.connection as? OnlineConnection.Playing ?: return+        val pending = playing.pendingPromotion ?: return+        sendLocalMove(pending.copy(promotion = pieceType))+    }++    /**+     * POSTs the UCI; the board advances when the server echoes it in the next `gameState`.+     * Sending twice (double-tap) is harmless — Lichess rejects the duplicate and the tail replay+     * skips what is already applied. A 401 drops to re-auth; other failures surface a message+     * 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+        if (playing.turn != playing.localColor || playing.resultText != null) return+        viewModelScope.launch {+            try {+                api.sendMove(playing.gameId, uci.toString())+                _uiState.update {+                    val current = it.connection as? OnlineConnection.Playing ?: return@update it+                    it.copy(+                        connection = current.copy(selectedPiece = null, pendingPromotion = null)+                    )+                }+            } catch (e: LichessAuthExpired) {+                requireReauth()+            } catch (_: IOException) {+                AppMessages.show(moveFailedText())+            }+        }+    }++    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+        viewModelScope.launch {+            try {+                api.resign(playing.gameId)+            } catch (e: LichessAuthExpired) {+                requireReauth()+            } catch (_: IOException) {+                AppMessages.show(moveFailedText())+            }+        }+    }++    fun onAbortConfirm() {+        val playing = _uiState.value.connection as? OnlineConnection.Playing ?: return+        viewModelScope.launch {+            try {+                api.abort(playing.gameId)+            } catch (e: LichessAuthExpired) {+                requireReauth()+            } catch (_: IOException) {+                AppMessages.show(moveFailedText())+            }+        }+    }++    /** Terminal result arrived via `gameState.status` or `gameFinish` — back to the lobby. */+    fun backToLobby() {+        gameJob?.cancel()+        attachedGameId = null+        appliedUciCount = 0+        _uiState.update { it.copy(connection = OnlineConnection.Idle) }+    }++    private fun stopStreams() {+        eventJob?.cancel()+        eventJob = null+        gameJob?.cancel()+        gameJob = null+    }++    override fun onCleared() {+        redirectJob?.cancel()+        stopStreams()+    }+}++/** Whether the lobby shows the sign-in CTA, the signing-in wait, or the signed-in identity. */+sealed interface OnlineAuth {+    data object SignedOut : OnlineAuth+    data object SigningIn : OnlineAuth+    data class SignedIn(val username: String) : OnlineAuth++    /** Sign-in failure vs token expiry; text resolves via `OnlineChessViewModel.authErrorText`. */+    sealed interface Error {+        data object SignInFailed : Error+        data object Expired : Error+    }+}++/** Matchmaking / game session state; `Playing` doubles as the game screen's state holder. */+sealed interface OnlineConnection {+    data object Idle : OnlineConnection+    data class Seeking(val timeControl: LichessTimeControl) : OnlineConnection+    data class Challenging(val username: String) : OnlineConnection+    data class Playing(+        val gameId: String,+        val localColor: PieceColor,+        val opponentName: String? = null,+        val board: Board = Board.initialState,+        val turn: PieceColor = PieceColor.WHITE,+        val whiteClockMs: Long? = null,+        val blackClockMs: Long? = null,+        val selectedPiece: Position? = null,+        /** Local promotion choice awaiting confirm; the preview board shows the pawn stepped. */+        val pendingPromotion: UciMove? = null,+        val resultText: String? = null,+        val reconnecting: Boolean = false,+    ) : OnlineConnection {+        /** True while the first moves can still be aborted instead of resigned. */+        val canAbort: Boolean get() = board.moves.isEmpty()+    }+}++/** Lobby-scoped transient messages; cleared by [OnlineChessViewModel.dismissLobbyMessage]. */+object OnlineLobby {+    sealed interface Error {+        data object SeekFailed : Error+        data object ChallengeFailed : Error+    }++    sealed interface Notice {+        data class ChallengeSent(val username: String) : Notice+        data object ChallengeDeclined : Notice+    }+}++data class OnlineChessUiState(+    val auth: OnlineAuth = OnlineAuth.SignedOut,+    val authError: OnlineAuth.Error? = null,+    val connection: OnlineConnection = OnlineConnection.Idle,+    val selectedTimeControl: LichessTimeControl = LichessTimeControl.BLITZ_3_2,+    val challengeUsername: String = "",+    val lobbyError: OnlineLobby.Error? = null,+    val lobbyNotice: OnlineLobby.Notice? = null,+) {+    /** Clocks shown beside the board for the side to move; null hides the row. */+    val turn: PieceColor get() = (connection as? OnlineConnection.Playing)?.turn ?: PieceColor.WHITE++    /** BoardGrid flips when the local player holds Black, mirroring offline VsAI-as-Black. */+    val isBoardFlipped: Boolean get() {+        val playing = connection as? OnlineConnection.Playing ?: return false+        return playing.localColor == PieceColor.BLACK+    }+}
games/chess/src/main/res/values/strings.xml
diff --git a/games/chess/src/main/res/values/strings.xml b/games/chess/src/main/res/values/strings.xmlindex be6f4c7f2e..69518c38d3 100644--- a/games/chess/src/main/res/values/strings.xml+++ b/games/chess/src/main/res/values/strings.xml@@ -55,6 +55,10 @@     <!-- ChessBoard: Accessibility description for black pawn. Noun -->     <string name="piece_black_pawn">Black Pawn</string> +    <!-- MainActivity: Bottom navigation tab for offline (local + AI) play. Noun phrase -->+    <string name="tab_offline">Offline Play</string>+    <!-- MainActivity: Bottom navigation tab for online (Lichess) play. Noun phrase -->+    <string name="tab_online">Online Play</string>     <!-- MainActivity: Bottom navigation tab for Puzzles screen. Noun -->     <string name="tab_puzzles">Puzzles</string>     <!-- MainActivity: Bottom navigation tab for Learn lessons. Noun -->@@ -93,4 +97,65 @@     <string name="puzzle_show_solution">Show Solution</string>     <!-- Puzzles: Loading state while fetching puzzle. Verb progressive -->     <string name="puzzle_loading">Loading puzzle…</string>++    <!-- Online: Sign-in CTA. Opens Lichess OAuth in a Custom Tab. Verb phrase -->+    <string name="online_sign_in">Sign in with Lichess</string>+    <!-- Online: Signed-in identity line. %1$s = Lichess username e.g. alice. Status -->+    <string name="online_signed_in_as">Signed in as <xliff:g id="username" example="alice">%1$s</xliff:g></string>+    <!-- Online: Sign-out button. Verb phrase -->+    <string name="online_sign_out">Sign out</string>+    <!-- Online: Lobby time-control option 1+0 (1 minute, no increment). Label -->+    <string name="online_tc_1_0">1+0</string>+    <!-- Online: Lobby time-control option 3+2. Label -->+    <string name="online_tc_3_2">3+2</string>+    <!-- Online: Lobby time-control option 5+3. Label -->+    <string name="online_tc_5_3">5+3</string>+    <!-- Online: Lobby time-control option 10+0. Label -->+    <string name="online_tc_10_0">10+0</string>+    <!-- Online: Quick Seek button, starts matchmaking with selected time control. Verb phrase CTA -->+    <string name="online_quick_seek">Quick Seek</string>+    <!-- Online: Seeking indicator while matchmaking. %1$s = time control e.g. 3+2. Verb progressive -->+    <string name="online_seeking">Seeking <xliff:g id="time_control" example="3+2">%1$s</xliff:g>…</string>+    <!-- Online: Username field label for challenge-by-username. Noun phrase -->+    <string name="online_challenge_username">Challenge by username</string>+    <!-- Online: Challenge button. Sends a game challenge to the typed username. Verb phrase CTA -->+    <string name="online_challenge">Challenge</string>+    <!-- Online: Confirmation after a challenge is sent. %1$s = opponent username e.g. alice. Sentence -->+    <string name="online_challenge_sent">Challenge sent to <xliff:g id="username" example="alice">%1$s</xliff:g>.</string>+    <!-- Online: Notice when the challenged player declines. Sentence -->+    <string name="online_challenge_declined">Challenge declined.</string>+    <!-- Online: Waiting for the Lichess approval to come back to the app. Verb progressive -->+    <string name="online_signing_in">Waiting for Lichess approval…</string>+    <!-- Online: You-resigned result line. Sentence -->+    <string name="online_result_resigned">You resigned.</string>+    <!-- Online: Opponent resigns result line. Sentence -->+    <string name="online_result_opponent_resigned">Opponent resigned. You win!</string>+    <!-- Online: Win result line. Sentence -->+    <string name="online_result_win">You win!</string>+    <!-- Online: Draw result line. Sentence -->+    <string name="online_result_draw">Draw.</string>+    <!-- Online: Loss result line. Sentence -->+    <string name="online_result_loss">You lose.</string>+    <!-- Online: Back-to-lobby button shown after a game ends. Verb phrase -->+    <string name="online_back_to_lobby">Back to lobby</string>+    <!-- Online: Resign confirm dialog title. Verb phrase -->+    <string name="online_resign_title">Resign this game?</string>+    <!-- Online: Resign confirm button. Verb -->+    <string name="online_resign_confirm">Resign</string>+    <!-- Online: Abort confirm dialog title. Shown before either side's first move. Verb phrase -->+    <string name="online_abort_title">Abort this game?</string>+    <!-- Online: Abort confirm button. Verb -->+    <string name="online_abort_confirm">Abort</string>+    <!-- Online: Connection banner while the game stream reconnects. Verb progressive -->+    <string name="online_reconnecting">Reconnecting…</string>+    <!-- Online: Error when the Lichess token expired (HTTP 401). Sentence -->+    <string name="online_auth_expired">Signed out by Lichess — please sign in again.</string>+    <!-- Online: Error when a seek or challenge fails. Sentence -->+    <string name="online_matchmaking_failed">Could not start a game. Try again.</string>+    <!-- Online: Error when sending a move fails. Sentence -->+    <string name="online_move_failed">Move not sent. Try again.</string>+    <!-- Online: Error when sign-in fails. Sentence -->+    <string name="online_sign_in_failed">Sign-in failed. Try again.</string>+    <!-- Online: Opponent label in game screen. %1$s = opponent username. Noun -->+    <string name="online_opponent"><xliff:g id="username" example="alice">%1$s</xliff:g></string> </resources>
games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessModelsTest.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessModelsTest.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessModelsTest.ktnew file mode 100644index 0000000000..264cb53dc7--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/network/LichessModelsTest.kt@@ -0,0 +1,177 @@+package com.vayunmathur.games.chess.network++import com.vayunmathur.games.chess.data.PieceColor+import com.vayunmathur.games.chess.data.PieceType+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlinx.serialization.json.Json++class LichessModelsTest {++    private val json = Json {+        ignoreUnknownKeys = true+        isLenient = true+    }++    // -- UCI parse/serialize --++    @Test+    fun parseSimpleMove() {+        val move = parseUci("e2e4")+        assertEquals(6 to 4, move.from.row to move.from.col)+        assertEquals(4 to 4, move.to.row to move.to.col)+        assertNull(move.promotion)+    }++    @Test+    fun parsePromotion() {+        val move = parseUci("e7e8q")+        assertEquals(1 to 4, move.from.row to move.from.col)+        assertEquals(0 to 4, move.to.row to move.to.col)+        assertEquals(PieceType.QUEEN, move.promotion)+    }++    @Test+    fun parseAllPromotions() {+        assertEquals(PieceType.QUEEN, parseUci("a7a8q").promotion)+        assertEquals(PieceType.ROOK, parseUci("a7a8r").promotion)+        assertEquals(PieceType.BISHOP, parseUci("a7a8b").promotion)+        assertEquals(PieceType.KNIGHT, parseUci("a7a8n").promotion)+    }++    @Test+    fun parseCastling() {+        val kingside = parseUci("e1g1")+        assertEquals(7 to 4, kingside.from.row to kingside.from.col)+        assertEquals(7 to 6, kingside.to.row to kingside.to.col)+        val queenside = parseUci("e8c8")+        assertEquals(0 to 4, queenside.from.row to queenside.from.col)+        assertEquals(0 to 2, queenside.to.row to queenside.to.col)+    }++    @Test+    fun parseRejectsMalformed() {+        assertFailsWith<IllegalArgumentException> { parseUci("e2") }+        assertFailsWith<IllegalArgumentException> { parseUci("e2e4qr") }+        assertFailsWith<IllegalArgumentException> { parseUci("e7e8x") }+    }++    @Test+    fun uciRoundTrip() {+        listOf("e2e4", "e7e8q", "e1g1", "e8c8", "g7g8n").forEach {+            assertEquals(it, parseUci(it).toString())+        }+    }++    @Test+    fun splitMovesEmpty() {+        assertEquals(emptyList(), splitUciMoves(""))+        assertEquals(emptyList(), splitUciMoves("   "))+    }++    @Test+    fun splitMovesSequence() {+        assertEquals(+            listOf("e2e4", "e7e5", "g1f3"),+            splitUciMoves("e2e4 e7e5 g1f3"),+        )+    }++    @Test+    fun colorMapping() {+        assertEquals(PieceColor.WHITE, colorFromLichess("white"))+        assertEquals(PieceColor.BLACK, colorFromLichess("black"))+        assertFailsWith<IllegalArgumentException> { colorFromLichess("red") }+    }++    // -- NDJSON event parsing --++    @Test+    fun gameStartEvent() {+        val envelope = json.decodeFromString(+            LichessEventEnvelope.serializer(),+            """{"type":"gameStart","game":{"gameId":"abc123","color":"white","opponent":{"username":"bob"},"isMyTurn":true}}""",+        )+        val event = envelope.toEvent()+        assertIs<LichessEvent.GameStart>(event)+        assertEquals("abc123", event.gameId)+        assertEquals(PieceColor.WHITE, event.color)+        assertEquals("bob", event.opponent)+    }++    @Test+    fun gameFinishEvent() {+        val envelope = json.decodeFromString(+            LichessEventEnvelope.serializer(),+            """{"type":"gameFinish","game":{"gameId":"abc123"}}""",+        )+        val event = envelope.toEvent()+        assertIs<LichessEvent.GameFinish>(event)+        assertEquals("abc123", event.gameId)+    }++    @Test+    fun unknownEventIgnored() {+        val envelope = json.decodeFromString(+            LichessEventEnvelope.serializer(),+            """{"type":"futureKind","whatever":42}""",+        )+        assertIs<LichessEvent.Ignored>(envelope.toEvent())+    }++    // -- NDJSON game-stream parsing --++    @Test+    fun gameFullDecodesWithState() {+        val update = decodeGameLine(+            json.parseToJsonElement(+                """{"type":"gameFull","id":"g1","rated":false,"variant":{"key":"standard"},"clock":{"initial":180000,"increment":2000},"white":{"id":"u1","name":"alice"},"black":{"id":"u2","name":"bob"},"initialFen":"startpos","state":{"type":"gameState","moves":"e2e4 e7e5","wtime":179000,"btime":180000,"status":"started"}}""",+            ),+            json,+        )+        assertIs<LichessGameUpdate.Full>(update)+        assertEquals("g1", update.game.id)+        assertEquals("e2e4 e7e5", update.game.state.moves)+        assertEquals(PieceColor.BLACK, update.game.myColor("u2"))+        assertEquals(PieceColor.WHITE, update.game.myColor("u1"))+    }++    @Test+    fun gameStateTerminalStatuses() {+        listOf("mate", "resign", "draw", "outoftime", "aborted", "stalemate", "timeout", "cheat")+            .forEach { status ->+                val update = decodeGameLine(+                    json.parseToJsonElement(+                        """{"type":"gameState","moves":"","wtime":0,"btime":0,"status":"$status"}""",+                    ),+                    json,+                )+                assertIs<LichessGameUpdate.State>(update)+                assertEquals(true, update.state.isTerminal, "status=$status")+            }+        val live = decodeGameLine(+            json.parseToJsonElement(+                """{"type":"gameState","moves":"e2e4","wtime":1,"btime":1,"status":"started"}""",+            ),+            json,+        )+        assertIs<LichessGameUpdate.State>(live)+        assertEquals(false, live.state.isTerminal)+    }++    @Test+    fun unknownGameLineIgnored() {+        assertIs<LichessGameUpdate.Ignored>(+            decodeGameLine(json.parseToJsonElement("""{"type":"chatLine","text":"gl"}"""), json)+        )+    }++    @Test+    fun timeControlLabels() {+        assertEquals("3+2", LichessTimeControl.BLITZ_3_2.label)+        assertEquals(4, LichessTimeControl.PRESETS.size)+    }+}
metadata_data/games-chess.md
diff --git a/metadata_data/games-chess.md b/metadata_data/games-chess.mdindex 613fb41cf3..9f54b743a2 100644--- a/metadata_data/games-chess.md+++ b/metadata_data/games-chess.md@@ -5,6 +5,7 @@ Features: - A human-like AI bundled in the app, at four difficulty levels - Around 50,000 Lichess puzzles, selectable by rating - Interactive Learn mode with staged lessons+- Online play via Lichess (quick seek and challenges) - Translated into 20 languages -100% offline+Internet only used for: online play