Compare commits

..

17 Commits

Author SHA1 Message Date
natehuby76 944e513e9f add official testing instructions to comma support 2026-11-25 01:16:59 -05:00
natehuby76 13ab471cc5 open private staff actions in older report threads 2026-11-25 01:02:49 -05:00
firestar5683 72aa8b89e1 Test Galaxy layout schema version 17 2026-11-25 00:01:06 -06:00
natehuby76 14babc867a open staff actions from the saved referral 2026-11-25 00:45:41 -05:00
natehuby76 69acfbb085 open staff actions privately from a ticket command 2026-11-25 00:41:25 -05:00
natehuby76 d4ddf420a5 match ticket colors and link fixes to testing requests 2026-11-25 00:33:35 -05:00
Raymond Nguyen 73eb7961d7 Honda Accord: angle steering for the modified EPS firmware 2026-11-24 23:29:49 -06:00
natehuby76 273f8b12e8 explain moved tickets to the reporter 2026-11-25 00:28:03 -05:00
natehuby76 cc36b77b65 share referral replies in the companion bot thread 2026-11-25 00:27:22 -05:00
natehuby76 3ab9f67c83 register the companion referral message command 2026-11-25 00:20:37 -05:00
firestar5683 df47158568 Fix Galaxy and C4 static analysis regressions 2026-11-24 23:11:51 -06:00
natehuby76 bc68e381ae recover companion referrals and confirm phone platform 2026-11-25 00:07:39 -05:00
Prabhaav Pillai f15af75c3a Adj Spot Monitoring for C4 2026-11-25 00:02:35 -05:00
natehuby76 1868dd0b90 update galaxy reporting and companion bot 2026-11-25 00:01:25 -05:00
Raymond Nguyen b51d18fd56 honda: tidy the Accord carcontroller
Drop an extra blank line and a comment about an older tree; the prebuilt
receipt is refreshed for the source change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 17:44:47 -08:00
Raymond Nguyen ac77f9a20c honda: rebuild the panda firmware for the Accord angle setpoint check
Built from 25323cef46 with the ARM64 device build container (DEBUG cert, as the
tracked images are), and the prebuilt receipt refreshed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 17:26:38 -08:00
Raymond Nguyen 25323cef46 Honda Accord: angle steering for the modified EPS firmware
The 2020 Accord with EPS firmware 39990-TVA,A16C takes an angle setpoint in the
steering message. openpilot sends the setpoint, limited last by the 3.589 m/s^2
lateral acceleration and jerk limits, and the panda blocks any angle frame that
exceeds them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 17:22:01 -08:00
100 changed files with 2066 additions and 260 deletions
+8 -1
View File
@@ -16,7 +16,8 @@ from opendbc.car.ford.discovery import (normal_bus0_selection as ford_normal_bus
normal_bus0_queries as ford_normal_bus0_queries, normal_bus_query_brand)
from opendbc.car.volvo.discovery import normal_bus_topology as volvo_normal_bus_topology, v60_bus_topology as volvo_v60_bus_topology
from opendbc.car.hyundai.discovery import normal_bus_topology
from opendbc.car.honda.discovery import nidec_bus0_topology, normal_bus_topology as honda_normal_bus_topology
from opendbc.car.honda.discovery import (eps_needs_obd as honda_eps_needs_obd, nidec_bus0_topology,
normal_bus_topology as honda_normal_bus_topology)
from opendbc.car.honda.values import CAR as HONDA, HondaFlags
from opendbc.car.mazda.discovery import normal_bus0_topology as mazda_normal_bus0_topology
from opendbc.car.chrysler.discovery import normal_bus_topology as chrysler_normal_bus_topology
@@ -215,6 +216,12 @@ def fingerprint(can_recv: CanRecvCallable, can_send: CanSendCallable, set_obd_mu
else:
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing,
query_brand=normal_brand, normal_bus_only=True)
if normal_brand == 'honda' and honda_eps_needs_obd(match_fw_to_car(car_fw, vin)[1], car_fw):
# Read this car's VIN and EPS through the OBD port, as the generic path below does. Without the VIN
# the result is never cached, so every start would repeat the query.
set_obd_multiplexing(True)
vin_rx_addr, vin_rx_bus, vin = get_vin(can_recv, can_send, (0, 1))
car_fw = get_fw_versions(can_recv, can_send, set_obd_multiplexing, query_brand='honda')
ecu_rx_addrs = {(fw.responseAddress, fw.subAddress or None, fw.bus) for fw in car_fw if fw.responseAddress > 0}
else:
full_scan = True
@@ -1,3 +1,5 @@
import math
import numpy as np
from opendbc.car import ACCEL_MAX_TAKEOFF
@@ -10,9 +12,12 @@ from opendbc.car.honda.nidec_interceptor import NidecInterceptor, create_command
from opendbc.car.honda.bosch_longitudinal import BoschLongitudinal, qualified as bosch_long_qualified
from opendbc.car.honda.values import CAR, CruiseButtons, HondaFlags, CarControllerParams
from opendbc.car.interfaces import CarControllerBase
from opendbc.car.lateral import apply_steer_angle_limits_vm, get_max_angle_delta_vm
from opendbc.car.vehicle_model import VehicleModel
VisualAlert = structs.CarControl.HUDControl.VisualAlert
LongCtrlState = structs.CarControl.Actuators.LongControlState
SteerControlType = structs.CarParams.SteerControlType
def compute_gb_honda_bosch(accel, speed):
@@ -120,6 +125,54 @@ class CarController(CarControllerBase):
self.brake = 0.0
self.last_torque = 0.0
# Accord angle-loop EPS (interface.py sets steerControlType = angle)
self.angle_mode = CP.steerControlType == SteerControlType.angle
self.VM = VehicleModel(CP) if self.angle_mode else None
self.apply_angle_last = None # None until the first frame seeds the limiter from the wheel
self.angle_steer_req = False # STEER_TORQUE_REQUEST of the last angle frame
def _angle_hold_allowed(self, CC, CS) -> bool:
# The panda blocks a nonzero 0xE4 field unless lateral_controls_allowed(). Without an AOL policy that is
# controls_allowed (needs ACC main on and engagement); with one it is a session-acknowledged axis permission the
# carcontroller cannot see, so the hold is sent only in the subset every policy allows: enabled with main on.
return bool(CS.out.cruiseState.available) and bool(CC.enabled)
def _update_angle(self, CC, CS) -> tuple[float, int]:
"""Angle setpoint (deg) and the 0xE4 STEER_TORQUE field."""
p = self.params
steering_angle = float(CS.out.steeringAngleDeg)
angle_last = steering_angle if self.apply_angle_last is None else self.apply_angle_last
desired = float(CC.actuators.steeringAngleDeg)
if CC.latActive:
# error clip first: it shapes the request, bounding the P torque the setpoint asks of the EPS
error_max = float(np.interp(CS.out.vEgoRaw, p.ANGLE_ERROR_MAX_BP, p.ANGLE_ERROR_MAX_V))
desired = float(np.clip(desired, steering_angle - error_max, steering_angle + error_max))
# The lateral accel and jerk limits (3.589) are the last adjustment: applied to exactly what is sent and seeded
# from the last value sent. The panda runs the same check on the frame (honda.h) and blocks one that exceeds it,
# so nothing may change the setpoint after this line.
apply_angle = apply_steer_angle_limits_vm(desired, angle_last, CS.out.vEgoRaw, steering_angle, CC.latActive, p, self.VM)
self.angle_steer_req = bool(CC.latActive)
if CC.latActive:
v = max(float(CS.out.vEgoRaw), 1.0)
max_delta = min(get_max_angle_delta_vm(v, self.VM, p), p.ANGLE_LIMITS.MAX_ANGLE_RATE)
if abs(apply_angle - angle_last) > max_delta + 1e-6:
# The accel limit is further from the last value sent than the jerk limit lets one frame move: the wheel is
# past the limit as the request starts. No setpoint satisfies both, and the panda would drop the frame, so
# the request waits at the wheel until the wheel is back inside.
apply_angle = steering_angle
self.angle_steer_req = False
self.apply_angle_last = apply_angle
# raw = round(-10 * deg), half-up; left-positive degrees are negative raw
if CC.latActive:
raw = math.floor(-10.0 * apply_angle + 0.5)
elif self._angle_hold_allowed(CC, CS):
# idle hold: keep the setpoint at the wheel so engagement starts without a step
raw = math.floor(-10.0 * steering_angle + 0.5)
else:
raw = 0 # the panda blocks a nonzero field here
return apply_angle, int(np.clip(raw, -p.ANGLE_RAW_MAX, p.ANGLE_RAW_MAX))
def update(self, CC, CS, now_nanos):
_projection = self.learning_projection_observer
if _projection is not None:
@@ -176,7 +229,12 @@ class CarController(CarControllerBase):
can_sends.append(make_tester_present_msg(0x18DAB0F1, 1, suppress_response=True))
# Send steering command.
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, apply_torque, CC.latActive, self.tja_control))
if self.angle_mode:
apply_angle, angle_raw = self._update_angle(CC, CS)
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, angle_raw, self.angle_steer_req,
self.tja_control, angle_arm=self.params.ANGLE_ARM))
else:
can_sends.append(hondacan.create_steering_control(self.packer, self.CAN, apply_torque, CC.latActive, self.tja_control))
if _projection is not None:
_projection.emit('honda.STEERING_CONTROL', apply_torque, CC.latActive, can_sends[-1])
@@ -286,6 +344,9 @@ class CarController(CarControllerBase):
new_actuators.brake = self.brake
new_actuators.torque = self.last_torque
new_actuators.torqueOutputCan = apply_torque
if self.angle_mode:
new_actuators.steeringAngleDeg = apply_angle
new_actuators.torqueOutputCan = angle_raw # the 0xE4 STEER_TORQUE field as sent (-10 x deg)
self.frame += 1
if _projection is not None:
@@ -13,6 +13,7 @@ from opendbc.car.dashboard_speed_limit import Tracker as LimitTracker, honda_sig
from opendbc.can.dbc import DBC as CANDBC
TransmissionType = structs.CarParams.TransmissionType
SteerControlType = structs.CarParams.SteerControlType
ButtonType = structs.CarState.ButtonEvent.Type
BUTTONS_DICT = {CruiseButtons.RES_ACCEL: ButtonType.accelCruise, CruiseButtons.DECEL_SET: ButtonType.decelCruise,
@@ -120,6 +121,16 @@ class CarState(CarStateBase):
ret.steerFaultPermanent = False
ret.steerFaultTemporary = False
if self.CP.flags & HondaFlags.EPS_FW_UNREAD:
ret.steerFaultPermanent = True
if self.CP.steerControlType == SteerControlType.angle and self.CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW:
# the angle-loop EPS's angle is a valid absolute angle only while all three sensor status bits read 1; outside
# that the EPS would servo from a false angle, so do not steer
sensors = cp.vl["STEERING_SENSORS"]
if not all(sensors[f"STEER_SENSOR_STATUS_{i}"] == 1 for i in (1, 2, 3)):
ret.steerFaultTemporary = True
# All Honda EPS cut off slightly above standstill, some much higher
# Don't alert in the near-standstill range, but alert for per-vehicle configured minimums above that
if CarControllerParams.STEER_GLOBAL_MIN_SPEED < ret.vEgo < (self.CP.minSteerSpeed + 0.5):
@@ -1,4 +1,5 @@
from opendbc.car.honda.hondacan import honda_checksum
from opendbc.car.honda.values import CAR
# Classic Bosch: PT on bus 1 and the stock ACC camera on bus 2. This selects
@@ -30,3 +31,9 @@ def normal_bus_topology(packets, *, layout=NORMAL_BUS_LAYOUT):
def nidec_bus0_topology(packets):
return any(normal_bus_topology(packets, layout=layout) for layout in NIDEC_BUS0_LAYOUTS)
def eps_needs_obd(candidates, car_fw) -> bool:
"""The Accord's EPS answers only through the OBD port (never on the normal bus 1 wiring), and its firmware
family decides between angle and torque steering. A normal-bus read that names the Accord is not complete."""
return CAR.HONDA_ACCORD in candidates and not any(fw.ecu == "eps" and not fw.logging for fw in car_fw)
+6 -2
View File
@@ -117,11 +117,15 @@ def create_acc_commands(packer, CAN, enabled, active, accel, gas, stopping_count
return commands
def create_steering_control(packer, CAN, apply_torque, lkas_active, tja_control):
def create_steering_control(packer, CAN, apply_torque, lkas_active, tja_control, angle_arm=None):
# angle_arm (Accord angle-loop EPS only): STEER_TORQUE is the angle setpoint, sent with the request off too, and
# STEER_CONTROL_ARM carries the arm the EPS lane requires. None = the torque frame, unchanged.
values = {
"STEER_TORQUE": apply_torque if lkas_active else 0,
"STEER_TORQUE": apply_torque if (lkas_active or angle_arm is not None) else 0,
"STEER_TORQUE_REQUEST": lkas_active,
}
if angle_arm is not None:
values["STEER_CONTROL_ARM"] = angle_arm
if tja_control:
values["STEER_DOWN_TO_ZERO"] = lkas_active
+24 -2
View File
@@ -7,7 +7,9 @@ from opendbc.car import Bus, get_safety_config, structs, uds
from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.disable_ecu import disable_ecu
from opendbc.car.honda.hondacan import CanBus
from opendbc.car.honda.values import CarControllerParams, HondaFlags, CAR, HondaSafetyFlags, MANUAL_TRANS_CARS, MODIFIED_EPS_FW, DBC
from opendbc.car.honda.values import CarControllerParams, HondaFlags, CAR, HondaSafetyFlags, MANUAL_TRANS_CARS, MODIFIED_EPS_FW, DBC, \
is_accord_eps_angle_loop_fw
from opendbc.car.lateral import MAX_LATERAL_ACCEL
from opendbc.car.honda.carcontroller import CarController
from opendbc.car.honda.carstate import CarState
from opendbc.car.honda.radar_interface import RadarInterface
@@ -100,7 +102,12 @@ class CarInterface(CarInterfaceBase):
ret.longitudinalTuning.kiV = [1.2, 0.8, 0.5]
eps_observations = [fw for fw in car_fw if fw.ecu == "eps" and not fw.logging]
modified_eps = any(b"," in fw.fwVersion for fw in eps_observations)
# Accord angle-loop EPS firmware (39990-TVA,A16<letter>): the EPS closes the angle loop and openpilot sends the
# setpoint. Not a torque-modified EPS, so it is kept out of the MODIFIED_EPS_FW allow-list check below (which would
# otherwise make the car dashcam-only). Every EPS response must be the family; a mixed read falls through to it.
eps_angle_loop_fw = (candidate == CAR.HONDA_ACCORD and len(eps_observations) > 0 and
all(is_accord_eps_angle_loop_fw(fw.fwVersion) for fw in eps_observations))
modified_eps = not eps_angle_loop_fw and any(b"," in fw.fwVersion for fw in eps_observations)
eps_modified = bool(modified_eps) and all(
fw.address == 0x18DA30F1 and fw.subAddress == 0 and
fw.fwVersion in MODIFIED_EPS_FW.get(candidate, ()) for fw in eps_observations)
@@ -121,6 +128,21 @@ class CarInterface(CarInterfaceBase):
elif candidate == CAR.HONDA_ACCORD:
ret.lateralTuning.pid.kpV, ret.lateralTuning.pid.kiV = ([[0.3], [0.09]] if eps_modified else [[0.6], [0.18]])
if eps_angle_loop_fw:
# angle-loop EPS firmware: the EPS closes the angle loop, openpilot sends the setpoint
ret.flags |= HondaFlags.EPS_ANGLE_LOOP_FW.value
ret.safetyConfigs[-1].safetyParam |= HondaSafetyFlags.ACCORD_ANGLE.value
ret.steerControlType = structs.CarParams.SteerControlType.angle
ret.steerActuatorDelay = CarControllerParams.ANGLE_STEER_ACTUATOR_DELAY
# The torque fit's MAX_LAT_ACCEL_MEASURED (0.32 m/s^2) means nothing to an angle setpoint; the onroad torque
# bar divides by this, so normalise it by the angle limit instead (3.589 m/s^2, where the setpoint clamp binds).
# Measured engaged hands-off over 35 routes: p99.9 3.46 m/s^2, per-route maxima 3.4-4.1. Only the bar and the
# car docs read maxLateralAccel; no controller or torque tune does.
ret.maxLateralAccel = MAX_LATERAL_ACCEL
elif not docs and not eps_observations:
# EPS fw unread: an angle-loop EPS would ignore torque frames (engaged, no steering, no alert), so fault instead.
# Note: upstream lists this EPS as non-essential (lost without comma power); such an Accord faults here too.
ret.flags |= HondaFlags.EPS_FW_UNREAD.value
elif candidate == CAR.HONDA_ACCORD_11G:
ret.longitudinalActuatorDelay = 0.05
+6 -1
View File
@@ -37,8 +37,11 @@ MANUAL_SELECTION_PORTS = CLASSIC_BOSCH | NIDEC | RADARLESS | CANFD_STOCK | ALT_R
# qualified() runs several times per 100 Hz frame in card and selfdrived, so
# everything that depends only on this module is computed once, and its flag
# tests use plain ints: IntFlag operators cost microseconds each in Python.
# EPS_ANGLE_LOOP_FW / EPS_FW_UNREAD: Accord-only EPS-firmware detections (interface.py); the angle car keeps AOL, and
# an unread EPS is already a permanent steer fault in carstate, so neither may drop the car out of these owners.
_DETECTED = int(HondaFlags.BOSCH_EXT_HUD | HondaFlags.BOSCH_ALT_BRAKE | HondaFlags.HAS_BSM |
HondaFlags.EPS_MODIFIED | HondaFlags.HYBRID | HondaFlags.GAS_INTERCEPTOR)
HondaFlags.EPS_MODIFIED | HondaFlags.HYBRID | HondaFlags.GAS_INTERCEPTOR |
HondaFlags.EPS_ANGLE_LOOP_FW | HondaFlags.EPS_FW_UNREAD)
_ALLOWED_FLAGS = {str(car): int(car.config.flags) | _DETECTED
for car in CLASSIC_BOSCH | NIDEC | RADARLESS | CANFD_STOCK | ALT_RADAR_STOCK | {CAR.HONDA_ACCORD_11G}}
_BOSCH, _BOSCH_RADARLESS, _BOSCH_ALT_BRAKE = int(HondaFlags.BOSCH), int(HondaFlags.BOSCH_RADARLESS), int(HondaFlags.BOSCH_ALT_BRAKE)
@@ -102,6 +105,8 @@ def qualified(cp, *, marked_only=False):
safety.safetyModel == _HONDA_NIDEC and safety.safetyParam == expected)
if fingerprint in CLASSIC_BOSCH and flags & _BOSCH and not flags & _BOSCH_RADARLESS:
expected = int(bool(flags & _BOSCH_ALT_BRAKE))
if fingerprint == CAR.HONDA_ACCORD and flags & int(HondaFlags.EPS_ANGLE_LOOP_FW):
expected |= int(HondaSafetyFlags.ACCORD_ANGLE)
if cp.openpilotLongitudinalControl:
expected |= int(HondaSafetyFlags.BOSCH_LONG)
if fingerprint == CAR.ACURA_RDX_3G:
@@ -39,9 +39,11 @@ def test_mixed_nonlogging_eps_still_refuses_modified_profile(other):
assert not cp.flags & HondaFlags.EPS_MODIFIED
def test_recorded_custom_angle_eps_remains_unsupported_in_mainline():
def test_recorded_custom_angle_eps_steers_by_angle():
cp = params(CAR.HONDA_ACCORD, [eps(ANGLE), eps(SERIAL, logging=True)])
assert cp.dashcamOnly
assert not cp.dashcamOnly
assert cp.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert cp.steerControlType == structs.CarParams.SteerControlType.angle
assert not cp.flags & HondaFlags.EPS_MODIFIED
@@ -0,0 +1,364 @@
"""Accord on the angle-loop EPS firmware (39990-TVA,A16<letter>): detection, the 0xE4 frame, the setpoint limits."""
import math
from types import SimpleNamespace
import numpy as np
import pytest
from opendbc import get_generated_dbcs
from opendbc.can import CANPacker
from opendbc.car import Bus, gen_empty_fingerprint
from opendbc.car.honda.carcontroller import CarController
from opendbc.car.honda.carstate import CarState
from opendbc.car.honda.hondacan import CanBus, create_steering_control
from opendbc.car.honda.interface import CarInterface
from opendbc.car.honda.values import CAR, DBC, CarControllerParams, HondaFlags, HondaSafetyFlags, is_accord_eps_angle_loop_fw, \
accord_angle_steer_ratio, ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V
from opendbc.car.interfaces import get_torque_params
from opendbc.car.lateral import MAX_LATERAL_ACCEL, apply_steer_angle_limits_vm, get_max_angle_delta_vm, get_max_angle_vm
from opendbc.car.toyota.interface import CarInterface as ToyotaInterface
from opendbc.car.toyota.values import CAR as TOYOTA
from opendbc.car.structs import CarParams
P = CarControllerParams
STEERING_CONTROL = 0xE4
def _eps_fw(fw: bytes):
return [CarParams.CarFw(ecu=CarParams.Ecu.eps, fwVersion=fw, address=0x18DA30F1, subAddress=0)]
def accord_cp(eps_fw: bytes | None):
car_fw = [] if eps_fw is None else _eps_fw(eps_fw)
return CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
@pytest.mark.parametrize("fw, expected", [
(b"39990-TVA,A16A\x00\x00", True), # V298, NUL-padded as the car reports it
(b"39990-TVA,A16B\x00\x00", True), # V299
(b"39990-TVA,A16C", True), # the release
(b"39990-TVA,A160\x00\x00", False), # torque-map images
(b"39990-TVA-A160\x00\x00", False), # stock
(b"39990-TVA,A16", False),
(b"39990-TVA,A16AB", False),
(b"39990-TVA,A16a", False),
(b"39990-TVB,A16A", False),
])
def test_fw_detection(fw, expected):
assert is_accord_eps_angle_loop_fw(fw) is expected
@pytest.mark.parametrize("fw", [b"39990-TVA,A16A\x00\x00", b"39990-TVA,A16B\x00\x00", b"39990-TVA,A16C\x00\x00"])
def test_angle_fw_selects_angle_control(fw):
CP = accord_cp(fw)
assert CP.steerControlType == CarParams.SteerControlType.angle
assert CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
assert CP.steerActuatorDelay == pytest.approx(P.ANGLE_STEER_ACTUATOR_DELAY)
# the angle fw carries a ',' but is not a torque-modified EPS: it must not hit the MODIFIED_EPS_FW dashcam fallback
assert not CP.dashcamOnly
assert not CP.flags & HondaFlags.EPS_MODIFIED
assert not CP.flags & HondaFlags.EPS_FW_UNREAD
def test_angle_fw_on_another_honda_is_not_angle_control():
# the family is Accord-only; on any other platform the ',' read is the upstream modified-EPS path
CP = CarInterface.get_params(CAR.HONDA_CIVIC_BOSCH, gen_empty_fingerprint(), _eps_fw(b"39990-TVA,A16C\x00\x00"),
False, False, False)
assert CP.steerControlType == CarParams.SteerControlType.torque
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
def test_mixed_eps_read_is_not_angle_control():
car_fw = _eps_fw(b"39990-TVA,A16C\x00\x00") + _eps_fw(b"39990-TVA-A160\x00\x00")
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
assert CP.steerControlType == CarParams.SteerControlType.torque
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
assert CP.dashcamOnly # upstream: a ',' EPS outside MODIFIED_EPS_FW
def test_angle_control_needs_no_params():
"""A fresh install selects angle control from the EPS fw alone and keeps the pid tuning block untouched.
Old tree (83fa2e68c8) also pinned this against stale torque-era toggles (ForceTorqueController, NNFF, NNFF Lite)
passed into get_params; this tree's get_params takes no toggles and has no ForceTorqueController conversion at all,
so only the fw-alone half of that test still has an API to exercise."""
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), _eps_fw(b"39990-TVA,A16C"), False, False, False)
assert CP.steerControlType == CarParams.SteerControlType.angle
assert CP.lateralTuning.which() == "pid"
assert CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP).angle_mode
@pytest.mark.parametrize("fw", [None, b"39990-TVA-A160\x00\x00", b"39990-TVA,A160\x00\x00"])
def test_other_fw_keeps_torque_control(fw):
CP = accord_cp(fw)
assert CP.steerControlType == CarParams.SteerControlType.torque
assert not CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert not CP.safetyConfigs[0].safetyParam & HondaSafetyFlags.ACCORD_ANGLE
assert not CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP).angle_mode
def test_max_lateral_accel_is_the_angle_limit_only_on_the_angle_fw():
# the onroad torque bar divides by CP.maxLateralAccel; the torque fit's 0.32 m/s^2 pegged it on every turn
torque_fit = get_torque_params()[CAR.HONDA_ACCORD]['MAX_LAT_ACCEL_MEASURED']
assert torque_fit == pytest.approx(0.3247, abs=1e-4)
assert accord_cp(b"39990-TVA,A16C").maxLateralAccel == pytest.approx(MAX_LATERAL_ACCEL)
assert MAX_LATERAL_ACCEL == pytest.approx(3.589, abs=1e-3)
for fw in (None, b"39990-TVA-A160\x00\x00", b"39990-TVA,A160\x00\x00"):
assert accord_cp(fw).maxLateralAccel == pytest.approx(torque_fit)
angle_fw = _eps_fw(b"39990-TVA,A16C")
for car in (CAR.HONDA_CIVIC_BOSCH, CAR.HONDA_CRV_5G):
CP = CarInterface.get_params(car, gen_empty_fingerprint(), angle_fw, False, False, False)
assert CP.maxLateralAccel == pytest.approx(get_torque_params()[car]['MAX_LAT_ACCEL_MEASURED'])
CP = ToyotaInterface.get_params(TOYOTA.TOYOTA_RAV4_TSS2, gen_empty_fingerprint(), [], False, False, False)
assert CP.maxLateralAccel == pytest.approx(get_torque_params()[TOYOTA.TOYOTA_RAV4_TSS2]['MAX_LAT_ACCEL_MEASURED'])
def _steer_faults(CP):
# an unfed parser set: only the fault logic, not the bus contents, is under test
CS = CarState(CP)
ret = CS.update(CS.get_can_parsers(CP))
return ret.steerFaultPermanent
@pytest.mark.parametrize("fw, angle, unread", [
(b"39990-TVA,A16C\x00\x00", True, False), # angle EPS read -> angle mode
(b"39990-TVA-A160\x00\x00", False, False), # stock EPS read -> torque mode, no fault
(b"39990-TVA,A160\x00\x00", False, False), # torque-map EPS read -> torque mode, no fault
(None, False, True), # no EPS fw at all -> permanent fault
])
def test_eps_fw_unread_faults(fw, angle, unread):
CP = accord_cp(fw)
assert (CP.steerControlType == CarParams.SteerControlType.angle) == angle
assert bool(CP.flags & HondaFlags.EPS_FW_UNREAD) == unread
if not angle:
# same unfed bus for every case, so the fault is decided by the flag alone (the read cases are the control)
assert _steer_faults(CP) == unread
def test_docs_params_do_not_fault():
CP = CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), [], False, False, True)
assert not CP.flags & HondaFlags.EPS_FW_UNREAD
def _upstream_dbc(tmp_path):
# the Accord DBC without STEER_CONTROL_ARM, i.e. as it was before the signal was added. The *_generated DBCs are
# built in memory in this tree (opendbc.get_generated_dbcs), so the stripped copy is written out from that content.
name = DBC[CAR.HONDA_ACCORD][Bus.pt]
content = get_generated_dbcs()[name]
assert "STEER_CONTROL_ARM" in content
lines = [ln for ln in content.splitlines(keepends=True) if "STEER_CONTROL_ARM" not in ln]
path = tmp_path / f"{name}.dbc"
path.write_text("".join(lines), encoding="utf-8")
return str(path)
def test_torque_frame_unchanged_by_the_dbc_signal(tmp_path):
CP = accord_cp(None)
new = CANPacker(DBC[CAR.HONDA_ACCORD][Bus.pt])
old = CANPacker(_upstream_dbc(tmp_path))
can = CanBus(CP)
for torque in range(-4096, 4097, 37):
for active in (False, True):
for tja in (False, True):
assert create_steering_control(new, can, torque, active, tja) == create_steering_control(old, can, torque, active, tja)
@pytest.mark.parametrize("active", [False, True])
def test_angle_frame_carries_the_arm_and_a_valid_checksum(active):
packer = CANPacker(DBC[CAR.HONDA_ACCORD][Bus.pt])
can = CanBus(accord_cp(b"39990-TVA,A16C"))
for raw in (-4000, -1234, -1, 0, 1, 987, 4000):
addr, dat, _ = create_steering_control(packer, can, raw, active, False, angle_arm=P.ANGLE_ARM)
assert addr == STEERING_CONTROL
assert (dat[2] >> 2) & 0x3 == P.ANGLE_ARM # byte 2 bits 3:2
assert int.from_bytes(dat[0:2], "big", signed=True) == raw # setpoint sent with the request off too
assert bool(dat[2] & 0x80) == active # STEER_TORQUE_REQUEST
sig = packer.dbc.addr_to_msg[addr].sigs["CHECKSUM"]
zeroed = bytearray(dat)
zeroed[4] &= 0xF0
assert sig.calc_checksum(addr, sig, zeroed) == dat[4] & 0xF # CHECKSUM 35|4 = byte 4 low nibble
def _controller(aol=False):
CP = accord_cp(b"39990-TVA,A16C")
if aol:
CP.alternativeExperience |= 32 # always-on lateral: the hold must NOT depend on it (the 7.0 panda predicate is a session grant)
return CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, CP)
def _cc_cs(desired, measured, v, lat_active, enabled=True, main_on=True):
CC = SimpleNamespace(actuators=SimpleNamespace(steeringAngleDeg=desired), latActive=lat_active, enabled=enabled)
CS = SimpleNamespace(out=SimpleNamespace(steeringAngleDeg=measured, vEgoRaw=v, cruiseState=SimpleNamespace(available=main_on)))
return CC, CS
def test_error_clip_then_the_accel_and_jerk_limits():
# the error clip shapes the request, the accel/jerk limiter runs last on it, and what is sent is the limiter's output
cc = _controller()
assert cc.angle_mode
v, measured = 20.0, 0.0
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
state = measured
for _ in range(400):
state = apply_steer_angle_limits_vm(min(90.0, measured + err), state, v, measured, True, cc.params, cc.VM)
apply_angle, raw = cc._update_angle(*_cc_cs(90.0, measured, v, True))
assert apply_angle == cc.apply_angle_last == state
assert raw == math.floor(-10.0 * apply_angle + 0.5)
assert apply_angle == pytest.approx(measured + err) # the wheel never moved: the send settles on the clip
@pytest.mark.parametrize("v", [1.0, 5.0, 10.0, 17.5, 26.9, 35.0])
def test_what_is_sent_never_exceeds_the_accel_and_jerk_limits(v):
# whatever the wheel does (a driver holding it far past the limit, or yanking it), every frame sent stays inside
# the 3.589 lateral accel angle and steps no further than the 3.589 jerk limit from the previous frame sent
rng = np.random.default_rng(int(v * 10))
cc = _controller()
max_angle = get_max_angle_vm(v, cc.VM, cc.params)
max_delta = min(get_max_angle_delta_vm(v, cc.VM, cc.params), P.ANGLE_LIMITS.MAX_ANGLE_RATE)
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
wheel = min(max_angle + err + 10.0, 390.0) # held past the limit: the case the old order got wrong
prev, _ = cc._update_angle(*_cc_cs(0.0, 0.0, v, True))
for i in range(600):
if i > 200:
wheel = float(np.clip(wheel + rng.normal(0.0, 3.0), -390.0, 390.0)) # then moving up to several hundred deg/s
sent, raw = cc._update_angle(*_cc_cs(float(rng.uniform(-400.0, 400.0)), wheel, v, True))
assert abs(sent) <= min(max_angle, P.ANGLE_LIMITS.STEER_ANGLE_MAX) + 1e-9
assert abs(sent - prev) <= max_delta + 1e-9
assert raw == math.floor(-10.0 * sent + 0.5)
prev = sent
def test_wheel_motion_inside_the_error_clip_does_not_feed_the_setpoint():
# same command, different wheel paths that stay inside the clip: the setpoint must not depend on the wheel
rng = np.random.default_rng(0)
a, b = _controller(), _controller()
a.apply_angle_last = b.apply_angle_last = 0.0
err = float(np.interp(12.0, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
for i in range(300):
desired = 20.0 * math.sin(i / 20.0)
wheel = float(np.clip(rng.normal(0.0, 10.0), -(err - 21.0), err - 21.0))
a._update_angle(*_cc_cs(desired, 0.0, 12.0, True))
b._update_angle(*_cc_cs(desired, wheel, 12.0, True))
assert a.apply_angle_last == b.apply_angle_last
def test_setpoint_returns_to_the_request_at_the_jerk_limit_after_the_clip_releases():
# wheel pushed away (clip binds), then let go: the setpoint walks back, it does not jump
cc = _controller()
v = 20.0
err = float(np.interp(v, P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V))
max_delta = get_max_angle_delta_vm(v, cc.VM, cc.params)
cc.apply_angle_last = 0.0
for _ in range(300):
pushed, _ = cc._update_angle(*_cc_cs(0.0, err + 5.0, v, True))
assert pushed == pytest.approx(5.0) # held at the clip edge, wheel - err
back, _ = cc._update_angle(*_cc_cs(0.0, 0.0, v, True))
assert back == pytest.approx(5.0 - max_delta)
def test_request_waits_at_the_wheel_while_the_wheel_is_past_the_accel_limit():
# lateral goes active with the wheel past the accel-limit angle: the limit is more than one jerk step away, so no
# setpoint is legal. The frame holds the wheel with the request off, and the request starts once the wheel is inside.
cc = _controller()
v = 26.9
max_angle = get_max_angle_vm(v, cc.VM, cc.params)
max_delta = get_max_angle_delta_vm(v, cc.VM, cc.params)
for wheel in (max_angle + 20.0, max_angle + 5.0, max_angle + max_delta + 0.1):
sent, raw = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
assert not cc.angle_steer_req
assert sent == wheel and raw == math.floor(-10.0 * wheel + 0.5)
wheel = max_angle + 0.5 * max_delta
cc._update_angle(*_cc_cs(0.0, wheel, v, True)) # the last value sent was the wheel further out: one more frame waits
assert not cc.angle_steer_req
sent, raw = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
assert cc.angle_steer_req
assert sent == pytest.approx(wheel - max_delta) # one jerk step in from the wheel, inside the accel limit
for _ in range(50): # and it stays on from there
prev = sent
sent, _ = cc._update_angle(*_cc_cs(0.0, wheel, v, True))
assert cc.angle_steer_req and abs(sent - prev) <= max_delta + 1e-9 and abs(sent) <= max_angle + 1e-9
def test_request_bit_follows_lat_active_otherwise():
cc = _controller()
cc._update_angle(*_cc_cs(3.0, 1.0, 20.0, True))
assert cc.angle_steer_req
cc._update_angle(*_cc_cs(3.0, 1.0, 20.0, False))
assert not cc.angle_steer_req
def test_each_step_is_bounded_by_the_rate_limit():
# MAX_ANGLE_RATE = 2.5 deg/frame (250 deg/s): no frame may step further than that
cc = _controller()
prev = 0.0
for _ in range(5):
a, _ = cc._update_angle(*_cc_cs(90.0, 0.0, 3.0, True))
assert abs(a - prev) <= P.ANGLE_LIMITS.MAX_ANGLE_RATE + 1e-9
prev = a
def test_first_frame_seeds_from_the_wheel():
cc = _controller()
a, _ = cc._update_angle(*_cc_cs(30.0, 25.0, 10.0, True))
assert abs(a - 25.0) <= P.ANGLE_LIMITS.MAX_ANGLE_RATE + 1e-9
@pytest.mark.parametrize("enabled, main_on, aol, holds", [
(True, True, False, True),
(False, True, True, False), # always-on lateral with ACC main on: the panda's grant is not visible here, so no hold
(True, True, True, True),
(False, True, False, False),
(True, False, False, False), # the panda drops controls_allowed with main off
(False, False, True, False),
])
def test_idle_hold(enabled, main_on, aol, holds):
cc = _controller(aol)
measured = -12.34
apply_angle, raw = cc._update_angle(*_cc_cs(50.0, measured, 15.0, False, enabled, main_on))
assert apply_angle == measured # lateral off: the limiter follows the wheel
assert raw == (math.floor(-10.0 * measured + 0.5) if holds else 0)
def test_raw_is_clipped():
cc = _controller()
cc.apply_angle_last = 399.0
_, raw = cc._update_angle(*_cc_cs(400.0, 399.0, 1.0, True))
assert raw == -P.ANGLE_RAW_MAX
def test_steer_ratio_map_level():
assert accord_angle_steer_ratio(0.0) == pytest.approx(16.84)
for deg in (0.0, 45.0, 120.0, -200.0, 500.0):
expected = float(np.interp(abs(deg), ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V)) * 16.84 / 16.88
assert accord_angle_steer_ratio(deg) == pytest.approx(expected)
def test_error_clip_is_the_p_room_under_the_firmware_sum_clamp():
# Operator rule (2026-10-21): the clip is the angle error where the V300 firmware's P term alone equals
# Kmax - Imax (sum clamp 15360 after the 254/256 taper, so 15481 before it; I cap 4096 / 6144 / 8192 by
# speed). Integer mirror of the image: E = 16 * 10 * deg, E' = (E * G(v)) >> 8, P = (E' * 112) >> 8.
g_v = {3.1: 1178, 8.0: 1465, 10.0: 760, 11.75: 560, 17.5: 1068, 26.9: 2188}
for v, clip in zip(P.ANGLE_ERROR_MAX_BP, P.ANGLE_ERROR_MAX_V, strict=True):
imax = 4096 if v <= 6.0 else (6144 if v <= 12.5 else 8192)
p_of = lambda deg, v=v: (((16 * round(10 * deg) * g_v[v]) >> 8) * 112) >> 8 # noqa: E731
assert p_of(clip) >= 15481 - imax > p_of(clip - 0.1)
def test_angle_frame_is_sent_by_the_controller():
# the full update(): angle mode packs the setpoint with the arm; the projection observer is never installed on angle
CP = accord_cp(b"39990-TVA,A16C")
ci = CarInterface(CP)
from opendbc.car import structs
CC = structs.CarControl(enabled=True, latActive=True)
CC.actuators.steeringAngleDeg = 5.0
ci.update([])
out, sends = ci.apply(CC.as_reader(), 1_000_000_000)
steer = [s for s in sends if s[0] == STEERING_CONTROL]
assert len(steer) == 1
dat = steer[0][1]
assert (dat[2] >> 2) & 0x3 == P.ANGLE_ARM
assert int.from_bytes(dat[0:2], "big", signed=True) == out.torqueOutputCan
assert out.steeringAngleDeg == pytest.approx(-out.torqueOutputCan / 10.0, abs=0.05)
@@ -1,5 +1,6 @@
import json
from pathlib import Path
from types import SimpleNamespace
import unittest
from unittest.mock import patch
@@ -33,6 +34,32 @@ class TestHondaNormalDiscovery(unittest.TestCase):
generic_query.assert_not_called()
self.assertIsNone(actual[0])
def _accord_discovery(self, normal_read, obd_read):
from opendbc.car.honda.values import CAR
switches = []
with patch('opendbc.car.car_helpers.get_vin', return_value=(-1, -1, VIN_UNKNOWN)) as vin, \
patch('opendbc.car.car_helpers.get_fw_versions', side_effect=[normal_read, obd_read]) as query, \
patch('opendbc.car.car_helpers.match_fw_to_car', return_value=(True, {CAR.HONDA_ACCORD})), \
patch('opendbc.car.car_helpers.can_fingerprint', return_value=(None, {})):
actual = fingerprint(lambda wait_for_one=False: [recorded_frames()], lambda frames: None, switches.append, None)
return switches, vin, query, actual
def test_accord_without_an_eps_read_queries_the_obd_port(self):
radar = SimpleNamespace(ecu="fwdRadar", logging=False, responseAddress=0, subAddress=0, bus=1)
eps = SimpleNamespace(ecu="eps", logging=False, responseAddress=0, subAddress=0, bus=1)
switches, vin, query, actual = self._accord_discovery([radar], [radar, eps])
self.assertEqual(switches, [False, True, False])
self.assertEqual(vin.call_count, 2)
self.assertEqual([call.kwargs for call in query.call_args_list],
[{'query_brand': 'honda', 'normal_bus_only': True}, {'query_brand': 'honda'}])
self.assertEqual(actual[3], [radar, eps])
def test_accord_with_an_eps_read_stays_on_normal_wiring(self):
eps = SimpleNamespace(ecu="eps", logging=False, responseAddress=0, subAddress=0, bus=1)
switches, vin, query, _ = self._accord_discovery([eps], AssertionError("no second query"))
self.assertFalse(any(switches))
query.assert_called_once()
def test_incomplete_or_invalid_traffic_cannot_select_honda(self):
from opendbc.car.honda.discovery import normal_bus_topology
frames = recorded_frames()
+74
View File
@@ -1,11 +1,14 @@
from dataclasses import dataclass, field
from enum import Enum, IntFlag
import numpy as np
from opendbc.car import Bus, CarSpecs, DbcDict, PlatformConfig, Platforms, structs, uds
from opendbc.car.common.conversions import Conversions as CV
from opendbc.car.docs_definitions import CarFootnote, CarHarness, CarDocs, CarParts, Column
from opendbc.car.fw_query_definitions import FwQueryConfig, Request, StdQueries, p16
from opendbc.car.honda.firmware_validation import validate_fw_match
from opendbc.car.lateral import AngleSteeringLimitsVM, MAX_LATERAL_ACCEL, MAX_LATERAL_JERK
Ecu = structs.CarParams.Ecu
VisualAlert = structs.CarControl.HUDControl.VisualAlert
@@ -41,6 +44,27 @@ class CarControllerParams:
STEER_DELTA_DOWN = 3
STEER_GLOBAL_MIN_SPEED = 3 * CV.MPH_TO_MS
# ---- Accord on the angle-loop EPS firmware (HondaFlags.EPS_ANGLE_LOOP_FW). 0xE4 STEER_TORQUE carries an angle
# setpoint, raw = round(-10 * deg) in carState.steeringAngleDeg's frame, and the EPS closes a 1 kHz angle loop on it.
# The panda checks every such frame (STEER_CONTROL_ARM == 2) against the same lateral accel and jerk limits with
# the same vehicle model (honda.h, HONDA_ACCORD_ANGLE_PARAMS), and blocks one that exceeds them.
ANGLE_LIMITS: AngleSteeringLimitsVM = AngleSteeringLimitsVM(
400, # deg; the EPS clamps its setpoint at raw +-4096
MAX_LATERAL_ACCEL=MAX_LATERAL_ACCEL, # 3.589 m/s^2
MAX_LATERAL_JERK=MAX_LATERAL_JERK, # 3.589 m/s^3
MAX_ANGLE_RATE=2.5, # deg/frame = 250 deg/s (V299 drives ran 250; Tesla and Rivian run 250 deg/s too)
)
# Error clip |setpoint - measured angle| <= ANGLE_ERROR_MAX(v): bounds the P torque the setpoint can demand. Each
# knot = the error at which the firmware's P term alone fills the room left under the PID sum clamp when the
# integral sits at its cap (operator rule, 2026-10-21): P = Kmax - Imax, read from the V300 image:
# P = ((16*10*deg * G(v)) >> 8) * 112 >> 8, Kmax = 15360 after the 254/256 taper (15481 before it),
# Imax = 4096 (<= 6 m/s), 6144 (6-12.5 m/s), 8192 (above, the ICL), G(v) = 1178/1465/760/560/1068/2188 at the knots.
ANGLE_ERROR_MAX_BP = [3.1, 8.0, 10.0, 11.75, 17.5, 26.9] # m/s, the firmware gain-table knots
ANGLE_ERROR_MAX_V = [35.4, 23.4, 45.0, 61.0, 25.0, 12.2] # deg (was 17.0, 15.5, 19.5, 17.0, 8.5, 4.5, model-sized)
ANGLE_RAW_MAX = 4000 # raw clip before packing
ANGLE_ARM = 2 # 0xE4 STEER_CONTROL_ARM: the EPS lane runs only while it reads 2; sent on every frame
ANGLE_STEER_ACTUATOR_DELAY = 0.15 # s, the inner angle loop's lag (model value; lagd learns the rest)
def __init__(self, CP):
self.BOSCH_GAS_LOOKUP_BP = list(type(self).BOSCH_GAS_LOOKUP_BP)
gas_max = {CAR.HONDA_CIVIC_BOSCH: 750, CAR.HONDA_ODYSSEY_5G_MMR: 2000,
@@ -92,6 +116,7 @@ class HondaSafetyFlags(IntFlag):
RADARLESS = 8
BOSCH_CANFD = 16
BOSCH_CANFD_MVL = 64
ACCORD_ANGLE = 4096
CLASSIC_LONG_AOL = 2048 # Exact marked DEBUG classic Bosch alpha owner.
ALT_RADAR_AOL = 1024 # Exact marked DEBUG alpha owner; physical EPS/gear token.
NIDEC_PEDAL_AOL = 512 # Model1 only; distinct from model20 STOCK_TJA.
@@ -121,6 +146,55 @@ class HondaFlags(IntFlag):
BOSCH_TJA_CONTROL = 4096
EPS_MODIFIED = 8192
GAS_INTERCEPTOR = 16384
EPS_ANGLE_LOOP_FW = 32768 # the Accord EPS reports the angle-loop firmware (is_accord_eps_angle_loop_fw)
EPS_FW_UNREAD = 65536 # Accord with no EPS fw response: the firmware family is unknown, so do not steer
# Accord EPS angle-loop firmware family: 39990-TVA,A16 + exactly one capital letter (A16A, A16B, A16C ...). Torque
# images read 39990-TVA,A160 (a digit) and stock 39990-TVA-A1x0, so neither matches.
ACCORD_EPS_ANGLE_LOOP_FW_FAMILY = b"39990-TVA,A16"
def is_accord_eps_angle_loop_fw(fw_version: bytes) -> bool:
v = bytes(fw_version).rstrip(b"\x00") # the EPS pads fwVersion with NULs
family = ACCORD_EPS_ANGLE_LOOP_FW_FAMILY
return len(v) == len(family) + 1 and v.startswith(family) and ord("A") <= v[-1] <= ord("Z")
# ---- Accord, angle mode only (steerControlType == angle): the variable-ratio rack map.
# In angle mode sR turns the model's curvature 1:1 into the angle setpoint, so the ratio is a tune here and the learner
# is ignored. SHAPE: absolute ratios measured over 82 routes, V[0] = the on-centre nominal. Not measurements:
# 0-23 deg (pinned by convention, not identified), 31-61 deg (interpolated across two bins that failed the lag test),
# 236+ deg (frozen; above 303 deg the data is parking speed). A compensation curve for calc_curvature's k = d/L,
# not the rack's true geometry. Bands: shape +/-0.12, level +/-0.57.
ACCORD_ANGLE_SR_BP = [0.0, 23.0, 31.0, 61.0, 76.0, 95.0, 116.0, 151.0, 178.0, 227.0, 236.0, 303.0, 380.0] # deg
ACCORD_ANGLE_SR_V = [16.88, 16.88, 16.88, 16.25, 15.97, 15.45, 15.03, 14.68, 14.45, 14.09, 14.25, 12.98, 12.31] # :1
# LEVEL: the served on-centre ratio; the whole shape is scaled by LEVEL / V[0]. 16.84 = the SteerRatio every angle
# drive ran (V298/V299 configs).
ACCORD_ANGLE_SR_LEVEL = 16.84
def accord_angle_steer_ratio(steer_angle_deg: float) -> float:
"""Local ratio of the Accord's rack at this wheel angle (deg, offset removed)."""
ratio = float(np.interp(abs(steer_angle_deg), ACCORD_ANGLE_SR_BP, ACCORD_ANGLE_SR_V))
return ratio * ACCORD_ANGLE_SR_LEVEL / ACCORD_ANGLE_SR_V[0]
def accord_angle_at_own_ratio(angle_vm_deg: float, sr_vm: float, max_passes: int = 10) -> float:
"""The angle setpoint with the map evaluated at the DESIRED angle instead of the measured one.
controlsd sets VM.sR = map(measured angle) and get_steer_from_curvature is linear in sR, so the consistent setpoint
is the fixed point theta = angle_vm_deg * map(theta) / sr_vm. Each pass shrinks the error by <= 0.44 (worst on the
236-303 deg knot); stops within 0.01 deg, a tenth of the EPS setpoint quantum.
"""
theta = float(angle_vm_deg)
for _ in range(max_passes):
nxt = float(angle_vm_deg) * accord_angle_steer_ratio(theta) / sr_vm
done = abs(nxt - theta) < 0.01
theta = nxt
if done:
break
return theta
# Car button codes
@@ -2,6 +2,7 @@ BO_ 228 STEERING_CONTROL: 5 EON
SG_ STEER_TORQUE : 7|16@0- (1,0) [-4096|4096] "" EPS
SG_ DRIVER_OVERRIDE : 17|1@0+ (1,0) [0|1] "" XXX
SG_ STEER_TORQUE_REQUEST : 23|1@0+ (1,0) [0|1] "" EPS
SG_ STEER_CONTROL_ARM : 19|2@0+ (1,0) [0|3] "" EPS
SG_ CONTROL_STATE : 26|3@0+ (1,0) [0|7] "" XXX
SG_ CHECKSUM : 35|4@0+ (1,0) [0|15] "" EPS
SG_ COUNTER : 37|2@0+ (1,0) [0|3] "" EPS
@@ -206,6 +207,7 @@ BO_ 13275 LKAS_HUD_B: 8 ADAS
SG_ COUNTER : 61|2@0+ (1,0) [0|3] "" BDY
CM_ SG_ 228 DRIVER_OVERRIDE "Appears to acknowledge STEER_STATUS.NO_TORQUE_ALERT_1";
CM_ SG_ 228 STEER_CONTROL_ARM "Stock camera sends 0 or 1. The Accord angle-loop EPS firmware (39990-TVA,A16x) runs its lane only while this reads 2";
CM_ SG_ 576 LINE_DISTANCE_VISIBLE "Length of line visible, undecoded";
CM_ SG_ 577 LINE_FAR_EDGE_POSITION "Appears to be a measure of line thickness, indicates location of the portion of the line furthest from the car, undecoded";
CM_ SG_ 577 LINE_PARAMETER "Unclear if this is low quality line curvature rate or if this is something else, but it is correlated with line curvature, undecoded";
+71 -1
View File
@@ -34,6 +34,8 @@ static bool honda_fwd_brake = false;
static bool honda_bosch_long = false;
static bool honda_bosch_radarless = false;
static bool honda_bosch_canfd = false;
static bool honda_accord_angle = false;
#define HONDA_PARAM_ACCORD_ANGLE 4096U
static bool honda_mvl_stock = false;
static uint8_t honda_mvl_buttons_fresh = 0U;
static bool honda_rdx_high_gas = false;
@@ -101,6 +103,23 @@ static uint8_t honda_get_counter(const CANPacket_t *msg) {
return (msg->data[counter_byte] >> 4U) & 0x3U;
}
// The Accord angle-loop EPS firmware (39990-TVA,A16x) exists only on classic Bosch. On it a 0xE4 frame with
// STEER_CONTROL_ARM == 2 carries an angle setpoint in bytes 0-1 (-0.1 deg); the EPS runs its angle lane on no other
// frame, and the stock camera only ever sends 0 or 1 there.
static bool honda_angle_setpoint_capable(void) {
return (honda_hw == HONDA_BOSCH) && honda_accord_angle;
}
// Wheel angle for the angle setpoint check: where a request may start from, and what a request-off frame may hold.
// STEERING_SENSORS is not a required RX check on Honda, so it arrives here, and its checksum is verified here.
static void honda_optional_rx_hook(const CANPacket_t *msg) {
if (honda_angle_setpoint_capable() && msg_matches(msg, 0x14AU, honda_get_pt_bus(), 8U) &&
(honda_get_checksum(msg) == honda_compute_checksum(msg))) {
// STEER_ANGLE, -0.1 deg: the same units and sign as the 0xE4 setpoint
update_sample(&angle_meas, to_signed((msg->data[0] << 8) | msg->data[1], 16));
}
}
static void honda_rx_hook(const CANPacket_t *msg) {
const bool pcm_cruise = ((honda_hw == HONDA_BOSCH) && !honda_bosch_long) || ((honda_hw == HONDA_NIDEC) && !honda_interceptor);
unsigned int pt_bus = honda_get_pt_bus();
@@ -111,6 +130,14 @@ static void honda_rx_hook(const CANPacket_t *msg) {
vehicle_moving = msg->data[0] | msg->data[1];
}
// speed for the angle setpoint check (Accord angle-loop EPS)
if (honda_angle_setpoint_capable()) {
if (msg_matches(msg, 0x158U, pt_bus)) {
// ENGINE_DATA XMISSION_SPEED, 0.01 kph
UPDATE_VEHICLE_SPEED(((msg->data[0] << 8) | msg->data[1]) * 0.01 * KPH_TO_MS);
}
}
// check ACC main state
// 0x326 for all Bosch and some Nidec, 0x1A6 for some Nidec
if ((!aol_honda_bosch_long && ((msg->addr == 0x326U) || (msg->addr == 0x1A6U))) ||
@@ -317,6 +344,40 @@ static bool honda_tx_hook(const CANPacket_t *msg) {
}
}
// STEER: angle setpoint frames (STEER_CONTROL_ARM == 2, Accord angle-loop EPS) must stay inside the lateral
// acceleration and jerk limits, checked with the vehicle model on the value as sent
if ((msg->addr == 0xE4U) && (((msg->data[2] >> 2) & 0x3U) == 2U)) {
const AngleSteeringLimits HONDA_ACCORD_ANGLE_LIMITS = {
.max_angle = 4000, // 400 deg, the EPS clamps its setpoint just above this
.angle_deg_to_can = 10,
.frequency = 100U,
};
// NOTE: HONDA_ACCORD, must match openpilot's VehicleModel
const AngleSteeringParams HONDA_ACCORD_ANGLE_PARAMS = {
.slip_factor = -0.0006999872680281922, // calc_slip_factor(VM)
.steer_ratio = 16.33,
.wheelbase = 2.83,
};
const int desired_angle = to_signed((msg->data[0] << 8) | msg->data[1], 16);
const bool steer_req = GET_BIT(msg, 23U); // STEER_TORQUE_REQUEST
bool violation = !honda_angle_setpoint_capable();
if (!violation) {
if (!steer_req && (desired_angle == 0)) {
// request off with a zero field: nothing is commanded, the next request starts from the wheel
desired_angle_last = SAFETY_CLAMP(angle_meas.values[0], -HONDA_ACCORD_ANGLE_LIMITS.max_angle, HONDA_ACCORD_ANGLE_LIMITS.max_angle);
} else {
violation |= steer_angle_cmd_checks_vm(desired_angle, steer_req, HONDA_ACCORD_ANGLE_LIMITS, HONDA_ACCORD_ANGLE_PARAMS);
violation |= safety_max_limit_check(desired_angle, HONDA_ACCORD_ANGLE_LIMITS.max_angle, -HONDA_ACCORD_ANGLE_LIMITS.max_angle);
}
}
if (violation) {
tx = false;
}
}
// Bosch supplemental control check
if (msg->addr == 0xE5U) {
if ((GET_BYTES_64_LE(msg, 0, 8) & 0x00FFFFFFFFFFFFFFULL) != 0x0000000010800004ULL) {
@@ -381,6 +442,7 @@ static safety_config honda_nidec_init(uint16_t param) {
const uint16_t HONDA_PARAM_NIDEC_ALT = 4;
honda_hw = HONDA_NIDEC;
honda_accord_angle = false;
honda_brake = 0;
honda_brake_switch_prev = false;
honda_fwd_brake = false;
@@ -426,7 +488,14 @@ static safety_config honda_nidec_init(uint16_t param) {
return ret;
}
static safety_config honda_bosch_init(uint16_t param) {
static safety_config honda_bosch_init(uint16_t requested_param) {
// Apply the Accord flag only to the classic Bosch base configurations the host can select.
const uint16_t param = (uint16_t)(requested_param & ~HONDA_PARAM_ACCORD_ANGLE);
bool accord_base = (param == 0U) || (param == 1U);
#ifdef ALLOW_DEBUG
accord_base = accord_base || (param == 2U) || (param == 3U) || (param == 2082U) || (param == 2083U);
#endif
honda_accord_angle = GET_FLAG(requested_param, HONDA_PARAM_ACCORD_ANGLE) && accord_base;
honda_mvl_stock = ((param == 80U) || (param == 81U)) && ((alternative_experience == 0) || (alternative_experience == 32));
honda_mvl_buttons_fresh = 0U;
honda_interceptor_reset(false);
@@ -614,6 +683,7 @@ const safety_hooks honda_bosch_hooks = {
.fwd = honda_mvl_stock_fwd_hook,
.init = honda_bosch_init,
.rx = honda_rx_hook,
.optional_rx = honda_optional_rx_hook,
.tx = honda_tx_hook,
.get_counter = honda_get_counter,
.get_checksum = honda_get_checksum,
@@ -0,0 +1,279 @@
#!/usr/bin/env python3
"""Accord angle-loop EPS: the panda bounds the 0xE4 angle setpoint by the lateral accel and jerk limits."""
import math
import re
import unittest
from pathlib import Path
from types import SimpleNamespace
import numpy as np
from opendbc.car import Bus, gen_empty_fingerprint
from opendbc.car.honda.carcontroller import CarController
from opendbc.car.honda.interface import CarInterface
from opendbc.car.honda.values import CAR, DBC, CarControllerParams, HondaSafetyFlags
from opendbc.car.lateral import MAX_LATERAL_ACCEL, get_max_angle_delta_vm, get_max_angle_vm
from opendbc.car.structs import CarParams
from opendbc.car.vehicle_model import VehicleModel, calc_slip_factor
from opendbc.safety.tests.libsafety import libsafety_py
from opendbc.safety.tests import test_honda # the module, so its test classes are not collected again here
P = CarControllerParams
ARM = P.ANGLE_ARM
DT_US = 10_000 # 0xE4 is sent at 100 Hz
SPEEDS = (1.0, 3.0, 5.0, 8.0, 10.0, 12.0, 17.5, 22.0, 26.9, 31.0, 38.0)
def accord_cp():
fw = [CarParams.CarFw(ecu=CarParams.Ecu.eps, fwVersion=b"39990-TVA,A16C", address=0x18DA30F1, subAddress=0)]
return CarInterface.get_params(CAR.HONDA_ACCORD, gen_empty_fingerprint(), fw, False, False, False)
class TestHondaAccordAngleSetpoint(unittest.TestCase):
def setUp(self):
self.fixture = test_honda.TestHondaBoschAltBrakeSafety('test_spam_cancel_safety_check')
self.fixture.setUp()
self.safety = self.fixture.safety
self.packer = self.fixture.packer
self.CP = accord_cp()
self.angle_flag = self.CP.safetyConfigs[0].safetyParam
self.assertNotEqual(self.angle_flag, 0)
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, self.angle_flag | 1), 0)
self.safety.init_tests()
self.VM = VehicleModel(self.CP)
self.params = P(self.CP)
self.t = 1_000_000
self.safety.set_timer(self.t)
# ---- helpers
def _angle_frame(self, raw, steer_req, arm=ARM, bus=None):
values = {"STEER_TORQUE": raw, "STEER_TORQUE_REQUEST": steer_req, "STEER_CONTROL_ARM": arm}
return self.packer.make_can_msg_safety("STEERING_CONTROL", self.fixture.STEER_BUS if bus is None else bus, values)
def _tx(self, raw, steer_req=True, arm=ARM, bus=None):
self.t += DT_US
self.safety.set_timer(self.t)
return self.fixture._tx(self._angle_frame(raw, steer_req, arm, bus))
def _rx_speed(self, v_ms):
self.fixture._rx(self.fixture._speed_msg(v_ms * 3.6))
def _rx_wheel(self, raw):
# STEER_ANGLE is -0.1 deg per count: the raw count equals the 0xE4 raw for the same angle
self.fixture._rx(self.packer.make_can_msg_safety("STEERING_SENSORS", self.fixture.PT_BUS, {"STEER_ANGLE": -raw / 10.0}))
def _settle(self, v_ms, wheel_raw=0):
for _ in range(6):
self._rx_speed(v_ms)
self._rx_wheel(wheel_raw)
def _panda_max_angle_raw(self, v_ms):
# the panda evaluates the model 1 m/s below its slowest speed sample and allows one count of rounding
return int(get_max_angle_vm(max(v_ms - 1.0, 1.0), self.VM, self.params) * 10 + 1.0)
def _panda_max_delta_raw(self, v_ms):
return int(get_max_angle_delta_vm(max(v_ms - 1.0, 1.0), self.VM, self.params) * 10 + 1.0)
def test_stock_profiles_and_incompatible_flag_combinations_reject_angle_frames(self):
is_debug = self.safety.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0
ordinary = (0, 1, 2, 3, 2082, 2083)
invalid = (self.angle_flag | 8, self.angle_flag | 16, self.angle_flag | 128)
if not is_debug:
invalid += tuple(self.angle_flag | word for word in ordinary if word & 2)
for word in ordinary + invalid:
with self.subTest(word=word):
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, word), 0)
self.safety.init_tests()
self._settle(10.0)
self.safety.set_controls_allowed(True)
bus = int(bool(is_debug and word & 2))
self.assertFalse(self._tx(10, bus=bus), word)
self.assertFalse(self._tx(0, steer_req=False, bus=bus), word)
if word in ordinary:
self.assertTrue(self._tx(10, arm=0, bus=bus), word)
def test_flag_preserves_lateral_on_supported_classic_bosch_configurations(self):
is_debug = self.safety.set_safety_hooks(CarParams.SafetyModel.allOutput, 0) == 0
base_words = (0, 1, 2, 3, 2082, 2083) if is_debug else (0, 1)
for base in base_words:
with self.subTest(base=base):
self.assertEqual(self.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, self.angle_flag | base), 0)
self.safety.init_tests()
self._settle(10.0)
self.safety.set_controls_allowed(True)
self.assertTrue(self._tx(10, bus=int(bool(base & 2))), base)
# ---- the model the panda uses is the one openpilot uses
def test_vehicle_model_constants_match_openpilot(self):
src = (Path(__file__).parents[1] / "modes" / "honda.h").read_text(encoding="utf-8")
block = src[src.index("HONDA_ACCORD_ANGLE_PARAMS = {"):]
block = block[:block.index("};")]
read = {k: float(v) for k, v in re.findall(r"\.(\w+)\s*=\s*(-?[\d.]+)", block)}
self.assertAlmostEqual(read["slip_factor"], calc_slip_factor(self.VM), places=12)
self.assertAlmostEqual(read["steer_ratio"], self.CP.steerRatio, places=5)
self.assertAlmostEqual(read["wheelbase"], self.CP.wheelbase, places=5)
self.assertAlmostEqual(MAX_LATERAL_ACCEL, 3.589, places=3)
self.assertEqual(self.params.ANGLE_LIMITS.MAX_LATERAL_ACCEL, MAX_LATERAL_ACCEL)
# ---- lateral acceleration limit
def test_setpoint_beyond_the_lateral_accel_limit_is_blocked(self):
for v in SPEEDS:
limit = self._panda_max_angle_raw(v)
if limit > 4000:
continue # below ~5 m/s the 400 deg ceiling binds first (covered below)
for sign in (-1, 1):
self._settle(v)
self.safety.set_controls_allowed(True)
self.safety.set_desired_angle_last(sign * limit)
self.assertTrue(self._tx(sign * limit), (v, sign))
self.assertFalse(self._tx(sign * (limit + 1)), (v, sign))
# the first blocked frame resets the panda to the wheel; a setpoint this far out stays blocked
self.assertFalse(self._tx(sign * (limit + 1)), (v, sign))
def test_the_old_order_counterexample_is_blocked(self):
# 26.9 m/s, wheel held at 42 deg: the old code sent 29.8 deg (5.4 m/s^2) against a 19.8 deg limit
v = 26.9
self._settle(v, wheel_raw=420)
self.safety.set_controls_allowed(True)
self.safety.set_desired_angle_last(298)
self.assertFalse(self._tx(298))
self.assertGreater(298, self._panda_max_angle_raw(v))
def test_setpoint_beyond_400_deg_is_blocked(self):
self._settle(1.0, wheel_raw=4000)
self.safety.set_controls_allowed(True)
for raw, ok in ((4000, True), (4001, False), (-4000, True), (-4001, False), (4096, False)):
self.safety.set_desired_angle_last(raw)
self.assertEqual(ok, self._tx(raw), raw)
# ---- lateral jerk limit
def test_step_beyond_the_lateral_jerk_limit_is_blocked(self):
for v in SPEEDS:
delta = self._panda_max_delta_raw(v)
for sign in (-1, 1):
for start in (0, 50):
if start + delta + 1 > min(self._panda_max_angle_raw(v), 4000):
continue
self._settle(v, wheel_raw=sign * start)
self.safety.set_controls_allowed(True)
self.safety.set_desired_angle_last(sign * start)
self.assertTrue(self._tx(sign * (start + delta)), (v, sign, start))
self.safety.set_desired_angle_last(sign * start)
self.assertFalse(self._tx(sign * (start + delta + 1)), (v, sign, start))
def test_a_blocked_frame_restarts_from_the_wheel(self):
v = 20.0
self._settle(v, wheel_raw=30)
self.safety.set_controls_allowed(True)
self.safety.set_desired_angle_last(30)
self.assertFalse(self._tx(30 + self._panda_max_delta_raw(v) + 1))
self.assertEqual(self.safety.get_desired_angle_last(), 30)
self.assertTrue(self._tx(30 + self._panda_max_delta_raw(v)))
# ---- request off
def test_request_off_frames(self):
v = 15.0
self._settle(v, wheel_raw=-234)
for allowed in (True, False):
self.safety.set_controls_allowed(allowed)
self.assertTrue(self._tx(0, steer_req=False)) # nothing commanded
self.assertEqual(self.safety.get_desired_angle_last(), -234)
self.assertEqual(allowed, self._tx(-234, steer_req=False)) # hold at the wheel: only while lateral is allowed
self.assertFalse(self._tx(-200, steer_req=False)) # anything else is not the wheel
self.assertFalse(self._tx(100, steer_req=False))
def test_request_needs_controls_allowed(self):
self._settle(15.0, wheel_raw=0)
self.safety.set_controls_allowed(False)
self.assertFalse(self._tx(0, steer_req=True))
self.assertFalse(self._tx(5, steer_req=True))
self.safety.set_controls_allowed(True)
self.assertTrue(self._tx(0, steer_req=True))
def test_engage_from_a_zero_field_starts_at_the_wheel(self):
# always-on lateral case: the carcontroller sends a zero field until the request, then starts from the wheel
v = 25.0
self._settle(v, wheel_raw=150)
self.safety.set_controls_allowed(True)
for _ in range(5):
self.assertTrue(self._tx(0, steer_req=False))
self.assertTrue(self._tx(150 + self._panda_max_delta_raw(v), steer_req=True))
# ---- torque frames (arm 0 or 1) are not angle setpoints
def test_torque_frames_are_unaffected(self):
self._settle(30.0)
self.safety.set_controls_allowed(True)
for arm in (0, 1):
for raw in (-4096, -1000, 0, 1000, 4096):
self.assertTrue(self._tx(raw, steer_req=True, arm=arm), (arm, raw))
self.safety.set_controls_allowed(False)
self.assertTrue(self._tx(0, steer_req=False, arm=0))
self.assertFalse(self._tx(1000, steer_req=True, arm=0))
# ---- message rate
def test_message_rate_limit(self):
self._settle(20.0)
self.safety.set_controls_allowed(True)
blocked = False
for _ in range(40): # 40 frames inside one 250 ms window: more than 100 Hz allows
blocked |= not self.fixture._tx(self._angle_frame(0, True))
self.assertTrue(blocked)
# ---- the carcontroller's own output is what the panda checks, and it always passes
def _controller_frames(self, v_of, wheel_of, desired_of, frames):
cc = CarController({Bus.pt: DBC[CAR.HONDA_ACCORD][Bus.pt]}, self.CP)
blocked = withheld = 0
for i in range(frames):
v, wheel = v_of(i), wheel_of(i)
wheel_raw = math.floor(-10.0 * wheel + 0.5)
self._rx_speed(v)
self._rx_wheel(wheel_raw)
active = i >= 12 # as on the road, request-off frames come first: they fill the panda's samples
CC = SimpleNamespace(actuators=SimpleNamespace(steeringAngleDeg=desired_of(i)), latActive=active, enabled=True)
# carState reads the angle off the same STEER_ANGLE counts and the speed off the wheels
CS = SimpleNamespace(out=SimpleNamespace(steeringAngleDeg=-wheel_raw / 10.0, vEgoRaw=v,
cruiseState=SimpleNamespace(available=True)))
_, raw = cc._update_angle(CC, CS)
withheld += active and not cc.angle_steer_req
blocked += not self._tx(raw, steer_req=cc.angle_steer_req)
return blocked, withheld
def test_carcontroller_output_is_never_blocked(self):
self.safety.set_controls_allowed(True)
rng = np.random.default_rng(1)
cases = {
"lane keeping": (lambda i: 28.0, lambda i: 2.0 * math.sin(i / 60.0), lambda i: 3.0 * math.sin(i / 50.0)),
"saturating request": (lambda i: 20.0, lambda i: 0.0, lambda i: 300.0 * math.sin(i / 100.0)),
"random request": (lambda i: 12.0, lambda i: 10.0 * math.sin(i / 40.0), lambda i: float(rng.uniform(-400, 400))),
"tight turn": (lambda i: 4.0, lambda i: min(i * 2.0, 380.0), lambda i: 400.0),
"driver past the limit": (lambda i: 26.9, lambda i: min(i * 0.3, 45.0), lambda i: 0.0),
"driver yank": (lambda i: 17.5, lambda i: 60.0 * math.sin(i / 8.0), lambda i: 5.0),
"braking": (lambda i: max(30.0 - i * 0.03, 2.0), lambda i: 5.0, lambda i: 400.0),
"accelerating": (lambda i: min(3.0 + i * 0.03, 35.0), lambda i: 0.0, lambda i: -400.0),
}
for name, (v_of, wheel_of, desired_of) in cases.items():
self.safety.set_controls_allowed(True)
blocked, withheld = self._controller_frames(v_of, wheel_of, desired_of, 900)
self.assertEqual(0, blocked, name)
# the request is withheld only where the wheel is past the limit when it would start: the yank reaches 60 deg
# against a 38 deg limit. Everywhere else every frame carries the request.
self.assertEqual(name == "driver yank", withheld > 0, (name, withheld))
class TestHondaAngleSetpointOnOtherBosch(unittest.TestCase):
"""A radarless or CAN FD Honda has no angle-loop EPS: an armed frame is never sent, and is blocked if it is."""
def test_armed_frame_is_blocked(self):
fixture = test_honda.TestHondaBoschRadarlessSafety('test_spam_cancel_safety_check')
fixture.setUp()
fixture.safety.set_safety_hooks(CarParams.SafetyModel.hondaBosch, HondaSafetyFlags.RADARLESS)
fixture.safety.init_tests()
fixture.safety.set_controls_allowed(True)
for arm, ok in ((0, True), (1, True), (ARM, False)):
# bytes 0-1 zero, STEER_TORQUE_REQUEST set, STEER_CONTROL_ARM in byte 2 bits 3:2
packet = libsafety_py.make_CANPacket(0xE4, fixture.STEER_BUS, bytes([0, 0, 0x80 | (arm << 2), 0, 0]))
self.assertEqual(ok, fixture._tx(packet), arm)
if __name__ == "__main__":
unittest.main()
@@ -16,6 +16,7 @@ from openpilot.selfdrive.controls.lib.cycle_timing import ControlCycleTiming, PU
from openpilot.common.swaglog import cloudlog
from opendbc.car.car_helpers import interfaces
from opendbc.car.honda.values import CAR as HONDA_CAR, accord_angle_steer_ratio
from opendbc.car.vehicle_model import VehicleModel
from openpilot.selfdrive.controls.lib.drive_helpers import clip_curvature
from openpilot.selfdrive.controls.lib.highway_correction_gain import HighwayCorrectionGain, predicted_lateral_accels, read_gain
@@ -357,6 +358,9 @@ class Controls:
torque_extension = getattr(self.LaC, 'starpilot_extension', None)
if torque_extension is not None:
sr = torque_extension.vehicle_model_ratio(sr, CS.vEgo)
if self.CP.carFingerprint == HONDA_CAR.HONDA_ACCORD and self.CP.steerControlType == car.CarParams.SteerControlType.angle:
# angle-loop EPS: the variable-ratio rack map at the measured angle replaces the learner
sr = accord_angle_steer_ratio(CS.steeringAngleDeg - lp.angleOffsetDeg)
self.VM.update_params(x, sr)
steer_angle_without_offset = math.radians(CS.steeringAngleDeg - lp.angleOffsetDeg)
@@ -1,6 +1,7 @@
import math
from openpilot.cereal import log
from opendbc.car.honda.values import CAR as HONDA_CAR, HondaFlags, accord_angle_at_own_ratio
from openpilot.selfdrive.controls.lib.latcontrol import LatControl
from openpilot.starpilot.car.subaru.angle_tune import _ascent_angle_tracking_target, _ascent_low_speed_angle_target
@@ -14,7 +15,11 @@ class LatControlAngle(LatControl):
self.is_ascent = CP.brand == 'subaru' and CP.carFingerprint == 'SUBARU_ASCENT_2023'
self.ascent_angle_target = None
self.sat_check_min_speed = 5.
self.use_steer_limited_by_safety = CP.brand in ("tesla", "hyundai")
# Accord on the angle-loop EPS: the EPS angle loop lags 0.3-0.6 s, so a raw angle-error rule flags ordinary turn
# entries; its carcontroller limits the setpoint itself (lateral accel/jerk, error clip), so use carOutput instead
self.is_accord_angle_loop = CP.brand == "honda" and bool(CP.flags & HondaFlags.EPS_ANGLE_LOOP_FW)
self.use_steer_limited_by_safety = CP.brand in ("tesla", "hyundai") or self.is_accord_angle_loop
self.is_accord = CP.carFingerprint == HONDA_CAR.HONDA_ACCORD
def update(self, active, CS, VM, params, steer_limited_by_safety, desired_curvature, curvature_limited, lat_delay):
angle_log = log.ControlsState.LateralAngleState.new_message()
@@ -26,6 +31,9 @@ class LatControlAngle(LatControl):
else:
angle_log.active = True
angle_steers_des = math.degrees(VM.get_steer_from_curvature(-desired_curvature, CS.vEgo, params.roll))
if self.is_accord:
# controlsd took sR from the rack map at the MEASURED angle; re-evaluate it at the desired angle
angle_steers_des = accord_angle_at_own_ratio(angle_steers_des, VM.sR)
angle_steers_des += params.angleOffsetDeg
if self.is_ascent:
if self.ascent_angle_target is None:
@@ -0,0 +1,121 @@
"""Accord on the angle-loop EPS: steerSaturated follows the carcontroller's limiter, not the raw angle error."""
import pytest
from openpilot.cereal import log
from opendbc.car import gen_empty_fingerprint
from opendbc.car.structs import car
from opendbc.car.honda import carcontroller as honda_carcontroller
from opendbc.car.honda import interface as honda_interface
from opendbc.car.honda.interface import CarInterface as HondaInterface
from opendbc.car.honda.values import CAR as HONDA, HondaFlags
from opendbc.car.nissan.interface import CarInterface as NissanInterface
from opendbc.car.nissan.values import CAR as NISSAN
from opendbc.car.structs import CarParams
from opendbc.car.vehicle_model import VehicleModel
from openpilot.selfdrive.controls.lib.latcontrol_angle import LatControlAngle
DT = 0.01
ERROR_DEG = 6.0 # an ordinary turn-entry error on the angle-loop EPS, above the 2.5 deg raw-error threshold
class FakeParams:
def get_bool(self, key, block=False, default=False):
return default
def get_float(self, key, block=False, default=0.0):
return default
def put_float(self, key, value):
pass
@pytest.fixture(autouse=True)
def fake_params(monkeypatch):
# the Honda port may read Params in the interface/carcontroller; keep the test off the device store
monkeypatch.setattr(honda_interface, "Params", FakeParams, raising=False)
monkeypatch.setattr(honda_carcontroller, "Params", FakeParams, raising=False)
def accord_cp(eps_fw: bytes):
car_fw = [CarParams.CarFw(ecu=CarParams.Ecu.eps, fwVersion=eps_fw, address=0x18DA30F1, subAddress=0)]
return HondaInterface.get_params(HONDA.HONDA_ACCORD, gen_empty_fingerprint(), car_fw, False, False, False)
def angle_cp():
return accord_cp(b"39990-TVA,A16C")
def torque_honda_cp():
return accord_cp(b"39990-TVA-A160\x00\x00")
def nissan_cp():
return NissanInterface.get_non_essential_params(NISSAN.NISSAN_LEAF)
def run(cp, steer_limited_by_safety, seconds=2.0, v_ego=20.0):
cp_reader = cp.as_reader()
controller = LatControlAngle(cp_reader, None, DT)
VM = VehicleModel(cp_reader)
params = log.VehicleParameters.new_message()
CS = car.CarState.new_message()
CS.vEgo = v_ego
CS.steeringPressed = False
CS.steeringAngleDeg = 0.0
# find the desired angle for a small curvature, then hold the wheel ERROR_DEG short of it
_, angle_des, _ = controller.update(True, CS, VM, params, False, 0.002, False, 0.2)
controller.reset()
CS.steeringAngleDeg = angle_des - ERROR_DEG
saturated = []
for _ in range(round(seconds / DT)):
_, des, lac_log = controller.update(True, CS, VM, params, steer_limited_by_safety, 0.002, False, 0.2)
assert abs((des - CS.steeringAngleDeg) - ERROR_DEG) < 1e-6
saturated.append(lac_log.saturated)
return controller, saturated
def test_accord_angle_cp_takes_the_carcontroller_path():
cp = angle_cp()
assert cp.steerControlType == CarParams.SteerControlType.angle
assert cp.flags & HondaFlags.EPS_ANGLE_LOOP_FW
assert cp.steerLimitTimer == pytest.approx(0.8)
def test_accord_angle_error_alone_does_not_saturate():
controller, saturated = run(angle_cp(), steer_limited_by_safety=False)
assert controller.use_steer_limited_by_safety
assert not any(saturated)
def test_accord_angle_limited_by_carcontroller_saturates():
_, saturated = run(angle_cp(), steer_limited_by_safety=True)
assert saturated[-1]
# debounced by steerLimitTimer (0.8 s), not instantly
assert not saturated[round(0.7 / DT)]
def test_accord_angle_curvature_limited_still_saturates():
cp = angle_cp().as_reader()
controller = LatControlAngle(cp, None, DT)
VM = VehicleModel(cp)
CS = car.CarState.new_message()
CS.vEgo = 20.0
params = log.VehicleParameters.new_message()
for _ in range(200):
_, _, lac_log = controller.update(True, CS, VM, params, False, 0.0, True, 0.2)
assert lac_log.saturated
@pytest.mark.parametrize("cp_fn", [torque_honda_cp, nissan_cp], ids=["honda_torque_fw", "nissan"])
def test_other_cars_keep_the_angle_error_rule(cp_fn):
controller, saturated = run(cp_fn(), steer_limited_by_safety=False)
assert not controller.use_steer_limited_by_safety
assert saturated[-1]
def test_tesla_still_uses_carcontroller_path():
from opendbc.car.tesla.interface import CarInterface as TeslaInterface
from opendbc.car.tesla.values import CAR as TESLA
controller, saturated = run(TeslaInterface.get_non_essential_params(TESLA.TESLA_MODEL_3), steer_limited_by_safety=False)
assert controller.use_steer_limited_by_safety
assert not any(saturated)
Binary file not shown.
Binary file not shown.
@@ -607,12 +607,13 @@ int main() {
unsupported.safety_param ^= 0x1U;
assert(!aol_capable(unsupported, TEST_MODE, TEST_REGISTRY));
for (uint16_t word = 0U; word < 4096U; ++word) {
for (uint16_t word = 0U; word < 8192U; ++word) {
auto stock_honda = status();
stock_honda.safety_mode = 20U;
stock_honda.safety_param = word;
const bool classic = word == 34U || word == 35U || word == 163U;
const bool stock = word == 0U || word == 1U || word == 8U || word == 9U || word == 10U || word == 11U || word == 16U || word == 17U || word == 80U || word == 81U || word == 512U || word == 513U || word == 1058U || word == 1059U || word == 1570U || word == 1571U || word == 2082U || word == 2083U || word == 2211U;
const bool stock = word == 0U || word == 1U || word == 8U || word == 9U || word == 10U || word == 11U || word == 16U || word == 17U || word == 80U || word == 81U || word == 512U || word == 513U || word == 1058U || word == 1059U || word == 1570U || word == 1571U || word == 2082U || word == 2083U || word == 2211U ||
word == 4096U || word == 4097U || word == 6178U || word == 6179U;
assert(aol_capable(stock_honda, 20U, VEHICLE_REGISTRY) == (classic || stock));
assert(aol_runtime_enabled(false, stock_honda, VEHICLE_REGISTRY) == stock);
stock_honda.safety_mode = 1U;
@@ -12,6 +12,7 @@ from openpilot.system.ui.lib.application import gui_app
from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient
from openpilot.system.ui.widgets import Widget
from openpilot.common.filter_simple import FirstOrderFilter
from openpilot.starpilot.ui.torque_feedback import accord_angle_error_bar, accord_angle_error_fraction
# TODO: arc_bar_pts doesn't consider rounded end caps part of the angle span
TORQUE_ANGLE_SPAN = 12.7 # degrees on the default 476 px camera view; narrower views beside the navigation panel scale down
@@ -162,6 +163,18 @@ class TorqueBar(Widget):
if self._demo:
return
# Accord on the angle-loop EPS firmware: the bar is the angle error the setpoint carries,
# (setpoint sent - wheel angle) / the carcontroller's error clip at this speed, so full
# scale means the clip is binding. Sign follows the torque branch: bar points the way the EPS pulls.
if accord_angle_error_bar(ui_state.CP):
car_state = ui_state.sm['carState']
if not ui_state.sm['carControl'].latActive:
self._torque_filter.update(0.0)
else:
setpoint = ui_state.sm['carOutput'].actuatorsOutput.steeringAngleDeg
self._torque_filter.update(accord_angle_error_fraction(setpoint, car_state.steeringAngleDeg, car_state.vEgoRaw))
return
# torque line
if ui_state.sm['controlsState'].lateralControlState.which() in ('angleState', 'curvatureState'):
controls_state = ui_state.sm['controlsState']
+2 -1
View File
@@ -11,7 +11,8 @@ inline constexpr AolSafetyProfile HONDA_AOL_PROFILE{20U, honda_aol_param, false}
inline bool honda_stock_aol_param(uint16_t param) {
return (param == 0U) || (param == 1U) || (param == 8U) || (param == 9U) || (param == 10U) || (param == 11U) || (param == 16U) || (param == 17U) || (param == 80U) || (param == 81U) || (param == 512U) || (param == 513U) ||
(param == 1058U) || (param == 1059U) || (param == 1570U) || (param == 1571U) || (param == 2082U) || (param == 2083U) || (param == 2211U);
(param == 1058U) || (param == 1059U) || (param == 1570U) || (param == 1571U) || (param == 2082U) || (param == 2083U) || (param == 2211U) ||
(param == 4096U) || (param == 4097U) || (param == 6178U) || (param == 6179U);
}
inline bool honda_nidec_aol_param(uint16_t param) {
@@ -99,7 +99,7 @@ class LogRelayStager:
self._connection_zip = connection_zip
self._controller_zip = controller_zip
self._post = post
self._stage_url = stage_url
self._stage_url: Callable[[], str] | str = stage_url
self._official = official
self._lock = threading.Lock()
self._thread: threading.Thread | None = None
@@ -108,7 +108,8 @@ class LogRelayStager:
self._fork: bool | None = None
def _url(self) -> str:
return self._stage_url() if callable(self._stage_url) else self._stage_url
stage_url = self._stage_url
return stage_url if isinstance(stage_url, str) else stage_url()
def status(self, session=None) -> dict:
with self._lock:
@@ -162,10 +162,10 @@ DESCRIPTIONS = {
'EngageVolume': 'Sets the engagement-chime volume.',
'DisengageVolume': 'Sets the disengagement-alert volume.',
'PromptVolume': 'Sets the volume of general prompts.',
'PIPPreviewEnabled': 'Shows the configured blind-spot camera preview when fresh camera frames are available.',
'PIPPreviewShowOnBlinker': 'Shows the blind-spot camera preview while a turn signal is on.',
'PIPPreviewShowOnBSM': 'Shows the blind-spot camera preview during a blind-spot warning.',
'PIPPreviewInvert': 'Mirrors the blind-spot camera crop horizontally.',
'PIPPreviewEnabled': 'Shows the configured Adj Spot Camera preview when fresh camera frames are available.',
'PIPPreviewShowOnBlinker': 'Shows the Adj Spot Camera preview while a turn signal is on.',
'PIPPreviewShowOnBSM': 'Shows the Adj Spot Camera preview during a blind-spot warning.',
'PIPPreviewInvert': 'Mirrors the Adj Spot Camera crop horizontally.',
'pip:mask:size': 'Sets the size of each camera-image crop shown in the preview.',
'pip:mask:editor': 'Edits the source-image crop for the vehicle left and right camera views.',
'pip:reset': 'Restores the default source-image camera crops.',
@@ -8,7 +8,7 @@ import threading
import time
from types import SimpleNamespace
import unittest
from unittest.mock import Mock, patch
from unittest.mock import Mock
from openpilot.starpilot.galaxy.access import GalaxyAccessOwner
from openpilot.starpilot.galaxy.log_relay_stage import LogRelayStager
@@ -27,8 +27,8 @@ print(json.dumps(documents))
`], { encoding: "utf8" }))
for (const document of signalEdges) assert.equal(validDocument(document, data.metadata), true)
assert.equal(validSnapshot(data), true)
assert.equal(data.document.version, 16)
for (const version of [9, 10, 15, 17]) {
assert.equal(data.document.version, 17)
for (const version of [9, 10, 15, 16, 18]) {
assert.equal(validSnapshot({ ...data, document: { ...data.document, version } }), false)
assert.equal(validSnapshot({ ...data, defaults: { ...data.defaults, version } }), false)
}
@@ -1,4 +1,5 @@
import assert from "node:assert/strict"
import { compile } from "../web/vendor/vue/vue.esm-browser.js"
import * as documentHelpers from "../web/js/onroad-layout-document.js"
import * as layoutModule from "../web/js/onroad-layout.js"
import { ONROAD_LAYOUT_TEMPLATE } from "../web/js/onroad-layout-template.js"
@@ -54,7 +55,7 @@ export function snapshot() {
metadata.roadColorFields = [{ id: 'path', label: 'Path', default: '#30FF9CFF' },
{ id: 'pathEdge', label: 'Path edges', default: '#00FF40FF' }, { id: 'laneLines', label: 'Lane lines', default: '#FFFFFFFF' }]
metadata.profiles.compact.widgets.speed_limit.visualInsetTop = 32
const document = { version: 16, roadColors: { large: {}, compact: {} }, widgetColors: { large: {}, compact: {} }, palette: Object.fromEntries(metadata.paletteFields.map((field) => [field.id, field.default])),
const document = { version: 17, roadColors: { large: {}, compact: {} }, widgetColors: { large: {}, compact: {} }, palette: Object.fromEntries(metadata.paletteFields.map((field) => [field.id, field.default])),
layouts: Object.fromEntries(Object.entries(metadata.profiles).map(([id, profile]) => [id,
Object.fromEntries(Object.entries(profile.widgets).map(([key, definition]) => [key,
{ ...definition.default, ...(definition.resizable ? { size: definition.resizable.default } : {}) }]))])) }
@@ -364,6 +365,11 @@ try {
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: {
getItem: key => preferences.get(key) ?? null, setItem: (key, value) => preferences.set(key, value)
} })
assert.equal(editor().vm.state.hiddenPreviewWidgets.compact.pip_left, true)
assert.equal(OnroadLayoutPage.setup({ projection: true }).state.hiddenPreviewWidgets.compact.pip_left, undefined)
preferences.set("gx-layout-preview-visibility-v2:comma", JSON.stringify({ compact: { pip_left: false } }))
assert.equal(editor().vm.state.hiddenPreviewWidgets.compact.pip_left, false)
preferences.delete("gx-layout-preview-visibility-v2:comma")
const preference = editor().vm
assert.equal(preference.state.snapEnabled, true)
preference.toggleSnap()
@@ -1386,11 +1392,11 @@ console.log("Ford rear fog: make visibility, saved placement and strict metadata
assert.equal(clampPlacement(profile, 'speed_limit', 330, 16, sample.document.layouts.compact).x, 320)
}
// The device writes version 16 once the speed limit actions widget is folded into the sign.
// The device writes version 17 with full-panel C4 side cameras.
{
const sample = snapshot()
assert.equal(validDocument(sample.document, sample.metadata), true)
sample.document.version = 15
sample.document.version = 16
assert.equal(validDocument(sample.document, sample.metadata), false)
}
@@ -1403,3 +1409,45 @@ for (const invalidOffset of [true, null, "1", NaN, Infinity, -5.1, 5.1]) {
assert.equal(validDocument(document, speedAdjustment.metadata), false)
}
assert.ok(SETTINGS_SECTIONS.find(section => section.id === "developer").pages.includes("developer"))
// C4 has one locked camera widget covering the road panel.
{
const sample = snapshot()
const profile = sample.metadata.profiles.compact
for (const side of ["left"]) {
const id = `pip_${side}`
profile.widgets[id] = widget("Adj Spot Camera", "pip_camera", 476, 240, 0, 0)
sample.document.layouts.compact[id] = { x: 0, y: 0, enabled: side === "left" }
assert.deepEqual(clampPlacement(profile, id, 300, 100, sample.document.layouts.compact), { x: 0, y: 0 })
assert.deepEqual(documentHelpers.widgetSize(profile.widgets[id], sample.document.layouts.compact[id]), [476, 240])
}
assert.equal(validDocument(sample.document, sample.metadata), true)
const vm = editor().vm
vm.state.data = sample; vm.state.draft = copy(sample.document); vm.state.profile = "compact"
assert.deepEqual(vm.cameraIds, ["pip_left"])
assert.deepEqual(vm.lockedCameraIds, ["pip_left"])
const original = copy(vm.state.draft)
assert.equal(vm.previewHidden("pip_left"), true)
assert.equal(vm.renderWidgets.some(widget => widget.id === "pip_left"), false)
vm.togglePreviewVisibility("pip_left")
assert.equal(vm.previewHidden("pip_left"), false)
assert.equal(vm.renderWidgets.some(widget => widget.id === "pip_left"), true)
assert.deepEqual(vm.state.draft, original)
assert.equal(vm.dirty, false)
}
// The actual Vue preview uses the same device-specific silhouettes as onroad.
{
const render = compile(LayoutWidgetPreview.template, { decodeEntities: value => value.replaceAll("&amp;", "&") })
const nodes = vnode => [vnode, ...(Array.isArray(vnode.children) ? vnode.children.flatMap(nodes) : [])]
for (const [profile, width, height, shape] of [["large", 600, 600, "circle"], ["compact", 476, 240, "rect"]]) {
const tree = render({ widget: widget("Adj Spot Camera", "pip_camera", width, height, 0, 0),
palette: {}, sprite: null, native: false, profile }, [])
const camera = nodes(tree).find(node => node.type === shape)
assert.ok(camera, `${profile} renders a ${shape}`)
assert.equal(nodes(tree).some(node => node.type === (shape === "rect" ? "circle" : "rect")), false)
if (shape === "rect") assert.deepEqual([camera.props.width, camera.props.height, camera.props.rx], [476, 240, 52.8])
}
}
@@ -3,7 +3,7 @@ import { validDocument } from "../web/js/onroad-layout.js"
const metadata = { profiles: Object.fromEntries(["large", "compact"].map(name => [name, {
bounds: {x:0,y:0,width:100,height:100}, widgets:{}, reservedZones:[]
}])) }
const document = { version:16, palette:{cardFill:"#000000A6",cardBorder:"#C4CDD0B4",text:"#FFFFFFFF"},
const document = { version:17, palette:{cardFill:"#000000A6",cardBorder:"#C4CDD0B4",text:"#FFFFFFFF"},
layouts:{large:{},compact:{}},widgetColors:{large:{},compact:{}},roadColors:{large:{},compact:{}} }
assert.equal(validDocument(document, metadata), true)
for (const flag of [true, false]) assert.equal(validDocument({...document,speedSources:flag},metadata),true)
@@ -1917,101 +1917,3 @@ 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; }
}
@@ -0,0 +1,97 @@
.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; }
}
@@ -13,6 +13,7 @@
<link rel="manifest" href="./manifest.webmanifest" crossorigin="use-credentials">
<link rel="stylesheet" href="./vendor/bootstrap-icons/bootstrap-icons.min.css">
<link rel="stylesheet" href="./css/galaxy.css">
<link rel="stylesheet" href="./css/log-help.css">
<link rel="stylesheet" href="./css/setup.css">
<link rel="stylesheet" href="./css/settings.css">
<link rel="stylesheet" href="./css/navigation.css">
@@ -85,6 +85,7 @@ export const ConnectionLogs = {
<div v-else class="gx-actions">
<button type="button" class="gx-btn gx-btn--tonal" :disabled="captureBusy" @click="downloadConnectionLogs">{{ captureBusy ? 'Preparing ZIP…' : 'Download connection ZIP' }}</button>
</div>
<p class="gx-note">Before collecting fresh logs, park and update your comma to the latest testing build from StarPilotHQ/StarPilot. Try the connection again.</p>
<GxNotice v-if="captureError" tone="danger">{{ captureError }}</GxNotice>
</div>`,
}
@@ -425,6 +425,7 @@ export const LogHelp = {
<i class="bi bi-info-circle" aria-hidden="true"></i>
<div class="gx-stack">
<strong>What we need</strong>
<p>Before collecting fresh logs, park and update your comma to the latest testing build from StarPilotHQ/StarPilot. Try the connection again.</p>
<p>{{ currentTopic.whatWeNeed }}</p>
<p v-if="currentTopic.extraHint" class="gx-note">{{ currentTopic.extraHint }}</p>
</div>
@@ -475,6 +476,7 @@ export const LogHelp = {
</template>
</div>
<p v-if="!bluetooth" class="gx-note">Comma offline? Save the ZIP on your phone and send it when you have internet. Include the branch and version you captured.</p>
<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>
@@ -145,7 +145,7 @@ export const PROJECTION_DISPLAY_SWITCHES = ["blindSpotBorder", "signalBorder", "
export function validDocument(document, metadata) {
if (!object(document)) return false
const profiles = metadata?.projection === true ? ["large"] : PROFILES
if (!keysEqual(document, ["version", "palette", "layouts", "widgetColors", "roadColors", ...(Object.hasOwn(document, "widgetOrder") ? ["widgetOrder"] : []), ...(Object.hasOwn(document, "speedSources") ? ["speedSources"] : []), ...(Object.hasOwn(document, "speedSourcesCard") ? ["speedSourcesCard"] : []), ...(Object.hasOwn(document, "speedAlign") ? ["speedAlign"] : []), ...(Object.hasOwn(document, "clock24Hour") ? ["clock24Hour"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "reduceMotion") ? ["reduceMotion"] : []), ...(Object.hasOwn(document, "showMaxSpeed") ? ["showMaxSpeed"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "speedDisplayOffset") ? ["speedDisplayOffset"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "display") ? ["display"] : []), ...(metadata?.projection === true && Object.hasOwn(document, "largeUiGammaTrial") ? ["largeUiGammaTrial"] : []), ...(metadata?.projection === true ? PROJECTION_DISPLAY_SWITCHES.filter(key => Object.hasOwn(document, key)) : []), ...(metadata?.projection === true && Object.hasOwn(document, "leadInfo") ? ["leadInfo"] : [])]) || (metadata?.projection === true ? document.version !== 8 : document.version !== 16) ||
if (!keysEqual(document, ["version", "palette", "layouts", "widgetColors", "roadColors", ...(Object.hasOwn(document, "widgetOrder") ? ["widgetOrder"] : []), ...(Object.hasOwn(document, "speedSources") ? ["speedSources"] : []), ...(Object.hasOwn(document, "speedSourcesCard") ? ["speedSourcesCard"] : []), ...(Object.hasOwn(document, "speedAlign") ? ["speedAlign"] : []), ...(Object.hasOwn(document, "clock24Hour") ? ["clock24Hour"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "reduceMotion") ? ["reduceMotion"] : []), ...(Object.hasOwn(document, "showMaxSpeed") ? ["showMaxSpeed"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "speedDisplayOffset") ? ["speedDisplayOffset"] : []), ...(metadata?.projection !== true && Object.hasOwn(document, "display") ? ["display"] : []), ...(metadata?.projection === true && Object.hasOwn(document, "largeUiGammaTrial") ? ["largeUiGammaTrial"] : []), ...(metadata?.projection === true ? PROJECTION_DISPLAY_SWITCHES.filter(key => Object.hasOwn(document, key)) : []), ...(metadata?.projection === true && Object.hasOwn(document, "leadInfo") ? ["leadInfo"] : [])]) || (metadata?.projection === true ? document.version !== 8 : document.version !== 17) ||
(Object.hasOwn(document, "speedSources") && typeof document.speedSources !== "boolean") ||
(Object.hasOwn(document, "speedSourcesCard") && typeof document.speedSourcesCard !== "boolean") ||
(Object.hasOwn(document, "speedAlign") && !SPEED_ALIGNMENTS.includes(document.speedAlign)) ||
@@ -207,7 +207,7 @@ export const ONROAD_LAYOUT_TEMPLATE = `
<div ref="widgetsHelp" class="gx-layout__subhead gx-layout__help-anchor"><h3>Widgets</h3><span>{{ activeWidgets.length }} active</span>
<button class="gx-icon-btn gx-layout__info" type="button" :aria-expanded="state.widgetsHelpOpen" aria-controls="gx-layout-widgets-help" aria-label="How the widget list works" title="How the widget list works" @click="toggleFloating('widgetsHelpOpen', 'widgetsHelp')"><i class="bi bi-info-circle" aria-hidden="true"></i></button>
<GxCollapse><div v-show="state.widgetsHelpOpen" id="gx-layout-widgets-help" class="gx-layout__popover" @click="closeFloating('widgetsHelpOpen')" @keydown.esc="closeFloating('widgetsHelpOpen')">
<p>Tap a widget to edit it.</p><p>Drag ⠿ to reorder. The top row is in front, and alerts stay above all widgets. Each side camera can be locked to the front; unlock it to move widgets above.</p><p>The eyes follow the chosen scene. Choose General edit to arrange every enabled widget. Hiding a widget with the eye affects only this scene's preview.</p>
<p>Tap a widget to edit it.</p><p>Drag ⠿ to reorder. The top row is in front, and alerts stay above all widgets. Each Adj Spot Camera can be locked to the front; unlock it to move widgets above.</p><p>The eyes follow the chosen scene. Choose General edit to arrange every enabled widget. Hiding a widget with the eye affects only this scene's preview.</p>
</div></GxCollapse>
</div>
<div v-if="!projection && leadRows.length" class="gx-actions">
@@ -443,7 +443,7 @@ export const ONROAD_LAYOUT_TEMPLATE = `
<h5 class="gx-layout__display-group">Camera</h5>
<GalaxySettingRow feedback="draft" :row="switchRow('Show Camera on Blind-Spot Warning', state.draft.blindSpotCamera === true)" :index="0"
:disabled="!editable || !!state.drag || !!state.layerDrag || !projectionHasPipWidget" :save-value="(index, value) => setProjectionDisplay('blindSpotCamera', value)" />
<p v-if="!projectionHasPipWidget" class="gx-note">Add a left or right blind-spot camera widget to enable this option.</p>
<p v-if="!projectionHasPipWidget" class="gx-note">Add a left or right Adj Spot Camera widget to enable this option.</p>
<GalaxySettingRow feedback="draft" :row="switchRow('Large UI Gamma Effect', state.draft.largeUiGammaTrial)" :index="1"
:disabled="!editable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setLargeUiGammaTrial(value)" />
<p class="gx-note">The large UI road-camera color effect on StarPort (not shown in the preview).</p>
@@ -471,7 +471,7 @@ export const ONROAD_LAYOUT_TEMPLATE = `
</GxDialog>
<GxDialog v-if="state.pipUnlockConfirm" labelledby="gx-layout-pip-unlock-title" describedby="gx-layout-pip-unlock-body" alert @close="cancelCameraUnlock">
<div><h3 id="gx-layout-pip-unlock-title">Unlock {{ profile?.widgets[state.pipUnlockConfirm]?.label }}?</h3>
<p id="gx-layout-pip-unlock-body">Warning: moving other widgets on top of this side camera may block your view of the blind-spot camera. Are you sure?</p></div>
<p id="gx-layout-pip-unlock-body">Warning: moving other widgets on top of this Adj Spot Camera may block your view of the Adj Spot Camera. Are you sure?</p></div>
<div class="gx-settings__controls gx-actions">
<button type="button" class="gx-btn gx-btn--tonal" @click="cancelCameraUnlock">Cancel</button>
<button type="button" class="gx-btn gx-btn--danger" @click="confirmCameraUnlock">Unlock</button>
@@ -21,7 +21,7 @@ export { layoutDocument, previewDocument, withDisplay, orderedWidgetIds, widgetP
const previewVisibilityKey = projection => "gx-layout-preview-visibility-v2:" + (projection ? "starport" : "comma")
const oldProjectionVisibilityKey = "gx-layout-preview-visibility-v2:android-auto"
function loadPreviewVisibility(projection) {
const hidden = { large: {}, compact: {} }
const hidden = { large: {}, compact: projection ? {} : { pip_left: true } }
try {
const currentKey = previewVisibilityKey(projection)
const raw = localStorage.getItem(currentKey) ?? (projection ? localStorage.getItem(oldProjectionVisibilityKey) : null)
@@ -377,7 +377,8 @@ export const LayoutWidgetPreview = {
<path :d="'M ' + widget.width / 2 + ' ' + widget.height * .68 + ' Q ' + widget.width * .65 + ' ' + widget.height * .68 + ' ' + widget.width * .8 + ' ' + widget.height * .74" :stroke-width="widget.height * .18" opacity=".9" />
</g>
<g v-else-if="widget.kind === 'pip_camera'">
<circle :cx="widget.width / 2" :cy="widget.height / 2" :r="widget.width / 2 - 3" fill="#152c39" fill-opacity=".35" stroke="#5ee5ee" stroke-width="3" />
<rect v-if="widget.width !== widget.height" x="0" y="0" :width="widget.width" :height="widget.height" :rx="Math.min(widget.width, widget.height) * .22" fill="#152c39" fill-opacity=".35" stroke="#5ee5ee" stroke-width="3" />
<circle v-else :cx="widget.width / 2" :cy="widget.height / 2" :r="widget.width / 2 - 3" fill="#152c39" fill-opacity=".35" stroke="#5ee5ee" stroke-width="3" />
<text :x="widget.width / 2" :y="widget.height / 2" text-anchor="middle" :font-size="widget.height / 10">{{ widget.label }}</text>
</g>
<g v-else-if="['nav_home', 'nav_work', 'bookmark'].includes(widget.kind)" :opacity="(widget.opacity ?? 100) / 100">
+6 -6
View File
@@ -175,22 +175,22 @@ export const PipPage = {
},
},
template: `
<section class="gx-settings gx-pip" aria-label="Blind Spot Camera & Preview saved settings" :inert="busy" :aria-busy="busy || undefined">
<header class="gx-settings__header gx-page-header"><div><h2>Blind Spot Camera & Preview</h2>
<section class="gx-settings gx-pip" aria-label="Adj Spot Camera & Preview saved settings" :inert="busy" :aria-busy="busy || undefined">
<header class="gx-settings__header gx-page-header"><div><h2>Adj Spot Camera & Preview</h2>
<p>Shows a close-up of the cabin window as you drive. Whether it appears on your turn signal or when a car is in your blind spot depends on your settings. Choose which window each side covers and how much to zoom in.</p></div>
<div class="gx-actions"><WikiHelp />
<button type="button" class="gx-btn gx-btn--tonal" :disabled="bluetooth || state.cameraWarming" @click="liveCamera.refresh()"><i class="bi bi-camera" aria-hidden="true"></i> Take new snapshot</button><button type="button" class="gx-icon-btn" aria-label="Position side cameras" title="Position side cameras" @click="go('/theme_maker')"><i class="bi bi-layout-wtf" aria-hidden="true"></i></button></div></header>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="bluetooth || state.cameraWarming" @click="liveCamera.refresh()"><i class="bi bi-camera" aria-hidden="true"></i> Take new snapshot</button><button type="button" class="gx-icon-btn" aria-label="Position Adj Spot Cameras" title="Position Adj Spot Cameras" @click="go('/theme_maker')"><i class="bi bi-layout-wtf" aria-hidden="true"></i></button></div></header>
<GxState v-if="mode !== 'local'">Local saved settings are unavailable in preview.</GxState>
<template v-else>
<GxNotice v-if="state.data && !state.data.parked" tone="warn">Turn the vehicle off to change these settings.</GxNotice>
<GxState v-if="state.status === 'loading'" loading>Reading blind-spot camera preferences and crop positions…</GxState>
<GxNotice tone="danger" v-else-if="state.status === 'unavailable' && !state.error">The device could not read blind-spot camera preferences or crop positions. Reconnecting automatically…</GxNotice>
<GxState v-if="state.status === 'loading'" loading>Reading Adj Spot Camera preferences and crop positions…</GxState>
<GxNotice tone="danger" v-else-if="state.status === 'unavailable' && !state.error">The device could not read Adj Spot Camera preferences or crop positions. Reconnecting automatically…</GxNotice>
<GxNotice tone="danger" v-if="state.error">{{ state.error }}</GxNotice>
<BluetoothNotice v-if="bluetooth" feature="Cabin camera preview">Saved settings remain available.</BluetoothNotice>
<GxNotice tone="danger" v-else-if="state.cameraError">{{ state.cameraError }}</GxNotice>
<div v-if="state.data" class="gx-settings__body">
<section class="gx-card gx-vasm__editor" aria-label="Blind Spot Camera crop editor">
<section class="gx-card gx-vasm__editor" aria-label="Adj Spot Camera crop editor">
<div class="gx-section__header"><i class="bi bi-crop" aria-hidden="true"></i><span class="gx-section__title">Camera Crop</span></div>
<p class="gx-note">Drag a circle onto the cabin window you want to watch. Both crops share one size.</p>
<p v-if="!bluetooth" class="gx-note gx-camera-status" role="status">{{ state.cameraWarming ? "Warming up the camera · about 10 seconds…" : state.imageName ? "Snapshot ready" : "Take a cabin snapshot while parked." }}</p>
@@ -34,7 +34,7 @@ export const SETTINGS_SECTIONS = Object.freeze([
])
// Crop numeric rows and the inline editor row are controlled from the dedicated
// Blind Spot Camera page; they stay writable through the settings API for the
// Adj Spot Camera page; they stay writable through the settings API for the
// widget/VASM editor but must not surface in the generic toggles list.
export const isPipCropRow = (row) => ["Visual camera crop editor", "Camera crop size", "Restore default camera crop"].includes(row.label) ||
/^Vehicle (left|right) crop/.test(row.label || "")
@@ -51,7 +51,7 @@ const SECTION_LINKS = {
{ label: "Display", page: "display", value: "Adjust screen brightness and display timing" },
{ label: "Driving Screen Widgets, Colors & Layout", page: "ui_layout" },
{ label: "Quick Select", page: "favorites" },
{ label: "Blind Spot Camera & Preview", page: "pip" },
{ label: "Adj Spot Camera & Preview", page: "pip" },
],
}
+8 -4
View File
@@ -317,7 +317,7 @@ class Compositor:
from openpilot.starpilot.ui.pip_render import PiPRenderer
self.pip_saved = read_pip(ui_state.params)
self.pip_stream = ReplayCameraStream(ui_state)
self.pip = PiPRenderer('bubble', self.pip_stream, frame_availability=PassiveAvailability())
self.pip = PiPRenderer('curved' if self.profile == 'compact' else 'bubble', self.pip_stream, frame_availability=PassiveAvailability())
self.resources.callback(lambda: self.pip.close())
self._new_view()
self.resources.callback(lambda: self.view.close())
@@ -443,15 +443,19 @@ class Compositor:
signals = Signals(car is not None, bool(car.leftBlinker) if car else False, bool(car.rightBlinker) if car else False,
bool(car.leftBlindspot) if car else False, bool(car.rightBlindspot) if car else False)
positions = {}
for side, key in zip(('left', 'right'), CAMERA_WIDGETS, strict=True):
for side, key in zip(('left', 'right'), CAMERA_WIDGETS if self.profile == 'large' else ('pip_left', 'pip_left'), strict=True):
position = placement(state.customization, self.profile, key)
if position['enabled']:
width, height = widget_size(state.customization, self.profile, key)
positions[side] = Rect(position['x'], position['y'], width, height)
if submit is not None and self.profile == 'compact':
submit_widget = submit
def submit(_key, draw):
submit_widget('pip_left', draw)
status = self.pip.render(rect, saved.mask, signals, enabled=self.cabin, on_blinker=saved.on_blinker,
on_bsm=saved.on_bsm, invert=saved.invert, now=now / 1e9, placements=positions, submit=submit)
if not self.cabin or status not in ('rendered', 'inactive'):
self.fonts.draw('RECORDED SIDE CAMERA UNAVAILABLE', FontRole.MEDIUM, 18 if self.profile == 'compact' else 25,
self.fonts.draw('RECORDED ADJ SPOT CAMERA UNAVAILABLE', FontRole.MEDIUM, 18 if self.profile == 'compact' else 25,
18 if self.profile == 'compact' else rect.x + 30,
180 if self.profile == 'compact' else rect.y + rect.height - 62, self.rl.Color(245, 200, 155, 255))
@@ -517,7 +521,7 @@ class Compositor:
self.pip_stream._client = pip_client
self.pip_stream.release_retired()
self.pip_stream.reset()
self.pip = PiPRenderer('bubble', self.pip_stream, frame_availability=PassiveAvailability())
self.pip = PiPRenderer('curved' if self.profile == 'compact' else 'bubble', self.pip_stream, frame_availability=PassiveAvailability())
self.view.close()
self.adapter = RuntimeSnapshotAdapter(self.ui)
self._new_view()
@@ -574,12 +574,14 @@ def test_published_readiness_survives_buffering_but_rejects_seeks_and_old_epochs
assert sleeps == [.01] * len(times) # Native playback keeps its original idle wait.
@pytest.mark.parametrize('profile', ('compact', 'large'))
@pytest.mark.parametrize('matching_frame', (False, True))
@pytest.mark.parametrize('streams,expected_streams', (({0, 2}, [0, 2]), ([2, 0], [2, 0])))
def test_epoch_reset_preserves_native_camera_stream_and_eligible_paused_frame(monkeypatch, matching_frame, streams, expected_streams):
def test_epoch_reset_preserves_native_camera_stream_and_eligible_paused_frame(monkeypatch, matching_frame, streams, expected_streams, profile):
monkeypatch.setattr('openpilot.starpilot.ui.runtime_snapshot.RuntimeSnapshotAdapter', Mock())
monkeypatch.setattr('openpilot.starpilot.ui.pip_render.PiPRenderer', Mock())
core: Any = object.__new__(Compositor)
core.profile = profile
client = Mock(frame_id=5 if matching_frame else 4, timestamp_sof=9_000_000_000, timestamp_eof=9_010_000_000)
client.is_connected.return_value = True
frame = SimpleNamespace(frame_id=5)
@@ -607,6 +609,8 @@ def test_epoch_reset_preserves_native_camera_stream_and_eligible_paused_frame(mo
_offroad_transition_callbacks=callbacks)
core.render_receipts = {'modelV2': 1}
core.reset_epoch(3)
from openpilot.starpilot.ui.pip_render import PiPRenderer
assert PiPRenderer.call_args.args[0] == ('curved' if profile == 'compact' else 'bubble')
for callback in callbacks:
callback()
assert core.render_receipts == {}
@@ -18,7 +18,7 @@ from openpilot.starpilot.ui.raylib import rl
from openpilot.starpilot.ui.layout_preview_transport import SCENES, validate_preview_document
from openpilot.starpilot.ui.developer_preview import OnroadVisualPreview
from openpilot.starpilot.ui.onroad_customization import (CAMERA_WIDGETS, PROFILES, ROAD_BASE_WIDTH, RUNTIME_PREVIEW_WIDGETS, fit_to_road, placement,
from openpilot.starpilot.ui.onroad_customization import (camera_widgets, PROFILES, ROAD_BASE_WIDTH, RUNTIME_PREVIEW_WIDGETS, fit_to_road, placement,
validate_document, widget_size)
from openpilot.starpilot.ui.onroad_widget_style import draw_widget_frame
from openpilot.starpilot.curve_speed.status import CurveObservation
@@ -276,17 +276,21 @@ class _Canvas:
if submit is None:
self._render_side_cameras(state)
return
for key in CAMERA_WIDGETS:
for key in camera_widgets(self.profile):
submit(key, lambda key=key: self._render_side_cameras(state, only=key))
def _render_side_cameras(self, state: OnroadState, only=None) -> None:
for key in CAMERA_WIDGETS:
for key in camera_widgets(self.profile):
if only is not None and key != only:
continue
position = placement(state.customization, self.profile, key)
if not position["enabled"]:
continue
widget = PROFILES[str(self.profile)]["widgets"][key]
if self.profile == Profile.COMPACT:
target = rl.Rectangle(position["x"], position["y"], widget["width"], widget["height"])
rl.draw_rectangle_rounded(target, 0.44, 16, rl.Color(21, 44, 57, 90))
continue
radius = widget["width"] / 2
shift = state.viewport_width - 1860 if self.profile == Profile.LARGE and key == "pip_right" and self.viewport is None else 0
center = rl.Vector2(position["x"] + shift + radius, position["y"] + radius)
+44 -12
View File
@@ -152,13 +152,19 @@ for _index, (_key, _label) in enumerate(zip(RAIL_WIDGETS, ("Model confidence", "
# Keep layouts saved before camera widgets valid when the registry grows.
CAMERALESS_WIDGETS = {profile: set(data["widgets"]) for profile, data in PROFILES.items()}
CAMERA_WIDGETS = ("pip_left", "pip_right")
for _profile, (_size, _margin) in {"large": (600, 24), "compact": (80, 16)}.items():
def camera_widgets(profile):
return CAMERA_WIDGETS[:1] if str(profile) == "compact" else CAMERA_WIDGETS
for _profile, (_width, _height, _margin) in {"large": (600, 600, 24), "compact": (476, 240, 0)}.items():
_bounds = PROFILES[_profile]["bounds"]
for _side, _key in zip(("left", "right"), CAMERA_WIDGETS, strict=True):
_x = _bounds["x"] + (_margin if _side == "left" else _bounds["width"] - _margin - _size)
_y = _bounds["y"] + _bounds["height"] - _margin - _size
for _side, _key in zip(("left", "right"), camera_widgets(_profile), strict=False):
_x = _bounds["x"] + (_margin if _side == "left" else _bounds["width"] - _margin - _width)
_y = _bounds["y"] + _bounds["height"] - _margin - _height
PROFILES[_profile]["widgets"][_key] = {
**_widget(f"PiP {_side} side camera", "pip_camera", _size, _size, _x, _y), "layer": "underlay"}
**_widget((f"Adj Spot Camera {_side.title()}" if _profile == "large" else "Adj Spot Camera"), "pip_camera", _width, _height, _x, _y), "layer": "underlay"}
MODE_WIDGET = "driving_mode_descriptions"
for _profile, _geometry in {"large": (580, 68, 640, 344), "compact": (168, 44, 154, 0)}.items():
@@ -372,7 +378,7 @@ DEFAULT_WIDGET_ORDER = {
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, UNIDEN_WIDGET, "rear_fog", "pip_left", "pip_right"),
"compact": ("speed_limit", "max_speed", "steering_wheel", "torque_bar",
"driver_monitor", *RAIL_WIDGETS, MODE_WIDGET, CLOCK_WIDGET, WEATHER_WIDGET,
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, "rear_fog", "pip_left", "pip_right"),
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, "rear_fog", "pip_left"),
}
@@ -427,7 +433,7 @@ def customization_metadata():
def default_document():
return {"version": 16, "clock24Hour": False, "reduceMotion": False, "palette": dict(PALETTE), "roadColors": {profile: {} for profile in PROFILES},
return {"version": 17, "clock24Hour": False, "reduceMotion": False, "palette": dict(PALETTE), "roadColors": {profile: {} for profile in PROFILES},
"widgetColors": {profile: {} for profile in PROFILES}, "layouts": {
profile: {key: {**widget["default"], **({"size": WIDGET_SIZES[key][profile][1]} if key in WIDGET_SIZES else {})}
for key, widget in data["widgets"].items()}
@@ -509,7 +515,7 @@ def migrate_confirmation_layout(layout, profile, widgets, bounds, *, extra_heigh
def validate_document(value):
if type(value) is not dict or type(value.get("version")) is not int or value["version"] not in range(1, 17):
if type(value) is not dict or type(value.get("version")) is not int or value["version"] not in range(1, 18):
raise ValueError("Invalid customization version")
if value["version"] < 16:
# Version 16 folded the separate speed limit actions widget into the speed limit sign.
@@ -521,6 +527,23 @@ def validate_document(value):
if type(value.get("widgetOrder")) is dict:
value["widgetOrder"] = {profile: [key for key in order if key != "speed_limit_actions"] if type(order) is list else order
for profile, order in value["widgetOrder"].items()}
# C4 has one shared camera panel; accept the old pair without changing C3.
compact = value.get("layouts", {}).get("compact") if type(value.get("layouts")) is dict else None
if type(compact) is dict and "pip_right" in compact:
value = copy.deepcopy(value)
compact = value["layouts"]["compact"]
right = compact.pop("pip_right")
left = compact.get("pip_left")
if any(type(item) is not dict or set(item) != {"x", "y", "enabled"} or type(item["enabled"]) is not bool or
any(type(item[axis]) not in (int, float) or not math.isfinite(item[axis]) for axis in ("x", "y")) for item in (left, right)):
raise ValueError("Invalid legacy camera placement")
left["enabled"] = left["enabled"] or right["enabled"]
colors = value.get("widgetColors", {}).get("compact") if type(value.get("widgetColors")) is dict else None
if type(colors) is dict and colors.get("pip_right") == {}:
colors.pop("pip_right")
order = value.get("widgetOrder", {}).get("compact") if type(value.get("widgetOrder")) is dict else None
if type(order) is list:
value["widgetOrder"]["compact"] = [key for key in order if key != "pip_right"]
fields = {"version", "palette", "layouts"} | ({"widgetColors"} if value["version"] >= 2 else set())
if value["version"] >= 3:
fields.add("roadColors")
@@ -587,13 +610,14 @@ def validate_document(value):
type(legacy["enabled"]) is not bool or
any(type(legacy[axis]) not in (int, float) or not math.isfinite(legacy[axis]) for axis in ("x", "y"))):
raise ValueError("Invalid legacy camera placement")
for side, key in enumerate(CAMERA_WIDGETS):
for side, key in enumerate(camera_widgets(profile)):
widget = PROFILES[profile]["widgets"][key]
position = dict(widget["default"])
if legacy is not None:
bounds = widget_bounds(profile, key)
shift = side * widget["width"] if profile == "large" else 0
position.update(enabled=legacy["enabled"],
x=max(bounds["x"], min(legacy["x"], bounds["x"] + bounds["width"] - 2 * widget["width"])) + side * widget["width"],
x=max(bounds["x"], min(legacy["x"], bounds["x"] + bounds["width"] - 2 * widget["width"])) + shift,
y=max(bounds["y"], min(legacy["y"], bounds["y"] + bounds["height"] - widget["height"])))
layouts[profile][key] = position
layouts = copy.deepcopy(layouts)
@@ -670,6 +694,14 @@ def validate_document(value):
bounds = data['bounds']
if legacy_signal:
_fit_legacy_signal(placement, bounds)
if value["version"] < 17 and profile == "compact" and key in CAMERA_WIDGETS and type(placement) is dict:
# Move the legacy 80px widget into the shared C4 panel.
if any(type(placement.get(axis)) not in (int, float) or not math.isfinite(placement[axis]) for axis in ("x", "y")):
raise ValueError("Invalid widget position")
if key in value["layouts"][profile] and not (0 <= placement["x"] <= bounds["width"] - 80 and
0 <= placement["y"] <= bounds["height"] - 80):
raise ValueError("Invalid legacy camera position")
placement = layout[key] = {**placement, "x": 0, "y": 0}
if (key == JETLINK_WIDGET and type(placement) is dict and type(placement.get('y')) in (int, float) and
math.isfinite(placement['y']) and
bounds['y'] + bounds['height'] - JETLINK_SIZE[1] < placement['y'] <= bounds['y'] + bounds['height'] - 84):
@@ -712,9 +744,9 @@ def validate_document(value):
size = WHEEL_SIZES[profile][1]
if scalable:
minimum, _, maximum = WIDGET_SIZES[key][profile]
if type(placement["size"]) is not int or not minimum <= cast(int, placement["size"]) <= maximum:
if type(placement["size"]) is not int or not minimum <= placement["size"] <= maximum:
raise ValueError("Invalid widget size")
size = cast(int, placement["size"])
size = placement["size"]
# Only a gauge the saved layout actually placed moves; one filled in from defaults is already in the new box.
saved_layout = value.get("layouts", {}).get(profile) if type(value.get("layouts")) is dict else None
old_gauge = key == CEM_GAUGE_WIDGET and value["version"] < 7 and type(saved_layout) is dict and key in saved_layout
+2 -2
View File
@@ -24,7 +24,7 @@ RESET = "pip:reset"
EDITOR = "pip:mask:editor"
FORMAT_PREFIX = "pip:format:"
MASK_PREFIX = "pip:mask:"
LABELS = {ENABLED: "Use blind spot camera", BLINKER: "Show on turn signal",
LABELS = {ENABLED: "Use Adj Spot Camera", BLINKER: "Show on turn signal",
BSM: "Show on blind spot warning", INVERT: "Mirror camera crop"}
@@ -230,7 +230,7 @@ class PiPOwner:
reason="" if live else "Open the live crop preview while parked to check the camera."))
defaults = dict.fromkeys(BOOL_KEYS, 'Off')
rows = [replace(row, default_value=defaults[row.key]) if row.key in defaults else row for row in rows]
return FeatureSettingsState(page="pip", title="Blind Spot Camera & Preview",
return FeatureSettingsState(page="pip", title="Adj Spot Camera & Preview",
subtitle="Choose when to show the camera and adjust its crop from the live preview. " +
"Resolution follows the camera automatically.",
rows=tuple(rows), parked=parked)
+1 -1
View File
@@ -122,7 +122,7 @@ def reference_feature_scene(scene: str) -> tuple[Destination, str, FeatureSettin
elif scene == "settings_pip":
rows = (boolean("pip:enabled", "On"), boolean("pip:blinker", "Off"), number, reset,
FeatureRow("", "Camera availability", "No fresh cabin frame", reason="Check the live crop preview while parked"))
destination, field, page, title = Destination.APPEARANCE, "appearance", "pip", "Blind Spot Camera & Preview"
destination, field, page, title = Destination.APPEARANCE, "appearance", "pip", "Adj Spot Camera & Preview"
else:
rows = (boolean("enabled_off", "Off"), boolean("enabled_on", "On"),
boolean("disabled_off", "Off", available=False), boolean("disabled_on", "On", available=False),
+6 -4
View File
@@ -170,7 +170,7 @@ class StarShellSession(TeslaSpeedActions):
self.network_layer = network_layer
self.settings_layer = settings_layer
self.fonts = BitmapFonts(profile, Path(font_dir) if font_dir else default_font_directory())
self.pip_renderer = PiPRenderer("bubble")
self.pip_renderer = PiPRenderer("curved" if profile == Profile.COMPACT else "bubble")
self.pip_warning = PiPWarningSource()
self._pip_saved = None
self._vasm_saved = None
@@ -905,7 +905,7 @@ class StarShellSession(TeslaSpeedActions):
self.pip_renderer.deactivate()
return
camera_positions = {}
for side, key in zip(("left", "right"), CAMERA_WIDGETS, strict=True):
for side, key in zip(("left", "right"), CAMERA_WIDGETS if self.profile == Profile.LARGE else ("pip_left", "pip_left"), strict=True):
position = placement(state.customization, self.profile, key)
if position["enabled"]:
width, height = widget_size(state.customization, self.profile, key)
@@ -913,9 +913,11 @@ class StarShellSession(TeslaSpeedActions):
camera_positions[side] = Rect(position["x"] + shift, position["y"], width, height)
status = self.pip_renderer.render(rect, saved.mask, signals, enabled=True,
on_blinker=saved.on_blinker, on_bsm=saved.on_bsm, invert=saved.invert,
placements=camera_positions, **({"submit": submit} if submit is not None else {}))
placements=camera_positions,
**({"submit": (lambda _key, draw: submit("pip_left", draw)) if self.profile == Profile.COMPACT else submit}
if submit is not None else {}))
if status not in ("rendered", "inactive") and state.alert.size == AlertSize.NONE:
self.fonts.draw("SIDE CAMERA UNAVAILABLE", FontRole.MEDIUM,
self.fonts.draw("ADJ SPOT CAMERA UNAVAILABLE", FontRole.MEDIUM,
18 if self.profile == Profile.COMPACT else 25,
18 if self.profile == Profile.COMPACT else rect.x + 30,
180 if self.profile == Profile.COMPACT else rect.y + rect.height - 62,
@@ -287,3 +287,9 @@ def test_large_shell_forwards_the_saved_camera_and_temporary_reverse(monkeypatch
session.view.camera_layer(rl.Rectangle(0, 0, 2160, 1080), state)
kwargs = camera.render_camera_model_layer.call_args.kwargs
assert kwargs['camera_view'] is choice and kwargs['reverse_driver'] is reverse
@pytest.mark.parametrize('profile,shape', [(runtime_app.Profile.COMPACT, 'curved'), (runtime_app.Profile.LARGE, 'bubble')])
def test_side_camera_shape_follows_device_profile(lifecycle, monkeypatch, request, profile, shape):
make_session(monkeypatch, request, profile, Mock())
runtime_app.PiPRenderer.assert_called_once_with(shape)
@@ -751,7 +751,7 @@ def test_v5_geometry_migrates_the_card():
doc['layouts']['large']['cruise_limits'].update(x=1550, y=638)
doc['layouts']['large']['speed_limit_actions'] = {'x': 1550, 'y': 954, 'enabled': True}
migrated = validate_document(doc)
assert migrated['version'] == 16
assert migrated['version'] == 17
assert migrated['layouts']['large']['cruise_limits'] == default_document()['layouts']['large']['cruise_limits']
assert 'speed_limit_actions' not in migrated['layouts']['large']
assert migrated['speedSources'] is True
@@ -319,15 +319,22 @@ if __name__ == "__main__":
unittest.main()
def test_native_preview_draws_independent_camera_circles_without_camera_input():
def test_native_preview_matches_camera_geometry_without_camera_input():
for profile, width in ((Profile.COMPACT, 536), (Profile.LARGE, 1860), (Profile.LARGE, 2160)):
canvas = _Canvas.__new__(_Canvas)
canvas.profile, canvas.viewport = profile, None
document = default_document()
state = replace(sample_state('engaged', document), viewport_width=width)
with patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_circle_v') as circle, \
patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_ring') as ring:
patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_ring') as ring, \
patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_rectangle_rounded') as panel:
canvas._render_side_cameras(state)
if profile == Profile.COMPACT:
assert panel.call_count == 1
assert circle.call_count == ring.call_count == 0
target = panel.call_args.args[0]
assert (target.x, target.y, target.width, target.height) == (0, 0, 476, 240)
continue
assert circle.call_count == ring.call_count == 2
right_center, radius = circle.call_args.args[:2]
assert right_center.x + radius == (width - 54 if profile == Profile.LARGE else 460)
@@ -13,7 +13,7 @@ import pytest
from openpilot.starpilot.ui.appearance_preferences import OnroadAppearance
from openpilot.starpilot.ui.onroad_customization import (
CLOCK_WIDGET, DEFAULT_WIDGET_ORDER, MAX_BYTES, STOPPED_TIMER_WIDGET, customization_metadata, default_document, offset, read_customization,
validate_document, decode_document, widget_palette, rgba, widget_size)
validate_document, camera_widgets, decode_document, widget_palette, rgba, widget_size)
from openpilot.starpilot.ui.onroad_compact_widgets import CompactHudRenderer
from openpilot.starpilot.ui.onroad_large_widgets import CurrentSpeedHud, UnifiedSpeedWidget, SteeringWheelWidget
from openpilot.starpilot.ui.onroad_state import (
@@ -69,7 +69,7 @@ def test_v12_portrait_upgrade_preserves_preferences_and_is_idempotent():
before = copy.deepcopy(old)
updated = validate_document(old)
expected = copy.deepcopy(old)
expected['version'] = 16
expected['version'] = 17
expected['layouts']['compact']['speed_limit'].update(x=320, y=16)
assert old == before and updated == expected
assert validate_document(updated) == updated
@@ -120,7 +120,7 @@ def test_v13_notice_upgrade_preserves_preferences_and_only_moves_a_conflicting_s
before = copy.deepcopy(old)
updated = validate_document(old)
expected = copy.deepcopy(old)
expected['version'] = 16
expected['version'] = 17
expected['layouts']['compact']['speed_limit']['y'] = min(sign_y, 16)
assert old == before and updated == expected
assert validate_document(updated) == updated
@@ -206,7 +206,7 @@ def test_v7_speed_layout_migration_is_bounded_non_mutating_and_idempotent():
original = copy.deepcopy(document)
migrated = validate_document(document)
assert document == original
assert migrated['version'] == 16 and validate_document(migrated) == migrated
assert migrated['version'] == 17 and validate_document(migrated) == migrated
assert migrated['layouts']['large']['cruise_limits']['x'] == 1391
assert migrated['layouts']['large']['current_speed'] == original['layouts']['large']['current_speed']
assert migrated['layouts']['large']['cem_gauge'] == {'x': 56, 'y': 536, 'enabled': True}
@@ -235,7 +235,7 @@ def test_v8_restores_only_compact_speed_defaults_and_preserves_customizations(cu
original = copy.deepcopy(document)
migrated = validate_document(document)
assert document == original
assert migrated['version'] == 16 and validate_document(migrated) == migrated
assert migrated['version'] == 17 and validate_document(migrated) == migrated
assert migrated['layouts']['large'] == document['layouts']['large']
assert migrated['widgetColors'] == document['widgetColors']
assert migrated['widgetOrder'] == document['widgetOrder']
@@ -274,7 +274,7 @@ def test_v8_layout_without_rails_preserves_customizations():
original = copy.deepcopy(document)
migrated = validate_document(document)
assert document == original
assert migrated['version'] == 16 and validate_document(migrated) == migrated
assert migrated['version'] == 17 and validate_document(migrated) == migrated
assert migrated['layouts']['large'] == original['layouts']['large']
assert migrated['layouts']['compact']['speed_limit'] == default_document()['layouts']['compact']['speed_limit']
assert migrated['palette'] == original['palette']
@@ -387,7 +387,7 @@ def test_v3_layout_migrates_wheel_size_without_changing_saved_placement_or_color
for profile in ("large", "compact"):
del document["layouts"][profile]["steering_wheel"]["size"]
migrated = validate_document(document)
assert migrated["version"] == 16
assert migrated["version"] == 17
assert migrated["palette"] == document["palette"]
assert migrated["layouts"]["large"]["steering_wheel"] == {"x": 1300, "y": 100, "enabled": False, "size": 192}
assert migrated["layouts"]["compact"]["steering_wheel"] == {"x": 90, "y": 130, "enabled": True, "size": 50}
@@ -425,7 +425,7 @@ def test_pre_action_saved_layout_migrates_without_losing_positions_or_palette(re
def test_duplicate_key_cannot_apply_otherwise_valid_placement():
document = default_document()
document["layouts"]["large"]["current_speed"]["x"] = 100
raw = json.dumps(document).replace('"version": 16', '"version": 11, "version": 11').encode()
raw = json.dumps(document).replace('"version": 17', '"version": 11, "version": 11').encode()
with patch("openpilot.starpilot.ui.onroad_customization.read_saved", return_value=(raw, True)):
assert read_customization(Mock()) == default_document()
@@ -440,7 +440,7 @@ def test_v9_large_sign_migration_preserves_customizations_and_clamps_bottom_edge
before = deepcopy(old)
updated = validate_document(old)
assert old == before
assert updated['version'] == 16
assert updated['version'] == 17
assert updated['layouts']['large']['cruise_limits']['y'] == default_document()['layouts']['large']['cruise_limits']['y']
assert updated['layouts']['compact'] == before['layouts']['compact']
assert validate_document(updated) == updated
@@ -680,7 +680,7 @@ def test_v1_palette_positions_and_visibility_migrate_without_mutating_source():
original = copy.deepcopy(old)
result = decode_document(json.dumps(old).encode())
assert old == original
assert result['version'] == 16
assert result['version'] == 17
assert result['palette'] == old['palette']
for profile, layout in old['layouts'].items():
for key, position in layout.items():
@@ -836,28 +836,30 @@ def test_overlapping_sign_stays_visible_and_chooser_keeps_exact_input():
@pytest.mark.parametrize('profile', ['large', 'compact'])
def test_pip_circles_are_independent_widgets_and_migrate_old_camera_pair(profile):
def test_pip_widgets_match_device_geometry_and_migrate_old_camera_pair(profile):
import copy
document = default_document()
metadata = customization_metadata()['profiles'][profile]['widgets']
assert 'vasm' not in metadata
for key in ('pip_left', 'pip_right'):
for key in camera_widgets(profile):
assert metadata[key]['kind'] == 'pip_camera'
assert metadata[key]['width'] == metadata[key]['height']
right = copy.deepcopy(document['layouts'][profile]['pip_right'])
assert metadata[key]['label'] == (f"Adj Spot Camera {key.removeprefix('pip_').title()}" if profile == 'large' else 'Adj Spot Camera')
assert (metadata[key]['width'], metadata[key]['height']) == ((600, 600) if profile == 'large' else (476, 240))
right = copy.deepcopy(document['layouts']['large']['pip_right'])
document['layouts'][profile]['pip_left']['enabled'] = False
assert validate_document(document)['layouts'][profile]['pip_right'] == right
assert validate_document(document)['layouts']['large']['pip_right'] == right
legacy = copy.deepcopy(document)
for name, layout in legacy['layouts'].items():
layout.pop('pip_left')
layout.pop('pip_right')
layout.pop('pip_right', None)
layout['vasm'] = {'x': 1200 if name == 'large' else 300, 'y': 650 if name == 'large' else 30, 'enabled': False}
migrated = validate_document(legacy)
for name, layout in migrated['layouts'].items():
assert 'vasm' not in layout
assert not layout['pip_left']['enabled'] and not layout['pip_right']['enabled']
assert layout['pip_left']['x'] <= layout['pip_right']['x']
assert all(not layout[key]['enabled'] for key in camera_widgets(name))
if name == 'large':
assert layout['pip_left']['x'] <= layout['pip_right']['x']
assert layout['current_speed' if name == 'large' else 'max_speed'] == document['layouts'][name]['current_speed' if name == 'large' else 'max_speed']
assert validate_document(migrated) == migrated
@@ -1053,3 +1055,18 @@ def test_compact_navigation_upgrade_preserves_saved_layout_and_order():
assert upgraded['layouts']['compact']['nav_card'] == default_document()['layouts']['compact']['nav_card']
assert upgraded['widgetOrder']['compact'] == older['widgetOrder']['compact'] + ['nav_card']
assert {k: v for k, v in upgraded['layouts']['compact'].items() if k != 'nav_card'} == older['layouts']['compact']
def test_c4_camera_upgrade_preserves_visibility_and_other_widgets():
document = default_document()
document["version"] = 16
document["layouts"]["compact"]["pip_left"].update(x=16, y=144, enabled=False)
document["layouts"]["compact"]["pip_right"] = {"x": 380, "y": 144, "enabled": True}
document["widgetColors"]["compact"]["pip_right"] = {}
document["widgetOrder"] = {profile: list(widgets) for profile, widgets in document["layouts"].items()}
migrated = validate_document(document)
assert migrated["layouts"]["compact"]["pip_left"] == {"x": 0, "y": 0, "enabled": True}
assert "pip_right" not in migrated["layouts"]["compact"]
assert migrated["layouts"]["large"] == document["layouts"]["large"]
assert migrated["layouts"]["compact"]["max_speed"] == document["layouts"]["compact"]["max_speed"]
assert validate_document(migrated) == migrated
@@ -45,7 +45,7 @@ class PiPSettingsTests(unittest.TestCase):
from openpilot.starpilot.ui.onroad_customization import PARAM_KEY, default_document, read_customization
document = default_document()
document["layouts"]["large"]["pip_left"]["enabled"] = False
document["layouts"]["compact"]["pip_right"]["enabled"] = False
document["layouts"]["compact"]["pip_left"]["enabled"] = False
layout = Path(self.params.get_param_path(PARAM_KEY))
layout.write_bytes(json.dumps(document).encode())
from openpilot.starpilot.system.starport.projection_layout import (ProjectionLayoutSource, decode_layout_for_viewport,
@@ -61,7 +61,7 @@ class PiPSettingsTests(unittest.TestCase):
self.assertTrue(self.owner.apply(action))
saved = read_customization(self.params)
self.assertTrue(all(saved["layouts"][profile][key]["enabled"]
for profile in ("large", "compact") for key in ("pip_left", "pip_right")))
for profile in ("large", "compact") for key in (("pip_left", "pip_right") if profile == "large" else ("pip_left",))))
projected = decode_layout_for_viewport(projection_path.read_bytes(), viewport)
self.assertTrue(projected["widgets"]["pip_left"]["enabled"] and projected["widgets"]["pip_right"]["enabled"])
# A camera removed while PiP is on stays removed; turning PiP off does not touch the layout.
@@ -111,7 +111,7 @@ class PiPSettingsTests(unittest.TestCase):
path = Path(self.params.get_param_path(MASK))
path.write_bytes(original)
page = self.owner.snapshot(include_editor=True)
self.assertEqual(page.title, 'Blind Spot Camera & Preview')
self.assertEqual(page.title, 'Adj Spot Camera & Preview')
self.assertFalse(any(row.key.startswith(FORMAT_PREFIX) for row in page.rows))
self.assertEqual(path.read_bytes(), original)
editor, source = self.owner.editor_with_source()
@@ -237,7 +237,7 @@ class PiPSettingsTests(unittest.TestCase):
session._pip_request_epoch = 0
session.input = Mock()
session._unavailable = Mock()
link = FeatureRow("", "Blind Spot Camera", "", page="pip", available=True)
link = FeatureRow("", "Adj Spot Camera", "", page="pip", available=True)
session._appearance_ui(FeatureUiAction("open", link))
self.assertEqual(session.appearance_page, "appearance")
session.appearance_page = "pip"
@@ -312,7 +312,7 @@ class PiPSettingsTests(unittest.TestCase):
patch.object(appearance_compact.gui_app, "texture", return_value=None):
appearance_compact.AppearanceCompact(Session()).entry_button().click()
parent = shown[-1]
self.assertFalse(any(item.label == "blind spot camera" for item in parent.items))
self.assertFalse(any(item.label == "Adj Spot Camera" for item in parent.items))
appearance_compact.AppearanceCompact(Session()).open("pip")
child = shown[-1]
next(item for item in child.items if item.label == "show on turn signal").click()
@@ -814,3 +814,28 @@ def test_white_balance_switch_follows_saved_choice(monkeypatch):
FakeParams.value = False
assert switch.enabled(0.5)
assert not switch.enabled(1.5)
def test_c4_shell_passes_full_panel_placements_and_saved_triggers():
from openpilot.starpilot.ui.runtime_app import StarShellSession
from openpilot.starpilot.ui.presentation import Profile
shell = StarShellSession.__new__(StarShellSession)
shell.profile = Profile.COMPACT
shell._pip_saved = SavedPiP((), enabled=True, mask=starting_mask(1928, 1208),
on_blinker=False, on_bsm=True, invert=True)
shell._pip_signals_cache = Signals(True, False, False, True, False)
shell.pip_renderer = Mock()
shell.pip_renderer.render.return_value = "rendered"
document = default_document()
state = SimpleNamespace(customization=document)
shell._render_pip(Rect(0, 0, 476, 240), state)
options = shell.pip_renderer.render.call_args.kwargs
assert options["placements"] == {"left": Rect(0, 0, 476, 240), "right": Rect(0, 0, 476, 240)}
assert options["on_blinker"] is False and options["on_bsm"] is True and options["invert"] is True
submit, draw = Mock(), Mock()
shell._render_pip(Rect(0, 0, 476, 240), state, submit=submit)
shell.pip_renderer.render.call_args.kwargs["submit"]("pip_right", draw)
submit.assert_called_once_with("pip_left", draw)
document["layouts"]["compact"]["pip_left"]["enabled"] = False
shell._render_pip(Rect(0, 0, 476, 240), state)
assert shell.pip_renderer.render.call_args.kwargs["placements"] == {}
@@ -156,7 +156,7 @@ def test_new_layouts_reject_torque_overlap_and_legacy_migration_is_targeted(prof
original = deepcopy(doc)
migrated = validate_document(doc)
assert doc == original
assert migrated['version'] == 16
assert migrated['version'] == 17
assert migrated['palette'] == doc['palette']
assert migrated['layouts']['large']['current_speed'] == doc['layouts']['large']['current_speed']
assert migrated['layouts'][str(profile)][owner]['y'] == default_document()['layouts'][str(profile)][owner]['y']
@@ -48,7 +48,7 @@ def test_v4_migration_preserves_settings_and_clamps_only_enlarged_widgets():
doc['layouts']['large']['cruise_limits'].update(x=1654, y=75)
old_speed = dict(doc['layouts']['large']['current_speed'])
migrated = validate_document(doc)
assert migrated['version'] == 16
assert migrated['version'] == 17
assert migrated['layouts']['large']['cruise_limits']['x'] == 1391
assert migrated['layouts']['large']['current_speed'] == old_speed
assert migrated['speedSources'] is True
@@ -4,6 +4,7 @@ from copy import deepcopy
from types import SimpleNamespace as NS
import unittest
from opendbc.car.honda.values import HondaFlags
from openpilot.starpilot.ui.torque_feedback import observe_torque_feedback
@@ -128,6 +129,27 @@ class TorqueFeedbackTests(unittest.TestCase):
output.lateralControlMode = "newUnknownChannel"
self.assertIsNone(observe(sm, cp).utilization)
def test_accord_angle_loop_shows_angle_error_not_roll(self):
sm = Messages("angleState")
cp = NS(brand="honda", flags=HondaFlags.EPS_ANGLE_LOOP_FW.value, maxLateralAccel=3.5886)
sm["carState"].steeringAngleDeg = 1.0
sm["carState"].vEgo = sm["carState"].vEgoRaw = 26.9
sm["carOutput"].actuatorsOutput.steeringAngleDeg = 1.0
sm["vehicleParameters"].roll = 0.0326 # the device's standing +1.87 deg roll bias
sm["controlsState"].curvature = sm["controlsState"].desiredCurvature = 0.0
self.assertEqual((observe(sm, cp).utilization, observe(sm, cp).source), (0.0, "angle_error"))
self.assertEqual(observe(sm, NS(brand="honda", flags=0, maxLateralAccel=3.5886)).source, "lateral_acceleration_demand",
"without the angle-loop flag the bar shows the lateral-acceleration demand")
sm["carOutput"].actuatorsOutput.steeringAngleDeg = 1.0 + 6.1 # left of the wheel by half the 12.2 deg clip
self.assertAlmostEqual(observe(sm, cp).utilization, -0.5)
sm["carOutput"].actuatorsOutput.steeringAngleDeg = 1.0 - 50.0
self.assertEqual(observe(sm, cp).utilization, 1.0)
sm["carControl"].latActive = False
self.assertEqual(observe(sm, cp).utilization, 0.0)
sm["carControl"].latActive = True
del sm["carOutput"]
self.assertIsNone(observe(sm, cp).utilization)
def test_read_only(self):
sm = Messages("angleState")
before = deepcopy(vars(sm)), repr(sm)
+29 -1
View File
@@ -4,6 +4,9 @@ from dataclasses import dataclass
import math
from typing import Any, Literal
import numpy as np
from opendbc.car.honda.values import CarControllerParams as HondaParams, HondaFlags
DEFAULT_MAX_LATERAL_ACCELERATION = 3.0
LATERAL_STATES = frozenset(("pidState", "angleState", "debugState", "torqueState", "curvatureState",
@@ -13,10 +16,26 @@ LATERAL_STATES = frozenset(("pidState", "angleState", "debugState", "torqueState
@dataclass(frozen=True)
class TorqueFeedback:
utilization: float | None = None
source: Literal["unavailable", "actuator_output", "lateral_acceleration_demand"] = "unavailable"
source: Literal["unavailable", "actuator_output", "lateral_acceleration_demand", "angle_error"] = "unavailable"
reason: str = "car_state_unavailable"
def accord_angle_error_bar(car_params: Any) -> bool:
try:
return car_params.brand == "honda" and bool(car_params.flags & HondaFlags.EPS_ANGLE_LOOP_FW)
except (AttributeError, TypeError):
return False
def accord_angle_error_fraction(setpoint_deg: float, angle_deg: float, v_ego: float) -> float:
"""(setpoint - wheel) over the Accord error clip at this speed, clipped to +-1.
Negated like the torque branch: openpilot angles are left-positive and the bar draws +x to the
right, so the bar must point the way the EPS is pulling the wheel (left pull = bar left)."""
error_max = float(np.interp(v_ego, HondaParams.ANGLE_ERROR_MAX_BP, HondaParams.ANGLE_ERROR_MAX_V))
return float(np.clip(-(setpoint_deg - angle_deg) / error_max, -1.0, 1.0))
def _finite(value: Any) -> float | None:
if type(value) not in (int, float):
return None
@@ -63,6 +82,15 @@ def observe_torque_feedback(car_state: Any, car_control: Any, controls_state: An
return TorqueFeedback(reason="lateral_activity_unavailable")
if not control.latActive:
return TorqueFeedback(0.0, "lateral_acceleration_demand", "lateral_inactive")
# Accord on the angle-loop EPS: show the angle error the setpoint carries, not the lateral-acceleration demand
# (the estimate this replaced subtracted road roll, so the device's standing roll bias drew as a constant pull).
if accord_angle_error_bar(car_params):
setpoint = _finite(getattr(getattr(output, "actuatorsOutput", None), "steeringAngleDeg", None))
angle = _finite(getattr(car, "steeringAngleDeg", None))
speed = _finite(getattr(car, "vEgoRaw", None))
if setpoint is None or angle is None or speed is None:
return TorqueFeedback(reason="actuator_output_unavailable")
return TorqueFeedback(accord_angle_error_fraction(setpoint, angle, speed), "angle_error", "observed")
parameters = vehicle_parameters
if parameters is None or getattr(parameters, "valid", None) is not True:
return TorqueFeedback(reason="vehicle_parameters_unavailable")
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1,4 +1,4 @@
#pragma once
extern const uint8_t gitversion[29];
const uint8_t gitversion[29] = "DEV-82f431d8-Pf38f504f-DEBUG";
const uint8_t gitversion[29] = "DEV-b666318e-Pf38f504f-DEBUG";
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
DEV-ada7b6bd-Pf38f504f-DEBUG
DEV-b666318e-Pf38f504f-DEBUG
Binary file not shown.
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "c62fb6fec8354753767abf1c79a13750939b7151cbf1f7024f4d432c2dce0f45", "schema_version": 1}
{"protected_inventory_sha256": "60dbc268cc3e6548f597a7f6dcff8032066fe868bab42e2a05a8acaa57de21cb", "schema_version": 1}
+20 -1
View File
@@ -1,3 +1,18 @@
import {supportForum} from './thread-tags.mjs';
export const ticketStates={
new:{circle:'🟠',color:0xf28c28},
reviewed:{circle:'⚪',color:0xffffff},
testing:{circle:'🟣',color:0x9b59b6},
investigating:{circle:'🔴',color:0xe74c3c},
fulfilled:{circle:'🟢',color:0x359467},
closed:{circle:'🔵',color:0x3498db}
};
export function ticketTitle(title,state){
const plain=title.replace(/^(?:🟠|⚪|🟣|🔴|🟢|🔵)\ufe0f?\s+/u,'');
return Array.from(state.circle+' '+plain).slice(0,100).join('');
}
export function supportCard(mention,text,buttons,inside=[],color=0xf2b134){
const components=[];
if(mention) components.push({type:10,content:mention});
@@ -35,7 +50,11 @@ export async function botPost(env, channel, payload) {
delete message.content;
Object.assign(message,card);
}
const data = name ? {name, message, ...(tags && {applied_tags:tags})} : message;
if(name && channel===supportForum){
const card=message.components?.find(component=>component.type===17);
if(card)card.accent_color=ticketStates.new.color;
}
const data = name ? {name:channel===supportForum?ticketTitle(name,ticketStates.new):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';
+143 -23
View File
@@ -1,13 +1,17 @@
import {botPost,supportCard,privateCard} from './bot-delivery.mjs';
import {updateComma} from './galaxy-log-request.mjs';
import {botPost,supportCard,privateCard,ticketStates,ticketTitle} 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',
awaiting:'Awaiting deploy', investigate:'Further investigation', overview:'Report overview', question:'Ask the reporter', testing:'Request User Testing', commaTesting:'Request Comma 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={
investigate:'Send this report back for investigation.',
commaTesting:'Ask the reporter to update the comma and test the fix. Include a phone build if needed.',
awaiting:'Record a fix that is waiting for deployment without pinging the reporter.',
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.',
@@ -20,7 +24,7 @@ const descriptions={
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 statusNames=['Open','In Progress','Closed'];
const row = component => ({type:1,components:[component]});
const ephemeral = (content,controls) => Response.json({type:4,data:privateCard(content,controls)});
const idPattern = /^\d{1,20}$/;
@@ -35,6 +39,83 @@ export function caseButtons(user, platform) {
return [{type:1,components:[button('note',titles.note,2),button('menu','Staff Actions',1)]}];
}
function staffMenu(base,channel){
const options=Object.entries(titles).filter(([key])=>key!=='note').map(([value,label])=>({label,value,description:descriptions[value]}));
return privateCard('**Staff Actions**',[row({type:3,custom_id:base+'pick:'+channel,placeholder:'Choose a staff action',options})]);
}
export function privateStaffCommand(i,env,ctx){
if(i.guild_id!=='1387432184121393333'||!idPattern.test(i.channel_id))return ephemeral('Open a Companion report thread.');
ctx.waitUntil((async()=>{
let card=privateCard('Could not find a saved Companion report for this thread.');
try{
const settings=env.REPORTS.get(env.REPORTS.idFromName('companion-bot-setup'));
const role=await settings.fetch('https://reports/sage-role');
if(!role.ok||!i.member?.roles?.includes((await role.json()).id)){
card=privateCard('Staff Actions requires the StarPilot Sage role.');
}else{
card=await ticketStaffMenu(i,env)||card;
}
}catch(error){
console.warn('Private staff menu lookup failed',i.channel_id,error.message);
card=privateCard('Could not verify the ticket. Try Staff Actions on the report card.');
}
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({...card,content:null,embeds:[]}),redirect:'manual'});
})());
return Response.json({type:5,data:{flags:64}});
}
async function ticketStaffMenu(i,env){
if(i.channel?.parent_id&&i.channel.parent_id!==supportForum)return;
const referrals=env.REPORTS.get(env.REPORTS.idFromName('driving-referral-review'));
const response=await referrals.fetch('https://reports/referrals/ticket',{method:'POST',body:JSON.stringify({channel:i.channel_id})});
const linked=response.ok?await response.json():null;
if(linked&&idPattern.test(linked.reporter)&&['ios','android'].includes(linked.platform))
return staffMenu('case:'+linked.reporter+':'+linked.platform+':',i.channel_id);
const thread=await getReportThread(env,i.channel_id);
const path='/channels/'+thread.id+'/messages';
const opener=await discordTags(env,path+'/'+thread.id).catch(()=>null);
function controls(message){
if(message?.author?.id!==i.application_id||message.channel_id!==thread.id)return;
const items=(message.components||[]).flatMap(row=>row.components||[]);
for(const item of items){
const match=/^case:(\d{1,20}):(ios|android):menu(?::(\d{1,20}))?$/.exec(item.custom_id||'');
if(match&&(!match[3]||match[3]===thread.id))return staffMenu('case:'+match[1]+':'+match[2]+':',thread.id);
}
}
const menu=controls(opener);
if(menu)return menu;
const platforms=thread.applied_tags.includes(supportTags.Android)?['android','ios']:['ios','android'];
const sameThread=url=>typeof url==='string'&&new RegExp('^https://discord\\.com/channels/'+i.guild_id+'/'+thread.id+'/\\d+$').test(url);
// Old webhooks posted the reporter and reference as text, before buttons existed.
const reporter=/^Report from <@!?(\d{1,20})>/.exec(opener?.content||'')?.[1];
const reference=/^Reference: ([a-f0-9-]{36})\s*$/im.exec(opener?.content||'')?.[1];
if(reporter&&reference){
const owner=env.REPORTS.get(env.REPORTS.idFromName(reporter));
for(const platform of platforms){
const result=await owner.fetch('https://reports/dashboard-record',{method:'POST',body:JSON.stringify({platform,userID:reporter,reference})});
if(result.ok&&sameThread((await result.json()).threadURL))return staffMenu('case:'+reporter+':'+platform+':',thread.id);
}
}
const recent=await discordTags(env,path+'?limit=100').catch(()=>[]);
const recentMenu=recent.map(controls).find(Boolean);
if(recentMenu)return recentMenu;
// Discord can omit an old webhook's text. Match the saved public thread URL instead.
for(const platform of platforms){
const index=env.REPORTS.get(env.REPORTS.idFromName('dashboard:'+platform));
let cursor;
do{
const result=await index.fetch('https://reports/dashboard-list',{method:'POST',body:JSON.stringify({platform,cursor})});
if(!result.ok)throw Error('Report index unavailable');
const page=await result.json();
const record=page.reports.find(r=>r.platform===platform&&idPattern.test(r.userID)&&sameThread(r.threadURL));
if(record)return staffMenu('case:'+record.userID+':'+platform+':',thread.id);
cursor=page.cursor;
}while(cursor);
}
}
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;
@@ -48,13 +129,14 @@ export async function caseInteraction(i,env,origin,ctx) {
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 selected=command==='pick'?i.data.values?.[0]:command;
const commaTesting=selected==='commaTesting';
const action=commaTesting?'testing':selected;
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})]);
return Response.json({type:4,data:staffMenu(base,channel)});
}
if(!reporterAction&&!Object.hasOwn(titles,action))return ephemeral('Unknown support action.');
if(i.type===3 && command==='pick' && action==='assign'){
@@ -71,18 +153,28 @@ export async function caseInteraction(i,env,origin,ctx) {
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'};
const prompts={question:'What do you need from the reporter?',feedback:'What did you find or what do you need?',note:'What happened?',testing:'Steps to test',awaiting:'Update for the reporter (optional)',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 fields=[row({type:4,custom_id:'value',label:prompts[action],style:['note','testing','awaiting','feedback','question'].includes(action)?2:1,required:action!=='awaiting',max_length:action==='rename'?100:action==='duplicate'?200:1500})];
if(['awaiting','testing'].includes(action)){
fields.push(row({type:4,custom_id:'build',label:'App build (optional)',placeholder:'e.g. iOS 2.0 (332)',style:1,required:false,max_length:120}),
row({type:4,custom_id:'commit',label:'GitHub commit URL (optional)',placeholder:'https://github.com/owner/repo/commit/...',style:1,required:false,max_length:300}));
}
return Response.json({type:9,data:{title:titles[selected]||'Give feedback',custom_id:base+selected+':'+channel,components:fields}});
}
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(prompts[action] && ((!value&&action!=='awaiting')||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 fields=(i.data.components||[]).flatMap(r=>r.components||[]);
const build=fields.find(field=>field.custom_id==='build')?.value?.trim();
const commit=fields.find(field=>field.custom_id==='commit')?.value?.trim();
if(commit&&!/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/commit\/[\da-f]{7,64}\/?$/i.test(commit))
return ephemeral('Use a GitHub commit URL ending in the commit hash.');
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})});
const response=await owner.fetch('https://reports/case-action',{method:'POST',body:JSON.stringify({user,platform,channel,action,actor,value,build,commit,commaTesting,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'});
@@ -101,13 +193,16 @@ export async function caseAction(storage,env,b){
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(!record||(record.platform===undefined?'ios':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 status=statusNames.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.releaseStage)summary.push('Fix: '+record.releaseStage);
if(record.build)summary.push('App build: '+record.build);
if(record.commit)summary.push('[View commit]('+record.commit+')');
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+')');
@@ -145,6 +240,12 @@ export async function caseAction(storage,env,b){
}
let message, nextStatus;
const patch={};
const state=action==='fulfilled'?ticketStates.fulfilled
:action==='status'&&value==='Closed'?ticketStates.closed
:action==='investigate'||action==='status'&&value==='Open'?ticketStates.investigating
:action==='testing'?ticketStates.testing
:['awaiting','working'].includes(action)||action==='status'&&value==='In Progress'?ticketStates.reviewed:null;
const rename=state&&thread.name?{name:ticketTitle(thread.name,state)}:{};
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.');
@@ -152,7 +253,8 @@ export async function caseAction(storage,env,b){
patch.duplicate=target;
message='Duplicate of <#'+target+'>.';
}else if(action==='rename'){
await discordTags(env,'/channels/'+channel,{name:value});
const currentState=Object.values(ticketStates).find(item=>thread.name?.startsWith(item.circle));
await discordTags(env,'/channels/'+channel,{name:currentState?ticketTitle(value,currentState):value});
patch.title=value;message='Renamed this report to '+value+'.';
}else if(action==='assign'||action==='unassign'){
patch.assignee=action==='assign'?value:null;
@@ -167,25 +269,43 @@ export async function caseAction(storage,env,b){
}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;
}else if(action==='status'||['working','investigate','fulfilled'].includes(action)){
const status=action==='fulfilled'?'Closed':['working','investigate'].includes(action)?'In Progress':value;
nextStatus=status;
patch.releaseStage=null;
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+'>';
await discordTags(env,'/channels/'+channel,{applied_tags:tags,...rename,...(reopening&&thread.thread_metadata?.archived?{archived:false}:{})});
message=action==='investigate'?'Staff are investigating this report again.':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==='awaiting'){
if(rename.name && rename.name!==thread.name)await discordTags(env,'/channels/'+channel,rename);
patch.releaseStage=action==='testing'?'Ready for testing':'Awaiting deploy';
if(b.build)patch.build=b.build;
if(b.commit)patch.commit=b.commit;
message=action==='testing'?'<@'+user+'>':'';
}else if(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)]));
if(action==='awaiting'||action==='testing'||action==='question'){
const fix=[];
if(action!=='question'){
const build=patch.build||record.build, commit=patch.commit||record.commit;
if(build)fix.push('**App build:** '+build);
if(commit)fix.push('[View commit]('+commit+')');
}
if(action==='awaiting'){
delete payload.content;
Object.assign(payload,supportCard('',['**Awaiting deploy**','A fix is waiting for release. Staff will ask you to test when it is available.',value,...fix].filter(Boolean).join('\n'),caseButtons(user,platform),[],state.color));
}else{
const text=[action==='testing'?'**Waiting for user testing**':'**Staff need more information**',...(action==='testing'&&b.commaTesting?[updateComma]:[]),value,...fix,'','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)],[],state?.color));
}
}else if(action==='feedback'||action==='note'){
delete payload.content;
Object.assign(payload,supportCard('',message,caseButtons(user,platform)));
@@ -193,7 +313,7 @@ export async function caseAction(storage,env,b){
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]));
Object.assign(payload,supportCard('','**'+nextStatus+'**\n'+message,controls,[],state.color));
}
const post=await botPost(env,channel,payload);
if(nextStatus==='Closed'){
+147 -2
View File
@@ -101,10 +101,10 @@ test('closing archives after the status card and reopening restores the same thr
});
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.deepEqual(events,[{applied_tags:['42','1565237052524466207']},0x3498db,{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]);
assert.deepEqual(events.slice(3),[{applied_tags:['42','1565236988913913887'],archived:false},0xe74c3c]);
});
test('the overview is staff-only and reads archived tickets without posting',async t=>{
@@ -134,3 +134,148 @@ test('asking a question pings only the reporter and offers feedback',async t=>{
assert.match(JSON.stringify(message.components),/Which build/);
assert.match(JSON.stringify(message.components),/case:1:ios:feedback:4/);
});
test('deployment keeps the commit, testing adds the build, and the forum title follows the ticket lifecycle',async t=>{
const records=new Map([['thread:4',{platform:'ios'}]]);
const storage={get:key=>records.get(key),put:(key,val)=>records.set(key,val),transaction:fn=>fn(storage)};
const thread={id:'4',type:11,parent_id:supportForum,name:'🟠 Sentry preview',applied_tags:[],thread_metadata:{}};
const posts=[];
t.mock.method(globalThis,'fetch',async(url,options)=>{
if(options.method==='PATCH')Object.assign(thread,JSON.parse(options.body));
if(options.method==='POST')posts.push(JSON.parse(options.body));
return Response.json(thread);
});
const run=(action,extra={})=>caseAction(storage,env,{channel:'4',user:'1',actor:'3',platform:'ios',action,interaction:action,...extra});
const commit='https://github.com/StarPilotHQ/StarPilot/commit/1234abc';
await run('awaiting',{commit});
assert.equal(thread.name,'⚪ Sentry preview');
assert.deepEqual(posts.at(-1).allowed_mentions.users,[]);
await run('testing',{build:'2.0 (332)',value:'Check the preview.'});
assert.equal(thread.name,'🟣 Sentry preview');
assert.deepEqual(posts.at(-1).allowed_mentions.users,['1']);
assert.ok(JSON.stringify(posts.at(-1)).includes(commit));
assert.ok(JSON.stringify(posts.at(-1)).includes('2.0 (332)'));
await run('investigate');
assert.equal(thread.name,'🔴 Sentry preview');
await run('fulfilled',{actor:'1'});
assert.equal(thread.name,'🟢 Sentry preview');
});
test('slash command opens only an ephemeral staff menu without posting to the ticket',async t=>{
const {privateStaffCommand}=await import('./case-actions.mjs');
const i={guild_id:'1387432184121393333',channel_id:'4',application_id:'9',token:'fixture',member:{roles:['6']}};
const edits=[];
t.mock.method(globalThis,'fetch',async(url,options)=>{
if(options.method==='PATCH'){
assert.ok(url.endsWith('/messages/@original'));
edits.push(JSON.parse(options.body));
return Response.json({});
}
assert.equal(options.method,'GET');
if(url.endsWith('/channels/4'))return Response.json({id:'4',type:11,parent_id:supportForum,applied_tags:[]});
assert.ok(url.endsWith('/channels/4/messages/4'));
return Response.json({channel_id:'4',author:{id:'9'},components:caseButtons('1','ios')});
});
for(const roles of [['6'],[]]){
i.member.roles=roles;
let job;
const deferred=await privateStaffCommand(i,env,{waitUntil:p=>{job=p;}}).json();
assert.equal(deferred.data.flags,64);
await job;
assert.ok(edits.at(-1).flags & 64);
assert.match(JSON.stringify(edits.at(-1)),roles.length?/case:1:ios:pick:4/:/requires the StarPilot Sage role/);
}
});
test('a renamed, previously moved ticket opens its private menu even without Discord message history',async t=>{
const {privateStaffCommand}=await import('./case-actions.mjs');
const {referralStore}=await import('./referrals.mjs');
const channel='1574999999999999999',reporter='1574000000000000000';
const entries=new Map([['report:old',{destination:channel,reporter,platform:'ios',state:'moved'}]]);
let lists=0;
const store={get:k=>entries.get(k),put:(k,v)=>entries.set(k,v),list:()=>{lists++;return new Map(entries);}};
const runtime={REPORTS:{idFromName:k=>k,get:k=>({fetch:(url,init)=>k==='companion-bot-setup'
?Response.json({id:'sage'}):referralStore(new URL(url).pathname,new Request(url,init),store,{})})}};
const i={guild_id:'1387432184121393333',channel_id:channel,channel:{parent_id:supportForum},application_id:'9',token:'fixture',member:{roles:['sage']}};
t.mock.method(globalThis,'fetch',async(url,o)=>{
assert.equal(o.method,'PATCH');
assert.ok(url.endsWith('/messages/@original'));
const card=JSON.parse(o.body);
assert.ok(card.flags & 64);
assert.ok(JSON.stringify(card).includes('case:'+reporter+':ios:pick:'+channel));
return Response.json({});
});
for(let n=0;n<2;n++){
let done;
assert.equal((await privateStaffCommand(i,runtime,{waitUntil:p=>{done=p;}}).json()).data.flags,64);
await done;
}
assert.equal(lists,1);
});
test('old webhook tickets use their verified report reference or exact saved thread URL',async t=>{
const {privateStaffCommand}=await import('./case-actions.mjs');
const guild='1387432184121393333', channel='1574999999999999999', user='1574000000000000000';
const ref='C80EA1A0-6ED0-4F9C-880C-E91C83F04049';
const threadURL='https://discord.com/channels/'+guild+'/'+channel+'/'+channel;
let readable=true, edits=0;
const runtime={DISCORD_BOT_TOKEN:'test',REPORTS:{idFromName:k=>k,get:k=>({fetch:async(url,init)=>{
if(k==='companion-bot-setup')return Response.json({id:'sage'});
if(k==='driving-referral-review')return new Response(null,{status:404});
const body=JSON.parse(init.body);
if(k===user){
assert.equal(body.reference,ref);
return Response.json({threadURL});
}
assert.equal(k,'dashboard:ios');
return Response.json(body.cursor?{reports:[{userID:user,platform:'ios',threadURL}],cursor:null}:
{reports:[{userID:'3',platform:'ios',threadURL:threadURL.replace(channel,'123')}],cursor:'page2'});
}})}};
t.mock.method(globalThis,'fetch',async(url,opts)=>{
if(opts.method==='PATCH'){
assert.ok(url.endsWith('/messages/@original'));
const card=JSON.parse(opts.body);
assert.ok(card.flags & 64);
assert.ok(JSON.stringify(card).includes('case:'+user+':ios:pick:'+channel));
edits++;
return Response.json({});
}
assert.equal(opts.method,'GET');
if(url.endsWith('/channels/'+channel))return Response.json({id:channel,parent_id:supportForum,type:11,applied_tags:[]});
if(!readable)return new Response(null,{status:403});
return Response.json({channel_id:channel,author:{id:'2'},content:'Report from <@'+user+'> (Nate)\nReference: '+ref+'\n\nTesting'});
});
for(readable of [true,false]){
let job;
const ack=await privateStaffCommand({guild_id:guild,channel_id:channel,application_id:'9',member:{roles:['sage']}},runtime,{waitUntil:p=>{job=p;}}).json();
assert.equal(ack.data.flags,64);
await job;
}
assert.equal(edits,2);
});
test('comma testing adds the official branch instruction only to the comma testing request',async t=>{
const {galaxyLogSteps,updateComma}=await import('./galaxy-log-request.mjs');
for(const kind of ['connection','controller','starport']){
const steps=galaxyLogSteps({kind,platform:'android'});
assert.ok(steps[0].startsWith(updateComma));
assert.match(steps.at(-1),/offline.*branch and version/);
}
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:[]});
});
const records=new Map([['thread:4',{platform:'ios'}]]);
const store={get:k=>records.get(k),put:(k,v)=>records.set(k,v),transaction:fn=>fn(store)};
for(const selected of ['testing','commaTesting']){
const pick=interaction('pick:4','3');
pick.data.values=[selected];
const modal=(await (await caseInteraction(pick,env)).json()).data;
assert.equal(modal.custom_id,'case:1:ios:'+selected+':4');
await caseAction(store,env,{action:'testing',commaTesting:selected==='commaTesting',platform:'ios',channel:'4',user:'1',actor:'3',value:'Verify the fix.',build:'2.0 (332)',interaction:selected});
const card=JSON.stringify(posts.at(-1));
assert.equal(card.includes(updateComma),selected==='commaTesting');
assert.ok(card.includes('2.0 (332)'));
}
});
+5 -4
View File
@@ -1,6 +1,6 @@
import {isReferral,referralInteraction} from './referrals.mjs';
import {galaxyLogSteps} from './galaxy-log-request.mjs';
import {caseInteraction,reporterButtons} from './case-actions.mjs';
import {galaxyLogSteps,routeSteps} from './galaxy-log-request.mjs';
import {caseInteraction,privateStaffCommand,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';
@@ -61,7 +61,7 @@ export function driveDownload(env, token, 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>
<h1>Submit drive logs</h1><p>${routeSteps} You can also attach a segment log. 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>`,
@@ -169,7 +169,7 @@ export async function driveObject(request,storage,env) {
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.';
'**Drive logs requested**\n'+routeSteps+' Use the link below to send your logs privately.';
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+')':'';
@@ -295,6 +295,7 @@ export async function driveInteraction(request,env,origin,ctx) {
const interaction=JSON.parse(raw);
if(interaction.type===1)return reply({type:1});
const answer=content=>reply({type:4,data:privateCard(content)});
if(interaction.type===2&&interaction.data?.type===1&&interaction.data.name==='companion-staff-action')return privateStaffCommand(interaction,env,ctx);
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.');
@@ -4,14 +4,20 @@ const topics={
starport:['StarPort / Car Screen','Send StarPort logs'],
};
export const updateComma='While parked, update your comma to the latest testing build from StarPilotHQ/StarPilot.';
export const routeSteps='For a drive that already happened, share the original comma connect route and the time of the issue. If staff ask for a new test drive, update your comma to the latest testing build from StarPilotHQ/StarPilot while parked before that drive.';
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';
const retry={connection:'Try connecting your phone again.',controller:'Try connecting your controller again.',starport:'Try StarPort again.'};
return [
updateComma+' '+retry[record.kind]+' If the issue persists, collect fresh logs:',
'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.',
'If your comma is offline, save the ZIP from Galaxy on your phone and keep it until you are online. Include the branch and version you captured.',
];
}
+169 -32
View File
@@ -1,4 +1,4 @@
import {botPost,privateCard,supportCard} from './bot-delivery.mjs';
import {botPost,ticketTitle,ticketStates,messageText,privateCard,supportCard} from './bot-delivery.mjs';
import {caseButtons} from './case-actions.mjs';
import {discordTags,supportForum,supportTags} from './thread-tags.mjs';
@@ -85,48 +85,131 @@ async function offer(store,env,thread,manual=false){
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 record={...details,source:thread.id,sourceTitle:title,state:'offering',attempted:Date.now(),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;
return deliverReview(store,env,key,record);
}
}
async function deliverReview(store,env,key,record){
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+':'+record.source}))};
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(record.source)+')',
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:record.source,enforce_nonce:true});
if(!sent.ok)throw Error('Review delivery unconfirmed');
const receipt=await sent.json();
if(!receipt.id)throw Error('Missing review receipt');
await acknowledgeReview(store,key,receipt.id);
return true;
}
async function acknowledgeReview(store,key,receipt){
await store.transaction(async tx=>{
const current=await tx.get(key);
if(current?.state==='offering'||current?.state==='pending')
await tx.put(key,{...current,state:'pending',reviewMessage:receipt});
});
}
async function recoverReview(store,env,key,record){
const bot=await discordTags(env,'/users/@me');
let before=record.reviewBefore;
const messages=await discordTags(env,'/channels/'+env.COMPANION_REVIEW_THREAD_ID+'/messages?limit=100'+(before?'&before='+before:''));
const match=messages.find(m=>m.author?.id===bot.id&&messageText(m).includes('[Open driving report]('+urlFor(record.source)+')'));
if(match)return acknowledgeReview(store,key,match.id);
const oldest=messages.at(-1)?.id;
if(messages.length===100&&BigInt(oldest)>BigInt(record.source)){
await store.transaction(async tx=>{
const current=await tx.get(key);
if(current?.state===record.state&&!current.reviewMessage)await tx.put(key,{...current,reviewBefore:oldest});
});
return;
}
// Reserve the retry so overlapping scans cannot both resend the card.
const reserved=await store.transaction(async tx=>{
const current=await tx.get(key);
if(!current||current.state!==record.state||current.reviewMessage||current.attempted>Date.now()-60000)return false;
await tx.put(key,{...current,state:'offering',attempted:Date.now(),reviewBefore:null});
return true;
});
if(reserved)await deliverReview(store,env,key,record);
}
async function ensureGuildCommand(store,env,key,definition){
const saved=await store.get(key);
if(saved?.id||saved?.retryAfter>Date.now())return;
await store.put(key,{retryAfter:Date.now()+300000});
try{
const app='1574857862872703088';
const response=await fetch('https://discord.com/api/v10/applications/'+app+'/guilds/'+guild+'/commands',{
method:'POST',redirect:'manual',signal:AbortSignal.timeout(10000),
headers:{Authorization:'Bot '+env.DISCORD_BOT_TOKEN,'Content-Type':'application/json'},
body:JSON.stringify(definition)
});
if(!response.ok)throw Error('HTTP '+response.status);
const registered=await response.json();
if(!id(registered.id)||registered.name!==definition.name||registered.type!==definition.type||registered.guild_id!==guild||registered.application_id!==app)
throw Error('Invalid command receipt');
await store.put(key,{id:registered.id});
}catch(error){console.warn('Discord referral command registration pending',error.message);}
}
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(path==='/referrals/ticket'){
const {channel}=await request.json();
if(!id(channel))return Response.json(null,{status:400});
const key='destination:'+channel;
const cached=await store.get(key);
if(cached)return Response.json(cached);
// Tickets moved before the destination index was added are keyed by their driving thread.
let startAfter;
do{
const page=await store.list({prefix:'report:',limit:100,...(startAfter&&{startAfter})});
for(const [source,record] of page){
startAfter=source;
if(record.destination===channel&&['moved','created'].includes(record.state)&&id(record.reporter)&&['android','ios'].includes(record.platform)){
const ticket={reporter:record.reporter,platform:record.platform};
await store.put(key,ticket);
return Response.json(ticket);
}
}
if(page.size<100)break;
}while(startAfter);
return Response.json(null,{status:404});
}
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')){
await ensureGuildCommand(store,env,'refer-command-v1',{name:command,type:3});
await ensureGuildCommand(store,env,'staff-action-command-v1',{name:'companion-staff-action',type:1,description:'Open Staff Actions privately for this Companion ticket'});
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;
const key='report:'+t.id;
const record=await store.get(key);
if(record && (!['offering','pending'].includes(record.state)||record.reviewMessage||record.attempted>Date.now()-60000))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);}
try{if(record)await recoverReview(store,env,key,record);else await offer(store,env,t);}catch(error){console.warn('Referral review deferred',t.id,error.name);}finally{await store.put(retry,Date.now()+300000);}
}
return Response.json({ok:true});
}
const {action,source,actor}=await request.json();
const {action:choice,source,actor}=await request.json();
const selected=['ios','android'].includes(choice)?choice:null;
const action=(selected||choice==='retry')?'move':choice;
if(!id(source)||!id(actor))return Response.json({message:'Invalid referral.'});
if(action==='manual'){
const thread=await discordTags(env,'/channels/'+source);
@@ -136,30 +219,42 @@ export async function referralStore(path,request,store,env){
}
const key='report:'+source;
if(!['leave','move'].includes(action))return Response.json({message:'Unknown referral action.'});
if(choice==='retry'){
await store.transaction(async tx=>{
const current=await tx.get(key);
if(current?.state==='creating'&&current.retryAllowed)await tx.put(key,{...current,state:'pending',retryAllowed:false});
});
}
const previous=await store.get(key);
if(action==='move'&&previous?.destination)return finishMove(store,env,key,previous);
if(action==='move'&&previous?.state==='creating')return recoverMove(store,env,key,previous);
if(!['offering','pending'].includes(previous?.state))return Response.json({message:'This referral has already been handled.'});
const reportKind=previous.category==='StarPort'?'starport':previous.category==='Bluetooth controller'?'controller':'connection';
const title=previous.category+' — '+(previous.observed||'').replace(/\s+/g,' ').slice(0,68);
const evidence=[previous.sourceTitle,previous.observed,previous.summary].join(' ');
const apple=/\b(?:iphone[s]?|ios|car[ -]?play)\b/i.test(evidence);
const android=/\bandroid\b/i.test(evidence);
const platform=selected||previous.platform||(reportKind==='starport'?'android':apple===android?null:apple?'ios':'android');
if(action==='move'&&!platform)return Response.json({message:'Choose the phone platform for this ticket.',choosePlatform:true});
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});
if(!['pending','offering'].includes(current?.state))return null;
await tx.put(key,{...current,state:action==='leave'?'dismissed':'creating',actor,platform,title,reportKind,created:Date.now()});
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(!record)return Response.json({message:'Another staff action is already in progress.'});
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']);
else 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}});
const card=supportCard('',mentions+'\n\n**'+record.category+' support**\nWe moved your report here from driving feedback so the Companion support team can help. We copied your report below. You can reply in this thread with updates.\n\n'+excerpt+'\n\n[Original driving report]('+urlFor(source)+')',caseButtons(record.reporter,platform));
let receipt;
try{receipt=await botPost(env,supportForum,{...card,thread_name:title,applied_tags:tags,allowed_mentions:{parse:[],users:recipients}});}
catch{return Response.json({message:'Ticket delivery is uncertain. Choose Move again in a minute to check Discord.'});}
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.'});
@@ -170,6 +265,39 @@ export async function referralStore(path,request,store,env){
return finishMove(store,env,key,moved);
}
async function recoverMove(store,env,key,record){
if(record.created>Date.now()-60000)return Response.json({message:'Discord is still confirming the ticket. Choose Move again in a minute.'});
const bot=await discordTags(env,'/users/@me');
const active=await discordTags(env,'/guilds/'+guild+'/threads/active');
const title=record.title||record.category+' — '+record.observed.replace(/\s+/g,' ').slice(0,68);
async function find(threads){
for(const thread of threads){
if(thread.parent_id!==supportForum||thread.owner_id!==bot.id||!(thread.name===title||thread.name===ticketTitle(title,ticketStates.new)))continue;
const opener=await discordTags(env,'/channels/'+thread.id+'/messages/'+thread.id);
if(opener.author?.id===bot.id&&messageText(opener).endsWith('[Original driving report]('+urlFor(record.source)+')'))return thread.id;
}
}
let destination=await find(active.threads);
if(!destination){
const archive=await discordTags(env,'/channels/'+supportForum+'/threads/archived/public?limit=100');
destination=await find(archive.threads);
if(!destination&&archive.has_more&&!(Date.parse(archive.threads.at(-1)?.thread_metadata?.archive_timestamp)<(record.created||Number(BigInt(record.source)>>22n)+1420070400000)))return Response.json({message:'Delivery is uncertain. Staff should check archived Companion tickets before retrying.'});
}
if(!destination){
await store.transaction(async tx=>{
const current=await tx.get(key);
if(current?.state==='creating'&&current.created===record.created)await tx.put(key,{...current,retryAllowed:true});
});
// A renamed ticket might exist. Never blindly repeat a forum creation.
return Response.json({message:'No matching ticket was confirmed. Check the Companion forum for a renamed ticket. If none exists, choose Retry creation.',retryMove:true});
}
const recovered={...record,title,destination,state:'created',created:record.created||Date.now(),
platform:record.platform||(record.category==='StarPort'||/android/i.test(record.observed)?'android':'ios'),
reportKind:record.reportKind||(record.category==='StarPort'?'starport':record.category==='Bluetooth controller'?'controller':'connection')};
await store.put(key,recovered);
return finishMove(store,env,key,recovered);
}
async function finishMove(store,env,key,record){
if(record.state!=='moved'){
const owner=env.REPORTS.get(env.REPORTS.idFromName(record.reporter));
@@ -177,6 +305,7 @@ async function finishMove(store,env,key,record){
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('destination:'+record.destination,{reporter:record.reporter,platform:record.platform});
await store.put(key,{...record,state:'moved'});
}
const link='[Open the Companion ticket]('+urlFor(record.destination)+')';
@@ -202,7 +331,7 @@ async function finishMove(store,env,key,record){
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 notice=supportCard('','**Your report moved to Companion support**\nThe Companion support team handles this issue. We copied your report into their forum, so there is no need to submit it again. This driving thread is closing. Use the link below to see your report and reply to the team.\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();
@@ -224,10 +353,14 @@ async function finishMove(store,env,key,record){
}
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||''));
return (i.type===2 && i.data?.type===3 && i.data.name===command) || (i.type===3 && /^refer:(leave|move|retry|ios|android):\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 inReview=configured(env)&&i.guild_id===guild&&i.channel_id===env.COMPANION_REVIEW_THREAD_ID;
const card=(text,controls=[])=>inReview
? {...supportCard('',text,[],controls,0x5865f2),allowed_mentions:{parse:[]}}
: privateCard(text,controls);
const reply=text=>Response.json({type:4,data:card(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'));
@@ -235,13 +368,17 @@ export async function referralInteraction(i,env,ctx){
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 controls=[];
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;
const result=await res.json();
text=result.message||text;
const choices=result.choosePlatform?[['ios','iOS'],['android','Android']]:result.retryMove?[['retry','Retry creation']]:[];
if(choices.length)controls=[{type:1,components:choices.map(([key,label])=>({type:2,style:2,label,custom_id:'refer:'+key+':'+source}))}];
}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:[]})});
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({...card(text,controls),content:null,embeds:[]})});
}
})());
return Response.json({type:5,data:{flags:64}});
return Response.json(inReview?{type:5}:{type:5,data:{flags:64}});
}
+91
View File
@@ -29,6 +29,7 @@ test('scan resolves the sample, skips old tickets, and sends a single private ca
const guild='1387432184121393333',forum='1574085782967292000',review='1575000066366644244',sample='1574085782967292086';
const bot='123456789123456789',user='987654321987654321';
const fresh=String(BigInt(Date.now()+1000-1420070400000)<<22n);
let registrations=0;
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();
@@ -36,6 +37,14 @@ test('scan resolves the sample, skips old tickets, and sends a single private ca
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(path==='/applications/1574857862872703088/guilds/'+guild+'/commands'){
assert.equal(opts.method,'POST');
const payload=JSON.parse(opts.body);
if(payload.type===3)assert.equal(payload.name,'Refer to Companion Support');
else assert.deepEqual(payload,{name:'companion-staff-action',type:1,description:'Open Staff Actions privately for this Companion ticket'});
registrations++;
return Response.json({...payload,id:sample,guild_id:guild,application_id:'1574857862872703088'});
}
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});
@@ -45,6 +54,7 @@ test('scan resolves the sample, skips old tickets, and sends a single private ca
throw Error('Unexpected access '+path);
});
for(let i=0;i<3;i++)await referralStore('/referrals/scan',{},store,env);
assert.equal(registrations,2);
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]});
@@ -98,6 +108,7 @@ test('Move closes only after registration and retries the same destination on a
assert.equal(opts.method,'POST');
const notice=JSON.parse(opts.body);
assert.ok(notice.components[0].components[0].content.includes(destination));
assert.match(notice.components[0].components[0].content,/no need to submit it again/);
assert.deepEqual(notice.allowed_mentions,{parse:[]});
if(!allowNotice)return new Response('',{status:403});
notices++;
@@ -150,5 +161,85 @@ test('new linked ticket mentions the original reporter and both maintainers once
for(const id of ids)assert.equal(text.split('<@'+id+'>').length,2);
assert.ok(!text.includes(firestar));
assert.ok(text.includes('Audio should continue.'));
assert.match(text,/reply in this thread/);
}
});
test('ambiguous referrals wait for Sage to pick the phone platform before creating a thread',async t=>{
const {referralStore}=await import('./referrals.mjs');
const source='1574085782967292086',review='1575000066366644244',guild='1387432184121393333';
const record={source,reporter:source,state:'pending',category:'Phone app',observed:'App disconnected'};
const rows=new Map([['source:'+source,{}],['report:'+source,record]]);
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:'test'};
const posts=[];
t.mock.method(globalThis,'fetch',async(url,options)=>{
if(url.endsWith('/channels/'+review))return Response.json({type:12,guild_id:guild});
posts.push(JSON.parse(options.body));
throw Error('lost acknowledgement');
});
const click=action=>referralStore('/referrals/action',{json:()=>({action,source,actor:source})},store,env);
assert.equal((await (await click('move')).json()).choosePlatform,true);
assert.equal(posts.length,0);
await click('android');
assert.equal(rows.get('report:'+source).platform,'android');
assert.equal(rows.get('report:'+source).state,'creating');
await click('move');
assert.equal(posts.length,1);
});
test('lost acknowledgements recover the existing review card and Companion ticket',async t=>{
const {referralStore}=await import('./referrals.mjs');
const source='1574085782967292086',review='1575000066366644244',guild='1387432184121393333',forum='1574085782967292000',bot='1574857862872703088',dest='1574999999999999999',support='1565235002734809168';
const key='report:'+source,title='A Companion report';
const record={state:'offering',category:'Phone app',source,reporter:source,observed:'Android app'};
const rows=new Map([['refer-command-v1',{id:dest}],['staff-action-command-v1',{id:dest}],['start',1],['source:'+source,{DRIVING_FORUM_ID:forum}],[key,record]]);
const store={get:k=>rows.get(k),put:(k,v)=>rows.set(k,v),transaction:fn=>fn(store)};
const env={COMPANION_REVIEW_THREAD_ID:review,DRIVING_SAMPLE_THREAD_ID:source,DISCORD_BOT_TOKEN:'test',REPORTS:{idFromName:k=>k,get:()=>({fetch:()=>new Response('',{status:503})})}};
t.mock.method(globalThis,'fetch',async(url,o)=>{
assert.equal(o.method,'GET');
const path=new URL(url).pathname.replace('/api/v10','');
if(path==='/users/@me')return Response.json({id:bot});
if(path==='/channels/'+review)return Response.json({type:12,guild_id:guild});
if(path.endsWith('/threads/active'))return Response.json({threads:[{parent_id:forum,id:source},{parent_id:support,id:dest,name:title,owner_id:bot}]});
const link='(https://discord.com/channels/'+guild+'/'+source+')';
if(path==='/channels/'+review+'/messages')return Response.json([{author:{id:bot},id:dest,content:'[Open driving report]'+link}]);
if(path==='/channels/'+dest+'/messages/'+dest)return Response.json({author:{id:bot},content:'[Original driving report]'+link});
throw Error(path);
});
await referralStore('/referrals/scan',{},store,env);
assert.equal(rows.get(key).reviewMessage,dest);
rows.set(key,{...record,title,state:'creating',platform:'android',reportKind:'connection',created:1});
await assert.rejects(referralStore('/referrals/action',{json:()=>({action:'move',source,actor:source})},store,env),/register/);
assert.equal(rows.get(key).destination,dest);
assert.equal(rows.get(key).platform,'android');
});
test('review thread replies are shared from acknowledgement through final card; driving thread commands stay private',async t=>{
const guild='1387432184121393333',review='1575000066366644244',source='1574085782967292086';
const edits=[];
t.mock.method(globalThis,'fetch',async(url,options)=>{
assert.equal(options.method,'PATCH');
edits.push(JSON.parse(options.body));
return Response.json({});
});
const env={COMPANION_REVIEW_THREAD_ID:review,DRIVING_SAMPLE_THREAD_ID:source,
REPORTS:{idFromName:name=>name,get:name=>({fetch:async()=>Response.json(name==='companion-bot-setup'?{id:'sage'}:{message:'Choose a platform',choosePlatform:true})})}};
for(const inReview of [true,false]){
const click={type:inReview?3:2,guild_id:guild,channel_id:inReview?review:source,member:{roles:['sage'],user:{id:source}},
application_id:'app',token:'fixture',data:{custom_id:'refer:move:'+source}};
let done;
const ack=await (await referralInteraction(click,env,{waitUntil:job=>{done=job;}})).json();
assert.equal(ack.type,5);
assert.equal(Boolean(ack.data?.flags & 64),!inReview);
await done;
assert.equal(Boolean(edits.at(-1).flags & 64),!inReview);
assert.deepEqual(edits.at(-1).allowed_mentions,{parse:[]});
assert.equal(edits.at(-1).components[0].components[1].components.length,2);
click.member.roles=[];
const denied=await (await referralInteraction(click,env,{})).json();
assert.equal(denied.type,4);
assert.equal(Boolean(denied.data.flags & 64),!inReview);
assert.match(JSON.stringify(denied.data),/requires StarPilot Sage/);
}
});