diff --git a/openpilot/starpilot/controllers/input.py b/openpilot/starpilot/controllers/input.py index 65f55348b9..ceb384b6cd 100644 --- a/openpilot/starpilot/controllers/input.py +++ b/openpilot/starpilot/controllers/input.py @@ -7,6 +7,7 @@ from itertools import islice import os from pathlib import Path import re +import secrets import stat import struct import time @@ -95,22 +96,60 @@ def _button_capable(sysfs: Path) -> bool: any(ABS_HAT0X <= axis <= ABS_HAT3Y for axis in axes) -def _inspect(path: Path) -> _Identity | None: - if not EVENT_NAME.fullmatch(path.name): +def _external(name: str) -> tuple[Path, re.Match[str]] | None: + """The sysfs device and modalias of a USB or Bluetooth event node.""" + if not EVENT_NAME.fullmatch(name): return None - sysfs = SYS_ROOT / path.name / "device" + sysfs = SYS_ROOT / name / "device" match = MODALIAS.match(_text(sysfs / "modalias")) - if match is None: + if match is None or int(match[1], 16) not in EXTERNAL_BUSES: return None + return sysfs, match + + +def _inspect(path: Path) -> _Identity | None: + external = _external(path.name) + if external is None or not _button_capable(external[0]): + return None + sysfs, match = external bus, vendor, product, _version = (int(token, 16) for token in match.groups()) - if bus not in EXTERNAL_BUSES or not _button_capable(sysfs): - return None name = _text(sysfs / "name") or "External input" uniq = _text(sysfs / "uniq") identity = f"{bus:04x}:{vendor:04x}:{product:04x}:{name.casefold()}:{uniq.casefold()}" return _Identity(path, hashlib.sha256(identity.encode()).hexdigest()[:20], name[:80], bus) +def controller_input_report() -> dict: + """Snapshot external input interfaces, including ones omitted from Attached Controllers; names are masked.""" + devices = [] + groups: dict[str, list[str]] = {} + salt = secrets.token_bytes(8) # equal names match within one report only + truncated = False + for entry in sorted(SYS_ROOT.iterdir()): + if (external := _external(entry.name)) is None: + continue + if len(devices) == MAX_CANDIDATES: + truncated = True + break + device, match = external + identity = _inspect(DEV_ROOT / entry.name) + if identity is not None: + groups.setdefault(identity.device_id, []).append(entry.name) + name = _text(device / "name") + devices.append({ + "event": entry.name, "name": f"masked-{hashlib.sha256(salt + name.encode()).hexdigest()[:8]}" if name else "", "inputId": match[0], + "properties": _text(device / "properties"), + "capabilities": {key: _text(device / "capabilities" / key) for key in ("ev", "key", "rel", "abs")}, + "discovery": "eligible" if identity else "filtered", + "eventNodePresent": (DEV_ROOT / entry.name).exists(), + }) + duplicates = {event: events for events in groups.values() if len(events) > 1 for event in events} + for row in devices: + if row["event"] in duplicates: + row.update(discovery="duplicate identity", matchingEvents=duplicates[row["event"]]) + return {"externalInputInterfaces": devices, "truncated": truncated} + + def _fresh(seconds: int, microseconds: int, now_ns: int) -> int | None: if seconds < 0 or not 0 <= microseconds < 1_000_000: return None diff --git a/openpilot/starpilot/controllers/tests/test_input.py b/openpilot/starpilot/controllers/tests/test_input.py index 297e671684..92e9763e9d 100644 --- a/openpilot/starpilot/controllers/tests/test_input.py +++ b/openpilot/starpilot/controllers/tests/test_input.py @@ -260,3 +260,41 @@ def test_device_and_scan_candidate_caps(kernel): reader.poll(NOW + source.RESCAN_NS) assert reader.devices() == [] reader.close() + + +def test_report_includes_filtered_and_duplicate_external_interfaces(monkeypatch, tmp_path): + kernel = Kernel(monkeypatch, tmp_path) + kernel.device(1, bus=5) + kernel.device(2, bus=5) + kernel.device(3, bus=5, keys=(115,), rel=(0, 1)) + kernel.device(4, bus=5, name="Media", keys=(115,)) + kernel.device(5, bus=1) + report = source.controller_input_report() + rows = report["externalInputInterfaces"] + assert [row["discovery"] for row in rows] == ["duplicate identity", "duplicate identity", "filtered", "eligible"] + assert rows[0]["matchingEvents"] == ["event1", "event2"] + assert rows[2]["capabilities"]["rel"] == "3" + assert not report["truncated"] + assert not kernel.path_by_fd + + +def test_report_masks_names(monkeypatch, tmp_path): + kernel = Kernel(monkeypatch, tmp_path) + kernel.device(1, bus=5, name="Danny's Pad") + kernel.device(2, bus=5, name="Danny's Pad", uniq="02") + kernel.device(3, bus=5, name="Media", keys=(115,)) + report = source.controller_input_report() + names = [row["name"] for row in report["externalInputInterfaces"]] + assert all(name.startswith("masked-") for name in names) + assert names[0] == names[1] != names[2] + assert "Danny" not in str(report) and "Media" not in str(report) + assert source.controller_input_report()["externalInputInterfaces"][0]["name"] != names[0] + + +def test_report_is_capped(monkeypatch, tmp_path): + kernel = Kernel(monkeypatch, tmp_path) + for index in range(source.MAX_CANDIDATES + 1): + kernel.device(index, bus=5, uniq=str(index)) + report = source.controller_input_report() + assert len(report["externalInputInterfaces"]) == source.MAX_CANDIDATES + assert report["truncated"] diff --git a/openpilot/starpilot/galaxy/bluetooth_send.py b/openpilot/starpilot/galaxy/bluetooth_send.py new file mode 100644 index 0000000000..8288e6a5a9 --- /dev/null +++ b/openpilot/starpilot/galaxy/bluetooth_send.py @@ -0,0 +1,43 @@ +"""Send the controller input report to the developer's Discord forum, beside StarPort logs.""" + +import json + +from openpilot.starpilot.controllers.input import controller_input_report +from openpilot.starpilot.galaxy import starport_send +from openpilot.starpilot.system.starport import identity as identity_store + +TITLE = "Bluetooth Log" +WEBHOOK_OVERRIDE_PATH = identity_store.DATA_DIR / "bluetooth_webhook_url" +# Obfuscation only; device-local configuration overrides this built-in webhook. +_WEBHOOK_KEY = b"bluetooth-log" +_WEBHOOK_DATA = "".join(("ChgBFQdVQFsMRB8MCBAIWwYbAkAVGERDGAIABBoKHxxARV0aWFdTU11GVU1aVkZcFFhdXk0PFAMMNlgjG1", + "RdDiMjOSVURjZaPTxjNStXJB0NExAhDgZZWi0cElEuRTUTHBotWmwqVyE0LkwjWVkoAQ9LVAIeJAFYSA==")) + + +def webhook_url() -> str: + return starport_send.webhook_url(WEBHOOK_OVERRIDE_PATH, _WEBHOOK_KEY, _WEBHOOK_DATA) + + +def summary() -> dict: + from openpilot.starpilot.system.starport.bugsink_transport import device_metadata + result = device_metadata() + try: + result["car_fingerprint"] = starport_send.car_fingerprint() + except Exception as error: + result["car_fingerprint_error"] = str(error) + return result + + +def report(**_) -> tuple[str, bytes]: + return "bluetooth-log.json", json.dumps(controller_input_report(), indent=2).encode() + + +def send(data: bytes, name: str, note: str, details: dict, *, discord: str, url: str | None = None, post=None, thread_dir=None) -> str | None: + return starport_send.send(data, name, note, details, url=webhook_url() if url is None else url, post=post, thread_dir=thread_dir, + discord=discord, heading=TITLE, fields=(), content_type="application/json", + title=f"{TITLE} {starport_send.thread_title(details)}"[:100]) + + +def sender() -> starport_send.StarPortLogSender: + return starport_send.StarPortLogSender(report, sender=send, summary=summary, url=webhook_url, + busy="The Bluetooth Log is already being sent.") diff --git a/openpilot/starpilot/galaxy/server.py b/openpilot/starpilot/galaxy/server.py index a13753b455..9abb8a082a 100644 --- a/openpilot/starpilot/galaxy/server.py +++ b/openpilot/starpilot/galaxy/server.py @@ -99,7 +99,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe sounds=None, software_operations=None, drive_stats=None, layout_preview_socket=None, controllers_socket=None, remote_pairing=None, parked=None, camera_snapshot=None, clock=time.monotonic, starport_setup=None, starport_client=None, navigation=None, offline_maps=None, drive_state=None, cloud_provider=None, cloud_offroad=None, projection_layout=None, - local_access=None, tmux_live=None, starport_logs=None, starport_log_sender=None, hotspot=None, toyota_tools=None, + local_access=None, tmux_live=None, starport_logs=None, starport_log_sender=None, bluetooth_log_sender=None, hotspot=None, toyota_tools=None, replay_client=None, replay_root=None, spotify_setup=None, companion=None, phone_location=None, reverse_proxy=None, local_hostnames=None, sound_preview=None): from openpilot.starpilot.galaxy.local_hostnames import LocalHostnames @@ -165,6 +165,16 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe source = starport_logs() starport_log_sender_source = StarPortLogSender(source.bundle, summary=lambda: device_summary(source.directory)) return starport_log_sender_source + bluetooth_log_sender_source = bluetooth_log_sender + bluetooth_log_sender_lock = threading.Lock() + + def bluetooth_log_sender(): + nonlocal bluetooth_log_sender_source + with bluetooth_log_sender_lock: + if bluetooth_log_sender_source is None: + from openpilot.starpilot.galaxy.bluetooth_send import sender + bluetooth_log_sender_source = sender() + return bluetooth_log_sender_source software_source = software software_operations_source = software_operations software_lock = threading.Lock() @@ -1013,37 +1023,18 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe elif path == '/api/starport/logs/send': if self.require_session(): self.json(200, starport_log_sender().status()) - elif path == '/api/starport/logs' or path.startswith('/api/starport/logs/'): + elif path == '/api/starport/logs': if not self.require_session(): return - from openpilot.starpilot.galaxy.starport_logs import LogMissing, LogsUnavailable - name = unquote(path.removeprefix('/api/starport/logs/file/')) if path.startswith('/api/starport/logs/file/') else None - if name is not None and not re.fullmatch(r'[\w.-]{1,128}', name): - self.json(400, {'error': 'Invalid log name'}) - return - if path not in ('/api/starport/logs', '/api/starport/logs/bundle') and name is None: - self.json(404, {'error': 'Not found'}) - return + from openpilot.starpilot.galaxy.starport_logs import LogsUnavailable try: - if path == '/api/starport/logs': - result = starport_logs().list() - elif name is None: - result = starport_logs().bundle() - else: - result = starport_logs().file(name) - except LogMissing: - self.json(404, {'error': 'That log is no longer kept; refresh the list'}) + result = starport_logs().list() except LogsUnavailable: self.json(503, {'error': 'Android Auto logs are unavailable'}) else: # The session can be revoked while logs are read; check again right before sending them. - if not self.require_session(): - return - if path == '/api/starport/logs': + if self.require_session(): self.json(200, result) - else: - filename, body = result - self.attachment(filename, body, 'application/zip' if filename.endswith('.zip') else 'text/plain; charset=utf-8') elif path.startswith('/api/navigation/map/tiles/'): if not self.require_session(): return @@ -1233,6 +1224,9 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe self.json(200, {'valid': True}) else: self.json(410, {'valid': False}) + elif path == '/api/controllers/log/send': + if self.require_session(): + self.json(200, bluetooth_log_sender().status()) elif path == '/api/controllers/status': if not self.require_session(): return @@ -1743,7 +1737,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe '/api/galaxy/pair', '/api/galaxy/unpair', '/api/galaxy/device-name', '/api/galaxy/hotspot', '/api/galaxy/networks', '/api/cameras/snapshot', '/api/cameras/white-balance', '/api/starport/layout', '/api/starport/enable', '/api/starport/control', '/api/starport/pairing', - '/api/starport/logs/send', + '/api/starport/logs/send', '/api/controllers/log/send', '/api/starport/pairing/response', '/api/starport/pairing/cancel', '/api/starport/pairing/select', '/api/spotify/enable', '/api/spotify/key', '/api/spotify/preferences', '/api/spotify/control', '/api/spotify/maintenance', '/api/ui/layout', '/api/ui/layout/preview', '/api/favorites/slots', @@ -2522,9 +2516,9 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe else: self.json(401, {'error': 'Sign in to Galaxy'}) return - if path == '/api/starport/logs/send': - if type(payload) is not dict or set(payload) not in ({'message'}, {'message', 'discord'}): - self.json(400, {'error': 'Invalid StarPort log send request'}) + if path in ('/api/starport/logs/send', '/api/controllers/log/send'): + if type(payload) is not dict or set(payload) != {'message', 'discord'}: + self.json(400, {'error': 'Invalid log send request'}) return identity = self.settings_session() if identity is None: @@ -2532,7 +2526,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe return from openpilot.starpilot.galaxy.starport_send import SendBusy, SendRejected try: - result = starport_log_sender().start(payload['message'], payload.get('discord', '')) + job = starport_log_sender() if path == '/api/starport/logs/send' else bluetooth_log_sender() + result = job.start(payload['message'], payload['discord']) except SendRejected as error: self.json(400, {'error': str(error)}) except SendBusy as error: diff --git a/openpilot/starpilot/galaxy/starport_logs.py b/openpilot/starpilot/galaxy/starport_logs.py index eab7fc67e1..9f534c4ee2 100644 --- a/openpilot/starpilot/galaxy/starport_logs.py +++ b/openpilot/starpilot/galaxy/starport_logs.py @@ -1,8 +1,6 @@ """Read-only access to the Android Auto logs under /data/starport/logs, for Logs & Diagnostics. -Lists the kept session logs with a one-line summary each, and serves one log or the shareable -bundle (``compat_report.bundle``: every session with its report, the settings without Bluetooth -addresses, and the renderer logs). Only names the log directory itself lists are served. +Lists the kept session logs with a one-line summary each, and builds the bundle that is sent to Discord. """ from __future__ import annotations @@ -14,17 +12,10 @@ from pathlib import Path from openpilot.starpilot.system.starport import compat_report from openpilot.starpilot.system.starport import identity as identity_store -MAX_FILE_BYTES = 8 << 20 # a session log is normally well under 1 MiB; the renderer logs rotate at 256 KiB - - class LogsUnavailable(Exception): pass -class LogMissing(Exception): - pass - - def _car(report: dict) -> str: car = report.get("car") or {} make = car.get("car_make") or car.get("head_unit_make") or "" @@ -60,17 +51,6 @@ class StarPortLogs: raise LogsUnavailable from None return {"schemaVersion": 1, "sessions": sessions, "others": others} - def file(self, name: str) -> tuple[str, bytes]: - path = next((path for path in self._files() if path.name == name), None) - if path is None or path.is_symlink(): - raise LogMissing - try: - return path.name, compat_report.read_log(path, MAX_FILE_BYTES) - except FileNotFoundError: - raise LogMissing from None - except OSError: - raise LogsUnavailable from None - def bundle(self, now: datetime | None = None, *, system_snapshot: bool = True) -> tuple[str, bytes]: try: data = compat_report.bundle(self.directory, self.config_path, **({} if system_snapshot else {"snapshot": None})) diff --git a/openpilot/starpilot/galaxy/starport_send.py b/openpilot/starpilot/galaxy/starport_send.py index 63d470a736..1f599d5001 100644 --- a/openpilot/starpilot/galaxy/starport_send.py +++ b/openpilot/starpilot/galaxy/starport_send.py @@ -26,6 +26,7 @@ _WEBHOOK_DATA = "".join(("GwAVAgNVXVtJBRwEHAEQTxEfAl0VXQVAEBYRHA4dGxxdRRhaWlJLRE DISCORD_FILE_LIMIT = 10 * 1024 * 1024 - 64 * 1024 # 10 MiB attachment limit, with room for the form fields THREAD_CACHE_WARNING = "The forum thread could not be remembered on this device. The next upload may create another post." CONTROL = re.compile(r"[\x00-\x1f\x7f]+") +STARPORT_FIELDS = (("Head unit", "head_unit"), ("Setup", "setup"), ("Handshake", "handshake")) class SendRejected(Exception): @@ -41,17 +42,17 @@ def official_install() -> bool: return is_official_repo(device_metadata().get("repo")) -def webhook_url(override_path: Path = WEBHOOK_OVERRIDE_PATH) -> str: +def webhook_url(override_path: Path = WEBHOOK_OVERRIDE_PATH, key: bytes = _WEBHOOK_KEY, encoded: str = _WEBHOOK_DATA) -> str: try: override = override_path.read_text().strip() except (OSError, UnicodeError): override = "" if override: return override - if not _WEBHOOK_DATA: + if not encoded: return "" - data = base64.b64decode(_WEBHOOK_DATA) - return bytes(byte ^ _WEBHOOK_KEY[index % len(_WEBHOOK_KEY)] for index, byte in enumerate(data)).decode() + data = base64.b64decode(encoded) + return bytes(byte ^ key[index % len(key)] for index, byte in enumerate(data)).decode() def clean_message(value) -> str: @@ -66,16 +67,18 @@ def clean_message(value) -> str: def clean_discord(value) -> str: - """An optional Discord username for a follow-up, without the leading @; "" when none was given.""" + """The required Discord username for a follow-up, without the leading @.""" if not isinstance(value, str): raise SendRejected("The Discord username must be text.") handle = value.strip().removeprefix("@") - if handle and not DISCORD_HANDLE.fullmatch(handle): + if not handle: + raise SendRejected("Add your Discord username so we can follow up.") + if not DISCORD_HANDLE.fullmatch(handle): raise SendRejected("That doesn't look like a Discord username.") return handle -def _car_fingerprint() -> str: +def car_fingerprint() -> str: from openpilot.common.params import Params from openpilot.starpilot.saved_source import read_saved raw, readable = read_saved(Params(), "CarParamsPersistent", 1 << 20) @@ -128,7 +131,7 @@ def _handshake(log_dir: Path | None, logs_to_check: int = 3) -> str: def device_summary(log_dir: Path | None = None) -> dict: from openpilot.starpilot.system.starport.bugsink_transport import device_metadata summary = device_metadata() - for key, read in (("car_fingerprint", _car_fingerprint), ("head_unit", lambda: _head_unit(log_dir)), ("setup", lambda: _setup(log_dir)), + for key, read in (("car_fingerprint", car_fingerprint), ("head_unit", lambda: _head_unit(log_dir)), ("setup", lambda: _setup(log_dir)), ("handshake", lambda: _handshake(log_dir))): try: summary[key] = read() @@ -163,25 +166,24 @@ def _save_thread_id(path: Path, key: str, thread_id: str) -> None: def send(data: bytes, name: str, note: str, summary: dict, url: str | None = None, post=None, - thread_dir: Path | None = None, discord: str = "") -> str | None: + thread_dir: Path | None = None, *, discord: str, heading: str = "StarPort logs", fields=STARPORT_FIELDS, + content_type: str = "application/zip", title: str | None = None) -> str | None: """Post the zip; return a cache warning after success, or raise SendRejected on an upload failure.""" url = webhook_url() if url is None else url if not url: - raise SendRejected("Sending isn't set up on this build. Use Download all logs and send the file instead.") + raise SendRejected("Sending isn't set up on this build.") if len(data) > DISCORD_FILE_LIMIT: - raise SendRejected(f"The logs are {len(data) / 1e6:.1f} MB, over Discord's 10 MB limit. Use Download all logs instead.") + raise SendRejected(f"The logs are {len(data) / 1e6:.1f} MB, over Discord's 10 MB limit.") if post is None: import requests post = requests.post dongle_id = summary.get("device_id") or "device" - lines = [f"**StarPort logs from {device_tag(summary)}**", + lines = [f"**{heading} from {device_tag(summary)}**", f"Car: {summary.get('car_fingerprint') or 'unknown'}", - f"Head unit: {summary.get('head_unit') or 'unknown'}", - f"Setup: {summary.get('setup') or 'unknown'}", - f"Handshake: {summary.get('handshake') or 'unknown'}", + *(f"{label}: {summary.get(key) or 'unknown'}" for label, key in fields), f"Repo {summary.get('repo', '?')} · Branch {summary.get('branch', '?')} @ {str(summary.get('commit', '?'))[:10]}", f"Note: {note.strip() or '(none)'}", - f"Follow-up: Discord `{discord}`" if discord else "Follow-up: not requested"] + f"Follow-up: Discord `{discord}`"] payload = {"content": "\n".join(lines)[:1900], "username": "StarPilot diagnostics", "allowed_mentions": {"parse": []}} parts = urlsplit(url) @@ -209,13 +211,13 @@ def send(data: bytes, name: str, note: str, summary: dict, url: str | None = Non query["thread_id"] = cached_id elif not explicit_thread: query.pop("thread_id", None) - payload["thread_name"] = thread_title(summary) + payload["thread_name"] = title or thread_title(summary) post_url = urlunsplit(parts._replace(query=urlencode(query))) try: - response = post(post_url, data={"payload_json": json.dumps(payload)}, files={"files[0]": (name, data, "application/zip")}, timeout=120) + response = post(post_url, data={"payload_json": json.dumps(payload)}, files={"files[0]": (name, data, content_type)}, timeout=120) except Exception as error: - raise SendRejected(f"Could not send the logs: {type(error).__name__}. Check the internet connection, or use Download all logs.") from error + raise SendRejected(f"Could not send the logs: {type(error).__name__}. Check the internet connection.") from error # Unknown Channel means the cached thread was deleted (Discord answers 400 for webhooks, 404 elsewhere). # Unknown Webhook does not. @@ -231,7 +233,7 @@ def send(data: bytes, name: str, note: str, summary: dict, url: str | None = Non if response.status_code not in (200, 204): reason = str(_response_json(response).get("message") or "")[:120] detail = f"HTTP {response.status_code}{f': {reason}' if reason else ''}" - raise SendRejected(f"Discord refused the logs ({detail}). Use Download all logs instead.") + raise SendRejected(f"Discord refused the logs ({detail}).") if not explicit_thread and not cached_id: new_thread_id = _response_json(response).get("channel_id") @@ -249,8 +251,9 @@ class StarPortLogSender: def __init__(self, bundle: Callable[..., tuple[str, bytes]], *, sender: Callable[..., str | None] = send, summary: Callable[[], dict] = device_summary, url: Callable[[], str] = webhook_url, - official: Callable[[], bool] = official_install): + official: Callable[[], bool] = official_install, busy: str = "StarPort logs are already being sent."): self._bundle, self._sender, self._summary, self._url, self._official = bundle, sender, summary, url, official + self._busy = busy self._lock = threading.Lock() self._thread: threading.Thread | None = None self._state = {"state": "idle", "message": ""} @@ -262,11 +265,11 @@ class StarPortLogSender: self._fork = not self._official() return {**self._state, "available": bool(self._url()), "fork": self._fork, "messageLimit": MESSAGE_LIMIT} - def start(self, message, discord="") -> dict: + def start(self, message, discord) -> dict: note, handle = clean_message(message), clean_discord(discord) with self._lock: if self._thread is not None and self._thread.is_alive(): - raise SendBusy("StarPort logs are already being sent.") + raise SendBusy(self._busy) self._state = {"state": "sending", "message": "Collecting logs"} self._thread = threading.Thread(target=self._run, args=(note, handle), name="starport_log_send", daemon=True) self._thread.start() @@ -291,4 +294,4 @@ class StarPortLogSender: except SendRejected as error: self._set(state="failed", message=str(error)[:400]) except Exception as error: - self._set(state="failed", message=f"Could not send the logs: {type(error).__name__}. Use Download all logs instead.") + self._set(state="failed", message=f"Could not send the logs: {type(error).__name__}.") diff --git a/openpilot/starpilot/galaxy/tests/browser/ui-consistency.cjs b/openpilot/starpilot/galaxy/tests/browser/ui-consistency.cjs index e912463ec1..31ecfc2673 100644 --- a/openpilot/starpilot/galaxy/tests/browser/ui-consistency.cjs +++ b/openpilot/starpilot/galaxy/tests/browser/ui-consistency.cjs @@ -86,13 +86,10 @@ const { resolve } = require('node:path') assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, 'Android Auto logs fit a phone viewport') const phoneCards = await page.locator('.gx-starport-log').evaluateAll(cards => cards.map(card => { const row = card.getBoundingClientRect(), body = card.querySelector('.gx-starport-log__body').getBoundingClientRect() - const download = card.querySelector('.gx-starport-log__download').getBoundingClientRect() - return { leftInset: body.left - row.left, rightInset: row.right - download.right, width: download.width, height: download.height } + return { leftInset: body.left - row.left } })) - assert.ok(phoneCards.every(card => card.leftInset >= 11 && card.rightInset >= 11), 'log text and downloads are padded inside cards') - assert.ok(phoneCards.every(card => card.width === 44 && card.height === 44), 'individual downloads remain compact touch targets') - assert.deepEqual(await page.locator('.gx-starport-log__download').evaluateAll(links => links.map(link => link.getAttribute('download'))), - ['session-000003.jsonl', 'session-000002.jsonl', 'car_ui.log']) + assert.ok(phoneCards.every(card => card.leftInset >= 11), 'log text is padded inside cards') + assert.equal(await page.locator('.gx-starport-logs a[download]').count(), 0, 'StarPort logs are sent, not downloaded') await page.setViewportSize({ width: 1280, height: 900 }) await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))) const desktop = await page.locator('.gx-starport-logs').evaluate(section => { diff --git a/openpilot/starpilot/galaxy/tests/discord_fakes.py b/openpilot/starpilot/galaxy/tests/discord_fakes.py new file mode 100644 index 0000000000..0ecc095773 --- /dev/null +++ b/openpilot/starpilot/galaxy/tests/discord_fakes.py @@ -0,0 +1,24 @@ +"""Fake Discord webhook responses shared by the log send tests.""" + +import json + +URL = "https://discord.example/api/webhooks/1/token" +SUMMARY = {"device_id": "0123456789abcdef", "car_fingerprint": "HONDA_CIVIC_2022", "head_unit": "Honda Display Audio", + "branch": "Dom", "commit": "abcdef1234567890"} + + +class Response: + def __init__(self, status_code=200, body=None): + self.status_code, self.body = status_code, body if body is not None else {"channel_id": "555"} + + def json(self): + return self.body + + +class Poster: + def __init__(self, *responses): + self.responses, self.calls = list(responses), [] + + def __call__(self, url, data, files, timeout): + self.calls.append({"url": url, "payload": json.loads(data["payload_json"]), "files": files}) + return self.responses.pop(0) diff --git a/openpilot/starpilot/galaxy/tests/test_bluetooth_send.py b/openpilot/starpilot/galaxy/tests/test_bluetooth_send.py new file mode 100644 index 0000000000..3dd0fe003a --- /dev/null +++ b/openpilot/starpilot/galaxy/tests/test_bluetooth_send.py @@ -0,0 +1,111 @@ +"""Bluetooth Log: the controller report sent to the developer's Discord forum and its routes.""" + +import http.client +import json +import tempfile +import threading +import unittest +from pathlib import Path +from unittest import mock + +from openpilot.starpilot.galaxy import bluetooth_send +from openpilot.starpilot.galaxy.access import GalaxyAccessOwner +from openpilot.starpilot.galaxy.server import make_server +from openpilot.starpilot.galaxy.starport_send import SendBusy, SendRejected +from openpilot.starpilot.galaxy.tests.discord_fakes import SUMMARY, URL, Poster, Response + + +class BluetoothSendTest(unittest.TestCase): + def test_posts_the_report_as_a_bluetooth_log_thread(self): + post = Poster(Response(body={"channel_id": "777"})) + with tempfile.TemporaryDirectory() as directory: + self.assertIsNone(bluetooth_send.send(b"{}", "bluetooth-log.json", "Pad not found", SUMMARY, url=URL, post=post, + thread_dir=Path(directory), discord="starfan_42")) + call = post.calls[0] + content = call["payload"]["content"] + self.assertTrue(content.startswith("**Bluetooth Log from ")) + self.assertIn("Car: HONDA_CIVIC_2022", content) + self.assertIn("Follow-up: Discord `starfan_42`", content) + self.assertNotIn("Head unit", content) + self.assertTrue(call["payload"]["thread_name"].startswith("Bluetooth Log HONDA_CIVIC_2022 ")) + self.assertEqual(call["files"]["files[0]"], ("bluetooth-log.json", b"{}", "application/json")) + + def test_report_is_json(self): + with mock.patch.object(bluetooth_send, "controller_input_report", return_value={"externalInputInterfaces": []}): + name, data = bluetooth_send.report(system_snapshot=False) + self.assertEqual((name, json.loads(data)), ("bluetooth-log.json", {"externalInputInterfaces": []})) + + def test_unset_webhook_refuses_and_override_wins(self): + with tempfile.TemporaryDirectory() as directory: + override = Path(directory) / "bluetooth_webhook_url" + with mock.patch.object(bluetooth_send, "WEBHOOK_OVERRIDE_PATH", override), mock.patch.object(bluetooth_send, "_WEBHOOK_DATA", ""): + self.assertEqual(bluetooth_send.webhook_url(), "") + with self.assertRaisesRegex(SendRejected, "isn't set up"): + bluetooth_send.send(b"{}", "bluetooth-log.json", "hi", SUMMARY, post=Poster(), discord="starfan_42") + override.write_text(URL + "\n") + self.assertEqual(bluetooth_send.webhook_url(), URL) + + +class BluetoothSendHTTPTest(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.owner = GalaxyAccessOwner(Path(temporary.name) / "access") + self.job = mock.Mock() + self.job.status.return_value = {"state": "idle", "message": "", "available": True, "messageLimit": 60} + self.job.start.return_value = {"state": "sending", "message": "Collecting logs", "available": True, "messageLimit": 60} + self.starport = mock.Mock() + self.server = make_server(port=0, owner=self.owner, bluetooth_log_sender=self.job, starport_log_sender=self.starport) + self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True) + self.thread.start() + self.addCleanup(self.close_server) + self.assertTrue(self.owner.configure("password123", lambda: True)) + + def close_server(self): + self.server.shutdown() + self.thread.join(timeout=2) + self.server.server_close() + + def request(self, path, *, method="GET", body=None, headers=None): + connection = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=2) + try: + origin = {"Origin": f"http://127.0.0.1:{self.server.server_port}"} if method == "POST" else {} + connection.request(method, path, body=body, headers={"Forwarded": "for=203.0.113.8", **origin, **(headers or {})}) + response = connection.getresponse() + return response.status, response.read(), dict(response.getheaders()) + finally: + connection.close() + + def post(self, body, cookie=None): + headers = {"Content-Type": "application/json", **({"Cookie": cookie} if cookie else {})} + return self.request("/api/controllers/log/send", method="POST", body=json.dumps(body), headers=headers) + + def login(self): + status, _, headers = self.request("/api/auth/login", method="POST", body=json.dumps({"password": "password123"}), + headers={"Content-Type": "application/json"}) + self.assertEqual(status, 200) + return headers["Set-Cookie"].split(";", 1)[0] + + def test_requires_a_session(self): + self.assertEqual(self.request("/api/controllers/log/send")[0], 401) + self.assertEqual(self.post({"message": "hi"})[0], 401) + self.job.start.assert_not_called() + + def test_status_start_and_rejections(self): + cookie = self.login() + status, body, _ = self.request("/api/controllers/log/send", headers={"Cookie": cookie}) + self.assertEqual((status, json.loads(body)["state"]), (200, "idle")) + status, body, _ = self.post({"message": "Pad not found", "discord": "starfan_42"}, cookie) + self.assertEqual((status, json.loads(body)["state"]), (202, "sending")) + self.job.start.assert_called_once_with("Pad not found", "starfan_42") + self.starport.start.assert_not_called() + self.assertEqual(self.post({"message": "hi"}, cookie)[0], 400) + self.assertEqual(self.post({"message": "hi", "discord": "starfan_42", "extra": 1}, cookie)[0], 400) + self.job.start.side_effect = SendRejected("Keep the message to 60 characters.") + self.assertEqual(self.post({"message": "x" * 61, "discord": "starfan_42"}, cookie)[0], 400) + self.job.start.side_effect = SendBusy("The Bluetooth Log is already being sent.") + self.assertEqual(self.post({"message": "hi", "discord": "starfan_42"}, cookie)[0], 409) + + +if __name__ == "__main__": + unittest.main() diff --git a/openpilot/starpilot/galaxy/tests/test_starport_logs.mjs b/openpilot/starpilot/galaxy/tests/test_starport_logs.mjs index d68e42a224..c7f208a00f 100644 --- a/openpilot/starpilot/galaxy/tests/test_starport_logs.mjs +++ b/openpilot/starpilot/galaxy/tests/test_starport_logs.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict" -import { StarPortLogsFeed, BUNDLE_URL, fileUrl, outcomeLabel } from "../web/js/starport-logs.js" +import { StarPortLogsFeed, outcomeLabel } from "../web/js/starport-logs.js" const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() } function fixture() { @@ -14,9 +14,6 @@ function fixture() { return { feed, requests, states, reply, get unauthorized() { return unauthorized } } } -assert.equal(BUNDLE_URL, "./api/starport/logs/bundle") -assert.equal(fileUrl("session-000002-20261005-094551.jsonl"), "./api/starport/logs/file/session-000002-20261005-094551.jsonl") -assert.equal(fileUrl("a b/c"), "./api/starport/logs/file/a%20b%2Fc") assert.equal(outcomeLabel("failed: RFCOMM: timed out"), "Failed: RFCOMM: timed out") assert.equal(outcomeLabel(""), "Unknown") diff --git a/openpilot/starpilot/galaxy/tests/test_starport_logs.py b/openpilot/starpilot/galaxy/tests/test_starport_logs.py index c6f19a3199..0d3b621f16 100644 --- a/openpilot/starpilot/galaxy/tests/test_starport_logs.py +++ b/openpilot/starpilot/galaxy/tests/test_starport_logs.py @@ -1,4 +1,4 @@ -"""Android Auto logs in Logs & Diagnostics: the read-only reader and its authenticated download routes.""" +"""Android Auto logs in Logs & Diagnostics: the read-only reader and its authenticated list route.""" import http.client import io @@ -11,9 +11,8 @@ from unittest import mock import zipfile from openpilot.starpilot.galaxy.access import GalaxyAccessOwner -from openpilot.starpilot.galaxy.starport_logs import StarPortLogs, LogMissing +from openpilot.starpilot.galaxy.starport_logs import StarPortLogs from openpilot.starpilot.galaxy.server import make_server -from openpilot.starpilot.system.starport import system_snapshot SESSION = "\n".join(json.dumps(event) for event in ( {"t": "2026-10-05T16:45:51.000+00:00", "event": "session_start", "receiver": "Honda CIVIC", "trigger": "auto"}, @@ -51,14 +50,8 @@ class StarPortLogsReaderTest(unittest.TestCase): self.assertEqual(session["trigger"], "auto") self.assertEqual([item["name"] for item in listing["others"]], ["car_ui.log"]) - def test_serves_only_listed_logs(self): - self.assertEqual(self.reader.file("car_ui.log"), ("car_ui.log", b"car view pipeline: nv12, async readback\n")) - for name in ("notes.txt", "../config.json", "missing.jsonl", ""): - with self.assertRaises(LogMissing): - self.reader.file(name) + def test_symlinked_logs_are_not_listed(self): (self.logs / "render_profile.txt").symlink_to(self.config) - with self.assertRaises(LogMissing): - self.reader.file("render_profile.txt") self.assertNotIn("render_profile.txt", [item["name"] for item in self.reader.list()["others"]]) def test_bundle_is_a_zip_without_bluetooth_addresses(self): @@ -98,9 +91,7 @@ class StarPortLogsHTTPTest(unittest.TestCase): self.server.server_close() def request(self, path, *, method="GET", body=None, headers=None): - # Bundles include the real bounded system report; allow cleanup and ZIP/HTTP delivery. - timeout = system_snapshot.DEADLINE_SECONDS + 3 if path == "/api/starport/logs/bundle" else 2 - connection = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=timeout) + connection = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=2) try: connection.request(method, path, body=body, headers={"Forwarded": "for=203.0.113.8", **(headers or {})}) response = connection.getresponse() @@ -116,14 +107,11 @@ class StarPortLogsHTTPTest(unittest.TestCase): def test_requires_a_session_before_reading_anything(self): self.assertTrue(self.owner.configure("password123", lambda: True)) - with mock.patch.object(self.reader, "list", wraps=self.reader.list) as listing, \ - mock.patch.object(self.reader, "bundle", wraps=self.reader.bundle) as bundle: - for path in ("/api/starport/logs", "/api/starport/logs/bundle", "/api/starport/logs/file/car_ui.log"): - self.assertEqual(self.request(path)[0], 401) + with mock.patch.object(self.reader, "list", wraps=self.reader.list) as listing: + self.assertEqual(self.request("/api/starport/logs")[0], 401) listing.assert_not_called() - bundle.assert_not_called() - def test_list_file_and_bundle_downloads(self): + def test_list(self): self.assertTrue(self.owner.configure("password123", lambda: True)) cookie = {"Cookie": self.login()} status, body, headers = self.request("/api/starport/logs", headers=cookie) @@ -131,24 +119,13 @@ class StarPortLogsHTTPTest(unittest.TestCase): self.assertEqual(headers["Cache-Control"], "no-store") self.assertEqual(len(json.loads(body)["sessions"]), 2) - status, body, headers = self.request("/api/starport/logs/file/session-000001-20261004-221339.jsonl", headers=cookie) - self.assertEqual(status, 200) - self.assertEqual(headers["Content-Disposition"], 'attachment; filename="session-000001-20261004-221339.jsonl"') - self.assertEqual(body.decode(), SESSION) - - status, body, headers = self.request("/api/starport/logs/bundle", headers=cookie) - self.assertEqual(status, 200) - self.assertEqual(headers["Content-Type"], "application/zip") - self.assertRegex(headers["Content-Disposition"], r'^attachment; filename="starpilot-starport-logs-\d{8}-\d{6}\.zip"$') - with zipfile.ZipFile(io.BytesIO(body)) as archive: - self.assertIn("REPORT.txt", archive.namelist()) - - def test_unknown_and_invalid_names(self): + def test_logs_cannot_be_downloaded(self): self.assertTrue(self.owner.configure("password123", lambda: True)) cookie = {"Cookie": self.login()} - self.assertEqual(self.request("/api/starport/logs/file/notes.txt", headers=cookie)[0], 404) - self.assertEqual(self.request("/api/starport/logs/file/..%2Fconfig.json", headers=cookie)[0], 400) - self.assertEqual(self.request("/api/starport/logs/other", headers=cookie)[0], 404) + with mock.patch.object(self.reader, "bundle") as bundle: + for path in ("/api/starport/logs/bundle", "/api/starport/logs/file/car_ui.log"): + self.assertEqual(self.request(path, headers=cookie)[0], 404) + bundle.assert_not_called() if __name__ == "__main__": diff --git a/openpilot/starpilot/galaxy/tests/test_starport_send.mjs b/openpilot/starpilot/galaxy/tests/test_starport_send.mjs index b4db5dab1b..42d88ab4e4 100644 --- a/openpilot/starpilot/galaxy/tests/test_starport_send.mjs +++ b/openpilot/starpilot/galaxy/tests/test_starport_send.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict" -import { StarPortLogSend, SEND_URL, MESSAGE_LIMIT } from "../web/js/starport-logs.js" +import { StarPortLogSend, SEND_URL, BLUETOOTH_SEND_URL, MESSAGE_LIMIT } from "../web/js/starport-logs.js" const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() } function fixture() { @@ -24,10 +24,10 @@ normal.client.start() assert.equal(normal.requests[0].url, SEND_URL) await normal.reply(0, { state: "idle", message: "", available: true }) assert.equal(normal.states.at(-1).state, "idle") -const sending = normal.client.send(" Black screen ") +const sending = normal.client.send(" Black screen ", "starfan_42") assert.equal(normal.states.at(-1).state, "sending") assert.equal(normal.requests[1].options.method, "POST") -assert.deepEqual(JSON.parse(normal.requests[1].options.body), { message: "Black screen" }) +assert.deepEqual(JSON.parse(normal.requests[1].options.body), { message: "Black screen", discord: "starfan_42" }) await normal.reply(1, { state: "sending", message: "Collecting logs" }, 202) assert.equal(await sending, true) assert.equal(normal.timers.length, 1) @@ -40,13 +40,16 @@ assert.equal(normal.timers.length, 1) const limited = fixture() limited.client.start() await limited.reply(0, { state: "idle" }) -assert.equal(await limited.client.send("x".repeat(61)), false) +assert.equal(await limited.client.send("x".repeat(61), "starfan_42"), false) assert.equal(limited.requests.length, 1) assert.match(limited.states.at(-1).error, /60 characters/) -assert.equal(await limited.client.send(" "), false) +assert.equal(await limited.client.send(" ", "starfan_42"), false) assert.equal(limited.requests.length, 1) assert.match(limited.states.at(-1).error, /short note/) -const busy = limited.client.send("hi") +assert.equal(await limited.client.send("hi", " @ "), false) +assert.equal(limited.requests.length, 1) +assert.match(limited.states.at(-1).error, /Discord username/) +const busy = limited.client.send("hi", "starfan_42") await limited.reply(1, { error: "StarPort logs are already being sent." }, 409) assert.equal(await busy, false) assert.equal(limited.states.at(-1).error, "StarPort logs are already being sent.") @@ -56,7 +59,7 @@ const signedOut = fixture() signedOut.client.start() await signedOut.reply(0, {}, 401) assert.equal(signedOut.unauthorized, 1) -assert.equal(await signedOut.client.send("hi"), false) +assert.equal(await signedOut.client.send("hi", "starfan_42"), false) // Sending unavailable on this build hides the card. const unset = fixture() @@ -88,7 +91,7 @@ assert.ok(interrupted.requests.every(({ options }) => options.method !== "POST") // An older status read cannot replace a send's newer status, even across navigation. const stale = fixture() stale.client.start() -const pendingSend = stale.client.send("hello") +const pendingSend = stale.client.send("hello", "starfan_42") await stale.reply(1, { state: "sending" }, 202) assert.equal(await pendingSend, true) await stale.reply(0, { state: "idle" }) @@ -100,7 +103,7 @@ assert.equal(stale.unauthorized, 0) await stale.reply(3, { state: "sent" }) assert.equal(stale.states.at(-1).state, "sent") -// A Discord username for a follow-up rides along only when given. +// The Discord username is sent as typed; the device strips the @. { const followUp = fixture() followUp.client.start() @@ -108,4 +111,47 @@ assert.equal(stale.states.at(-1).state, "sent") followUp.client.send("No video", " @star.fan_42 ") assert.deepEqual(JSON.parse(followUp.requests[1].options.body), { message: "No video", discord: "@star.fan_42" }) } + +// The Bluetooth Log uses the same client with its own route and wording. +{ + const requests = [], states = [] + const client = new StarPortLogSend({ url: BLUETOOTH_SEND_URL, unavailable: "Sending the Bluetooth Log is unavailable", + publish: (state) => states.push(state), fetcher: (url) => { requests.push(url); return Promise.reject(new TypeError("offline")) }, + schedule: () => 1, cancel: () => {} }) + client.start() + await flush() + assert.equal(requests[0], "./api/controllers/log/send") + assert.equal(states.at(-1).error, "offline") + const failing = new StarPortLogSend({ url: BLUETOOTH_SEND_URL, unavailable: "Sending the Bluetooth Log is unavailable", + publish: (state) => states.push(state), fetcher: () => Promise.resolve({ ok: false, status: 503, json: async () => ({}) }), + schedule: () => 1, cancel: () => {} }) + failing.start() + await flush() + assert.equal(states.at(-1).error, "Sending the Bluetooth Log is unavailable") +} + +// Clicking Send with an empty field outlines it like the theme maker's save prompt, without sending. +{ + const { LogSendCard } = await import("../web/js/starport-logs.js") + const sent = [], focused = [] + const card = { ...LogSendCard.data(), feed: { send: async (...args) => { sent.push(args); return true } }, + $refs: { note: { focus: () => focused.push("note") }, discord: { focus: () => focused.push("discord") } } } + const submit = LogSendCard.methods.submit.bind(card) + await submit() + assert.deepEqual(card.missing, ["note", "discord"]) + assert.deepEqual(focused, ["note"]) + card.note = "No pad" + LogSendCard.watch.note.call(card, card.note) + assert.deepEqual(card.missing, ["discord"]) + card.discord = "@" + await submit() + assert.deepEqual(card.missing, ["discord"]) + assert.equal(sent.length, 0) + card.discord = "starfan_42" + await submit() + assert.deepEqual(card.missing, []) + assert.deepEqual(sent, [["No pad", "starfan_42"]]) + assert.equal(card.note, "") + assert.match(LogSendCard.template, /gx-field--required/) +} console.log("StarPort log send: Discord follow-up passed") diff --git a/openpilot/starpilot/galaxy/tests/test_starport_send.py b/openpilot/starpilot/galaxy/tests/test_starport_send.py index fe07091e5e..129e2da5c1 100644 --- a/openpilot/starpilot/galaxy/tests/test_starport_send.py +++ b/openpilot/starpilot/galaxy/tests/test_starport_send.py @@ -16,26 +16,7 @@ from openpilot.starpilot.galaxy.server import make_server from openpilot.starpilot.galaxy.starport_send import (DISCORD_FILE_LIMIT, MESSAGE_LIMIT, SendBusy, SendRejected, StarPortLogSender, clean_discord, clean_message, send, thread_title) -URL = "https://discord.example/api/webhooks/1/token" -SUMMARY = {"device_id": "0123456789abcdef", "car_fingerprint": "HONDA_CIVIC_2022", "head_unit": "Honda Display Audio", - "branch": "Dom", "commit": "abcdef1234567890"} - - -class Response: - def __init__(self, status_code=200, body=None): - self.status_code, self.body = status_code, body if body is not None else {"channel_id": "555"} - - def json(self): - return self.body - - -class Poster: - def __init__(self, *responses): - self.responses, self.calls = list(responses), [] - - def __call__(self, url, data, files, timeout): - self.calls.append({"url": url, "payload": json.loads(data["payload_json"]), "files": files}) - return self.responses.pop(0) +from openpilot.starpilot.galaxy.tests.discord_fakes import SUMMARY, URL, Poster, Response def query(call): @@ -49,7 +30,7 @@ class SendTest(unittest.TestCase): self.threads = Path(temporary.name) def send(self, post, note="Dropped at the light", data=b"zip"): - return send(data, "logs.zip", note, SUMMARY, url=URL, post=post, thread_dir=self.threads) + return send(data, "logs.zip", note, SUMMARY, url=URL, post=post, thread_dir=self.threads, discord="starfan_42") def test_first_send_opens_a_device_thread_and_later_sends_reuse_it(self): first = Poster(Response(body={"channel_id": "555"})) @@ -91,7 +72,7 @@ class SendTest(unittest.TestCase): self.send(poster, data=b"x" * (DISCORD_FILE_LIMIT + 1)) self.assertEqual(poster.calls, []) with self.assertRaisesRegex(SendRejected, "isn't set up"): - send(b"zip", "logs.zip", "", SUMMARY, url="", post=poster, thread_dir=self.threads) + send(b"zip", "logs.zip", "", SUMMARY, url="", post=poster, thread_dir=self.threads, discord="starfan_42") def test_message_is_limited_and_single_line(self): self.assertEqual(MESSAGE_LIMIT, 60) @@ -133,7 +114,7 @@ class SenderJobTest(unittest.TestCase): job = StarPortLogSender(bundle, sender=sender, summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True) try: - self.assertEqual(job.start("hello")["state"], "sending") + self.assertEqual(job.start("hello", "starfan_42")["state"], "sending") self.assertTrue(sending.wait(2)) self.assertEqual(job.status()["state"], "sending") self.assertEqual(sent, []) @@ -146,7 +127,7 @@ class SenderJobTest(unittest.TestCase): self.assertEqual(status["state"], "sent") self.assertIn("snapshot was left out", status["message"]) self.assertEqual(bundles, [True, False]) - self.assertEqual(sent, [((b"x" * 10, "logs.zip", "hello", SUMMARY), {"discord": ""})]) + self.assertEqual(sent, [((b"x" * 10, "logs.zip", "hello", SUMMARY), {"discord": "starfan_42"})]) def test_one_send_at_a_time_and_failures_are_reported(self): release = threading.Event() @@ -156,9 +137,9 @@ class SenderJobTest(unittest.TestCase): raise SendRejected("Discord refused the logs (HTTP 500).") job = StarPortLogSender(lambda **_: ("logs.zip", b"zip"), sender=sender, summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True) - job.start("first") + job.start("first", "starfan_42") with self.assertRaises(SendBusy): - job.start("again") + job.start("again", "starfan_42") release.set() self.assertEqual(self.wait(job), {"state": "failed", "message": "Discord refused the logs (HTTP 500).", "available": True, "fork": False, "messageLimit": 60}) @@ -216,26 +197,25 @@ class SendHTTPTest(unittest.TestCase): status, body, _ = self.request("/api/starport/logs/send", headers={"Cookie": cookie}) self.assertEqual((status, json.loads(body)["state"]), (200, "idle")) - status, body, _ = self.post({"message": "Black screen after unlock"}, cookie) + status, body, _ = self.post({"message": "Black screen after unlock", "discord": "starfan_42"}, cookie) self.assertEqual((status, json.loads(body)["state"]), (202, "sending")) - self.job.start.assert_called_once_with("Black screen after unlock", "") - self.assertEqual(self.post({"message": "hi", "discord": "starfan_42"}, cookie)[0], 202) - self.job.start.assert_called_with("hi", "starfan_42") + self.job.start.assert_called_once_with("Black screen after unlock", "starfan_42") - self.assertEqual(self.post({"message": "hi", "extra": 1}, cookie)[0], 400) + self.assertEqual(self.post({"message": "hi"}, cookie)[0], 400) + self.assertEqual(self.post({"message": "hi", "discord": "starfan_42", "extra": 1}, cookie)[0], 400) + self.assertEqual(self.job.start.call_count, 1) self.job.start.side_effect = SendRejected("Keep the message to 60 characters.") - self.assertEqual(self.post({"message": "x" * 61}, cookie)[0], 400) + self.assertEqual(self.post({"message": "x" * 61, "discord": "starfan_42"}, cookie)[0], 400) self.job.start.side_effect = SendBusy("StarPort logs are already being sent.") - self.assertEqual(self.post({"message": "hi"}, cookie)[0], 409) + self.assertEqual(self.post({"message": "hi", "discord": "starfan_42"}, cookie)[0], 409) class DiscordFollowUpTest(unittest.TestCase): - def test_a_handle_is_optional_and_checked(self): - self.assertEqual(clean_discord(""), "") + def test_a_handle_is_required_and_checked(self): self.assertEqual(clean_discord(" @star.fan_42 "), "star.fan_42") self.assertEqual(clean_discord("OldName#1234"), "OldName#1234") - for bad in ("x", "has space", "<@123>", "a" * 33, 5): + for bad in ("", " ", "@", "x", "has space", "<@123>", "a" * 33, 5): with self.assertRaises(SendRejected): clean_discord(bad) @@ -246,14 +226,12 @@ class DiscordFollowUpTest(unittest.TestCase): payload = post.calls[0]["payload"] self.assertIn("Follow-up: Discord `star.fan_42`", payload["content"]) self.assertEqual(payload["allowed_mentions"], {"parse": []}) - post = Poster(Response()) - send(b"zip", "logs.zip", "", SUMMARY, url=URL, post=post, thread_dir=Path(directory)) - self.assertIn("Follow-up: not requested", post.calls[0]["payload"]["content"]) - def test_a_bad_handle_is_refused_before_anything_is_sent(self): + def test_a_missing_or_bad_handle_is_refused_before_anything_is_sent(self): job = StarPortLogSender(lambda **_: ("logs.zip", b"zip"), sender=mock.Mock(), summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True) - with self.assertRaises(SendRejected): - job.start("hi", "not a handle") + for handle in ("not a handle", ""): + with self.assertRaises(SendRejected): + job.start("hi", handle) self.assertIsNone(job._thread) def test_a_failed_fork_check_is_raised_and_retried(self): @@ -278,7 +256,7 @@ class DiscordFollowUpTest(unittest.TestCase): official=lambda: False) self.assertEqual(job.status()["fork"], True) self.assertEqual(job.status()["available"], True) - job.start("hi") + job.start("hi", "starfan_42") job._thread.join(2) self.assertEqual(job.status()["state"], "sent") sender.assert_called_once() diff --git a/openpilot/starpilot/galaxy/web/css/galaxy.css b/openpilot/starpilot/galaxy/web/css/galaxy.css index 104004747c..6f6eaa1dc9 100644 --- a/openpilot/starpilot/galaxy/web/css/galaxy.css +++ b/openpilot/starpilot/galaxy/web/css/galaxy.css @@ -939,14 +939,11 @@ background: var(--glass-bg-hover); .gx-crash-preview { margin-top: var(--sp-3); } .gx-crash-preview__head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); overflow-wrap: anywhere; } .gx-starport-logs { width: min(100%, 960px); margin-inline: auto; } -.gx-starport-logs__format { padding: 2px 7px; border-radius: var(--radius-full); background: rgba(255, 255, 255, .16); font-size: var(--fs-xs); letter-spacing: .04em; } .gx-starport-log-list { display: grid; gap: var(--sp-3); } .gx-starport-log { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: var(--sp-4); margin: 0; padding: var(--sp-4); cursor: default; } .gx-starport-log__body { display: grid; gap: var(--sp-1); min-width: 0; } .gx-starport-log__body strong { line-height: 1.35; overflow-wrap: anywhere; } .gx-starport-log__body span { color: var(--text-muted); font-size: var(--fs-sm); line-height: 1.45; overflow-wrap: anywhere; } -.gx-starport-log__download { flex: none; width: var(--touch-target); height: var(--touch-target); border: 1px solid var(--glass-border); background: var(--primary-container); color: var(--on-primary-container); } -.gx-starport-log__download:hover { background: var(--primary); color: var(--on-primary); } .gx-starport-logs__section-title { margin: var(--sp-6) 0 var(--sp-3); } .gx-starport-send__fork { justify-content: center; text-align: center; margin-block: var(--sp-4); } .gx-starport-send__fork .gx-alert__body { flex: 0 1 auto; } diff --git a/openpilot/starpilot/galaxy/web/css/settings.css b/openpilot/starpilot/galaxy/web/css/settings.css index 4db249367c..2d9e4185f5 100644 --- a/openpilot/starpilot/galaxy/web/css/settings.css +++ b/openpilot/starpilot/galaxy/web/css/settings.css @@ -554,7 +554,7 @@ input[type="range"].gx-slider:active::-moz-range-thumb { .gx-layout__color-values input[type="text"] { min-width: 0; width: 100%; font-family: ui-monospace, monospace; } .gx-layout__color input[type="range"] { width: 100%; accent-color: var(--primary); min-height: 36px; } .gx-layout__color > label { color: var(--on-surface-variant); } -.gx-layout__savebar.gx-layout__savebar--leave, .gx-card.gx-layout__leave-dialog { --leave-glow: 0 0 0 1px var(--primary-glow), 0 0 24px var(--primary-glow); border: 1px solid var(--primary); box-shadow: var(--leave-glow); } +.gx-layout__savebar.gx-layout__savebar--leave, .gx-card.gx-layout__leave-dialog, .gx-field.gx-field--required { --leave-glow: 0 0 0 1px var(--primary-glow), 0 0 24px var(--primary-glow); border: 1px solid var(--primary); box-shadow: var(--leave-glow); } /* One workspace structure at every size; panels replace long stacked controls. */ .gx-layout { max-width: 1440px; margin-inline: auto; gap: 12px; } .gx-layout__workspace { grid-template-columns: minmax(0, 1.4fr) minmax(320px, 1fr); gap: 16px; } diff --git a/openpilot/starpilot/galaxy/web/data/catalog.json b/openpilot/starpilot/galaxy/web/data/catalog.json index 4d7d8ae067..5a21fcdb6d 100644 --- a/openpilot/starpilot/galaxy/web/data/catalog.json +++ b/openpilot/starpilot/galaxy/web/data/catalog.json @@ -67,6 +67,13 @@ "description": "Read local reports", "availability": "local-only" }, + { + "name": "Bluetooth Log", + "path": "/logs/bluetooth", + "icon": "bi-controller", + "description": "Send a USB and Bluetooth controller report", + "availability": "local-only" + }, { "name": "StarPort Logs", "path": "/logs/starport", diff --git a/openpilot/starpilot/galaxy/web/js/logs.js b/openpilot/starpilot/galaxy/web/js/logs.js index c38d7554c8..37cf572910 100644 --- a/openpilot/starpilot/galaxy/web/js/logs.js +++ b/openpilot/starpilot/galaxy/web/js/logs.js @@ -6,21 +6,21 @@ import { navigate } from "./router.js" import { SystemMonitor } from "./system-monitor.js" import { CrashReportsFeed } from "./crash-reports.js" import { storedSize } from "./record-deletion.js" -import { StarPortLogsFeed, StarPortLogSend, BUNDLE_URL, MESSAGE_LIMIT, fileUrl, outcomeLabel } from "./starport-logs.js" +import { StarPortLogsFeed, StarPortLogSend, LogSendCard, BLUETOOTH_SEND_URL, outcomeLabel } from "./starport-logs.js" import { MenuTile } from "./menu-tile.js" -import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js" export const Logs = { name: "Logs", - components: { WikiHelp, GxState, GxNotice, BluetoothNotice, SystemMonitor, TroubleshootPage, TmuxPage, MenuTile }, + components: { WikiHelp, GxState, GxNotice, LogSendCard, SystemMonitor, TroubleshootPage, TmuxPage, MenuTile }, props: { path: { type: String, required: true }, mode: { type: String, required: true }, unauthorized: { type: Function, required: true }, tools: { type: Array, required: true } }, data: () => ({ crashes: { reports: [], scanIncomplete: false, listLimited: false, status: "idle", error: "", selected: null, preview: null, previewStatus: "idle", deleting: false, storageBytes: 0, reportCount: 0 }, search: "", - starportLogs: { sessions: [], others: [], status: "idle", error: "" }, bluetooth: bluetoothConnection(), - logSend: { state: "idle", message: "", available: true, fork: false, error: "" }, sendNote: "", sendDiscord: "", messageLimit: MESSAGE_LIMIT + starportLogs: { sessions: [], others: [], status: "idle", error: "" }, + logSend: { state: "idle", message: "", available: true, fork: false, error: "" }, + bluetoothSend: { state: "idle", message: "", available: true, fork: false, error: "" } }), computed: { visibleReports() { return this.crashes.reports.filter((item) => item.name.toLowerCase().includes(this.search.toLowerCase())) }, @@ -29,29 +29,29 @@ export const Logs = { this.crashFeed = new CrashReportsFeed({ publish: (update) => Object.assign(this.crashes, update), unauthorized: this.unauthorized }) this.starportFeed = new StarPortLogsFeed({ publish: (update) => Object.assign(this.starportLogs, update), unauthorized: this.unauthorized }) this.sendFeed = new StarPortLogSend({ publish: (update) => Object.assign(this.logSend, update), unauthorized: this.unauthorized }) + this.bluetoothFeed = new StarPortLogSend({ url: BLUETOOTH_SEND_URL, unavailable: "Sending the Bluetooth Log is unavailable", + publish: (update) => Object.assign(this.bluetoothSend, update), unauthorized: this.unauthorized }) }, mounted() { if (this.path === "/logs/crashes" && this.mode === "local") this.crashFeed.start() if (this.path === "/logs/starport" && this.mode === "local") { this.starportFeed.start(); this.sendFeed.start() } + if (this.path === "/logs/bluetooth" && this.mode === "local") this.bluetoothFeed.start() }, - beforeUnmount() { this.crashFeed.stop(); this.starportFeed.stop(); this.sendFeed.stop() }, + beforeUnmount() { this.crashFeed.stop(); this.starportFeed.stop(); this.sendFeed.stop(); this.bluetoothFeed.stop() }, watch: { path(next, previous) { if (next === "/logs/crashes" && this.mode === "local") this.crashFeed.start() else if (previous === "/logs/crashes") { this.crashFeed.stop(); this.search = "" } if (next === "/logs/starport" && this.mode === "local") { this.starportFeed.start(); this.sendFeed.start() } else if (previous === "/logs/starport") { this.starportFeed.stop(); this.sendFeed.stop() } + if (next === "/logs/bluetooth" && this.mode === "local") this.bluetoothFeed.start() + else if (previous === "/logs/bluetooth") this.bluetoothFeed.stop() }, }, methods: { storedSize, go: navigate, - bundleUrl: () => BUNDLE_URL, - fileUrl, outcomeLabel, - async sendLogs() { - if (await this.sendFeed.send(this.sendNote, this.sendDiscord)) this.sendNote = "" - }, reportDate(seconds) { return new Date(seconds * 1000).toLocaleString() }, reportSize(bytes) { return `${(bytes / 1024).toFixed(1)} KiB` }, async copyPreview() { @@ -70,6 +70,12 @@ export const Logs = { :availability="mode !== 'local' && tool.availability === 'local-only' ? 'Unavailable in preview' : ''" :disabled="mode !== 'local' && tool.availability === 'local-only'" @select="go(tool.path)" /> +
+

