Add dashboard chat controls and suppress echoes
This commit is contained in:
1 parent
5a3b299aa9
commit
c3a045d17a
10 files changed
+178
-13
No files matched your search
@@ -72,3 +72,11 @@ PY
|
|||||||
```
|
```
|
||||||
$ for i in $(seq 1 8); do curl -fsS --max-time 2 http://127.0.0.1:3301/api/global | jq -c '{movement_status,pos,path,breaking,job_state}'; sleep 1; done (timeout 15s)
|
$ for i in $(seq 1 8); do curl -fsS --max-time 2 http://127.0.0.1:3301/api/global | jq -c '{movement_status,pos,path,breaking,job_state}'; sleep 1; done (timeout 15s)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
- Send a Minecraft command through the web chat API while `mosfet1` is running:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -sS http://127.0.0.1:3301/api/chat \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"message":"1farm sand"}'
|
||||||
|
```
|
||||||
@@ -389,6 +389,33 @@ def _fetch_item_texture(name):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/api/chat', methods=['POST'])
|
||||||
|
def api_chat():
|
||||||
|
origin = request.headers.get('Origin')
|
||||||
|
if origin:
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
if urlparse(origin).netloc.lower() != request.host.lower():
|
||||||
|
return jsonify(ok=False, error='cross-origin chat actions are blocked'), 403
|
||||||
|
|
||||||
|
payload = request.get_json(silent=True)
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
return jsonify(ok=False, error='JSON body must be an object'), 400
|
||||||
|
message = payload.get('message')
|
||||||
|
if not isinstance(message, str):
|
||||||
|
return jsonify(ok=False, error='message must be a string'), 400
|
||||||
|
message = message.strip()
|
||||||
|
if not message:
|
||||||
|
return jsonify(ok=False, error='message cannot be empty'), 400
|
||||||
|
if len(message) > 256:
|
||||||
|
return jsonify(ok=False, error='message exceeds 256 characters'), 400
|
||||||
|
if not g.get('connected') or not g.get('chat'):
|
||||||
|
return jsonify(ok=False, error='bot is not connected'), 503
|
||||||
|
|
||||||
|
with g.reload_lock:
|
||||||
|
g.chat.send(message)
|
||||||
|
return jsonify(ok=True, command=message.startswith('/'))
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/item-icon/<name>')
|
@app.route('/api/item-icon/<name>')
|
||||||
def api_item_icon(name):
|
def api_item_icon(name):
|
||||||
from mosfet.info.items import ITEM_NAMES
|
from mosfet.info.items import ITEM_NAMES
|
||||||
|
|||||||
@@ -143,8 +143,8 @@ class ModernChatManager:
|
|||||||
self.g.connection.write_packet(
|
self.g.connection.write_packet(
|
||||||
ChatCommand(command=message[1:]), force=True)
|
ChatCommand(command=message[1:]), force=True)
|
||||||
else:
|
else:
|
||||||
append_chat_event(self.g, 'outgoing', message,
|
|
||||||
self.g.get('name', 'Mosfet'))
|
|
||||||
packet = ServerboundChatPacket(
|
packet = ServerboundChatPacket(
|
||||||
message=message, timestamp=int(time.time() * 1000))
|
message=message, timestamp=int(time.time() * 1000))
|
||||||
self.g.connection.write_packet(packet, force=True)
|
self.g.connection.write_packet(packet, force=True)
|
||||||
|
append_chat_event(self.g, 'outgoing', message,
|
||||||
|
self.g.get('name', 'Mosfet'))
|
||||||
@@ -5,7 +5,7 @@ import unittest
|
|||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from munch import Munch
|
from munch import Munch
|
||||||
from minecraft.networking.modern import ClientboundPlayerChatPacket
|
from minecraft.networking.modern import ChatCommand, ClientboundPlayerChatPacket
|
||||||
|
|
||||||
from mosfet.commands import Commands
|
from mosfet.commands import Commands
|
||||||
from mosfet.connect import _system_chat_log_entry, component_text
|
from mosfet.connect import _system_chat_log_entry, component_text
|
||||||
@@ -142,6 +142,8 @@ class TestModernChat(unittest.TestCase):
|
|||||||
self.assertEqual(state.chat_log[0]['sender'], 'mosfet1')
|
self.assertEqual(state.chat_log[0]['sender'], 'mosfet1')
|
||||||
self.assertEqual(state.chat_log[0]['message'], 'hello server')
|
self.assertEqual(state.chat_log[0]['message'], 'hello server')
|
||||||
self.assertEqual(len(connection.packets), 2)
|
self.assertEqual(len(connection.packets), 2)
|
||||||
|
self.assertIsInstance(connection.packets[1][0], ChatCommand)
|
||||||
|
self.assertEqual(connection.packets[1][0].command, 'login secret')
|
||||||
|
|
||||||
def test_player_chat_parser_reads_optional_target_name(self):
|
def test_player_chat_parser_reads_optional_target_name(self):
|
||||||
def varint(value):
|
def varint(value):
|
||||||
|
|||||||
@@ -95,7 +95,7 @@ class TestWebInventoryAPI(unittest.TestCase):
|
|||||||
key: self.g.get(key) for key in
|
key: self.g.get(key) for key in
|
||||||
('connected', 'game', 'inv', 'chest_viewers', 'time', 'time_base',
|
('connected', 'game', 'inv', 'chest_viewers', 'time', 'time_base',
|
||||||
'weather', 'rain_level', 'thunder_level', 'chunks', 'pos', 'yaw',
|
'weather', 'rain_level', 'thunder_level', 'chunks', 'pos', 'yaw',
|
||||||
'path', 'chat_log')
|
'path', 'chat_log', 'chat')
|
||||||
}
|
}
|
||||||
self.game = FakeGame()
|
self.game = FakeGame()
|
||||||
self.g.connected = True
|
self.g.connected = True
|
||||||
@@ -281,6 +281,46 @@ class TestWebInventoryAPI(unittest.TestCase):
|
|||||||
'(12, 64, -7)': 1,
|
'(12, 64, -7)': 1,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
def test_chat_endpoint_sends_messages_and_slash_commands(self):
|
||||||
|
class FakeChat:
|
||||||
|
def __init__(self):
|
||||||
|
self.messages = []
|
||||||
|
|
||||||
|
def send(self, message):
|
||||||
|
self.messages.append(message)
|
||||||
|
|
||||||
|
chat = FakeChat()
|
||||||
|
self.g.chat = chat
|
||||||
|
|
||||||
|
message = self.client.post('/api/chat', json={
|
||||||
|
'message': 'hello from dashboard',
|
||||||
|
})
|
||||||
|
command = self.client.post('/api/chat', json={
|
||||||
|
'message': '/help',
|
||||||
|
})
|
||||||
|
|
||||||
|
self.assertEqual(message.status_code, 200)
|
||||||
|
self.assertFalse(message.get_json()['command'])
|
||||||
|
self.assertEqual(command.status_code, 200)
|
||||||
|
self.assertTrue(command.get_json()['command'])
|
||||||
|
self.assertEqual(chat.messages, ['hello from dashboard', '/help'])
|
||||||
|
|
||||||
|
def test_chat_endpoint_validates_input_and_rejects_cross_origin(self):
|
||||||
|
class FakeChat:
|
||||||
|
def send(self, _message):
|
||||||
|
raise AssertionError('invalid request must not be sent')
|
||||||
|
|
||||||
|
self.g.chat = FakeChat()
|
||||||
|
self.assertEqual(self.client.post('/api/chat', json={
|
||||||
|
'message': ' ',
|
||||||
|
}).status_code, 400)
|
||||||
|
self.assertEqual(self.client.post('/api/chat', json={
|
||||||
|
'message': 'x' * 257,
|
||||||
|
}).status_code, 400)
|
||||||
|
self.assertEqual(self.client.post('/api/chat', json={
|
||||||
|
'message': '/help',
|
||||||
|
}, headers={'Origin': 'https://elsewhere.example'}).status_code, 403)
|
||||||
|
|
||||||
def test_drop_endpoint_supports_one_stack_and_matching_actions(self):
|
def test_drop_endpoint_supports_one_stack_and_matching_actions(self):
|
||||||
one = self.client.post('/api/inventory/drop', json={
|
one = self.client.post('/api/inventory/drop', json={
|
||||||
'slot': 9, 'action': 'one'})
|
'slot': 9, 'action': 'one'})
|
||||||
|
|||||||
@@ -6,8 +6,8 @@
|
|||||||
<meta name="theme-color" content="#10130f" />
|
<meta name="theme-color" content="#10130f" />
|
||||||
<meta name="description" content="Live Minecraft bot dashboard" />
|
<meta name="description" content="Live Minecraft bot dashboard" />
|
||||||
<title>Mosfet · Minecraft Bot</title>
|
<title>Mosfet · Minecraft Bot</title>
|
||||||
<link rel="stylesheet" href="/static/css/dashboard.css?v=20" />
|
<link rel="stylesheet" href="/static/css/dashboard.css?v=21" />
|
||||||
<script defer src="/static/js/dashboard.js?v=23"></script>
|
<script defer src="/static/js/dashboard.js?v=25"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="shell">
|
<div class="shell">
|
||||||
@@ -83,6 +83,13 @@
|
|||||||
<div id="chat-log" class="chat-log" role="log" aria-label="Chat messages">
|
<div id="chat-log" class="chat-log" role="log" aria-label="Chat messages">
|
||||||
<div class="chat-empty">No chat messages yet</div>
|
<div class="chat-empty">No chat messages yet</div>
|
||||||
</div>
|
</div>
|
||||||
|
<form id="chat-form" class="chat-form">
|
||||||
|
<input id="chat-input" type="text" maxlength="256"
|
||||||
|
placeholder="Message or /command…" aria-label="Chat message or command"
|
||||||
|
autocomplete="off" disabled>
|
||||||
|
<button id="chat-send" type="submit" disabled>Send</button>
|
||||||
|
</form>
|
||||||
|
<div id="chat-send-status" class="chat-send-status" role="status" aria-live="polite"></div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -6,8 +6,8 @@
|
|||||||
<meta name="theme-color" content="#10130f" />
|
<meta name="theme-color" content="#10130f" />
|
||||||
<meta name="description" content="Live Minecraft bot dashboard" />
|
<meta name="description" content="Live Minecraft bot dashboard" />
|
||||||
<title>Mosfet · Minecraft Bot</title>
|
<title>Mosfet · Minecraft Bot</title>
|
||||||
<link rel="stylesheet" href="/static/css/dashboard.css?v=20" />
|
<link rel="stylesheet" href="/static/css/dashboard.css?v=21" />
|
||||||
<script defer src="/static/js/dashboard.js?v=23"></script>
|
<script defer src="/static/js/dashboard.js?v=25"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="shell">
|
<div class="shell">
|
||||||
@@ -83,6 +83,13 @@
|
|||||||
<div id="chat-log" class="chat-log" role="log" aria-label="Chat messages">
|
<div id="chat-log" class="chat-log" role="log" aria-label="Chat messages">
|
||||||
<div class="chat-empty">No chat messages yet</div>
|
<div class="chat-empty">No chat messages yet</div>
|
||||||
</div>
|
</div>
|
||||||
|
<form id="chat-form" class="chat-form">
|
||||||
|
<input id="chat-input" type="text" maxlength="256"
|
||||||
|
placeholder="Message or /command…" aria-label="Chat message or command"
|
||||||
|
autocomplete="off" disabled>
|
||||||
|
<button id="chat-send" type="submit" disabled>Send</button>
|
||||||
|
</form>
|
||||||
|
<div id="chat-send-status" class="chat-send-status" role="status" aria-live="polite"></div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -96,6 +96,17 @@ h1 { margin: 5px 0 3px; font-size: 34px; line-height: 1.05; letter-spacing: -.02
|
|||||||
.chat-entry-leave .chat-entry-message { color: #d19b82; }
|
.chat-entry-leave .chat-entry-message { color: #d19b82; }
|
||||||
.chat-entry-system .chat-entry-message { color: var(--muted); }
|
.chat-entry-system .chat-entry-message { color: var(--muted); }
|
||||||
.chat-empty { padding: 15px 4px; color: var(--muted); text-align: center; font-size: 11px; }
|
.chat-empty { padding: 15px 4px; color: var(--muted); text-align: center; font-size: 11px; }
|
||||||
|
.chat-form { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 5px; margin-top: 7px; }
|
||||||
|
.chat-form input { min-width: 0; height: 32px; padding: 5px 8px; border: 1px solid var(--border); border-radius: 3px; outline: none; color: var(--text); background: #111411; font: 11px var(--sans); }
|
||||||
|
.chat-form input:focus { border-color: #68894e; }
|
||||||
|
.chat-form input::placeholder { color: var(--subtle); }
|
||||||
|
.chat-form input:disabled { opacity: .55; }
|
||||||
|
.chat-form button { min-width: 56px; padding: 4px 9px; border: 1px solid #536a42; border-radius: 3px; color: var(--accent); background: #22291f; font: 10px var(--mono); cursor: pointer; }
|
||||||
|
.chat-form button:hover:not(:disabled) { border-color: var(--accent); background: #2c3825; }
|
||||||
|
.chat-form button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||||
|
.chat-form button:disabled { opacity: .45; cursor: not-allowed; }
|
||||||
|
.chat-send-status { min-height: 14px; margin-top: 4px; color: var(--subtle); font-size: 10px; }
|
||||||
|
.chat-send-status.is-error { color: var(--red); }
|
||||||
.section-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 11px; }
|
.section-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 11px; }
|
||||||
h2 { margin: 3px 0 0; font-size: 20px; letter-spacing: -.01em; font-weight: 600; }
|
h2 { margin: 3px 0 0; font-size: 20px; letter-spacing: -.01em; font-weight: 600; }
|
||||||
.inventory-summary { display: flex; gap: 8px; align-items: center; color: var(--muted); font: 11px var(--mono); }
|
.inventory-summary { display: flex; gap: 8px; align-items: center; color: var(--muted); font: 11px var(--mono); }
|
||||||
|
|||||||
@@ -20,6 +20,7 @@
|
|||||||
let minimapNorthLocked = true;
|
let minimapNorthLocked = true;
|
||||||
let minimapLarge = false;
|
let minimapLarge = false;
|
||||||
let minimapRequestPending = false;
|
let minimapRequestPending = false;
|
||||||
|
let chatSendPending = false;
|
||||||
let lastMinimapData = null;
|
let lastMinimapData = null;
|
||||||
const storedChatState = loadChatState();
|
const storedChatState = loadChatState();
|
||||||
let chatEntries = storedChatState.entries;
|
let chatEntries = storedChatState.entries;
|
||||||
@@ -676,12 +677,27 @@
|
|||||||
if (chatSeenIds.has(event.id)) continue;
|
if (chatSeenIds.has(event.id)) continue;
|
||||||
const type = ['chat', 'dm', 'outgoing', 'system', 'join', 'leave'].includes(event.type)
|
const type = ['chat', 'dm', 'outgoing', 'system', 'join', 'leave'].includes(event.type)
|
||||||
? event.type : 'system';
|
? event.type : 'system';
|
||||||
|
const sender = String(event.sender || '');
|
||||||
|
const message = String(event.message || '');
|
||||||
|
const eventTime = Number(event.timestamp);
|
||||||
|
const botName = String(lastState?.name || '').toLowerCase();
|
||||||
|
// Servers echo sent messages back as player chat; keep the SENT entry only.
|
||||||
|
const isBotEcho = type === 'chat' && botName &&
|
||||||
|
sender.toLowerCase() === botName && chatEntries.some((sent) => {
|
||||||
|
const age = eventTime - Number(sent.timestamp);
|
||||||
|
return sent.type === 'outgoing' && sent.sender === event.sender &&
|
||||||
|
sent.message === message && age >= -1 && age <= 30;
|
||||||
|
});
|
||||||
|
if (isBotEcho) {
|
||||||
|
chatSeenIds.add(event.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
chatEntries.push({
|
chatEntries.push({
|
||||||
id: event.id,
|
id: event.id,
|
||||||
timestamp: Number(event.timestamp),
|
timestamp: eventTime,
|
||||||
type,
|
type,
|
||||||
sender: String(event.sender || ''),
|
sender,
|
||||||
message: String(event.message || ''),
|
message,
|
||||||
});
|
});
|
||||||
chatSeenIds.add(event.id);
|
chatSeenIds.add(event.id);
|
||||||
changed = true;
|
changed = true;
|
||||||
@@ -706,6 +722,43 @@
|
|||||||
toastTimer = window.setTimeout(() => toast.classList.remove('visible'), 2400);
|
toastTimer = window.setTimeout(() => toast.classList.remove('visible'), 2400);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function sendChatMessage(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
const input = $('chat-input');
|
||||||
|
const send = $('chat-send');
|
||||||
|
const status = $('chat-send-status');
|
||||||
|
const message = input.value.trim();
|
||||||
|
if (!message) return;
|
||||||
|
|
||||||
|
chatSendPending = true;
|
||||||
|
input.disabled = true;
|
||||||
|
send.disabled = true;
|
||||||
|
status.classList.remove('is-error');
|
||||||
|
status.textContent = 'Sending…';
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/chat', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({message}),
|
||||||
|
});
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok || !result.ok) {
|
||||||
|
throw new Error(result.error || `API ${response.status}`);
|
||||||
|
}
|
||||||
|
input.value = '';
|
||||||
|
status.textContent = result.command ? 'Command sent' : 'Message sent';
|
||||||
|
} catch (error) {
|
||||||
|
status.textContent = error.message;
|
||||||
|
status.classList.add('is-error');
|
||||||
|
} finally {
|
||||||
|
chatSendPending = false;
|
||||||
|
const online = Boolean(lastState?.connected) &&
|
||||||
|
lastState.connection_status === 'in_game';
|
||||||
|
input.disabled = !online;
|
||||||
|
send.disabled = !online;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function runInventoryAction(action) {
|
async function runInventoryAction(action) {
|
||||||
if (!selectedInventoryItem) return;
|
if (!selectedInventoryItem) return;
|
||||||
const selected = {...selectedInventoryItem};
|
const selected = {...selectedInventoryItem};
|
||||||
@@ -804,6 +857,8 @@
|
|||||||
$('afk-state').textContent = state.afk ? 'YES' : 'NO';
|
$('afk-state').textContent = state.afk ? 'YES' : 'NO';
|
||||||
$('movement-error').hidden = !state.movement_error;
|
$('movement-error').hidden = !state.movement_error;
|
||||||
$('movement-error').textContent = state.movement_error ? `Movement error: ${state.movement_error}` : '';
|
$('movement-error').textContent = state.movement_error ? `Movement error: ${state.movement_error}` : '';
|
||||||
|
$('chat-input').disabled = !online || chatSendPending;
|
||||||
|
$('chat-send').disabled = !online || chatSendPending;
|
||||||
|
|
||||||
renderInventory(state);
|
renderInventory(state);
|
||||||
renderPlayers(state);
|
renderPlayers(state);
|
||||||
@@ -947,6 +1002,7 @@
|
|||||||
positionFloating($('inventory-menu'), rect.left, rect.bottom + 4);
|
positionFloating($('inventory-menu'), rect.left, rect.bottom + 4);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$('chat-form').addEventListener('submit', sendChatMessage);
|
||||||
$('chat-clear').addEventListener('click', () => {
|
$('chat-clear').addEventListener('click', () => {
|
||||||
chatClearBefore = latestChatEventId || chatEntries.at(-1)?.id || chatClearBefore;
|
chatClearBefore = latestChatEventId || chatEntries.at(-1)?.id || chatClearBefore;
|
||||||
chatEntries = [];
|
chatEntries = [];
|
||||||
|
|||||||
@@ -6,8 +6,8 @@
|
|||||||
<meta name="theme-color" content="#10130f" />
|
<meta name="theme-color" content="#10130f" />
|
||||||
<meta name="description" content="Live Minecraft bot dashboard" />
|
<meta name="description" content="Live Minecraft bot dashboard" />
|
||||||
<title>Mosfet · Minecraft Bot</title>
|
<title>Mosfet · Minecraft Bot</title>
|
||||||
<link rel="stylesheet" href="/static/css/dashboard.css?v=20" />
|
<link rel="stylesheet" href="/static/css/dashboard.css?v=21" />
|
||||||
<script defer src="/static/js/dashboard.js?v=23"></script>
|
<script defer src="/static/js/dashboard.js?v=25"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="shell">
|
<div class="shell">
|
||||||
@@ -83,6 +83,13 @@
|
|||||||
<div id="chat-log" class="chat-log" role="log" aria-label="Chat messages">
|
<div id="chat-log" class="chat-log" role="log" aria-label="Chat messages">
|
||||||
<div class="chat-empty">No chat messages yet</div>
|
<div class="chat-empty">No chat messages yet</div>
|
||||||
</div>
|
</div>
|
||||||
|
<form id="chat-form" class="chat-form">
|
||||||
|
<input id="chat-input" type="text" maxlength="256"
|
||||||
|
placeholder="Message or /command…" aria-label="Chat message or command"
|
||||||
|
autocomplete="off" disabled>
|
||||||
|
<button id="chat-send" type="submit" disabled>Send</button>
|
||||||
|
</form>
|
||||||
|
<div id="chat-send-status" class="chat-send-status" role="status" aria-live="polite"></div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user