From 57ee0810381b2d1d271fcfa6678bb8de456c7151 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:56:53 +0500 Subject: [PATCH 01/23] Keep sprint state independent of held sprint keys Let PlayerCommand control the server sprint flag, matching vanilla, so releasing Ctrl cannot leave the client's speed modifier and FOV stuck. Cover the packet sequence and FOV recovery in regression tests. Co-Authored-By: Codex (GPT-6) --- crates/horizon-client/src/game/agent.rs | 3 +- crates/horizon-client/src/lan/hub.rs | 4 +- crates/horizon-client/tests/lan_bot.rs | 59 +++++++++++++++++++++++++ tools/lan_e2e.py | 46 +++++++++++++++++++ 4 files changed, 110 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index f6b68aa74..57c12da97 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -469,7 +469,8 @@ impl Game<'_> { "flying": p.flying, "fall_flying": p.fall_flying, "sneaking": self.keys.contains(&KeyCode::ShiftLeft), - "sprinting": self.keys.contains(&KeyCode::ControlLeft), + "sprinting": p.sprinting, + "fov_modifier": self.view.fov_modifier, "health": p.health.health(), "absorption": p.health.absorption(), // The hurt animation's ticks left (the camera's hurt tilt). diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index c2a395899..dd0a32f22 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1984,7 +1984,9 @@ impl Hub { S::PlayerInput(p) => { self.guests[i].input = p.flags; self.guests[i].sneaking = p.flags & 32 != 0; - self.guests[i].sprinting = p.flags & 64 != 0 && p.flags & 1 != 0; + // handlePlayerInput only records keys and updates crouching. + // Sprinting persists after the sprint key is released (or + // starts with a double tap); PlayerCommand changes it. } // OPEN_INVENTORY (the ridden mount's inventory) and // START_FALL_FLYING (checked against the guest's chest slot diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 6dd1b8258..34e8265a1 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -278,6 +278,65 @@ fn run( handle.join().unwrap().unwrap() } +#[test] +fn sprint_commands_survive_keyboard_input_changes() { + let Some(resources) = resources() else { + return; + }; + let mut s = server(&resources); + let port = s.hub.lan.port; + let _bot = run(&mut s, move || connect(port, "Sprinter", true)); + let deadline = Instant::now() + Duration::from_secs(5); + while s.hub.guests.is_empty() { + s.tick(&[]); + assert!(Instant::now() < deadline, "guest did not join"); + thread::yield_now(); + } + let id = s.hub.guests[0].entity_id; + s.hub.guests[0].loaded = true; + s.hub.guests[0] + .inbox + .push_back(S::PlayerCommand(play::PlayerCommand { + id, + action: 1, + data: 0, + })); + s.tick(&[]); + assert!(s.hub.guests[0].sprinting); + // LocalPlayer keeps sprinting after Ctrl is released while W remains + // down. Double-tap sprint also sends forward without the sprint key. + for flags in [65, 1, 0, 33] { + s.hub.guests[0] + .inbox + .push_back(S::PlayerInput(play::PlayerInput { flags })); + s.tick(&[]); + let g = &s.hub.guests[0]; + assert!( + g.sprinting, + "keyboard input {flags} cleared the sprint flag" + ); + assert_eq!(g.input, flags); + assert_eq!(g.sneaking, flags & 32 != 0); + } + s.hub.guests[0] + .inbox + .push_back(S::PlayerCommand(play::PlayerCommand { + id, + action: 2, + data: 0, + })); + s.tick(&[]); + assert!(!s.hub.guests[0].sprinting); + s.hub.guests[0] + .inbox + .push_back(S::PlayerInput(play::PlayerInput { flags: 65 })); + s.tick(&[]); + assert!( + !s.hub.guests[0].sprinting, + "keyboard input started a sprint" + ); +} + #[test] fn status_and_join() { let Some(resources) = resources() else { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0c8979f0a..892e393f0 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -6162,5 +6162,51 @@ CHECKS += ['falling'] CHECK_FNS.update(falling=check_falling) +def check_sprint_fov(host, guest, out): + """Releasing Ctrl must preserve a sprint until W is released, then reset FOV. + + PlayerInput reports keys; PlayerCommand starts/stops the sprint. Confusing + them clears the client's sprint flag while leaving its speed modifier on. + """ + seen = {} + for game in (host, guest): + game('command', command='gamemode creative') + game('command', command='effect clear @s') + game.raw('options-set', 'fovEffectScale', '1.0') + x, y, z = map(math.floor, pos_of(game)) + game('command', command=f'fill {x - 2} {y} {z - 2} {x + 2} {y + 3} {z + 20} minecraft:air') + game('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 2} {y - 1} {z + 20} minecraft:stone') + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0') + game.wait(20) + try: + game.raw('key', 'w', 'down') + game.raw('key', 'ctrl', 'down') + game.wait(10) + started = game('state')['player'] + game.raw('key', 'ctrl', 'up') + game.wait(10) + released_ctrl = game('state')['player'] + game.raw('key', 'w', 'up') + game.wait(20) + stopped = game('state')['player'] + finally: + game.raw('key', 'ctrl', 'up') + game.raw('key', 'w', 'up') + seen[game.name] = states = { + label: {k: p[k] for k in ('sprinting', 'fov_modifier')} + for label, p in [('started', started), ('released_ctrl', released_ctrl), ('stopped', stopped)] + } + for label in ('started', 'released_ctrl'): + assert states[label]['sprinting'], f'{game.name} {label}: {states}' + assert abs(states[label]['fov_modifier'] - 1.15) < 0.002, f'{game.name} {label}: {states}' + assert not stopped['sprinting'], f'{game.name}: {states}' + assert abs(stopped['fov_modifier'] - 1.0) < 0.002, f'{game.name}: {states}' + return seen + + +CHECKS += ['sprint-fov'] +CHECK_FNS['sprint-fov'] = check_sprint_fov + + if __name__ == '__main__': main() From 0bc85843ce0d9672c6990345af6ffd4e4b180993 Mon Sep 17 00:00:00 2001 From: socksprox Date: Sun, 25 Oct 2026 00:19:47 +0200 Subject: [PATCH 02/23] Client: remote players keep their skins instead of falling back MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit skins::unpack discarded a profile's whole textures payload when any one entry lacked "url" or pointed outside the texture services' domains, so a player with e.g. an unusual cape lost their skin too; it now drops only the offending texture. The 32 skin atlas slots evicted past players back to defaults on busy servers — now 128. A dimension reset (join game or respawn onto another world) now also clears the entity-id→profile map so a re-used entity id can't pin the wrong skin or name to a player, and the nametag join falls back to the player-list entry's name. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game/remote.rs | 12 +++++++++++- crates/horizon-client/src/hud.rs | 4 +++- crates/horizon-client/src/skins.rs | 21 +++++++++++---------- 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5a71b13a8..36122d42a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1006,6 +1006,9 @@ impl Game<'_> { r.stepped.clear(); r.head_lerps.clear(); r.pending_items.clear(); + // The entity ids are the old world's; the new dimension's + // player entities re-map to their profiles on AddEntity. + r.level_players.clear(); // A new ClientLevel: a new chunk storage, centred on 0, 0. r.chunk_center = (0, 0); } @@ -5065,7 +5068,14 @@ impl Game<'_> { r.level_players .iter() .filter(|(_, uuid)| **uuid != r.profile) - .filter_map(|(id, uuid)| Some((*id as u32, r.players.get(uuid)?.clone()))) + .filter_map(|(id, uuid)| { + let name = r + .players + .get(uuid) + .cloned() + .or_else(|| r.tab_players.get(uuid).map(|t| t.name.clone()))?; + Some((*id as u32, name)) + }) .collect() } /// `ClientClockManager.tick`: the clock moves on by the game time that diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 89d1b1c3c..90a8b346c 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -78,7 +78,9 @@ pub const MAP_SLOTS: usize = 256; /// The atlas slot the minimap extra draws into. pub const MINIMAP_SPRITE: &str = "horizon/minimap"; /// Atlas slots for downloaded player skins (`skins/`), 64x64 each. -pub const SKIN_SLOTS: usize = 32; +/// Vanilla registers a texture per skin; too few slots evict a busy +/// server's players back to their default skins. +pub const SKIN_SLOTS: usize = 128; /// Reused by the visible rows of the classic world selector. pub const WORLD_ICON_SLOTS: usize = 32; /// Atlas slots for the pack icons on the pack screen, one per icon drawn diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index 9014032c4..0cf9cc8a2 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -92,22 +92,23 @@ pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Texture ..empty.clone() }; for (kind, texture) in textures { - let Some(url) = texture.get("url").and_then(|u| u.as_str()) else { - return empty; - }; - let allowed = valid_uris - .iter() - .any(|u| url.starts_with(&u.replace("{textureId}", ""))); - if !allowed { - return empty; - } let slot = match kind.as_str() { "SKIN" => &mut out.skin, "CAPE" => &mut out.cape, "ELYTRA" => &mut out.elytra, _ => continue, }; - *slot = Some(url.to_owned()); + // One bad entry (no `url`, or a URL outside the texture services' + // domains) drops only that texture, not the whole payload. + let Some(url) = texture.get("url").and_then(|u| u.as_str()) else { + continue; + }; + let allowed = valid_uris + .iter() + .any(|u| url.starts_with(&u.replace("{textureId}", ""))); + if allowed { + *slot = Some(url.to_owned()); + } } out } From 3740de5116dbf9322e39d18c3ce0777d087d0401 Mon Sep 17 00:00:00 2001 From: socksprox Date: Sun, 25 Oct 2026 13:40:07 +0100 Subject: [PATCH 03/23] Launcher: pin the macOS title bar to the chosen appearance The launcher's Appearance setting darkened the page but not the window's native chrome: NSWindow keeps the system appearance, so a launcher set to Dark still drew a light title bar on a light desktop. apply_appearance (titlebar.rs) pins the NSWindow's appearance to the choice at startup and when the setting changes; System clears the pin so the chrome follows the computer again. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- launcher/Cargo.lock | 2 ++ launcher/Cargo.toml | 4 ++++ launcher/src/main.rs | 4 ++++ launcher/src/titlebar.rs | 49 +++++++++++++++++++++++++++++++++++++++- 4 files changed, 58 insertions(+), 1 deletion(-) diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 5155420e0..922a92f2f 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2680,8 +2680,10 @@ dependencies = [ "horizon-theme", "image", "keyring", + "objc2-app-kit", "oo7", "pulldown-cmark", + "raw-window-handle", "self-replace", "serde", "serde_json", diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index a402d0e28..570e2bd75 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -48,6 +48,10 @@ oo7 = { version = "0.5", default-features = false, features = ["async-std", "nat futures-lite = "2" [target.'cfg(target_os = "macos")'.dependencies] keyring = { version = "3", features = ["apple-native"] } +# Painting the window's title bar dark or light (titlebar::apply_appearance): crates already in +# the lockfile through gpui and wgpu. +objc2-app-kit = { version = "0.3", default-features = false, features = ["NSAppearance", "NSView", "NSWindow"] } +raw-window-handle = "0.6" [target.'cfg(target_os = "windows")'.dependencies] keyring = { version = "3", features = ["windows-native"] } diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 0bcbc4011..ebde171e5 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -265,6 +265,9 @@ impl Launcher { { settings.selected = installed.first().cloned(); } + // Pin the window's chrome (macOS title bar) to the choice before the theme reads + // `window.appearance()`, so both draw the same look. + titlebar::apply_appearance(window, settings.appearance); let mut this = Self { theme: Theme::for_appearance(settings.appearance, window.appearance()), page: Page::from_env(), @@ -2482,6 +2485,7 @@ impl Launcher { let _ = this.update(cx, |this, cx| { this.settings.appearance = choice; this.settings.save(); + titlebar::apply_appearance(window, choice); this.theme = Theme::for_appearance(choice, window.appearance()); cx.notify(); }); diff --git a/launcher/src/titlebar.rs b/launcher/src/titlebar.rs index 3c2a78ea4..2e6445091 100644 --- a/launcher/src/titlebar.rs +++ b/launcher/src/titlebar.rs @@ -1,6 +1,8 @@ -//! Custom Windows chrome. Other platforms keep their native window decorations. +//! Custom Windows chrome. Other platforms keep their native window decorations; on macOS, +//! `apply_appearance` repaints that chrome (the title bar) to match the chosen look. use crate::theme::Theme; use gpui::{Div, TitlebarOptions, Window}; +use horizon_launcher::backend::Appearance; /// Whether the launcher draws its own title bar (`render`) rather than the system. pub const DRAWN: bool = cfg!(target_os = "windows"); @@ -18,6 +20,51 @@ pub fn render(_theme: &Theme, _window: &Window) -> Option
{ None } +/// macOS keeps the window's appearance on the system setting, so a launcher set to Dark still +/// draws a light title bar on a light desktop. Pin the NSWindow's appearance to the choice +/// instead (`System` clears the pin, handing the chrome back to the system), honouring the same +/// `HORIZON_LAUNCHER_APPEARANCE` override the theme does. Other platforms' chrome already +/// follows the setting (ours is drawn, Windows and Linux follow the system either way). +#[cfg(target_os = "macos")] +pub fn apply_appearance(window: &Window, choice: Appearance) { + use objc2_app_kit::{ + NSAppearance, NSAppearanceCustomization, NSAppearanceName, NSAppearanceNameAqua, + NSAppearanceNameDarkAqua, NSView, + }; + use raw_window_handle::{HasWindowHandle, RawWindowHandle}; + + // Reading AppKit's name constants is unsafe to rustc only (`use of extern static`). + let name: Option<&'static NSAppearanceName> = unsafe { + match std::env::var("HORIZON_LAUNCHER_APPEARANCE").as_deref() { + Ok("light") => Some(NSAppearanceNameAqua), + Ok("dark") => Some(NSAppearanceNameDarkAqua), + _ => match choice { + Appearance::Dark => Some(NSAppearanceNameDarkAqua), + Appearance::Light => Some(NSAppearanceNameAqua), + Appearance::System => None, + }, + } + }; + // The trait, not `Window::window_handle` (which is gpui's own `AnyWindowHandle`). + let Ok(handle) = HasWindowHandle::window_handle(window) else { + return; + }; + let RawWindowHandle::AppKit(appkit) = handle.as_raw() else { + return; + }; + // The handle is the window's content view; its `window` is the NSWindow itself. Both outlive + // this call. + let view = unsafe { appkit.ns_view.cast::().as_ref() }; + let Some(native) = view.window() else { + return; + }; + let appearance = name.and_then(NSAppearance::appearanceNamed); + native.setAppearance(appearance.as_deref()); +} + +#[cfg(not(target_os = "macos"))] +pub fn apply_appearance(_: &Window, _: Appearance) {} + #[cfg(target_os = "windows")] mod windows { use super::*; From 87b3c9aa38e5568733a2678d0332ad33e0e792e3 Mon Sep 17 00:00:00 2001 From: socksprox Date: Sun, 25 Oct 2026 13:51:12 +0100 Subject: [PATCH 04/23] Drop the stale craft grid when a remote menu closes The server's AbstractContainerMenu.removed gives the grid and the carried stack back to the inventory and syncs those slots, but the client kept its copies: a crafting table closed with items inside left ghost stacks in the inventory's 2x2 grid that could not be picked up. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game/remote.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5a71b13a8..d8148f77f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -4783,6 +4783,11 @@ impl Game<'_> { self.mount_menu_reset(); // The client's menu has no level access: what it holds is the server's. self.station = None; + // AbstractContainerMenu.removed: the server gives the grid and the + // carried stack back to the inventory and syncs it; the copies here + // are stale the moment the window closes. + self.craft_grid.fill(None); + self.carried = None; self.craft_size = 2; if let Some(key) = self.container.take() { // Server containers stay renderable but lose their copied slots. From fb1142cd71dba47247f5f897c8ff487362431413 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:31:41 +0100 Subject: [PATCH 05/23] Skins: keep vanilla's whole-payload rejection, drop the dead name fallback authlib 10.0.77 MinecraftServicesSessionService.unpackTextures returns MinecraftProfileTextures.EMPTY when any texture has no URL or a URL outside the allowed domains, so skins::unpack goes back to main's behaviour. remote_player_names: r.players and r.tab_players are filled from the same ADD_PLAYER entries and emptied by the same PlayerInfoRemove, so the tab-list fallback could never apply. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 9 +-------- crates/horizon-client/src/hud.rs | 5 +++-- crates/horizon-client/src/skins.rs | 21 ++++++++++----------- 3 files changed, 14 insertions(+), 21 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 36122d42a..74850110b 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -5068,14 +5068,7 @@ impl Game<'_> { r.level_players .iter() .filter(|(_, uuid)| **uuid != r.profile) - .filter_map(|(id, uuid)| { - let name = r - .players - .get(uuid) - .cloned() - .or_else(|| r.tab_players.get(uuid).map(|t| t.name.clone()))?; - Some((*id as u32, name)) - }) + .filter_map(|(id, uuid)| Some((*id as u32, r.players.get(uuid)?.clone()))) .collect() } /// `ClientClockManager.tick`: the clock moves on by the game time that diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 90a8b346c..617126c2e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -78,8 +78,9 @@ pub const MAP_SLOTS: usize = 256; /// The atlas slot the minimap extra draws into. pub const MINIMAP_SPRITE: &str = "horizon/minimap"; /// Atlas slots for downloaded player skins (`skins/`), 64x64 each. -/// Vanilla registers a texture per skin; too few slots evict a busy -/// server's players back to their default skins. +/// Vanilla registers a texture per skin. Here a skin evicted from its slot +/// is not stored again, and its player falls back to the default skin, so +/// the slots must cover a busy server's player list. pub const SKIN_SLOTS: usize = 128; /// Reused by the visible rows of the classic world selector. pub const WORLD_ICON_SLOTS: usize = 32; diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index 0cf9cc8a2..9014032c4 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -92,23 +92,22 @@ pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Texture ..empty.clone() }; for (kind, texture) in textures { + let Some(url) = texture.get("url").and_then(|u| u.as_str()) else { + return empty; + }; + let allowed = valid_uris + .iter() + .any(|u| url.starts_with(&u.replace("{textureId}", ""))); + if !allowed { + return empty; + } let slot = match kind.as_str() { "SKIN" => &mut out.skin, "CAPE" => &mut out.cape, "ELYTRA" => &mut out.elytra, _ => continue, }; - // One bad entry (no `url`, or a URL outside the texture services' - // domains) drops only that texture, not the whole payload. - let Some(url) = texture.get("url").and_then(|u| u.as_str()) else { - continue; - }; - let allowed = valid_uris - .iter() - .any(|u| url.starts_with(&u.replace("{textureId}", ""))); - if allowed { - *slot = Some(url.to_owned()); - } + *slot = Some(url.to_owned()); } out } From 56560b467a8fad3ffe02457691bd8486a1a77cb6 Mon Sep 17 00:00:00 2001 From: socksprox Date: Sun, 25 Oct 2026 00:19:47 +0200 Subject: [PATCH 06/23] Multiplayer: answer cookie requests, store cookies, follow transfer packets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ClientboundCookieRequestPacket in play state decoded as Unknown and was dropped; StoreCookie and Transfer likewise, and the configuration-phase CookieRequest was always answered empty. Proxies (BungeeCord, Velocity) store and read cookies around a server switch and send Transfer to move a player to another address — both ended in a kick. Play-state cookie_request/store_cookie/transfer now have packet types, cookie requests answer from the stored cookies in both configuration and play (ClientCommonPacketListenerImpl.handleRequestCookie), stored cookies land in the session's map (handleStoreCookie), and a transfer reconnects the game to the target address carrying them (handleTransfer → ConnectScreen.startConnecting with TransferState). Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game.rs | 10 +- crates/horizon-client/src/game/remote.rs | 51 +++++++++- .../horizon-client/src/game/startup_menu.rs | 4 +- crates/horizon-client/src/net.rs | 94 +++++++++++++++++-- crates/horizon-protocol/src/packets/play.rs | 9 +- 5 files changed, 153 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..7fcb3be89 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -12098,6 +12098,8 @@ enum PendingWorldEntry { Server { address: String, name: String, + /// A transfer's carried-over server cookies (`TransferState`). + cookies: Option, }, } @@ -12172,8 +12174,12 @@ impl Game<'_> { }) => { self.open_world(&folder, name.as_deref(), seed, creative, create.as_deref())?; } - Some(PendingWorldEntry::Server { address, name }) => { - self.connect_server(&address, &name)?; + Some(PendingWorldEntry::Server { + address, + name, + cookies, + }) => { + self.connect_server_with_cookies(&address, &name, cookies)?; } None => {} } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 044e43835..c10b64c54 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -193,6 +193,9 @@ pub(super) struct Remote { /// the oldest of them first waited (`poll_remote`). backlog: VecDeque, backlog_since: Option, + /// `ClientboundTransferPacket`'s target: when the connection ends the + /// game connects here, the stored cookies carried over (`TransferState`). + transfer: Option, } /// The time a frame spends on chunk packets before it leaves the rest of @@ -257,14 +260,25 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo impl Game<'_> { /// Leave the title for a server (ConnectScreen): an empty world fed by the connection. pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> { + self.connect_server_with_cookies(address, name, None) + } + /// `connect_server` carrying a transfer's stored server cookies + /// (`TransferState`); None on an ordinary join. + pub(super) fn connect_server_with_cookies( + &mut self, + address: &str, + name: &str, + cookies: Option, + ) -> Result<()> { if self.defer_world_entry(super::PendingWorldEntry::Server { address: address.to_owned(), name: name.to_owned(), + cookies: cookies.clone(), })? { return Ok(()); } self.join_world_rest()?; - if let Err(error) = self.join_server(address, name, None) { + if let Err(error) = self.join_server(address, name, None, cookies) { log::warn!("Horizon: could not join server: {error}"); if self.title.is_none() { self.title = Some(horizon_client::title::Title::new( @@ -285,13 +299,14 @@ impl Game<'_> { pipe: horizon_protocol::connection::Pipe, name: &str, ) -> Result<()> { - self.join_server("local", name, Some(pipe)) + self.join_server("local", name, Some(pipe), None) } fn join_server( &mut self, address: &str, name: &str, local: Option, + cookies: Option, ) -> Result<()> { self.perf.world_opening(); let root = self.options.resources.clone(); @@ -323,7 +338,17 @@ impl Game<'_> { Some(pipe) => Session::connect_local(pipe, name, view, lang.clone()), None => { self.extras_connecting(address, name); - Session::connect(address, name, auth.clone(), view, lang.clone()) + match cookies { + Some(cookies) => Session::connect_transferred( + address, + name, + auth.clone(), + view, + lang.clone(), + cookies, + ), + None => Session::connect(address, name, auth.clone(), view, lang.clone()), + } } }; let player_type = super::perspective::player_type(&root); @@ -446,6 +471,7 @@ impl Game<'_> { chunk_center: (0, 0), backlog: VecDeque::new(), backlog_since: None, + transfer: None, }); // The level's TickRateManager follows the server's ticking packets. self.clock = horizon_client::clock::FixedStep::client(); @@ -867,6 +893,11 @@ impl Game<'_> { } } Event::Reconfigured(registries) => self.set_registries(registries), + Event::Transfer { host, port } => { + if let Some(r) = self.remote.as_mut() { + r.transfer = Some(format!("{host}:{port}")); + } + } Event::PackPush(p) => self.handle_pack_push(p), Event::PackPop(id) => self.handle_pack_pop(id), Event::DecodeError(e) => { @@ -882,6 +913,20 @@ impl Game<'_> { from_server, } => { log::info!("Horizon: disconnected: {reason}"); + // ClientboundTransferPacket left a target: connect there + // instead of showing the disconnect, the stored cookies + // carried over (ClientCommonPacketListenerImpl. + // handleTransfer → ConnectScreen.startConnecting). + let transfer = self.remote.as_mut().and_then(|r| { + r.transfer.take().map(|address| { + (address, r.session.name.clone(), r.session.cookies.clone()) + }) + }); + if let Some((address, name, cookies)) = transfer { + self.leave_server(None)?; + self.connect_server_with_cookies(&address, &name, Some(cookies))?; + return Ok(()); + } let retry = self.reconnect_after(&reason, from_server); self.leave_server(Some(reason))?; self.offer_reconnect(retry); diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index 96af99bbc..fe568fe71 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -33,6 +33,7 @@ impl StartupMenu { Some(PendingWorldEntry::Server { address: address.clone(), name: options.player_name(), + cookies: None, }) } else { options @@ -125,6 +126,7 @@ impl StartupMenu { Action::Connect { address } => PendingWorldEntry::Server { address, name: player_name, + cookies: None, }, _ => return, }; @@ -762,7 +764,7 @@ mod tests { "Guest".into(), ); assert!( - matches!(menu.pending.take(), Some(PendingWorldEntry::Server { address, name }) + matches!(menu.pending.take(), Some(PendingWorldEntry::Server { address, name, .. }) if address == "localhost:25565" && name == "Guest") ); assert!(menu.pending.take().is_none(), "an entry is consumed once"); diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 9cce9e1c6..c4e53cef4 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -18,6 +18,7 @@ use horizon_protocol::{ text::{Language, plain, translatable}, }; use std::{ + collections::HashMap, sync::{ Arc, Mutex, atomic::{AtomicBool, Ordering}, @@ -27,6 +28,12 @@ use std::{ time::Duration, }; +/// `CommonListenerCookie.serverCookies`: cookies the server asked the client +/// to store (`ClientboundStoreCookiePacket`), answered to +/// `ClientboundCookieRequestPacket`. A `transfer` carries them to the next +/// connection (`TransferState`), so a proxy's backend switch keeps them. +pub type Cookies = Arc>>>; + /// What the network thread reports to the game. pub enum Event { /// Progress text for the connecting screen. @@ -48,6 +55,13 @@ pub enum Event { PackPush(cfg::ResourcePackPush), /// ClientboundResourcePackPopPacket: one pack, or every pack. PackPop(Option), + /// `ClientboundTransferPacket`: the server sent us to another address. + /// The connection ends right after; the game reconnects there with the + /// stored cookies. + Transfer { + host: String, + port: i32, + }, /// 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). @@ -67,6 +81,8 @@ pub struct Session { pub address: String, pub name: String, pub counters: Arc>>>, + /// The cookies this server stored on us (`ClientboundStoreCookiePacket`). + pub cookies: Cookies, /// HORIZON_NET_DEBUG=1 logs every packet sent from the game thread. debug: bool, } @@ -79,7 +95,27 @@ impl Session { view_distance: i8, lang: Arc, ) -> Self { - Self::start(address, name, auth, view_distance, lang, None) + Self::start(address, name, auth, view_distance, lang, None, None) + } + /// `ConnectScreen.startConnecting` for a `transfer`: the cookies the + /// server stored carry to the new connection (`TransferState`). + pub fn connect_transferred( + address: &str, + name: &str, + auth: Option>, + view_distance: i8, + lang: Arc, + cookies: Cookies, + ) -> Self { + Self::start( + address, + name, + auth, + view_distance, + lang, + None, + Some(cookies), + ) } /// Join an integrated server through memory (`Connection.connectToLocalServer`). pub fn connect_local( @@ -88,7 +124,7 @@ impl Session { view_distance: i8, lang: Arc, ) -> Self { - Self::start("local", name, None, view_distance, lang, Some(pipe)) + Self::start("local", name, None, view_distance, lang, Some(pipe), None) } fn start( address: &str, @@ -97,12 +133,15 @@ impl Session { view_distance: i8, lang: Arc, local: Option, + cookies: Option, ) -> Self { let (send, events) = channel(); let writer = Arc::new(Mutex::new(None)); let configuring = Arc::new(AtomicBool::new(true)); let counters = Arc::new(Mutex::new(None)); - let (thread_writer, thread_counters) = (writer.clone(), counters.clone()); + let cookies = cookies.unwrap_or_default(); + let (thread_writer, thread_counters, thread_cookies) = + (writer.clone(), counters.clone(), cookies.clone()); let thread_configuring = configuring.clone(); let (address_owned, name_owned) = (address.to_owned(), name.to_owned()); let thread = std::thread::Builder::new() @@ -119,6 +158,7 @@ impl Session { &thread_writer, &thread_configuring, &thread_counters, + &thread_cookies, ); let from_server = result.is_ok(); let reason = result.unwrap_or_else(|e| e); @@ -140,6 +180,7 @@ impl Session { address: address.to_owned(), name: name.to_owned(), counters, + cookies, debug, } } @@ -291,6 +332,7 @@ fn run( shared_writer: &Mutex>, configuring: &AtomicBool, shared_counters: &Mutex>>, + cookies: &Cookies, ) -> Result { let (host, port, mut c) = if let Some(pipe) = local { (address.to_owned(), 0, Connection::local(pipe)) @@ -419,13 +461,13 @@ fn run( .map_err(e)?; let (mut reader, writer) = c.split(); *shared_writer.lock().unwrap() = Some(writer); - let registries = configure(&mut reader, shared_writer, configuring, lang, send)?; + let registries = configure(&mut reader, shared_writer, configuring, lang, send, cookies)?; let _ = send.send(Event::Joined { registries: Arc::new(registries), uuid: profile.uuid, name: profile.name, }); - receive_play(&mut reader, shared_writer, configuring, lang, send) + receive_play(&mut reader, shared_writer, configuring, lang, send, cookies) } fn receive_play( @@ -434,6 +476,7 @@ fn receive_play( configuring: &AtomicBool, lang: &Language, send: &Sender, + cookies: &Cookies, ) -> Result { loop { let (id, payload) = reader.recv().map_err(|e| e.to_string())?; @@ -469,9 +512,31 @@ fn receive_play( let _ = w.send(&play::Serverbound::ConfigurationAcknowledged(Empty).encode()); configuring.store(true, Ordering::Relaxed); } - let registries = configure(reader, shared_writer, configuring, lang, send)?; + let registries = + configure(reader, shared_writer, configuring, lang, send, cookies)?; let _ = send.send(Event::Reconfigured(Arc::new(registries))); } + // ClientCommonPacketListenerImpl.handleRequestCookie: the stored + // cookie (or none) goes straight back. + play::Clientbound::CookieRequest(q) => { + let payload = cookies.lock().unwrap().get(&q.key).cloned(); + reply(play::Serverbound::CookieResponse(cfg::CookieResponse { + key: q.key, + payload, + })); + } + play::Clientbound::StoreCookie(p) => { + cookies.lock().unwrap().insert(p.key, p.payload); + } + // ClientCommonPacketListenerImpl.handleTransfer: the connection + // ends and the game connects to the other address. + play::Clientbound::Transfer(p) => { + let _ = send.send(Event::Transfer { + host: p.host, + port: p.port, + }); + return Ok(tr(lang, "disconnect.transfer")); + } play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)), play::Clientbound::CustomPayload(p) if p.channel == "minecraft:brand" => { receive_brand(&p, send); @@ -493,6 +558,7 @@ fn configure( configuring: &AtomicBool, lang: &Language, send: &Sender, + cookies: &Cookies, ) -> Result { let mut registries = Dynamic::default(); let reply = |p: cfg::Serverbound| -> Result<(), String> { @@ -525,11 +591,22 @@ fn configure( let _ = send.send(Event::PackPop(p.id)); } cfg::Clientbound::CookieRequest(q) => { + let payload = cookies.lock().unwrap().get(&q.key).cloned(); reply(cfg::Serverbound::CookieResponse(cfg::CookieResponse { key: q.key, - payload: None, + payload, }))? } + cfg::Clientbound::StoreCookie(p) => { + cookies.lock().unwrap().insert(p.key, p.payload); + } + cfg::Clientbound::Transfer(p) => { + let _ = send.send(Event::Transfer { + host: p.host, + port: p.port, + }); + return Err(tr(lang, "disconnect.transfer")); + } cfg::Clientbound::Disconnect(d) => return Err(plain(&d.reason, lang)), cfg::Clientbound::FinishConfiguration(_) => { let mut w = writer.lock().unwrap(); @@ -659,6 +736,7 @@ mod tests { &AtomicBool::new(false), &Language::new(), &send, + &Cookies::default(), ) }); let mut server = Connection::local(server); @@ -708,6 +786,7 @@ mod tests { address: "local".into(), name: "Player".into(), counters: Arc::new(Mutex::new(None)), + cookies: Cookies::default(), debug: false, }; let (thread_writer, thread_configuring) = @@ -719,6 +798,7 @@ mod tests { &thread_configuring, &Language::new(), &send, + &Cookies::default(), ) }); let mut server = Connection::local(server); diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 26bb96316..67373cf4b 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -13,8 +13,9 @@ use crate::{ packets::{ Empty, configuration::{ - ClientInformation, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPop, - ResourcePackPush, ResourcePackResponse, UpdateTags, + ClientInformation, CookieRequest, CookieResponse, CustomPayload, Disconnect, KeepAlive, + Ping, ResourcePackPop, ResourcePackPush, ResourcePackResponse, StoreCookie, Transfer, + UpdateTags, }, login::Property, }, @@ -1759,6 +1760,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { ContainerSetContent(ContainerSetContent) = CONTAINER_SET_CONTENT, ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA, ContainerSetSlot(ContainerSetSlot) = CONTAINER_SET_SLOT, + CookieRequest(CookieRequest) = COOKIE_REQUEST, CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, Disconnect(Disconnect) = DISCONNECT, DisguisedChat(DisguisedChat) = DISGUISED_CHAT, @@ -1836,6 +1838,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { SoundEntity(SoundEntity) = SOUND_ENTITY, StopSound(StopSound) = STOP_SOUND, StartConfiguration(Empty) = START_CONFIGURATION, + StoreCookie(StoreCookie) = STORE_COOKIE, SwingAnimation(SwingAnimation) = SWING_ANIMATION, SystemChat(SystemChat) = SYSTEM_CHAT, TabList(TabList) = TAB_LIST, @@ -1843,6 +1846,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { TeleportEntity(TeleportEntity) = TELEPORT_ENTITY, TickingState(TickingState) = TICKING_STATE, TickingStep(TickingStep) = TICKING_STEP, + Transfer(Transfer) = TRANSFER, UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS, UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES, LevelParticles(LevelParticles) = LEVEL_PARTICLES, @@ -2223,6 +2227,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ContainerButtonClick(ContainerButtonClick) = CONTAINER_BUTTON_CLICK, ContainerClick(ContainerClick) = CONTAINER_CLICK, ContainerClose(ContainerClose) = CONTAINER_CLOSE, + CookieResponse(CookieResponse) = COOKIE_RESPONSE, CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, EditBook(EditBook) = EDIT_BOOK, Interact(Interact) = INTERACT, From 98bebd26bdc33efaa4483ac5d5cbb07250fc1345 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:14:48 +0100 Subject: [PATCH 07/23] Launcher: one place reads the pinned appearance (theme::pinned_dark) The title bar and the theme both resolved HORIZON_LAUNCHER_APPEARANCE and the Settings choice; titlebar::apply_appearance now uses the theme's helper. Co-Authored-By: Claude Opus 5.5 --- launcher/src/theme.rs | 39 +++++++++++++++++++++++++-------------- launcher/src/titlebar.rs | 21 +++++++-------------- 2 files changed, 32 insertions(+), 28 deletions(-) diff --git a/launcher/src/theme.rs b/launcher/src/theme.rs index 60b796709..9d495a598 100644 --- a/launcher/src/theme.rs +++ b/launcher/src/theme.rs @@ -74,22 +74,33 @@ fn c(hex: u32) -> Hsla { rgb(hex).into() } +/// Whether the launcher is pinned dark (`Some(true)`) or light, or follows the system (`None`): +/// `HORIZON_LAUNCHER_APPEARANCE=light` or `dark` (for screenshots and tests), else the player's +/// choice in Settings. +pub fn pinned_dark(choice: Appearance) -> Option { + match std::env::var("HORIZON_LAUNCHER_APPEARANCE").as_deref() { + Ok("light") => Some(false), + Ok("dark") => Some(true), + _ => match choice { + Appearance::Dark => Some(true), + Appearance::Light => Some(false), + Appearance::System => None, + }, + } +} + impl Theme { - /// The player's choice in Settings (dark unless they picked another), the system's when they - /// asked to follow it. `HORIZON_LAUNCHER_APPEARANCE=light` or `dark` overrides both (for - /// screenshots and tests). + /// The pinned look (`pinned_dark`: dark unless the player picked another), the system's when + /// they asked to follow it. pub fn for_appearance(choice: Appearance, system: WindowAppearance) -> Self { - match std::env::var("HORIZON_LAUNCHER_APPEARANCE").as_deref() { - Ok("light") => return Self::light(), - Ok("dark") => return Self::dark(), - _ => {} - } - match (choice, system) { - (Appearance::Light, _) => Self::light(), - (Appearance::System, WindowAppearance::Light | WindowAppearance::VibrantLight) => { - Self::light() - } - _ => Self::dark(), + let system_dark = !matches!( + system, + WindowAppearance::Light | WindowAppearance::VibrantLight + ); + if pinned_dark(choice).unwrap_or(system_dark) { + Self::dark() + } else { + Self::light() } } diff --git a/launcher/src/titlebar.rs b/launcher/src/titlebar.rs index 2e6445091..a023f7d7d 100644 --- a/launcher/src/titlebar.rs +++ b/launcher/src/titlebar.rs @@ -22,9 +22,8 @@ pub fn render(_theme: &Theme, _window: &Window) -> Option
{ /// macOS keeps the window's appearance on the system setting, so a launcher set to Dark still /// draws a light title bar on a light desktop. Pin the NSWindow's appearance to the choice -/// instead (`System` clears the pin, handing the chrome back to the system), honouring the same -/// `HORIZON_LAUNCHER_APPEARANCE` override the theme does. Other platforms' chrome already -/// follows the setting (ours is drawn, Windows and Linux follow the system either way). +/// instead (`theme::pinned_dark`: `System` clears the pin, handing the chrome back to the +/// system). Elsewhere the chrome is ours (Windows) or the system's (Linux). #[cfg(target_os = "macos")] pub fn apply_appearance(window: &Window, choice: Appearance) { use objc2_app_kit::{ @@ -33,17 +32,11 @@ pub fn apply_appearance(window: &Window, choice: Appearance) { }; use raw_window_handle::{HasWindowHandle, RawWindowHandle}; - // Reading AppKit's name constants is unsafe to rustc only (`use of extern static`). - let name: Option<&'static NSAppearanceName> = unsafe { - match std::env::var("HORIZON_LAUNCHER_APPEARANCE").as_deref() { - Ok("light") => Some(NSAppearanceNameAqua), - Ok("dark") => Some(NSAppearanceNameDarkAqua), - _ => match choice { - Appearance::Dark => Some(NSAppearanceNameDarkAqua), - Appearance::Light => Some(NSAppearanceNameAqua), - Appearance::System => None, - }, - } + // AppKit's name constants are extern statics: reading them is `unsafe` to rustc only. + let name: Option<&'static NSAppearanceName> = match crate::theme::pinned_dark(choice) { + Some(true) => Some(unsafe { NSAppearanceNameDarkAqua }), + Some(false) => Some(unsafe { NSAppearanceNameAqua }), + None => None, }; // The trait, not `Window::window_handle` (which is gpui's own `AnyWindowHandle`). let Ok(handle) = HasWindowHandle::window_handle(window) else { From 6b97107dc7ed8cc1ce6f5d76fcf932febf8b796d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:37:02 +0100 Subject: [PATCH 08/23] Transfers: handshake with the TRANSFER intent, answer login cookie requests Vanilla 26.3 reconnects after ClientboundTransferPacket with a TransferState, so Connection.initiateServerboundPlayConnection sends ClientIntent.TRANSFER (3): a target with accepts-transfers=false refuses the player, and the target can ask for the carried cookies during login (ClientHandshakePacketListenerImpl.handleRequestCookie). Both now match. A transfer from single player closes the world instead of connecting elsewhere (handleTransfer: "Cannot transfer to server from singleplayer"). Adds a unit test for the play-state store/request round trip and the Transfer event. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 6 +- crates/horizon-client/src/net.rs | 78 +++++++++++++++++++++++- 2 files changed, 81 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index c10b64c54..d70c0a4ae 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -893,8 +893,12 @@ impl Game<'_> { } } Event::Reconfigured(registries) => self.set_registries(registries), + // handleTransfer: "Cannot transfer to server from + // singleplayer" (no ServerData), so the world just closes. Event::Transfer { host, port } => { - if let Some(r) = self.remote.as_mut() { + if let Some(r) = self.remote.as_mut() + && r.session.address != "local" + { r.transfer = Some(format!("{host}:{port}")); } } diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index c4e53cef4..18aec0bea 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -139,6 +139,9 @@ impl Session { let writer = Arc::new(Mutex::new(None)); let configuring = Arc::new(AtomicBool::new(true)); let counters = Arc::new(Mutex::new(None)); + // Connection.initiateServerboundPlayConnection: a transfer's + // handshake says so (ClientIntent.TRANSFER). + let transferred = cookies.is_some(); let cookies = cookies.unwrap_or_default(); let (thread_writer, thread_counters, thread_cookies) = (writer.clone(), counters.clone(), cookies.clone()); @@ -159,6 +162,7 @@ impl Session { &thread_configuring, &thread_counters, &thread_cookies, + transferred, ); let from_server = result.is_ok(); let reason = result.unwrap_or_else(|e| e); @@ -333,6 +337,7 @@ fn run( configuring: &AtomicBool, shared_counters: &Mutex>>, cookies: &Cookies, + transferred: bool, ) -> Result { let (host, port, mut c) = if let Some(pipe) = local { (address.to_owned(), 0, Connection::local(pipe)) @@ -363,7 +368,11 @@ fn run( protocol: PROTOCOL_VERSION, host: host.clone(), port, - intent: handshake::LOGIN, + intent: if transferred { + handshake::TRANSFER + } else { + handshake::LOGIN + }, }) .encode(), ) @@ -433,11 +442,14 @@ fn run( ) .map_err(e)?; } + // ClientHandshakePacketListenerImpl.handleRequestCookie: the + // cookies a transfer carried over (none on a plain join). login::Clientbound::CookieRequest(q) => { + let payload = cookies.lock().unwrap().get(&q.key).cloned(); c.send( &login::Serverbound::CookieResponse(login::CookieResponse { key: q.key, - payload: None, + payload, }) .encode(), ) @@ -829,6 +841,68 @@ mod tests { assert!(thread.join().unwrap().is_err()); } + #[test] + fn play_answers_cookie_requests_from_stored_cookies_and_follows_transfers() { + let (client, server) = horizon_protocol::connection::Pipe::pair(); + let (mut reader, writer) = Connection::local(client).split(); + let writer = Arc::new(Mutex::new(Some(writer))); + let (send, events) = channel(); + let cookies = Cookies::default(); + let (thread_writer, thread_cookies) = (writer.clone(), cookies.clone()); + let thread = std::thread::spawn(move || { + receive_play( + &mut reader, + &thread_writer, + &AtomicBool::new(false), + &Language::new(), + &send, + &thread_cookies, + ) + }); + let mut server = Connection::local(server); + let ask = |server: &mut Connection, key: &str| { + let request = play::Clientbound::CookieRequest(cfg::CookieRequest { key: key.into() }); + server.send(&request.encode()).unwrap(); + let (id, body) = server.recv().unwrap(); + play::Serverbound::decode(id, &body).unwrap() + }; + // handleRequestCookie answers an unknown key with no payload. + assert_eq!( + ask(&mut server, "proxy:session"), + play::Serverbound::CookieResponse(cfg::CookieResponse { + key: "proxy:session".into(), + payload: None, + }) + ); + let store = play::Clientbound::StoreCookie(cfg::StoreCookie { + key: "proxy:session".into(), + payload: vec![1, 2, 3], + }); + server.send(&store.encode()).unwrap(); + assert_eq!( + ask(&mut server, "proxy:session"), + play::Serverbound::CookieResponse(cfg::CookieResponse { + key: "proxy:session".into(), + payload: Some(vec![1, 2, 3]), + }) + ); + let transfer = play::Clientbound::Transfer(cfg::Transfer { + host: "example.net".into(), + port: 25566, + }); + server.send(&transfer.encode()).unwrap(); + assert!(thread.join().unwrap().is_ok()); + assert!(matches!( + events.try_iter().last(), + Some(Event::Transfer { host, port: 25566 }) if host == "example.net" + )); + // The stored cookie stays for the next connection (TransferState). + assert_eq!( + cookies.lock().unwrap().get("proxy:session"), + Some(&vec![1, 2, 3]) + ); + } + #[test] fn server_brand_payload_is_decoded_and_invalid_or_unrelated_payloads_are_ignored() { let (send, events) = channel(); From 5d40d6a33ea36d07440d4eecf03ab63028eff3f6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:54:39 +0100 Subject: [PATCH 09/23] Telemetry server: the hub's votes (POST /hub/vote, GET /hub/votes) A thumbs-up on a roadmap item at playhorizon.dev/hub: one per browser (a random id the page keeps), taken back with "up": false, counts cached a minute. Item ids are checked for shape and capped at 1000 distinct items. Rate limits key their buckets by a keyed hash of the address (key drawn at start, in memory); no address is stored. CORS preflight for the website's JSON posts. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-telemetry-server/README.md | 7 +- crates/horizon-telemetry-server/src/hub.rs | 239 +++++++++++++++++++ crates/horizon-telemetry-server/src/lib.rs | 29 ++- crates/horizon-telemetry-server/src/store.rs | 3 +- crates/horizon-telemetry-server/tests/hub.rs | 116 +++++++++ 5 files changed, 388 insertions(+), 6 deletions(-) create mode 100644 crates/horizon-telemetry-server/src/hub.rs create mode 100644 crates/horizon-telemetry-server/tests/hub.rs diff --git a/crates/horizon-telemetry-server/README.md b/crates/horizon-telemetry-server/README.md index ed54024a1..2b86bf99d 100644 --- a/crates/horizon-telemetry-server/README.md +++ b/crates/horizon-telemetry-server/README.md @@ -1,6 +1,6 @@ # horizon-telemetry-server -This server receives what players choose to send (performance summaries, crash and bug reports, benchmark uploads: [docs/telemetry.md](../../docs/telemetry.md)) and stores it in one SQLite file. It serves anonymous totals to the website. It also keeps the live player count from the games' anonymous "I'm playing" pings, in memory only. It is one small Rust process, about 7 MB of memory when idle. +This server receives what players choose to send (performance summaries, crash and bug reports, benchmark uploads: [docs/telemetry.md](../../docs/telemetry.md)) and stores it in one SQLite file. It serves anonymous totals to the website. It also keeps the live player count from the games' anonymous "I'm playing" pings, in memory only, and the 👍 players give roadmap items on the hub (playhorizon.dev/hub). It is one small Rust process, about 7 MB of memory when idle. cargo run --release # in this folder: its own workspace, like the launcher's PORT=8080 HORIZON_TELEMETRY_DB=/data/telemetry.sqlite3 horizon-telemetry-server @@ -17,6 +17,8 @@ It runs at **https://telemetry.playhorizon.dev** (`DEFAULT_ENDPOINT` in `crates/ | `GET /v1/benchmarks/summary` | Players' benchmark uploads grouped by GPU, CPU, render distance and game, for the website's Benchmarks page (below). Cached 10 minutes, same `Access-Control-Allow-Origin`. | | `POST /v1/live` | A game's "I'm playing" ping (JSON, at most 512 bytes). Returns 204. Returns 400 for a bad ping, 413 for one too large, 429 over the address's limit, 503 when it holds `LIVE_MAX_SESSIONS` already. | | `GET /v1/live` | How many play now, rounded: `playing`, `lan`, `versions`, `platforms`. Made again at most every 15 seconds, with the same `Access-Control-Allow-Origin`. | +| `POST /hub/vote` | `{"item": "", "voter": "", "up": true}`: a 👍 on a roadmap item, one per voter; `"up": false` takes it back. Returns `{"item", "votes"}`. 400 for a bad id, 429 over the address's limit. `OPTIONS` answers the website's preflight. | +| `GET /hub/votes` | `{"votes": {"": n}}`. Made again at most every minute. | | `GET /healthz` | `ok` | The totals are grouped per version, OS, GPU vendor and render distance. Each group has its sessions, install-days, hours played, the 14 frame-time buckets summed, and the mean p50 and p99 frame times. Groups with fewer than 5 install-days are left out. The totals also list crash counts per version. Benchmark uploads are published only through the summary below, never one by one. @@ -56,6 +58,8 @@ The live count is a table in memory: a session ID, when it last pinged, its vers The day stored is the day the server received an item. The sender's IP address is never written down. The per-address rate limit keeps addresses in memory for an hour at most. +A hub vote is stored as an item ID and the browser's random ID. The hub's rate limits key their buckets by a hash of the address with a key drawn at each start, in memory. + Raw rows are deleted after `HORIZON_TELEMETRY_RETENTION_DAYS` (180). The daily totals stay; they hold no install ID. ## Settings @@ -73,6 +77,7 @@ All are environment variables: - `HORIZON_TELEMETRY_LIVE_PER_HOUR` per address, pings and reads (600, bursts of 60: ten players behind one address) - `HORIZON_TELEMETRY_LIVE_WINDOW_SECONDS` (120) - `HORIZON_TELEMETRY_LIVE_MAX_SESSIONS` (200 000) +- `HORIZON_TELEMETRY_HUB_PER_HOUR` votes and vote reads per address (120, bursts of 12) ## Hosting diff --git a/crates/horizon-telemetry-server/src/hub.rs b/crates/horizon-telemetry-server/src/hub.rs new file mode 100644 index 000000000..ebf22610d --- /dev/null +++ b/crates/horizon-telemetry-server/src/hub.rs @@ -0,0 +1,239 @@ +//! The hub's votes: a 👍 on a roadmap item at playhorizon.dev/hub. roadmap/README.md documents them for Kira and the website. +//! +//! - `POST /hub/vote`: a 👍 on a roadmap item, one per browser (`voter`, a random id the page makes and +//! keeps); `"up": false` takes it back. Answers the item's count. +//! - `GET /hub/votes`: every item's count, cached a minute. +//! +//! Stored: an item id and the browser's random id per vote. Never an IP address: the rate limits key their +//! buckets by a hash of it with a key drawn at start, in memory. +use std::collections::HashMap; +use std::hash::BuildHasher; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use axum::extract::{Request, State}; +use axum::http::{HeaderValue, StatusCode, header}; +use axum::response::Response; +use rusqlite::params; +use serde_json::{Map, Value, json}; + +use crate::store::Store; +use crate::{App, json_response, peer, take}; + +pub const SCHEMA: &str = " +CREATE TABLE IF NOT EXISTS hub_votes (item TEXT NOT NULL, voter TEXT NOT NULL, PRIMARY KEY (item, voter)) WITHOUT ROWID; +"; + +/// Items with votes, at most: a vote for a new id past this is refused (ids are only checked for shape). +const MAX_ITEMS: i64 = 1000; +/// The largest body accepted: a report's fields at their limits, as JSON, fit. +const MAX_BODY: usize = 24 * 1024; +const VOTES_FOR: Duration = Duration::from_secs(60); + +/// The hub's buckets: keyed by a keyed hash of the address, never the address itself. +pub type HashedBuckets = HashMap; + +/// A roadmap item id's shape: lowercase words joined by dashes (tools/roadmap.py), at most 48 characters. +pub fn item_id(id: &str) -> bool { + (1..=48).contains(&id.len()) + && !id.starts_with('-') + && !id.ends_with('-') + && !id.contains("--") + && id + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +/// A voter id's shape: what `crypto.randomUUID()` and similar make. +fn voter_id(id: &str) -> bool { + (16..=64).contains(&id.len()) + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +impl Store { + /// Adds or takes back a vote; the item's count after it. None when the item would be one too many. + pub fn vote(&mut self, item: &str, voter: &str, up: bool) -> rusqlite::Result> { + let tx = self.db.transaction()?; + if up { + let known = tx + .prepare("SELECT 1 FROM hub_votes WHERE item = ?1 LIMIT 1")? + .exists([item])?; + let items: i64 = + tx.query_row("SELECT count(DISTINCT item) FROM hub_votes", [], |r| { + r.get(0) + })?; + if !known && items >= MAX_ITEMS { + return Ok(None); + } + tx.execute( + "INSERT OR IGNORE INTO hub_votes (item, voter) VALUES (?1, ?2)", + params![item, voter], + )?; + } else { + tx.execute( + "DELETE FROM hub_votes WHERE item = ?1 AND voter = ?2", + params![item, voter], + )?; + } + let count = tx.query_row( + "SELECT count(*) FROM hub_votes WHERE item = ?1", + [item], + |r| r.get(0), + )?; + tx.commit()?; + Ok(Some(count)) + } + + /// Every item's count. + pub fn votes(&self) -> rusqlite::Result> { + let mut statement = self + .db + .prepare("SELECT item, count(*) FROM hub_votes GROUP BY item ORDER BY item")?; + let rows = + statement.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?; + rows.map(|row| row.map(|(item, n)| (item, Value::from(n)))) + .collect() + } +} + +impl App { + pub(crate) fn hashed(&self, req: &Request) -> u64 { + self.hub_key.hash_one(self.client(req.headers(), peer(req))) + } + + /// Takes a token from the address's hub bucket (votes and reads of the counts). + fn allow_hub(&self, req: &Request) -> bool { + take( + &self.hub_buckets, + self.config.hub_per_hour, + self.hashed(req), + ) + } + + /// The hub's share of `maintain`: idle buckets are forgotten. + pub(crate) fn forget_hub_buckets(&self) { + self.hub_buckets + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|_, (_, at)| at.elapsed() < Duration::from_secs(3600)); + } +} + +/// A JSON answer to the website: its origin may read it, nothing caches it. +pub(crate) fn answer(app: &App, code: StatusCode, body: Value) -> Response { + let mut response = json_response(app, body.to_string(), 0); + *response.status_mut() = code; + response + .headers_mut() + .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + response +} + +pub(crate) fn refuse(app: &App, code: StatusCode, message: &str) -> Response { + answer(app, code, json!({ "error": message })) +} + +/// A browser's preflight for the JSON posts: the website may post them. +pub async fn preflight(State(app): State>) -> Response { + let mut response = answer(&app, StatusCode::NO_CONTENT, Value::Null); + *response.body_mut() = axum::body::Body::empty(); + let headers = response.headers_mut(); + headers.remove(header::CONTENT_TYPE); + headers.insert( + header::ACCESS_CONTROL_ALLOW_METHODS, + HeaderValue::from_static("POST"), + ); + headers.insert( + header::ACCESS_CONTROL_ALLOW_HEADERS, + HeaderValue::from_static("content-type"), + ); + headers.insert( + header::ACCESS_CONTROL_MAX_AGE, + HeaderValue::from_static("86400"), + ); + response +} + +pub(crate) async fn json_body(req: Request) -> Result { + let bytes = axum::body::to_bytes(req.into_body(), MAX_BODY) + .await + .map_err(|_| "too large")?; + serde_json::from_slice(&bytes).map_err(|_| "send JSON") +} + +/// `POST /hub/vote` `{"item", "voter", "up"}`: 200 `{"item", "votes"}`. +pub async fn vote(State(app): State>, req: Request) -> Response { + if !app.allow_hub(&req) { + return refuse(&app, StatusCode::TOO_MANY_REQUESTS, "too many requests"); + } + let body = match json_body(req).await { + Ok(body) => body, + Err(e) => return refuse(&app, StatusCode::BAD_REQUEST, e), + }; + let item = body["item"].as_str().unwrap_or(""); + let voter = body["voter"].as_str().unwrap_or(""); + if !item_id(item) || !voter_id(voter) { + return refuse(&app, StatusCode::BAD_REQUEST, "an item id and a voter id"); + } + let up = body["up"].as_bool().unwrap_or(true); + let counted = app.store().vote(item, voter, up); + match counted { + Ok(Some(votes)) => { + *app.votes_cache.lock().unwrap_or_else(|e| e.into_inner()) = None; + answer( + &app, + StatusCode::OK, + json!({ "item": item, "votes": votes }), + ) + } + Ok(None) => refuse(&app, StatusCode::BAD_REQUEST, "no such item"), + Err(e) => { + eprintln!("horizon-telemetry-server: could not store a vote: {e}"); + refuse(&app, StatusCode::SERVICE_UNAVAILABLE, "try again later") + } + } +} + +/// `GET /hub/votes`: `{"votes": {"": n}}`, made again at most every minute. +pub async fn votes(State(app): State>, req: Request) -> Response { + if !app.allow_hub(&req) { + return refuse(&app, StatusCode::TOO_MANY_REQUESTS, "too many requests"); + } + let json = { + let mut cache = app.votes_cache.lock().unwrap_or_else(|e| e.into_inner()); + match &*cache { + Some((at, json)) if at.elapsed() < VOTES_FOR => json.clone(), + _ => { + let counts = app.store().votes(); + match counts { + Ok(counts) => { + let json = json!({ "votes": counts }).to_string(); + *cache = Some((Instant::now(), json.clone())); + json + } + Err(e) => { + eprintln!("horizon-telemetry-server: could not read the votes: {e}"); + return refuse(&app, StatusCode::SERVICE_UNAVAILABLE, "try again later"); + } + } + } + } + }; + json_response(&app, json, VOTES_FOR.as_secs()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ids_are_checked_for_shape() { + assert!(item_id("smooth-frames") && item_id("v2")); + for bad in ["", "-a", "a-", "a--b", "Smooth", "a b", &"a".repeat(49)] { + assert!(!item_id(bad), "{bad}"); + } + assert!(voter_id("0b7c3c9e-3f0a-4d8e-9a39-4c1f5a6b7d21") && !voter_id("short")); + } +} diff --git a/crates/horizon-telemetry-server/src/lib.rs b/crates/horizon-telemetry-server/src/lib.rs index 1a8e750e6..19ba3e1dc 100644 --- a/crates/horizon-telemetry-server/src/lib.rs +++ b/crates/horizon-telemetry-server/src/lib.rs @@ -7,6 +7,7 @@ //! least 3 installs only (`summary`), cached; the website's Benchmarks page reads it. //! - `POST /v1/live`: a game's anonymous "I'm playing" ping (`live`, in memory only). //! - `GET /v1/live`: how many play now, rounded, cached briefly. +//! - `POST /hub/vote`, `GET /hub/votes`: the hub's 👍 on roadmap items (`hub`). //! - `GET /healthz`. //! //! Abuse limits: a token bucket per IP address (kept in memory for an hour, never stored), a @@ -15,6 +16,7 @@ //! rows expire after `retention_days`; the daily totals stay. One small process and one SQLite //! file: see `README.md` for running it. use std::collections::HashMap; +use std::hash::{Hash, RandomState}; use std::net::{IpAddr, SocketAddr}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -27,6 +29,7 @@ use axum::routing::{delete, get, post}; use horizon_telemetry::batch; pub mod classes; +pub mod hub; pub mod live; pub mod store; pub mod summary; @@ -56,6 +59,8 @@ pub struct Config { pub live_window: Duration, /// Sessions the live count holds at most; a new one past that is refused. pub live_max_sessions: usize, + /// The hub's votes and reads of their counts an IP address may make an hour. + pub hub_per_hour: f64, } impl Default for Config { @@ -70,6 +75,7 @@ impl Default for Config { live_per_hour: 600.0, live_window: horizon_telemetry::live::WINDOW, live_max_sessions: 200_000, + hub_per_hour: 120.0, } } } @@ -77,7 +83,7 @@ impl Default for Config { impl Config { /// The defaults, with `HORIZON_TELEMETRY_RETENTION_DAYS`, `…_MIN_INSTALL_DAYS`, /// `…_REQUESTS_PER_HOUR`, `…_ITEMS_PER_DAY`, `…_TRUST_PROXY` (1), `…_ALLOW_ORIGIN`, - /// `…_LIVE_PER_HOUR`, `…_LIVE_WINDOW_SECONDS` and `…_LIVE_MAX_SESSIONS`. + /// `…_LIVE_PER_HOUR`, `…_LIVE_WINDOW_SECONDS`, `…_LIVE_MAX_SESSIONS` and `…_HUB_PER_HOUR`. pub fn from_env() -> Self { let var = |k: &str| std::env::var(format!("HORIZON_TELEMETRY_{k}")).ok(); let d = Self::default(); @@ -105,6 +111,9 @@ impl Config { live_max_sessions: var("LIVE_MAX_SESSIONS") .and_then(|v| v.parse().ok()) .unwrap_or(d.live_max_sessions), + hub_per_hour: var("HUB_PER_HOUR") + .and_then(|v| v.parse().ok()) + .unwrap_or(d.hub_per_hour), } } } @@ -126,6 +135,12 @@ pub struct App { summary_cache: Mutex>, /// Today, in days since 1970 (a test moves it). today: Box u32 + Send + Sync>, + /// The key the hub's buckets hash addresses with, drawn at start and never stored. + hub_key: RandomState, + /// The hub's votes and vote counts, per hashed address. + hub_buckets: Mutex, + /// `GET /hub/votes`'s answer and when it was made. + votes_cache: Mutex>, } type Buckets = HashMap; @@ -157,6 +172,9 @@ impl App { cache: Mutex::default(), summary_cache: Mutex::default(), today, + hub_key: RandomState::new(), + hub_buckets: Mutex::default(), + votes_cache: Mutex::default(), }) } @@ -221,6 +239,7 @@ impl App { pub fn maintain(&self) -> rusqlite::Result { let oldest = (self.today)().saturating_sub(self.config.retention_days); let removed = self.store().expire(oldest)?; + self.forget_hub_buckets(); for buckets in [&self.buckets, &self.live_buckets] { buckets .lock() @@ -235,14 +254,14 @@ impl App { } } -/// Takes a token for `ip` from its bucket in `buckets` (`per_hour`, bursts of a tenth of it); +/// Takes a token for `key` from its bucket in `buckets` (`per_hour`, bursts of a tenth of it); /// false when it has none left. -fn take(buckets: &Mutex, per_hour: f64, ip: IpAddr) -> bool { +fn take(buckets: &Mutex>, per_hour: f64, key: K) -> bool { let rate = per_hour / 3600.0; let burst = (per_hour / 10.0).max(1.0); let mut buckets = buckets.lock().unwrap_or_else(|e| e.into_inner()); let now = Instant::now(); - let (tokens, at) = buckets.entry(ip).or_insert((burst, now)); + let (tokens, at) = buckets.entry(key).or_insert((burst, now)); *tokens = (*tokens + now.duration_since(*at).as_secs_f64() * rate).min(burst); *at = now; if *tokens < 1.0 { @@ -482,6 +501,8 @@ pub fn router(app: Arc) -> Router { .route("/v1/installs/{id}", delete(forget)) .route("/v1/aggregate", get(aggregate)) .route("/v1/benchmarks/summary", get(benchmarks)) + .route("/hub/vote", post(hub::vote).options(hub::preflight)) + .route("/hub/votes", get(hub::votes)) .route("/healthz", get(|| async { "ok" })) .with_state(app) } diff --git a/crates/horizon-telemetry-server/src/store.rs b/crates/horizon-telemetry-server/src/store.rs index 02c8803ae..d1137d197 100644 --- a/crates/horizon-telemetry-server/src/store.rs +++ b/crates/horizon-telemetry-server/src/store.rs @@ -123,13 +123,14 @@ pub fn gpu_vendor(gpu: &str) -> &'static str { } pub struct Store { - db: Connection, + pub(crate) db: Connection, } impl Store { pub fn open(path: &str) -> rusqlite::Result { let mut db = Connection::open(path)?; db.execute_batch(SCHEMA)?; + db.execute_batch(crate::hub::SCHEMA)?; migrate(&mut db)?; Ok(Self { db }) } diff --git a/crates/horizon-telemetry-server/tests/hub.rs b/crates/horizon-telemetry-server/tests/hub.rs new file mode 100644 index 000000000..10ddc12c4 --- /dev/null +++ b/crates/horizon-telemetry-server/tests/hub.rs @@ -0,0 +1,116 @@ +//! The hub's votes through the HTTP interface. +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use horizon_telemetry_server::store::Store; +use horizon_telemetry_server::{App, Config, router}; +use http_body_util::BodyExt; +use serde_json::{Value, json}; +use tower::ServiceExt; + +const DAY: u32 = 20_741; +const VOTER: &str = "0b7c3c9e-3f0a-4d8e-9a39-4c1f5a6b7d21"; + +struct Hub { + app: Arc, +} + +fn hub(config: Config) -> Hub { + let app = App::with_clock(Store::open(":memory:").unwrap(), config, Box::new(|| DAY)); + Hub { app } +} + +fn config() -> Config { + Config::default() +} + +impl Hub { + async fn send(&self, req: Request) -> (StatusCode, Value) { + let res = router(self.app.clone()).oneshot(req).await.unwrap(); + let code = res.status(); + let body = res.into_body().collect().await.unwrap().to_bytes(); + (code, serde_json::from_slice(&body).unwrap_or(Value::Null)) + } + + async fn post(&self, path: &str, body: Value) -> (StatusCode, Value) { + self.send( + Request::post(path) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + } + + async fn get(&self, path: &str) -> (StatusCode, Value) { + self.send(Request::get(path).body(Body::empty()).unwrap()) + .await + } +} + +#[tokio::test] +async fn votes_count_once_per_browser_and_can_be_taken_back() { + let hub = hub(config()); + let vote = |up: bool, voter: &str| json!({ "item": "smooth-frames", "voter": voter, "up": up }); + assert_eq!( + hub.post("/hub/vote", vote(true, VOTER)).await, + ( + StatusCode::OK, + json!({ "item": "smooth-frames", "votes": 1 }) + ) + ); + assert_eq!( + hub.post("/hub/vote", vote(true, VOTER)).await.1["votes"], + 1, + "a second vote changes nothing" + ); + let other = "f".repeat(32); + assert_eq!( + hub.post("/hub/vote", vote(true, &other)).await.1["votes"], + 2 + ); + assert_eq!( + hub.get("/hub/votes").await, + (StatusCode::OK, json!({ "votes": { "smooth-frames": 2 } })) + ); + assert_eq!( + hub.post("/hub/vote", vote(false, VOTER)).await.1["votes"], + 1 + ); + assert_eq!( + hub.get("/hub/votes").await.1["votes"]["smooth-frames"], + 1, + "a vote drops the cached counts" + ); + for bad in [ + json!({ "item": "Not An Id", "voter": VOTER }), + json!({ "item": "a", "voter": "short" }), + json!([]), + ] { + assert_eq!(hub.post("/hub/vote", bad).await.0, StatusCode::BAD_REQUEST); + } +} + +#[tokio::test] +async fn the_website_may_post_from_the_browser() { + let hub = hub(config()); + let res = router(hub.app.clone()) + .oneshot( + Request::options("/hub/vote") + .header("origin", "https://playhorizon.dev") + .header("access-control-request-method", "POST") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::NO_CONTENT); + let header = |name: &str| res.headers()[name].to_str().unwrap().to_owned(); + assert_eq!( + header("access-control-allow-origin"), + "https://playhorizon.dev" + ); + assert_eq!(header("access-control-allow-methods"), "POST"); + assert_eq!(header("access-control-allow-headers"), "content-type"); +} From e936e412ba04f67d907d4b5abdeb412a8f3e6462 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:29:37 +0100 Subject: [PATCH 10/23] Website: the hub (/hub) with the roadmap, a Simple / Technical switch and live states playhorizon.dev/hub is the public entry point to what is happening on Horizon. Overview: where Horizon is, the 3 to 5 things in focus, what is next, what shipped last, how to help. Roadmap: Now / Next / Later / Help wanted / Shipped, filtered by area, every item with its issues and pull requests in their GitHub state (baked at build, refreshed in the browser). Contribute: good first tasks, claiming, connecting an agent to Kira, the rules. A Simple / Technical switch swaps every item's plain and dev text and is remembered. /roadmap redirects to the Roadmap tab. tools/roadmap.py build now also writes website/data/roadmap.json, which the site reads and serves at /hub/roadmap.json. Co-Authored-By: Claude Opus 5.5 --- tests/test_roadmap.py | 13 +- tools/roadmap.py | 46 +++- website/Caddyfile | 5 +- website/README.md | 4 + website/build.mjs | 64 ++++- website/data/roadmap.json | 557 ++++++++++++++++++++++++++++++++++++++ website/serve.mjs | 5 + website/src/hub-page.js | 119 ++++++++ website/src/hub.html | 110 ++++++++ website/src/hub.js | 175 ++++++++++++ website/src/hub.test.mjs | 48 ++++ website/src/style.css | 63 ++++- 12 files changed, 1187 insertions(+), 22 deletions(-) create mode 100644 website/data/roadmap.json create mode 100644 website/src/hub-page.js create mode 100644 website/src/hub.html create mode 100644 website/src/hub.js create mode 100644 website/src/hub.test.mjs diff --git a/tests/test_roadmap.py b/tests/test_roadmap.py index 3b8e15b45..641d4e11b 100644 --- a/tests/test_roadmap.py +++ b/tests/test_roadmap.py @@ -1,5 +1,6 @@ import copy import datetime +import json import tomllib import unittest from unittest import mock @@ -77,9 +78,15 @@ class RepositoryRoadmap(unittest.TestCase): def test_the_roadmap_keeps_its_rules(self): self.assertEqual(roadmap.validate(roadmap.load()), []) - def test_roadmap_md_is_generated_from_the_toml(self): - self.assertEqual(roadmap.OUTPUT.read_text(), roadmap.render(roadmap.load()), - "ROADMAP.md is out of date: run `python3 tools/roadmap.py build`") + def test_generated_files_match_the_toml(self): + for path, text in roadmap.outputs(roadmap.load()).items(): + self.assertEqual(path.read_text(), text, f"{path.name} is out of date: run `python3 tools/roadmap.py build`") + + def test_site_data_has_every_item_in_one_line_text(self): + data = json.loads(roadmap.site_data(tomllib.loads(SAMPLE))) + self.assertEqual([item["id"] for item in data["items"]], ["fast", "faster", "fastest", "old"]) + self.assertEqual(data["items"][0]["dev"], "Multiply, not divide (#10).") + self.assertEqual(data["areas"], [{"id": "performance", "name": "Performance"}]) class Rules(unittest.TestCase): diff --git a/tools/roadmap.py b/tools/roadmap.py index d80c9692c..1a4f58136 100644 --- a/tools/roadmap.py +++ b/tools/roadmap.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 """Horizon's roadmap: roadmap/roadmap.toml is the source, ROADMAP.md is generated from it. - python3 tools/roadmap.py build write ROADMAP.md - python3 tools/roadmap.py build --check fail when ROADMAP.md is out of date (CI) + python3 tools/roadmap.py build write ROADMAP.md and website/data/roadmap.json + python3 tools/roadmap.py build --check fail when either is out of date (CI) python3 tools/roadmap.py check --offline the file's own rules (CI) python3 tools/roadmap.py check the same, then GitHub: links resolve, no stale Now item python3 tools/roadmap.py sync [--dry-run] items whose pull requests all merged become shipped, @@ -28,6 +28,8 @@ from pathlib import Path ROOT = Path(__file__).resolve().parent.parent SOURCE = ROOT / "roadmap" / "roadmap.toml" OUTPUT = ROOT / "ROADMAP.md" +# What the website's hub reads (website/build.mjs), and serves at /hub/roadmap.json for Kira and others. +SITE_DATA = ROOT / "website" / "data" / "roadmap.json" REPO = "ludovic111/horizon" SITE = "https://playhorizon.dev/hub" @@ -227,6 +229,27 @@ def render(data): return "\n".join(out) + "\n" +def site_data(data): + """website/data/roadmap.json: the items as the hub and Kira read them, in the file's order.""" + keys = ("id", "title", "status", "area", "plain", "dev", "links", "focus", "ongoing", "shipped_in", "post") + out = { + "format": "horizon-roadmap", + "version": 1, + "source": "roadmap/roadmap.toml", + "overview": {key: " ".join(value.split()) for key, value in data["overview"].items()}, + "statuses": [{"id": key, "name": name} for key, name in STATUSES.items()], + "areas": [{"id": key, "name": name} for key, name in areas_in_order(data)], + "items": [{key: (" ".join(item[key].split()) if isinstance(item[key], str) else item[key]) + for key in keys if key in item} for item in data.get("item", [])], + } + return json.dumps(out, indent=1, ensure_ascii=False) + "\n" + + +def outputs(data): + """Every generated file and its content.""" + return {OUTPUT: render(data), SITE_DATA: site_data(data)} + + # --- GitHub --------------------------------------------------------------------------------------------------- def token(): @@ -466,13 +489,15 @@ def command_build(args): problems = validate(data) if problems: return report(problems) - markdown = render(data) + files = outputs(data) if args.check: - if not OUTPUT.exists() or OUTPUT.read_text() != markdown: - return report(["ROADMAP.md is out of date: run `python3 tools/roadmap.py build`"]) - return 0 - OUTPUT.write_text(markdown) - print(f"roadmap: wrote {OUTPUT.relative_to(ROOT)}") + stale = [path for path, text in files.items() if not path.exists() or path.read_text() != text] + return report([f"{path.relative_to(ROOT)} is out of date: run `python3 tools/roadmap.py build`" + for path in stale]) + for path, text in files.items(): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + print(f"roadmap: wrote {path.relative_to(ROOT)}") return 0 @@ -505,8 +530,9 @@ def command_sync(args): if len(new.get("item", [])) != len(data.get("item", [])) or validate(new): return report(["sync produced an invalid file; nothing written"] + validate(new)) SOURCE.write_text(text) - OUTPUT.write_text(render(new)) - print("roadmap: wrote roadmap/roadmap.toml and ROADMAP.md") + for path, content in outputs(new).items(): + path.write_text(content) + print("roadmap: wrote roadmap/roadmap.toml, ROADMAP.md and website/data/roadmap.json") return 0 diff --git a/website/Caddyfile b/website/Caddyfile index 1571566ad..50ba44381 100644 --- a/website/Caddyfile +++ b/website/Caddyfile @@ -33,9 +33,12 @@ rewrite /privacy /privacy.html rewrite /releases /releases.html rewrite /benchmarks /benchmarks.html + rewrite /hub /hub.html + # The roadmap is the hub's Roadmap tab. + redir /roadmap /hub#roadmap permanent @doc path_regexp doc ^/docs/([a-z-]+)$ rewrite @doc /docs/{re.doc.1}.html - @pages path / /index.html /404.html /privacy.html /releases /releases.html /benchmarks /benchmarks.html /benchmarks.json /docs /docs/* /sitemap.xml + @pages path / /index.html /404.html /privacy.html /releases /releases.html /benchmarks /benchmarks.html /benchmarks.json /hub /hub.html /hub/* /docs /docs/* /sitemap.xml header @pages Cache-Control "no-cache" @legal path /LEGAL.md /fonts/*.txt header @legal Content-Type "text/plain; charset=utf-8" diff --git a/website/README.md b/website/README.md index 9d1f8dc8d..c73683c73 100644 --- a/website/README.md +++ b/website/README.md @@ -25,6 +25,7 @@ src/404.html the not-found page src/privacy.html what the launcher can send when players allow it, retention, deletion (/privacy) src/releases.html every release, newest first, with what it adds and fixes, its notes and downloads (/releases) src/benchmarks.html Horizon against vanilla 26.3 on our machines, the hardware picker, players' results (/benchmarks) +src/hub.html the hub (/hub, /roadmap redirects to its Roadmap tab): Overview, Roadmap, Contribute, a Simple / Technical switch src/docs.html the template of every documentation page (/docs/...), with its left navigation src/tokens.css the design tokens, generated from crates/horizon-theme (do not edit) src/style.css every style, on top of the tokens @@ -39,6 +40,9 @@ src/estimate.js estimates for unmeasured hardware from the nearest measured m src/markdown.js a small Markdown renderer (escapes everything), shared by build and page src/releases.js the home page's "Recently added" and the Releases page's markup, shared by build and page src/contributors.js the contributors' filtering and markup, shared by build and page +src/hub.js the hub's markup from data/roadmap.json and GitHub's issue states, shared by build and page +src/hub-page.js the hub page: tabs by #hash, the Simple / Technical switch (localStorage), the area filter, live states +data/roadmap.json the roadmap, generated by tools/roadmap.py from roadmap/roadmap.toml (do not edit); served at /hub/roadmap.json public/ fonts, screenshots, icons, og.png, robots.txt, benchmarks.json: copied as is (sitemap.xml is written by the build) data/benchmarks/ our raw benchmark reports (tools/perf_bench.py) and fleet.json, the list scripts/benchmarks.mjs reads scripts/benchmarks.mjs benchmark reports -> public/benchmarks.json (ours, and players' groups of 3+ installs) diff --git a/website/build.mjs b/website/build.mjs index 8b0954054..b36e0e103 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -16,6 +16,7 @@ import { machinesHtml, playersHtml } from "./src/bench.js"; import { CPUS, GPUS, singleThread } from "./src/hardware.js"; import { isGame, isLauncher, launcherVersion, newestFirst } from "./src/versions.js"; import { contributorsFrom, contributorsHtml } from "./src/contributors.js"; +import { areaFilterHtml, helpWantedHtml, overviewHtml, roadmapHtml, slimIssue } from "./src/hub.js"; const site = dirname(fileURLToPath(import.meta.url)); const dist = join(site, "dist"); @@ -77,6 +78,45 @@ try { console.warn(`contributors: ${e.message}; the page will load them itself`); } +// The hub's roadmap (data/roadmap.json, generated from roadmap/roadmap.toml by tools/roadmap.py) and the live state +// of the issues and pull requests its items link: the open ones and those closed lately, then (with a token) the +// older ones in one GraphQL request. Without GitHub the hub shows the links without their state. +const roadmap = JSON.parse(await readFile(join(site, "data", "roadmap.json"), "utf8")); +const linked = new Set(roadmap.items.flatMap((i) => (i.links || []).map((l) => Number((l.match(/^#(\d+)$/) || [])[1])).filter(Boolean))); +let hubLive = []; +try { + const urls = [1, 2, 3].map((p) => `https://api.github.com/repos/${REPO}/issues?state=open&per_page=100&page=${p}`); + urls.push(`https://api.github.com/repos/${REPO}/issues?state=closed&sort=updated&direction=desc&per_page=100`); + for (const url of urls) { + const res = await fetch(url, { headers: githubHeaders, signal: AbortSignal.timeout(15000) }); + if (!res.ok) throw new Error(`${res.status} from GitHub`); + hubLive.push(...(await res.json()).map(slimIssue)); + } + const missing = [...linked].filter((n) => !hubLive.some((i) => i.n === n)); + if (missing.length && process.env.GITHUB_TOKEN) { + const fields = missing.map((n) => `n${n}: issueOrPullRequest(number: ${n}) { ... on Issue { number title state stateReason url } ... on PullRequest { number title state isDraft mergedAt url } }`).join(" "); + const res = await fetch("https://api.github.com/graphql", { + method: "POST", + headers: githubHeaders, + body: JSON.stringify({ query: `query { repository(owner: "ludovic111", name: "horizon") { ${fields} } }` }), + signal: AbortSignal.timeout(15000), + }); + const nodes = Object.values((await res.json()).data?.repository || {}).filter(Boolean); + hubLive.push( + ...nodes.map((x) => + slimIssue({ + number: x.number, title: x.title, html_url: x.url, draft: x.isDraft, + state: x.state === "OPEN" ? "open" : "closed", state_reason: x.stateReason === "NOT_PLANNED" ? "not_planned" : null, + pull_request: "isDraft" in x ? { merged_at: x.mergedAt } : undefined, + }), + ), + ); + } +} catch (e) { + console.warn(`hub: ${e.message}; the page will load the states itself`); +} +const hubLinked = new Map(hubLive.filter((i) => linked.has(i.n)).map((i) => [i.n, i])); + // --- The parity table ------------------------------------------------------------------ const status = section(readme, "Project status") ?? ""; @@ -170,7 +210,7 @@ await writeFile(join(dist, "favicon.ico"), Buffer.concat([ico, png32])); const names = {}; const rewrite = (code) => code.replace(/"\.\/(\w+\.js)"/g, (all, file) => (names[file] ? `"./${names[file]}"` : all)); // Dependencies before what imports them. -const modules = ["markdown.js", "versions.js", "chrome.js", "hardware.js", "estimate.js", "releases.js", "contributors.js", "bench.js", "main.js", "releases-page.js", "benchmarks-page.js", "docs-page.js"]; +const modules = ["markdown.js", "versions.js", "chrome.js", "hardware.js", "estimate.js", "releases.js", "contributors.js", "bench.js", "hub.js", "main.js", "releases-page.js", "benchmarks-page.js", "docs-page.js", "hub-page.js"]; for (const file of modules) { const code = rewrite(await readFile(join(site, "src", file), "utf8")); names[file] = `${file.replace(".js", "")}.${fingerprint(code)}.js`; @@ -203,7 +243,7 @@ const unavailable = `

The release notes could not be loaded here. // One top bar and phone menu for Home, Releases, Benchmarks and every Docs page. const navSections = [["/#about", "About"], ["/#screenshots", "In game"], ["/#parity", "Parity"], ["/#launcher", "Launcher"], ["/#recent", "New", "Recently added"], ["/#community", "Community"]]; -const navPages = [["/releases", "Releases"], ["/benchmarks", "Benchmarks"], ["/docs/", "Docs", "Documentation"]]; +const navPages = [["/hub", "Hub"], ["/releases", "Releases"], ["/benchmarks", "Benchmarks"], ["/docs/", "Docs", "Documentation"]]; const navLink = ([href, label, menuLabel], current, menu = false) => `${menu && menuLabel ? menuLabel : label}`; const siteNav = (current) => `

@@ -58,6 +60,23 @@

The roadmap lives in the repository: ROADMAP.md, generated from roadmap/roadmap.toml. Pull requests carry the roadmap:<id> label of their item.

+
+
+

Every open issue and pull request, placed by its state on GitHub, as on Kira's work board in Discord.

+ +
+
+{{HUB_BOARD}} +
+
+ +
+

Every release with what it changed, grouped by roadmap item in Technical, and a summary of each week. Also as journal.json.

+
+{{HUB_JOURNAL}} +
+
+

Good first tasks

diff --git a/website/src/hub.js b/website/src/hub.js index ecfb4da80..cda3b4e5b 100644 --- a/website/src/hub.js +++ b/website/src/hub.js @@ -4,6 +4,8 @@ // twice: `plain` (.hub-plain) for players and `dev` (.hub-dev) for contributors; the page's Simple / Technical // switch shows one of them. import { escape, inline } from "./markdown.js"; +import { parts, plainItem, sections } from "./releases.js"; +import { isGame, isLauncher } from "./versions.js"; export const REPO = "ludovic111/horizon"; const issueUrl = (n) => `https://github.com/${REPO}/issues/${n}`; @@ -173,3 +175,199 @@ export function helpWantedHtml(roadmap) { }) .join(""); } + +// --- The work board -------------------------------------------------------------------------------------------- + +export const COLUMNS = [ + { id: "todo", name: "To do", about: "Open and free: pick one, and say so with /claim on Discord." }, + { id: "progress", name: "In progress", about: "Claimed, assigned, or a draft pull request." }, + { id: "review", name: "In review", about: "A pull request is ready for review." }, + { id: "done", name: "Done", about: "Closed or merged in the last seven days." }, +]; +const DONE_DAYS = 7; + +// The roadmap item an issue or pull request moves: its roadmap: label, else the item linking it, else (for a +// pull request) the item linking an issue it fixes. +export function itemOf(issue, roadmap) { + const label = issue.labels.find((l) => l.startsWith("roadmap:")); + const ids = new Set(roadmap.items.map((i) => i.id)); + if (label && ids.has(label.slice(8))) return label.slice(8); + const linking = (n) => roadmap.items.find((i) => (i.links || []).includes(`#${n}`))?.id; + return linking(issue.n) || issue.fixes.map(linking).find(Boolean) || null; +} + +// The board from GitHub's open issues and pull requests and those closed lately, placed as Kira's work board places +// them: an issue goes to review when an open, ready pull request fixes it, to progress when a draft one does or it is +// claimed or assigned; a pull request that fixes no open issue is a card of its own. +export function boardFrom(list, roadmap, now = Date.now()) { + const columns = Object.fromEntries(COLUMNS.map((c) => [c.id, []])); + const open = list.filter((i) => i.state === "open"); + const openIssues = new Set(open.filter((i) => i.kind === "issue").map((i) => i.n)); + const fixing = (n) => open.filter((p) => p.kind === "pr" && p.fixes.includes(n)); + const card = (i, prs = []) => ({ n: i.n, kind: i.kind, title: i.title, user: i.user, url: i.url, item: itemOf(i, roadmap) || prs.map((p) => itemOf(p, roadmap)).find(Boolean) || null, prs: prs.map((p) => p.n) }); + for (const i of open) { + if (i.kind === "issue") { + const prs = fixing(i.n); + const claimed = i.assigned || i.labels.some((l) => /^(in progress|claimed)$/i.test(l)); + const column = prs.some((p) => !p.draft) ? "review" : prs.length || claimed ? "progress" : "todo"; + columns[column].push(card(i, prs)); + } else if (!i.fixes.some((n) => openIssues.has(n))) { + columns[i.draft ? "progress" : "review"].push(card(i)); + } + } + const since = now - DONE_DAYS * 864e5; + const seen = new Set(); + for (const i of list) { + if (seen.has(i.n) || !["merged", "closed"].includes(i.state) || !(Date.parse(i.at) >= since)) continue; + seen.add(i.n); + columns.done.push(card(i)); + } + columns.done.sort((a, b) => b.n - a.n); + return columns; +} + +const SHOWN = 20; // cards per column before "Show more" + +function cardHtml(c, roadmap, more) { + const item = c.item && roadmap.items.find((i) => i.id === c.item); + return `
  • ${c.kind === "pr" ? "PR" : "Issue"} #${c.n}${c.prs.length ? ` · ${c.prs.map((n) => `PR #${n}`).join(", ")}` : ""}${escape(c.title)}${item ? `${escape(item.title)}` : ""}${c.user ? `${escape(c.user)}` : ""}
  • `; +} + +export function boardHtml(columns, roadmap) { + return COLUMNS.map(({ id, name, about }) => { + const cards = columns[id]; + return `
    +

    ${escape(name)}${cards.length}

    +

    ${escape(about)}

    +
      ${cards.map((c, i) => cardHtml(c, roadmap, i >= SHOWN)).join("")}
    + ${cards.length > SHOWN ? `` : ""} +
    `; + }).join("\n"); +} + +// The board's roadmap filter: every item that has a card. +export function boardFilterHtml(columns, roadmap) { + const used = new Set(Object.values(columns).flat().map((c) => c.item).filter(Boolean)); + return [``, ``] + .concat(roadmap.items.filter((i) => used.has(i.id)).map((i) => ``)) + .join(""); +} + +// --- The journal ----------------------------------------------------------------------------------------------- + +export const JOURNAL_URL = "https://playhorizon.dev/hub#journal"; +const ENTRIES = 40; + +// The journal, newest first: each release with its changes grouped by roadmap item, the weekly summaries +// (roadmap/journal/), and what merged since the newest game release. releases: GitHub's release objects; list: the +// hub's issues and pull requests (their roadmap: labels place changes the roadmap doesn't link). +export function journalFrom(releases, list, roadmap) { + const prs = new Map(list.filter((i) => i.kind === "pr").map((i) => [i.n, i])); + const placed = (numbers) => { + for (const n of numbers) { + const known = prs.get(n); + const id = known ? itemOf(known, roadmap) : roadmap.items.find((i) => (i.links || []).includes(`#${n}`))?.id; + if (id) return id; + } + return null; + }; + const ours = releases.filter((r) => !r.draft && (isGame(r.tag_name) || isLauncher(r.tag_name))); + const entries = ours.map((r) => { + const changes = sections(r.body) + .filter((x) => /^(new|what's new|fixed)/i.test(x.title)) + .flatMap((x) => x.items.map((text) => ({ section: /^fixed/i.test(x.title) ? "fixed" : "new", text }))) + .map((c) => { + const numbers = [...c.text.matchAll(/#(\d+)/g)].map((m) => Number(m[1])); + return { ...c, text: plainItem(c.text), prs: numbers, item: placed(numbers) }; + }); + return { + id: r.tag_name, + kind: isLauncher(r.tag_name) ? "launcher" : "release", + date: r.published_at || "", + title: r.name || r.tag_name, + plain: parts(r).line, + url: r.html_url, + changes, + shipped: roadmap.items.filter((i) => i.status === "shipped" && i.shipped_in === r.tag_name).map((i) => i.id), + }; + }); + // Merged but in no release's notes yet: a release is cut from main a while after its last merge, so the newest + // releases' notes, not their dates, say what they hold. Pull requests players don't see (skip-release) never are. + const games = ours.filter((r) => isGame(r.tag_name)).map((r) => r.published_at).sort().reverse(); + const since = games[Math.min(4, games.length - 1)] || ""; + const noted = new Set(entries.flatMap((e) => e.changes.flatMap((c) => c.prs))); + const pending = list + .filter((i) => i.kind === "pr" && i.state === "merged" && i.at > since && !noted.has(i.n) && !i.labels.includes("skip-release")) + .sort((a, b) => b.at.localeCompare(a.at)); + if (pending.length) { + entries.push({ + id: "next-release", + kind: "merged", + date: pending[0].at, + title: "Merged, in the next release", + plain: `${pending.length} change${pending.length === 1 ? "" : "s"} merged since the last release.`, + url: `https://github.com/${REPO}/pulls?q=is%3Apr+is%3Amerged`, + changes: pending.map((p) => ({ section: "merged", text: p.title, prs: [p.n], item: itemOf(p, roadmap) })), + shipped: [], + }); + } + for (const w of roadmap.journal || []) { + // A week's summary sits after its last day's releases. + const end = new Date(Date.parse(w.date) + 7 * 864e5 - 1).toISOString(); + entries.push({ id: `week-${w.week}`, kind: "week", date: end, title: w.title, plain: w.plain, dev: w.dev, url: `${JOURNAL_URL.replace("#journal", "")}#week-${w.week}`, changes: [], shipped: [] }); + } + return entries.sort((a, b) => b.date.localeCompare(a.date)).slice(0, ENTRIES); +} + +// /hub/journal.json: the journal for Kira's #updates and posts elsewhere, with each shipped item's short text. +export function journalJson(entries, roadmap, generated = new Date().toISOString()) { + const item = (id) => { + const i = roadmap.items.find((x) => x.id === id); + return i && { id: i.id, title: i.title, plain: i.plain, post: i.post || i.plain }; + }; + return { + format: "horizon-journal", + version: 1, + generated, + url: JOURNAL_URL, + entries: entries.map((e) => ({ ...e, items: [...new Set(e.changes.map((c) => c.item).filter(Boolean))].map(item).filter(Boolean), shipped: e.shipped.map(item).filter(Boolean) })), + }; +} + +const KIND = { release: "Game", launcher: "Launcher", merged: "Merged", week: "This week" }; + +function changesHtml(entry, roadmap) { + if (!entry.changes.length) return ""; + const line = (c) => `
  • ${inline(c.text)}${c.prs.length ? ` ${c.prs.map((n) => `#${n}`).join(" ")}` : ""}
  • `; + // Simple: what is new, then how many fixes. Technical: every change, under the roadmap item it moves. + const added = entry.changes.filter((c) => c.section !== "fixed"); + const fixes = entry.changes.length - added.length; + const simple = `
    ${added.length ? `
      ${added.map((c) => `
    • ${inline(c.text)}
    • `).join("")}
    ` : ""}${fixes ? `

    ${added.length ? "And " : ""}${fixes} fix${fixes === 1 ? "" : "es"}.

    ` : ""}
    `; + const groups = new Map(); + for (const c of entry.changes) groups.set(c.item || "", [...(groups.get(c.item || "") || []), c]); + const order = [...groups.keys()].sort((a, b) => (a === "") - (b === "")); + const dev = `
    ${order + .map((id) => { + const item = roadmap.items.find((i) => i.id === id); + return `

    ${item ? `${escape(item.title)}` : "Other changes"}

      ${groups.get(id).map(line).join("")}
    `; + }) + .join("")}
    `; + return simple + dev; +} + +export function journalHtml(entries, roadmap) { + return entries + .map((e) => { + const shipped = e.shipped.map((id) => roadmap.items.find((i) => i.id === id)).filter(Boolean); + const items = [...new Set(e.changes.map((c) => c.item).filter(Boolean))].map((id) => roadmap.items.find((i) => i.id === id)).filter(Boolean); + return `
    + +

    ${e.url ? `${escape(e.title)}` : escape(e.title)}

    + ${e.kind === "week" ? `

    ${inline(e.plain)}

    ${inline(e.dev.replace(/(^|[^\w[/`])#(\d+)\b/g, (_, b, n) => `${b}[#${n}](${issueUrl(n)})`))}

    ` : ""} + ${shipped.length ? `

    Shipped: ${shipped.map((i) => `${escape(i.title)}`).join(", ")}

    ` : ""} + ${items.length ? `

    ${items.map((i) => `${escape(i.title)}`).join("")}

    ` : ""} + ${changesHtml(e, roadmap)} +
    `; + }) + .join("\n"); +} diff --git a/website/src/hub.test.mjs b/website/src/hub.test.mjs index eb9b8a087..a6337399b 100644 --- a/website/src/hub.test.mjs +++ b/website/src/hub.test.mjs @@ -1,7 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; -import { fixesIn, overviewHtml, progress, roadmapHtml, slimIssue } from "./hub.js"; +import { boardFrom, fixesIn, itemOf, journalFrom, journalHtml, journalJson, overviewHtml, progress, roadmapHtml, slimIssue } from "./hub.js"; const roadmap = JSON.parse(readFileSync(new URL("../data/roadmap.json", import.meta.url), "utf8")); @@ -53,3 +53,48 @@ test("the overview lists the focus items and never nests links", () => { for (const item of roadmap.items.filter((i) => i.focus)) assert.ok(html.includes(`href="#${item.id}"`), item.id); for (const row of html.match(/
  • [\s\S]*?<\/li>/g)) assert.equal(row.split(" { + const now = Date.parse("2030-01-10T00:00:00Z"); + const list = [ + issue(1), + issue(2), + issue(3, { assignees: [{ login: "x" }] }), + pr(10, { body: "Fixes #1" }), + pr(11, { body: "Fixes #2", draft: true }), + pr(12, { labels: [{ name: `roadmap:${roadmap.items[0].id}` }] }), + pr(13, { draft: true }), + pr(14, { state: "closed", pull_request: { merged_at: "2030-01-09T00:00:00Z" } }), + pr(15, { state: "closed", pull_request: { merged_at: "2029-12-01T00:00:00Z" } }), + ].map(slimIssue); + const board = boardFrom(list, roadmap, now); + const ids = (column) => board[column].map((c) => c.n); + assert.deepEqual(ids("todo"), []); + assert.deepEqual(ids("progress"), [2, 3, 13]); + assert.deepEqual(ids("review"), [1, 12]); + assert.deepEqual(ids("done"), [14]); + assert.deepEqual(board.review[0].prs, [10]); + assert.equal(board.review[1].item, roadmap.items[0].id); + assert.equal(itemOf(slimIssue(pr(16, { body: "Fixes #1438" })), roadmap), "end-city-banners"); +}); + +test("the journal groups a release's changes by roadmap item and lists what awaits a release", () => { + const releases = [ + { tag_name: "v0.2.2", name: "Horizon 0.2.2: Rich presence", published_at: "2030-01-02T00:00:00Z", html_url: "u2", body: "### New\n- Discord Rich Presence (#1787)\n\n### Fixed\n- A fix (#5, fixes #4)\n" }, + { tag_name: "launcher@0.2.1", name: "Horizon launcher 0.2.1", published_at: "2030-01-01T00:00:00Z", html_url: "u1", body: "### Fixed\n- Window (#6)\n" }, + ]; + const list = [ + pr(1788, { state: "closed", pull_request: { merged_at: "2030-01-03T00:00:00Z" } }), + pr(7, { state: "closed", pull_request: { merged_at: "2030-01-03T00:00:00Z" }, labels: [{ name: "skip-release" }] }), + ].map(slimIssue); + const entries = journalFrom(releases, list, { ...roadmap, journal: [] }); + assert.deepEqual(entries.map((e) => e.id), ["next-release", "v0.2.2", "launcher@0.2.1"]); + assert.deepEqual(entries[0].changes.map((c) => [c.prs, c.item]), [[[1788], "discord-presence"]]); + assert.deepEqual(entries[1].changes.map((c) => [c.section, c.text, c.item]), [["new", "Discord Rich Presence", "discord-presence"], ["fixed", "A fix", null]]); + const json = journalJson(entries, roadmap, "now"); + assert.equal(json.format, "horizon-journal"); + assert.equal(json.entries[1].items[0].post.length <= 240, true); + const html = journalHtml(entries, roadmap); + assert.ok(html.includes('href="#item-discord-presence"')); + assert.ok(html.includes("And 1 fix.")); +}); diff --git a/website/src/style.css b/website/src/style.css index 4ec688812..f32e24a30 100644 --- a/website/src/style.css +++ b/website/src/style.css @@ -783,7 +783,46 @@ code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--ou .hub-rules li + li { margin-top: 10px; } .hub-rules li::marker { color: var(--muted); font-family: var(--mono); } .hub-source { margin-top: 40px; max-width: var(--measure); } +.hub-board-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px 24px; } +.hub-board-head .hub-intro { margin-bottom: 0; } +.hub-select { display: inline-flex; align-items: center; gap: 10px; } +.hub-select select { + height: 32px; max-width: 22rem; padding: 0 10px; font: var(--text-label) / 1 var(--font); color: var(--ink); + background: var(--well); border: 0; box-shadow: 0 0 0 var(--block-outline) var(--outline); +} +.hub-board { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; margin-top: 24px; align-items: start; } +.hub-column { padding: 14px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); } +.hub-column h3 { display: flex; justify-content: space-between; align-items: baseline; font-size: var(--text-heading); } +.hub-count { font: var(--text-micro) / 1 var(--mono); color: var(--muted); } +.hub-column > .meta { margin: 6px 0 12px; } +.hub-cards-list { display: grid; gap: 6px; } +.js .hub-column:not(.is-open) .hub-card[data-more] { display: none; } +.hub-card a { display: grid; gap: 4px; padding: 10px 12px; background: var(--well); box-shadow: 0 0 0 var(--block-outline) var(--outline); color: var(--ink); } +.hub-card a:hover { box-shadow: 0 0 0 var(--block-outline) var(--accent); } +.hub-card-ref, .hub-card-meta { font: var(--text-micro) / 1.4 var(--mono); letter-spacing: var(--text-micro-tracking); color: var(--muted); } +.hub-card-title { font-size: var(--text-label); line-height: 1.4; overflow-wrap: anywhere; } +.hub-card-meta { display: flex; flex-wrap: wrap; gap: 4px 10px; } +.hub-card-item { color: var(--accent); } +.hub-more { margin-top: 10px; width: 100%; justify-content: center; } +.hub-journal { display: grid; gap: 8px; margin-top: 24px; max-width: 56rem; } +.hub-entry { display: grid; gap: 10px; padding: 18px 20px; background: var(--panel); border: var(--block-outline) solid var(--outline); box-shadow: var(--panel-edges); scroll-margin-top: calc(var(--nav) + 24px); } +.hub-entry-week { background: color-mix(in srgb, var(--accent) 8%, var(--panel)); } +.hub-entry-meta { display: flex; align-items: center; gap: 10px; font: var(--text-micro) / 1 var(--mono); color: var(--muted); } +.hub-entry-meta .badge { margin-right: 0; } +.hub-entry-title { font-size: var(--text-heading); line-height: var(--text-heading-line); } +.hub-entry-title a { color: var(--ink); } +.hub-entry-title a:hover { color: var(--accent); } +.hub-entry .hub-plain, .hub-entry .hub-dev { font-size: var(--text-ui); color: var(--ink-soft); } +.hub-entry-items { display: flex; flex-wrap: wrap; gap: 6px; } +.hub-shipped { font-size: var(--text-ui); color: var(--ink); } +.hub-changes { list-style: square; padding-left: 18px; font-size: var(--text-ui); color: var(--ink-soft); } +.hub-changes li + li { margin-top: 4px; } +.hub-ref { font: var(--text-micro) / 1 var(--mono); } +.hub-group { margin-top: 8px; font: 500 var(--text-label) / 1.4 var(--font); } +.hub-group:first-child { margin-top: 0; } +@media (max-width: 1100px) { .hub-board { grid-template-columns: repeat(2, minmax(0, 1fr)); } } @media (max-width: 720px) { + .hub-board { grid-template-columns: minmax(0, 1fr); } .hub-rows .row > a { grid-template-columns: var(--index) minmax(0, 1fr); } .hub-rows .row-meta { grid-column: 2; text-align: left; } } From e458e3724924360dfad1252358368ff090cc4dae Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:02:36 +0100 Subject: [PATCH 13/23] Hub: journal.json in the flat format Kira reads, at /data/journal.json One entry per merged pull request (with its roadmap item), game or launcher release, shipped roadmap item (post and announce) and weekly summary, newest first, ids stable forever: the feed kira's src/journal.js posts to #updates and X. The journal's item links are hub#; the board's and the journal's ids are reserved too, and the page-wide unique-id test covers every tab. Co-Authored-By: Claude Opus 5.5 --- roadmap/README.md | 36 ++++++++++++------ tools/roadmap.py | 2 +- website/README.md | 2 +- website/build.mjs | 2 +- website/src/hub.html | 2 +- website/src/hub.js | 79 ++++++++++++++++++++++++++++++++-------- website/src/hub.test.mjs | 51 +++++++++++++++++++++++--- 7 files changed, 136 insertions(+), 38 deletions(-) diff --git a/roadmap/README.md b/roadmap/README.md index f16e83f8c..55cf9d09f 100644 --- a/roadmap/README.md +++ b/roadmap/README.md @@ -53,7 +53,7 @@ Whoever moves the work (the orchestrator on each heartbeat, or anyone in their p 5. Once a week, write the week's summary in `roadmap/journal/-.md` (for example `2026-43.md`): `# Title`, a paragraph or two for players, then `## Technical` and the same week for contributors, with its pull requests. `build` puts it into website/data/roadmap.json; the hub's Journal tab - shows it among the releases, and `/hub/journal.json` carries it to Kira's #updates and to posts elsewhere. + shows it among the releases, and `/data/journal.json` carries it to Kira's #updates and to X. 6. Suggestions from the website and Discord are read and triaged by the maintainers. A good one becomes an item in a normal pull request; none is published automatically. @@ -62,18 +62,30 @@ or when the file breaks a rule; `python3 tools/roadmap.py check --offline` runs ## The journal -The hub's Journal tab and `https://playhorizon.dev/hub/journal.json` are built with each deploy of the website -(`website/src/hub.js`, `journalFrom`): every game and launcher release with its notes' changes, each placed under -the roadmap item it moves (the pull request's `roadmap:` label, else the item that links it); the merged pull -requests no release has yet; and the weekly summaries above. Its JSON, newest first: +The hub's Journal tab and `https://playhorizon.dev/data/journal.json` are built with each deploy of the website +(`website/src/hub.js`). The tab shows every game and launcher release with its notes' changes, each placed under +the roadmap item it moves (the pull request's `roadmap:` label, else the item that links it), the merged pull +requests no release has yet, and the weekly summaries above. + +`journal.json` is what Kira reads for `#updates` and its X posts (kira's `src/journal.js`): one flat entry per +merged pull request, release, shipped item and weekly summary, newest first, the latest 300. ```json -{ "format": "horizon-journal", "version": 1, "generated": "…", "url": "https://playhorizon.dev/hub#journal", - "entries": [ { "id": "v0.2.57", "kind": "release | launcher | merged | week", "date": "…", "title": "…", - "plain": "one line for players", "url": "…", "dev": "weeks only", - "changes": [ { "section": "new | fixed | merged", "text": "…", "prs": [1787], "item": "discord-presence" } ], - "items": [ { "id", "title", "plain", "post" } ], // roadmap items the entry moved - "shipped": [ { "id", "title", "plain", "post" } ] } ] } // items that shipped in this release +{ "format": "horizon-journal", "version": 2, "generated": "…", "url": "https://playhorizon.dev/hub#journal", + "entries": [ + { "id": "pr-1788", "kind": "merge", "date": "…", "title": "the pull request's title", "url": "…", + "number": 1788, "item": "discord-presence", "item_title": "Discord Rich Presence" }, + { "id": "release-v0.2.57", "kind": "release", "date": "…", "title": "…", "plain": "one line", "url": "…", + "tag": "v0.2.57" }, + { "id": "shipped-server-resource-packs", "kind": "shipped", "date": "the release's", "title": "…", + "plain": "…", "url": "https://playhorizon.dev/hub#server-resource-packs", "item": "…", "item_title": "…", + "shipped_in": "v0.2.48", "post": "at most 240 characters", "announce": false }, + { "id": "weekly-2026-43", "kind": "weekly", "date": "the week's last second", "title": "…", "plain": "…", + "dev": "…", "url": "https://playhorizon.dev/hub#week-2026-43" } ] } ``` -`post` is at most 240 characters, ready to announce as is. Readers should remember the ids they have posted. +- An `id` never changes: readers post each one once. `merge` entries are the pull requests players see (no + `skip-release` label), plus any that moves a roadmap item; `item` is absent when none does. +- `announce: true` (the item's `announce` key) asks Kira to post the shipped item on X too, with `post`. +- `https://playhorizon.dev/data/roadmap.json` is `roadmap.toml` as JSON (`areas`, `items` with every key above, + `overview`, the weekly summaries); an item's page is `https://playhorizon.dev/hub#`. diff --git a/tools/roadmap.py b/tools/roadmap.py index ab0147e70..fe97285ff 100644 --- a/tools/roadmap.py +++ b/tools/roadmap.py @@ -57,7 +57,7 @@ ISSUE = re.compile(r"#(\d+)$") ID = re.compile(r"[a-z0-9]+(-[a-z0-9]+)*$") # An item is the anchor playhorizon.dev/hub#: it can't take the name of a tab, a section or a heading. RESERVED = {"main", "overview", "roadmap", "board", "journal", "contribute", "hub-data", *STATUSES} -RESERVED_PREFIXES = ("h-", "tab-", "week-") +RESERVED_PREFIXES = ("h-", "tab-", "col-", "week-", "journal-") RELEASE = re.compile(r"(v\d[\w.]*|launcher@\d[\w.]*|launcher-v\d[\w.]*|website)$") MONTHS = ("January|February|March|April|June|July|August|September|October|November|December") # Kira's rule: no dates and no promises of when. "Coming soon" is the one allowed phrase. diff --git a/website/README.md b/website/README.md index 56fa515b9..d17bd0cd1 100644 --- a/website/README.md +++ b/website/README.md @@ -40,7 +40,7 @@ src/estimate.js estimates for unmeasured hardware from the nearest measured m src/markdown.js a small Markdown renderer (escapes everything), shared by build and page src/releases.js the home page's "Recently added" and the Releases page's markup, shared by build and page src/contributors.js the contributors' filtering and markup, shared by build and page -src/hub.js the hub's roadmap, board and journal from data/roadmap.json, GitHub's issues and the releases, shared by build and page; /hub/journal.json +src/hub.js the hub's roadmap, board and journal from data/roadmap.json, GitHub's issues and the releases, shared by build and page; /data/journal.json src/hub-page.js the hub page: tabs by #hash, the Simple / Technical switch (localStorage), the area filter, live states data/roadmap.json the roadmap, generated by tools/roadmap.py from roadmap/roadmap.toml (do not edit); served at /data/roadmap.json public/ fonts, screenshots, icons, og.png, robots.txt, benchmarks.json: copied as is (sitemap.xml is written by the build) diff --git a/website/build.mjs b/website/build.mjs index 17768e5fc..c3203891e 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -437,7 +437,7 @@ for (const { file, values: own } of docPages) { await mkdir(join(dist, "data"), { recursive: true }); await cp(join(site, "data", "roadmap.json"), join(dist, "data", "roadmap.json")); // The journal for Kira's #updates and its X posts: /data/journal.json, rebuilt with every deploy. -await writeFile(join(dist, "data", "journal.json"), JSON.stringify(journalJson(journal, roadmap), null, 1) + "\n"); +await writeFile(join(dist, "data", "journal.json"), JSON.stringify(journalJson(releases, hubLive, roadmap), null, 1) + "\n"); // The pages' inline scripts (they mark the page as scripted and apply the saved theme before CSS // applies) and the inlined stylesheet: the Content-Security-Policy in the Caddyfile allows them by hash. diff --git a/website/src/hub.html b/website/src/hub.html index a6e146080..d4ba4600c 100644 --- a/website/src/hub.html +++ b/website/src/hub.html @@ -71,7 +71,7 @@
  • -

    Every release with what it changed, grouped by roadmap item in Technical, and a summary of each week. Also as journal.json.

    +

    Every release with what it changed, grouped by roadmap item in Technical, and a summary of each week. Also as journal.json.

    {{HUB_JOURNAL}}
    diff --git a/website/src/hub.js b/website/src/hub.js index cda3b4e5b..d293b7250 100644 --- a/website/src/hub.js +++ b/website/src/hub.js @@ -319,19 +319,66 @@ export function journalFrom(releases, list, roadmap) { return entries.sort((a, b) => b.date.localeCompare(a.date)).slice(0, ENTRIES); } -// /hub/journal.json: the journal for Kira's #updates and posts elsewhere, with each shipped item's short text. -export function journalJson(entries, roadmap, generated = new Date().toISOString()) { - const item = (id) => { - const i = roadmap.items.find((x) => x.id === id); - return i && { id: i.id, title: i.title, plain: i.plain, post: i.post || i.plain }; - }; - return { - format: "horizon-journal", - version: 1, - generated, - url: JOURNAL_URL, - entries: entries.map((e) => ({ ...e, items: [...new Set(e.changes.map((c) => c.item).filter(Boolean))].map(item).filter(Boolean), shipped: e.shipped.map(item).filter(Boolean) })), - }; +const HUB = "https://playhorizon.dev/hub"; +const FEED = 300; + +// /data/journal.json, which Kira reads for #updates and X (kira's src/journal.js): one flat entry per merged pull +// request, release, shipped roadmap item and weekly summary, newest first. An entry's id never changes: Kira posts +// each id once. Shipped items carry `post` (at most 240 characters, tools/roadmap.py checks) and `announce`. +export function journalJson(releases, list, roadmap, generated = new Date().toISOString()) { + const items = new Map(roadmap.items.map((i) => [i.id, i])); + const ours = releases.filter((r) => !r.draft && (isGame(r.tag_name) || isLauncher(r.tag_name))); + const published = new Map(ours.map((r) => [r.tag_name, r.published_at || ""])); + const merges = list + .filter((i) => i.kind === "pr" && i.state === "merged") + .map((pr) => ({ pr, item: itemOf(pr, roadmap) })) + // What players see, and anything that moves a roadmap item. + .filter(({ pr, item }) => item || !pr.labels.includes("skip-release")) + .map(({ pr, item }) => ({ + id: `pr-${pr.n}`, + kind: "merge", + date: pr.at, + title: pr.title, + url: pr.url, + number: pr.n, + ...(item ? { item, item_title: items.get(item)?.title } : {}), + })); + const released = ours.map((r) => ({ + id: `release-${r.tag_name}`, + kind: "release", + date: r.published_at || "", + title: r.name || r.tag_name, + plain: parts(r).line, + url: r.html_url, + tag: r.tag_name, + })); + const shipped = roadmap.items + .filter((i) => i.status === "shipped") + .map((i) => ({ + id: `shipped-${i.id}`, + kind: "shipped", + date: published.get(i.shipped_in) || generated, + title: i.title, + plain: i.plain, + url: `${HUB}#${i.id}`, + item: i.id, + item_title: i.title, + shipped_in: i.shipped_in, + post: i.post || i.plain, + announce: Boolean(i.announce), + })); + // A week's summary is dated at the end of its week, after that week's releases. + const weekly = (roadmap.journal || []).map((w) => ({ + id: `weekly-${w.week}`, + kind: "weekly", + date: new Date(Date.parse(w.date) + 7 * 864e5 - 1000).toISOString(), + title: w.title, + plain: w.plain, + dev: w.dev, + url: `${HUB}#week-${w.week}`, + })); + const entries = [...merges, ...released, ...shipped, ...weekly].sort((a, b) => b.date.localeCompare(a.date) || a.id.localeCompare(b.id)); + return { format: "horizon-journal", version: 2, generated, url: `${HUB}#journal`, entries: entries.slice(0, FEED) }; } const KIND = { release: "Game", launcher: "Launcher", merged: "Merged", week: "This week" }; @@ -349,7 +396,7 @@ function changesHtml(entry, roadmap) { const dev = `
    ${order .map((id) => { const item = roadmap.items.find((i) => i.id === id); - return `

    ${item ? `${escape(item.title)}` : "Other changes"}

      ${groups.get(id).map(line).join("")}
    `; + return `

    ${item ? `${escape(item.title)}` : "Other changes"}

      ${groups.get(id).map(line).join("")}
    `; }) .join("")}
    `; return simple + dev; @@ -364,8 +411,8 @@ export function journalHtml(entries, roadmap) {

    ${e.url ? `${escape(e.title)}` : escape(e.title)}

    ${e.kind === "week" ? `

    ${inline(e.plain)}

    ${inline(e.dev.replace(/(^|[^\w[/`])#(\d+)\b/g, (_, b, n) => `${b}[#${n}](${issueUrl(n)})`))}

    ` : ""} - ${shipped.length ? `

    Shipped: ${shipped.map((i) => `${escape(i.title)}`).join(", ")}

    ` : ""} - ${items.length ? `

    ${items.map((i) => `${escape(i.title)}`).join("")}

    ` : ""} + ${shipped.length ? `

    Shipped: ${shipped.map((i) => `${escape(i.title)}`).join(", ")}

    ` : ""} + ${items.length ? `

    ${items.map((i) => `${escape(i.title)}`).join("")}

    ` : ""} ${changesHtml(e, roadmap)} `; }) diff --git a/website/src/hub.test.mjs b/website/src/hub.test.mjs index a6337399b..d688489e9 100644 --- a/website/src/hub.test.mjs +++ b/website/src/hub.test.mjs @@ -1,7 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; -import { boardFrom, fixesIn, itemOf, journalFrom, journalHtml, journalJson, overviewHtml, progress, roadmapHtml, slimIssue } from "./hub.js"; +import { boardFrom, boardHtml, fixesIn, itemOf, journalFrom, journalHtml, journalJson, overviewHtml, progress, roadmapHtml, slimIssue } from "./hub.js"; const roadmap = JSON.parse(readFileSync(new URL("../data/roadmap.json", import.meta.url), "utf8")); @@ -42,7 +42,11 @@ test("the roadmap renders every item once, with both texts, in its status's sect }); test("an item is its own anchor (hub#, as Kira links it) and takes no other id of the page", () => { - const page = readFileSync(new URL("./hub.html", import.meta.url), "utf8") + roadmapHtml(roadmap) + overviewHtml(roadmap); + const week = { week: "2030-01", date: "2029-12-31", title: "A week", plain: "p", dev: "d" }; + const release = { tag_name: "v0.2.2", name: "0.2.2", published_at: "2030-01-02T00:00:00Z", html_url: "u", body: "" }; + const journal = journalHtml(journalFrom([release], [], { ...roadmap, journal: [week] }), roadmap); + const board = boardHtml(boardFrom([], roadmap), roadmap); + const page = readFileSync(new URL("./hub.html", import.meta.url), "utf8") + roadmapHtml(roadmap) + overviewHtml(roadmap) + board + journal; const ids = [...page.matchAll(/ id="([^"]+)"/g)].map((m) => m[1]); assert.deepEqual(ids.filter((id, i) => ids.indexOf(id) !== i), []); for (const item of roadmap.items) assert.ok(ids.includes(item.id), item.id); @@ -91,10 +95,45 @@ test("the journal groups a release's changes by roadmap item and lists what awai assert.deepEqual(entries.map((e) => e.id), ["next-release", "v0.2.2", "launcher@0.2.1"]); assert.deepEqual(entries[0].changes.map((c) => [c.prs, c.item]), [[[1788], "discord-presence"]]); assert.deepEqual(entries[1].changes.map((c) => [c.section, c.text, c.item]), [["new", "Discord Rich Presence", "discord-presence"], ["fixed", "A fix", null]]); - const json = journalJson(entries, roadmap, "now"); - assert.equal(json.format, "horizon-journal"); - assert.equal(json.entries[1].items[0].post.length <= 240, true); const html = journalHtml(entries, roadmap); - assert.ok(html.includes('href="#item-discord-presence"')); + assert.ok(html.includes('href="#discord-presence"')); assert.ok(html.includes("And 1 fix.")); }); + +test("journal.json is the flat feed Kira reads: merges, releases, shipped items, weeks, ids that never change", () => { + const releases = [ + { tag_name: "v0.2.48", name: "Horizon 0.2.48", published_at: "2030-01-02T00:00:00Z", html_url: "https://github.com/ludovic111/horizon/releases/tag/v0.2.48", body: "### New\n- Packs (#1)\n" }, + { tag_name: "nightly-1", name: "Nightly", published_at: "2030-01-03T00:00:00Z", html_url: "u", body: "" }, + ]; + const list = [ + pr(1788, { state: "closed", pull_request: { merged_at: "2030-01-04T00:00:00Z" }, html_url: "https://github.com/ludovic111/horizon/pull/1788" }), + pr(7, { state: "closed", pull_request: { merged_at: "2030-01-04T00:00:00Z" }, labels: [{ name: "skip-release" }] }), + pr(8, { state: "closed", pull_request: { merged_at: "2030-01-04T00:00:00Z" }, labels: [{ name: "skip-release" }, { name: "roadmap:lean-code" }] }), + pr(9), + ].map(slimIssue); + const week = { week: "2030-01", date: "2029-12-31", title: "A week", plain: "p", dev: "d" }; + const feed = journalJson(releases, list, { ...roadmap, journal: [week] }, "2030-01-05T00:00:00Z"); + const byId = new Map(feed.entries.map((e) => [e.id, e])); + // A merged pull request, with its roadmap item; skip-release ones only when they move an item; open ones never. + assert.deepEqual(byId.get("pr-1788"), { id: "pr-1788", kind: "merge", date: "2030-01-04T00:00:00Z", title: "PR 1788", url: "https://github.com/ludovic111/horizon/pull/1788", number: 1788, item: "discord-presence", item_title: "Discord Rich Presence" }); + assert.ok(!byId.has("pr-7") && byId.get("pr-8").item === "lean-code" && !byId.has("pr-9")); + // Game and launcher releases only. + assert.equal(byId.get("release-v0.2.48").tag, "v0.2.48"); + assert.ok(!byId.has("release-nightly-1")); + // Every shipped item, dated by its release when the feed has it, with its post and the announce flag. + const shipped = roadmap.items.filter((i) => i.status === "shipped"); + for (const item of shipped) { + const e = byId.get(`shipped-${item.id}`); + assert.equal(e.kind, "shipped"); + assert.equal(e.url, `https://playhorizon.dev/hub#${item.id}`); + assert.ok(e.post.length <= 240 && typeof e.announce === "boolean", item.id); + } + assert.equal(byId.get("shipped-server-resource-packs").date, "2030-01-02T00:00:00Z"); + assert.equal(byId.get("weekly-2030-01").date, "2030-01-06T23:59:59.000Z"); + // Newest first; every entry has what Kira needs, and links only where Kira shows them. + assert.deepEqual(feed.entries.map((e) => e.date), feed.entries.map((e) => e.date).sort().reverse()); + for (const e of feed.entries) { + assert.ok(e.id && ["merge", "release", "weekly", "shipped"].includes(e.kind) && e.date && e.title, e.id); + assert.match(e.url, /^https:\/\/(github\.com|playhorizon\.dev)\//, e.id); + } +}); From 91148cdf74b18741253bfcc20313c0f239a4c3b6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:09:48 +0100 Subject: [PATCH 14/23] Telemetry server: hub votes allow 600 an hour per address (bursts of 60) A visitor voting down the roadmap, or a school behind one address, ran out of the 12-request burst. Votes are cheap; the item cap and the voter id still bound them. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-telemetry-server/README.md | 2 +- crates/horizon-telemetry-server/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/horizon-telemetry-server/README.md b/crates/horizon-telemetry-server/README.md index 2b86bf99d..69095be73 100644 --- a/crates/horizon-telemetry-server/README.md +++ b/crates/horizon-telemetry-server/README.md @@ -77,7 +77,7 @@ All are environment variables: - `HORIZON_TELEMETRY_LIVE_PER_HOUR` per address, pings and reads (600, bursts of 60: ten players behind one address) - `HORIZON_TELEMETRY_LIVE_WINDOW_SECONDS` (120) - `HORIZON_TELEMETRY_LIVE_MAX_SESSIONS` (200 000) -- `HORIZON_TELEMETRY_HUB_PER_HOUR` votes and vote reads per address (120, bursts of 12) +- `HORIZON_TELEMETRY_HUB_PER_HOUR` votes and vote reads per address (600, bursts of 60: a page load is one read, and several players can share an address) ## Hosting diff --git a/crates/horizon-telemetry-server/src/lib.rs b/crates/horizon-telemetry-server/src/lib.rs index 19ba3e1dc..9c273727c 100644 --- a/crates/horizon-telemetry-server/src/lib.rs +++ b/crates/horizon-telemetry-server/src/lib.rs @@ -75,7 +75,7 @@ impl Default for Config { live_per_hour: 600.0, live_window: horizon_telemetry::live::WINDOW, live_max_sessions: 200_000, - hub_per_hour: 120.0, + hub_per_hour: 600.0, } } } From bac51e3fba6922c0a10eb4105cfc68886d6ae573 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:55:50 +0100 Subject: [PATCH 15/23] Telemetry server: the hub's bug reports and suggestions POST /hub/report opens a GitHub issue at once (labels bug and from-website, the every template field required, people's text made inert (no mentions, issue references, HTML or closing keywords) and the same report twice answered with the first issue. If GitHub fails it answers 202 and the upkeep tries again for a week. Off (503) without HORIZON_TELEMETRY_GITHUB_TOKEN. POST /hub/suggest queues a suggestion; GET /hub/suggestions?after= hands the queue to Kira with the HORIZON_TELEMETRY_HUB_TOKEN bearer (404 when unset, 401 for a wrong token). Nothing is published. Per-address limits (20 an hour, bursts of 2) on keyed hashes of the address, daily caps from everyone (30 reports, 200 suggestions), a honeypot field, entries kept 90 days. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-telemetry-server/Cargo.lock | 52 +++ crates/horizon-telemetry-server/Cargo.toml | 2 + crates/horizon-telemetry-server/README.md | 18 +- crates/horizon-telemetry-server/src/github.rs | 128 ++++++ crates/horizon-telemetry-server/src/hub.rs | 13 +- crates/horizon-telemetry-server/src/intake.rs | 370 ++++++++++++++++++ crates/horizon-telemetry-server/src/lib.rs | 80 +++- crates/horizon-telemetry-server/src/main.rs | 3 + crates/horizon-telemetry-server/src/store.rs | 1 + .../horizon-telemetry-server/tests/github.rs | 41 ++ crates/horizon-telemetry-server/tests/hub.rs | 304 +++++++++++++- 11 files changed, 990 insertions(+), 22 deletions(-) create mode 100644 crates/horizon-telemetry-server/src/github.rs create mode 100644 crates/horizon-telemetry-server/src/intake.rs create mode 100644 crates/horizon-telemetry-server/tests/github.rs diff --git a/crates/horizon-telemetry-server/Cargo.lock b/crates/horizon-telemetry-server/Cargo.lock index e4e7d060e..9b5fc960d 100644 --- a/crates/horizon-telemetry-server/Cargo.lock +++ b/crates/horizon-telemetry-server/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "atomic-waker" version = "1.1.2" @@ -92,6 +98,15 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -131,6 +146,17 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "foldhash" version = "0.1.5" @@ -235,6 +261,7 @@ dependencies = [ "serde_json", "tokio", "tower", + "ureq", ] [[package]] @@ -473,6 +500,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.4" @@ -701,6 +738,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "slab" version = "0.4.12" @@ -851,10 +894,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d" dependencies = [ "base64", + "flate2", "log", "once_cell", "rustls", "rustls-pki-types", + "serde", + "serde_json", "url", "webpki-roots 0.26.11", ] @@ -1099,6 +1145,12 @@ dependencies = [ "syn", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/crates/horizon-telemetry-server/Cargo.toml b/crates/horizon-telemetry-server/Cargo.toml index 8dbb0b7fd..486648b5f 100644 --- a/crates/horizon-telemetry-server/Cargo.toml +++ b/crates/horizon-telemetry-server/Cargo.toml @@ -19,6 +19,8 @@ rusqlite = { version = "0.37", features = ["bundled"] } serde = { version = "1", features = ["derive"] } serde_json = "1" ruzstd = "0.9" +# Opens the hub's bug reports as GitHub issues (blocking, run off the async workers; rustls). +ureq = { version = "2.12", features = ["json"] } [dev-dependencies] # The uploader the launcher uses, against this server, end to end. diff --git a/crates/horizon-telemetry-server/README.md b/crates/horizon-telemetry-server/README.md index 69095be73..a401a72b0 100644 --- a/crates/horizon-telemetry-server/README.md +++ b/crates/horizon-telemetry-server/README.md @@ -1,6 +1,6 @@ # horizon-telemetry-server -This server receives what players choose to send (performance summaries, crash and bug reports, benchmark uploads: [docs/telemetry.md](../../docs/telemetry.md)) and stores it in one SQLite file. It serves anonymous totals to the website. It also keeps the live player count from the games' anonymous "I'm playing" pings, in memory only, and the 👍 players give roadmap items on the hub (playhorizon.dev/hub). It is one small Rust process, about 7 MB of memory when idle. +This server receives what players choose to send (performance summaries, crash and bug reports, benchmark uploads: [docs/telemetry.md](../../docs/telemetry.md)) and stores it in one SQLite file. It serves anonymous totals to the website. It also keeps the live player count from the games' anonymous "I'm playing" pings, in memory only, and takes what players send from the hub (playhorizon.dev/hub): votes, bug reports and suggestions. It is one small Rust process, about 7 MB of memory when idle. cargo run --release # in this folder: its own workspace, like the launcher's PORT=8080 HORIZON_TELEMETRY_DB=/data/telemetry.sqlite3 horizon-telemetry-server @@ -17,10 +17,15 @@ It runs at **https://telemetry.playhorizon.dev** (`DEFAULT_ENDPOINT` in `crates/ | `GET /v1/benchmarks/summary` | Players' benchmark uploads grouped by GPU, CPU, render distance and game, for the website's Benchmarks page (below). Cached 10 minutes, same `Access-Control-Allow-Origin`. | | `POST /v1/live` | A game's "I'm playing" ping (JSON, at most 512 bytes). Returns 204. Returns 400 for a bad ping, 413 for one too large, 429 over the address's limit, 503 when it holds `LIVE_MAX_SESSIONS` already. | | `GET /v1/live` | How many play now, rounded: `playing`, `lan`, `versions`, `platforms`. Made again at most every 15 seconds, with the same `Access-Control-Allow-Origin`. | -| `POST /hub/vote` | `{"item": "", "voter": "", "up": true}`: a 👍 on a roadmap item, one per voter; `"up": false` takes it back. Returns `{"item", "votes"}`. 400 for a bad id, 429 over the address's limit. `OPTIONS` answers the website's preflight. | +| `POST /hub/vote` | `{"item": "", "voter": "", "up": true}`: a 👍 on a roadmap item, one per voter; `"up": false` takes it back. Returns `{"item", "votes"}`. 400 for a bad id, 429 over the address's limit. | | `GET /hub/votes` | `{"votes": {"": n}}`. Made again at most every minute. | +| `POST /hub/report` | A bug report from the hub's form: `{"title", "did", "happened", "expected", "version"?, "system", "name"?}`. Opens a GitHub issue at once (labels `bug` and `from-website`, the `#horizon-bugs` template, "Reported on playhorizon.dev") and returns 201 `{"id", "issue": ""}`. If GitHub fails: 202 `{"id", "issue": null}`, and the upkeep tries again for a week. The same report twice in a day returns the first one's issue. 400 for an empty or too long field, 429 over the address's limit, 503 past the day's cap or without `GITHUB_TOKEN`. | +| `POST /hub/suggest` | `{"text", "item"?, "name"?}` into the suggestion queue. Returns 202 `{"id"}`. Never published: Kira relays it to the maintainers' private channel. | +| `GET /hub/suggestions?after=&limit=100` | The queue, oldest first, for Kira: `{"suggestions": [{"id", "text", "item"?, "name"?, "created_at"}]}`. Needs `Authorization: Bearer `: 401 without it, 404 when the server has none. | | `GET /healthz` | `ok` | +The hub's posts take JSON from the website (`OPTIONS` preflights answer with its origin). A form's hidden `website` field filled in (a bot) gets 202 and is dropped. + The totals are grouped per version, OS, GPU vendor and render distance. Each group has its sessions, install-days, hours played, the 14 frame-time buckets summed, and the mean p50 and p99 frame times. Groups with fewer than 5 install-days are left out. The totals also list crash counts per version. Benchmark uploads are published only through the summary below, never one by one. ## Benchmarks summary @@ -58,7 +63,7 @@ The live count is a table in memory: a session ID, when it last pinged, its vers The day stored is the day the server received an item. The sender's IP address is never written down. The per-address rate limit keeps addresses in memory for an hour at most. -A hub vote is stored as an item ID and the browser's random ID. The hub's rate limits key their buckets by a hash of the address with a key drawn at each start, in memory. +The hub keeps votes as an item ID and the browser's random ID, and reports and suggestions as their text, for `HORIZON_TELEMETRY_HUB_KEEP_DAYS` (90). Its rate limits key their buckets by a hash of the address with a key drawn at each start, in memory. Raw rows are deleted after `HORIZON_TELEMETRY_RETENTION_DAYS` (180). The daily totals stay; they hold no install ID. @@ -78,6 +83,13 @@ All are environment variables: - `HORIZON_TELEMETRY_LIVE_WINDOW_SECONDS` (120) - `HORIZON_TELEMETRY_LIVE_MAX_SESSIONS` (200 000) - `HORIZON_TELEMETRY_HUB_PER_HOUR` votes and vote reads per address (600, bursts of 60: a page load is one read, and several players can share an address) +- `HORIZON_TELEMETRY_HUB_POSTS_PER_HOUR` reports and suggestions per address (20, bursts of 2) +- `HORIZON_TELEMETRY_HUB_REPORTS_PER_DAY` from everyone (30): each opens an issue +- `HORIZON_TELEMETRY_HUB_SUGGESTIONS_PER_DAY` from everyone (200) +- `HORIZON_TELEMETRY_HUB_KEEP_DAYS` (90) +- `HORIZON_TELEMETRY_HUB_TOKEN`: the token Kira reads the suggestions with (unset: `GET /hub/suggestions` is off) +- `HORIZON_TELEMETRY_GITHUB_TOKEN`: a fine-grained token with Issues read and write on the repository only (unset: `POST /hub/report` answers 503 and the form points to GitHub and Discord) +- `HORIZON_TELEMETRY_GITHUB_REPO` (`ludovic111/horizon`) ## Hosting diff --git a/crates/horizon-telemetry-server/src/github.rs b/crates/horizon-telemetry-server/src/github.rs new file mode 100644 index 000000000..a800442e7 --- /dev/null +++ b/crates/horizon-telemetry-server/src/github.rs @@ -0,0 +1,128 @@ +//! A website bug report as a GitHub issue: the text made inert (no mentions, no cross-references, no HTML), +//! written as the template Kira's `/report` and `#horizon-bugs` use, and the call that opens it. +use std::time::Duration; + +use serde_json::{Map, Value, json}; + +/// Opens an issue; its URL, or why not. The server's is [`Filer::github`]; tests give their own. +pub type Filer = dyn Fn(&Issue) -> Result + Send + Sync; + +pub struct Issue { + pub title: String, + pub body: String, + pub labels: Vec, +} + +/// Labels every website report gets. +pub const LABELS: [&str; 2] = ["bug", "from-website"]; + +/// Text people wrote, safe in an issue: no HTML, no `@` mentions, no `#12` or issue-URL cross-references, +/// no closing keywords, no code spans to break out of. The same rules as Kira's `neutralise`. +pub fn neutralise(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let chars: Vec = text.chars().collect(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + let next = chars.get(i + 1).copied(); + let word_start = i == 0 || !chars[i - 1].is_alphanumeric(); + match c { + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '`' => out.push('\''), + // A zero-width space after `@` or `#` keeps the text and drops the mention or the link. + '@' | '#' if next.is_some_and(|n| n.is_alphanumeric()) => { + out.push(c); + out.push('\u{200b}'); + } + _ if word_start && closing_keyword(&chars[i..]) => { + out.push(c); + out.push('\u{200b}'); + } + _ => out.push(c), + } + i += 1; + } + // github.com/owner/repo/issues/12 links cross-reference the issue: shown, not linked. + out.replace("github.com/", "github.com\u{200b}/") +} + +fn closing_keyword(rest: &[char]) -> bool { + let word: String = rest + .iter() + .take_while(|c| c.is_alphabetic()) + .flat_map(|c| c.to_lowercase()) + .collect(); + [ + "close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved", + ] + .contains(&word.as_str()) +} + +/// Text as a markdown quote, every line prefixed. +fn quote(text: &str) -> String { + text.lines() + .map(|l| format!("> {l}").trim_end().to_owned()) + .collect::>() + .join("\n") +} + +/// The issue for a report's fields (`hub::REPORT`'s names, already checked). +pub fn issue(fields: &Map) -> Issue { + let field = |name: &str| { + fields + .get(name) + .and_then(Value::as_str) + .map(neutralise) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "not given".into()) + }; + let title = neutralise(&field("title").replace(['\n', '\r'], " ")); + let text = [ + format!("**What I did:**\n{}", field("did")), + format!("**What happened:**\n{}", field("happened")), + format!("**What I expected:**\n{}", field("expected")), + format!("**Horizon version:** {}", field("version")), + format!("**OS, CPU, GPU:** {}", field("system")), + ] + .join("\n"); + let by = fields + .get("name") + .and_then(Value::as_str) + .map(|n| neutralise(n).replace(['*', '_', '~', '|', '[', ']'], "")) + .filter(|n| !n.is_empty()) + .map(|n| format!(" by **{n}**")) + .unwrap_or_default(); + let body = format!( + "{}\n\nReported on playhorizon.dev{by}\n\nOpened by the bug form on playhorizon.dev/hub. The reporter has this issue's link; they don't get GitHub notifications.", + quote(&text) + ); + Issue { + title, + body, + labels: LABELS.iter().map(|l| (*l).to_owned()).collect(), + } +} + +/// Opens issues in `repo` (`owner/name`) with `token` (a fine-grained token with Issues: write on that repo +/// only). Errors never carry the token or GitHub's answer body. +pub fn github(repo: String, token: String) -> Box { + Box::new(move |issue: &Issue| { + let response = ureq::post(&format!("https://api.github.com/repos/{repo}/issues")) + .set("Authorization", &format!("Bearer {token}")) + .set("Accept", "application/vnd.github+json") + .set("X-GitHub-Api-Version", "2022-11-28") + .set("User-Agent", "horizon-telemetry-server") + .timeout(Duration::from_secs(20)) + .send_json(json!({ "title": issue.title, "body": issue.body, "labels": issue.labels })); + match response { + Ok(response) => response + .into_json::() + .ok() + .and_then(|v| v["html_url"].as_str().map(str::to_owned)) + .ok_or_else(|| "GitHub's answer had no issue URL".into()), + Err(ureq::Error::Status(code, _)) => Err(format!("GitHub answered {code}")), + Err(ureq::Error::Transport(e)) => Err(format!("could not reach GitHub: {}", e.kind())), + } + }) +} diff --git a/crates/horizon-telemetry-server/src/hub.rs b/crates/horizon-telemetry-server/src/hub.rs index ebf22610d..eb92cd692 100644 --- a/crates/horizon-telemetry-server/src/hub.rs +++ b/crates/horizon-telemetry-server/src/hub.rs @@ -1,4 +1,5 @@ -//! The hub's votes: a 👍 on a roadmap item at playhorizon.dev/hub. roadmap/README.md documents them for Kira and the website. +//! The hub's votes: a 👍 on a roadmap item at playhorizon.dev/hub, and the helpers the hub's other +//! endpoints (`intake`) share. roadmap/README.md documents them for Kira and the website. //! //! - `POST /hub/vote`: a 👍 on a roadmap item, one per browser (`voter`, a random id the page makes and //! keeps); `"up": false` takes it back. Answers the item's count. @@ -114,10 +115,12 @@ impl App { /// The hub's share of `maintain`: idle buckets are forgotten. pub(crate) fn forget_hub_buckets(&self) { - self.hub_buckets - .lock() - .unwrap_or_else(|e| e.into_inner()) - .retain(|_, (_, at)| at.elapsed() < Duration::from_secs(3600)); + for buckets in [&self.hub_buckets, &self.hub_post_buckets] { + buckets + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|_, (_, at)| at.elapsed() < Duration::from_secs(3600)); + } } } diff --git a/crates/horizon-telemetry-server/src/intake.rs b/crates/horizon-telemetry-server/src/intake.rs new file mode 100644 index 000000000..59ce57141 --- /dev/null +++ b/crates/horizon-telemetry-server/src/intake.rs @@ -0,0 +1,370 @@ +//! What players send from the hub (playhorizon.dev/hub) for the maintainers: bug reports and suggestions. +//! roadmap/README.md documents it for Kira and the website. +//! +//! - `POST /hub/report`: a bug report, opened at once as a GitHub issue (labels `bug`, `from-website`) in +//! the template Kira's `/report` uses (`github`). Kept and tried again by the upkeep if GitHub fails. +//! - `POST /hub/suggest`: a suggestion, into the queue. Never published: Kira relays it to the +//! maintainers' private channel. +//! - `GET /hub/suggestions?after=`: the queue for Kira, with the `HORIZON_TELEMETRY_HUB_TOKEN` bearer. +//! +//! Stored: reports and suggestions as their text, for `hub_keep_days`. Never an IP address. +use std::sync::Arc; + +use axum::extract::{Query, Request, State}; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use rusqlite::params; +use serde::Deserialize; +use serde_json::{Map, Value, json}; + +use crate::hub::{answer, item_id, json_body, refuse}; +use crate::store::Store; +use crate::{App, github, take, utc_now}; + +pub const SCHEMA: &str = " +CREATE TABLE IF NOT EXISTS hub_queue ( + id INTEGER PRIMARY KEY, kind TEXT NOT NULL, day INTEGER NOT NULL, created TEXT NOT NULL, + state TEXT NOT NULL DEFAULT 'new', issue TEXT NOT NULL DEFAULT '', body TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS hub_queue_kind ON hub_queue (kind, state, id); +"; + +/// Days the upkeep keeps trying to open a report's issue. +const RETRY_DAYS: u32 = 7; + +/// A field's rules: its name, whether it is needed, its length in characters, whether it may hold lines. +struct Field(&'static str, bool, std::ops::RangeInclusive, bool); + +/// A bug report: the `#horizon-bugs` template's fields. +const REPORT: &[Field] = &[ + Field("title", true, 5..=120, false), + Field("did", true, 3..=2000, true), + Field("happened", true, 3..=2000, true), + Field("expected", true, 3..=2000, true), + Field("version", false, 0..=60, false), + Field("system", true, 3..=200, false), + Field("name", false, 0..=64, false), +]; +const SUGGESTION: &[Field] = &[ + Field("text", true, 10..=1000, true), + Field("item", false, 0..=48, false), + Field("name", false, 0..=64, false), +]; + +/// Text as stored: no control characters but line breaks (where allowed), trimmed. +fn clean(text: &str, lines: bool) -> String { + let text = text.replace("\r\n", "\n"); + let kept: String = text + .chars() + .map(|c| if !lines && c == '\n' { ' ' } else { c }) + .filter(|c| !c.is_control() || (lines && *c == '\n')) + .collect(); + kept.trim().to_owned() +} + +/// The request's fields checked against `rules`: the cleaned object, or what is wrong. +fn fields(body: &Value, rules: &[Field]) -> Result, String> { + let object = body.as_object().ok_or("send a JSON object")?; + let mut out = Map::new(); + for Field(name, needed, length, lines) in rules { + let text = match object.get(*name) { + None | Some(Value::Null) => String::new(), + Some(Value::String(s)) => clean(s, *lines), + Some(_) => return Err(format!("{name} is text")), + }; + if text.is_empty() && !needed { + continue; + } + if !length.contains(&text.chars().count()) { + return Err(format!( + "{name}: {} to {} characters", + length.start(), + length.end() + )); + } + out.insert((*name).to_owned(), Value::String(text)); + } + Ok(out) +} + +impl Store { + /// How many entries of `kind` came in on `day`. + pub fn queued_on(&self, kind: &str, day: u32) -> rusqlite::Result { + self.db.query_row( + "SELECT count(*) FROM hub_queue WHERE kind = ?1 AND day = ?2", + params![kind, day], + |r| r.get(0), + ) + } + + /// Queues an entry: its id, and its issue when the same text already came in since `since` and was + /// opened (a double click, a form sent twice). + pub fn enqueue( + &mut self, + kind: &str, + day: u32, + since: u32, + body: &Map, + ) -> rusqlite::Result<(i64, Option)> { + let body = Value::Object(body.clone()).to_string(); + let same = self + .db + .prepare( + "SELECT id, issue FROM hub_queue WHERE kind = ?1 AND body = ?2 AND day >= ?3 LIMIT 1", + )? + .query_row(params![kind, body, since], |r| { + Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?)) + }); + match same { + Ok((id, issue)) => return Ok((id, Some(issue).filter(|i| !i.is_empty()))), + Err(rusqlite::Error::QueryReturnedNoRows) => {} + Err(e) => return Err(e), + } + self.db.execute( + "INSERT INTO hub_queue (kind, day, created, body) VALUES (?1, ?2, ?3, ?4)", + params![kind, day, utc_now(), body], + )?; + Ok((self.db.last_insert_rowid(), None)) + } + + /// Suggestions after `after`, oldest first: `{id, text, item?, name?, created_at}`. + pub fn suggestions(&self, after: i64, limit: u32) -> rusqlite::Result> { + let mut statement = self.db.prepare( + "SELECT id, created, body FROM hub_queue WHERE kind = 'suggestion' AND id > ?1 ORDER BY id LIMIT ?2", + )?; + let rows = statement.query_map(params![after, limit], |r| { + let mut entry: Map = + serde_json::from_str(&r.get::<_, String>(2)?).unwrap_or_default(); + entry.insert("id".into(), r.get::<_, i64>(0)?.into()); + entry.insert("created_at".into(), r.get::<_, String>(1)?.into()); + Ok(Value::Object(entry)) + })?; + rows.collect() + } + + /// Reports whose issue isn't open yet, from `since` on: id and fields. + pub fn unfiled(&self, since: u32) -> rusqlite::Result)>> { + let mut statement = self.db.prepare( + "SELECT id, body FROM hub_queue WHERE kind = 'report' AND state = 'new' AND day >= ?1 ORDER BY id", + )?; + let rows = statement.query_map([since], |r| { + Ok(( + r.get::<_, i64>(0)?, + serde_json::from_str(&r.get::<_, String>(1)?).unwrap_or_default(), + )) + })?; + rows.collect() + } + + /// Marks a report as opened: `issue` is its URL. + pub fn filed(&mut self, id: i64, issue: &str) -> rusqlite::Result<()> { + self.db.execute( + "UPDATE hub_queue SET state = 'filed', issue = ?2 WHERE id = ?1", + params![id, issue], + )?; + Ok(()) + } + + /// Reports from before `retry_from` that never got an issue are given up; entries before `oldest_day` + /// go. + pub fn expire_queue(&mut self, oldest_day: u32, retry_from: u32) -> rusqlite::Result { + self.db.execute( + "UPDATE hub_queue SET state = 'failed' WHERE kind = 'report' AND state = 'new' AND day < ?1", + [retry_from], + )?; + self.db + .execute("DELETE FROM hub_queue WHERE day < ?1", [oldest_day]) + } +} + +impl App { + /// The same for reports and suggestions, a much smaller bucket. + fn allow_post(&self, req: &Request) -> bool { + take( + &self.hub_post_buckets, + self.config.hub_posts_per_hour, + self.hashed(req), + ) + } + + /// Opens the reports whose issue isn't open yet (the upkeep calls it off the async workers; it blocks). + /// Stops at the first failure: GitHub is down or the token is wrong, the next round tries again. + pub fn file_pending(&self) { + let Some(filer) = &self.filer else { return }; + let since = (self.today)().saturating_sub(RETRY_DAYS); + let pending = self.store().unfiled(since).unwrap_or_default(); + for (id, fields) in pending { + match filer(&github::issue(&fields)) { + Ok(url) => self.mark_filed(id, &url), + Err(e) => { + eprintln!("horizon-telemetry-server: report {id} still not opened: {e}"); + return; + } + } + } + } + + fn mark_filed(&self, id: i64, url: &str) { + let marked = self.store().filed(id, url); + if let Err(e) = marked { + eprintln!("horizon-telemetry-server: report {id} opened as {url}, not marked: {e}"); + } + } + + /// The intake's share of `maintain`: entries past `hub_keep_days` go, reports never opened after + /// [`RETRY_DAYS`] are given up. + pub(crate) fn expire_intake(&self) -> rusqlite::Result { + let today = (self.today)(); + self.store().expire_queue( + today.saturating_sub(self.config.hub_keep_days), + today.saturating_sub(RETRY_DAYS), + ) + } +} + +/// What `receive` keeps: the entry's id, its issue if already opened, its fields. +type Received = (i64, Option, Map); + +/// Checks a report or a suggestion and queues it. +async fn receive( + app: &App, + req: Request, + kind: &str, + rules: &[Field], + per_day: u32, +) -> Result> { + let no = |code: StatusCode, message: &str| Box::new(refuse(app, code, message)); + if !app.allow_post(&req) { + return Err(no(StatusCode::TOO_MANY_REQUESTS, "too many requests")); + } + let body = json_body(req) + .await + .map_err(|e| no(StatusCode::BAD_REQUEST, e))?; + // The form's hidden field, which people leave empty and form-filling bots don't: thanked, dropped. + if body["website"].as_str().is_some_and(|s| !s.is_empty()) { + let thanks = answer(app, StatusCode::ACCEPTED, json!({ "id": 0 })); + return Err(Box::new(thanks)); + } + let entry = fields(&body, rules).map_err(|e| no(StatusCode::BAD_REQUEST, &e))?; + if let Some(item) = entry.get("item").and_then(Value::as_str) + && !item_id(item) + { + return Err(no(StatusCode::BAD_REQUEST, "item: a roadmap item id")); + } + let today = (app.today)(); + let mut store = app.store(); + if store.queued_on(kind, today).unwrap_or(u32::MAX) >= per_day { + let full = "too many today: please try again tomorrow"; + return Err(no(StatusCode::SERVICE_UNAVAILABLE, full)); + } + match store.enqueue(kind, today, today.saturating_sub(1), &entry) { + Ok((id, issue)) => Ok((id, issue, entry)), + Err(e) => { + eprintln!("horizon-telemetry-server: could not queue a {kind}: {e}"); + Err(no(StatusCode::SERVICE_UNAVAILABLE, "try again later")) + } + } +} + +/// `POST /hub/report` `{"title", "did", "happened", "expected", "version"?, "system", "name"?}`: 201 +/// `{"id", "issue"}` once the issue is open, 202 `{"id", "issue": null}` when GitHub failed and the upkeep +/// will try again; 503 when reports are off (no GitHub token). +pub async fn report(State(app): State>, req: Request) -> Response { + let Some(filer) = app.filer.clone() else { + return refuse( + &app, + StatusCode::SERVICE_UNAVAILABLE, + "reports are closed here: use GitHub or Discord", + ); + }; + let per_day = app.config.hub_reports_per_day; + let (id, issue, fields) = match receive(&app, req, "report", REPORT, per_day).await { + Ok(received) => received, + Err(response) => return *response, + }; + if let Some(issue) = issue { + return answer( + &app, + StatusCode::CREATED, + json!({ "id": id, "issue": issue }), + ); + } + let opened = tokio::task::spawn_blocking(move || filer(&github::issue(&fields))) + .await + .map_err(|e| e.to_string()) + .and_then(|opened| opened); + match opened { + Ok(url) => { + app.mark_filed(id, &url); + answer(&app, StatusCode::CREATED, json!({ "id": id, "issue": url })) + } + Err(e) => { + eprintln!("horizon-telemetry-server: report {id} not opened yet: {e}"); + answer( + &app, + StatusCode::ACCEPTED, + json!({ "id": id, "issue": null }), + ) + } + } +} + +/// `POST /hub/suggest` `{"text", "item"?, "name"?}`: 202 `{"id"}`. +pub async fn suggest(State(app): State>, req: Request) -> Response { + let per_day = app.config.hub_suggestions_per_day; + match receive(&app, req, "suggestion", SUGGESTION, per_day).await { + Ok((id, ..)) => answer(&app, StatusCode::ACCEPTED, json!({ "id": id })), + Err(response) => *response, + } +} + +#[derive(Deserialize)] +pub struct After { + after: Option, + limit: Option, +} + +/// `GET /hub/suggestions?after=&limit=100` with `Authorization: Bearer `: +/// `{"suggestions": [{"id", "text", "item"?, "name"?, "created_at"}]}`, oldest first. 404 when no token is +/// set, 401 for a wrong one. +pub async fn suggestions( + State(app): State>, + headers: HeaderMap, + Query(after): Query, +) -> Response { + let Some(token) = app.config.hub_token.as_deref() else { + return StatusCode::NOT_FOUND.into_response(); + }; + let sent = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .unwrap_or(""); + if !same(sent.as_bytes(), token.as_bytes()) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let limit = after.limit.unwrap_or(100).clamp(1, 500); + let listed = app.store().suggestions(after.after.unwrap_or(0), limit); + match listed { + Ok(list) => ( + [ + ( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ), + (header::CACHE_CONTROL, HeaderValue::from_static("no-store")), + ], + json!({ "suggestions": list }).to_string(), + ) + .into_response(), + Err(e) => { + eprintln!("horizon-telemetry-server: could not read the suggestions: {e}"); + StatusCode::SERVICE_UNAVAILABLE.into_response() + } + } +} + +/// Equal, in a time that doesn't depend on where they differ. +fn same(a: &[u8], b: &[u8]) -> bool { + a.len() == b.len() && a.iter().zip(b).fold(0, |diff, (x, y)| diff | (x ^ y)) == 0 +} diff --git a/crates/horizon-telemetry-server/src/lib.rs b/crates/horizon-telemetry-server/src/lib.rs index 9c273727c..3ab923969 100644 --- a/crates/horizon-telemetry-server/src/lib.rs +++ b/crates/horizon-telemetry-server/src/lib.rs @@ -7,7 +7,7 @@ //! least 3 installs only (`summary`), cached; the website's Benchmarks page reads it. //! - `POST /v1/live`: a game's anonymous "I'm playing" ping (`live`, in memory only). //! - `GET /v1/live`: how many play now, rounded, cached briefly. -//! - `POST /hub/vote`, `GET /hub/votes`: the hub's 👍 on roadmap items (`hub`). +//! - `/hub/…`: the hub's votes (`hub`), bug reports and suggestions (`intake`). //! - `GET /healthz`. //! //! Abuse limits: a token bucket per IP address (kept in memory for an hour, never stored), a @@ -29,11 +29,14 @@ use axum::routing::{delete, get, post}; use horizon_telemetry::batch; pub mod classes; +pub mod github; pub mod hub; +pub mod intake; pub mod live; pub mod store; pub mod summary; +use github::Filer; use horizon_telemetry::live::{MAX_PING_BYTES, Ping}; use live::Live; use store::Store; @@ -61,6 +64,20 @@ pub struct Config { pub live_max_sessions: usize, /// The hub's votes and reads of their counts an IP address may make an hour. pub hub_per_hour: f64, + /// Bug reports and suggestions together an IP address may send an hour. + pub hub_posts_per_hour: f64, + /// Bug reports taken a day, from everyone: each one opens a GitHub issue. + pub hub_reports_per_day: u32, + /// Suggestions taken a day, from everyone. + pub hub_suggestions_per_day: u32, + /// Days reports and suggestions are kept (Kira has relayed them long before). + pub hub_keep_days: u32, + /// The bearer token `GET /hub/suggestions` wants (Kira's); unset, it answers 404. + pub hub_token: Option, + /// Opens the website's bug reports as issues; unset, `POST /hub/report` answers 503. + pub github_token: Option, + /// Where those issues go, `owner/name`. + pub github_repo: String, } impl Default for Config { @@ -76,6 +93,13 @@ impl Default for Config { live_window: horizon_telemetry::live::WINDOW, live_max_sessions: 200_000, hub_per_hour: 600.0, + hub_posts_per_hour: 20.0, + hub_reports_per_day: 30, + hub_suggestions_per_day: 200, + hub_keep_days: 90, + hub_token: None, + github_token: None, + github_repo: "ludovic111/horizon".into(), } } } @@ -83,9 +107,16 @@ impl Default for Config { impl Config { /// The defaults, with `HORIZON_TELEMETRY_RETENTION_DAYS`, `…_MIN_INSTALL_DAYS`, /// `…_REQUESTS_PER_HOUR`, `…_ITEMS_PER_DAY`, `…_TRUST_PROXY` (1), `…_ALLOW_ORIGIN`, - /// `…_LIVE_PER_HOUR`, `…_LIVE_WINDOW_SECONDS`, `…_LIVE_MAX_SESSIONS` and `…_HUB_PER_HOUR`. + /// `…_LIVE_PER_HOUR`, `…_LIVE_WINDOW_SECONDS`, `…_LIVE_MAX_SESSIONS`, `…_HUB_PER_HOUR`, + /// `…_HUB_POSTS_PER_HOUR`, `…_HUB_REPORTS_PER_DAY`, `…_HUB_SUGGESTIONS_PER_DAY`, `…_HUB_KEEP_DAYS`, + /// `…_HUB_TOKEN`, `…_GITHUB_TOKEN` and `…_GITHUB_REPO`. Empty tokens count as unset. pub fn from_env() -> Self { let var = |k: &str| std::env::var(format!("HORIZON_TELEMETRY_{k}")).ok(); + let secret = |k: &str| { + var(k) + .map(|v| v.trim().to_owned()) + .filter(|v| !v.is_empty()) + }; let d = Self::default(); Self { retention_days: var("RETENTION_DAYS") @@ -114,6 +145,21 @@ impl Config { hub_per_hour: var("HUB_PER_HOUR") .and_then(|v| v.parse().ok()) .unwrap_or(d.hub_per_hour), + hub_posts_per_hour: var("HUB_POSTS_PER_HOUR") + .and_then(|v| v.parse().ok()) + .unwrap_or(d.hub_posts_per_hour), + hub_reports_per_day: var("HUB_REPORTS_PER_DAY") + .and_then(|v| v.parse().ok()) + .unwrap_or(d.hub_reports_per_day), + hub_suggestions_per_day: var("HUB_SUGGESTIONS_PER_DAY") + .and_then(|v| v.parse().ok()) + .unwrap_or(d.hub_suggestions_per_day), + hub_keep_days: var("HUB_KEEP_DAYS") + .and_then(|v| v.parse().ok()) + .unwrap_or(d.hub_keep_days), + hub_token: secret("HUB_TOKEN"), + github_token: secret("GITHUB_TOKEN"), + github_repo: var("GITHUB_REPO").unwrap_or(d.github_repo), } } } @@ -139,8 +185,12 @@ pub struct App { hub_key: RandomState, /// The hub's votes and vote counts, per hashed address. hub_buckets: Mutex, + /// The hub's reports and suggestions, per hashed address. + hub_post_buckets: Mutex, /// `GET /hub/votes`'s answer and when it was made. votes_cache: Mutex>, + /// Opens bug reports as GitHub issues; None without a token. + filer: Option>, } type Buckets = HashMap; @@ -160,6 +210,20 @@ impl App { store: Store, config: Config, today: Box u32 + Send + Sync>, + ) -> Arc { + let filer = config + .github_token + .clone() + .map(|token| Arc::from(github::github(config.github_repo.clone(), token))); + Self::with_filer(store, config, today, filer) + } + + /// [`Self::with_clock`] with the hub's bug reports opened by `filer` (tests give their own). + pub fn with_filer( + store: Store, + config: Config, + today: Box u32 + Send + Sync>, + filer: Option>, ) -> Arc { let live = Live::new(config.live_window, config.live_max_sessions); Arc::new(Self { @@ -174,7 +238,9 @@ impl App { today, hub_key: RandomState::new(), hub_buckets: Mutex::default(), + hub_post_buckets: Mutex::default(), votes_cache: Mutex::default(), + filer, }) } @@ -235,10 +301,12 @@ impl App { } /// Daily upkeep: totals rebuilt, expired rows removed, idle rate-limit entries and live - /// sessions forgotten. + /// sessions forgotten, the hub's old reports and suggestions removed. Reports still waiting for + /// their issue are [`Self::file_pending`]'s. pub fn maintain(&self) -> rusqlite::Result { let oldest = (self.today)().saturating_sub(self.config.retention_days); let removed = self.store().expire(oldest)?; + self.expire_intake()?; self.forget_hub_buckets(); for buckets in [&self.buckets, &self.live_buckets] { buckets @@ -503,6 +571,12 @@ pub fn router(app: Arc) -> Router { .route("/v1/benchmarks/summary", get(benchmarks)) .route("/hub/vote", post(hub::vote).options(hub::preflight)) .route("/hub/votes", get(hub::votes)) + .route("/hub/report", post(intake::report).options(hub::preflight)) + .route( + "/hub/suggest", + post(intake::suggest).options(hub::preflight), + ) + .route("/hub/suggestions", get(intake::suggestions)) .route("/healthz", get(|| async { "ok" })) .with_state(app) } diff --git a/crates/horizon-telemetry-server/src/main.rs b/crates/horizon-telemetry-server/src/main.rs index 9b9c702c3..728846a0f 100644 --- a/crates/horizon-telemetry-server/src/main.rs +++ b/crates/horizon-telemetry-server/src/main.rs @@ -22,6 +22,9 @@ async fn main() { if let Err(e) = upkeep.maintain() { eprintln!("horizon-telemetry-server: upkeep failed: {e}"); } + // The hub's reports GitHub refused before: their issues, off the async workers. + let filing = upkeep.clone(); + let _ = tokio::task::spawn_blocking(move || filing.file_pending()).await; } }); let listener = tokio::net::TcpListener::bind(SocketAddr::from(([0, 0, 0, 0], port))) diff --git a/crates/horizon-telemetry-server/src/store.rs b/crates/horizon-telemetry-server/src/store.rs index d1137d197..9286dd36a 100644 --- a/crates/horizon-telemetry-server/src/store.rs +++ b/crates/horizon-telemetry-server/src/store.rs @@ -131,6 +131,7 @@ impl Store { let mut db = Connection::open(path)?; db.execute_batch(SCHEMA)?; db.execute_batch(crate::hub::SCHEMA)?; + db.execute_batch(crate::intake::SCHEMA)?; migrate(&mut db)?; Ok(Self { db }) } diff --git a/crates/horizon-telemetry-server/tests/github.rs b/crates/horizon-telemetry-server/tests/github.rs new file mode 100644 index 000000000..81f480b58 --- /dev/null +++ b/crates/horizon-telemetry-server/tests/github.rs @@ -0,0 +1,41 @@ +//! A website bug report as the issue GitHub gets: the template, and people's text made inert. +use horizon_telemetry_server::github::{issue, neutralise}; +use serde_json::{Map, Value, json}; + +#[test] +fn people_text_mentions_and_references_nothing() { + let text = + neutralise("@octocat see #12 and https://github.com/a/b/issues/3 `x` Fixes it"); + assert!(!text.contains("@o") && !text.contains("#1") && !text.contains("github.com/")); + assert!(!text.contains('<') && !text.contains('`')); + assert!(text.contains("F\u{200b}ixes")); + // Words that only start like a keyword stay as they are. + assert_eq!(neutralise("closet fixture"), "closet fixture"); +} + +#[test] +fn a_report_reads_as_the_template() { + let fields: Map = serde_json::from_value(json!({ + "title": "Water is black\non AMD", "did": "Opened a world", "happened": "Black water", + "expected": "Blue water", "system": "Windows 11, RX 6600", "name": "steve_" + })) + .unwrap(); + let issue = issue(&fields); + assert_eq!(issue.title, "Water is black on AMD"); + assert!( + issue + .body + .starts_with("> **What I did:**\n> Opened a world\n> **What happened:**") + ); + assert!( + issue + .body + .contains("> **Horizon version:** not given\n> **OS, CPU, GPU:** Windows 11, RX 6600") + ); + assert!( + issue + .body + .contains("Reported on playhorizon.dev by **steve**") + ); + assert_eq!(issue.labels, ["bug", "from-website"]); +} diff --git a/crates/horizon-telemetry-server/tests/hub.rs b/crates/horizon-telemetry-server/tests/hub.rs index 10ddc12c4..056978212 100644 --- a/crates/horizon-telemetry-server/tests/hub.rs +++ b/crates/horizon-telemetry-server/tests/hub.rs @@ -1,8 +1,11 @@ -//! The hub's votes through the HTTP interface. -use std::sync::Arc; +//! The hub's intake through its HTTP interface: votes, bug reports (opened as issues by a fake GitHub), +//! suggestions and the queue Kira reads. +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Mutex}; use axum::body::Body; use axum::http::{Request, StatusCode}; +use horizon_telemetry_server::github::{Filer, Issue}; use horizon_telemetry_server::store::Store; use horizon_telemetry_server::{App, Config, router}; use http_body_util::BodyExt; @@ -12,17 +15,54 @@ use tower::ServiceExt; const DAY: u32 = 20_741; const VOTER: &str = "0b7c3c9e-3f0a-4d8e-9a39-4c1f5a6b7d21"; +/// The issues the fake GitHub opened, and whether it is up. +#[derive(Default)] +struct GitHub { + opened: Mutex>, + down: Mutex, +} + struct Hub { app: Arc, + github: Arc, + day: Arc, } fn hub(config: Config) -> Hub { - let app = App::with_clock(Store::open(":memory:").unwrap(), config, Box::new(|| DAY)); - Hub { app } + let github = Arc::new(GitHub::default()); + let fake = github.clone(); + let filer: Arc = Arc::new(move |issue: &Issue| { + if *fake.down.lock().unwrap() { + return Err("GitHub answered 502".into()); + } + let mut opened = fake.opened.lock().unwrap(); + opened.push(Issue { + title: issue.title.clone(), + body: issue.body.clone(), + labels: issue.labels.clone(), + }); + Ok(format!( + "https://github.com/ludovic111/horizon/issues/{}", + 1000 + opened.len() + )) + }); + let day = Arc::new(AtomicU32::new(DAY)); + let clock = day.clone(); + let app = App::with_filer( + Store::open(":memory:").unwrap(), + config, + Box::new(move || clock.load(Ordering::SeqCst)), + Some(filer), + ); + Hub { app, github, day } } fn config() -> Config { - Config::default() + Config { + hub_token: Some("kira-secret".into()), + hub_posts_per_hour: 1000.0, + ..Config::default() + } } impl Hub { @@ -43,12 +83,27 @@ impl Hub { .await } - async fn get(&self, path: &str) -> (StatusCode, Value) { - self.send(Request::get(path).body(Body::empty()).unwrap()) - .await + async fn get(&self, path: &str, token: Option<&str>) -> (StatusCode, Value) { + let mut req = Request::get(path); + if let Some(token) = token { + req = req.header("authorization", format!("Bearer {token}")); + } + self.send(req.body(Body::empty()).unwrap()).await } } +fn report(title: &str) -> Value { + json!({ + "title": title, + "did": "Opened a new world\nWalked to the sea", + "happened": "The water is black", + "expected": "Blue water, as in vanilla", + "version": "v0.2.57", + "system": "Windows 11, Ryzen 5 5600, RX 6600", + "website": "", + }) +} + #[tokio::test] async fn votes_count_once_per_browser_and_can_be_taken_back() { let hub = hub(config()); @@ -71,7 +126,7 @@ async fn votes_count_once_per_browser_and_can_be_taken_back() { 2 ); assert_eq!( - hub.get("/hub/votes").await, + hub.get("/hub/votes", None).await, (StatusCode::OK, json!({ "votes": { "smooth-frames": 2 } })) ); assert_eq!( @@ -79,7 +134,7 @@ async fn votes_count_once_per_browser_and_can_be_taken_back() { 1 ); assert_eq!( - hub.get("/hub/votes").await.1["votes"]["smooth-frames"], + hub.get("/hub/votes", None).await.1["votes"]["smooth-frames"], 1, "a vote drops the cached counts" ); @@ -92,12 +147,239 @@ async fn votes_count_once_per_browser_and_can_be_taken_back() { } } +#[tokio::test] +async fn a_report_becomes_an_issue_in_the_bug_template() { + let hub = hub(config()); + let (code, body) = hub + .post("/hub/report", report("Water is black on AMD")) + .await; + assert_eq!(code, StatusCode::CREATED); + assert_eq!( + body["issue"], + "https://github.com/ludovic111/horizon/issues/1001" + ); + let issue = hub.github.opened.lock().unwrap().remove(0); + assert_eq!(issue.title, "Water is black on AMD"); + assert_eq!(issue.labels, ["bug", "from-website"]); + for line in [ + "> **What I did:**\n> Opened a new world\n> Walked to the sea", + "> **What happened:**\n> The water is black", + "> **What I expected:**\n> Blue water, as in vanilla", + "> **Horizon version:** v0.2.57", + "> **OS, CPU, GPU:** Windows 11, Ryzen 5 5600, RX 6600", + "Reported on playhorizon.dev", + ] { + assert!(issue.body.contains(line), "{line}\n---\n{}", issue.body); + } + // The same report again (a double click) answers the same issue and opens nothing. + let (code, again) = hub + .post("/hub/report", report("Water is black on AMD")) + .await; + assert_eq!( + (code, &again["issue"]), + (StatusCode::CREATED, &body["issue"]) + ); + assert!(hub.github.opened.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn reports_need_every_template_field_and_skip_bots() { + let hub = hub(config()); + for empty in ["title", "did", "happened", "expected", "system"] { + let mut body = report("Water is black on AMD"); + body[empty] = json!(" "); + let (code, answer) = hub.post("/hub/report", body).await; + assert_eq!(code, StatusCode::BAD_REQUEST, "{empty}"); + assert!(answer["error"].as_str().unwrap().starts_with(empty)); + } + let mut bot = report("Cheap watches"); + bot["website"] = json!("https://spam.example"); + assert_eq!( + hub.post("/hub/report", bot).await, + (StatusCode::ACCEPTED, json!({ "id": 0 })) + ); + assert!(hub.github.opened.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn a_report_github_refused_is_opened_by_the_upkeep() { + let hub = hub(config()); + *hub.github.down.lock().unwrap() = true; + let (code, body) = hub + .post("/hub/report", report("Crash when opening a chest")) + .await; + assert_eq!((code, &body["issue"]), (StatusCode::ACCEPTED, &Value::Null)); + hub.app.file_pending(); + assert_eq!(hub.github.opened.lock().unwrap().len(), 0); + *hub.github.down.lock().unwrap() = false; + hub.app.file_pending(); + assert_eq!(hub.github.opened.lock().unwrap().len(), 1); + hub.app.file_pending(); + assert_eq!(hub.github.opened.lock().unwrap().len(), 1, "opened once"); +} + +#[tokio::test] +async fn reports_are_closed_without_a_github_token() { + let app = App::with_clock( + Store::open(":memory:").unwrap(), + Config::default(), + Box::new(|| DAY), + ); + let res = router(app) + .oneshot( + Request::post("/hub/report") + .header("content-type", "application/json") + .body(Body::from(report("Water is black").to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE); +} + +#[tokio::test] +async fn suggestions_wait_in_the_queue_for_kira() { + let hub = hub(config()); + let first = json!({ "text": " Add a waypoint mod\r\nto the\u{7} browser ", "item": "mod-registry", "name": "alex", "extra": 1 }); + let (code, body) = hub.post("/hub/suggest", first).await; + assert_eq!(code, StatusCode::ACCEPTED); + let first_id = body["id"].as_i64().unwrap(); + hub.post( + "/hub/suggest", + json!({ "text": "Bigger render distance on the Steam Deck" }), + ) + .await; + assert_eq!( + hub.post("/hub/suggest", json!({ "text": "too short" })) + .await + .0, + StatusCode::BAD_REQUEST + ); + assert_eq!( + hub.post( + "/hub/suggest", + json!({ "text": "A long enough idea", "item": "Bad Id" }) + ) + .await + .0, + StatusCode::BAD_REQUEST + ); + + assert_eq!( + hub.get("/hub/suggestions", None).await.0, + StatusCode::UNAUTHORIZED + ); + assert_eq!( + hub.get("/hub/suggestions", Some("wrong-secret")).await.0, + StatusCode::UNAUTHORIZED + ); + let (code, all) = hub.get("/hub/suggestions", Some("kira-secret")).await; + assert_eq!(code, StatusCode::OK); + let list = all["suggestions"].as_array().unwrap(); + assert_eq!(list.len(), 2); + assert_eq!( + list[0]["text"], "Add a waypoint mod\nto the browser", + "trimmed, no control characters" + ); + assert!(list[0].get("extra").is_none()); + assert_eq!(list[0]["item"], "mod-registry"); + assert_eq!(list[0]["name"], "alex"); + assert!(list[0]["created_at"].as_str().unwrap().ends_with('Z')); + assert!(list[1].get("name").is_none()); + let (_, after) = hub + .get( + &format!("/hub/suggestions?after={first_id}"), + Some("kira-secret"), + ) + .await; + assert_eq!(after["suggestions"].as_array().unwrap().len(), 1); + + let closed = hub_without_token(); + assert_eq!( + closed.get("/hub/suggestions", Some("anything")).await.0, + StatusCode::NOT_FOUND + ); +} + +fn hub_without_token() -> Hub { + hub(Config::default()) +} + +#[tokio::test] +async fn posts_are_rate_limited_per_address_and_capped_per_day() { + let hub = hub(Config { + hub_posts_per_hour: 20.0, + hub_suggestions_per_day: 3, + ..config() + }); + // A burst of a tenth of the hourly rate: two, then refused. + let idea = |n: u32| json!({ "text": format!("Idea number {n}, long enough") }); + assert_eq!( + hub.post("/hub/suggest", idea(1)).await.0, + StatusCode::ACCEPTED + ); + assert_eq!( + hub.post("/hub/suggest", idea(2)).await.0, + StatusCode::ACCEPTED + ); + assert_eq!( + hub.post("/hub/suggest", idea(3)).await.0, + StatusCode::TOO_MANY_REQUESTS + ); + + let busy = self::hub(Config { + hub_posts_per_hour: 1000.0, + hub_suggestions_per_day: 3, + ..config() + }); + for n in 0..3 { + assert_eq!( + busy.post("/hub/suggest", idea(n)).await.0, + StatusCode::ACCEPTED + ); + } + assert_eq!( + busy.post("/hub/suggest", idea(9)).await.0, + StatusCode::SERVICE_UNAVAILABLE + ); + busy.day.store(DAY + 1, Ordering::SeqCst); + assert_eq!( + busy.post("/hub/suggest", idea(9)).await.0, + StatusCode::ACCEPTED, + "a new day" + ); +} + +#[tokio::test] +async fn old_entries_go_and_reports_never_opened_are_given_up() { + let hub = hub(config()); + *hub.github.down.lock().unwrap() = true; + let (_, body) = hub + .post("/hub/report", report("Crash when opening a chest")) + .await; + assert!(body["id"].as_i64().unwrap() > 0); + hub.post("/hub/suggest", json!({ "text": "An idea from long ago" })) + .await; + hub.day.store(DAY + 8, Ordering::SeqCst); + hub.app.maintain().unwrap(); + *hub.github.down.lock().unwrap() = false; + hub.app.file_pending(); + assert!( + hub.github.opened.lock().unwrap().is_empty(), + "past a week a report is given up" + ); + hub.day.store(DAY + 91, Ordering::SeqCst); + hub.app.maintain().unwrap(); + let (_, left) = hub.get("/hub/suggestions", Some("kira-secret")).await; + assert!(left["suggestions"].as_array().unwrap().is_empty()); +} + #[tokio::test] async fn the_website_may_post_from_the_browser() { let hub = hub(config()); let res = router(hub.app.clone()) .oneshot( - Request::options("/hub/vote") + Request::options("/hub/report") .header("origin", "https://playhorizon.dev") .header("access-control-request-method", "POST") .body(Body::empty()) From 4a9ca2988732944ea794e23852132e02c2aec567 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 15:07:49 +0100 Subject: [PATCH 16/23] Website: the API portal at /docs/api, with Markdown tables The repository's docs/api/ (the portal, its surface pages and the generated mod and server references) is built into the docs section: /docs/api is its README and /docs/api/ each page, in two nav groups, "Build on Horizon" and "API reference". The pages are read from the checkout or from main on GitHub, like the README, so the site never holds a copy. Links between portal pages become the site's (and the build's link check covers them); other relative links go to the file on GitHub. The renderer gains tables: the "Ways in" table, the references and the other tables on the site (apis, performance) showed as raw pipes. A link whose label is a code span no longer throws. Caddy and the dev server route /docs/api/ and redirect /docs/api/ to /docs/api; Railway rebuilds when docs/api/ changes. /docs/mods links the Mod API, its reference and its ways in; the summary page is now "APIs at a glance". Co-Authored-By: Claude Opus 5.5 --- docs/api/README.md | 3 ++- website/Caddyfile | 4 ++++ website/README.md | 9 ++++++-- website/build.mjs | 34 +++++++++++++++++++++++------- website/docs/apis.md | 4 ++-- website/docs/mods.md | 2 +- website/docs/nav.json | 3 ++- website/railway.json | 2 +- website/serve.mjs | 6 +++++- website/src/docs.html | 2 +- website/src/markdown.js | 39 ++++++++++++++++++++++++++++++++--- website/src/markdown.test.mjs | 25 ++++++++++++++++++++++ website/src/style.css | 4 ++++ 13 files changed, 117 insertions(+), 20 deletions(-) create mode 100644 website/src/markdown.test.mjs diff --git a/docs/api/README.md b/docs/api/README.md index ad49ff609..ef3649105 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -51,5 +51,6 @@ Every page has the same parts: **Overview** (what you can build), **Guide** (whe **Examples**, **Stability** (the level of each part, per [stability.md](stability.md)), **Changelog** and **Not there yet** (what is planned, so nobody builds on a guess). -The website's summary for players and authors is [playhorizon.dev/docs/apis](https://playhorizon.dev/docs/apis) +The website shows these pages at [playhorizon.dev/docs/api](https://playhorizon.dev/docs/api), built from this +folder, and a summary for players and authors at [playhorizon.dev/docs/apis](https://playhorizon.dev/docs/apis) (`website/docs/apis.md`). diff --git a/website/Caddyfile b/website/Caddyfile index fb96e836d..4ef85d2fc 100644 --- a/website/Caddyfile +++ b/website/Caddyfile @@ -35,6 +35,10 @@ rewrite /benchmarks /benchmarks.html @doc path_regexp doc ^/docs/([a-z-]+)$ rewrite @doc /docs/{re.doc.1}.html + # The API portal: /docs/api is its index, /docs/api/ its pages. + redir /docs/api/ /docs/api permanent + @apidoc path_regexp apidoc ^/docs/api/([a-z-]+)$ + rewrite @apidoc /docs/api/{re.apidoc.1}.html # The registry's submission service (crates/horizon-mod-registry), over Railway's private network. Unset, the # form says it isn't open. handle /api/mods/* { diff --git a/website/README.md b/website/README.md index 8ced5a0aa..7339cf966 100644 --- a/website/README.md +++ b/website/README.md @@ -77,8 +77,13 @@ mark merged-but-unreleased things "next release". `{{HARNESSES}}` and `{{PERCENT the README. A line holding only `![caption](/media/...)` becomes a figure (the file must be in `public/media/`); links to other pages are `/docs/#heading`. The build checks every link between pages and every image, and fails with the list when one is broken. `/server` -redirects to `/docs/hosting`. The developer docs in the repository's `docs/` stay as they are and are linked from -the Contributing page. +redirects to `/docs/hosting`. + +The API portal is the repository's `docs/api/`, not a copy: `nav.json` lists its README as `api` (`/docs/api`) and +its pages as `api/` (`/docs/api/`), read from the checkout or from `main` on GitHub like the README. +Links between its pages become the site's, every other relative link goes to the file on GitHub, and the same link +check applies. Markdown tables render as tables. The other developer docs in `docs/` stay on GitHub and are linked +from the Contributing page. ## Run it locally diff --git a/website/build.mjs b/website/build.mjs index 12bba71cb..4045297fb 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -3,12 +3,13 @@ // docs/nav.json), plus public/ and fingerprinted CSS and JS. No dependencies. // // Railway builds only website/, so the README and links.json come from the repo when they -// are next to it (a local checkout) and from main on GitHub otherwise. The documentation lives in website/. The latest releases and +// are next to it (a local checkout) and from main on GitHub otherwise. The documentation lives in website/, except the +// API portal (docs/api/), read the same way as the README. The latest releases and // the contributors are baked in when GitHub answers, so the page reads well before (or without) JavaScript. import { readFile, writeFile, mkdir, rm, cp } from "node:fs/promises"; import { existsSync } from "node:fs"; import { createHash } from "node:crypto"; -import { join, dirname } from "node:path"; +import { join, dirname, posix } from "node:path"; import { fileURLToPath } from "node:url"; import { markdown, inline, section, escape } from "./src/markdown.js"; import { recentHtml, releasesPageHtml } from "./src/releases.js"; @@ -303,16 +304,35 @@ const values = { // --- The documentation --------------------------------------------------------------------- // website/docs/.md: "# Title", a one-paragraph lede, then the body. docs/nav.json orders them in groups. +// The API portal is the repository's docs/api/ (the pages and their generated references): nav.json lists it as +// `api` (its README, /docs/api) and `api/` (/docs/api/). Its links are written for GitHub, so links +// between its pages become the site's and every other relative link goes to the file on GitHub. const docsNav = JSON.parse(await readFile(join(site, "docs", "nav.json"), "utf8")); +const docSlugs = new Set(docsNav.flatMap((g) => g.pages)); +const apiSource = (slug) => `docs/api/${slug === "api" ? "README" : slug.slice(4)}.md`; +function apiLinks(text, from) { + return text.replace(/\]\(([^)\s]+)\)/g, (all, url) => { + if (url.startsWith("https://playhorizon.dev/")) return `](${url.slice(23)})`; + if (/^([a-z]+:|#|\/)/i.test(url)) return all; + const [file, id] = url.split("#"); + const path = posix.normalize(posix.join(posix.dirname(from), file)); + const page = path.match(/^docs\/api\/([\w-]+)\.md$/)?.[1]; + const slug = page === "README" ? "api" : page && `api/${page}`; + const to = docSlugs.has(slug) ? `/docs/${slug}` : `https://github.com/${REPO}/blob/main/${path}`; + return `](${to}${id ? `#${id}` : ""})`; + }); +} const docs = []; for (const { group, pages: slugs } of docsNav) { for (const slug of slugs) { - const file = `${slug}.md`; - const text = (await readFile(join(site, "docs", file), "utf8")).replace(/\r\n?/g, "\n"); + const api = slug === "api" || slug.startsWith("api/"); + const file = api ? apiSource(slug) : `website/docs/${slug}.md`; + let text = (api ? (await repoFile(file))[0] : await readFile(join(site, "docs", `${slug}.md`), "utf8")).replace(/\r\n?/g, "\n"); + if (api) text = apiLinks(text.replace(/^\n/, ""), file); const m = text.match(/^# (.+)\n\n((?:[^\n]+\n)+)\n/); - if (!m) throw new Error(`docs/${file}: needs "# Title", a blank line, a lede paragraph and a blank line`); - docs.push({ slug, file, group, title: m[1].trim(), lede: m[2].trim().replace(/\n/g, " "), body: text.slice(m[0].length), path: slug === "index" ? "/docs/" : `/docs/${slug}` }); + if (!m) throw new Error(`${file}: needs "# Title", a blank line, a lede paragraph and a blank line`); + docs.push({ slug, file, group, title: m[1].replace(/`/g, "").trim(), lede: m[2].trim().replace(/\n/g, " "), body: text.slice(m[0].length), path: slug === "index" ? "/docs/" : `/docs/${slug}` }); } } const plain = (md) => md.replace(/`/g, "").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/\*\*/g, ""); @@ -352,7 +372,7 @@ const docNav = (current) => .join("\n"); const pagerLink = (d, rel) => (d ? `${rel === "next" ? "Next" : "Previous"}${escape(d.title)}` : ""); -await mkdir(join(dist, "docs"), { recursive: true }); +await mkdir(join(dist, "docs", "api"), { recursive: true }); const docPageFiles = []; const docPages = renderedDocs.map((d, i) => { const toc = d.headings.filter((h) => h.level === 2); diff --git a/website/docs/apis.md b/website/docs/apis.md index f948b1d54..fbed5fe53 100644 --- a/website/docs/apis.md +++ b/website/docs/apis.md @@ -1,4 +1,4 @@ -# Horizon's APIs +# APIs at a glance Horizon is built to be built on. Mods, shaders, agents, server panels, launchers' scripts and tools all get a documented API with a version, a stability level and a reference generated from the code, so it never says something the game doesn't do. @@ -13,7 +13,7 @@ Horizon is built to be built on. Mods, shaders, agents, server panels, launchers | **Launcher** | your agent, pack makers | `horizon-launcher`'s 46 commands and its MCP server | preview | | **Data formats** | tools that read Horizon's files | benchmark reports, telemetry, settings, release checksums; worlds are vanilla's format | per format | -The full pages, one per surface, are in the repository: [docs/api](https://github.com/ludovic111/horizon/tree/main/docs/api). Mods for players: [Mods](/docs/mods). Agents: [Control Horizon with your AI agent](/docs/agents). Hosting: [Host a server](/docs/hosting). +The full pages, one per surface, with their references: [the API portal](/docs/api), starting with [the Mod API](/docs/api/mods). Mods for players: [Mods](/docs/mods). Agents: [Control Horizon with your AI agent](/docs/agents). Hosting: [Host a server](/docs/hosting). ## What the levels mean diff --git a/website/docs/mods.md b/website/docs/mods.md index 0c125cf73..77a1734fd 100644 --- a/website/docs/mods.md +++ b/website/docs/mods.md @@ -30,7 +30,7 @@ cd my-mod cargo horizon-mod run ``` -`run` builds the mod and starts the game with it. After an edit, `cargo horizon-mod build` rebuilds it and the running game reloads it. The full guide, with the API, the manifest and the roadmap, is [docs/mods.md](https://github.com/ludovic111/horizon/blob/main/docs/mods.md). Java mod jars don't run in Horizon: their code calls and patches Minecraft's Java classes, and Horizon has none. What carries over is the data and assets inside a jar ([modpacks](https://github.com/ludovic111/horizon/blob/main/docs/modpacks.md)). +`run` builds the mod and starts the game with it. After an edit, `cargo horizon-mod build` rebuilds it and the running game reloads it. The [Mod API](/docs/api/mods) lists what a mod can do today, its [reference](/docs/api/mods-reference), the [ways in](/docs/api/mods#ways-in) (Rust today, Lua scripts planned) and what comes next; the full guide, with the manifest and the runtime, is [docs/mods.md](https://github.com/ludovic111/horizon/blob/main/docs/mods.md). Java mod jars don't run in Horizon: their code calls and patches Minecraft's Java classes, and Horizon has none. What carries over is the data and assets inside a jar ([modpacks](https://github.com/ludovic111/horizon/blob/main/docs/modpacks.md)). ## Finding resource packs and modpacks diff --git a/website/docs/nav.json b/website/docs/nav.json index 3bc2ec8d2..18eab69fd 100644 --- a/website/docs/nav.json +++ b/website/docs/nav.json @@ -3,6 +3,7 @@ { "group": "Playing", "pages": ["settings", "multiplayer", "troubleshooting"] }, { "group": "Hosting", "pages": ["hosting"] }, { "group": "Going further", "pages": ["modpacks", "mods", "performance", "agents"] }, - { "group": "Build on Horizon", "pages": ["apis"] }, + { "group": "Build on Horizon", "pages": ["apis", "api", "api/stability"] }, + { "group": "API reference", "pages": ["api/mods", "api/mods-reference", "api/mod-index", "api/server", "api/server-reference", "api/agent-control", "api/launcher", "api/data-formats", "api/shaders"] }, { "group": "Project", "pages": ["contributing", "faq"] } ] diff --git a/website/railway.json b/website/railway.json index 0f84cf952..3bbe9dfb3 100644 --- a/website/railway.json +++ b/website/railway.json @@ -3,7 +3,7 @@ "build": { "builder": "DOCKERFILE", "dockerfilePath": "Dockerfile", - "watchPatterns": ["/website/**", "/README.md", "/launcher/links.json"] + "watchPatterns": ["/website/**", "/README.md", "/launcher/links.json", "/docs/api/**"] }, "deploy": { "healthcheckPath": "/", diff --git a/website/serve.mjs b/website/serve.mjs index 761eef48a..6159474a0 100644 --- a/website/serve.mjs +++ b/website/serve.mjs @@ -11,6 +11,10 @@ const port = Number(process.env.PORT) || 4173; createServer(async (req, res) => { let path = normalize(decodeURIComponent(new URL(req.url, "http://x").pathname)).replace(/^(\.\.[/\\])+/, ""); + if (path === "/docs/api/") { + res.writeHead(301, { Location: "/docs/api" }); + return res.end(); + } if (path.endsWith("/")) path += "index.html"; // The server guide is part of the docs now, as the Caddyfile redirects it. if (path === "/server" || path === "/server.html") { @@ -18,7 +22,7 @@ createServer(async (req, res) => { return res.end(); } if (path === "/docs") path = "/docs/index.html"; - // /privacy and /docs/ are .html files, as the Caddyfile rewrites them. + // /privacy, /docs/ and /docs/api/ are .html files, as the Caddyfile rewrites them. if (!extname(path)) path += ".html"; let file = join(root, path); let status = 200; diff --git a/website/src/docs.html b/website/src/docs.html index 1277803b5..56ba89c09 100644 --- a/website/src/docs.html +++ b/website/src/docs.html @@ -46,7 +46,7 @@ -

    Edit this page on GitHub · Spotted something wrong? Open an issue or ask on Discord.

    +

    Edit this page on GitHub · Spotted something wrong? Open an issue or ask on Discord.

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    diff --git a/website/src/markdown.js b/website/src/markdown.js index 252e554ec..1735f7304 100644 --- a/website/src/markdown.js +++ b/website/src/markdown.js @@ -1,5 +1,5 @@ -// A small Markdown renderer for release notes and the README: headings, paragraphs, -// lists (nested by indentation), fenced code, quotes, rules, and inline code, bold, +// A small Markdown renderer for release notes, the README and the docs: headings, paragraphs, +// lists (nested by indentation), fenced code, quotes, rules, tables, and inline code, bold, // italic and links. Everything is escaped first, so its output never carries raw HTML. // Shared by build.mjs (Node) and main.js (browser). @@ -38,12 +38,41 @@ export function inline(text, site = false) { out = out.replace(/\u0001(\d+)\u0001/g, (_, i) => { const [label, url] = links[i]; const target = href(url, site); - const body = inline(label, site); + // The label's code spans are already placeholders: put them back for its own pass. + const body = inline(label.replace(/\u0000(\d+)\u0000/g, (_, c) => `\`${codes[c]}\``), site); return target ? `${body}` : body; }); return out.replace(/\u0000(\d+)\u0000/g, (_, i) => `${escape(codes[i])}`); } +// A table: a row of cells, a rule row (`| --- | :-: |`), then body rows, until a line that isn't a row. +const ROW = /^\s*\|.*\|\s*$/; +const RULE = /^\s*\|(\s*:?-+:?\s*\|)+\s*$/; + +/** A row's cells: split on `|` outside code spans; `\|` is a literal bar. */ +function cells(row) { + const s = row.trim().slice(1, -1); + const out = [""]; + let code = false; + for (let i = 0; i < s.length; i++) { + if (s[i] === "\\" && s[i + 1] === "|") out[out.length - 1] += s[++i]; + else if (s[i] === "|" && !code) out.push(""); + else { + if (s[i] === "`") code = !code; + out[out.length - 1] += s[i]; + } + } + return out.map((c) => c.trim()); +} + +function table(lines, start, site) { + const row = (line, tag) => `${cells(line).map((c) => `<${tag}>${inline(c, site)}`).join("")}`; + let i = start + 2; + const body = []; + while (i < lines.length && ROW.test(lines[i])) body.push(row(lines[i++], "td")); + return [`
    ${row(lines[start], "th")}${body.join("")}
    `, i]; +} + const indentOf = (line) => line.match(/^ */)[0].length; const ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/; @@ -131,6 +160,10 @@ export function markdown(source, { shift = 0, site = false, headings = null } = } else if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { out.push("
    "); i++; + } else if (ROW.test(line) && RULE.test(lines[i + 1] || "")) { + const [html, end] = table(lines, i, site); + out.push(html); + i = end; } else if (ITEM.test(line)) { const [html, end] = list(lines, i, site); out.push(html); diff --git a/website/src/markdown.test.mjs b/website/src/markdown.test.mjs new file mode 100644 index 000000000..171348e45 --- /dev/null +++ b/website/src/markdown.test.mjs @@ -0,0 +1,25 @@ +// node --test src/: the Markdown the docs pages and release notes are rendered from. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { markdown } from "./markdown.js"; + +test("a table renders with its header, cells and inline Markdown", () => { + const html = markdown("| Way in | Status |\n| --- | :-: |\n| Rust | `cargo horizon-mod` |\n| Lua | planned \\| soon |\n\nAfter."); + assert.equal( + html, + '
    ' + + "
    Way inStatus
    Rustcargo horizon-mod
    Luaplanned | soon
    \n

    After.

    ", + ); +}); + +test("a bar inside a code span stays in its cell", () => { + assert.match(markdown("| a | b |\n|---|---|\n| `x | y` | z |"), /x \| y<\/code><\/td>z<\/td>/); +}); + +test("rows without a rule line are a paragraph", () => { + assert.equal(markdown("| a | b |\n| c | d |"), "

    | a | b | | c | d |

    "); +}); + +test("a link whose label is code keeps it", () => { + assert.equal(markdown("See [`AGENTS.md`](/docs/agents).", { site: true }), '

    See AGENTS.md.

    '); +}); diff --git a/website/src/style.css b/website/src/style.css index 4ce91791d..0279c38aa 100644 --- a/website/src/style.css +++ b/website/src/style.css @@ -687,6 +687,10 @@ code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--ou .bench-table td.num { font-variant-numeric: tabular-nums; white-space: nowrap; } .bench-table td.wins { color: var(--ink); font-weight: 600; } .bench-table td.vs { font-size: var(--text-caption); white-space: nowrap; } +.md-table { width: 100%; border-collapse: collapse; font-size: var(--text-ui); } +.md-table th, .md-table td { padding: 8px 12px 8px 0; text-align: left; border-bottom: 1px solid var(--rule); vertical-align: baseline; } +.md-table th { font-weight: 500; color: var(--ink); } +.md-table td code, .md-table th code { overflow-wrap: anywhere; } .vs-horizon { color: var(--success); } .vs-java { color: var(--danger); } .vs-tie, .vs-none { color: var(--muted); } From c1ffa17c87bcef7d2d564644123c3142c169b0d3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:14:12 +0100 Subject: [PATCH 17/23] Hub: vote for roadmap items, report a bug and suggest something from the page Each item still to come gets a "Want it" button with its count; the Contribute tab gets a bug report form (the #horizon-bugs template, which the telemetry server opens as a GitHub issue and links back) and a suggestion form (to the private queue Kira relays), and a Contributors list that shows the Discord name of those who agreed on Kira (/contributors.json). The forms and buttons appear once the hub's server answers; until then the page points to GitHub and Discord. roadmap/README.md documents the intake API that Kira shares. Co-Authored-By: Claude Opus 5.5 --- roadmap/README.md | 29 ++++++++- tools/roadmap.py | 3 +- website/build.mjs | 19 +++++- website/src/contributors.js | 2 +- website/src/hub-page.js | 120 ++++++++++++++++++++++++++++++++++++ website/src/hub.html | 43 ++++++++++++- website/src/hub.js | 41 +++++++++++- website/src/hub.test.mjs | 22 ++++++- website/src/style.css | 25 +++++++- 9 files changed, 293 insertions(+), 11 deletions(-) diff --git a/roadmap/README.md b/roadmap/README.md index 55cf9d09f..22cde1a7d 100644 --- a/roadmap/README.md +++ b/roadmap/README.md @@ -54,8 +54,8 @@ Whoever moves the work (the orchestrator on each heartbeat, or anyone in their p `2026-43.md`): `# Title`, a paragraph or two for players, then `## Technical` and the same week for contributors, with its pull requests. `build` puts it into website/data/roadmap.json; the hub's Journal tab shows it among the releases, and `/data/journal.json` carries it to Kira's #updates and to X. -6. Suggestions from the website and Discord are read and triaged by the maintainers. A good one becomes an - item in a normal pull request; none is published automatically. +6. Suggestions from the website and Discord reach the maintainers' private channel through Kira (below). A good + one becomes an item in a normal pull request; none is published automatically. CI runs `tests/test_roadmap.py` (in the Python tests), which fails when ROADMAP.md is not what `build` writes or when the file breaks a rule; `python3 tools/roadmap.py check --offline` runs the same rules without GitHub. @@ -89,3 +89,28 @@ merged pull request, release, shipped item and weekly summary, newest first, the - `announce: true` (the item's `announce` key) asks Kira to post the shipped item on X too, with `post`. - `https://playhorizon.dev/data/roadmap.json` is `roadmap.toml` as JSON (`areas`, `items` with every key above, `overview`, the weekly summaries); an item's page is `https://playhorizon.dev/hub#`. + +## The intake: votes, bug reports, suggestions + +The hub's forms and vote buttons talk to the telemetry server (`https://telemetry.playhorizon.dev`, +`crates/horizon-telemetry-server`, `src/hub.rs` and `src/intake.rs`; its README lists the limits and settings). +Kira uses the same endpoints, so a bug or an idea goes the same way from the site and from Discord. + +| Endpoint | Body | Answer | +| --- | --- | --- | +| `POST /hub/vote` | `{"item": "", "voter": "", "up": true}` | `{"item", "votes"}`; `"up": false` takes the vote back | +| `GET /hub/votes` | | `{"votes": {"": n}}`, a minute old at most | +| `POST /hub/report` | `{"title", "did", "happened", "expected", "version"?, "system", "name"?}` | 201 `{"id", "issue": ""}`; 202 `{"id", "issue": null}` when GitHub was down (opened later) | +| `POST /hub/suggest` | `{"text", "item"?, "name"?}` | 202 `{"id"}` | +| `GET /hub/suggestions?after=` | `Authorization: Bearer ` | `{"suggestions": [{"id", "text", "item"?, "name"?, "created_at"}]}`, oldest first | + +- A report becomes an issue at once, labels `bug` and `from-website`, in the `#horizon-bugs` template (What I did, + What happened, What I expected, Horizon version, OS, CPU, GPU) with "Reported on playhorizon.dev". Every field + but the version and the name is required; mentions, `#123` references and HTML in people's text are made inert. +- Suggestions are never published. Kira polls `/hub/suggestions` with the last id it relayed and posts each one + to `#roadmap-suggestions`. +- Errors are `{"error": "…"}`: 400 names the field (`"did: 3 to 2000 characters"`), 429 means too many from that + address, 503 a full day or reports turned off (no GitHub token on the server). +- The page shows the forms and the buttons only once `GET /hub/votes` answers. Until then it points to GitHub and + Discord. It keeps a random voter id and the items it voted for in `localStorage` (`hub:voter`, `hub:voted`). + diff --git a/tools/roadmap.py b/tools/roadmap.py index fe97285ff..4bc439e4d 100644 --- a/tools/roadmap.py +++ b/tools/roadmap.py @@ -56,7 +56,8 @@ ITEM_KEYS = {"id", "title", "status", "area", "plain", "dev", "links", "focus", ISSUE = re.compile(r"#(\d+)$") ID = re.compile(r"[a-z0-9]+(-[a-z0-9]+)*$") # An item is the anchor playhorizon.dev/hub#: it can't take the name of a tab, a section or a heading. -RESERVED = {"main", "overview", "roadmap", "board", "journal", "contribute", "hub-data", *STATUSES} +RESERVED = {"main", "overview", "roadmap", "board", "journal", "contribute", "report", "suggest", "contributors", + "hub-data", *STATUSES} RESERVED_PREFIXES = ("h-", "tab-", "col-", "week-", "journal-") RELEASE = re.compile(r"(v\d[\w.]*|launcher@\d[\w.]*|launcher-v\d[\w.]*|website)$") MONTHS = ("January|February|March|April|June|July|August|September|October|November|December") diff --git a/website/build.mjs b/website/build.mjs index c3203891e..b766b3d79 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -16,7 +16,7 @@ import { machinesHtml, playersHtml } from "./src/bench.js"; import { CPUS, GPUS, singleThread } from "./src/hardware.js"; import { isGame, isLauncher, launcherVersion, newestFirst } from "./src/versions.js"; import { contributorsFrom, contributorsHtml } from "./src/contributors.js"; -import { areaFilterHtml, boardFilterHtml, boardFrom, boardHtml, helpWantedHtml, journalFrom, journalHtml, journalJson, overviewHtml, roadmapHtml, slimIssue } from "./src/hub.js"; +import { areaFilterHtml, boardFilterHtml, boardFrom, boardHtml, creditFrom, creditHtml, helpWantedHtml, journalFrom, journalHtml, journalJson, overviewHtml, roadmapHtml, slimIssue, suggestItemsHtml } from "./src/hub.js"; const site = dirname(fileURLToPath(import.meta.url)); const dist = join(site, "dist"); @@ -119,6 +119,18 @@ const hubLinked = new Map(hubLive.filter((i) => linked.has(i.n)).map((i) => [i.n const board = boardFrom(hubLive, roadmap); const journal = journalFrom(releases, hubLive, roadmap); +// The hub's server (crates/horizon-telemetry-server: votes, bug reports, suggestions), and Kira's list of the +// contributors who linked their Discord account and agreed to be credited (kira's /contributors.json). +const hubApi = process.env.HUB_API_URL || "https://telemetry.playhorizon.dev"; +let kiraCredit = {}; +try { + const res = await fetch(process.env.KIRA_CONTRIBUTORS_URL || "https://kira-production-500e.up.railway.app/contributors.json", { signal: AbortSignal.timeout(10000) }); + if (!res.ok) throw new Error(`${res.status} from Kira`); + kiraCredit = await res.json(); +} catch (e) { + console.warn(`hub: contributors' Discord names: ${e.message}`); +} + // --- The parity table ------------------------------------------------------------------ const status = section(readme, "Project status") ?? ""; @@ -332,7 +344,10 @@ const values = { HUB_BOARD: hubLive.length ? boardHtml(board, roadmap) : `

    The board could not be loaded here.

    `, HUB_BOARD_FILTER: boardFilterHtml(board, roadmap), HUB_JOURNAL: journalHtml(journal, roadmap) || unavailable, - HUB_DATA: JSON.stringify({ roadmap, live: [...hubLinked.values()] }).replace(/ { + try { + return JSON.parse(localStorage.getItem(key)) ?? fallback; + } catch { + return fallback; + } +}; +const save = (key, value) => { + try { + localStorage.setItem(key, JSON.stringify(value)); + } catch {} +}; +const post = (path, body) => fetch(`${data.api}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + +// This browser's random id (one vote per item per browser) and the items it voted for. Nothing else identifies it. +function voter() { + let id = saved("hub:voter", ""); + if (typeof id !== "string" || id.length < 16) { + id = crypto.randomUUID ? crypto.randomUUID() : [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, "0")).join(""); + save("hub:voter", id); + } + return id; +} +const mine = new Set(saved("hub:voted", [])); +let counts = null; // { item: votes } once the server answered; until then the buttons stay hidden + +function showVotes() { + if (!counts) return; + for (const button of document.querySelectorAll("[data-vote]")) { + const id = button.dataset.vote; + button.hidden = false; + button.setAttribute("aria-pressed", String(mine.has(id))); + button.querySelector(".hub-vote-label").textContent = mine.has(id) ? "Wanted" : "Want it"; + button.querySelector("[data-votes]").textContent = counts[id] ? String(counts[id]) : ""; + } +} + +async function vote(id) { + const up = !mine.has(id); + const apply = (on, step) => { + if (on) mine.add(id); + else mine.delete(id); + counts[id] = Math.max(0, (counts[id] || 0) + step); + save("hub:voted", [...mine]); + showVotes(); + }; + apply(up, up ? 1 : -1); + try { + const res = await post("/hub/vote", { item: id, voter: voter(), up }); + if (!res.ok) throw new Error(res.status); + counts[id] = (await res.json()).votes; + showVotes(); + } catch { + apply(!up, up ? -1 : 1); + } +} +document.addEventListener("click", (e) => { + const button = e.target.closest("[data-vote]"); + if (button && counts) vote(button.dataset.vote); +}); + +const LABELS = { title: "the title", did: "what you did", happened: "what happened", expected: "what you expected", version: "the version", system: "OS, CPU, GPU", text: "your idea", name: "your name" }; +// The server's answer in words: "did: 3 to 2000 characters" becomes "Check what you did: 3 to 2000 characters." +function trouble(code, answer) { + if (code === 429) return "Too many sent from your connection: try again in a few minutes."; + const said = typeof answer.error === "string" ? answer.error : ""; + const field = said.match(/^(\w+): (.+)$/); + if (code === 400 && field) return `Check ${LABELS[field[1]] || field[1]}: ${field[2]}.`; + return said ? `${said[0].toUpperCase()}${said.slice(1)}.` : "That didn't go through: try again in a moment."; +} + +function setUpForm(form, path, thanks) { + const status = form.querySelector("[data-status]"); + form.hidden = false; + form.parentElement.querySelector("[data-closed]").hidden = true; + form.addEventListener("submit", async (e) => { + e.preventDefault(); + if (!form.reportValidity()) return; + const button = form.querySelector('[type="submit"]'); + button.disabled = true; + status.textContent = "Sending…"; + try { + const res = await post(path, Object.fromEntries(new FormData(form))); + const answer = await res.json().catch(() => ({})); + if (res.ok) { + thanks(status, answer); + // A new report starts with the version filled in again; the name stays for the next one. + for (const field of form.querySelectorAll("textarea, input:not([name='version']):not([name='name'])")) field.value = ""; + } else status.textContent = trouble(res.status, answer); + } catch { + status.textContent = "Couldn't reach the server: try again, or use GitHub or Discord."; + } + button.disabled = false; + }); +} + +// The forms and the votes show once the server answers; without it the page points to GitHub and Discord. +async function connect() { + try { + // Revalidated: the server keeps the counts a minute, a browser's copy would miss this browser's own vote. + const res = await fetch(`${data.api}/hub/votes`, { cache: "no-cache" }); + if (!res.ok) return; + counts = (await res.json()).votes || {}; + } catch { + return; + } + showVotes(); + setUpForm(document.querySelector('[data-form="report"]'), "/hub/report", (status, answer) => { + const issue = typeof answer.issue === "string" && answer.issue.match(/^https:\/\/github\.com\/ludovic111\/horizon\/issues\/(\d+)$/); + status.innerHTML = issue ? `Thanks! It's issue #${issue[1]} on GitHub: follow it there.` : "Thanks! It will be on GitHub in a few minutes."; + }); + setUpForm(document.querySelector('[data-form="suggest"]'), "/hub/suggest", (status) => { + status.textContent = "Thanks! The maintainers read every suggestion."; + }); +} + setUpTheme(); setUpMenu(); +connect(); follow(); refresh().then(() => data.roadmap.items.some((i) => `#${i.id}` === location.hash) && follow()); diff --git a/website/src/hub.html b/website/src/hub.html index d4ba4600c..167ffc15e 100644 --- a/website/src/hub.html +++ b/website/src/hub.html @@ -90,7 +90,7 @@

    Take a task

    @@ -109,6 +109,41 @@
    +
    +

    Report a bug

    +

    One bug per report: something that breaks, or doesn't play like vanilla. It becomes an issue on GitHub, public, and you get its link to follow it. Search the open bugs first.

    + +

    Report it on GitHub or in #horizon-bugs on Discord, where Kira turns your post into an issue.

    +
    +
    +

    Suggest something

    +

    An idea for Horizon, or about something on the roadmap. The maintainers read every one, and the good ones become roadmap items. Nothing you send here is published.

    + +

    Post it in #horizon-ideas on Discord, or send it to Kira with /suggest.

    +

    The rules

      @@ -119,6 +154,12 @@

    The contributing guideCONTRIBUTING.md

    +
    +

    Contributors

    +

    Everyone with commits in Horizon. On Discord, /link-github <your login> credit:True adds your Discord name next to yours.

    +
      {{HUB_CREDIT}}
    +

    All contributors on GitHub

    +

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    diff --git a/website/src/hub.js b/website/src/hub.js index d293b7250..f11668d8c 100644 --- a/website/src/hub.js +++ b/website/src/hub.js @@ -6,6 +6,7 @@ import { escape, inline } from "./markdown.js"; import { parts, plainItem, sections } from "./releases.js"; import { isGame, isLauncher } from "./versions.js"; +import { avatar } from "./contributors.js"; export const REPO = "ludovic111/horizon"; const issueUrl = (n) => `https://github.com/${REPO}/issues/${n}`; @@ -85,11 +86,16 @@ export function progress(item, live) { const areaName = (roadmap, id) => roadmap.areas.find((a) => a.id === id)?.name || id; +// An item's vote button: hidden until the page has the counts from the hub's server (hub-page.js). +export function voteHtml(item) { + return ``; +} + export function itemHtml(item, roadmap, live) { const done = item.status === "shipped"; const state = done ? "" : progress(item, live); return `
    -

    ${escape(areaName(roadmap, item.area))}${done ? `${escape(item.shipped_in)}` : ""}${item.ongoing ? `Ongoing` : ""}

    +

    ${escape(areaName(roadmap, item.area))}${done ? `${escape(item.shipped_in)}` : ""}${item.ongoing ? `Ongoing` : ""}${done ? "" : voteHtml(item)}

    ${escape(item.title)}

    ${inline(item.plain)}

    ${devHtml(item)}

    @@ -160,7 +166,7 @@ export function overviewHtml(roadmap, live = new Map()) {

    How to help

    ${inline(o.help_plain)}

    ${inline(o.help_dev)}

    -

    ContributeHelp wanted

    +

    ContributeHelp wantedReport a bugSuggest something

    `; } @@ -418,3 +424,34 @@ export function journalHtml(entries, roadmap) { }) .join("\n"); } + +// --- Contribute: the suggestion form's items and the contributors ------------------------------------------------ + +// The suggestion form's "About" choices: the items still to come. +export function suggestItemsHtml(roadmap) { + const open = roadmap.items.filter((i) => i.status !== "shipped"); + return [``] + .concat(open.map((i) => ``)) + .join(""); +} + +// The contributors, from GitHub (contributors.js's list), with the Discord name of those who linked their accounts +// on Kira and agreed to be credited (Kira's /contributors.json: { contributors: [{ github, discord }] }). +export function creditFrom(github, kira) { + const discord = new Map( + (Array.isArray(kira?.contributors) ? kira.contributors : []) + .filter((c) => c && typeof c.github === "string" && typeof c.discord === "string") + .map((c) => [c.github.toLowerCase(), c.discord]), + ); + return github.map((c) => ({ ...c, discord: discord.get(c.login.toLowerCase()) || "" })); +} + +export function creditHtml(list) { + return list + .map((c) => { + const src = avatar(c.avatar_url); + const count = `${c.contributions.toLocaleString("en-US")} ${c.contributions === 1 ? "commit" : "commits"}`; + return `
  • ${src ? `` : ``}${escape(c.login)}${count}${c.discord ? ` · ${escape(c.discord)} on Discord` : ""}
  • `; + }) + .join(""); +} diff --git a/website/src/hub.test.mjs b/website/src/hub.test.mjs index d688489e9..4213d8a87 100644 --- a/website/src/hub.test.mjs +++ b/website/src/hub.test.mjs @@ -1,7 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; -import { boardFrom, boardHtml, fixesIn, itemOf, journalFrom, journalHtml, journalJson, overviewHtml, progress, roadmapHtml, slimIssue } from "./hub.js"; +import { boardFrom, boardHtml, creditFrom, creditHtml, fixesIn, itemOf, journalFrom, journalHtml, journalJson, overviewHtml, progress, roadmapHtml, slimIssue, suggestItemsHtml } from "./hub.js"; const roadmap = JSON.parse(readFileSync(new URL("../data/roadmap.json", import.meta.url), "utf8")); @@ -137,3 +137,23 @@ test("journal.json is the flat feed Kira reads: merges, releases, shipped items, assert.match(e.url, /^https:\/\/(github\.com|playhorizon\.dev)\//, e.id); } }); + +test("items still to come take votes and suggestions; shipped ones don't", () => { + const html = roadmapHtml(roadmap); + for (const item of roadmap.items) { + assert.equal(html.includes(`data-vote="${item.id}"`), item.status !== "shipped", item.id); + assert.equal(suggestItemsHtml(roadmap).includes(`value="${item.id}"`), item.status !== "shipped", item.id); + } + // Hidden until the hub's server answers. + assert.ok(html.includes('aria-pressed="false" hidden>')); +}); + +test("the contributors carry the Discord name of those who agreed on Kira", () => { + const github = [{ login: "Alex", html_url: "https://github.com/Alex", avatar_url: "", contributions: 3 }, { login: "sam", html_url: "https://github.com/sam", avatar_url: "", contributions: 1 }]; + const kira = { contributors: [{ github: "alex", discord: "Alex " }, { github: 5 }, null] }; + const credit = creditFrom(github, kira); + assert.deepEqual(credit.map((c) => c.discord), ["Alex ", ""]); + const html = creditHtml(credit); + assert.ok(html.includes("3 commits · Alex <b> on Discord") && html.includes("1 commit")); + assert.deepEqual(creditFrom(github, "not json").map((c) => c.discord), ["", ""]); +}); diff --git a/website/src/style.css b/website/src/style.css index f32e24a30..1a23e79c8 100644 --- a/website/src/style.css +++ b/website/src/style.css @@ -645,7 +645,7 @@ code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--ou /* Releases: a filter, then every release as a panel that opens. */ .release-filter { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 32px; } -.release-filter .button[aria-pressed="true"], .hub-detail .button[aria-pressed="true"] { background: var(--face); color: var(--on-face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--face-lip); } +.release-filter .button[aria-pressed="true"], .hub-detail .button[aria-pressed="true"], .button.hub-vote[aria-pressed="true"] { background: var(--face); color: var(--on-face); box-shadow: inset 0 var(--block-bevel) 0 var(--face-bevel), inset 0 calc(-1 * var(--block-lip)) 0 var(--face-lip); } .release-count { margin: 16px 0 12px; } .release-list { display: grid; gap: 8px; } .release-list .release + .release { margin-top: 0; } @@ -826,3 +826,26 @@ code { border-radius: 0; background: var(--well); box-shadow: 0 0 0 1px var(--ou .hub-rows .row > a { grid-template-columns: var(--index) minmax(0, 1fr); } .hub-rows .row-meta { grid-column: 2; text-align: left; } } + +/* --- Hub: votes, the report and suggestion forms, the contributors ---------------------- */ +.hub-vote { margin-left: auto; } +.hub-vote-count { margin-left: -2px; } +.hub-vote-count:empty { display: none; } +.hub-form { display: grid; gap: 16px; max-width: 46rem; margin-top: 8px; } +.hub-form-pair { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } +.hub-field { display: grid; gap: 6px; font-size: var(--text-label); color: var(--ink-soft); } +.hub-field input, .hub-field textarea, .hub-field select { + width: 100%; min-height: 36px; padding: 8px 10px; font: var(--text-ui) / 1.4 var(--font); color: var(--ink); + background: var(--well); border: 0; box-shadow: 0 0 0 var(--block-outline) var(--outline); +} +.hub-field textarea { resize: vertical; } +.hub-field input:focus-visible, .hub-field textarea:focus-visible, .hub-field select:focus-visible { outline: 1px solid var(--accent); outline-offset: 2px; } +.hub-field input::placeholder, .hub-field textarea::placeholder { color: var(--muted); } +.hub-trap { position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden; } +.hub-form-foot { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; } +.hub-form-foot [data-status] { color: var(--ink); } +.hub-form-foot .button:disabled { opacity: 0.4; cursor: default; } +.hub-form-closed { color: var(--ink-soft); } +@media (max-width: 720px) { + .hub-form-pair { grid-template-columns: minmax(0, 1fr); } +} From 818b9638ed1a737d8ef09c16a3108215fc1d588e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:15:16 +0100 Subject: [PATCH 18/23] CONTRIBUTING.md and docs/README.md point to the hub Where to start is playhorizon.dev/hub: the roadmap, the work board, good first tasks and the forms; roadmap PRs carry their roadmap: label, ideas go to the suggestion queue and issues are for bugs. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 5 +++++ docs/README.md | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e6e959186..21951c083 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,6 +7,11 @@ welcome on [Discord](https://discord.gg/HcTeMZxe5E). This repository holds the game, the launcher and the website, plus the tools, tests and docs that build, check and release them. Anything else (videos, Discord and other community material) lives elsewhere. +**Where to start: [playhorizon.dev/hub](https://playhorizon.dev/hub).** It shows what is being done now and next +([ROADMAP.md](ROADMAP.md) in the repository), the work board, good first tasks, and the forms to report a bug or +suggest something. A pull request for a roadmap item carries its `roadmap:` label; ideas go to the suggestion +queue (the hub, or `/suggest` on Discord) rather than to issues, which are for bugs. + ## Build it You need Rust (stable), Python 3.10+, JDK 25, and on Linux the ALSA and udev headers (`libasound2-dev libudev-dev`). diff --git a/docs/README.md b/docs/README.md index 1450ba388..f946ee10b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,6 +1,6 @@ # Horizon documentation -To play, use [the launcher](../launcher/README.md); the project site is [playhorizon.dev](https://playhorizon.dev). These pages are for developers. +To play, use [the launcher](../launcher/README.md); the project site is [playhorizon.dev](https://playhorizon.dev). These pages are for developers. What is being done now and next, the work board and how to help: [the hub](https://playhorizon.dev/hub) ([ROADMAP.md](../ROADMAP.md), [roadmap/README.md](../roadmap/README.md) for keeping it current). ## Build and run From a6f951e126f2dc210aa278531790334ff655e10c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:22:19 +0100 Subject: [PATCH 19/23] Website: Make a mod, the full guide from the first line to the registry Six pages under a "Make a mod" group of the docs: set up and see a mod in the game (the launcher's Game arguments or cargo horizon-mod run), the manifest and every capability, the hooks and calls with a worked example (Playtime, built and checked), content mods, testing and check, and publishing (minisign signing, the submit form, review, updates). /mods, the submit page, the docs index, Mods and data packs and the Mod API link to it. Co-Authored-By: Claude Opus 5.5 --- docs/api/mods.md | 3 + website/build.mjs | 2 +- website/docs/content-mods.md | 114 ++++++++++++++++++++ website/docs/index.md | 1 + website/docs/make-a-mod.md | 88 ++++++++++++++++ website/docs/mod-code.md | 190 ++++++++++++++++++++++++++++++++++ website/docs/mod-manifest.md | 60 +++++++++++ website/docs/mods.md | 8 +- website/docs/nav.json | 1 + website/docs/publish-a-mod.md | 57 ++++++++++ website/docs/test-a-mod.md | 59 +++++++++++ website/src/mods.js | 1 + 12 files changed, 580 insertions(+), 4 deletions(-) create mode 100644 website/docs/content-mods.md create mode 100644 website/docs/make-a-mod.md create mode 100644 website/docs/mod-code.md create mode 100644 website/docs/mod-manifest.md create mode 100644 website/docs/publish-a-mod.md create mode 100644 website/docs/test-a-mod.md diff --git a/docs/api/mods.md b/docs/api/mods.md index bec03e84e..3e6108c70 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -24,6 +24,9 @@ the player before the mod is turned on, and checked against the component's real ## Guide +The step-by-step guide, from installing the tools to publishing on the registry, is +[Make a mod](https://playhorizon.dev/docs/make-a-mod) on the website. In short: + 1. `rustup target add wasm32-unknown-unknown`, `cargo install --git https://github.com/ludovic111/horizon cargo-horizon-mod`, then `cargo horizon-mod new my-mod` ([Making a mod](../mods.md#making-a-mod)). 2. Implement `Mod` for your type, list the capabilities you import in `horizon-mod.toml` diff --git a/website/build.mjs b/website/build.mjs index 4045297fb..d92f452ed 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -411,7 +411,7 @@ const modsTemplate = await readFile(join(site, "src", "mods.html"), "utf8"); const modsList = `

    ModsMade for Horizon, reviewed

    Horizon mods

    Mods, modpacks and resource packs made for Horizon. Each one was reviewed before it was listed, and the launcher checks every file before it installs it. Mods run in a sandbox and can only do what their page says.

    -

    Submit yours Make a mod

    +

    Submit yours Make a mod

    diff --git a/website/docs/content-mods.md b/website/docs/content-mods.md new file mode 100644 index 000000000..1ad8cd5fb --- /dev/null +++ b/website/docs/content-mods.md @@ -0,0 +1,114 @@ +# Content mods + +A content mod adds blocks and items to the game with data files only: no Rust, no compiler. Each new block or item copies a vanilla one (its template) and changes what differs, and comes with its recipes, loot table, tags, model, textures and name, in the same formats as vanilla's data packs and resource packs. + +## What a content mod is + +A folder (while you work on it) or a `.hmod` zip (to share it) holding a manifest, `assets/` and `data/`. This is the SDK's [`ruby-content`](https://github.com/ludovic111/horizon/tree/main/crates/horizon-mod-sdk/examples/ruby-content) example, a ruby gem and a block of ruby: + +``` +ruby/ +├── horizon-mod.toml +├── data/ruby/horizon/block/ruby_block.json the block: a template and what differs +├── data/ruby/horizon/item/ruby.json the item +├── data/ruby/recipe/ruby_block.json recipes, as in a data pack +├── data/ruby/recipe/ruby_from_ruby_block.json +├── data/ruby/loot_table/blocks/ruby_block.json what the block drops +├── data/minecraft/tags/block/mineable/pickaxe.json added to vanilla's tags +├── data/minecraft/tags/block/needs_iron_tool.json +├── assets/ruby/blockstates/ruby_block.json models and textures, as in a resource pack +├── assets/ruby/models/block/ruby_block.json +├── assets/ruby/models/item/ruby.json +├── assets/ruby/items/ruby.json +├── assets/ruby/items/ruby_block.json +├── assets/ruby/textures/block/ruby_block.png +├── assets/ruby/textures/item/ruby.png +└── assets/ruby/lang/en_us.json the names players see +``` + +Its manifest asks for API `0.2` and the `registries` capability. It has no code, so it needs no `Cargo.toml` and no `mod.wasm`: + +```toml +id = "ruby" +name = "Ruby" +version = "0.1.0" +description = "A ruby gem and a block of ruby" +authors = ["You"] +api = "0.2" +side = "both" +capabilities = ["registries"] +``` + +## Blocks + +A block is a file `data//horizon/block/.json`. It becomes the block `:`, with the template's behaviour, states and shapes: + +```json +{ + "template": "minecraft:iron_block", + "properties": { "hardness": 4.0, "light": 3, "sounds": "minecraft:amethyst_block", "map_color": 28 } +} +``` + +| Key | Meaning | +| --- | --- | +| `template` | The vanilla block it copies, such as `minecraft:iron_block`, `minecraft:oak_door` or `minecraft:diamond_ore`. A door copies a door's states and shape, an ore an ore's. | +| `properties.hardness` | How long it takes to mine (vanilla's destroy time; `-1` cannot be broken). | +| `properties.explosion_resistance` | How well it stands up to explosions. | +| `properties.light` | The light it gives, 0 to 15. | +| `properties.requires_tool` | `true`: it drops nothing unless mined with the right tool (the tags say which). | +| `properties.friction` | How slippery it is (ice is `0.98`). | +| `properties.map_color` | Its colour on maps, a vanilla map colour id from 0 to 61. | +| `properties.sounds` | A vanilla block whose sounds it uses. | +| `item` | `false` for a block with no item. By default the block gets an item of the same id. | + +Every property you leave out is the template's. + +## Items + +An item is a file `data//horizon/item/.json`, copying a vanilla item: + +```json +{ "template": "minecraft:diamond", "rarity": "uncommon" } +``` + +It may change `max_stack_size` (1 to 99) and `rarity` (`common`, `uncommon`, `rare` or `epic`, the colour of its name). + +## Recipes, loot, tags, models and names + +Everything else uses vanilla 26.3's own formats, so the [Minecraft Wiki's](https://minecraft.wiki/w/Data_pack) pages on data packs and resource packs apply: + +- **Recipes** in `data//recipe/`, **loot tables** in `data//loot_table/`. +- **Tags**: your own in `data//tags/`. To add to vanilla's (which pickaxe mines the block, for example), put a tag file in `data/minecraft/tags/`; to add to the convention tags NeoForge and Fabric mods share, in `data/c/tags/`. They add to the tag as a data pack does; `"replace": true` drops what came before it, and the log says so. +- **Block states, models, item models and textures** in `assets//`, as in a resource pack. Models can use vanilla's parents, such as `minecraft:block/cube_all`. +- **Names** in `assets//lang/en_us.json`: `"block.ruby.ruby_block": "Block of Ruby"`, `"item.ruby.ruby": "Ruby"`. + +**Structures.** A content mod can also carry structures, template pools and structure sets in its namespace, and add its own pieces to vanilla's villages or to another mod's pools. The [mod design page](https://github.com/ludovic111/horizon/blob/main/docs/mods.md#content-mods-api-02) has the details. + +## Namespaces + +Your files go under your mod's id (`assets/ruby/`, `data/ruby/`), plus vanilla's and the convention tags (`data/minecraft/tags/`, `data/c/tags/`). Tags are the only files a mod may put under `minecraft`. + +A mod made from a Java mod whose files use other names lists them in its manifest: `namespaces = ["kaisyn", "towns_and_towers"]`. A listed namespace is the mod's own, as its id is, but blocks and items are still declared under `data//horizon/`. `minecraft`, `c` and `horizon` can't be listed, and two mods that are on can't own the same namespace: the game keeps the first and logs the clash. + +## Limits + +- A mod's files use vanilla's resource-name characters: at most 65,536 files, 16 MiB each and 512 MiB in all. +- A file the game can't read (a block model that doesn't parse, a recipe with a typo) is logged and skipped, as vanilla does: the rest of the mod still loads. Read the log while you work. +- Unknown keys in a block or item file are refused, and the mod stays off with the reason on its row. +- Content mods work in single player today. Playing them together on a server is planned. + +## Try it and share it + +While you work, give the game the folder as a dev mod ([how](/docs/make-a-mod#see-it-in-the-game)): `--dev-mod "/path/to/ruby"`. The first start with a new set of mods takes a little longer while the game adds their content to its tables; after a change to the files, start the game again. + +To share it, zip the folder's contents, with `horizon-mod.toml` at the top of the zip, and name the file `.hmod`: + +```sh +cd ruby +zip -r ../ruby.hmod horizon-mod.toml assets data +``` + +Players put that file in their `horizon-mods` folder and turn it on in **Options, Mods...**. The registry doesn't take content-only mods yet: its checks (`cargo horizon-mod check`) expect code in the file. That is coming next. + +Next: [test it](/docs/test-a-mod). diff --git a/website/docs/index.md b/website/docs/index.md index 2b16c4db9..24f969840 100644 --- a/website/docs/index.md +++ b/website/docs/index.md @@ -30,4 +30,5 @@ There is no build for Intel Macs, 32-bit systems, or ARM Linux and Windows. The - **Playing:** [install and first launch](/docs/install), [settings worth knowing](/docs/settings), [multiplayer](/docs/multiplayer) and [what to do when something breaks](/docs/troubleshooting). - **Hosting:** [host a server](/docs/hosting), from the launcher or the command line. - **Going further:** [modpacks](/docs/modpacks), [mods and data packs](/docs/mods) and [performance](/docs/performance). +- **Making mods:** [make a mod](/docs/make-a-mod), from the first line of code to the registry, and the [Mod API](/docs/api/mods). - **Helping out:** [contribute](/docs/contributing) and the [FAQ](/docs/faq). diff --git a/website/docs/make-a-mod.md b/website/docs/make-a-mod.md new file mode 100644 index 000000000..94c3deca2 --- /dev/null +++ b/website/docs/make-a-mod.md @@ -0,0 +1,88 @@ +# Make a mod + +This guide takes you from nothing to a mod that other players can install from [playhorizon.dev/mods](/mods). You write the mod in Rust. It is compiled to WebAssembly and runs in a sandbox, so a player can see what it may do before turning it on. You need no Minecraft modding experience. + +## The path + +1. **Set up** (this page): install Rust and `cargo horizon-mod`, make your first mod and see it in the game. +2. **[The manifest and capabilities](/docs/mod-manifest)**: the file that names your mod and lists what it may do. +3. **[Write the code](/docs/mod-code)**: the hooks the game calls, what your code can call, and a worked example. +4. **[Content mods](/docs/content-mods)**: blocks, items, recipes and textures from data files, with no code at all. +5. **[Test it](/docs/test-a-mod)**: unit tests, the game's dev mode and the registry's own checks. +6. **[Publish it](/docs/publish-a-mod)**: package, sign and submit it to the registry. + +The [Mod API](/docs/api/mods) lists everything a mod can do today, and its [reference](/docs/api/mods-reference) has every function and type. + +## What a mod can do today + +- **Client mods** run in the player's game. They read what the F3 screen shows (position, facing, health, food, dimension, the time), draw a text panel on the screen, show chat lines only that player sees, add chat commands, and keep small files of their own. They work in single player and on any server, and a server cannot see them. +- **Content mods** add blocks and items copied from vanilla templates, with their recipes, loot tables, tags, models, textures and names. They need no code. +- **Server mods** (rules, world events, server commands) are being built. The [Mod API](/docs/api/mods#not-there-yet) says what comes next. + +A Horizon mod is not a Java mod. Fabric, NeoForge and Forge jars don't run in Horizon, and Horizon mods don't run in Java Minecraft. + +## Install the tools + +You need [Rust](https://rustup.rs) (the stable toolchain), its WebAssembly target and `cargo horizon-mod`, the tool that makes, builds and checks mods. On Windows, macOS or Linux: + +```sh +rustup target add wasm32-unknown-unknown +cargo install --git https://github.com/ludovic111/horizon cargo-horizon-mod +``` + +The second command builds the tool from source, which takes a few minutes the first time. Run it again later to update the tool. + +You also need Horizon itself, installed with the launcher ([Install](/docs/install)), and prepared at least once so the game has its files. + +## Make your first mod + +```sh +cargo horizon-mod new my-mod +cd my-mod +``` + +`new` makes a folder with a working mod in it: a `/hello` command that answers in chat. `--name "My Mod"` sets the name players see. The folder holds: + +``` +my-mod/ +├── Cargo.toml the Rust crate (a cdylib depending on horizon-mod-sdk) +├── horizon-mod.toml the manifest: id, name, version, what the mod may do +├── .gitignore +└── src/lib.rs the code +``` + +Build it: + +```sh +cargo horizon-mod build +``` + +This compiles the crate, checks that the code uses nothing its manifest doesn't declare, and writes `target/horizon-mod/my_mod.hmod`. A `.hmod` is a zip file holding the manifest and the compiled code (`mod.wasm`). It is the one file you give players: the same file runs on Windows, macOS and Linux. + +## See it in the game + +A **dev mod** is a mod the game loads from a path you give it. It is always on, and the game looks at its file once a second: build again and the game reloads it, saying "Mods reloaded" in chat. Its memory starts over; what it saved to its storage stays. + +**From the launcher.** Open the launcher's **Settings** and put this in **Game arguments**, with the full path to your file: + +``` +--dev-mod "/path/to/my-mod/target/horizon-mod/my_mod.hmod" +``` + +Then press **Play**, open a world and type `/hello world` in chat. Leave the setting there while you work on the mod, and clear it when you are done. The launcher's command line does the same: `horizon-launcher play --arg --dev-mod --arg /path/to/my_mod.hmod`. + +**With `cargo horizon-mod run`.** If you have a `horizon-client` you built from source, `cargo horizon-mod run` builds the mod and starts that game with it. It looks for `horizon-client` on your `PATH`, or takes `--game ` or the `HORIZON_CLIENT` variable; anything after `--` goes to the game: + +```sh +cargo horizon-mod run --game ../horizon/target/fast/horizon-client -- --resources ../horizon/.local/horizon-client/26.3 +``` + +Either way, edit `src/lib.rs`, run `cargo horizon-mod build`, and the game picks up the new file. + +## Where things go + +- **Your mod's messages** go to the game log as `[mod my_mod] …` (the `logs/latest.log` file in the game folder), and the game prints them in its terminal too. +- **Mods players install** go in the `horizon-mods` folder of the game folder (Linux `~/.local/share/horizon`, macOS `~/Library/Application Support/horizon`, Windows `%APPDATA%\horizon`). **Options, Mods...** in the game lists them, each with what it may do and a switch. They start off. +- **A mod that fails** to load, or that breaks while running, is switched off with the reason in red on its row of the Mods screen. It never takes the game down with it. + +Next: [the manifest and capabilities](/docs/mod-manifest). diff --git a/website/docs/mod-code.md b/website/docs/mod-code.md new file mode 100644 index 000000000..42cc6f04b --- /dev/null +++ b/website/docs/mod-code.md @@ -0,0 +1,190 @@ +# Write the code + +A mod is a Rust type that implements the `Mod` trait from `horizon-mod-sdk`. The game calls its methods, the hooks, at fixed points, and the mod calls back into the game through the parts of the API its capabilities allow. This page explains both, then builds a complete mod step by step. + +## The shape of a mod + +```rust +use horizon_mod_sdk::{Mod, Registration, chat}; + +struct Hello { + greeted: u32, +} + +impl Mod for Hello { + fn init() -> Result<(Self, Registration), String> { + Ok((Hello { greeted: 0 }, Registration::new().command("hello"))) + } + + fn command(&mut self, _name: &str, args: &str) -> Result, String> { + self.greeted += 1; + chat::show(&format!("Hello {args}! ({} so far)", self.greeted)); + Ok(None) + } +} + +horizon_mod_sdk::export_mod!(Hello); +``` + +- **The state lives in your type.** `init` creates it, and every hook gets `&mut self`. +- **`export_mod!`** connects the type to the game. A mod has exactly one. +- **The game calls only the hooks you ask for.** `init` returns a `Registration` that lists them. The other methods keep their default, empty bodies, and a hook you didn't ask for costs nothing. + +## Hooks + +| Hook | Ask for it with | When the game calls it | +| --- | --- | --- | +| `init() -> Result<(Self, Registration), String>` | always called | Once, when the mod loads. An `Err` keeps the mod off and shows the message on its row. | +| `tick(&mut self, tick: u64)` | `.on_tick()` | Every game tick while the player is in a world: 20 times a second. | +| `frame(&mut self, seconds: f32)` | `.on_frame()` | Every frame the game draws, with the time since the last one. | +| `command(&mut self, name: &str, args: &str)` | `.command("name")` | When the player types `/name …` in chat. `args` is everything after the name. | +| `chat(&mut self, text: &str)` | `.on_chat()` | For each chat line the player receives, as plain text. | + +**Commands.** Ask for as many as you like with `.command("…")`, without the slash. The chat box colours them and completes them with Tab, like vanilla's commands. Vanilla's names win: a mod can't take `/give`, and when two mods ask for the same name, the first one loaded keeps it. The game logs both cases. The return value says what happens next: + +- `Ok(None)`: nothing more. Use it when the mod already answered with `chat::show`. +- `Ok(Some(text))`: the game shows `text` to the player. +- `Err(text)`: the game shows `text` in red, as a failed command. + +**Prefer ticks to frames.** A tick happens 20 times a second whatever the frame rate. The HUD panel is kept by the game and drawn every frame for you, so most mods never need `frame`. + +## What your code can call + +Each module of the SDK is one part of the API, and each needs its capability in the manifest ([the list](/docs/mod-manifest#capabilities)): + +| Module | Capability | Calls | +| --- | --- | --- | +| `game` | `game-read` | `get_player() -> Option` (`x`, `y`, `z`, `yaw`, `pitch`, `health`, `food`, `dimension`), `get_clock() -> Option` (`game_time`, `day_time`). `None` outside a world. | +| `chat` | `chat` | `show(text)` | +| `hud` | `hud` | `set_panel(Corner, &[Line])` (`Line { text, color }`, colour as `0xRRGGBB`; corners `TopLeft`, `TopRight`, `BottomLeft`, `BottomRight`), `clear()` | +| `storage` | `storage` | `get(key) -> Option>`, `set(key, &[u8]) -> Result<(), String>`, `delete(key)` | +| `log` | none | `horizon_mod_sdk::info(text)` and `warn(text)`: lines in the game log | + +What the game reads for you (`game`) is a snapshot taken once a tick, and again before a command runs. It never changes in the middle of a call. Everything else is plain Rust: your own types, maths and text, and the crates you add to `Cargo.toml`, as long as they build for `wasm32-unknown-unknown` without the operating system (no files, threads, network or clock). + +## A worked example: Playtime + +This mod counts how long you play, shows it in the top-right corner, and keeps the count when you quit. `/playtime` says it in chat; `/playtime hide`, `show` and `reset` do what they say. It uses three capabilities (`hud`, `chat`, `storage`) and two hooks (`tick`, `command`). + +**1. Make the mod.** + +```sh +cargo horizon-mod new playtime --name "Playtime" +cd playtime +``` + +**2. Declare what it may do.** In `horizon-mod.toml`, set the description and the capabilities: + +```toml +description = "How long you have played, in a corner of the screen" +capabilities = ["hud", "chat", "storage"] +``` + +**3. The state and a helper.** Replace `src/lib.rs` with the code below, in parts. First the imports, the state and a function that turns ticks into hours and minutes. It touches no API, so an ordinary unit test can check it (step 7). + +```rust +use horizon_mod_sdk::{ + Mod, Registration, chat, + hud::{self, Corner, Line}, + storage, +}; + +/// Ticks played, kept across sessions in the mod's storage. +struct Playtime { + ticks: u64, + shown: bool, +} + +/// `1h 05m` from a number of ticks (20 a second). +fn format(ticks: u64) -> String { + let minutes = ticks / 20 / 60; + format!("{}h {:02}m", minutes / 60, minutes % 60) +} +``` + +**4. Saving and drawing.** `storage::set` writes bytes under a key of your choice; it can fail when the mod is over its quota, so the error goes to the log. The panel is set once and the game draws it until it changes, so redraw only when there is something new to show. + +```rust +impl Playtime { + fn save(&self) { + if let Err(e) = storage::set("ticks", &self.ticks.to_le_bytes()) { + horizon_mod_sdk::warn(&format!("could not save: {e}")); + } + } + + fn draw(&self) { + if self.shown { + let line = Line { text: format!("Played {}", format(self.ticks)), color: 0xFFFF55 }; + hud::set_panel(Corner::TopRight, &[line]); + } else { + hud::clear(); + } + } +} +``` + +**5. The hooks.** `init` reads what an earlier session saved, draws the panel and asks for one command and the tick hook. `tick` counts, and once a minute redraws and saves. `command` reads its arguments. + +```rust +impl Mod for Playtime { + fn init() -> Result<(Self, Registration), String> { + // What an earlier session saved, or 0 the first time. + let ticks = storage::get("ticks") + .and_then(|bytes| bytes.try_into().ok()) + .map_or(0, u64::from_le_bytes); + let state = Playtime { ticks, shown: true }; + state.draw(); + Ok((state, Registration::new().command("playtime").on_tick())) + } + + fn tick(&mut self, _tick: u64) { + self.ticks += 1; + // Once a minute: redraw the panel and save. + if self.ticks % (20 * 60) == 0 { + self.draw(); + self.save(); + } + } + + fn command(&mut self, _name: &str, args: &str) -> Result, String> { + match args.trim() { + "" => chat::show(&format!("You have played {}", format(self.ticks))), + "hide" | "show" => { + self.shown = args.trim() == "show"; + self.draw(); + } + "reset" => { + self.ticks = 0; + self.save(); + self.draw(); + return Ok(Some("Playtime reset".into())); + } + other => return Err(format!("Unknown option {other}: use hide, show or reset")), + } + Ok(None) + } +} + +horizon_mod_sdk::export_mod!(Playtime); +``` + +**6. Try it.** `cargo horizon-mod build`, then start the game with it as a dev mod ([how](/docs/make-a-mod#see-it-in-the-game)). Open a world: "Played 0h 00m" sits in the top-right corner and goes up each minute. Type `/playtime`, then `/playtime hide`. `/playtime foo` answers in red. Quit and come back: the count goes on from where it was. + +**7. Test the helper.** At the end of `src/lib.rs`: + +```rust +#[cfg(test)] +mod tests { + #[test] + fn formats_hours_and_minutes() { + assert_eq!(super::format(0), "0h 00m"); + assert_eq!(super::format(20 * 60 * 65), "1h 05m"); + } +} +``` + +`cargo test` runs it on your computer, with no game. [Test it](/docs/test-a-mod) covers the rest. + +**Where to go from here.** The SDK's examples are complete mods to read: [`coords-hud`](https://github.com/ludovic111/horizon/tree/main/crates/horizon-mod-sdk/examples/coords-hud) (coordinates, facing and the time on the HUD, `/where` and `/coords`) and [`ruby-content`](https://github.com/ludovic111/horizon/tree/main/crates/horizon-mod-sdk/examples/ruby-content) (a content mod). The [reference](/docs/api/mods-reference) lists every type and function, with its limits. + +Next: [content mods](/docs/content-mods), or straight to [testing](/docs/test-a-mod) if your mod has no blocks or items. diff --git a/website/docs/mod-manifest.md b/website/docs/mod-manifest.md new file mode 100644 index 000000000..c0e0e4b51 --- /dev/null +++ b/website/docs/mod-manifest.md @@ -0,0 +1,60 @@ +# The manifest and capabilities + +Every mod has a `horizon-mod.toml` at its root. It names the mod, says which version of the mod API it was made for, and lists its capabilities: what it may do. Players read that list before they turn the mod on, and the game holds the mod to it. + +## The manifest + +```toml +id = "playtime" +name = "Playtime" +version = "0.1.0" +description = "How long you have played, in a corner of the screen" +authors = ["You"] +api = "0.1" +side = "client" +capabilities = ["hud", "chat", "storage"] +``` + +| Key | What it is | +| --- | --- | +| `id` | The mod's id: 1 to 64 characters of `a-z`, `0-9` and `_`. It names the mod's setting, its log lines, its storage folder and, for content, its namespace. Keep it once you have published the mod. | +| `name` | The name players see. | +| `version` | Your mod's version, such as `0.1.0`. Each version you publish needs a new one. | +| `description` | One or two sentences for the Mods screen. | +| `authors` | A list of names. | +| `api` | The mod API line the mod was made for: `"0.1"` for code, `"0.2"` for content. The game refuses a line it doesn't serve, with a message that says so. | +| `side` | `"client"` for a mod that runs in the player's game. Content mods use `"both"`. | +| `capabilities` | What the mod may do: the list below. | +| `namespaces` | Content mods only: extra namespaces the mod's files use (see [Content mods](/docs/content-mods#namespaces)). | + +Unknown keys are refused, so a typo is an error, not a permission that silently does nothing. + +## Capabilities + +A capability is a part of the API the mod may use. Each one shows on the Mods screen as a sentence that starts with "May". Writing to the game log needs no capability. + +| Capability | The player reads | What the code can do | +| --- | --- | --- | +| `game-read` | May see your position, health and the time | `game::get_player()`: position, facing (yaw and pitch), health, food and dimension. `game::get_clock()`: the game time and the time of day. | +| `chat` | May show you chat messages | `chat::show(text)`: a chat line only this player sees, after the mod's name. At most 8 per call into the mod. | +| `hud` | May draw text on your screen | `hud::set_panel(corner, lines)` and `hud::clear()`: a panel of up to 16 coloured lines of 256 characters in one corner. The game keeps drawing it until you change it. | +| `storage` | May save its own settings to disk | `storage::get`, `set` and `delete`: small files in a folder of the mod's own. Up to 64 files and 4 MiB in all, and at most 1 MiB written per call. Keys are 1 to 64 characters of `a-z`, `0-9`, `_`, `.` and `-`. | +| `registries` | May add blocks and items to your worlds | Content mods: blocks and items from the mod's data files. No code. | + +Ask only for what the mod uses: players are more likely to turn on a mod that asks for little. + +**The game checks.** When you build, and again when a game loads the mod, the compiled code's imports are compared with the manifest. A mod whose code calls `chat::show` without `chat` in its capabilities is refused (`uses capability chat, missing from horizon-mod.toml`). The list players read is what the code can do, not a promise. + +## What no mod can do + +A mod runs in a WebAssembly sandbox. Whatever its capabilities: + +- It cannot open files (apart from its own storage), the network, other programs or the clock. +- It sees the game only through the snapshot the game gives it once a tick, and changes it only through the calls above. It cannot patch the game's code. +- It has 64 MiB of memory and a time budget for each call. A mod that runs past its budget, runs out of memory or crashes is switched off, with the reason on its row of the Mods screen. The game goes on. + +## API versions + +The mod API is versioned apart from the game. A mod made for API `0.1` keeps loading on every game that serves `0.1`, and new functions arrive as additions. A change that would break mods comes as a new line, served beside the old one for at least one release cycle. The [stability page](/docs/api/stability) has the whole policy, and the [Mod API's changelog](/docs/api/mods#changelog) what each line added. + +Next: [write the code](/docs/mod-code). diff --git a/website/docs/mods.md b/website/docs/mods.md index 77a1734fd..405c62976 100644 --- a/website/docs/mods.md +++ b/website/docs/mods.md @@ -6,7 +6,7 @@ Horizon has its own mod system, written for Horizon and not compatible with Java Horizon mods are written in Rust, compiled to WebAssembly and run in a sandbox. A mod can only do what it asks for and you allow, and a mod that crashes is switched off without taking the game down. -> **Early.** The mod system is new. There is no store for Horizon mods yet: they are files to put in a folder. The launcher's **Mods** page (see below) finds resource packs and modpacks, not `.hmod` mods. +> **Early.** The mod system is new. Reviewed mods are listed at [playhorizon.dev/mods](/mods), and any `.hmod` file can be put in the folder by hand. **Playing with mods** @@ -22,15 +22,17 @@ Horizon mods are written in Rust, compiled to WebAssembly and run in a sandbox. **Making a mod** +[Make a mod](/docs/make-a-mod) is the full guide: the tools, your first mod in the game, the manifest and capabilities, the code with a worked example, content mods, testing, and publishing on [the registry](/mods). In short: + ```sh rustup target add wasm32-unknown-unknown cargo install --git https://github.com/ludovic111/horizon cargo-horizon-mod cargo horizon-mod new my-mod cd my-mod -cargo horizon-mod run +cargo horizon-mod build ``` -`run` builds the mod and starts the game with it. After an edit, `cargo horizon-mod build` rebuilds it and the running game reloads it. The [Mod API](/docs/api/mods) lists what a mod can do today, its [reference](/docs/api/mods-reference), the [ways in](/docs/api/mods#ways-in) (Rust today, Lua scripts planned) and what comes next; the full guide, with the manifest and the runtime, is [docs/mods.md](https://github.com/ludovic111/horizon/blob/main/docs/mods.md). Java mod jars don't run in Horizon: their code calls and patches Minecraft's Java classes, and Horizon has none. What carries over is the data and assets inside a jar ([modpacks](https://github.com/ludovic111/horizon/blob/main/docs/modpacks.md)). +The [Mod API](/docs/api/mods) lists what a mod can do today and what comes next, and its [reference](/docs/api/mods-reference) every function. Java mod jars don't run in Horizon: their code calls and patches Minecraft's Java classes, and Horizon has none. What carries over is the data and assets inside a jar ([modpacks](/docs/modpacks)). ## Finding resource packs and modpacks diff --git a/website/docs/nav.json b/website/docs/nav.json index 18eab69fd..76c06dc47 100644 --- a/website/docs/nav.json +++ b/website/docs/nav.json @@ -3,6 +3,7 @@ { "group": "Playing", "pages": ["settings", "multiplayer", "troubleshooting"] }, { "group": "Hosting", "pages": ["hosting"] }, { "group": "Going further", "pages": ["modpacks", "mods", "performance", "agents"] }, + { "group": "Make a mod", "pages": ["make-a-mod", "mod-manifest", "mod-code", "content-mods", "test-a-mod", "publish-a-mod"] }, { "group": "Build on Horizon", "pages": ["apis", "api", "api/stability"] }, { "group": "API reference", "pages": ["api/mods", "api/mods-reference", "api/mod-index", "api/server", "api/server-reference", "api/agent-control", "api/launcher", "api/data-formats", "api/shaders"] }, { "group": "Project", "pages": ["contributing", "faq"] } diff --git a/website/docs/publish-a-mod.md b/website/docs/publish-a-mod.md new file mode 100644 index 000000000..c24a77a2f --- /dev/null +++ b/website/docs/publish-a-mod.md @@ -0,0 +1,57 @@ +# Publish a mod + +Horizon's registry lists mods, modpacks and resource packs made for Horizon. Players find them at [playhorizon.dev/mods](/mods) and on the launcher's Mods page, which checks every file before it installs it. Each project is reviewed by a person before it is published. This page takes your mod from a file on your computer to the registry. + +## Before you submit + +1. **Choose a version.** Set `version` in `horizon-mod.toml` (such as `1.0.0`). Every version you publish needs a new one, and a published file never changes. +2. **Build it for release.** `cargo horizon-mod build` (release is the default; `--debug` is for quick local builds) writes `target/horizon-mod/.hmod`. That file is what you submit. +3. **Check it.** `cargo horizon-mod check target/horizon-mod/.hmod` must pass ([Test a mod](/docs/test-a-mod#check-it-as-the-registry-does)). +4. **Publish the source.** Put the mod's source in a public repository, under a licence that lets players use it (MIT, Apache-2.0, GPL and so on, as an [SPDX](https://spdx.org/licenses/) name). Reviewers read it, and the file must be built from it. + +## Sign it + +Signing is optional and recommended. When your project has a public key, every later version must be signed with the matching secret key, so nobody else can publish an update in your name, even with access to your GitHub account. + +Horizon uses [minisign](https://jedisct1.github.io/minisign/) signatures. Install minisign (`brew install minisign`, `scoop install minisign`, or your Linux distribution's package), then make a key pair once: + +```sh +minisign -G -p horizon-mods.pub -s horizon-mods.key +``` + +Keep `horizon-mods.key` and its password private and backed up: losing it means changing the project's key by hand, through the registry's maintainers. The public key is the last line of `horizon-mods.pub` (it starts with `RW`). + +Sign each file you publish, and check the signature as the registry will: + +```sh +minisign -S -s horizon-mods.key -m target/horizon-mod/playtime.hmod +cargo horizon-mod check target/horizon-mod/playtime.hmod --key "RW…your public key…" --signature target/horizon-mod/playtime.hmod.minisig +``` + +The report then says "signature verified". + +## Submit it + +Open [playhorizon.dev/mods/submit](/mods/submit) and sign in with GitHub. The page reads only your public profile. Then fill in: + +- **The file**: the kind (mod), the `.hmod`, its id (the manifest's `id`), its version, the Minecraft version (26.3) and what changed. +- **Its page**: the name, a one-line summary for the list, a description (Markdown), the authors, the licence, the source address and, optionally, a square PNG icon (at most 256 KiB). +- **Signature**: your public key (for a new project) and the file's `.minisig`. + +**Submit for review** checks the file again and opens a pull request in [ludovic111/horizon-mods](https://github.com/ludovic111/horizon-mods). It adds `mods/.toml`, with you as the project's owner. The repository's checks run the file in the sandbox and post their report on the pull request. + +## Review and publication + +A reviewer reads the pull request, your source and the checks' report. Questions and requests for changes come as comments on the pull request: answer them there, and submit a new version from the form when the file must change. + +When the reviewer merges it, the file becomes a release of horizon-mods within minutes, and the project gets its page at `playhorizon.dev/mods/` and shows in the launcher. The page lists what the mod may do, as the game's Mods screen does, with your source, licence and the file's SHA-256. + +## Updates + +An update is the same form with a new version: it adds the version to your project's entry. The project's owners publish updates without a reviewer's extra look, and if the project has a key, the new file must be signed with it. + +Without the form, you can open the pull request by hand: the [horizon-mods README](https://github.com/ludovic111/horizon-mods) says how. The registry's file formats are in [the mod index reference](/docs/api/mod-index). + +## Reports and takedowns + +Anyone can report a project from its page (**Report it**). A project that does harm is taken down: the launcher then refuses its files and turns installed copies off, telling players why. diff --git a/website/docs/test-a-mod.md b/website/docs/test-a-mod.md new file mode 100644 index 000000000..650810963 --- /dev/null +++ b/website/docs/test-a-mod.md @@ -0,0 +1,59 @@ +# Test a mod + +Three kinds of checks catch most mistakes before players see them: unit tests for your own logic, the game's dev mode for how the mod looks and feels, and `cargo horizon-mod check`, which runs the same checks as the registry. + +## Unit tests for your logic + +Code that doesn't call the game (formatting, maths, parsing a command's arguments) is ordinary Rust. Put it in plain functions and test it with `#[test]`, as the [Playtime example](/docs/mod-code#a-worked-example-playtime) does with its `format` function: + +```sh +cargo test +``` + +The tests run on your computer, with no game and no WebAssembly. Keeping the hooks thin and the logic in functions makes most of a mod testable this way. + +## In the game, as a dev mod + +Start the game with your mod as a dev mod ([how](/docs/make-a-mod#see-it-in-the-game)) and keep it running. After each edit: + +```sh +cargo horizon-mod build +``` + +The game sees the new file within a second, says "Mods reloaded" in chat and starts the mod over. What it saved with `storage` stays. Things to try each time: + +- Every command, with no arguments, with good ones and with wrong ones. An `Err` should say what to type instead. +- Leaving the world and opening another: `game::get_player()` is `None` on the title screen. +- Quitting and starting again, for a mod that saves. +- **Options, Mods...**: the mod's row lists what it may do. If it says the mod stopped, the reason is there. + +The game log (`logs/latest.log` in the game folder) has your mod's `info` and `warn` lines as `[mod ]`, and the reason when the game refused or stopped the mod. + +**Why a mod stops.** A mod that panics, runs past its time budget for one call (an endless loop, for example) or uses more than 64 MiB of memory is switched off. The rest of the game carries on. Fix the cause and build again: a dev mod starts over with the new file. + +## Check it as the registry does + +Before you publish, run what the registry runs on every submission: + +```sh +cargo horizon-mod check target/horizon-mod/playtime.hmod +``` + +``` +playtime 0.1.0 (mod, API 0.1, client) + 12424 bytes, SHA-256 6561…ac13, unsigned + may draw text on your screen + may show you chat messages + may save its own settings to disk + trial run: started, 40 ticks, 120 frames, a chat line, /playtime: ok +``` + +It reads the manifest, refuses code that uses a capability the manifest doesn't list, then plays the mod in the sandbox, as the game does: 40 ticks with a moving player, 120 frames, a chat line and each of its commands once with no arguments. The mod must start and must never crash or overrun its budget. It fails with the reason when one of those goes wrong. + +- `--json` prints the report as JSON, for scripts. +- `--key --signature .minisig` also checks your signature ([Publish](/docs/publish-a-mod#sign-it)). +- It checks modpacks (`.hpack`) and resource packs (`.zip`) too; `--kind mod|modpack|resourcepack` when the file's extension doesn't say which. + +A mod that passes `check` passes the registry's automatic checks. A person still reviews it (see [Publish](/docs/publish-a-mod)). + +Next: [publish it](/docs/publish-a-mod). diff --git a/website/src/mods.js b/website/src/mods.js index 4819af374..a597e2847 100644 --- a/website/src/mods.js +++ b/website/src/mods.js @@ -121,6 +121,7 @@ export function submitHtml() { return `

    ModsSubmit

    Submit to the registry

    A mod, a modpack of registry mods, or a resource pack made for Horizon. The form checks the file and opens a pull request; a reviewer reads it, its source and the checks' report, and merging publishes it to this site and the launcher.

    +

    First time? Publish a mod walks through building, checking and signing the file, and Make a mod starts from the beginning.

    The form needs JavaScript. You can also open a pull request by hand.

    From ba4cf45aacb5564ae04bce109e466c48dea9f2eb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:35:01 +0100 Subject: [PATCH 20/23] cargo horizon-mod: content mods (new --template content, build packs assets and data, check takes no code) - `new --template content`: a content mod with one block (Glowing Amethyst, copying vanilla's amethyst block) and its block state, model, item model, name, loot, recipe and pickaxe tag; `--template code` is the default. - `build` packs the mod's `assets/` and `data/` (read and checked as the game reads them) beside the component; a folder without `Cargo.toml` is a content mod and needs no compiler. - `check` takes a `.hmod` with no `mod.wasm`: "no code: content only, nothing to run" instead of the trial run, which refused it, so the registry can publish content mods. - The guide (content mods, make a mod) and docs/mods.md, docs/api/mods.md say so. Co-Authored-By: Claude Opus 5.5 --- crates/cargo-horizon-mod/src/check.rs | 16 +- crates/cargo-horizon-mod/src/main.rs | 168 +++++++++++++++--- .../template/content/block.json | 4 + .../template/content/blockstate.json | 5 + .../template/content/horizon-mod.toml | 10 ++ .../template/content/item.json | 3 + .../template/content/lang.json | 3 + .../template/content/loot.json | 11 ++ .../template/content/model.json | 4 + .../template/content/pickaxe.json | 3 + .../template/content/recipe.json | 6 + docs/api/mods.md | 3 +- docs/mods.md | 8 +- website/docs/content-mods.md | 20 ++- website/docs/make-a-mod.md | 2 +- 15 files changed, 233 insertions(+), 33 deletions(-) create mode 100644 crates/cargo-horizon-mod/template/content/block.json create mode 100644 crates/cargo-horizon-mod/template/content/blockstate.json create mode 100644 crates/cargo-horizon-mod/template/content/horizon-mod.toml create mode 100644 crates/cargo-horizon-mod/template/content/item.json create mode 100644 crates/cargo-horizon-mod/template/content/lang.json create mode 100644 crates/cargo-horizon-mod/template/content/loot.json create mode 100644 crates/cargo-horizon-mod/template/content/model.json create mode 100644 crates/cargo-horizon-mod/template/content/pickaxe.json create mode 100644 crates/cargo-horizon-mod/template/content/recipe.json diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index 0294bec98..8a25d1a24 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -21,6 +21,8 @@ pub struct Report { pub sha256: String, pub size: u64, pub signed: bool, + /// A mod has code to run (a content mod may have none). + pub code: bool, /// A mod's component imports. pub imports: Vec, /// A mod's commands, each run once. @@ -49,6 +51,7 @@ impl Report { "sha256": self.sha256, "size": self.size, "signed": self.signed, + "code": self.code, "imports": self.imports, "commands": self.commands, "output": self.output, @@ -87,7 +90,9 @@ impl Report { for r in &f.requires { out += &format!(" needs {} {} ({})\n", r.id, r.version, &r.sha256[..12]); } - if self.kind == Kind::Mod { + if self.kind == Kind::Mod && !self.code { + out += " no code: content only, nothing to run\n"; + } else if self.kind == Kind::Mod { let commands = if self.commands.is_empty() { String::new() } else { @@ -142,6 +147,7 @@ pub fn check( sha256: index::sha256_file(path)?, size, signed, + code: false, imports: Vec::new(), commands: Vec::new(), output: Vec::new(), @@ -153,10 +159,14 @@ pub fn check( } /// Runs a mod in the sandbox, as the game does, from a scratch copy so its -/// storage lands in a folder removed afterwards. +/// storage lands in a folder removed afterwards. A content mod has no code to +/// run: `inspect` already read its content as the game does. fn trial_run(path: &Path, report: &mut Report) -> Result<(), String> { let package = Package::read(path)?; - let wasm = package.wasm.as_deref().ok_or("the .hmod has no mod.wasm")?; + let Some(wasm) = package.wasm.as_deref() else { + return Ok(()); + }; + report.code = true; report.imports = component_imports(wasm)?; package .manifest diff --git a/crates/cargo-horizon-mod/src/main.rs b/crates/cargo-horizon-mod/src/main.rs index 925633930..a4585f680 100644 --- a/crates/cargo-horizon-mod/src/main.rs +++ b/crates/cargo-horizon-mod/src/main.rs @@ -1,14 +1,16 @@ //! `cargo horizon-mod`: make Horizon mods in Rust (`docs/mods.md`). //! -//! - `new [--name "Name"] [--sdk-path ]`: a mod crate from the template. -//! - `build [--debug]`: the `.hmod` in `target/horizon-mod/`. +//! - `new [--template code|content] [--name "Name"] [--sdk-path ]`: +//! a mod from a template: a Rust crate, or a content mod (no code). +//! - `build [--debug]`: the `.hmod` in `target/horizon-mod/`, with the mod's +//! `assets/` and `data/`; a folder without `Cargo.toml` is content only. //! - `run [--game ] [-- ]`: build, then play with //! the mod; run `build` again and the game reloads it. //! - `check [--json]`: what the registry checks of a submission //! (`.hmod`, `.hpack`, resource pack `.zip`), with a trial run for a mod. //! - `registry build|review|check|list`: the registry repository's CI. use horizon_mods::{ - Manifest, Package, + Capability, Content, Manifest, Package, manifest::{MANIFEST, component_imports, componentize}, }; mod check; @@ -36,7 +38,7 @@ fn main() -> ExitCode { Some("run") => run(&args[1..]), Some("check") => check(&args[1..]), Some("registry") => registry::main(&args[1..]), - _ => Err("usage: cargo horizon-mod new | build [--debug] | run [--game ] [-- ] | check [--kind ] [--key --signature ] [--json] | registry build|review|check|list".into()), + _ => Err("usage: cargo horizon-mod new [--template code|content] | build [--debug] | run [--game ] [-- ] | check [--kind ] [--key --signature ] [--json] | registry build|review|check|list".into()), }; match result { Ok(()) => ExitCode::SUCCESS, @@ -90,19 +92,68 @@ fn new(args: &[String]) -> Result<(), String> { .replace("{name}", &name) .replace("{sdk}", &sdk) }; - let files = [ + let code = [ ("Cargo.toml", include_str!("../template/Cargo.toml.in")), (MANIFEST, include_str!("../template/horizon-mod.toml")), ("src/lib.rs", include_str!("../template/src/lib.rs")), (".gitignore", include_str!("../template/gitignore")), ]; - for (file, text) in files { + // A block copying a vanilla one, with its model, name, loot, recipe and tag. + let content = [ + ( + MANIFEST, + include_str!("../template/content/horizon-mod.toml"), + ), + ( + "data/{id}/horizon/block/glowing_amethyst.json", + include_str!("../template/content/block.json"), + ), + ( + "assets/{id}/blockstates/glowing_amethyst.json", + include_str!("../template/content/blockstate.json"), + ), + ( + "assets/{id}/models/block/glowing_amethyst.json", + include_str!("../template/content/model.json"), + ), + ( + "assets/{id}/items/glowing_amethyst.json", + include_str!("../template/content/item.json"), + ), + ( + "assets/{id}/lang/en_us.json", + include_str!("../template/content/lang.json"), + ), + ( + "data/{id}/loot_table/blocks/glowing_amethyst.json", + include_str!("../template/content/loot.json"), + ), + ( + "data/{id}/recipe/glowing_amethyst.json", + include_str!("../template/content/recipe.json"), + ), + ( + "data/minecraft/tags/block/mineable/pickaxe.json", + include_str!("../template/content/pickaxe.json"), + ), + (".gitignore", include_str!("../template/gitignore")), + ]; + let files: &[(&str, &str)] = match flag(args, "--template").unwrap_or("code") { + "code" => &code, + "content" => &content, + other => return Err(format!("no template {other}: code or content")), + }; + for &(file, text) in files { + let file = fill(file); + let file = file.as_str(); let to = dir.join(file); std::fs::create_dir_all(to.parent().expect("a file in the mod")) .map_err(|e| e.to_string())?; std::fs::write(&to, fill(text)).map_err(|e| format!("{}: {e}", to.display()))?; } - Manifest::parse(&std::fs::read_to_string(dir.join(MANIFEST)).map_err(|e| e.to_string())?)?; + let manifest = + Manifest::parse(&std::fs::read_to_string(dir.join(MANIFEST)).map_err(|e| e.to_string())?)?; + Content::read(dir, &manifest)?; println!( "Created {} (mod id {id}). Next: cd {path} && cargo horizon-mod run", dir.display() @@ -110,14 +161,53 @@ fn new(args: &[String]) -> Result<(), String> { Ok(()) } -/// Builds the crate in the current folder and packs `target/horizon-mod/.hmod`. +/// Builds the mod in the current folder and packs `target/horizon-mod/.hmod`: +/// the manifest, the crate's component (none without a `Cargo.toml`: a +/// content mod) and the files in `assets/` and `data/`. fn build(release: bool) -> Result { - let manifest_text = std::fs::read_to_string(MANIFEST) + build_in(Path::new("."), release) +} + +fn build_in(root: &Path, release: bool) -> Result { + let manifest_text = std::fs::read_to_string(root.join(MANIFEST)) .map_err(|e| format!("{MANIFEST}: {e} (run this in a mod's folder)"))?; let manifest = Manifest::parse(&manifest_text)?; + let (wasm, target_dir) = if root.join("Cargo.toml").exists() { + let (wasm, target) = compile(root, release)?; + // The game refuses a component importing capabilities the manifest lacks. + manifest.check_imports(component_imports(&wasm)?.iter().map(String::as_str))?; + (Some(wasm), target) + } else if manifest.capabilities.contains(&Capability::Registries) { + (None, root.join("target")) + } else { + return Err(format!( + "no Cargo.toml: only a content mod (capability registries in {MANIFEST}) has no code" + )); + }; + // The same checks as the game's, and the files in the order it lists them. + let content = Content::read(root, &manifest)?; + let mut reader = content.reader()?; + let mut files = Vec::with_capacity(content.files.len()); + for name in &content.files { + files.push((name.as_str(), reader.read(name)?)); + } + let files: Vec<(&str, &[u8])> = files.iter().map(|(n, b)| (*n, b.as_slice())).collect(); + let dir = target_dir.join("horizon-mod"); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let path = dir.join(format!("{}.hmod", manifest.id)); + // Write then rename, so a running game never reads half a file. + let partial = path.with_extension("hmod.partial"); + let bytes = Package::write_files(&manifest_text, wasm.as_deref(), &files)?; + std::fs::write(&partial, bytes).map_err(|e| e.to_string())?; + std::fs::rename(&partial, &path).map_err(|e| e.to_string())?; + Ok(path) +} + +/// Builds the crate for WebAssembly: its component, and Cargo's target folder. +fn compile(root: &Path, release: bool) -> Result<(Vec, PathBuf), String> { let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()); let mut cmd = Command::new(cargo); - cmd.args([ + cmd.current_dir(root).args([ "build", "--lib", "--target", @@ -145,17 +235,8 @@ fn build(release: bool) -> Result { .rfind(|f| f.extension().is_some_and(|e| e == "wasm")) .ok_or("the build made no .wasm: is the crate a cdylib?")?; let wasm = componentize(&std::fs::read(&core).map_err(|e| e.to_string())?)?; - // The game refuses a component importing capabilities the manifest lacks. - manifest.check_imports(component_imports(&wasm)?.iter().map(String::as_str))?; - let target_dir = core.ancestors().nth(3).ok_or("unexpected target folder")?; - let dir = target_dir.join("horizon-mod"); - std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; - let path = dir.join(format!("{}.hmod", manifest.id)); - // Write then rename, so a running game never reads half a file. - let partial = path.with_extension("hmod.partial"); - std::fs::write(&partial, Package::write(&manifest_text, &wasm)?).map_err(|e| e.to_string())?; - std::fs::rename(&partial, &path).map_err(|e| e.to_string())?; - Ok(path) + let target = core.ancestors().nth(3).ok_or("unexpected target folder")?; + Ok((wasm, target.to_path_buf())) } /// `check `: the registry's checks of a submission, printed; fails @@ -237,4 +318,49 @@ mod tests { ); std::fs::remove_dir_all(&dir).unwrap(); } + + #[test] + fn the_content_template_builds_and_checks_with_no_code() { + let dir = std::env::temp_dir().join(format!("horizon-mod-content-{}", std::process::id())); + let path = dir.join("gems"); + let new_args = [ + path.display().to_string(), + "--template".into(), + "content".into(), + ]; + new(&new_args).unwrap(); + assert!(!path.join("Cargo.toml").exists()); + let hmod = build_in(&path, true).unwrap(); + assert_eq!(hmod, path.join("target/horizon-mod/gems.hmod")); + let package = Package::read(&hmod).unwrap(); + assert!(package.wasm.is_none()); + let content = Content::read(&hmod, &package.manifest).unwrap(); + assert!( + content + .files + .contains(&"data/gems/horizon/block/glowing_amethyst.json".into()) + ); + assert_eq!(content.files.len(), 8, "{:?}", content.files); + let report = check::check(&hmod, check::kind_of(&hmod).unwrap(), None, None).unwrap(); + assert!(!report.code); + assert!( + report.text().contains("no code: content only"), + "{}", + report.text() + ); + // Without registries, a mod needs code. + let manifest = std::fs::read_to_string(path.join(MANIFEST)).unwrap(); + let manifest = manifest.replace("[\"registries\"]", "[]"); + std::fs::write(path.join(MANIFEST), manifest).unwrap(); + assert!(build_in(&path, true).unwrap_err().contains("no Cargo.toml")); + assert!( + new(&[ + dir.join("x").display().to_string(), + "--template".into(), + "lua".into() + ]) + .is_err() + ); + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/cargo-horizon-mod/template/content/block.json b/crates/cargo-horizon-mod/template/content/block.json new file mode 100644 index 000000000..ea68a1a27 --- /dev/null +++ b/crates/cargo-horizon-mod/template/content/block.json @@ -0,0 +1,4 @@ +{ + "template": "minecraft:amethyst_block", + "properties": { "hardness": 2.0, "light": 7 } +} diff --git a/crates/cargo-horizon-mod/template/content/blockstate.json b/crates/cargo-horizon-mod/template/content/blockstate.json new file mode 100644 index 000000000..ea472666e --- /dev/null +++ b/crates/cargo-horizon-mod/template/content/blockstate.json @@ -0,0 +1,5 @@ +{ + "variants": { + "": { "model": "{id}:block/glowing_amethyst" } + } +} diff --git a/crates/cargo-horizon-mod/template/content/horizon-mod.toml b/crates/cargo-horizon-mod/template/content/horizon-mod.toml new file mode 100644 index 000000000..4f133a905 --- /dev/null +++ b/crates/cargo-horizon-mod/template/content/horizon-mod.toml @@ -0,0 +1,10 @@ +id = "{id}" +name = "{name}" +version = "0.1.0" +description = "" +authors = [] +# A content mod: blocks and items from data/ and assets/, no code (API 0.2). +api = "0.2" +side = "both" +# registries: "May add blocks and items to your worlds". +capabilities = ["registries"] diff --git a/crates/cargo-horizon-mod/template/content/item.json b/crates/cargo-horizon-mod/template/content/item.json new file mode 100644 index 000000000..411bc4499 --- /dev/null +++ b/crates/cargo-horizon-mod/template/content/item.json @@ -0,0 +1,3 @@ +{ + "model": { "type": "minecraft:model", "model": "{id}:block/glowing_amethyst" } +} diff --git a/crates/cargo-horizon-mod/template/content/lang.json b/crates/cargo-horizon-mod/template/content/lang.json new file mode 100644 index 000000000..74baddab8 --- /dev/null +++ b/crates/cargo-horizon-mod/template/content/lang.json @@ -0,0 +1,3 @@ +{ + "block.{id}.glowing_amethyst": "Glowing Amethyst" +} diff --git a/crates/cargo-horizon-mod/template/content/loot.json b/crates/cargo-horizon-mod/template/content/loot.json new file mode 100644 index 000000000..898111f1b --- /dev/null +++ b/crates/cargo-horizon-mod/template/content/loot.json @@ -0,0 +1,11 @@ +{ + "type": "minecraft:block", + "pools": [ + { + "condition": { "type": "minecraft:survives_explosion" }, + "entries": [{ "type": "minecraft:item", "name": "{id}:glowing_amethyst" }], + "rolls": 1 + } + ], + "random_sequence": "{id}:blocks/glowing_amethyst" +} diff --git a/crates/cargo-horizon-mod/template/content/model.json b/crates/cargo-horizon-mod/template/content/model.json new file mode 100644 index 000000000..5710fecb1 --- /dev/null +++ b/crates/cargo-horizon-mod/template/content/model.json @@ -0,0 +1,4 @@ +{ + "parent": "minecraft:block/cube_all", + "textures": { "all": "minecraft:block/amethyst_block" } +} diff --git a/crates/cargo-horizon-mod/template/content/pickaxe.json b/crates/cargo-horizon-mod/template/content/pickaxe.json new file mode 100644 index 000000000..8725edebd --- /dev/null +++ b/crates/cargo-horizon-mod/template/content/pickaxe.json @@ -0,0 +1,3 @@ +{ + "values": ["{id}:glowing_amethyst"] +} diff --git a/crates/cargo-horizon-mod/template/content/recipe.json b/crates/cargo-horizon-mod/template/content/recipe.json new file mode 100644 index 000000000..5edb03d94 --- /dev/null +++ b/crates/cargo-horizon-mod/template/content/recipe.json @@ -0,0 +1,6 @@ +{ + "type": "minecraft:crafting_shapeless", + "category": "building", + "ingredients": ["minecraft:amethyst_block", "minecraft:glowstone_dust"], + "result": { "id": "{id}:glowing_amethyst" } +} diff --git a/docs/api/mods.md b/docs/api/mods.md index 3e6108c70..5c323a0e1 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -19,7 +19,7 @@ the player before the mod is turned on, and checked against the component's real | Capabilities | 5: `game-read`, `chat`, `hud`, `storage`, `registries` | | Manifest `api` lines served | 2: `0.1` (code), `0.2` (content) | | SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers | -| `cargo horizon-mod` | `new`, `build`, `run` | +| `cargo horizon-mod` | `new` (templates `code` and `content`), `build`, `run`, `check` | | Example mods | `coords-hud` (code), `ruby-content` (content) | ## Guide @@ -58,6 +58,7 @@ scripting runtime in the game. | Way in | For | Status | Template and example | | --- | --- | --- | --- | | Rust | most mods; the fastest | first-class: the SDK, `cargo horizon-mod` | `cargo horizon-mod new`, `coords-hud` | +| Data only | blocks and items with no code | first-class: content mods (API 0.2) | `cargo horizon-mod new --template content`, `ruby-content` | | Lua scripts | people who don't want a compiler | planned: a script mod whose code is a `.lua` file, run by Horizon's own interpreter mod | planned, with the same example as Rust | | C, C++, Zig | authors of those languages | to evaluate: bindings generated from the WIT, built without WASI | one each if it passes | | Go (TinyGo), AssemblyScript, JavaScript / TypeScript | authors of those languages | to evaluate: each needs its toolchain to emit a component without WASI imports, or an interpreter mod as for Lua | one each if it passes | diff --git a/docs/mods.md b/docs/mods.md index bac207f60..3a4473032 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -16,7 +16,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 | | Example mod | `crates/horizon-mod-sdk/examples/coords-hud` | coordinates, facing and time HUD, `/where`, `/coords` | | Runtime | `crates/horizon-mods` | wasmtime 36 LTS, component model | -| Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new / build / run / check`, and the registry's CI (`registry build / review / list`) | +| Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new [--template code\|content] / build / run / check`, and the registry's CI (`registry build / review / list`) | | In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods | | Launcher mod browser (Modrinth, CurseForge with a key) | [mod-browser.md](mod-browser.md) | resource packs, modpacks | | Registry index (`index.json`, `.hpack`), signatures | `horizon_mods::index`, [api/mod-index.md](api/mod-index.md) | schema 1; launcher and website next | @@ -215,6 +215,7 @@ Benchmarks (`--benchmark`) never load mods. rustup target add wasm32-unknown-unknown cargo install --git https://github.com/ludovic111/horizon cargo-horizon-mod cargo horizon-mod new my-mod # Cargo.toml, horizon-mod.toml, src/lib.rs + # (--template content: a content mod, no code) cd my-mod cargo horizon-mod run # build, then start the game with it cargo horizon-mod build # again after an edit: the running game reloads it @@ -292,7 +293,10 @@ permission. ### Content mods (API 0.2) A mod with `api = "0.2"` and capability `registries` may carry `assets/` and -`data/` in the `.hmod`, and needs no `mod.wasm` if it has no code. It adds +`data/` in the `.hmod`, and needs no `mod.wasm` if it has no code +(`cargo horizon-mod new --template content` starts one; `build` in a folder +with no `Cargo.toml` packs the manifest, `assets/` and `data/`, and `check` +reads it without a trial run). It adds blocks and items by declaring them in `data//horizon/block/*.json` and `data//horizon/item/*.json`, each copying a vanilla template ([modpacks.md](modpacks.md#registries-02-data-driven-blocks-and-items)): diff --git a/website/docs/content-mods.md b/website/docs/content-mods.md index 1ad8cd5fb..9504bceb6 100644 --- a/website/docs/content-mods.md +++ b/website/docs/content-mods.md @@ -4,7 +4,7 @@ A content mod adds blocks and items to the game with data files only: no Rust, n ## What a content mod is -A folder (while you work on it) or a `.hmod` zip (to share it) holding a manifest, `assets/` and `data/`. This is the SDK's [`ruby-content`](https://github.com/ludovic111/horizon/tree/main/crates/horizon-mod-sdk/examples/ruby-content) example, a ruby gem and a block of ruby: +A folder (while you work on it) or a `.hmod` file (to share it) holding a manifest, `assets/` and `data/`. This is the SDK's [`ruby-content`](https://github.com/ludovic111/horizon/tree/main/crates/horizon-mod-sdk/examples/ruby-content) example, a ruby gem and a block of ruby: ``` ruby/ @@ -98,17 +98,27 @@ A mod made from a Java mod whose files use other names lists them in its manifes - Unknown keys in a block or item file are refused, and the mod stays off with the reason on its row. - Content mods work in single player today. Playing them together on a server is planned. +## Start one + +```sh +cargo horizon-mod new my-blocks --template content +``` + +makes a content mod with one block, Glowing Amethyst: an amethyst block that gives light, with its block state, model (using vanilla's amethyst texture), item model, name, loot table, a recipe (an amethyst block and glowstone dust) and the pickaxe tag. Rename and copy its files to add your own. + ## Try it and share it While you work, give the game the folder as a dev mod ([how](/docs/make-a-mod#see-it-in-the-game)): `--dev-mod "/path/to/ruby"`. The first start with a new set of mods takes a little longer while the game adds their content to its tables; after a change to the files, start the game again. -To share it, zip the folder's contents, with `horizon-mod.toml` at the top of the zip, and name the file `.hmod`: +To share it, build the `.hmod` in the mod's folder: ```sh -cd ruby -zip -r ../ruby.hmod horizon-mod.toml assets data +cargo horizon-mod build +cargo horizon-mod check target/horizon-mod/ruby.hmod ``` -Players put that file in their `horizon-mods` folder and turn it on in **Options, Mods...**. The registry doesn't take content-only mods yet: its checks (`cargo horizon-mod check`) expect code in the file. That is coming next. +A folder without a `Cargo.toml` is a content mod: `build` checks its files as the game will and packs the manifest, `assets/` and `data/` into `target/horizon-mod/.hmod`, with no compiler involved. `check` reads it as the registry does and says "no code: content only, nothing to run". Players put that file in their `horizon-mods` folder and turn it on in **Options, Mods...**, and you can [publish it](/docs/publish-a-mod) like any mod. + +A mod can have both: a `Cargo.toml` with code, and `assets/` and `data/` with content. `build` packs both. Next: [test it](/docs/test-a-mod). diff --git a/website/docs/make-a-mod.md b/website/docs/make-a-mod.md index 94c3deca2..89f2d8bcd 100644 --- a/website/docs/make-a-mod.md +++ b/website/docs/make-a-mod.md @@ -41,7 +41,7 @@ cargo horizon-mod new my-mod cd my-mod ``` -`new` makes a folder with a working mod in it: a `/hello` command that answers in chat. `--name "My Mod"` sets the name players see. The folder holds: +`new` makes a folder with a working mod in it: a `/hello` command that answers in chat. `--name "My Mod"` sets the name players see, and `--template content` makes a [content mod](/docs/content-mods) instead, with no code. The folder holds: ``` my-mod/ From c6405610008b0c779ffe281a6cdab34c67f9199a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:56:26 +0100 Subject: [PATCH 21/23] Launcher: the registry pack tests build file URLs with forward slashes, so they pass on Windows A Windows temp path's backslashes went into the test index's JSON as escapes, so the index failed to parse and the Windows launcher release stopped at its tests. Co-Authored-By: Claude Opus 5.5 --- launcher/src/browser/horizon/pack.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/launcher/src/browser/horizon/pack.rs b/launcher/src/browser/horizon/pack.rs index 73dcd0cc1..a2cc4d079 100644 --- a/launcher/src/browser/horizon/pack.rs +++ b/launcher/src/browser/horizon/pack.rs @@ -208,6 +208,8 @@ mod tests { zip.write_all(b"renderDistance:8\n").unwrap(); zip.finish().unwrap(); let size = |p: &Path| fs::metadata(p).unwrap().len(); + // Forward slashes: a Windows path's backslashes would be escapes in the JSON. + let url = |p: &Path| p.display().to_string().replace('\\', "/"); let text = format!( r#"{{"schema": 1, "projects": [ {{"id": "coords_hud", "kind": "mod", "name": "Coordinates HUD", "summary": "", "license": "MIT", @@ -219,9 +221,9 @@ mod tests { "requires": [{{"id": "coords_hud", "version": "0.1.0", "sha256": "{hmod_sha}"}}], "file": {{"name": "cozy-1.0.0.hpack", "url": "file://{}", "size": {}, "sha256": "{}"}}}}]}} ]{extra}}}"#, - hmod.display(), + url(&hmod), size(&hmod), - hpack.display(), + url(&hpack), size(&hpack), idx::sha256_file(&hpack).unwrap() ); From fd154dcbba30d8b4ad8320f6f93231013965391d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:13:06 +0100 Subject: [PATCH 22/23] Website image: copy data/ so the build finds the roadmap build.mjs reads website/data/roadmap.json since the hub (#1819), but the Dockerfile never copied data/, so every site deploy since then failed and playhorizon.dev kept the old build. Co-Authored-By: Claude Opus 5.5 --- website/Dockerfile | 1 + 1 file changed, 1 insertion(+) diff --git a/website/Dockerfile b/website/Dockerfile index ea9cc9afc..b075f9b58 100644 --- a/website/Dockerfile +++ b/website/Dockerfile @@ -5,6 +5,7 @@ WORKDIR /site COPY build.mjs ./ COPY src ./src COPY docs ./docs +COPY data ./data COPY public ./public COPY LEGAL.md ./ ARG GITHUB_TOKEN From d41a3075aa86491e6ac23821480ff2a86b494289 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:13:26 +0100 Subject: [PATCH 23/23] Launcher: a local registry's file:/// URLs open on Windows file:///C:/x left /C:/x after the scheme, which Windows can't open; the pack tests now write real file:/// URLs (the index only accepts those), with forward slashes. Co-Authored-By: Claude Opus 5.5 --- launcher/src/browser/horizon.rs | 9 +++++++++ launcher/src/browser/horizon/pack.rs | 12 ++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/launcher/src/browser/horizon.rs b/launcher/src/browser/horizon.rs index e56f31e09..66553ab50 100644 --- a/launcher/src/browser/horizon.rs +++ b/launcher/src/browser/horizon.rs @@ -343,6 +343,7 @@ fn fetch( ) -> Result { match file.url.strip_prefix("file://").filter(|_| local) { Some(path) => { + let path = local_path(path); let reader = fs::File::open(path).map_err(|e| format!("{path}: {e}"))?; download::save_from_anywhere(file, reader, folder, progress) } @@ -350,6 +351,14 @@ fn fetch( } } +/// The path of a `file:///` URL: on Windows `/C:/x` is `C:/x`. +fn local_path(path: &str) -> &str { + match path.strip_prefix('/') { + Some(rest) if cfg!(windows) && rest.get(1..2) == Some(":") => rest, + _ => path, + } +} + /// What the registry adds to an installed entry. fn trust_label(trust: Trust) -> &'static str { match trust { diff --git a/launcher/src/browser/horizon/pack.rs b/launcher/src/browser/horizon/pack.rs index a2cc4d079..3cb6d7c9b 100644 --- a/launcher/src/browser/horizon/pack.rs +++ b/launcher/src/browser/horizon/pack.rs @@ -208,8 +208,16 @@ mod tests { zip.write_all(b"renderDistance:8\n").unwrap(); zip.finish().unwrap(); let size = |p: &Path| fs::metadata(p).unwrap().len(); - // Forward slashes: a Windows path's backslashes would be escapes in the JSON. - let url = |p: &Path| p.display().to_string().replace('\\', "/"); + // A `file:///` URL: forward slashes (a Windows path's backslashes would be escapes in + // the JSON) and a leading slash before a Windows drive. + let url = |p: &Path| { + let path = p.display().to_string().replace('\\', "/"); + if path.starts_with('/') { + path + } else { + format!("/{path}") + } + }; let text = format!( r#"{{"schema": 1, "projects": [ {{"id": "coords_hud", "kind": "mod", "name": "Coordinates HUD", "summary": "", "license": "MIT",