Fix the hang that made a networked game impossible to leave

Leaving a multiplayer game froze the app for good. Closing a link closed
the BufferedReader first, and BufferedReader.close() wants the very lock
readLine() holds for the whole of a blocking read — a read that only
closing the socket underneath it can ever end, which is the step the
close never reached. Both callers run on the thread drawing the screen
(AppRoot.pop and PlayScreen's onDispose), so the main thread waited on
itself and the app stopped responding. runCatching was no help: nothing
was thrown, it simply never came back.

StreamConnection.close() now closes only the raw streams, which is what
actually ends the read; the reader coroutine then closes its own wrapper
on its own thread, where it owns the lock. Leaving takes single-digit
milliseconds instead of never returning.

It bit chess because chess is the one game here worth leaving in the
middle of. A card hand is over in minutes; a game of chess between two
people who have had enough of it has no natural end, and there was
nothing to end it with, so:

  - Chess has an End game action, with a confirmation, so a table can be
    walked away from without hunting for a way out.

  - A link that drops on its own now reports itself on the same channel
    as everything else, so the device still at the table is told the
    other player has left rather than waiting on a move that is not
    coming. Bye was in the protocol and never sent; nothing needed to
    change on the wire for this.

  - Leaving a table no longer lands back in the lobby that started it. A
    lobby starts advertising the moment it is drawn, so "leave the game"
    used to put the player straight into another one.

Two crashes of the same shape on the same path, both in coroutines
launched in the screen's own scope where nothing catches anything:

  - The host's AI applied a move chosen before it took the lock, checking
    only that the seat had not changed. applyMove throws on a move that
    is no longer legal. Harmless while an AI answered instantly, which
    stopped being true when the chess search moved off-thread and started
    taking seconds. It is now checked against the position as it stands,
    and a stale choice is made again rather than forced.

  - A table the rules reject, or a state a client cannot decode, took the
    app down. Both are now reported.

Covered by MatchControllerNetworkTest, which plays a game over a real
socket pair and leaves it from either end. The leaving test runs on a
daemon thread and asserts it returns, so a regression fails the build
rather than hanging it — verified by reinstating the old close(), which
hangs the suite until it is killed.
This commit is contained in:
Claude
2026-08-06 14:44:01 +00:00
parent ee81fb7bc2
commit 0927e735a2
5 changed files with 468 additions and 21 deletions
@@ -86,12 +86,23 @@ fun AppRoot(env: AppEnv) {
val pop: () -> Unit = {
if (stack.size > 1) {
val leaving = stack.last()
// Leaving a lobby or a table tears the networking down with it.
when (stack.last()) {
when (leaving) {
is Route.Lobby, is Route.Play -> env.lobby.stop()
else -> Unit
}
stack = stack.dropLast(1)
stack = stack.dropLast(1).let { remaining ->
// Leaving a table must not land back in the lobby that started
// it. A lobby starts advertising the moment it is drawn, so
// ending a game would have put the player straight into another
// one — which is no way to leave a game.
if (leaving is Route.Play) {
remaining.dropLastWhile { it is Route.Lobby }
} else {
remaining
}
}
}
}
@@ -72,16 +72,32 @@ fun ChessScreen(
) {
val state by controller.state.collectAsState()
val legal by controller.legalMoves.collectAsState()
val abandoned by controller.abandoned.collectAsState()
var selected by remember { mutableStateOf<Int?>(null) }
// A pawn reaching the last rank is one tap that stands for four moves, so
// the destination is held while the piece is chosen.
var promotionTo by remember { mutableStateOf<Int?>(null) }
// A game with nobody left to play it, or one being walked away from, both end
// through a dialog rather than by silently dropping off the screen.
var confirmingEnd by remember { mutableStateOf(false) }
val endGameAction: @Composable () -> Unit = {
TextButton(onClick = { confirmingEnd = true }) { Text("End game") }
}
val current = state
if (current == null) {
ScreenScaffold(title = "Chess", onBack = onExit) { modifier ->
ScreenScaffold(title = "Chess", onBack = onExit, actions = endGameAction) { modifier ->
Box(modifier, contentAlignment = Alignment.Center) { Text("Setting up…") }
// A table that never arrives — a host that went away mid-handshake —
// still has to be leavable.
abandoned?.let {
LeftTheTableDialog(it, onExit = onExit, onStay = controller::dismissAbandoned)
}
if (confirmingEnd) {
ConfirmEndDialog(onEnd = onExit, onKeepPlaying = { confirmingEnd = false })
}
}
return
}
@@ -104,7 +120,7 @@ fun ChessScreen(
}
}
ScreenScaffold(title = "Chess", onBack = onExit) { modifier ->
ScreenScaffold(title = "Chess", onBack = onExit, actions = endGameAction) { modifier ->
BoxWithConstraints(modifier = modifier) {
val wide = maxWidth > maxHeight
val boardSide = if (wide) {
@@ -152,10 +168,21 @@ fun ChessScreen(
}
}
promotionTo?.let { destination ->
PromotionDialog(
// One dialog at a time, most pressing first. A game nobody can finish
// comes before the result of one that finished, and before a
// half-made promotion: there is no point choosing a piece for a move
// that has nowhere left to go.
val over = abandoned
when {
over != null ->
LeftTheTableDialog(over, onExit = onExit, onStay = controller::dismissAbandoned)
confirmingEnd ->
ConfirmEndDialog(onEnd = onExit, onKeepPlaying = { confirmingEnd = false })
promotionTo != null -> PromotionDialog(
white = current.whiteToMove,
choices = fromSelected.filter { it.to == destination },
choices = fromSelected.filter { it.to == promotionTo },
onPick = {
controller.submit(it)
promotionTo = null
@@ -163,15 +190,48 @@ fun ChessScreen(
},
onDismiss = { promotionTo = null },
)
}
if (current.phase == ChessPhase.GAME_OVER) {
ResultDialog(current, onExit)
current.phase == ChessPhase.GAME_OVER -> ResultDialog(current, onExit)
}
}
}
}
/**
* Leaving a game on purpose.
*
* Chess is the one game here that a player wants out of before the position is
* settled: a card hand is over in minutes, whereas a game of chess between two
* people who are no longer enjoying it has no natural end at all.
*/
@Composable
private fun ConfirmEndDialog(onEnd: () -> Unit, onKeepPlaying: () -> Unit) {
AlertDialog(
onDismissRequest = onKeepPlaying,
title = { Text("End this game?") },
text = {
Text(
"This game ends here and the position is not saved. Anyone else " +
"at the table is told you have left."
)
},
confirmButton = { TextButton(onClick = onEnd) { Text("End the game") } },
dismissButton = { TextButton(onClick = onKeepPlaying) { Text("Keep playing") } },
)
}
/** The other end has gone, so no further move is ever going to arrive. */
@Composable
private fun LeftTheTableDialog(notice: String, onExit: () -> Unit, onStay: () -> Unit) {
AlertDialog(
onDismissRequest = onStay,
title = { Text("The game has ended") },
text = { Text("$notice There are no more moves to play.") },
confirmButton = { TextButton(onClick = onExit) { Text("Leave the game") } },
dismissButton = { TextButton(onClick = onStay) { Text("Look at the board") } },
)
}
@Composable
private fun Board(
state: ChessState,
@@ -372,7 +432,7 @@ private fun ResultDialog(state: ChessState, onExit: () -> Unit) {
)
}
},
confirmButton = { TextButton(onClick = onExit) { Text("Back to the menu") } },
confirmButton = { TextButton(onClick = onExit) { Text("Leave the game") } },
dismissButton = { TextButton(onClick = { dismissed = true }) { Text("Look at the board") } },
)
}