From d8bf7ebb72ac57023546d539ca9c3a15c379fbb9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 28 Sep 2026 20:05:11 +0000 Subject: [PATCH 1/2] Remote Crew: browser hint for non-Chromium browsers, startup watchdog, 31 kn navigation limit --- data/commander/css/screens.css | 1 + data/commander/css/shell.css | 1 + data/commander/index.html | 7 +- data/commander/js/browser-check.js | 31 ++++ data/commander/js/input/wiring.js | 2 +- data/commander/js/state/display-model.js | 2 +- data/i18n/de.json | 2 + data/i18n/en.json | 2 + tests/test_commander_pairing_browser.py | 186 +++++++++++++++++++++++ 9 files changed, 229 insertions(+), 5 deletions(-) create mode 100644 data/commander/js/browser-check.js create mode 100644 tests/test_commander_pairing_browser.py diff --git a/data/commander/css/screens.css b/data/commander/css/screens.css index 632888b0..046230aa 100644 --- a/data/commander/css/screens.css +++ b/data/commander/css/screens.css @@ -108,3 +108,4 @@ body.workstation-mode .role-rail, body.workstation-mode .mobile-role { display: .mobile-role:not([hidden]) { grid-template-columns: minmax(0, 1fr) auto; } .mobile-role label { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0, 0, 0, 0); } } +.pair-card > .browser-hint { padding: .6rem .8rem; color: var(--text); background: var(--bg-3); border-left: 3px solid var(--alarm); } diff --git a/data/commander/css/shell.css b/data/commander/css/shell.css index 492e4a36..9807a0fd 100644 --- a/data/commander/css/shell.css +++ b/data/commander/css/shell.css @@ -268,3 +268,4 @@ body.workstation-mode .tablist { display: none; } .dock[data-collapsed="true"] .dock-title { writing-mode: horizontal-tb; transform: none; } .dock[data-collapsed="true"] .dock-toggle { order: 0; } } +.bootstrap-hint { flex-basis: 100%; max-width: 46ch; margin: 0; color: var(--alarm); text-align: center; } diff --git a/data/commander/index.html b/data/commander/index.html index e48d10f1..bad9a58c 100644 --- a/data/commander/index.html +++ b/data/commander/index.html @@ -14,11 +14,12 @@ + -
U-Jagd Commander
+
U-Jagd Commander
diff --git a/data/commander/js/browser-check.js b/data/commander/js/browser-check.js new file mode 100644 index 00000000..41db0a4b --- /dev/null +++ b/data/commander/js/browser-check.js @@ -0,0 +1,31 @@ +// Browser check of the pairing page. A classic script, independent of the +// ES module client: it still runs when a browser cannot load or evaluate the +// modules, so the page never stays silently on its loading screen. +(() => { + const agent = navigator.userAgent || ""; + // Chrome, Chromium, Edge, Opera and other Blink browsers name "Chrome/"; + // Firefox and Safari (also Chrome on iOS, which is WebKit) do not. + const chromium = /(?:Chrome|Chromium)\/\d/.test(agent) && !/\b(?:CriOS|FxiOS|EdgiOS)\//.test(agent); + const root = document.documentElement; + root.dataset.browser = chromium ? "chromium" : "other"; + const hint = document.getElementById("browser-hint"); + if (hint) hint.hidden = chromium; + // The module client hides #bootstrap once its language catalog is loaded. + setTimeout(async () => { + const bootstrap = document.getElementById("bootstrap"); + const note = document.getElementById("bootstrap-hint"); + if (!bootstrap || bootstrap.hidden || !note) return; + root.dataset.startup = "stalled"; + const language = /^de\b/i.test(navigator.language || "") ? "de" : "en"; + try { + const response = await fetch(`/api/v2/ui?lang=${language}`, {cache: "no-store", credentials: "omit"}); + const catalog = response.ok ? await response.json() : null; + const text = catalog && catalog["commander.web.browser_stalled"]; + if (typeof text !== "string" || bootstrap.hidden) return; + note.textContent = text; + note.hidden = false; + } catch (_) { + // The host is unreachable: the loading screen stays as it is. + } + }, 8000); +})(); diff --git a/data/commander/js/input/wiring.js b/data/commander/js/input/wiring.js index 3b86ba2a..5b07521b 100644 --- a/data/commander/js/input/wiring.js +++ b/data/commander/js/input/wiring.js @@ -670,7 +670,7 @@ export function init() { if (course !== null) params.course = course; if (speed !== null) params.speed_kn = speed; if (!Object.keys(params).length || (course !== null && (!finite(course) || course < 0 || course >= 360)) || - (speed !== null && (!finite(speed) || speed < 0 || speed > 25))) { + (speed !== null && (!finite(speed) || speed < 0 || speed > 31))) { S.commandMessage = {key: "navigation_invalid", status: "rejected"}; renderActionState(); return; diff --git a/data/commander/js/state/display-model.js b/data/commander/js/state/display-model.js index 2cb2665a..0662562d 100644 --- a/data/commander/js/state/display-model.js +++ b/data/commander/js/state/display-model.js @@ -118,7 +118,7 @@ export function validateProposals(value) { if (value.navigation !== null && (!exactKeys(value.navigation, ["course", "speed_kn", "status"]) || value.role !== "bridge" || !validStatus(value.navigation.status) || (value.navigation.course !== null && (!finite(value.navigation.course) || value.navigation.course < 0 || value.navigation.course >= 360)) || - (value.navigation.speed_kn !== null && (!finite(value.navigation.speed_kn) || value.navigation.speed_kn < 0 || value.navigation.speed_kn > 25)) || + (value.navigation.speed_kn !== null && (!finite(value.navigation.speed_kn) || value.navigation.speed_kn < 0 || value.navigation.speed_kn > 31)) || value.navigation.course === null && value.navigation.speed_kn === null)) throw new Error("proposals"); } export function validateEvents(value) { diff --git a/data/i18n/de.json b/data/i18n/de.json index 63c6d184..1a78cb85 100644 --- a/data/i18n/de.json +++ b/data/i18n/de.json @@ -417,6 +417,8 @@ "commander.web.pair_intro": "Mission beobachten, Kontakte bewerten und der Besatzung ein Ziel vorschlagen. Das taktische Lagebild im Blick behalten, ohne das Ruder zu übernehmen.", "commander.web.authority_note": "Schiffsführung und Waffeneinsatz bleiben bei der Besatzung. Ein Zielvorschlag ist kein Waffenbefehl.", "commander.web.pair_heading": "Mit der Besatzung verbinden", + "commander.web.browser_hint": "Remote Crew ist für Chrome oder Chromium (auch Edge) auf einem Desktop-PC gebaut und getestet. Dieser Browser basiert nicht auf Chromium, daher können Kopplung, Ton oder Stationsbilder versagen. Öffne diese Adresse in Chrome oder Chromium.", + "commander.web.browser_stalled": "Die Crew-Seite ist in diesem Browser nicht gestartet. Öffne diese Adresse in Chrome oder Chromium (auch Edge) oder lade die Seite neu.", "commander.web.pair_help": "Den Host-Code eingeben: 3 Ziffern, danach 3 Großbuchstaben. Kleinbuchstaben werden automatisch umgewandelt. Der Code läuft nach 5 Minuten ab. Nur ein vertrauenswürdiges Netz verwenden.", "commander.web.pair_name": "Stationsname", "commander.web.pair_name_default": "Wachoffizier", diff --git a/data/i18n/en.json b/data/i18n/en.json index e4d2f9d1..93bc4a60 100644 --- a/data/i18n/en.json +++ b/data/i18n/en.json @@ -417,6 +417,8 @@ "commander.web.pair_intro": "Observe the mission, annotate contacts and propose a target to the crew. Keep the tactical picture in view without taking the helm.", "commander.web.authority_note": "The crew retains ship control and weapon authority. A target proposal is not a weapon order.", "commander.web.pair_heading": "Join the crew", + "commander.web.browser_hint": "Remote Crew is built and tested for Chrome or Chromium (also Edge) on a desktop PC. This browser is not Chromium-based, so pairing, sound or station pictures may fail. Open this address in Chrome or Chromium.", + "commander.web.browser_stalled": "The crew page did not start in this browser. Open this address in Chrome or Chromium (also Edge), or reload the page.", "commander.web.pair_help": "Enter the host's code: 3 digits followed by 3 uppercase letters. Lowercase input is converted automatically. The code expires after 5 minutes. Use only a network you trust.", "commander.web.pair_name": "Station name", "commander.web.pair_name_default": "Watch Officer", diff --git a/tests/test_commander_pairing_browser.py b/tests/test_commander_pairing_browser.py new file mode 100644 index 00000000..3f4d2488 --- /dev/null +++ b/tests/test_commander_pairing_browser.py @@ -0,0 +1,186 @@ +"""LAN pairing in a real browser, and the hint for browsers that are not Chromium. + +Pairs the packaged page in Chromium against the real Game and a crew-mode +CommanderServer (the F9 LAN listener). A Firefox user agent must see the +browser hint and still pair; a client whose modules fail to start must not +stay silently on its loading screen. +""" + +import json +import re +import shutil +import subprocess +import time + +import pytest +from commander_web import copy_assets, index_html, inject_probe + +from src.commander import server as commander_transport +from src.commander.assets import static_assets +from src.core import config, manual +from src.core.game import Game +from test_commander_assets import ASSETS, PREFIX, Document, catalogs + +FIREFOX = "Mozilla/5.0 (X11; Linux x86_64; rv:130.0) Gecko/20100101 Firefox/130.0" + +PAIR_SCRIPT = r""" +(() => { +"use strict"; +const $ = (id) => document.getElementById(id); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +async function until(check, message, limit = 1500) { + for (let index = 0; index < limit; index++) { + if (check()) return; + await sleep(20); + } + throw new Error(message); +} +async function run() { + await until(() => !$("shell").hidden, "translations missing"); + const root = document.documentElement; + root.dataset.hintVisible = String(!$("browser-hint").hidden); + root.dataset.hintText = $("browser-hint").textContent; + $("name").value = "LAN"; + $("code").value = __CODE__; + $("pair-form").requestSubmit(); + await until(() => $("pairing").hidden && !$("lobby").hidden, "pairing did not reach the lobby: " + $("pair-error").textContent); + root.dataset.pairTest = "passed"; +} +addEventListener("load", () => { + run().catch((error) => { document.documentElement.dataset.failure = String(error?.stack || error); }); +}); +})(); +""" + + +def _chromium(): + chromium = (shutil.which("chromium") or shutil.which("chromium-browser") + or shutil.which("google-chrome")) + if not chromium: + pytest.skip("Optional pairing browser contract: no installed Chromium") + return chromium + + +def _pair(tmp_path, monkeypatch, *extra_args): + chromium = _chromium() + monkeypatch.setattr(config, "SAVE_DIR", str(tmp_path / "saves")) + en, de = catalogs() + game = Game(seed=917, start_menu=False, audio_enabled=False, language="en") + console = game.commander + console.solo = False + console.port = 0 + console._translations = { + "en": {key: value for key, value in en.items() if key.startswith(PREFIX)}, + "de": {key: value for key, value in de.items() if key.startswith(PREFIX)}, + } + console._contact_analysis_assets = {} + console._manual_pages = {lang: manual.html_page(lang) for lang in manual.LANGUAGES} + copy_assets(tmp_path, inject_probe(index_html(), "pair-test.js")) + monkeypatch.setattr(commander_transport.resources, "files", lambda _package: tmp_path) + + console.activate(game) + assert console.address is not None and console.server.solo_mode is False + console.server._http.assets["/pair-test.js"] = ( + "text/javascript; charset=utf-8", + PAIR_SCRIPT.replace("__CODE__", json.dumps(console.pairing_code)).encode("utf-8")) + process = subprocess.Popen( + [chromium, "--headless", "--no-sandbox", "--disable-gpu", + "--disable-background-networking", "--no-first-run", + "--no-default-browser-check", "--disable-dev-shm-usage", + f"--user-data-dir={tmp_path / 'pair-browser'}", "--virtual-time-budget=20000", + "--window-size=1600,900", *extra_args, "--dump-dom", + f"http://{console.address[0]}:{console.address[1]}/"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + started = time.monotonic() + try: + while process.poll() is None and time.monotonic() - started < 120: + console.pump(game) + game.update(.02) + time.sleep(.02) + stdout, stderr = process.communicate(timeout=5) + finally: + if process.poll() is None: + process.kill() + stdout, stderr = process.communicate(timeout=5) + console.stop() + game.audio.shutdown() + root = next((attrs for tag, attrs in Document(stdout).elements if tag == "html"), {}) + assert root.get("data-pair-test") == "passed", root.get( + "data-failure", stdout[-4000:] + stderr[-2000:]) + return root, en + + +def test_lan_pairing_reaches_the_lobby_in_chromium_without_a_browser_hint( + tmp_path, monkeypatch): + root, _en = _pair(tmp_path, monkeypatch) + assert root.get("data-browser") == "chromium" + assert root.get("data-hint-visible") == "false" + + +def test_firefox_sees_the_browser_hint_and_can_still_pair(tmp_path, monkeypatch): + root, en = _pair(tmp_path, monkeypatch, f"--user-agent={FIREFOX}") + assert root.get("data-browser") == "other" + assert root.get("data-hint-visible") == "true" + assert root.get("data-hint-text") == en[PREFIX + "browser_hint"] + + +def test_a_client_that_cannot_start_explains_itself(tmp_path, monkeypatch): + """Modules that fail to load leave the loading screen with a browser note.""" + chromium = _chromium() + en, de = catalogs() + translations = { + "en": {key: value for key, value in en.items() if key.startswith(PREFIX)}, + "de": {key: value for key, value in de.items() if key.startswith(PREFIX)}, + } + copy_assets(tmp_path) + (tmp_path / "js" / "main.js").write_text( + 'throw new Error("module client unsupported");\n', encoding="utf-8") + monkeypatch.setattr(commander_transport.resources, "files", lambda _package: tmp_path) + server = commander_transport.CommanderServer(translations=translations, + contact_analysis_assets={}) + server.start("127.0.0.1", 0) + try: + host, port = server.address + result = subprocess.run( + [chromium, "--headless", "--no-sandbox", "--disable-gpu", + "--disable-background-networking", "--no-first-run", + "--no-default-browser-check", "--disable-dev-shm-usage", + f"--user-data-dir={tmp_path / 'stall-browser'}", "--lang=de-DE", + "--virtual-time-budget=20000", "--dump-dom", f"http://{host}:{port}/"], + capture_output=True, text=True, timeout=90) + finally: + server.stop() + root = next((attrs for tag, attrs in Document(result.stdout).elements if tag == "html"), {}) + assert root.get("data-startup") == "stalled", result.stdout[-3000:] + result.stderr[-1500:] + note = re.search(r'

]*)>(.*?)

', result.stdout, re.S) + assert note is not None and "hidden" not in note.group(1) + # navigator.language decides the catalog; headless Chromium may ignore --lang. + assert note.group(2) in (en[PREFIX + "browser_stalled"], de[PREFIX + "browser_stalled"]) + + +def test_browser_check_ships_with_every_listener_and_runs_before_the_client(): + page = index_html() + check = '' + assert page.index(check) < page.index('