Opt-in data collection (2/5): the launcher asks, and Settings changes it

- First run (and when CONSENT_VERSION changes): a question over the launcher
  with four switches, all off, what each sends in plain words, what is never
  sent, "View what would be sent" (the exact JSON), and "Send nothing" /
  "Save choices".
- Settings → Data collection: the same switches any time, the install ID and
  what waits, "View what would be sent" and "Delete my data" (server deletion,
  outbox cleared, new install ID).
- The outbox is sent at start and on close (at most 3 s), only when there is a
  server (none yet) and only what the player allows.
- CLI `horizon-launcher data status|allow|deny|show|delete|send|bug|benchmark`
  and MCP tools data_collection, set_data_collection, data_preview,
  delete_my_data, report_bug. Bug reports and benchmark uploads are printed for
  the player to confirm; logs are scrubbed and lose chat lines.
- horizon-telemetry joins the launcher's paths (launcher.yml, release_train,
  pr_ready).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-15 02:33:04 +02:00
parent 713ff1d4a1
commit d53a366718
10 changed files with 836 additions and 7 deletions
+3 -1
View File
@@ -1,6 +1,7 @@
name: launcher
# Builds the launcher on Linux, macOS and Windows, and releases it by itself (docs/release-flow.md): after a
# push to main that changes the launcher or what it builds in (crates/horizon-prepare, crates/horizon-theme),
# push to main that changes the launcher or what it builds in (crates/horizon-prepare, crates/horizon-theme,
# crates/horizon-telemetry),
# every 10 minutes (a release waiting for merges to settle goes out) and by hand, tools/release_train.py decides as
# for the game.
# A release is launcher-vX.Y.Z: the patch after the last launcher tag, or the next minor when a merged pull
@@ -16,6 +17,7 @@ on:
- 'launcher/**'
- 'crates/horizon-prepare/**'
- 'crates/horizon-theme/**'
- 'crates/horizon-telemetry/**'
- '.github/workflows/launcher.yml'
schedule:
- cron: '7-59/10 * * * *'
+23 -4
View File
@@ -84,9 +84,15 @@ The same binary is a command-line tool; without a subcommand it opens the window
horizon-launcher account select <name> play as this account
horizon-launcher account offline play without an account
horizon-launcher benchmark [--repeats N] measure the launcher (see Performance log)
horizon-launcher data [status] what data collection is allowed, the install ID, what waits
horizon-launcher data allow|deny <kinds|all> performance, crashes, bugs, benchmarks
horizon-launcher data show exactly what would be sent
horizon-launcher data delete delete what was sent and what waits; new install ID
horizon-launcher data bug "<text>" [--log] a bug report, printed for you to confirm first
horizon-launcher data benchmark <report.json> upload a benchmark report, printed first
`--json` prints JSON where there is something to report (`versions`, `install`, `notes`,
`next`, `links`, `menu-style`, `update --check`, `logs`, `account`, `benchmark`). Errors go to stderr with exit code 1. `server` runs in the terminal,
`next`, `links`, `menu-style`, `update --check`, `logs`, `account`, `benchmark`, `data`). 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).
@@ -100,7 +106,9 @@ scripts and tests).
`install_version`, `remove_version`, `prepare_resources`, `launch_client`, `start_server`,
`server_command`, `server_log`, `stop_server`, `patch_notes`, `links`, `menu_style`, `logs`,
`check_updates`, `accounts`, `sign_in` (returns the link and code for the player; the sign-in
finishes in the background), `sign_out` and `select_account`.
finishes in the background), `sign_out`, `select_account`, and for data collection
`data_collection`, `set_data_collection`, `data_preview`, `delete_my_data` and `report_bug`
(only with the player's say-so).
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.
@@ -136,8 +144,19 @@ The game writes its log to `logs/latest.log` in the game folder (`HORIZON_HOME`,
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.
logs folder and report it on Discord; Settings has the logs folder too. A crash report leaves the
machine only if you turn on crash reports (below).
## Data collection
The first time it opens, the launcher asks whether you want to send performance statistics,
crash reports, bug reports and benchmark uploads, each on its own switch and all off until you
turn one on ("Send nothing" is one click). Settings → Data collection changes them any time, shows
exactly what would be sent (the JSON), and deletes everything sent from your install. It asks
again only when what is collected changes. The game obeys the same answer, kept in
`telemetry/consent.json` in the game folder. What waits is sent when the launcher starts and
closes. Every field, the caps and the format: [docs/telemetry.md](../docs/telemetry.md).
## Performance log
+120
View File
@@ -38,6 +38,44 @@ enum AccountCmd {
Offline,
}
#[derive(Subcommand)]
enum DataCmd {
/// What is allowed, the install ID and how many items wait (the default)
Status,
/// Turn kinds on: performance, crashes, bugs, benchmarks, or all
Allow {
#[arg(required = true)]
kinds: Vec<String>,
},
/// Turn kinds off: performance, crashes, bugs, benchmarks, or all
Deny {
#[arg(required = true)]
kinds: Vec<String>,
},
/// Print exactly what would be sent
Show,
/// Delete everything sent from here, and what waits, and take a new install ID
Delete,
/// Send what is waiting now
Send,
/// Send a bug report you write; it is printed first, as it would leave
Bug {
text: String,
/// Add the end of the game's log (scrubbed, without chat)
#[arg(long)]
log: bool,
/// Send without asking
#[arg(long)]
yes: bool,
},
/// Upload a benchmark report (docs/benchmark-report.md); it is printed first
Benchmark {
file: PathBuf,
#[arg(long)]
yes: bool,
},
}
#[derive(Subcommand)]
enum Cmd {
/// List Horizon releases, or the installed versions
@@ -116,6 +154,12 @@ enum Cmd {
#[arg(long)]
remove: bool,
},
/// Opt-in data collection (docs/telemetry.md): what is allowed, what would be sent, and
/// deleting it; all off until you allow a kind
Data {
#[command(subcommand)]
action: Option<DataCmd>,
},
/// Serve the Model Context Protocol on stdin and stdout, for AI agents
Mcp,
/// Measure the launcher: starts (the first is the cold one), page switching, idle CPU and
@@ -341,6 +385,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
}
}
Cmd::Update { check } => update(check, as_json)?,
Cmd::Data { action } => data(action.unwrap_or(DataCmd::Status), as_json)?,
Cmd::DesktopEntry { remove } => {
let mut settings = backend::Settings::load();
settings.desktop_entry = Some(!remove);
@@ -469,3 +514,78 @@ fn account_command(action: AccountCmd, as_json: bool) -> Result<(), String> {
}
Ok(())
}
/// `data`: the same consent as Settings → Data collection.
fn data(action: DataCmd, as_json: bool) -> Result<(), String> {
use horizon_launcher::telemetry;
let review = |item: &horizon_telemetry::Item, yes: bool| -> Result<bool, String> {
println!(
"{}",
serde_json::to_string_pretty(item).map_err(|e| e.to_string())?
);
if yes {
return Ok(true);
}
if !std::io::stdin().is_terminal() {
return Err("Add --yes to send it without asking.".into());
}
eprint!("Send this? [y/N] ");
let mut line = String::new();
std::io::stdin()
.read_line(&mut line)
.map_err(|e| e.to_string())?;
Ok(line.trim().eq_ignore_ascii_case("y"))
};
match action {
DataCmd::Status => {
let status = telemetry::status_json();
if as_json {
json(status);
return Ok(());
}
let consent = telemetry::consent();
if consent.needs_asking() {
println!("Not answered yet: nothing is collected.");
}
for (kind, name, _) in telemetry::SWITCHES {
let on = consent.allows(kind);
println!("{name}: {}", if on { "on" } else { "off" });
}
println!("Waiting to be sent: {}", status["waiting"]);
match horizon_telemetry::endpoint() {
Some(url) => println!("Server: {url}"),
None => println!("Server: none yet, nothing is sent"),
}
}
DataCmd::Allow { kinds } => {
telemetry::set(&telemetry::parse_kinds(&kinds)?, true)?;
return data(DataCmd::Status, as_json);
}
DataCmd::Deny { kinds } => {
telemetry::set(&telemetry::parse_kinds(&kinds)?, false)?;
return data(DataCmd::Status, as_json);
}
DataCmd::Show => {
let (what, text) = telemetry::preview();
eprintln!("{what}");
println!("{text}");
}
DataCmd::Delete => println!("{}", telemetry::delete_my_data()?),
DataCmd::Send => println!("{:?}", telemetry::send()),
DataCmd::Bug { text, log, yes } => {
telemetry::ensure_allowed(horizon_telemetry::Kind::Bug)?;
let item = telemetry::bug_report(&text, log)?;
if review(&item, yes)? {
println!("{}", telemetry::submit(&item)?);
}
}
DataCmd::Benchmark { file, yes } => {
telemetry::ensure_allowed(horizon_telemetry::Kind::Benchmark)?;
let item = telemetry::benchmark_report(&file)?;
if review(&item, yes)? {
println!("{}", telemetry::submit(&item)?);
}
}
}
Ok(())
}
+307
View File
@@ -0,0 +1,307 @@
//! Data collection in the window: the question asked once (and again when what is collected
//! changes), and its section in Settings. Everything goes through `horizon_launcher::telemetry`.
use super::*;
use horizon_launcher::telemetry;
use horizon_telemetry::{Choices, Consent, Kind as DataKind};
/// What the window keeps about data collection.
pub(crate) struct Collection {
pub consent: Consent,
/// The question's switches, until the player answers.
pub draft: Choices,
/// "View what would be sent": a line on what it is, and the JSON.
pub view: Option<(String, String)>,
/// What "Delete my data" did, or why it could not.
pub note: Option<String>,
pub confirm_delete: bool,
}
impl Collection {
pub fn load() -> Self {
Self {
consent: telemetry::consent(),
draft: Choices::NONE,
view: None,
note: None,
confirm_delete: false,
}
}
}
fn kind_id(prefix: &str, kind: DataKind) -> &'static str {
match (prefix, kind) {
("ask", DataKind::Perf) => "ask-perf",
("ask", DataKind::Crash) => "ask-crash",
("ask", DataKind::Bug) => "ask-bug",
("ask", DataKind::Benchmark) => "ask-benchmark",
(_, DataKind::Perf) => "data-perf",
(_, DataKind::Crash) => "data-crash",
(_, DataKind::Bug) => "data-bug",
(_, DataKind::Benchmark) => "data-benchmark",
}
}
/// The exact JSON, in mono, scrolling inside a plate.
fn json_view(view: &(String, String), t: &Theme) -> Div {
div()
.flex()
.flex_col()
.gap(px(8.))
.child(
text(theme::CAPTION)
.text_color(t.muted)
.child(view.0.clone()),
)
.child(
div()
.id("data-json")
.max_h(px(260.))
.overflow_y_scroll()
.p(px(16.))
.rounded(px(theme::RADIUS_PLATE))
.bg(t.plate)
.font_family(theme::MONO)
.text_size(px(theme::CAPTION.px))
.line_height(px(18.))
.text_color(t.ink_soft)
.children(view.1.lines().map(|l| div().child(l.to_string()))),
)
}
impl Launcher {
/// Whether the question covers the window: not answered for this consent version, and the
/// opening is over.
pub(crate) fn asking_consent(&self) -> bool {
self.opening.is_none() && self.collection.consent.needs_asking()
}
fn answer_consent(&mut self, choices: Choices) {
match telemetry::answer(choices) {
Ok(consent) => self.collection.consent = consent,
Err(e) => self.collection.note = Some(format!("Could not save your choice: {e}")),
}
self.collection.view = None;
}
fn toggle_view(&mut self) {
self.collection.view = match self.collection.view {
Some(_) => None,
None => Some(telemetry::preview()),
};
}
/// The question, centred over the launcher. Everything starts off; "Send nothing" is one
/// click, as easy as saying yes.
pub(crate) fn consent_screen(&mut self, cx: &mut Context<Self>) -> Stateful<Div> {
let t = self.theme;
let draft = self.collection.draft;
let rows = telemetry::SWITCHES.iter().map(|&(kind, name, what)| {
let on = draft.allows(kind);
div()
.flex()
.items_start()
.gap(px(16.))
.py(px(10.))
.border_b_1()
.border_color(t.rule)
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_w_0()
.gap(px(2.))
.child(text(theme::UI).text_color(t.ink).child(name))
.child(text(theme::CAPTION).text_color(t.muted).child(what)),
)
.child(switch(kind_id("ask", kind), on, &t).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
this.collection.draft.set(kind, !on);
cx.notify();
},
)))
});
let viewing = self.collection.view.is_some();
let card = plate(&t)
.flex()
.flex_col()
.gap(px(12.))
.w_full()
.max_w(px(680.))
.p(px(28.))
.bg(t.page)
.border_1()
.border_color(t.rule)
.child(caps("Data collection").text_color(t.muted))
.child(
text(theme::HEADING)
.text_color(t.ink)
.child("Help make Horizon faster and steadier?"),
)
.child(text(theme::UI).text_color(t.muted).child(
"Horizon can send a few things to its developers. Everything is off until you turn it on, and Settings can change it any time.",
))
.child(div().flex().flex_col().border_t_1().border_color(t.rule).children(rows))
.child(text(theme::CAPTION).text_color(t.muted).child(telemetry::NEVER))
.child(
div()
.id("ask-view")
.text_size(px(theme::UI.px))
.text_color(t.accent)
.cursor_pointer()
.hover(|s| s.opacity(0.8))
.child(if viewing { "Hide what would be sent" } else { "View what would be sent" })
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.toggle_view();
cx.notify();
})),
)
.children(self.collection.view.as_ref().map(|v| json_view(v, &t)))
.child(
div()
.flex()
.justify_end()
.gap(px(12.))
.pt(px(8.))
.child(button("ask-none", "Send nothing", Kind::Secondary, &t).on_click(
cx.listener(|this, _: &ClickEvent, _, cx| {
this.answer_consent(Choices::NONE);
cx.notify();
}),
))
.child(button("ask-save", "Save choices", Kind::Primary, &t).on_click(
cx.listener(|this, _: &ClickEvent, _, cx| {
this.answer_consent(this.collection.draft);
cx.notify();
}),
)),
);
div()
.id("consent")
.absolute()
.top_0()
.left_0()
.size_full()
.flex()
.flex_col()
.bg(t.page.opacity(0.92))
.overflow_y_scroll()
// Taller than a small window: it scrolls, from the top, rather than shrinking.
.child(
div()
.flex()
.flex_none()
.justify_center()
.px(px(32.))
.py(px(24.))
.child(card),
)
}
/// Settings' data collection: a switch per kind, then the player's data.
pub(crate) fn collection_section(&mut self, cx: &mut Context<Self>) -> Div {
let t = self.theme;
let consent = self.collection.consent.clone();
let mut list = div().flex().flex_col().border_t_1().border_color(t.rule);
for (i, &(kind, name, what)) in telemetry::SWITCHES.iter().enumerate() {
let on = !consent.needs_asking() && consent.choices.allows(kind);
let toggle = switch(kind_id("data", kind), on, &t).on_click(cx.listener(
move |this, _: &ClickEvent, _, cx| {
let mut choices = if this.collection.consent.needs_asking() {
Choices::NONE
} else {
this.collection.consent.choices
};
choices.set(kind, !on);
this.answer_consent(choices);
cx.notify();
},
));
list = list.child(index_row(
i + 1,
name,
Some(div().child(what).into_any_element()),
Some(toggle.into_any_element()),
&t,
));
}
let waiting = horizon_telemetry::outbox::pending(&telemetry::home()).len();
let id = match consent.install_id.as_str() {
"" => "No install ID: nothing has been collected".to_string(),
id => format!("Install ID {}…{}", &id[..4], &id[id.len() - 4..]),
};
let server = if horizon_telemetry::endpoint().is_some() {
format!("{waiting} waiting to be sent")
} else {
"No data server yet: nothing is sent".into()
};
let confirm = self.collection.confirm_delete;
let actions = div()
.flex()
.gap(px(8.))
.child(
button(
"data-view",
if self.collection.view.is_some() {
"Hide"
} else {
"View what would be sent"
},
Kind::Ghost,
&t,
)
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
this.toggle_view();
cx.notify();
})),
)
.child(
button(
"data-delete",
if confirm {
"Delete everything?"
} else {
"Delete my data"
},
Kind::Secondary,
&t,
)
.on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
if this.collection.confirm_delete {
this.collection.note = Some(match telemetry::delete_my_data() {
Ok(done) => done,
Err(e) => e,
});
this.collection.consent = telemetry::consent();
this.collection.view = None;
}
this.collection.confirm_delete = !this.collection.confirm_delete;
cx.notify();
})),
);
list = list.child(index_row(
telemetry::SWITCHES.len() + 1,
"Your data",
Some(
div()
.font_family(theme::MONO)
.child(format!("{id} · {server}"))
.into_any_element(),
),
Some(actions.into_any_element()),
&t,
));
div()
.flex()
.flex_col()
.gap(px(16.))
.child(text(theme::HEADING).text_color(t.ink).child("Data collection"))
.child(text(theme::UI).max_w(px(600.)).text_color(t.muted).child(
"Off unless you turn it on. What each switch sends is below it; the privacy page on playhorizon.dev says how long it is kept.",
))
.child(list)
.child(text(theme::CAPTION).text_color(t.muted).child(telemetry::NEVER))
.children(self.collection.note.clone().map(|n| text(theme::UI).text_color(t.ink).child(n)))
.children(self.collection.view.as_ref().map(|v| json_view(v, &t)))
}
}
+1
View File
@@ -2,3 +2,4 @@
pub mod account;
pub mod backend;
pub mod desktop;
pub mod telemetry;
+16 -1
View File
@@ -2,6 +2,7 @@
//! and starts the client or a dedicated server.
mod cli;
mod collection;
mod game_tools;
mod markdown;
mod mcp;
@@ -16,6 +17,7 @@ use gpui::{
};
use horizon_launcher::account::{self, Accounts, SignIn, SignInState};
use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates};
use horizon_launcher::telemetry;
use std::borrow::Cow;
use std::collections::VecDeque;
use std::sync::mpsc::{channel, Receiver, Sender};
@@ -147,6 +149,8 @@ struct Launcher {
friend_focus: FocusHandle,
joining: Option<String>,
console_scroll: ScrollHandle,
/// Opt-in data collection: the player's answer and Settings' section (`collection`).
collection: collection::Collection,
tx: Sender<Msg>,
rx: Receiver<Msg>,
_appearance: Subscription,
@@ -253,6 +257,7 @@ impl Launcher {
friend_focus: cx.focus_handle(),
joining: None,
console_scroll: ScrollHandle::new(),
collection: collection::Collection::load(),
tx,
rx,
_appearance: appearance,
@@ -279,6 +284,8 @@ impl Launcher {
});
this.fetch_startup_releases();
this.fetch_links();
// What the game and the launcher kept, if the player allows it and there is a server.
telemetry::send_in_background();
this
}
@@ -2020,6 +2027,7 @@ impl Launcher {
))
}),
)
.child(self.collection_section(cx))
.child(agents)
}
@@ -2814,6 +2822,9 @@ impl Render for Launcher {
)
.child(self.footer(cx)),
);
if self.asking_consent() {
root = root.child(self.consent_screen(cx));
}
if let Some(opening) = &self.opening {
// The wordmark arrives letter by letter, then gives way to the launcher; a click or
// a key skips ahead.
@@ -2931,7 +2942,11 @@ fn main() {
|window, cx| cx.new(|cx| Launcher::new(window, cx)),
)
.expect("window");
cx.on_window_closed(|cx| cx.quit()).detach();
cx.on_window_closed(|cx| {
telemetry::send_before_exit();
cx.quit()
})
.detach();
cx.activate(true);
});
}
+47
View File
@@ -5,6 +5,7 @@
use crate::game_tools::{self, GameTools};
use horizon_launcher::account::{self, Accounts, SignIn, SignInState};
use horizon_launcher::backend::{self, Job, Logged};
use horizon_launcher::telemetry;
use serde_json::{json, Value};
use std::io::{BufRead, Write};
use std::path::PathBuf;
@@ -58,6 +59,13 @@ fn tools() -> Value {
{ "name": "select_account", "description": "Choose the account the game plays as, or \"offline\" to play without one.",
"inputSchema": { "type": "object", "properties": { "account": { "type": "string", "description": "A name or UUID, or \"offline\"." } }, "required": ["account"] } },
{ "name": "check_updates", "description": "Check GitHub for a Horizon release newer than every installed version, and for a newer launcher.", "inputSchema": none },
{ "name": "data_collection", "description": "The player's opt-in data collection: which kinds they allow (performance, crashes, bugs, benchmarks; all off until they answer), the install ID, how many items wait, and the data server. Read-only.", "inputSchema": none },
{ "name": "set_data_collection", "description": "Turn kinds of data collection on or off. Only when the player asks: it records their consent.",
"inputSchema": { "type": "object", "properties": { "kinds": { "type": "array", "items": { "type": "string", "enum": ["performance", "crashes", "bugs", "benchmarks", "all"] } }, "on": { "type": "boolean" } }, "required": ["kinds", "on"] } },
{ "name": "data_preview", "description": "Exactly what would be sent (the JSON), or an example of each kind when nothing waits. Sends nothing.", "inputSchema": none },
{ "name": "delete_my_data", "description": "Ask the server to delete everything sent from this install, remove what waits, and take a new install ID. Only when the player asks.", "inputSchema": none },
{ "name": "report_bug", "description": "Send a bug report in the player's words, only once they have agreed to send it (bug reports must be allowed). With include_log the end of the game's log goes too, scrubbed and without chat: show it to the player first (the logs tool). Returns exactly what was kept.",
"inputSchema": { "type": "object", "properties": { "text": { "type": "string" }, "include_log": { "type": "boolean" } }, "required": ["text"] } },
])
}
@@ -273,6 +281,45 @@ impl Session {
}
Ok(format!("Menu style: {}", backend::menu_style().name()))
}
"data_collection" => Ok(serde_json::to_string_pretty(&telemetry::status_json())
.map_err(|e| e.to_string())?),
"set_data_collection" => {
let kinds: Vec<String> = args
.get("kinds")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect()
})
.unwrap_or_default();
let on = args
.get("on")
.and_then(Value::as_bool)
.ok_or("on is required")?;
telemetry::set(&telemetry::parse_kinds(&kinds)?, on)?;
Ok(serde_json::to_string_pretty(&telemetry::status_json())
.map_err(|e| e.to_string())?)
}
"data_preview" => {
let (what, text) = telemetry::preview();
Ok(format!("{what}\n{text}"))
}
"delete_my_data" => telemetry::delete_my_data(),
"report_bug" => {
let text = arg_str(args, "text").ok_or("text is required")?;
let with_log = args
.get("include_log")
.and_then(Value::as_bool)
.unwrap_or(false);
let item = telemetry::bug_report(text, with_log)?;
let done = telemetry::submit(&item)?;
Ok(format!(
"{done}\n{}",
serde_json::to_string_pretty(&item).map_err(|e| e.to_string())?
))
}
"check_updates" => {
let u = backend::check_updates()?;
Ok(serde_json::to_string_pretty(&json!({
+317
View File
@@ -0,0 +1,317 @@
//! Opt-in data collection from the launcher (`horizon_telemetry`): the player's answer, what
//! would be sent, deleting it, bug reports and benchmark uploads, and sending the outbox when
//! the launcher starts and closes. The window, the CLI and the MCP server all go through here.
use std::path::{Path, PathBuf};
use horizon_telemetry::payload::{Bug, Crash, Perf, System, Timings};
use horizon_telemetry::scrub::Scrubber;
use horizon_telemetry::upload::{self, Flush};
use horizon_telemetry::{outbox, Choices, Consent, Item, Kind, Payload, Source};
use crate::{account::Accounts, backend};
/// Each switch: its name, and in plain words exactly what it sends.
pub const SWITCHES: [(Kind, &str, &str); 4] = [
(
Kind::Perf,
"Performance statistics",
"After each session: frame-time percentiles and a 14-bucket histogram, tick times, peak memory and startup times, with your OS, CPU, GPU, driver, memory size and the settings that change performance.",
),
(
Kind::Crash,
"Crash reports",
"When the game crashes: the error, where in Horizon's code it happened, your graphics adapter and settings. No log, no world or server, no user name in paths.",
),
(
Kind::Bug,
"Bug reports",
"Only the reports you write and send yourself, with the game's log if you add it after reading it.",
),
(
Kind::Benchmark,
"Benchmark uploads",
"The results of benchmarks you run, for the community results on playhorizon.dev.",
),
];
/// Never sent, whatever the switches say.
pub const NEVER: &str = "Never sent: your account name or UUID, world names, server addresses, chat, or your IP address. Each report is dated to the day, under a random install ID you can delete.";
pub fn home() -> PathBuf {
backend::game_home()
}
pub fn consent() -> Consent {
Consent::load(&home())
}
/// Records the player's answer. Waiting items of kinds now off are deleted at once.
pub fn answer(choices: Choices) -> Result<Consent, String> {
let home = home();
let mut consent = Consent::load(&home);
consent.answer(choices);
consent.save(&home).map_err(|e| e.to_string())?;
outbox::retain_allowed(&home);
Ok(consent)
}
/// The exact JSON the next upload would send, under a line saying what it is. With nothing
/// waiting, one example of each kind, made on this machine.
pub fn preview() -> (String, String) {
let home = home();
let waiting = outbox::retain_allowed(&home).len();
if waiting > 0 {
let what = format!(
"{waiting} item{} waiting to be sent, exactly as they will leave (compressed):",
if waiting == 1 { "" } else { "s" }
);
return (what, upload::preview(&home));
}
let system = System::detect();
let examples = vec![
Item::new(
Source::Game,
"v2026.10.15",
Payload::Perf(Perf {
system: system.clone(),
seconds: 1800,
frames: Timings::new().summary(),
..Perf::default()
}),
),
Item::new(
Source::Game,
"v2026.10.15",
Payload::Crash(Crash {
system: system.clone(),
error: "panicked at crates/horizon-client/src/game.rs:120:9: …".into(),
stack: "horizon_client::game::Game::tick (crates/horizon-client/src/game.rs:120:9)"
.into(),
thread: "Render thread".into(),
details: vec![("Graphics".into(), "Apple M4 Pro (Metal)".into())],
}),
),
Item::new(
Source::Launcher,
backend::VERSION,
Payload::Bug(Bug {
system,
text: "What you write.".into(),
log: None,
}),
),
];
let json = serde_json::to_string_pretty(&serde_json::json!({
"schema": horizon_telemetry::SCHEMA,
"install_id": consent().install_id,
"items": examples,
}))
.unwrap_or_default();
(
"Nothing is waiting. One example of each kind, from this machine (a benchmark upload is the report itself, see docs/benchmark-report.md):".into(),
json,
)
}
/// "Delete my data": the server deletes everything sent under this install's ID, the waiting
/// items go, and the install gets a new ID. If the server can't be reached the ID is kept, so
/// the deletion can be asked again.
pub fn delete_my_data() -> Result<String, String> {
let home = home();
let mut consent = Consent::load(&home);
outbox::clear(&home).map_err(|e| e.to_string())?;
let remote = match horizon_telemetry::endpoint() {
_ if consent.install_id.is_empty() => "Nothing was ever sent from here.",
None => "Nothing was sent: there is no data server yet.",
Some(url) => {
upload::delete_remote(&url, &consent.install_id)
.map_err(|e| format!("The server could not be reached ({e}). Try again later."))?;
"The server deleted everything sent from here."
}
};
consent.reset_install_id();
consent.save(&home).map_err(|e| e.to_string())?;
Ok(format!(
"{remote} Nothing is waiting, and this install has a new ID."
))
}
/// Hides the player's account names and UUIDs and their worlds' folder names, besides what
/// `Scrubber` finds on its own.
pub fn scrubber() -> Scrubber {
let mut s = Scrubber::new();
for account in Accounts::load().accounts {
s = s.term(account.name).term(account.uuid);
}
let saves = std::fs::read_dir(home().join("saves"))
.into_iter()
.flatten()
.flatten();
for world in saves {
s = s.term(world.file_name().to_string_lossy());
}
s
}
/// The end of the game's log as a bug report would carry it: scrubbed, without chat.
pub fn log_for_report() -> Option<String> {
let (_, text) = backend::read_logs(300, false).ok()?;
let kept: Vec<&str> = text.lines().filter(|l| !l.contains("[CHAT]")).collect();
let mut log = scrubber().scrub(&kept.join("\n"));
// Within the item's size, the newest lines first to stay.
while log.len() > 64 * 1024 {
let cut = log.find('\n').map_or(log.len(), |i| i + 1);
log.drain(..cut);
}
Some(log)
}
/// A bug report, ready to be read before it is kept.
pub fn bug_report(text: &str, with_log: bool) -> Result<Item, String> {
let item = Item::new(
Source::Launcher,
backend::VERSION,
Payload::Bug(Bug {
system: System::detect(),
text: scrubber().scrub(text.trim()),
log: with_log.then(log_for_report).flatten(),
}),
);
item.validate()?;
Ok(item)
}
/// An error unless the player allows `kind`.
pub fn ensure_allowed(kind: Kind) -> Result<(), String> {
if consent().allows(kind) {
return Ok(());
}
Err(format!(
"{} are off: turn them on in Settings → Data collection first.",
label(kind)
))
}
/// Keeps `item` and sends the outbox; says what happened.
pub fn submit(item: &Item) -> Result<String, String> {
ensure_allowed(item.kind())?;
if !outbox::push(&home(), item).map_err(|e| e.to_string())? {
return Err("Today's limit for these is reached; try again tomorrow.".into());
}
Ok(match send() {
Flush::Sent { .. } => "Sent. Thank you.".into(),
Flush::Nothing if horizon_telemetry::endpoint().is_none() => {
"Kept to be sent once the data server is up.".into()
}
_ => "Kept; it will be sent the next time the launcher starts.".into(),
})
}
/// A benchmark report file (`docs/benchmark-report.md`), scrubbed, as an upload.
pub fn benchmark_report(path: &Path) -> Result<Item, String> {
let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
let report: serde_json::Value = serde_json::from_str(&scrubber().scrub(&text))
.map_err(|e| format!("{}: not a JSON report ({e})", path.display()))?;
let item = Item::new(
Source::Launcher,
backend::VERSION,
Payload::Benchmark(report),
);
item.validate()?;
Ok(item)
}
pub fn label(kind: Kind) -> &'static str {
SWITCHES.iter().find(|s| s.0 == kind).map_or("", |s| s.1)
}
/// Sends what is waiting, if there is a server and the player allows it.
pub fn send() -> Flush {
match horizon_telemetry::endpoint() {
Some(url) => upload::flush(&home(), &url),
None => Flush::Nothing,
}
}
/// [`send`] on its own thread, at start and when the window closes.
pub fn send_in_background() -> std::thread::JoinHandle<()> {
std::thread::spawn(|| drop(send()))
}
/// The status as `telemetry status` and the MCP tool give it.
pub fn status_json() -> serde_json::Value {
let consent = consent();
serde_json::json!({
"asked": !consent.needs_asking(),
"consent_version": consent.version,
"answered": consent.answered,
"choices": consent.choices,
"install_id": consent.install_id,
"waiting": outbox::pending(&home()).len(),
"server": horizon_telemetry::endpoint(),
})
}
/// [`send`] as the launcher closes, waiting at most a few seconds for it.
pub fn send_before_exit() {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
send();
let _ = tx.send(());
});
let _ = rx.recv_timeout(std::time::Duration::from_secs(3));
}
/// The kinds named as the CLI and MCP take them: `performance`, `crashes`, `bugs`,
/// `benchmarks` (or `perf`, `crash`…), or `all`.
pub fn parse_kinds(names: &[String]) -> Result<Vec<Kind>, String> {
let mut kinds = Vec::new();
for name in names {
match name.as_str() {
"all" => kinds.extend(Kind::ALL),
"performance" => kinds.push(Kind::Perf),
"crashes" => kinds.push(Kind::Crash),
"bugs" => kinds.push(Kind::Bug),
"benchmarks" => kinds.push(Kind::Benchmark),
other => kinds.push(Kind::from_name(other).ok_or_else(|| {
format!("{other}: one of performance, crashes, bugs, benchmarks, all")
})?),
}
}
Ok(kinds)
}
/// Turns `kinds` on or off, keeping the other switches as they are (off if never asked).
pub fn set(kinds: &[Kind], on: bool) -> Result<Consent, String> {
let current = consent();
let mut choices = if current.needs_asking() {
Choices::NONE
} else {
current.choices
};
for &kind in kinds {
choices.set(kind, on);
}
answer(choices)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kinds_are_named_in_plain_words_or_short() {
let names = |n: &[&str]| parse_kinds(&n.iter().map(|s| s.to_string()).collect::<Vec<_>>());
assert_eq!(
names(&["performance", "crash"]).unwrap(),
[Kind::Perf, Kind::Crash]
);
assert_eq!(names(&["all"]).unwrap(), Kind::ALL);
assert!(names(&["everything"]).is_err());
}
#[test]
fn every_kind_has_a_switch() {
assert!(Kind::ALL.iter().all(|&k| !label(k).is_empty()));
}
}
+1
View File
@@ -33,6 +33,7 @@ class PrReadyTests(unittest.TestCase):
self.assertTrue(pr_ready.launcher_rust("launcher/src/main.rs"))
self.assertTrue(pr_ready.launcher_rust("crates/horizon-prepare/src/lib.rs"))
self.assertTrue(pr_ready.launcher_rust("crates/horizon-theme/src/lib.rs"))
self.assertTrue(pr_ready.launcher_rust("crates/horizon-telemetry/src/lib.rs"))
self.assertFalse(pr_ready.launcher_rust("launcher/links.json"))
self.assertFalse(pr_ready.launcher_rust("launcher/README.md"))
self.assertFalse(pr_ready.launcher_rust("crates/horizon-client/src/game.rs"))
+1 -1
View File
@@ -39,7 +39,7 @@ EXPORTERS = "mods/horizon/src/test/java/dev/horizonlab/parity/"
# What players run. Documentation (*.md), tests, benchmarks and harness probes (examples/) never count.
GAME_PATHS = ["crates/", "xtask/", "packaging/", "Cargo.toml", "Cargo.lock", "research-lock.json"]
LAUNCHER_PATHS = ["launcher/", "crates/horizon-prepare/", "crates/horizon-theme/"]
LAUNCHER_PATHS = ["launcher/", "crates/horizon-prepare/", "crates/horizon-theme/", "crates/horizon-telemetry/"]
LAUNCHER_IGNORED = ["launcher/links.json", "launcher/docs/", "launcher/tests/"]
FOOTER = {