Bluetooth Log

+

Sends the USB and Bluetooth input devices the comma sees to the developer.

+ Connect the controller and wake it before sending. A short note and your Discord username are required. + Sending isn't set up on this build. +

Help & Community

Guides and help from the community.

Discord
@@ -98,23 +104,10 @@ export const Logs = {

StarPort Logs

-

The last 20 connection sessions, newest first. The archive includes every session, a readable report for each, StarPort settings, the car view's renderer logs, and a snapshot of the device (Wi-Fi, Bluetooth and kernel logs, build, CPU load). Hardware addresses are masked.

- Log summaries remain available. - +

The last 20 connection sessions, newest first. Sent logs include every session, a readable report for each, StarPort settings, the car view's renderer logs, and a snapshot of the device (Wi-Fi, Bluetooth and kernel logs, build, CPU load). Hardware addresses are masked.

+
Custom forks may have changed StarPort or be out of date. Make sure your branch is up to date with StarPilotHQ before sending, or share the logs with your branch's maintainer or in the StarPilot Discord. -
-
Send StarPort logs
-

Only for StarPort issues. For anything else, ask in the Discord. Sends the same archive as Download all logs straight from the device. A short note about what happened is required.

-
-
{{ sendNote.length }}/{{ messageLimit }}
- - -
- {{ logSend.message || 'Sending logs' }}… - {{ logSend.message }} - {{ logSend.message }} - {{ logSend.error }} -
+ Only for StarPort issues. For anything else, ask in the Discord. Sends every session with its report, StarPort settings, renderer logs and a device snapshot straight from the device. A short note and your Discord username are required. Loading StarPort logs… {{ starportLogs.error || 'StarPort logs are unavailable.' }} @@ -122,7 +115,6 @@ export const Logs = {
{{ outcomeLabel(log.outcome) }}{{ log.car || 'Car not identified' }}{{ log.transport ? ' · ' + log.transport : '' }}{{ log.trigger ? ' · ' + log.trigger : '' }}{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}
-
diff --git a/openpilot/starpilot/galaxy/web/js/starport-logs.js b/openpilot/starpilot/galaxy/web/js/starport-logs.js index 89f5eec932..fe154cc890 100644 --- a/openpilot/starpilot/galaxy/web/js/starport-logs.js +++ b/openpilot/starpilot/galaxy/web/js/starport-logs.js @@ -1,7 +1,8 @@ // Read-only StarPort session logs. State is cleared on navigation and sign-out. +import { GxState } from "./state.js" +import { GxNotice } from "./notice.js" + export const LOGS_URL = "./api/starport/logs" -export const BUNDLE_URL = `${LOGS_URL}/bundle` -export const fileUrl = (name) => `${LOGS_URL}/file/${encodeURIComponent(name)}` // compat_report's outcome is a short phrase: "projected", "failed: ", "stopped at rfcomm", "no session". export const outcomeLabel = (outcome) => (outcome ? outcome[0].toUpperCase() + outcome.slice(1) : "Unknown") @@ -70,15 +71,16 @@ export class StarPortLogsFeed { } export const SEND_URL = `${LOGS_URL}/send` +export const BLUETOOTH_SEND_URL = "./api/controllers/log/send" export const MESSAGE_LIMIT = 60 const POLL_MS = 1500 -// "Send StarPort logs": the device builds the same zip as Download all logs and posts it to the developer's Discord. +// The device builds the log and posts it to the developer's Discord. // Only small JSON crosses the connection, so this also works over Bluetooth. export class StarPortLogSend { constructor({ publish, unauthorized = () => {}, fetcher = (...args) => fetch(...args), schedule = (fn, ms) => setTimeout(fn, ms), - cancel = (id) => clearTimeout(id) }) { - Object.assign(this, { publish, unauthorized, fetcher, schedule, cancel }) + cancel = (id) => clearTimeout(id), url = SEND_URL, unavailable = "Sending StarPort logs is unavailable" }) { + Object.assign(this, { publish, unauthorized, fetcher, schedule, cancel, url, unavailable }) this.active = false this.timer = null this.generation = 0 @@ -98,7 +100,7 @@ export class StarPortLogSend { } async call(options, generation) { - const response = await this.fetcher(SEND_URL, { cache: "no-store", credentials: "same-origin", ...options }) + const response = await this.fetcher(this.url, { cache: "no-store", credentials: "same-origin", ...options }) if (!this.active || generation !== this.generation) return null if (response.status === 401) { this.stop() @@ -107,7 +109,7 @@ export class StarPortLogSend { } const body = await response.json().catch(() => null) if (!this.active || generation !== this.generation) return null - if (!response.ok) throw new Error(body?.error || "Sending StarPort logs is unavailable") + if (!response.ok) throw new Error(body?.error || this.unavailable) return body } @@ -129,13 +131,13 @@ export class StarPortLogSend { this.apply(await this.call({}, generation)) } catch (error) { if (this.active && generation === this.generation) { - this.publish({ error: error?.message || "Sending StarPort logs is unavailable" }) + this.publish({ error: error?.message || this.unavailable }) this.queuePoll() } } } - async send(message, discord = "") { + async send(message, discord) { if (!this.active) return false const text = String(message ?? "").trim() const handle = String(discord ?? "").trim() @@ -147,20 +149,56 @@ export class StarPortLogSend { this.publish({ error: `Keep the message to ${MESSAGE_LIMIT} characters.` }) return false } + if (!handle.replace(/^@/, "")) { + this.publish({ error: "Add your Discord username so we can follow up." }) + return false + } const generation = ++this.generation this.queuePoll(false) this.publish({ state: "sending", message: "Starting", error: "" }) try { - const body = await this.call({ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(handle ? { message: text, discord: handle } : { message: text }) }, generation) + const body = await this.call({ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: text, discord: handle }) }, generation) if (body === null) return false this.apply(body) return true } catch (error) { if (this.active && generation === this.generation) { - this.publish({ state: "idle", error: error?.message || "Sending StarPort logs is unavailable" }) + this.publish({ state: "idle", error: error?.message || this.unavailable }) this.queuePoll() } return false } } } + +export const LogSendCard = { + name: "LogSendCard", + components: { GxState, GxNotice }, + props: { feed: { type: Object, required: true }, state: { type: Object, required: true }, title: { type: String, required: true } }, + data: () => ({ note: "", discord: "", limit: MESSAGE_LIMIT, missing: [] }), + watch: { + note(value) { if (value.trim()) this.missing = this.missing.filter((field) => field !== "note") }, + discord(value) { if (value.trim().replace(/^@/, "")) this.missing = this.missing.filter((field) => field !== "discord") }, + }, + methods: { + async submit() { + this.missing = [!this.note.trim() && "note", !this.discord.trim().replace(/^@/, "") && "discord"].filter(Boolean) + if (this.missing.length) return this.$refs[this.missing[0]]?.focus() + if (await this.feed.send(this.note, this.discord)) this.note = "" + }, + }, + template: ` +
+
{{ title }}
+

+
+
{{ note.length }}/{{ limit }}
+ + +
+ {{ state.message || 'Sending logs' }}… + {{ state.message }} + {{ state.message }} + {{ state.error }} +
`, +} diff --git a/openpilot/starpilot/ui/translation_messages.json b/openpilot/starpilot/ui/translation_messages.json index 22970ad0c9..a54dda57fc 100644 --- a/openpilot/starpilot/ui/translation_messages.json +++ b/openpilot/starpilot/ui/translation_messages.json @@ -4552,12 +4552,6 @@ "openpilot/starpilot/galaxy/web/js/install-app.js" ] }, - { - "source": "Download all logs", - "refs": [ - "openpilot/starpilot/galaxy/web/js/logs.js" - ] - }, { "source": "Download all logs (.tar)", "refs": [ @@ -8511,12 +8505,6 @@ "openpilot/starpilot/galaxy/web/js/vehicle-controls.js" ] }, - { - "source": "Log summaries remain available.", - "refs": [ - "openpilot/starpilot/galaxy/web/js/logs.js" - ] - }, { "source": "Log uploads", "refs": [ @@ -17441,12 +17429,6 @@ "openpilot/starpilot/galaxy/web/js/onroad-layout-template.js" ] }, - { - "source": "The last 20 connection sessions, newest first. The archive includes every session, a readable report for each, StarPort settings, the car view's renderer logs, and a snapshot of the device (Wi-Fi, Bluetooth and kernel logs, build, CPU load). Hardware addresses are masked.", - "refs": [ - "openpilot/starpilot/galaxy/web/js/logs.js" - ] - }, { "source": "The last update was invalid.", "refs": [