diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8471e007d..cfbb526ef 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1165,6 +1165,10 @@ struct Game<'a> { /// returns: the line, whether operators get it and whether the console /// logs it. admin_feedback: Vec<(horizon_client::text::Text, bool, bool)>, + /// The server console is running a command: whether its feedback goes to + /// the operators (`DedicatedServer.shouldInformAdmins`, + /// `broadcast-console-to-ops`). + console_broadcast: Option, /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. cmds: commands::extra::CommandExtras, ui: chat::UiState, @@ -10404,6 +10408,7 @@ impl<'a> Game<'a> { lan_acting_uuid: None, chat_capture: None, admin_feedback: Vec::new(), + console_broadcast: None, cmds: Default::default(), ui: Default::default(), combat: Default::default(), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index b5f9aed25..575f5c93e 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -165,14 +165,20 @@ impl Game<'_> { } self.broadcast_to_admins(message); } - /// CommandSourceStack.broadcastToAdmins, for a guest's command on a - /// dedicated server (`sendSuccess` with `broadcast`): `[name: message]`, - /// gray and italic, for the other operators when `send_command_feedback` - /// and the console when `log_admin_commands`. Queued while the guest acts; - /// `send_admin_feedback` sends it. - fn broadcast_to_admins(&mut self, message: Text) { - if self.lan_acting.is_none() - || self.options.dedicated.is_none() + /// CommandSourceStack.broadcastToAdmins (`sendSuccess` with `broadcast`) + /// for a guest's command, the host's in a world open to LAN and the + /// dedicated server console's when `broadcast-console-to-ops` is on: + /// `[name: message]`, gray and italic, for the other operators when + /// `send_command_feedback`, and for a player's command on a dedicated + /// server the console when `log_admin_commands`. Queued while the + /// command runs; `send_admin_feedback` sends it. + pub(super) fn broadcast_to_admins(&mut self, message: Text) { + let informs = match self.console_broadcast { + Some(broadcast) => broadcast, + // While a guest acts the host's LanHost is out of `self.lan`. + None => self.lan_acting.is_some() || self.lan.is_some(), + }; + if !informs || message .translation_key() .is_some_and(|k| admin::QUIET.contains(&k)) @@ -180,20 +186,46 @@ impl Game<'_> { return; } let ops = self.ui.rules.bool("send_command_feedback"); - let console = self.ui.rules.bool("log_admin_commands"); + // MinecraftServer.sendSystemMessage, unless the server is the source. + let console = self.console_broadcast.is_none() + && self.lan_acting.is_some() + && self.options.dedicated.is_some() + && self.ui.rules.bool("log_admin_commands"); if !ops && !console { return; } - // getDisplayName: the entity the command runs as (`execute as`). - let who = self - .command_source - .and_then(|s| s.entity) - .unwrap_or(Target::Player); - let line = Text::translate("chat.type.admin", &[self.target_name(who), message]) + // getDisplayName: the entity the command runs as (`execute as`), or + // the server's own source, "Server". + let who = match self.command_source.and_then(|s| s.entity) { + Some(entity) => self.target_name(entity), + None if self.console_broadcast.is_some() => Text::literal("Server".to_owned()), + None => self.player_display_name(), + }; + let line = Text::translate("chat.type.admin", &[who, message]) .with_color(text::GRAY) .italic(); self.admin_feedback.push((line, ops, console)); } + /// Player.getDisplayName: the name (team-formatted), suggesting a + /// `/tell`, showing the player on hover, inserting the name. + fn player_display_name(&self) -> Text { + let name = self.acting_player_name().to_owned(); + let Some(uuid) = self.lan_acting_uuid else { + return self.target_name(Target::Player); + }; + self.target_name(Target::Player).with_component_fields(vec![ + ( + "click_event".into(), + serde_json::json!({"action": "suggest_command", "command": format!("/tell {name} ")}), + ), + ( + "hover_event".into(), + serde_json::json!({"action": "show_entity", "id": "minecraft:player", + "uuid": horizon_protocol::crypto::uuid_string(uuid), "name": name}), + ), + ("insertion".into(), name.into()), + ]) + } fn source_position(&self) -> [f64; 3] { if let Some(s) = &self.command_source { return s.pos; diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 49b77eb13..7348f3f9e 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -402,8 +402,32 @@ struct ServerState { /// When the last passes of the loop ended, for the tick rate horizon-server shows. ticks: std::collections::VecDeque, paused: bool, + /// `broadcast-console-to-ops`. + broadcast_console: bool, } +/// The dedicated-only commands' replies vanilla sends with `broadcast` +/// (`sendSuccess(..., true)`): the operators hear of them. +const BROADCAST: &[&str] = &[ + "commands.ban.success", + "commands.banip.info", + "commands.banip.success", + "commands.deop.success", + "commands.kick.success", + "commands.op.success", + "commands.pardon.success", + "commands.pardonip.success", + "commands.save.disabled", + "commands.save.enabled", + "commands.save.success", + "commands.stop.stopping", + "commands.whitelist.add.success", + "commands.whitelist.disabled", + "commands.whitelist.enabled", + "commands.whitelist.reloaded", + "commands.whitelist.remove.success", +]; + impl Game<'_> { /// DedicatedServer.initServer and MinecraftServer.runServer. pub(super) fn run_dedicated(&mut self) -> Result<()> { @@ -612,6 +636,7 @@ impl Game<'_> { empty_ticks: 0, ticks: Default::default(), paused: false, + broadcast_console: props.broadcast_console_to_ops, }; let pause_after = props.pause_when_empty_seconds * 20; let idle_timeout = props.player_idle_timeout; @@ -619,7 +644,7 @@ impl Game<'_> { while !state.stop { let tick_start = Instant::now(); while let Ok(line) = state.console.try_recv() { - self.console_command(&mut state, &line); + self.console_line(&mut state, &line); } self.poll_server_control(&mut state); let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len()); @@ -767,14 +792,36 @@ impl Game<'_> { }) }); if found.is_none() { - self.console_reply(Text::translate("argument.player.unknown", &[])); + let unknown = Text::translate("argument.player.unknown", &[]); + log("INFO", &format!("System chat: {}", unknown.plain())); } found } - /// MinecraftServer.sendSystemMessage: what the console is told. - fn console_reply(&self, text: Text) { + /// MinecraftServer.sendSystemMessage: what the console is told; while + /// the console runs a command, the replies vanilla broadcasts go to the + /// operators too. + fn console_reply(&mut self, text: Text) { log("INFO", &format!("System chat: {}", text.plain())); + if self.console_broadcast.is_some() + && text + .translation_key() + .is_some_and(|k| BROADCAST.contains(&k)) + { + self.broadcast_to_admins(text); + } + } + + /// One console line, then the operators' share of its feedback. + fn console_line(&mut self, state: &mut ServerState, line: &str) { + self.console_broadcast = Some(state.broadcast_console); + self.console_command(state, line); + self.console_broadcast = None; + if let Some(mut host) = self.lan.take() { + self.send_admin_feedback(&mut host, None); + self.lan = Some(host); + } + self.admin_feedback.clear(); } /// DedicatedServer.handleConsoleInputs: one console line, run as the diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 0e659cbc5..30cd89b3d 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -794,6 +794,10 @@ impl Game<'_> { }; // What the tick sends a guest goes to its connection at the end. let holding = lan::Holding::start(); + // The host's own commands' broadcastToAdmins lines. + if !self.admin_feedback.is_empty() { + self.send_admin_feedback(&mut host, None); + } let state = self.lan_host_state(&host); // A dedicated server runs the hub without a host player. if state.is_some() || host.hub.config.dedicated { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index b327686b9..59d71e7b2 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -728,7 +728,7 @@ impl Game<'_> { }), ); } - self.send_admin_feedback(host, conn); + self.send_admin_feedback(host, Some(conn)); } } S::Unknown(8, payload) => { @@ -942,13 +942,19 @@ impl Game<'_> { }), ); } - self.send_admin_feedback(host, conn); + self.send_admin_feedback(host, Some(conn)); } - /// The `broadcastToAdmins` lines a guest's command queued: every other + /// The `broadcastToAdmins` lines a command queued (`source`: the guest + /// whose it was; none for the host's or the console's): every other /// operator gets them, and the console logs them as the server's own /// system messages (MinecraftServer.sendSystemMessage). - fn send_admin_feedback(&mut self, host: &mut LanHost, source: u32) { + pub(super) fn send_admin_feedback(&mut self, host: &mut LanHost, source: Option) { + // PlayerList.isOp for the host of a world open to LAN: the owner when + // the world allows commands, everyone when the LAN does. + let host_op = source.is_some() + && !host.hub.config.dedicated + && (self.allow_commands() || host.hub.config.guest_commands); for (line, ops, console) in std::mem::take(&mut self.admin_feedback) { if ops { let content = horizon_client::lan::data::component_nbt(&line.component()); @@ -956,13 +962,16 @@ impl Game<'_> { .hub .guests .iter() - .filter(|g| g.conn != source && g.permission > 0) + .filter(|g| Some(g.conn) != source && g.permission > 0) { g.send(&C::SystemChat(play::SystemChat { content: content.clone(), overlay: false, })); } + if host_op { + self.system_message(line.clone()); + } } if console { super::dedicated::log("INFO", &format!("System chat: {}", line.plain())); diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index e0b144714..ea11d4163 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -267,6 +267,18 @@ impl Text { _ => c, } } + /// Style fields the spans don't model (an entity hover, an insertion), + /// set on the component sent to vanilla only. + pub fn with_component_fields(mut self, fields: Vec<(String, Value)>) -> Self { + let mut c = self.component(); + if let Value::Object(o) = &mut c { + for (k, v) in fields { + o.entry(k).or_insert(v); + } + } + self.source = Some(c.into()); + self + } pub fn with_color(self, color: u32) -> Self { self.with_style(&Style::color(color)) } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java index a29b95231..e2de1b004 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java @@ -80,12 +80,15 @@ import net.minecraft.world.phys.Vec3; * position reminder LocalPlayer.sendPosition sends every 20 ticks standing * still), {@code quit NAME}, {@code * players on|off} (whether each player also records the other players added - * to and removed from its level, and its own respawns into a dimension) and - * {@code end}, which writes each player's lines to OUT. + * to and removed from its level, and its own respawns into a dimension), + * {@code chat on|off} (whether the system chat each player receives is + * recorded too, as component JSON) and {@code end}, which writes each + * player's lines to OUT. */ public final class LocatorBarClient { private static volatile String step = "start"; private static volatile boolean players; + private static volatile boolean chat; private static final Map NAMES = new LinkedHashMap<>(); public static void main(String[] args) throws Exception { @@ -118,6 +121,7 @@ public final class LocatorBarClient { case "still" -> players.get(w[1]).still(); case "quit" -> players.get(w[1]).close(); case "players" -> LocatorBarClient.players = w[1].equals("on"); + case "chat" -> chat = w[1].equals("on"); case "end" -> { try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) { for (Player p : players.values()) { @@ -298,7 +302,12 @@ public final class LocatorBarClient { seen.clear(); } else if (p instanceof ClientboundTrackedWaypointPacket) { record(waypoint(r.payload)); - } else if (p instanceof ClientboundSystemChatPacket) { + } else if (p instanceof ClientboundSystemChatPacket c) { + if (chat) { + record("chat " + (c.overlay() ? "overlay " : "") + net.minecraft.network.chat.ComponentSerialization.CODEC + .encodeStart(ParityData.access.createSerializationContext(com.mojang.serialization.JsonOps.INSTANCE), c.content()) + .getOrThrow()); + } synchronized (replyLock) { replies++; replyLock.notifyAll(); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index cf8b3788f..7dc8b2c01 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -30,7 +30,8 @@ address. The script then checks, from both sides, what a guest's game used to ge tree (Tab), and runs what it completed; - recipes: the guest's recipe book lists the planks recipe the logs unlock, and clicking it places a log in the inventory's crafting grid (the server places it). -- feedback: the guest's command feedback names the guest and shows the numbers. +- feedback: the guest's command feedback names the guest and shows the numbers, and the host (an + operator) is told of it as `[Guest: ...]`. - clicks: with real mouse presses (not click-slot, which skips the screen's press and drag handling), the guest puts a stack into a chest and a furnace, drags planks across its crafting grid and gathers a stack with a double click; the server has each. @@ -695,6 +696,8 @@ def check_feedback(host, guest, out): guest('command', command=f'tp @s {x:.1f} {y:.1f} {z:.1f}') guest.wait(10) chat = guest.raw('messages', 5)['chat'] + # The host is an operator: broadcastToAdmins tells it, as `[Guest: ...]`. + host_chat = host.raw('messages', 5)['chat'] guest.raw('key', 't', 'tap') guest.wait(5) guest.shot(out, 'feedback') @@ -705,7 +708,9 @@ def check_feedback(host, guest, out): assert any(replaced in line for line in chat), f'no "{replaced}" in {chat}' assert any(line.startswith(f'Teleported {GUEST_NAME} to {x:.6f}') for line in chat), f'teleport feedback: {chat}' assert screen in (None, 'playing'), f'the chat did not close: {screen}' - return chat + told = f'[{GUEST_NAME}: Teleported {GUEST_NAME} to {x:.6f}' + assert any(line.startswith(told) for line in host_chat), f'no "{told}" for the host: {host_chat}' + return chat + host_chat def chat_input(game): diff --git a/tools/test_server_ops_feedback_parity.py b/tools/test_server_ops_feedback_parity.py new file mode 100644 index 000000000..2dd405517 --- /dev/null +++ b/tools/test_server_ops_feedback_parity.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Command feedback the operators get on a dedicated server (`[Server: ...]`), against vanilla's. + +CommandSourceStack.broadcastToAdmins: a command's success that vanilla sends with `broadcast` goes, gray and +italic as `[name: message]`, to every other operator while `send_command_feedback` is on, including the +console's own commands when `broadcast-console-to-ops` is (DedicatedServer.shouldInformAdmins). + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat +world vanilla generated first, with the same server.properties and Alice and Bob as operators. LocatorBarClient +joins them both (players made of vanilla's protocol code) and records the system chat each receives while, step +by step, the console sets the time, asks for the difficulty (a query, told to nobody), whitelists a player, +deops Bob (who stops hearing of it) and ops him again, turns `send_command_feedback` off and on and saves, and +Alice runs a command herself (Bob hears of it as an operator). Then again with `broadcast-console-to-ops=false`. +Each player's chat in each step is compared exactly. +""" +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server + from .test_locator_bar_parity import generate_world, server_dir +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server + from test_locator_bar_parity import generate_world, server_dir + +NAME = 'server-ops-feedback-parity' +# (label, what the console does, what the players do). +BROADCAST = [ + ('console-time', ['time set 1000'], []), + ('console-query', ['difficulty'], []), + ('console-whitelist', ['whitelist add Alice'], []), + ('console-deop', ['deop Bob'], []), + ('bob-not-op', ['time set 2000'], []), + ('alice-bob-not-op', [], ['cmd Alice time set 3000']), + ('console-op', ['op Bob'], []), + ('alice-bob-op', [], ['cmd Alice time set 4000']), + ('feedback-off', ['gamerule send_command_feedback false'], []), + ('console-feedback-off', ['time set 5000'], []), + ('feedback-on', ['gamerule send_command_feedback true'], []), + ('console-save', ['save-all'], []), +] +QUIET = [ + ('console-time', ['time set 1000'], []), + ('console-whitelist', ['whitelist add Alice'], []), + ('alice', [], ['cmd Alice time set 3000']), +] +CASES = {'broadcast': ({}, BROADCAST), 'quiet': ({'broadcast-console-to-ops': 'false'}, QUIET)} +STEP_SECONDS = 2.0 + + +def run_side(label, case, server_command, client_command, build, world): + properties, script = CASES[case] + directory = build / label / case + directory.parent.mkdir(parents=True, exist_ok=True) + port = server_dir(directory, world) + with (directory / 'server.properties').open('a', encoding='iso-8859-1') as f: + f.writelines(f'{k}={v}\n' for k, v in properties.items()) + out = build / f'{label}-{case}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, f'{label}-{case}') + try: + server.wait_for(r'Done \(') + with (build / f'{label}-{case}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def tell(line): + client.stdin.write(line + '\n') + client.stdin.flush() + try: + for name in ('Alice', 'Bob'): + tell(f'join {name}') + server.wait_for(rf'{name} joined the game', timeout=120) + time.sleep(STEP_SECONDS) + tell('chat on') + for step, console, actions in script: + tell(f'step {step}') + for command in console: + server.console(command) + for action in actions: + tell(action) + time.sleep(STEP_SECONDS) + tell('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label} {case}: the client wrote no transcript (see {build}/{label}-{case}-client.log)') + lines = out.read_text(encoding='utf-8').splitlines() + errors = [l for l in lines if ' error ' in f' {l} ' or 'disconnected' in l] + return [f'{case} {l}' for l in lines if l.split(' ', 2)[2:3] and l.split(' ', 2)[2].startswith('chat ')], errors + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + import json + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + + world = generate_world(vanilla_server, build) + sides = {'vanilla': ([], []), 'horizon': ([], [])} + for case in CASES: + for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]: + lines, errors = run_side(label, case, command, client, build, world) + sides[label][0].extend(lines) + sides[label][1].extend(errors) + (vanilla, vanilla_errors), (horizon, horizon_errors) = sides['vanilla'], sides['horizon'] + (build / 'vanilla.txt').write_text('\n'.join(vanilla) + '\n', encoding='utf-8') + (build / 'horizon.txt').write_text('\n'.join(horizon) + '\n', encoding='utf-8') + errors = vanilla_errors + horizon_errors + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:6000]) + if sum('[Server' in l or 'chat.type.admin' in l for l in vanilla) < 5: + raise AssertionError(f'vanilla sent the operators too little: the script did not run (see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='The system chat two operators get on a dedicated server while the console and one of them run ' + 'commands: broadcastToAdmins for the console (broadcast-console-to-ops on and off) and a player, ' + 'queries, deop and op, send_command_feedback off and on, and save-all.')) + print(f'server ops feedback: {len(vanilla)} chat lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}')