Skip to main content

runecast_protocol/protocol/
server_messages.rs

1//! Server-to-client messages.
2//!
3//! All messages that can be sent from the backend server to frontend clients.
4//! Messages are tagged with `type` field for JSON serialization.
5//!
6//! # Categories
7//!
8//! - **Connection**: Handshake responses, heartbeat acks
9//! - **Lobby State**: Snapshots and deltas for lobby state
10//! - **Game State**: Full game snapshots; changes arrive as discrete events
11//! - **Events**: Discrete events (player joined, word scored, etc.)
12//! - **Errors**: Error responses with codes and messages
13
14use serde::{Deserialize, Serialize};
15
16use crate::protocol::GameType;
17
18use super::types::{
19    default_dictionary, AdminGameInfo, AdventureEventKind, CustomMeta, DebugBackendGameState,
20    DebugHandlerGameState, DebugLobbyState, DebugPlayerInfo, DebugWebsocketContext, ErrorCode,
21    GameConfig, GamePlayerInfo, GameSnapshot, Grid, LobbyChange, LobbyGameInfo, LobbyPlayerInfo,
22    LobbyType, ModeCap, NewsItemPayload, Position, RematchCountdownState, RuneBoxStanding,
23    ScoreInfo, SpectatorInfo, TimerVoteState, TurnPassReason,
24};
25
26/// Messages sent from server to client.
27// Servers box outgoing messages; boxing fields here would change the public API.
28#[allow(clippy::large_enum_variant)]
29#[serde_with::serde_as]
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(tag = "type", rename_all = "snake_case")]
32pub enum ServerMessage {
33    // ========================================================================
34    // Connection Messages
35    // ========================================================================
36    /// Initial server greeting after WebSocket connect.
37    ///
38    /// Sent immediately upon connection, before any other message.
39    Hello {
40        /// Recommended heartbeat interval in milliseconds
41        heartbeat_interval_ms: u32,
42        /// Server version for compatibility checks
43        #[serde(skip_serializing_if = "Option::is_none")]
44        server_version: Option<String>,
45    },
46
47    /// Heartbeat response.
48    ///
49    /// Echoes back for latency calculation.
50    HeartbeatAck {
51        /// Server timestamp when heartbeat was received
52        server_time: u64,
53    },
54
55    // ========================================================================
56    // Lobby State Messages
57    // ========================================================================
58    /// Sent when successfully joining a lobby.
59    LobbyJoined {
60        lobby_id: String,
61        /// 6-char code for custom lobbies
62        #[serde(skip_serializing_if = "Option::is_none")]
63        lobby_code: Option<String>,
64        /// Full lobby state
65        lobby: LobbySnapshot,
66    },
67
68    /// Full lobby state snapshot.
69    ///
70    /// Sent on `request_sync`, and whenever a lobby change needs the whole
71    /// state (sandbox config, a host transfer after a player leaves).
72    LobbySnapshot { lobby: LobbySnapshot },
73
74    /// Incremental lobby state update.
75    ///
76    /// More efficient than full snapshots for small changes.
77    LobbyDelta { changes: Vec<LobbyChange> },
78
79    /// Confirmation of leaving lobby.
80    LobbyLeft,
81
82    /// This connection was replaced by a newer one for the same player and
83    /// is about to be closed.
84    ConnectionReplaced,
85
86    /// Sent to a pooled player the per-mode cap left out of a game start.
87    GameFull {
88        /// The game that filled up.
89        game_id: String,
90        /// The mode whose cap was reached.
91        game_type: GameType,
92    },
93    // ========================================================================
94    // Game Lifecycle Messages
95    // ========================================================================
96    /// A new game has started.
97    ///
98    /// Contains initial game state for all participants.
99    GameStarted {
100        game_id: String,
101        /// Which mode this game is — the same field, and the same reasoning, as
102        /// [`GameSnapshot::game_type`].
103        ///
104        /// v0.18.0 put the mode on the snapshot and stopped there, which left
105        /// the JOIN path still inferring it. That is the worse half to leave
106        /// undone: a snapshot is a reconnect/spectate message, so a player who
107        /// joins normally never receives one, and every bug that has hidden in
108        /// this mode so far hid on exactly this path.
109        #[serde(default)]
110        game_type: GameType,
111        grid: Grid,
112        players: Vec<GamePlayerInfo>,
113        /// Your turn order (0-indexed)
114        your_turn_order: u8,
115        /// Who goes first
116        #[serde_as(as = "serde_with::DisplayFromStr")]
117        current_turn: i64,
118        round: u8,
119        max_rounds: u8,
120        /// Turn time limit in seconds (if configured)
121        #[serde(skip_serializing_if = "Option::is_none")]
122        turn_time_limit: Option<u32>,
123        /// `Some` marks this as an unranked custom (sandbox) game so every
124        /// participant — not just the host — can render the unranked badge.
125        /// Omitted for FFA/Adventure (wire format unchanged).
126        #[serde(default, skip_serializing_if = "Option::is_none")]
127        custom: Option<CustomMeta>,
128        /// Server-authoritative time left in the run, in milliseconds. Set for
129        /// Daily Challenge runs (incl. resumes); omitted otherwise.
130        #[serde(default, skip_serializing_if = "Option::is_none")]
131        time_remaining_ms: Option<u64>,
132        /// Slug of the dictionary this game uses — the same field as
133        /// [`GameSnapshot::dictionary`]. Absent before v0.23.0, so it reads as
134        /// `main`; always serialized.
135        #[serde(default = "default_dictionary")]
136        dictionary: String,
137    },
138
139    /// Full game state snapshot, sent to a player: on a mid-game `join_game`,
140    /// on `request_sync`, when their seat comes back live or the table is
141    /// refreshed, and on every RuneBox round change. A spectator gets
142    /// `SpectatorJoined` instead.
143    GameSnapshot { game_id: String, game: GameSnapshot },
144
145    /// Game has ended normally.
146    GameOver {
147        game_id: String,
148        /// Final scores, sorted by rank
149        final_scores: Vec<ScoreInfo>,
150        /// Winner's user ID
151        #[serde_as(as = "serde_with::DisplayFromStr")]
152        winner_id: i64,
153        /// Whether it was a draw
154        #[serde(default)]
155        is_draw: bool,
156    },
157
158    /// Game was cancelled (not enough players, host left, etc.).
159    GameCancelled { game_id: String, reason: String },
160
161    /// Adventure Mode level ended. Sent after `GameOver` for sessions that
162    /// had `adventure_level.is_some()` in their config. The client uses
163    /// this to render the level-complete modal; the server has already
164    /// upserted the row in `adventure_progress` by the time this is sent.
165    AdventureLevelResult {
166        /// Which level was played (1..=50).
167        level: u32,
168        /// Human player's final score for this run.
169        score: i32,
170        /// Stars awarded (0..=3). 0 = target not hit; 1+ = hit one_star/two_star/three_star.
171        stars: u8,
172        /// True iff `score` exceeded the prior `high_score` for this user + level.
173        personal_best: bool,
174        /// If this run unlocked a new level, the newly-unlocked level id.
175        /// `None` if no new level was unlocked (level was already completed
176        /// or was the campaign finale).
177        #[serde(skip_serializing_if = "Option::is_none")]
178        unlocked_level: Option<u32>,
179        /// This run's duration in milliseconds (from game creation to
180        /// game_over). Lets the client render "Time: 2:34" in the result
181        /// modal without fetching progress. Unsigned since durations
182        /// are non-negative, and consistent with other duration /
183        /// interval fields in the protocol (`heartbeat_interval_ms`,
184        /// `server_time`).
185        #[serde(skip_serializing_if = "Option::is_none")]
186        duration_ms: Option<u64>,
187    },
188
189    /// Daily Challenge run finished (deadline reached or player ended early).
190    /// The server has already recorded the attempt + move log by send time.
191    DailyResult {
192        /// The day's seed (deterministic from the UTC date).
193        seed: i64,
194        /// This run's final score.
195        score: i32,
196        /// The player's best score across today's attempts.
197        personal_best: i32,
198        /// 1-based rank on today's shared leaderboard.
199        rank: u32,
200        /// Attempts used so far today (incl. this one).
201        attempts_used: u8,
202        /// Max attempts today for this user (1 free, 3 premium).
203        attempts_max: u8,
204    },
205
206    /// Adventure Mode random event (bomb / snake / UFO). Broadcast by
207    /// the event scheduler when a roll succeeds at round change.
208    /// `affected_positions` is the set of grid cells the client should
209    /// animate; `new_grid` is the post-effect board so the client can
210    /// swap in the updated tiles atomically with the animation.
211    AdventureEvent {
212        game_id: String,
213        kind: AdventureEventKind,
214        affected_positions: Vec<Position>,
215        /// Full post-effect grid. Clients apply this as an authoritative
216        /// snapshot — no delta needed.
217        new_grid: Grid,
218        /// Short human-readable label for the event, already localized
219        /// server-side. Rendered in a brief toast alongside the animation.
220        label: String,
221    },
222
223    // ========================================================================
224    // Game Event Messages
225    // ========================================================================
226    /// A player joined the lobby.
227    PlayerJoined { player: LobbyPlayerInfo },
228
229    /// A player left the lobby.
230    PlayerLeft {
231        #[serde_as(as = "serde_with::DisplayFromStr")]
232        player_id: i64,
233        #[serde(skip_serializing_if = "Option::is_none")]
234        reason: Option<String>,
235    },
236
237    /// A player reconnected after disconnection.
238    PlayerReconnected {
239        #[serde_as(as = "serde_with::DisplayFromStr")]
240        player_id: i64,
241        /// The game the player was seated in, when known.
242        #[serde(default, skip_serializing_if = "Option::is_none")]
243        game_id: Option<String>,
244    },
245
246    /// A player disconnected (may reconnect).
247    PlayerDisconnected {
248        #[serde(skip_serializing_if = "Option::is_none")]
249        game_id: Option<String>,
250        #[serde_as(as = "serde_with::DisplayFromStr")]
251        player_id: i64,
252        /// Grace period in seconds before they're removed
253        grace_period_seconds: u32,
254    },
255
256    /// A word was successfully scored.
257    WordScored {
258        #[serde_as(as = "serde_with::DisplayFromStr")]
259        player_id: i64,
260        game_id: String,
261        word: String,
262        score: i32,
263        /// Positions that formed the word
264        path: Vec<super::types::Position>,
265        /// New total score
266        total_score: i32,
267        /// Gems earned from this word
268        gems_earned: i32,
269        /// New gem total
270        total_gems: i32,
271        /// Updated grid (letters replaced)
272        new_grid: Grid,
273    },
274
275    /// RuneBox: a word was accepted — sent to the **submitting player only**.
276    ///
277    /// Deliberately not a reuse of [`ServerMessage::WordScored`]. That variant
278    /// carries gems and a full `new_grid`, neither of which exists in RuneBox
279    /// (the board is static and there are no gems), so both would be dead weight
280    /// re-sent on every word — and its `word` field would leak to opponents.
281    RuneBoxWordAccepted {
282        /// Game this word was played in.
283        game_id: String,
284        /// The accepted word, echoed back so the client can list it.
285        word: String,
286        /// Letters gained — equal to the word's length. Sent explicitly so the
287        /// client never re-derives scoring rules locally.
288        letters: i32,
289        /// The submitting player's new running total.
290        total_score: i32,
291    },
292
293    /// RuneBox: another player's score moved — broadcast to everyone else.
294    ///
295    /// Carries **no word, and must never gain one**. RuneBox found-sets are
296    /// independent, so a word another player found is still worth full value to
297    /// you; naming it would hand you the answer. Opponents see the score move
298    /// and nothing more.
299    RuneBoxScoreChanged {
300        /// Whose score changed.
301        #[serde_as(as = "serde_with::DisplayFromStr")]
302        player_id: i64,
303        /// Game the score belongs to.
304        game_id: String,
305        /// That player's new running total.
306        total_score: i32,
307    },
308
309    /// RuneBox: a **round** ended and the match continues.
310    ///
311    /// Deliberately distinct from [`ServerMessage::GameOver`], which keeps its
312    /// existing meaning: the MATCH is over, no further play. That separation is
313    /// what makes this addition non-breaking — every other mode plays exactly
314    /// one round, so it only ever sends `GameOver` and never sees this message.
315    ///
316    /// A client that receives this should present standings and wait, NOT tear
317    /// the game screen down.
318    ///
319    /// Carries no word lists, and must never gain any: the anti-leak rule that
320    /// splits [`ServerMessage::RuneBoxWordAccepted`] from
321    /// [`ServerMessage::RuneBoxScoreChanged`] applies just as much between
322    /// rounds, because an eliminated player may still be watching.
323    RuneBoxRoundEnded {
324        /// Match this round belongs to.
325        game_id: String,
326        /// Which round just finished, 1-based.
327        round: u8,
328        /// How many rounds this match will play at most. `N - 1` for an
329        /// elimination match of N players; 3 for a two-player best-of-3, which
330        /// can still finish in 2.
331        max_rounds: u8,
332        /// THIS round's scores alone, highest first. Not cumulative — the
333        /// running match total lives on `standings`.
334        round_scores: Vec<ScoreInfo>,
335        /// Players eliminated by this round's result.
336        ///
337        /// Empty in a two-player best-of-3, where nobody is eliminated until
338        /// the match itself ends. Normally one id, but the field is a list
339        /// because the rules do not forbid a round that eliminates more than
340        /// one player.
341        #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
342        eliminated: Vec<i64>,
343        /// Every player's match standing after this round — survivors and
344        /// eliminated alike, so a client renders the whole picture without
345        /// accumulating round results itself. A client that missed a round
346        /// (reconnect) is therefore still correct.
347        standings: Vec<RuneBoxStanding>,
348        /// When the next round's board goes live, for the client's countdown.
349        ///
350        /// `None` means the server has not scheduled it yet; it does NOT mean
351        /// the match is over — that is `GameOver`.
352        #[serde(skip_serializing_if = "Option::is_none")]
353        next_round_starts_at: Option<chrono::DateTime<chrono::Utc>>,
354    },
355
356    /// Turn changed to another player.
357    TurnChanged {
358        #[serde_as(as = "serde_with::DisplayFromStr")]
359        player_id: i64,
360        game_id: String,
361        round: u8,
362        /// Time remaining for this turn (if timer active)
363        #[serde(skip_serializing_if = "Option::is_none")]
364        time_remaining: Option<u32>,
365    },
366
367    /// A player passed their turn.
368    TurnPassed {
369        #[serde_as(as = "serde_with::DisplayFromStr")]
370        player_id: i64,
371        game_id: String,
372        /// Why the turn was passed. Absent from backends before v0.49.0.
373        #[serde(default, skip_serializing_if = "Option::is_none")]
374        reason: Option<TurnPassReason>,
375    },
376
377    /// Round number changed.
378    RoundChanged {
379        game_id: String,
380        round: u8,
381        max_rounds: u8,
382        /// New grid if board was regenerated at the start of this round.
383        /// Only present when the game is configured with `regenerate_board_each_round: true`.
384        #[serde(skip_serializing_if = "Option::is_none")]
385        new_grid: Option<Grid>,
386    },
387
388    /// Board was shuffled.
389    BoardShuffled {
390        #[serde_as(as = "serde_with::DisplayFromStr")]
391        player_id: i64,
392        game_id: String,
393        new_grid: Grid,
394        gems_spent: i32,
395        /// Player's remaining gems after shuffle
396        total_gems: i32,
397    },
398
399    /// A tile was swapped.
400    TileSwapped {
401        #[serde_as(as = "serde_with::DisplayFromStr")]
402        player_id: i64,
403        game_id: String,
404        row: usize,
405        col: usize,
406        old_letter: char,
407        new_letter: char,
408        gems_spent: i32,
409        /// Player's remaining gems after swap
410        total_gems: i32,
411    },
412
413    /// Player entered swap mode (for animation).
414    SwapModeEntered {
415        #[serde_as(as = "serde_with::DisplayFromStr")]
416        player_id: i64,
417        game_id: String,
418    },
419
420    /// Player exited swap mode.
421    SwapModeExited {
422        #[serde_as(as = "serde_with::DisplayFromStr")]
423        player_id: i64,
424        game_id: String,
425    },
426
427    // ========================================================================
428    // Spectator Messages
429    // ========================================================================
430    /// Successfully joined as spectator.
431    SpectatorJoined {
432        game_id: String,
433        /// Full game state
434        game: GameSnapshot,
435    },
436
437    /// A new spectator joined (broadcast to others).
438    SpectatorAdded {
439        spectator: SpectatorInfo,
440        game_id: String,
441    },
442
443    /// A spectator left.
444    SpectatorRemoved {
445        #[serde_as(as = "serde_with::DisplayFromStr")]
446        spectator_id: i64,
447        game_id: String,
448    },
449
450    // ========================================================================
451    // Live Update Messages
452    // ========================================================================
453    /// Another player's tile selection (for live preview).
454    SelectionUpdate {
455        #[serde_as(as = "serde_with::DisplayFromStr")]
456        player_id: i64,
457        game_id: String,
458        positions: Vec<super::types::Position>,
459    },
460
461    // ========================================================================
462    // Timer Vote Messages
463    // ========================================================================
464    /// Timer vote state changed.
465    TimerVoteUpdate {
466        state: TimerVoteState,
467        game_id: String,
468    },
469
470    /// Turn timer expired - player auto-passed.
471    TurnTimerExpired {
472        #[serde_as(as = "serde_with::DisplayFromStr")]
473        player_id: i64,
474        game_id: String,
475    },
476
477    // ========================================================================
478    // Rematch Countdown Messages
479    // ========================================================================
480    /// Rematch countdown state update.
481    ///
482    /// Sent to all players on the results screen after a game ends.
483    RematchCountdownUpdate {
484        /// Current countdown state
485        state: RematchCountdownState,
486        /// The game that just ended
487        previous_game_id: String,
488    },
489
490    /// A player opted out of rematch pool.
491    ///
492    /// Broadcast to remaining players so they can update the player list.
493    PlayerLeftRematch {
494        #[serde_as(as = "serde_with::DisplayFromStr")]
495        player_id: i64,
496        /// The game they left from
497        previous_game_id: String,
498    },
499
500    /// Rematch is starting (sent right before `GameStarted`).
501    ///
502    /// Allows frontend to show "Starting..." before the new game begins.
503    RematchStarting {
504        /// Who triggered the early start (None if countdown expired naturally)
505        #[serde(skip_serializing_if = "Option::is_none")]
506        #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
507        triggered_by: Option<i64>,
508        /// The previous game that ended
509        previous_game_id: String,
510    },
511
512    // ========================================================================
513    // Pool
514    // ========================================================================
515    //
516    PlayerPoolChanged {
517        #[serde_as(as = "serde_with::DisplayFromStr")]
518        player_id: i64,
519        old_pool: Option<GameType>,
520        new_pool: Option<GameType>,
521    },
522
523    // ========================================================================
524    // Admin Messages
525    // ========================================================================
526    /// Response to admin game list request.
527    AdminGamesList { games: Vec<AdminGameInfo> },
528
529    /// Game was deleted by admin.
530    AdminGameDeleted { game_id: String },
531
532    // ========================================================================
533    // Legacy Compatibility Messages
534    // ========================================================================
535    /// Lobby state update (legacy format).
536    #[serde(rename = "lobby_state")]
537    LobbyStateUpdate {
538        lobby_id: String,
539        players: Vec<LobbyPlayerInfo>,
540        games: Vec<LobbyGameInfo>,
541    },
542
543    // ========================================================================
544    // Debug Messages
545    // ========================================================================
546    /// Debug state response with player context diagnostics.
547    DebugStateResponse {
548        timestamp: String,
549        player: DebugPlayerInfo,
550        websocket_context: DebugWebsocketContext,
551        lobby_state: Option<DebugLobbyState>,
552        backend_game_state: Option<DebugBackendGameState>,
553        handler_game_state: Option<DebugHandlerGameState>,
554    },
555
556    // ========================================================================
557    // News / Maintenance Announcements
558    // ========================================================================
559    /// A news/notification item was created or activated by an admin.
560    ///
561    /// Pushed to every connected client when an admin posts a new item
562    /// via the news admin endpoints, or when an existing item is
563    /// updated in a way that should re-surface it (becoming active,
564    /// extending expires_at, etc.). Clients should treat it the same
565    /// as if they had just fetched `/api/news` and seen this entry —
566    /// in particular, maintenance items with a future `expires_at`
567    /// drive the corner-countdown toast, while announcement/update
568    /// items go through the existing full-screen overlay.
569    NewsAnnounced { item: NewsItemPayload },
570
571    // ========================================================================
572    // Error Messages
573    // ========================================================================
574    /// Error response.
575    Error {
576        code: ErrorCode,
577        message: String,
578        /// Additional context (e.g., which field was invalid)
579        #[serde(skip_serializing_if = "Option::is_none")]
580        details: Option<serde_json::Value>,
581    },
582}
583
584impl ServerMessage {
585    /// Create an error message from an error code.
586    #[must_use]
587    pub fn error(code: ErrorCode) -> Self {
588        Self::Error {
589            message: code.message().to_string(),
590            code,
591            details: None,
592        }
593    }
594
595    /// Create an error message with custom message.
596    pub fn error_with_message(code: ErrorCode, message: impl Into<String>) -> Self {
597        Self::Error {
598            code,
599            message: message.into(),
600            details: None,
601        }
602    }
603
604    /// Create an error message with details.
605    pub fn error_with_details(
606        code: ErrorCode,
607        message: impl Into<String>,
608        details: serde_json::Value,
609    ) -> Self {
610        Self::Error {
611            code,
612            message: message.into(),
613            details: Some(details),
614        }
615    }
616
617    /// Get the message type as a string (for logging/debugging).
618    #[must_use]
619    pub fn message_type(&self) -> &'static str {
620        match self {
621            Self::Hello { .. } => "hello",
622            Self::HeartbeatAck { .. } => "heartbeat_ack",
623            Self::LobbyJoined { .. } => "lobby_joined",
624            Self::LobbySnapshot { .. } => "lobby_snapshot",
625            Self::LobbyDelta { .. } => "lobby_delta",
626            Self::LobbyLeft => "lobby_left",
627            Self::ConnectionReplaced => "connection_replaced",
628            Self::GameFull { .. } => "game_full",
629            Self::GameStarted { .. } => "game_started",
630            Self::GameSnapshot { .. } => "game_snapshot",
631            Self::GameOver { .. } => "game_over",
632            Self::GameCancelled { .. } => "game_cancelled",
633            Self::AdventureLevelResult { .. } => "adventure_level_result",
634            Self::DailyResult { .. } => "daily_result",
635            Self::AdventureEvent { .. } => "adventure_event",
636            Self::PlayerJoined { .. } => "player_joined",
637            Self::PlayerLeft { .. } => "player_left",
638            Self::PlayerReconnected { .. } => "player_reconnected",
639            Self::PlayerDisconnected { .. } => "player_disconnected",
640            Self::PlayerPoolChanged { .. } => "player_pool_changed",
641            Self::WordScored { .. } => "word_scored",
642            Self::RuneBoxWordAccepted { .. } => "rune_box_word_accepted",
643            Self::RuneBoxScoreChanged { .. } => "rune_box_score_changed",
644            Self::RuneBoxRoundEnded { .. } => "rune_box_round_ended",
645            Self::TurnChanged { .. } => "turn_changed",
646            Self::TurnPassed { .. } => "turn_passed",
647            Self::RoundChanged { .. } => "round_changed",
648            Self::BoardShuffled { .. } => "board_shuffled",
649            Self::TileSwapped { .. } => "tile_swapped",
650            Self::SwapModeEntered { .. } => "swap_mode_entered",
651            Self::SwapModeExited { .. } => "swap_mode_exited",
652            Self::SpectatorJoined { .. } => "spectator_joined",
653            Self::SpectatorAdded { .. } => "spectator_added",
654            Self::SpectatorRemoved { .. } => "spectator_removed",
655            Self::SelectionUpdate { .. } => "selection_update",
656            Self::TimerVoteUpdate { .. } => "timer_vote_update",
657            Self::TurnTimerExpired { .. } => "turn_timer_expired",
658            Self::RematchCountdownUpdate { .. } => "rematch_countdown_update",
659            Self::PlayerLeftRematch { .. } => "player_left_rematch",
660            Self::RematchStarting { .. } => "rematch_starting",
661            Self::AdminGamesList { .. } => "admin_games_list",
662            Self::AdminGameDeleted { .. } => "admin_game_deleted",
663            Self::LobbyStateUpdate { .. } => "lobby_state",
664            Self::DebugStateResponse { .. } => "debug_state_response",
665
666            Self::NewsAnnounced { .. } => "news_announced",
667
668            Self::Error { .. } => "error",
669        }
670    }
671
672    /// Check if this is an error message.
673    #[must_use]
674    pub fn is_error(&self) -> bool {
675        matches!(self, Self::Error { .. })
676    }
677}
678
679/// Convert a `serde_json::Value` to a `ServerMessage`.
680impl TryFrom<serde_json::Value> for ServerMessage {
681    type Error = serde_json::Error;
682
683    fn try_from(
684        value: serde_json::Value,
685    ) -> Result<Self, <ServerMessage as TryFrom<serde_json::Value>>::Error> {
686        serde_json::from_value(value)
687    }
688}
689// ============================================================================
690// Snapshot Types
691// ============================================================================
692
693/// Complete lobby state snapshot.
694#[serde_with::serde_as]
695#[derive(Debug, Clone, Serialize, Deserialize)]
696pub struct LobbySnapshot {
697    pub lobby_id: String,
698    pub lobby_type: LobbyType,
699    #[serde(skip_serializing_if = "Option::is_none")]
700    pub lobby_code: Option<String>,
701    pub players: Vec<LobbyPlayerInfo>,
702    pub games: Vec<LobbyGameInfo>,
703    /// Maximum players allowed
704    #[serde(default = "default_max_players")]
705    pub max_players: u8,
706    /// Current sandbox config for the lobby, if a host has set one.
707    /// Absent for normal (non-sandbox) lobbies.
708    #[serde(default, skip_serializing_if = "Option::is_none")]
709    pub sandbox_config: Option<GameConfig>,
710    /// The lobby's current host (the player who controls sandbox config),
711    /// if one has been assigned. Lets clients show host-only controls and a
712    /// read-only mirror for non-hosts. Updated live on host transfer.
713    /// Serialized as a STRING (like every other id) so JS doesn't lose
714    /// precision on snowflake-magnitude ids (>2^53).
715    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
716    #[serde(default, skip_serializing_if = "Option::is_none")]
717    pub host_id: Option<i64>,
718    /// Whether a finished game arms a rematch countdown (`true`) or an opt-in
719    /// (`false`). Absent from backends before v0.48.0, so it reads as on.
720    #[serde(default = "default_true")]
721    pub auto_rematch: bool,
722    /// Slug of the dictionary the lobby's games use. Absent from backends
723    /// before v0.23.0, so it reads as `main`; always serialized.
724    #[serde(default = "default_dictionary")]
725    pub dictionary: String,
726    /// Per-mode player caps that differ from `max_players`. Absent from
727    /// backends before v0.49.0 (and when empty).
728    #[serde(default, skip_serializing_if = "Vec::is_empty")]
729    pub mode_caps: Vec<ModeCap>,
730}
731
732fn default_max_players() -> u8 {
733    6
734}
735
736fn default_true() -> bool {
737    true
738}
739
740#[cfg(test)]
741mod tests {
742    use super::*;
743    // Test-only: the lib build has no other use of this, so importing it at
744    // module scope makes it an unused import outside `cfg(test)`.
745    use crate::protocol::types::NewsNotificationType;
746    use crate::protocol::{types, GameType};
747
748    #[test]
749    fn test_server_message_into_json() {
750        let msg = ServerMessage::BoardShuffled {
751            player_id: 1_234_567_890,
752            game_id: "1234567890".to_string(),
753            new_grid: Grid::new(),
754            gems_spent: 0,
755            total_gems: 0,
756        };
757        let json = serde_json::to_string(&msg).unwrap();
758        assert!(json.contains(r#""type":"board_shuffled""#));
759        assert!(json.contains(r#""player_id":"1234567890""#));
760        assert!(json.contains(r#""game_id":"1234567890""#));
761        assert!(json.contains(r#""new_grid":[]"#));
762        assert!(json.contains(r#""gems_spent":0"#));
763        assert!(json.contains(r#""total_gems":0"#));
764    }
765
766    #[test]
767    fn test_heartbeat_ack_serialization() {
768        let msg = ServerMessage::HeartbeatAck {
769            server_time: 1_701_234_567_890,
770        };
771        let json = serde_json::to_string(&msg).unwrap();
772        assert!(json.contains(r#""type":"heartbeat_ack""#));
773        assert!(json.contains(r#""server_time":1701234567890"#));
774    }
775
776    #[test]
777    fn test_error_message_creation() {
778        let msg = ServerMessage::error(ErrorCode::NotYourTurn);
779        match msg {
780            ServerMessage::Error { code, message, .. } => {
781                assert_eq!(code, ErrorCode::NotYourTurn);
782                assert_eq!(message, "It's not your turn");
783            }
784            _ => panic!("Expected error message"),
785        }
786    }
787
788    #[test]
789    fn test_error_with_details() {
790        let msg = ServerMessage::error_with_details(
791            ErrorCode::InvalidPath,
792            "Tiles must be adjacent",
793            serde_json::json!({"positions": [[0,0], [2,2]]}),
794        );
795        match msg {
796            ServerMessage::Error { details, .. } => {
797                assert!(details.is_some());
798            }
799            _ => panic!("Expected error message"),
800        }
801    }
802
803    #[test]
804    fn test_player_joined_serialization() {
805        let msg = ServerMessage::PlayerJoined {
806            player: LobbyPlayerInfo {
807                user_id: 123,
808                username: "TestPlayer".to_string(),
809                name: None,
810                avatar_url: None,
811                banner_url: None,
812                accent_color: None,
813                current_game_pool: None,
814                active_game_id: None,
815                spectate_game_id: None,
816            },
817        };
818        let json = serde_json::to_string(&msg).unwrap();
819        assert!(json.contains(r#""type":"player_joined""#));
820        assert!(json.contains(r#""user_id":"123""#));
821    }
822
823    #[test]
824    fn test_message_type() {
825        assert_eq!(
826            ServerMessage::HeartbeatAck { server_time: 0 }.message_type(),
827            "heartbeat_ack"
828        );
829        assert_eq!(
830            ServerMessage::error(ErrorCode::NotYourTurn).message_type(),
831            "error"
832        );
833
834        // Adventure-mode variants — keep these assertions in sync with
835        // any future additions so the match in `message_type()` can't
836        // silently fall out of step with the enum.
837        assert_eq!(
838            ServerMessage::AdventureLevelResult {
839                level: 1,
840                score: 10,
841                stars: 1,
842                personal_best: true,
843                unlocked_level: None,
844                duration_ms: None,
845            }
846            .message_type(),
847            "adventure_level_result",
848        );
849        assert_eq!(
850            ServerMessage::AdventureEvent {
851                game_id: "g".to_string(),
852                kind: types::AdventureEventKind::Bomb,
853                affected_positions: vec![],
854                new_grid: vec![],
855                label: String::new(),
856            }
857            .message_type(),
858            "adventure_event",
859        );
860    }
861
862    #[test]
863    fn test_adventure_level_result_serialization() {
864        // With both optional fields absent: they should be omitted
865        // entirely via skip_serializing_if so older clients don't
866        // see unexpected nulls.
867        let msg = ServerMessage::AdventureLevelResult {
868            level: 3,
869            score: 120,
870            stars: 2,
871            personal_best: false,
872            unlocked_level: None,
873            duration_ms: None,
874        };
875        let json = serde_json::to_string(&msg).unwrap();
876        assert!(json.contains(r#""type":"adventure_level_result""#));
877        assert!(json.contains(r#""level":3"#));
878        assert!(json.contains(r#""score":120"#));
879        assert!(json.contains(r#""stars":2"#));
880        assert!(json.contains(r#""personal_best":false"#));
881        assert!(
882            !json.contains("unlocked_level"),
883            "unlocked_level should be omitted when None (got: {json})"
884        );
885        assert!(
886            !json.contains("duration_ms"),
887            "duration_ms should be omitted when None (got: {json})"
888        );
889
890        // Both optional fields present: serialize with their canonical
891        // field names. duration_ms must be a plain JSON number (u64);
892        // JSON-wise that looks the same as a signed int, but exercising
893        // the path ensures the u64 type didn't accidentally become a
894        // stringified-int somewhere.
895        let msg = ServerMessage::AdventureLevelResult {
896            level: 3,
897            score: 120,
898            stars: 3,
899            personal_best: true,
900            unlocked_level: Some(4),
901            duration_ms: Some(123_456),
902        };
903        let json = serde_json::to_string(&msg).unwrap();
904        assert!(json.contains(r#""unlocked_level":4"#));
905        assert!(json.contains(r#""duration_ms":123456"#));
906
907        // Round-trip — the deserialize path needs to accept the
908        // serialized form and reproduce the same structure.
909        let parsed: ServerMessage = serde_json::from_str(&json).unwrap();
910        match parsed {
911            ServerMessage::AdventureLevelResult {
912                level,
913                score,
914                stars,
915                personal_best,
916                unlocked_level,
917                duration_ms,
918            } => {
919                assert_eq!(level, 3);
920                assert_eq!(score, 120);
921                assert_eq!(stars, 3);
922                assert!(personal_best);
923                assert_eq!(unlocked_level, Some(4));
924                assert_eq!(duration_ms, Some(123_456));
925            }
926            other => panic!("expected AdventureLevelResult, got {other:?}"),
927        }
928    }
929
930    #[test]
931    fn daily_result_serializes() {
932        let msg = ServerMessage::DailyResult {
933            seed: 1_592_668_382,
934            score: 240,
935            personal_best: 240,
936            rank: 3,
937            attempts_used: 1,
938            attempts_max: 1,
939        };
940        assert_eq!(msg.message_type(), "daily_result");
941        let s = serde_json::to_string(&msg).unwrap();
942        assert!(s.contains("\"type\":\"daily_result\""));
943        assert!(s.contains("\"rank\":3"));
944        let back: ServerMessage = serde_json::from_str(&s).unwrap();
945        assert!(matches!(back, ServerMessage::DailyResult { rank: 3, .. }));
946    }
947
948    #[test]
949    fn game_started_time_remaining_optional() {
950        let msg = ServerMessage::GameStarted {
951            game_type: GameType::Open,
952            game_id: "g1".into(),
953            grid: vec![],
954            players: vec![],
955            your_turn_order: 0,
956            current_turn: 42,
957            round: 1,
958            max_rounds: 1,
959            turn_time_limit: None,
960            custom: None,
961            time_remaining_ms: None,
962            dictionary: "main".to_string(),
963        };
964        let s = serde_json::to_string(&msg).unwrap();
965        assert!(!s.contains("time_remaining_ms"));
966    }
967
968    #[test]
969    fn test_adventure_event_serialization() {
970        let msg = ServerMessage::AdventureEvent {
971            game_id: "abc".to_string(),
972            kind: types::AdventureEventKind::Bomb,
973            affected_positions: vec![
974                types::Position { row: 1, col: 2 },
975                types::Position { row: 2, col: 2 },
976            ],
977            new_grid: vec![vec![
978                // One plain cell + one hole cell — this lets the test
979                // assert GridCell's is_hole flag on AdventureEvent's
980                // embedded Grid field stays wire-compatible.
981                types::GridCell {
982                    letter: 'A',
983                    value: 1,
984                    multiplier: None,
985                    has_gem: false,
986                    is_hole: false,
987                    is_poisoned: false,
988                    is_abducted: false,
989                },
990                types::GridCell {
991                    letter: ' ',
992                    value: 0,
993                    multiplier: None,
994                    has_gem: false,
995                    is_hole: true,
996                    is_poisoned: false,
997                    is_abducted: false,
998                },
999            ]],
1000            label: "💣 Bomb!".to_string(),
1001        };
1002
1003        let json = serde_json::to_string(&msg).unwrap();
1004        assert!(json.contains(r#""type":"adventure_event""#));
1005        assert!(json.contains(r#""game_id":"abc""#));
1006        // kind serializes via the enum's snake_case rename.
1007        assert!(json.contains(r#""kind":"bomb""#));
1008        // Affected positions are plain { row, col } objects.
1009        assert!(json.contains(r#""affected_positions":[{"row":1,"col":2}"#));
1010        // new_grid's plain cell omits is_hole; hole cell carries it.
1011        assert!(json.contains(r#""letter":"A""#));
1012        assert!(json.contains(r#""is_hole":true"#));
1013
1014        // Round-trip so we know the type tag + enum field decode correctly.
1015        let parsed: ServerMessage = serde_json::from_str(&json).unwrap();
1016        match parsed {
1017            ServerMessage::AdventureEvent {
1018                game_id,
1019                kind,
1020                affected_positions,
1021                new_grid,
1022                label,
1023            } => {
1024                assert_eq!(game_id, "abc");
1025                assert_eq!(kind, types::AdventureEventKind::Bomb);
1026                assert_eq!(affected_positions.len(), 2);
1027                assert_eq!(new_grid[0].len(), 2);
1028                assert!(new_grid[0][1].is_hole);
1029                assert_eq!(label, "💣 Bomb!");
1030            }
1031            other => panic!("expected AdventureEvent, got {other:?}"),
1032        }
1033    }
1034
1035    #[test]
1036    fn test_selection_update_serialization() {
1037        let msg = ServerMessage::SelectionUpdate {
1038            player_id: 11,
1039            game_id: "game1".to_string(),
1040            positions: vec![
1041                types::Position { row: 0, col: 0 },
1042                types::Position { row: 0, col: 1 },
1043            ],
1044        };
1045        let json = serde_json::to_string(&msg).unwrap();
1046        assert!(json.contains(r#""type":"selection_update""#));
1047        assert!(json.contains(r#""player_id":"11""#));
1048        assert!(json.contains(r#""game_id":"game1""#));
1049    }
1050
1051    #[test]
1052    fn test_player_queue_changed_serialization() {
1053        let msg = ServerMessage::PlayerPoolChanged {
1054            player_id: 123,
1055            old_pool: Some(GameType::Open),
1056            new_pool: Some(GameType::Adventure),
1057        };
1058        let json = serde_json::to_string(&msg).unwrap();
1059        assert!(json.contains(r#""type":"player_pool_changed""#));
1060        assert!(json.contains(r#""player_id":"123""#));
1061        assert!(json.contains(r#""old_pool":"open""#));
1062        assert!(json.contains(r#""new_pool":"adventure""#));
1063    }
1064
1065    #[test]
1066    fn test_debug_state_response_serialization() {
1067        let msg = ServerMessage::DebugStateResponse {
1068            timestamp: "2024-01-01T12:00:00Z".to_string(),
1069            player: DebugPlayerInfo {
1070                user_id: 987654321,
1071                username: "debug_user".to_string(),
1072            },
1073            websocket_context: DebugWebsocketContext {
1074                lobby_id: Some("lobby123".to_string()),
1075                game_id: Some("game456".to_string()),
1076                is_spectating: false,
1077            },
1078            lobby_state: Some(DebugLobbyState::Found {
1079                lobby_id: "lobby123".to_string(),
1080                player_in_lobby: true,
1081                lobby_player_ids: vec![111, 222, 333],
1082                active_game_id: Some("game456".to_string()),
1083            }),
1084            backend_game_state: Some(DebugBackendGameState::Found {
1085                game_id: "game456".to_string(),
1086                player_in_session_players: true,
1087                spectator_in_session: false,
1088                session_player_ids: vec![111, 222],
1089                session_spectator_ids: vec![],
1090                lobby_id: "lobby123".to_string(),
1091            }),
1092            handler_game_state: Some(DebugHandlerGameState::Found {
1093                game_id: "game456".to_string(),
1094                player_in_handler_game: true,
1095                handler_player_ids: vec![111, 222],
1096                current_turn_index: 0,
1097                round: 1,
1098                state: "in_progress".to_string(),
1099            }),
1100        };
1101
1102        // Test serialization
1103        let json = serde_json::to_string(&msg).unwrap();
1104
1105        // Verify type field
1106        assert!(json.contains(r#""type":"debug_state_response""#));
1107
1108        // Verify ID fields are serialized as numbers
1109        assert!(json.contains(r#""user_id":987654321"#));
1110        assert!(json.contains(r#""lobby_player_ids":[111,222,333]"#));
1111        assert!(json.contains(r#""session_player_ids":[111,222]"#));
1112        assert!(json.contains(r#""handler_player_ids":[111,222]"#));
1113
1114        // Verify other key fields
1115        assert!(json.contains(r#""timestamp":"2024-01-01T12:00:00Z""#));
1116        assert!(json.contains(r#""username":"debug_user""#));
1117        assert!(json.contains(r#""lobby_id":"lobby123""#));
1118        assert!(json.contains(r#""game_id":"game456""#));
1119        assert!(json.contains(r#""is_spectating":false"#));
1120        assert!(json.contains(r#""player_in_lobby":true"#));
1121
1122        // Test deserialization (round-trip)
1123        let deserialized: ServerMessage = serde_json::from_str(&json).unwrap();
1124        match deserialized {
1125            ServerMessage::DebugStateResponse {
1126                timestamp,
1127                player,
1128                websocket_context,
1129                lobby_state,
1130                backend_game_state,
1131                handler_game_state,
1132            } => {
1133                assert_eq!(timestamp, "2024-01-01T12:00:00Z");
1134                assert_eq!(player.user_id, 987654321);
1135                assert_eq!(player.username, "debug_user");
1136                assert_eq!(websocket_context.lobby_id, Some("lobby123".to_string()));
1137                assert_eq!(websocket_context.game_id, Some("game456".to_string()));
1138                assert!(!websocket_context.is_spectating);
1139                assert!(lobby_state.is_some());
1140                assert!(backend_game_state.is_some());
1141                assert!(handler_game_state.is_some());
1142            }
1143            _ => panic!("Expected DebugStateResponse message"),
1144        }
1145    }
1146
1147    #[test]
1148    fn test_debug_state_response_with_errors() {
1149        // Test with error variants in debug states
1150        let msg = ServerMessage::DebugStateResponse {
1151            timestamp: "2024-01-01T12:00:00Z".to_string(),
1152            player: DebugPlayerInfo {
1153                user_id: 123,
1154                username: "test".to_string(),
1155            },
1156            websocket_context: DebugWebsocketContext {
1157                lobby_id: None,
1158                game_id: None,
1159                is_spectating: false,
1160            },
1161            lobby_state: Some(DebugLobbyState::Error {
1162                error: "Lobby not found".to_string(),
1163            }),
1164            backend_game_state: Some(DebugBackendGameState::Error {
1165                error: "Game not found".to_string(),
1166            }),
1167            handler_game_state: Some(DebugHandlerGameState::Error {
1168                error: "Handler not found".to_string(),
1169            }),
1170        };
1171
1172        let json = serde_json::to_string(&msg).unwrap();
1173
1174        // Verify error messages are included
1175        assert!(json.contains(r#""error":"Lobby not found""#));
1176        assert!(json.contains(r#""error":"Game not found""#));
1177        assert!(json.contains(r#""error":"Handler not found""#));
1178
1179        // Round-trip test
1180        let deserialized: ServerMessage = serde_json::from_str(&json).unwrap();
1181        assert!(matches!(
1182            deserialized,
1183            ServerMessage::DebugStateResponse { .. }
1184        ));
1185    }
1186
1187    #[test]
1188    fn test_debug_state_response_minimal() {
1189        // Test with None values for optional fields
1190        let msg = ServerMessage::DebugStateResponse {
1191            timestamp: "2024-01-01T12:00:00Z".to_string(),
1192            player: DebugPlayerInfo {
1193                user_id: 456,
1194                username: "minimal_user".to_string(),
1195            },
1196            websocket_context: DebugWebsocketContext {
1197                lobby_id: None,
1198                game_id: None,
1199                is_spectating: true,
1200            },
1201            lobby_state: None,
1202            backend_game_state: None,
1203            handler_game_state: None,
1204        };
1205
1206        let json = serde_json::to_string(&msg).unwrap();
1207
1208        // Verify type field
1209        assert!(json.contains(r#""type":"debug_state_response""#));
1210
1211        // Verify required fields
1212        assert!(json.contains(r#""user_id":456"#));
1213        assert!(json.contains(r#""username":"minimal_user""#));
1214        assert!(json.contains(r#""is_spectating":true"#));
1215
1216        // Round-trip test
1217        let deserialized: ServerMessage = serde_json::from_str(&json).unwrap();
1218        match deserialized {
1219            ServerMessage::DebugStateResponse {
1220                player,
1221                lobby_state,
1222                backend_game_state,
1223                handler_game_state,
1224                ..
1225            } => {
1226                assert_eq!(player.user_id, 456);
1227                assert!(lobby_state.is_none());
1228                assert!(backend_game_state.is_none());
1229                assert!(handler_game_state.is_none());
1230            }
1231            _ => panic!("Expected DebugStateResponse message"),
1232        }
1233    }
1234
1235    #[test]
1236    fn test_news_announced_round_trip() {
1237        let now = chrono::Utc::now();
1238        let expires = now + chrono::Duration::hours(1);
1239        let original = ServerMessage::NewsAnnounced {
1240            item: NewsItemPayload {
1241                id: "abc-123".to_string(),
1242                title: "Scheduled Maintenance".to_string(),
1243                message: "Servers will restart for ~5 minutes.".to_string(),
1244                notification_type: NewsNotificationType::Maintenance,
1245                created_at: now,
1246                expires_at: Some(expires),
1247                auto_hide_seconds: 0,
1248                refresh_on_every_login: false,
1249                priority: 100,
1250            },
1251        };
1252
1253        let json = serde_json::to_string(&original).unwrap();
1254        assert!(json.contains(r#""type":"news_announced""#));
1255        assert!(json.contains(r#""notification_type":"maintenance""#));
1256
1257        let parsed: ServerMessage = serde_json::from_str(&json).unwrap();
1258        match parsed {
1259            ServerMessage::NewsAnnounced { item } => {
1260                assert_eq!(item.id, "abc-123");
1261                assert_eq!(item.notification_type, NewsNotificationType::Maintenance);
1262                assert_eq!(item.priority, 100);
1263                assert_eq!(item.expires_at, Some(expires));
1264            }
1265            _ => panic!("Expected NewsAnnounced"),
1266        }
1267    }
1268
1269    #[test]
1270    fn game_started_custom_marker_roundtrips_and_omits_when_none() {
1271        use crate::protocol::types::CustomMeta;
1272
1273        // Build a GameStarted with custom: Some(CustomMeta {})
1274        let msg = ServerMessage::GameStarted {
1275            game_type: GameType::Open,
1276            game_id: "game-sandbox-1".to_string(),
1277            grid: vec![],
1278            players: vec![types::GamePlayerInfo {
1279                user_id: 111_222_333_444_555_666,
1280                username: "Player1".to_string(),
1281                name: None,
1282                avatar_url: None,
1283                turn_order: 0,
1284                score: 0,
1285                gems: 0,
1286                is_connected: true,
1287                team: None,
1288            }],
1289            your_turn_order: 0,
1290            current_turn: 111_222_333_444_555_666,
1291            round: 1,
1292            max_rounds: 5,
1293            turn_time_limit: None,
1294            custom: Some(CustomMeta {}),
1295            time_remaining_ms: None,
1296            dictionary: "main".to_string(),
1297        };
1298        let json = serde_json::to_string(&msg).unwrap();
1299        assert!(
1300            json.contains("\"custom\""),
1301            "custom should serialize when Some (got: {json})"
1302        );
1303        let back: ServerMessage = serde_json::from_str(&json).unwrap();
1304        assert!(
1305            matches!(
1306                back,
1307                ServerMessage::GameStarted {
1308                    custom: Some(_),
1309                    ..
1310                }
1311            ),
1312            "custom should deserialize as Some"
1313        );
1314
1315        // Same shape but custom: None — field must be absent on the wire
1316        let ffa = ServerMessage::GameStarted {
1317            game_type: GameType::Open,
1318            game_id: "game-ffa-1".to_string(),
1319            grid: vec![],
1320            players: vec![],
1321            your_turn_order: 0,
1322            current_turn: 111_222_333_444_555_666,
1323            round: 1,
1324            max_rounds: 5,
1325            turn_time_limit: None,
1326            custom: None,
1327            time_remaining_ms: None,
1328            dictionary: "main".to_string(),
1329        };
1330        let json2 = serde_json::to_string(&ffa).unwrap();
1331        assert!(
1332            !json2.contains("\"custom\""),
1333            "custom should be omitted when None (got: {json2})"
1334        );
1335    }
1336
1337    #[test]
1338    fn turn_passed_carries_an_optional_reason() {
1339        let m = ServerMessage::TurnPassed {
1340            player_id: 7,
1341            game_id: "g".into(),
1342            reason: Some(crate::TurnPassReason::Disconnected),
1343        };
1344        assert_eq!(serde_json::to_value(&m).unwrap()["reason"], "disconnected");
1345        let old: ServerMessage =
1346            serde_json::from_str(r#"{"type":"turn_passed","player_id":"7","game_id":"g"}"#)
1347                .unwrap();
1348        assert!(matches!(
1349            old,
1350            ServerMessage::TurnPassed { reason: None, .. }
1351        ));
1352        let none = ServerMessage::TurnPassed {
1353            player_id: 7,
1354            game_id: "g".into(),
1355            reason: None,
1356        };
1357        assert!(serde_json::to_value(&none).unwrap().get("reason").is_none());
1358    }
1359
1360    #[test]
1361    fn player_reconnected_names_its_game_when_known() {
1362        let m = ServerMessage::PlayerReconnected {
1363            player_id: 7,
1364            game_id: Some("g".into()),
1365        };
1366        assert_eq!(serde_json::to_value(&m).unwrap()["game_id"], "g");
1367        let none = ServerMessage::PlayerReconnected {
1368            player_id: 7,
1369            game_id: None,
1370        };
1371        assert!(serde_json::to_value(&none)
1372            .unwrap()
1373            .get("game_id")
1374            .is_none());
1375        let old: ServerMessage =
1376            serde_json::from_str(r#"{"type":"player_reconnected","player_id":"7"}"#).unwrap();
1377        assert!(matches!(
1378            old,
1379            ServerMessage::PlayerReconnected { game_id: None, .. }
1380        ));
1381    }
1382
1383    #[test]
1384    fn connection_replaced_is_a_bare_tag() {
1385        let m = ServerMessage::ConnectionReplaced;
1386        assert_eq!(
1387            serde_json::to_string(&m).unwrap(),
1388            r#"{"type":"connection_replaced"}"#
1389        );
1390        assert_eq!(m.message_type(), "connection_replaced");
1391    }
1392
1393    #[test]
1394    fn game_full_round_trips() {
1395        let m = ServerMessage::GameFull {
1396            game_id: "g".into(),
1397            game_type: GameType::Open,
1398        };
1399        let json = serde_json::to_string(&m).unwrap();
1400        assert_eq!(
1401            serde_json::from_str::<serde_json::Value>(&json).unwrap(),
1402            serde_json::from_str::<serde_json::Value>(
1403                r#"{"type":"game_full","game_id":"g","game_type":"open"}"#
1404            )
1405            .unwrap()
1406        );
1407        assert!(matches!(
1408            serde_json::from_str::<ServerMessage>(&json).unwrap(),
1409            ServerMessage::GameFull {
1410                game_type: GameType::Open,
1411                ..
1412            }
1413        ));
1414        assert_eq!(m.message_type(), "game_full");
1415    }
1416
1417    #[test]
1418    fn lobby_snapshot_mode_caps_are_additive() {
1419        let old = r#"{"lobby_id":"l","lobby_type":"custom","players":[],"games":[]}"#;
1420        let snap: LobbySnapshot = serde_json::from_str(old).unwrap();
1421        assert!(snap.mode_caps.is_empty());
1422        assert!(!serde_json::to_string(&snap).unwrap().contains("mode_caps"));
1423        let capped = LobbySnapshot {
1424            mode_caps: vec![crate::ModeCap {
1425                game_type: GameType::Open,
1426                max_players: 5,
1427            }],
1428            ..snap
1429        };
1430        let v = serde_json::to_value(&capped).unwrap();
1431        assert_eq!(
1432            v["mode_caps"],
1433            serde_json::json!([{"game_type":"open","max_players":5}])
1434        );
1435    }
1436
1437    #[test]
1438    fn connect_params_parse_kind_and_tab() {
1439        use crate::{ConnectKind, ConnectParams};
1440        assert_eq!(
1441            serde_json::to_string(&ConnectKind::TakeOver).unwrap(),
1442            r#""take_over""#
1443        );
1444        let p: ConnectParams = serde_json::from_str(r#"{"tab":"t1","kind":"take_over"}"#).unwrap();
1445        assert_eq!(p.tab.as_deref(), Some("t1"));
1446        assert_eq!(p.kind, Some(ConnectKind::TakeOver));
1447        let d = ConnectParams::default();
1448        assert!(d.tab.is_none() && d.kind.is_none());
1449    }
1450
1451    #[test]
1452    fn lobby_snapshot_carries_sandbox_config() {
1453        // Build a minimal LobbySnapshot with sandbox_config set.
1454        let mut snap = LobbySnapshot {
1455            lobby_id: "test-lobby".to_string(),
1456            lobby_type: LobbyType::Custom,
1457            lobby_code: None,
1458            players: vec![],
1459            games: vec![],
1460            max_players: 6,
1461            sandbox_config: None,
1462            host_id: None,
1463            auto_rematch: true,
1464            mode_caps: vec![],
1465            dictionary: "main".to_string(),
1466        };
1467        snap.sandbox_config = Some(GameConfig::default());
1468
1469        let json = serde_json::to_string(&snap).unwrap();
1470        assert!(
1471            json.contains("sandbox_config"),
1472            "sandbox_config should be present when Some (got: {json})"
1473        );
1474        let back: LobbySnapshot = serde_json::from_str(&json).unwrap();
1475        assert!(back.sandbox_config.is_some());
1476
1477        // Confirm it's omitted on the wire when None (back-compat).
1478        let plain = LobbySnapshot {
1479            lobby_id: "plain-lobby".to_string(),
1480            lobby_type: LobbyType::Custom,
1481            lobby_code: None,
1482            players: vec![],
1483            games: vec![],
1484            max_players: 6,
1485            sandbox_config: None,
1486            host_id: None,
1487            auto_rematch: true,
1488            mode_caps: vec![],
1489            dictionary: "main".to_string(),
1490        };
1491        assert!(
1492            !serde_json::to_string(&plain)
1493                .unwrap()
1494                .contains("sandbox_config"),
1495            "sandbox_config should be omitted when None"
1496        );
1497        assert!(
1498            !serde_json::to_string(&plain).unwrap().contains("host_id"),
1499            "host_id should be omitted when None"
1500        );
1501    }
1502
1503    #[test]
1504    fn lobby_snapshot_host_id_serializes_as_string_snowflake_safe() {
1505        // host_id must serialize as a STRING (like every other id) so JS
1506        // doesn't lose precision on snowflake-magnitude ids (>2^53). A
1507        // JSON-number would round and break host detection on the client.
1508        let snowflake: i64 = 123_456_789_012_345_678; // 18 digits, > 2^53
1509        let snap = LobbySnapshot {
1510            lobby_id: "lobby".to_string(),
1511            lobby_type: LobbyType::Custom,
1512            lobby_code: None,
1513            players: vec![],
1514            games: vec![],
1515            max_players: 6,
1516            sandbox_config: None,
1517            host_id: Some(snowflake),
1518            auto_rematch: true,
1519            mode_caps: vec![],
1520            dictionary: "main".to_string(),
1521        };
1522        let json = serde_json::to_string(&snap).unwrap();
1523        // Quoted = string on the wire; an unquoted number would be the bug.
1524        assert!(
1525            json.contains(r#""host_id":"123456789012345678""#),
1526            "host_id must serialize as a quoted string, got: {json}"
1527        );
1528        // Exact round-trip (no precision loss).
1529        let back: LobbySnapshot = serde_json::from_str(&json).unwrap();
1530        assert_eq!(back.host_id, Some(snowflake));
1531    }
1532
1533    #[test]
1534    fn runebox_word_accepted_round_trips() {
1535        let msg = ServerMessage::RuneBoxWordAccepted {
1536            game_id: "g1".to_string(),
1537            word: "RUNES".to_string(),
1538            letters: 5,
1539            total_score: 17,
1540        };
1541        let json = serde_json::to_string(&msg).unwrap();
1542        assert!(json.contains(r#""type":"rune_box_word_accepted""#));
1543        let back: ServerMessage = serde_json::from_str(&json).unwrap();
1544        match back {
1545            ServerMessage::RuneBoxWordAccepted {
1546                word,
1547                letters,
1548                total_score,
1549                ..
1550            } => {
1551                assert_eq!(word, "RUNES");
1552                assert_eq!(letters, 5);
1553                assert_eq!(total_score, 17);
1554            }
1555            other => panic!("wrong variant: {other:?}"),
1556        }
1557    }
1558
1559    #[test]
1560    fn runebox_score_changed_carries_no_word() {
1561        // THE anti-leak assertion. RuneBox found-sets are independent, so a word
1562        // another player found is still worth full value to you — telling you
1563        // what it was would hand you the answer. This variant having no `word`
1564        // field is what enforces that, so assert on the serialized form: a
1565        // future field addition fails here rather than silently shipping.
1566        let msg = ServerMessage::RuneBoxScoreChanged {
1567            player_id: 1_234_567_890_123_456_789,
1568            game_id: "g1".to_string(),
1569            total_score: 12,
1570        };
1571        let json = serde_json::to_string(&msg).unwrap();
1572        assert!(
1573            !json.contains("word"),
1574            "opponent broadcast leaked a word: {json}"
1575        );
1576        // Snowflakes ride as strings or they corrupt above 2^53 in JS.
1577        assert!(
1578            json.contains(r#""player_id":"1234567890123456789""#),
1579            "player_id must serialize as a quoted string, got: {json}"
1580        );
1581        let back: ServerMessage = serde_json::from_str(&json).unwrap();
1582        match back {
1583            ServerMessage::RuneBoxScoreChanged {
1584                player_id,
1585                total_score,
1586                ..
1587            } => {
1588                assert_eq!(player_id, 1_234_567_890_123_456_789);
1589                assert_eq!(total_score, 12);
1590            }
1591            other => panic!("wrong variant: {other:?}"),
1592        }
1593    }
1594
1595    #[test]
1596    fn runebox_messages_have_distinct_wire_types() {
1597        let accepted = ServerMessage::RuneBoxWordAccepted {
1598            game_id: "g1".to_string(),
1599            word: "RUNES".to_string(),
1600            letters: 5,
1601            total_score: 5,
1602        };
1603        let changed = ServerMessage::RuneBoxScoreChanged {
1604            player_id: 1,
1605            game_id: "g1".to_string(),
1606            total_score: 5,
1607        };
1608        assert_eq!(accepted.message_type(), "rune_box_word_accepted");
1609        assert_eq!(changed.message_type(), "rune_box_score_changed");
1610    }
1611
1612    /// The JOIN path must be self-describing too.
1613    ///
1614    /// v0.18.0 put the mode on `GameSnapshot` and stopped, which fixed the
1615    /// reconnect/spectate path and left the one a normal player actually takes
1616    /// still inferring. Both halves or neither.
1617    #[test]
1618    fn game_started_carries_its_game_type() {
1619        let msg = ServerMessage::GameStarted {
1620            game_type: GameType::RuneBox,
1621            game_id: "g1".to_string(),
1622            grid: vec![],
1623            players: vec![],
1624            your_turn_order: 0,
1625            current_turn: 1,
1626            round: 1,
1627            max_rounds: 3,
1628            turn_time_limit: None,
1629            custom: None,
1630            time_remaining_ms: Some(90_000),
1631            dictionary: "main".to_string(),
1632        };
1633        let json = serde_json::to_string(&msg).unwrap();
1634        assert!(
1635            json.contains(r#""game_type":"rune_box""#),
1636            "game_started must name the mode, got: {json}"
1637        );
1638        let back: ServerMessage = serde_json::from_str(&json).unwrap();
1639        match back {
1640            ServerMessage::GameStarted { game_type, .. } => {
1641                assert_eq!(game_type, GameType::RuneBox);
1642            }
1643            other => panic!("wrong variant: {other:?}"),
1644        }
1645    }
1646
1647    /// A two-round match state used by the round-end tests below.
1648    fn round_ended_sample(
1649        next_round_starts_at: Option<chrono::DateTime<chrono::Utc>>,
1650    ) -> ServerMessage {
1651        ServerMessage::RuneBoxRoundEnded {
1652            game_id: "g1".to_string(),
1653            round: 1,
1654            max_rounds: 2,
1655            round_scores: vec![
1656                ScoreInfo {
1657                    user_id: 1_234_567_890_123_456_789,
1658                    username: "Ada".to_string(),
1659                    name: None,
1660                    score: 41,
1661                },
1662                ScoreInfo {
1663                    user_id: 8_876_543_210_987_654_321_i64,
1664                    username: "Bo".to_string(),
1665                    name: None,
1666                    score: 12,
1667                },
1668            ],
1669            eliminated: vec![8_876_543_210_987_654_321_i64],
1670            standings: vec![RuneBoxStanding {
1671                player_id: 1_234_567_890_123_456_789,
1672                username: "Ada".to_string(),
1673                name: None,
1674                round_wins: 1,
1675                total_score: 41,
1676                eliminated: false,
1677            }],
1678            next_round_starts_at,
1679        }
1680    }
1681
1682    /// Round-end must be its OWN message. `GameOver` keeps meaning "the match is
1683    /// over" — that is what makes this addition non-breaking for the modes that
1684    /// play exactly one round and only ever send `GameOver`.
1685    #[test]
1686    fn round_end_is_a_distinct_message_type_from_game_over() {
1687        let round_end = round_ended_sample(None);
1688        let match_end = ServerMessage::GameOver {
1689            game_id: "g1".to_string(),
1690            final_scores: vec![],
1691            winner_id: 1,
1692            is_draw: false,
1693        };
1694        assert_eq!(round_end.message_type(), "rune_box_round_ended");
1695        assert_eq!(match_end.message_type(), "game_over");
1696        assert_ne!(round_end.message_type(), match_end.message_type());
1697    }
1698
1699    #[test]
1700    fn round_ended_round_trips_with_snowflakes_as_strings() {
1701        let json = serde_json::to_string(&round_ended_sample(None)).unwrap();
1702        assert!(json.contains(r#""type":"rune_box_round_ended""#));
1703        // Every snowflake on this message rides as a quoted string, including
1704        // the ones inside the `eliminated` list — a bare i64 there corrupts
1705        // above 2^53 in JS exactly like a top-level one would.
1706        assert!(
1707            json.contains(r#""eliminated":["8876543210987654321"]"#),
1708            "eliminated ids must be quoted strings, got: {json}"
1709        );
1710        assert!(
1711            json.contains(r#""player_id":"1234567890123456789""#),
1712            "standings player_id must be a quoted string, got: {json}"
1713        );
1714        assert!(
1715            json.contains(r#""user_id":"1234567890123456789""#),
1716            "round score user_id must be a quoted string, got: {json}"
1717        );
1718
1719        let back: ServerMessage = serde_json::from_str(&json).unwrap();
1720        match back {
1721            ServerMessage::RuneBoxRoundEnded {
1722                round,
1723                max_rounds,
1724                round_scores,
1725                eliminated,
1726                standings,
1727                next_round_starts_at,
1728                ..
1729            } => {
1730                assert_eq!(round, 1);
1731                assert_eq!(max_rounds, 2);
1732                assert_eq!(round_scores.len(), 2);
1733                assert_eq!(eliminated, vec![8_876_543_210_987_654_321_i64]);
1734                assert_eq!(standings[0].round_wins, 1);
1735                assert_eq!(standings[0].total_score, 41);
1736                assert!(!standings[0].eliminated);
1737                assert!(next_round_starts_at.is_none());
1738            }
1739            other => panic!("wrong variant: {other:?}"),
1740        }
1741    }
1742
1743    /// The SP1 anti-leak rule does not lapse between rounds. An eliminated
1744    /// player is still watching, and the survivors keep playing boards they
1745    /// remember, so a round-end summary must never name anyone's words.
1746    #[test]
1747    fn round_ended_leaks_no_words() {
1748        let json = serde_json::to_string(&round_ended_sample(None)).unwrap();
1749        assert!(
1750            !json.contains("word"),
1751            "round-end summary leaked a word field: {json}"
1752        );
1753    }
1754
1755    /// `None` means "not scheduled yet", not "match over" — so it must be
1756    /// omitted rather than serialized as an explicit null a client could
1757    /// misread as a value.
1758    #[test]
1759    fn round_ended_omits_unscheduled_next_round() {
1760        let json = serde_json::to_string(&round_ended_sample(None)).unwrap();
1761        assert!(!json.contains("next_round_starts_at"), "got: {json}");
1762
1763        let at = chrono::DateTime::parse_from_rfc3339("2026-07-29T12:00:00Z")
1764            .unwrap()
1765            .with_timezone(&chrono::Utc);
1766        let json = serde_json::to_string(&round_ended_sample(Some(at))).unwrap();
1767        assert!(json.contains("next_round_starts_at"), "got: {json}");
1768        let back: ServerMessage = serde_json::from_str(&json).unwrap();
1769        match back {
1770            ServerMessage::RuneBoxRoundEnded {
1771                next_round_starts_at,
1772                ..
1773            } => assert_eq!(next_round_starts_at, Some(at)),
1774            other => panic!("wrong variant: {other:?}"),
1775        }
1776    }
1777
1778    #[test]
1779    fn a_snapshot_without_auto_rematch_reads_as_on() {
1780        let json = r#"{"lobby_id":"l","lobby_type":"channel","players":[],"games":[]}"#;
1781        let snap: LobbySnapshot = serde_json::from_str(json).unwrap();
1782        assert!(
1783            snap.auto_rematch,
1784            "an older server's snapshot must read as auto-rematch on"
1785        );
1786    }
1787
1788    #[test]
1789    fn a_snapshot_carries_auto_rematch_off() {
1790        let json = r#"{"lobby_id":"l","lobby_type":"channel","players":[],"games":[],"auto_rematch":false}"#;
1791        let snap: LobbySnapshot = serde_json::from_str(json).unwrap();
1792        assert!(!snap.auto_rematch);
1793        let out = serde_json::to_string(&snap).unwrap();
1794        assert!(out.contains(r#""auto_rematch":false"#), "{out}");
1795    }
1796
1797    #[test]
1798    fn a_snapshot_without_dictionary_reads_as_main() {
1799        let json = r#"{"lobby_id":"l","lobby_type":"channel","players":[],"games":[]}"#;
1800        let snap: LobbySnapshot = serde_json::from_str(json).unwrap();
1801        assert_eq!(snap.dictionary, "main");
1802    }
1803
1804    #[test]
1805    fn a_snapshot_always_serializes_dictionary() {
1806        let json = r#"{"lobby_id":"l","lobby_type":"channel","players":[],"games":[]}"#;
1807        let snap: LobbySnapshot = serde_json::from_str(json).unwrap();
1808        let out = serde_json::to_string(&snap).unwrap();
1809        assert!(out.contains(r#""dictionary":"main""#), "{out}");
1810    }
1811
1812    #[test]
1813    fn a_game_started_without_dictionary_reads_as_main() {
1814        let json = r#"{"type":"game_started","game_id":"g","grid":[],"players":[],"your_turn_order":0,"current_turn":"1","round":1,"max_rounds":3}"#;
1815        match serde_json::from_str::<ServerMessage>(json).unwrap() {
1816            ServerMessage::GameStarted { dictionary, .. } => assert_eq!(dictionary, "main"),
1817            other => panic!("wrong variant: {other:?}"),
1818        }
1819    }
1820}