From 492238aa2271877f6c59793c8fdab76a779ff8d5 Mon Sep 17 00:00:00 2001 From: Tanner Date: Sat, 14 Nov 2026 22:02:08 +0000 Subject: [PATCH] Add persistent web chat log --- mosfet.py | 4 + mosfet/chat_log.py | 35 +++++++++ mosfet/connect.py | 27 +++++++ mosfet/info/death_messages.py | 120 +++++++++++++++++++++++++++++ mosfet/protocol/modern.py | 5 ++ tests/test_modern_chat.py | 60 ++++++++++++++- tests/test_web_inventory_api.py | 16 +++- web_interface/build/index.html | 47 ++++++++---- web_interface/public/index.html | 47 ++++++++---- web_interface/src/dashboard.css | 20 ++++- web_interface/src/dashboard.js | 129 ++++++++++++++++++++++++++++++++ web_interface/src/index.html | 47 ++++++++---- 12 files changed, 506 insertions(+), 51 deletions(-) create mode 100644 mosfet/chat_log.py create mode 100644 mosfet/info/death_messages.py diff --git a/mosfet.py b/mosfet.py index 0f148fd..9ac17c5 100644 --- a/mosfet.py +++ b/mosfet.py @@ -36,6 +36,7 @@ g.connected = False g.connection_status = 'disconnected' g.player_position = None g.last_chat = None +g.chat_log = [] g.name = None g.mcdata = False g.pos = False @@ -155,7 +156,10 @@ def _api_json_default(value): @app.route('/api/global') def api_global(): + from mosfet.chat_log import snapshot_chat_log + snapshot = dict(_api_dict_items(g)) + snapshot['chat_log'] = snapshot_chat_log(g) job = g.get('job') job_state = getattr(job, 'state', None) if job else None snapshot['job_state'] = getattr(job_state, '__name__', 'idle') diff --git a/mosfet/chat_log.py b/mosfet/chat_log.py new file mode 100644 index 0000000..f7c3d5b --- /dev/null +++ b/mosfet/chat_log.py @@ -0,0 +1,35 @@ +"""Small shared in-memory chat history for the web dashboard.""" +import threading +import time + + +MAX_CHAT_EVENTS = 200 +_lock = threading.RLock() +_last_event_id = 0 + + +def append_chat_event(global_state, event_type, message, sender=None): + global _last_event_id + with _lock: + event_id = max(time.time_ns(), _last_event_id + 1) + _last_event_id = event_id + event = { + 'id': str(event_id), + 'timestamp': time.time(), + 'type': event_type, + 'message': str(message), + } + if sender: + event['sender'] = str(sender) + events = global_state.get('chat_log') + if not isinstance(events, list): + events = [] + global_state.chat_log = events + events.append(event) + del events[:-MAX_CHAT_EVENTS] + return event + + +def snapshot_chat_log(global_state): + with _lock: + return [dict(event) for event in global_state.get('chat_log', ())] diff --git a/mosfet/connect.py b/mosfet/connect.py index a75e878..188010e 100644 --- a/mosfet/connect.py +++ b/mosfet/connect.py @@ -9,6 +9,7 @@ from minecraft.networking.modern import ( CancelPostjoinDialog, ChatCommand, PlayGameEventPacket, PlayShowDialog, PlayLogin, SubmitPostjoinLoginDialog, SystemChat, TeleportPosition, ) +from mosfet.chat_log import append_chat_event from mosfet.protocol.managers import WorldState from mosfet.vector import Point3D @@ -63,10 +64,21 @@ def component_text(value): if 'translate' in fields: translation = component_text(fields['translate']) arguments = fields.get('with', []) + if translation.startswith(('death.attack.', 'death.fell.')): + from mosfet.info.death_messages import translate_death_message + translated = translate_death_message( + translation, arguments, component_text) + if translated is not None: + return translated if translation == 'commands.message.display.incoming' and len(arguments) >= 2: return '{} whispers to you: {}'.format( component_text(arguments[0]), component_text(arguments[1])) + if translation in ('multiplayer.player.joined', + 'multiplayer.player.left') and arguments: + name = component_text(arguments[0]) + action = 'joined' if translation.endswith('.joined') else 'left' + return '{} {} the game'.format(name, action) return translation + component_text(arguments) return ''.join(component_text(v) for v in fields.values()) if isinstance(value, (list, tuple)): @@ -74,6 +86,19 @@ def component_text(value): return str(value) +def _system_chat_log_entry(message): + if message.endswith(' joined the game'): + return 'join', message[:-len(' joined the game')], message + if message.endswith(' left the game'): + return 'leave', message[:-len(' left the game')], message + from mosfet.protocol.modern import parse_incoming_private_message + incoming = parse_incoming_private_message(message) + if incoming: + sender, body = incoming + return 'dm', sender, body + return 'system', None, message + + def main(global_state=None, *, server=None, port=None, username=None, password=None): server = server or os.environ.get('SERVER', '127.0.0.1') @@ -182,6 +207,8 @@ def main(global_state=None, *, server=None, port=None, username=None, chat_handled = False if global_state is not None: global_state.last_chat = message + event_type, sender, log_message = _system_chat_log_entry(message) + append_chat_event(global_state, event_type, log_message, sender) chat = global_state.get('chat') if chat is not None: chat_handled = chat.handle_system_chat(packet, message) diff --git a/mosfet/info/death_messages.py b/mosfet/info/death_messages.py new file mode 100644 index 0000000..9d88fa7 --- /dev/null +++ b/mosfet/info/death_messages.py @@ -0,0 +1,120 @@ +"""English templates for Minecraft 26.3 death chat components.""" + +DEATH_MESSAGE_TEMPLATES = { + 'death.attack.anvil': '{0} was squashed by a falling anvil', + 'death.attack.anvil.player': '{0} was squashed by a falling anvil while fighting {1}', + 'death.attack.arrow': '{0} was shot by {1}', + 'death.attack.arrow.item': '{0} was shot by {1} using {2}', + 'death.attack.badRespawnPoint.message': '{0} was killed by {1}', + 'death.attack.cactus': '{0} was pricked to death', + 'death.attack.cactus.player': '{0} walked into a cactus while trying to escape {1}', + 'death.attack.cramming': '{0} was squished too much', + 'death.attack.cramming.player': '{0} was squashed by {1}', + 'death.attack.dragonBreath': "{0} was roasted in dragon's breath", + 'death.attack.dragonBreath.player': "{0} was roasted in dragon's breath by {1}", + 'death.attack.drown': '{0} drowned', + 'death.attack.drown.player': '{0} drowned while trying to escape {1}', + 'death.attack.dryout': '{0} died from dehydration', + 'death.attack.dryout.player': '{0} died from dehydration while trying to escape {1}', + 'death.attack.even_more_magic': '{0} was killed by even more magic', + 'death.attack.explosion': '{0} blew up', + 'death.attack.explosion.player': '{0} was blown up by {1}', + 'death.attack.explosion.player.item': '{0} was blown up by {1} using {2}', + 'death.attack.fall': '{0} hit the ground too hard', + 'death.attack.fall.player': '{0} hit the ground too hard while trying to escape {1}', + 'death.attack.fallingBlock': '{0} was squashed by a falling block', + 'death.attack.fallingBlock.player': '{0} was squashed by a falling block while fighting {1}', + 'death.attack.fallingStalactite': '{0} was skewered by a falling stalactite', + 'death.attack.fallingStalactite.player': '{0} was skewered by a falling stalactite while fighting {1}', + 'death.attack.fireball': '{0} was fireballed by {1}', + 'death.attack.fireball.item': '{0} was fireballed by {1} using {2}', + 'death.attack.fireworks': '{0} went off with a bang', + 'death.attack.fireworks.item': '{0} went off with a bang due to a firework fired from {2} by {1}', + 'death.attack.fireworks.player': '{0} went off with a bang while fighting {1}', + 'death.attack.flyIntoWall': '{0} experienced kinetic energy', + 'death.attack.flyIntoWall.player': '{0} experienced kinetic energy while trying to escape {1}', + 'death.attack.freeze': '{0} froze to death', + 'death.attack.freeze.player': '{0} was frozen to death by {1}', + 'death.attack.generic': '{0} died', + 'death.attack.generic.player': '{0} died because of {1}', + 'death.attack.genericKill': '{0} was killed', + 'death.attack.genericKill.player': '{0} was killed while fighting {1}', + 'death.attack.hotFloor': '{0} discovered the floor was lava', + 'death.attack.hotFloor.player': '{0} walked into the danger zone due to {1}', + 'death.attack.indirectMagic': '{0} was killed by {1} using magic', + 'death.attack.indirectMagic.item': '{0} was killed by {1} using {2}', + 'death.attack.inFire': '{0} went up in flames', + 'death.attack.inFire.player': '{0} walked into fire while fighting {1}', + 'death.attack.inWall': '{0} suffocated in a wall', + 'death.attack.inWall.player': '{0} suffocated in a wall while fighting {1}', + 'death.attack.lava': '{0} tried to swim in lava', + 'death.attack.lava.player': '{0} tried to swim in lava to escape {1}', + 'death.attack.lightningBolt': '{0} was struck by lightning', + 'death.attack.lightningBolt.player': '{0} was struck by lightning while fighting {1}', + 'death.attack.mace_smash': '{0} was smashed by {1}', + 'death.attack.mace_smash.item': '{0} was smashed by {1} with {2}', + 'death.attack.magic': '{0} was killed by magic', + 'death.attack.magic.player': '{0} was killed by magic while trying to escape {1}', + 'death.attack.mob': '{0} was slain by {1}', + 'death.attack.mob.item': '{0} was slain by {1} using {2}', + 'death.attack.onFire': '{0} burned to death', + 'death.attack.onFire.item': '{0} was burned to a crisp while fighting {1} wielding {2}', + 'death.attack.onFire.player': '{0} was burned to a crisp while fighting {1}', + 'death.attack.outOfWorld': '{0} fell out of the world', + 'death.attack.outOfWorld.player': "{0} didn't want to live in the same world as {1}", + 'death.attack.outsideBorder': '{0} left the confines of this world', + 'death.attack.outsideBorder.player': '{0} left the confines of this world while fighting {1}', + 'death.attack.player': '{0} was slain by {1}', + 'death.attack.player.item': '{0} was slain by {1} using {2}', + 'death.attack.sonic_boom': '{0} was obliterated by a sonically-charged shriek', + 'death.attack.sonic_boom.item': '{0} was obliterated by a sonically-charged shriek while trying to escape {1} wielding {2}', + 'death.attack.sonic_boom.player': '{0} was obliterated by a sonically-charged shriek while trying to escape {1}', + 'death.attack.spear': '{0} was speared by {1}', + 'death.attack.spear.item': '{0} was speared by {1} using {2}', + 'death.attack.stalagmite': '{0} was impaled on a stalagmite', + 'death.attack.stalagmite.player': '{0} was impaled on a stalagmite while fighting {1}', + 'death.attack.starve': '{0} starved to death', + 'death.attack.starve.player': '{0} starved to death while fighting {1}', + 'death.attack.sting': '{0} was stung to death', + 'death.attack.sting.item': '{0} was stung to death by {1} using {2}', + 'death.attack.sting.player': '{0} was stung to death by {1}', + 'death.attack.sulfurCubeHot': '{0} died because not just the floor is lava', + 'death.attack.sulfurCubeHot.item': '{1} showed {0} that not just the floor is lava using {2}', + 'death.attack.sulfurCubeHot.player': '{1} showed {0} that not just the floor is lava', + 'death.attack.sweetBerryBush': '{0} was poked to death by a sweet berry bush', + 'death.attack.sweetBerryBush.player': '{0} was poked to death by a sweet berry bush while trying to escape {1}', + 'death.attack.thorns': '{0} was killed while trying to hurt {1}', + 'death.attack.thorns.item': '{0} was killed by {2} while trying to hurt {1}', + 'death.attack.thrown': '{0} was pummeled by {1}', + 'death.attack.thrown.item': '{0} was pummeled by {1} using {2}', + 'death.attack.trident': '{0} was impaled by {1}', + 'death.attack.trident.item': '{0} was impaled by {1} with {2}', + 'death.attack.wither': '{0} withered away', + 'death.attack.wither.player': '{0} withered away while fighting {1}', + 'death.attack.witherSkull': '{0} was shot by a skull from {1}', + 'death.attack.witherSkull.item': '{0} was shot by a skull from {1} using {2}', + 'death.fell.accident.generic': '{0} fell from a high place', + 'death.fell.accident.ladder': '{0} fell off a ladder', + 'death.fell.accident.other_climbable': '{0} fell while climbing', + 'death.fell.accident.scaffolding': '{0} fell off scaffolding', + 'death.fell.accident.twisting_vines': '{0} fell off some twisting vines', + 'death.fell.accident.vines': '{0} fell off some vines', + 'death.fell.accident.weeping_vines': '{0} fell off some weeping vines', + 'death.fell.assist': '{0} was doomed to fall by {1}', + 'death.fell.assist.item': '{0} was doomed to fall by {1} using {2}', + 'death.fell.finish': '{0} fell too far and was finished by {1}', + 'death.fell.finish.item': '{0} fell too far and was finished by {1} using {2}', + 'death.fell.killer': '{0} was doomed to fall', +} + + +def translate_death_message(translation, arguments, render_component): + """Format a known death translation with its component arguments.""" + template = DEATH_MESSAGE_TEMPLATES.get(translation) + if template is None: + return None + values = [render_component(argument) for argument in arguments] + try: + return template.format(*values) + except (IndexError, KeyError, ValueError): + return None diff --git a/mosfet/protocol/modern.py b/mosfet/protocol/modern.py index 602f2e4..b018363 100644 --- a/mosfet/protocol/modern.py +++ b/mosfet/protocol/modern.py @@ -10,6 +10,7 @@ from minecraft.networking.types import ( from minecraft.networking.modern import ( ChatCommand, ClientboundPlayerChatPacket, ServerboundChatPacket, SystemChat, ) +from mosfet.chat_log import append_chat_event class UpdateTimePacket(Packet): @@ -106,6 +107,8 @@ class ModernChatManager: ) ) label = '[DM] ' if is_dm else '' + append_chat_event( + self.g, 'dm' if is_dm else 'chat', packet.message, sender_name) print('[chat] {}{}: {}'.format(label, sender_name, packet.message), flush=True) if self.handler: @@ -140,6 +143,8 @@ class ModernChatManager: self.g.connection.write_packet( ChatCommand(command=message[1:]), force=True) else: + append_chat_event(self.g, 'outgoing', message, + self.g.get('name', 'Mosfet')) packet = ServerboundChatPacket( message=message, timestamp=int(time.time() * 1000)) self.g.connection.write_packet(packet, force=True) diff --git a/tests/test_modern_chat.py b/tests/test_modern_chat.py index b4d24da..9ae2874 100644 --- a/tests/test_modern_chat.py +++ b/tests/test_modern_chat.py @@ -8,16 +8,22 @@ from munch import Munch from minecraft.networking.modern import ClientboundPlayerChatPacket from mosfet.commands import Commands -from mosfet.connect import component_text +from mosfet.connect import _system_chat_log_entry, component_text from mosfet.protocol.modern import ( ModernChatManager, parse_incoming_private_message, ) class FakeConnection: + def __init__(self): + self.packets = [] + def register_packet_listener(self, *_args, **_kwargs): pass + def write_packet(self, packet, force=False): + self.packets.append((packet, force)) + class FakeChat: def __init__(self): @@ -42,6 +48,40 @@ class TestModernChat(unittest.TestCase): self.assertEqual(parse_incoming_private_message( 'tanner -> me: 1ping'), ('tanner', '1ping')) + def test_death_message_translations_are_readable(self): + self.assertEqual(component_text({ + 'translate': 'death.attack.player', + 'with': ['mosfet1', 'tanner'], + }), 'mosfet1 was slain by tanner') + self.assertEqual(component_text({ + 'translate': 'death.attack.player.item', + 'with': ['mosfet1', 'tanner', {'text': 'diamond sword'}], + }), 'mosfet1 was slain by tanner using diamond sword') + self.assertEqual(component_text({ + 'translate': 'death.attack.thorns.item', + 'with': ['mosfet1', 'zombie', {'text': 'thorns'}], + }), 'mosfet1 was killed by thorns while trying to hurt zombie') + + def test_player_join_and_leave_translations_are_readable(self): + self.assertEqual(component_text({ + 'translate': 'multiplayer.player.joined', + 'with': [{'text': 'tanner'}], + }), 'tanner joined the game') + self.assertEqual(component_text({ + 'translate': 'multiplayer.player.left', + 'with': [{'text': 'tanner'}], + }), 'tanner left the game') + self.assertEqual(_system_chat_log_entry('tanner joined the game'), ( + 'join', 'tanner', 'tanner joined the game')) + self.assertEqual(_system_chat_log_entry('tanner left the game'), ( + 'leave', 'tanner', 'tanner left the game')) + + def test_system_chat_log_recognizes_private_messages(self): + self.assertEqual(_system_chat_log_entry( + 'tanner whispers to you: hello'), ('dm', 'tanner', 'hello')) + self.assertEqual(_system_chat_log_entry('Server restarting'), ( + 'system', None, 'Server restarting')) + def test_player_chat_console_uses_name_but_keeps_uuid_for_commands(self): player_uuid = 'f6126022-2c68-37f7-be93-aaa551374663' state = Munch( @@ -62,6 +102,9 @@ class TestModernChat(unittest.TestCase): self.assertEqual(received, [ ('CHAT', player_uuid, 'tanner: !ping'), ]) + self.assertEqual(state.chat_log[0]['type'], 'chat') + self.assertEqual(state.chat_log[0]['sender'], 'tanner') + self.assertEqual(state.chat_log[0]['message'], '!ping') def test_player_chat_target_name_marks_dm_and_routes_reply(self): player_uuid = 'f6126022-2c68-37f7-be93-aaa551374663' @@ -84,6 +127,21 @@ class TestModernChat(unittest.TestCase): self.assertEqual(received, [ ('DM', player_uuid, 'tanner -> me: !ping', 'tanner'), ]) + self.assertEqual(state.chat_log[0]['type'], 'dm') + + def test_outgoing_chat_is_logged_but_commands_are_not(self): + connection = FakeConnection() + state = Munch(connection=connection, name='mosfet1', reload_lock=None) + manager = ModernChatManager(state) + + manager.send('hello server') + manager.send('/login secret') + + self.assertEqual(len(state.chat_log), 1) + self.assertEqual(state.chat_log[0]['type'], 'outgoing') + self.assertEqual(state.chat_log[0]['sender'], 'mosfet1') + self.assertEqual(state.chat_log[0]['message'], 'hello server') + self.assertEqual(len(connection.packets), 2) def test_player_chat_parser_reads_optional_target_name(self): def varint(value): diff --git a/tests/test_web_inventory_api.py b/tests/test_web_inventory_api.py index 3576f8c..90bc80e 100644 --- a/tests/test_web_inventory_api.py +++ b/tests/test_web_inventory_api.py @@ -69,7 +69,7 @@ class TestWebInventoryAPI(unittest.TestCase): key: self.g.get(key) for key in ('connected', 'game', 'inv', 'chest_viewers', 'time', 'time_base', 'weather', 'rain_level', 'thunder_level', 'chunks', 'pos', 'yaw', - 'path') + 'path', 'chat_log') } self.game = FakeGame() self.g.connected = True @@ -187,6 +187,20 @@ class TestWebInventoryAPI(unittest.TestCase): self.assertEqual(data['radius_x'], 48) self.assertEqual(data['radius_z'], 36) + def test_global_api_exposes_chat_log_events(self): + self.g.chat_log = [{ + 'id': '123', 'timestamp': 123.0, 'type': 'join', + 'sender': 'tanner', 'message': 'tanner joined the game', + }] + + response = self.client.get('/api/global') + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.get_json()['chat_log'][0], { + 'id': '123', 'timestamp': 123.0, 'type': 'join', + 'sender': 'tanner', 'message': 'tanner joined the game', + }) + def test_global_api_exposes_world_time_ticks(self): self.g.time = 12345.5 self.g.time_base = 12345.5 diff --git a/web_interface/build/index.html b/web_interface/build/index.html index 8ed5cb9..8ca252a 100644 --- a/web_interface/build/index.html +++ b/web_interface/build/index.html @@ -52,24 +52,39 @@
-
-
-
-
PLAYER STORAGE
-

Inventory

+
+
+
+
+
PLAYER STORAGE
+

Inventory

+
+
+ 0 items + + 0 / 46 slots +
-
- 0 items - - 0 / 46 slots + -
- -
-
Empty slot Selected hotbar slot Hover for details · click an item for actions
-
+
+
Empty slot Selected hotbar slot Hover for details · click an item for actions
+
+ +
+
+
+
SERVER · CHAT
+

Chat Log

+
+ +
+
+
No chat messages yet
+
+
+