StarPort Logs: Require a Note, Warn on Custom Forks, Log the Repo

This commit is contained in:
Danny
2026-11-20 19:07:46 -06:00
committed by firestar5683
parent 256924b83c
commit d7b3560862
10 changed files with 88 additions and 19 deletions
+18 -4
View File
@@ -36,6 +36,11 @@ class SendBusy(Exception):
pass
def official_install() -> bool:
from openpilot.starpilot.system.starport.bugsink_transport import device_metadata, is_official_repo
return is_official_repo(device_metadata().get("repo"))
def webhook_url(override_path: Path = WEBHOOK_OVERRIDE_PATH) -> str:
try:
override = override_path.read_text().strip()
@@ -53,6 +58,8 @@ def clean_message(value) -> str:
if not isinstance(value, str):
raise SendRejected("The message must be text.")
message = CONTROL.sub(" ", value).strip()
if not message:
raise SendRejected("Add a short note about what happened.")
if len(message) > MESSAGE_LIMIT:
raise SendRejected(f"Keep the message to {MESSAGE_LIMIT} characters.")
return message
@@ -172,7 +179,7 @@ def send(data: bytes, name: str, note: str, summary: dict, url: str | None = Non
f"Head unit: {summary.get('head_unit') or 'unknown'}",
f"Setup: {summary.get('setup') or 'unknown'}",
f"Handshake: {summary.get('handshake') or 'unknown'}",
f"Branch {summary.get('branch', '?')} @ {str(summary.get('commit', '?'))[:10]}",
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"]
payload = {"content": "\n".join(lines)[:1900], "username": "StarPilot diagnostics", "allowed_mentions": {"parse": []}}
@@ -241,15 +248,22 @@ class StarPortLogSender:
"""One send at a time, off the request thread; the page polls status()."""
def __init__(self, bundle: Callable[..., tuple[str, bytes]], *, sender: Callable[..., str | None] = send,
summary: Callable[[], dict] = device_summary, url: Callable[[], str] = webhook_url):
self._bundle, self._sender, self._summary, self._url = bundle, sender, summary, url
summary: Callable[[], dict] = device_summary, url: Callable[[], str] = webhook_url,
official: Callable[[], bool] = official_install):
self._bundle, self._sender, self._summary, self._url, self._official = bundle, sender, summary, url, official
self._lock = threading.Lock()
self._thread: threading.Thread | None = None
self._state = {"state": "idle", "message": ""}
self._fork: bool | None = None
def status(self) -> dict:
with self._lock:
return {**self._state, "available": bool(self._url()), "messageLimit": MESSAGE_LIMIT}
if self._fork is None:
try:
self._fork = not self._official()
except Exception:
self._fork = False
return {**self._state, "available": bool(self._url()), "fork": self._fork, "messageLimit": MESSAGE_LIMIT}
def start(self, message, discord="") -> dict:
note, handle = clean_message(message), clean_discord(discord)
@@ -43,6 +43,9 @@ await limited.reply(0, { state: "idle" })
assert.equal(await limited.client.send("x".repeat(61)), 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(limited.requests.length, 1)
assert.match(limited.states.at(-1).error, /short note/)
const busy = limited.client.send("hi")
await limited.reply(1, { error: "StarPort logs are already being sent." }, 409)
assert.equal(await busy, false)
@@ -60,6 +63,14 @@ const unset = fixture()
unset.client.start()
await unset.reply(0, { state: "idle", available: false })
assert.equal(unset.states.at(-1).available, false)
assert.equal(unset.states.at(-1).fork, false)
// A custom fork can still send, with a warning.
const fork = fixture()
fork.client.start()
await fork.reply(0, { state: "idle", available: true, fork: true })
assert.equal(fork.states.at(-1).available, true)
assert.equal(fork.states.at(-1).fork, true)
// A lost Bluetooth response retries the status read without repeating the upload.
const interrupted = fixture()
@@ -97,7 +97,7 @@ class SendTest(unittest.TestCase):
self.assertEqual(MESSAGE_LIMIT, 60)
self.assertEqual(clean_message(" car\nwent black "), "car went black")
self.assertEqual(clean_message("x" * 60), "x" * 60)
for bad in ("x" * 61, None, 5):
for bad in ("x" * 61, "", " \n ", None, 5):
with self.assertRaises(SendRejected):
clean_message(bad)
@@ -131,7 +131,7 @@ class SenderJobTest(unittest.TestCase):
raise TimeoutError("The test did not release the send")
sent.append((args, kwargs))
job = StarPortLogSender(bundle, sender=sender, summary=lambda: SUMMARY, url=lambda: URL)
job = StarPortLogSender(bundle, sender=sender, summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True)
try:
self.assertEqual(job.start("hello")["state"], "sending")
self.assertTrue(sending.wait(2))
@@ -155,13 +155,13 @@ class SenderJobTest(unittest.TestCase):
release.wait(2)
raise SendRejected("Discord refused the logs (HTTP 500).")
job = StarPortLogSender(lambda **_: ("logs.zip", b"zip"), sender=sender, summary=lambda: SUMMARY, url=lambda: URL)
job.start("")
job = StarPortLogSender(lambda **_: ("logs.zip", b"zip"), sender=sender, summary=lambda: SUMMARY, url=lambda: URL, official=lambda: True)
job.start("first")
with self.assertRaises(SendBusy):
job.start("again")
release.set()
self.assertEqual(self.wait(job), {"state": "failed", "message": "Discord refused the logs (HTTP 500).", "available": True,
"messageLimit": 60})
"fork": False, "messageLimit": 60})
class SendHTTPTest(unittest.TestCase):
@@ -251,11 +251,31 @@ class DiscordFollowUpTest(unittest.TestCase):
self.assertIn("Follow-up: not requested", post.calls[0]["payload"]["content"])
def test_a_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)
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")
self.assertIsNone(job._thread)
def test_custom_forks_are_flagged_but_can_still_send(self):
from openpilot.starpilot.system.starport.bugsink_transport import is_official_repo, repo_name
for origin, repo in (("https://github.com/StarPilotHQ/StarPilot.git", "StarPilotHQ/StarPilot"),
("git@github.com:starpilothq/starpilot", "starpilothq/starpilot"),
("https://user:token@github.com/dirwin31/openpilot.git", "dirwin31/openpilot"),
("https://evil.com/github.com/StarPilotHQ/StarPilot", "other"), ("", "unknown"), (None, "unknown")):
self.assertEqual(repo_name(origin), repo, origin)
self.assertTrue(is_official_repo("StarPilotHQ/StarPilot"))
self.assertFalse(is_official_repo("dirwin31/openpilot"))
sender = mock.Mock(return_value=None)
job = StarPortLogSender(lambda **_: ("logs.zip", b"zip"), sender=sender, summary=lambda: SUMMARY, url=lambda: URL,
official=lambda: False)
self.assertEqual(job.status()["fork"], True)
self.assertEqual(job.status()["available"], True)
job.start("hi")
job._thread.join(2)
self.assertEqual(job.status()["state"], "sent")
sender.assert_called_once()
if __name__ == "__main__":
unittest.main()
@@ -948,6 +948,8 @@ background: var(--glass-bg-hover);
.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; }
.gx-starport-send__row { display: grid; gap: var(--sp-3); margin-top: var(--sp-3); }
.gx-starport-send__row .gx-field { width: 100%; box-sizing: border-box; }
.gx-starport-send__field { position: relative; }
+5 -4
View File
@@ -20,7 +20,7 @@ export const Logs = {
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, error: "" }, sendNote: "", sendDiscord: "", messageLimit: MESSAGE_LIMIT
logSend: { state: "idle", message: "", available: true, fork: false, error: "" }, sendNote: "", sendDiscord: "", messageLimit: MESSAGE_LIMIT
}),
computed: {
visibleReports() { return this.crashes.reports.filter((item) => item.name.toLowerCase().includes(this.search.toLowerCase())) },
@@ -101,13 +101,14 @@ export const Logs = {
<p>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.</p></div><WikiHelp /></header>
<BluetoothNotice v-if="bluetooth" feature="Log downloads">Log summaries remain available.</BluetoothNotice>
<div class="gx-settings__controls gx-actions"><a v-if="!bluetooth" class="gx-btn" :href="bundleUrl()" download><i class="bi bi-file-earmark-zip" aria-hidden="true"></i><span>Download all logs</span><span class="gx-starport-logs__format">ZIP</span></a><button type="button" class="gx-btn gx-btn--tonal" @click="starportFeed.load()"><i class="bi bi-arrow-clockwise" aria-hidden="true"></i><span>Refresh</span></button></div>
<GxNotice v-if="logSend.fork" class="gx-starport-send__fork" tone="warn" title="This device is running a StarPilot fork">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.</GxNotice>
<section v-if="logSend.available" class="gx-card gx-panel gx-starport-send" aria-labelledby="gx-starport-send-title">
<div class="gx-section__header"><i class="bi bi-send" aria-hidden="true"></i><span id="gx-starport-send-title" class="gx-section__title">Send StarPort logs</span></div>
<p class="gx-note">Only for StarPort issues. For anything else, ask in the Discord. Sends the same archive as Download all logs straight from the device. Add a short note about what happened.</p>
<p class="gx-note">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.</p>
<div class="gx-starport-send__row">
<div class="gx-starport-send__field"><input class="gx-field" type="text" v-model="sendNote" :maxlength="messageLimit" placeholder="What happened? (optional)" aria-label="Note for the developer" :disabled="logSend.state === 'sending'" @keydown.enter="sendLogs"><span class="gx-starport-send__count" aria-live="polite">{{ sendNote.length }}/{{ messageLimit }}</span></div>
<div class="gx-starport-send__field"><input class="gx-field" type="text" v-model="sendNote" :maxlength="messageLimit" placeholder="What happened?" aria-label="Note for the developer" :disabled="logSend.state === 'sending'" @keydown.enter="sendLogs"><span class="gx-starport-send__count" aria-live="polite">{{ sendNote.length }}/{{ messageLimit }}</span></div>
<input class="gx-field" type="text" v-model="sendDiscord" maxlength="40" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="Discord username (optional)" aria-label="Discord username for a follow-up" :disabled="logSend.state === 'sending'" @keydown.enter="sendLogs">
<button type="button" class="gx-btn" :disabled="logSend.state === 'sending'" @click="sendLogs"><i class="bi bi-send" aria-hidden="true"></i><span>Send StarPort logs</span></button>
<button type="button" class="gx-btn" :disabled="logSend.state === 'sending' || !sendNote.trim()" @click="sendLogs"><i class="bi bi-send" aria-hidden="true"></i><span>Send StarPort logs</span></button>
</div>
<GxState v-if="logSend.state === 'sending'" loading>{{ logSend.message || 'Sending logs' }}…</GxState>
<GxNotice v-else-if="logSend.state === 'sent'" tone="success">{{ logSend.message }}</GxNotice>
@@ -113,7 +113,7 @@ export class StarPortLogSend {
apply(body) {
if (!this.active || !body) return
this.publish({ state: body.state, message: body.message || "", available: body.available !== false, error: "" })
this.publish({ state: body.state, message: body.message || "", available: body.available !== false, fork: body.fork === true, error: "" })
this.queuePoll(body.state === "sending")
}
@@ -139,6 +139,10 @@ export class StarPortLogSend {
if (!this.active) return false
const text = String(message ?? "").trim()
const handle = String(discord ?? "").trim()
if (!text) {
this.publish({ error: "Add a short note about what happened." })
return false
}
if (text.length > MESSAGE_LIMIT) {
this.publish({ error: `Keep the message to ${MESSAGE_LIMIT} characters.` })
return false
@@ -3,6 +3,7 @@
import hashlib
import json
import os
import re
from datetime import UTC, datetime
import urllib.error
import urllib.parse
@@ -68,6 +69,22 @@ class Sender:
return False
GITHUB_REPO = re.compile(r"(?:(?:https?|ssh|git)://)?(?:[^@/\s]+@)?github\.com[:/]([^/\s]+/[^/\s]+?)(?:\.git)?/?", re.IGNORECASE)
OFFICIAL_REPO = "starpilothq/starpilot"
def repo_name(origin) -> str:
"""owner/name of a GitHub remote; never the raw URL, which can carry credentials."""
if not isinstance(origin, str) or not origin.strip():
return "unknown"
match = GITHUB_REPO.fullmatch(origin.strip())
return match.group(1) if match else "other"
def is_official_repo(repo) -> bool:
return isinstance(repo, str) and repo.lower() == OFFICIAL_REPO
def device_metadata():
values = {"device_id": os.getenv("DONGLE_ID", "unknown"), "commit": os.getenv("GIT_COMMIT", "unknown")}
try:
@@ -75,7 +92,7 @@ def device_metadata():
from openpilot.common.params import Params
from openpilot.common.version import get_build_metadata
build = get_build_metadata()
values.update(commit=build.openpilot.git_commit, branch=build.channel)
values.update(commit=build.openpilot.git_commit, branch=build.channel, repo=repo_name(build.openpilot.git_origin))
values.update(device_id=Params().get("DongleId") or values["device_id"], device=HARDWARE.get_device_type())
except Exception:
pass
@@ -1475,7 +1475,7 @@ class Supervisor:
software = device_metadata()
profile, profile_source = car_profiles.resolve(self.config)
self.log("session_start", receiver=receiver, generation=generation, trigger=trigger,
software={key: software.get(key, "unknown") for key in ("commit", "branch")},
software={key: software.get(key, "unknown") for key in ("repo", "commit", "branch")},
settings={key: self.config.get(key) for key in REPORTED_SETTINGS},
# What the owner chose, so a report can tell a built-in unit from a dongle and say which profile applied.
setup={"type": {"wired": "usb", "headunitpad": "app", "openheadunit": "app"}.get(connection) or self.car_type(),
@@ -328,7 +328,7 @@ def test_supervisor_records_build_at_session_start(monkeypatch):
sup._count_dedicated = lambda _: None # ty: ignore[invalid-assignment] # test double
sup._release_phone = lambda: None # ty: ignore[invalid-assignment] # test double
sup._run(1)
assert records[0]["software"] == {"commit": "session-build", "branch": "session-branch"}
assert records[0]["software"] == {"repo": "unknown", "commit": "session-build", "branch": "session-branch"}
HANDSHAKE_FAILED = [
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "df36329d311701194fe18520c13f5c7c03f43ce61f43eaeedadf04ee16721dac", "schema_version": 1}
{"protected_inventory_sha256": "05c49bd791d78b58a070246b534f788e779de8dda55c8b4a6ea248256b6b4602", "schema_version": 1}