mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-25 14:23:45 +08:00
Compare commits
8 Commits
testing
...
Nate-testing
| Author | SHA1 | Date | |
|---|---|---|---|
| 8c14810edd | |||
| 947bc2026d | |||
| 88d9b60a13 | |||
| 7392d42e9e | |||
| c02a563a59 | |||
| 5ef8ef1009 | |||
| f6d3829470 | |||
| 00486de7ad |
@@ -246,7 +246,7 @@ class _LocalHTTPHandler(BaseHTTPRequestHandler):
|
||||
if cookie is not None:
|
||||
self.send_header('Set-Cookie', cookie)
|
||||
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; " +
|
||||
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/fresh/")
|
||||
"img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
|
||||
self.end_headers()
|
||||
if self.command != 'HEAD':
|
||||
self.wfile.write(body)
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Stage diagnostic log archives on the StarPilot log relay for one-click Discord confirmation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
from collections.abc import Callable
|
||||
from urllib.parse import quote
|
||||
|
||||
from openpilot.starpilot.galaxy.starport_send import DISCORD_FILE_LIMIT, official_install
|
||||
|
||||
STAGE_URL = "https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/stage"
|
||||
CLAIM_RE = re.compile(r"^https://starpilot-log-relay\.nathan-g-hubbard\.workers\.dev/report/galaxy/claim/[a-f0-9]{64}$")
|
||||
NOTE_LIMIT = 200
|
||||
MODEL_LIMIT = 80
|
||||
KINDS = ("starport", "connection", "controller")
|
||||
PHONES = ("ios", "android")
|
||||
CONTROL = re.compile(r"[\x00-\x1f\x7f]+")
|
||||
|
||||
|
||||
class StageRejected(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class StageBusy(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _clean_text(value: object) -> str:
|
||||
if not isinstance(value, str):
|
||||
return ""
|
||||
return CONTROL.sub(" ", value).strip()
|
||||
|
||||
|
||||
def clean_stage_request(payload: object) -> tuple[str, str, str]:
|
||||
"""Validate and normalize a staging request; return (kind, platform, formatted_note)."""
|
||||
if not isinstance(payload, dict):
|
||||
raise StageRejected("Invalid log report request.")
|
||||
kind = payload.get("kind")
|
||||
if kind not in KINDS:
|
||||
raise StageRejected("Choose what you are sending logs for.")
|
||||
allowed = {"kind", "note"} | ({"phone"} if kind == "connection" else {"model"} if kind == "controller" else set())
|
||||
if set(payload) - allowed:
|
||||
raise StageRejected("Invalid log report request.")
|
||||
note = payload.get("note")
|
||||
if not isinstance(note, str):
|
||||
raise StageRejected("Add a short note about what happened.")
|
||||
note = _clean_text(note)
|
||||
if not note:
|
||||
raise StageRejected("Add a short note about what happened.")
|
||||
if len(note) > NOTE_LIMIT:
|
||||
raise StageRejected(f"Keep the note to {NOTE_LIMIT} characters.")
|
||||
|
||||
if kind == "connection":
|
||||
phone = payload.get("phone")
|
||||
if phone not in PHONES:
|
||||
raise StageRejected("Choose iPhone or Android.")
|
||||
label = "iPhone" if phone == "ios" else "Android"
|
||||
return kind, phone, f"[{label}] {note}"
|
||||
|
||||
if kind == "controller":
|
||||
raw_model = payload.get("model")
|
||||
if not isinstance(raw_model, str):
|
||||
raise StageRejected("Enter your controller make and model.")
|
||||
model = _clean_text(raw_model)
|
||||
if not model:
|
||||
raise StageRejected("Enter your controller make and model.")
|
||||
if len(model) > MODEL_LIMIT:
|
||||
raise StageRejected(f"Keep the controller model to {MODEL_LIMIT} characters.")
|
||||
return kind, "ios", f"Controller ({model}): {note}"
|
||||
|
||||
return kind, "android", note
|
||||
|
||||
|
||||
def _response_error(response) -> str:
|
||||
try:
|
||||
body = response.json()
|
||||
except (AttributeError, ValueError):
|
||||
return ""
|
||||
if isinstance(body, dict) and isinstance(body.get("error"), str):
|
||||
return body["error"][:240]
|
||||
return ""
|
||||
|
||||
|
||||
class LogRelayStager:
|
||||
"""One diagnostic upload at a time, off the request thread; the page polls status()."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
starport_bundle: Callable[..., tuple[str, bytes]],
|
||||
connection_zip: Callable[[], bytes],
|
||||
controller_zip: Callable[[], bytes],
|
||||
*,
|
||||
post=None,
|
||||
stage_url: Callable[[], str] | str = STAGE_URL,
|
||||
official: Callable[[], bool] = official_install,
|
||||
):
|
||||
self._starport_bundle = starport_bundle
|
||||
self._connection_zip = connection_zip
|
||||
self._controller_zip = controller_zip
|
||||
self._post = post
|
||||
self._stage_url = stage_url
|
||||
self._official = official
|
||||
self._lock = threading.Lock()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._state = {"state": "idle", "message": "", "claimUrl": "", "kind": ""}
|
||||
self._session = None
|
||||
self._fork: bool | None = None
|
||||
|
||||
def _url(self) -> str:
|
||||
return self._stage_url() if callable(self._stage_url) else self._stage_url
|
||||
|
||||
def status(self, session=None) -> dict:
|
||||
with self._lock:
|
||||
if self._fork is None:
|
||||
self._fork = not self._official()
|
||||
return {
|
||||
**(self._state if session == self._session else {"state": "idle", "message": "", "claimUrl": "", "kind": ""}),
|
||||
"available": bool(self._url()),
|
||||
"fork": self._fork,
|
||||
"noteLimit": NOTE_LIMIT,
|
||||
"modelLimit": MODEL_LIMIT,
|
||||
}
|
||||
|
||||
def start(self, payload: object, session=None) -> dict:
|
||||
kind, platform, formatted_note = clean_stage_request(payload)
|
||||
if not self._url():
|
||||
raise StageRejected("Online log relay is unavailable. Use Download ZIP instead.")
|
||||
with self._lock:
|
||||
if self._thread is not None and self._thread.is_alive():
|
||||
raise StageBusy("Logs are already being prepared.")
|
||||
self._session = session
|
||||
self._state = {"state": "staging", "message": "Collecting logs", "claimUrl": "", "kind": kind}
|
||||
self._thread = threading.Thread(
|
||||
target=self._run,
|
||||
args=(kind, platform, formatted_note),
|
||||
name="galaxy_log_stage",
|
||||
daemon=True,
|
||||
)
|
||||
self._thread.start()
|
||||
return self.status(session)
|
||||
|
||||
def _set(self, **values) -> None:
|
||||
with self._lock:
|
||||
self._state.update(values)
|
||||
|
||||
def _build_zip(self, kind: str) -> bytes:
|
||||
if kind == "starport":
|
||||
_, data = self._starport_bundle()
|
||||
if len(data) > DISCORD_FILE_LIMIT:
|
||||
_, data = self._starport_bundle(system_snapshot=False)
|
||||
return data
|
||||
if kind == "connection":
|
||||
return self._connection_zip()
|
||||
return self._controller_zip()
|
||||
|
||||
def _run(self, kind: str, platform: str, formatted_note: str) -> None:
|
||||
try:
|
||||
data = self._build_zip(kind)
|
||||
if len(data) > DISCORD_FILE_LIMIT:
|
||||
raise StageRejected("The log archive exceeds the upload limit. Use Download ZIP instead.")
|
||||
self._set(message="Uploading bundle")
|
||||
if self._post is None:
|
||||
import requests
|
||||
post = requests.post
|
||||
else:
|
||||
post = self._post
|
||||
response = post(
|
||||
self._url(),
|
||||
data=data,
|
||||
headers={
|
||||
"Content-Type": "application/zip",
|
||||
"X-Galaxy-Kind": kind,
|
||||
"X-Galaxy-Platform": platform,
|
||||
"X-Galaxy-Note": quote(formatted_note, safe=""),
|
||||
},
|
||||
allow_redirects=False,
|
||||
timeout=(5, 60),
|
||||
)
|
||||
if response.status_code == 404:
|
||||
raise StageRejected("Online log relay is updating. Use Download ZIP instead.")
|
||||
if response.status_code == 413:
|
||||
raise StageRejected("The log archive exceeds the upload limit. Use Download ZIP instead.")
|
||||
if response.status_code != 200:
|
||||
detail = _response_error(response)
|
||||
raise StageRejected(detail or "Could not stage logs for Discord. Use Download ZIP instead.")
|
||||
try:
|
||||
body = response.json()
|
||||
except (AttributeError, ValueError) as error:
|
||||
raise StageRejected("Invalid response from log relay. Use Download ZIP instead.") from error
|
||||
claim_url = body.get("claimUrl") if isinstance(body, dict) else None
|
||||
if not isinstance(claim_url, str) or not CLAIM_RE.fullmatch(claim_url):
|
||||
raise StageRejected("Invalid relay claim link. Use Download ZIP instead.")
|
||||
self._set(state="ready", claimUrl=claim_url, message="Logs uploaded. Continue to post your report on Discord.")
|
||||
except StageRejected as error:
|
||||
self._set(state="failed", claimUrl="", message=str(error)[:400])
|
||||
except Exception:
|
||||
self._set(state="failed", claimUrl="", message="Your comma could not reach the internet. Use Download ZIP instead.")
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Galaxy settings, device services and software management."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
from contextlib import nullcontext
|
||||
from http.cookies import SimpleCookie
|
||||
@@ -99,7 +100,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, log_relay_stager=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 +166,23 @@ 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
|
||||
|
||||
log_relay_stager_source = log_relay_stager
|
||||
log_relay_stager_lock = threading.Lock()
|
||||
|
||||
def log_stager():
|
||||
nonlocal log_relay_stager_source
|
||||
with log_relay_stager_lock:
|
||||
if log_relay_stager_source is None:
|
||||
from openpilot.starpilot.galaxy.controller_diagnostics import controller_capture
|
||||
from openpilot.starpilot.galaxy.log_relay_stage import LogRelayStager
|
||||
source = starport_logs()
|
||||
log_relay_stager_source = LogRelayStager(
|
||||
source.bundle,
|
||||
lambda: base64.b64decode(connection_capture(address_source.snapshot(), configuration_allowed=configuration_allowed)['zipBase64']),
|
||||
lambda: base64.b64decode(controller_capture()['zipBase64']),
|
||||
)
|
||||
return log_relay_stager_source
|
||||
software_source = software
|
||||
software_operations_source = software_operations
|
||||
software_lock = threading.Lock()
|
||||
@@ -1018,6 +1036,13 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
# immediately before sending potentially sensitive content.
|
||||
if self.require_session():
|
||||
self.json(200, result)
|
||||
elif path == '/api/logs/stage':
|
||||
if self.require_session():
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
else:
|
||||
self.json(200, log_stager().status(identity))
|
||||
elif path == '/api/starport/logs/send':
|
||||
if self.require_session():
|
||||
self.json(200, starport_log_sender().status())
|
||||
@@ -1753,7 +1778,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/companion/support-ticket',
|
||||
'/api/starport/logs/send', '/api/logs/stage',
|
||||
'/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',
|
||||
@@ -1770,7 +1795,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
self.json(405, {'error': 'Method unavailable'})
|
||||
return
|
||||
if (path.startswith(('/api/companion/', '/api/replay/', '/api/recordings/', '/api/connect/', '/api/cameras/', '/api/settings/', '/api/maps/',
|
||||
'/api/bluetooth/',
|
||||
'/api/bluetooth/', '/api/logs/',
|
||||
'/api/starport/', '/api/spotify/', '/api/controllers/', '/api/vehicle-selection/', '/api/toyota-tools/',
|
||||
'/api/models/', '/api/ui/', '/api/favorites/', '/api/sounds/', '/api/software/',
|
||||
'/api/drives/', '/api/navigation/', '/api/drive-state/', '/api/sentry/', '/api/crash-reports/')) and
|
||||
@@ -1828,50 +1853,23 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
else:
|
||||
self.json(200 if authorized() else 401, result if authorized() else {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if path == '/api/companion/support-ticket':
|
||||
import requests
|
||||
if path == '/api/logs/stage':
|
||||
identity = self.settings_session()
|
||||
if identity is None:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
if (not isinstance(payload, dict) or not isinstance(payload.get('code'), str) or
|
||||
not re.fullmatch(r'[0-9a-f]{16}', payload['code']) or payload.get('action') not in ('check', 'send')):
|
||||
self.json(400, {'error': 'Enter the code from the Discord request.'})
|
||||
return
|
||||
relay = 'https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/device'
|
||||
def relay_post(body):
|
||||
response = requests.post(relay, json=body, allow_redirects=False, timeout=(5, 30))
|
||||
if response.status_code == 410:
|
||||
raise LookupError()
|
||||
response.raise_for_status()
|
||||
if response.status_code != 200:
|
||||
raise ValueError()
|
||||
return response.json()
|
||||
from openpilot.starpilot.galaxy.log_relay_stage import StageBusy, StageRejected
|
||||
try:
|
||||
code = payload['code']
|
||||
ticket = relay_post({'action': 'check', 'code': code})
|
||||
kind = ticket['kind']
|
||||
if kind not in ('controller', 'connection'):
|
||||
raise ValueError()
|
||||
if payload['action'] == 'check':
|
||||
self.json(200, {'kind': kind, 'title': ticket['title']})
|
||||
return
|
||||
if kind == 'controller':
|
||||
from openpilot.starpilot.galaxy.controller_diagnostics import controller_capture
|
||||
capture = controller_capture()
|
||||
result = log_stager().start(payload, identity)
|
||||
except StageRejected as error:
|
||||
self.json(400, {'error': str(error)})
|
||||
except StageBusy as error:
|
||||
self.json(409, {'error': str(error)})
|
||||
else:
|
||||
if self.settings_session() == identity:
|
||||
self.json(202, result)
|
||||
else:
|
||||
capture = connection_capture(address_source.snapshot(), configuration_allowed=configuration_allowed)
|
||||
if self.settings_session() != identity:
|
||||
self.json(401, {'error': 'Sign in to Galaxy'})
|
||||
return
|
||||
result = relay_post({'action': 'send', 'code': code, 'archive': capture['zipBase64']})
|
||||
if result.get('sent') is not True:
|
||||
raise ValueError()
|
||||
self.json(200, {'sent': True})
|
||||
except LookupError:
|
||||
self.json(410, {'error': 'Code expired or incorrect. Reopen the request in Discord.'})
|
||||
except (requests.RequestException, OSError, RuntimeError, TypeError, ValueError):
|
||||
self.json(503, {'error': 'Could not confirm delivery. Check the comma internet connection and your Discord thread.'})
|
||||
return
|
||||
if path == '/api/settings/flm-finding/accept':
|
||||
identity = self.settings_session()
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright')
|
||||
const assert = require('node:assert/strict')
|
||||
|
||||
;(async () => {
|
||||
const browser = await chromium.launch({ headless: true })
|
||||
const page = await browser.newPage()
|
||||
const errors = []
|
||||
page.on('pageerror', error => errors.push(error.message))
|
||||
const base = process.env.GALAXY_URL || 'http://127.0.0.1:8765/'
|
||||
const CLAIM_URL = 'https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/claim/' + 'a'.repeat(64)
|
||||
const stagedPayloads = []
|
||||
let stageState = { state: 'idle', message: '', claimUrl: '', kind: '', available: true, fork: false, noteLimit: 200, modelLimit: 80 }
|
||||
|
||||
await page.route('**/data/runtime.json', route => route.fulfill({
|
||||
json: { schemaVersion: 1, monitor: 'local' },
|
||||
}))
|
||||
await page.route('**/api/**', async route => {
|
||||
const path = new URL(route.request().url()).pathname
|
||||
if (path === '/api/auth/session') {
|
||||
return route.fulfill({ json: { state: 'configured', authenticated: true, localAccess: true } })
|
||||
}
|
||||
if (path === '/api/device/state') {
|
||||
return route.fulfill({ json: { state: 'parked', maxAgeMs: 3000 } })
|
||||
}
|
||||
if (path === '/api/logs/stage') {
|
||||
if (route.request().method() === 'POST') {
|
||||
const body = route.request().postDataJSON()
|
||||
stagedPayloads.push(body)
|
||||
stageState = {
|
||||
...stageState,
|
||||
state: 'ready',
|
||||
claimUrl: CLAIM_URL,
|
||||
kind: body.kind,
|
||||
message: 'Logs uploaded. Continue to post your report on Discord.',
|
||||
}
|
||||
return route.fulfill({ status: 202, json: stageState })
|
||||
}
|
||||
return route.fulfill({ json: stageState })
|
||||
}
|
||||
if (path === '/api/starport/logs') {
|
||||
return route.fulfill({
|
||||
json: {
|
||||
schemaVersion: 1,
|
||||
sessions: [
|
||||
{
|
||||
name: 'session-000003.jsonl',
|
||||
size: 51712,
|
||||
modifiedAt: 1791354093,
|
||||
outcome: "projected, then failed: finding android auto: Could not find the car's Android Auto service: [Errno 112] Host is down",
|
||||
car: 'Honda T20',
|
||||
transport: 'wireless',
|
||||
trigger: 'car_connected',
|
||||
},
|
||||
],
|
||||
others: [{ name: 'car_ui.log', size: 4096, modifiedAt: 1791354093 }],
|
||||
},
|
||||
})
|
||||
}
|
||||
return route.fulfill({ status: 503, json: { error: 'Device unavailable. Reconnect to read this tool.' } })
|
||||
})
|
||||
|
||||
// 1. Themes x responsive viewports across all log reporting and entry routes
|
||||
const paths = ['/logs', '/logs/help', '/logs/help/connection', '/logs/help/controller', '/logs/starport', '/networks', '/bluetooth']
|
||||
for (const theme of ['dark', 'light']) {
|
||||
for (const width of [320, 390, 1280, 3440]) {
|
||||
await page.setViewportSize({ width, height: 900 })
|
||||
for (const path of paths) {
|
||||
await page.goto(base + '#' + path)
|
||||
await page.waitForTimeout(150)
|
||||
await page.evaluate(name => { document.documentElement.dataset.theme = name }, theme)
|
||||
await page.waitForTimeout(50)
|
||||
assert.equal(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
|
||||
false,
|
||||
`${theme} ${width}px ${path}: no horizontal overflow`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. #/logs catalog: Get help present, duplicate StarPort Logs tile removed
|
||||
await page.setViewportSize({ width: 390, height: 900 })
|
||||
await page.goto(base + '#/logs')
|
||||
await page.locator('.gx-menu-tile').first().waitFor()
|
||||
const tileTitles = await page.locator('.gx-menu-tile').evaluateAll(tiles => tiles.map(t => t.textContent))
|
||||
assert.ok(tileTitles.some(text => text.includes('Get help')), '#/logs includes Get help tile')
|
||||
assert.ok(!tileTitles.some(text => text.includes('StarPort Logs')), '#/logs has no separate StarPort Logs tile')
|
||||
|
||||
// 3. #/networks and #/bluetooth Connection logs panel -> #/logs/help/connection
|
||||
for (const routePath of ['#/networks', '#/bluetooth']) {
|
||||
await page.goto(base + routePath)
|
||||
const sendBtn = page.locator('.gx-connection-logs').getByRole('button', { name: 'Send logs', exact: true })
|
||||
await sendBtn.waitFor()
|
||||
const box = await sendBtn.boundingBox()
|
||||
assert.ok(box.height >= 44, `${routePath} Send logs meets 44px touch target (${box.height}px)`)
|
||||
await sendBtn.click()
|
||||
await page.waitForFunction(() => location.hash === '#/logs/help/connection')
|
||||
}
|
||||
|
||||
// 4. Desktop centering, 3 tabs, touch targets, Discord footer, and StarPort session disclosure
|
||||
await page.setViewportSize({ width: 1280, height: 900 })
|
||||
await page.goto(base + '#/logs/help')
|
||||
await page.locator('.gx-log-help__tab').first().waitFor()
|
||||
await page.waitForFunction(() => !document.querySelector('.gx-route-enter-active, .gx-route-leave-active'))
|
||||
const desktop = await page.locator('.gx-log-help').evaluate(section => {
|
||||
const bounds = section.getBoundingClientRect()
|
||||
const content = section.closest('.gx-content').getBoundingClientRect()
|
||||
return { width: bounds.width, center: bounds.left + bounds.width / 2, contentCenter: content.left + content.width / 2 }
|
||||
})
|
||||
assert.ok(desktop.width <= 960 && Math.abs(desktop.center - desktop.contentCenter) < 1, 'LogHelp is centered and bounded <=960px on desktop')
|
||||
|
||||
const tabTitles = await page.locator('.gx-log-help__tab strong').allTextContents()
|
||||
assert.deepEqual(tabTitles, ['StarPort / Car Screen', 'Phone App', 'Controller'])
|
||||
const discordHref = await page.locator('.gx-log-help__discord a').getAttribute('href')
|
||||
assert.equal(discordHref, 'https://firestar.link/discord')
|
||||
|
||||
// Touch targets >= 44px on StarPort tab + disclosure
|
||||
const starportTargets = await page.locator('.gx-log-help__tab, .gx-log-help__card button, .gx-log-help__card a.gx-btn, .gx-log-help__sessions > summary, .gx-log-help__discord a').evaluateAll(
|
||||
nodes => nodes.filter(n => n.offsetParent !== null).map(n => ({ text: n.textContent.trim(), height: n.getBoundingClientRect().height })),
|
||||
)
|
||||
assert.ok(starportTargets.every(item => item.height >= 43.5), `StarPort touch targets >=44px: ${JSON.stringify(starportTargets)}`)
|
||||
|
||||
await page.locator('.gx-log-help__sessions > summary').click()
|
||||
await page.locator('.gx-starport-log').first().waitFor()
|
||||
const dlBoxes = await page.locator('.gx-starport-log__download').evaluateAll(links => links.map(l => {
|
||||
const r = l.getBoundingClientRect()
|
||||
return { width: r.width, height: r.height, dl: l.getAttribute('download') }
|
||||
}))
|
||||
assert.ok(dlBoxes.every(b => b.width === 44 && b.height === 44), 'Session download links are 44x44px')
|
||||
assert.deepEqual(dlBoxes.map(b => b.dl), ['session-000003.jsonl', 'car_ui.log'])
|
||||
|
||||
// 5. Switch to Phone App on 390px, check chip targets, submit, claimUrl card, and reset
|
||||
await page.setViewportSize({ width: 390, height: 900 })
|
||||
await page.getByRole('tab', { name: /Phone App/ }).click()
|
||||
const androidChip = page.locator('.gx-log-help__pills').getByRole('button', { name: 'Android', exact: true })
|
||||
await androidChip.waitFor()
|
||||
const chipHeights = await page.locator('.gx-log-help__pills button.gx-chip').evaluateAll(btns => btns.map(b => b.getBoundingClientRect().height))
|
||||
assert.ok(chipHeights.every(h => h >= 43.5), `Phone chips meet 44px touch target (${chipHeights})`)
|
||||
await androidChip.click()
|
||||
await page.locator('#gx-log-help-note').fill('App keeps spinning on Wi-Fi')
|
||||
|
||||
// Block window.open popup side effect in headless run while still verifying claimUrl link renders
|
||||
await page.evaluate(() => { window.open = () => null })
|
||||
await page.getByRole('button', { name: 'Send phone app logs', exact: true }).click()
|
||||
const claimLink = page.locator('.gx-log-help__ready').getByRole('link', { name: /Continue on Discord support/ })
|
||||
await claimLink.waitFor()
|
||||
assert.equal(await claimLink.getAttribute('href'), CLAIM_URL)
|
||||
assert.deepEqual(stagedPayloads, [{ kind: 'connection', note: 'App keeps spinning on Wi-Fi', phone: 'android' }])
|
||||
|
||||
await page.getByRole('button', { name: 'Send another report', exact: true }).click()
|
||||
await page.locator('#gx-log-help-note').waitFor()
|
||||
assert.equal(await page.locator('.gx-log-help__ready').count(), 0)
|
||||
|
||||
assert.deepEqual(errors, [], 'LogHelp browser checks completed without runtime page errors')
|
||||
console.log('Passed LogHelp browser flow, responsiveness, touch targets, themes, and staging checks.')
|
||||
await browser.close()
|
||||
})().catch(error => { console.error(error); process.exit(1) })
|
||||
@@ -24,6 +24,9 @@ const { resolve } = require('node:path')
|
||||
json: { state: 'configured', authenticated: true, localAccess: true },
|
||||
})
|
||||
if (path === '/api/device/state') return route.fulfill({ json: { state: 'parked', maxAgeMs: 3000 } })
|
||||
if (path === '/api/logs/stage') return route.fulfill({
|
||||
json: { state: 'idle', message: '', claimUrl: '', kind: '', available: true, fork: false, noteLimit: 200, modelLimit: 80 },
|
||||
})
|
||||
if (path === '/api/starport/logs') return route.fulfill({ json: { schemaVersion: 1,
|
||||
sessions: [
|
||||
{ name: 'session-000003.jsonl', size: 51712, modifiedAt: 1791354093, outcome: "projected, then failed: finding android auto: Could not find the car's Android Auto service: [Errno 112] Host is down", car: 'Honda T20', transport: 'wireless', trigger: 'car_connected' },
|
||||
@@ -44,6 +47,7 @@ const { resolve } = require('node:path')
|
||||
|
||||
const paths = [...new Set(['/', '/tools', '/settings', '/developer/connect', '/cameras/events',
|
||||
'/cameras/sentry-settings', '/cameras/pip', '/cameras/vasm', '/theme_maker/starport',
|
||||
'/logs/help', '/logs/help/connection', '/logs/help/controller',
|
||||
'/logs/crashes', '/logs/starport', '/logs/monitor', '/logs/troubleshoot', '/logs/tmux', '/tuning/plots', '/tuning/flm',
|
||||
'/driving/longitudinal-curves', '/appearance', '/driving/conditional', '/driving/curve', '/driving/slc', '/driving/profiles', '/driving/traffic',
|
||||
...groups.filter(([page]) => page !== "standard").map(([page]) => '/driving/' + page), ...catalog.tools.map(tool => tool.path)])]
|
||||
@@ -81,6 +85,8 @@ const { resolve } = require('node:path')
|
||||
}
|
||||
await page.setViewportSize({ width: 390, height: 900 })
|
||||
await page.goto(base + '#/logs/starport')
|
||||
await page.locator('.gx-log-help__sessions > summary').waitFor()
|
||||
await page.locator('.gx-log-help__sessions > summary').click()
|
||||
await page.locator('.gx-starport-log').first().waitFor()
|
||||
await page.waitForFunction(() => !document.querySelector('.gx-route-enter-active, .gx-route-leave-active'))
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, 'Android Auto logs fit a phone viewport')
|
||||
@@ -93,14 +99,19 @@ const { resolve } = require('node:path')
|
||||
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'])
|
||||
for (const label of ['Phone App', 'Controller']) {
|
||||
await page.getByRole('tab', { name: new RegExp(label) }).click()
|
||||
await page.waitForTimeout(50)
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, `${label}: no phone overflow`)
|
||||
}
|
||||
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 => {
|
||||
const desktop = await page.locator('.gx-log-help').evaluate(section => {
|
||||
const bounds = section.getBoundingClientRect()
|
||||
const content = section.closest('.gx-content').getBoundingClientRect()
|
||||
return { width: bounds.width, center: bounds.left + bounds.width / 2, contentCenter: content.left + content.width / 2 }
|
||||
})
|
||||
assert.ok(desktop.width <= 960 && Math.abs(desktop.center - desktop.contentCenter) < 1, 'StarPort logs are centered and readable on desktop')
|
||||
assert.ok(desktop.width <= 960 && Math.abs(desktop.center - desktop.contentCenter) < 1, 'Log help is centered and readable on desktop')
|
||||
await page.setViewportSize({ width: 390, height: 900 })
|
||||
await page.goto(base + '#/settings')
|
||||
const manage = page.getByRole('button', { name: 'Manage', exact: true }).first()
|
||||
|
||||
@@ -5,11 +5,13 @@ import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
|
||||
from openpilot.starpilot.galaxy.log_relay_stage import LogRelayStager
|
||||
from openpilot.starpilot.galaxy.server import make_server
|
||||
from openpilot.starpilot.galaxy.settings import AuthorityContext, SettingsGateway
|
||||
|
||||
@@ -25,12 +27,25 @@ class DiagnosticHTTPTest(unittest.TestCase):
|
||||
self.console = SimpleNamespace(snapshot=lambda: self.record('console', {'available': True, 'text': 'actual console',
|
||||
'truncated': False, 'pane': 'comma:0.0', 'reason': ''}))
|
||||
self.settings = SimpleNamespace(diagnostics=lambda: self.record('settings', {'schemaVersion': 1, 'sections': []}))
|
||||
self.stage_posts = []
|
||||
self.stage_response = None
|
||||
self.stager = LogRelayStager(
|
||||
lambda **_kw: ('starport-logs.zip', b'PK\x03\x04' + b'0' * 32),
|
||||
lambda: b'PK\x03\x04' + b'1' * 32,
|
||||
lambda: b'PK\x03\x04' + b'2' * 32,
|
||||
post=self._stage_post,
|
||||
official=lambda: True,
|
||||
)
|
||||
self.server = make_server(port=0, owner=self.access, parked=lambda: True, local_access=self.addresses,
|
||||
tmux_live=self.console, settings=self.settings)
|
||||
tmux_live=self.console, settings=self.settings, log_relay_stager=self.stager)
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, kwargs={'poll_interval': .01}, daemon=True)
|
||||
self.thread.start()
|
||||
self.cookie = ''
|
||||
|
||||
def _stage_post(self, url, **kwargs):
|
||||
self.stage_posts.append((url, kwargs))
|
||||
return self.stage_response
|
||||
|
||||
def tearDown(self):
|
||||
self.server.shutdown()
|
||||
self.thread.join(2)
|
||||
@@ -57,7 +72,7 @@ class DiagnosticHTTPTest(unittest.TestCase):
|
||||
connection.close()
|
||||
|
||||
def test_real_http_routes_authentication_and_no_mutations(self):
|
||||
for path in ('/api/local-access', '/api/local-access/capture', '/api/tmux/live', '/api/troubleshoot'):
|
||||
for path in ('/api/local-access', '/api/local-access/capture', '/api/tmux/live', '/api/troubleshoot', '/api/logs/stage'):
|
||||
self.assertEqual(self.request(path, remote=True)[0], 401)
|
||||
self.assertEqual(self.calls, [])
|
||||
status, _, self.cookie = self.request('/api/auth/session')
|
||||
@@ -73,21 +88,35 @@ class DiagnosticHTTPTest(unittest.TestCase):
|
||||
self.assertNotEqual(self.request('/api/tmux/live', method='POST', payload={})[0], 200)
|
||||
self.assertEqual(len(self.calls), before)
|
||||
|
||||
def test_support_code_captures_on_device_and_confirms_delivery(self):
|
||||
def test_log_stage_routes_require_session_and_stage_bundle(self):
|
||||
self.assertEqual(self.request('/api/logs/stage', method='POST', payload={'kind': 'starport', 'note': 'Blank'}, remote=True)[0], 401)
|
||||
_, _, self.cookie = self.request('/api/auth/session')
|
||||
code = 'ab12' * 4
|
||||
path = '/api/companion/support-ticket'
|
||||
def post(action):
|
||||
return self.request(path, method='POST', payload={'code': code, 'action': action})
|
||||
ticket = Mock(status_code=200)
|
||||
ticket.json.return_value = {'title': 'Lost network', 'kind': 'connection'}
|
||||
receipt = Mock(status_code=200)
|
||||
receipt.json.return_value = {'sent': True}
|
||||
with patch('requests.post', side_effect=[ticket, ticket, receipt]) as relay:
|
||||
self.assertEqual(post('check')[:2], (200, {'kind': 'connection', 'title': 'Lost network'}))
|
||||
self.assertEqual(post('send')[:2], (200, {'sent': True}))
|
||||
self.assertTrue(relay.call_args.kwargs['json']['archive'].startswith('UEsD'))
|
||||
self.assertFalse(relay.call_args.kwargs['allow_redirects'])
|
||||
claim_url = 'https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/claim/' + ('a' * 64)
|
||||
self.stage_response = Mock(status_code=200)
|
||||
self.stage_response.json.return_value = {'claimUrl': claim_url}
|
||||
status, idle, _ = self.request('/api/logs/stage')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(idle['state'], 'idle')
|
||||
self.assertTrue(idle['available'])
|
||||
|
||||
status, accepted, _ = self.request('/api/logs/stage', method='POST',
|
||||
payload={'kind': 'connection', 'phone': 'ios', 'note': 'Lost network'})
|
||||
self.assertEqual(status, 202)
|
||||
self.assertEqual(accepted['kind'], 'connection')
|
||||
|
||||
deadline = time.monotonic() + 2
|
||||
state = accepted
|
||||
while state['state'] == 'staging' and time.monotonic() < deadline:
|
||||
time.sleep(0.01)
|
||||
_, state, _ = self.request('/api/logs/stage')
|
||||
self.assertEqual(state['state'], 'ready')
|
||||
self.assertEqual(state['claimUrl'], claim_url)
|
||||
self.assertEqual(len(self.stage_posts), 1)
|
||||
_, kwargs = self.stage_posts[0]
|
||||
self.assertFalse(kwargs['allow_redirects'])
|
||||
self.assertEqual(kwargs['headers']['X-Galaxy-Kind'], 'connection')
|
||||
self.assertEqual(kwargs['headers']['X-Galaxy-Platform'], 'ios')
|
||||
self.assertIn('Lost%20network', kwargs['headers']['X-Galaxy-Note'])
|
||||
|
||||
def test_authenticated_forwarded_transport_uses_same_tools(self):
|
||||
status, _, self.cookie = self.request('/api/auth/login', method='POST', payload={'password': 'test-password-123'}, remote=True)
|
||||
|
||||
@@ -69,43 +69,48 @@ assert.ok(!GalaxyPage.template.includes('<LocalAccess'))
|
||||
compile(GalaxyPage.template, { decodeEntities: value => value.replaceAll('&', '&') })
|
||||
console.log('Galaxy local access remains independent of app installation')
|
||||
|
||||
const capture = { onUnauthorized() { assert.fail('unexpected sign-in request') },
|
||||
const capture = { panel: false, controller: false, onUnauthorized() { assert.fail('unexpected sign-in request') },
|
||||
...ConnectionLogs.data(), ...ConnectionLogs.methods }
|
||||
const originalFetch = globalThis.fetch
|
||||
const originalDocument = globalThis.document
|
||||
const downloads = []
|
||||
globalThis.document = {
|
||||
createElement(tag) {
|
||||
assert.equal(tag, 'a')
|
||||
return { href: '', download: '', click() { downloads.push({ href: this.href, download: this.download }) }, remove() {} }
|
||||
},
|
||||
body: { appendChild() {} },
|
||||
}
|
||||
try {
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, './api/local-access/capture')
|
||||
assert.equal(options.credentials, 'same-origin')
|
||||
return { ok: true, json: async () => ({ schemaVersion: 1, zipBase64: 'UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA' }) }
|
||||
}
|
||||
await capture.captureConnectionLogs()
|
||||
assert.equal(capture.capture.type, 'application/zip')
|
||||
assert.equal(capture.captureRequest, null)
|
||||
capture.resetCapture()
|
||||
assert.equal(capture.capture, null)
|
||||
} finally { globalThis.fetch = originalFetch }
|
||||
const thread = { ...ConnectionLogs.data(), ...ConnectionLogs.methods, supportCode: 'AB12 CD34-EF56' }
|
||||
try {
|
||||
await capture.downloadConnectionLogs()
|
||||
assert.equal(capture.captureBusy, false)
|
||||
assert.equal(capture.captureError, '')
|
||||
assert.equal(downloads.at(-1).download, 'starpilot-connection-logs.zip')
|
||||
|
||||
const controllerCapture = { panel: true, controller: true, onUnauthorized() { assert.fail('unexpected sign-in request') },
|
||||
...ConnectionLogs.data(), ...ConnectionLogs.methods }
|
||||
globalThis.fetch = async (url, options) => {
|
||||
assert.equal(url, './api/companion/support-ticket')
|
||||
const { action, code } = JSON.parse(options.body)
|
||||
assert.equal(code, 'ab12cd34ef56')
|
||||
const body = action === 'check' ? { title: 'Lost network', kind: 'connection' } : { sent: true }
|
||||
return { ok: true, json: async () => body }
|
||||
assert.equal(url, './api/controllers/log/capture')
|
||||
assert.equal(options.credentials, 'same-origin')
|
||||
return { ok: true, json: async () => ({ schemaVersion: 1, zipBase64: 'UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA' }) }
|
||||
}
|
||||
await thread.threadAction('check')
|
||||
assert.equal(thread.supportTicket.title, 'Lost network')
|
||||
assert.equal(thread.supportSent, false)
|
||||
await thread.threadAction('send')
|
||||
assert.equal(thread.supportSent, true)
|
||||
} finally { globalThis.fetch = originalFetch }
|
||||
await controllerCapture.downloadConnectionLogs()
|
||||
assert.equal(downloads.at(-1).download, 'starpilot-controller-logs.zip')
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch
|
||||
globalThis.document = originalDocument
|
||||
}
|
||||
assert.equal(LocalAccess.components.ConnectionLogs, ConnectionLogs)
|
||||
assert.ok(LocalAccess.template.includes("mode === 'local'"))
|
||||
compile(ConnectionLogs.template, { decodeEntities: value => value })
|
||||
assert.ok(ConnectionLogs.template.includes('Send to existing Discord thread'))
|
||||
assert.ok(ConnectionLogs.components.ReportingGuide.template.includes('#submit-logs-through-discord'))
|
||||
assert.ok(ConnectionLogs.components.ReportingGuide.template.includes('#report-a-problem-through-discord'))
|
||||
assert.match(ConnectionLogs.template, /<details[^>]*><summary><small>Manual ZIP download<\/small><\/summary>[\s\S]*Download ZIP<\/button>\s*<\/details>/)
|
||||
assert.ok(ConnectionLogs.template.includes('Send logs'))
|
||||
assert.ok(ConnectionLogs.template.includes('Download connection ZIP'))
|
||||
assert.equal(ConnectionLogs.components.ReportingGuide, undefined)
|
||||
for (const endpoint of ['./api/galaxy/qr.svg', './api/galaxy/session/qr.svg']) {
|
||||
const qr = {endpoint, ...RemoteQR.data(), ...RemoteQR.methods}
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { compile } from "../web/vendor/vue/vue.esm-browser.js"
|
||||
|
||||
globalThis.location = { hash: "#/logs/help" }
|
||||
|
||||
const { LOG_TOPICS, LogHelp, LogStageClient, MODEL_LIMIT, NOTE_LIMIT, STAGE_URL, captureZip, downloadCaptureZip } = await import("../web/js/log-help.js")
|
||||
const { Logs } = await import("../web/js/logs.js")
|
||||
|
||||
// 1. Topic catalog & template verification (Option A: only 3 topics, zero legacy forms)
|
||||
assert.deepEqual(LOG_TOPICS.map(t => t.id), ["starport", "connection", "controller"])
|
||||
compile(LogHelp.template, { decodeEntities: v => v.replaceAll("&", "&") })
|
||||
compile(Logs.template, { decodeEntities: v => v.replaceAll("&", "&") })
|
||||
assert.ok(LogHelp.template.includes("https://firestar.link/discord"))
|
||||
assert.ok(LogHelp.template.includes("Individual session files"))
|
||||
assert.ok(!LogHelp.template.includes("Connecting via"))
|
||||
assert.ok(!LogHelp.template.includes("Driving behavior report"))
|
||||
|
||||
// 2. Logs route resolution for /logs/help, /logs/help/*, and /logs/starport
|
||||
for (const [path, expectedRoute, expectedTopic] of [
|
||||
["/logs", false, "starport"],
|
||||
["/logs/help", true, "starport"],
|
||||
["/logs/starport", true, "starport"],
|
||||
["/logs/help/connection", true, "connection"],
|
||||
["/logs/help/controller", true, "controller"],
|
||||
]) {
|
||||
assert.equal(Logs.computed.helpRoute.call({ path }), expectedRoute, `${path} helpRoute`)
|
||||
assert.equal(Logs.computed.helpTopic.call({ path }), expectedTopic, `${path} helpTopic`)
|
||||
}
|
||||
|
||||
// 3. LogStageClient lifecycle, validation, polling, ready callback, reset, and 401
|
||||
const CLAIM = "https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/claim/" + "f".repeat(64)
|
||||
const state = { state: "idle", message: "", claimUrl: "", kind: "", error: "" }
|
||||
const readyUrls = []
|
||||
const scheduled = []
|
||||
const requests = []
|
||||
let unauthorizedCount = 0
|
||||
|
||||
let pollStep = 0
|
||||
const client = new LogStageClient({
|
||||
publish: update => Object.assign(state, update),
|
||||
unauthorized: () => { unauthorizedCount++ },
|
||||
schedule: (fn, ms) => { scheduled.push({ fn, ms }); return scheduled.length },
|
||||
cancel: () => {},
|
||||
onReady: url => readyUrls.push(url),
|
||||
fetcher: async (url, options) => {
|
||||
requests.push({ url, options })
|
||||
if (options.method === "POST") {
|
||||
return { ok: true, status: 202, json: async () => ({ state: "staging", message: "Collecting logs", claimUrl: "", kind: JSON.parse(options.body).kind }) }
|
||||
}
|
||||
pollStep++
|
||||
if (pollStep === 1) {
|
||||
return { ok: true, status: 200, json: async () => ({ state: "idle", message: "", claimUrl: "", kind: "", available: true, fork: false, noteLimit: NOTE_LIMIT, modelLimit: MODEL_LIMIT }) }
|
||||
}
|
||||
return { ok: true, status: 200, json: async () => ({ state: "ready", message: "Logs uploaded", claimUrl: CLAIM, kind: "connection", available: true }) }
|
||||
},
|
||||
})
|
||||
|
||||
await client.start()
|
||||
assert.equal(requests[0].url, STAGE_URL)
|
||||
assert.equal(requests[0].options.cache, "no-store")
|
||||
assert.equal(requests[0].options.credentials, "same-origin")
|
||||
assert.equal(scheduled.length, 0, "idle state does not schedule polling")
|
||||
|
||||
assert.equal(await client.stage({ kind: "unknown", note: "hi" }), false)
|
||||
assert.match(state.error, /Choose what/)
|
||||
assert.equal(await client.stage({ kind: "starport", note: " " }), false)
|
||||
assert.match(state.error, /short note/)
|
||||
assert.equal(await client.stage({ kind: "starport", note: "a".repeat(NOTE_LIMIT + 1) }), false)
|
||||
assert.match(state.error, /200 characters/)
|
||||
assert.equal(await client.stage({ kind: "connection", phone: "web", note: "hi" }), false)
|
||||
assert.match(state.error, /iPhone or Android/)
|
||||
assert.equal(await client.stage({ kind: "controller", model: " ", note: "hi" }), false)
|
||||
assert.match(state.error, /make and model/)
|
||||
assert.equal(await client.stage({ kind: "controller", model: "m".repeat(MODEL_LIMIT + 1), note: "hi" }), false)
|
||||
assert.match(state.error, /80 characters/)
|
||||
assert.equal(requests.length, 1, "client-side validation prevents network calls")
|
||||
|
||||
assert.equal(await client.stage({ kind: "connection", phone: "ios", note: "Stuck connecting" }), true)
|
||||
const postBody = JSON.parse(requests.at(-1).options.body)
|
||||
assert.deepEqual(postBody, { kind: "connection", note: "Stuck connecting", phone: "ios" })
|
||||
assert.equal(state.state, "staging")
|
||||
assert.equal(scheduled.length, 1)
|
||||
|
||||
await client.poll()
|
||||
assert.equal(state.state, "ready")
|
||||
assert.equal(state.claimUrl, CLAIM)
|
||||
assert.deepEqual(readyUrls, [CLAIM])
|
||||
|
||||
client.reset(CLAIM)
|
||||
assert.equal(state.state, "idle")
|
||||
assert.equal(state.claimUrl, "")
|
||||
await client.poll()
|
||||
assert.equal(state.state, "idle", "dismissed claimUrl stays hidden on subsequent polls")
|
||||
assert.equal(readyUrls.length, 1)
|
||||
|
||||
client.fetcher = async () => ({ status: 401 })
|
||||
await client.poll()
|
||||
assert.equal(unauthorizedCount, 1)
|
||||
assert.equal(client.active, false)
|
||||
|
||||
// 4. captureZip and downloadCaptureZip contracts
|
||||
const originalDocument = globalThis.document
|
||||
const clicked = []
|
||||
globalThis.document = {
|
||||
createElement(tag) {
|
||||
assert.equal(tag, "a")
|
||||
return { href: "", download: "", click() { clicked.push(this.download) }, remove() {} }
|
||||
},
|
||||
body: { appendChild() {} },
|
||||
}
|
||||
try {
|
||||
const validZip = "UEsDBAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
const okConnection = await downloadCaptureZip("connection", {
|
||||
fetcher: async url => {
|
||||
assert.equal(url, "./api/local-access/capture")
|
||||
return { ok: true, status: 200, headers: { get: () => "application/json" }, json: async () => ({ schemaVersion: 1, zipBase64: validZip }) }
|
||||
},
|
||||
})
|
||||
assert.equal(okConnection, true)
|
||||
const okController = await downloadCaptureZip("controller", {
|
||||
fetcher: async url => {
|
||||
assert.equal(url, "./api/controllers/log/capture")
|
||||
return { ok: true, status: 200, headers: { get: () => "application/json" }, json: async () => ({ schemaVersion: 1, zipBase64: validZip }) }
|
||||
},
|
||||
})
|
||||
assert.equal(okController, true)
|
||||
assert.deepEqual(clicked, ["starpilot-connection-logs.zip", "starpilot-controller-logs.zip"])
|
||||
|
||||
await assert.rejects(
|
||||
() => captureZip("connection", { fetcher: async () => ({ ok: true, status: 200, headers: { get: () => "application/json" }, json: async () => ({ schemaVersion: 1, zipBase64: btoa("not-a-zip-header-at-all-123456") }) }) }),
|
||||
/Invalid diagnostic capture/,
|
||||
)
|
||||
} finally {
|
||||
globalThis.document = originalDocument
|
||||
}
|
||||
|
||||
console.log("LogHelp UI routing, LogStageClient, and captureZip checks passed")
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Tests for one-way log relay staging and Galaxy /api/logs/stage endpoints."""
|
||||
|
||||
import http.client
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
from urllib.parse import unquote
|
||||
|
||||
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
|
||||
from openpilot.starpilot.galaxy.log_relay_stage import (
|
||||
CLAIM_RE,
|
||||
MODEL_LIMIT,
|
||||
NOTE_LIMIT,
|
||||
STAGE_URL,
|
||||
LogRelayStager,
|
||||
StageBusy,
|
||||
StageRejected,
|
||||
clean_stage_request,
|
||||
)
|
||||
from openpilot.starpilot.galaxy.server import make_server
|
||||
from openpilot.starpilot.galaxy.starport_send import DISCORD_FILE_LIMIT
|
||||
|
||||
VALID_CLAIM = "https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/claim/" + ("a1b2" * 16)
|
||||
SAMPLE_ZIP = b"PK\x03\x04" + b"\x00" * 32
|
||||
|
||||
|
||||
def wait_until(predicate, timeout=2.0):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
value = predicate()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(0.01)
|
||||
raise AssertionError("Timed out waiting for condition")
|
||||
|
||||
|
||||
class CleanStageRequestTest(unittest.TestCase):
|
||||
def test_valid_requests_per_kind(self):
|
||||
self.assertEqual(
|
||||
clean_stage_request({"kind": "starport", "note": " Black\nscreen\ton start "}),
|
||||
("starport", "android", "Black screen on start"),
|
||||
)
|
||||
self.assertEqual(
|
||||
clean_stage_request({"kind": "connection", "phone": "ios", "note": "App keeps spinning"}),
|
||||
("connection", "ios", "[iPhone] App keeps spinning"),
|
||||
)
|
||||
self.assertEqual(
|
||||
clean_stage_request({"kind": "connection", "phone": "android", "note": "Stuck on pairing"}),
|
||||
("connection", "android", "[Android] Stuck on pairing"),
|
||||
)
|
||||
self.assertEqual(
|
||||
clean_stage_request({"kind": "controller", "model": " 8BitDo\tMicro ", "note": "No response"}),
|
||||
("controller", "ios", "Controller (8BitDo Micro): No response"),
|
||||
)
|
||||
|
||||
def test_rejects_invalid_payloads(self):
|
||||
invalid = [
|
||||
None,
|
||||
[],
|
||||
{},
|
||||
{"kind": "crash", "note": "nope"},
|
||||
{"kind": "starport", "note": " "},
|
||||
{"kind": "starport", "note": 123},
|
||||
{"kind": "starport", "note": "x" * (NOTE_LIMIT + 1)},
|
||||
{"kind": "starport", "note": "ok", "phone": "ios"},
|
||||
{"kind": "starport", "note": "ok", "extra": 1},
|
||||
{"kind": "connection", "note": "ok"},
|
||||
{"kind": "connection", "phone": "windows", "note": "ok"},
|
||||
{"kind": "controller", "note": "ok"},
|
||||
{"kind": "controller", "model": "\n\t ", "note": "ok"},
|
||||
{"kind": "controller", "model": "m" * (MODEL_LIMIT + 1), "note": "ok"},
|
||||
]
|
||||
for payload in invalid:
|
||||
with self.subTest(payload=payload):
|
||||
with self.assertRaises(StageRejected):
|
||||
clean_stage_request(payload)
|
||||
|
||||
|
||||
class LogRelayStagerTest(unittest.TestCase):
|
||||
def test_stages_starport_connection_and_controller_bundles(self):
|
||||
calls = []
|
||||
|
||||
def fake_post(url, data, headers, allow_redirects, timeout):
|
||||
calls.append({"url": url, "data": data, "headers": headers, "allow_redirects": allow_redirects, "timeout": timeout})
|
||||
response = Mock(status_code=200)
|
||||
response.json.return_value = {"claimUrl": VALID_CLAIM}
|
||||
return response
|
||||
|
||||
stager = LogRelayStager(
|
||||
lambda **_kw: ("starport-logs.zip", b"starport-zip"),
|
||||
lambda: b"connection-zip",
|
||||
lambda: b"controller-zip",
|
||||
post=fake_post,
|
||||
official=lambda: False,
|
||||
)
|
||||
initial = stager.status()
|
||||
self.assertEqual(initial["state"], "idle")
|
||||
self.assertTrue(initial["available"])
|
||||
self.assertTrue(initial["fork"])
|
||||
self.assertEqual(initial["noteLimit"], NOTE_LIMIT)
|
||||
self.assertEqual(initial["modelLimit"], MODEL_LIMIT)
|
||||
|
||||
cases = [
|
||||
({"kind": "starport", "note": "Dropped after 2m"}, b"starport-zip", "starport", "android", "Dropped after 2m"),
|
||||
({"kind": "connection", "phone": "android", "note": "mDNS fail"}, b"connection-zip", "connection", "android", "[Android] mDNS fail"),
|
||||
({"kind": "controller", "model": "Xbox Series", "note": "D-pad dead"}, b"controller-zip", "controller", "ios", "Controller (Xbox Series): D-pad dead"),
|
||||
]
|
||||
for payload, expected_zip, expected_kind, expected_platform, expected_note in cases:
|
||||
with self.subTest(kind=expected_kind):
|
||||
started = stager.start(payload)
|
||||
self.assertEqual(started["state"], "staging")
|
||||
ready = wait_until(lambda: stager.status() if stager.status()["state"] == "ready" else None)
|
||||
self.assertEqual(ready["claimUrl"], VALID_CLAIM)
|
||||
self.assertEqual(ready["kind"], expected_kind)
|
||||
self.assertTrue(CLAIM_RE.fullmatch(ready["claimUrl"]))
|
||||
call = calls[-1]
|
||||
self.assertEqual(call["url"], STAGE_URL)
|
||||
self.assertEqual(call["data"], expected_zip)
|
||||
self.assertFalse(call["allow_redirects"])
|
||||
self.assertEqual(call["headers"]["Content-Type"], "application/zip")
|
||||
self.assertEqual(call["headers"]["X-Galaxy-Kind"], expected_kind)
|
||||
self.assertEqual(call["headers"]["X-Galaxy-Platform"], expected_platform)
|
||||
self.assertEqual(unquote(call["headers"]["X-Galaxy-Note"]), expected_note)
|
||||
|
||||
def test_retries_starport_without_system_snapshot_when_oversize(self):
|
||||
seen_args = []
|
||||
posts = []
|
||||
|
||||
def build_starport(*, system_snapshot=True):
|
||||
seen_args.append(system_snapshot)
|
||||
return ("starport-logs.zip", b"x" * (DISCORD_FILE_LIMIT + 1) if system_snapshot else b"small-zip")
|
||||
|
||||
def fake_post(url, data, **_kwargs):
|
||||
posts.append(data)
|
||||
response = Mock(status_code=200)
|
||||
response.json.return_value = {"claimUrl": VALID_CLAIM}
|
||||
return response
|
||||
|
||||
stager = LogRelayStager(build_starport, lambda: b"c", lambda: b"k", post=fake_post, official=lambda: True)
|
||||
stager.start({"kind": "starport", "note": "Trim snapshot"})
|
||||
ready = wait_until(lambda: stager.status() if stager.status()["state"] == "ready" else None)
|
||||
self.assertEqual(seen_args, [True, False])
|
||||
self.assertEqual(posts, [b"small-zip"])
|
||||
self.assertFalse(ready["fork"])
|
||||
|
||||
def test_failures_surface_clear_fallback_messages(self):
|
||||
def run_failure(response_or_exc, *, zip_bytes=b"zip"):
|
||||
def fake_post(*_args, **_kwargs):
|
||||
if isinstance(response_or_exc, Exception):
|
||||
raise response_or_exc
|
||||
return response_or_exc
|
||||
|
||||
stager = LogRelayStager(lambda **_kw: ("s.zip", zip_bytes), lambda: zip_bytes, lambda: zip_bytes, post=fake_post)
|
||||
stager.start({"kind": "connection", "phone": "ios", "note": "Fail test"})
|
||||
return wait_until(lambda: stager.status() if stager.status()["state"] == "failed" else None)
|
||||
|
||||
r404 = Mock(status_code=404)
|
||||
self.assertIn("updating", run_failure(r404)["message"])
|
||||
|
||||
r413 = Mock(status_code=413)
|
||||
self.assertIn("upload limit", run_failure(r413)["message"])
|
||||
self.assertIn("upload limit", run_failure(Mock(status_code=200), zip_bytes=b"x" * (DISCORD_FILE_LIMIT + 1))["message"])
|
||||
|
||||
r429 = Mock(status_code=429)
|
||||
r429.json.return_value = {"error": "Too many uploads from this IP"}
|
||||
self.assertEqual(run_failure(r429)["message"], "Too many uploads from this IP")
|
||||
|
||||
bad_claim = Mock(status_code=200)
|
||||
bad_claim.json.return_value = {"claimUrl": "https://evil.example/claim/" + ("a" * 64)}
|
||||
self.assertIn("Invalid relay claim link", run_failure(bad_claim)["message"])
|
||||
|
||||
bad_json = Mock(status_code=200)
|
||||
bad_json.json.side_effect = ValueError("not json")
|
||||
self.assertIn("Invalid response", run_failure(bad_json)["message"])
|
||||
|
||||
self.assertIn("internet", run_failure(RuntimeError("dns failed"))["message"])
|
||||
|
||||
def test_busy_and_unavailable_guards(self):
|
||||
entered = threading.Event()
|
||||
release = threading.Event()
|
||||
|
||||
def slow_post(*_args, **_kwargs):
|
||||
entered.set()
|
||||
release.wait(2)
|
||||
response = Mock(status_code=200)
|
||||
response.json.return_value = {"claimUrl": VALID_CLAIM}
|
||||
return response
|
||||
|
||||
stager = LogRelayStager(lambda **_kw: ("s.zip", b"zip"), lambda: b"c", lambda: b"k", post=slow_post)
|
||||
stager.start({"kind": "starport", "note": "First"})
|
||||
self.assertTrue(entered.wait(2))
|
||||
try:
|
||||
with self.assertRaises(StageBusy):
|
||||
stager.start({"kind": "starport", "note": "Second"})
|
||||
finally:
|
||||
release.set()
|
||||
wait_until(lambda: stager.status()["state"] == "ready")
|
||||
|
||||
disabled = LogRelayStager(lambda **_kw: ("s.zip", b"zip"), lambda: b"c", lambda: b"k", stage_url="")
|
||||
self.assertFalse(disabled.status()["available"])
|
||||
with self.assertRaises(StageRejected):
|
||||
disabled.start({"kind": "starport", "note": "Disabled"})
|
||||
|
||||
|
||||
class LogStageHTTPTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.access = GalaxyAccessOwner(Path(self.temp.name))
|
||||
self.access.configure("test-password-123", lambda: True)
|
||||
self.release = threading.Event()
|
||||
self.entered = threading.Event()
|
||||
|
||||
def slow_or_fast_post(*_args, **_kwargs):
|
||||
self.entered.set()
|
||||
self.release.wait(2)
|
||||
response = Mock(status_code=200)
|
||||
response.json.return_value = {"claimUrl": VALID_CLAIM}
|
||||
return response
|
||||
|
||||
self.stager = LogRelayStager(
|
||||
lambda **_kw: ("starport-logs.zip", SAMPLE_ZIP),
|
||||
lambda: SAMPLE_ZIP,
|
||||
lambda: SAMPLE_ZIP,
|
||||
post=slow_or_fast_post,
|
||||
official=lambda: True,
|
||||
)
|
||||
self.server = make_server(port=0, owner=self.access, parked=lambda: True, log_relay_stager=self.stager)
|
||||
self.addCleanup(self.server.server_close)
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True)
|
||||
self.thread.start()
|
||||
self.addCleanup(lambda: (self.server.shutdown(), self.thread.join(2)))
|
||||
self.cookie = ""
|
||||
|
||||
def request(self, path, *, method="GET", payload=None, origin=None, remote=False):
|
||||
headers = {"Origin": origin or f"http://127.0.0.1:{self.server.server_port}", "Content-Type": "application/json"}
|
||||
if self.cookie:
|
||||
headers["Cookie"] = self.cookie
|
||||
if remote:
|
||||
headers["Forwarded"] = "for=203.0.113.9"
|
||||
conn = http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=4)
|
||||
try:
|
||||
conn.request(method, path, None if payload is None else json.dumps(payload), headers)
|
||||
resp = conn.getresponse()
|
||||
cookie = resp.getheader("Set-Cookie")
|
||||
return resp.status, json.loads(resp.read()), cookie.split(";")[0] if cookie else ""
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def test_http_validation_busy_status_and_auth(self):
|
||||
self.assertEqual(self.request("/api/logs/stage", remote=True)[0], 401)
|
||||
_, _, self.cookie = self.request("/api/auth/session")
|
||||
self.assertEqual(self.request("/api/logs/stage", origin="https://other.example")[0], 403)
|
||||
self.assertEqual(self.request("/api/logs/stage", method="POST", payload={"kind": "starport", "note": ""})[0], 400)
|
||||
|
||||
status, body, _ = self.request("/api/logs/stage", method="POST", payload={"kind": "controller", "model": "DualSense", "note": "Not detected"})
|
||||
self.assertEqual(status, 202)
|
||||
self.assertEqual(body["state"], "staging")
|
||||
self.assertTrue(self.entered.wait(2))
|
||||
self.assertEqual(self.request("/api/logs/stage", method="POST", payload={"kind": "starport", "note": "Busy"})[0], 409)
|
||||
self.release.set()
|
||||
|
||||
ready = wait_until(lambda: res if (res := self.request("/api/logs/stage")[1])["state"] == "ready" else None)
|
||||
self.assertEqual(ready["claimUrl"], VALID_CLAIM)
|
||||
first_cookie, self.cookie = self.cookie, ""
|
||||
_, _, self.cookie = self.request("/api/auth/session")
|
||||
self.assertNotEqual(self.cookie, first_cookie)
|
||||
self.assertEqual(self.request("/api/logs/stage")[1]["claimUrl"], "")
|
||||
self.cookie = first_cookie
|
||||
self.assertEqual(self.request("/api/logs/stage")[1]["claimUrl"], VALID_CLAIM)
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -65,7 +65,7 @@ try {
|
||||
|
||||
// Compile the changed page templates to catch invalid nesting or Vue directives.
|
||||
for (const name of ['models', 'settings', 'navigation', 'starport', 'spotify', 'bluetooth', 'cameras',
|
||||
'home', 'system-monitor', 'sentry', 'vasm', 'pip', 'galaxy', 'networks', 'tools', 'logs', 'software-status', 'driving',
|
||||
'home', 'system-monitor', 'sentry', 'vasm', 'pip', 'galaxy', 'networks', 'tools', 'logs', 'log-help', 'software-status', 'driving',
|
||||
'longitudinal-curves', 'flm', 'record-history', 'onroad-layout-template', 'settings-recovery', 'diagnostic-tools']) {
|
||||
const source = readFileSync(new URL(`../web/js/${name}.js`, import.meta.url), 'utf8')
|
||||
const templates = [...source.matchAll(/(?:template:\s*|ONROAD_LAYOUT_TEMPLATE = )`([\s\S]*?)`/g)]
|
||||
|
||||
@@ -1917,3 +1917,101 @@ progress { max-width: 100%; accent-color: var(--primary); }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.gx-select-menu { transition: none; }
|
||||
}
|
||||
|
||||
.gx-log-help { width: min(100%, 960px); margin-inline: auto; }
|
||||
.gx-log-help__tabs { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--sp-3); }
|
||||
@media (max-width: 720px) {
|
||||
.gx-log-help__tabs { grid-template-columns: minmax(0, 1fr); gap: var(--sp-2); }
|
||||
}
|
||||
.gx-card.gx-log-help__tab {
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
color: var(--on-surface);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
min-height: 64px;
|
||||
min-width: 0;
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
border: 1px solid var(--glass-border);
|
||||
transition: background-color var(--motion-fast), border-color var(--motion-fast);
|
||||
}
|
||||
.gx-card.gx-log-help__tab:hover { background: var(--glass-bg-hover); }
|
||||
.gx-card.gx-log-help__tab--active { background: var(--primary-container); border-color: var(--primary); }
|
||||
.gx-log-help__tab-icon {
|
||||
flex: none;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: var(--radius-sm);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--surface-container-high);
|
||||
color: var(--primary);
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
.gx-log-help__tab--active .gx-log-help__tab-icon { background: var(--primary); color: var(--on-primary); }
|
||||
.gx-log-help__tab-text { display: grid; gap: 2px; min-width: 0; }
|
||||
.gx-log-help__tab-text strong { font-size: var(--fs-base); line-height: 1.3; overflow-wrap: anywhere; }
|
||||
.gx-log-help__tab-text small { color: var(--text-muted); font-size: var(--fs-xs); line-height: 1.35; overflow-wrap: anywhere; }
|
||||
.gx-log-help__card > .gx-section__header > div { flex: 1 1 12rem; min-width: 0; }
|
||||
.gx-log-help__card > .gx-section__header p { margin: 2px 0 0; }
|
||||
.gx-connection-logs > .gx-section__header > .gx-btn { margin-left: auto; flex: none; }
|
||||
.gx-log-help__callout {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: var(--sp-3);
|
||||
align-items: start;
|
||||
padding: var(--sp-3) var(--sp-4);
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--glass-border);
|
||||
background: var(--surface-container);
|
||||
}
|
||||
.gx-log-help__callout > i { color: var(--primary); font-size: 1.1rem; margin-top: 2px; }
|
||||
.gx-log-help__callout p { margin: 0; line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.gx-log-help__group { display: grid; gap: var(--sp-2); min-width: 0; }
|
||||
.gx-log-help__group .gx-field { width: 100%; box-sizing: border-box; }
|
||||
.gx-log-help__label { font-size: var(--fs-sm); font-weight: var(--fw-bold); color: var(--on-surface); }
|
||||
.gx-log-help__pills { display: flex; flex-wrap: wrap; gap: var(--sp-2); }
|
||||
.gx-log-help__pills > button.gx-chip { min-height: var(--touch-target); padding: 0 var(--sp-4); font-size: var(--fs-sm); }
|
||||
.gx-log-help__pills > button.gx-chip.gx-chip--selected { background: var(--primary); border-color: var(--primary); color: var(--on-primary); }
|
||||
.gx-log-help__attaches {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--sp-2);
|
||||
margin: 0;
|
||||
color: var(--text-muted);
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.45;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.gx-log-help__attaches > i { color: var(--secondary); flex: none; margin-top: 2px; }
|
||||
.gx-log-help__ready {
|
||||
padding: var(--sp-4);
|
||||
border-radius: var(--radius-sm);
|
||||
border: 1px solid var(--primary);
|
||||
background: var(--primary-container);
|
||||
}
|
||||
.gx-log-help__ready p { margin: 0; }
|
||||
.gx-log-help__sessions { border-top: 1px solid var(--outline); padding-top: var(--sp-2); }
|
||||
.gx-log-help__sessions > summary {
|
||||
cursor: pointer;
|
||||
min-height: var(--touch-target);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-2);
|
||||
font-weight: var(--fw-medium);
|
||||
color: var(--on-surface-variant);
|
||||
}
|
||||
.gx-log-help__sessions-body { padding-top: var(--sp-3); }
|
||||
.gx-log-help__discord { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); flex-wrap: wrap; }
|
||||
.gx-log-help__discord-copy { display: flex; align-items: flex-start; gap: var(--sp-3); flex: 1 1 16rem; min-width: 0; }
|
||||
.gx-log-help__discord-copy > i { color: var(--primary); font-size: 1.35rem; flex: none; margin-top: 2px; }
|
||||
.gx-log-help__discord-copy h3 { margin: 0 0 4px; font-size: var(--fs-base); }
|
||||
.gx-log-help__discord-copy p { margin: 0; overflow-wrap: anywhere; }
|
||||
@media (max-width: 560px) {
|
||||
.gx-log-help__card > .gx-actions > .gx-btn,
|
||||
.gx-log-help__ready > .gx-actions > .gx-btn,
|
||||
.gx-log-help__discord > .gx-btn { flex: 1 1 100%; justify-content: center; }
|
||||
}
|
||||
|
||||
@@ -76,13 +76,6 @@
|
||||
"description": "Read local reports",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "StarPort Logs",
|
||||
"path": "/logs/starport",
|
||||
"icon": "bi-phone",
|
||||
"description": "Session logs and a download for bug reports",
|
||||
"availability": "local-only"
|
||||
},
|
||||
{
|
||||
"name": "tmux Live View",
|
||||
"path": "/logs/tmux",
|
||||
@@ -108,7 +101,7 @@
|
||||
"name": "Get help",
|
||||
"path": "/logs/help",
|
||||
"icon": "bi-life-preserver",
|
||||
"description": "Driving, phone connection, controllers, and StarPort support",
|
||||
"description": "Send StarPort, phone app, or controller logs, or ask on Discord",
|
||||
"availability": "always"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ConnectionLogs, ReportingGuide } from "./local-access.js"
|
||||
import { ConnectionLogs } from "./local-access.js"
|
||||
import { WikiHelp } from './wiki-help.js'
|
||||
import { UnidenPanel } from './uniden.js'
|
||||
import { GxState } from "./state.js"
|
||||
@@ -170,7 +170,7 @@ export class BluetoothFeed {
|
||||
}
|
||||
|
||||
export const BluetoothPage = {
|
||||
components: { WikiHelp, UnidenPanel, GxState, GxNotice, BluetoothTabs, GxDialog, ConnectionLogs, ReportingGuide },
|
||||
components: { WikiHelp, UnidenPanel, GxState, GxNotice, BluetoothTabs, GxDialog, ConnectionLogs },
|
||||
props: { go: { type: Function, default: path => { location.hash = path } }, unidenSettings: Boolean, mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
|
||||
data: () => ({ status: null, busy: false, error: "", pairValue: "", now: Date.now(), claimAt: Date.now(), forgetting: null, adding: false, dismissedPairing: null }),
|
||||
mounted() {
|
||||
@@ -323,7 +323,6 @@ export const BluetoothPage = {
|
||||
<button class="gx-btn gx-btn--danger" :disabled="forgetting.state === 'working'" @click="confirmForget">{{ forgetting.state === 'working' ? 'Forgetting…' : forgetting.state === 'failed' ? 'Try again' : 'Forget' }}</button></div>
|
||||
</template>
|
||||
</GxDialog>
|
||||
<ConnectionLogs v-if="mode === 'local' && !unidenSettings" panel show-controller :on-unauthorized="unauthorized" @help="go('/logs/help')" />
|
||||
<ReportingGuide v-if="mode === 'local' && !unidenSettings" />
|
||||
<ConnectionLogs v-if="mode === 'local' && !unidenSettings" panel :on-unauthorized="unauthorized" @help="go('/logs/help/connection')" />
|
||||
</section>`,
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { PollTimer, connectionError } from "./polling.js"
|
||||
import { requestJson } from "./startup.js"
|
||||
import { downloadCaptureZip } from "./log-help.js"
|
||||
import { reactive } from "../vendor/vue/vue.esm-browser.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
|
||||
@@ -49,117 +50,42 @@ export class LocalAccessFeed {
|
||||
}
|
||||
}
|
||||
|
||||
export const ReportingGuide = {
|
||||
template: `<p class="gx-note">Reporting a new companion app issue? Read the instructions for
|
||||
<a href="https://wiki.firestar.link/usage/companion-apps/ios/#submit-logs-through-discord" target="_blank" rel="noopener noreferrer">iPhone</a> or
|
||||
<a href="https://wiki.firestar.link/usage/companion-apps/android/#report-a-problem-through-discord" target="_blank" rel="noopener noreferrer">Android</a>.</p>`,
|
||||
}
|
||||
|
||||
export const ConnectionLogs = {
|
||||
components: { GxNotice, ReportingGuide },
|
||||
props: { ticket: String, panel: Boolean, controller: Boolean, showController: Boolean, onUnauthorized: { type: Function, default: () => {} } },
|
||||
components: { GxNotice },
|
||||
props: { panel: Boolean, controller: Boolean, onUnauthorized: { type: Function, default: () => {} } },
|
||||
emits: ["help"],
|
||||
data: () => ({ supportCode: "", supportTicket: null, supportBusy: false, supportSent: false, capture: null, captureError: "", captureRequest: null }),
|
||||
beforeUnmount() { this.resetCapture() },
|
||||
data: () => ({ captureBusy: false, captureError: "", captureSignal: null }),
|
||||
beforeUnmount() { this.captureSignal?.abort() },
|
||||
methods: {
|
||||
resetCapture() {
|
||||
this.captureRequest?.abort()
|
||||
this.captureRequest = null
|
||||
this.capture = null
|
||||
this.captureError = ""
|
||||
},
|
||||
async threadAction(action) {
|
||||
if (this.supportBusy) return
|
||||
this.supportBusy = true
|
||||
async downloadConnectionLogs() {
|
||||
if (this.captureBusy) return
|
||||
const controller = new AbortController()
|
||||
this.captureSignal = controller
|
||||
this.captureBusy = true
|
||||
this.captureError = ""
|
||||
try {
|
||||
const result = await requestJson("./api/companion/support-ticket", { timeout: 90000, request: {
|
||||
method: "POST", headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({action, code: this.supportCode.replace(/[\s-]/g, "").toLowerCase()})
|
||||
}})
|
||||
if (action === "check") this.supportTicket = result
|
||||
else this.supportSent = result.sent === true
|
||||
await downloadCaptureZip(this.controller ? "controller" : "connection", {
|
||||
unauthorized: this.onUnauthorized,
|
||||
request: { signal: controller.signal },
|
||||
})
|
||||
} catch (error) {
|
||||
if (error.status === 401) this.onUnauthorized()
|
||||
else this.captureError = error.message
|
||||
} finally { this.supportBusy = false }
|
||||
},
|
||||
async captureConnectionLogs() {
|
||||
if (this.captureRequest) return
|
||||
const request = new AbortController()
|
||||
this.captureRequest = request
|
||||
this.capture = null
|
||||
this.captureError = ""
|
||||
try {
|
||||
const endpoint = this.controller ? "./api/controllers/log/capture" : "./api/local-access/capture"
|
||||
const data = await requestJson(endpoint, { request: { signal: request.signal } })
|
||||
if (this.captureRequest !== request) return
|
||||
if (data?.schemaVersion !== 1 || typeof data.zipBase64 !== "string" || data.zipBase64.length > 131072)
|
||||
throw new Error("Invalid diagnostic capture")
|
||||
const bytes = Uint8Array.from(atob(data.zipBase64), character => character.charCodeAt(0))
|
||||
if (bytes.length < 22 || bytes[0] !== 80 || bytes[1] !== 75 || bytes[2] !== 3 || bytes[3] !== 4)
|
||||
throw new Error("Invalid diagnostic capture")
|
||||
this.capture = new Blob([bytes], { type: "application/zip" })
|
||||
if (this.ticket && /^[a-f0-9]{64}$/.test(this.ticket)) {
|
||||
const form = document.createElement("form")
|
||||
form.method = "post"
|
||||
form.action = "https://starpilot-log-relay.nathan-g-hubbard.workers.dev/report/galaxy/fresh/" + this.ticket
|
||||
const input = document.createElement("input")
|
||||
input.type = "hidden"
|
||||
input.name = "archive"
|
||||
input.value = data.zipBase64
|
||||
form.appendChild(input)
|
||||
document.body.appendChild(form)
|
||||
form.submit()
|
||||
form.remove()
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.captureRequest !== request) return
|
||||
if (error.status === 401 || ["setup_required", "access_unavailable"].includes(error.code)) this.onUnauthorized()
|
||||
else this.captureError = connectionError(error)
|
||||
if (error?.name !== "AbortError") this.captureError = error?.message || "Could not prepare diagnostic ZIP."
|
||||
} finally {
|
||||
if (this.captureRequest === request) this.captureRequest = null
|
||||
if (this.captureSignal === controller) {
|
||||
this.captureSignal = null
|
||||
this.captureBusy = false
|
||||
}
|
||||
}
|
||||
},
|
||||
downloadConnectionLogs() {
|
||||
if (!this.capture) return
|
||||
const url = URL.createObjectURL(this.capture)
|
||||
const link = document.createElement("a")
|
||||
link.href = url
|
||||
link.download = this.controller ? "starpilot-controller-logs.zip" : "starpilot-connection-logs.zip"
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
},
|
||||
},
|
||||
template: `<div class="gx-stack gx-connection-logs" :class="{ 'gx-card gx-panel': panel }">
|
||||
<div v-if="panel" class="gx-section__header"><i class="bi bi-file-earmark-text" aria-hidden="true"></i><span class="gx-section__title">Connection logs</span>
|
||||
<button type="button" class="gx-btn gx-btn--tonal" @click="$emit('help')">Get help</button>
|
||||
<button type="button" class="gx-btn gx-btn--tonal" @click="$emit('help')">Send logs</button>
|
||||
</div>
|
||||
<div v-if="panel" class="gx-actions"><a class="gx-btn gx-btn--tonal" href="https://wiki.firestar.link/usage/companion-apps/#pair-your-phone" target="_blank" rel="noopener noreferrer">App connection help</a></div>
|
||||
<details v-if="!ticket"><summary class="gx-btn">Send to existing Discord thread</summary>
|
||||
<p v-if="supportSent" role="status">Support received the logs. Your Discord thread has the receipt.</p>
|
||||
<form v-else class="gx-log-form" @submit.prevent="threadAction(supportTicket ? 'send' : 'check')">
|
||||
<label class="gx-field-group">Discord request code<input class="gx-field" v-model="supportCode" :disabled="supportBusy" @input="supportTicket = null; captureError = ''" maxlength="24" autocomplete="off" spellcheck="false"></label>
|
||||
<button v-if="!supportTicket" class="gx-btn" type="submit" :disabled="supportBusy || !supportCode.trim()">{{ supportBusy ? 'Finding report…' : 'Find report' }}</button>
|
||||
<template v-else><p>{{ supportTicket.title }}</p><p>Only support staff receive the {{ supportTicket.kind }} logs.</p>
|
||||
<button class="gx-btn" type="submit" :disabled="supportBusy">{{ supportBusy ? 'Sending…' : 'Capture and send' }}</button>
|
||||
</template>
|
||||
</form>
|
||||
</details>
|
||||
<details v-if="!ticket"><summary><small>Manual ZIP download</small></summary>
|
||||
<p v-if="showController" class="gx-note">For controller ZIPs, open Get help and choose Bluetooth Controller Support.</p>
|
||||
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!!captureRequest" @click="captureConnectionLogs">{{ captureRequest ? 'Capturing…' : 'Capture logs' }}</button>
|
||||
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!capture" @click="downloadConnectionLogs">Download ZIP</button>
|
||||
</details>
|
||||
<div v-else class="gx-actions">
|
||||
<button type="button" class="gx-btn gx-btn--tonal" :disabled="!!captureRequest" @click="captureConnectionLogs">{{ captureRequest ? 'Capturing…' : 'Capture and send' }}</button>
|
||||
|
||||
<button type="button" class="gx-btn gx-btn--tonal" :disabled="captureBusy" @click="downloadConnectionLogs">{{ captureBusy ? 'Preparing ZIP…' : 'Download connection ZIP' }}</button>
|
||||
</div>
|
||||
<GxNotice v-if="captureError" tone="danger">{{ captureError }}</GxNotice>
|
||||
<p v-if="capture && !ticket" class="gx-note" role="status">Capture ready. Download it to share with support.</p>
|
||||
<ReportingGuide v-if="!panel && !ticket" />
|
||||
</div>`,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,528 @@
|
||||
import { WikiHelp } from "./wiki-help.js"
|
||||
import { GxState } from "./state.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
import { BluetoothNotice, bluetoothConnection } from "./bluetooth-notice.js"
|
||||
import { StarPortLogsFeed, BUNDLE_URL, fileUrl, outcomeLabel } from "./starport-logs.js"
|
||||
import { requestJson } from "./startup.js"
|
||||
import { connectionError } from "./polling.js"
|
||||
|
||||
export const STAGE_URL = "./api/logs/stage"
|
||||
export const NOTE_LIMIT = 200
|
||||
export const MODEL_LIMIT = 80
|
||||
const POLL_MS = 1200
|
||||
const KINDS = ["starport", "connection", "controller"]
|
||||
const PHONES = ["ios", "android"]
|
||||
|
||||
export const LOG_TOPICS = [
|
||||
{
|
||||
id: "starport",
|
||||
title: "StarPort / Car Screen",
|
||||
subtitle: "Android Auto, wireless adapter, or black screen",
|
||||
icon: "bi-display",
|
||||
cta: "Send StarPort logs",
|
||||
placeholder: "What happened on the car screen?",
|
||||
whatWeNeed: "Try connecting to your car once first so the attempt is recorded, then describe what happened on your car screen.",
|
||||
extraHint: "",
|
||||
attaches: "Last 20 StarPort sessions, StarPort settings, renderer logs, and masked device snapshot.",
|
||||
},
|
||||
{
|
||||
id: "connection",
|
||||
title: "Phone App",
|
||||
subtitle: "Pairing or connecting the StarPilot phone app",
|
||||
icon: "bi-phone",
|
||||
cta: "Send phone app logs",
|
||||
placeholder: "What happened in the phone app?",
|
||||
whatWeNeed: "Pick whether you're on iPhone or Android and tell us what happened in the StarPilot app.",
|
||||
extraHint: "Can't reach Galaxy on your comma at all? You can also send logs from the phone app's Logs & support screen.",
|
||||
attaches: "Local network interfaces, Bonjour discovery, and Bluetooth bridge events (passwords & MACs masked).",
|
||||
},
|
||||
{
|
||||
id: "controller",
|
||||
title: "Controller",
|
||||
subtitle: "USB or Bluetooth gamepad / button inputs",
|
||||
icon: "bi-controller",
|
||||
cta: "Send controller logs",
|
||||
placeholder: "What went wrong with the controller?",
|
||||
whatWeNeed: "1. Turn on and wake your USB or Bluetooth controller right now so the comma detects it. 2. Enter the controller model below (hardware names are masked in the log).",
|
||||
extraHint: "",
|
||||
attaches: "USB & Bluetooth input interface report (bluetooth-log.json, device names masked).",
|
||||
},
|
||||
]
|
||||
|
||||
export class LogStageClient {
|
||||
constructor({
|
||||
publish,
|
||||
unauthorized = () => {},
|
||||
fetcher = (...args) => fetch(...args),
|
||||
schedule = (fn, ms) => setTimeout(fn, ms),
|
||||
cancel = (id) => clearTimeout(id),
|
||||
onReady = () => {},
|
||||
}) {
|
||||
Object.assign(this, { publish, unauthorized, fetcher, schedule, cancel, onReady })
|
||||
this.active = false
|
||||
this.timer = null
|
||||
this.generation = 0
|
||||
this.dismissedUrl = ""
|
||||
this.initiated = false
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.generation++
|
||||
this.active = false
|
||||
this.initiated = false
|
||||
if (this.timer !== null) this.cancel(this.timer)
|
||||
this.timer = null
|
||||
}
|
||||
|
||||
start() {
|
||||
this.stop()
|
||||
this.active = true
|
||||
return this.poll()
|
||||
}
|
||||
|
||||
reset(currentUrl = "") {
|
||||
if (currentUrl) this.dismissedUrl = currentUrl
|
||||
this.initiated = false
|
||||
this.publish({ state: "idle", message: "", claimUrl: "", kind: "", error: "" })
|
||||
}
|
||||
|
||||
async call(options, generation) {
|
||||
const response = await this.fetcher(STAGE_URL, { cache: "no-store", credentials: "same-origin", ...options })
|
||||
if (!this.active || generation !== this.generation) return null
|
||||
if (response.status === 401) {
|
||||
this.stop()
|
||||
this.unauthorized()
|
||||
return null
|
||||
}
|
||||
const body = await response.json().catch(() => null)
|
||||
if (!this.active || generation !== this.generation) return null
|
||||
if (!response.ok) throw new Error(body?.error || "Sending logs is unavailable")
|
||||
return body
|
||||
}
|
||||
|
||||
apply(body) {
|
||||
if (!this.active || !body) return
|
||||
const dismissed = body.state === "ready" && !!body.claimUrl && body.claimUrl === this.dismissedUrl
|
||||
const nextState = dismissed ? "idle" : (body.state || "idle")
|
||||
const claimUrl = dismissed ? "" : (body.claimUrl || "")
|
||||
const message = dismissed ? "" : (body.message || "")
|
||||
const kind = dismissed ? "" : (body.kind || "")
|
||||
this.publish({
|
||||
state: nextState,
|
||||
message,
|
||||
claimUrl,
|
||||
kind,
|
||||
available: body.available !== false,
|
||||
fork: body.fork === true,
|
||||
noteLimit: body.noteLimit || NOTE_LIMIT,
|
||||
modelLimit: body.modelLimit || MODEL_LIMIT,
|
||||
error: "",
|
||||
})
|
||||
if (this.initiated && nextState === "ready" && claimUrl) {
|
||||
this.initiated = false
|
||||
this.onReady(claimUrl)
|
||||
}
|
||||
this.queuePoll(nextState === "staging")
|
||||
}
|
||||
|
||||
queuePoll(pending = true) {
|
||||
if (this.timer !== null) this.cancel(this.timer)
|
||||
this.timer = this.active && pending ? this.schedule(() => { this.timer = null; this.poll() }, POLL_MS) : null
|
||||
}
|
||||
|
||||
async poll() {
|
||||
if (!this.active) return
|
||||
const generation = this.generation
|
||||
try {
|
||||
this.apply(await this.call({}, generation))
|
||||
} catch (error) {
|
||||
if (this.active && generation === this.generation) {
|
||||
this.publish({ error: error?.message || "Sending logs is unavailable" })
|
||||
this.queuePoll(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async stage(payload) {
|
||||
if (!this.active) return false
|
||||
const kind = payload?.kind
|
||||
if (!KINDS.includes(kind)) {
|
||||
this.publish({ error: "Choose what you are sending logs for." })
|
||||
return false
|
||||
}
|
||||
const note = String(payload?.note ?? "").trim()
|
||||
if (!note) {
|
||||
this.publish({ error: "Add a short note about what happened." })
|
||||
return false
|
||||
}
|
||||
if (note.length > NOTE_LIMIT) {
|
||||
this.publish({ error: `Keep the note to ${NOTE_LIMIT} characters.` })
|
||||
return false
|
||||
}
|
||||
const bodyPayload = { kind, note }
|
||||
if (kind === "connection") {
|
||||
if (!PHONES.includes(payload?.phone)) {
|
||||
this.publish({ error: "Choose iPhone or Android." })
|
||||
return false
|
||||
}
|
||||
bodyPayload.phone = payload.phone
|
||||
} else if (kind === "controller") {
|
||||
const model = String(payload?.model ?? "").trim()
|
||||
if (!model) {
|
||||
this.publish({ error: "Enter your controller make and model." })
|
||||
return false
|
||||
}
|
||||
if (model.length > MODEL_LIMIT) {
|
||||
this.publish({ error: `Keep the controller model to ${MODEL_LIMIT} characters.` })
|
||||
return false
|
||||
}
|
||||
bodyPayload.model = model
|
||||
}
|
||||
|
||||
this.dismissedUrl = ""
|
||||
this.initiated = true
|
||||
const generation = ++this.generation
|
||||
this.queuePoll(false)
|
||||
this.publish({ state: "staging", message: "Collecting logs", claimUrl: "", kind, error: "" })
|
||||
try {
|
||||
const body = await this.call({
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(bodyPayload),
|
||||
}, generation)
|
||||
if (body === null) return false
|
||||
this.apply(body)
|
||||
return true
|
||||
} catch (error) {
|
||||
if (this.active && generation === this.generation) {
|
||||
this.initiated = false
|
||||
this.publish({ state: "idle", error: error?.message || "Sending logs is unavailable" })
|
||||
this.queuePoll(false)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function captureZip(kind, { fetcher = (...args) => fetch(...args), unauthorized = () => {}, request = {} } = {}) {
|
||||
const controller = kind === "controller"
|
||||
const endpoint = controller ? "./api/controllers/log/capture" : "./api/local-access/capture"
|
||||
try {
|
||||
const data = await requestJson(endpoint, { fetcher, request })
|
||||
if (data?.schemaVersion !== 1 || typeof data.zipBase64 !== "string" || data.zipBase64.length > 131072) {
|
||||
throw new Error("Invalid diagnostic capture")
|
||||
}
|
||||
const bytes = Uint8Array.from(atob(data.zipBase64), character => character.charCodeAt(0))
|
||||
if (bytes.length < 22 || bytes[0] !== 80 || bytes[1] !== 75 || bytes[2] !== 3 || bytes[3] !== 4) {
|
||||
throw new Error("Invalid diagnostic capture")
|
||||
}
|
||||
return {
|
||||
blob: new Blob([bytes], { type: "application/zip" }),
|
||||
filename: controller ? "starpilot-controller-logs.zip" : "starpilot-connection-logs.zip",
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.status === 401 || ["setup_required", "access_unavailable"].includes(error.code)) {
|
||||
unauthorized()
|
||||
return null
|
||||
}
|
||||
throw new Error(connectionError(error))
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadCaptureZip(kind, options = {}) {
|
||||
const result = await captureZip(kind, options)
|
||||
if (!result) return false
|
||||
const url = URL.createObjectURL(result.blob)
|
||||
const link = document.createElement("a")
|
||||
link.href = url
|
||||
link.download = result.filename
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
return true
|
||||
}
|
||||
|
||||
export const LogHelp = {
|
||||
name: "LogHelp",
|
||||
components: { WikiHelp, GxState, GxNotice, BluetoothNotice },
|
||||
props: {
|
||||
mode: { type: String, required: true },
|
||||
unauthorized: { type: Function, required: true },
|
||||
topic: { type: String, default: "starport" },
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
selected: KINDS.includes(this.topic) ? this.topic : "starport",
|
||||
stage: { state: "idle", message: "", claimUrl: "", kind: "", available: true, fork: false, noteLimit: NOTE_LIMIT, modelLimit: MODEL_LIMIT, error: "" },
|
||||
starportLogs: { sessions: [], others: [], status: "idle", error: "" },
|
||||
sessionsOpen: false,
|
||||
bluetooth: bluetoothConnection(),
|
||||
notes: { starport: "", connection: "", controller: "" },
|
||||
phone: "ios",
|
||||
controllerModel: "",
|
||||
zipBusy: false,
|
||||
zipError: "",
|
||||
zipSignal: null,
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
topics() { return LOG_TOPICS },
|
||||
currentTopic() { return LOG_TOPICS.find(item => item.id === this.selected) || LOG_TOPICS[0] },
|
||||
bundleUrl() { return BUNDLE_URL },
|
||||
currentNote() { return this.notes[this.selected] || "" },
|
||||
canSend() {
|
||||
if (!this.currentNote.trim()) return false
|
||||
if (this.selected === "controller" && !this.controllerModel.trim()) return false
|
||||
return true
|
||||
},
|
||||
claimReady() {
|
||||
return this.stage.state === "ready" && !!this.stage.claimUrl && this.stage.kind === this.selected
|
||||
},
|
||||
missingHint() {
|
||||
if (this.selected === "controller") return "Enter your controller model and a short note above to send."
|
||||
return "Add a short note about what happened above to send."
|
||||
},
|
||||
},
|
||||
created() {
|
||||
this.stageClient = new LogStageClient({
|
||||
publish: update => Object.assign(this.stage, update),
|
||||
unauthorized: this.unauthorized,
|
||||
onReady: url => {
|
||||
try { window.open(url, "_blank", "noopener,noreferrer") } catch {}
|
||||
},
|
||||
})
|
||||
this.starportFeed = new StarPortLogsFeed({
|
||||
publish: update => Object.assign(this.starportLogs, update),
|
||||
unauthorized: this.unauthorized,
|
||||
})
|
||||
},
|
||||
mounted() {
|
||||
if (this.mode === "local") this.stageClient.start()
|
||||
},
|
||||
beforeUnmount() {
|
||||
this.zipSignal?.abort()
|
||||
this.stageClient.stop()
|
||||
this.starportFeed.stop()
|
||||
},
|
||||
watch: {
|
||||
topic(next) {
|
||||
if (KINDS.includes(next)) this.selected = next
|
||||
},
|
||||
mode(next) {
|
||||
if (next === "local") {
|
||||
this.stageClient.start()
|
||||
if (this.sessionsOpen && this.selected === "starport") this.starportFeed.start()
|
||||
} else {
|
||||
this.stageClient.stop()
|
||||
this.starportFeed.stop()
|
||||
}
|
||||
},
|
||||
selected(next) {
|
||||
this.zipError = ""
|
||||
this.stage.error = ""
|
||||
if (next !== "starport") this.starportFeed.stop()
|
||||
else if (this.sessionsOpen && this.mode === "local") this.starportFeed.start()
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
fileUrl,
|
||||
outcomeLabel,
|
||||
reportDate(seconds) { return new Date(seconds * 1000).toLocaleString() },
|
||||
reportSize(bytes) { return `${(bytes / 1024).toFixed(1)} KiB` },
|
||||
selectTopic(id) {
|
||||
this.selected = id
|
||||
},
|
||||
updateNote(value) {
|
||||
this.notes[this.selected] = value
|
||||
if (this.stage.error) this.stage.error = ""
|
||||
},
|
||||
resetStage() {
|
||||
this.stageClient.reset(this.stage.claimUrl)
|
||||
},
|
||||
async submitReport() {
|
||||
if (!this.canSend || this.stage.state === "staging" || this.zipBusy) return
|
||||
const payload = { kind: this.selected, note: this.currentNote }
|
||||
if (this.selected === "connection") payload.phone = this.phone
|
||||
if (this.selected === "controller") payload.model = this.controllerModel
|
||||
await this.stageClient.stage(payload)
|
||||
},
|
||||
async saveZip() {
|
||||
if (this.zipBusy || this.selected === "starport") return
|
||||
this.zipSignal?.abort()
|
||||
const controller = new AbortController()
|
||||
this.zipSignal = controller
|
||||
this.zipBusy = true
|
||||
this.zipError = ""
|
||||
try {
|
||||
await downloadCaptureZip(this.selected, { unauthorized: this.unauthorized, request: { signal: controller.signal } })
|
||||
} catch (error) {
|
||||
if (error?.name !== "AbortError") this.zipError = error?.message || "Could not prepare diagnostic ZIP."
|
||||
} finally {
|
||||
if (this.zipSignal === controller) {
|
||||
this.zipSignal = null
|
||||
this.zipBusy = false
|
||||
}
|
||||
}
|
||||
},
|
||||
onSessionsToggle(event) {
|
||||
this.sessionsOpen = !!event.target?.open
|
||||
if (this.sessionsOpen && this.mode === "local" && this.selected === "starport") this.starportFeed.start()
|
||||
else this.starportFeed.stop()
|
||||
},
|
||||
},
|
||||
template: `
|
||||
<section class="gx-settings gx-log-help" aria-labelledby="gx-log-help-title">
|
||||
<header class="gx-settings__header gx-page-header">
|
||||
<div>
|
||||
<h2 id="gx-log-help-title">Send logs & get help</h2>
|
||||
<p>Choose what you're sending logs for. Your comma prepares the logs and hands off once to Discord.</p>
|
||||
</div>
|
||||
<WikiHelp path="/logs/help" />
|
||||
</header>
|
||||
|
||||
<div class="gx-log-help__tabs" role="tablist" aria-label="Log report type">
|
||||
<button v-for="item in topics" :key="item.id" type="button" role="tab"
|
||||
class="gx-card gx-log-help__tab"
|
||||
:class="{ 'gx-log-help__tab--active': selected === item.id }"
|
||||
:aria-selected="selected === item.id"
|
||||
@click="selectTopic(item.id)">
|
||||
<span class="gx-log-help__tab-icon" aria-hidden="true"><i class="bi" :class="item.icon"></i></span>
|
||||
<span class="gx-log-help__tab-text">
|
||||
<strong>{{ item.title }}</strong>
|
||||
<small>{{ item.subtitle }}</small>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section class="gx-card gx-panel gx-stack gx-log-help__card" :aria-label="currentTopic.title">
|
||||
<div class="gx-section__header">
|
||||
<i class="bi" :class="currentTopic.icon" aria-hidden="true"></i>
|
||||
<div>
|
||||
<h3 class="gx-section__title">{{ currentTopic.title }}</h3>
|
||||
<p class="gx-note">{{ currentTopic.subtitle }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="mode !== 'local'" class="gx-note">Connect to your comma to send or download diagnostic logs.</p>
|
||||
<template v-else>
|
||||
<GxNotice v-if="selected === 'starport' && stage.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>
|
||||
<BluetoothNotice v-if="bluetooth" feature="ZIP downloads">Direct log sending from the comma remains available.</BluetoothNotice>
|
||||
|
||||
<div v-if="claimReady" class="gx-log-help__ready gx-stack" role="status">
|
||||
<strong>Logs uploaded from your comma</strong>
|
||||
<p class="gx-note">Continue to StarPilot Support to sign in with Discord and post to a new or existing thread. Only staff receive the diagnostic ZIP.</p>
|
||||
<div class="gx-actions">
|
||||
<a class="gx-btn" :href="stage.claimUrl" target="_blank" rel="noopener noreferrer"><i class="bi bi-box-arrow-up-right" aria-hidden="true"></i><span>Continue on Discord support</span></a>
|
||||
<button type="button" class="gx-btn gx-btn--tonal" @click="resetStage">Send another report</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<div class="gx-log-help__callout" role="note">
|
||||
<i class="bi bi-info-circle" aria-hidden="true"></i>
|
||||
<div class="gx-stack">
|
||||
<strong>What we need</strong>
|
||||
<p>{{ currentTopic.whatWeNeed }}</p>
|
||||
<p v-if="currentTopic.extraHint" class="gx-note">{{ currentTopic.extraHint }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="selected === 'connection'" class="gx-log-help__group" role="group" aria-label="Phone type">
|
||||
<label class="gx-log-help__label">Phone</label>
|
||||
<div class="gx-log-help__pills">
|
||||
<button type="button" class="gx-chip" :class="{ 'gx-chip--selected': phone === 'ios' }" :aria-pressed="phone === 'ios'" @click="phone = 'ios'">iPhone</button>
|
||||
<button type="button" class="gx-chip" :class="{ 'gx-chip--selected': phone === 'android' }" :aria-pressed="phone === 'android'" @click="phone = 'android'">Android</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="selected === 'controller'" class="gx-log-help__group">
|
||||
<label class="gx-log-help__label" for="gx-log-help-model">Controller make & model</label>
|
||||
<input id="gx-log-help-model" class="gx-field" type="text" v-model="controllerModel" :maxlength="stage.modelLimit"
|
||||
placeholder="e.g. 8BitDo Micro, Xbox Wireless, PS5 DualSense" :disabled="stage.state === 'staging'" @keydown.enter="submitReport">
|
||||
</div>
|
||||
|
||||
<div class="gx-log-help__group">
|
||||
<label class="gx-log-help__label" for="gx-log-help-note">What happened?</label>
|
||||
<div class="gx-starport-send__field">
|
||||
<input id="gx-log-help-note" class="gx-field" type="text" :value="currentNote" :maxlength="stage.noteLimit"
|
||||
:placeholder="currentTopic.placeholder" :disabled="stage.state === 'staging'"
|
||||
@input="updateNote($event.target.value)" @keydown.enter="submitReport">
|
||||
<span class="gx-starport-send__count" aria-live="polite">{{ currentNote.length }}/{{ stage.noteLimit }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="gx-log-help__attaches">
|
||||
<i class="bi bi-check-circle" aria-hidden="true"></i>
|
||||
<span><strong>Automatically attaches:</strong> {{ currentTopic.attaches }}</span>
|
||||
</p>
|
||||
|
||||
<div class="gx-actions">
|
||||
<button v-if="stage.available" type="button" class="gx-btn"
|
||||
:disabled="!canSend || stage.state === 'staging' || zipBusy" @click="submitReport">
|
||||
<i class="bi bi-send" aria-hidden="true"></i>
|
||||
<span>{{ stage.state === 'staging' ? (stage.message || 'Uploading logs') + '…' : currentTopic.cta }}</span>
|
||||
</button>
|
||||
<template v-if="!bluetooth">
|
||||
<a v-if="selected === 'starport'" class="gx-btn gx-btn--tonal" :href="bundleUrl" download>
|
||||
<i class="bi bi-download" aria-hidden="true"></i><span>Download ZIP instead</span>
|
||||
</a>
|
||||
<button v-else type="button" class="gx-btn gx-btn--tonal" :disabled="zipBusy || stage.state === 'staging'" @click="saveZip">
|
||||
<i class="bi bi-download" aria-hidden="true"></i><span>{{ zipBusy ? 'Preparing ZIP…' : 'Download ZIP instead' }}</span>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<p v-if="stage.available && !canSend && stage.state !== 'staging'" class="gx-note">{{ missingHint }}</p>
|
||||
<GxState v-if="stage.state === 'staging'" loading>{{ stage.message || 'Uploading logs' }}…</GxState>
|
||||
<GxNotice v-if="stage.state === 'failed' || stage.error || zipError" tone="danger">{{ stage.error || stage.message || zipError }}</GxNotice>
|
||||
</template>
|
||||
|
||||
<details v-if="selected === 'starport'" class="gx-log-help__sessions" @toggle="onSessionsToggle">
|
||||
<summary>Individual session files</summary>
|
||||
<div class="gx-stack gx-log-help__sessions-body">
|
||||
<div class="gx-actions">
|
||||
<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>
|
||||
<GxState v-if="starportLogs.status === 'loading'" loading>Loading StarPort logs…</GxState>
|
||||
<GxNotice v-else-if="starportLogs.status === 'unavailable'" tone="danger">{{ starportLogs.error || 'StarPort logs are unavailable.' }}</GxNotice>
|
||||
<GxState v-else-if="starportLogs.status === 'ready' && !starportLogs.sessions.length">No StarPort sessions have been logged yet.</GxState>
|
||||
<div v-if="starportLogs.status === 'ready'" class="gx-starport-log-list">
|
||||
<article v-for="log in starportLogs.sessions" :key="log.name" class="gx-card gx-starport-log">
|
||||
<div class="gx-starport-log__body">
|
||||
<strong>{{ outcomeLabel(log.outcome) }}</strong>
|
||||
<span>{{ log.car || 'Car not identified' }}{{ log.transport ? ' · ' + log.transport : '' }}{{ log.trigger ? ' · ' + log.trigger : '' }}</span>
|
||||
<span>{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}</span>
|
||||
</div>
|
||||
<a v-if="!bluetooth" class="gx-icon-btn gx-starport-log__download" :href="fileUrl(log.name)" :download="log.name" :aria-label="'Download ' + log.name" :title="'Download ' + log.name"><i class="bi bi-download" aria-hidden="true"></i></a>
|
||||
</article>
|
||||
</div>
|
||||
<template v-if="starportLogs.status === 'ready' && starportLogs.others.length">
|
||||
<h4 class="gx-starport-logs__section-title">Renderer logs</h4>
|
||||
<div class="gx-starport-log-list">
|
||||
<article v-for="log in starportLogs.others" :key="log.name" class="gx-card gx-starport-log">
|
||||
<div class="gx-starport-log__body"><strong>{{ log.name }}</strong><span>{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}</span></div>
|
||||
<a v-if="!bluetooth" class="gx-icon-btn gx-starport-log__download" :href="fileUrl(log.name)" :download="log.name" :aria-label="'Download ' + log.name" :title="'Download ' + log.name"><i class="bi bi-download" aria-hidden="true"></i></a>
|
||||
</article>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</details>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<section class="gx-card gx-panel gx-log-help__discord" aria-label="Discord community support">
|
||||
<div class="gx-log-help__discord-copy">
|
||||
<i class="bi bi-discord" aria-hidden="true"></i>
|
||||
<div>
|
||||
<h3>Driving behavior or general questions?</h3>
|
||||
<p class="gx-note">Log uploads here are only for StarPort, the phone app, and controllers. For driving behavior, alerts, or anything else, ask in the StarPilot Discord (if it's about a drive, share your car model and route link).</p>
|
||||
</div>
|
||||
</div>
|
||||
<a class="gx-btn gx-btn--tonal" href="https://firestar.link/discord" target="_blank" rel="noopener noreferrer">Join Discord</a>
|
||||
</section>
|
||||
</section>
|
||||
`,
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { DrivingHelp } from "./driving-help.js"
|
||||
import { ConnectionLogs } from "./local-access.js"
|
||||
import { WikiHelp } from './wiki-help.js'
|
||||
import { LogHelp } from "./log-help.js"
|
||||
import { WikiHelp } from "./wiki-help.js"
|
||||
import { GxState } from "./state.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
import { TroubleshootPage, TmuxPage } from "./diagnostic-tools.js"
|
||||
@@ -8,56 +7,45 @@ 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 { 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, DrivingHelp, ConnectionLogs },
|
||||
components: { LogHelp, WikiHelp, GxState, GxNotice, 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 }, localRoutes: Boolean
|
||||
},
|
||||
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
|
||||
}),
|
||||
computed: {
|
||||
freshRequest() {
|
||||
const match = /^\/logs\/help\/fresh\/(connection|controller)\/([a-f0-9]{64})$/.exec(this.path)
|
||||
return match && { controller: match[1] === "controller", token: match[2] }
|
||||
helpRoute() {
|
||||
return this.path === "/logs/help" || this.path.startsWith("/logs/help/") || this.path === "/logs/starport"
|
||||
},
|
||||
helpTopic() {
|
||||
if (this.path === "/logs/help/connection") return "connection"
|
||||
if (this.path === "/logs/help/controller") return "controller"
|
||||
return "starport"
|
||||
},
|
||||
visibleReports() { return this.crashes.reports.filter((item) => item.name.toLowerCase().includes(this.search.toLowerCase())) },
|
||||
},
|
||||
created() {
|
||||
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 })
|
||||
},
|
||||
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() }
|
||||
},
|
||||
beforeUnmount() { this.crashFeed.stop(); this.starportFeed.stop(); this.sendFeed.stop() },
|
||||
beforeUnmount() { this.crashFeed.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() }
|
||||
},
|
||||
},
|
||||
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() {
|
||||
@@ -76,41 +64,7 @@ export const Logs = {
|
||||
:availability="mode !== 'local' && tool.availability === 'local-only' ? 'Unavailable in preview' : ''"
|
||||
:disabled="mode !== 'local' && tool.availability === 'local-only'" @select="go(tool.path)" />
|
||||
</div>
|
||||
<section v-else-if="freshRequest" class="gx-settings">
|
||||
<header class="gx-settings__header"><h2>Requested {{ freshRequest.controller ? 'controller' : 'connection' }} logs</h2></header>
|
||||
<p class="gx-note">Capture fresh diagnostics for your support report. Only support staff receive the log file.</p>
|
||||
<ConnectionLogs v-if="mode === 'local'" :key="freshRequest.token" :ticket="freshRequest.token" :controller="freshRequest.controller" :on-unauthorized="unauthorized" />
|
||||
<p v-else class="gx-note">Connect to your comma to capture these logs.</p>
|
||||
</section>
|
||||
<section v-else-if="path === '/logs/help'" class="gx-settings">
|
||||
<header class="gx-settings__header gx-page-header"><div><h2>Get help</h2><p>Choose what went wrong.</p></div><WikiHelp path="/logs/help" /></header>
|
||||
<section class="gx-card gx-panel gx-stack" aria-label="Driving behavior or a specific drive">
|
||||
<div class="gx-section__header"><i class="bi bi-car-front" aria-hidden="true"></i><h3 class="gx-section__title">Driving behavior or a specific drive</h3></div>
|
||||
<DrivingHelp :routes-available="localRoutes" @routes="go('/recordings')" />
|
||||
</section>
|
||||
<section class="gx-card gx-panel gx-stack" aria-label="Mobile App Support">
|
||||
<div class="gx-section__header"><i class="bi bi-phone" aria-hidden="true"></i><h3 class="gx-section__title">Mobile App Support</h3></div>
|
||||
<p class="gx-note">For Wi-Fi, Bluetooth pairing, or Galaxy Tunnel issues. Send connection logs privately with your Discord account. If you use StarPilot on iPhone, you can also report from Logs & support.</p>
|
||||
<ConnectionLogs v-if="mode === 'local'" :on-unauthorized="unauthorized" />
|
||||
<p v-else class="gx-note">Connect to your comma to capture its connection logs.</p>
|
||||
|
||||
</section>
|
||||
<section class="gx-card gx-panel gx-stack" aria-label="Bluetooth Controller Support">
|
||||
<div class="gx-section__header"><i class="bi bi-controller" aria-hidden="true"></i><h3 class="gx-section__title">Bluetooth Controller Support</h3></div>
|
||||
<p class="gx-note">Connect and wake your USB or Bluetooth controller before capturing its input report. Include the controller model and what went wrong when you send it.</p>
|
||||
<ConnectionLogs v-if="mode === 'local'" controller :on-unauthorized="unauthorized" />
|
||||
<p v-else class="gx-note">Connect to your comma to capture a controller log.</p>
|
||||
<div class="gx-actions">
|
||||
<button v-if="mode === 'local'" type="button" class="gx-btn gx-btn--tonal" @click="go('/bluetooth/controllers')">Open Controllers</button>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
<section class="gx-card gx-panel gx-stack" aria-label="StarPort / Android Auto Support">
|
||||
<div class="gx-section__header"><i class="bi bi-phone" aria-hidden="true"></i><h3 class="gx-section__title">StarPort / Android Auto Support</h3></div>
|
||||
<p class="gx-note">Open StarPort Logs to download your session bundle or send it to the developer.</p>
|
||||
<button v-if="mode === 'local'" type="button" class="gx-btn gx-btn--tonal" @click="go('/logs/starport')">Open StarPort Logs</button>
|
||||
</section>
|
||||
</section>
|
||||
<LogHelp v-else-if="helpRoute" :mode="mode" :unauthorized="unauthorized" :topic="helpTopic" />
|
||||
<TroubleshootPage v-else-if="path === '/logs/troubleshoot'" :mode="mode" :unauthorized="unauthorized" @navigate="go" />
|
||||
<TmuxPage v-else-if="path === '/logs/tmux'" :mode="mode" :unauthorized="unauthorized" @navigate="go" />
|
||||
<template v-else-if="path === '/logs/monitor'"><SystemMonitor :mode="mode" :unauthorized="unauthorized" /></template>
|
||||
@@ -131,45 +85,6 @@ export const Logs = {
|
||||
<GxState v-if="crashes.previewStatus === 'loading'" loading>Loading report…</GxState>
|
||||
<section v-else-if="crashes.preview" class="gx-card gx-crash-preview gx-panel"><div class="gx-crash-preview__head"><strong>{{ crashes.preview.name }}</strong><button type="button" class="gx-btn gx-btn--tonal" @click="copyPreview">Copy visible text</button></div><p v-if="crashes.preview.truncated" class="gx-note">Preview truncated to the first 256 KiB.</p><pre>{{ crashes.preview.text }}</pre></section>
|
||||
</template>
|
||||
<section v-else-if="path === '/logs/starport' && mode === 'local'" class="gx-settings gx-starport-logs" aria-labelledby="gx-starport-logs-title">
|
||||
<header class="gx-settings__header gx-page-header"><div><h2 id="gx-starport-logs-title">StarPort Logs</h2>
|
||||
<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. 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?" 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' || !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>
|
||||
<GxNotice v-else-if="logSend.state === 'failed'" tone="danger">{{ logSend.message }}</GxNotice>
|
||||
<GxNotice v-if="logSend.error" tone="danger">{{ logSend.error }}</GxNotice>
|
||||
</section>
|
||||
|
||||
<GxState v-if="starportLogs.status === 'loading'" loading>Loading StarPort logs…</GxState>
|
||||
<GxNotice v-else-if="starportLogs.status === 'unavailable'" tone="danger">{{ starportLogs.error || 'StarPort logs are unavailable.' }}</GxNotice>
|
||||
<GxState v-else-if="starportLogs.status === 'ready' && !starportLogs.sessions.length">No StarPort sessions have been logged yet.</GxState>
|
||||
<div v-if="starportLogs.status === 'ready'" class="gx-starport-log-list">
|
||||
<article v-for="log in starportLogs.sessions" :key="log.name" class="gx-card gx-starport-log">
|
||||
<div class="gx-starport-log__body"><strong>{{ outcomeLabel(log.outcome) }}</strong><span>{{ log.car || 'Car not identified' }}{{ log.transport ? ' · ' + log.transport : '' }}{{ log.trigger ? ' · ' + log.trigger : '' }}</span><span>{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}</span></div>
|
||||
<a v-if="!bluetooth" class="gx-icon-btn gx-starport-log__download" :href="fileUrl(log.name)" :download="log.name" :aria-label="'Download ' + log.name" :title="'Download ' + log.name"><i class="bi bi-download" aria-hidden="true"></i></a>
|
||||
</article>
|
||||
</div>
|
||||
<template v-if="starportLogs.status === 'ready' && starportLogs.others.length">
|
||||
<h3 class="gx-starport-logs__section-title">Renderer logs</h3>
|
||||
<div class="gx-starport-log-list">
|
||||
<article v-for="log in starportLogs.others" :key="log.name" class="gx-card gx-starport-log">
|
||||
<div class="gx-starport-log__body"><strong>{{ log.name }}</strong><span>{{ reportDate(log.modifiedAt) }} · {{ reportSize(log.size) }}</span></div>
|
||||
<a v-if="!bluetooth" class="gx-icon-btn gx-starport-log__download" :href="fileUrl(log.name)" :download="log.name" :aria-label="'Download ' + log.name" :title="'Download ' + log.name"><i class="bi bi-download" aria-hidden="true"></i></a>
|
||||
</article>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
<GxState v-else>This Logs & Diagnostics page is unavailable in the offline preview.</GxState>
|
||||
</div>`,
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ConnectionLogs, ReportingGuide } from "./local-access.js"
|
||||
import { ConnectionLogs } from "./local-access.js"
|
||||
import { WikiHelp } from './wiki-help.js'
|
||||
import { requestJson } from "./startup.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
@@ -29,7 +29,7 @@ export const choiceRow = (label, value, choices, reason = '') => ({ label, value
|
||||
|
||||
export const NetworksPage = {
|
||||
name: "NetworksPage",
|
||||
components: { WikiHelp, GxNotice, GxState, GalaxySettingRow, GalaxyHotspot, GxDialog, ConnectionLogs, ReportingGuide },
|
||||
components: { WikiHelp, GxNotice, GxState, GalaxySettingRow, GalaxyHotspot, GxDialog, ConnectionLogs },
|
||||
props: { go: { type: Function, required: true }, mode: { type: String, required: true }, unauthorized: { type: Function, required: true } },
|
||||
data: () => ({ snapshot: null, busy: false, error: '', openUuid: null, adding: false, joiningSsid: '', joinPassword: '',
|
||||
hiddenOpen: false, hiddenSsid: '', showJoinPassword: false, forgetUuid: null, timer: null, controller: null, generation: 0, active: false }),
|
||||
@@ -262,7 +262,6 @@ export const NetworksPage = {
|
||||
</template>
|
||||
<GxNotice v-if="error" tone="danger">{{ error }}</GxNotice>
|
||||
<GalaxyHotspot v-if="mode === 'local'" :mode="mode" :unauthorized="unauthorized" />
|
||||
<ConnectionLogs v-if="mode === 'local'" panel :on-unauthorized="unauthorized" @help="go('/logs/help')" />
|
||||
<ReportingGuide v-if="mode === 'local'" />
|
||||
<ConnectionLogs v-if="mode === 'local'" panel :on-unauthorized="unauthorized" @help="go('/logs/help/connection')" />
|
||||
</section>`,
|
||||
}
|
||||
|
||||
@@ -1018,7 +1018,7 @@ export const StarPortPage = {
|
||||
</div>
|
||||
<div class="gx-step__body">
|
||||
<div class="gx-driving__actions gx-actions">
|
||||
<a class="gx-btn gx-btn--tonal" href="#/logs/starport"><i class="bi bi-journal-text"></i> Connection Logs</a>
|
||||
<a class="gx-btn gx-btn--tonal" href="#/logs/help/starport"><i class="bi bi-journal-text"></i> Send StarPort logs</a>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"protected_inventory_sha256": "a4af25d9ff1f1698f69203d21bd60e8d4e285da323e701c70fb1effa40c49997", "schema_version": 1}
|
||||
{"protected_inventory_sha256": "c62fb6fec8354753767abf1c79a13750939b7151cbf1f7024f4d432c2dce0f45", "schema_version": 1}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
export function supportCard(mention,text,buttons,inside=[],color=0xf2b134){
|
||||
const components=[];
|
||||
if(mention) components.push({type:10,content:mention});
|
||||
components.push({type:17,accent_color:color,components:[{type:10,content:text},...inside]},...buttons);
|
||||
return {flags:1<<15,components};
|
||||
}
|
||||
|
||||
export function privateCard(text, controls=[]) {
|
||||
const card=supportCard('',text,[],controls,0x5865f2);
|
||||
return {...card,flags:card.flags | 64,allowed_mentions:{parse:[]}};
|
||||
}
|
||||
|
||||
export function messageText(message) {
|
||||
function textOf(component) {
|
||||
if(component.type===10)return [component.content];
|
||||
return (component.components || []).flatMap(textOf);
|
||||
}
|
||||
return [message.content,...(message.components || []).flatMap(textOf)].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
// Normalize Discord's forum-thread response to the same message receipt used for replies.
|
||||
export async function botPost(env, channel, payload) {
|
||||
if (!env.DISCORD_BOT_TOKEN || !/^[0-9]{1,20}$/.test(channel)) throw Error('Bot destination unavailable');
|
||||
const multipart = payload instanceof FormData;
|
||||
const fields = multipart ? JSON.parse(payload.get('payload_json')) : payload;
|
||||
const {thread_name:name, applied_tags:tags, ...message} = fields;
|
||||
if(message.content && !(message.flags & (1<<15))){
|
||||
const files=[];
|
||||
if(multipart){
|
||||
for(const [key,file] of payload){
|
||||
if(key.startsWith('files[') && file?.name)files.push({type:13,file:{url:'attachment://'+file.name}});
|
||||
}
|
||||
}
|
||||
const card=supportCard('',message.content,message.components || [],files,0x5865f2);
|
||||
delete message.content;
|
||||
Object.assign(message,card);
|
||||
}
|
||||
const data = name ? {name, message, ...(tags && {applied_tags:tags})} : message;
|
||||
const headers = {Authorization:'Bot '+env.DISCORD_BOT_TOKEN};
|
||||
if (multipart) payload.set('payload_json',JSON.stringify(data));
|
||||
else headers['Content-Type']='application/json';
|
||||
const response = await fetch('https://discord.com/api/v10/channels/'+channel+(name?'/threads':'/messages'),{
|
||||
method:'POST', headers, body:multipart?payload:JSON.stringify(data), redirect:'manual', signal:AbortSignal.timeout(15000)
|
||||
});
|
||||
if (!name || !response.ok) return response;
|
||||
const thread=await response.json();
|
||||
if (thread.parent_id!==channel || !thread.message?.id || thread.message.channel_id!==thread.id)
|
||||
throw Error('Discord did not confirm the forum post');
|
||||
return Response.json(thread.message);
|
||||
}
|
||||
|
||||
export async function botMessage(env, channel, id) {
|
||||
if (!env.DISCORD_BOT_TOKEN || ![channel,id].every(v=>/^[0-9]{1,20}$/.test(v))) throw Error('Bot message unavailable');
|
||||
const result=await fetch('https://discord.com/api/v10/channels/'+channel+'/messages/'+id,{
|
||||
headers:{Authorization:'Bot '+env.DISCORD_BOT_TOKEN},redirect:'manual',signal:AbortSignal.timeout(10000)
|
||||
});
|
||||
if (!result.ok) throw Error('Discord could not read the saved message ('+result.status+').');
|
||||
const message=await result.json();
|
||||
if (message.channel_id!==channel || message.id!==id) throw Error('Discord returned a different message');
|
||||
return message;
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import {botPost,supportCard,privateCard} from './bot-delivery.mjs';
|
||||
import {discordTags, getReportThread, supportForum, supportTags} from './thread-tags.mjs';
|
||||
import {issueDriveLink, sendDriveInvite} from './drive-logs.mjs';
|
||||
|
||||
const titles = {
|
||||
note:'Additional Report', tags:'Apply tags', working:'Mark in progress', assign:'Assign someone', unassign:'Clear assignment', priority:'Set Priority', status:'Change Status',
|
||||
overview:'Report overview', question:'Ask the reporter', testing:'Request User Testing', rename:'Rename Thread', duplicate:'Link Duplicate',
|
||||
appLogs:'Request Phone App Logs', connection:'Request Comma Connection Logs', controller:'Request Controller Logs', starport:'Request StarPort Logs', removeTags:'Remove topic tags'
|
||||
};
|
||||
const descriptions={
|
||||
overview:'See status, priority, assignment and the latest available diagnostic link privately.',
|
||||
question:'Mention the reporter and give them a feedback button.',
|
||||
tags:'Add topics such as Galaxy, Navigation or CarPlay.', removeTags:'Remove selected topics while keeping the platform and status.',
|
||||
working:'Show that you are actively working on the report.', assign:'Pick and notify the person handling the report.',
|
||||
unassign:'Remove the current assignee.', priority:'Set urgency from 0 (highest) to 5, or clear it.',
|
||||
status:'Open, mark in progress, or close and archive the thread.', testing:'Mention the reporter with the build and steps to test.',
|
||||
rename:'Update the title people see in the forum.', duplicate:'Link to the original report by thread link or ID.',
|
||||
appLogs:'Ask the reporter for fresh diagnostics from the phone app in this ticket.',
|
||||
connection:'Phone app pairing, Bluetooth bridge, Wi-Fi and discovery on the comma.',
|
||||
starport:'Request the original StarPort session ZIP for Android Auto troubleshooting.',
|
||||
controller:'USB and Bluetooth input inventory for a physical controller.'
|
||||
};
|
||||
const statusColor={'Open':0x3498db,'In Progress':0xe69b22,'Closed':0x359467};
|
||||
const row = component => ({type:1,components:[component]});
|
||||
const ephemeral = (content,controls) => Response.json({type:4,data:privateCard(content,controls)});
|
||||
const idPattern = /^\d{1,20}$/;
|
||||
|
||||
export function reporterButtons(user,platform,channel) {
|
||||
const button=(action,label,style)=>({type:2,style,label,custom_id:['case',user,platform,action,channel].join(':')});
|
||||
return {type:1,components:[button('feedback','Give feedback',1),button('fulfilled','My request is fulfilled',3)]};
|
||||
}
|
||||
|
||||
export function caseButtons(user, platform) {
|
||||
const button = (action,label,style) => ({type:2,style,label,custom_id:['case',user,platform,action].join(':')});
|
||||
return [{type:1,components:[button('note',titles.note,2),button('menu','Staff Actions',1)]}];
|
||||
}
|
||||
|
||||
export async function caseInteraction(i,env,origin,ctx) {
|
||||
const [prefix,user,platform,command,bound] = (i.data?.custom_id||'').split(':');
|
||||
const channel=i.channel_id, actor=i.member?.user?.id;
|
||||
if(prefix!=='case'||!idPattern.test(user)||!idPattern.test(channel)||!idPattern.test(actor)||!['ios','android'].includes(platform)||
|
||||
(bound && bound!==channel)) return ephemeral('Open the original support thread.');
|
||||
const roles=i.guild_id==='1387432184121393333' && Array.isArray(i.member?.roles)?i.member.roles:[];
|
||||
let sage=false;
|
||||
if(roles.length){
|
||||
const settings=env.REPORTS.get(env.REPORTS.idFromName('companion-bot-setup'));
|
||||
const response=await settings.fetch('https://reports/sage-role');
|
||||
if(response.ok)sage=roles.includes((await response.json()).id);
|
||||
}
|
||||
const base=['case',user,platform].join(':')+':';
|
||||
const action=command==='pick'?i.data.values?.[0]:command;
|
||||
const reporterAction=['feedback','fulfilled'].includes(action);
|
||||
if(reporterAction && (actor!==user || bound!==channel))return ephemeral('Only the original reporter can respond to this request.');
|
||||
if(!reporterAction && (action==='note' ? actor!==user&&!sage : !sage)) return ephemeral(action==='note'?'Only the reporter or StarPilot Sage can add details.':'Staff Actions requires the StarPilot Sage role.');
|
||||
if(i.type===3 && command==='menu'){
|
||||
const options=Object.entries(titles).filter(([k])=>k!=='note').map(([value,label])=>({label,value,description:descriptions[value]}));
|
||||
return ephemeral('**Staff Actions**', [row({type:3,custom_id:base+'pick:'+channel,placeholder:'Choose a staff action',options})]);
|
||||
}
|
||||
if(!reporterAction&&!Object.hasOwn(titles,action))return ephemeral('Unknown support action.');
|
||||
if(i.type===3 && command==='pick' && action==='assign'){
|
||||
return ephemeral(titles[action], [row({type:5,custom_id:base+'assign:'+channel,placeholder:'Choose a server member'})]);
|
||||
}
|
||||
if(i.type===3 && command==='pick' && ['tags','removeTags'].includes(action)){
|
||||
const forum=await discordTags(env,'/channels/'+supportForum);
|
||||
const thread=await getReportThread(env,channel);
|
||||
const options=topicTags(forum).filter(t=>thread.applied_tags.includes(t.id)===(action==='removeTags')).map(t=>({label:t.name,value:t.id}));
|
||||
if(!options.length)return ephemeral('There are no topics available for that action.');
|
||||
return ephemeral(titles[action], [row({type:3,custom_id:base+action+':'+channel,placeholder:titles[action],max_values:Math.min(5,options.length),options})]);
|
||||
}
|
||||
const choices={priority:['0','1','2','3','4','5','Clear'],status:['Open','In Progress','Closed']};
|
||||
if(i.type===3 && command==='pick' && choices[action]){
|
||||
return ephemeral(titles[action], [row({type:3,custom_id:base+action+':'+channel,placeholder:titles[action],options:choices[action].map(value=>({label:value,value}))})]);
|
||||
}
|
||||
const prompts={question:'What do you need from the reporter?',feedback:'What did you find or what do you need?',note:'What happened?',testing:'Build and steps to test',rename:'New thread title',duplicate:'Original Discord thread link or ID'};
|
||||
if(i.type===3 && prompts[action]){
|
||||
return Response.json({type:9,data:{title:titles[action]||'Give feedback',custom_id:base+action+':'+channel,components:[row({type:4,custom_id:'value',label:prompts[action],style:['note','testing','feedback','question'].includes(action)?2:1,required:true,max_length:action==='rename'?100:action==='duplicate'?200:1500})]}});
|
||||
}
|
||||
const value=['tags','removeTags'].includes(action)?i.data.values:i.type===5?i.data.components?.[0]?.components?.[0]?.value?.trim():i.data.values?.[0];
|
||||
if(prompts[action] && (!value||i.type!==5) || choices[action]&&!choices[action].includes(value))return ephemeral('Choose a valid value.');
|
||||
if(action==='assign'&&(!idPattern.test(value)||!i.data.resolved?.members?.[value]))return ephemeral('Choose a server member.');
|
||||
const owner=env.REPORTS.get(env.REPORTS.idFromName(user));
|
||||
ctx.waitUntil((async()=>{
|
||||
let content='Could not confirm the action. Check the thread before retrying.';
|
||||
try{
|
||||
const response=await owner.fetch('https://reports/case-action',{method:'POST',body:JSON.stringify({user,platform,channel,action,actor,value,interaction:i.id,origin})});
|
||||
content=(await response.json()).message||content;
|
||||
}finally{
|
||||
await fetch('https://discord.com/api/v10/webhooks/'+i.application_id+'/'+i.token+'/messages/@original',{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({...privateCard(content),content:null,embeds:[]}),redirect:'manual'});
|
||||
}
|
||||
})());
|
||||
return Response.json({type:5,data:{flags:64}});
|
||||
}
|
||||
|
||||
function topicTags(forum){
|
||||
const reserved=['Open','In Progress','Closed','iOS','Android'].map(name=>supportTags[name]);
|
||||
return (forum.available_tags||[]).filter(tag=>!reserved.includes(tag.id));
|
||||
}
|
||||
|
||||
export async function caseAction(storage,env,b){
|
||||
const result=message=>Response.json({message});
|
||||
const {channel,platform,user,action,actor,value}=b;
|
||||
const key='thread:'+channel;
|
||||
const record=await storage.get(key);
|
||||
if(!record||record.platform!==platform)return result('This ticket could not be verified.');
|
||||
if(['feedback','fulfilled'].includes(action)&&actor!==user)return result('Only the reporter can respond.');
|
||||
const thread=await getReportThread(env,channel);
|
||||
if(action==='overview'){
|
||||
const status=Object.keys(statusColor).find(name=>thread.applied_tags.includes(supportTags[name])) || 'No status tag';
|
||||
const summary=['**Report overview**', 'Status: '+status+(thread.thread_metadata?.archived?' (archived)':''),
|
||||
'Assigned to: '+(record.assignee?' <@'+record.assignee+'>':'Unassigned'), 'Priority: '+(record.priority??'Unset')];
|
||||
if(record.duplicate)summary.push('Original thread: <#'+record.duplicate+'>');
|
||||
const diagnostics=await storage.get('latest-diagnostics:'+channel);
|
||||
if(diagnostics)summary.push('[Open latest private diagnostics]('+diagnostics+')');
|
||||
return result(summary.join('\n'));
|
||||
}
|
||||
const reopening=action==='status'&&value==='Open';
|
||||
if(thread.thread_metadata?.locked)return result('A moderator locked this thread. Unlock it in Discord first.');
|
||||
if((thread.applied_tags.includes(supportTags.Closed)||thread.thread_metadata?.archived)&&!reopening&&!(action==='status'&&value==='Closed'))
|
||||
return result('This report is closed or archived. Staff can use Change Status → Open to resume it.');
|
||||
const fresh=await storage.transaction(async tx=>{
|
||||
const recent=await tx.get('case-interactions')||[];
|
||||
if(recent.includes(b.interaction))return false;
|
||||
await tx.put('case-interactions',[...recent.slice(-99),b.interaction]);return true;
|
||||
});
|
||||
if(!fresh)return result('This action was already received.');
|
||||
if(action==='appLogs'){
|
||||
const steps=platform==='android'
|
||||
? 'Open the StarPilot Android app and go to **Debugging options → Report a problem**. If the last report is marked sent, tap **Start another report**. Describe what happened, choose this existing thread, then tap **Send report** and confirm the preview.'
|
||||
: 'Open StarPilot on your iPhone and go to **Settings → Logs & support → Report a problem on Discord**. Describe what happened and tap **Send**. Select this existing thread and tap **Send report**.';
|
||||
const instructions='**Fresh phone app logs requested**\nIf you can, reproduce the issue first. Sign in with the Discord account you used for this ticket.\n\n'+steps+'\n\nSupport staff receive the phone diagnostics privately.';
|
||||
const card=supportCard('<@'+user+'>',instructions,[reporterButtons(user,platform,channel)]);
|
||||
const sent=await botPost(env,channel,{...card,nonce:b.interaction,enforce_nonce:true,allowed_mentions:{parse:[],users:[user]}});
|
||||
return result(sent.ok?'Phone app log instructions sent.':'Could not confirm delivery of the phone app log instructions.');
|
||||
}
|
||||
if(['connection','controller','starport'].includes(action)){
|
||||
const link=await issueDriveLink(env,channel,b.origin,{userID:user,platform},action);
|
||||
const data=await link.json();
|
||||
if(!link.ok)return result(data.error||'Could not create the request.');
|
||||
await storage.transaction(async tx=>{
|
||||
const latest=await tx.get(key);
|
||||
await tx.put(key,{...latest,requestedLogKinds:{...latest.requestedLogKinds,[action]:Date.now()+86400000}});
|
||||
});
|
||||
const sent=await sendDriveInvite(env,channel,new URL(data.url).pathname.split('/').pop());
|
||||
return result(sent.ok?'Log instructions sent to this thread.':'Could not confirm delivery of the instructions.');
|
||||
}
|
||||
let message, nextStatus;
|
||||
const patch={};
|
||||
if(action==='duplicate'){
|
||||
const target=/^https:\/\/discord\.com\/channels\/1387432184121393333\/(\d{1,20})(?:\/\d{1,20})?\/?$/.exec(value)?.[1]||value;
|
||||
if(!idPattern.test(target)||channel===target)return result('Choose a different support thread.');
|
||||
await getReportThread(env,target);
|
||||
patch.duplicate=target;
|
||||
message='Duplicate of <#'+target+'>.';
|
||||
}else if(action==='rename'){
|
||||
await discordTags(env,'/channels/'+channel,{name:value});
|
||||
patch.title=value;message='Renamed this report to '+value+'.';
|
||||
}else if(action==='assign'||action==='unassign'){
|
||||
patch.assignee=action==='assign'?value:null;
|
||||
message=patch.assignee?'Assigned to <@'+value+'>.':'Assignment cleared.';
|
||||
}else if(action==='tags'||action==='removeTags'){
|
||||
const allowed=topicTags(await discordTags(env,'/channels/'+supportForum));
|
||||
if(!Array.isArray(value)||!value.length||value.some(id=>!allowed.some(t=>t.id===id)))return result('Reopen Apply tags to see the current choices.');
|
||||
const tags=action==='removeTags'?thread.applied_tags.filter(id=>!value.includes(id)):[...new Set([...thread.applied_tags,...value])];
|
||||
if(tags.length>5)return result('Discord allows five tags. Remove a tag or choose fewer.');
|
||||
await discordTags(env,'/channels/'+channel,{applied_tags:tags});
|
||||
message=(action==='removeTags'?'Removed topics: ':'Added topics: ')+allowed.filter(t=>value.includes(t.id)).map(t=>t.name).join(', ')+'.';
|
||||
}else if(action==='priority'){
|
||||
patch.priority=value==='Clear'?null:value;
|
||||
message=patch.priority===null?'Priority cleared.':'Priority '+value+' (0 is highest).';
|
||||
}else if(action==='status'||action==='working'||action==='fulfilled'){
|
||||
const status=action==='fulfilled'?'Closed':action==='working'?'In Progress':value;
|
||||
nextStatus=status;
|
||||
const statuses=['Open','In Progress','Closed'].map(name=>supportTags[name]);
|
||||
const tags=[...thread.applied_tags.filter(id=>!statuses.includes(id)),supportTags[status]];
|
||||
if(tags.length>5)return result('Remove a forum tag to make room for the status.');
|
||||
await discordTags(env,'/channels/'+channel,{applied_tags:tags,...(reopening&&thread.thread_metadata?.archived?{archived:false}:{})});
|
||||
message=action==='fulfilled'?'The reporter marked this request fulfilled.':action==='working'?'<@'+actor+'> is working on this report.':'Status changed to '+status+'.';
|
||||
}else if(action==='testing'||action==='question')message='<@'+user+'>';
|
||||
else if(action==='feedback')message='Feedback from <@'+actor+'>\n'+value;
|
||||
else if(action==='note')message='Additional report from <@'+actor+'>\n'+value;
|
||||
else return result('Unknown action.');
|
||||
if(Object.keys(patch).length)await storage.transaction(async tx=>tx.put(key,{...await tx.get(key),...patch}));
|
||||
const payload={content:message,nonce:b.interaction,enforce_nonce:true,
|
||||
allowed_mentions:{parse:[],users:['testing','question'].includes(action)?[user]:action==='assign'?[value]:[]}};
|
||||
if(action==='testing'||action==='question'){
|
||||
const text=[action==='testing'?'**Waiting for user testing**':'**Staff need more information**',value,'','Choose **Give feedback** to share your results, or **My request is fulfilled** to close the report.'].join('\n');
|
||||
delete payload.content;
|
||||
Object.assign(payload,supportCard(message,text,[reporterButtons(user,platform,channel)]));
|
||||
}else if(action==='feedback'||action==='note'){
|
||||
delete payload.content;
|
||||
Object.assign(payload,supportCard('',message,caseButtons(user,platform)));
|
||||
}
|
||||
if(nextStatus){
|
||||
delete payload.content;
|
||||
const controls=nextStatus==='Closed'?[row({type:2,style:2,label:'Staff Actions',custom_id:'case:'+user+':'+platform+':menu:'+channel})]:caseButtons(user,platform);
|
||||
Object.assign(payload,supportCard('','**'+nextStatus+'**\n'+message,controls,[],statusColor[nextStatus]));
|
||||
}
|
||||
const post=await botPost(env,channel,payload);
|
||||
if(nextStatus==='Closed'){
|
||||
try{await discordTags(env,'/channels/'+channel,{archived:true});}
|
||||
catch{return result('Tagged Closed, but archiving failed. Check Manage Threads, then choose Closed again.');}
|
||||
return result(post.ok?'Closed and archived. The original thread link still works.':'Closed and archived. Discord did not confirm the status card.');
|
||||
}
|
||||
return result(post.ok?'Updated this report.':'Could not confirm the update message. Refresh the thread.');
|
||||
}
|
||||
|
||||
|
||||
export async function enableCaseControls(env) {
|
||||
const endpoint='https://starpilot-log-relay.nathan-g-hubbard.workers.dev/drive-interactions';
|
||||
const path='/applications/@me';
|
||||
let app=await discordTags(env,path);
|
||||
if(app.id!=='1574857862872703088'||app.verify_key!==env.DISCORD_PUBLIC_KEY)throw Error('Check the Companion-Bot application and verification key.');
|
||||
if(app.interactions_endpoint_url===endpoint)return;
|
||||
if(app.interactions_endpoint_url)throw Error('Companion-Bot already uses another interactions endpoint.');
|
||||
app=await discordTags(env,path,{interactions_endpoint_url:endpoint});
|
||||
if(app.interactions_endpoint_url!==endpoint)throw Error('Discord has not confirmed the support controls endpoint.');
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {caseButtons,caseInteraction,caseAction} from './case-actions.mjs';
|
||||
import {supportForum} from './thread-tags.mjs';
|
||||
|
||||
const env={REPORTS:{idFromName:v=>v,get:()=>({fetch:()=>Response.json({id:'6'})})},REPORT_MAINTAINER_ID:'2',ANDROID_REPORT_MAINTAINER_ID:'3',DISCORD_BOT_TOKEN:'test'};
|
||||
const interaction=(command,actor)=>({type:3,guild_id:'1387432184121393333',member:{user:{id:actor},roles:actor==='3'?['6']:[]},channel_id:'4',data:{custom_id:'case:1:ios:'+command}});
|
||||
|
||||
test('reporter can add details and staff get a private action menu',async()=>{
|
||||
assert.equal(caseButtons('1','ios')[0].components.length,2);
|
||||
assert.equal((await (await caseInteraction(interaction('note','1'),env)).json()).type,9);
|
||||
assert.equal((await (await caseInteraction(interaction('menu','1'),env)).json()).data.components[0].components.length,1);
|
||||
assert.equal((await (await caseInteraction(interaction('menu','2'),env)).json()).data.components[0].components.length,1);
|
||||
const menu=await (await caseInteraction(interaction('menu','3'),env)).json();
|
||||
assert.equal(menu.data.flags,32832);
|
||||
assert.deepEqual(menu.data.components[0].components[1].components[0].options.slice(0,3).map(o=>o.value),['tags','working','assign']);
|
||||
assert.match((await (await caseInteraction(interaction('priority:5','2'),env)).json()).data.components[0].components[0].content,/original/);
|
||||
});
|
||||
test('priority is stored on the verified ticket and a repeated interaction posts once',async()=>{
|
||||
const data=new Map([['thread:4',{platform:'ios',title:'Original'}]]);
|
||||
const storage={get:k=>data.get(k),put:(k,v)=>data.set(k,v),transaction:fn=>fn(storage)};
|
||||
const prior=globalThis.fetch;
|
||||
const messages=[];
|
||||
globalThis.fetch=async(url,options)=>{
|
||||
if(options.method==='POST'){messages.push(JSON.parse(options.body));return Response.json({id:'8'});}
|
||||
return Response.json({id:'4',type:11,parent_id:supportForum,applied_tags:[]});
|
||||
};
|
||||
try{
|
||||
const action={action:'priority',channel:'4',platform:'ios',value:'0',actor:'2',interaction:'9'};
|
||||
await caseAction(storage,env,action);
|
||||
await caseAction(storage,env,action);
|
||||
assert.equal(data.get('thread:4').priority,'0');
|
||||
assert.equal(data.get('thread:4').title,'Original');
|
||||
assert.equal(messages.length,1);
|
||||
assert.deepEqual(messages[0].allowed_mentions.parse,[]);
|
||||
}finally{globalThis.fetch=prior;}
|
||||
});
|
||||
|
||||
test('marking in progress preserves topics and assignment uses a Discord user picker',async()=>{
|
||||
const pick=interaction('pick:4','3');
|
||||
pick.data.values=['assign'];
|
||||
const picker=await (await caseInteraction(pick,env)).json();
|
||||
assert.equal(picker.data.flags,32832);
|
||||
assert.equal(picker.data.components[0].components[1].components[0].type,5);
|
||||
const prior=globalThis.fetch, patched=[];
|
||||
globalThis.fetch=async(url,options)=>{
|
||||
if(options.method==='PATCH'){patched.push(JSON.parse(options.body));return Response.json({});}
|
||||
if(options.method==='POST')return Response.json({id:'8'});
|
||||
return Response.json({id:'4',type:11,parent_id:supportForum,applied_tags:['1565236988913913887','42']});
|
||||
};
|
||||
const data=new Map([['thread:4',{platform:'ios'}]]);
|
||||
const store={get:k=>data.get(k),put:(k,v)=>data.set(k,v),transaction:fn=>fn(store)};
|
||||
try{
|
||||
await caseAction(store,env,{channel:'4',platform:'ios',action:'working',actor:'3',interaction:'11'});
|
||||
assert.deepEqual(patched,[{applied_tags:['42','1565237023265263657']}]);
|
||||
}finally{globalThis.fetch=prior;}
|
||||
});
|
||||
|
||||
test('only the reporter can give feedback or mark a request fulfilled',async()=>{
|
||||
const open=async(command,actor)=> (await caseInteraction(interaction(command,actor),env)).json();
|
||||
assert.equal((await open('feedback:4','1')).type,9);
|
||||
assert.equal((await open('feedback:4','2')).data.flags,32832);
|
||||
assert.equal((await open('fulfilled:4','3')).data.flags,32832);
|
||||
assert.equal((await open('fulfilled:5','1')).data.flags,32832);
|
||||
});
|
||||
|
||||
test('each reporter update puts working staff controls beneath the new card',async t=>{
|
||||
const data=new Map([['thread:4',{platform:'ios'}]]);
|
||||
const store={get:k=>data.get(k),put:(k,v)=>data.set(k,v),transaction:fn=>fn(store)};
|
||||
const posts=[];
|
||||
t.mock.method(globalThis,'fetch',async(url,options)=>{
|
||||
if(options.method==='POST'){posts.push(JSON.parse(options.body));return Response.json({id:'8'});}
|
||||
return Response.json({id:'4',type:11,parent_id:supportForum,applied_tags:[]});
|
||||
});
|
||||
for(const action of ['feedback','note']){
|
||||
await caseAction(store,env,{channel:'4',platform:'ios',user:'1',actor:'1',action,value:'Still happens',interaction:action});
|
||||
const post=posts.at(-1);
|
||||
assert.equal(post.flags,32768);
|
||||
assert.match(post.components[0].components[0].content,/Still happens/);
|
||||
assert.equal(post.components[1].components[1].custom_id,'case:1:ios:menu');
|
||||
}
|
||||
});
|
||||
|
||||
test('closing archives after the status card and reopening restores the same thread',async t=>{
|
||||
const data=new Map([['thread:4',{platform:'ios'}]]);
|
||||
const store={get:k=>data.get(k),put:(k,v)=>data.set(k,v),transaction:fn=>fn(store)};
|
||||
const thread={id:'4',type:11,parent_id:supportForum,applied_tags:['42','1565236988913913887'],thread_metadata:{archived:false}};
|
||||
const events=[];
|
||||
t.mock.method(globalThis,'fetch',async(url,options)=>{
|
||||
if(options.method==='PATCH'){
|
||||
const patch=JSON.parse(options.body);
|
||||
if(patch.applied_tags)thread.applied_tags=patch.applied_tags;
|
||||
if('archived' in patch)thread.thread_metadata.archived=patch.archived;
|
||||
events.push(patch);
|
||||
}
|
||||
if(options.method==='POST'){
|
||||
events.push(JSON.parse(options.body).components[0].accent_color);
|
||||
return Response.json({id:'8'});
|
||||
}
|
||||
return Response.json(thread);
|
||||
});
|
||||
const act=(action,value,id)=>caseAction(store,env,{channel:'4',user:'1',platform:'ios',actor:'3',action,value,interaction:id});
|
||||
await act('status','Closed','1');
|
||||
assert.deepEqual(events,[{applied_tags:['42','1565237052524466207']},0x359467,{archived:true}]);
|
||||
assert.match((await (await act('working',null,'2')).json()).message,/closed or archived/);
|
||||
await act('status','Open','3');
|
||||
assert.deepEqual(events.slice(3),[{applied_tags:['42','1565236988913913887'],archived:false},0x3498db]);
|
||||
});
|
||||
|
||||
test('the overview is staff-only and reads archived tickets without posting',async t=>{
|
||||
const denied=await (await caseInteraction(interaction('overview:4','1'),env)).json();
|
||||
assert.match(denied.data.components[0].components[0].content,/Sage/);
|
||||
const data=new Map([['thread:4',{platform:'ios',priority:'0',assignee:'3'}],['latest-diagnostics:4','https://discord.com/channels/1/10/20']]);
|
||||
t.mock.method(globalThis,'fetch',async(url,options)=>{
|
||||
assert.equal(options.method,'GET');
|
||||
return Response.json({id:'4',type:11,parent_id:supportForum,applied_tags:[],thread_metadata:{archived:true}});
|
||||
});
|
||||
const summary=await (await caseAction({get:k=>data.get(k)},env,{channel:'4',platform:'ios',action:'overview'})).json();
|
||||
assert.match(summary.message,/archived/);
|
||||
assert.match(summary.message,/Priority: 0/);
|
||||
assert.match(summary.message,/channels\/1\/10\/20/);
|
||||
});
|
||||
|
||||
test('asking a question pings only the reporter and offers feedback',async t=>{
|
||||
const data=new Map([['thread:4',{platform:'ios'}]]);
|
||||
const storage={get:k=>data.get(k),put:(k,v)=>data.set(k,v),transaction:fn=>fn(storage)};
|
||||
let message;
|
||||
t.mock.method(globalThis,'fetch',async(url,options)=>{
|
||||
if(options.method==='POST'){message=JSON.parse(options.body);return Response.json({id:'9'});}
|
||||
return Response.json({id:'4',type:11,parent_id:supportForum,applied_tags:[]});
|
||||
});
|
||||
await caseAction(storage,env,{channel:'4',platform:'ios',user:'1',actor:'3',action:'question',interaction:'123',value:'Which build?'});
|
||||
assert.deepEqual(message.allowed_mentions,{parse:[],users:['1']});
|
||||
assert.match(JSON.stringify(message.components),/Which build/);
|
||||
assert.match(JSON.stringify(message.components),/case:1:ios:feedback:4/);
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import {messageText,botMessage} from './bot-delivery.mjs';
|
||||
const reviewReply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'no-store'}});
|
||||
const reviewUUID=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;
|
||||
|
||||
function reviewObject(env,name){
|
||||
return env.REPORTS.get(env.REPORTS.idFromName('codex-review:'+name));
|
||||
}
|
||||
function reviewCall(env,name,action,data){
|
||||
return reviewObject(env,name).fetch('https://reports/review/'+action,{method:'POST',body:JSON.stringify(data)});
|
||||
}
|
||||
export async function rememberDriveMessage(env,record,message){
|
||||
return reviewCall(env,'thread:'+record.threadID,'remember',{channel:message.channel_id,id:message.id,reference:record.reference,...(message.bot && {bot:true})});
|
||||
}
|
||||
export async function reviewStorage(storage,action,body){
|
||||
if(['enqueue','lease','finish','status'].includes(action))return reviewQueue(storage,action,body);
|
||||
if(action==='remember'){
|
||||
await storage.transaction(async tx=>{
|
||||
const list=await tx.get('driveMessages')||[];
|
||||
if(!list.some(x=>x.id===body.id))await tx.put('driveMessages',[body,...list].slice(0,20));
|
||||
});
|
||||
return reviewReply({saved:true});
|
||||
}
|
||||
if(action==='list')return reviewReply(await storage.get('driveMessages')||[]);
|
||||
if(action==='issue'){
|
||||
await storage.setAlarm(Date.now()+300000);
|
||||
await storage.put('reviewTicket',{...body,expires:Date.now()+300000});
|
||||
return reviewReply({ready:true});
|
||||
}
|
||||
if(action==='take'){
|
||||
const ticket=await storage.transaction(async tx=>{
|
||||
const value=await tx.get('reviewTicket');
|
||||
if(value)await tx.delete('reviewTicket');
|
||||
return value;
|
||||
});
|
||||
if(!ticket||ticket.expires<=Date.now())return reviewReply({error:'Review link expired. Click Review with Codex again.'},410);
|
||||
return reviewReply(ticket);
|
||||
}
|
||||
return reviewReply({error:'Unknown review action'},404);
|
||||
}
|
||||
export function claimReview(env,token){return reviewCall(env,'ticket:'+token,'take',{});}
|
||||
export async function webhookMessage(raw,channel,id){
|
||||
const url=new URL(raw);
|
||||
if(url.origin!=='https://discord.com'||!/^\/api\/webhooks\/\d+\/[\w-]+$/.test(url.pathname)||!/^\d+$/.test(channel)||!/^\d+$/.test(id))
|
||||
throw Error('Invalid report destination');
|
||||
url.pathname+='/messages/'+id;url.search='';url.searchParams.set('thread_id',channel);
|
||||
const r=await fetch(url,{redirect:'manual',signal:AbortSignal.timeout(10000)});
|
||||
if(r.status>=300&&r.status<400)throw Error('Discord returned an unexpected redirect for the saved report.');
|
||||
if(!r.ok)throw Error('Discord could not retrieve a saved report ('+r.status+').');
|
||||
const m=await r.json();
|
||||
if(m.id!==id||m.channel_id!==channel)throw Error('Discord returned a different report.');
|
||||
return m;
|
||||
}
|
||||
export async function prepareReview(env,report,chat){
|
||||
if(chat!==''&&!reviewUUID.test(chat))return reviewReply({error:'Enter a Codex chat ID.'},400);
|
||||
const ids=new URL(report.threadURL).pathname.split('/');
|
||||
const publicMessage=report.botPublic ? await botMessage(env,ids[3],ids[4]) : await webhookMessage(env.DISCORD_WEBHOOK_URL,ids[3],ids[4]);
|
||||
const messages=[];
|
||||
const original=/\nPrivate diagnostics: https:\/\/discord\.com\/channels\/\d+\/(\d+)\/(\d+)\s*$/.exec(messageText(publicMessage));
|
||||
if(report.botPrivateURL){
|
||||
const location = new URL(report.botPrivateURL).pathname.split("/");
|
||||
messages.push(await botMessage(env,location[3],location[4]));
|
||||
} else if(original)messages.push(await webhookMessage(env.DISCORD_PRIVATE_WEBHOOK_URL,original[1],original[2]));
|
||||
const drives=await (await reviewCall(env,'thread:'+ids[3],'list',{})).json();
|
||||
for(const drive of drives)messages.push(drive.bot ? await botMessage(env,drive.channel,drive.id) : await webhookMessage(env.DISCORD_PRIVATE_WEBHOOK_URL,drive.channel,drive.id));
|
||||
const token=Array.from(crypto.getRandomValues(new Uint8Array(32)),x=>x.toString(16).padStart(2,'0')).join('');
|
||||
// Only references and Discord's short-lived attachment URLs enter the ticket.
|
||||
const entries=messages.map(m=>({message:messageText(m),attachments:(m.attachments||[]).map(a=>({name:a.filename,url:a.url,size:a.size}))}));
|
||||
const saved=await reviewCall(env,'ticket:'+token,'issue',{chat,reference:report.reference,title:report.title,description:messageText(publicMessage),entries});
|
||||
return saved.ok?reviewReply({ticket:token}):saved;
|
||||
}
|
||||
|
||||
|
||||
|
||||
const queueSize=40;
|
||||
const jobLifetime=86400000;
|
||||
// Allow the next 30-minute Codex check to pick up a staged report.
|
||||
const leaseDuration=60*60*1000;
|
||||
const publicJob=job=>({id:job.id,state:job.state});
|
||||
|
||||
export function queueReview(env,report,chat){
|
||||
if(typeof chat!=='string'||(chat!==''&&!reviewUUID.test(chat)))return reviewReply({error:'Enter a Codex chat ID.'},400);
|
||||
return reviewCall(env,'queue','enqueue',{report,chat});
|
||||
}
|
||||
|
||||
export async function reviewWorker(env,body){
|
||||
if(body.action==='finish'){
|
||||
if(!reviewUUID.test(body.id||'')||!reviewUUID.test(body.lease||'')||typeof body.delivered!=='boolean')
|
||||
return reviewReply({error:'Invalid review receipt'},400);
|
||||
return reviewCall(env,'queue','finish',body);
|
||||
}
|
||||
if(body.action!=='claim')return reviewReply({error:'Unknown review worker action'},400);
|
||||
const claimed=await reviewCall(env,'queue','lease',{});
|
||||
if(!claimed.ok)return claimed;
|
||||
const {job}=await claimed.json();
|
||||
if(!job)return reviewReply({job:null});
|
||||
try {
|
||||
const prepared=await prepareReview(env,job.report,job.chat);
|
||||
if(!prepared.ok)throw Error('Review preparation failed');
|
||||
const {ticket}=await prepared.json();
|
||||
return reviewReply({job:{id:job.id,lease:job.lease,ticket}});
|
||||
} catch {
|
||||
await reviewCall(env,'queue','finish',{id:job.id,lease:job.lease,delivered:false});
|
||||
return reviewReply({job:null});
|
||||
}
|
||||
}
|
||||
|
||||
export function reviewStatus(env,id){
|
||||
if(!reviewUUID.test(id||''))return reviewReply({error:'Invalid review ID'},400);
|
||||
return reviewCall(env,'queue','status',{id});
|
||||
}
|
||||
|
||||
async function reviewQueue(storage,action,body){
|
||||
return storage.transaction(async tx=>{
|
||||
const now=Date.now();
|
||||
const jobs=(await tx.get('jobs')||[]).filter(job=>now-job.created<jobLifetime);
|
||||
for(const job of jobs){
|
||||
if(job.state==='delivering'&&job.leaseUntil<=now)job.state='unconfirmed';
|
||||
}
|
||||
const save=()=>tx.put('jobs',jobs);
|
||||
if(action==='status'){
|
||||
const job=jobs.find(j=>j.id===body.id);
|
||||
return job?reviewReply(publicJob(job)):reviewReply({error:'Review status expired.'},404);
|
||||
}
|
||||
if(action==='enqueue'){
|
||||
const existing=jobs.find(j=>j.report.reference===body.report.reference&&j.chat===body.chat&&
|
||||
(j.state==='queued'||j.state==='delivering'||j.state==='unconfirmed'));
|
||||
if(existing)return reviewReply(publicJob(existing));
|
||||
if(jobs.length>=queueSize){
|
||||
const oldestFinished=jobs.findIndex(j=>j.state==='delivered'||j.state==='failed');
|
||||
if(oldestFinished<0)return reviewReply({error:'The review queue is full. Try again later.'},429);
|
||||
jobs.splice(oldestFinished,1);
|
||||
}
|
||||
const job={id:crypto.randomUUID(),created:now,state:'queued',report:body.report,chat:body.chat};
|
||||
jobs.push(job);
|
||||
await save();
|
||||
return reviewReply(publicJob(job),202);
|
||||
}
|
||||
if(action==='lease'){
|
||||
const job=jobs.find(j=>j.state==='queued');
|
||||
if(!job)return reviewReply({job:null});
|
||||
job.state='delivering';
|
||||
job.lease=crypto.randomUUID();
|
||||
job.leaseUntil=now+leaseDuration;
|
||||
await save();
|
||||
return reviewReply({job});
|
||||
}
|
||||
const job=jobs.find(j=>j.id===body.id&&j.lease===body.lease);
|
||||
if(!job)return reviewReply({error:'Invalid review receipt'},409);
|
||||
if(job.state==='delivering'||job.state==='unconfirmed'){
|
||||
job.state=body.delivered?'delivered':'failed';
|
||||
await save();
|
||||
}
|
||||
return reviewReply(publicJob(job));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {prepareReview,claimReview,reviewStorage,queueReview,reviewWorker,reviewStatus} from './codex-review.mjs';
|
||||
|
||||
const record={title:'lost nav',reference:'BC67EAFB-EDB5-4F15-BD20-C1F54B8A62EA',threadURL:'https://discord.com/channels/1/2/3'};
|
||||
test('handoff uses the specified chat and can be claimed only once',async t=>{
|
||||
const stores=new Map();
|
||||
const env={DISCORD_WEBHOOK_URL:'https://discord.com/api/webhooks/111/public',
|
||||
DISCORD_PRIVATE_WEBHOOK_URL:'https://discord.com/api/webhooks/222/private',
|
||||
REPORTS:{idFromName:n=>n,get:n=>({fetch:(url,options)=>{
|
||||
if(!stores.has(n))stores.set(n,new Map());
|
||||
const rows=stores.get(n);
|
||||
const storage={get:k=>rows.get(k),put:(k,v)=>rows.set(k,v),delete:k=>rows.delete(k),setAlarm:()=>{},transaction:cb=>cb(storage)};
|
||||
return reviewStorage(storage,new URL(url).pathname.split('/').pop(),JSON.parse(options.body));
|
||||
}})}};
|
||||
let redirect=false;
|
||||
const request=t.mock.method(globalThis,'fetch',async (url,options)=>{
|
||||
assert.equal(options.redirect,'manual');
|
||||
if(redirect)return Response.redirect('https://example.com/',302);
|
||||
const pub=String(url).includes('/public/');
|
||||
return Response.json(pub?{id:'3',channel_id:'2',content:'Lost nav\nPrivate diagnostics: https://discord.com/channels/1/4/5'}:
|
||||
{id:'5',channel_id:'4',content:'Private report',attachments:[{filename:'report.txt',url:'https://cdn.discordapp.com/attachments/4/report.txt',size:12}]});
|
||||
});
|
||||
assert.equal((await prepareReview(env,record,'arbitrary')).status,400);
|
||||
for(const chat of ['',crypto.randomUUID()]){
|
||||
const {ticket}=await (await prepareReview(env,record,chat)).json();
|
||||
const result=await (await claimReview(env,ticket)).json();
|
||||
assert.equal(result.chat,chat);
|
||||
assert.equal(result.entries[0].attachments[0].name,'report.txt');
|
||||
assert.equal((await claimReview(env,ticket)).status,410);
|
||||
}
|
||||
const chat=crypto.randomUUID();
|
||||
const enqueued=await queueReview(env,record,chat);
|
||||
assert.equal(enqueued.status,202);
|
||||
const queued=await enqueued.json();
|
||||
assert.deepEqual(await (await queueReview(env,record,chat)).json(),queued);
|
||||
assert.deepEqual(await (await reviewStatus(env,queued.id)).json(),queued);
|
||||
const {job}=await (await reviewWorker(env,{action:'claim'})).json();
|
||||
assert.equal(job.id,queued.id);
|
||||
assert.equal((await (await reviewStatus(env,job.id)).json()).state,'delivering');
|
||||
assert.equal((await (await reviewWorker(env,{action:'claim'})).json()).job,null);
|
||||
assert.equal((await (await claimReview(env,job.ticket)).json()).chat,chat);
|
||||
assert.equal((await reviewWorker(env,{action:'finish',id:job.id,lease:crypto.randomUUID(),delivered:true})).status,409);
|
||||
await reviewWorker(env,{action:'finish',id:job.id,lease:job.lease,delivered:true});
|
||||
assert.equal((await (await reviewStatus(env,job.id)).json()).state,'delivered');
|
||||
redirect=true;
|
||||
const calls=request.mock.callCount();
|
||||
await assert.rejects(prepareReview(env,record,''),/unexpected redirect/);
|
||||
assert.equal(request.mock.callCount(),calls+1);
|
||||
});
|
||||
|
||||
test('bot review reads the recorded private message, including on an older webhook thread',async t=>{
|
||||
const reads=[];
|
||||
const env={DISCORD_BOT_TOKEN:'test',REPORTS:{idFromName:n=>n,get:()=>({fetch:async url=>url.endsWith('/list')?Response.json([]):Response.json({ready:true})})}};
|
||||
t.mock.method(globalThis,'fetch',async(url,opts)=>{
|
||||
assert.equal(opts.headers.Authorization,'Bot test');
|
||||
reads.push(url);
|
||||
const [,channel,id]=url.match(/channels[/]([0-9]+)[/]messages[/]([0-9]+)$/);
|
||||
return Response.json({id,channel_id:channel,content:'Report',attachments:[]});
|
||||
});
|
||||
const result=await prepareReview(env,{...record,botPublic:true,botPrivateURL:'https://discord.com/channels/1/4/5'},'');
|
||||
assert.equal(result.status,200);
|
||||
assert.deepEqual(reads,['https://discord.com/api/v10/channels/2/messages/3','https://discord.com/api/v10/channels/4/messages/5']);
|
||||
});
|
||||
@@ -0,0 +1,308 @@
|
||||
import {isReferral,referralInteraction} from './referrals.mjs';
|
||||
import {galaxyLogSteps} from './galaxy-log-request.mjs';
|
||||
import {caseInteraction,reporterButtons} from './case-actions.mjs';
|
||||
import {botPost,supportCard,privateCard} from './bot-delivery.mjs';
|
||||
import {rememberDriveMessage,webhookMessage} from './codex-review.mjs';
|
||||
import { getReportThread, supportTags, supportForum } from './thread-tags.mjs';
|
||||
|
||||
const day = 86400000;
|
||||
const maxBytes = 24 * 1024 * 1024;
|
||||
const reply = (data, status = 200) => Response.json(data, {status, headers:{'Cache-Control':'no-store'}});
|
||||
const hex = bytes => Array.from(new Uint8Array(bytes), n => n.toString(16).padStart(2, '0')).join('');
|
||||
function object(env, token) {
|
||||
const namespace = env.REPORTS;
|
||||
return namespace.get(namespace.idFromName('drive-log:' + token));
|
||||
}
|
||||
|
||||
export async function issueDriveLink(env, threadID, origin, report, kind = "drive") {
|
||||
let title;
|
||||
if(!env.DISCORD_BOT_TOKEN && report){
|
||||
const [, , , channel, message]=new URL(report.threadURL).pathname.split('/');
|
||||
if(channel!==threadID)throw Error('Select the original thread.');
|
||||
await webhookMessage(env.DISCORD_WEBHOOK_URL,threadID,message);
|
||||
title=report.title;
|
||||
} else {
|
||||
const thread=await getReportThread(env,threadID);
|
||||
if(thread.thread_metadata?.archived||thread.thread_metadata?.locked||thread.applied_tags.includes(supportTags.Closed))
|
||||
return reply({error:'Select an open support thread.'},409);
|
||||
title=thread.name;
|
||||
}
|
||||
const token = hex(crypto.getRandomValues(new Uint8Array(32)));
|
||||
const saved = await object(env, token).fetch('https://reports/drive/issue', {
|
||||
method:'POST', body:JSON.stringify({threadID, token, origin, title, kind, userID:report?.userID, platform:report?.platform, expires:Date.now()+day, reference:crypto.randomUUID()})
|
||||
});
|
||||
if (!saved.ok) return saved;
|
||||
return reply({url:origin+(kind === 'drive' ? '/drive/' : '/report/galaxy/fresh/')+token});
|
||||
}
|
||||
|
||||
export async function sendDriveInvite(env, threadID, token) {
|
||||
if (!/^[a-f0-9]{64}$/.test(token)) return reply({error:'Create a link first.'},400);
|
||||
return object(env,token).fetch('https://reports/drive/invite',{method:'POST',body:JSON.stringify({threadID})});
|
||||
}
|
||||
|
||||
export async function startGalaxyCapture(env, origin, userID, kind) {
|
||||
const token = hex(crypto.getRandomValues(new Uint8Array(32)));
|
||||
const record = {token,origin,userID,kind,platform:kind==='starport'?'android':'ios',reference:crypto.randomUUID(),expires:Date.now()+day};
|
||||
const stored = await object(env,token).fetch('https://reports/drive/issue',{method:'POST',body:JSON.stringify(record)});
|
||||
if (!stored.ok) return stored;
|
||||
return new Response(null,{status:303,headers:{Location:'/report/galaxy/fresh/'+token,'Cache-Control':'no-store'}});
|
||||
}
|
||||
|
||||
export async function freshRequest(env, token) {
|
||||
if (!/^[a-f0-9]{64}$/.test(token)) return null;
|
||||
const response = await object(env, token).fetch('https://reports/drive/fresh');
|
||||
return response.ok ? response.json() : null;
|
||||
}
|
||||
|
||||
export function driveDownload(env, token, secret) {
|
||||
return object(env,token).fetch('https://reports/drive/file/'+secret);
|
||||
}
|
||||
|
||||
function formPage() {
|
||||
return new Response(`<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Submit drive logs</title>
|
||||
<style>body{font:1rem/1.5 system-ui;margin:6vh auto;padding:1rem;max-width:32rem}label,input,textarea,button{display:block}label{margin-top:1rem}input,textarea{width:100%;box-sizing:border-box;padding:.55rem}button{margin-top:1.5rem;padding:.65rem 1rem}</style>
|
||||
<h1>Submit drive logs</h1><p>Share a comma connect route link, a segment log, or both. Your drive details go to the private support forum. Your support thread receives a receipt with a reference number.</p>
|
||||
<form method="post" enctype="multipart/form-data"><label>Comma connect route link<input type="url" name="route" maxlength="1500" placeholder="https://connect.comma.ai/…"></label>
|
||||
<label>Time into the drive<input name="time" maxlength="40" placeholder="6:49"></label><label>What happened?<textarea name="note" maxlength="1000"></textarea></label>
|
||||
<label>Segment log (up to 24 MiB)<input type="file" name="log" accept=".zst"></label><button>Submit drive logs</button></form></html>`,
|
||||
{headers:{'Content-Type':'text/html;charset=utf-8','Cache-Control':'no-store','Referrer-Policy':'no-referrer','Content-Security-Policy':"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'"}});
|
||||
}
|
||||
|
||||
export async function drivePage(request, env, token) {
|
||||
if (!['GET','POST'].includes(request.method)) return reply({error:'Method unavailable'},405);
|
||||
const target=object(env,token);
|
||||
if(request.method==='GET') {
|
||||
const status=await target.fetch('https://reports/drive/status');
|
||||
return status.ok ? formPage() : status;
|
||||
}
|
||||
const sent=await target.fetch(new Request('https://reports/drive/send',request));
|
||||
const data=await sent.json();
|
||||
return new Response(data.sent ? 'Drive logs received. Reference: '+data.reference : data.error, {
|
||||
status:sent.status, headers:{'Content-Type':'text/plain;charset=utf-8','Cache-Control':'no-store','Referrer-Policy':'no-referrer'}
|
||||
});
|
||||
}
|
||||
|
||||
async function readForm(request) {
|
||||
if (!request.headers.get('content-type')?.startsWith('multipart/form-data')) throw Error('Expected a drive submission form.');
|
||||
const limit=maxBytes+16384;
|
||||
if (Number(request.headers.get('content-length'))>limit) throw Error('Segment log exceeds 24 MiB.');
|
||||
const reader=request.body?.getReader();
|
||||
if (!reader) throw Error('Empty submission.');
|
||||
let size=0;
|
||||
const stream=new ReadableStream({async pull(controller) {
|
||||
const {done,value}=await reader.read();
|
||||
if(done){controller.close();return;}
|
||||
size+=value.length;
|
||||
if(size>limit){await reader.cancel();controller.error(Error('Segment log exceeds 24 MiB.'));return;}
|
||||
controller.enqueue(value);
|
||||
}});
|
||||
const form=await new Response(stream,{headers:{'Content-Type':request.headers.get('content-type')}}).formData();
|
||||
const field=(name,max)=>{
|
||||
const value=form.get(name)??'';
|
||||
if(typeof value!=='string'||value.length>max)throw Error('Invalid '+name+' field.');
|
||||
return value.trim();
|
||||
};
|
||||
const route=field('route',1500), time=field('time',40), note=field('note',1000);
|
||||
if(route){
|
||||
let url;try{url=new URL(route);}catch{}
|
||||
if(url?.origin!=='https://connect.comma.ai'||url.username||url.password||url.pathname==='/')throw Error('Enter a comma connect route link.');
|
||||
}
|
||||
const file=form.get('log');
|
||||
if(file?.size){
|
||||
if(!/^(rlog|qlog)\.zst$/i.test(file.name)||file.size>maxBytes)throw Error('Choose rlog.zst or qlog.zst, up to 24 MiB.');
|
||||
if(hex(await file.slice(0,4).arrayBuffer())!=='28b52ffd')throw Error('Choose a Zstandard-compressed segment log.');
|
||||
}else if(!route)throw Error('Add a route link or a segment log.');
|
||||
const fileHash=file?.size ? hex(await crypto.subtle.digest('SHA-256',await file.arrayBuffer())) : '';
|
||||
const fingerprint=hex(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(JSON.stringify([route,time,note,fileHash,file?.size?file.name:'']))));
|
||||
return {route,time,note,file,fingerprint};
|
||||
}
|
||||
|
||||
async function postWebhook(raw,threadID,body) {
|
||||
const url=new URL(raw);
|
||||
if(url.origin!=='https://discord.com'||!/^\/api\/webhooks\/\d+\/[\w-]+$/.test(url.pathname))throw Error('Invalid webhook');
|
||||
url.search='';url.searchParams.set('wait','true');
|
||||
if(threadID)url.searchParams.set('thread_id',threadID);
|
||||
const options=body instanceof FormData?{body}:{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)};
|
||||
return fetch(url,{...options,method:'POST',redirect:'manual',signal:AbortSignal.timeout(30000)});
|
||||
}
|
||||
|
||||
export async function driveObject(request,storage,env) {
|
||||
const action=new URL(request.url).pathname;
|
||||
if(action==='/drive/issue'){
|
||||
const record=await request.json();
|
||||
record.downloadToken=hex(crypto.getRandomValues(new Uint8Array(32)));
|
||||
await storage.setAlarm(record.expires);
|
||||
await storage.put('drive',record);
|
||||
return reply({created:true});
|
||||
}
|
||||
const record=await storage.get('drive');
|
||||
if(action.startsWith('/drive/file/')){
|
||||
const token=action.slice('/drive/file/'.length);
|
||||
if(!record?.fileKey || token!==record.downloadToken || record.fileExpires<=Date.now())return reply({error:'File expired'},404);
|
||||
const stored=await env.DRIVE_FILES.get(record.fileKey);
|
||||
if(!stored)return reply({error:'File unavailable'},404);
|
||||
return new Response(stored.body,{headers:{'Content-Type':'application/octet-stream','Content-Disposition':'attachment; filename="'+record.fileName+'"','Cache-Control':'private, no-store','Referrer-Policy':'no-referrer','X-Content-Type-Options':'nosniff'}});
|
||||
}
|
||||
if(!record||record.expires<=Date.now())return reply({error:'This link expired. Request a new one.'},410);
|
||||
if(record.done)return action==='/drive/send'?reply({sent:true,reference:record.reference}):reply({error:'Drive logs already received. Reference: '+record.reference},410);
|
||||
if(action==='/drive/invite'){
|
||||
const {threadID}=await request.json();
|
||||
if(threadID!==record.threadID)return reply({error:'Select the original thread.'},409);
|
||||
if(await storage.get('postedInvite'))return reply({sent:true});
|
||||
if(!env.DISCORD_BOT_TOKEN && !env.DISCORD_WEBHOOK_URL)return reply({error:'Support thread posting is unavailable.'},503);
|
||||
if(env.DISCORD_BOT_TOKEN){
|
||||
const thread=await getReportThread(env,threadID);
|
||||
if(thread.thread_metadata?.archived||thread.thread_metadata?.locked||thread.applied_tags.includes(supportTags.Closed))
|
||||
return reply({error:'Thread is closed.'},409);
|
||||
}
|
||||
const reserved=await storage.transaction(async tx=>{
|
||||
if(await tx.get('postedInvite'))return 'sent';
|
||||
if(await tx.get('invitePending'))return 'pending';
|
||||
await tx.put('invitePending',true);
|
||||
return 'new';
|
||||
});
|
||||
if(reserved==='sent')return reply({sent:true});
|
||||
const unconfirmed=()=>reply({error:'Discord delivery is pending or unconfirmed. Open the thread to check before trying again.'},409);
|
||||
if(reserved==='pending')return unconfirmed();
|
||||
let result;
|
||||
try {
|
||||
const capture = ['connection','controller','starport'].includes(record.kind);
|
||||
const title={connection:'Phone app connection logs',controller:'Controller logs',starport:'StarPort logs'}[record.kind];
|
||||
const intro=capture?'**'+title+' requested**\n'+galaxyLogSteps(record).map((step,i)=>(i+1)+'. '+step).join('\n\n'):
|
||||
'**Drive logs requested**\nUse the link below to submit the drive logs privately for this report.';
|
||||
const link=record.origin+'/drive/'+record.token;
|
||||
const help=capture?'If the app can’t connect, open Galaxy in your phone’s browser using the Local Galaxy address on the comma while connected to its Wi-Fi or hotspot.':'';
|
||||
const backup=capture && record.kind!=='starport'?'[Offline ZIP help]('+record.origin+'/report/galaxy/fresh/'+record.token+')':'';
|
||||
const reporter=/^\d{1,20}$/.test(record.userID) ? record.userID : null;
|
||||
const mention=reporter ? '<@'+reporter+'>' : '';
|
||||
const mentions={parse:[],users:reporter?[reporter]:[]};
|
||||
const linkRow={type:1,components:[{type:2,style:5,label:'Submit drive logs',url:link}]};
|
||||
const replies=reporter&&['ios','android'].includes(record.platform)?[reporterButtons(reporter,record.platform,threadID)]:[];
|
||||
if(env.DISCORD_BOT_TOKEN){
|
||||
result = await fetch('https://discord.com/api/v10/channels/'+threadID+'/messages',{
|
||||
method:'POST',redirect:'manual',signal:AbortSignal.timeout(15000),
|
||||
headers:{Authorization:'Bot '+env.DISCORD_BOT_TOKEN,'Content-Type':'application/json'},
|
||||
body:JSON.stringify({...supportCard(mention,intro,capture?replies:[linkRow,...replies],
|
||||
capture?[{type:14},{type:10,content:[help,backup].filter(Boolean).join('\n')}]:[]),allowed_mentions:mentions})
|
||||
});
|
||||
} else {
|
||||
result=await postWebhook(env.DISCORD_WEBHOOK_URL,threadID,{content:[mention,intro,capture?help:'<'+link+'>',backup].filter(Boolean).join('\n'),allowed_mentions:mentions});
|
||||
}
|
||||
} catch {
|
||||
return unconfirmed();
|
||||
}
|
||||
if(result.status>=400&&result.status<500&&result.status!==408){
|
||||
await storage.delete('invitePending');
|
||||
return reply({error:result.status===429?'Discord is rate limiting posts. Try again shortly.':'Discord rejected the post. Check that the support thread is open.'},result.status===429?429:503);
|
||||
}
|
||||
if(!result.ok)return unconfirmed();
|
||||
const message=await result.json().catch(()=>null);
|
||||
if(message?.channel_id!==threadID||!/^\d+$/.test(message.id))return unconfirmed();
|
||||
await storage.put('postedInvite',message.id);
|
||||
await storage.delete('invitePending');
|
||||
return reply({sent:true});
|
||||
}
|
||||
if (action === '/drive/fresh' && ['controller','connection','starport'].includes(record.kind)) {
|
||||
const {userID, platform, threadID, reference, title, kind} = record;
|
||||
return reply({userID, platform, threadID, reference, title, kind});
|
||||
}
|
||||
if (record.kind && record.kind !== 'drive') return reply({error:'Open the Galaxy request link.'},400);
|
||||
if(action==='/drive/status')return reply({open:true});
|
||||
if(action!=='/drive/send')return reply({error:'Unknown action'},404);
|
||||
let input;
|
||||
try{input=await readForm(request);}catch(e){return reply({error:e.message},400);}
|
||||
const blocked=await storage.transaction(async tx=>{
|
||||
const r=await tx.get('drive');
|
||||
if(!r||r.expires<=Date.now())return 'This link expired.';
|
||||
if(r.done||r.busy)return 'Delivery is already in progress or awaiting confirmation. Check the support thread.';
|
||||
if(r.fingerprint&&r.fingerprint!==input.fingerprint)return 'Retry with the original submission.';
|
||||
await tx.put('drive',{...r,busy:true,fingerprint:input.fingerprint});
|
||||
return null;
|
||||
});
|
||||
if(blocked)return reply({error:blocked},409);
|
||||
const state=await storage.get('drive');
|
||||
let posting=false;
|
||||
try {
|
||||
if(!state.privateSent){
|
||||
if(env.DISCORD_PRIVATE_FORUM!=='true'||!env.DISCORD_PRIVATE_WEBHOOK_URL||env.DISCORD_PRIVATE_WEBHOOK_URL===env.DISCORD_WEBHOOK_URL)throw Error('Private forum required');
|
||||
const privateMeta=await fetch(env.DISCORD_PRIVATE_WEBHOOK_URL,{redirect:'manual',signal:AbortSignal.timeout(10000)});
|
||||
const publicMeta=await fetch(env.DISCORD_WEBHOOK_URL,{redirect:'manual',signal:AbortSignal.timeout(10000)});
|
||||
if(!privateMeta.ok||!publicMeta.ok)throw Error('Forum metadata unavailable');
|
||||
const priv=await privateMeta.json(),pub=await publicMeta.json();
|
||||
if(!/^\d+$/.test(priv.channel_id)||pub.channel_id!==supportForum||priv.channel_id===pub.channel_id||priv.guild_id!==pub.guild_id)throw Error('Verify private forum configuration');
|
||||
const form=new FormData();
|
||||
const payload={thread_name:('Drive logs · '+state.title).slice(0,100),content:'Drive logs received. Reference: '+state.reference,allowed_mentions:{parse:[]}};
|
||||
if(input.file?.size && env.DRIVE_FILES){
|
||||
state.fileKey='drive/'+state.reference;
|
||||
state.fileName=input.file.name.toLowerCase();
|
||||
state.fileExpires=Date.now()+7*day;
|
||||
await storage.put('drive',state);
|
||||
await storage.setAlarm(state.fileExpires);
|
||||
await env.DRIVE_FILES.put(state.fileKey,input.file.stream());
|
||||
payload.content+='\nSegment log (7 days): <'+state.origin+'/drive-file/'+state.token+'/'+state.downloadToken+'>';
|
||||
}
|
||||
form.set('payload_json',JSON.stringify(payload));
|
||||
form.set('files[0]',new Blob([['Reference: '+state.reference,'Support thread: '+state.threadID,'Route: '+input.route,'Time into drive: '+input.time,'Notes: '+input.note].join('\n')]),'drive-details.txt');
|
||||
if(input.file?.size && !state.fileKey)form.set('files[1]',input.file,input.file.name);
|
||||
posting=true;
|
||||
const privatePost=env.DISCORD_BOT_TOKEN ? await botPost(env,priv.channel_id,form) : await postWebhook(env.DISCORD_PRIVATE_WEBHOOK_URL,null,form);
|
||||
if(!privatePost.ok)return rejectDelivery(privatePost,state,storage);
|
||||
const msg=await privatePost.json();
|
||||
if(!/^\d+$/.test(msg.id)||!/^\d+$/.test(msg.channel_id)||msg.channel_id===state.threadID)throw Error('Unconfirmed private post');
|
||||
state.privateSent=true;
|
||||
state.privateMessage={id:msg.id,channel_id:msg.channel_id,...(env.DISCORD_BOT_TOKEN && {bot:true})};
|
||||
await storage.put('drive',state);
|
||||
}
|
||||
if(state.privateMessage){
|
||||
const indexed=await rememberDriveMessage(env,state,state.privateMessage);
|
||||
if(!indexed.ok)throw Error('Private message indexing failed');
|
||||
}
|
||||
posting=true;
|
||||
const payload={content:'Drive logs received. Reference: '+state.reference,allowed_mentions:{parse:[]}};
|
||||
const receipt=env.DISCORD_BOT_TOKEN ? await botPost(env,state.threadID,payload) : await postWebhook(env.DISCORD_WEBHOOK_URL,state.threadID,payload);
|
||||
if(!receipt.ok)return rejectDelivery(receipt,state,storage);
|
||||
const msg=await receipt.json();
|
||||
if(msg.channel_id!==state.threadID||!/^\d+$/.test(msg.id))throw Error('Unconfirmed receipt');
|
||||
await storage.put('drive',{...state,done:true,busy:false});
|
||||
return reply({sent:true,reference:state.reference});
|
||||
}catch{
|
||||
if(!posting){
|
||||
await storage.put('drive',{...state,busy:false});
|
||||
return reply({error:'The private submission service is unavailable. Retry the same submission.'},503);
|
||||
}
|
||||
return reply({error:'Delivery is unconfirmed. Contact support with reference '+state.reference},409);
|
||||
}
|
||||
}
|
||||
async function rejectDelivery(response,state,storage){
|
||||
if(response.status>=400&&response.status<500&&response.status!==408){
|
||||
await storage.put('drive',{...state,busy:false});
|
||||
return reply({error:'Discord declined delivery. Retry the same submission or contact support. Reference: '+state.reference},503);
|
||||
}
|
||||
return reply({error:'Delivery is unconfirmed. Contact support with reference '+state.reference},409);
|
||||
}
|
||||
|
||||
|
||||
// Discord delivers signed interactions only when this Worker is configured as the application's endpoint.
|
||||
export async function driveInteraction(request,env,origin,ctx) {
|
||||
const key=env.DISCORD_PUBLIC_KEY;
|
||||
const sig=request.headers.get('X-Signature-Ed25519')||'';
|
||||
const ts=request.headers.get('X-Signature-Timestamp')||'';
|
||||
if(!/^[a-f0-9]{64}$/i.test(key||'')||!/^[a-f0-9]{128}$/i.test(sig)||!/^\d{10}$/.test(ts)||Math.abs(Date.now()/1000-Number(ts))>300)return reply({error:'Invalid signature'},401);
|
||||
const raw=await request.text();
|
||||
const bytes=s=>Uint8Array.from(s.match(/../g),h=>parseInt(h,16));
|
||||
const signer=await crypto.subtle.importKey('raw',bytes(key),'Ed25519',false,['verify']);
|
||||
if(!await crypto.subtle.verify('Ed25519',signer,bytes(sig),new TextEncoder().encode(ts+raw)))return reply({error:'Invalid signature'},401);
|
||||
const interaction=JSON.parse(raw);
|
||||
if(interaction.type===1)return reply({type:1});
|
||||
const answer=content=>reply({type:4,data:privateCard(content)});
|
||||
if(isReferral(interaction))return referralInteraction(interaction,env,ctx);
|
||||
if([3,5].includes(interaction.type))return caseInteraction(interaction,env,origin,ctx);
|
||||
if(interaction.type!==2||interaction.data?.name!=='request-logs')return answer('Unknown command.');
|
||||
const staff=[env.REPORT_MAINTAINER_ID,env.ANDROID_REPORT_MAINTAINER_ID].filter(Boolean);
|
||||
if(!staff.includes(interaction.member?.user?.id))return answer('A support maintainer can request drive logs.');
|
||||
try{
|
||||
const result=await issueDriveLink(env,interaction.channel_id,origin);
|
||||
const data=await result.json();
|
||||
return answer(result.ok?'Send this single-use link to the driver (valid for 24 hours): '+data.url:data.error);
|
||||
}catch{return answer('Open an active support thread and try again.');}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {driveObject,drivePage,issueDriveLink,sendDriveInvite} from './drive-logs.mjs';
|
||||
import {supportForum} from './thread-tags.mjs';
|
||||
|
||||
function fixture(t){
|
||||
const records=new Map(), posts=[];
|
||||
const store={get:async k=>structuredClone(records.get(k)),put:async(k,v)=>records.set(k,structuredClone(v)),delete:async k=>records.delete(k),transaction:async cb=>cb(store),setAlarm:async()=>{}};
|
||||
const env={DISCORD_WEBHOOK_URL:'https://discord.com/api/webhooks/123/public',DISCORD_PRIVATE_WEBHOOK_URL:'https://discord.com/api/webhooks/456/private',DISCORD_PRIVATE_FORUM:'true',DISCORD_BOT_TOKEN:'test'};
|
||||
const run=(path,init)=>driveObject(new Request('https://reports'+path,init),store,env);
|
||||
env.REPORTS={idFromName:x=>x,get:()=>({fetch:(url,init)=>String(url).endsWith('/review/remember')?Response.json({saved:true}):driveObject(new Request(url,init),store,env)})};
|
||||
let rejectReceipt=false;
|
||||
t.mock.method(globalThis,'fetch',async (url,init)=>{
|
||||
const target=new URL(url);
|
||||
if(target.pathname==='/api/v10/channels/777')return Response.json({id:'777',name:'test thread',type:11,parent_id:supportForum,applied_tags:[]});
|
||||
if(target.pathname==='/api/webhooks/123/public/messages/777')return Response.json({id:'777',channel_id:'777'});
|
||||
if(target.pathname==='/api/v10/channels/777/messages'){
|
||||
assert.equal(init.headers.Authorization,'Bot test');
|
||||
const message=JSON.parse(init.body);
|
||||
const receipt=message.components[0]?.components?.[0]?.content?.startsWith('Drive logs received.');
|
||||
if(rejectReceipt && receipt){rejectReceipt=false;return new Response('',{status:429});}
|
||||
posts.push(!receipt?{invite:message}:{priv:false,body:init.body});
|
||||
return Response.json({id:'456',channel_id:'777'});
|
||||
}
|
||||
if(target.pathname==='/api/v10/channels/888/threads'){
|
||||
assert.equal(init.headers.Authorization,'Bot test');
|
||||
const {name,message}=JSON.parse(init.body.get('payload_json'));
|
||||
assert.match(name,/Drive logs/);assert.match(message.components[0].components[0].content,/Reference/);assert.ok(message.components[0].components.some(c=>c.type===13));
|
||||
posts.push({priv:true,body:init.body});
|
||||
return Response.json({id:'222',parent_id:'888',message:{id:'111',channel_id:'222'}});
|
||||
}
|
||||
const priv=target.pathname.endsWith('/private');
|
||||
if(init.method!=='POST')return Response.json({guild_id:'1',channel_id:priv?'888':supportForum});
|
||||
if(!priv && rejectReceipt){rejectReceipt=false;return new Response('',{status:429});}
|
||||
if(!priv&&typeof init.body==='string'&&JSON.parse(init.body).content.startsWith('Submit your drive logs privately:')){
|
||||
assert.equal(target.searchParams.get('thread_id'),'777');
|
||||
assert.equal(target.searchParams.get('wait'),'true');
|
||||
posts.push({invite:JSON.parse(init.body)});
|
||||
return Response.json({id:'456',channel_id:'777'});
|
||||
}
|
||||
posts.push({priv,body:init.body});
|
||||
if(!priv)assert.equal(target.searchParams.get('thread_id'),'777');
|
||||
return Response.json({id:'111',channel_id:priv?'222':'777'});
|
||||
});
|
||||
const form=()=>{const data=new FormData();data.set('route','https://connect.comma.ai/test/drive');data.set('note','private test note');data.set('time','6:49');return data;};
|
||||
const send=body=>run('/drive/send',{method:'POST',body});
|
||||
return {env,store,run,form,posts,send,rejectOnce:()=>{rejectReceipt=true;}};
|
||||
}
|
||||
|
||||
test('issue a link, deliver private details and attach a segment, publish only a receipt',async t=>{
|
||||
const f=fixture(t);
|
||||
const {url}=await (await issueDriveLink(f.env,'777','https://example.com')).json();
|
||||
const token=new URL(url).pathname.split('/').pop();
|
||||
assert.match(token,/^[a-f0-9]{64}$/);
|
||||
assert.match(await (await drivePage(new Request(url),f.env,token)).text(),/private support forum/);
|
||||
const data=f.form();data.set('log',new Blob([new Uint8Array([40,181,47,253])]),'rlog.zst');
|
||||
assert.equal((await f.send(data)).status,200);
|
||||
assert.equal(f.posts.length,2);
|
||||
const [priv,pub]=f.posts;
|
||||
assert.ok(priv.priv);
|
||||
assert.match(await priv.body.get('files[0]').text(),/private test note/);
|
||||
assert.equal(priv.body.get('files[1]').name,'rlog.zst');
|
||||
const state=await f.store.get('drive');
|
||||
assert.equal(JSON.parse(pub.body).components[0].components[0].content,'Drive logs received. Reference: '+state.reference);
|
||||
await f.send(f.form());
|
||||
assert.equal(f.posts.length,2);
|
||||
});
|
||||
test('a retry delivers the receipt without duplicating the private post',async t=>{
|
||||
const f=fixture(t);
|
||||
await issueDriveLink(f.env,'777','https://example.com');
|
||||
f.rejectOnce();
|
||||
assert.equal((await f.send(f.form())).status,503);
|
||||
assert.equal((await f.send(f.form())).status,200);
|
||||
assert.equal(f.posts.filter(p=>p.priv).length,1);
|
||||
});
|
||||
test('reject arbitrary URLs, expired invitations and files with invalid compression',async t=>{
|
||||
const f=fixture(t);
|
||||
await issueDriveLink(f.env,'777','https://example.com');
|
||||
const data=f.form();data.set('route','https://other.example/test');
|
||||
assert.equal((await f.send(data)).status,400);
|
||||
const bad=f.form();bad.set('log',new Blob(['bad']),'qlog.zst');
|
||||
assert.equal((await f.send(bad)).status,400);
|
||||
await f.store.put('drive',{expires:0});
|
||||
assert.equal((await f.send(f.form())).status,410);
|
||||
assert.equal(f.posts.length,0);
|
||||
});
|
||||
test('R2 download requires the private download token and expires',async t=>{
|
||||
const f=fixture(t);let bytes;
|
||||
f.env.DRIVE_FILES={put:async(k,stream)=>{bytes=await new Response(stream).arrayBuffer();},get:async()=>({body:bytes})};
|
||||
await issueDriveLink(f.env,'777','https://example.com');
|
||||
const data=f.form();data.set('log',new Blob([new Uint8Array([40,181,47,253])]),'rlog.zst');
|
||||
await f.send(data);
|
||||
const state=await f.store.get('drive');
|
||||
assert.equal((await f.run('/drive/file/wrong')).status,404);
|
||||
const download=await f.run('/drive/file/'+state.downloadToken);
|
||||
assert.equal((await download.arrayBuffer()).byteLength,4);
|
||||
await f.store.put('drive',{...state,fileExpires:0});
|
||||
assert.equal((await f.run('/drive/file/'+state.downloadToken)).status,404);
|
||||
});
|
||||
|
||||
test('Companion-Bot sends the drive link once to its original thread',async t=>{
|
||||
const f=fixture(t);
|
||||
const {url}=await (await issueDriveLink(f.env,'777','https://example.com')).json();
|
||||
const token=new URL(url).pathname.split('/').pop();
|
||||
assert.equal((await sendDriveInvite(f.env,'777',token)).status,200);
|
||||
assert.equal((await sendDriveInvite(f.env,'777',token)).status,200);
|
||||
assert.equal(f.posts.length,1);
|
||||
assert.equal(f.posts[0].invite.components[1].components[0].url,url);
|
||||
assert.deepEqual(f.posts[0].invite.allowed_mentions.parse,[]);
|
||||
});
|
||||
|
||||
test('dashboard can issue a link for a saved report without bot access',async t=>{
|
||||
const f=fixture(t);
|
||||
delete f.env.DISCORD_BOT_TOKEN;
|
||||
const report={title:'Test report',threadURL:'https://discord.com/channels/1/777/777'};
|
||||
const response=await issueDriveLink(f.env,'777','https://example.com',report);
|
||||
assert.equal(response.status,200);
|
||||
const {url}=await response.json();
|
||||
const token=new URL(url).pathname.split('/').pop();
|
||||
assert.equal((await sendDriveInvite(f.env,'778',token)).status,409);
|
||||
assert.equal((await sendDriveInvite(f.env,'777',token)).status,200);
|
||||
assert.equal((await sendDriveInvite(f.env,'777',token)).status,200);
|
||||
assert.equal(f.posts.length,1);
|
||||
});
|
||||
|
||||
for (const [kind,page] of [['controller','Controller'],['connection','Phone App'],['starport','StarPort / Car Screen']]) {
|
||||
test('bot posts the selected '+kind+' Galaxy instructions in the requesting thread',async t=>{
|
||||
const f=fixture(t);
|
||||
const {url}=await (await issueDriveLink(f.env,'777','https://example.com',{userID:'555',platform:'ios'},kind)).json();
|
||||
const token=new URL(url).pathname.split('/').pop();
|
||||
assert.deepEqual(await (await sendDriveInvite(f.env,'777',token)).json(),{sent:true});
|
||||
const {invite}=f.posts[0];
|
||||
assert.equal(invite.components[0].content,'<@555>');
|
||||
assert.equal(invite.flags,32768);
|
||||
assert.equal(invite.components[1].type,17);
|
||||
const [intro,divider,help]=invite.components[1].components;
|
||||
assert.ok(intro.content.includes('Logs & Diagnostics → Get help → '+page));
|
||||
assert.match(intro.content,/Post to, select “test thread” and tap Post report/);
|
||||
assert.equal(divider.type,14);
|
||||
assert.match(help.content,/Local Galaxy address/);
|
||||
assert.doesNotMatch(JSON.stringify(invite),/Get my code|Find report|Capture and send|Older Galaxy/i);
|
||||
assert.deepEqual(invite.allowed_mentions.users,['555']);
|
||||
assert.equal(invite.components[2].components[0].label,'Give feedback');
|
||||
assert.match(url,/[/]report[/]galaxy[/]fresh[/]/);
|
||||
assert.deepEqual(invite.allowed_mentions.parse,[]);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
const topics={
|
||||
connection:['Phone App','Send phone app logs'],
|
||||
controller:['Controller','Send controller logs'],
|
||||
starport:['StarPort / Car Screen','Send StarPort logs'],
|
||||
};
|
||||
|
||||
export function galaxyLogSteps(record){
|
||||
const [topic,send]=topics[record.kind];
|
||||
const detail=record.kind==='connection'?'Select '+(record.platform==='android'?'Android':'iPhone')+' and describe the issue':
|
||||
record.kind==='controller'?'Enter your controller model and describe the issue':'Describe what happened';
|
||||
return [
|
||||
'In Galaxy, open Logs & Diagnostics → Get help → '+topic+'.',
|
||||
detail+', then tap '+send+'. The comma needs internet to upload.',
|
||||
'If the browser doesn’t open, tap Continue on Discord support. Sign in with the Discord account that opened this thread.',
|
||||
'Under Post to, select “'+String(record.title||'this support thread').replace(/[\r\n]/g,' ').slice(0,100)+'” and tap Post report. Only support staff receive the ZIP.',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import {botPost,privateCard,supportCard} from './bot-delivery.mjs';
|
||||
import {caseButtons} from './case-actions.mjs';
|
||||
import {discordTags,supportForum,supportTags} from './thread-tags.mjs';
|
||||
|
||||
const guild='1387432184121393333';
|
||||
const command='Refer to Companion Support';
|
||||
const object=env=>env.REPORTS.get(env.REPORTS.idFromName('driving-referral-review'));
|
||||
const rules=[
|
||||
['StarPort',/\b(?:star[ -]?port|android[ -]?auto)\b/i],
|
||||
['Bluetooth controller',/\b(?:(?:bluetooth|bt|usb|wireless|game)[ -]?controllers?|gamepads?|dualsense|joy[ -]?cons?)\b/i],
|
||||
['Phone app',/\b(?:car[ -]?play|galaxy|companion|apps?|phones?|iphones?|android|ios|bluetooth|bt|wi[ -]?fi|hotspots?|mdns|bonjour|sentry|tunnel)\b/i],
|
||||
];
|
||||
export function discover(summary){
|
||||
for(const [category,pattern] of rules){
|
||||
for(const line of summary.split('\n')){
|
||||
const index=line.search(pattern);
|
||||
if(index>=0)return {category,evidence:line.slice(Math.max(0,index-140),index+300).trim()};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const id=value=>/^\d{17,20}$/.test(value||'');
|
||||
const configured=env=>id(env.COMPANION_REVIEW_THREAD_ID) && id(env.DRIVING_SAMPLE_THREAD_ID);
|
||||
async function resolveSource(store,env){
|
||||
const key='source:'+env.DRIVING_SAMPLE_THREAD_ID;
|
||||
let source=await store.get(key);
|
||||
if(!source){
|
||||
const path='/channels/'+env.DRIVING_SAMPLE_THREAD_ID;
|
||||
const thread=await discordTags(env,path);
|
||||
if(thread.guild_id!==guild || thread.type!==11 || !id(thread.parent_id) || thread.parent_id===supportForum)throw Error('Driving sample is outside the expected forum');
|
||||
const parent=await discordTags(env,'/channels/'+thread.parent_id);
|
||||
const msg=await discordTags(env,path+'/messages/'+thread.id);
|
||||
if(parent.type!==15 || parent.guild_id!==guild || !id(msg.author?.id) || !reportDetails(msg,msg.author.id))throw Error('Driving sample report fields unavailable');
|
||||
source={DRIVING_FORUM_ID:parent.id,DRIVING_REPORT_BOT_ID:msg.author.id};
|
||||
await store.put(key,source);
|
||||
}
|
||||
return {...env,...source};
|
||||
}
|
||||
async function staffDestination(env){
|
||||
const t=await discordTags(env,'/channels/'+env.COMPANION_REVIEW_THREAD_ID);
|
||||
if(t.guild_id!==guild || t.thread_metadata?.archived || t.thread_metadata?.locked)throw Error('Review thread unavailable');
|
||||
if(t.type===12)return;
|
||||
if(t.type===0){
|
||||
const everyone=t.permission_overwrites?.find(p=>p.id===guild && p.type===0);
|
||||
if(BigInt(everyone?.deny||0)&1024n)return;
|
||||
throw Error('Review channel must restrict View Channel');
|
||||
}
|
||||
if(t.type!==11 || t.parent_id===env.DRIVING_FORUM_ID || t.parent_id===supportForum)throw Error('Staff-only thread required');
|
||||
const parent=await discordTags(env,'/channels/'+t.parent_id);
|
||||
const everyone=parent.permission_overwrites?.find(p=>p.id===guild && p.type===0);
|
||||
if(!(BigInt(everyone?.deny||0)&1024n))throw Error('Review forum must restrict View Channel');
|
||||
}
|
||||
const urlFor=id=>'https://discord.com/channels/'+guild+'/'+id;
|
||||
const clean=text=>String(text).replace(/https?:\/\/\S+/gi,'[link omitted]').replace(/<[@#][^>]+>/g,'[mention omitted]').slice(0,1800);
|
||||
export function reportDetails(message,bot){
|
||||
if(message.author?.id!==bot || !message.author?.bot)return null;
|
||||
const embeds=message.embeds||[];
|
||||
const fields=embeds.flatMap(embed=>embed.fields||[]);
|
||||
const by=fields.find(f=>/^(by|reporter|submitted by|requested by)$/i.test(f.name.trim()))?.value;
|
||||
const reporter=/^<@!?(\d{17,20})>/.exec(by||message.content||'')?.[1];
|
||||
if(!reporter)return null;
|
||||
const metadata=/wiki|related article|assigned|route (?:link|tracker|id)|donation|reported by|^by$|^reporter$|^submitted by$|^requested by$/i;
|
||||
const body=text=>clean(String(text||'').split(/(?:potentially related wiki articles|mods route tracker|starpilot is free)/i)[0]);
|
||||
const parts=[...embeds.flatMap(embed=>[body(embed.title),body(embed.description)]),
|
||||
...fields.filter(f=>!metadata.test(f.name)).map(f=>body(f.value))].filter(Boolean);
|
||||
const observed=body(fields.find(f=>/^observed behavio[u]?r$/i.test(f.name.trim()))?.value)||parts[0];
|
||||
const opening=body((message.content||'').replace(/^<@!?\d+>/,'').trim());
|
||||
const sections=[opening,...embeds.map(embed=>body(embed.description)),
|
||||
...fields.filter(field=>!metadata.test(field.name)&&body(field.value))
|
||||
.map(field=>'**'+clean(field.name)+'**\n'+body(field.value))].filter(Boolean);
|
||||
return {reporter,observed,summary:[opening,...parts].filter(Boolean).join('\n'),reportText:sections.join('\n\n')};
|
||||
|
||||
}
|
||||
async function offer(store,env,thread,manual=false){
|
||||
const key='report:'+thread.id;
|
||||
const existing=await store.get(key);
|
||||
if(existing)return existing.state==='ignored' && manual?offerIgnored():false;
|
||||
return offerIgnored();
|
||||
async function offerIgnored(){
|
||||
const msg=await discordTags(env,'/channels/'+thread.id+'/messages/'+thread.id);
|
||||
const details=reportDetails(msg,env.DRIVING_REPORT_BOT_ID);
|
||||
if(!details)return false;
|
||||
const title=clean(thread.name||'');
|
||||
const match=discover([title,details.summary].join('\n'));
|
||||
details.observed ||= title;
|
||||
if(!manual&&!match){await store.put(key,{state:'ignored'});return false;}
|
||||
const record={...details,source:thread.id,state:'pending',category:match?.category||'Staff referral',evidence:match?.evidence||details.summary.slice(0,450)};
|
||||
const reserved=await store.transaction(async tx=>{
|
||||
const old=await tx.get(key);
|
||||
if(old && !(manual&&old.state==='ignored'))return false;
|
||||
await tx.put(key,record);return true;
|
||||
});
|
||||
if(!reserved)return false;
|
||||
const buttons={type:1,components:[['leave','Leave as is',2],['move','Move to Companion Logs',1]].map(([action,label,style])=>({type:2,style,label,custom_id:'refer:'+action+':'+thread.id}))};
|
||||
const reviewers=[...new Set([env.REPORT_MAINTAINER_ID,env.ANDROID_REPORT_MAINTAINER_ID,env.FIRESTAR_DISCORD_USER_ID].filter(id))];
|
||||
const text=['**Possible '+record.category+' report**',record.evidence,'','[Open driving report]('+urlFor(thread.id)+')',
|
||||
reviewers.map(user=>'<@'+user+'>').join(' ')].filter(Boolean).join('\n');
|
||||
const card=supportCard('',text,[],[buttons]);
|
||||
const sent=await botPost(env,env.COMPANION_REVIEW_THREAD_ID,{...card,flags:card.flags|4096,allowed_mentions:{parse:[],users:reviewers},nonce:thread.id,enforce_nonce:true});
|
||||
if(!sent.ok){if(sent.status>=400&&sent.status<500)await store.delete(key);throw Error('Review delivery unconfirmed');}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
export async function pollReferrals(env){
|
||||
if(!configured(env))return;
|
||||
const res=await object(env).fetch('https://reports/referrals/scan',{method:'POST'});
|
||||
if(!res.ok)throw Error('Referral scan unavailable');
|
||||
}
|
||||
export async function referralStore(path,request,store,env){
|
||||
if(!configured(env))return Response.json({message:'Referral review is awaiting setup.'},{status:503});
|
||||
env=await resolveSource(store,env);
|
||||
await staffDestination(env);
|
||||
if(path.endsWith('/scan')){
|
||||
const start=await store.get('start');
|
||||
if(!start){await store.put('start',Date.now());return Response.json({ready:true});}
|
||||
const {threads}=await discordTags(env,'/guilds/'+guild+'/threads/active');
|
||||
const candidates=threads.filter(t=>t.parent_id===env.DRIVING_FORUM_ID && id(t.id) && Number(BigInt(t.id)>>22n)+1420070400000>=start);
|
||||
let examined=0;
|
||||
for(const t of candidates){
|
||||
if(await store.get('report:'+t.id))continue;
|
||||
if(examined++>=8)break;
|
||||
const retry='retry:'+t.id;
|
||||
if((await store.get(retry))>Date.now()){examined--;continue;}
|
||||
try{await offer(store,env,t);}finally{await store.put(retry,Date.now()+300000);}
|
||||
}
|
||||
return Response.json({ok:true});
|
||||
}
|
||||
const {action,source,actor}=await request.json();
|
||||
if(!id(source)||!id(actor))return Response.json({message:'Invalid referral.'});
|
||||
if(action==='manual'){
|
||||
const thread=await discordTags(env,'/channels/'+source);
|
||||
if(thread.guild_id!==guild||thread.parent_id!==env.DRIVING_FORUM_ID)return Response.json({message:'Use this command in a driving report thread.'});
|
||||
const offered=await offer(store,env,thread,true);
|
||||
return Response.json({message:offered?'Sent to staff review.':'Already reviewed or the original StarBot summary is unavailable.'});
|
||||
}
|
||||
const key='report:'+source;
|
||||
if(!['leave','move'].includes(action))return Response.json({message:'Unknown referral action.'});
|
||||
const record=await store.transaction(async tx=>{
|
||||
const current=await tx.get(key);
|
||||
if(current?.state!=='pending')return null;
|
||||
await tx.put(key,{...current,state:action==='leave'?'dismissed':'creating',actor});
|
||||
return current;
|
||||
});
|
||||
if(!record){
|
||||
const current=await store.get(key);
|
||||
if(action==='move' && current?.destination)return finishMove(store,env,key,current);
|
||||
return Response.json({message:'This referral has already been handled or is awaiting delivery confirmation.'});
|
||||
}
|
||||
if(action==='leave')return Response.json({message:'Left in driving feedback.'});
|
||||
const reportKind=record.category==='StarPort'?'starport':record.category==='Bluetooth controller'?'controller':'connection';
|
||||
const platform=reportKind==='starport'||/android/i.test(record.observed)?'android':'ios';
|
||||
const title=record.category+' — '+record.observed.replace(/\s+/g,' ').slice(0,68);
|
||||
const tags=[supportTags.Open];
|
||||
if(reportKind==='controller'&&id(env.CONTROLLER_FORUM_TAG_ID))tags.push(env.CONTROLLER_FORUM_TAG_ID);
|
||||
else if(reportKind==='starport'||/android|iphone|carplay|\bios\b/i.test(record.observed))tags.push(supportTags[platform==='ios'?'iOS':'Android']);
|
||||
const recipients=[...new Set([record.reporter,env.REPORT_MAINTAINER_ID,env.ANDROID_REPORT_MAINTAINER_ID].filter(id))];
|
||||
const mentions=recipients.map(user=>'<@'+user+'>').join(' ');
|
||||
const original=record.reportText||record.summary||record.observed;
|
||||
const excerpt=original.length>3200?original.slice(0,3199)+'…':original;
|
||||
const card=supportCard('',mentions+'\n\n**'+record.category+' support**\n'+excerpt+'\n\n[Original driving report]('+urlFor(source)+')',caseButtons(record.reporter,platform));
|
||||
const receipt=await botPost(env,supportForum,{...card,thread_name:title,applied_tags:tags,allowed_mentions:{parse:[],users:recipients}});
|
||||
if(!receipt.ok){
|
||||
if(receipt.status>=400&&receipt.status<500)await store.put(key,record);
|
||||
return Response.json({message:'Discord did not confirm the Companion ticket. Check the forum before retrying.'});
|
||||
}
|
||||
const destination=(await receipt.json()).channel_id;
|
||||
const moved={...record,actor,state:'created',destination,title,platform,reportKind,created:Date.now()};
|
||||
await store.put(key,moved);
|
||||
return finishMove(store,env,key,moved);
|
||||
}
|
||||
|
||||
async function finishMove(store,env,key,record){
|
||||
if(record.state!=='moved'){
|
||||
const owner=env.REPORTS.get(env.REPORTS.idFromName(record.reporter));
|
||||
const result=await owner.fetch('https://reports/register-referral',{method:'POST',body:JSON.stringify({
|
||||
id:record.destination,title:record.title,platform:record.platform,reportKind:record.reportKind,created:record.created,reporter:record.reporter
|
||||
})});
|
||||
if(!result.ok)throw Error('Could not register Companion ticket');
|
||||
await store.put(key,{...record,state:'moved'});
|
||||
}
|
||||
const link='[Open the Companion ticket]('+urlFor(record.destination)+')';
|
||||
if(record.sourceClosed)return Response.json({message:'Driving thread closed. '+link});
|
||||
try{
|
||||
const path='/channels/'+record.source;
|
||||
const thread=await discordTags(env,path);
|
||||
if(thread.id!==record.source || thread.type!==11 || thread.guild_id!==guild || thread.parent_id!==env.DRIVING_FORUM_ID)
|
||||
throw Error('Original driving thread could not be verified.');
|
||||
const forum=await discordTags(env,'/channels/'+thread.parent_id);
|
||||
const tags=forum.available_tags||[];
|
||||
const closed=tags.filter(tag=>tag.name.trim().toLowerCase()==='closed');
|
||||
if(closed.length>1)throw Error('The driving forum has multiple Closed tags.');
|
||||
const patch={archived:true};
|
||||
const remove=tags.filter(tag=>{
|
||||
const name=tag.name.trim().toLowerCase();
|
||||
return /^(?:[^a-z0-9]*)(?:waiting for dev(?:eloper)?s?)\s*$/.test(name)
|
||||
|| (closed.length && ['open','in progress'].includes(name));
|
||||
}).map(tag=>tag.id);
|
||||
const applied=thread.applied_tags.filter(tag=>!remove.includes(tag));
|
||||
if(closed.length&&!applied.includes(closed[0].id))applied.push(closed[0].id);
|
||||
if(applied.length>5)throw Error('The driving thread has no room for its Closed tag.');
|
||||
if(applied.length!==thread.applied_tags.length||applied.some(tag=>!thread.applied_tags.includes(tag)))patch.applied_tags=applied;
|
||||
let postedNotice=false;
|
||||
if(!record.moveNotice){
|
||||
const notice=supportCard('','**Moved to Companion Logs**\nStaff moved this report to Companion support. Your original report is linked there. Please post updates and reply to staff in the new ticket.\n\n'+link,[]);
|
||||
const sent=await botPost(env,record.source,{...notice,flags:notice.flags|4096,allowed_mentions:{parse:[]},nonce:'move-'+record.source,enforce_nonce:true});
|
||||
if(!sent.ok)return Response.json({message:'Companion ticket created. Discord did not confirm the notice in the original thread. Check Send Messages in Threads and retry Move. '+link});
|
||||
const receipt=await sent.json();
|
||||
if(!id(receipt.id)||receipt.channel_id!==record.source)throw Error('Missing move notice receipt');
|
||||
record={...record,state:'moved',moveNotice:receipt.id};
|
||||
await store.put(key,record);
|
||||
postedNotice=true;
|
||||
}
|
||||
if(postedNotice || !thread.thread_metadata?.archived || patch.applied_tags){
|
||||
const updated=await discordTags(env,path,patch);
|
||||
if(updated.id!==record.source || !updated.thread_metadata?.archived || updated.applied_tags?.some(tag=>remove.includes(tag)) || (closed.length&&!updated.applied_tags?.includes(closed[0].id)))
|
||||
throw Error('Discord did not confirm the close.');
|
||||
}
|
||||
await store.put(key,{...record,state:'moved',sourceClosed:true});
|
||||
return Response.json({message:'Driving thread closed. '+link});
|
||||
}catch{
|
||||
return Response.json({message:'Companion ticket created. Closing the driving thread could not be confirmed. Check the forum permissions and tags, then choose Move again to retry. '+link});
|
||||
}
|
||||
}
|
||||
|
||||
export function isReferral(i){
|
||||
return (i.type===2 && i.data?.type===3 && i.data.name===command) || (i.type===3 && /^refer:(leave|move):\d{17,20}$/.test(i.data?.custom_id||''));
|
||||
}
|
||||
export async function referralInteraction(i,env,ctx){
|
||||
const reply=text=>Response.json({type:4,data:privateCard(text)});
|
||||
const manual=i.type===2;
|
||||
if(!configured(env)||i.guild_id!==guild||(!manual && i.channel_id!==env.COMPANION_REVIEW_THREAD_ID))return reply('Use the configured support review thread.');
|
||||
const settings=env.REPORTS.get(env.REPORTS.idFromName('companion-bot-setup'));
|
||||
const sage=await settings.fetch('https://reports/sage-role');
|
||||
if(!sage.ok || !i.member?.roles?.includes((await sage.json()).id))return reply('This action requires StarPilot Sage.');
|
||||
const [,action,source]=manual?['','manual',i.channel_id]:i.data.custom_id.split(':');
|
||||
ctx.waitUntil((async()=>{
|
||||
let text='Could not confirm this referral. Check the review thread.';
|
||||
try{
|
||||
const res=await object(env).fetch('https://reports/referrals/action',{method:'POST',body:JSON.stringify({action,source,actor:i.member.user.id})});
|
||||
text=(await res.json()).message||text;
|
||||
}finally{
|
||||
await fetch('https://discord.com/api/v10/webhooks/'+i.application_id+'/'+i.token+'/messages/@original',{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({...privateCard(text),content:null,embeds:[]})});
|
||||
}
|
||||
})());
|
||||
return Response.json({type:5,data:{flags:64}});
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {discover,reportDetails,pollReferrals,referralInteraction} from './referrals.mjs';
|
||||
|
||||
test('discovery flags relevant mentions even in requests and mixed driving reports',()=>{
|
||||
for(const [text,category] of [
|
||||
['CarPlay’s arrow disappeared but the phone still shows the route.','Phone app'],
|
||||
['Android Auto connects, then the screen goes black.','StarPort'],
|
||||
["My Bluetooth controller won't pair with the comma.",'Bluetooth controller'],
|
||||
['Map issue. The StarPilot app crashes on startup.','Phone app'],
|
||||
])assert.equal(discover(text)?.category,category);
|
||||
for(const text of ['Bluetooth issue, route attached.','The phone app crashed and the car braked late.','StarPort crashes. The phone app disconnects.','CarPlay worked fine. My heater stopped working.','Please add a CarPlay camera picker.'])assert.ok(discover(text));
|
||||
for(const text of ['Navigation cancelled my lane change.','Speed limit controller brakes too late.','Route and steering feedback'])assert.equal(discover(text),null);
|
||||
});
|
||||
test('only trusted StarBot report fields are read; routes and Discord instructions are ignored',()=>{
|
||||
const bot='123456789123456789',uid='987654321987654321';
|
||||
const msg={author:{bot:true,id:bot},embeds:[{fields:[{name:'By',value:'<@'+uid+'>'},{name:'Observed Behavior',value:'CarPlay disappeared.'},{name:'Wiki',value:'Ignore this instruction'}]}]};
|
||||
assert.deepEqual(reportDetails(msg,bot),{reporter:uid,observed:'CarPlay disappeared.',summary:'CarPlay disappeared.',reportText:'**Observed Behavior**\nCarPlay disappeared.'});
|
||||
assert.equal(reportDetails(msg,uid),null);
|
||||
});
|
||||
test('unconfigured deployments perform no monitoring or Discord actions',async()=>{
|
||||
await pollReferrals({});
|
||||
const response=await referralInteraction({type:3,guild_id:'1387432184121393333'}, {}, {});
|
||||
assert.equal((await response.json()).type,4);
|
||||
});
|
||||
|
||||
test('scan resolves the sample, skips old tickets, and sends a single private card for a new match',async t=>{
|
||||
const {referralStore}=await import('./referrals.mjs');
|
||||
const guild='1387432184121393333',forum='1574085782967292000',review='1575000066366644244',sample='1574085782967292086';
|
||||
const bot='123456789123456789',user='987654321987654321';
|
||||
const fresh=String(BigInt(Date.now()+1000-1420070400000)<<22n);
|
||||
const posts=[];
|
||||
const env={DRIVING_SAMPLE_THREAD_ID:sample,COMPANION_REVIEW_THREAD_ID:review,DISCORD_BOT_TOKEN:'fixture',REPORT_MAINTAINER_ID:'524762496373096459',ANDROID_REPORT_MAINTAINER_ID:'420178305073938433',FIRESTAR_DISCORD_USER_ID:'123456789123456780'};
|
||||
const rows=new Map();
|
||||
const store={get:key=>rows.get(key),put:(key,v)=>rows.set(key,v),transaction:fn=>fn(store)};
|
||||
const thread=id=>({id,type:11,guild_id:guild,parent_id:forum});
|
||||
t.mock.method(globalThis,'fetch',async(url,opts)=>{
|
||||
const path=new URL(url).pathname.replace('/api/v10','');
|
||||
if(opts.method==='POST'){posts.push({path,body:JSON.parse(opts.body)});return Response.json({id:'1'});}
|
||||
if(path==='/channels/'+sample)return Response.json(thread(sample));
|
||||
if(path==='/channels/'+forum)return Response.json({id:forum,type:15,guild_id:guild});
|
||||
if(path==='/channels/'+review)return Response.json({type:12,guild_id:guild});
|
||||
if(path==='/guilds/'+guild+'/threads/active')return Response.json({threads:[thread(sample),thread(fresh)]});
|
||||
if([sample,fresh].some(id=>path==='/channels/'+id+'/messages/'+id))return Response.json({author:{id:bot,bot:true},embeds:[{fields:[{name:'By',value:'<@'+user+'>'},{name:'Observed Behavior',value:'StarPort crashes.'}]}]});
|
||||
throw Error('Unexpected access '+path);
|
||||
});
|
||||
for(let i=0;i<3;i++)await referralStore('/referrals/scan',{},store,env);
|
||||
assert.equal(posts.length,1);
|
||||
assert.ok(posts[0].body.flags & 4096);
|
||||
assert.deepEqual(posts[0].body.allowed_mentions,{parse:[],users:[env.REPORT_MAINTAINER_ID,env.ANDROID_REPORT_MAINTAINER_ID,env.FIRESTAR_DISCORD_USER_ID]});
|
||||
const [card]=posts[0].body.components;
|
||||
assert.equal(card.type,17);
|
||||
for(const user of posts[0].body.allowed_mentions.users)assert.ok(card.components[0].content.includes('<@'+user+'>'));
|
||||
assert.equal(posts[0].path,'/channels/'+review+'/messages');
|
||||
assert.deepEqual(card.components.at(-1).components.map(b=>b.label),['Leave as is','Move to Companion Logs']);
|
||||
assert.ok(rows.has('report:'+fresh));
|
||||
assert.ok(!rows.has('report:'+sample));
|
||||
});
|
||||
|
||||
test('feature requests use the title and report fields while wiki suggestions and route links stay out',()=>{
|
||||
const bot='123456789123456789', reporter='987654321987654321';
|
||||
const details=(fields,description='')=>reportDetails({author:{id:bot,bot:true},content:'<@'+reporter+'>',embeds:[{title:'Feature Request',description,fields}]},bot);
|
||||
assert.equal(discover(details([{name:'Proposed improvement',value:'Show the camera on CarPlay.'}]).summary).category,'Phone app');
|
||||
assert.equal(discover(details([{name:'Potentially Related Wiki Articles',value:'Bluetooth Controls'},{name:'Route link',value:'https://galaxy.test'}],'Steering felt heavy.\nMods Route Tracker →\nPotentially Related Wiki Articles\nCarPlay').summary),null);
|
||||
});
|
||||
|
||||
test('leave as is and unauthorized clicks never write to the original forum',async t=>{
|
||||
const {referralStore}=await import('./referrals.mjs');
|
||||
const sample='1574085782967292086',review='1575000066366644244',guild='1387432184121393333';
|
||||
const env={DRIVING_SAMPLE_THREAD_ID:sample,COMPANION_REVIEW_THREAD_ID:review,DISCORD_BOT_TOKEN:'fixture',REPORTS:{idFromName:n=>n,get:()=>({fetch:()=>Response.json({id:'sage'})})}};
|
||||
const rows=new Map([['source:'+sample,{DRIVING_FORUM_ID:'1574085782967292000',DRIVING_REPORT_BOT_ID:'123456789123456789'}],['report:'+sample,{state:'pending'}]]);
|
||||
const store={get:k=>rows.get(k),put:(k,v)=>rows.set(k,v),transaction:fn=>fn(store)};
|
||||
t.mock.method(globalThis,'fetch',async(url,opts)=>{
|
||||
assert.equal(opts.method,'GET');
|
||||
assert.ok(url.endsWith('/channels/'+review));
|
||||
return Response.json({guild_id:guild,type:12});
|
||||
});
|
||||
const click={type:3,guild_id:guild,channel_id:review,data:{custom_id:'refer:move:'+sample},member:{roles:[]}};
|
||||
assert.match(JSON.stringify(await (await referralInteraction(click,env,{})).json()),/requires StarPilot Sage/);
|
||||
const res=await referralStore('/referrals/action',{json:()=>({action:'leave',source:sample,actor:'987654321987654321'})},store,env);
|
||||
assert.equal((await res.json()).message,'Left in driving feedback.');
|
||||
assert.equal(rows.get('report:'+sample).state,'dismissed');
|
||||
});
|
||||
|
||||
test('Move closes only after registration and retries the same destination on a Discord failure',async t=>{
|
||||
const {referralStore}=await import('./referrals.mjs');
|
||||
const sample='1574085782967292086',review='1575000066366644244',source='1574085782967292087',forum='1574085782967292000',guild='1387432184121393333';
|
||||
const destination='1574085782967292090';
|
||||
const rows=new Map([['source:'+sample,{DRIVING_FORUM_ID:forum,DRIVING_REPORT_BOT_ID:'123456789123456789'}],['report:'+source,{source,state:'created',destination,reporter:'987654321987654321'}]]);
|
||||
const store={get:k=>rows.get(k),put:(k,v)=>rows.set(k,v),transaction:fn=>fn(store)};
|
||||
let registered=false,allowClose=false,allowNotice=false,notices=0,patches=0;
|
||||
const env={DRIVING_SAMPLE_THREAD_ID:sample,COMPANION_REVIEW_THREAD_ID:review,DISCORD_BOT_TOKEN:'fixture',REPORTS:{idFromName:n=>n,get:()=>({fetch:()=>new Response('',{status:registered?200:503})})}};
|
||||
t.mock.method(globalThis,'fetch',async(url,opts)=>{
|
||||
const path=new URL(url).pathname.replace('/api/v10','');
|
||||
if(path==='/channels/'+review)return Response.json({type:12,guild_id:guild});
|
||||
if(path==='/channels/'+forum)return Response.json({available_tags:[{id:'1',name:'OPEN'},{id:'3',name:'CLOSED'},{id:'4',name:'Waiting for Dev'}]});
|
||||
if(path==='/channels/'+source+'/messages'){
|
||||
assert.equal(opts.method,'POST');
|
||||
const notice=JSON.parse(opts.body);
|
||||
assert.ok(notice.components[0].components[0].content.includes(destination));
|
||||
assert.deepEqual(notice.allowed_mentions,{parse:[]});
|
||||
if(!allowNotice)return new Response('',{status:403});
|
||||
notices++;
|
||||
return Response.json({id:'987654321987654320',channel_id:source});
|
||||
}
|
||||
assert.equal(path,'/channels/'+source);
|
||||
if(opts.method==='GET')return Response.json({type:11,guild_id:guild,parent_id:forum,id:source,applied_tags:['1','2','4'],thread_metadata:{archived:false}});
|
||||
assert.equal(opts.method,'PATCH');
|
||||
assert.deepEqual(JSON.parse(opts.body),{archived:true,applied_tags:['2','3']});
|
||||
patches++;
|
||||
return allowClose?Response.json({id:source,thread_metadata:{archived:true},applied_tags:['2','3']}):new Response('',{status:403});
|
||||
});
|
||||
const click=()=>referralStore('/referrals/action',{json:()=>({action:'move',source,actor:'987654321987654321'})},store,env);
|
||||
await assert.rejects(click(),/register/);
|
||||
assert.equal(patches,0);
|
||||
registered=true;
|
||||
assert.match((await (await click()).json()).message,/notice/);
|
||||
assert.equal(patches,0);
|
||||
allowNotice=true;
|
||||
assert.match((await (await click()).json()).message,/could not be confirmed/);
|
||||
allowClose=true;
|
||||
assert.match((await (await click()).json()).message,/Driving thread closed/);
|
||||
await click();
|
||||
assert.equal(patches,2);
|
||||
assert.equal(notices,1);
|
||||
assert.equal(rows.get('report:'+source).destination,destination);
|
||||
});
|
||||
|
||||
test('new linked ticket mentions the original reporter and both maintainers once, excluding review-only recipients',async t=>{
|
||||
const {referralStore}=await import('./referrals.mjs');
|
||||
const guild='1387432184121393333',forum='1574085782967292000',review='1575000066366644244',source='1574085782967292086';
|
||||
const reporter='123456789123456789',nate='524762496373096459',di='420178305073938433',firestar='446126627701915653';
|
||||
const rows=new Map([['source:'+source,{DRIVING_FORUM_ID:forum,DRIVING_REPORT_BOT_ID:reporter}],['report:'+source,{source,reporter,observed:'CarPlay disconnected',reportText:'**Observed Behavior**\nCarPlay disconnected\n\n**Expected Behavior**\nAudio should continue.',category:'Phone app',state:'pending'}]]);
|
||||
const store={get:k=>rows.get(k),put:(k,v)=>rows.set(k,v),transaction:fn=>fn(store)};
|
||||
const env={DRIVING_SAMPLE_THREAD_ID:source,COMPANION_REVIEW_THREAD_ID:review,DISCORD_BOT_TOKEN:'fixture',REPORT_MAINTAINER_ID:nate,ANDROID_REPORT_MAINTAINER_ID:di,FIRESTAR_DISCORD_USER_ID:firestar};
|
||||
const posts=[];
|
||||
t.mock.method(globalThis,'fetch',async(url,opts)=>{
|
||||
if(opts.method==='GET' && url.endsWith('/channels/'+review))return Response.json({type:12,guild_id:guild});
|
||||
assert.ok(url.endsWith('/channels/1565235002734809168/threads'));
|
||||
posts.push(JSON.parse(opts.body).message);
|
||||
return new Response('',{status:403});
|
||||
});
|
||||
for(const user of [reporter,nate]){
|
||||
rows.get('report:'+source).reporter=user;
|
||||
await referralStore('/referrals/action',{json:()=>({action:'move',source,actor:nate})},store,env);
|
||||
}
|
||||
for(const [index,ids] of [[0,[reporter,nate,di]],[1,[nate,di]]]){
|
||||
assert.deepEqual(posts[index].allowed_mentions,{parse:[],users:ids});
|
||||
const text=posts[index].components[0].components[0].content;
|
||||
for(const id of ids)assert.equal(text.split('<@'+id+'>').length,2);
|
||||
assert.ok(!text.includes(firestar));
|
||||
assert.ok(text.includes('Audio should continue.'));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
export const supportForum='1565235002734809168';
|
||||
export const supportTags={Open:'1565236988913913887','In Progress':'1565237023265263657',Closed:'1565237052524466207',Navigation:'1565237084447445122',CarPlay:'1565237111391527112',Galaxy:'1567747425047941200',iOS:'1567744790856990730',Android:'1567744808926322811'};
|
||||
export async function discordTags(env,path,body){
|
||||
if(!env.DISCORD_BOT_TOKEN)throw Error('Tag controls need a Discord bot with View Channel and Manage Threads access.');
|
||||
const response=await fetch('https://discord.com/api/v10'+path,{method:body?'PATCH':'GET',headers:{Authorization:'Bot '+env.DISCORD_BOT_TOKEN,'Content-Type':'application/json'},...(body?{body:JSON.stringify(body)}:{}),redirect:'manual',signal:AbortSignal.timeout(15000)});
|
||||
if(!response.ok)throw Error('Discord tags unavailable (HTTP '+response.status+'). Refresh before retrying.');
|
||||
return response.json();
|
||||
}
|
||||
export async function getReportThread(env,id){
|
||||
const t=await discordTags(env,'/channels/'+id);
|
||||
if(t.id!==id||t.parent_id!==supportForum||t.type!==11||!Array.isArray(t.applied_tags))throw Error('Thread is not in the support forum.');
|
||||
return t;
|
||||
}
|
||||
export function nextReportTags(current,platform,status,topics){
|
||||
if(!['Open','In Progress','Closed'].includes(status)||!Array.isArray(topics)||topics.some(t=>!['Navigation','CarPlay','Galaxy'].includes(t)))throw Error('Invalid status or topic.');
|
||||
const known=new Set(Object.values(supportTags));
|
||||
const tags=[...new Set([...current.filter(t=>!known.has(t)),supportTags[platform==='ios'?'iOS':'Android'],supportTags[status],...topics.map(t=>supportTags[t])])];
|
||||
if(tags.length>5)throw Error('Discord allows five tags. Remove a topic or custom tag first.');
|
||||
return tags;
|
||||
}
|
||||
export async function filterReportThreads(env,items){
|
||||
if(!env.DISCORD_BOT_TOKEN)return items;
|
||||
const forum=await discordTags(env,'/channels/'+supportForum);
|
||||
if(!/^\d+$/.test(forum.guild_id||''))throw Error('Support forum unavailable.');
|
||||
const active=await discordTags(env,'/guilds/'+forum.guild_id+'/threads/active');
|
||||
if(!Array.isArray(active.threads))throw Error('Invalid Discord thread list.');
|
||||
const ids=new Set(active.threads.filter(t=>t.parent_id===supportForum&&!t.applied_tags?.includes(supportTags.Closed)&&!t.thread_metadata?.locked).map(t=>t.id));
|
||||
return items.filter(t=>ids.has(t.id));
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import test from 'node:test';import assert from 'node:assert/strict';
|
||||
import {supportTags,supportForum,nextReportTags,filterReportThreads} from './thread-tags.mjs';
|
||||
test('tag edits preserve custom tags, enforce platform, mutually exclusive status and five-tag limit',()=>{
|
||||
const changed=nextReportTags([supportTags.iOS,supportTags.Open,supportTags.Closed,'custom'],'android','In Progress',['Galaxy']);
|
||||
assert.deepEqual(new Set(changed),new Set(['custom',supportTags.Android,supportTags['In Progress'],supportTags.Galaxy]));
|
||||
assert.throws(()=>nextReportTags(['custom'],'ios','Open',['Navigation','CarPlay','Galaxy']),/five/);
|
||||
assert.throws(()=>nextReportTags([],'ios','Fake',[]),/Invalid/);
|
||||
});
|
||||
test('closed threads disappear and reopened threads return, with two requests regardless of report count',async()=>{
|
||||
const old=globalThis.fetch;let closed=true,calls=0;
|
||||
globalThis.fetch=async url=>{calls++;return Response.json(url.endsWith('/channels/'+supportForum)?{guild_id:'1'}:{threads:[{id:'open',parent_id:supportForum,applied_tags:[]},{id:'changing',parent_id:supportForum,applied_tags:closed?[supportTags.Closed]:[]},{id:'foreign',parent_id:'other',applied_tags:[]}]});};
|
||||
try{const items=['open','changing','archived','foreign'].map(id=>({id}));assert.deepEqual((await filterReportThreads({DISCORD_BOT_TOKEN:'test'},items)).map(x=>x.id),['open']);assert.equal(calls,2);closed=false;assert.deepEqual((await filterReportThreads({DISCORD_BOT_TOKEN:'test'},items)).map(x=>x.id),['open','changing']);assert.equal(calls,4);
|
||||
globalThis.fetch=async()=>new Response('',{status:429});await assert.rejects(filterReportThreads({DISCORD_BOT_TOKEN:'test'},items),/429/);
|
||||
assert.deepEqual(await filterReportThreads({},items),items);
|
||||
}finally{globalThis.fetch=old;}
|
||||
});
|
||||
Reference in New Issue
Block a user