Join a friend with the full code (no server) or a relay's short code

The game joins `friend:CODE` with either code: a full invite is dialled
directly, then through the relay it names; a short code goes through the
relay the player set. Join a friend gains a Relay (optional) field, saved
to horizon.txt (friendsRelay) and used for hosting too; the code field
shows the end of long codes and says what is wrong with one (typo, other
version, short code without a relay). The launcher validates both kinds.

tools/test_friends.py now runs (a) the code alone with no relay anywhere
and (b) a relay run locally with the short code; routers and STUN stay
out of tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-15 00:41:54 +02:00
parent 341aa98a96
commit a3913be641
7 changed files with 231 additions and 136 deletions
+60 -22
View File
@@ -455,7 +455,7 @@ impl Title {
_ => 50,
}),
FIELD_A | FIELD_B => {
if let Screen::Edit { focus, .. } = screen {
if let Screen::Edit { focus, .. } | Screen::Friend { focus, .. } = screen {
*focus = u8::from(hit == FIELD_B);
}
None
@@ -488,6 +488,25 @@ impl Title {
}
}
/// The end of `text` that fits `width`, led by an ellipsis when cut.
fn tail_fit(ui: &Ui, text: &str, width: f32) -> String {
if ui.measure(Face::Regular, BODY, text) <= width {
return text.to_owned();
}
let chars: Vec<char> = text.chars().collect();
let mut start = 0;
while start < chars.len() {
let tail: String = std::iter::once('…')
.chain(chars[start..].iter().copied())
.collect();
if ui.measure(Face::Regular, BODY, &tail) <= width {
return tail;
}
start += 1;
}
String::new()
}
/// The page header plus a row of actions under it; returns the y below.
fn header(ui: &mut Ui, x: f32, title: &str, description: &str) -> f32 {
let y = 36.0;
@@ -960,15 +979,15 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
);
ui.divider(x, y + rh, w);
}
Screen::Friend { code } => {
Screen::Friend { code, relay, focus } => {
let y = header(
ui,
x,
"Join a friend",
"Paste the invite code your friend sees in their pause menu.",
);
let available = horizon_friends::relay_url().is_some();
let ok = available && horizon_friends::Code::parse(code).is_some();
let parsed = horizon_friends::invite::parse_detailed(code);
let ok = parsed.is_ok();
actions_right(
ui,
x + w,
@@ -980,26 +999,45 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
);
ui.divider(x, y, w);
let rh = 12.0 + CONTROL + 12.0;
ui.text_line(Face::Regular, BODY, rh, x, y, color::MUTED, "Invite code");
let fx = x + t::ROW_LABEL + 16.0;
ui.field(
FIELD_A,
[fx, y + 12.0, (w - t::ROW_LABEL - 16.0).min(240.0), CONTROL],
code,
"K7QM-3XPD",
true,
caret,
);
ui.divider(x, y + rh, w);
if !available {
ui.text(
Face::Regular,
SMALL,
x,
y + rh + 12.0,
color::FAINT,
"Joining friends isn't available yet in this build.",
let fw = w - t::ROW_LABEL - 16.0;
let rows = [
(FIELD_A, "Invite code", code, "Paste the code here", fw),
(
FIELD_B,
"Relay (optional)",
relay,
"host:port, for short codes",
fw.min(360.0),
),
];
let mut ry = y;
for (i, (fid, label, value, hint, width)) in rows.into_iter().enumerate() {
ui.text_line(Face::Regular, BODY, rh, x, ry, color::MUTED, label);
// A long code shows its end, where the typing is.
let shown = tail_fit(ui, value, width - 28.0);
ui.field(
fid,
[fx, ry + 12.0, width, CONTROL],
&shown,
hint,
usize::from(*focus) == i,
caret,
);
ry += rh;
ui.divider(x, ry, w);
}
let note = match parsed {
_ if code.trim().is_empty() => None,
Err(e) => Some(e.to_string()),
Ok(horizon_friends::invite::Parsed::Short(_)) if relay.trim().is_empty() => Some(
"This is a relay's short code: fill in your friend's relay above, or ask for the full code."
.to_owned(),
),
Ok(_) => None,
};
if let Some(note) = note {
ui.text(Face::Regular, SMALL, x, ry + 12.0, color::MUTED, &note);
}
}
Screen::Disconnected { reason, retry } => {
+1 -10
View File
@@ -30,15 +30,6 @@ pub const HELP: &[&str] = &[
"friends status the code, how friends reach this host, the guests",
];
/// The relay the player set (Join a friend's Relay field, `friendsRelay`
/// in horizon.txt), else `HORIZON_RELAY_URL`. None by default.
pub(super) fn relay_setting() -> Option<String> {
let dir = std::env::current_dir().ok()?;
horizon_client::ui_theme::preference(&dir, "friendsRelay")
.filter(|r| !r.is_empty())
.or_else(horizon_friends::relay_url)
}
/// `HORIZON_STUN_SERVERS`, else `friendsStun` in horizon.txt, else the defaults.
fn stun_servers() -> Vec<String> {
if std::env::var_os("HORIZON_STUN_SERVERS").is_some() {
@@ -78,7 +69,7 @@ impl Game<'_> {
lan: std::net::SocketAddr::from(([127, 0, 0, 1], port)),
protocol: PROTOCOL_VERSION,
game: GAME_VERSION.to_owned(),
relay: relay_setting(),
relay: horizon_client::net::friends_relay_setting(),
path: PathMode::from_env(),
port: std::env::var("HORIZON_FRIENDS_PORT")
.ok()
+50 -19
View File
@@ -49,6 +49,9 @@ pub enum Screen {
/// from Horizon's multiplayer page).
Friend {
code: String,
/// The relay for short codes (optional; saved on Join).
relay: String,
focus: u8,
},
Disconnected {
reason: String,
@@ -212,18 +215,18 @@ impl Screen {
53,
),
],
Self::Friend { code } => vec![
Self::Friend { code, .. } => vec![
b(
w / 2.0 - 100.0,
h / 4.0 + 96.0 + 12.0,
h / 4.0 + 96.0 + 18.0,
200.0,
"Join",
horizon_friends::Code::parse(code).is_some(),
horizon_friends::invite::parse(code).is_some(),
56,
),
b(
w / 2.0 - 100.0,
h / 4.0 + 120.0 + 12.0,
h / 4.0 + 120.0 + 18.0,
200.0,
"Cancel",
true,
@@ -465,9 +468,18 @@ impl Screen {
blink,
);
}
Self::Friend { code } => {
Self::Friend { code, relay, focus } => {
centered(batch, "Join a Friend", 20.0, u32::MAX);
Self::field(atlas, batch, "Invite Code", code, 100.0 - 11.0, true, blink);
Self::field(atlas, batch, "Invite Code", code, 53.0, *focus == 0, blink);
Self::field(
atlas,
batch,
"Relay (optional)",
relay,
94.0,
*focus == 1,
blink,
);
}
Self::Disconnected { reason, retry } => {
centered(
@@ -514,11 +526,7 @@ impl Screen {
address: String::new(),
}
}
(Self::List { .. }, Some(47)) => {
*self = Self::Friend {
code: String::new(),
}
}
(Self::List { .. }, Some(47)) => *self = Self::friend(),
(Self::List { .. }, Some(42)) => {
*self = Self::Edit {
index: None,
@@ -610,12 +618,14 @@ impl Screen {
(Self::Direct { address }, Some(52)) => {
return Outcome::Connect(address.trim().to_owned());
}
(Self::Friend { code }, Some(56)) => {
if let Some(code) = horizon_friends::Code::parse(code) {
(Self::Friend { code, relay, .. }, Some(56)) => {
if horizon_friends::invite::parse(code).is_some() {
crate::net::save_friends_relay(relay.trim());
let code: String = code.chars().filter(|c| !c.is_whitespace()).collect();
return Outcome::Connect(format!("{}{code}", crate::net::FRIEND));
}
}
(Self::Edit { focus, .. }, None) => {
(Self::Edit { focus, .. } | Self::Friend { focus, .. }, None) => {
for (i, fy) in [(0u8, 53.0 + 11.0), (1, 94.0 + 11.0)] {
if y >= fy && y < fy + 20.0 && (x - w / 2.0).abs() < 100.0 {
*focus = i;
@@ -635,10 +645,20 @@ impl Screen {
..
} => Some(if *focus == 0 { name } else { address }),
Self::Direct { address } => Some(address),
Self::Friend { code } => Some(code),
Self::Friend {
code, relay, focus, ..
} => Some(if *focus == 0 { code } else { relay }),
_ => None,
}
}
/// Join a friend, with the relay the player set before.
pub fn friend() -> Self {
Self::Friend {
code: String::new(),
relay: crate::net::friends_relay_setting().unwrap_or_default(),
focus: 0,
}
}
/// Auto-reconnect's attempt, once its countdown is over.
pub fn due_retry(&mut self) -> Option<crate::reconnect::Retry> {
let Self::Disconnected { retry, .. } = self else {
@@ -655,15 +675,26 @@ impl Screen {
Self::Edit { focus: 0, .. } => ("server.name", 0),
Self::Edit { .. } => ("server.address", 0),
Self::Direct { .. } => ("server.direct", 0),
Self::Friend { .. } => ("friend.code", 0),
Self::Friend { focus: 0, .. } => ("friend.code", 0),
Self::Friend { .. } => ("friend.relay", 0),
_ => return None,
};
self.focused_field().map(|f| (id, f, 128))
let max = self.max_length();
self.focused_field().map(|f| (id, f, max))
}
/// Invite codes with IPv6 and a relay run past a server address's 128.
fn max_length(&self) -> usize {
if matches!(self, Self::Friend { .. }) {
256
} else {
128
}
}
pub fn type_text(&mut self, text: &str) {
let max = self.max_length();
if let Some(field) = self.focused_field() {
for c in text.chars().filter(|c| !c.is_control()) {
if field.chars().count() < 128 {
if field.chars().count() < max {
field.push(c);
}
}
@@ -675,7 +706,7 @@ impl Screen {
}
}
pub fn tab(&mut self) {
if let Self::Edit { focus, .. } = self {
if let Self::Edit { focus, .. } | Self::Friend { focus, .. } = self {
*focus = (*focus + 1) % 2;
}
}
+27 -13
View File
@@ -150,32 +150,46 @@ impl Drop for Session {
/// client reaches on a loopback port, so everything after is a plain join.
pub const FRIEND: &str = horizon_friends::ADDRESS_PREFIX;
/// An address as players and logs see it: a friend's invite code without
/// its secret half.
/// An address as players and logs see it: a friend's invite code stays
/// out of it (its secret is in there).
pub fn shown_address(address: &str) -> String {
match address.strip_prefix(FRIEND) {
Some(code) => match horizon_friends::Code::parse(code) {
Some(code) => format!("Friend's world ({}-****)", code.nameplate),
None => "Friend's world".to_owned(),
Some(code) => match horizon_friends::invite::parse(code) {
Some(horizon_friends::invite::Parsed::Short(c)) => {
format!("Friend's world ({}-****)", c.nameplate)
}
_ => "Friend's world".to_owned(),
},
None => address.to_owned(),
}
}
/// Find the friend's world behind the code and open the tunnel: the loopback
/// address to connect to.
/// The relay the player set (`friendsRelay` in horizon.txt, beside
/// options.txt), else `HORIZON_RELAY_URL`. None by default.
pub fn friends_relay_setting() -> Option<String> {
let dir = std::env::current_dir().ok()?;
crate::ui_theme::preference(&dir, "friendsRelay")
.filter(|r| !r.is_empty())
.or_else(horizon_friends::relay_url)
}
/// Remember the relay typed on Join a friend (empty forgets it).
pub fn save_friends_relay(relay: &str) {
if let Ok(dir) = std::env::current_dir() {
crate::ui_theme::set_preference(&dir, "friendsRelay", (!relay.is_empty()).then_some(relay));
}
}
/// Reach the friend's world from the code (directly, or through a relay)
/// and open the tunnel: the loopback address to connect to.
fn join_friend(code: &str, send: &Sender<Event>) -> Result<(String, u16), String> {
use horizon_friends::{
Code, JoinError, PathMode,
PathMode,
guest::{self, GuestConfig},
};
let code = Code::parse(code)
.ok_or("That isn't an invite code: codes are eight letters and digits, like K7QM-3XPD.")?;
let relay = horizon_friends::relay_url().ok_or_else(|| JoinError::NotAvailable.to_string())?;
status(send, "Finding your friend's world...");
let tunnel = guest::join(&GuestConfig {
relay,
code,
code: code.to_owned(),
relay: friends_relay_setting(),
protocol: PROTOCOL_VERSION,
game: horizon_protocol::GAME_VERSION.to_owned(),
path: PathMode::from_env(),
+2 -2
View File
@@ -1057,8 +1057,8 @@ pub fn client(tag: &str) -> Result<Command, String> {
/// Start the game straight into a friend's world: `--server friend:CODE`.
pub fn join_friend(cmd: &mut Command, code: &str) -> Result<(), String> {
let code = horizon_friends::Code::parse(code)
.ok_or("That isn't an invite code: codes are eight letters and digits, like K7QM-3XPD.")?;
horizon_friends::invite::parse_detailed(code).map_err(|e| e.to_string())?;
let code: String = code.chars().filter(|c| !c.is_whitespace()).collect();
cmd.arg("--server")
.arg(format!("{}{code}", horizon_friends::ADDRESS_PREFIX));
Ok(())
+2 -1
View File
@@ -2228,7 +2228,8 @@ impl Launcher {
}
fn join_friend(&mut self) {
if self.mode != Mode::Client || horizon_friends::invite::parse(&self.friend_code).is_none() {
if self.mode != Mode::Client || horizon_friends::invite::parse(&self.friend_code).is_none()
{
return;
}
self.joining = Some(self.friend_code.clone());
+89 -69
View File
@@ -1,22 +1,24 @@
#!/usr/bin/env python3
"""Play with friends end to end, without the internet.
A relay (`horizon-relay`) on a free local port; a host Horizon that opens a
world and shares it behind an invite code (`friends host`); a guest Horizon
that joins with the code (`connect friend:CODE`). The guest joins twice:
first on the direct path, then started with HORIZON_FRIENDS_PATH=relay so
the session goes through the relay. Each time both sides must see the
other's chat line, the other moving, a block the host places and the block
the guest breaks; the host's counts say which path each session took, and
the relay's relayed bytes must stay small for the direct session and grow
with the relayed one. Last, the host stops sharing and a guest using the
old code is told the invite has ended.
(a) The code alone: a host Horizon opens a world and shares it (`friends
host`) with no relay anywhere; a guest Horizon joins with the full invite
code (`connect friend:CODE`) by dialling the endpoints in it. (b) A
self-hosted relay run locally (`horizon-relay`): the host also gets a short
code from it, and a guest started with HORIZON_FRIENDS_PATH=relay joins with
the short code through it. Each time both sides must see the other's chat
line, the other moving, a block the host places and the block the guest
breaks; then the host stops sharing and a guest with the old code is told
why it can't join. `--baseline` first runs the same checks over plain LAN.
The router is never asked to open a port (HORIZON_FRIENDS_UPNP=0) and STUN
is off: nothing leaves the machine.
python3 tools/test_friends.py --client target/fast/horizon-client --relay target/fast/horizon-relay
`--relay-url HOST:PORT` uses a relay already running elsewhere (two
machines); `--role host|guest` then runs one side only and prints or takes
the code (`--code`). Needs a display on Linux (xvfb-run -a).
`--role host|guest` runs one side only (two machines, e.g. over a tailnet):
the host prints the code, the guest takes it with `--code` (`--relay-url`
for a relay elsewhere, `--path relay` to force it). Needs a display on Linux
(xvfb-run -a).
"""
import argparse
import json
@@ -112,7 +114,6 @@ class Game:
def host_world(host):
host('open Friends 0 creative')
host.wait('status', lambda v: v['player'] is not None and v['pending_chunks'] == 0, 120, 'host world')
assert host('friends status')['available'], 'HORIZON_RELAY_URL did not reach the host'
host('friends host')
return host.wait('friends status', lambda v: v['code'], 30, 'invite code')['code']
@@ -182,13 +183,45 @@ def leave(host, guest, name):
host.wait('lan status', lambda v: all(g['name'] != name for g in v['guests']), 30, 'the guest leaving')
def full(args, work, relay_url):
env = {'HORIZON_RELAY_URL': relay_url}
def start_relay(args, work):
"""A relay on a free local port, as anyone would run their own."""
port = free_port()
url = f'127.0.0.1:{port}'
log = (work / 'relay.log').open('w+')
process = subprocess.Popen([str(args.relay.resolve())], env=dict(os.environ, PORT=str(port)),
stdout=log, stderr=subprocess.STDOUT)
deadline = time.monotonic() + 10
while True:
try:
health(url)
return process, log, url
except OSError:
assert time.monotonic() < deadline, 'the relay did not start'
time.sleep(0.1)
def set_relay(game, url):
"""What typing the relay on Join a friend saves (horizon.txt)."""
path = game.home / 'horizon.txt'
lines = [l for l in (path.read_text().splitlines() if path.exists() else []) if not l.startswith('friendsRelay:')]
path.write_text('\n'.join(lines + [f'friendsRelay:{url}']) + '\n')
def full(args, work):
# Tests never touch the real router or ask the internet. Both games run on
# this machine, so the code also holds 127.0.0.1 (a firewall such as
# macOS's may hold back connections to the LAN address from an unsigned
# binary started over SSH, which can't show its prompt).
env = {'HORIZON_FRIENDS_UPNP': '0', 'HORIZON_STUN_SERVERS': 'none', 'HORIZON_FRIENDS_LOOPBACK': '1'}
host = Game(args.client, args.resources, work, 'host', env)
games = [host]
relay = None
try:
# (a) The code alone: no relay anywhere.
code = host_world(host)
print(f'host shares the world: {code[:4]}-****')
status = host('friends status')
assert status['short'] is None and len(code) > 30, status
print(f'host shares the world: a {len(code.replace("-", ""))}-symbol code, no relay; {status["summary"]}')
if args.baseline:
# The same checks over plain LAN, without the tunnel: the behaviour
# the tunnel must reproduce.
@@ -199,42 +232,47 @@ def full(args, work, relay_url):
print('plain LAN: chat, movement and blocks both ways')
leave(host, guest, 'Plain')
guest.stop()
# Direct path.
guest = Game(args.client, args.resources, work, 'guest-direct', env)
guest = Game(args.client, args.resources, work, 'guest-code', env)
games.append(guest)
before = health(relay_url)['relayed_bytes']
join(guest, code, 'Guest')
play_together(host, guest, 'Guest', 1)
direct_bytes = health(relay_url)['relayed_bytes'] - before
assert host('friends status')['direct'] == 1, host('friends status')
assert direct_bytes < 64 * 1024, f'the direct session went through the relay ({direct_bytes} bytes)'
print(f'direct path: chat, movement and blocks both ways; relay carried {direct_bytes} bytes')
print('code alone: chat, movement and blocks both ways, no server involved')
leave(host, guest, 'Guest')
host('friends stop')
assert host('friends status')['code'] is None
assert host('lan status') == {'open': False}, 'sharing opened LAN, so stopping closes it'
join(guest, code, 'Late')
reason = guest.wait('screen', lambda v: v['menu']['disconnected'], 30, 'the ended code')['menu']['disconnected']
assert "Couldn't reach your friend's game" in reason, reason
print(f'after stopping: "{reason}"')
guest.stop()
# Forced relay path.
guest = Game(args.client, args.resources, work, 'guest-relay',
dict(env, HORIZON_FRIENDS_PATH='relay'))
# (b) A self-hosted relay, run locally: the short code, relayed.
relay, relay_log, relay_url = start_relay(args, work)
set_relay(host, relay_url)
host('friends host')
status = host.wait('friends status', lambda v: v['short'], 30, 'the short code')
short = status['short']
guest = Game(args.client, args.resources, work, 'guest-relay', dict(env, HORIZON_FRIENDS_PATH='relay'))
games.append(guest)
set_relay(guest, relay_url)
before = health(relay_url)['relayed_bytes']
join(guest, code, 'Relayed')
join(guest, short, 'Relayed')
play_together(host, guest, 'Relayed', 2)
relayed_bytes = health(relay_url)['relayed_bytes'] - before
status = host('friends status')
assert status['relayed'] == 1, status
# Render distance 2: the join is some tens of kB of compressed chunks.
assert relayed_bytes > max(32 * 1024, 4 * direct_bytes), \
f'the relayed session carried only {relayed_bytes} bytes (direct: {direct_bytes})'
print(f'relay path: chat, movement and blocks both ways; relay carried {relayed_bytes} bytes')
assert relayed_bytes > 32 * 1024, f'the relayed session carried only {relayed_bytes} bytes'
print(f'self-hosted relay, short code {short[:4]}-****: chat, movement and blocks both ways; '
f'relay carried {relayed_bytes} bytes')
leave(host, guest, 'Relayed')
# The code ends with sharing.
host('friends stop')
assert host('friends status')['code'] is None
join(guest, code, 'Late')
join(guest, short, 'Late')
reason = guest.wait('screen', lambda v: v['menu']['disconnected'], 30, 'the ended invite')['menu']['disconnected']
assert 'invite has ended' in reason, reason
print(f'after stopping: "{reason}"')
assert host('lan status') == {'open': False}, 'sharing opened LAN, so stopping closes it'
return code
return code + short
except Exception:
for g in games:
print(f'--- {g.home.name} log tail ---')
@@ -243,10 +281,21 @@ def full(args, work, relay_url):
finally:
for g in games:
g.stop()
if relay:
relay.terminate()
relay.wait(timeout=10)
relay_log.seek(0)
text = relay_log.read()
print(f'relay log: {text.splitlines()}')
# Counts only: no code, no address, no name.
for secret in ['127.0.0.1', 'Guest', 'Relayed', 'Late']:
assert secret not in text, f'the relay logged {secret!r}'
def one_side(args, work):
env = {'HORIZON_RELAY_URL': args.relay_url}
env = {'HORIZON_FRIENDS_UPNP': '0', 'HORIZON_STUN_SERVERS': 'none'}
if args.relay_url:
env['HORIZON_RELAY_URL'] = args.relay_url
if args.path:
env['HORIZON_FRIENDS_PATH'] = args.path
game = Game(args.client, args.resources, work, args.role, env)
@@ -276,7 +325,7 @@ def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--client', type=Path, required=True)
parser.add_argument('--relay', type=Path, help='horizon-relay binary (started on a free local port)')
parser.add_argument('--relay-url', help='an already running relay, HOST:PORT')
parser.add_argument('--relay-url', help='--role: a relay already running elsewhere, HOST:PORT')
parser.add_argument('--resources', type=Path, default=ROOT / '.local/horizon-client/26.3')
parser.add_argument('--role', choices=['host', 'guest'])
parser.add_argument('--code')
@@ -290,39 +339,10 @@ def main():
with tempfile.TemporaryDirectory(prefix='hzf-', dir='/tmp') as directory:
work = Path(directory)
if args.role:
assert args.relay_url, '--role needs --relay-url'
return one_side(args, work)
relay = None
relay_url = args.relay_url
if not relay_url:
assert args.relay, 'give --relay or --relay-url'
port = free_port()
relay_url = f'127.0.0.1:{port}'
relay_log = (work / 'relay.log').open('w+')
relay = subprocess.Popen([str(args.relay.resolve())], env=dict(os.environ, PORT=str(port)),
stdout=relay_log, stderr=subprocess.STDOUT)
deadline = time.monotonic() + 10
while True:
try:
health(relay_url)
break
except OSError:
assert time.monotonic() < deadline, 'the relay did not start'
time.sleep(0.1)
try:
code = full(args, work, relay_url)
finally:
if relay:
relay.terminate()
relay.wait(timeout=10)
relay_log.seek(0)
text = relay_log.read()
print(f'relay log: {text.splitlines()}')
if relay:
# Counts only: no code, no address, no name.
for secret in [code[:4], '127.0.0.1', 'Guest', 'Relayed']:
assert secret not in text, f'the relay logged {secret!r}'
print('Play with friends passed: direct and relayed sessions, chat, movement and blocks both ways')
assert args.relay, 'give --relay (the relay binary, run locally for the relay half)'
full(args, work)
print('Play with friends passed: the code alone and a self-hosted relay; chat, movement and blocks both ways')
if __name__ == '__main__':