Merge pull request #98 from ludovic111/feat/logs-crash-reports

Logs and crash reports: game, launcher, CLI and MCP
This commit is contained in:
Ludovic Marie
2026-10-14 17:28:44 +02:00
committed by GitHub
38 changed files with 1844 additions and 100 deletions
Generated
+38
View File
@@ -316,6 +316,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chrono"
version = "0.4.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
dependencies = [
"iana-time-zone",
"num-traits",
"windows-link",
]
[[package]]
name = "clipboard-win"
version = "5.4.1"
@@ -826,13 +837,16 @@ dependencies = [
"ab_glyph",
"arboard",
"bytemuck",
"chrono",
"cpal",
"flate2",
"glam",
"horizon-assets",
"horizon-core",
"horizon-protocol",
"horizon-theme",
"horizon-world",
"log",
"miniz_oxide 0.8.9",
"png",
"pollster",
@@ -884,6 +898,30 @@ dependencies = [
"xxhash-rust",
]
[[package]]
name = "iana-time-zone"
version = "0.1.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.62.2",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]]
name = "indexmap"
version = "2.14.2"
+3
View File
@@ -23,6 +23,9 @@ cpal = "0.16"
symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] }
miniz_oxide = "0.8"
ab_glyph = "0.2.32"
log = "0.4"
chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] }
flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] }
horizon-theme = { path = "../horizon-theme" }
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
+3 -3
View File
@@ -461,7 +461,7 @@ fn build_stream<T: cpal::SizedSample + cpal::FromSample<f32>>(
*out = T::from_sample(*s);
}
},
|e| eprintln!("Horizon: audio stream error: {e}"),
|e| log::warn!("Horizon: audio stream error: {e}"),
None,
)?;
Ok(stream)
@@ -486,7 +486,7 @@ impl Audio {
Ok(v) => (Some(v), true),
Err(e) => {
if output {
eprintln!("Horizon: no sound: {e}");
log::warn!("Horizon: no sound: {e}");
}
(None, false)
}
@@ -533,7 +533,7 @@ impl Audio {
tried.push(name.clone());
match open_device(&device, mixer.clone()) {
Ok((stream, config)) => {
eprintln!(
log::info!(
"Horizon: audio output {name} ({} Hz, {} channels, {})",
config.sample_rate().0,
config.channels(),
@@ -150,6 +150,11 @@ pub const COMMANDS: &[Cmd] = &[
cmd!("wait-ready", Session, "wait-ready [SECONDS]", "wait until the player has spawned and no chunks are pending",
"Polls status every 250 ms; replies with the status, or an error after SECONDS (default 120).",
["horizon-ctl wait-ready 300"], &[opt("seconds", Ty::Num, "how long to wait (default 120)")], mcp: true, local: true),
cmd!("logs", Session, "logs [--lines N] [--crash]", "the end of the game's log, or its newest crash report",
"Reads the game home ($HORIZON_HOME, else ~/.local/share/horizon): logs/latest.log (the last N lines, default 100) or, with --crash, the newest file in crash-reports. Read-only; works whether the game runs or not.",
["horizon-ctl logs", "horizon-ctl logs --lines 300", "horizon-ctl logs --crash"],
&[flag("lines", Ty::Int, "how many lines of latest.log (default 100)"), flag("crash", Ty::Bool, "the newest crash report instead")],
mcp: true, local: true),
cmd!("status", Session, "status", "game, renderer and streaming state (the scripting socket's original summary)",
"", ["horizon-ctl status"], &[], mcp: false, local: false),
cmd!("open", Session, "open WORLD [SEED] [creative]", "open or create a world from the title screen",
@@ -10,6 +10,7 @@ use std::{
time::{Duration, Instant},
};
use horizon_client::logging::{data_dir, game_home};
use serde_json::{Value, json};
#[cfg(windows)]
@@ -17,42 +18,12 @@ const CLIENT: &str = "horizon-client.exe";
#[cfg(not(windows))]
const CLIENT: &str = "horizon-client";
/// The platform data folder (what the `dirs` crate's data_dir gives).
fn data_dir() -> PathBuf {
let env = |k: &str| {
std::env::var_os(k)
.filter(|v| !v.is_empty())
.map(PathBuf::from)
};
let home = env("HOME").or_else(|| env("USERPROFILE"));
if cfg!(windows) {
if let Some(d) = env("APPDATA") {
return d;
}
} else if cfg!(target_os = "macos") {
if let Some(h) = &home {
return h.join("Library/Application Support");
}
} else if let Some(d) = env("XDG_DATA_HOME") {
return d;
} else if let Some(h) = &home {
return h.join(".local/share");
}
std::env::temp_dir()
}
pub fn launcher_home() -> PathBuf {
match std::env::var_os("HORIZON_LAUNCHER_HOME").filter(|h| !h.is_empty()) {
Some(h) => PathBuf::from(h),
None => data_dir().join("horizon-launcher"),
}
}
pub fn game_home() -> PathBuf {
match std::env::var_os("HORIZON_HOME").filter(|h| !h.is_empty()) {
Some(h) => PathBuf::from(h),
None => data_dir().join("horizon"),
}
}
/// `v2026.10.13.1` gives [2026, 10, 13, 1]; a pre-release suffix is ignored.
pub fn version_parts(tag: &str) -> Vec<u64> {
tag.trim_start_matches('v')
@@ -183,6 +183,7 @@ impl Session {
thread::sleep(Duration::from_secs_f64(seconds.max(0.0)));
self.game(&format!("key {key} up"))
}
"logs" => logs(&horizon_client::logging::game_home(), &words[1..]),
"wait-ready" => {
let limit = if words.len() > 1 {
number(1, "SECONDS")?
@@ -228,6 +229,52 @@ impl Session {
}
}
/// `logs [--lines N] [--crash]` for the game in `home`: the reply's `text` is the log's last
/// lines or the report.
fn logs(home: &Path, words: &[String]) -> Result<Value, Failure> {
use horizon_client::logging;
let mut lines = 100;
let mut crash = false;
let mut it = words.iter();
while let Some(word) = it.next() {
match word.as_str() {
"--crash" => crash = true,
"--lines" => {
lines = it
.next()
.and_then(|n| n.parse::<usize>().ok())
.filter(|&n| n > 0)
.ok_or_else(|| Failure::usage("--lines takes a number above 0"))?;
}
other => {
return Err(Failure::usage(format!(
"unknown argument {other}; usage: {}",
usage("logs")
)));
}
}
}
let missing = |what: String| Failure {
reply: json!({ "error": what }),
status: GAME_ERROR,
};
if crash {
let path = logging::newest_crash_report(home).ok_or_else(|| {
missing(format!(
"no crash report in {}",
logging::crash_reports_dir(home).display()
))
})?;
let text = std::fs::read_to_string(&path)
.map_err(|e| missing(format!("{}: {e}", path.display())))?;
return Ok(json!({ "path": path, "text": text }));
}
let path = logging::logs_dir(home).join("latest.log");
let tail =
logging::tail(&path, lines).map_err(|e| missing(format!("{}: {e}", path.display())))?;
Ok(json!({ "path": path, "text": tail.join("\n") + "\n" }))
}
fn usage(name: &str) -> String {
commands::find(name).map_or_else(|| name.to_owned(), |c| format!("horizon-ctl {}", c.usage))
}
@@ -424,6 +471,17 @@ fn main() -> ExitCode {
_ => script(&mut session, std::io::stdin().lock(), keep_going, pretty),
}
}
// Text for people; scripts and MCP get the JSON reply.
Some("logs") => match session.run(&args) {
Ok(reply) => {
print!("{}", reply["text"].as_str().unwrap_or_default());
0
}
Err(f) => {
print(&f.reply, pretty);
f.status
}
},
Some(_) => match session.run(&args) {
Ok(reply) => {
print(&reply, pretty);
@@ -442,6 +500,52 @@ fn main() -> ExitCode {
mod tests {
use super::*;
#[test]
fn logs_reads_the_end_of_latest_log_and_the_newest_crash_report() {
let home = std::env::temp_dir().join(format!("horizon-ctl-logs-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&home);
let words = |s: &str| -> Vec<String> { s.split_whitespace().map(String::from).collect() };
let failure = logs(&home, &words("")).unwrap_err();
assert!(
failure.reply["error"]
.as_str()
.unwrap()
.contains("latest.log")
);
std::fs::create_dir_all(home.join("logs")).unwrap();
let text: String = (1..=150)
.map(|i| format!("[10:00:00] [Render thread/INFO]: line {i}\n"))
.collect();
std::fs::write(home.join("logs/latest.log"), text).unwrap();
let reply = logs(&home, &words("")).unwrap();
let tail = reply["text"].as_str().unwrap();
assert_eq!(tail.lines().count(), 100);
assert!(tail.starts_with("[10:00:00] [Render thread/INFO]: line 51\n"));
assert!(tail.ends_with("line 150\n"));
let reply = logs(&home, &words("--lines 2")).unwrap();
assert_eq!(
reply["text"],
"[10:00:00] [Render thread/INFO]: line 149\n[10:00:00] [Render thread/INFO]: line 150\n"
);
assert_eq!(logs(&home, &words("--lines 0")).unwrap_err().status, USAGE);
assert_eq!(logs(&home, &words("--tail")).unwrap_err().status, USAGE);
assert!(logs(&home, &words("--crash")).is_err());
std::fs::create_dir_all(home.join("crash-reports")).unwrap();
std::fs::write(
home.join("crash-reports/crash-2026-10-13_10.00.00-client.txt"),
"old",
)
.unwrap();
std::fs::write(
home.join("crash-reports/crash-2026-10-14_10.00.00-client.txt"),
"new",
)
.unwrap();
let reply = logs(&home, &words("--crash")).unwrap();
assert_eq!(reply["text"], "new");
let _ = std::fs::remove_dir_all(&home);
}
#[test]
fn script_lines_split_like_a_shell() {
assert_eq!(
@@ -91,6 +91,21 @@ impl Session {
Err(f) => (vec![text(&f.reply)], true),
};
}
if cmd.name == "logs" {
let words = match commands::line_for(cmd, args) {
Ok(w) => w,
Err(e) => return (vec![text(&json!({ "error": e, "kind": "usage" }))], true),
};
return match self.run(&words) {
Ok(reply) => (
vec![
json!({ "type": "text", "text": format!("{}\n\n{}", reply["path"].as_str().unwrap_or_default(), reply["text"].as_str().unwrap_or_default()) }),
],
false,
),
Err(f) => (vec![text(&f.reply)], true),
};
}
let mut words = match commands::line_for(cmd, args) {
Ok(w) => w,
Err(e) => return (vec![text(&json!({ "error": e, "kind": "usage" }))], true),
@@ -202,6 +217,7 @@ mod tests {
"click_button",
"screenshot",
"inventory",
"logs",
] {
let want = if want == "break_block" { "break" } else { want };
assert!(names.contains(want), "{want}");
+2
View File
@@ -113,6 +113,8 @@ impl Chat {
ticks: u64,
focused: bool,
) {
// ChatComponent.logChatMessage: every message is in the log.
crate::logging::write_only(log::Level::Info, &format!("[CHAT] {}", content.plain()));
if self.log {
println!("[CHAT] {}", content.plain());
}
+614
View File
@@ -0,0 +1,614 @@
//! Crash reports, laid out like vanilla's CrashReport.getFriendlyReport: a comment, the time,
//! a description, the error with its stack, then the details of the game and the machine.
//! Written to `crash-reports/crash-<yyyy-MM-dd_HH.mm.ss>-client.txt` in the game folder when
//! the main thread panics or `main` gets an error back. Nothing is sent anywhere.
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use chrono::{DateTime, Local};
/// What the game is doing, set as it goes: graphics adapter, settings, packs, world.
static DETAILS: Mutex<Vec<(&'static str, String)>> = Mutex::new(Vec::new());
static REPORTED: AtomicBool = AtomicBool::new(false);
/// Sets one line of the report's details (replacing the last value under `key`).
pub fn set_detail(key: &'static str, value: impl Into<String>) {
let mut details = DETAILS.lock().unwrap_or_else(|e| e.into_inner());
let value = value.into();
match details.iter_mut().find(|(k, _)| *k == key) {
Some(entry) => entry.1 = value,
None => details.push((key, value)),
}
}
pub fn clear_detail(key: &'static str) {
DETAILS
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|(k, _)| *k != key);
}
fn details() -> Vec<(&'static str, String)> {
DETAILS.lock().unwrap_or_else(|e| e.into_inner()).clone()
}
/// Vanilla picks a line from a list of jokes; these only say what happened.
const COMMENTS: &[&str] = &[
"Something went wrong.",
"The game stopped here.",
"This should not have happened.",
"Details below.",
];
/// One crash, ready to be written.
pub struct Report {
pub time: DateTime<Local>,
pub description: String,
/// The error's message, first line of the stack section.
pub error: String,
/// Where it happened and how it got there: one frame a line (`function (file:line:col)`).
pub stack: String,
pub thread: String,
/// `client` or `server`, the end of the file name.
pub side: &'static str,
pub details: Vec<(String, String)>,
pub log: Vec<String>,
}
/// `crash-2026-10-14_09.05.07-client.txt`
pub fn file_name(time: &DateTime<Local>, side: &str) -> String {
format!("crash-{}-{side}.txt", time.format("%Y-%m-%d_%H.%M.%S"))
}
impl Report {
/// The report's text.
pub fn text(&self) -> String {
let comment = COMMENTS[self.time.timestamp().rem_euclid(COMMENTS.len() as i64) as usize];
let mut out = String::new();
let _ = writeln!(out, "---- Horizon Crash Report ----");
let _ = writeln!(out, "// {comment}\n");
let _ = writeln!(out, "Time: {}", self.time.format("%Y-%m-%d %H:%M:%S"));
let _ = writeln!(out, "Description: {}\n", self.description);
let _ = writeln!(out, "{}", self.error);
for line in self.stack.lines() {
let _ = writeln!(out, "\tat {line}");
}
let _ = writeln!(
out,
"\n\nA detailed walkthrough of the error, its code path and all known details is as follows:"
);
let _ = writeln!(out, "{}\n", "-".repeat(87));
let _ = writeln!(out, "-- Head --");
let _ = writeln!(out, "Thread: {}\n", self.thread);
let _ = writeln!(out, "-- System Details --");
let _ = writeln!(out, "Details:");
for (key, value) in &self.details {
let _ = writeln!(out, "\t{key}: {value}");
}
let _ = writeln!(out, "\n-- Last {} log lines --", self.log.len());
for line in &self.log {
let _ = writeln!(out, "{line}");
}
out
}
/// Writes the report in `home/crash-reports` and returns its path.
pub fn save(&self, home: &Path) -> std::io::Result<PathBuf> {
let dir = crate::logging::crash_reports_dir(home);
std::fs::create_dir_all(&dir)?;
let path = dir.join(file_name(&self.time, self.side));
std::fs::write(&path, self.text())?;
Ok(path)
}
}
/// The release this binary came with: launcher installs live in a folder named after the tag.
fn release_tag() -> Option<String> {
let exe = std::env::current_exe().ok()?;
let folder = exe.parent()?.file_name()?.to_str()?;
(folder.starts_with('v') && folder[1..].starts_with(|c: char| c.is_ascii_digit()))
.then(|| folder.to_owned())
}
fn command_output(program: &str, args: &[&str]) -> Option<String> {
let out = std::process::Command::new(program)
.args(args)
.output()
.ok()?;
let text = String::from_utf8_lossy(&out.stdout).trim().to_owned();
(out.status.success() && !text.is_empty()).then_some(text)
}
fn read(path: &str) -> Option<String> {
std::fs::read_to_string(path).ok()
}
/// `PRETTY_NAME` of /etc/os-release and the kernel, or the system's own version string.
fn operating_system() -> String {
let arch = std::env::consts::ARCH;
let version = if cfg!(target_os = "linux") {
let name = read("/etc/os-release").and_then(|t| {
t.lines()
.find_map(|l| l.strip_prefix("PRETTY_NAME="))
.map(|v| v.trim_matches('"').to_owned())
});
let kernel = read("/proc/sys/kernel/osrelease").map(|k| k.trim().to_owned());
match (name, kernel) {
(Some(n), Some(k)) => Some(format!("{n}, kernel {k}")),
(n, k) => n.or(k),
}
} else if cfg!(target_os = "macos") {
command_output("sw_vers", &["-productVersion"]).map(|v| format!("macOS {v}"))
} else if cfg!(windows) {
command_output("cmd", &["/C", "ver"])
} else {
None
};
format!(
"{} ({arch}) version {}",
std::env::consts::OS,
version.unwrap_or_else(|| "unknown".into())
)
}
fn cpu() -> String {
let threads = std::thread::available_parallelism().map_or(0, |n| n.get());
let name = if cfg!(target_os = "linux") {
read("/proc/cpuinfo").and_then(|t| {
t.lines()
.find(|l| l.starts_with("model name"))
.and_then(|l| l.split_once(':'))
.map(|(_, v)| v.trim().to_owned())
})
} else if cfg!(target_os = "macos") {
command_output("sysctl", &["-n", "machdep.cpu.brand_string"])
} else {
std::env::var("PROCESSOR_IDENTIFIER").ok()
};
format!(
"{threads}x {}",
name.unwrap_or_else(|| std::env::consts::ARCH.into())
)
}
/// Total memory and what this process uses, in MiB where the system says.
fn memory() -> String {
const MIB: u64 = 1024 * 1024;
let kib = |text: &str, key: &str| -> Option<u64> {
text.lines()
.find(|l| l.starts_with(key))?
.split_whitespace()
.nth(1)?
.parse()
.ok()
};
let (total, used) = if cfg!(target_os = "linux") {
(
read("/proc/meminfo")
.and_then(|t| kib(&t, "MemTotal:"))
.map(|k| k * 1024),
read("/proc/self/status")
.and_then(|t| kib(&t, "VmRSS:"))
.map(|k| k * 1024),
)
} else if cfg!(target_os = "macos") {
(
command_output("sysctl", &["-n", "hw.memsize"]).and_then(|v| v.parse().ok()),
None,
)
} else if cfg!(windows) {
(
command_output(
"powershell",
&[
"-NoProfile",
"-Command",
"(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory",
],
)
.and_then(|v| v.parse().ok()),
None,
)
} else {
(None, None)
};
match (total, used) {
(Some(t), Some(u)) => format!(
"{} MiB used by the game, {} MiB installed",
u / MIB,
t / MIB
),
(Some(t), None) => format!("{} MiB installed", t / MIB),
_ => "unknown".into(),
}
}
/// The report's details: Horizon's and the machine's, then what the game set as it ran.
pub fn system_details() -> Vec<(String, String)> {
let mut version = env!("CARGO_PKG_VERSION").to_owned();
if let Some(tag) = release_tag() {
version = format!("{tag} (client {version})");
}
let mut out = vec![
("Horizon Version".to_owned(), version),
("Minecraft Version".to_owned(), "26.3".to_owned()),
("Operating System".to_owned(), operating_system()),
("CPU".to_owned(), cpu()),
("Memory".to_owned(), memory()),
];
out.extend(details().into_iter().map(|(k, v)| (k.to_owned(), v)));
out
}
fn thread_name() -> String {
let current = std::thread::current();
match current.name() {
Some("main") | None => "Render thread".into(),
Some(name) => name.into(),
}
}
/// Writes the report and tells where it is; the log gets the error too.
fn deliver(home: &Path, report: Report) -> Option<PathBuf> {
if REPORTED.swap(true, Ordering::SeqCst) {
return None;
}
// The panic is on stderr already: the stack goes to the log only.
crate::logging::write_only(
log::Level::Error,
&format!(
"Horizon crashed: {}\n{}",
report.error,
report
.stack
.lines()
.map(|l| format!("\tat {l}"))
.collect::<Vec<_>>()
.join("\n")
),
);
crate::logging::flush();
match report.save(home) {
Ok(path) => {
eprintln!("Horizon: crash report saved to {}", path.display());
Some(path)
}
Err(e) => {
eprintln!("Horizon: could not save a crash report: {e}");
eprintln!("{}", report.text());
None
}
}
}
fn panic_message(info: &std::panic::PanicHookInfo) -> String {
let payload = info.payload();
let text = payload
.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "Box<dyn Any>".into());
match info.location() {
Some(at) => format!("panicked at {at}:\n{text}"),
None => format!("panicked:\n{text}"),
}
}
/// A `std::backtrace` as one line a frame, `function (file:line:col)`. Captured in a panic hook
/// (`from_panic`), it starts at the frame that panicked: the hook's and the panic machinery's
/// frames go. Paths inside the workspace lose the build machine's prefix.
pub fn stack_lines(backtrace: &str, from_panic: bool) -> String {
// The workspace as it was on the machine that built this binary (it need not exist here).
let manifest = env!("CARGO_MANIFEST_DIR");
let root = manifest
.strip_suffix("crates/horizon-client")
.unwrap_or(manifest);
let mut frames: Vec<(String, Option<String>)> = Vec::new();
for line in backtrace.lines() {
let line = line.trim();
if let Some(at) = line.strip_prefix("at ") {
if let Some(frame) = frames.last_mut() {
frame.1 = Some(short_path(at, root).to_owned());
}
} else if let Some((n, name)) = line.split_once(": ")
&& n.chars().all(|c| c.is_ascii_digit())
{
frames.push((name.to_owned(), None));
}
}
let machinery = |name: &str| {
[
"std::panicking::",
"core::panicking::",
"std::sys::backtrace::",
"__rustc::",
]
.iter()
.any(|p| name.starts_with(p))
|| name.contains("rust_begin_unwind")
};
// The hook's frames, then the panic machinery's, then the code that panicked.
let top = frames.iter().take(30).position(|(name, _)| machinery(name));
let first = match top.filter(|_| from_panic) {
Some(start) => {
start
+ frames[start..]
.iter()
.take_while(|(name, _)| machinery(name))
.count()
}
None => 0,
};
// Some platforms keep std's own capture frames (`<std::backtrace::Backtrace>::create`).
let first = first
+ frames[first..]
.iter()
.take_while(|(name, _)| name.trim_start_matches('<').starts_with("std::backtrace"))
.count();
frames[first..]
.iter()
.map(|(name, at)| match at {
Some(at) => format!("{name} ({at})\n"),
None => format!("{name}\n"),
})
.collect()
}
/// A source path without the build machine's folders: relative to the workspace, or from the
/// crate's folder for dependencies (`winit-0.30.13/src/event_loop.rs:642:56`).
fn short_path<'a>(path: &'a str, root: &str) -> &'a str {
if let Some(rest) = path.strip_prefix(root) {
return rest;
}
if let Some(i) = path.find("/registry/src/") {
let rest = &path[i + "/registry/src/".len()..];
if let Some((_index, krate)) = rest.split_once('/') {
return krate;
}
}
path
}
/// A report for a panic, with the stack captured now (RUST_BACKTRACE or not).
pub fn panic_report(info: &std::panic::PanicHookInfo, side: &'static str) -> Report {
Report {
time: Local::now(),
description: "Unexpected error".into(),
error: panic_message(info),
stack: stack_lines(
&std::backtrace::Backtrace::force_capture().to_string(),
true,
),
thread: thread_name(),
side,
details: system_details(),
log: crate::logging::recent_lines(),
}
}
/// Reports panics: on the main thread a crash report (the panic then ends the game, exit code
/// 101); on other threads the error goes to the log, as vanilla's uncaught exception handler
/// does. The default hook still prints the panic.
pub fn install(home: PathBuf, side: &'static str) {
let default = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
default(info);
let main = std::thread::current().name() == Some("main");
if main {
deliver(&home, panic_report(info, side));
} else {
log::error!(
"Caught previously unhandled exception in thread {}: {}",
thread_name(),
panic_message(info)
);
}
}));
}
/// Vanilla's debug crash (`key.debug.crash` held for ten seconds): the error `main` gets back,
/// with the stack where it was raised.
#[derive(Debug)]
pub struct DebugCrash {
stack: String,
}
impl DebugCrash {
pub const MESSAGE: &str = "Manually triggered debug crash";
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
stack: stack_lines(
&std::backtrace::Backtrace::force_capture().to_string(),
false,
),
}
}
}
impl std::fmt::Display for DebugCrash {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(Self::MESSAGE)
}
}
impl std::error::Error for DebugCrash {}
/// A report for an error `main` got back: the game ends with it.
pub fn report_error(
home: &Path,
side: &'static str,
error: &(dyn std::error::Error + 'static),
) -> Option<PathBuf> {
if let Some(debug) = error.downcast_ref::<DebugCrash>() {
return deliver(
home,
Report {
time: Local::now(),
description: DebugCrash::MESSAGE.into(),
error: DebugCrash::MESSAGE.into(),
stack: debug.stack.clone(),
thread: thread_name(),
side,
details: system_details(),
log: crate::logging::recent_lines(),
},
);
}
let mut message = error.to_string();
let mut source = error.source();
while let Some(e) = source {
let _ = write!(message, "\nCaused by: {e}");
source = e.source();
}
deliver(
home,
Report {
time: Local::now(),
description: "Fatal error".into(),
error: message,
stack: String::new(),
thread: thread_name(),
side,
details: system_details(),
log: crate::logging::recent_lines(),
},
)
}
/// Called every frame: panics once `HORIZON_DEBUG_CRASH` asks (development builds only).
pub fn debug_crash_tick() {
static AT: std::sync::OnceLock<Option<(std::time::Instant, std::time::Duration)>> =
std::sync::OnceLock::new();
if let Some((first, after)) =
AT.get_or_init(|| debug_crash_after().map(|d| (std::time::Instant::now(), d)))
&& first.elapsed() >= *after
{
panic!("Manually triggered debug crash");
}
}
/// Development builds crash on purpose when `HORIZON_DEBUG_CRASH` is set (vanilla has F3+C held
/// for ten seconds): the number is seconds after the first frame (default 5).
pub fn debug_crash_after() -> Option<std::time::Duration> {
if !cfg!(debug_assertions) {
return None;
}
let value = std::env::var("HORIZON_DEBUG_CRASH").ok()?;
let seconds = value.parse::<f64>().unwrap_or(5.0).max(0.0);
Some(std::time::Duration::from_secs_f64(seconds))
}
#[cfg(test)]
mod tests {
use super::*;
fn report() -> Report {
Report {
time: chrono::TimeZone::with_ymd_and_hms(&Local, 2026, 10, 14, 9, 5, 7).unwrap(),
description: "Unexpected error".into(),
error: "panicked at src/game.rs:10:5:\nboom".into(),
stack: "horizon_client::game::frame (src/game.rs:10:5)\n".into(),
thread: "Render thread".into(),
side: "client",
details: vec![
("Horizon Version".into(), "0.1.0".into()),
("Minecraft Version".into(), "26.3".into()),
("Graphics".into(), "Test GPU (Vulkan), driver 1.0".into()),
],
log: vec!["[09:05:06] [Render thread/INFO]: load assets: 1.20s".into()],
}
}
#[test]
fn file_names_are_vanillas() {
assert_eq!(
file_name(&report().time, "client"),
"crash-2026-10-14_09.05.07-client.txt"
);
}
#[test]
fn the_report_reads_like_vanillas() {
let text = report().text();
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines[0], "---- Horizon Crash Report ----");
assert!(lines[1].starts_with("// "));
assert_eq!(lines[3], "Time: 2026-10-14 09:05:07");
assert_eq!(lines[4], "Description: Unexpected error");
assert_eq!(lines[6], "panicked at src/game.rs:10:5:");
assert_eq!(lines[7], "boom");
assert_eq!(
lines[8],
"\tat horizon_client::game::frame (src/game.rs:10:5)"
);
assert!(text.contains("-- Head --\nThread: Render thread\n"));
assert!(text.contains(
"-- System Details --\nDetails:\n\tHorizon Version: 0.1.0\n\tMinecraft Version: 26.3\n\tGraphics: Test GPU (Vulkan), driver 1.0\n"
));
assert!(text.ends_with(
"-- Last 1 log lines --\n[09:05:06] [Render thread/INFO]: load assets: 1.20s\n"
));
}
#[test]
fn stacks_start_at_the_panicking_frame() {
let bt = format!(
" 0: horizon_client::crash::panic_report\n at {root}/src/crash.rs:296:16\n 1: std::panicking::panic_with_hook\n at /rustc/abc/library/std/src/panicking.rs:823:13\n 2: core::panicking::panic_fmt\n at /rustc/abc/library/core/src/panicking.rs:80:14\n 3: horizon_client::crash::debug_crash_tick\n at {root}/src/crash.rs:359:9\n 4: winit::dispatch\n at /home/someone/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/winit-0.30.13/src/event_loop.rs:642:56\n 5: main\n",
root = env!("CARGO_MANIFEST_DIR")
);
assert_eq!(
stack_lines(&bt, true),
"horizon_client::crash::debug_crash_tick (crates/horizon-client/src/crash.rs:359:9)\nwinit::dispatch (winit-0.30.13/src/event_loop.rs:642:56)\nmain\n"
);
}
#[test]
fn the_debug_crash_is_reported_as_vanillas() {
let error: Box<dyn std::error::Error> = DebugCrash::new().into();
assert_eq!(error.to_string(), "Manually triggered debug crash");
let debug = error.downcast_ref::<DebugCrash>().unwrap();
// The stack starts where the crash was raised (DebugCrash::new, in this file).
let first = debug.stack.lines().next().unwrap();
assert!(first.contains("crash.rs"), "{}", debug.stack);
}
#[test]
fn a_panic_becomes_a_report() {
// A real panic through a hook, as the game's would be.
let caught = std::sync::Arc::new(Mutex::new(None));
let sink = caught.clone();
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
if panic_message(info).contains("the test crash") {
*sink.lock().unwrap() = Some(panic_report(info, "client"));
}
}));
let _ = std::panic::catch_unwind(|| panic!("the test crash"));
std::panic::set_hook(previous);
let report = caught.lock().unwrap().take().expect("the hook ran");
assert!(report.error.contains("the test crash"));
assert!(report.error.contains("crash.rs"));
// The first frame is the test's own code, not the panic machinery.
let first = report.stack.lines().next().unwrap();
assert!(first.contains("crash.rs"), "{}", report.stack);
let text = report.text();
assert!(text.contains("Description: Unexpected error"));
assert!(text.contains("\tMinecraft Version: 26.3\n"));
assert!(text.contains("\tOperating System: "));
assert!(text.contains("\tCPU: "));
let home = std::env::temp_dir().join(format!("horizon-crash-save-{}", std::process::id()));
let path = report.save(&home).unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), text);
assert!(
path.file_name()
.unwrap()
.to_str()
.unwrap()
.ends_with("-client.txt")
);
let _ = std::fs::remove_dir_all(&home);
}
}
+25 -21
View File
@@ -658,7 +658,8 @@ struct Game<'a> {
fps_at: Instant,
ticks: u64,
health_hud: hud_layout::HealthHud,
error: Option<String>,
/// What ends the game with an error; kept as it is, so main can tell a debug crash.
error: Option<Box<dyn std::error::Error>>,
message: Option<(String, Instant)>,
save: Arc<SaveDir>,
level: Level,
@@ -5437,6 +5438,7 @@ impl Game<'_> {
..Level::default()
});
let mut level = level;
horizon_client::crash::set_detail("World", format!("{} (saves/{folder})", level.name));
if let Some(d) = &self.options.dimension {
level.dimension = d.clone();
level.position = None;
@@ -5962,6 +5964,7 @@ impl Game<'_> {
}
self.stats.custom("leave_game", 1);
self.save_game()?;
horizon_client::crash::clear_detail("World");
self.streaming.paused = true;
self.world = World::new(self.res.facts.air, 0);
self.player = None;
@@ -7970,7 +7973,7 @@ impl Game<'_> {
}
fn update_world(&mut self) {
if let Err(e) = self.poll_remote() {
eprintln!("Horizon: {e}");
log::warn!("Horizon: {e}");
}
if let Some(p) = &self.player {
self.streaming.center = (
@@ -8005,7 +8008,7 @@ impl Game<'_> {
.save_later(&modified, self.res.assets.registry, &self.res.biomes)
})
{
eprintln!("Horizon: failed to save unloaded chunks: {e}");
log::warn!("Horizon: failed to save unloaded chunks: {e}");
}
if let Some(renderer) = self.renderer.as_mut() {
let g = &self.settings.horizon;
@@ -8076,7 +8079,7 @@ impl ApplicationHandler for Game<'_> {
) {
Ok(w) => Arc::new(w),
Err(e) => {
self.error = Some(e.to_string());
self.error = Some(e.into());
event_loop.exit();
return;
}
@@ -8084,7 +8087,7 @@ impl ApplicationHandler for Game<'_> {
match self.new_renderer(window.clone()) {
Ok(r) => self.renderer = Some(r),
Err(e) => {
self.error = Some(e.to_string());
self.error = Some(e);
event_loop.exit();
return;
}
@@ -8576,7 +8579,7 @@ impl ApplicationHandler for Game<'_> {
.filter(|(_, ms)| *ms >= 0.5)
.map(|(n, ms)| format!("{n} {ms:.1}"))
.collect();
eprintln!(
log::info!(
"Horizon: slow frame {cpu:.1} ms ({} ticks): {}",
steps,
list.join(", ")
@@ -8633,6 +8636,7 @@ impl ApplicationHandler for Game<'_> {
self.frame_stats.record(elapsed.as_secs_f32() * 1000.0);
self.frames += 1;
self.fps_frames += 1;
horizon_client::crash::debug_crash_tick();
if self.fps_at.elapsed() >= Duration::from_secs(1) {
self.fps = self.fps_frames as f32 / self.fps_at.elapsed().as_secs_f32();
self.fps_frames = 0;
@@ -8648,7 +8652,7 @@ impl ApplicationHandler for Game<'_> {
Ok(())
})();
if let Err(e) = result {
self.error = Some(e.to_string());
self.error = Some(e);
event_loop.exit();
}
}
@@ -8680,7 +8684,7 @@ impl ApplicationHandler for Game<'_> {
/// window turns it into a window close, so Minecraft.stop saves the world.
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
if let Err(e) = self.save_for_exit() {
eprintln!("Horizon: failed to save the world on exit: {e}");
log::warn!("Horizon: failed to save the world on exit: {e}");
}
}
}
@@ -8720,7 +8724,7 @@ pub fn run() -> Result<()> {
// Minecraft.rollbackResourcePacks: the packs break loading, start
// with the game's own resources.
Err(e) if options.resources != vanilla_root => {
eprintln!("Horizon: resource packs failed to load ({e}); using the default resources");
log::warn!("Horizon: resource packs failed to load ({e}); using the default resources");
options.resources = vanilla_root.clone();
Assets::load(&vanilla_root)?
}
@@ -8733,29 +8737,29 @@ pub fn run() -> Result<()> {
};
let root = options.resources.clone();
let assets = Arc::new(assets);
eprintln!("load assets: {:.2}s", started.elapsed().as_secs_f32());
log::info!("load assets: {:.2}s", started.elapsed().as_secs_f32());
let facts = BlockFacts::load(&root, assets.registry)?;
let mob_data = horizon_client::mobs::MobData::load(&root, &facts);
eprintln!("load facts: {:.2}s", started.elapsed().as_secs_f32());
log::info!("load facts: {:.2}s", started.elapsed().as_secs_f32());
let items = Items::load(&root, assets.registry, &facts)?;
eprintln!("load items: {:.2}s", started.elapsed().as_secs_f32());
log::info!("load items: {:.2}s", started.elapsed().as_secs_f32());
let recipes = Recipes::load(&root, &items)?;
let transformers = horizon_client::block_transform::Transformers::load(&root, assets.registry)?;
let biomes = Arc::new(Biomes::load(&root)?);
let environment = Environment::load(&root)?;
eprintln!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32());
log::info!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32());
let visibility = models::load_visibility(&root, assets.registry)?;
eprintln!("load visibility: {:.2}s", started.elapsed().as_secs_f32());
log::info!("load visibility: {:.2}s", started.elapsed().as_secs_f32());
let tables = Arc::new(MeshTables::new(&assets, &facts, visibility)?);
let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?);
eprintln!("load tables: {:.2}s", started.elapsed().as_secs_f32());
log::info!("load tables: {:.2}s", started.elapsed().as_secs_f32());
let atlas = HudAtlas::build(&root)?;
horizon_client::ui::load_metadata(&root);
horizon_client::lang::set(horizon_client::lang::Language::load(
&[&root],
&early_settings.language,
));
eprintln!("load atlas: {:.2}s", started.elapsed().as_secs_f32());
log::info!("load atlas: {:.2}s", started.elapsed().as_secs_f32());
let layer_names = assets
.sprite_layers
.iter()
@@ -8764,7 +8768,7 @@ pub fn run() -> Result<()> {
let registry_owner = assets.clone();
let collision = collisions::load(&root, registry_owner.registry)?;
let motion = MotionResources::load(&root, &registry_owner)?;
eprintln!(
log::info!(
"load collision+motion: {:.2}s",
started.elapsed().as_secs_f32()
);
@@ -8775,7 +8779,7 @@ pub fn run() -> Result<()> {
light,
});
let threads = early_settings.horizon.worker_threads();
eprintln!(
log::info!(
"Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads",
started.elapsed().as_secs_f32(),
facts.states.len(),
@@ -9104,7 +9108,7 @@ pub fn run() -> Result<()> {
if let Some(path) = &game.options.control {
let server = horizon_client::control::Server::start(path)
.map_err(|e| format!("control socket {}: {e}", path.display()))?;
eprintln!("Horizon: control socket {}", server.path().display());
log::info!("Horizon: control socket {}", server.path().display());
game.control = Some(server);
}
if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") {
@@ -9157,12 +9161,12 @@ pub fn run() -> Result<()> {
"generated": game.streaming.generated_total,
"meshed_sections": game.streaming.meshed_total,
"player": game.player.as_ref().map(|p| [p.position.x, p.position.y, p.position.z]),
"error": game.error,
"error": game.error.as_ref().map(|e| e.to_string()),
});
std::fs::write(path, serde_json::to_vec_pretty(&report)?)?;
}
if let Some(e) = game.error {
return Err(e.into());
return Err(e);
}
Ok(())
}
+1 -1
View File
@@ -224,7 +224,7 @@ impl Game<'_> {
max_y: 320,
};
let found = inner.find_closest_biome(&search);
eprintln!("Horizon: title backdrop: {BIOME} at {found:?}");
log::info!("Horizon: title backdrop: {BIOME} at {found:?}");
let (_, p) = found?;
let _ = std::fs::write(&cache, format!("{} {}\n", p[0], p[2]));
Some((p[0], p[2]))
+3 -5
View File
@@ -151,12 +151,10 @@ impl Game<'_> {
)),
Some(CrashNotice::Crash) => {
// Minecraft.emergencySaveAndCrash: the world is saved, then the
// game stops with the report.
eprintln!(
"---- Minecraft Crash Report ----\n\nDescription: Manually triggered debug crash\n\njava.lang.Throwable: Manually triggered debug crash"
);
// game stops; main writes the crash report.
let crash = horizon_client::crash::DebugCrash::new();
let _ = self.save_game();
return Err("Manually triggered debug crash".into());
return Err(crash.into());
}
}
Ok(())
@@ -58,6 +58,12 @@ static SETUP: OnceLock<Mutex<Option<Setup>>> = OnceLock::new();
/// Log4j's console pattern: `[HH:mm:ss] [thread/LEVEL]: message`.
pub(super) fn log(level: &str, message: &str) {
let file_level = match level {
"WARN" => ::log::Level::Warn,
"ERROR" => ::log::Level::Error,
_ => ::log::Level::Info,
};
horizon_client::logging::write_only(file_level, message);
let secs = now_millis().div_euclid(1000).rem_euclid(86_400);
println!(
"[{:02}:{:02}:{:02}] [Server thread/{level}]: {message}",
+1 -1
View File
@@ -108,7 +108,7 @@ impl Game<'_> {
.collect();
let store = DataStore::load(&packs);
for (id, e) in &store.errors {
eprintln!("Horizon: failed to load function {id}: {e}");
log::warn!("Horizon: failed to load function {id}: {e}");
}
self.fns.store = store;
self.sync_function_registries();
+3 -3
View File
@@ -21,12 +21,12 @@ impl Game<'_> {
match features {
Ok(Some(features)) => {
self.res.behaviours.set_live_features(Arc::new(features));
eprintln!("Horizon: live features ready in {:?}", started.elapsed());
log::info!("Horizon: live features ready in {:?}", started.elapsed());
}
Ok(None) => {
eprintln!("Horizon: the worldgen bundle has no features; saplings will not grow")
log::warn!("Horizon: the worldgen bundle has no features; saplings will not grow")
}
Err(e) => eprintln!("Horizon: live features unavailable: {e}"),
Err(e) => log::warn!("Horizon: live features unavailable: {e}"),
}
}
/// `BoneMealItem.useOn` for the targeted block.
+2 -2
View File
@@ -31,7 +31,7 @@ pub fn open_folder(dir: &Path) {
"xdg-open"
};
if let Err(e) = std::process::Command::new(program).arg(dir).spawn() {
eprintln!("Horizon: could not open {}: {e}", dir.display());
log::warn!("Horizon: could not open {}: {e}", dir.display());
}
}
/// The resource root to load from, given the vanilla root and the selection.
@@ -106,7 +106,7 @@ impl Game<'_> {
}
let root = startup_root(&vanilla, &self.settings.resource_packs);
if let Err(e) = self.reload_resources(&root) {
eprintln!("Horizon: resource reload failed: {e}");
log::warn!("Horizon: resource reload failed: {e}");
}
}
fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> {
+1 -1
View File
@@ -833,7 +833,7 @@ impl Game<'_> {
let keys: HashSet<(i32, i32)> = unloaded.iter().map(|c| (c.x, c.z)).collect();
let chunks = self.entity_chunks(&keys, true);
if let Err(e) = self.save.save_entities_later(chunks) {
eprintln!("Horizon: failed to save entities: {e}");
log::warn!("Horizon: failed to save entities: {e}");
}
}
/// Leaving a dimension: its entities are saved with it.
+6 -4
View File
@@ -157,6 +157,7 @@ impl Game<'_> {
.ok_or("registries.json not found next to the resources; run the data generator reports (horizon-prepare)")?;
let lang = Arc::new(horizon_client::net::load_language(&root));
let view = self.settings.render_distance.clamp(2, 32) as i8;
horizon_client::crash::set_detail("Server", address.to_owned());
let session = Session::connect(address, name, view, lang.clone());
let player_type = super::perspective::player_type(&root);
let mut streaming = Streaming::new(
@@ -259,6 +260,7 @@ impl Game<'_> {
if let Some(mut r) = self.remote.take() {
r.session.disconnect();
}
horizon_client::crash::clear_detail("Server");
self.tab_list.reset();
self.score.board = Default::default();
self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1);
@@ -342,7 +344,7 @@ impl Game<'_> {
Some(stack)
}
fn chat_line(&mut self, text: String) {
eprintln!("[chat] {text}");
log::info!("[chat] {text}");
if let Some(r) = self.remote.as_mut() {
r.chat.push((text, Instant::now()));
if r.chat.len() > 100 {
@@ -380,12 +382,12 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.decode_errors += 1;
if r.decode_errors <= 20 {
eprintln!("Horizon: skipped undecodable packet {e}");
log::warn!("Horizon: skipped undecodable packet {e}");
}
}
}
Event::Disconnected(reason) => {
eprintln!("Horizon: disconnected: {reason}");
log::info!("Horizon: disconnected: {reason}");
return self.leave_server(Some(reason));
}
Event::Packet(packet) => self.handle_packet(*packet)?,
@@ -766,7 +768,7 @@ impl Game<'_> {
self.sync_block_entity(pos, state);
}
}
Err(e) => eprintln!("Horizon: chunk {} {}: {e}", p.x, p.z),
Err(e) => log::warn!("Horizon: chunk {} {}: {e}", p.x, p.z),
},
C::ForgetLevelChunk(p) => {
let [x, z] = p.pos;
+11 -2
View File
@@ -399,9 +399,18 @@ impl Renderer {
.await
.map_err(|e| format!("{NO_GPU_DRIVER} ({e})"))?;
let info = adapter.get_info();
eprintln!(
log::info!(
"Horizon renderer: {} ({:?}, {:?})",
info.name, info.backend, info.device_type
info.name,
info.backend,
info.device_type
);
crate::crash::set_detail(
"Graphics Adapter",
format!(
"{} ({:?}, {:?}), driver {} {}",
info.name, info.backend, info.device_type, info.driver, info.driver_info
),
);
let limits = adapter.limits();
if limits.max_texture_array_layers < layers {
+1 -1
View File
@@ -815,7 +815,7 @@ impl Hub {
let mut g = self.guests.remove(i);
g.left_reason = reason.to_owned();
if std::env::var_os("HORIZON_NET_DEBUG").is_some() {
eprintln!("[lan] {} left: {reason}", g.name);
log::info!("[lan] {} left: {reason}", g.name);
}
if !g.placed {
return g;
+1 -1
View File
@@ -403,7 +403,7 @@ fn handle(stream: TcpStream, addr: SocketAddr, shared: Arc<Shared>) {
if let Err(e) = conn::serve(stream, addr, shared)
&& std::env::var_os("HORIZON_NET_DEBUG").is_some()
{
eprintln!("[lan] {addr}: {e}");
log::warn!("[lan] {addr}: {e}");
}
}
+2
View File
@@ -36,6 +36,7 @@ pub mod container_screen;
pub mod containers;
pub mod control;
pub mod crafting;
pub mod crash;
pub mod creative;
pub mod data_cmd;
pub mod datapack;
@@ -78,6 +79,7 @@ pub mod lan;
pub mod landing;
pub mod lang;
pub mod light;
pub mod logging;
pub mod menu;
pub mod merchant;
pub mod mesher;
+505
View File
@@ -0,0 +1,505 @@
//! The game's log, as vanilla's log4j configuration writes it (client-1.21.2.xml, the one
//! 26.3's version manifest names): `logs/latest.log` in the game folder with the pattern
//! `[%d{HH:mm:ss}] [%t/%level]: %msg%n`, rolled over at start (OnStartupTriggeringPolicy, a
//! non-empty file only) and when the day changes (TimeBasedTriggeringPolicy) to
//! `logs/%d{yyyy-MM-dd}-%i.log.gz`, dated by the old file's last write. DefaultRolloverStrategy
//! keeps 7 archives a day, the newest with the highest index.
//!
//! Messages go through the `log` facade. Horizon's own still print their plain text on stderr,
//! as they did before the log existed; other crates' errors only reach the file (their
//! warnings are mostly the Vulkan loader's startup chatter).
use std::collections::VecDeque;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use chrono::{DateTime, Local, NaiveDate};
/// DefaultRolloverStrategy's default `max`: archives kept for one date.
pub const MAX_ARCHIVES_PER_DAY: u32 = 7;
/// Formatted lines kept in memory for crash reports.
const RECENT: usize = 50;
/// The platform data folder (what the `dirs` crate's data_dir gives).
pub fn data_dir() -> PathBuf {
let env = |k: &str| {
std::env::var_os(k)
.filter(|v| !v.is_empty())
.map(PathBuf::from)
};
let home = env("HOME").or_else(|| env("USERPROFILE"));
if cfg!(windows) {
if let Some(d) = env("APPDATA") {
return d;
}
} else if cfg!(target_os = "macos") {
if let Some(h) = &home {
return h.join("Library/Application Support");
}
} else if let Some(d) = env("XDG_DATA_HOME") {
return d;
} else if let Some(h) = &home {
return h.join(".local/share");
}
std::env::temp_dir()
}
/// Where the launcher runs the game and keeps its saves: `HORIZON_HOME`, else `horizon` in the
/// platform data folder (launcher/src/backend.rs `game_home`).
pub fn game_home() -> PathBuf {
match std::env::var_os("HORIZON_HOME").filter(|h| !h.is_empty()) {
Some(h) => PathBuf::from(h),
None => data_dir().join("horizon"),
}
}
/// `logs/` and `crash-reports/` of a game folder.
pub fn logs_dir(home: &Path) -> PathBuf {
home.join("logs")
}
pub fn crash_reports_dir(home: &Path) -> PathBuf {
home.join("crash-reports")
}
/// `2026-10-14-3.log.gz`
pub fn archive_name(date: NaiveDate, index: u32) -> String {
format!("{}-{index}.log.gz", date.format("%Y-%m-%d"))
}
/// The archive index of `name` if it is one of `date`'s archives.
fn archive_index(name: &str, date: NaiveDate) -> Option<u32> {
let prefix = format!("{}-", date.format("%Y-%m-%d"));
name.strip_prefix(&prefix)?
.strip_suffix(".log.gz")?
.parse()
.ok()
.filter(|&i| i > 0)
}
/// What one rollover does to the archives already there.
#[derive(Debug, PartialEq, Eq)]
pub struct Rollover {
pub delete: Option<String>,
/// In order: each target is free when its rename runs.
pub renames: Vec<(String, String)>,
pub archive: String,
}
/// DefaultRolloverStrategy with fileIndex "max": the new archive takes the next index; once
/// `max` are there the lowest goes and the others move down one.
pub fn rollover(existing: &[String], date: NaiveDate, max: u32) -> Rollover {
let mut present: Vec<u32> = existing
.iter()
.filter_map(|n| archive_index(n, date))
.collect();
present.sort_unstable();
present.dedup();
let highest = present.last().copied().unwrap_or(0);
if highest < max {
return Rollover {
delete: None,
renames: Vec::new(),
archive: archive_name(date, highest + 1),
};
}
let delete = Some(archive_name(date, present[0]));
let kept = &present[1..];
let renames = kept
.iter()
.enumerate()
.map(|(i, &from)| (from, i as u32 + 1))
.filter(|(from, to)| from != to)
.map(|(from, to)| (archive_name(date, from), archive_name(date, to)))
.collect();
Rollover {
delete,
renames,
archive: archive_name(date, kept.len() as u32 + 1),
}
}
/// `[12:04:31] [Render thread/INFO]: message`
pub fn format_line(
time: &DateTime<Local>,
thread: &str,
level: log::Level,
message: &str,
) -> String {
format!(
"[{}] [{thread}/{level}]: {message}",
time.format("%H:%M:%S")
)
}
/// Gzips `text` into the next archive for `date` in `dir`.
fn archive(dir: &Path, date: NaiveDate, text: &[u8]) -> io::Result<()> {
let names: Vec<String> = fs::read_dir(dir)?
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.collect();
let plan = rollover(&names, date, MAX_ARCHIVES_PER_DAY);
if let Some(name) = &plan.delete {
fs::remove_file(dir.join(name))?;
}
for (from, to) in &plan.renames {
fs::rename(dir.join(from), dir.join(to))?;
}
let mut gz = flate2::write::GzEncoder::new(
File::create(dir.join(&plan.archive))?,
flate2::Compression::default(),
);
gz.write_all(text)?;
gz.finish()?.sync_all()
}
/// Moves what `file` holds into an archive dated `date` and empties it. The file stays open
/// (and locked), so this works on Windows too.
fn roll(file: &mut File, dir: &Path, date: NaiveDate) -> io::Result<()> {
let mut text = Vec::new();
file.seek(SeekFrom::Start(0))?;
file.read_to_end(&mut text)?;
if !text.is_empty() {
archive(dir, date, &text)?;
}
file.set_len(0)?;
file.seek(SeekFrom::Start(0))?;
Ok(())
}
/// The open `latest.log` and the lock that keeps it this game's.
pub struct Latest {
pub file: File,
_lock: File,
}
/// Opens `dir/latest.log` for this run, archiving the last run's. None when another Horizon
/// using the same folder is writing it: that game keeps it, this one logs to stderr only. The
/// lock is a separate file (`.lock`): Windows locks are mandatory, and a locked latest.log could
/// not be read while the game runs.
pub fn open_latest(dir: &Path) -> io::Result<Option<Latest>> {
fs::create_dir_all(dir)?;
let lock = OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.open(dir.join(".lock"))?;
match lock.try_lock() {
Ok(()) => {}
Err(fs::TryLockError::WouldBlock) => return Ok(None),
Err(fs::TryLockError::Error(e)) => return Err(e),
}
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(dir.join("latest.log"))?;
let modified = file.metadata()?.modified()?;
let date = DateTime::<Local>::from(modified).date_naive();
roll(&mut file, dir, date)?;
Ok(Some(Latest { file, _lock: lock }))
}
struct State {
file: Option<Latest>,
dir: PathBuf,
/// The day the open file's lines belong to.
date: NaiveDate,
recent: VecDeque<String>,
}
struct Logger {
state: Mutex<State>,
/// What the main thread is called in the log: "Render thread", or "Server thread" for the
/// dedicated server, as in vanilla.
main_thread: &'static str,
}
static LOGGER: std::sync::OnceLock<Logger> = std::sync::OnceLock::new();
fn ours(target: &str) -> bool {
target.starts_with("horizon")
}
impl log::Log for Logger {
fn enabled(&self, meta: &log::Metadata) -> bool {
meta.level() <= log::Level::Info
&& (ours(meta.target()) || meta.level() <= log::Level::Error)
}
fn log(&self, record: &log::Record) {
if !self.enabled(record.metadata()) {
return;
}
let message = record.args().to_string();
if ours(record.target()) {
eprintln!("{message}");
}
let current = std::thread::current();
let thread = match current.name() {
Some("main") => self.main_thread,
Some(name) => name,
None => "unnamed",
};
self.write(thread, record.level(), &message);
}
fn flush(&self) {
if let Some(latest) = &mut self.state.lock().unwrap_or_else(|e| e.into_inner()).file {
let _ = latest.file.flush();
}
}
}
impl Logger {
fn write(&self, thread: &str, level: log::Level, message: &str) {
let now = Local::now();
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
let state = &mut *state;
if now.date_naive() != state.date {
if let Some(latest) = &mut state.file
&& let Err(e) = roll(&mut latest.file, &state.dir, state.date)
{
eprintln!("Horizon: could not roll over the log: {e}");
}
state.date = now.date_naive();
}
// As log4j writes a multi-line message: the pattern once, the rest as it is.
for (i, line) in message.lines().enumerate() {
let line = if i == 0 {
format_line(&now, thread, level, line)
} else {
line.to_owned()
};
if let Some(latest) = &mut state.file {
let _ = writeln!(latest.file, "{line}");
}
state.recent.push_back(line);
if state.recent.len() > RECENT {
state.recent.pop_front();
}
}
}
}
/// Starts the log in `home/logs`. The main thread shows as `main_thread` in it. Messages are
/// still printed when the file cannot be opened.
pub fn init(home: &Path, main_thread: &'static str) {
let dir = logs_dir(home);
let file = match open_latest(&dir) {
Ok(Some(latest)) => Some(latest),
Ok(None) => {
eprintln!(
"Horizon: another game is writing {}; this one logs to the terminal only",
dir.join("latest.log").display()
);
None
}
Err(e) => {
eprintln!(
"Horizon: could not open {}: {e}",
dir.join("latest.log").display()
);
None
}
};
let logger = LOGGER.get_or_init(|| Logger {
state: Mutex::new(State {
file,
dir,
date: Local::now().date_naive(),
recent: VecDeque::new(),
}),
main_thread,
});
if log::set_logger(logger).is_ok() {
log::set_max_level(log::LevelFilter::Info);
}
}
/// A line in the log from code that prints it elsewhere itself (the dedicated server console).
pub fn write_only(level: log::Level, message: &str) {
if let Some(logger) = LOGGER.get() {
let current = std::thread::current();
let thread = match current.name() {
Some("main") | None => logger.main_thread,
Some(name) => name,
};
logger.write(thread, level, message);
}
}
/// The last lines written, oldest first (for crash reports).
pub fn recent_lines() -> Vec<String> {
LOGGER.get().map_or_else(Vec::new, |l| {
l.state
.lock()
.unwrap_or_else(|e| e.into_inner())
.recent
.iter()
.cloned()
.collect()
})
}
/// Flushes the log file (before the process exits).
pub fn flush() {
if let Some(logger) = LOGGER.get() {
log::Log::flush(logger);
}
}
/// The last `lines` lines of a text file.
pub fn tail(path: &Path, lines: usize) -> io::Result<Vec<String>> {
let text = fs::read(path)?;
let text = String::from_utf8_lossy(&text);
let all: Vec<&str> = text.lines().collect();
Ok(all[all.len().saturating_sub(lines)..]
.iter()
.map(|l| l.to_string())
.collect())
}
/// The newest `crash-*.txt` in a game folder's crash-reports (names sort by time).
pub fn newest_crash_report(home: &Path) -> Option<PathBuf> {
fs::read_dir(crash_reports_dir(home))
.ok()?
.flatten()
.map(|e| e.path())
.filter(|p| {
p.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.starts_with("crash-") && n.ends_with(".txt"))
})
.max_by_key(|p| p.file_name().map(|n| n.to_owned()))
}
#[cfg(test)]
mod tests {
use super::*;
fn day(d: u32) -> NaiveDate {
NaiveDate::from_ymd_opt(2026, 10, d).unwrap()
}
#[test]
fn archives_are_named_like_vanillas() {
assert_eq!(archive_name(day(4), 1), "2026-10-04-1.log.gz");
let none: Vec<String> = Vec::new();
assert_eq!(
rollover(&none, day(14), 7),
Rollover {
delete: None,
renames: vec![],
archive: "2026-10-14-1.log.gz".into()
}
);
// Another day's archives and unrelated files do not count.
let names: Vec<String> = [
"2026-10-13-1.log.gz",
"2026-10-13-2.log.gz",
"2026-10-14-1.log.gz",
"2026-10-14-2.log.gz",
"latest.log",
"debug-1.log.gz",
]
.map(String::from)
.to_vec();
assert_eq!(rollover(&names, day(14), 7).archive, "2026-10-14-3.log.gz");
assert_eq!(rollover(&names, day(13), 7).archive, "2026-10-13-3.log.gz");
assert_eq!(rollover(&names, day(15), 7).archive, "2026-10-15-1.log.gz");
}
#[test]
fn the_eighth_archive_of_a_day_drops_the_oldest() {
let names: Vec<String> = (1..=7).map(|i| archive_name(day(14), i)).collect();
let plan = rollover(&names, day(14), 7);
assert_eq!(plan.delete.as_deref(), Some("2026-10-14-1.log.gz"));
assert_eq!(plan.renames.len(), 6);
assert_eq!(
plan.renames[0],
("2026-10-14-2.log.gz".into(), "2026-10-14-1.log.gz".into())
);
assert_eq!(
plan.renames[5],
("2026-10-14-7.log.gz".into(), "2026-10-14-6.log.gz".into())
);
assert_eq!(plan.archive, "2026-10-14-7.log.gz");
}
#[test]
fn lines_look_like_log4js_pattern() {
let time = chrono::TimeZone::with_ymd_and_hms(&Local, 2026, 10, 14, 9, 5, 7).unwrap();
assert_eq!(
format_line(
&time,
"Render thread",
log::Level::Info,
"load assets: 1.20s"
),
"[09:05:07] [Render thread/INFO]: load assets: 1.20s"
);
assert_eq!(
format_line(&time, "Worker-1", log::Level::Warn, "x"),
"[09:05:07] [Worker-1/WARN]: x"
);
}
#[test]
fn startup_archives_the_last_runs_log() {
let dir = std::env::temp_dir().join(format!("horizon-logs-test-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
// Empty: nothing is archived (OnStartupTriggeringPolicy's minSize is 1 byte).
drop(open_latest(&dir).unwrap().unwrap());
assert_eq!(fs::read_dir(&dir).unwrap().count(), 2);
fs::write(
dir.join("latest.log"),
"[10:00:00] [Render thread/INFO]: first run\n",
)
.unwrap();
let mut latest = open_latest(&dir).unwrap().unwrap();
// A second game in the same folder leaves the file alone.
assert!(open_latest(&dir).unwrap().is_none());
writeln!(latest.file, "second run").unwrap();
drop(latest);
let today = Local::now().date_naive();
let archive = dir.join(archive_name(today, 1));
let mut text = String::new();
flate2::read::GzDecoder::new(File::open(&archive).unwrap())
.read_to_string(&mut text)
.unwrap();
assert_eq!(text, "[10:00:00] [Render thread/INFO]: first run\n");
assert_eq!(
fs::read_to_string(dir.join("latest.log")).unwrap(),
"second run\n"
);
assert_eq!(
tail(&dir.join("latest.log"), 100).unwrap(),
vec!["second run"]
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn the_newest_crash_report_is_found_by_name() {
let home = std::env::temp_dir().join(format!("horizon-crash-test-{}", std::process::id()));
let _ = fs::remove_dir_all(&home);
assert!(newest_crash_report(&home).is_none());
let dir = crash_reports_dir(&home);
fs::create_dir_all(&dir).unwrap();
for name in [
"crash-2026-10-13_23.59.59-client.txt",
"crash-2026-10-14_08.00.01-client.txt",
"notes.txt",
] {
fs::write(dir.join(name), "x").unwrap();
}
assert_eq!(
newest_crash_report(&home).unwrap(),
dir.join("crash-2026-10-14_08.00.01-client.txt")
);
let _ = fs::remove_dir_all(&home);
}
}
+20 -1
View File
@@ -2,9 +2,27 @@
#![forbid(unsafe_code)]
mod game;
use horizon_client::{crash, logging};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let game_args = args.iter().take_while(|a| *a != "--dedicated");
let help = game_args.clone().any(|a| a == "--help" || a == "-h");
// The dedicated server logs in its own folder, as vanilla's does; the game in its home.
let (home, side, thread) = if args.iter().any(|a| a == "--dedicated") {
(std::path::PathBuf::from("."), "server", "Server thread")
} else {
(logging::game_home(), "client", "Render thread")
};
if !help {
logging::init(&home, thread);
crash::install(home.clone(), side);
}
if let Err(error) = game::run() {
eprintln!("Horizon: {error}");
log::error!("Horizon: {error}");
if !help {
crash::report_error(&home, side, &*error);
}
// Started from Explorer, the console window closes with the game:
// keep the message on screen until it is read.
#[cfg(windows)]
@@ -14,4 +32,5 @@ fn main() {
}
std::process::exit(1);
}
logging::flush();
}
+1 -1
View File
@@ -623,7 +623,7 @@ pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> PathBuf {
match build_overlay(vanilla, packs, &out) {
Ok(()) => out,
Err(e) => {
eprintln!("Horizon: resource packs not applied: {e}");
log::warn!("Horizon: resource packs not applied: {e}");
vanilla.to_path_buf()
}
}
+1 -1
View File
@@ -1394,7 +1394,7 @@ impl SaveDir {
};
let records = batch.iter().map(|(k, r, _)| (*k, r.tag())).collect();
if let Err(e) = write_region_records(&root, cache, folder, records) {
eprintln!("Horizon: failed to write {folder} files: {e}");
log::warn!("Horizon: failed to write {folder} files: {e}");
}
// Readers find the files (and a fresh region cache) from here on.
if let Ok(mut pending) = pending.lock() {
@@ -356,7 +356,7 @@ impl<E: Entry> UserList<E> {
}
self.map.put(key, entry);
if let Err(e) = self.save() {
eprintln!("Could not save the list after adding a user. {e}");
log::warn!("Could not save the list after adding a user. {e}");
}
true
}
@@ -365,7 +365,7 @@ impl<E: Entry> UserList<E> {
return false;
}
if let Err(e) = self.save() {
eprintln!("Could not save the list after removing a user. {e}");
log::warn!("Could not save the list after removing a user. {e}");
}
true
}
+47 -7
View File
@@ -280,16 +280,55 @@ impl Settings {
.parent()
.map(crate::graphics::Graphics::load)
.unwrap_or_default();
let Ok(bytes) = fs::read(path) else {
return Self {
let settings = match fs::read(path) {
Ok(bytes) => Self {
horizon,
..Self::parse(&String::from_utf8_lossy(&bytes))
},
Err(_) => Self {
horizon,
..Self::default()
};
},
};
Self {
horizon,
..Self::parse(&String::from_utf8_lossy(&bytes))
}
settings.describe_for_crashes();
settings
}
/// The render settings and resource packs a crash report lists.
fn describe_for_crashes(&self) {
let on = |b: bool| if b { "on" } else { "off" };
let scale = match self.gui_scale {
0 => "auto".to_owned(),
n => n.to_string(),
};
crate::crash::set_detail(
"Render Settings",
format!(
"render distance {}, simulation distance {}, graphics {}, FOV {:.0}, max FPS {}, VSync {}, fullscreen {}, GUI scale {scale}, smooth lighting {}, clouds {}, biome blend {}, mipmap levels {}",
self.render_distance,
self.simulation_distance,
self.graphics_preset,
self.fov,
if self.max_fps >= 260 {
"unlimited".to_owned()
} else {
self.max_fps.to_string()
},
on(self.vsync),
on(self.fullscreen),
on(self.smooth_lighting),
self.clouds,
self.biome_blend,
self.mipmap_levels,
),
);
crate::crash::set_detail(
"Resource Packs",
if self.resource_packs.is_empty() {
"vanilla".to_owned()
} else {
self.resource_packs.join(", ")
},
);
}
pub fn parse(text: &str) -> Self {
Self::from_file(OptionsFile::parse(text))
@@ -474,6 +513,7 @@ impl Settings {
self.to_file().serialize()
}
pub fn save(&self, path: &Path) {
self.describe_for_crashes();
let _ = fs::write(path, self.serialize());
if let Some(dir) = path.parent() {
self.horizon.save(dir);
+1 -1
View File
@@ -93,7 +93,7 @@ impl Sprites {
match self.load(root, name) {
Ok(layer) => Ok(layer),
Err(e) => {
eprintln!("Horizon: using the missing texture for {name}: {e}");
log::warn!("Horizon: using the missing texture for {name}: {e}");
// MissingTextureAtlasSprite.generateMissingImage: 16x16,
// magenta and black quarters.
let frame: Vec<u8> = (0..SPRITE_SIZE * SPRITE_SIZE)
@@ -18,7 +18,7 @@ pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
LOOT.get_or_init(|| match LootData::load(root) {
Ok(data) => Some(Arc::new(data)),
Err(e) => {
eprintln!("Horizon: loot tables unavailable, structure containers stay empty: {e}");
log::warn!("Horizon: loot tables unavailable, structure containers stay empty: {e}");
None
}
})
+4 -4
View File
@@ -55,12 +55,12 @@ impl VanillaTerrain {
OverworldGenerator::for_dimension(data, seed, "minecraft:normal", dimension)?;
let unsupported = generator.unsupported_features();
if !unsupported.is_empty() {
eprintln!(
log::warn!(
"Horizon: {} placed features cannot run and will be skipped",
unsupported.len()
);
if !dir.join("blocks/block-properties.nbt").exists() {
eprintln!(
log::warn!(
"Horizon: the worldgen bundle lacks the block behavior exports (worldgen/blocks/*.nbt); \
prepare again (the launcher, or horizon-prepare --prepare) to add them"
);
@@ -156,7 +156,7 @@ impl ChunkGenerator for VanillaTerrain {
match worker.generate_proto(ChunkPos::new(x, z)) {
Ok(chunk) => Box::new(VanillaProto::Ready(Box::new(chunk))),
Err(e) => {
eprintln!("Horizon: generating chunk {x} {z} failed: {e}");
log::warn!("Horizon: generating chunk {x} {z} failed: {e}");
Box::new(VanillaProto::Failed(x, z))
}
}
@@ -187,7 +187,7 @@ impl ChunkGenerator for VanillaTerrain {
Err(_) => unreachable!(),
};
if let Err(e) = worker.decorate(&mut array) {
eprintln!("Horizon: decorating chunk failed: {e}");
log::warn!("Horizon: decorating chunk failed: {e}");
}
for (slot, chunk) in region.iter_mut().zip(array) {
*slot = Box::new(VanillaProto::Ready(Box::new(chunk)));
+15
View File
@@ -136,6 +136,21 @@ the launcher, `horizon-ctl launch --world X --wait` is all an agent needs.
Other arguments go to the game; its output goes to a `.log` file beside the
socket.
**Logs and crash reports.** Like vanilla, the game writes `logs/latest.log`
in the game home (`$HORIZON_HOME`, else `~/.local/share/horizon`; the
dedicated server in its own folder) with lines like
`[12:04:31] [Render thread/INFO]: message`, and at start archives the last
run's as `logs/<yyyy-mm-dd>-<n>.log.gz` (seven a day). Messages still print on
stderr as before. A panic on the main thread or a fatal error writes
`crash-reports/crash-<yyyy-mm-dd_HH.MM.SS>-client.txt` (the error, its stack,
the machine, the GPU, render settings, resource packs, the open world and the
last 50 log lines) and the game exits with a non-zero code. `horizon-ctl logs
[--lines N]` prints the end of latest.log and `horizon-ctl logs --crash` the
newest report (the `logs` MCP tool returns the same). F3 + C held for ten
seconds crashes the game on purpose, as in vanilla (the world is saved first);
development builds also crash with `HORIZON_DEBUG_CRASH=SECONDS`, that long
after the first frame.
**MCP.** `horizon-ctl mcp` serves the Model Context Protocol over stdin and
stdout (JSON-RPC 2.0, one message per line), with one tool per command and a
JSON schema for each; `screenshot` returns the frame as an image. Register it
+14 -2
View File
@@ -67,9 +67,10 @@ The same binary is a command-line tool; without a subcommand it opens the window
horizon-launcher links the Discord, sponsor and website links
horizon-launcher menu-style [horizon|classic] show or set the game's menu style
horizon-launcher update [--check] Horizon and the launcher
horizon-launcher logs [--lines N] [--crash] the end of the game's log, or its newest crash report
`--json` prints JSON where there is something to report (`versions`, `install`, `notes`,
`next`, `links`, `menu-style`, `update --check`). Errors go to stderr with exit code 1. `server` runs in the terminal,
`next`, `links`, `menu-style`, `update --check`, `logs`). Errors go to stderr with exit code 1. `server` runs in the terminal,
so lines you type reach its console. `HORIZON_LAUNCHER_HOME` replaces the data folder (for
scripts and tests).
@@ -81,12 +82,23 @@ scripts and tests).
(with the full path to the binary if it is not on your `PATH`). Its tools: `list_versions`,
`install_version`, `remove_version`, `prepare_resources`, `launch_client`, `start_server`,
`server_command`, `server_log`, `stop_server`, `patch_notes`, `links`, `menu_style` and `check_updates`.
`server_command`, `server_log`, `stop_server`, `patch_notes`, `links`, `menu_style`, `logs` and
`check_updates`.
A server started through MCP stops (cleanly, with `stop`) when the session ends. Starting one
needs `accept_eula`, which an agent should only pass with the player's consent.
The window, the command line and the MCP server all call the same core, `src/backend.rs`.
## Logs and crash reports
The game writes its log to `logs/latest.log` in the game folder (`HORIZON_HOME`, else
`~/.local/share/horizon`, `~/Library/Application Support/horizon` or `%APPDATA%\horizon`), and
archives the previous one at start as `logs/<date>-<n>.log.gz`, as Minecraft does. When it
crashes it writes `crash-reports/crash-<date>_<time>-client.txt` beside them. When a game the
launcher started crashes, the Play page says so, with buttons to open or copy the report, open the
logs folder and report it on Discord; Settings has the logs folder too. Nothing is ever sent
anywhere by itself.
## Building
cargo build --release
+114
View File
@@ -704,6 +704,90 @@ pub fn game_home() -> PathBuf {
.join("horizon")
}
// ----- Logs and crash reports ---------------------------------------------------------------------
/// The game's logs (`latest.log` and the day archives), as it writes them in its home.
pub fn logs_dir() -> PathBuf {
game_home().join("logs")
}
/// Where the game writes `crash-<date>_<time>-client.txt` when it crashes.
pub fn crash_reports_dir() -> PathBuf {
game_home().join("crash-reports")
}
/// The crash reports in `dir`, oldest first (their names sort by time).
fn crash_reports_in(dir: &Path) -> Vec<PathBuf> {
let mut reports: Vec<PathBuf> = fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| {
p.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.starts_with("crash-") && n.ends_with(".txt"))
})
.collect();
reports.sort();
reports
}
/// The newest crash report, if any.
pub fn newest_crash_report() -> Option<PathBuf> {
crash_reports_in(&crash_reports_dir()).pop()
}
/// The newest crash report written at or after `since` (one from the run that started then).
pub fn crash_report_since(since: std::time::SystemTime) -> Option<PathBuf> {
crash_report_in_since(&crash_reports_dir(), since)
}
fn crash_report_in_since(dir: &Path, since: std::time::SystemTime) -> Option<PathBuf> {
crash_reports_in(dir).into_iter().rev().find(|p| {
fs::metadata(p)
.and_then(|m| m.modified())
.is_ok_and(|t| t >= since)
})
}
/// The error a crash report describes, on one line: the lines between its description and the
/// stack (`panicked at src/game.rs:10:5: boom`).
pub fn crash_summary(report: &str) -> Option<String> {
let mut lines = report
.lines()
.skip_while(|l| !l.starts_with("Description:"));
lines.next()?;
let error: Vec<&str> = lines
.skip_while(|l| l.trim().is_empty())
.take_while(|l| !l.trim().is_empty() && !l.starts_with('\t'))
.map(str::trim)
.collect();
(!error.is_empty()).then(|| error.join(" "))
}
/// The last `lines` lines of `file`, or why it cannot be read.
fn tail_of(file: &Path, lines: usize) -> Result<String, String> {
let bytes = fs::read(file).map_err(|e| format!("{}: {e}", file.display()))?;
let text = String::from_utf8_lossy(&bytes);
let all: Vec<&str> = text.lines().collect();
Ok(all[all.len().saturating_sub(lines)..].join("\n") + "\n")
}
/// `logs`: the end of the game's latest.log, or with `crash` its newest crash report. The path
/// read comes first.
pub fn read_logs(lines: usize, crash: bool) -> Result<(PathBuf, String), String> {
if crash {
let path = newest_crash_report()
.ok_or_else(|| format!("No crash report in {}.", crash_reports_dir().display()))?;
let text = fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
return Ok((path, text));
}
let path = logs_dir().join("latest.log");
let text = tail_of(&path, lines.max(1))?;
Ok((path, text))
}
/// Which drawing the game's menus use. Classic is vanilla's own screens, which have no way to
/// switch back, so the launcher is where the player returns to Horizon's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -1686,6 +1770,36 @@ mod tests {
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn crash_reports_are_found_and_summarised() {
let dir =
std::env::temp_dir().join(format!("horizon-launcher-crash-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let start = std::time::SystemTime::now() - std::time::Duration::from_secs(2);
assert!(crash_report_in_since(&dir, start).is_none());
fs::create_dir_all(&dir).unwrap();
let report = "---- Horizon Crash Report ----\n// Details below.\n\nTime: 2026-10-14 09:05:07\nDescription: Unexpected error\n\npanicked at src/game.rs:10:5:\nboom\n\t0: horizon_client::game::frame\n";
fs::write(dir.join("crash-2026-10-14_09.05.07-client.txt"), report).unwrap();
fs::write(dir.join("notes.txt"), "x").unwrap();
assert_eq!(
crash_report_in_since(&dir, start).unwrap(),
dir.join("crash-2026-10-14_09.05.07-client.txt")
);
let later = std::time::SystemTime::now() + std::time::Duration::from_secs(60);
assert!(crash_report_in_since(&dir, later).is_none());
assert_eq!(
crash_summary(report).as_deref(),
Some("panicked at src/game.rs:10:5: boom")
);
assert_eq!(crash_summary("no report"), None);
let log = dir.join("latest.log");
fs::write(&log, "a\nb\nc\n").unwrap();
assert_eq!(tail_of(&log, 2).unwrap(), "b\nc\n");
assert_eq!(tail_of(&log, 100).unwrap(), "a\nb\nc\n");
assert!(tail_of(&dir.join("missing.log"), 5).is_err());
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn plain_notes() {
let text = markdown_to_text(
+18
View File
@@ -67,6 +67,16 @@ enum Cmd {
#[arg(value_parser = ["horizon", "classic"])]
style: Option<String>,
},
/// Print the end of the game's log (logs/latest.log in the game folder), or its newest crash
/// report
Logs {
/// How many lines of latest.log
#[arg(long, default_value_t = 100)]
lines: usize,
/// The newest crash report instead
#[arg(long)]
crash: bool,
},
/// Look for a newer Horizon release and launcher, and install them
Update {
/// Only report what is available
@@ -267,6 +277,14 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
println!("Menu style: {style}");
}
}
Cmd::Logs { lines, crash } => {
let (path, text) = backend::read_logs(lines, crash)?;
if as_json {
json(serde_json::json!({ "path": path, "text": text }));
} else {
print!("{text}");
}
}
Cmd::Update { check } => update(check, as_json)?,
Cmd::Mcp => unreachable!(),
}
+182 -5
View File
@@ -50,6 +50,16 @@ enum SelfUpdate {
Failed(String),
}
/// The last game the launcher started ended badly: what it left behind.
#[derive(Clone)]
struct Crash {
/// The crash report the run wrote, if it wrote one.
report: Option<std::path::PathBuf>,
/// One line on what went wrong: the report's error, else how the process ended.
summary: String,
copied: bool,
}
/// The opening: the wordmark over the image holds at least `OPENING_HOLD` (until the release
/// list is in, at most `OPENING_MAX`), then the launcher appears over `OPENING_REVEAL`.
const OPENING_HOLD: Duration = horizon_theme::OPENING_HOLD;
@@ -133,6 +143,9 @@ struct Launcher {
prepare_error: Option<String>,
client: Option<Running>,
client_error: Option<String>,
/// When the running client started, to tell its crash report from older ones.
client_started: Option<std::time::SystemTime>,
crash: Option<Crash>,
server: Option<Running>,
server_log: VecDeque<String>,
server_error: Option<String>,
@@ -212,6 +225,8 @@ impl Launcher {
prepare_error: None,
client: None,
client_error: None,
client_started: None,
crash: None,
server: None,
server_log: VecDeque::new(),
server_error: None,
@@ -391,11 +406,32 @@ impl Launcher {
}
Job::Client => {
self.client = None;
self.client_error = error.map(|e| {
let tail =
self.prepare_log.iter().rev().find(|l| !l.trim().is_empty());
tail.map_or(e.clone(), |t| format!("{e}: {t}"))
});
let report = self
.client_started
.take()
.and_then(backend::crash_report_since);
if error.is_some() || report.is_some() {
let summary = report
.as_ref()
.and_then(|p| std::fs::read_to_string(p).ok())
.and_then(|text| backend::crash_summary(&text))
.or_else(|| {
let tail = self
.prepare_log
.iter()
.rev()
.find(|l| !l.trim().is_empty());
error.as_ref().map(|e| {
tail.map_or(e.clone(), |t| format!("{e}: {t}"))
})
})
.unwrap_or_default();
self.crash = Some(Crash {
report,
summary,
copied: false,
});
}
}
Job::Server => {
self.server = None;
@@ -511,7 +547,11 @@ impl Launcher {
return;
}
self.client_error = None;
self.crash = None;
self.prepare_log.clear();
// A little earlier than the spawn: file times can be coarse.
self.client_started =
Some(std::time::SystemTime::now() - std::time::Duration::from_secs(2));
match backend::spawn(Job::Client, backend::client_command(&tag), self.tx.clone()) {
Ok(r) => self.client = Some(r),
Err(e) => self.client_error = Some(e),
@@ -1328,6 +1368,9 @@ impl Launcher {
if let Some(e) = self.client_error.clone() {
page = page.child(notice(e, &t));
}
if let Some(crash) = self.crash.clone() {
page = page.child(self.crash_notice(crash, cx));
}
} else {
if let Some(e) = self.server_error.clone() {
page = page.child(notice(e, &t));
@@ -1337,6 +1380,120 @@ impl Launcher {
page
}
/// "Horizon crashed": the report and the logs, and where to report it.
fn crash_notice(&self, crash: Crash, cx: &mut Context<Self>) -> Div {
let t = self.theme;
let mut actions = div().flex().flex_wrap().gap(px(8.)).mt(px(4.));
if let Some(report) = crash.report.clone() {
let open = report.clone();
actions = actions
.child(
button("crash-open", "Open report", Kind::Secondary, &t)
.on_click(move |_, _, cx| cx.open_with_system(&open)),
)
.child(
button(
"crash-copy",
if crash.copied {
"Copied"
} else {
"Copy report"
},
Kind::Secondary,
&t,
)
.on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
if let Ok(text) = std::fs::read_to_string(&report) {
cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
if let Some(c) = &mut this.crash {
c.copied = true;
}
}
cx.notify();
},
)),
);
}
actions = actions.child(
button("crash-logs", "Open logs folder", Kind::Secondary, &t).on_click(|_, _, cx| {
let dir = backend::logs_dir();
let _ = std::fs::create_dir_all(&dir);
cx.open_with_system(&dir);
}),
);
let discord = self.links.discord.clone();
if !discord.is_empty() {
actions = actions.child(
button("crash-discord", "Report on Discord", Kind::Secondary, &t)
.on_click(move |_, _, cx| cx.open_url(&discord)),
);
}
actions = actions.child(
button("crash-dismiss", "Dismiss", Kind::Ghost, &t).on_click(cx.listener(
|this, _: &ClickEvent, _, cx| {
this.crash = None;
cx.notify();
},
)),
);
let help = if crash.report.is_some() {
"When you report it on Discord, attach the crash report file (or paste it with Copy report) and say what you were doing."
} else {
"The game ended without a crash report. When you report it on Discord, attach latest.log from the logs folder and say what you were doing."
};
let mut body = div()
.flex_1()
.min_w_0()
.flex()
.flex_col()
.gap(px(4.))
.child(
div()
.font_weight(FontWeight::MEDIUM)
.child("Horizon crashed"),
);
if !crash.summary.is_empty() {
body = body.child(div().text_color(t.muted).child(crash.summary));
}
if let Some(report) = &crash.report {
body = body.child(
div()
.font_family(theme::MONO)
.text_size(px(theme::SMALL))
.text_color(t.faint)
.truncate()
.child(short(report)),
);
}
body = body.child(actions).child(
div()
.mt(px(2.))
.text_size(px(theme::SMALL))
.text_color(t.muted)
.child(help),
);
div()
.flex()
.gap(px(10.))
.p(px(12.))
.rounded(px(6.))
.border_1()
.border_color(t.border)
.text_size(px(13.))
.line_height(px(19.))
.text_color(t.text)
.child(
div()
.flex_none()
.mt(px(6.))
.size(px(6.))
.rounded_full()
.bg(t.danger),
)
.child(body)
}
/// The Play page's focal point: what will start, and a line from its notes.
fn hero(&self, tag: &str, version: &str, prepared: bool, cx: &mut Context<Self>) -> Div {
let t = self.theme;
@@ -1624,6 +1781,26 @@ impl Launcher {
None,
&t,
))
.child(divider(&t))
.child(row(
"Logs",
div()
.flex()
.flex_col()
.gap(px(2.))
.child(short(&backend::logs_dir()))
.child(div().text_size(px(theme::SMALL)).text_color(t.muted).child(
"The game's log, and crash reports beside it in crash-reports.",
)),
Some(button("open-logs", "Open", Kind::Secondary, &t).on_click(
|_, _, cx| {
let dir = backend::logs_dir();
let _ = std::fs::create_dir_all(&dir);
cx.open_with_system(&dir);
},
)),
&t,
))
.child(divider(&t)),
)
.child(agents)
+8
View File
@@ -40,6 +40,8 @@ fn tools() -> Value {
{ "name": "links", "description": "The Horizon links: the Discord invite, the GitHub Sponsors page and the website (an empty one is not offered).", "inputSchema": none },
{ "name": "menu_style", "description": "Show or set the game's menu style. \"horizon\" is Horizon's own menus, \"classic\" is vanilla's screens, which have no way back inside the game. The game reads it when it starts.",
"inputSchema": { "type": "object", "properties": { "style": { "type": "string", "enum": ["horizon", "classic"], "description": "Omit to show the current style." } } } },
{ "name": "logs", "description": "Read the game's log: the last lines of logs/latest.log in the game folder, or with crash the newest crash report (what the game wrote when it last crashed). Read-only.",
"inputSchema": { "type": "object", "properties": { "lines": { "type": "integer", "minimum": 1, "maximum": 5000, "description": "How many lines of latest.log (default 100)." }, "crash": { "type": "boolean", "description": "Return the newest crash report instead." } } } },
{ "name": "check_updates", "description": "Check GitHub for a Horizon release newer than every installed version, and for a newer launcher.", "inputSchema": none },
])
}
@@ -212,6 +214,12 @@ impl Session {
))
}
"links" => Ok(serde_json::to_string_pretty(&backend::links()).unwrap()),
"logs" => {
let lines = args.get("lines").and_then(Value::as_u64).unwrap_or(100);
let crash = args.get("crash").and_then(Value::as_bool).unwrap_or(false);
let (path, text) = backend::read_logs(lines.clamp(1, 5000) as usize, crash)?;
Ok(format!("{}\n\n{text}", path.display()))
}
"menu_style" => {
if let Some(name) = arg_str(args, "style") {
let style = backend::MenuStyle::parse(name)
+62
View File
@@ -0,0 +1,62 @@
//! `horizon-launcher logs`: the end of the game's latest.log, and its newest crash report.
use std::path::Path;
use std::process::Command;
fn logs(home: &Path, args: &[&str]) -> (bool, String, String) {
let out = Command::new(env!("CARGO_BIN_EXE_horizon-launcher"))
.arg("logs")
.args(args)
.env("HORIZON_HOME", home)
.output()
.unwrap();
(
out.status.success(),
String::from_utf8_lossy(&out.stdout).into_owned(),
String::from_utf8_lossy(&out.stderr).into_owned(),
)
}
#[test]
fn logs_prints_the_log_tail_and_the_newest_crash_report() {
let home = std::env::temp_dir().join(format!("horizon-launcher-logs-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&home);
let (ok, _, err) = logs(&home, &[]);
assert!(!ok);
assert!(err.contains("latest.log"), "{err}");
std::fs::create_dir_all(home.join("logs")).unwrap();
let text: String = (1..=150)
.map(|i| format!("[10:00:00] [Render thread/INFO]: line {i}\n"))
.collect();
std::fs::write(home.join("logs/latest.log"), text).unwrap();
let (ok, out, _) = logs(&home, &[]);
assert!(ok);
assert_eq!(out.lines().count(), 100);
assert!(out.starts_with("[10:00:00] [Render thread/INFO]: line 51\n"));
let (_, out, _) = logs(&home, &["--lines", "1"]);
assert_eq!(out, "[10:00:00] [Render thread/INFO]: line 150\n");
let (_, out, _) = logs(&home, &["--json", "--lines", "1"]);
let json: serde_json::Value = serde_json::from_str(&out).unwrap();
assert_eq!(json["text"], "[10:00:00] [Render thread/INFO]: line 150\n");
assert!(json["path"].as_str().unwrap().ends_with("latest.log"));
let (ok, _, err) = logs(&home, &["--crash"]);
assert!(!ok);
assert!(err.contains("No crash report"), "{err}");
std::fs::create_dir_all(home.join("crash-reports")).unwrap();
std::fs::write(
home.join("crash-reports/crash-2026-10-13_08.00.00-client.txt"),
"old\n",
)
.unwrap();
std::fs::write(
home.join("crash-reports/crash-2026-10-14_08.00.00-client.txt"),
"new\n",
)
.unwrap();
let (ok, out, _) = logs(&home, &["--crash"]);
assert!(ok);
assert_eq!(out, "new\n");
let _ = std::fs::remove_dir_all(&home);
}