From 43b45fabc7f713794183dbdd82b4d5d339ee81c3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:44:03 +0200 Subject: [PATCH 1/4] Horizon extras: auto-reconnect, off by default On the Disconnected screen after a lost multiplayer connection, a countdown "Reconnecting in N s" with a Cancel button, then the same address again. Attempts back off (5, 10, 20, 40, 60 s) and stop after five; the count resets only after a minute connected. Only failed connections and the server's shutdown, restart, time-out or full reasons are retried, never kicks, bans, whitelists, version refusals or duplicate logins: the network thread now says whether the server gave the reason (login refusals included). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/extras.rs | 20 +- crates/horizon-client/src/front.rs | 20 +- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/extras.rs | 52 +++++ crates/horizon-client/src/game/remote.rs | 21 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/multiplayer.rs | 48 ++++- crates/horizon-client/src/net.rs | 32 +-- crates/horizon-client/src/reconnect.rs | 235 +++++++++++++++++++++++ crates/horizon-client/src/title.rs | 7 + 10 files changed, 411 insertions(+), 26 deletions(-) create mode 100644 crates/horizon-client/src/reconnect.rs diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index 33854e67d..86c301603 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -92,6 +92,8 @@ pub struct Extras { pub minimap_zoom: f32, /// Turn with the player (forward up) instead of north up. pub minimap_rotate: bool, + /// Retry lost multiplayer connections (`reconnect`). + pub auto_reconnect: bool, } impl Default for Extras { fn default() -> Self { @@ -113,6 +115,7 @@ impl Default for Extras { minimap_round: false, minimap_zoom: 1.0, minimap_rotate: false, + auto_reconnect: false, } } } @@ -169,6 +172,7 @@ impl Extras { } } "minimapRotate" => e.minimap_rotate = flag(e.minimap_rotate), + "autoReconnect" => e.auto_reconnect = flag(e.auto_reconnect), _ => {} } } @@ -176,7 +180,7 @@ impl Extras { } pub fn serialize(&self) -> String { format!( - "zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\n", + "zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\n", bool_text(self.zoom), self.zoom_key, self.zoom_level, @@ -198,6 +202,7 @@ impl Extras { }, self.minimap_zoom, bool_text(self.minimap_rotate), + bool_text(self.auto_reconnect), ) } /// Written only once something differs from the defaults, so a vanilla @@ -398,6 +403,7 @@ pub enum Item { MinimapShape, MinimapZoom, MinimapRotate, + AutoReconnect, } /// The Extras page: headers and items. pub fn rows() -> Vec> { @@ -424,6 +430,8 @@ pub fn rows() -> Vec> { Ok(Keystrokes), Ok(KeystrokesCorner), Ok(KeystrokesCps), + Err("Multiplayer"), + Ok(AutoReconnect), ] } /// "1 block", "2 blocks", "½ block". @@ -456,6 +464,7 @@ impl Item { Item::MinimapShape => "Shape", Item::MinimapZoom => "Zoom", Item::MinimapRotate => "Turn with the player", + Item::AutoReconnect => "Auto-reconnect", Item::FpsLows => "Minimum and 1% low", Item::Keystrokes => "Keystrokes", Item::KeystrokesCps => "Clicks per second", @@ -478,6 +487,9 @@ impl Item { Item::MinimapShape => "Square or round.", Item::MinimapZoom => "Blocks per pixel: smaller shows more detail, larger more land.", Item::MinimapRotate => "Forward is up; off keeps north up.", + Item::AutoReconnect => { + "Rejoins a server after a lost connection or a restart, never after a kick or ban." + } Item::FpsLows => "The slowest frame and the 1% low of the last 5 seconds.", Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.", Item::KeystrokesCps => "Clicks in the last second under each mouse button.", @@ -489,6 +501,7 @@ impl Item { match self { Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None), Item::Minimap => Some(Cost::Low), + Item::AutoReconnect => Some(Cost::None), _ => None, } } @@ -504,6 +517,7 @@ impl Item { Item::KeystrokesCps => e.keystrokes_cps, Item::Minimap => e.minimap, Item::MinimapRotate => e.minimap_rotate, + Item::AutoReconnect => e.auto_reconnect, _ => return None, }) } @@ -545,6 +559,7 @@ impl Item { } Item::Minimap => e.minimap = !e.minimap, Item::MinimapRotate => e.minimap_rotate = !e.minimap_rotate, + Item::AutoReconnect => e.auto_reconnect = !e.auto_reconnect, Item::MinimapCorner => e.minimap_corner = next(&Corner::ALL, e.minimap_corner, back), Item::MinimapSize => { let sizes: Vec = MINIMAP_SIZES.iter().map(|s| s.0).collect(); @@ -564,7 +579,7 @@ mod tests { #[test] fn everything_is_off_by_default_and_round_trips() { let d = Extras::default(); - assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap); + assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect); assert_eq!(Extras::parse(""), d); assert_eq!(Extras::parse(&d.serialize()), d); let mut e = d.clone(); @@ -580,6 +595,7 @@ mod tests { e.minimap_zoom = 0.5; e.minimap_rotate = true; e.minimap_corner = Corner::BottomLeft; + e.auto_reconnect = true; assert_eq!(Extras::parse(&e.serialize()), e); } diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index a99bfaf57..52bd977aa 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -38,6 +38,7 @@ const REFRESH: u64 = id("mp.refresh", 0); const FIELD_A: u64 = id("mp.field", 0); const FIELD_B: u64 = id("mp.field", 1); const DONE: u64 = id("mp.done", 0); +const CANCEL_RETRY: u64 = id("mp.cancel_retry", 0); /// The launcher's opening (`launcher/src/main.rs`): the wordmark holds over /// the backdrop, then the interface comes in. A click or a key skips ahead. @@ -404,6 +405,7 @@ impl Title { Screen::Direct { .. } => 53, Screen::Disconnected { .. } => 54, }), + CANCEL_RETRY => Some(55), DONE => Some(match screen { Screen::Direct { .. } => 52, _ => 50, @@ -809,7 +811,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { ); ui.divider(x, y + rh, w); } - Screen::Disconnected { reason } => { + Screen::Disconnected { reason, retry } => { let mut y = header( ui, x, @@ -836,6 +838,12 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { ); } y += box_h + 16.0; + if let Some(r) = retry { + // Auto-reconnect's countdown, with a way out. + let text = r.text(std::time::Instant::now()); + ui.text_line(Face::Regular, BODY, 19.0, x, y, color::MUTED, &text); + y += 19.0 + 12.0; + } let bw = ui.button_width("Back to servers", false); ui.button( BACK, @@ -844,6 +852,16 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { Kind::Secondary, true, ); + if retry.is_some() { + let cw = ui.button_width("Cancel reconnecting", false); + ui.button( + CANCEL_RETRY, + [x + bw + 8.0, y, cw, CONTROL], + "Cancel reconnecting", + Kind::Ghost, + true, + ); + } } } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 88163e47c..4d721d6e0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8691,6 +8691,7 @@ impl ApplicationHandler for Game<'_> { } } self.extras_frame(elapsed); + self.extras_retry()?; self.apply_mouse_look(); self.pad_look(elapsed.as_secs_f32()); self.advance_flight(); diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 721dc0280..0ef74407c 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -9,6 +9,9 @@ use horizon_client::{ hud::{HudBatch, MINIMAP_SPRITE}, keybinds, minimap::{self, Layer, Minimap, View}, + multiplayer, + reconnect::{Retry, Tracker}, + title::Mode, }; use std::time::Duration; use winit::{event::MouseButton, keyboard::KeyCode}; @@ -23,6 +26,8 @@ pub(super) struct ExtrasState { minimap: Minimap, /// The dimension the minimap's tiles belong to. minimap_dim: Option, + /// Auto-reconnect's attempts at the current server. + reconnect: Tracker, } /// CPU time the minimap's tiles may take per frame. const MINIMAP_BUDGET: Duration = Duration::from_micros(300); @@ -85,6 +90,53 @@ impl Game<'_> { self.extras.fps.clear(); } } + /// Auto-reconnect: a connection to `address` starts. + pub(super) fn extras_connecting(&mut self, address: &str) { + self.extras.reconnect.connecting(address); + } + /// Auto-reconnect: the server let the player in. + pub(super) fn extras_joined(&mut self) { + self.extras.reconnect.joined(std::time::Instant::now()); + } + /// Auto-reconnect: the player left the server on purpose. + pub(super) fn extras_left(&mut self) { + self.extras.reconnect.reset(); + } + /// Auto-reconnect's next attempt after a disconnect, when it is on and + /// the reason allows one. + pub(super) fn reconnect_after(&mut self, reason: &str, from_server: bool) -> Option { + if !self.settings.extras.auto_reconnect { + self.extras.reconnect.reset(); + return None; + } + let now = std::time::Instant::now(); + self.extras.reconnect.ended(reason, from_server, now) + } + /// Show the attempt's countdown on the Disconnected screen. + pub(super) fn offer_reconnect(&mut self, retry: Option) { + let Some(retry) = retry else { + return; + }; + if let Some(title) = self.title.as_mut() + && let Mode::Multiplayer(multiplayer::Screen::Disconnected { retry: slot, .. }) = + &mut title.mode + { + log::info!( + "Horizon: reconnecting to {} in {} s", + retry.address, + retry.seconds_left(std::time::Instant::now()) + ); + *slot = Some(retry); + } + } + /// Auto-reconnect: connect again once the countdown is over. + pub(super) fn extras_retry(&mut self) -> horizon_client::Result<()> { + if let Some(address) = self.title.as_mut().and_then(|t| t.due_retry()) { + let name = self.options.player_name.clone(); + self.connect_server(&address, &name)?; + } + Ok(()) + } /// The minimap's view of the player, if it shows. fn minimap_view(&self) -> Option { let e = &self.settings.extras; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index ae6b810d4..bc2268653 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -162,6 +162,7 @@ impl Game<'_> { let auth = horizon_client::auth::current(); let name = auth.as_ref().map_or(name, |a| a.name.as_str()); let session = Session::connect(address, name, auth.clone(), view, lang.clone()); + self.extras_connecting(address); let player_type = super::perspective::player_type(&root); let mut streaming = Streaming::new( Arc::new(NoTerrain), @@ -260,6 +261,10 @@ impl Game<'_> { /// Disconnect and return to the multiplayer screen (DisconnectedScreen). pub(super) fn leave_server(&mut self, reason: Option) -> Result<()> { + if reason.is_none() { + // Leaving on purpose: nothing for auto-reconnect to retry. + self.extras_left(); + } if let Some(mut r) = self.remote.take() { r.session.disconnect(); } @@ -284,7 +289,10 @@ impl Game<'_> { let saves = std::env::current_dir()?.join("saves"); let mut title = horizon_client::title::Title::new(saves.clone()); title.mode = horizon_client::title::Mode::Multiplayer(match reason { - Some(reason) => horizon_client::multiplayer::Screen::Disconnected { reason }, + Some(reason) => horizon_client::multiplayer::Screen::Disconnected { + reason, + retry: None, + }, None => horizon_client::multiplayer::Screen::list(&saves), }); self.title = Some(title); @@ -374,6 +382,7 @@ impl Game<'_> { uuid, } => { self.set_registries(registries); + self.extras_joined(); if let Some(r) = self.remote.as_mut() { r.joined = true; r.profile = uuid; @@ -389,9 +398,15 @@ impl Game<'_> { } } } - Event::Disconnected(reason) => { + Event::Disconnected { + reason, + from_server, + } => { log::info!("Horizon: disconnected: {reason}"); - return self.leave_server(Some(reason)); + let retry = self.reconnect_after(&reason, from_server); + self.leave_server(Some(reason))?; + self.offer_reconnect(retry); + return Ok(()); } Event::Packet(packet) => self.handle_packet(*packet)?, } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ecb5c33c0..d8f9b0766 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -114,6 +114,7 @@ pub mod raid; pub mod random_sequences; pub mod recipe_book; pub mod recipe_book_screen; +pub mod reconnect; pub mod save; pub mod scoreboard; pub mod scoreboard_cmd; diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 6b3646cb9..660d31dbe 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -47,6 +47,8 @@ pub enum Screen { }, Disconnected { reason: String, + /// Auto-reconnect's next attempt, until it is cancelled. + retry: Option, }, } /// What a click asks the title screen to do. @@ -205,14 +207,27 @@ impl Screen { 53, ), ], - Self::Disconnected { .. } => vec![b( - w / 2.0 - 100.0, - h / 2.0 + 30.0, - 200.0, - "Back to Server List", - true, - 54, - )], + Self::Disconnected { retry, .. } => { + let mut v = vec![b( + w / 2.0 - 100.0, + h / 2.0 + 30.0, + 200.0, + "Back to Server List", + true, + 54, + )]; + if retry.is_some() { + v.push(b( + w / 2.0 - 100.0, + h / 2.0 + 54.0, + 200.0, + "Cancel Reconnecting", + true, + 55, + )); + } + v + } } } fn field( @@ -427,7 +442,7 @@ impl Screen { blink, ); } - Self::Disconnected { reason } => { + Self::Disconnected { reason, retry } => { centered( batch, "Connection Lost", @@ -437,6 +452,10 @@ impl Screen { for (i, line) in wrap(reason, 300.0, atlas).iter().enumerate() { centered(batch, line, h / 2.0 - 16.0 + i as f32 * 9.0, u32::MAX); } + if let Some(r) = retry { + let text = r.text(std::time::Instant::now()); + centered(batch, &text, h / 2.0 + 16.0, rgba(170, 170, 170, 255)); + } } } } @@ -552,6 +571,7 @@ impl Screen { Self::Edit { .. } | Self::Direct { .. } | Self::Disconnected { .. }, Some(51 | 53 | 54), ) => *self = Self::list(saves), + (Self::Disconnected { retry, .. }, Some(55)) => *retry = None, (Self::Direct { address }, Some(52)) => { return Outcome::Connect(address.trim().to_owned()); } @@ -578,6 +598,16 @@ impl Screen { _ => None, } } + /// Auto-reconnect's attempt, once its countdown is over. + pub fn due_retry(&mut self) -> Option { + let Self::Disconnected { retry, .. } = self else { + return None; + }; + if !retry.as_ref()?.due(std::time::Instant::now()) { + return None; + } + retry.take().map(|r| r.address) + } /// The focused text field, its id and maximum length (copy and paste). pub fn focused_text(&mut self) -> Option<(crate::clipboard::FieldId, &mut String, usize)> { let id = match self { diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 2e733c9ba..ef1938ead 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -40,7 +40,13 @@ pub enum Event { DecodeError(String), /// The server sent us back to configuration and finished it again. Reconfigured(Arc), - Disconnected(String), + /// The connection ended. `from_server`: the server gave the reason (or + /// the connection was refused for good), rather than the connection + /// failing (auto-reconnect retries only failures and shutdowns). + Disconnected { + reason: String, + from_server: bool, + }, } pub struct Session { @@ -70,7 +76,7 @@ impl Session { let thread = std::thread::Builder::new() .name("horizon-net".into()) .spawn(move || { - let reason = match run( + let result = run( &address_owned, &name_owned, auth.as_deref(), @@ -79,14 +85,16 @@ impl Session { &send, &thread_writer, &thread_counters, - ) { - Ok(reason) => reason, - Err(e) => e, - }; + ); + let from_server = result.is_ok(); + let reason = result.unwrap_or_else(|e| e); if let Some(w) = thread_writer.lock().unwrap().take() { w.shutdown(); } - let _ = send.send(Event::Disconnected(reason)); + let _ = send.send(Event::Disconnected { + reason, + from_server, + }); }) .ok(); let debug = std::env::var_os("HORIZON_NET_DEBUG").is_some(); @@ -149,7 +157,8 @@ fn tr(lang: &Language, key: &str) -> String { lang.get(key).cloned().unwrap_or_else(|| key.to_owned()) } -/// The whole connection; returns the disconnect reason. +/// The whole connection. Ok: why it ended for good (the server's reason, or +/// a refusal no retry fixes); Err: the connection failed. fn run( address: &str, name: &str, @@ -160,8 +169,9 @@ fn run( shared_writer: &Mutex>, shared_counters: &Mutex>>, ) -> Result { - let (host, port) = - parse_address(address).ok_or_else(|| format!("Invalid server address: {address}"))?; + let Some((host, port)) = parse_address(address) else { + return Ok(format!("Invalid server address: {address}")); + }; status(send, "Connecting to the server..."); let mut c = Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; @@ -200,7 +210,7 @@ fn run( let reason = serde_json::from_str::(&p.reason_json) .map(|v| json_text(&v, lang)) .unwrap_or(p.reason_json); - return Err(reason); + return Ok(reason); } login::Clientbound::Hello(hello) => { status(send, &tr(lang, "connect.authorizing")); diff --git a/crates/horizon-client/src/reconnect.rs b/crates/horizon-client/src/reconnect.rs new file mode 100644 index 000000000..31a3930bd --- /dev/null +++ b/crates/horizon-client/src/reconnect.rs @@ -0,0 +1,235 @@ +//! The auto-reconnect extra (`docs/extras.md`): whether a lost multiplayer +//! connection may be retried, and when. Only lost connections and the +//! server's own shutdown or restart are retried, never kicks, bans or +//! refusals; attempts back off and stop after a few. +use std::time::{Duration, Instant}; + +/// Seconds before each attempt; there are no more after the last. +pub const DELAYS: [u64; 5] = [5, 10, 20, 40, 60]; +/// Staying connected this long counts the next drop as a fresh one. +pub const STABLE: Duration = Duration::from_secs(60); + +/// Whether a disconnect may be retried. `from_server`: the server (or a +/// permanent refusal) gave `reason`, rather than the connection failing. +pub fn allowed(reason: &str, from_server: bool) -> bool { + let r = reason.to_lowercase(); + // Kicks, bans, whitelists, version and session refusals: never. + const NEVER: [&str; 9] = [ + "ban", + "kick", + "white-list", + "whitelist", + "incompatible", + "outdated", + "another location", + "online mode", + "invalid server address", + ]; + if NEVER.iter().any(|w| r.contains(w)) { + return false; + } + if !from_server { + return true; + } + // The server going away for a while: vanilla's shutdown and time-out + // reasons, a full server, a slow login, and restart messages. + const RETRY: [&str; 5] = [ + "server closed", + "timed out", + "the server is full", + "took too long to log in", + "restart", + ]; + RETRY.iter().any(|w| r.contains(w)) +} + +/// Attempts at one address. +#[derive(Debug, Default)] +pub struct Tracker { + address: Option, + /// Attempts already made since the last stable connection. + attempts: usize, + joined: Option, +} +/// A planned attempt. +#[derive(Clone, Debug, PartialEq)] +pub struct Retry { + pub address: String, + pub at: Instant, + /// 1-based, of `DELAYS.len()`. + pub attempt: usize, +} +impl Retry { + /// Whole seconds left, rounded up. + pub fn seconds_left(&self, now: Instant) -> u64 { + let left = self.at.saturating_duration_since(now); + left.as_secs() + u64::from(left.subsec_nanos() > 0) + } + pub fn due(&self, now: Instant) -> bool { + now >= self.at + } + pub fn text(&self, now: Instant) -> String { + format!( + "Reconnecting in {} s (attempt {} of {})", + self.seconds_left(now), + self.attempt, + DELAYS.len() + ) + } +} +impl Tracker { + /// A connection to `address` starts: a new address starts counting anew. + pub fn connecting(&mut self, address: &str) { + if self.address.as_deref() != Some(address) { + self.address = Some(address.to_owned()); + self.attempts = 0; + } + self.joined = None; + } + /// The server let the player in. + pub fn joined(&mut self, now: Instant) { + self.joined = Some(now); + } + /// The player left on purpose, or cancelled: nothing to retry. + pub fn reset(&mut self) { + *self = Self::default(); + } + /// The connection ended: the next attempt, or None (not allowed, or + /// out of attempts). + pub fn ended(&mut self, reason: &str, from_server: bool, now: Instant) -> Option { + if self + .joined + .take() + .is_some_and(|t| now.saturating_duration_since(t) >= STABLE) + { + self.attempts = 0; + } + let address = self.address.clone()?; + if !allowed(reason, from_server) || self.attempts >= DELAYS.len() { + self.reset(); + return None; + } + let delay = Duration::from_secs(DELAYS[self.attempts]); + self.attempts += 1; + Some(Retry { + address, + at: now + delay, + attempt: self.attempts, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_lost_connections_and_shutdowns_are_retried() { + assert!(allowed("Connection reset by peer (os error 104)", false)); + assert!(allowed("Connection refused (os error 111)", false)); + assert!(allowed("Server closed", true)); + assert!(allowed("Timed out", true)); + assert!(allowed("The server is full!", true)); + assert!(allowed("Server is restarting, back soon", true)); + assert!(!allowed("Kicked by an operator", true)); + assert!(!allowed( + "You are banned from this server.\nReason: griefing", + true + )); + assert!(!allowed("You are not white-listed on this server!", true)); + assert!(!allowed("You logged in from another location", true)); + assert!(!allowed("Incompatible client! Please use 26.3", true)); + assert!(!allowed("You have been idle for too long!", true)); + assert!( + !allowed("Go away", true), + "unknown server reasons are not retried" + ); + assert!(!allowed( + "This server is in online mode. Horizon only joins offline-mode servers.", + true + )); + assert!(!allowed("Kicked for spamming", false)); + } + + #[test] + fn attempts_back_off_and_stop() { + let mut t = Tracker::default(); + let now = Instant::now(); + t.connecting("localhost:25565"); + let mut delays = Vec::new(); + while let Some(r) = t.ended("Connection refused", false, now) { + assert_eq!(r.address, "localhost:25565"); + assert_eq!(r.attempt, delays.len() + 1); + delays.push(r.at.duration_since(now).as_secs()); + t.connecting(&r.address); + } + assert_eq!(delays, DELAYS); + // Out of attempts, the tracker forgets the address. + assert_eq!(t.ended("Connection refused", false, now), None); + } + + #[test] + fn a_short_stay_does_not_reset_the_count() { + let mut t = Tracker::default(); + let now = Instant::now(); + t.connecting("a"); + for _ in 0..DELAYS.len() { + t.connecting("a"); + t.joined(now); + assert!( + t.ended("Server closed", true, now + Duration::from_secs(5)) + .is_some() + ); + } + t.connecting("a"); + t.joined(now); + assert_eq!( + t.ended("Server closed", true, now + Duration::from_secs(5)), + None + ); + // A minute connected starts over. + t.connecting("a"); + for _ in 0..3 { + t.ended("Timed out", true, now); + t.connecting("a"); + } + t.joined(now); + let r = t.ended("Timed out", true, now + STABLE).unwrap(); + assert_eq!(r.attempt, 1); + } + + #[test] + fn kicks_and_leaving_reset_and_new_addresses_start_over() { + let mut t = Tracker::default(); + let now = Instant::now(); + t.connecting("a"); + assert!(t.ended("Server closed", true, now).is_some()); + assert_eq!(t.ended("Kicked by an operator", true, now), None); + assert_eq!( + t.ended("Server closed", true, now), + None, + "forgotten after a kick" + ); + t.connecting("a"); + t.ended("Server closed", true, now); + t.connecting("b"); + assert_eq!(t.ended("Server closed", true, now).unwrap().attempt, 1); + let mut t = Tracker::default(); + assert_eq!(t.ended("Server closed", true, now), None, "never connected"); + } + + #[test] + fn the_countdown_rounds_up() { + let now = Instant::now(); + let r = Retry { + address: "a".into(), + at: now + Duration::from_millis(4200), + attempt: 2, + }; + assert_eq!(r.seconds_left(now), 5); + assert_eq!(r.text(now), "Reconnecting in 5 s (attempt 2 of 5)"); + assert!(!r.due(now)); + assert!(r.due(now + Duration::from_secs(5))); + assert_eq!(r.seconds_left(now + Duration::from_secs(9)), 0); + } +} diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 1d21aa305..b48a93e90 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -593,6 +593,13 @@ impl Title { *focus = (*focus + 1) % 2; } } + /// The server auto-reconnect retries now, once its countdown is over. + pub fn due_retry(&mut self) -> Option { + match &mut self.mode { + Mode::Multiplayer(screen) => screen.due_retry(), + _ => None, + } + } pub fn escape(&mut self) { if let Mode::Multiplayer(screen) = &mut self.mode && !screen.escape(&self.saves) From 5797cf2702e9584fcb619b6b41bf040d4cce06a2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:09:14 +0200 Subject: [PATCH 2/4] Auto-reconnect retries with the session's player name Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/extras.rs | 11 ++++---- crates/horizon-client/src/game/remote.rs | 2 +- crates/horizon-client/src/multiplayer.rs | 4 +-- crates/horizon-client/src/reconnect.rs | 36 +++++++++++++++--------- crates/horizon-client/src/title.rs | 2 +- 5 files changed, 32 insertions(+), 23 deletions(-) diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 0ef74407c..e904ca0d2 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -90,9 +90,9 @@ impl Game<'_> { self.extras.fps.clear(); } } - /// Auto-reconnect: a connection to `address` starts. - pub(super) fn extras_connecting(&mut self, address: &str) { - self.extras.reconnect.connecting(address); + /// Auto-reconnect: a connection to `address` as `name` starts. + pub(super) fn extras_connecting(&mut self, address: &str, name: &str) { + self.extras.reconnect.connecting(address, name); } /// Auto-reconnect: the server let the player in. pub(super) fn extras_joined(&mut self) { @@ -131,9 +131,8 @@ impl Game<'_> { } /// Auto-reconnect: connect again once the countdown is over. pub(super) fn extras_retry(&mut self) -> horizon_client::Result<()> { - if let Some(address) = self.title.as_mut().and_then(|t| t.due_retry()) { - let name = self.options.player_name.clone(); - self.connect_server(&address, &name)?; + if let Some(retry) = self.title.as_mut().and_then(|t| t.due_retry()) { + self.connect_server(&retry.address, &retry.name)?; } Ok(()) } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index bc2268653..0e8219609 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -162,7 +162,7 @@ impl Game<'_> { let auth = horizon_client::auth::current(); let name = auth.as_ref().map_or(name, |a| a.name.as_str()); let session = Session::connect(address, name, auth.clone(), view, lang.clone()); - self.extras_connecting(address); + self.extras_connecting(address, name); let player_type = super::perspective::player_type(&root); let mut streaming = Streaming::new( Arc::new(NoTerrain), diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 660d31dbe..be1ddf2b2 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -599,14 +599,14 @@ impl Screen { } } /// Auto-reconnect's attempt, once its countdown is over. - pub fn due_retry(&mut self) -> Option { + pub fn due_retry(&mut self) -> Option { let Self::Disconnected { retry, .. } = self else { return None; }; if !retry.as_ref()?.due(std::time::Instant::now()) { return None; } - retry.take().map(|r| r.address) + retry.take() } /// The focused text field, its id and maximum length (copy and paste). pub fn focused_text(&mut self) -> Option<(crate::clipboard::FieldId, &mut String, usize)> { diff --git a/crates/horizon-client/src/reconnect.rs b/crates/horizon-client/src/reconnect.rs index 31a3930bd..3143be717 100644 --- a/crates/horizon-client/src/reconnect.rs +++ b/crates/horizon-client/src/reconnect.rs @@ -47,6 +47,8 @@ pub fn allowed(reason: &str, from_server: bool) -> bool { #[derive(Debug, Default)] pub struct Tracker { address: Option, + /// The player name the connection used. + name: String, /// Attempts already made since the last stable connection. attempts: usize, joined: Option, @@ -55,6 +57,7 @@ pub struct Tracker { #[derive(Clone, Debug, PartialEq)] pub struct Retry { pub address: String, + pub name: String, pub at: Instant, /// 1-based, of `DELAYS.len()`. pub attempt: usize, @@ -78,12 +81,14 @@ impl Retry { } } impl Tracker { - /// A connection to `address` starts: a new address starts counting anew. - pub fn connecting(&mut self, address: &str) { + /// A connection to `address` as `name` starts: a new address starts + /// counting anew. + pub fn connecting(&mut self, address: &str, name: &str) { if self.address.as_deref() != Some(address) { self.address = Some(address.to_owned()); self.attempts = 0; } + self.name = name.to_owned(); self.joined = None; } /// The server let the player in. @@ -113,6 +118,7 @@ impl Tracker { self.attempts += 1; Some(Retry { address, + name: self.name.clone(), at: now + delay, attempt: self.attempts, }) @@ -155,13 +161,16 @@ mod tests { fn attempts_back_off_and_stop() { let mut t = Tracker::default(); let now = Instant::now(); - t.connecting("localhost:25565"); + t.connecting("localhost:25565", "Tester"); let mut delays = Vec::new(); while let Some(r) = t.ended("Connection refused", false, now) { - assert_eq!(r.address, "localhost:25565"); + assert_eq!( + (r.address.as_str(), r.name.as_str()), + ("localhost:25565", "Tester") + ); assert_eq!(r.attempt, delays.len() + 1); delays.push(r.at.duration_since(now).as_secs()); - t.connecting(&r.address); + t.connecting(&r.address, &r.name); } assert_eq!(delays, DELAYS); // Out of attempts, the tracker forgets the address. @@ -172,26 +181,26 @@ mod tests { fn a_short_stay_does_not_reset_the_count() { let mut t = Tracker::default(); let now = Instant::now(); - t.connecting("a"); + t.connecting("a", "P"); for _ in 0..DELAYS.len() { - t.connecting("a"); + t.connecting("a", "P"); t.joined(now); assert!( t.ended("Server closed", true, now + Duration::from_secs(5)) .is_some() ); } - t.connecting("a"); + t.connecting("a", "P"); t.joined(now); assert_eq!( t.ended("Server closed", true, now + Duration::from_secs(5)), None ); // A minute connected starts over. - t.connecting("a"); + t.connecting("a", "P"); for _ in 0..3 { t.ended("Timed out", true, now); - t.connecting("a"); + t.connecting("a", "P"); } t.joined(now); let r = t.ended("Timed out", true, now + STABLE).unwrap(); @@ -202,7 +211,7 @@ mod tests { fn kicks_and_leaving_reset_and_new_addresses_start_over() { let mut t = Tracker::default(); let now = Instant::now(); - t.connecting("a"); + t.connecting("a", "P"); assert!(t.ended("Server closed", true, now).is_some()); assert_eq!(t.ended("Kicked by an operator", true, now), None); assert_eq!( @@ -210,9 +219,9 @@ mod tests { None, "forgotten after a kick" ); - t.connecting("a"); + t.connecting("a", "P"); t.ended("Server closed", true, now); - t.connecting("b"); + t.connecting("b", "P"); assert_eq!(t.ended("Server closed", true, now).unwrap().attempt, 1); let mut t = Tracker::default(); assert_eq!(t.ended("Server closed", true, now), None, "never connected"); @@ -223,6 +232,7 @@ mod tests { let now = Instant::now(); let r = Retry { address: "a".into(), + name: "P".into(), at: now + Duration::from_millis(4200), attempt: 2, }; diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index b48a93e90..123b20b98 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -594,7 +594,7 @@ impl Title { } } /// The server auto-reconnect retries now, once its countdown is over. - pub fn due_retry(&mut self) -> Option { + pub fn due_retry(&mut self) -> Option { match &mut self.mode { Mode::Multiplayer(screen) => screen.due_retry(), _ => None, From ce9c1d3a5cc8b092454d6a21ce45c7b79f97e96e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:41:14 +0200 Subject: [PATCH 3/4] Auto-reconnect: never after account session refusals, retry when session servers are down Classifies the online-mode login outcomes from #161: invalid session, banned from playing online, multiplayer disabled, no account signed in and the server failing to verify the username are never retried; unreachable session servers (the client's or the server's) are. A retry of an online-mode server joins with the account held in memory for the whole run. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/extras.rs | 5 ++- crates/horizon-client/src/reconnect.rs | 50 ++++++++++++++++++++++-- docs/extras.md | 12 ++++-- 3 files changed, 58 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index e904ca0d2..b934f8279 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -129,7 +129,10 @@ impl Game<'_> { *slot = Some(retry); } } - /// Auto-reconnect: connect again once the countdown is over. + /// Auto-reconnect: connect again once the countdown is over. An + /// online-mode server gets the signed-in account again: `connect_server` + /// takes it from `auth::current()`, held in memory for the whole run + /// (the launcher's session file is gone after the first read). pub(super) fn extras_retry(&mut self) -> horizon_client::Result<()> { if let Some(retry) = self.title.as_mut().and_then(|t| t.due_retry()) { self.connect_server(&retry.address, &retry.name)?; diff --git a/crates/horizon-client/src/reconnect.rs b/crates/horizon-client/src/reconnect.rs index 3143be717..c5184d7ad 100644 --- a/crates/horizon-client/src/reconnect.rs +++ b/crates/horizon-client/src/reconnect.rs @@ -13,8 +13,11 @@ pub const STABLE: Duration = Duration::from_secs(60); /// permanent refusal) gave `reason`, rather than the connection failing. pub fn allowed(reason: &str, from_server: bool) -> bool { let r = reason.to_lowercase(); - // Kicks, bans, whitelists, version and session refusals: never. - const NEVER: [&str; 9] = [ + // Kicks, bans, whitelists, version refusals and the account's session + // refusals (`disconnect.loginFailedInfo.*` but the unreachable session + // servers, the server's failed username check, joining an online-mode + // server without an account): never. + const NEVER: [&str; 13] = [ "ban", "kick", "white-list", @@ -24,6 +27,10 @@ pub fn allowed(reason: &str, from_server: bool) -> bool { "another location", "online mode", "invalid server address", + "invalid session", + "multiplayer is disabled", + "failed to verify username", + "microsoft account", ]; if NEVER.iter().any(|w| r.contains(w)) { return false; @@ -32,12 +39,14 @@ pub fn allowed(reason: &str, from_server: bool) -> bool { return true; } // The server going away for a while: vanilla's shutdown and time-out - // reasons, a full server, a slow login, and restart messages. - const RETRY: [&str; 5] = [ + // reasons, a full server, a slow login, the server's own session + // servers being down, and restart messages. + const RETRY: [&str; 6] = [ "server closed", "timed out", "the server is full", "took too long to log in", + "authentication servers", "restart", ]; RETRY.iter().any(|w| r.contains(w)) @@ -157,6 +166,39 @@ mod tests { assert!(!allowed("Kicked for spamming", false)); } + #[test] + fn online_mode_login_failures() { + // The client's join with the session service (net.rs: Err, with + // vanilla's disconnect.loginFailedInfo texts). + let failed = |why: &str| format!("Failed to log in: {why}"); + assert!(!allowed( + &failed("Invalid session (Try restarting your game and the launcher)"), + false + )); + assert!(!allowed( + &failed("You are banned from playing online"), + false + )); + assert!(!allowed( + &failed("Multiplayer is disabled. Please check your Microsoft account settings."), + false + )); + assert!(!allowed(crate::net::NOT_SIGNED_IN, false)); + // Unreachable session servers are worth another try. + assert!(allowed( + &failed("The authentication servers are currently not reachable. Please try again."), + false + )); + assert!(allowed(&failed("Connection timed out"), false)); + // The server's side: its username check failed, or its session + // servers are down. + assert!(!allowed("Failed to verify username!", true)); + assert!(allowed( + "Authentication servers are down. Please try again later. Sorry!", + true + )); + } + #[test] fn attempts_back_off_and_stop() { let mut t = Tracker::default(); diff --git a/docs/extras.md b/docs/extras.md index 9ace6e593..adb69b00a 100644 --- a/docs/extras.md +++ b/docs/extras.md @@ -85,10 +85,14 @@ Horizon category in Controls, and adding one would put a non-vanilla mapping int - Backoff 5, 10, 20, 40, 60 s; at most 5 attempts, then it stops. The count only resets after staying connected for a minute, so a server that drops players at once never causes an endless loop. -- Never after a kick, a ban, a whitelist or version refusal, a duplicate login - or an online-mode refusal: only lost connections (errors, time-outs, refused - connections while the server restarts) and the server's own "Server closed" - shutdown reason. +- Never after a kick, a ban, a whitelist or version refusal, a duplicate login, + an online-mode refusal (no account signed in), or a session refusal from the + account's login (invalid session, banned from playing online, multiplayer + disabled, the server failing to verify the username). Unreachable session + servers, on either side, are retried with the same backoff. +- Online-mode servers: the retry joins with the account the game signed in + with, held in memory for the whole run (`auth::current()`); nothing is + written to disk. ## Shared rules From 37043b3dff2ff04a9e87dab709e96329ecff9acc Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:44:56 +0200 Subject: [PATCH 4/4] net harness: the Disconnected screen gained auto-reconnect's retry Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/net_harness.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/net_harness.rs b/crates/horizon-client/src/game/net_harness.rs index 681a950b0..1ec573e7c 100644 --- a/crates/horizon-client/src/game/net_harness.rs +++ b/crates/horizon-client/src/game/net_harness.rs @@ -30,7 +30,7 @@ impl Game<'_> { if self.remote.is_none() { error = Some(match self.title.as_ref().map(|t| &t.mode) { Some(horizon_client::title::Mode::Multiplayer( - horizon_client::multiplayer::Screen::Disconnected { reason }, + horizon_client::multiplayer::Screen::Disconnected { reason, .. }, )) => format!("disconnected: {reason}"), _ => "disconnected".to_owned(), });