mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-26 06:43:43 +08:00
Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e4e3e945b2 | |||
| cf4c99e7fa | |||
| 0e8e2bc468 | |||
| 033f8725f4 | |||
| df9be543f4 | |||
| 046e084c86 | |||
| 10cb116607 | |||
| d4decb9018 | |||
| ed9e871b35 | |||
| cc2ff90032 | |||
| 63f4b4b07c | |||
| 6fc0173aad | |||
| 782a00c69f | |||
| 4cd84f603c | |||
| 39de0fe3e6 | |||
| bd9206cc83 | |||
| 9dee2cb5ae | |||
| 36c071f878 |
@@ -539,3 +539,32 @@ bool safety_test_honda_aol_unconfigured_sources(void) {
|
||||
honda_stock_aol_eps_index = saved;
|
||||
return current;
|
||||
}
|
||||
|
||||
|
||||
bool safety_test_honda_rx_capacity(unsigned int count) {
|
||||
if ((current_safety_mode != SAFETY_NOOUTPUT) || (count > 9U)) { return false; }
|
||||
RxCheck source[9] = {0};
|
||||
for (unsigned int i = 0U; i < 9U; i++) { source[i].msg[0].addr = 0x100U + i; }
|
||||
const unsigned int capacity = sizeof(honda_rx_workspace) / sizeof(honda_rx_workspace[0]);
|
||||
const unsigned int expected = (count <= capacity) ? count : 0U;
|
||||
const safety_config result = honda_copy_rx(source, count, (safety_config){0});
|
||||
bool copied = (result.rx_checks == honda_rx_workspace) && (result.rx_checks_len == (int)expected);
|
||||
for (unsigned int i = 0U; i < capacity; i++) {
|
||||
copied &= honda_rx_workspace[i].msg[0].addr == ((i < expected) ? source[i].msg[0].addr : 0U);
|
||||
}
|
||||
return copied;
|
||||
}
|
||||
|
||||
int safety_test_honda_configuration_bounds(unsigned int count, unsigned int pt_bus) {
|
||||
if ((current_safety_mode != SAFETY_NOOUTPUT) || controls_allowed || (aol_policy != NULL) || (count > 9U)) { return -1; }
|
||||
RxCheck source[9] = {0};
|
||||
safety_config config = {.rx_checks = source, .rx_checks_len = (int)count};
|
||||
const int previous_experience = alternative_experience;
|
||||
alternative_experience = 32;
|
||||
config = honda_stock_aol_configure(0U, false, false, pt_bus, config);
|
||||
const int result = (honda_stock_aol_flag(HONDA_STOCK_ENABLED) ? 1 : 0) |
|
||||
((aol_policy != NULL) ? 2 : 0) | (config.rx_checks_len << 2);
|
||||
alternative_experience = previous_experience;
|
||||
set_safety_hooks(SAFETY_NOOUTPUT, 0U);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -456,7 +456,9 @@ def build_priority_tests(site, catalog, core_tests):
|
||||
"ford": ("ford", "angle_native"),
|
||||
}.get(family, (family,))
|
||||
family_modules = [name for name in sorted(catalog) if any(name == f"test_{alias}.py" or name.startswith(f"test_{alias}_")
|
||||
for alias in aliases)]
|
||||
for alias in aliases) or
|
||||
name.startswith(f"openpilot/starpilot/car/{family}/") or
|
||||
family == "volkswagen" and name == "openpilot/starpilot/aol/tests/test_pq_aol.py"]
|
||||
if family_modules:
|
||||
targets = [test_id for name in family_modules for test_id in catalog[name]]
|
||||
if family == "honda":
|
||||
@@ -535,19 +537,23 @@ def _pytest_id(item):
|
||||
|
||||
def _discover_test_catalog():
|
||||
import pytest
|
||||
from tools.ci.safety_pytest_coverage import RELEASE_ONLY
|
||||
from tools.ci.safety_pytest_coverage import RELEASE_ONLY, targets_for_coverage
|
||||
from tools.ci.run_vehicle_tests import RELEASE_TARGETS
|
||||
if not RELEASE_ONLY.issubset(RELEASE_TARGETS):
|
||||
raise RuntimeError("Release-only mutation dispositions lack a mandatory RELEASE gate")
|
||||
loader = unittest.TestLoader()
|
||||
catalog = {}
|
||||
test_files = [*sorted(SAFETY_TESTS_DIR.glob("test_*.py")), *sorted((BLUEPILOT_SAFETY_DIR / "tests").glob("test_*.py"))]
|
||||
test_files.extend(sorted({ROOT.parent / target.split("::", 1)[0] for target in targets_for_coverage(ROOT.parent)
|
||||
if not (ROOT.parent / target.split("::", 1)[0]).is_relative_to(ROOT)}))
|
||||
keys = {path: path.name if path.is_relative_to(ROOT) else path.relative_to(ROOT.parent).as_posix() for path in test_files}
|
||||
for test_file in test_files:
|
||||
module_name = ".".join(test_file.relative_to(ROOT).with_suffix("").parts)
|
||||
module_root = ROOT if test_file.is_relative_to(ROOT) else ROOT.parent
|
||||
module_name = ".".join(test_file.relative_to(module_root).with_suffix("").parts)
|
||||
suite = loader.loadTestsFromName(module_name)
|
||||
if loader.errors:
|
||||
raise RuntimeError("unittest safety collection failed: " + "\n".join(str(error) for error in loader.errors))
|
||||
catalog[test_file.name] = list(_unittest_ids(suite))
|
||||
catalog[keys[test_file]] = list(_unittest_ids(suite))
|
||||
|
||||
class Collection:
|
||||
def pytest_collection_finish(self, session):
|
||||
@@ -555,11 +561,11 @@ def _discover_test_catalog():
|
||||
if item.cls is None or not issubclass(item.cls, unittest.TestCase):
|
||||
owner = item.path.relative_to(ROOT.parent).as_posix() + "::" + item.nodeid.split("::")[1]
|
||||
if owner not in RELEASE_ONLY:
|
||||
catalog[item.path.name].append(_pytest_id(item))
|
||||
catalog[keys[item.path]].append(_pytest_id(item))
|
||||
|
||||
stream = io.StringIO()
|
||||
with redirect_stdout(stream), redirect_stderr(stream):
|
||||
code = pytest.main(["--collect-only", "-q", "-o", "addopts=", *(str(path) for path in test_files)], plugins=[Collection()])
|
||||
code = pytest.main(["--collect-only", "-q", "--import-mode=importlib", "-o", "addopts=", *(str(path) for path in test_files)], plugins=[Collection()])
|
||||
if code != 0:
|
||||
raise RuntimeError("pytest safety collection failed: " + stream.getvalue()[-32768:])
|
||||
return catalog
|
||||
@@ -621,7 +627,7 @@ def _run_pytest(targets):
|
||||
debug_root = Path(native_builds.enter_context(tempfile.TemporaryDirectory(prefix="mutation-pytest-native-")))
|
||||
native_builds.callback(libsafety_py.load, native_path)
|
||||
native_builds.enter_context(patch.object(libsafety_py, "_build_libsafety", side_effect=fixture_native))
|
||||
code = pytest.main(["-xq", "-o", "addopts=", *(target.removeprefix("pytest:") for target in targets)], plugins=[Results()])
|
||||
code = pytest.main(["-xq", "--import-mode=importlib", "-o", "addopts=", *(target.removeprefix("pytest:") for target in targets)], plugins=[Results()])
|
||||
if code not in (0, 1) or (code == 1 and not failures and not errors):
|
||||
errors.append(f"pytest exit {code}")
|
||||
return TestRun(len(completed), len(skipped), 0, tuple(failures), tuple(errors), stream.getvalue()[-32768:])
|
||||
|
||||
@@ -256,6 +256,14 @@ class TestHondaNidecSafetyBase(HondaBase):
|
||||
values = {"PCM_GAS": pcm_gas, "PCM_SPEED": pcm_speed}
|
||||
return self.packer.make_can_msg_safety("ACC_HUD", 0, values)
|
||||
|
||||
def test_alternate_steering_address_requires_lateral_permission(self):
|
||||
for allowed in (False, True):
|
||||
self.safety.set_controls_allowed(allowed)
|
||||
for torque in (0, 1, 256, 32767, 65535):
|
||||
data = torque.to_bytes(2, "big") + bytes(2)
|
||||
msg = libsafety_py.make_CANPacket(0x194, self.STEER_BUS, data)
|
||||
self.assertEqual(allowed or torque == 0, self._tx(msg), (allowed, torque))
|
||||
|
||||
def test_acc_hud_safety_check(self):
|
||||
for controls_allowed in [True, False]:
|
||||
self.safety.set_controls_allowed(controls_allowed)
|
||||
@@ -366,6 +374,18 @@ class TestHondaBoschSafetyBase(HondaBase):
|
||||
FWD_BLACKLISTED_ADDRS = {2: [0xE4, 0xE5, 0x33D, 0x33DA, 0x33DB]}
|
||||
RELAY_MALFUNCTION_ADDRS = {0: (0xE4, 0xE5, 0x33D, 0x33DA, 0x33DB)} # STEERING_CONTROL, BOSCH_SUPPLEMENTAL_1
|
||||
|
||||
def test_supplemental_control_payload(self):
|
||||
admitted = [0xE5, self.STEER_BUS] in self.TX_MSGS
|
||||
payload = bytes.fromhex("0400801000000000")
|
||||
for allowed in (False, True):
|
||||
self.safety.set_controls_allowed(allowed)
|
||||
for checksum in (0, 1, 127, 255):
|
||||
data = payload[:7] + bytes([checksum])
|
||||
self.assertEqual(admitted, self._tx(libsafety_py.make_CANPacket(0xE5, self.STEER_BUS, data)))
|
||||
for bit in range(56):
|
||||
data = (int.from_bytes(payload, "little") ^ (1 << bit)).to_bytes(8, "little")
|
||||
self.assertFalse(self._tx(libsafety_py.make_CANPacket(0xE5, self.STEER_BUS, data)), (allowed, bit))
|
||||
|
||||
def _alt_brake_msg(self, brake):
|
||||
values = {"BRAKE_PRESSED": brake}
|
||||
return self.packer.make_can_msg_safety("BRAKE_MODULE", self.PT_BUS, values)
|
||||
|
||||
@@ -41,6 +41,26 @@ CASES = (
|
||||
|
||||
|
||||
class TestHondaStockAol(unittest.TestCase):
|
||||
def test_rx_copy_obeys_actual_workspace_capacity(self):
|
||||
safety = libsafety_py.libsafety
|
||||
self.assertEqual(safety.set_safety_hooks(structs.CarParams.SafetyModel.noOutput, 0), 0)
|
||||
for count in range(10):
|
||||
with self.subTest(count=count):
|
||||
self.assertTrue(safety.safety_test_honda_rx_capacity(count))
|
||||
self.assertFalse(safety.get_controls_allowed())
|
||||
|
||||
def test_configuration_shape_respects_rx_and_bus_bounds(self):
|
||||
safety = libsafety_py.libsafety
|
||||
for count in (0, 2, 3, 4, 6, 7, 8, 9):
|
||||
for bus in (0, 1, 2):
|
||||
with self.subTest(count=count, bus=bus):
|
||||
self.assertEqual(safety.set_safety_hooks(structs.CarParams.SafetyModel.noOutput, 0), 0)
|
||||
admitted = 3 <= count <= 6 and bus <= 1
|
||||
length = count + 2 if admitted else count
|
||||
expected = (3 if admitted else 0) | (length << 2)
|
||||
self.assertEqual(safety.safety_test_honda_configuration_bounds(count, bus), expected)
|
||||
self.assertFalse(safety.get_controls_allowed())
|
||||
|
||||
def tearDown(self):
|
||||
# Later safety suites configure hooks before init_tests resets shared experience.
|
||||
libsafety_py.libsafety.set_alternative_experience(0)
|
||||
|
||||
@@ -5,8 +5,10 @@ import importlib.util
|
||||
from collections import Counter
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -432,6 +434,29 @@ def test_function(value):
|
||||
self.assertEqual(catalog[path.name], [legacy.id(), 'pytest:' + str(path) + '::test_function[1]',
|
||||
'pytest:' + str(path) + '::test_function[2]'])
|
||||
|
||||
def test_external_registered_callers_keep_distinct_catalogs_and_family_targets(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
native = root / 'opendbc_repo'
|
||||
native.mkdir()
|
||||
(native / 'test_native_mutation_fixture.py').write_text('def test_baseline():\n assert True\n')
|
||||
paths = [root / 'openpilot/starpilot/car/nissan/tests/test_aol.py',
|
||||
root / 'openpilot/starpilot/car/rivian/tests/test_aol_native.py',
|
||||
root / 'openpilot/starpilot/aol/tests/test_pq_aol.py']
|
||||
for path in paths:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("import pytest\n@pytest.mark.parametrize('value', [1, 2])\ndef test_native(value):\n assert value > 0\n")
|
||||
with patch.object(mutation, 'ROOT', native), patch.object(mutation, 'SAFETY_TESTS_DIR', native), \
|
||||
patch.object(mutation, 'BLUEPILOT_SAFETY_DIR', native / 'absent'), \
|
||||
patch.object(unittest.TestLoader, 'loadTestsFromName', return_value=unittest.TestSuite()), patch.dict(sys.modules):
|
||||
catalog = mutation._discover_test_catalog()
|
||||
self.assertEqual(set(catalog), {'test_native_mutation_fixture.py'} | {path.relative_to(root).as_posix() for path in paths})
|
||||
for family, path in zip(('nissan', 'rivian', 'volkswagen'), paths, strict=True):
|
||||
site = SimpleNamespace(origin_file=native / 'opendbc/safety/modes' / (family + '.h'))
|
||||
expected = ['pytest:' + str(path) + '::test_native[1]', 'pytest:' + str(path) + '::test_native[2]']
|
||||
self.assertEqual(catalog[path.relative_to(root).as_posix()], expected)
|
||||
self.assertEqual(mutation.build_priority_tests(site, catalog, []), expected)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -1594,3 +1594,32 @@ struct LiveTrackingResponseWitness @0xdaa1a9f0d8968e31 {
|
||||
residualRmse @6 :Float64; validUntilMonoTime @7 :UInt64;
|
||||
}
|
||||
|
||||
struct ConditionalModelState {
|
||||
session @0 :Text;
|
||||
requestId @1 :Text;
|
||||
phase @2 :Text;
|
||||
activeModel @3 :Text;
|
||||
highwayModel @4 :Text;
|
||||
cityModel @5 :Text;
|
||||
error @6 :Text;
|
||||
frameMonoTime @7 :UInt64;
|
||||
canSwitch @8 :Bool;
|
||||
processPid @9 :UInt32;
|
||||
processStartTicks @10 :UInt64;
|
||||
sessionStartMonoTime @11 :UInt64;
|
||||
transitionSeconds @12 :Float32;
|
||||
fallbackModel @13 :Text;
|
||||
paused @14 :Bool;
|
||||
targetMode @15 :Text;
|
||||
thresholdMph @16 :UInt16;
|
||||
unavailableReason @17 :Text;
|
||||
}
|
||||
|
||||
struct ConditionalModelAck {
|
||||
session @0 :Text;
|
||||
requestId @1 :Text;
|
||||
holding @2 :Bool;
|
||||
stateMonoTime @3 :UInt64;
|
||||
idle @4 :Bool;
|
||||
}
|
||||
|
||||
|
||||
@@ -2637,6 +2637,8 @@ struct Event {
|
||||
aolSafetyWire @124 :Data;
|
||||
aolIntentWire @125 :Data;
|
||||
laneChangeAssistWire @126 :Data;
|
||||
conditionalModelState @154 :Custom.ConditionalModelState;
|
||||
conditionalModelAck @155 :Custom.ConditionalModelAck;
|
||||
|
||||
# DO change the name of the field and struct
|
||||
# DON'T change the ID (e.g. @107)
|
||||
|
||||
@@ -70,6 +70,8 @@ _services: dict[str, tuple] = {
|
||||
"aolSafetyWire": (True, 10., 10),
|
||||
"aolIntentWire": (True, 100., 10),
|
||||
"laneChangeAssistWire": (True, 20., 10),
|
||||
"conditionalModelState": (True, 20., 1),
|
||||
"conditionalModelAck": (True, 100., 10),
|
||||
"mapdOut": (True, 20., 10),
|
||||
"mapdExtendedOut": (True, 1., 1),
|
||||
"mapdIn": (True, 1., 1),
|
||||
|
||||
@@ -211,7 +211,7 @@ def clear_partition_hash(target_slot_number: int, partition: dict) -> None:
|
||||
os.sync()
|
||||
|
||||
|
||||
def extract_compressed_image(target_slot_number: int, partition: dict, cloudlog):
|
||||
def extract_compressed_image(target_slot_number: int, partition: dict, cloudlog, progress=None):
|
||||
path = get_partition_path(target_slot_number, partition)
|
||||
downloader = StreamingDecompressor(partition['url'])
|
||||
|
||||
@@ -227,6 +227,8 @@ def extract_compressed_image(target_slot_number: int, partition: dict, cloudlog)
|
||||
if p != last_p:
|
||||
last_p = p
|
||||
print(f"Installing {partition['name']}: {p}", flush=True)
|
||||
if progress is not None:
|
||||
progress(f"Downloading and writing AGNOS {partition['name']}", p)
|
||||
|
||||
if raw_hash.hexdigest().lower() != partition['hash_raw'].lower():
|
||||
raise Exception(f"Raw hash mismatch '{raw_hash.hexdigest().lower()}'")
|
||||
@@ -240,7 +242,7 @@ def extract_compressed_image(target_slot_number: int, partition: dict, cloudlog)
|
||||
os.sync()
|
||||
|
||||
|
||||
def flash_partition(target_slot_number: int, partition: dict, cloudlog, standalone=False):
|
||||
def flash_partition(target_slot_number: int, partition: dict, cloudlog, standalone=False, progress=None):
|
||||
cloudlog.info(f"Downloading and writing {partition['name']}")
|
||||
|
||||
if verify_partition(target_slot_number, partition):
|
||||
@@ -254,7 +256,7 @@ def flash_partition(target_slot_number: int, partition: dict, cloudlog, standalo
|
||||
|
||||
path = get_partition_path(target_slot_number, partition)
|
||||
|
||||
extract_compressed_image(target_slot_number, partition, cloudlog)
|
||||
extract_compressed_image(target_slot_number, partition, cloudlog, progress=progress)
|
||||
|
||||
# Write hash after successful flash
|
||||
if not full_check:
|
||||
@@ -278,7 +280,7 @@ def swap(manifest_path: str, target_slot_number: int, cloudlog) -> None:
|
||||
cloudlog.error(f"Swap failed {out}")
|
||||
|
||||
|
||||
def flash_agnos_update(manifest_path: str, target_slot_number: int, cloudlog, standalone=False) -> None:
|
||||
def flash_agnos_update(manifest_path: str, target_slot_number: int, cloudlog, standalone=False, progress=None) -> None:
|
||||
update = load_manifest(manifest_path)
|
||||
|
||||
cloudlog.info(f"Target slot {target_slot_number}")
|
||||
@@ -291,7 +293,9 @@ def flash_agnos_update(manifest_path: str, target_slot_number: int, cloudlog, st
|
||||
|
||||
for retries in range(10):
|
||||
try:
|
||||
flash_partition(target_slot_number, partition, cloudlog, standalone)
|
||||
if progress is not None:
|
||||
progress(f"Downloading and verifying AGNOS {partition['name']}", None)
|
||||
flash_partition(target_slot_number, partition, cloudlog, standalone, progress=progress)
|
||||
success = True
|
||||
break
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ from ipaddress import IPv4Address, AddressValueError
|
||||
from enum import Enum
|
||||
|
||||
from openpilot.common.esim.base import WEBBING_ICCID_PREFIX
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -302,6 +303,8 @@ class Modem:
|
||||
return lines
|
||||
except (RuntimeError, TimeoutError, OSError) as e:
|
||||
logging.info(f"AT {cmd} failed: {e}")
|
||||
if cmd in (*AT_INIT, "AT+CGMI", "AT+CGSN", "AT+QCCID", "AT+CIMI", "AT+GMR"):
|
||||
cloudlog.error(f"modem: {cmd} failed: {e}")
|
||||
return []
|
||||
finally:
|
||||
fcntl.flock(fd, fcntl.LOCK_UN)
|
||||
@@ -364,7 +367,7 @@ class Modem:
|
||||
fcntl.flock(fd, fcntl.LOCK_UN)
|
||||
os.close(fd)
|
||||
if len(ports) != 2:
|
||||
logging.warning(f"found AT ports {ports} in {ttys}, retrying")
|
||||
cloudlog.warning(f"modem: found AT ports {ports} in {ttys}, retrying")
|
||||
return False
|
||||
|
||||
for link, tty in zip((AT_PORT, PPP_PORT), reversed(ports), strict=True):
|
||||
@@ -383,12 +386,13 @@ class Modem:
|
||||
return State.INITIALIZING
|
||||
|
||||
if not self._init_at_channel():
|
||||
logging.warning("AT echo still on, retrying")
|
||||
cloudlog.error("modem: AT channel initialization failed, retrying")
|
||||
return State.INITIALIZING
|
||||
|
||||
identity = self._read_identity()
|
||||
if not identity["iccid"] or not identity["imei"]:
|
||||
logging.warning(f"identity read incomplete: {identity}, retrying")
|
||||
cloudlog.error("modem: identity read incomplete: imei_present=%s iccid_present=%s, retrying",
|
||||
bool(identity["imei"]), bool(identity["iccid"]))
|
||||
return State.INITIALIZING
|
||||
|
||||
self._configure_modem(identity["modem_version"])
|
||||
@@ -659,7 +663,7 @@ class Modem:
|
||||
self._publish_state(state=state.value)
|
||||
logging.info(f"{prev.value} -> {state.value}")
|
||||
except Exception:
|
||||
logging.exception(f"error in {state.value}")
|
||||
cloudlog.exception(f"modem: error in {state.value}")
|
||||
state = State.DISCONNECTING
|
||||
time.sleep(STATE_WAIT)
|
||||
|
||||
|
||||
@@ -181,3 +181,20 @@ def test_explicit_incompatible_manual_manifest_is_not_replaced(tmp_path, release
|
||||
with patch.object(agnos, 'DEVICE_MODEL_PATH', model):
|
||||
with pytest.raises(RuntimeError, match='incompatible with comma 3'):
|
||||
agnos.load_manifest(str(manual))
|
||||
|
||||
|
||||
def test_agnos_download_reports_partition_progress(tmp_path):
|
||||
import hashlib
|
||||
|
||||
data = b'firmware'
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
partition = {'name': 'system', 'url': 'https://example.invalid/system.xz', 'size': len(data), 'sparse': False, 'hash': digest, 'hash_raw': digest}
|
||||
downloader = Mock(sha256=hashlib.sha256(data))
|
||||
downloader.read.side_effect = [data[:4], data[4:], b'']
|
||||
progress = Mock()
|
||||
with patch.object(agnos, 'get_partition_path', return_value=str(tmp_path / 'partition')), \
|
||||
patch.object(agnos, 'StreamingDecompressor', return_value=downloader), patch.object(agnos.os, 'sync'):
|
||||
agnos.extract_compressed_image(1, partition, Mock(), progress=progress)
|
||||
assert [call.args for call in progress.call_args_list] == [
|
||||
('Downloading and writing AGNOS system', 50), ('Downloading and writing AGNOS system', 100)]
|
||||
assert (tmp_path / 'partition').read_bytes() == data
|
||||
|
||||
@@ -536,6 +536,7 @@ class Car:
|
||||
cancel_boot_ns = (time.clock_gettime_ns(time.CLOCK_BOOTTIME)
|
||||
if (getattr(self.CI.CS, 'ev6_aol_source_healthy', False) or
|
||||
qualified_honda_stock_aol(self.CP, marked_only=True) or
|
||||
self.CP.brand == 'volkswagen' and self.CP.openpilotLongitudinalControl or
|
||||
qualified_gm(self.CP) and (is_bolt_present_no_acc_pedal_profile(self.CP) or
|
||||
f1_conventional_lateral_owner(self.CP)) and
|
||||
int(self.CP.alternativeExperience) in (32, 96)) else 0)
|
||||
@@ -892,6 +893,10 @@ class Car:
|
||||
def aol_cancel_source(self, CS, now_ns: int) -> int:
|
||||
"""Bind Cancel to this parsed CAN batch and its local monotonic receipt."""
|
||||
observation = getattr(self, '_aol_can_observation', None)
|
||||
if self.CP.brand == 'volkswagen':
|
||||
from opendbc.car import Bus
|
||||
from openpilot.starpilot.car.volkswagen.aol import cancel_source
|
||||
return cancel_source(self.CP, CS, self.CI.can_parsers[Bus.pt], observation, now_ns)
|
||||
if getattr(getattr(self, 'CP', None), 'brand', '') == 'honda' and qualified_honda_stock_aol(self.CP, marked_only=True):
|
||||
from opendbc.car import Bus
|
||||
parser = self.CI.can_parsers[Bus.pt]
|
||||
|
||||
@@ -316,8 +316,11 @@ def main(demo=False):
|
||||
# a Jetson, PC or phone on the port looks like a chestnut to cable_connected(): the cable counts with Jetlink off only
|
||||
chestnut_available = chestnut_present() or (cable_connected() and not jetlink_adapter.link_on() and not usb_host_connected())
|
||||
recovery_small_only = os.getenv("STARPILOT_MODELD_RECOVERY_SMALL_ONLY") == "1"
|
||||
selection = resolve_runtime(chestnut_available=chestnut_available and not recovery_small_only, randomize=not recovery_small_only)
|
||||
requested_model_id = requested_runtime_id(chestnut_available)
|
||||
recovery_model = os.getenv('STARPILOT_CONDITIONAL_RECOVERY_MODEL') if recovery_small_only else None
|
||||
recovery_options = {'small_override': recovery_model} if recovery_model else {}
|
||||
selection = resolve_runtime(chestnut_available=chestnut_available and not recovery_small_only,
|
||||
randomize=not recovery_small_only, **recovery_options)
|
||||
requested_model_id = recovery_model or requested_runtime_id(chestnut_available)
|
||||
from openpilot.starpilot.models.laboratory import freeze_request
|
||||
from openpilot.starpilot.models.laboratory_runner import LaboratoryPair, load_laboratory_pair
|
||||
from openpilot.starpilot.models.runtime_bridge.runtime import bind_laboratory_request
|
||||
@@ -454,6 +457,14 @@ def main(demo=False):
|
||||
initial_chestnut_fallback = CHESTNUT and model is None
|
||||
if model is None:
|
||||
model = small_model
|
||||
from openpilot.starpilot.models.manager import preferences
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelRuntime
|
||||
conditional_runtime = ConditionalModelRuntime(small_model, small_prepared, preferences(MODEL_ROOT)['conditionalModel'],
|
||||
root=MODEL_ROOT, cam_w=cam_w, cam_h=cam_h,
|
||||
enabled=model is small_model and not CHESTNUT and not jetlink_adapter.link_on() and not recovery_small_only)
|
||||
conditional_loaded_id = small_model.model_id
|
||||
if recovery_small_only and conditional_runtime.config['enabled']:
|
||||
conditional_runtime.owner.error = 'Single-model recovery is running; live switching is disabled until the next drive'
|
||||
if isinstance(model, LaboratoryPair):
|
||||
import hashlib
|
||||
import json
|
||||
@@ -462,7 +473,7 @@ def main(demo=False):
|
||||
else:
|
||||
receipt_owner.loaded(big_prepared if model.chestnut else small_prepared,
|
||||
ModelVariant.CHESTNUT if model.chestnut else ModelVariant.SMALL,
|
||||
"chestnut-run-stalled" if recovery_small_only else
|
||||
"conditional-switch-failed" if recovery_model else "chestnut-run-stalled" if recovery_small_only else
|
||||
"chestnut-load-failed" if initial_chestnut_fallback else
|
||||
"selected-load-failed" if (selected_small_failed and not model.chestnut) or requested_model_id != model.model_id else None,
|
||||
model_id=model.model_id)
|
||||
@@ -485,10 +496,11 @@ def main(demo=False):
|
||||
config_realtime_process(7, 54)
|
||||
|
||||
# messaging
|
||||
pub_socks = ["modelIdentity", "modelV2", "drivingModelData", "cameraOdometry", "laneChangeAssistWire"] + (["chestnutGpuState"] if CHESTNUT else [])
|
||||
pub_socks = (["modelIdentity", "modelV2", "drivingModelData", "cameraOdometry", "laneChangeAssistWire", "conditionalModelState"] +
|
||||
(["chestnutGpuState"] if CHESTNUT else []))
|
||||
pm = PubMaster(pub_socks)
|
||||
sm = SubMaster(["deviceState", "carState", "narrowRoadCameraState", "extrinsicsCalibration", "driverMonitoringState",
|
||||
"carControl", "controlsState", "lateralDelay", "starpilotNavigation", "longitudinalPlan"])
|
||||
"carControl", "controlsState", "lateralDelay", "starpilotNavigation", "longitudinalPlan", "selfdriveState"])
|
||||
|
||||
publish_state = PublishState()
|
||||
params = Params()
|
||||
@@ -557,6 +569,13 @@ def main(demo=False):
|
||||
meta_extra = meta_main
|
||||
|
||||
sm.update(0)
|
||||
handoff = conditional_runtime.before_frame(sm)
|
||||
if handoff is not None:
|
||||
model, small_prepared, _ = handoff
|
||||
prev_action = log.ModelDataV2.Action(desiredCurvature=float(sm['controlsState'].curvature))
|
||||
DH = DesireHelper(runtime_lane_policy)
|
||||
frame_dropped_filter.x = 0.
|
||||
run_count = 0
|
||||
turn_models = (model.lateral, model.longitudinal) if isinstance(model, LaboratoryPair) else (model,)
|
||||
turn_supported = all(state.npy.get('desire') is not None and state.npy['desire'].shape[-1] == 8 for state in turn_models)
|
||||
desire = navigation_turn.select(sm, time.monotonic_ns(), DH.desire,
|
||||
@@ -617,30 +636,46 @@ def main(demo=False):
|
||||
model.lat_delay = lat_delay
|
||||
model.frame_drop_ratio = frame_drop_ratio
|
||||
mt1 = time.perf_counter()
|
||||
conditional_action = None
|
||||
try:
|
||||
send_chestnut = (chestnut_state is not None and
|
||||
run_count % round(ModelConstants.MODEL_RUN_FREQ / SERVICE_LIST['chestnutGpuState'].frequency) == 0)
|
||||
model_output = model.run(bufs, transforms, inputs, chestnut_state.send if send_chestnut else None)
|
||||
if conditional_runtime.owner.phase == 'switching':
|
||||
conditional_action = model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego)
|
||||
laboratory_action = (model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego)
|
||||
if isinstance(model, LaboratoryPair) else None)
|
||||
except Exception:
|
||||
if not model.chestnut:
|
||||
if conditional_runtime.owner.phase == 'switching':
|
||||
cloudlog.exception('Conditional Model candidate failed; retaining the previous model')
|
||||
conditional_runtime.owner.abort('Candidate inference failed; previous model restored', time.monotonic_ns())
|
||||
model, small_prepared, _ = conditional_runtime.owner.models[conditional_runtime.owner.active]
|
||||
prev_action = log.ModelDataV2.Action(desiredCurvature=float(sm['controlsState'].curvature))
|
||||
DH = DesireHelper(runtime_lane_policy)
|
||||
conditional_action = None
|
||||
model.lat_delay, model.frame_drop_ratio = lat_delay, frame_drop_ratio
|
||||
model_output = model.run(bufs, transforms, inputs)
|
||||
elif not model.chestnut:
|
||||
raise
|
||||
# fallback to small model
|
||||
fallback_reason = "chestnut-load-failed"
|
||||
if model is jetlink_model:
|
||||
model.close()
|
||||
fallback_reason = None
|
||||
else:
|
||||
drop_chestnut()
|
||||
params.put_bool("ChestnutActive", False)
|
||||
cloudlog.exception("big model failed, fall back to small")
|
||||
model = small_model
|
||||
receipt_owner.loaded(small_prepared, ModelVariant.SMALL, fallback_reason, model_id=model.model_id)
|
||||
if chestnut_state is not None:
|
||||
chestnut_state.big = False
|
||||
run_count = 0
|
||||
model_output = None
|
||||
# Existing Chestnut/Jetlink fallback is owned below.
|
||||
model_output = None
|
||||
if model.chestnut:
|
||||
# fallback to small model
|
||||
fallback_reason = "chestnut-load-failed"
|
||||
if model is jetlink_model:
|
||||
model.close()
|
||||
fallback_reason = None
|
||||
else:
|
||||
drop_chestnut()
|
||||
params.put_bool("ChestnutActive", False)
|
||||
cloudlog.exception("big model failed, fall back to small")
|
||||
model = small_model
|
||||
receipt_owner.loaded(small_prepared, ModelVariant.SMALL, fallback_reason, model_id=model.model_id)
|
||||
if chestnut_state is not None:
|
||||
chestnut_state.big = False
|
||||
run_count = 0
|
||||
model_output = None
|
||||
mt2 = time.perf_counter()
|
||||
model_execution_time = mt2 - mt1
|
||||
if model is jetlink_model and HOOKS.handed_over(model):
|
||||
@@ -653,6 +688,11 @@ def main(demo=False):
|
||||
cloudlog.event("jetlinkHandover", state=HOOKS.state(model), handovers=model.handovers)
|
||||
|
||||
if model_output is not None and vipc_dropped_frames == 0:
|
||||
if conditional_runtime.owner.models and model.model_id != conditional_loaded_id:
|
||||
small_model = model
|
||||
receipt_owner.loaded(small_prepared, ModelVariant.SMALL, model_id=model.model_id)
|
||||
cloudlog.event('conditionalModelHandover', model_id=model.model_id, request=conditional_runtime.owner.request)
|
||||
conditional_loaded_id = model.model_id
|
||||
modelv2_send = messaging.new_message('modelV2')
|
||||
drivingdata_send = messaging.new_message('drivingModelData')
|
||||
posenet_send = messaging.new_message('cameraOdometry')
|
||||
@@ -661,7 +701,8 @@ def main(demo=False):
|
||||
assert laboratory_action is not None
|
||||
action = laboratory_action
|
||||
else:
|
||||
action = model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego)
|
||||
action = (conditional_action if conditional_action is not None else
|
||||
model.get_action_from_model(model_output, prev_action, lat_action_t, long_action_t, v_ego))
|
||||
filter_action(action, prev_action, v_ego, subaru_tau + volkswagen_tau + kona_tau)
|
||||
prev_action = action
|
||||
fill_model_msg(modelv2_send, model_output, action,
|
||||
@@ -719,6 +760,9 @@ def main(demo=False):
|
||||
pm.send('laneChangeAssistWire', lane_status_msg)
|
||||
pm.send('drivingModelData', drivingdata_send)
|
||||
pm.send('cameraOdometry', posenet_send)
|
||||
settled_frame = (model_output is not None and vipc_dropped_frames == 0 and
|
||||
modelv2_send.valid and drivingdata_send.valid and posenet_send.valid)
|
||||
conditional_runtime.publish(pm, sm, int(modelv2_send.logMonoTime) if settled_frame else 0)
|
||||
last_vipc_frame_id = meta_main.frame_id
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -234,6 +234,8 @@ class SelfdriveD:
|
||||
self.initialized = False
|
||||
self.enabled = False
|
||||
self.active = False
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelGate
|
||||
self.conditional_model_gate = ConditionalModelGate()
|
||||
self.mismatch_counter = 0
|
||||
self.cruise_mismatch_counter = 0
|
||||
self.last_steering_pressed_frame = 0
|
||||
@@ -566,9 +568,10 @@ class SelfdriveD:
|
||||
|
||||
from openpilot.starpilot.car.hyundai.aol import source_deadline_supported
|
||||
input_proof = getattr(self, 'aol_step_input_proof', None)
|
||||
from opendbc.car.mazda.stock_aol import qualified as qualified_mazda
|
||||
reconcile_input = bool(input_proof is not None and not REPLAY and self.aol_replay and self.axis_transport_required and
|
||||
(source_deadline_supported(self.CP) or self.ford_source_deadline_supported() or
|
||||
getattr(self, 'hybrid_input_reconcile', False)) and
|
||||
qualified_mazda(self.CP, marked_only=True) or getattr(self, 'hybrid_input_reconcile', False)) and
|
||||
input_proof[0] == self.aol_session_id and
|
||||
(input_proof[8] or input_proof[9]))
|
||||
self.aol_event_input_reconcile = reconcile_input
|
||||
@@ -1299,6 +1302,8 @@ class SelfdriveD:
|
||||
for alert_type in DEPARTURE_ALERTS:
|
||||
if alert_type not in retained_types:
|
||||
self.AM.alerts.pop(alert_type, None)
|
||||
if getattr(self, 'conditional_model_gate', None) is not None:
|
||||
self.conditional_model_gate.update_alerts(alerts, self.AM, self.sm.frame)
|
||||
self.AM.add_many(self.sm.frame, alerts)
|
||||
self.AM.process_alerts(self.sm.frame, clear_event_types)
|
||||
from openpilot.starpilot.audio.availability_warning import AvailabilityWarningDelivery
|
||||
@@ -2311,6 +2316,10 @@ class SelfdriveD:
|
||||
self.events.add(EventName.controlsMismatch)
|
||||
lost_active_aol |= pause
|
||||
was_enabled = self.enabled
|
||||
conditional_gate = getattr(self, 'conditional_model_gate', None)
|
||||
conditional_hold = conditional_gate.step(self, CS) if conditional_gate is not None else False
|
||||
if conditional_hold:
|
||||
self.events.add(EventName.selfdriveInitializing)
|
||||
if self.aol_replay and source_current and was_enabled and (
|
||||
CS.doorOpen or any(event in LONGITUDINAL_ONLY_EVENTS for event in self.events.names)):
|
||||
# Ordinary cruise is withdrawn; its legacy permission is no longer expected.
|
||||
@@ -2405,6 +2414,8 @@ class SelfdriveD:
|
||||
if (getattr(self, 'hkg_angle_steering', False) and self.aol_axis_decision.lateral_active and
|
||||
EventName.steerSaturated in self.events.names and ET.WARNING not in self.state_machine.current_alert_types):
|
||||
self.state_machine.current_alert_types.append(ET.WARNING)
|
||||
if conditional_hold:
|
||||
self.aol_axis_decision = AxisDecision()
|
||||
axis_published = bool(not REPLAY and self.aol_replay and self.axis_transport_required)
|
||||
if axis_published:
|
||||
self.aol_axis_publication_deferred = bool(not previous_deferred and self.defer_expired_axis_publication(CS, initial_state))
|
||||
|
||||
@@ -29,6 +29,7 @@ class Sources:
|
||||
self.recv_frame = dict.fromkeys(self.data, self.frame)
|
||||
self.recv_frame['alertDebug'] = self.recv_frame['lateralManeuverPlan'] = 0
|
||||
self.logMonoTime = dict.fromkeys(self.data, 100_000_000_000)
|
||||
self.services = list(self.data)
|
||||
self['controlsState'].lateralControlState.init('pidState')
|
||||
self['extrinsicsCalibration'].calStatus = log.ExtrinsicsCalibration.Status.calibrated
|
||||
self['deviceState'].freeSpacePercent = 100
|
||||
@@ -79,7 +80,7 @@ def events_drive():
|
||||
|
||||
@pytest.mark.parametrize('fault,event', [('comm', EventName.commIssue),
|
||||
('posenet', EventName.posenetInvalid), ('localizer', EventName.locationdTemporaryError),
|
||||
('can', EventName.canError), ('radar', EventName.canError), ('process', EventName.processNotRunning)])
|
||||
('can', EventName.canError), ('radar', EventName.radarFault), ('process', EventName.processNotRunning)])
|
||||
def test_real_selfdrived_faults_survive_jetlink_swap(fault, event):
|
||||
drive, cs = events_drive()
|
||||
with patch('openpilot.selfdrive.selfdrived.helpers.time.monotonic', return_value=100.):
|
||||
|
||||
@@ -91,6 +91,7 @@ def test_sonata_cancel_source_requires_current_real_parser_batch(role):
|
||||
observed = state.as_reader().as_builder() if role == 'foreign_state' else state
|
||||
receipt = now - 30_000_001 if role == 'expired_receipt' else now
|
||||
caller = Car.__new__(Car)
|
||||
caller.CP = cp
|
||||
caller.CI = ci
|
||||
caller._aol_can_observation = (observed, receipt, now, now)
|
||||
assert (caller.aol_cancel_source(state, now) == now) == (role == 'marked')
|
||||
|
||||
@@ -239,7 +239,7 @@ def test_shared_cancel_source_is_actual_parser_evidence(role):
|
||||
if role == 'wrong_bus':
|
||||
state.buttonEvents = [structs.CarState.ButtonEvent(type='cancel', pressed=True)]
|
||||
received = now - 30_000_001 if role == 'expired_receipt' else now
|
||||
caller = NS(CI=ci, _aol_can_observation=(state, received, now, now))
|
||||
caller = NS(CP=cp, CI=ci, _aol_can_observation=(state, received, now, now))
|
||||
source = Car.aol_cancel_source(cast(Car, caller), state, now)
|
||||
assert (source == now) == (role == 'marked')
|
||||
assert source == 0 or ci.CS.ev6_aol_source_healthy
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
from collections import deque
|
||||
from contextlib import ExitStack
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
from opendbc.car import gen_empty_fingerprint
|
||||
from opendbc.car.mazda.interface import CarInterface
|
||||
from opendbc.car.mazda.values import CAR
|
||||
from openpilot.cereal import log, messaging
|
||||
from openpilot.common.prefix import OpenpilotPrefix
|
||||
from openpilot.starpilot.aol.tests import test_ioniq_availability as fixture
|
||||
from openpilot.starpilot.aol.tests.test_carstate_queue import message
|
||||
from openpilot.starpilot.aol.tests.test_input_deadline_continuity import BASE, intent
|
||||
|
||||
|
||||
@pytest.mark.parametrize('identity', (CAR.MAZDA_CX5_2022, CAR.MAZDA_CX9_2021))
|
||||
@pytest.mark.parametrize('pulse', ('healthy', 'cancel', 'permanent_eps', 'invalid_can'))
|
||||
def test_mazda_consumes_input_arriving_during_car_event_work(identity, pulse):
|
||||
with OpenpilotPrefix(), ExitStack() as cleanup:
|
||||
case = fixture.IoniqAvailabilityTests(methodName='runTest')
|
||||
cleanup.callback(case.doCleanups)
|
||||
cp = CarInterface.get_params(identity, gen_empty_fingerprint(), [], False, False, False)
|
||||
sd, _, drive = case._authority_callers(True, cp=cp, genuine_events=True)
|
||||
state = fixture.car_state()
|
||||
state.cruiseState.available = state.cruiseState.enabled = True
|
||||
options = {'observed_state': state, 'native_request_long': False, 'long_allowed': False, 'panda_controls_allowed': True}
|
||||
drive(0, **options)
|
||||
old, _, command = drive(2, state_stamp=BASE, offset_ns=4_237_448, intent_message=intent(BASE, 3), **options)
|
||||
assert old.lateralActive and command.latActive and not command.longActive
|
||||
now = [BASE + 27_000_000]
|
||||
queue, wires = deque(), deque()
|
||||
original_receive, original_update = messaging.recv_one_or_none, sd._update_car_event_sample
|
||||
visited = []
|
||||
|
||||
def receive(sock):
|
||||
if sock is sd.car_state_sock:
|
||||
return queue.popleft() if queue else None
|
||||
if sock is sd.aol_intent_companion.sock:
|
||||
return wires.popleft() if wires else None
|
||||
return original_receive(sock)
|
||||
|
||||
def update(sample, previous):
|
||||
result = original_update(sample, previous)
|
||||
visited.append(float(sample.vEgo))
|
||||
if len(visited) == 1:
|
||||
late = state.as_reader().as_builder()
|
||||
late.vEgo = 25.0
|
||||
if pulse == 'cancel':
|
||||
late.buttonEvents = [{'type': 'cancel', 'pressed': True}]
|
||||
elif pulse == 'permanent_eps':
|
||||
late.steerFaultPermanent = True
|
||||
stamp = BASE + 35_000_000
|
||||
queue.append(message(stamp, late, valid=pulse != 'invalid_can'))
|
||||
wires.append(intent(stamp, 4).as_reader())
|
||||
now[0] = BASE + 38_846_614
|
||||
return result
|
||||
|
||||
with mock.patch('openpilot.selfdrive.selfdrived.selfdrived.time.monotonic_ns', side_effect=lambda: now[0]), \
|
||||
mock.patch('openpilot.selfdrive.selfdrived.selfdrived.messaging.recv_one_or_none', side_effect=receive), \
|
||||
mock.patch.object(sd, '_update_car_event_sample', side_effect=update):
|
||||
axis, _, command = drive(4, state_stamp=BASE, offset_ns=7_000_000, intent_message=intent(BASE, 3), **options)
|
||||
assert not queue and visited == [20.0, 25.0]
|
||||
assert not command.longActive
|
||||
if pulse == 'healthy':
|
||||
assert axis.sourceCarStateMonoTime == BASE + 35_000_000
|
||||
assert log.OnroadEvent.EventName.controlsMismatch not in sd.events.names
|
||||
assert not sd.aol_authority_lost
|
||||
elif pulse == 'cancel':
|
||||
assert log.OnroadEvent.EventName.controlsMismatch not in sd.events.names
|
||||
assert not sd.aol_authority_lost
|
||||
assert log.OnroadEvent.EventName.buttonCancel in sd.events.names
|
||||
assert not sd.enabled
|
||||
elif pulse == 'permanent_eps':
|
||||
assert not command.latActive
|
||||
else:
|
||||
assert axis.sourceCarStateMonoTime == 0 and not command.latActive
|
||||
|
||||
if pulse in ('healthy', 'cancel'):
|
||||
fresh = BASE + 45_000_000
|
||||
axis, _, command = drive(6, state_stamp=fresh, offset_ns=10_000_000, intent_message=intent(fresh, 5), **options)
|
||||
assert axis.sourceCarStateMonoTime == fresh and command.latActive
|
||||
assert not command.longActive and not sd.aol_authority_lost
|
||||
@@ -39,7 +39,8 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
|
||||
cancel_steering=True, cancel_axis_expiry=False, startup_event_delay=0,
|
||||
startup_delivery_delay=0, startup_delivery_services=(), receipt_sink=None,
|
||||
route2c_start=False, startup_block_until=0, startup_expect_expiry=False,
|
||||
startup_probe_denials=False, startup_stall=None, startup_stall_mode='frozen'):
|
||||
startup_probe_denials=False, startup_stall=None, startup_stall_mode='frozen',
|
||||
startup_floor_dip=False, cancel_delivery_delay=0):
|
||||
pq = candidate == CAR.VOLKSWAGEN_SHARAN_MK2
|
||||
with ExitStack() as cleanup:
|
||||
cleanup.enter_context(OpenpilotPrefix())
|
||||
@@ -165,6 +166,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
|
||||
request = 0
|
||||
startup_vetoes_checked = False
|
||||
route2c_denials_checked = False
|
||||
floor_vetoes_checked = False
|
||||
reverse_event_vetoes_checked = False
|
||||
cancel_join_vetoes_checked = False
|
||||
for tick in range(120):
|
||||
@@ -179,7 +181,8 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
|
||||
assert not quiet.get_controls_allowed()
|
||||
assert native.get_current_safety_mode() != quiet.get_current_safety_mode()
|
||||
|
||||
brake = (60 if early_brake else 65) <= tick < 75 or (brake_held_engagement and tick < 29) or (reverse_boot and not reverse_unbraked and tick < 40)
|
||||
brake = (((60 if early_brake else 65) <= tick < 75 and not startup_floor_dip) or
|
||||
(brake_held_engagement and tick < 29) or (reverse_boot and not reverse_unbraked and tick < 40))
|
||||
reverse = 85 <= tick < 95 or (reverse_boot and tick < 35)
|
||||
if route2c_start:
|
||||
reverse = 20 <= tick < 35 or 85 <= tick < 95
|
||||
@@ -203,6 +206,9 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
|
||||
'GRA_Tip_Setzen': int(engage_on_set and (tick in (20, 50) if creep_start else tick == 20))},
|
||||
'ACC_02': {'ACC_Gesetzte_Zeitluecke': 1},
|
||||
}
|
||||
if startup_floor_dip and 39 <= tick < 48:
|
||||
overrides['ESP_19'] = dict.fromkeys(('ESP_VL_Radgeschw_02', 'ESP_VR_Radgeschw_02',
|
||||
'ESP_HL_Radgeschw_02', 'ESP_HR_Radgeschw_02'), 0)
|
||||
if pq:
|
||||
overrides = {
|
||||
'Motor_2': {'MO2_Sta_GRA': int(ordinary and not alpha), 'MO2_BLS': int(brake)},
|
||||
@@ -284,6 +290,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
|
||||
assert not waiting(cs=bad)
|
||||
for field, value in (('failed', True), ('paused', True), ('pending_event', now),
|
||||
('sequence', card.sm['aolAxisState'].sequence + 1), ('cp', ('foreign',))):
|
||||
assert feedback is not None
|
||||
bad_feedback = copy(feedback)
|
||||
setattr(bad_feedback, field, value)
|
||||
assert not waiting(tracker=bad_feedback), field
|
||||
@@ -325,6 +332,9 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
|
||||
reverse_event_vetoes_checked = True
|
||||
assert owner.startup_arm_ns == anchor
|
||||
startup_vetoes_checked = True
|
||||
if startup_floor_dip and getattr(card.aol_card_intent, 'startup_floor_pending', False) and not floor_vetoes_checked:
|
||||
assert_floor_recovery_vetoes(card, state, now)
|
||||
floor_vetoes_checked = True
|
||||
if startup_probe_denials and not route2c_denials_checked and card.aol_card_intent.startup_ready:
|
||||
assert_readiness_denials(card, state, now)
|
||||
route2c_denials_checked = True
|
||||
@@ -338,6 +348,10 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
|
||||
'authority_message': card.pm.messages['starpilotCarState'].as_builder() if 'starpilotCarState' in card.pm.messages else None,
|
||||
'companion': 'starpilotCarState' in card.pm.messages,
|
||||
'timeout': stalled and startup_stall_mode == 'frozen-timeout'} if startup_stall is not None else {}))
|
||||
if startup_floor_dip and state.vEgo <= cp.minSteerSpeed:
|
||||
assert not command.latActive and not command.longActive
|
||||
if startup_floor_dip and command.latActive and not card.aol_card_intent.startup_granted:
|
||||
assert now <= card.aol_card_intent.startup_arm_ns + 200_000_000
|
||||
if early_brake and tick == 60:
|
||||
assert not state.brakePressed and state.steeringPressed
|
||||
if pq_real_fault:
|
||||
@@ -380,7 +394,12 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
|
||||
bad_sources = copy(card.sm)
|
||||
bad_sources.logMonoTime = dict(card.sm.logMonoTime)
|
||||
bad_sources.logMonoTime['onroadEvents'] = now - 30_000_001
|
||||
assert retained(sources=bad_sources) is None
|
||||
assert feedback is not None
|
||||
bad_feedback = copy(feedback)
|
||||
bad_feedback.longitudinal_cancel_ns = 0
|
||||
assert retained(sources=bad_sources, feedback=bad_feedback) is None
|
||||
if feedback.longitudinal_cancel_ns:
|
||||
assert retained(sources=bad_sources) is not None
|
||||
cancel_join_vetoes_checked = True
|
||||
if cancel_axis_expiry and tick == 58:
|
||||
assert not card.aol_card_intent.allowed_latch
|
||||
@@ -434,6 +453,8 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
|
||||
frames = [message for message in frames if message.which() not in startup_delivery_services]
|
||||
if startup_event_delay and 35 <= tick < 35 + startup_event_delay:
|
||||
frames = [message for message in frames if message.which() != 'onroadEvents']
|
||||
if cancel_delivery_delay and 55 <= tick < 55 + cancel_delivery_delay:
|
||||
frames = [message for message in frames if message.which() not in ('aolAxisState', 'onroadEvents')]
|
||||
if cancel_axis_delay and 55 <= tick < 55 + cancel_axis_delay:
|
||||
frames = [message for message in frames if message.which() != 'aolAxisState']
|
||||
card.sm.update_msgs(now / 1e9, frames)
|
||||
@@ -518,7 +539,7 @@ def test_mqb_full_engagement_brake_reverse_drive_actual_callers(gearbox, alpha,
|
||||
assert not any(lat_commands[35:]) and not any(long_commands)
|
||||
assert card.aol_card_intent.startup_aborted and not card.aol_card_intent.allowed_latch
|
||||
return
|
||||
assert any(lat_commands[45:60] if reverse_boot else lat_commands[35:60])
|
||||
assert any(lat_commands[60:74] if startup_floor_dip else lat_commands[45:60] if reverse_boot else lat_commands[35:60])
|
||||
assert any(lat_commands[76:84]) # braking released long, not qualified lateral intent
|
||||
assert not any(lat_commands[86:95])
|
||||
assert any(lat_commands[100:])
|
||||
@@ -1012,3 +1033,70 @@ def test_route2c_card_stall_preserves_original_deadline(phase, stall, mode):
|
||||
)
|
||||
if intent.observedMonoTime > deadline:
|
||||
assert not intent.allowedLatch and not intent.lateralArmed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('phase', range(10))
|
||||
def test_mqb_cold_start_floor_dip_recovers_on_fresh_drive_feedback(phase):
|
||||
test_mqb_full_engagement_brake_reverse_drive_actual_callers(
|
||||
'manual', True, 0, False, False, parked_boot=True, reverse_boot=True,
|
||||
reverse_unbraked=True, delayed_heartbeat=True, native_phase=phase, cold_creep=True, route2c_start=True,
|
||||
startup_delivery_delay=1, startup_delivery_services=('aolAxisState', 'onroadEvents'), startup_floor_dip=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('phase', range(10))
|
||||
@pytest.mark.parametrize('delay', (1, 2))
|
||||
def test_mqb_cancel_receipt_precedes_both_status_publications(phase, delay):
|
||||
test_mqb_full_engagement_brake_reverse_drive_actual_callers(
|
||||
'manual', True, 0, False, True, cruise_cancel=True, native_phase=phase, cancel_delivery_delay=delay)
|
||||
|
||||
|
||||
def assert_floor_recovery_vetoes(card, state, now):
|
||||
from copy import copy
|
||||
from dataclasses import replace
|
||||
from openpilot.starpilot.aol.runtime import current_native
|
||||
proof = current_native(card.sm, card.CP, now_ns=now, axis_session_id=card.aol_axis_session())
|
||||
assert proof is not None
|
||||
def observe(cs=state, native=proof, stamp=now, producer=card.slc_producer_session, owner=card.aol_card_intent):
|
||||
candidate = copy(owner)
|
||||
candidate.observe_startup_readiness(card.sm, cs, native=native, panda_ready=True, now_ns=stamp, producer=producer)
|
||||
return candidate
|
||||
assert observe().startup_floor_pending
|
||||
for field, value in (('canValid', False), ('canTimeout', True), ('steerFaultPermanent', True),
|
||||
('steerFaultTemporary', True), ('accFaulted', True), ('steeringDisengage', True)):
|
||||
cs = structs.CarState(**state.to_dict())
|
||||
setattr(cs, field, value)
|
||||
result = observe(cs=cs)
|
||||
assert not result.startup_floor_pending and not result.allowed_latch
|
||||
for native in (None, replace(proof, axisSessionId='foreign'), replace(proof, pandaInventory=())):
|
||||
result = observe(native=native)
|
||||
assert not result.startup_floor_pending and not result.allowed_latch
|
||||
assert not observe(stamp=now + 30_000_001).startup_floor_pending
|
||||
assert not observe(producer='foreign').startup_floor_pending
|
||||
off = copy(card.aol_card_intent)
|
||||
off.settings = replace(off.settings, enabled=False)
|
||||
assert not observe(owner=off).startup_floor_pending
|
||||
|
||||
|
||||
@pytest.mark.parametrize('veto', ('none', 'held', 'stale_receipt', 'future_receipt', 'stale_signal', 'future_signal', 'no_raw_press', 'foreign_state'))
|
||||
def test_mqb_cancel_receipt_binds_exact_current_raw_press(veto):
|
||||
from types import SimpleNamespace
|
||||
from openpilot.starpilot.car.volkswagen.aol import cancel_source, policy_for
|
||||
cp = CarInterface.get_params(CAR.VOLKSWAGEN_GOLF_MK7, {bus: ({0xFD: 8} if bus == 1 else {}) for bus in range(8)}, [], True, False, False)
|
||||
cp.fingerprintSource = structs.CarParams.FingerprintSource.fw
|
||||
addition = policy_for(cp).safety_param_addition
|
||||
assert addition
|
||||
cp.safetyConfigs[-1].safetyParam |= addition
|
||||
cp.alternativeExperience = 32
|
||||
state = structs.CarState(canValid=True, gearShifter=structs.CarState.GearShifter.drive)
|
||||
state.cruiseState.available = True
|
||||
state.buttonEvents = [structs.CarState.ButtonEvent(type=structs.CarState.ButtonEvent.Type.cancel, pressed=veto != 'held')]
|
||||
now, stamp, received = 10_000_000_000, 20_000_000_000, 10_000_000_000
|
||||
if veto == 'stale_receipt':
|
||||
received -= 30_000_001
|
||||
if veto == 'future_receipt':
|
||||
received += 1
|
||||
signal = stamp - 30_000_001 if veto == 'stale_signal' else stamp + 1 if veto == 'future_signal' else stamp
|
||||
parser = SimpleNamespace(vl={'GRA_ACC_01': {'GRA_Abbrechen': int(veto != 'no_raw_press')}},
|
||||
ts_nanos={'GRA_ACC_01': {'GRA_Abbrechen': signal}})
|
||||
observation = (object() if veto == 'foreign_state' else state, received, stamp, stamp)
|
||||
assert cancel_source(cp, state, parser, observation, now) == (now if veto == 'none' else 0)
|
||||
|
||||
@@ -210,5 +210,5 @@ def test_cancel_source_is_bound_to_real_mixed_parser_receipt(identity, fault):
|
||||
if fault == 'wrong_bus':
|
||||
cs.buttonEvents = [structs.CarState.ButtonEvent(type='cancel', pressed=True)]
|
||||
received = now - 30_000_001 if fault == 'stale' else now
|
||||
caller = SimpleNamespace(CI=ci, _aol_can_observation=(cs, received, now, now))
|
||||
caller = SimpleNamespace(CP=cp, CI=ci, _aol_can_observation=(cs, received, now, now))
|
||||
assert Car.aol_cancel_source(cast(Car, caller), cs, now) == (now if fault == 'none' else 0)
|
||||
|
||||
@@ -55,7 +55,6 @@ def _healthy_transport_native(sm, cp, cs, session, now_ns, native=None, *, requi
|
||||
|
||||
|
||||
def _newer_combined_intent_native(sm, cp, cs, axis, now_ns):
|
||||
# FULL before ACK: intent only; output needs native proof/original deadlines.
|
||||
from opendbc.car.volkswagen.long_aol import qualified as volkswagen_long_qualified
|
||||
from openpilot.starpilot.car.hyundai.aol import early_native_long_withdrawal_supported
|
||||
if (not axis.nativeAcknowledged or not axis.desiredLateral or not axis.lateralActive or
|
||||
@@ -239,7 +238,6 @@ class TransportPauseFeedback:
|
||||
any(event.immediateDisable or event.softDisable or event.userDisable for event in sm['onroadEvents'])):
|
||||
return None
|
||||
native = independent_lateral_health(sm, cp, cs, self.session, now_ns)
|
||||
# 10Hz LAT grant may precede waiting axis: intent only.
|
||||
if (native is None or native.observedMonoTime < max(self.healthy_native_ns, self.lateral_native_ns) or
|
||||
(now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS and native.observedMonoTime <= self.healthy_native_ns) or
|
||||
not native.pandaInventory or not native.requestedLongitudinal or native.longitudinalAllowed or
|
||||
@@ -256,13 +254,11 @@ class TransportPauseFeedback:
|
||||
from opendbc.car import structs
|
||||
ev9 = cp.brand == 'hyundai' and ev9_qualified(cp, marked_only=True)
|
||||
from opendbc.car.ford.aol import qualified as ford_qualified
|
||||
# Pedal/Cancel before LONG echo: LAT intent only.
|
||||
ford_withdrawal = bool(cp.brand == 'ford' and ford_qualified(cp, marked_only=True) and cp.openpilotLongitudinalControl and
|
||||
(cs.brakePressed or not cs.cruiseState.enabled or physical_cancel(cs, cp) or
|
||||
not axis.desiredLongitudinal and not axis.longitudinalActive) and not cs.regenBraking and
|
||||
cs.cruiseState.available and not cs.doorOpen and not cs.seatbeltUnlatched and
|
||||
not cs.vehicleSensorsInvalid and cs.gearShifter == structs.CarState.GearShifter.drive)
|
||||
# Ford angle/curvature: intent-only LONG echo join.
|
||||
# Require fresh LAT and all health/fault checks.
|
||||
ford_long = bool(ford_qualified(cp, marked_only=True) and cp.openpilotLongitudinalControl)
|
||||
from opendbc.car.volkswagen.long_aol import qualified as volkswagen_long_qualified
|
||||
@@ -270,7 +266,9 @@ class TransportPauseFeedback:
|
||||
volkswagen_cancel = bool(0 < cancel_event_ns <= now_ns and now_ns - cancel_event_ns <= AXIS_MAX_AGE_NS and
|
||||
any(event.name == log.OnroadEvent.EventName.buttonCancel and event.userDisable for event in sm['onroadEvents']))
|
||||
volkswagen_withdrawal = bool(volkswagen_long_qualified(cp, marked_only=True) and cs.cruiseState.available and
|
||||
(physical_cancel(cs, cp) or volkswagen_cancel or not axis.desiredLongitudinal and not axis.longitudinalActive))
|
||||
(physical_cancel(cs, cp) or volkswagen_cancel or
|
||||
0 < self.longitudinal_cancel_ns <= now_ns <= self.longitudinal_cancel_ns + SAFETY_MAX_AGE_NS or
|
||||
not axis.desiredLongitudinal and not axis.longitudinalActive))
|
||||
early_long = gm or cp.brand == 'hyundai' and early_native_long_withdrawal_supported(cp) or ev9 or ford_withdrawal or ford_long or volkswagen_withdrawal
|
||||
from openpilot.starpilot.car.gm.aol import f1_conventional_lateral_owner, gm_physical_pedal_withdrawal
|
||||
gm_pedal = gm_physical_pedal_withdrawal(cp, cs) and not f1_conventional_lateral_owner(cp)
|
||||
@@ -306,10 +304,7 @@ class TransportPauseFeedback:
|
||||
return None
|
||||
native = independent_lateral_health(sm, cp, cs, self.session, now_ns)
|
||||
# Brake health may precede axis status.
|
||||
# Keep LAT intent only; physical pedal owns LONG.
|
||||
# Cancel can withdraw raw Panda LONG before its next native axis receipt.
|
||||
# Retain only the already acknowledged LAT-only axis, under the original
|
||||
# source/native deadlines and a fresh matching cruise-withdrawal event.
|
||||
# Cancel needs acknowledged LAT, original deadlines and a fresh withdrawal event.
|
||||
ford_cancel_health = bool(ford_withdrawal and not cs.cruiseState.enabled and
|
||||
not axis.desiredLongitudinal and not axis.longitudinalActive and
|
||||
0 < event_ns <= now_ns and now_ns - event_ns <= AXIS_MAX_AGE_NS and
|
||||
@@ -392,7 +387,6 @@ class TransportPauseFeedback:
|
||||
(max(axis.faultEventMonoTime, event_ns) != self.pending_event if repeated_join else
|
||||
axis.faultEventMonoTime != self.pending_event)):
|
||||
return False
|
||||
# Pre-event SOFT: intent only, original 30ms join; no reanchoring.
|
||||
axis_first = bool(str(axis.faultReason) == 'availabilityPause' and
|
||||
not (axis.lateralActive or axis.longitudinalActive or axis.desiredLateral or axis.desiredLongitudinal or axis.nativeAcknowledged) and
|
||||
prior is not None and prior[5] == 'none' and prior[11] and prior[13] and
|
||||
@@ -490,7 +484,6 @@ class TransportPauseFeedback:
|
||||
gears = structs.CarState.GearShifter
|
||||
|
||||
# PCM-off is not AOL-off: retain intent for location/EPS recovery;
|
||||
# native/session/source guards remain.
|
||||
recovering_user = bool((location_fault or eps_recovery) and users)
|
||||
stock_angle = recovering_user and cp.brand == 'hyundai' and angle_qualified(cp, marked_only=True)
|
||||
stock_hkg = recovering_user and cp.brand == 'hyundai' and (stock_angle or stock_canfd_qualified(cp, marked_only=True) or
|
||||
@@ -580,7 +573,6 @@ class TransportPauseFeedback:
|
||||
faults = [event for event in events if event.immediateDisable or event.softDisable]
|
||||
isolated = bool(len(faults) == 1 and faults[0].name == log.OnroadEvent.EventName.selfdrivedLagging and
|
||||
faults[0].softDisable and not faults[0].immediateDisable)
|
||||
# Healthy skips policy/native/provenance; critical proof never exempts lag.
|
||||
recovering = bool(cp.brand == 'gm' and not faults and reason == 'none' and
|
||||
0 < self.lag_withdrawal_ns <= now_ns <= self.lag_withdrawal_ns + SAFETY_MAX_AGE_NS and
|
||||
axis.desiredLateral and not axis.lateralActive and axis.nativeAcknowledged and
|
||||
@@ -658,7 +650,6 @@ class TransportPauseFeedback:
|
||||
elif joining:
|
||||
self.pending_event = 0
|
||||
if matched and cp.brand == 'gm':
|
||||
# Latest inactive proof, not fault age; lag renews no lease, permission or baseline.
|
||||
self.lag_withdrawal_ns = stamp
|
||||
return True
|
||||
|
||||
@@ -778,11 +769,13 @@ class TransportPauseFeedback:
|
||||
return None
|
||||
|
||||
classic = classic_qualified(cp, marked_only=True)
|
||||
from opendbc.car.volkswagen.long_aol import qualified as volkswagen_long_qualified
|
||||
volkswagen = volkswagen_long_qualified(cp, marked_only=True)
|
||||
if (not latched or self.failed or self.paused or self.pending_event or
|
||||
not self.session or str(axis.sessionId) != self.session or
|
||||
classic and (not self.availability_producer or axis.intentProducerSessionId != self.availability_producer or
|
||||
(classic or volkswagen) and (not self.availability_producer or axis.intentProducerSessionId != self.availability_producer or
|
||||
axis.intentIntegrityEpoch != self.availability_epoch) or
|
||||
not (qualified(cp, marked_only=True) or ev9_qualified(cp, marked_only=True) or mixed_qualified(cp, marked_only=True) or classic) or
|
||||
not (qualified(cp, marked_only=True) or ev9_qualified(cp, marked_only=True) or mixed_qualified(cp, marked_only=True) or classic or volkswagen) or
|
||||
not self.lateral_baseline_ns or not 0 <= now_ns - self.lateral_baseline_ns <= AXIS_MAX_AGE_NS or
|
||||
str(axis.faultReason) != 'none' or not axis.nativeAcknowledged or
|
||||
not axis.desiredLateral or not axis.lateralActive or cs.accFaulted or
|
||||
@@ -948,7 +941,6 @@ class TransportPauseFeedback:
|
||||
combined = bool(axis.desiredLongitudinal and axis.longitudinalActive)
|
||||
if combined:
|
||||
# Event-first: NEW occurrence, verified OFF/source-zero, exact join;
|
||||
# never renew pending deadline or old command lease.
|
||||
previous = self.signature
|
||||
if (previous is None or previous[0] != self.session or previous[5] != 'availabilityPause' or
|
||||
previous[7] != self.session or previous[8] != 0 or previous[9] or previous[10] or
|
||||
@@ -1609,6 +1601,11 @@ class TransportPauseFeedback:
|
||||
stamp - axis.sourceCarStateMonoTime <= AXIS_MAX_AGE_NS)
|
||||
if native is None and latched and current and continuity and baseline:
|
||||
native = _newer_combined_intent_native(sm, cp, cs, axis, now_ns)
|
||||
from opendbc.car.volkswagen.long_aol import qualified as volkswagen_long_qualified
|
||||
if (current and continuity and baseline and volkswagen_long_qualified(cp, marked_only=True) and
|
||||
self._longitudinal_cancel_current(sm, cp, cs, axis, now_ns, latched=latched,
|
||||
cancel_source_ns=cancel_source_ns, withdrawal_required=False) is not None):
|
||||
self.longitudinal_cancel_ns = self.last_cancel_source_ns = int(cancel_source_ns)
|
||||
lateral_native = (self._native_long_withdrawal_lateral_current(sm, cp, cs, axis, now_ns,
|
||||
latched=latched, producer=intent_producer_session)
|
||||
if native is None and current and continuity and baseline else None)
|
||||
|
||||
@@ -135,14 +135,23 @@ class DepartureNotifications:
|
||||
lead, tracked = projected.raw_lead, projected.lead_observation.tracked
|
||||
light, stopped, action_stop = projected.scene.stop_light_detected, projected.raw_model_stopped, projected.current_model_should_stop
|
||||
stationary = bool(car.standstill and not car.gasPressed and str(car.gearShifter) == 'drive')
|
||||
radar_id = int(sm['radarState'].leadOne.radarTrackId)
|
||||
# The control tracker only acquires while moving; a stopped physical lead
|
||||
# can independently arm this advisory's continuous-track departure check.
|
||||
if stationary and lead is not None and lead.present and lead.radar and radar_id >= 0:
|
||||
tracked = True
|
||||
eof = int(sm['modelV2'].timestampEof)
|
||||
# A qualified stop release need not qualify full curve/lead geometry.
|
||||
light_valid = (type(light) is bool and type(action_stop) is bool and
|
||||
(type(stopped) is bool or action_stop is False))
|
||||
valid = (all(k in projected.fresh_services for k in ('carState', 'modelV2', 'radarState')) and
|
||||
type(tracked) is bool and type(light) is bool and type(stopped) is bool and type(action_stop) is bool and
|
||||
type(tracked) is bool and (tracked or light_valid) and
|
||||
0 < eof <= boot and boot - eof <= 150_000_000 and
|
||||
car.canValid and not car.canTimeout and drive < model_ns <= now and now - model_ns <= 150_000_000)
|
||||
lead_speed = lead.speed_mps if lead is not None else None
|
||||
distance = lead.distance_m if lead is not None else None
|
||||
valid &= (not tracked or lead is not None and
|
||||
all(isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) for x in (distance, lead_speed)))
|
||||
radar_id = int(sm['radarState'].leadOne.radarTrackId)
|
||||
dashboard_sign = dashboard_stop_sign(sm, now_ns=now, drive_id=drive)
|
||||
return self.episode.step(drive=drive, model_ns=model_ns, now_ns=now, stationary=stationary, valid=bool(valid),
|
||||
light=light, model_stopped=bool(stopped or action_stop), tracked=tracked, distance=distance, lead_speed=lead_speed,
|
||||
|
||||
@@ -184,8 +184,8 @@ def test_defaults_skip_perception_and_never_mutate_settings(tmp_path):
|
||||
assert all(not Path(params.get_param_path(k)).exists() for k in KEYS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', [1, 2])
|
||||
def test_existing_scene_projector_drives_each_notice_without_control_changes(tmp_path, kind):
|
||||
@pytest.mark.parametrize('kind,prefix_noise', [(1, False), (1, True), (2, False), (2, True)])
|
||||
def test_existing_scene_projector_drives_each_notice_without_control_changes(tmp_path, kind, prefix_noise):
|
||||
import numpy as np
|
||||
from openpilot.starpilot.conditional_mode.tests.test_projection import FakeSubMaster, serialized_scene
|
||||
|
||||
@@ -214,6 +214,8 @@ def test_existing_scene_projector_drives_each_notice_without_control_changes(tmp
|
||||
payloads['carState'].gearShifter = 'drive'
|
||||
payloads['controlsState'].curvature = 0.0
|
||||
payloads['modelV2'].action.shouldStop = not departing if kind == 1 else False
|
||||
if prefix_noise and stationary and departing:
|
||||
payloads['modelV2'].position.x = [0.0, -0.0001, 0.0002, -0.0004, *[horizon * i / 32 for i in range(4, 33)]]
|
||||
payloads['radarState'].leadOne.radarTrackId = 7
|
||||
payloads['deviceState'] = NS(started=True, startedMonoTime=DRIVE)
|
||||
sm = FakeSubMaster(payloads, now)
|
||||
@@ -291,3 +293,68 @@ def test_known_stop_sign_never_becomes_a_green_light_notice_until_next_stop():
|
||||
sample(owner, 5, stationary=False)
|
||||
sample(owner, 6)
|
||||
assert sample(owner, 7, model_stopped=False)[0] == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', [None, 'vision', 'missing-lead', 'new-track', 'invalid-can', 'gas', 'reverse',
|
||||
'stale-radar', 'radar-receipt', 'invalid-radar', 'dead-radar',
|
||||
'stale-model', 'stale-eof', 'future-eof', 'safe-mode', 'disabled'])
|
||||
def test_stopped_physical_lead_departure_does_not_need_moving_control_tracking(tmp_path, fault):
|
||||
import numpy as np
|
||||
from openpilot.starpilot.conditional_mode.tests.test_projection import FakeSubMaster, serialized_scene
|
||||
|
||||
params = Params(str(tmp_path))
|
||||
Path(params.get_param_path('LeadDepartingAlert')).write_bytes(b'0' if fault == 'disabled' else b'1')
|
||||
if fault == 'safe-mode':
|
||||
Path(params.get_param_path('SafeMode')).write_bytes(b'1')
|
||||
owner = DepartureNotifications(params)
|
||||
cp = NS(openpilotLongitudinalControl=True, pcmCruise=True, carFingerprint='TOYOTA_RAV4_TSS2',
|
||||
passive=False, dashcamOnly=False, notCar=False)
|
||||
planner = NS(mpc=NS(params=np.array([[0.0, 0.0, 0.0, 0.0, 1.45]])))
|
||||
before = planner.mpc.params.copy()
|
||||
emitted = []
|
||||
for tick in range(100):
|
||||
now = NOW + tick * 50_000_000
|
||||
departing = tick >= 40
|
||||
payloads = serialized_scene(stamp=now, speed=0.0, standstill=True, horizon=50.0,
|
||||
lead_distance=5.1 if departing else 3.85, lead_speed=1.3 if departing else 0.0)
|
||||
payloads = {k: v.as_builder() for k, v in payloads.items()}
|
||||
car, model, lead = payloads['carState'], payloads['modelV2'], payloads['radarState'].leadOne
|
||||
car.gearShifter = 'reverse' if fault == 'reverse' else 'drive'
|
||||
car.canValid = fault != 'invalid-can'
|
||||
car.gasPressed = fault == 'gas'
|
||||
car.brakePressed = True
|
||||
car.vCruise = 255.0
|
||||
car.vEgo = -3.98e-9
|
||||
car.vEgoRaw = 0.0
|
||||
model.position.x = [0.0, -0.0001, 0.0002, -0.0004, *[50.0 * i / 32 for i in range(4, 33)]]
|
||||
model.action.shouldStop = False
|
||||
model.timestampEof = now - 200_000_000 if fault == 'stale-eof' else now + 1 if fault == 'future-eof' else now
|
||||
lead.present = fault != 'missing-lead'
|
||||
lead.radar = fault != 'vision'
|
||||
lead.radarTrackId = tick if fault == 'new-track' and departing else 3630
|
||||
payloads['deviceState'] = NS(started=True, startedMonoTime=DRIVE)
|
||||
sm = FakeSubMaster(payloads, now)
|
||||
for attr in ('valid', 'alive', 'seen'):
|
||||
getattr(sm, attr)['deviceState'] = True
|
||||
sm.logMonoTime['deviceState'] = now
|
||||
sm.recv_time['deviceState'] = now / 1e9
|
||||
sm.all_checks = lambda keys, sm=sm: all(sm.valid[k] and sm.alive[k] for k in keys)
|
||||
if fault == 'stale-radar':
|
||||
sm.logMonoTime['radarState'] = now - 300_000_000
|
||||
elif fault == 'radar-receipt':
|
||||
sm.recv_time['radarState'] = (now - 300_000_000) / 1e9
|
||||
elif fault == 'invalid-radar':
|
||||
sm.valid['radarState'] = False
|
||||
elif fault == 'dead-radar':
|
||||
sm.alive['radarState'] = False
|
||||
elif fault == 'stale-model':
|
||||
sm.logMonoTime['modelV2'] = now - 300_000_000
|
||||
notice = owner.sample(sm, cp, planner, clocks=(now, now, 0))
|
||||
if notice[0]:
|
||||
emitted.append(notice)
|
||||
if fault is None:
|
||||
assert emitted and {kind for kind, _ in emitted} == {2}
|
||||
assert len({stamp for _, stamp in emitted}) == 1
|
||||
else:
|
||||
assert not emitted
|
||||
np.testing.assert_array_equal(planner.mpc.params, before)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Retain established Subaru OFF intent; this proof never grants a command."""
|
||||
"""Preserve established Subaru intent; this proof never grants a command."""
|
||||
from dataclasses import dataclass
|
||||
from math import isfinite
|
||||
|
||||
@@ -135,19 +135,21 @@ def retain_stopped_source_feedback(feedback, sm, cp, state, axis, stamp, now_ns,
|
||||
|
||||
|
||||
def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, latched, producer):
|
||||
"""Accepted intent survives coherent OFF, waiting, and active LAT phases."""
|
||||
if retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, now_ns, latched=latched, producer=producer):
|
||||
return True
|
||||
from openpilot.starpilot.aol.transport_pause import _configured_transport_native
|
||||
previous = feedback.signature
|
||||
if (cp.carFingerprint != CAR.SUBARU_IMPREZA_2020 or not qualified(cp, marked_only=True) or
|
||||
if (not qualified(cp, marked_only=True) or cp.openpilotLongitudinalControl or
|
||||
not latched or feedback.failed or feedback.paused or
|
||||
feedback.retention_started_ns or feedback.source_retention_started_ns or not feedback.ever_lateral_active or
|
||||
feedback.retention_started_ns or feedback.source_retention_started_ns or
|
||||
previous is None or not feedback.session or not producer or
|
||||
previous[0] != previous[7] or previous[0] != feedback.session or previous[5] != 'none' or
|
||||
previous[10] or previous[12] or previous[9] != previous[11] or not previous[13] or previous[14:16] != (producer, int(axis.intentIntegrityEpoch)) or
|
||||
previous[10] or previous[12] or previous[9] and not previous[11] or not previous[13] or previous[14:16] != (producer, int(axis.intentIntegrityEpoch)) or
|
||||
axis.intentProducerSessionId != producer or str(axis.sessionId) != feedback.session or
|
||||
str(axis.faultReason) != 'none' or str(axis.mode) != 'off' or not axis.nativeAcknowledged or
|
||||
any((axis.desiredLateral, axis.lateralActive, axis.desiredLongitudinal, axis.longitudinalActive)) or
|
||||
str(axis.faultReason) != 'none' or not axis.nativeAcknowledged or
|
||||
str(axis.mode) != ('lateralOnly' if axis.lateralActive else 'off') or
|
||||
axis.lateralActive and not axis.desiredLateral or axis.desiredLongitudinal or axis.longitudinalActive or
|
||||
not 0 < previous[8] <= previous[2] <= now_ns <= previous[4] or now_ns - previous[8] > AXIS_MAX_AGE_NS or
|
||||
not previous[8] <= axis.sourceCarStateMonoTime <= stamp <= now_ns or now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or
|
||||
not state.steerFaultTemporary or state.steerFaultPermanent or not state.canValid or state.canTimeout or
|
||||
@@ -178,7 +180,8 @@ def retain_paused_restriction(feedback, sm, cp, state, axis, stamp, now_ns, *, l
|
||||
return False
|
||||
native = _configured_transport_native(sm, cp, feedback.session, now_ns, allow_restricted_lateral=True)
|
||||
if (native is None or not native.pandaInventory or native.requestedLateral != native.lateralAllowed or
|
||||
native.requestedLongitudinal or native.longitudinalAllowed or native.observedMonoTime < feedback.healthy_native_ns or
|
||||
axis.lateralActive and not native.lateralAllowed or native.requestedLongitudinal or native.longitudinalAllowed or
|
||||
native.observedMonoTime < feedback.healthy_native_ns or
|
||||
feedback.healthy_inventory != (native.pandaSerial, tuple(slot.hardwareSerial for slot in native.pandaInventory))):
|
||||
return False
|
||||
if matched:
|
||||
@@ -199,7 +202,7 @@ def retain_pending_restriction_recovery(feedback, sm, cp, state, axis, stamp, no
|
||||
pending, restriction = feedback.pending_event, getattr(feedback, 'temporary_eps_event_ns', 0)
|
||||
if (not qualified(cp, marked_only=True) or not cp.pcmCruise or cp.openpilotLongitudinalControl or
|
||||
not latched or feedback.failed or feedback.paused or feedback.retention_started_ns or
|
||||
feedback.source_retention_started_ns or not feedback.ever_lateral_active or
|
||||
feedback.source_retention_started_ns or not 0 < feedback.healthy_feedback_ns <= now_ns or
|
||||
previous is None or not feedback.session or cp_identity(cp) != feedback.cp or
|
||||
not 0 < restriction < pending <= now_ns or now_ns - pending > AXIS_MAX_AGE_NS or
|
||||
previous[0] != previous[7] or previous[0] != feedback.session or previous[5] != 'none' or
|
||||
|
||||
@@ -192,7 +192,7 @@ def test_paused_restriction_preserves_independent_fault_user_and_authority_vetoe
|
||||
elif fault == 'failed':
|
||||
feedback.failed = True
|
||||
elif fault == 'no_history':
|
||||
feedback.ever_lateral_active = False
|
||||
feedback.healthy_feedback_ns = 0
|
||||
elif fault == 'other_car':
|
||||
cp.carFingerprint = 'SUBARU_OUTBACK'
|
||||
elif fault != 'off':
|
||||
@@ -273,7 +273,7 @@ def test_pending_subaru_recovery_does_not_bypass_independent_vetoes(fault):
|
||||
elif fault == 'failed':
|
||||
feedback.failed = True
|
||||
elif fault == 'no_history':
|
||||
feedback.ever_lateral_active = False
|
||||
feedback.healthy_feedback_ns = 0
|
||||
elif fault == 'new_event':
|
||||
sm.logMonoTime['onroadEvents'] += 1
|
||||
elif fault == 'no_warning':
|
||||
@@ -354,3 +354,28 @@ def test_recovery_brake_release_preserves_only_a_known_pending_eps_brake():
|
||||
assert retain_pending_restriction_recovery(feedback, sm, cp, state, sm['aolAxisState'], sm.logMonoTime['aolAxisState'], now,
|
||||
latched=True, producer=PRODUCER)
|
||||
assert leases(feedback) == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('previous_role', ('off', 'waiting', 'active'))
|
||||
@pytest.mark.parametrize('current_role', ('off', 'waiting', 'active'))
|
||||
@pytest.mark.parametrize('native_granted', (False, True))
|
||||
@pytest.mark.parametrize('ever_active', (False, True))
|
||||
@pytest.mark.parametrize('steering_pressed', (False, True))
|
||||
@pytest.mark.parametrize('brake_pressed', (False, True))
|
||||
def test_subaru_temporary_intent_depends_on_accepted_proof_not_actuation_phase(
|
||||
previous_role, current_role, native_granted, ever_active, steering_pressed, brake_pressed):
|
||||
from openpilot.starpilot.car.subaru.paused_intent import retain_paused_restriction
|
||||
cp, state, feedback, sm, native, stamp = paused_case()
|
||||
state.steeringPressed, state.brakePressed = steering_pressed, brake_pressed
|
||||
feedback.ever_lateral_active = ever_active
|
||||
previous = list(feedback.signature)
|
||||
previous[9], previous[11] = previous_role == 'active', previous_role != 'off'
|
||||
feedback.signature = tuple(previous)
|
||||
change(sm, 'aolAxisState', lambda a: (setattr(a, 'lateralActive', current_role == 'active'),
|
||||
setattr(a, 'desiredLateral', current_role != 'off'), setattr(a, 'mode', 'lateralOnly' if current_role == 'active' else 'off')))
|
||||
native_change(sm, native, requestedLateral=native_granted, lateralAllowed=native_granted)
|
||||
before = leases(feedback), feedback.signature, sm['aolAxisState'].to_dict()
|
||||
retained = retain_paused_restriction(feedback, sm, cp, state, sm['aolAxisState'], stamp, stamp,
|
||||
latched=True, producer=PRODUCER)
|
||||
assert retained == (current_role != 'active' or native_granted)
|
||||
assert (leases(feedback), feedback.signature, sm['aolAxisState'].to_dict()) == before
|
||||
|
||||
@@ -30,7 +30,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
high_angle_guard=False, main_on_brake=False, guard_brake_release=False,
|
||||
stopped_feedback_gap=False, rearm_on_brake=0, main_during_eps=False,
|
||||
angle_continuation=0, stopped_source_gap=False, paused_eps=0,
|
||||
eps_clear_join=0, eps_clear_axis_first=False):
|
||||
eps_clear_join=0, eps_clear_axis_first=False, stop_creep_eps=0, cold_stop=False):
|
||||
angle_handoff = fixed_angle_handoff or vm_angle_handoff
|
||||
fw = firmware_records(candidate, FW_VERSIONS, 'subaru') if firmware is None else firmware
|
||||
rows = []
|
||||
@@ -77,7 +77,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
published = {}
|
||||
ticks = (list(range(30)) + list(range(30, 50)) * 16 + list(range(50, 460))
|
||||
if main_during_eps else list(range(125)) + list(range(125, 135)) * 30 + list(range(135, 460))
|
||||
if hard_stop_native_first else list(range(70)) + list(range(70, 90)) * 16 + list(range(90, 460))
|
||||
if hard_stop_native_first or stop_creep_eps else list(range(70)) + list(range(70, 90)) * 16 + list(range(90, 460))
|
||||
if angle_continuation else range(460))
|
||||
gap_tick = 75 if main_only else 210
|
||||
last_card_published = {}
|
||||
@@ -101,9 +101,13 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
reverse = 150 <= tick < 185
|
||||
temporary = not guard_brake_release and 225 <= tick < 260
|
||||
main = not 310 <= tick < 350 and (tick >= 30 or not main_only)
|
||||
stopped = stop_resume and (125 <= tick < 135 if hard_stop_native_first or host_first_stop else 185 <= tick < 195)
|
||||
stopped = stop_resume and (125 <= tick < 135 if hard_stop_native_first or host_first_stop or stop_creep_eps else 185 <= tick < 195)
|
||||
if stop_creep_eps:
|
||||
stopped = tick < 135 and (cold_stop or tick >= 125)
|
||||
brake = bool(stopped and tick < 129)
|
||||
first_resume = False
|
||||
first_resume = 145 <= tick < 150 if hard_stop_native_first or host_first_stop else 125 <= tick < 145
|
||||
if paused_eps or eps_clear_join:
|
||||
if paused_eps or eps_clear_join or stop_creep_eps:
|
||||
first_resume = False # Blinker debounce overlaps the later reverse pause.
|
||||
source_missing = bool(source_outage and 75 <= tick < 81)
|
||||
if paused_eps:
|
||||
@@ -175,6 +179,15 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
values['Brake_Pressure_L_R'] = {'Steering_Angle': 101 if 95 <= tick < 102 else 0}
|
||||
else:
|
||||
values['Steering_Torque']['Steer_Warning'] = int(95 <= tick < 102 or temporary)
|
||||
if stop_creep_eps:
|
||||
values['Dashlights'] = {'LEFT_BLINKER': 0, 'RIGHT_BLINKER': 0}
|
||||
values['Brake_Pedal'] = {'Speed': 0 if stopped else .171 if 135 <= tick < 137 else .356 if 137 <= tick < 148 else 14.4}
|
||||
values['Wheel_Speeds'] = dict.fromkeys(('FL', 'FR', 'RL', 'RR'), values['Brake_Pedal']['Speed'])
|
||||
values['Steering_Torque']['Steer_Torque_Sensor'] = -121 if 125 <= tick < 137 else -118 if 137 <= tick < 148 else 0
|
||||
if stop_creep_eps == 1:
|
||||
values['Brake_Pressure_L_R'] = {'Steering_Angle': 101 if 125 <= tick < 148 else 0}
|
||||
else:
|
||||
values['Steering_Torque']['Steer_Warning'] = int(137 <= tick < 148 or temporary)
|
||||
incoming = stream.frames(values, tick=tick)
|
||||
if source_outage:
|
||||
pending_host_can.append((now, incoming))
|
||||
@@ -401,7 +414,7 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
assert card.aol_card_intent.allowed_latch, ('SUBARU_STOPPED_FEEDBACK_GAP_CLEARED', row)
|
||||
assert not command.latActive and not command.longActive and row['permission'] == 0, row
|
||||
assert row['fault'] == 'none' and 'controlsMismatch' not in row['events'], row
|
||||
if stopped:
|
||||
if stopped and (not stop_creep_eps or tick >= 40):
|
||||
assert not row['lat'] and row['cardLatch'] and row['permission'] == 0 and row['fault'] in (
|
||||
('none', 'availabilityPause') if stopped_source_gap else ('none',)), ('SUBARU_STOP_LOST_ARMED_INTENT', row)
|
||||
if source_outage and 78 <= tick < 81:
|
||||
@@ -414,10 +427,13 @@ def test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(candidate,
|
||||
if eps_clear_join and 100 <= tick < 145:
|
||||
assert row['cardLatch'] and row['armed'] and not row['lat'] and not row['long'], ('SUBARU_EPS_CLEAR_LOST_INTENT', row)
|
||||
assert all(not frame['request'] and frame['output'] == 0 and frame['nativeAccepted'] for frame in row['steering']), row
|
||||
if stop_creep_eps and 135 <= tick < 148:
|
||||
assert row['cardLatch'] and row['armed'] and not row['lat'] and not row['long'], ('SUBARU_STOP_CREEP_EPS_LOST_INTENT', row)
|
||||
assert all(not frame['request'] and frame['output'] == 0 and frame['nativeAccepted'] for frame in row['steering']), row
|
||||
assert not command.longActive, row
|
||||
if 10 <= tick < 30:
|
||||
assert not command.latActive and not bool(intent and intent.allowedLatch) and row['permission'] == 0, row
|
||||
if 65 <= tick < 90 and not (main_during_eps and tick < 75) and not (source_outage and 75 <= tick < 84):
|
||||
if 65 <= tick < 90 and not (stop_creep_eps and cold_stop) and not (main_during_eps and tick < 75) and not (source_outage and 75 <= tick < 84):
|
||||
assert command.latActive and bool(intent and intent.allowedLatch) == aol and row['permission'] == int(aol), row
|
||||
if not stopped and (first_resume or 205 <= tick < 220 or 280 <= tick < 300):
|
||||
assert command.latActive == aol and bool(intent and intent.allowedLatch) == aol and row['permission'] == int(aol) and not row['controls'], row
|
||||
@@ -697,3 +713,22 @@ def test_actual_subaru_paused_restriction_event_join(subaru_native_pair, tmp_pat
|
||||
CAR.SUBARU_IMPREZA_2020, subaru_native_pair, tmp_path, main_only=True, paused_eps=restriction,
|
||||
eps_clear_axis_first=axis_first,
|
||||
preferences={'PauseLateralOnSignal': True, 'PauseLateralSpeed': 100., 'LateralResumeDelay': 0.})
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cold_stop', (False, True), ids=('previously-active', 'first-main-at-stop'))
|
||||
@pytest.mark.parametrize('restriction', (1, 2), ids=('host-guard', 'raw-eps'))
|
||||
def test_actual_subaru_stop_creep_restriction_preserves_armed_intent(
|
||||
subaru_native_pair, tmp_path, restriction, cold_stop, candidate=CAR.SUBARU_IMPREZA_2020):
|
||||
test_actual_full_engage_brake_reverse_temporary_recovery_mainoff(
|
||||
candidate, subaru_native_pair, tmp_path, main_only=candidate in (
|
||||
CAR.SUBARU_IMPREZA_2020, CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_CROSSTREK_2025, CAR.SUBARU_OUTBACK_2023),
|
||||
stop_resume=True, hard_stop_native_first=not cold_stop, stop_creep_eps=restriction, cold_stop=cold_stop)
|
||||
rows = json.loads((tmp_path / (str(candidate) + '-True-actual.json')).read_text())
|
||||
assert any(row['cardLatch'] and row['armed'] and not row['lat'] and row['permission'] == 0 for row in rows if 135 <= row['tick'] < 137)
|
||||
assert all(row['cardLatch'] and row['armed'] for row in rows if 135 <= row['tick'] < 148)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('candidate', (CAR.SUBARU_ASCENT_2023, CAR.SUBARU_LEGACY_2025, CAR.SUBARU_CROSSTREK_2025,
|
||||
CAR.SUBARU_IMPREZA_2025, CAR.SUBARU_FORESTER, CAR.SUBARU_OUTBACK, CAR.SUBARU_OUTBACK_2023))
|
||||
def test_actual_subaru_family_stop_creep_restriction(candidate, subaru_native_pair, tmp_path):
|
||||
test_actual_subaru_stop_creep_restriction_preserves_armed_intent(subaru_native_pair, tmp_path, 2, False, candidate=candidate)
|
||||
|
||||
@@ -95,6 +95,10 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
self.startup_ready = False
|
||||
self.startup_identity = None
|
||||
self.startup_observation_identity = None
|
||||
self.startup_floor_pending = False
|
||||
self.startup_floor_source_ns = 0
|
||||
self.startup_floor_seen_ns = 0
|
||||
self.startup_floor_event_ns = 0
|
||||
self.reverse_pause = False
|
||||
super().__init__(settings, explicit_latch=True, lkas_button_supported=False,
|
||||
preserve_unassigned_cancel=self.cruise_lateral)
|
||||
@@ -198,7 +202,9 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
from openpilot.starpilot.aol.runtime import AXIS_MAX_AGE_NS, SAFETY_MAX_AGE_NS, current_axis
|
||||
from openpilot.starpilot.aol.transport_pause import _configured_transport_native, cp_identity
|
||||
self.startup_ready = False
|
||||
if (self.startup_granted or self.startup_aborted or not self.settings.enabled or self.pause_lateral or
|
||||
floor_pending = self.startup_floor_pending
|
||||
self.startup_floor_pending = False
|
||||
if (self.startup_granted or not self.settings.enabled or self.pause_lateral or
|
||||
self.settings.main_action == AOL_TOGGLE or self.settings.lkas_action == AOL_TOGGLE or
|
||||
not long_qualified(self.cp, marked_only=True) or
|
||||
self.cp.transmissionType != structs.CarParams.TransmissionType.manual):
|
||||
@@ -232,7 +238,8 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
now_ns - axis.sourceCarStateMonoTime > AXIS_MAX_AGE_NS or
|
||||
not 0 < axis.validUntilMonoTime - axis.observedMonoTime <= AXIS_MAX_AGE_NS or
|
||||
not sm.seen['onroadEvents'] or not sm.valid['onroadEvents'] or not sm.alive['onroadEvents'] or
|
||||
not self.startup_arm_ns <= event_ns == axis.faultEventMonoTime <= axis.observedMonoTime or
|
||||
not (0 < event_ns == axis.faultEventMonoTime <= axis.observedMonoTime and
|
||||
(self.startup_arm_ns <= event_ns or event_ns == self.startup_floor_event_ns)) or
|
||||
now_ns - event_ns > 1_500_000_000 or
|
||||
any(e.immediateDisable or e.softDisable or e.userDisable for e in sm['onroadEvents']) or
|
||||
not cs.canValid or cs.canTimeout or not cs.cruiseState.available or
|
||||
@@ -243,6 +250,31 @@ class VolkswagenStockCardIntent(AolCardIntent):
|
||||
return
|
||||
if proof.requestedLongitudinal or proof.longitudinalAllowed or axis.desiredLongitudinal or axis.longitudinalActive:
|
||||
return
|
||||
if floor_pending and not 0 <= now_ns - self.startup_floor_seen_ns <= AXIS_MAX_AGE_NS:
|
||||
return
|
||||
at_floor = min(abs(cs.vEgo), abs(cs.vEgoRaw)) <= max(self.cp.minSteerSpeed, .3) or cs.standstill
|
||||
if at_floor:
|
||||
if floor_pending or (self.allowed_latch and self.startup_release_ns and not self.startup_aborted and now_ns <= deadline):
|
||||
# A physical floor withdrawal ends this attempt; no armed lease survives it.
|
||||
self.startup_floor_pending = True
|
||||
self.startup_floor_source_ns = self.startup_floor_seen_ns = now_ns
|
||||
self.allowed_latch = self.main_startup_pending = False
|
||||
self.startup_aborted = True
|
||||
return
|
||||
if floor_pending:
|
||||
self.startup_floor_pending = True
|
||||
self.startup_floor_seen_ns = now_ns
|
||||
if (axis.sourceCarStateMonoTime > self.startup_floor_source_ns and not cs.brakePressed and not cs.regenBraking and
|
||||
not axis.desiredLateral and not axis.lateralActive and not proof.requestedLateral and not proof.lateralAllowed):
|
||||
self.startup_floor_pending = False
|
||||
self.startup_aborted = False
|
||||
self.main_startup_pending = self.startup_ready = True
|
||||
self.startup_arm_ns = axis.sourceCarStateMonoTime
|
||||
self.startup_floor_event_ns = event_ns
|
||||
self.startup_release_ns = 0
|
||||
return
|
||||
if self.startup_aborted:
|
||||
return
|
||||
if self.startup_release_ns:
|
||||
if (self.allowed_latch and identity == self.startup_identity and
|
||||
self.startup_release_ns <= proof.observedMonoTime <= deadline and
|
||||
@@ -483,3 +515,18 @@ def retain_reverse_withdrawal(feedback, sm, cp, cs, axis, now_ns, *, latched, pr
|
||||
return retained
|
||||
except (AttributeError, KeyError, TypeError, ValueError, OverflowError):
|
||||
return False
|
||||
|
||||
|
||||
def cancel_source(cp, cs, parser, observation, now_ns):
|
||||
"""Bind a physical MQB Cancel edge to its fresh parsed CAN receipt."""
|
||||
if (not long_qualified(cp, marked_only=True) or observation is None or observation[0] is not cs or
|
||||
not cs.canValid or cs.canTimeout or not cs.cruiseState.available or
|
||||
not any(e.type == ButtonType.cancel and e.pressed for e in cs.buttonEvents)):
|
||||
return 0
|
||||
_, received_ns, source_ns, boot_ns = observation
|
||||
stamp = int(parser.ts_nanos.get('GRA_ACC_01', {}).get('GRA_Abbrechen', 0))
|
||||
if (parser.vl.get('GRA_ACC_01', {}).get('GRA_Abbrechen') != 1 or
|
||||
not 0 < received_ns <= now_ns or now_ns - received_ns > 30_000_000 or
|
||||
not 0 < stamp <= source_ns <= boot_ns or boot_ns - stamp > 30_000_000 or source_ns - stamp > 30_000_000):
|
||||
return 0
|
||||
return received_ns
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Restore the manual Golf's factory PID/PopV2 target and timing contract."""
|
||||
"""Restore the manual Golf's factory PID target timing for verified Small models."""
|
||||
import math
|
||||
|
||||
from opendbc.car import structs
|
||||
@@ -27,9 +27,15 @@ def supported(cp):
|
||||
((pid.kpV[0], .6), (pid.kiV[0], .2), (pid.kf, .00006))))
|
||||
|
||||
|
||||
STABLE_PID_MODELS = {
|
||||
'pop223': POPV2_SHA256,
|
||||
'spz_polaris_vega': '863de9a72463f9ce51b69b47600db7dcd77c45d232f4913c389f9ea398e3fb2e',
|
||||
}
|
||||
|
||||
|
||||
def seconds(cp, load):
|
||||
return .1 if (supported(cp) and isinstance(load, ModelLoad) and load.model_id == 'pop223' and
|
||||
load.variant == ModelVariant.SMALL and load.artifact_sha256 == POPV2_SHA256 and
|
||||
return .1 if (supported(cp) and isinstance(load, ModelLoad) and load.model_id in STABLE_PID_MODELS and
|
||||
load.variant == ModelVariant.SMALL and load.artifact_sha256 == STABLE_PID_MODELS[load.model_id] and
|
||||
load.fallback_reason is None) else 0.
|
||||
|
||||
|
||||
|
||||
@@ -123,3 +123,37 @@ def test_model_join_applies_matching_input_delay_and_exactly_one_filter():
|
||||
assert env['lat_delay'] == pytest.approx(.3893982231616974)
|
||||
assert action.desiredCurvature == pytest.approx(float(smooth_value(.001, 0., .1)), abs=1e-9)
|
||||
assert action.desiredAcceleration == -.25 and action.shouldStop
|
||||
|
||||
|
||||
@pytest.mark.parametrize('gearbox', ('manual', 'automatic', 'direct'))
|
||||
@pytest.mark.parametrize('alpha', (False, True))
|
||||
@pytest.mark.parametrize('offset', (0, 4))
|
||||
def test_verified_polaris_vega_uses_the_same_matched_pid_timing(gearbox, alpha, offset):
|
||||
cp, load = setup(gearbox, alpha, offset)
|
||||
load = replace(load, model_id='spz_polaris_vega',
|
||||
artifact_sha256='863de9a72463f9ce51b69b47600db7dcd77c45d232f4913c389f9ea398e3fb2e')
|
||||
assert seconds(cp, load) == (.1 if gearbox == 'manual' else 0.)
|
||||
assert seconds(cp, replace(load, artifact_sha256=POPV2_SHA256)) == 0.
|
||||
assert seconds(cp, replace(load, variant=ModelVariant.CHESTNUT)) == 0.
|
||||
assert seconds(cp, replace(load, fallback_reason='selected-load-failed')) == 0.
|
||||
assert seconds(cp, replace(load, model_id='spz_polaris_r4a')) == 0.
|
||||
|
||||
|
||||
def test_polaris_v15_action_units_and_stable_filter_are_preserved():
|
||||
from openpilot.starpilot.models.runner import action_from_outputs
|
||||
cp, load = setup()
|
||||
load = replace(load, model_id='spz_polaris_vega',
|
||||
artifact_sha256='863de9a72463f9ce51b69b47600db7dcd77c45d232f4913c389f9ea398e3fb2e')
|
||||
tau = seconds(cp, load)
|
||||
for speed in (.0, .3, .4, 1., 2.5, 8., 35.):
|
||||
previous = log.ModelDataV2.Action(desiredCurvature=.001, desiredAcceleration=.1)
|
||||
for value in (.1, -.1, .2, 0.):
|
||||
outputs = {'action': np.array([[value, -.1]], dtype=np.float32)}
|
||||
action = action_from_outputs(outputs, 'v15', previous, .4 + tau, .8, speed)
|
||||
acceleration, stop = action.desiredAcceleration, action.shouldStop
|
||||
raw = float(outputs['action'][0, 0]) / max(2.5, speed) ** 2
|
||||
expected = smooth_value(raw, previous.desiredCurvature, .1) if speed > .3 else previous.desiredCurvature
|
||||
filter_action(action, previous, speed, tau)
|
||||
assert action.desiredCurvature == pytest.approx(expected, abs=1e-8)
|
||||
assert action.desiredAcceleration == acceleration and action.shouldStop == stop
|
||||
previous = action
|
||||
|
||||
@@ -19,7 +19,7 @@ PRODUCER_SOURCE_HASHES = (
|
||||
('openpilot', 'system/camerad/cameras/camera_qcom2.cc', 'b34c24c9984a0ac086f7b961cb7ff09d0501231da50aaad0e676bb3dc3f2edd9'),
|
||||
('openpilot', 'system/camerad/cameras/camera_common.cc', 'bd9a416a6ee21047b4deec6df04276d8717cd92fe14de43f3e9daff86b62bb8f'),
|
||||
('openpilot', 'selfdrive/modeld/modeld.py', '58dc00dcfc6a497469ce71698f71650abcc5c995b299d560b576d291422eed3b'),
|
||||
('openpilot', 'starpilot/car/volkswagen/model_smoothing.py', 'dd5d0ddaf77fe05960b673557b1b9f649d303ddfdad77a5185c7b3156fc6bbd2'),
|
||||
('openpilot', 'starpilot/car/volkswagen/model_smoothing.py', 'f26a0db1992a99d41b2b63626bc24ed6538cc89d9cfd4e96008e8c86126d7540'),
|
||||
('openpilot', 'starpilot/car/hyundai/model_smoothing.py', '28b1b8c64dd2d8e83f1bc71d39de7f797741d0911b39b7184a6e2d7d34d75243'),
|
||||
('openpilot', 'selfdrive/modeld/fill_model_msg.py', 'b3916c34d1073d0c26a7a8adc51e7b148f63a1ac68b388226170fd0f8b8b56b4'),
|
||||
('openpilot', 'system/sensord/sensord.py', '7c79ab07d775622a43001e5a9b9ccc9a7bafb065940185849b33eefc2fd26420'),
|
||||
|
||||
@@ -9,7 +9,7 @@ from openpilot.starpilot.flm import producer_clock_equivalence as clock
|
||||
|
||||
|
||||
APPROVED = {
|
||||
'starpilot/car/volkswagen/model_smoothing.py': 'dd5d0ddaf77fe05960b673557b1b9f649d303ddfdad77a5185c7b3156fc6bbd2',
|
||||
'starpilot/car/volkswagen/model_smoothing.py': 'f26a0db1992a99d41b2b63626bc24ed6538cc89d9cfd4e96008e8c86126d7540',
|
||||
'selfdrive/modeld/modeld.py': '58dc00dcfc6a497469ce71698f71650abcc5c995b299d560b576d291422eed3b',
|
||||
'starpilot/car/hyundai/model_smoothing.py': '28b1b8c64dd2d8e83f1bc71d39de7f797741d0911b39b7184a6e2d7d34d75243',
|
||||
'visionipc/visionipc_py.cc': '6c131c4f5eccb9f822f1aaae63733f26b1427c52340b61c9cdaf6cd4aee2f89d',
|
||||
|
||||
@@ -548,7 +548,8 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.starpilot.models.manager import ModelManager
|
||||
authority = context_source(Params())
|
||||
model_manager_source = ModelManager(parked=authority.parked, refresh_catalog=True)
|
||||
model_manager_source = ModelManager(parked=authority.parked, refresh_catalog=True,
|
||||
live_status=lambda: model_status().get('conditionalModelState'))
|
||||
server.model_authority = authority
|
||||
server.model_manager_source = model_manager_source
|
||||
return model_manager_source
|
||||
@@ -1738,7 +1739,7 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
|
||||
'/api/ui/layout', '/api/ui/layout/preview', '/api/favorites/slots',
|
||||
'/api/maps/start', '/api/maps/cancel',
|
||||
'/api/bluetooth/action', '/api/controllers/action',
|
||||
'/api/models/active', '/api/models/preferences', '/api/models/download', '/api/models/download_all',
|
||||
'/api/models/active', '/api/models/conditional_model', '/api/models/preferences', '/api/models/download', '/api/models/download_all',
|
||||
'/api/models/cancel', '/api/models/delete', '/api/models/refresh_manifest', '/api/models/jetlink',
|
||||
'/api/models/laboratory', '/api/models/laboratory/download', '/api/models/laboratory/delete',
|
||||
'/api/sounds/preview', '/api/sounds/download', '/api/sounds/cancel', '/api/software/action', '/api/drives/ignore',
|
||||
|
||||
@@ -30,7 +30,7 @@ from openpilot.starpilot.ui.feature_settings_state import (
|
||||
FeatureRow, FeatureSettingsRequest, FEATURE_CONFIRM_ACTIONS, is_heading, is_long_confirm_action, row_change, row_default,
|
||||
)
|
||||
from openpilot.starpilot.saved_source import read_saved
|
||||
from openpilot.starpilot.galaxy.device_settings import CALIBRATION_RESET, DRIVER_MONITORING_RESET, DeviceSettingsOwner
|
||||
from openpilot.starpilot.galaxy.device_settings import CALIBRATION_RESET, DRIVER_MONITORING_RESET, KEY as VOACC_KEY, HOLD_KEY, DeviceSettingsOwner
|
||||
from openpilot.starpilot.speed_limits.vision_gate import diagnostic_choice_enabled
|
||||
from openpilot.starpilot.parked_evidence import ParkedEvidence, RESUME_SKEW_NS, fresh_offroad, host_parked
|
||||
from openpilot.starpilot.ui.pip_owner import EDITOR as PIP_EDITOR, FORMAT_PREFIX as PIP_FORMAT_PREFIX, RESET as PIP_RESET, PiPOwner, validated_editor_draft
|
||||
@@ -39,7 +39,7 @@ from openpilot.starpilot.ui.sentry_owner import RESET as SENTRY_RESET, SentryOwn
|
||||
from openpilot.starpilot.ui.vasm_owner import ANNOTATION as VASM_ANNOTATION, RESET as VASM_RESET, VASMOwner, validated_annotation
|
||||
|
||||
|
||||
PAGES = frozenset(("hub", "developer", "localization", "starport_options", "driving_options", "resets", "vehicle",
|
||||
PAGES = frozenset(("hub", "developer", "localization", "starport_options", "resets", "vehicle",
|
||||
"slc", "lane", "lane_change", "profiles", "personalities",
|
||||
"traffic", "aggressive", "standard", "relaxed",
|
||||
"curve", "torque", "torque/developer", "tuning", "torque/bluepilot", "aol", "wheel", "appearance", "display",
|
||||
@@ -56,7 +56,7 @@ TTL = 60.0
|
||||
CAR_CONTROL_SECTIONS = (
|
||||
("lateral", "Lateral (Steering)", ("aol", "lane_change", "lane", "torque", "torque/developer")),
|
||||
("longitudinal", "Longitudinal (Speed & Following)",
|
||||
("driving_options", "profiles", "conditional", "curve", "slc", "aggressive", "standard", "relaxed", "traffic")),
|
||||
("profiles", "conditional", "curve", "slc", "aggressive", "standard", "relaxed", "traffic")),
|
||||
("wheel", "Wheel Controls", ("wheel",)),
|
||||
("visual", "Visual (Display & UI)", ("display", "appearance", "pip")),
|
||||
("sounds", "Sounds & Alerts", ("sounds",)),
|
||||
@@ -147,8 +147,8 @@ def _onroad_preference(page: str, key: str) -> bool:
|
||||
# Regular saved choices are consumed by their runtime owners. Only explicit
|
||||
# multi-key reset/repair operations need the offroad transaction boundary;
|
||||
# their owners independently recheck that requirement at commit time.
|
||||
return bool(page not in ("starport_options", "driving_options", "resets", "power") and key and key != SETUP_ACTION and key not in (
|
||||
"IsRhdDetected", "AlphaLongitudinalEnabled", "reset_profiles", "curve_reset", "slc_reset",
|
||||
return bool(page not in ("starport_options", "resets", "power") and key and key != SETUP_ACTION and key not in (
|
||||
VOACC_KEY, HOLD_KEY, "IsRhdDetected", "AlphaLongitudinalEnabled", "reset_profiles", "curve_reset", "slc_reset",
|
||||
"conditional:reset", "conditional:manual_reset",
|
||||
) and not is_long_confirm_action(key) and not key.startswith("torque_repair:"))
|
||||
|
||||
@@ -649,10 +649,12 @@ class SettingsGateway:
|
||||
def _state(self, page: str, ctx: AuthorityContext):
|
||||
if page == "localization":
|
||||
return self._localization_owner(ctx).snapshot()
|
||||
if page in ("starport_options", "driving_options", "resets"):
|
||||
if page in ("starport_options", "resets"):
|
||||
return self._device_settings_owner(ctx).snapshot(page)
|
||||
if page == "developer":
|
||||
return self._appearance_owner(ctx).developer_snapshot()
|
||||
state = self._appearance_owner(ctx).developer_snapshot()
|
||||
driving = self._device_settings_owner(ctx).snapshot("driving_options")
|
||||
return replace(state, subtitle="Advanced driving and display settings.", rows=driving.rows + state.rows)
|
||||
if page == "appearance":
|
||||
return self._appearance_owner(ctx).snapshot(Profile.COMPACT, include_large=True)
|
||||
if page == "sounds":
|
||||
@@ -683,8 +685,7 @@ class SettingsGateway:
|
||||
state = replace(state, title="Data & Connections")
|
||||
if page == "hub":
|
||||
state = replace(state, rows=state.rows + (
|
||||
FeatureRow("", "Developer", "Advanced display calibration", page="developer", available=True),
|
||||
FeatureRow("", "Longitudinal options", "Vision-only cruise control and Enhanced Stops", page="driving_options", available=True),
|
||||
FeatureRow("", "Developer", "Advanced driving and display settings", page="developer", available=True),
|
||||
))
|
||||
if page in ("torque", "torque/developer"):
|
||||
state = replace(state, rows=tuple(row for row in state.rows if row.key not in ("torque:factor:reset", "torque:friction:reset")))
|
||||
@@ -887,6 +888,8 @@ class SettingsGateway:
|
||||
raise SettingsChanged("Default or saved settings changed")
|
||||
if intent.page == "pip":
|
||||
return self._pip_owner(ctx, live=True, session_valid=session_valid).apply(intent.request)
|
||||
if intent.page == "developer" and intent.request.key in (VOACC_KEY, HOLD_KEY):
|
||||
return self._device_settings_owner(ctx, live=True, session_valid=session_valid).apply(intent.request)
|
||||
if intent.page in ("appearance", "developer"):
|
||||
return self._appearance_owner(ctx, live=True, session_valid=session_valid).apply(intent.request)
|
||||
if intent.page == "sounds":
|
||||
@@ -901,7 +904,7 @@ class SettingsGateway:
|
||||
return self._vasm_owner(ctx, live=True, session_valid=session_valid).apply(intent.request)
|
||||
if intent.page == "localization":
|
||||
return self._localization_owner(ctx, live=True, session_valid=session_valid).apply(intent.request)
|
||||
if intent.page in ("starport_options", "driving_options", "resets"):
|
||||
if intent.page in ("starport_options", "resets"):
|
||||
return self._device_settings_owner(ctx, live=True, session_valid=session_valid).apply(intent.request)
|
||||
owner = self._owner(ctx, live=True, session_valid=session_valid)
|
||||
return owner.apply(intent.request, reset_default=True) if intent.recovery_default else owner.apply(intent.request)
|
||||
|
||||
@@ -27,7 +27,7 @@ def _fast_state(raw):
|
||||
try:
|
||||
value = json.loads(raw) if raw is not None else None
|
||||
if not isinstance(value, dict) or value.get("version") != 1 or value.get("stage") not in (
|
||||
"preparing", "fetching", "validating", "applying", "submodules", "rebooting", "complete", "error", "finalizing"):
|
||||
"preparing", "fetching", "validating", "applying", "agnos", "submodules", "rebooting", "complete", "error", "finalizing"):
|
||||
return None
|
||||
detail = value.get("detail")
|
||||
if not isinstance(detail, str) or len(detail) > 512:
|
||||
|
||||
@@ -6,7 +6,7 @@ const assert = require('node:assert/strict')
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 390, height: 844 } })
|
||||
const errors = [], writes = [], requests = []
|
||||
let parked = true, enabled = false
|
||||
let parked = true, enabled = false, hold = false, pendingRow = 0
|
||||
page.on('pageerror', error => errors.push(error.message))
|
||||
await page.route('**/device-settings-test', route => route.fulfill({ contentType: 'text/html', body:
|
||||
'<meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="css/galaxy.css"><link rel="stylesheet" href="css/setup.css"><link rel="stylesheet" href="css/settings.css"><main class="gx-content"><div id="test"></div></main>' }))
|
||||
@@ -18,17 +18,17 @@ const assert = require('node:assert/strict')
|
||||
canSelect: parked, providers: [{ id: 'comma', label: 'comma', url: 'https://connect.comma.ai' }] }
|
||||
else if (path.endsWith('/connect/proxy')) data = { enabled: false, address: '', origin: '', revision: 'proxy', canEdit: parked, passwordConfigured: true }
|
||||
else if (path.endsWith('/pages/hub')) data = { page: 'hub', title: 'Driving Controls', view: 'hub', parked,
|
||||
rows: [{ page: 'driving_options', label: 'Longitudinal options', available: true }, { page: 'profiles', label: 'Long Planner', available: true }] }
|
||||
rows: [{ page: 'developer', label: 'Developer', available: true }, { page: 'profiles', label: 'Long Planner', available: true }] }
|
||||
else if (path.endsWith('/pages/display')) data = { page: 'display', title: 'Display', view: 'display', parked, rows: [{label:'Screen Brightness',value:'Auto',available:true}] }
|
||||
else if (path.endsWith('/pages/data')) data = { page: 'data', title: 'Data & Connections', view: 'data', parked, rows: [{label:'Always Allow Uploads',value:'Off',choices:['Off','On'],available:parked}] }
|
||||
else if (path.endsWith('/pages/starport_options')) data = { page: 'starport_options', title: 'StarPort', view: 'starport', parked, rows: [{label:'Stay on Wi-Fi',value:'On',choices:['Off','On'],available:parked}] }
|
||||
else if (path.endsWith('/pages/localization')) data = { page: 'localization', title: 'Localization', view: 'localization', parked, rows: [{label:'Language',value:'English',available:true}] }
|
||||
else if (path.endsWith('/pages/driving_options')) data = { page: 'driving_options', title: 'Longitudinal options', view: 'driving', parked,
|
||||
rows: [{ label: 'Use VOACC', value: enabled ? 'On' : 'Off', choices: ['Off', 'On'], available: parked, action: true, reason: 'Applies next drive.' }] }
|
||||
else if (path.endsWith('/pages/developer')) data = { page: 'developer', title: 'Developer', view: 'driving', parked,
|
||||
rows: [{ label: 'Use VOACC', value: enabled ? 'On' : 'Off', choices: ['Off', 'On'], available: parked, action: true, reason: 'Applies next drive.' }, { label: 'Always Hold Enhanced Stops', value: hold ? 'On' : 'Off', choices: ['Off', 'On'], available: parked, action: true, reason: 'Applies next drive.' }] }
|
||||
else if (path.endsWith('/pages/resets')) data = { page: 'resets', title: 'Device resets', view: 'resets', parked,
|
||||
rows: ['Reset Driver Monitoring', 'Reset Calibration'].map(label => ({ label, value: 'Ready', confirm: true, available: parked, action: true })) }
|
||||
else if (path.endsWith('/preview')) { writes.push(route.request().postDataJSON()); data = { intent: 'voacc', proposed: 'On', question: 'Set Use VOACC to On?' } }
|
||||
else if (path.endsWith('/confirm')) { enabled = true; data = { saved: true } }
|
||||
else if (path.endsWith('/preview')) { writes.push(route.request().postDataJSON()); pendingRow = writes.at(-1).row; data = { intent: 'voacc', proposed: 'On', question: 'Set Use VOACC to On?' } }
|
||||
else if (path.endsWith('/confirm')) { if (pendingRow === 1) hold = true; else enabled = true; data = { saved: true } }
|
||||
else return route.fulfill({ status: 404, json: { error: 'Unexpected endpoint' } })
|
||||
return route.fulfill({ json: data })
|
||||
})
|
||||
@@ -80,15 +80,22 @@ const assert = require('node:assert/strict')
|
||||
await page.getByText('Language',{exact:true}).waitFor()
|
||||
await page.evaluate(()=>vm.back())
|
||||
await page.getByRole('button', { name: 'Longitudinal (Speed & Following)', exact: true }).click()
|
||||
await page.locator('.gx-row').filter({has:page.getByText('Longitudinal options', {exact:true})}).getByRole('button', {name:'Manage'}).click()
|
||||
assert.equal(await page.getByText('Longitudinal options', {exact:true}).count(), 0)
|
||||
assert.equal(await page.getByRole('switch', {name:'Use VOACC',exact:true}).count(), 0)
|
||||
await page.evaluate(() => mount({ initialPage: 'developer', title: 'Developer' }))
|
||||
const toggle = page.getByRole('switch', { name: 'Use VOACC', exact: true })
|
||||
await toggle.waitFor()
|
||||
await toggle.click()
|
||||
await page.waitForFunction(() => vm.state.data?.rows[0]?.value === 'On')
|
||||
assert.equal(writes[0].value, 'On')
|
||||
const holdToggle = page.getByRole('switch', { name: 'Always Hold Enhanced Stops', exact: true })
|
||||
await holdToggle.click()
|
||||
await page.waitForFunction(() => vm.state.data?.rows[1]?.value === 'On')
|
||||
assert.equal(writes[1].value, 'On')
|
||||
parked = false
|
||||
await page.evaluate(() => vm.feed.load('driving_options'))
|
||||
await page.evaluate(() => vm.feed.load('developer'))
|
||||
assert.equal(await toggle.isDisabled(), true)
|
||||
assert.equal(await holdToggle.isDisabled(), true)
|
||||
await page.evaluate(() => mount({ initialPage: 'resets', title: 'Device resets' }))
|
||||
await page.getByText('Reset Driver Monitoring', { exact: true }).waitFor()
|
||||
await page.getByText('Reset Calibration', { exact: true }).waitFor()
|
||||
|
||||
@@ -71,9 +71,6 @@ print(json.dumps(dict(native=native,projection=projection)))
|
||||
assert.equal(await page.getByRole('button', { name: `${name} is hidden in this scene. Choose General edit to arrange it.`, exact: true }).isDisabled(), true)
|
||||
}
|
||||
if (target !== 'large') assert.equal(state.visible.includes('stopped_timer'), ['general', 'stopped'].includes(scene.id))
|
||||
if (scene.id !== 'general') {
|
||||
assert.equal(state.visible.includes('speed_limit_actions'), false)
|
||||
}
|
||||
if (output) await page.locator('svg.gx-layout__preview').screenshot({ path: path.join(output, `${target}-${scene.id}.png`) })
|
||||
}
|
||||
await page.evaluate(() => { window.editor.state.scene = 'general'; window.editor.togglePreviewVisibility('driver_monitor'); window.editor.state.scene = 'engaged' })
|
||||
|
||||
@@ -178,7 +178,7 @@ class DeviceSettingsTest(unittest.TestCase):
|
||||
token, generation = "session", b"generation"
|
||||
|
||||
def preview(value):
|
||||
page = gateway.page("driving_options", token, generation)
|
||||
page = gateway.page("developer", token, generation)
|
||||
self.assertEqual(page["rows"][0]["label"], "Use VOACC")
|
||||
self.assertEqual(page["rows"][0]["defaultValue"], "Off")
|
||||
self.assertIn("next drive", page["rows"][0]["reason"])
|
||||
@@ -193,7 +193,7 @@ class DeviceSettingsTest(unittest.TestCase):
|
||||
gateway.confirm(intent, token, generation)
|
||||
self.assertEqual(self.path.read_bytes(), b"1")
|
||||
context.value = replace(context.value, parked=True)
|
||||
page = gateway.page("driving_options", token, generation)
|
||||
page = gateway.page("developer", token, generation)
|
||||
intent = gateway.preview(page["view"], 0, 0, token, generation, reset_default=True)
|
||||
self.assertTrue(gateway.confirm(intent["intent"], token, generation))
|
||||
self.assertEqual(self.path.read_bytes(), b"0")
|
||||
@@ -201,6 +201,39 @@ class DeviceSettingsTest(unittest.TestCase):
|
||||
with self.assertRaises(SettingsChanged):
|
||||
gateway.confirm(intent, token, generation, session_valid=lambda: False)
|
||||
|
||||
def test_developer_driving_rows_keep_owner_and_parked_guards(self):
|
||||
from openpilot.starpilot.longitudinal.enhanced_stop_hold import KEY as HOLD_KEY
|
||||
from openpilot.starpilot.galaxy.settings import SettingsUnavailable, _onroad_preference
|
||||
context = SimpleNamespace(value=AuthorityContext(True, None, None))
|
||||
context.sample = lambda: context.value
|
||||
gateway = SettingsGateway(self.params, cast(ContextSource, context), clock=lambda: 10.)
|
||||
token, generation = "session", b"generation"
|
||||
with self.assertRaises(SettingsUnavailable):
|
||||
gateway.page("driving_options", token, generation)
|
||||
for index, key in enumerate((KEY, HOLD_KEY)):
|
||||
with self.subTest(key=key):
|
||||
self.assertFalse(_onroad_preference("developer", key))
|
||||
page = gateway.page("developer", token, generation)
|
||||
row = page["rows"][index]
|
||||
self.assertEqual(row["defaultValue"], "Off")
|
||||
intent = gateway.preview(page["view"], index, 0, token, generation, value="On")["intent"]
|
||||
self.assertTrue(gateway.confirm(intent, token, generation))
|
||||
self.assertEqual(Path(self.params.get_param_path(key)).read_bytes(), b"1")
|
||||
page = gateway.page("developer", token, generation)
|
||||
intent = gateway.preview(page["view"], index, 0, token, generation, value="Off")["intent"]
|
||||
context.value = replace(context.value, parked=False)
|
||||
with self.assertRaises(SettingsChanged):
|
||||
gateway.confirm(intent, token, generation)
|
||||
self.assertFalse(gateway.page("developer", token, generation)["rows"][index]["available"])
|
||||
context.value = replace(context.value, parked=True, editing_saved_vehicle=True)
|
||||
self.assertFalse(gateway.page("developer", token, generation)["rows"][index]["available"])
|
||||
context.value = replace(context.value, editing_saved_vehicle=False)
|
||||
page = gateway.page("developer", token, generation)
|
||||
intent = gateway.preview(page["view"], index, 0, token, generation, reset_default=True)["intent"]
|
||||
self.assertTrue(gateway.confirm(intent, token, generation))
|
||||
self.assertEqual(Path(self.params.get_param_path(key)).read_bytes(), b"0")
|
||||
self.assertEqual(gateway.page("developer", token, generation)["rows"][2]["label"], "Speed display adjustment")
|
||||
|
||||
def test_starport_stay_on_wifi_toggle(self):
|
||||
self.assertNotIn(STARPORT_WIFI_KEY, [row.key for row in self.owner.snapshot("starport_options").rows])
|
||||
service = FakeStarPort()
|
||||
|
||||
@@ -4,20 +4,16 @@ import { LayoutPreviewFeed, PREVIEW_SCENES, sceneHidesWidget } from "../web/js/l
|
||||
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() }
|
||||
const document = { version: 1, palette: { text: "#FFFFFFFF" }, layouts: { large: {}, compact: {} } }
|
||||
|
||||
const signLayout = { speed_limit: { x: 160, y: 80, enabled: true }, speed_limit_actions: { x: 16, y: 20, enabled: true } }
|
||||
const signWidgets = { speed_limit: { width: 264, height: 82, visualInsetTop: 12 }, speed_limit_actions: { width: 440, height: 52 } }
|
||||
const signLayout = { speed_limit: { x: 160, y: 80, enabled: true } }
|
||||
const signWidgets = { speed_limit: { width: 264, height: 82, visualInsetTop: 12 } }
|
||||
assert.equal(sceneHidesWidget('slc_pending', 'compact', 'speed_limit', signLayout, signWidgets), false, 'The chooser belongs to the sign and must not hide it')
|
||||
assert.equal(sceneHidesWidget('engaged', 'compact', 'speed_limit', signLayout, signWidgets), false)
|
||||
for (const scene of ['slc_pending', 'slc_max', 'slc_retained']) {
|
||||
for (const profile of ['large', 'compact'])
|
||||
assert.equal(sceneHidesWidget(scene, profile, 'speed_limit_actions'), true)
|
||||
for (const scene of ['slc_pending', 'slc_max', 'slc_retained'])
|
||||
assert.equal(sceneHidesWidget(scene, 'compact', 'speed_limit', signLayout, signWidgets), false)
|
||||
}
|
||||
assert.equal(sceneHidesWidget('slc_equal', 'compact', 'speed_limit_actions'), true)
|
||||
assert.equal(sceneHidesWidget('slc_pending', 'compact', 'speed_limit', signLayout,
|
||||
{ ...signWidgets, speed_limit: { ...signWidgets.speed_limit, visualInsetTop: 0 } }), false)
|
||||
const restoredLayout = { speed_limit: {x:330, y:20, enabled:true}, speed_limit_actions: {x:128, y:186, enabled:true} }
|
||||
const restoredWidgets = { speed_limit: {width:118, height:132}, speed_limit_actions: {width:348, height:54} }
|
||||
const restoredLayout = { speed_limit: {x:330, y:20, enabled:true} }
|
||||
const restoredWidgets = { speed_limit: {width:118, height:132} }
|
||||
assert.equal(sceneHidesWidget('slc_pending', 'compact', 'speed_limit', restoredLayout, restoredWidgets), false)
|
||||
assert.equal(sceneHidesWidget('slc_pending', 'compact', 'speed_limit', {
|
||||
...restoredLayout, speed_limit: {...restoredLayout.speed_limit, y:60}
|
||||
|
||||
@@ -81,13 +81,15 @@ assert.equal(download.requests[1].url,'./api/models/laboratory/download');assert
|
||||
await download.reply(1,{message:'Starting download'});await download.reply(2,{...p,download:{downloading:true,jobId:'job',progress:'40%'}});await downloading
|
||||
const canceling=download.feed.action('cancel');assert.equal(download.requests[3].url,'./api/models/cancel');assert.deepEqual(JSON.parse(download.requests[3].options.body),{jobId:'job'})
|
||||
await download.reply(3,{message:'Cancelling'});await download.reply(4,p);await canceling;download.feed.stop()
|
||||
// Model Laboratory lives on the Models page: Single model / Model pair mode switcher and eGPU variants on the model rows
|
||||
// Split Model has its own tab alongside Single Model and Conditional Model.
|
||||
const template = ModelsPage.template
|
||||
const labCard = template.indexOf('id="gx-model-laboratory"')
|
||||
assert.ok(template.indexOf('Single model') < labCard && labCard < template.indexOf('gx-model-list'))
|
||||
assert.match(template,/aria-label="Lateral model"/)
|
||||
assert.match(template,/aria-label="Longitudinal model"/)
|
||||
assert.ok(template.includes(`@click="setDriveMode('pair')"><i aria-hidden="true" class="bi bi-bezier2"></i> Model pair</button>`))
|
||||
assert.ok(template.indexOf('Single Model') < labCard && labCard < template.indexOf('gx-model-list'))
|
||||
assert.match(template,/aria-label="Steering model"/)
|
||||
assert.match(template,/aria-label="Speed model"/)
|
||||
assert.ok(template.includes(`@click="setDriveMode('split')"><i aria-hidden="true" class="bi bi-bezier2"></i> Split Model</button>`))
|
||||
assert.match(template, /setDriveMode\('conditional'\)/)
|
||||
assert.match(template, /Use Split Model/)
|
||||
assert.match(template,/Verified downloads/)
|
||||
assert.match(template,/eGPU variant/)
|
||||
assert.match(template,/Pairable/)
|
||||
@@ -107,7 +109,7 @@ console.log('Model Laboratory contracts passed')
|
||||
assert.match(template,/steers · \{\{ labModelLabel\(labConfig\.longitudinalModel\) \}\} paces/)
|
||||
assert.match(template,/The pair takes effect the next time the driving model starts/)
|
||||
assert.match(template,/row\?\.small \|\| row\?\.modelLabEligible/)
|
||||
assert.match(template,/Pair lateral judgment from one model with longitudinal judgment from another\./)
|
||||
assert.match(template,/One model for steering, another for speed\. Requires Chestnut\./)
|
||||
|
||||
const malformedSave=fixture();malformedSave.feed.start();await malformedSave.reply(0,p)
|
||||
const malformedSaving=malformedSave.feed.action('save',null,p.configuration)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { GalaxySettingRow, settingControl } from "../web/js/galaxy-setting-row.js"
|
||||
import { ModelStatusFeed, ModelManagerFeed, ModelsPage, modelActionAllowed, fitsModelProfile, formatRate, formatEta, describeProgress } from "../web/js/models.js"
|
||||
|
||||
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() }
|
||||
@@ -48,6 +49,13 @@ await normal.reply(1, payload)
|
||||
assert.equal(normal.states.at(-1).status, "idle")
|
||||
assert.equal(normal.timers.size, 0)
|
||||
|
||||
const conditionalRecovery = fixture()
|
||||
conditionalRecovery.feed.start()
|
||||
await conditionalRecovery.reply(0, { ...payload, fallbackReason: 'conditional-switch-failed' })
|
||||
assert.equal(conditionalRecovery.states.at(-1).status, 'ready')
|
||||
assert.equal(conditionalRecovery.states.at(-1).data.fallbackReason, 'conditional-switch-failed')
|
||||
conditionalRecovery.feed.stop()
|
||||
|
||||
const late = fixture()
|
||||
late.feed.start()
|
||||
late.feed.stop()
|
||||
@@ -201,6 +209,44 @@ await download
|
||||
assert.equal(management.unauthorized, 0)
|
||||
assert.equal(management.timers.size, 0)
|
||||
|
||||
const conditionalPayload = { ...managerPayload, conditionalModel: { enabled: true, highway: 'small', city: 'pending', thresholdMph: 50 },
|
||||
capabilities: { ...managerPayload.capabilities, conditionalModel: true, randomizer: true } }
|
||||
assert.equal(modelActionAllowed(conditionalPayload, 'conditional_model'), true)
|
||||
for (const denied of [{isOnroad:true}, {isOnroad:undefined}, {randomizer:true}, {downloading:true}]) {
|
||||
assert.equal(modelActionAllowed({...conditionalPayload, ...denied}, 'conditional_model'), false)
|
||||
}
|
||||
assert.equal(modelActionAllowed(conditionalPayload, 'select-small', small), false)
|
||||
assert.equal(modelActionAllowed(conditionalPayload, 'enable-randomizer'), false)
|
||||
assert.equal(modelActionAllowed(conditionalPayload, 'delete', { ...pending, installed: true }), false)
|
||||
assert.deepEqual(ModelsPage.computed.conditionalModels.call({ models: managerPayload.models, conditionalModel: conditionalPayload.conditionalModel })
|
||||
.map(m => m.value), ['small', 'pending'])
|
||||
const conditional = managerFixture()
|
||||
conditional.manager.start()
|
||||
await conditional.reply(0, conditionalPayload)
|
||||
const speedSave = conditional.manager.action('conditional_model', null, { thresholdMph: 60 })
|
||||
assert.equal(conditional.requests[1].url, './api/models/conditional_model')
|
||||
assert.deepEqual(JSON.parse(conditional.requests[1].options.body), { thresholdMph: 60 })
|
||||
assert.equal(conditional.manager.data.conditionalModel.thresholdMph, 50)
|
||||
;[...conditional.timers.values()].find(t => t.ms === 10000).fn()
|
||||
assert.equal(conditional.manager.data, null)
|
||||
assert.equal(await conditional.manager.action('conditional_model', null, { thresholdMph: 70 }), null)
|
||||
await conditional.reply(1, { message: 'late success' })
|
||||
if (conditional.requests[2]) await conditional.reply(2, { ...conditionalPayload, conditionalModel: { ...conditionalPayload.conditionalModel, thresholdMph: 60 } })
|
||||
await speedSave
|
||||
conditional.manager.stop()
|
||||
for (const phase of ['waiting', 'switching', 'recovering', 'ready']) {
|
||||
assert.equal(ModelsPage.computed.conditionalSwitchPending.call({status:{conditionalModelState:{phase}}}), phase !== 'ready')
|
||||
}
|
||||
const speedRow = ModelsPage.computed.conditionalSpeedRow.call({conditionalModel:{thresholdMph:50}})
|
||||
assert.equal(speedRow.value, '50')
|
||||
assert.equal(settingControl(speedRow), 'slider')
|
||||
assert.equal(ModelsPage.components.GalaxySettingRow, GalaxySettingRow)
|
||||
const settingsWrites=[]
|
||||
const settingsPage={configureConditionalModel: async update => { settingsWrites.push(update); return true }}
|
||||
await ModelsPage.methods.saveConditionalSetting.call(settingsPage, 0, 'On')
|
||||
await ModelsPage.methods.saveConditionalSetting.call(settingsPage, 1, '60')
|
||||
assert.deepEqual(settingsWrites, [{enabled:true}, {thresholdMph:60}])
|
||||
|
||||
const access = managerFixture()
|
||||
access.manager.start()
|
||||
await access.reply(0, { code: "access_unavailable" }, 503)
|
||||
@@ -252,8 +298,8 @@ console.log('Randomizer and exclusion interactions passed')
|
||||
|
||||
assert.match(ModelsPage.template, /Selections apply next onroad cycle/)
|
||||
assert.doesNotMatch(ModelsPage.template, /Onroad: switching/)
|
||||
// Active Small, Active Big summary items, and the Laboratory pair's lateral and longitudinal pickers
|
||||
assert.equal((ModelsPage.template.match(/class="gx-model-control[\s"]/g) || []).length, 4)
|
||||
assert.match(ModelsPage.template, /Conditional driving models/)
|
||||
assert.match(ModelsPage.template, /Starts each drive in City/)
|
||||
// the library tab is only a view: every model is one tap away, and a sleeping GPU never hides anything
|
||||
assert.equal(ModelsPage.data().tab, 'both')
|
||||
assert.equal(ModelsPage.computed.libraryTab.call({ tab: 'gpu' }), 'gpu')
|
||||
@@ -402,6 +448,11 @@ const pairPage = { selectionUncertain: false, status: {}, runtime: { status: 're
|
||||
assert.equal(ModelsPage.computed.runningModelLabel.call(pairPage), 'Small model/Big model')
|
||||
assert.equal(ModelsPage.computed.runningModelLabel.call({ ...pairPage, runtime: { status: 'stale', data: pairData } }), 'Status unavailable')
|
||||
assert.equal(ModelsPage.computed.runningModelLabel.call({ ...pairPage, runtime: { status: 'ready', data: { ...pairData, laboratory: { ...pairData.laboratory, active: false } } } }), 'Laboratory output unavailable')
|
||||
for (const [health, expected] of [['loading', 'Loading…'], ['stale', 'Model output stale'], ['failed', 'Model status mismatch'],
|
||||
['identity-unavailable', 'Identity unverified']]) {
|
||||
assert.equal(ModelsPage.computed.runningModelLabel.call({ ...pairPage,
|
||||
runtime: { status: 'ready', data: { ...pairData, laboratory: null, health } } }), expected)
|
||||
}
|
||||
assert.match(ModelsPage.template, /fallback choices/)
|
||||
const pendingStart = data => ModelsPage.computed.pendingNextStart.call({ runtime: { status: 'ready', data } })
|
||||
assert.equal(pendingStart({ ...pairData, pendingNextStart: false }), false)
|
||||
@@ -410,6 +461,35 @@ assert.equal(pendingStart({ ...pairData, laboratory: { ...pairData.laboratory, p
|
||||
assert.equal(ModelsPage.computed.pendingNextStart.call({ runtime: { status: 'stale', data: { pendingNextStart: true } } }), false)
|
||||
assert.equal(ModelsPage.template.match(/v-if="pendingNextStart"> · saved changes pending next start/g).length, 2)
|
||||
|
||||
// Browsing settings must never change the driving configuration.
|
||||
{
|
||||
const page = { ...ModelsPage.data(), lab: { configuration: { enabled: true } }, conditionalModel: { enabled: true },
|
||||
runLabAction: () => { throw new Error('Tab navigation wrote configuration') },
|
||||
enablePair: () => { throw new Error('Tab navigation enabled Split Model') } }
|
||||
assert.equal(ModelsPage.computed.driveMode.call(page), 'split')
|
||||
for (const mode of ['conditional', 'single', 'split']) {
|
||||
ModelsPage.methods.setDriveMode.call(page, mode)
|
||||
assert.equal(ModelsPage.computed.driveMode.call(page), mode)
|
||||
}
|
||||
ModelsPage.methods.setDriveMode.call(page, 'invalid')
|
||||
assert.equal(page.driveView, 'split')
|
||||
assert.equal(ModelsPage.computed.driveMode.call({ driveView: null, lab: null, conditionalModel: { enabled: true } }), 'conditional')
|
||||
assert.equal(ModelsPage.computed.driveMode.call({ driveView: null, lab: null, conditionalModel: { enabled: false } }), 'single')
|
||||
const conditionalTemplate = ModelsPage.template.slice(ModelsPage.template.indexOf(`<template v-else-if="driveMode === 'conditional'">`),
|
||||
ModelsPage.template.indexOf('id="gx-model-laboratory"'))
|
||||
assert.match(conditionalTemplate, /Conditional driving models/)
|
||||
assert.match(conditionalTemplate, /Starts each drive in City/)
|
||||
assert.match(conditionalTemplate, /Switching conditional models/)
|
||||
assert.doesNotMatch(conditionalTemplate, /Road selection|Start the drive in|cooldown|cityDelaySeconds|type="number"|Switch to Highway|Switch to City/)
|
||||
assert.match(conditionalTemplate, /Wait before engaging/)
|
||||
const single = ModelsPage.template.slice(ModelsPage.template.indexOf(`<template v-if="driveMode === 'single'">`),
|
||||
ModelsPage.template.indexOf(`<template v-else-if="driveMode === 'conditional'">`))
|
||||
assert.doesNotMatch(single, /id="gx-small-/)
|
||||
const saved = await ModelsPage.methods.saveLabPair.call({ disposed: false, labActionAvailable: () => true,
|
||||
runLabAction: async () => ({ message: 'saved' }), enablePair: () => { throw new Error('Saving enabled Split Model') } })
|
||||
assert.equal(saved.message, 'saved')
|
||||
}
|
||||
|
||||
// Merged page: search, row list, Single model / Model pair mode switcher, and pair saving.
|
||||
{
|
||||
const { matchesSearch, laboratoryActionAllowed, hardwareTag } = await import("../web/js/models.js")
|
||||
|
||||
@@ -136,6 +136,11 @@ class LocalModelManagerHttpTest(unittest.TestCase):
|
||||
status, snapshot = request('/api/models/manager')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertFalse(snapshot['randomizer'])
|
||||
self.assertFalse(snapshot['conditionalModel']['enabled'])
|
||||
self.assertTrue(snapshot['capabilities']['conditionalModel'])
|
||||
self.assertEqual(request('/api/models/conditional_model', {'thresholdMph': 60})[0], 200)
|
||||
self.assertEqual(preferences(manager.root)['conditionalModel']['thresholdMph'], 60)
|
||||
self.assertEqual(request('/api/models/conditional_model', {'selected': 'unknown'})[0], 409)
|
||||
self.assertIsNone(snapshot['downloadProgress'])
|
||||
self.assertEqual(request('/api/models/jetlink', {'mode': 'usb'})[0], 200)
|
||||
self.assertEqual(link.mode, 'usb')
|
||||
@@ -160,6 +165,8 @@ class LocalModelManagerHttpTest(unittest.TestCase):
|
||||
self.assertEqual(preferences(manager.root)['blacklistedModels'], ['gwm8223'])
|
||||
self.assertEqual(request('/api/models/active', {'profile': 'small', 'model': 'bundled-current'})[0], 409)
|
||||
parked[0] = False
|
||||
self.assertEqual(request('/api/models/conditional_model', {'selected': 'highway'})[0], 409)
|
||||
self.assertEqual(preferences(manager.root)['conditionalModel']['thresholdMph'], 60)
|
||||
self.assertEqual(request('/api/models/jetlink', {'mode': 'off'})[0], 409)
|
||||
self.assertEqual(link.mode, 'usb')
|
||||
self.assertEqual(request('/api/models/laboratory', pair)[0], 200)
|
||||
@@ -170,6 +177,7 @@ class LocalModelManagerHttpTest(unittest.TestCase):
|
||||
self.assertEqual(request('/api/models/jetlink', {'mode': 'off'}, forwarded=True)[0], 503)
|
||||
self.assertEqual(link.mode, 'usb')
|
||||
self.assertEqual(request('/api/models/manager', forwarded=True)[0], 503)
|
||||
self.assertEqual(request('/api/models/conditional_model', {'selected': 'highway'}, forwarded=True)[0], 503)
|
||||
self.assertEqual(request('/api/models/laboratory', forwarded=True)[0], 503)
|
||||
finally:
|
||||
server.shutdown()
|
||||
|
||||
@@ -26,11 +26,9 @@ for style in SIGNAL_SIZES:
|
||||
print(json.dumps(documents))
|
||||
`], { encoding: "utf8" }))
|
||||
for (const document of signalEdges) assert.equal(validDocument(document, data.metadata), true)
|
||||
for (const version of [11, 12, 13, 14, 15]) {
|
||||
assert.equal(validSnapshot({ ...data, document: { ...data.document, version } }), true)
|
||||
assert.equal(validSnapshot({ ...data, defaults: { ...data.defaults, version } }), true)
|
||||
}
|
||||
for (const version of [9, 10, 16]) {
|
||||
assert.equal(validSnapshot(data), true)
|
||||
assert.equal(data.document.version, 16)
|
||||
for (const version of [9, 10, 15, 17]) {
|
||||
assert.equal(validSnapshot({ ...data, document: { ...data.document, version } }), false)
|
||||
assert.equal(validSnapshot({ ...data, defaults: { ...data.defaults, version } }), false)
|
||||
}
|
||||
@@ -107,36 +105,28 @@ assert.equal(vm.layout.nav_map.enabled, true)
|
||||
assert.equal(vm.layout.nav_map.opacity, 35)
|
||||
assert.equal(validSnapshot({ ...data, document: vm.state.draft }), true)
|
||||
|
||||
// Use actual native geometry for source attachment, bounds, and the transient timer.
|
||||
assert.deepEqual(data.metadata.profiles.large.widgets.cruise_limits.sourcesExtent, {inline:114, card:122, actionGap:8})
|
||||
// Use actual native geometry for source growth, bounds, and the transient timer.
|
||||
assert.deepEqual(data.metadata.profiles.large.widgets.cruise_limits.sourcesExtent, {inline:114, card:122})
|
||||
vm.state.draft = structuredClone(data.document)
|
||||
vm.state.selected = "cruise_limits"
|
||||
vm.setSpeedSources("speedSources", true)
|
||||
assert.equal(vm.layout.speed_limit_actions.y, 449)
|
||||
vm.setSpeedSources("speedSourcesCard", true)
|
||||
assert.equal(vm.layout.speed_limit_actions.y, 457)
|
||||
assert.equal(vm.layout.cruise_limits.y, 75)
|
||||
vm.setSpeedSources("speedSources", false)
|
||||
assert.equal(vm.layout.speed_limit_actions.y, 325)
|
||||
const overlapping = structuredClone(data.document)
|
||||
overlapping.layouts.large.cruise_limits.y = 550
|
||||
assert.equal(validDocument(overlapping, data.metadata), false)
|
||||
// Disable torque while testing source attachment at the lower screen edge.
|
||||
// Disable torque while testing sources at the lower screen edge.
|
||||
vm.layout.torque_bar.enabled = false
|
||||
vm.layout.cruise_limits.x = 1300
|
||||
vm.layout.speed_limit_actions.x = 1324
|
||||
vm.layout.cruise_limits.y = 690
|
||||
vm.layout.speed_limit_actions.y = 940
|
||||
vm.setSpeedSources("speedSources", true)
|
||||
assert.equal(vm.layout.cruise_limits.y, 500)
|
||||
assert.equal(vm.layout.speed_limit_actions.y, 882)
|
||||
assert.equal(vm.layout.cruise_limits.y, 1050 - vm.profile.widgets.cruise_limits.height)
|
||||
assert.equal(validDocument(vm.state.draft, data.metadata), true)
|
||||
const beyondNewPromptWidth = JSON.parse(JSON.stringify(vm.state.draft))
|
||||
beyondNewPromptWidth.layouts.large.cruise_limits.x = 1430
|
||||
assert.equal(validDocument(beyondNewPromptWidth, data.metadata), false)
|
||||
|
||||
Object.assign(vm.layout.speed_limit_actions, {x:600, y:500})
|
||||
vm.setSpeedSources("speedSources", false)
|
||||
assert.deepEqual([vm.layout.speed_limit_actions.x, vm.layout.speed_limit_actions.y], [600, 500])
|
||||
const signal = vm.profile.widgets.network_signal, signalBounds = signal.bounds || vm.profile.bounds
|
||||
assert.equal(signal.label, "Connections")
|
||||
vm.layout.network_signal.enabled = true
|
||||
@@ -177,7 +167,7 @@ vm.state.profile = "compact"
|
||||
vm.add("stopped_timer")
|
||||
assert.equal(vm.layout.stopped_timer.enabled, true)
|
||||
assert.equal(validDocument(vm.state.draft, data.metadata), true)
|
||||
assert.deepEqual(clampPlacement(vm.profile, "speed_limit_actions", 146, 44, vm.layout), {x:146, y:44})
|
||||
assert.deepEqual(clampPlacement(vm.profile, "steering_wheel", 146, 44, vm.layout), {x:146, y:44})
|
||||
console.log("Native Big widgets: real metadata, optional add/move/remove, map resize/opacity and undo passed")
|
||||
|
||||
// C4 has the same independent native navigation switch; StarPort is another document.
|
||||
|
||||
@@ -56,12 +56,12 @@ class TestOffroadConfigurationPages(unittest.TestCase):
|
||||
with self.subTest(page=name):
|
||||
current = self.editable_inventory(self.page(name))
|
||||
expected = saved[name]
|
||||
if name == 'driving_options':
|
||||
if name == 'developer':
|
||||
# gated by Park, not by the vehicle
|
||||
self.assertEqual([row[0] for row in expected], ['Use VOACC', 'Always Hold Enhanced Stops'])
|
||||
self.assertEqual([row[1] for row in expected], [False, False])
|
||||
self.assertEqual([row[1] for row in current], [True, True])
|
||||
expected = [(row[0], True, *row[2:]) for row in expected]
|
||||
self.assertEqual([row[0] for row in expected[:2]], ['Use VOACC', 'Always Hold Enhanced Stops'])
|
||||
self.assertEqual([row[1] for row in expected[:2]], [False, False])
|
||||
self.assertEqual([row[1] for row in current[:2]], [True, True])
|
||||
expected = [(row[0], True, *row[2:]) for row in expected[:2]] + expected[2:]
|
||||
if name == 'profiles':
|
||||
# Saved configuration uses the native catalog; this preference is Galaxy-only.
|
||||
label = 'Disengage on Accelerator Pedal'
|
||||
|
||||
@@ -15,16 +15,14 @@ export function snapshot() {
|
||||
large: { label: "Large UI", width: 2160, height: 1080, bounds: { x: 30, y: 30, width: 1800, height: 1020 }, reservedZones: [], widgets: {
|
||||
current_speed: widget("Current speed", "current_speed", 580, 300, 640, 30),
|
||||
cruise_limits: widget("Cruise and speed limit", "cruise_limits", 480, 522, 88, 75),
|
||||
speed_limit_actions: widget("Speed limit actions", "speed_limit_actions", 480, 108, 88, 567),
|
||||
steering_wheel: widget("Steering wheel", "steering_wheel", 192, 192, 1588, 75),
|
||||
driver_monitor: widget("Driver monitoring", "driver_monitor", 192, 192, 88, 808),
|
||||
torque_bar: { ...widget("Torque bar", "torque_bar", 998, 240, 439, 759), layer: "underlay" },
|
||||
} },
|
||||
compact: { label: "Small UI", width: 536, height: 240, bounds: { x: 0, y: 0, width: 476, height: 240 },
|
||||
protectedWidget: "speed_limit_actions", reservedZones: [], widgets: {
|
||||
reservedZones: [], widgets: {
|
||||
max_speed: widget("Maximum speed", "max_speed", 162, 162, 0, 0),
|
||||
speed_limit: widget("Speed limit", "speed_limit", 118, 132, 330, 20),
|
||||
speed_limit_actions: widget("Speed limit actions", "speed_limit_actions", 282, 54, 174, 180),
|
||||
steering_wheel: widget("Steering wheel", "steering_wheel", 50, 50, 21, 176),
|
||||
driver_monitor: widget("Driver monitoring", "driver_monitor", 60, 60, 16, 10),
|
||||
torque_bar: { ...widget("Torque bar", "torque_bar", 260, 61, 116, 167), layer: "underlay" },
|
||||
@@ -38,11 +36,10 @@ export function snapshot() {
|
||||
{ id: "text", label: "Text", default: "#FFFFFFFF" },
|
||||
] }
|
||||
const frame = { cardFill: "#00000000", cardBorder: "#00000000" }
|
||||
const actions = { cardFill: "#0C1820EB", cardBorder: "#A6DFBEFF", text: "#FFFFFFFF" }
|
||||
const colors = {
|
||||
large: { current_speed: { text: null }, cruise_limits: { cardFill: null, cardBorder: null, text: null },
|
||||
speed_limit_actions: actions, steering_wheel: { cardFill: null, cardBorder: "#00000000" }, driver_monitor: frame },
|
||||
compact: { max_speed: { text: null }, speed_limit_actions: actions, driver_monitor: frame, model_confidence: frame,
|
||||
steering_wheel: { cardFill: null, cardBorder: "#00000000" }, driver_monitor: frame },
|
||||
compact: { max_speed: { text: null }, driver_monitor: frame, model_confidence: frame,
|
||||
conditional_mode: frame, following_distance: { ...frame, text: "#FFFFFFFF" } },
|
||||
}
|
||||
for (const [profile, data] of Object.entries(metadata.profiles))
|
||||
@@ -56,8 +53,8 @@ export function snapshot() {
|
||||
metadata.profiles.compact.widgets.steering_wheel.resizable = { min: 40, default: 50, max: 70 }
|
||||
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_actions.visualInsetTop = 32
|
||||
const document = { version: 11, roadColors: { large: {}, compact: {} }, widgetColors: { large: {}, compact: {} }, palette: Object.fromEntries(metadata.paletteFields.map((field) => [field.id, field.default])),
|
||||
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])),
|
||||
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 } : {}) }]))])) }
|
||||
@@ -70,14 +67,13 @@ for (const name of ["layoutDocument", "previewDocument", "withDisplay", "ordered
|
||||
|
||||
const data = snapshot()
|
||||
const restoredCompact = copy(data)
|
||||
for (const [id, width, height, x, y] of [["max_speed", 162, 162, 0, 0], ["speed_limit", 118, 132, 330, 20], ["speed_limit_actions", 348, 54, 128, 186]]) {
|
||||
for (const [id, width, height, x, y] of [["max_speed", 162, 162, 0, 0], ["speed_limit", 118, 132, 330, 20]]) {
|
||||
Object.assign(restoredCompact.metadata.profiles.compact.widgets[id], { width, height, default: {x, y, enabled:true} })
|
||||
restoredCompact.document.layouts.compact[id] = {x, y, enabled:true}
|
||||
}
|
||||
delete restoredCompact.metadata.profiles.compact.widgets.speed_limit_actions.visualInsetTop
|
||||
restoredCompact.defaults = copy(restoredCompact.document)
|
||||
assert.equal(validSnapshot(restoredCompact), true, "Restored small-UI defaults are editable")
|
||||
assert.equal(clampPlacement(restoredCompact.metadata.profiles.compact, "max_speed", 174, 25, restoredCompact.document.layouts.compact), null)
|
||||
assert.deepEqual(clampPlacement(restoredCompact.metadata.profiles.compact, "max_speed", 174, 25, restoredCompact.document.layouts.compact), {x:174, y:25})
|
||||
assert.deepEqual(clampPlacement(restoredCompact.metadata.profiles.compact, "speed_limit", 330, 20, restoredCompact.document.layouts.compact), {x:330, y:20})
|
||||
assert.deepEqual(restoredCompact.document.layouts.large, data.document.layouts.large)
|
||||
const withMode = copy(data)
|
||||
@@ -86,26 +82,24 @@ withMode.metadata.profiles.compact.widgets[modeId] = {
|
||||
...widget("Driving Mode Descriptions", modeId, 168, 60, 162, 22), colors: { text: "#FFFFFFFF" },
|
||||
}
|
||||
withMode.document.layouts.compact[modeId] = { x: 162, y: 22, enabled: false }
|
||||
withMode.document.layouts.compact.speed_limit_actions.y = 45
|
||||
withMode.defaults = copy(withMode.document)
|
||||
assert.equal(validSnapshot(withMode), true)
|
||||
assert.equal(clampPlacement(withMode.metadata.profiles.compact, modeId, 162, 22, withMode.document.layouts.compact), null)
|
||||
assert.deepEqual(clampPlacement(withMode.metadata.profiles.compact, modeId, 162, 22, withMode.document.layouts.compact), { x: 162, y: 22 })
|
||||
withMode.document.layouts.compact[modeId].enabled = true
|
||||
assert.equal(validDocument(withMode.document, withMode.metadata), false)
|
||||
withMode.document.layouts.compact[modeId].y = 110
|
||||
assert.equal(validDocument(withMode.document, withMode.metadata), true)
|
||||
|
||||
// Hidden widgets free their space, but adding them back still requires a valid placement.
|
||||
{
|
||||
const sample = copy(data), layout = sample.document.layouts.compact, profile = sample.metadata.profiles.compact
|
||||
profile.widgets.speed_limit.confirmation = { x: -172, y: -8, width: 328, height: 159 }
|
||||
layout.max_speed.enabled = false
|
||||
assert.deepEqual(clampPlacement(profile, "speed_limit_actions", 80, 80, layout), { x: 80, y: 80 })
|
||||
Object.assign(layout.speed_limit_actions, { x: 80, y: 80 })
|
||||
assert.equal(validSnapshot(sample), true)
|
||||
assert.equal(clampPlacement(profile, "max_speed", 0, 0, layout), null)
|
||||
assert.deepEqual(clampPlacement(profile, "speed_limit", 200, 16, layout), { x: 200, y: 16 })
|
||||
Object.assign(layout.speed_limit, { x: 200, y: 16 })
|
||||
assert.equal(validDocument(sample.document, sample.metadata), true)
|
||||
assert.deepEqual(clampPlacement(profile, "max_speed", 0, 0, layout), { x: 0, y: 0 })
|
||||
layout.max_speed.enabled = true
|
||||
assert.equal(validDocument(sample.document, sample.metadata), false)
|
||||
assert.equal(clampPlacement(profile, "speed_limit_actions", 80, 80, layout), null)
|
||||
assert.equal(clampPlacement(profile, "speed_limit", 200, 16, layout), null)
|
||||
layout.max_speed.enabled = false
|
||||
layout.max_speed.x = -1
|
||||
assert.equal(validDocument(sample.document, sample.metadata), false)
|
||||
@@ -131,7 +125,7 @@ for (const mutate of [
|
||||
(value) => { value.document.palette.text = "red" },
|
||||
(value) => { value.document.layouts.large.current_speed.x = Infinity },
|
||||
(value) => { value.document.layouts.compact.steering_wheel.size = 71 },
|
||||
(value) => { value.document.layouts.compact.speed_limit_actions.size = 70 },
|
||||
(value) => { value.document.layouts.compact.max_speed.size = 70 },
|
||||
(value) => { delete value.document.layouts.compact },
|
||||
(value) => { value.metadata.profiles.compact.bounds.width = 9999 },
|
||||
(value) => { value.metadata.paletteFields[1].id = "text" },
|
||||
@@ -140,21 +134,12 @@ for (const mutate of [
|
||||
const invalid = copy(data); mutate(invalid); assert.equal(validSnapshot(invalid), false)
|
||||
}
|
||||
assert.equal(validDocument({ ...data.document, arbitrary: 1 }, data.metadata), false)
|
||||
assert.equal(clampPlacement(data.metadata.profiles.compact, "max_speed", 999, 999), null)
|
||||
assert.deepEqual(clampPlacement(data.metadata.profiles.compact, "max_speed", 999, 18), { x: 314, y: 18 })
|
||||
assert.equal(clampPlacement(data.metadata.profiles.compact, "max_speed", 999, 19), null)
|
||||
const movedActions = copy(data.document.layouts.compact)
|
||||
movedActions.speed_limit_actions.x = 100
|
||||
assert.deepEqual(clampPlacement(data.metadata.profiles.compact, "speed_limit_actions", 100, 180, data.document.layouts.compact), { x: 100, y: 180 })
|
||||
assert.equal(clampPlacement(data.metadata.profiles.compact, "speed_limit_actions", 10, 180, data.document.layouts.compact), null)
|
||||
assert.equal(clampPlacement(data.metadata.profiles.compact, "max_speed", 100, 19, movedActions), null)
|
||||
assert.deepEqual(clampPlacement(data.metadata.profiles.compact, "speed_limit", 330, 20, movedActions), { x: 330, y: 20 })
|
||||
assert.equal(validDocument({ ...data.document, layouts: { ...data.document.layouts, compact: movedActions } }, data.metadata), true)
|
||||
assert.deepEqual(clampPlacement(data.metadata.profiles.compact, "max_speed", 999, 999), { x: 314, y: 78 })
|
||||
const resizedWheel = copy(data.document)
|
||||
resizedWheel.layouts.compact.steering_wheel.size = 70
|
||||
resizedWheel.layouts.compact.steering_wheel.y = 160
|
||||
assert.equal(validDocument(resizedWheel, data.metadata), true)
|
||||
assert.equal(clampPlacement(data.metadata.profiles.compact, "steering_wheel", 150, 170, resizedWheel.layouts.compact), null)
|
||||
assert.deepEqual(clampPlacement(data.metadata.profiles.compact, "steering_wheel", 150, 170, resizedWheel.layouts.compact), { x: 150, y: 170 })
|
||||
assert.deepEqual(clampPlacement(data.metadata.profiles.compact, "steering_wheel", 21, 176, resizedWheel.layouts.compact), { x: 21, y: 170 })
|
||||
assert.deepEqual(clampPlacement(data.metadata.profiles.large, "current_speed", -999, -99), { x: -120, y: 30 }, "the sidebar-hidden screen is reachable")
|
||||
assert.deepEqual(clampPlacement(data.metadata.profiles.large, "cruise_limits", 9999, 30), { x: 2130 - 480, y: 30 })
|
||||
@@ -309,13 +294,13 @@ targetVisibility.cancelDrag()
|
||||
const invalidSnap = editor().vm
|
||||
invalidSnap.selectProfile("compact")
|
||||
invalidSnap.$refs.preview.getBoundingClientRect = () => ({ left: 0, top: 0, width: 536, height: 240 })
|
||||
invalidSnap.state.hiddenPreviewWidgets.compact.speed_limit_actions = true
|
||||
invalidSnap.state.data.metadata.profiles.compact.reservedZones = [{ label: "Reserved", x: 174, y: 180, width: 282, height: 54 }]
|
||||
const smallPoint = (x, y) => ({ ...snappedDrag.event(x, y), pointerType: "mouse" })
|
||||
invalidSnap.startDrag("max_speed", smallPoint(0, 0))
|
||||
invalidSnap.moveDrag(smallPoint(100, 18)) // Speed limit's top attracts to y=20, overlapping protected actions.
|
||||
invalidSnap.moveDrag(smallPoint(100, 18)) // Speed limit's top attracts to y=20, overlapping the reserved zone.
|
||||
assert.equal(clampPlacement(invalidSnap.profile, "max_speed", 100, 20, invalidSnap.layout), null)
|
||||
assert.deepEqual(invalidSnap.layout.max_speed, { x: 100, y: 18, enabled: true })
|
||||
assert.deepEqual(invalidSnap.state.snapGuides, [])
|
||||
assert.deepEqual(invalidSnap.state.snapGuides, [{ axis: 'y', value: 180, kind: 'zone', label: 'a reserved area' }])
|
||||
assert.equal(invalidSnap.state.placementError, "")
|
||||
invalidSnap.moveDrag(smallPoint(100, 100))
|
||||
assert.deepEqual(invalidSnap.layout.max_speed, { x: 100, y: 18, enabled: true })
|
||||
@@ -354,22 +339,22 @@ resizeSnap.profile.widgets.map = { ...widget("Map", "nav_map", 200, 200, 300, 30
|
||||
resizeSnap.layout.map = { x: 300, y: 300, width: 200, height: 200, enabled: true }
|
||||
const resizePoint = (x, y, options = {}) => ({ ...largePoint(x, y, options), stopPropagation() {} })
|
||||
resizeSnap.startResize("map", resizePoint(500, 500))
|
||||
resizeSnap.moveDrag(resizePoint(564, 671))
|
||||
assert.deepEqual([resizeSnap.layout.map.width, resizeSnap.layout.map.height], [268, 375])
|
||||
resizeSnap.moveDrag(resizePoint(564, 593)) // Right and bottom edges meet the cruise card's (568, 597).
|
||||
assert.deepEqual([resizeSnap.layout.map.width, resizeSnap.layout.map.height], [268, 297])
|
||||
assert.deepEqual([resizeSnap.layout.map.x, resizeSnap.layout.map.y], [300, 300])
|
||||
assert.equal(resizeSnap.state.snapGuides.length, 2)
|
||||
resizeSnap.endDrag(resizePoint(564, 671))
|
||||
resizeSnap.endDrag(resizePoint(564, 593))
|
||||
assert.deepEqual(resizeSnap.state.snapGuides, [])
|
||||
assert.equal(resizeSnap.state.history.undo.length, 1)
|
||||
resizeSnap.undo()
|
||||
resizeSnap.startResize("map", resizePoint(500, 500))
|
||||
resizeSnap.moveDrag(resizePoint(564, 671, { altKey: true }))
|
||||
assert.deepEqual([resizeSnap.layout.map.width, resizeSnap.layout.map.height], [264, 371])
|
||||
resizeSnap.moveDrag(resizePoint(564, 593, { altKey: true }))
|
||||
assert.deepEqual([resizeSnap.layout.map.width, resizeSnap.layout.map.height], [264, 293])
|
||||
assert.deepEqual(resizeSnap.state.snapGuides, [])
|
||||
resizeSnap.cancelDrag()
|
||||
resizeSnap.profile.widgets.map.box.maxWidth = 250
|
||||
resizeSnap.startResize("map", resizePoint(500, 500))
|
||||
resizeSnap.moveDrag(resizePoint(564, 671))
|
||||
resizeSnap.moveDrag(resizePoint(564, 593))
|
||||
assert.equal(resizeSnap.layout.map.width, 250)
|
||||
assert.deepEqual(resizeSnap.state.snapGuides, [])
|
||||
resizeSnap.cancelDrag()
|
||||
@@ -445,8 +430,8 @@ dmEditor.selectProfile("compact")
|
||||
dmEditor.changePosition("driver_monitor", 90, 70)
|
||||
assert.deepEqual(dmEditor.state.draft.layouts.large.driver_monitor, { x: 700, y: 600, enabled: true })
|
||||
assert.deepEqual(dmEditor.layout.driver_monitor, { x: 90, y: 70, enabled: true })
|
||||
dmEditor.changePosition("driver_monitor", 200, 190)
|
||||
assert.deepEqual(dmEditor.layout.driver_monitor, { x: 90, y: 70, enabled: true })
|
||||
dmEditor.changePosition("driver_monitor", 200, 190) // Clamped to the bottom edge; nothing reserves this space now.
|
||||
assert.deepEqual(dmEditor.layout.driver_monitor, { x: 200, y: 180, enabled: true })
|
||||
dmEditor.remove("driver_monitor")
|
||||
assert.equal(dmEditor.layout.driver_monitor.enabled, false)
|
||||
dmEditor.add("driver_monitor")
|
||||
@@ -455,16 +440,6 @@ dmEditor.resetLayout()
|
||||
assert.deepEqual(dmEditor.layout.driver_monitor, { x: 16, y: 10, enabled: true })
|
||||
assert.equal(dmEditor.state.draft.layouts.large.driver_monitor.x, 700)
|
||||
|
||||
const actionEditor = editor().vm
|
||||
actionEditor.changePosition("speed_limit_actions", 388, 600)
|
||||
assert.deepEqual(actionEditor.layout.speed_limit_actions, { x: 388, y: 600, enabled: true })
|
||||
actionEditor.selectProfile("compact")
|
||||
actionEditor.changePosition("speed_limit_actions", 100, 180)
|
||||
assert.deepEqual(actionEditor.layout.speed_limit_actions, { x: 100, y: 180, enabled: true })
|
||||
actionEditor.changePosition("speed_limit_actions", 10, 180)
|
||||
assert.equal(actionEditor.layout.speed_limit_actions.x, 100)
|
||||
assert.equal(validDocument(actionEditor.state.draft, actionEditor.state.data.metadata), true)
|
||||
|
||||
const wheelEditor = editor().vm
|
||||
wheelEditor.state.selected = "steering_wheel"
|
||||
wheelEditor.resizeSelected({ target: { value: "240" } })
|
||||
@@ -521,13 +496,14 @@ vm.changePosition("max_speed", 200, 18)
|
||||
vm.resetColors()
|
||||
assert.equal(vm.selectedColors.cardFill, "#00000000")
|
||||
assert.equal(vm.layout.max_speed.x, 200)
|
||||
vm.profile.reservedZones = [{ label: "Reserved", x: 174, y: 200, width: 100, height: 40 }]
|
||||
vm.changePosition("max_speed", 200, 65)
|
||||
assert.equal(vm.layout.max_speed.y, 18)
|
||||
assert.match(vm.state.placementError, /last valid position/)
|
||||
assert.ok(vm.state.placementError)
|
||||
const compactPoint = (x, y) => event(100 + x * 1080 / 536, 100 + y * 540 / 240)
|
||||
vm.startDrag("speed_limit", compactPoint(350, 40))
|
||||
vm.moveDrag(compactPoint(350, 100))
|
||||
assert.equal(vm.layout.speed_limit.y, 80) // Intentional sign/action overlap survives dragging.
|
||||
assert.equal(vm.layout.speed_limit.y, 80)
|
||||
vm.endDrag(compactPoint(350, 100))
|
||||
assert.equal(vm.layout.speed_limit.y, 80)
|
||||
assert.equal(vm.state.drag, null)
|
||||
@@ -590,26 +566,23 @@ assert.equal(vm.sceneGroups.flatMap(group => group.scenes).length, vm.scenes.len
|
||||
assert.match(OnroadLayoutPage.template, /<GalaxySelect class="gx-field gx-field--full" aria-label="Preview scene"/)
|
||||
// The widget open in Edit glows; the sources panel is a layout setting, not an on-screen toggle.
|
||||
assert.match(OnroadLayoutPage.template, /'is-editing': state\.showEditingAids && state\.inspectorPanel === 'edit' && state\.selected === widget\.id/)
|
||||
// Sources sit inside the cruise card (or a card right under it), so its box grows and actions right below follow.
|
||||
// Sources sit inside the cruise card (or a card right under it), so its box grows and a low card moves up to fit.
|
||||
vm.state.data.metadata.profiles.large.widgets.cruise_limits.sourcesExtent = { inline: 76, card: 84 }
|
||||
vm.state.selected = "cruise_limits"
|
||||
const sourcesCard = vm.layout.cruise_limits, sourcesActions = vm.layout.speed_limit_actions
|
||||
const actionsBefore = { ...sourcesActions }
|
||||
const sourceDx = vm.profile.widgets.speed_limit_actions.default.x - vm.profile.widgets.cruise_limits.default.x
|
||||
const sourceGap = vm.profile.widgets.speed_limit_actions.default.y - vm.profile.widgets.cruise_limits.default.y - 522
|
||||
Object.assign(sourcesActions, { x: sourcesCard.x + sourceDx, y: sourcesCard.y + 522 + sourceGap })
|
||||
const cardBefore = { ...vm.layout.cruise_limits }
|
||||
vm.layout.cruise_limits.y = 1050 - 522
|
||||
vm.setSpeedSources("speedSources", true)
|
||||
assert.equal(vm.state.draft.speedSources, true)
|
||||
assert.equal(vm.profile.widgets.cruise_limits.height, 522 + 76)
|
||||
assert.equal(sourcesActions.y, sourcesCard.y + 522 + 76 + sourceGap)
|
||||
assert.equal(vm.layout.cruise_limits.y, 1050 - 522 - 76)
|
||||
vm.setSpeedSources("speedSourcesCard", true)
|
||||
assert.equal(vm.profile.widgets.cruise_limits.height, 522 + 84)
|
||||
assert.equal(sourcesActions.y, sourcesCard.y + 522 + 84 + sourceGap)
|
||||
assert.equal(vm.layout.cruise_limits.y, 1050 - 522 - 84)
|
||||
vm.undo(); vm.undo()
|
||||
assert.notEqual(vm.state.draft.speedSources, true)
|
||||
assert.equal(vm.profile.widgets.cruise_limits.height, 522)
|
||||
assert.equal(vm.layout.speed_limit_actions.y, vm.layout.cruise_limits.y + 522 + sourceGap)
|
||||
Object.assign(vm.layout.speed_limit_actions, actionsBefore)
|
||||
assert.equal(vm.layout.cruise_limits.y, 1050 - 522)
|
||||
Object.assign(vm.layout.cruise_limits, cardBefore)
|
||||
vm.state.selected = "current_speed"
|
||||
vm.setSpeedSources("speedSources", true)
|
||||
assert.notEqual(vm.state.draft.speedSources, true) // Only from the cruise widget's own panel.
|
||||
@@ -920,7 +893,7 @@ assert.deepEqual(railEditor.layout.conditional_mode, { x: 476, y: 80, enabled: t
|
||||
const badRail = snapshot()
|
||||
badRail.metadata.profiles.compact.widgets.model_confidence.bounds.width = 900
|
||||
assert.equal(validSnapshot(badRail), false)
|
||||
assert.equal(clampPlacement(data.metadata.profiles.compact, "conditional_mode", 260, 101), null)
|
||||
assert.deepEqual(clampPlacement(data.metadata.profiles.compact, "conditional_mode", 260, 101), { x: 260, y: 101 })
|
||||
|
||||
const scoped = editor().vm
|
||||
const legacyPalette = copy(scoped.state.draft.palette)
|
||||
@@ -972,12 +945,12 @@ assert.equal(widgetPalette(migrated.state.draft, migrated.state.data.metadata, '
|
||||
console.log('Widget colors: real fields, visible picks, profile/widget isolation, undo/reset, legacy inheritance and invalid fields passed')
|
||||
const savedSelection = editor()
|
||||
savedSelection.vm.selectProfile('compact')
|
||||
savedSelection.vm.state.selected = 'speed_limit_actions'
|
||||
savedSelection.vm.state.selected = 'driver_monitor'
|
||||
savedSelection.vm.color('cardFill', '#12345680')
|
||||
const savedData = snapshot()
|
||||
savedData.document = copy(savedSelection.vm.state.draft)
|
||||
savedSelection.publish({ status: 'ready', data: savedData, draft: copy(savedData.document) })
|
||||
assert.equal(savedSelection.vm.state.selected, 'speed_limit_actions')
|
||||
assert.equal(savedSelection.vm.state.selected, 'driver_monitor')
|
||||
assert.equal(savedSelection.vm.selectedColors.cardFill, '#12345680')
|
||||
|
||||
const roadEditor = editor().vm
|
||||
@@ -1014,28 +987,25 @@ roadEditor.resetToStock()
|
||||
assert.deepEqual(copy(roadEditor.state.draft.roadColors), { large: {}, compact: {} })
|
||||
console.log('Road colors: original defaults, custom/rainbow modes, alpha, profile separation, undo/reset and validation passed')
|
||||
|
||||
// Both drag directions permit the sign/action pair and persist the whole draft.
|
||||
// Moving the sign keeps the whole draft and the layer order.
|
||||
const overlap = editor().vm
|
||||
const bigBefore = copy(overlap.state.draft.layouts.large)
|
||||
overlap.selectProfile('compact')
|
||||
overlap.changePosition('speed_limit', 330, 108)
|
||||
assert.equal(overlap.layout.speed_limit.y, 108)
|
||||
overlap.changePosition('speed_limit_actions', 174, 100)
|
||||
assert.equal(overlap.layout.speed_limit_actions.y, 100)
|
||||
assert.equal(validDocument(overlap.state.draft, overlap.state.data.metadata), true)
|
||||
assert.deepEqual(copy(overlap.state.draft.layouts.large), bigBefore)
|
||||
const originalOrder = overlap.renderWidgets.map(widget => widget.id)
|
||||
overlap.state.selected = 'speed_limit'
|
||||
assert.deepEqual(overlap.renderWidgets.map(widget => widget.id), originalOrder)
|
||||
overlap.state.selected = 'speed_limit_actions'
|
||||
assert.deepEqual(overlap.renderWidgets.map(widget => widget.id), originalOrder)
|
||||
|
||||
overlap.changePosition('speed_limit_actions', 174, 0)
|
||||
assert.equal(overlap.layout.speed_limit_actions.y, 0)
|
||||
// A header that would leave the screen moves below the widget.
|
||||
overlap.changePosition('speed_limit', 330, 0)
|
||||
assert.equal(overlap.layout.speed_limit.y, 0)
|
||||
assert.equal(validDocument(overlap.state.draft, overlap.state.data.metadata), true)
|
||||
assert.equal(overlap.renderWidgets.find(widget => widget.id === "speed_limit_actions").visualHeaderY, 62)
|
||||
assert.equal(overlap.renderWidgets.find(widget => widget.id === "speed_limit_actions").visualInsetTop, 0)
|
||||
assert.equal(overlap.renderWidgets.find(widget => widget.id === "speed_limit_actions").visualInsetBottom, 32)
|
||||
assert.equal(overlap.renderWidgets.find(widget => widget.id === "speed_limit").visualHeaderY, 140)
|
||||
assert.equal(overlap.renderWidgets.find(widget => widget.id === "speed_limit").visualInsetTop, 0)
|
||||
assert.equal(overlap.renderWidgets.find(widget => widget.id === "speed_limit").visualInsetBottom, 32)
|
||||
|
||||
const synchronizedDrag = editor()
|
||||
const syncVm = synchronizedDrag.vm
|
||||
@@ -1296,7 +1266,6 @@ console.log("Ford rear fog: make visibility, saved placement and strict metadata
|
||||
profile.widgets.max_speed.width = 146
|
||||
profile.widgets.speed_limit = { ...profile.widgets.speed_limit, width: 128, height: 144,
|
||||
confirmation: { x: -172, y: -8, width: 328, height: 159 } }
|
||||
sample.document.version = 14
|
||||
sample.document.layouts.compact.speed_limit = { x: 320, y: 16, enabled: true }
|
||||
assert.equal(documentHelpers.overlapsReserved(profile, 'speed_limit', 320, 16, sample.document.layouts.compact), false)
|
||||
assert.equal(validDocument(sample.document, sample.metadata), true)
|
||||
@@ -1306,12 +1275,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 15 after the attached-actions gap migration.
|
||||
// The device writes version 16 once the speed limit actions widget is folded into the sign.
|
||||
{
|
||||
const sample = snapshot()
|
||||
sample.document.version = 15
|
||||
assert.equal(validDocument(sample.document, sample.metadata), true)
|
||||
sample.document.version = 16
|
||||
sample.document.version = 15
|
||||
assert.equal(validDocument(sample.document, sample.metadata), false)
|
||||
}
|
||||
|
||||
|
||||
@@ -427,7 +427,7 @@ assert.equal(sections.at(-2).label, 'Device & System')
|
||||
assert(!sections.some(section => section.id === 'localization'))
|
||||
assert(sections.find(section => section.id === 'device').pages.includes('localization'))
|
||||
assert(sections.find(section => section.id === 'device').pages.includes('starport_options'))
|
||||
assert(sections.find(section => section.id === 'longitudinal').pages.includes('driving_options'))
|
||||
assert(!sections.find(section => section.id === 'longitudinal').pages.includes('driving_options'))
|
||||
assert.match(SettingsPage.template, /state.data\?\.page === 'data'/)
|
||||
|
||||
for (const subtitle of ["Off: Motion monitoring is disabled.", "Not armed: Battery is low or its charge cannot be checked.", "Not armed: The car is on or the device is shutting down."]) {
|
||||
|
||||
@@ -262,7 +262,7 @@ class SettingsGatewayTest(unittest.TestCase):
|
||||
self.assertEqual(next(page for page in lateral["pages"] if page["id"] == "aol")["title"], self.page("aol")["title"])
|
||||
self.assertEqual([row["page"] for row in hub["rows"]],
|
||||
["aol", "lane_change", "lane", "torque", "torque/developer", "curve", "slc", "profiles", "conditional", "wheel",
|
||||
"vehicle", "personalities", "developer", "driving_options"])
|
||||
"vehicle", "personalities", "developer"])
|
||||
self.assertEqual([row["page"] for row in self.page("personalities")["rows"]],
|
||||
["aggressive", "standard", "relaxed", "traffic"])
|
||||
for page in ("slc", "lane", "lane_change", "profiles", "conditional", "conditional/cem",
|
||||
|
||||
@@ -814,3 +814,7 @@ let toggleSettings
|
||||
SoftwarePage.methods.configureAutomaticInstalls.call({operations:{restartSchedule:'0 0 * * *',restartTimezone:'UTC'},restartTimezone:'Asia/Tokyo',
|
||||
feed:{configureInstallPreferences:(...args)=>{toggleSettings=args}}},true)
|
||||
assert.deepEqual(toggleSettings,[true,'0 0 * * *','UTC'],'toggle preserves the saved timezone')
|
||||
|
||||
assert.deepEqual(softwareProgress({...updater, state: "downloading..."},
|
||||
{progress: {stage: "agnos", detail: "Downloading and writing AGNOS system", percent: 37}}),
|
||||
{active: true, failed: false, percent: 37, label: "Downloading and installing AGNOS", detail: "Downloading and writing AGNOS system"})
|
||||
|
||||
@@ -27,10 +27,11 @@ def test_real_gateway_global_slider_saves_restores_and_keeps_layout(tmp_path):
|
||||
context = SimpleNamespace(sample=lambda: AuthorityContext(True, None, None))
|
||||
gateway = SettingsGateway(params, cast(ContextSource, context))
|
||||
page = gateway.page('developer', 'session', b'generation')
|
||||
row = page['rows'][0]
|
||||
index = next(index for index, row in enumerate(page['rows']) if row['label'] == 'Speed display adjustment')
|
||||
row = page['rows'][index]
|
||||
assert row['label'] == 'Speed display adjustment' and row['value'] == '0'
|
||||
assert row['available'] and row['minimum'] == -5 and row['maximum'] == 5 and row['step'] == .1
|
||||
intent = gateway.preview(page['view'], 0, 0, 'session', b'generation', value='-1.7')['intent']
|
||||
intent = gateway.preview(page['view'], index, 0, 'session', b'generation', value='-1.7')['intent']
|
||||
assert gateway.confirm(intent, 'session', b'generation')
|
||||
assert AppearanceOwner(Params(str(tmp_path)), lambda: True).developer_snapshot().rows[0].value == '-1.7'
|
||||
saved = decode_document(Path(params.get_param_path(PARAM_KEY)).read_bytes())
|
||||
@@ -120,7 +121,8 @@ def test_gateway_refuses_expired_session_or_concurrent_layout_edit(tmp_path, con
|
||||
context = SimpleNamespace(sample=lambda: AuthorityContext(True, None, None))
|
||||
gateway = SettingsGateway(params, cast(ContextSource, context))
|
||||
page = gateway.page('developer', 'session', b'generation')
|
||||
intent = gateway.preview(page['view'], 0, 0, 'session', b'generation', value='-1.7')['intent']
|
||||
index = next(index for index, row in enumerate(page['rows']) if row['label'] == 'Speed display adjustment')
|
||||
intent = gateway.preview(page['view'], index, 0, 'session', b'generation', value='-1.7')['intent']
|
||||
if condition == 'changed-layout':
|
||||
document = default_document()
|
||||
document['clock24Hour'] = True
|
||||
|
||||
@@ -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:11, palette:{cardFill:"#000000A6",cardBorder:"#C4CDD0B4",text:"#FFFFFFFF"},
|
||||
const document = { version:16, 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)
|
||||
|
||||
@@ -23,11 +23,8 @@ assert.deepEqual(await widgetArtMetadata(stripped,header),meta,'Sprite sheet sur
|
||||
await assert.rejects(widgetArtMetadata(stripped,null),/metadata/)
|
||||
assert.deepEqual(await widgetArtMetadata(image(),'image/png'),meta,'A malformed header falls back to the PNG chunk')
|
||||
await assert.rejects(widgetArtMetadata(stripped,Buffer.from(JSON.stringify({...meta,width:3})).toString('base64')))
|
||||
const withHeader={...meta,sprites:{speed_limit_actions:{x:0,y:0,width:2,height:1,offsetY:-32.5}}}
|
||||
assert.deepEqual(await widgetArtMetadata(image(withHeader)),withHeader,'Native action sprites include the heading above the buttons')
|
||||
for(const bad of [{...meta,width:3},{...meta,sprites:{conditional_mode:{x:1,y:0,width:2,height:1}}},
|
||||
{...meta,sprites:{conditional_mode:{x:0,y:0,width:NaN,height:1}}},
|
||||
{...meta,sprites:{speed_limit_actions:{x:0,y:0,width:2,height:1,offsetY:-34}}},
|
||||
{...meta,sprites:{conditional_mode:{x:0,y:0,width:2,height:1,offsetY:-32}}},
|
||||
{...meta,sprites:{conditional_mode:{x:0,y:0,width:2,height:1,offsetX:1}}}])await assert.rejects(widgetArtMetadata(image(bad)))
|
||||
await assert.rejects(widgetArtMetadata(new Blob(['not PNG'])))
|
||||
@@ -46,11 +43,11 @@ for (const rect of [{offsetY:-20.01}, {offsetX:-2.01}, {x:1}, {width:3}]) {
|
||||
await assert.rejects(widgetArtMetadata(image({...meta,sprites:{cruise_limits:{x:0,y:0,width:2,height:1,...rect}}})))
|
||||
}
|
||||
const compactIds=['weather','max_speed','speed_limit','steering_wheel','conditional_mode','following_distance','model_confidence',
|
||||
'driver_monitor','speed_limit_actions','rear_fog','driving_mode_descriptions','clock']
|
||||
'driver_monitor','rear_fog','driving_mode_descriptions','clock']
|
||||
const complete={...meta,sprites:Object.fromEntries(compactIds.map(id=>[id,{x:0,y:0,width:2,height:1,visible:true}]))}
|
||||
assert.deepEqual(await widgetArtMetadata(image(complete)),complete)
|
||||
const atCapacity={...complete,sprites:{...complete.sprites,...Object.fromEntries(
|
||||
Array.from({length:12},(_,i)=>[`extra_${String.fromCharCode(97+i)}`,{x:0,y:0,width:2,height:1,visible:true}]))}}
|
||||
Array.from({length:13},(_,i)=>[`extra_${String.fromCharCode(97+i)}`,{x:0,y:0,width:2,height:1,visible:true}]))}}
|
||||
assert.deepEqual(await widgetArtMetadata(image(atCapacity)),atCapacity)
|
||||
await assert.rejects(widgetArtMetadata(image({...atCapacity,sprites:{...atCapacity.sprites,extra:{x:0,y:0,width:2,height:1}}})))
|
||||
const flush=async()=>{for(let i=0;i<20;i++)await Promise.resolve()}
|
||||
|
||||
@@ -321,13 +321,16 @@ input[type="range"].gx-slider:active::-moz-range-thumb {
|
||||
.gx-model-manager { --panel-padding: var(--sp-4); gap: var(--sp-3); }
|
||||
.gx-model-manager .gx-btn, .gx-model-card__progress { min-height: var(--touch-target); padding: 6px var(--sp-4); }
|
||||
|
||||
/* Single / pair mode switch */
|
||||
.gx-tabs.gx-model-mode { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 4px; padding: 4px; border-radius: var(--radius-full);
|
||||
/* Driving model settings tabs */
|
||||
.gx-tabs.gx-model-mode { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; padding: 4px; border-radius: var(--radius-full);
|
||||
border: 1px solid var(--glass-border); background: var(--surface-container-high); }
|
||||
.gx-model-mode > button { display: inline-flex; align-items: center; justify-content: center; gap: var(--sp-2); min-height: 40px; border: 0; border-radius: var(--radius-full);
|
||||
background: transparent; color: var(--on-surface-variant); font: inherit; font-weight: var(--fw-bold); cursor: pointer; transition: background-color var(--motion-fast), color var(--motion-fast); }
|
||||
.gx-model-mode > button[aria-pressed="true"] { background: var(--primary); color: var(--on-primary); box-shadow: 0 4px 12px var(--primary-glow); }
|
||||
.gx-model-mode > button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
@media (max-width: 480px) {
|
||||
.gx-model-mode > button { flex-direction: column; gap: 2px; padding: 6px 2px; font-size: var(--fs-sm); }
|
||||
}
|
||||
|
||||
/* Driving and Laboratory controls */
|
||||
.gx-model-driving__body, .gx-model-laboratory { display: grid; gap: var(--sp-3); }
|
||||
|
||||
@@ -42,7 +42,6 @@ export function sceneHidesWidget(scene, profile, id, layout = {}, widgets = {},
|
||||
if (id === "cem_gauge") return !scene.startsWith("cem_")
|
||||
if (id === "torque_bar" || profile === "compact" && id === "steering_wheel") return !lateral
|
||||
if (profile === "compact" && id === "max_speed") return !longitudinal
|
||||
if (id === "speed_limit_actions") return true
|
||||
const overlaps = (a, b) => a && b && a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y
|
||||
const box = key => {
|
||||
if (!layout[key]?.enabled || !widgets[key]) return null
|
||||
|
||||
@@ -4,6 +4,7 @@ import { GxState } from "./state.js"
|
||||
import { GxNotice } from "./notice.js"
|
||||
import { connectionError } from "./polling.js"
|
||||
import { GalaxySelect } from "./galaxy-select.js"
|
||||
import { GalaxySettingRow, switchRow } from "./galaxy-setting-row.js"
|
||||
import { reportSave } from "./save-feedback.js"
|
||||
|
||||
// Read-only model identity; a saved label never proves what modeld loaded.
|
||||
@@ -64,7 +65,7 @@ export class ModelStatusFeed {
|
||||
if (data?.schemaVersion !== 1 || !ids.length || new Set(ids).size !== ids.length ||
|
||||
data.catalog.some(m => typeof m.id !== "string" || !m.id || typeof m.name !== "string" || typeof m.selectable !== "boolean") ||
|
||||
!ids.includes(data.requestedId) || !(data.loadedId === null || ids.includes(data.loadedId)) || !variants.includes(data.variant) ||
|
||||
!states.includes(data.health) || ![null, "chestnut-load-failed", "chestnut-run-stalled", "selected-load-failed"].includes(data.fallbackReason) ||
|
||||
!states.includes(data.health) || ![null, "chestnut-load-failed", "chestnut-run-stalled", "selected-load-failed", "conditional-switch-failed"].includes(data.fallbackReason) ||
|
||||
!(digest === null || typeof digest === "string" && /^[0-9a-f]{64}$/.test(digest)) ||
|
||||
typeof data.pendingNextStart !== "boolean" ||
|
||||
(data.pendingNextStart && (data.loadedId === null || data.requestedId === data.loadedId)) ||
|
||||
@@ -203,10 +204,10 @@ export function describeProgress(data, models = []) {
|
||||
}
|
||||
|
||||
|
||||
const actionPaths = { "select-small": "active", "select-big": "active", favorite: "preferences", unfavorite: "preferences",
|
||||
const actionPaths = { conditional_model: "conditional_model", "select-small": "active", "select-big": "active", favorite: "preferences", unfavorite: "preferences",
|
||||
"enable-randomizer": "preferences", "disable-randomizer": "preferences", exclude: "preferences", include: "preferences",
|
||||
download: "download", downloadAll: "download_all", cancel: "cancel", delete: "delete", refresh: "refresh_manifest", jetlink: "jetlink" }
|
||||
const actionCapabilities = { "select-small": "select", "select-big": "select", favorite: "favorites", unfavorite: "favorites",
|
||||
const actionCapabilities = { conditional_model: "conditionalModel", "select-small": "select", "select-big": "select", favorite: "favorites", unfavorite: "favorites",
|
||||
"enable-randomizer": "randomizer", "disable-randomizer": "randomizer", exclude: "exclusions", include: "exclusions",
|
||||
download: "download", downloadAll: "downloadAll", cancel: "cancel", delete: "delete", refresh: "refresh", jetlink: "jetlink" }
|
||||
|
||||
@@ -218,7 +219,9 @@ export function modelActionAllowed(data, action, model = null) {
|
||||
if (!data || data.capabilities?.[actionCapabilities[action]] !== true) return false
|
||||
if (data.isOnroad !== false && !["favorite", "unfavorite", "cancel", "select-small", "select-big", "enable-randomizer", "disable-randomizer", "exclude", "include"].includes(action)) return false
|
||||
if (action === "jetlink") return data.jetlink !== undefined
|
||||
if (action === "conditional_model") return !data.downloading && !data.randomizer
|
||||
if (["select-small", "select-big"].includes(action)) {
|
||||
if (action === "select-small" && data.conditionalModel?.enabled) return false
|
||||
if (action === "select-big" && data.jetlinkBig && data.isOnroad !== false) return false
|
||||
if (data.downloading && data.refreshing !== true || data.randomizer === true) return false
|
||||
if (action === "select-big" && model === null) return true
|
||||
@@ -229,9 +232,10 @@ export function modelActionAllowed(data, action, model = null) {
|
||||
if (action === "downloadAll") return !data.downloading && data.models.some(m => !m.installed && m.downloadAvailable === true)
|
||||
if (action === "cancel") return data.downloading === true
|
||||
if (action === "delete") return !data.downloading && !!model && !model.builtin && model.deletable !== false &&
|
||||
(model.installed || model.partial) && ![data.currentModel, data.activeSmallModel, data.activeBigModel].includes(model.value)
|
||||
(model.installed || model.partial) && ![data.currentModel, data.activeSmallModel, data.activeBigModel,
|
||||
data.conditionalModel?.highway, data.conditionalModel?.city].includes(model.value)
|
||||
if (["exclude", "include"].includes(action)) return !!model
|
||||
if (["enable-randomizer", "disable-randomizer"].includes(action)) return !data.downloading
|
||||
if (["enable-randomizer", "disable-randomizer"].includes(action)) return !data.downloading && !data.conditionalModel?.enabled
|
||||
return ["favorite", "unfavorite"].includes(action) ? !!model : action === "refresh" && !data.downloading
|
||||
}
|
||||
|
||||
@@ -339,7 +343,8 @@ export class ModelManagerFeed {
|
||||
this.publish({ loading: false, data, error: "" })
|
||||
}
|
||||
}
|
||||
if (this.poll === null) this.poll = this.later(() => this.load(), this.data?.jetlink?.mode !== "off" && this.data?.jetlink ? 1000 : 2000)
|
||||
if (this.poll === null) this.poll = this.later(() => this.load(), this.data?.conditionalModel?.enabled ? 200 :
|
||||
this.data?.jetlink?.mode !== "off" && this.data?.jetlink ? 1000 : 2000)
|
||||
return this.data
|
||||
}
|
||||
async action(action, model = null, extra = {}) {
|
||||
@@ -351,7 +356,7 @@ export class ModelManagerFeed {
|
||||
if (!modelActionAllowed(this.data, action, model)) return null
|
||||
const data = this.data
|
||||
const key = model?.value || ""
|
||||
let payload = action === "jetlink" ? extra : {}
|
||||
let payload = ["jetlink", "conditional_model"].includes(action) ? extra : {}
|
||||
if (action.startsWith("select-")) payload = { profile: action === "select-big" ? "big" : "small", model: key }
|
||||
else if (["favorite", "unfavorite"].includes(action)) {
|
||||
const userFavorites = data.models.filter(m => m.userFavorite && m.value !== key).map(m => m.value)
|
||||
@@ -524,7 +529,7 @@ const ModelDownloadProgress = {
|
||||
|
||||
export const ModelsPage = {
|
||||
name: "ModelsPage",
|
||||
components: { WikiHelp, GxDialog, GxState, GalaxySelect, GxNotice, ModelDownloadProgress },
|
||||
components: { WikiHelp, GxDialog, GxState, GalaxySelect, GalaxySettingRow, GxNotice, ModelDownloadProgress },
|
||||
props: {
|
||||
mode: { type: String, required: true },
|
||||
unauthorized: { type: Function, required: true },
|
||||
@@ -538,10 +543,26 @@ export const ModelsPage = {
|
||||
summary: { installed: 0, missing: 0, total: 0 }, status: { isOnroad: true },
|
||||
runtime: { status: "idle", data: null, error: "" }, dialog: null, pendingChoice: null,
|
||||
lab: null, labError: "", labDirty: false, labConfig: { enabled: false, lateralModel: "", longitudinalModel: "" }, focused: false,
|
||||
pairView: null,
|
||||
driveView: null,
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
conditionalModel() { return this.status.conditionalModel || { enabled: false, highway: "", city: "", thresholdMph: 50 } },
|
||||
conditionalSwitchPending() {
|
||||
return ['waiting', 'switching', 'recovering'].includes(this.status.conditionalModelState?.phase)
|
||||
},
|
||||
conditionalEnabledRow() {
|
||||
return switchRow('Enable Conditional Model', this.conditionalModel.enabled)
|
||||
},
|
||||
conditionalSpeedRow() {
|
||||
return { label: 'Highway speed', value: String(this.conditionalModel.thresholdMph ?? 50),
|
||||
minimum: 10, maximum: 100, step: 1, unit: 'mph', defaultValue: '50', resetAvailable: true,
|
||||
available: true, action: true }
|
||||
},
|
||||
conditionalModels() {
|
||||
return this.models.filter(m => fitsModelProfile(m, "small") &&
|
||||
(m.selectable || [this.conditionalModel.highway, this.conditionalModel.city].includes(m.value)))
|
||||
},
|
||||
currentLabel() { return this.models.find(m => m.value === this.currentModel)?.label || this.currentModel || "" },
|
||||
runningModelLabel() {
|
||||
if (!this.selectionUncertain && this.status.jetlink?.active) return "Jetlink remote model"
|
||||
@@ -552,6 +573,10 @@ export const ModelsPage = {
|
||||
if (pair?.active) return [pair.lateralModel, pair.longitudinalModel].map(id => model.catalog.find(m => m.id === id)?.name || id).join("/")
|
||||
if (pair?.lateralModel) return "Laboratory output unavailable"
|
||||
if (model.health === "unavailable") return "No running model"
|
||||
if (model.health === "loading") return "Loading…"
|
||||
if (model.health === "stale") return "Model output stale"
|
||||
if (model.health === "failed") return "Model status mismatch"
|
||||
if (model.health === "identity-unavailable") return "Identity unverified"
|
||||
if (!model.loadedId) return model.health === "loading" ? "Loading…" : "Identity unverified"
|
||||
return model.catalog.find(item => item.id === model.loadedId)?.name || model.loadedId
|
||||
},
|
||||
@@ -626,7 +651,7 @@ export const ModelsPage = {
|
||||
return this.status.gpuAvailable ? "" : "An external GPU is not detected. Active Small is used; your Big selection is saved for later."
|
||||
},
|
||||
jetlinkOpen() { return !!this.status.jetlink && this.status.jetlink.mode !== "off" },
|
||||
driveMode() { return this.pairView ?? (this.lab?.configuration.enabled ? "pair" : "single") },
|
||||
driveMode() { return this.driveView ?? (this.lab?.configuration.enabled ? "split" : this.conditionalModel.enabled ? "conditional" : "single") },
|
||||
labRows() { return new Map(laboratoryModels(this.lab).map(m => [m.value, m])) },
|
||||
labReady() { return laboratoryReady(this.lab) },
|
||||
labCandidates() { return this.labReady.filter(m => m.value !== this.labConfig.lateralModel) },
|
||||
@@ -692,7 +717,7 @@ export const ModelsPage = {
|
||||
methods: {
|
||||
focusLaboratory() {
|
||||
if (this.focus !== "laboratory" || this.focused) return
|
||||
if (this.driveMode !== "pair") this.pairView = "pair"
|
||||
if (this.driveMode !== "split") this.driveView = "split"
|
||||
this.$nextTick(() => {
|
||||
const card = this.$refs.laboratory
|
||||
if (!card) return
|
||||
@@ -726,20 +751,11 @@ export const ModelsPage = {
|
||||
this.labDirty = false
|
||||
if (this.lab) this.labConfig = laboratoryDraft(this.lab, this.labConfig, false)
|
||||
}
|
||||
if (result && !this.disposed && this.driveMode === "pair" && !this.lab?.configuration.enabled && this.labActionAvailable("enable")) return this.enablePair()
|
||||
return result
|
||||
},
|
||||
enablePair() { return reportSave(() => this.runLabAction("enable")) },
|
||||
async setDriveMode(mode) {
|
||||
if (mode === this.driveMode) return null
|
||||
if (mode === "single") {
|
||||
this.pairView = "single"
|
||||
const result = this.lab?.configuration.enabled ? await reportSave(() => this.runLabAction("disable")) : true
|
||||
this.pairView = null
|
||||
return result
|
||||
}
|
||||
this.pairView = "pair"
|
||||
return this.labActionAvailable("enable") ? this.enablePair() : null
|
||||
setDriveMode(mode) {
|
||||
if (["single", "split", "conditional"].includes(mode)) this.driveView = mode
|
||||
},
|
||||
activeRoles(model) {
|
||||
const roles = []
|
||||
@@ -776,7 +792,7 @@ export const ModelsPage = {
|
||||
if (this.disposed) return
|
||||
const result = await this.laboratory.action(action, model, this.labConfig)
|
||||
if (!this.disposed && result) {
|
||||
this.message = action === "save" ? "Model pair saved for the next start." : result.message || "Updated"
|
||||
this.message = action === "save" ? "Split Model models saved for the next start." : result.message || "Updated"
|
||||
this.trackingProgress = action === "download"
|
||||
if (["enable", "disable", "delete", "save"].includes(action)) {
|
||||
this.labDirty = false
|
||||
@@ -861,6 +877,17 @@ export const ModelsPage = {
|
||||
if (result) this.message = result.message
|
||||
} finally { this.pendingChoice = null; this.busy = "" }
|
||||
},
|
||||
async configureConditionalModel(update) {
|
||||
if (!this.canAction("conditional_model")) return false
|
||||
this.busy = "conditional_model:"
|
||||
try {
|
||||
const result = await reportSave(() => this.manager.action("conditional_model", null, update))
|
||||
return result || false
|
||||
} finally { this.busy = "" }
|
||||
},
|
||||
saveConditionalSetting(index, value) {
|
||||
return this.configureConditionalModel(index === 0 ? { enabled: value === 'On' } : { thresholdMph: Number(value) })
|
||||
},
|
||||
async runAction(action, model = null) {
|
||||
if (this.disposed || !this.canAction(action, model)) return
|
||||
if (action.startsWith("select-")) this.pendingChoice = { action, value: model?.value || "" }
|
||||
@@ -898,7 +925,7 @@ export const ModelsPage = {
|
||||
|
||||
<template v-else>
|
||||
<header class="gx-settings__header gx-page-header"><div><h2>Models</h2>
|
||||
<p>Choose what drives your car, pair models, and manage downloads.</p></div>
|
||||
<p>Choose one model, split control, or automatic speed-based switching.</p></div>
|
||||
<WikiHelp /></header>
|
||||
<GxNotice v-if="message" tone="info">{{ message }}</GxNotice>
|
||||
<GxNotice v-if="error" tone="danger" title="Models">{{ error }}</GxNotice>
|
||||
@@ -916,13 +943,16 @@ export const ModelsPage = {
|
||||
<section class="gx-card gx-model-driving">
|
||||
<div class="gx-panel gx-model-driving__body">
|
||||
<div class="gx-tabs gx-model-mode" role="group" aria-label="Driving models">
|
||||
<button type="button" :aria-pressed="driveMode === 'single'" :disabled="!!busy || labLocked && driveMode !== 'single'" @click="setDriveMode('single')"><i aria-hidden="true" class="bi bi-cpu"></i> Single model</button>
|
||||
<button type="button" :aria-pressed="driveMode === 'pair'" :disabled="!!busy || labLocked" @click="setDriveMode('pair')"><i aria-hidden="true" class="bi bi-bezier2"></i> Model pair</button>
|
||||
<button type="button" :aria-pressed="driveMode === 'single'" @click="setDriveMode('single')"><i aria-hidden="true" class="bi bi-cpu"></i> Single Model</button>
|
||||
<button type="button" :aria-pressed="driveMode === 'split'" @click="setDriveMode('split')"><i aria-hidden="true" class="bi bi-bezier2"></i> Split Model</button>
|
||||
<button type="button" :aria-pressed="driveMode === 'conditional'" @click="setDriveMode('conditional')"><i aria-hidden="true" class="bi bi-signpost-split"></i> Conditional Model</button>
|
||||
</div>
|
||||
|
||||
<div class="gx-panel-stage" :style="{'--panel-direction': driveMode === 'pair' ? 1 : -1}">
|
||||
<div class="gx-panel-stage" :style="{'--panel-direction': driveMode === 'split' ? 1 : -1}">
|
||||
<div :key="driveMode" class="gx-model-driving__body">
|
||||
<template v-if="driveMode === 'single'">
|
||||
<p class="gx-model-reason">One model handles all driving.</p>
|
||||
<GxNotice v-if="conditionalModel.enabled" tone="info">Conditional Model is enabled. Turn it off in Conditional Model to choose Active Small here.</GxNotice>
|
||||
<div class="gx-model-driving__summary" role="group" aria-label="Active models">
|
||||
<div class="gx-model-control gx-model-summary-item">
|
||||
<span class="gx-model-summary-item__meta"><i aria-hidden="true" class="bi bi-cpu"></i> Active Small · On-device</span>
|
||||
@@ -946,7 +976,27 @@ export const ModelsPage = {
|
||||
</div>
|
||||
<p v-if="status.randomizer" class="gx-model-reason">A different verified model is chosen each start. {{ status.gpuAvailable && activeBigModel ? 'Big GPU' : 'Small on-device' }} models are used. {{ (status.blacklistedModels || []).length }} excluded. Favorites only mark your preferred models.</p>
|
||||
<p v-if="gpuNote" class="gx-model-reason">{{ gpuNote }}</p>
|
||||
<p class="gx-model-reason">{{ laboratoryEnabled ? 'Small/Big selections are saved as fallback choices. Turn off Laboratory to use them normally at the next start.' : 'Selections take effect the next time the driving model starts.' }}</p>
|
||||
<p class="gx-model-reason">{{ laboratoryEnabled ? 'Small/Big selections are saved as fallback choices. Turn off Split Model to use them normally at the next start.' : 'Selections take effect the next time the driving model starts.' }}</p>
|
||||
</template>
|
||||
|
||||
<template v-else-if="driveMode === 'conditional'">
|
||||
<p class="gx-model-reason">Starts each drive in City and automatically selects Highway at your chosen speed, only while fully disengaged.</p>
|
||||
<GxNotice v-if="conditionalSwitchPending" tone="warn">Switching conditional models · Wait before engaging.</GxNotice>
|
||||
<GxNotice v-if="status.conditionalModelState?.error" tone="warn">{{ status.conditionalModelState.error }}</GxNotice>
|
||||
<GxNotice v-else-if="status.conditionalModelState?.unavailableReason" tone="info">{{ status.conditionalModelState.unavailableReason }}</GxNotice>
|
||||
<GxNotice v-if="laboratoryEnabled && !status.conditionalModelState?.unavailableReason" tone="info">Split Model takes priority while enabled.</GxNotice>
|
||||
<GalaxySettingRow :row="conditionalEnabledRow" :index="0" :busy="!!busy" :disabled="!actionAvailable('conditional_model')" :save-value="saveConditionalSetting" feedback="none" />
|
||||
<div class="gx-model-driving__selects" role="group" aria-label="Conditional driving models">
|
||||
<div v-for="condition in ['city', 'highway']" :key="condition" class="gx-model-control">
|
||||
<label :for="'gx-conditional-' + condition">{{ condition === 'highway' ? 'Highway model' : 'City model' }}</label>
|
||||
<GalaxySelect :id="'gx-conditional-' + condition" class="gx-field" :value="conditionalModel[condition]" :disabled="!!busy || !actionAvailable('conditional_model')" @change="configureConditionalModel({[condition]: $event.target.value})">
|
||||
<option v-for="m in conditionalModels" :key="m.value" :value="m.value" :disabled="!m.selectable">{{ m.label }}{{ m.selectable ? '' : ' · ' + m.unavailableReason }}</option>
|
||||
</GalaxySelect>
|
||||
</div>
|
||||
</div>
|
||||
<GalaxySettingRow :row="conditionalSpeedRow" :index="1" :busy="!!busy" :disabled="!actionAvailable('conditional_model')" :save-value="saveConditionalSetting" feedback="none" @reset-default="configureConditionalModel({thresholdMph: 50})" />
|
||||
<GxNotice v-if="status.randomizer" tone="info">Turn off Model Randomizer to enable Conditional Model.</GxNotice>
|
||||
<span class="gx-chip gx-model-driving__running">Running now: {{ runningModelLabel }}</span>
|
||||
</template>
|
||||
|
||||
<div v-else id="gx-model-laboratory" ref="laboratory" class="gx-model-laboratory">
|
||||
@@ -957,22 +1007,24 @@ export const ModelsPage = {
|
||||
</div>
|
||||
<span class="gx-chip gx-model-driving__running">Running now: {{ runningModelLabel }}<template v-if="pendingNextStart"> · saved changes pending next start</template></span>
|
||||
</div>
|
||||
<GxNotice v-if="labError" tone="danger" title="Model Laboratory">{{ labError }}</GxNotice>
|
||||
<GxNotice v-if="labError" tone="danger" title="Split Model">{{ labError }}</GxNotice>
|
||||
<GxNotice v-if="lab?.configurationError" tone="danger">{{ lab.configurationError }}</GxNotice>
|
||||
<p v-if="!lab && !labError" class="gx-note">Loading Model Laboratory…</p>
|
||||
<p v-if="!lab && !labError" class="gx-note">Loading Split Model…</p>
|
||||
<template v-if="lab">
|
||||
<p class="gx-model-reason">Pair lateral judgment from one model with longitudinal judgment from another.</p>
|
||||
<p class="gx-model-reason">One model for steering, another for speed. Requires Chestnut.</p>
|
||||
<p v-if="conditionalModel.enabled" class="gx-model-reason">Conditional Model remains your Small fallback while Split Model is enabled.</p>
|
||||
<button type="button" class="gx-btn" :disabled="!!busy || !labActionAvailable(lab.configuration.enabled ? 'disable' : 'enable')" @click="lab.configuration.enabled ? runLabAction('disable') : enablePair()">{{ lab.configuration.enabled ? 'Turn off Split Model' : 'Use Split Model' }}</button>
|
||||
<div class="gx-model-driving__selects">
|
||||
<div class="gx-model-control">
|
||||
<label class="gx-row__label" for="gx-lab-lateral">Lateral model <small class="gx-model-driving__random-hint">steering & path</small></label>
|
||||
<GalaxySelect id="gx-lab-lateral" class="gx-field" aria-label="Lateral model" :disabled="labLocked" :value="labConfig.lateralModel" @change="changeLateral($event.target.value)">
|
||||
<label class="gx-row__label" for="gx-lab-lateral">Steering model <small class="gx-model-driving__random-hint">path & lane position</small></label>
|
||||
<GalaxySelect id="gx-lab-lateral" class="gx-field" aria-label="Steering model" :disabled="labLocked" :value="labConfig.lateralModel" @change="changeLateral($event.target.value)">
|
||||
<option value="">Choose a model</option>
|
||||
<option v-for="m in labReady" :key="m.value" :value="m.value">{{ m.label }} · {{ m.version }}</option>
|
||||
</GalaxySelect>
|
||||
</div>
|
||||
<div class="gx-model-control">
|
||||
<label class="gx-row__label" for="gx-lab-longitudinal">Longitudinal model <small class="gx-model-driving__random-hint">speed & lead pacing</small></label>
|
||||
<GalaxySelect id="gx-lab-longitudinal" class="gx-field" aria-label="Longitudinal model" :disabled="labLocked" :value="labConfig.longitudinalModel" @change="changeLongitudinal($event.target.value)">
|
||||
<label class="gx-row__label" for="gx-lab-longitudinal">Speed model <small class="gx-model-driving__random-hint">acceleration & braking</small></label>
|
||||
<GalaxySelect id="gx-lab-longitudinal" class="gx-field" aria-label="Speed model" :disabled="labLocked" :value="labConfig.longitudinalModel" @change="changeLongitudinal($event.target.value)">
|
||||
<option value="">Choose a model</option>
|
||||
<option v-for="m in labCandidates" :key="m.value" :value="m.value">{{ m.label }} · {{ m.version }}</option>
|
||||
</GalaxySelect>
|
||||
@@ -1057,8 +1109,8 @@ export const ModelsPage = {
|
||||
|
||||
<div v-if="!sorted.length" class="gx-empty">No models match these filters. <button type="button" class="gx-btn gx-btn--tonal" @click="clearFilters">Show all models</button></div>
|
||||
<ul v-else class="gx-model-list" aria-label="Models">
|
||||
<li class="gx-model-item" :class="{'gx-model-item--pair': driveMode === 'pair', 'gx-model-card--polaris': isPolaris(m), 'gx-model-card--selected': rowState(m) === 'active'}" v-for="m in visibleModels" :key="m.value">
|
||||
<template v-if="driveMode === 'pair'">
|
||||
<li class="gx-model-item" :class="{'gx-model-item--pair': driveMode === 'split', 'gx-model-card--polaris': isPolaris(m), 'gx-model-card--selected': rowState(m) === 'active'}" v-for="m in visibleModels" :key="m.value">
|
||||
<template v-if="driveMode === 'split'">
|
||||
<div class="gx-model-item__row gx-model-item__row--pair">
|
||||
<div class="gx-model-item__ver">
|
||||
<span v-if="m.version" class="gx-model-spec gx-model-spec--ver">{{ m.version }}</span>
|
||||
|
||||
@@ -61,8 +61,7 @@ export function placementLimits(profile, id, layout = null) {
|
||||
minY: bounds.y, maxY: bounds.y + bounds.height - height
|
||||
}
|
||||
const confirmation = widget.confirmation
|
||||
if (confirmation && (layout?.[id]?.enabled ?? widget.default.enabled) &&
|
||||
(layout?.speed_limit_actions?.enabled ?? profile.widgets.speed_limit_actions.default.enabled)) {
|
||||
if (confirmation && (layout?.[id]?.enabled ?? widget.default.enabled)) {
|
||||
limits.minX = Math.max(limits.minX, bounds.x - confirmation.x)
|
||||
limits.maxX = Math.min(limits.maxX, bounds.x + bounds.width - confirmation.x - confirmation.width)
|
||||
limits.minY = Math.max(limits.minY, bounds.y - confirmation.y)
|
||||
@@ -99,7 +98,7 @@ export function overlapsReserved(profile, id, x, y, layout = null) {
|
||||
const widget = profile.widgets[id]
|
||||
const owner = Object.keys(profile.widgets).find(key => profile.widgets[key].confirmation)
|
||||
const positions = layout || Object.fromEntries(Object.entries(profile.widgets).map(([key, item]) => [key, item.default]))
|
||||
if (owner && positions[owner]?.enabled && positions.speed_limit_actions?.enabled) {
|
||||
if (owner && positions[owner]?.enabled) {
|
||||
const area = profile.widgets[owner].confirmation, at = positions[owner]
|
||||
const critical = owner === "speed_limit" ? ["max_speed", "torque_bar"] : ["torque_bar"]
|
||||
const overlaps = (a, b) => a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y
|
||||
@@ -124,19 +123,7 @@ export function overlapsReserved(profile, id, x, y, layout = null) {
|
||||
const [width, height] = widgetSize(widget, layout?.[id])
|
||||
const intersects = (left, top, otherWidth, otherHeight) => x < left + otherWidth && x + width > left &&
|
||||
y < top + otherHeight && y + height > top
|
||||
if (profile.reservedZones.some((zone) => intersects(zone.x, zone.y, zone.width, zone.height))) return true
|
||||
const actions = profile.widgets.speed_limit_actions
|
||||
if (!actions || profile.protectedWidget !== "speed_limit_actions") return false
|
||||
if (id === "speed_limit_actions") return Object.entries(profile.widgets).some(([key, other]) => {
|
||||
const at = positions[key]
|
||||
return key !== id && key !== "speed_limit" && key !== "stopped_timer" && key !== "nav_card" && other.layer !== "underlay" && at &&
|
||||
at.enabled && Number.isFinite(at.x) && Number.isFinite(at.y) &&
|
||||
intersects(at.x, at.y, ...widgetSize(other, at))
|
||||
})
|
||||
if (id === "speed_limit" || id === "stopped_timer" || id === "nav_card") return false
|
||||
const at = positions.speed_limit_actions
|
||||
if (!at || !Number.isFinite(at.x) || !Number.isFinite(at.y)) return true
|
||||
return intersects(at.x, at.y, actions.width, actions.height)
|
||||
return profile.reservedZones.some((zone) => intersects(zone.x, zone.y, zone.width, zone.height))
|
||||
}
|
||||
|
||||
export function previewPoint(event, rect, profile) {
|
||||
@@ -155,7 +142,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 : ![11, 12, 13, 14, 15].includes(document.version)) ||
|
||||
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) ||
|
||||
(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)) ||
|
||||
@@ -239,8 +226,6 @@ export function validSnapshot(data) {
|
||||
zone.y + zone.height > profile.bounds.y + profile.bounds.height))) return false
|
||||
const bounds = profile.bounds
|
||||
if (projection && (profile.widgets?.car_exit?.kind !== "car_exit" || profile.widgets.car_exit.required !== true)) return false
|
||||
if (profile.protectedWidget != null && (profile.protectedWidget !== "speed_limit_actions" ||
|
||||
profile.widgets?.[profile.protectedWidget]?.kind !== "speed_limit_actions")) return false
|
||||
if (!positive(profile.width) || !positive(profile.height) || typeof profile.label !== "string" ||
|
||||
!bounds || !Number.isFinite(bounds.x) || !Number.isFinite(bounds.y) || bounds.x < 0 || bounds.y < 0 ||
|
||||
!positive(bounds.width) || !positive(bounds.height) || bounds.x + bounds.width > profile.width ||
|
||||
|
||||
@@ -176,7 +176,6 @@ export const ONROAD_LAYOUT_TEMPLATE = `
|
||||
<p v-if="selectedWidget?.kind === 'weather'" class="gx-note">Weather data by <a href="https://open-meteo.com/" target="_blank" rel="noopener noreferrer">Open-Meteo</a>. Uses your GPS area when enabled; updates in the background about every 10 minutes.</p>
|
||||
<p class="gx-note">The stopped timer appears in General edit and Stopped timer. Turn off editing aids to see the screen without outlines and guides.</p>
|
||||
<p class="gx-note">The steering wheel and driver monitoring icon can be resized in each layout.{{ projection ? ' Drag the corner to resize the map, PiP views, and turn-by-turn card. The map also has adjustable opacity.' : profile.widgets.nav_map ? ' The map overlay has adjustable size and opacity.' : '' }} Existing display preferences and driving state still control when widgets appear.</p>
|
||||
<p v-if="!projection" class="gx-note">Small speed-limit signs can overlap confirmation actions. Live confirmations hide an overlapping sign until the decision ends. Select either widget in the list to edit it.</p>
|
||||
<p v-if="!projection && state.showFavoriteZones" class="gx-note">Favorite tap areas apply to enabled slots. Speed-limit controls and the steering wheel take priority when the drawer is closed.</p>
|
||||
</div></GxCollapse>
|
||||
<GxNotice v-if="state.placementError" tone="warn">{{ state.placementError }}</GxNotice>
|
||||
|
||||
@@ -365,16 +365,6 @@ export const LayoutWidgetPreview = {
|
||||
<path v-if="pending(scene)" d="M90 12 V-8 M84 -2 L90 -8 L96 -2" fill="none" :stroke="palette.text || '#ffffff'" stroke-width="2" />
|
||||
<text x="0" y="66" font-size="58" font-weight="700">45<tspan dx="10" font-size="36" font-weight="500">+5</tspan></text>
|
||||
</template>
|
||||
<template v-else-if="widget.kind === 'speed_limit_actions'">
|
||||
<template v-if="pending(scene)">
|
||||
<line :x1="widget.width / 2" :x2="widget.width / 2" :y1="profile === 'large' ? 46 : 6" :y2="profile === 'large' ? 98 : 42" stroke="#9bb2adaa" />
|
||||
<text v-for="(label, index) in ['Accept', 'Decline']" :key="label" :x="widget.width * (index ? .75 : .25)"
|
||||
:y="profile === 'large' ? 72 : 24" text-anchor="middle" dominant-baseline="middle"
|
||||
:font-size="profile === 'large' ? 64 : 50" font-weight="500">{{ label }}</text>
|
||||
</template>
|
||||
<text v-else :x="widget.width / 2" :y="profile === 'large' ? 72 : 24" text-anchor="middle"
|
||||
dominant-baseline="middle" :font-size="profile === 'large' ? 48 : 28">Toyota guidance</text>
|
||||
</template>
|
||||
<g v-else-if="widget.kind === 'torque_bar'" fill="none" stroke="white" stroke-linecap="round">
|
||||
<path :d="'M 12 ' + widget.height * .8 + ' Q ' + widget.width / 2 + ' ' + widget.height * .55 + ' ' + (widget.width - 12) + ' ' + widget.height * .8" :stroke-width="widget.height * .18" opacity=".3" />
|
||||
<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" />
|
||||
@@ -1167,7 +1157,7 @@ export const OnroadLayoutPage = {
|
||||
Object.assign(this.layout[id], position)
|
||||
if (before) this.recordChange(before)
|
||||
this.state.placementError = ""
|
||||
} else this.state.placementError = "Keep widgets within the screen and clear of Speed limit actions. The last valid position is kept."
|
||||
} else this.state.placementError = "Speed-limit confirmation overlaps set speed, torque, or screen bounds"
|
||||
this.state.notice = ""
|
||||
},
|
||||
add(id) {
|
||||
@@ -1243,24 +1233,11 @@ export const OnroadLayoutPage = {
|
||||
setSpeedSources(key, value) {
|
||||
if (!this.editable || this.state.drag || this.state.layerDrag || this.selectedWidget?.kind !== "cruise_limits" ||
|
||||
!["speedSources", "speedSourcesCard"].includes(key)) return
|
||||
const before = clone(this.state.draft), oldHeight = this.profile.widgets.cruise_limits.height
|
||||
const widgets = this.state.data.metadata.profiles[this.state.profile].widgets
|
||||
const dx = widgets.speed_limit_actions.default.x - widgets.cruise_limits.default.x
|
||||
const gap = widgets.speed_limit_actions.default.y - widgets.cruise_limits.default.y - widgets.cruise_limits.height
|
||||
const sourceGap = widgets.cruise_limits.sourcesExtent?.actionGap ?? gap
|
||||
const oldGap = this.state.draft.speedSources === true ? sourceGap : gap
|
||||
const before = clone(this.state.draft)
|
||||
this.state.draft[key] = value === true
|
||||
const card = this.layout.cruise_limits, actions = this.layout.speed_limit_actions, height = this.profile.widgets.cruise_limits.height
|
||||
// Actions that sat right under the card follow its new bottom; both stay on screen.
|
||||
if (actions && actions.x === card.x + dx && actions.y === card.y + oldHeight + oldGap) {
|
||||
const nextGap = this.state.draft.speedSources === true ? sourceGap : gap
|
||||
card.y = Math.min(card.y, placementLimits(this.limitProfile, "speed_limit_actions", this.layout).maxY - height - nextGap)
|
||||
actions.y = card.y + height + nextGap
|
||||
}
|
||||
for (const id of ["cruise_limits", "speed_limit_actions"].filter(id => this.layout[id])) {
|
||||
const limits = placementLimits(this.limitProfile, id, this.layout)
|
||||
this.layout[id].y = Math.max(limits.minY, Math.min(this.layout[id].y, limits.maxY))
|
||||
}
|
||||
// The card grows with its sources; keep it on screen.
|
||||
const card = this.layout.cruise_limits, limits = placementLimits(this.limitProfile, "cruise_limits", this.layout)
|
||||
card.y = Math.max(limits.minY, Math.min(card.y, limits.maxY))
|
||||
this.recordChange(before)
|
||||
this.state.notice = ""
|
||||
},
|
||||
@@ -1330,7 +1307,7 @@ export const OnroadLayoutPage = {
|
||||
this.state.placementError = ""
|
||||
} else {
|
||||
Object.assign(position, before.layouts[this.state.profile][this.state.selected])
|
||||
this.state.placementError = "That size would cover Speed limit actions. The last valid size is kept."
|
||||
this.state.placementError = "Invalid widget size"
|
||||
}
|
||||
event.target.value = position.size
|
||||
},
|
||||
@@ -1420,7 +1397,7 @@ export const OnroadLayoutPage = {
|
||||
} else {
|
||||
position.size = previous
|
||||
event.target.value = previous
|
||||
this.state.placementError = "That size would cover Speed limit actions. The last valid size is kept."
|
||||
this.state.placementError = "Invalid widget size"
|
||||
}
|
||||
},
|
||||
boxInput(axis, event) {
|
||||
|
||||
@@ -24,7 +24,7 @@ const post = (fetcher, path, body, signal) => fetcher(path, {
|
||||
|
||||
export const SETTINGS_SECTIONS = Object.freeze([
|
||||
{ id: "lateral", label: "Lateral (Steering)", icon: "bi-arrows-move", pages: ["aol", "lane_change", "lane", "torque", "torque/developer"] },
|
||||
{ id: "longitudinal", label: "Longitudinal (Speed & Following)", icon: "bi-speedometer2", pages: ["driving_options", "profiles", "conditional", "curve", "slc", "personalities", "aggressive", "standard", "relaxed", "traffic"] },
|
||||
{ id: "longitudinal", label: "Longitudinal (Speed & Following)", icon: "bi-speedometer2", pages: ["profiles", "conditional", "curve", "slc", "personalities", "aggressive", "standard", "relaxed", "traffic"] },
|
||||
{ id: "wheel", label: "Wheel Controls", icon: "bi-controller", pages: ["wheel"] },
|
||||
{ id: "visual", label: "Visual (Display & UI)", icon: "bi-eye", pages: ["display", "appearance", "ui_layout", "favorites", "pip"] },
|
||||
{ id: "sounds", label: "Sounds & Alerts", icon: "bi-volume-up", pages: ["sounds"] },
|
||||
|
||||
@@ -70,7 +70,7 @@ export function softwareProgress(updater, operations = {}) {
|
||||
"finalizing update...": "Preparing update", "updating...": "Updating software",
|
||||
checking: "Checking for updates", downloading: "Downloading update", finalizing: "Preparing update",
|
||||
preparing: "Preparing update", fetching: "Downloading update", validating: "Validating update",
|
||||
applying: "Applying update", submodules: "Preparing dependencies", rebooting: "Restarting device",
|
||||
agnos: "Downloading and installing AGNOS", applying: "Applying update", submodules: "Preparing dependencies", rebooting: "Restarting device",
|
||||
complete: "Update complete", error: "Update failed", unavailable: "Updater status unavailable", timed_out: "Update is taking longer than expected" }
|
||||
if (!active && (!stage || ["idle", "unknown"].includes(stage))) return null
|
||||
const percent = Number.isFinite(progress?.percent) && progress.percent >= 0 && progress.percent <= 100 ? progress.percent : null
|
||||
|
||||
@@ -35,7 +35,7 @@ export async function widgetArtMetadata(blob, header = null) {
|
||||
Object.keys(metadata.sprites).length > 24) throw new Error("Invalid widget art metadata")
|
||||
for (const [id, rect] of Object.entries(metadata.sprites)) {
|
||||
const minX = id === "speed_limit" ? -192 : -2
|
||||
const minY = id === "speed_limit_actions" ? -33 : id === "cruise_limits" ? -20 : id === "speed_limit" ? -13 : -1
|
||||
const minY = id === "cruise_limits" ? -20 : id === "speed_limit" ? -13 : -1
|
||||
if (!/^[a-z_]+$/.test(id) || !rect || ![rect.x,rect.y,rect.width,rect.height].every(Number.isInteger) ||
|
||||
rect.x < 0 || rect.y < 0 || rect.width < 1 || rect.height < 1 ||
|
||||
rect.x + rect.width > metadata.width || rect.y + rect.height > metadata.height ||
|
||||
|
||||
@@ -34,7 +34,6 @@ export const SETTINGS_WIKI_LINKS = Object.freeze({
|
||||
hub: settings,
|
||||
lateral: settings + '#steering',
|
||||
longitudinal: settings + '#driving-controls',
|
||||
driving_options: settings + '#driving-controls',
|
||||
personalities: settings + '#customize-driving-personalities',
|
||||
starport_options: starport,
|
||||
aol: settings + '#always-on-lateral',
|
||||
|
||||
@@ -4,15 +4,141 @@ Model Manager installs the versioned catalog into `/data/models/v26`. Downloads
|
||||
|
||||
Catalog behavior versions describe model inputs and outputs. The artifact ABI and compiler revision separately identify runtime compatibility. Existing compiled artifacts can be migrated when their kernels and state can be preserved and verified; changing the version label alone does not establish compatibility. Unavailable catalog entries cannot be downloaded or selected.
|
||||
|
||||
`modeld` records the loaded artifact digest, process identity, variant, and fallback reason in a bounded volatile receipt. Status requires a matching running process and fresh valid model outputs before reporting an active model. A failed Chestnut load falls back to the initialized small runner. Artifact integrity and bench inference do not establish on-road driving quality.
|
||||
`modeld` records the loaded artifact digest, process identity, variant, and fallback reason in a bounded volatile receipt. Status requires a matching running process and fresh valid model outputs before reporting an active model. A failed Chestnut startup requests isolated Small recovery; inference failure falls back to the initialized Small runner. Artifact integrity and bench inference do not establish on-road driving quality.
|
||||
|
||||
## Conditional Model: automatic local model switching
|
||||
|
||||
Galaxy Models has three settings tabs: **Single Model**, **Split Model** and
|
||||
**Conditional Model**. Single Model handles all driving. Split Model assigns
|
||||
steering and speed to separate models using Model Laboratory and Chestnut.
|
||||
Conditional Model switches the entire local Small runner according to speed;
|
||||
no external GPU is required. Browsing a settings tab does not activate a mode.
|
||||
|
||||
Configure City, Highway and the Highway speed while offroad, then enable
|
||||
Conditional Model. The speed uses the same `GalaxySettingRow` slider as Toggles,
|
||||
including fine scrubbing, default reset and save feedback. It defaults to
|
||||
**50 mph** and accepts 10–100 mph. Every normal drive starts with **City**.
|
||||
There is no manual road selection, configurable starting mode or cooldown input.
|
||||
The separate Single Model choice remains saved when Conditional Model is enabled.
|
||||
|
||||
Both verified runners load and warm sequentially at drive startup and remain
|
||||
resident until normal process teardown. Only one runs per frame, with independent
|
||||
history buffers. Identical City/Highway assignments use a single runner.
|
||||
Missing/corrupt artifacts, unsupported state mapping or insufficient memory
|
||||
headroom disable switching and retain the initialized fallback. Chestnut, Split
|
||||
Model and Jetlink retain their existing precedence and fallback behavior;
|
||||
expected external-model precedence is informational, not a driver fault alert.
|
||||
|
||||
### Speed selection and interlock
|
||||
|
||||
Highway is requested at the exact configured speed, without a delay.
|
||||
City requires **30 continuous seconds** at least **5 mph below** that speed;
|
||||
both guards are internal constants. A subsequent Highway request can happen
|
||||
immediately, avoiding a cooldown delay during a merge. Repeated City entries
|
||||
always require another complete low-speed interval. Speed is a condition hint,
|
||||
not geographic road classification: slow highway traffic and fast local roads
|
||||
can be misclassified.
|
||||
|
||||
Stale, missing, reordered, nonfinite or implausible speed samples reset the City
|
||||
timer. Sampling continues while engaged, but crossing a threshold cannot acquire
|
||||
an engagement hold or switch a runner. Requests require fresh valid model output,
|
||||
fresh disengaged vehicle/control state and a fresh idle acknowledgment. There
|
||||
is no preferences-reading thread, onroad configuration API or filesystem I/O in
|
||||
the automatic request path.
|
||||
|
||||
Selfdrived grants the session/request-bound hold only while ordinary control is
|
||||
disabled and both independent axes are inactive, unrequested and disarmed. Stock
|
||||
cruise must also be off. Same-tick engagement loses to the existing no-entry
|
||||
protection; the final independent-axis publication is inhibited as well. Standing
|
||||
still never permits an engaged switch. Missing acknowledgments time out after
|
||||
one second with the current runner retained.
|
||||
|
||||
The target's preallocated state is reset in place, preserving captured JIT buffer
|
||||
addresses. Action smoothing and lane-change state restart at the handoff. Existing
|
||||
model, driving-data, odometry, lane-change and identity messages keep their sole
|
||||
original publisher. The hold spans five valid output frames and releases only
|
||||
when selfdrived sees fresh output at or after completion. Stale/missing status,
|
||||
old output and expired timers never release a hold. A restarted process must
|
||||
establish fresh output before a prior hold can clear. There is no automatic
|
||||
re-engagement.
|
||||
|
||||
### Failure recovery and driver notices
|
||||
|
||||
A target reset/inference/action failure retains or restores the previous model;
|
||||
five valid recovery frames are required before releasing an established hold.
|
||||
Failures pause further switching for the drive. A previous-runner reset failure
|
||||
exits under the hold instead of running potentially corrupted history.
|
||||
|
||||
A two-second handoff timeout rolls back when disengagement is established.
|
||||
Manager bounds startup preload to 120 seconds. During an acknowledged hold, a
|
||||
native inference stall with progressing cameras triggers bounded SIGINT/SIGKILL
|
||||
escalation. The old process must exit before a single-model recovery process can
|
||||
start using the prior model. An established runner cannot be reclassified as a
|
||||
preload merely because its receipt disappears. An arbitrary established/engaged
|
||||
Small crash does not authorize loading another model. Recovery overrides do not
|
||||
change the next drive's City startup.
|
||||
|
||||
The native alert manager displays **Switching conditional models** throughout a
|
||||
held handoff. Genuine failures and prolonged holds produce visible notices.
|
||||
Notices yield to equal/higher-priority current or retained vehicle alerts, and
|
||||
completion removes only Conditional Model notices. Expected engagement, short
|
||||
message gaps, ordinary speed changes and external-model precedence do not create
|
||||
failure alerts.
|
||||
|
||||
Galaxy shows the actual verified running model, switching and failure state.
|
||||
An enabled setting is configuration, not proof that a runner is active.
|
||||
`POST /api/models/conditional_model` accepts only `enabled`, `city`, `highway` and
|
||||
`thresholdMph`, and only offroad. Legacy `smallProfiles` data is read at one
|
||||
migration boundary; model assignments, enablement and speed migrate, while
|
||||
manual selection, pending manual requests and custom cooldowns are discarded.
|
||||
The next save writes only the canonical `conditionalModel` shape.
|
||||
|
||||
### Module boundaries and qualification
|
||||
|
||||
`conditional_model.py` owns configuration and City startup selection;
|
||||
`conditional_policy.py` owns speed/hysteresis clocks; `conditional_protocol.py`
|
||||
owns the pure held handoff; `conditional_runtime.py` adapts modeld/selfdrived;
|
||||
`conditional_alerts.py` supplies native notices. Tests cover migration, removed
|
||||
controls/APIs, City startup/recovery, shared sliders, speed boundaries, anti-flap
|
||||
behavior, invalid/gapped inputs, engagement races, independent axes, real typed
|
||||
IPC, timeouts, rollback, watchdogs and native-alert priority/retirement.
|
||||
|
||||
Five output frames represent about 250 ms at 20 Hz, plus reset, inference and
|
||||
handshake overhead; actual QCOM timing remains unmeasured. Standard Small files
|
||||
occupy 57.9–85.6 MiB each; disk size is not a device-residency bound. Startup checks
|
||||
host memory headroom (512 MiB plus four times the alternate artifact size), a
|
||||
heuristic rather than accelerator-memory qualification. `modeld.catalog_load`
|
||||
logs verification/construction/warmup durations and peak process RSS; RSS does
|
||||
not measure device allocations. Host tests cannot certify 100% safety, memory
|
||||
capacity, driving quality or device timing. Target bench validation remains
|
||||
required. Small upstream hooks still require review during merges.
|
||||
|
||||
## Model Laboratory
|
||||
|
||||
Laboratory artifact management uses separate AMD variants of small models. A standard on-device artifact or a Chestnut-class large model cannot substitute for one. The manifest declares each variant under `accelerator_artifacts.amd`, with `execution_device: "AMD"`, the current `compiler_revision`, and the same artifact format, digest, size, and chunk-count fields as ordinary catalog artifacts. Files are named `<id>_driving_amd_tinygrad.pkl` under the model's existing catalog directory. Deleting an AMD variant preserves the ordinary on-device model.
|
||||
Laboratory artifact management supports separate AMD variants of Small models
|
||||
and Chestnut-class large models. At startup the frozen request can substitute
|
||||
an installed native Small counterpart for one Small role while retaining a
|
||||
Chestnut-backed role. The manifest declares AMD variants under
|
||||
`accelerator_artifacts.amd`, with `execution_device: "AMD"`, the current
|
||||
`compiler_revision`, and the same artifact format, digest, size, and chunk-count
|
||||
fields as ordinary catalog artifacts. Files are named
|
||||
`<id>_driving_amd_tinygrad.pkl` under the model's existing catalog directory.
|
||||
Deleting an AMD variant preserves the ordinary on-device model.
|
||||
|
||||
The Galaxy page and parked configuration owner are available. The standalone pair runner verifies both AMD artifacts, shares compatible camera preprocessing, keeps each model's state separate, and rejects the whole frame if either role fails. It decodes each model's own action units before choosing lateral curvature and longitudinal acceleration/stopping. The compositor assigns lateral geometry and the corresponding plan columns to the lateral model, and leads, scene metadata, and current-frame pose to the longitudinal model.
|
||||
The Galaxy page and configuration owner are available. The pair runner verifies
|
||||
both role artifacts, shares compatible camera preprocessing, keeps each model's
|
||||
state separate, and rejects the whole frame if either role fails. It decodes each
|
||||
model's own action units before choosing lateral curvature and longitudinal
|
||||
acceleration/stopping. The compositor assigns lateral geometry and the
|
||||
corresponding plan columns to the lateral model, and leads, scene metadata, and
|
||||
current-frame pose to the longitudinal model.
|
||||
|
||||
Paired inference is not integrated into modeld yet, so production reports `runtimeSupported: false` and rejects enabling a pair. Completing it requires two verified AMD small-model variants, modeld loading/fallback and fresh pair status, then a Chestnut bench run covering real shared-warp execution, memory, timing and driver monitoring coexistence. CPU state-isolation and mocked frame tests do not qualify the AMD pair.
|
||||
Paired inference is integrated into modeld through a frozen startup request and
|
||||
pair receipts. Production advertises `runtimeSupported: true`; configuration
|
||||
requires Chestnut and at least one Chestnut-backed role. Failed pair startup uses
|
||||
the existing isolated Small recovery, and inference failures fall back to the
|
||||
initialized Small runner. CPU state-isolation and mocked frame tests do not
|
||||
establish device memory, timing, or on-road driving quality.
|
||||
|
||||
Jetlink is a separate remote model connection for comma 3X and comma 4. In Galaxy
|
||||
Model Manager, choose **Off**, **USB computer**, or **iPhone / iPad** while parked.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Conditional Model notices use the existing alert manager and native UI surfaces."""
|
||||
from openpilot.selfdrive.selfdrived.events import Alert, AlertStatus, AlertSize, Priority, VisualAlert, AudibleAlert, ET
|
||||
|
||||
ALERT_TYPES = ('conditionalModelSwitch/permanent', 'conditionalModelFailure/permanent')
|
||||
|
||||
|
||||
def conditional_model_alert(state, *, holding, stalled=False):
|
||||
error = str(state.error) if state is not None else ''
|
||||
switching = holding or state is not None and str(state.phase) in ('waiting', 'switching', 'recovering')
|
||||
if not error and not switching:
|
||||
return None
|
||||
failed = bool(error or stalled)
|
||||
title = 'Conditional model switch stalled' if stalled else 'Conditional Model unavailable' if error else 'Switching conditional models'
|
||||
detail = ('Engagement blocked; waiting for model recovery' if stalled else
|
||||
error if error else 'Wait for completion before engaging')
|
||||
alert = Alert(title, detail, AlertStatus.userPrompt if failed else AlertStatus.normal,
|
||||
AlertSize.mid if failed else AlertSize.small, Priority.LOW if failed else Priority.LOWEST,
|
||||
VisualAlert.none, AudibleAlert.none, .1)
|
||||
alert.alert_type = ALERT_TYPES[1 if failed else 0]
|
||||
alert.event_type = ET.PERMANENT
|
||||
return alert
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Persistent configuration for automatic, resident City/Highway model switching."""
|
||||
from openpilot.starpilot.models.catalog import BUNDLED_CURRENT, DEFAULT_SMALL
|
||||
from openpilot.starpilot.models.conditional_policy import DEFAULT_THRESHOLD_MPH
|
||||
|
||||
CONDITIONS = ('city', 'highway')
|
||||
|
||||
|
||||
def defaults() -> dict:
|
||||
return {'enabled': False, 'city': DEFAULT_SMALL, 'highway': DEFAULT_SMALL, 'thresholdMph': DEFAULT_THRESHOLD_MPH}
|
||||
|
||||
|
||||
def validate(value: object, entries) -> bool:
|
||||
return (isinstance(value, dict) and set(value) == set(defaults()) and type(value['enabled']) is bool and
|
||||
type(value['thresholdMph']) is int and 10 <= value['thresholdMph'] <= 100 and
|
||||
all(isinstance(value[name], str) and value[name] != BUNDLED_CURRENT and value[name] in entries and
|
||||
not entries[value[name]].uses_external_gpu for name in CONDITIONS))
|
||||
|
||||
|
||||
def configuration(saved: dict, entries) -> dict:
|
||||
if 'conditionalModel' in saved:
|
||||
value = saved['conditionalModel']
|
||||
else:
|
||||
# Compatibility boundary only. Obsolete manual intent and cooldown values
|
||||
# never enter the runtime; the next configuration save writes the new shape.
|
||||
legacy = saved.get('smallProfiles')
|
||||
allowed = {'enabled', 'highway', 'city', 'selected', 'automatic', 'thresholdMph', 'cityDelaySeconds'}
|
||||
if not isinstance(legacy, dict) or not {'enabled', 'city', 'highway'} <= set(legacy) or set(legacy) - allowed:
|
||||
return defaults()
|
||||
value = {name: legacy.get(name, default) for name, default in defaults().items()}
|
||||
if not validate(value, entries):
|
||||
return defaults()
|
||||
if value['enabled'] and saved.get('randomizer') is True:
|
||||
return value | {'enabled': False}
|
||||
return dict(value)
|
||||
|
||||
|
||||
def starting_model(saved: dict) -> str:
|
||||
"""Every normal Conditional Model startup uses City; recovery may override it."""
|
||||
return saved['conditionalModel']['city'] if saved['conditionalModel']['enabled'] else saved['small']
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Speed is a road-mode hint, never authority to change models or engage."""
|
||||
import math
|
||||
|
||||
from openpilot.starpilot.models.conditional_protocol import FRESH_NS, fresh
|
||||
|
||||
MPH_TO_MS = 0.44704
|
||||
HYSTERESIS_MPH = 5
|
||||
DEFAULT_THRESHOLD_MPH = 50
|
||||
CITY_DELAY_SECONDS = 30
|
||||
|
||||
|
||||
class SpeedPolicy:
|
||||
"""Fast Highway entry, delayed City entry, and no progress on stale samples."""
|
||||
def __init__(self, threshold_mph=DEFAULT_THRESHOLD_MPH):
|
||||
if type(threshold_mph) is not int or not 10 <= threshold_mph <= 100:
|
||||
raise ValueError('Invalid Conditional Model speed policy')
|
||||
self.high = threshold_mph * MPH_TO_MS
|
||||
self.low = (threshold_mph - HYSTERESIS_MPH) * MPH_TO_MS
|
||||
self.delay = CITY_DELAY_SECONDS * 1_000_000_000
|
||||
self.low_since = None
|
||||
self.last_sample = self.last_switch = 0
|
||||
self.hint = ''
|
||||
|
||||
def switched(self, now):
|
||||
self.last_switch, self.low_since = now, None
|
||||
|
||||
def sample(self, speed, stamp, now, *, valid, current):
|
||||
self.hint = ''
|
||||
if (not valid or type(speed) not in (int, float) or not math.isfinite(speed) or not 0 <= speed <= 100 or
|
||||
not fresh(stamp, now) or stamp < self.last_sample or current not in ('highway', 'city')):
|
||||
self.low_since = None
|
||||
return None
|
||||
if self.last_sample and stamp - self.last_sample > FRESH_NS:
|
||||
self.low_since = None
|
||||
self.last_sample = stamp
|
||||
if speed >= self.high:
|
||||
self.hint = 'highway'
|
||||
self.low_since = None
|
||||
return 'highway' if current != 'highway' else None
|
||||
if speed <= self.low and current != 'city':
|
||||
self.hint = 'city'
|
||||
if self.low_since is None:
|
||||
self.low_since = stamp
|
||||
if now - self.low_since >= self.delay and now - self.last_switch >= self.delay:
|
||||
return 'city'
|
||||
else:
|
||||
self.low_since = None
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Pure Conditional Model handshake and resident-runner state machine; no process or GPU imports."""
|
||||
from dataclasses import dataclass
|
||||
import uuid
|
||||
|
||||
FRESH_NS = 150_000_000
|
||||
ACK_TIMEOUT_NS = 1_000_000_000
|
||||
SWITCH_TIMEOUT_NS = 2_000_000_000
|
||||
SETTLE_FRAMES = 5
|
||||
PRELOAD_TIMEOUT_NS = 120_000_000_000
|
||||
|
||||
|
||||
def fresh(stamp: int, now: int) -> bool:
|
||||
return 0 < stamp <= now and now - stamp <= FRESH_NS
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class State:
|
||||
session: str
|
||||
request: str
|
||||
phase: str
|
||||
frame: int
|
||||
born: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Ack:
|
||||
session: str
|
||||
request: str
|
||||
holding: bool
|
||||
source: int
|
||||
stamp: int
|
||||
idle: bool = False
|
||||
|
||||
|
||||
class EngagementHold:
|
||||
"""A granted hold never expires into permission to engage."""
|
||||
def __init__(self):
|
||||
self.owner: tuple[str, str] | None = None
|
||||
self.last_stamp = 0
|
||||
self.held_since = 0
|
||||
|
||||
def step(self, state: State | None, stamp: int, now: int, *, idle: bool, model_stamp: int, model_valid: bool,
|
||||
release_allowed: bool = True) -> bool:
|
||||
if state is None or not fresh(stamp, now) or stamp < self.last_stamp:
|
||||
return self.owner is not None
|
||||
self.last_stamp = stamp
|
||||
key = state.session, state.request
|
||||
if state.phase in ('waiting', 'switching', 'recovering'):
|
||||
if idle and state.session and state.request:
|
||||
if self.owner != key:
|
||||
self.held_since = now
|
||||
self.owner = key
|
||||
elif self.owner is not None and state.phase in ('ready', 'disabled'):
|
||||
# The same request can finish/abort, or a new process can establish a new
|
||||
# publisher. Old output cannot release a hold after either boundary.
|
||||
same = key == self.owner
|
||||
restarted = state.session != self.owner[0]
|
||||
if (idle and release_allowed and (same or restarted) and model_valid and fresh(model_stamp, now) and
|
||||
0 < state.born <= state.frame <= model_stamp <= now and state.born <= stamp):
|
||||
self.owner = None
|
||||
self.held_since = 0
|
||||
return self.owner is not None
|
||||
|
||||
|
||||
class ResidentSwitch:
|
||||
def __init__(self, models: dict, active: str, *, now: int, error: str = ''):
|
||||
# Each entry is (runner, prepared artifact, preallocated reset closure).
|
||||
self.models = models
|
||||
self.active = self.previous = self.target = active
|
||||
self.session = uuid.uuid4().hex
|
||||
self.born = now
|
||||
self.request = ''
|
||||
self.phase = 'ready' if models else 'disabled'
|
||||
self.error = error
|
||||
self.started = self.announced = self.frame = self.frames = 0
|
||||
self.elapsed = 0.
|
||||
self.safe_to_finish = False
|
||||
|
||||
def before_frame(self, desired: dict | None, *, now: int, idle: bool, ack: Ack | None) -> bool:
|
||||
"""Return True only when the active runner changed at this frame boundary."""
|
||||
old = self.active
|
||||
self.safe_to_finish = idle
|
||||
if (desired and desired.get('session') == self.session and desired.get('id') != self.request and
|
||||
self.phase == 'ready'):
|
||||
self.request = desired['id']
|
||||
self.error = ''
|
||||
if desired.get('model') not in self.models:
|
||||
self.error = 'Requested model is not resident; configure models with the vehicle off'
|
||||
elif not idle:
|
||||
self.error = 'Fully disengage cruise and independent lateral control before switching'
|
||||
elif desired['model'] != self.active:
|
||||
self.previous, self.target = self.active, desired['model']
|
||||
self.phase, self.started, self.announced = 'waiting', now, 0
|
||||
if self.phase == 'waiting':
|
||||
if not idle:
|
||||
# The driver may engage before the hold is granted, or a source may
|
||||
# briefly go stale. Retain the current runner without declaring a fault.
|
||||
self.abort('', now)
|
||||
elif now - self.started >= ACK_TIMEOUT_NS:
|
||||
self.abort('Engagement hold acknowledgment timed out; current model retained', now)
|
||||
elif (self.announced and ack is not None and ack.holding and fresh(ack.stamp, now) and
|
||||
(ack.session, ack.request) == (self.session, self.request) and
|
||||
self.announced <= ack.source <= ack.stamp):
|
||||
try:
|
||||
self.models[self.target][2]()
|
||||
except Exception:
|
||||
self.abort('Model state reset failed; current model retained', now)
|
||||
else:
|
||||
self.active, self.phase, self.frames = self.target, 'switching', 0
|
||||
elif self.phase == 'switching' and idle and now - self.started >= SWITCH_TIMEOUT_NS:
|
||||
self.abort('Model handoff timed out; previous model restored', now)
|
||||
return self.active != old
|
||||
|
||||
def abort(self, error: str, now: int) -> None:
|
||||
resetting = self.active != self.previous
|
||||
self.active, self.phase, self.error = self.previous, 'recovering' if resetting else 'ready', error
|
||||
self.frames = 0
|
||||
self.elapsed = (now - self.started) / 1e9 if self.started else 0.
|
||||
if resetting:
|
||||
try:
|
||||
self.models[self.previous][2]()
|
||||
except Exception as exc:
|
||||
# Do not run potentially corrupted history after a reset fails. Exit
|
||||
# under the existing hold; manager owns the isolated recovery process.
|
||||
self.error = 'Previous model reset failed; isolated recovery required'
|
||||
raise RuntimeError(self.error) from exc
|
||||
|
||||
def published(self, frame: int, now: int) -> None:
|
||||
if frame <= self.frame:
|
||||
return
|
||||
self.frame = frame
|
||||
if self.phase in ('switching', 'recovering') and self.safe_to_finish:
|
||||
self.frames += 1
|
||||
if self.frames >= SETTLE_FRAMES:
|
||||
self.phase = 'ready'
|
||||
self.elapsed = (now - self.started) / 1e9
|
||||
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Resident Small-model switching and a fail-closed engagement handshake.
|
||||
|
||||
All GPU allocation and artifact loading happen at startup on the model thread. The engagement owner acknowledges a hold
|
||||
before modeld may change runners, and releases it only after fresh output.
|
||||
"""
|
||||
import time
|
||||
import uuid
|
||||
import math
|
||||
|
||||
from openpilot.starpilot.models.conditional_policy import SpeedPolicy
|
||||
from openpilot.starpilot.models.conditional_protocol import (
|
||||
SWITCH_TIMEOUT_NS, State, Ack, EngagementHold, ResidentSwitch, fresh,
|
||||
)
|
||||
|
||||
|
||||
def modeld_idle(sm, now: int) -> bool:
|
||||
"""Unknown, stale, paused/armed, stock cruise and either active axis all deny."""
|
||||
try:
|
||||
for name in ('selfdriveState', 'carControl', 'carState'):
|
||||
if not (sm.seen[name] and sm.valid[name] and sm.alive[name] and fresh(int(sm.logMonoTime[name]), now)):
|
||||
return False
|
||||
state, command, car = sm['selfdriveState'], sm['carControl'], sm['carState']
|
||||
if (state.enabled or state.active or str(state.state) != 'disabled' or
|
||||
command.enabled or command.latActive or command.longActive or car.cruiseState.enabled or
|
||||
not car.canValid or car.canTimeout or not math.isfinite(car.vEgo) or not 0 <= car.vEgo <= 100):
|
||||
return False
|
||||
# Selfdrived's ack additionally covers armed independent control. This
|
||||
# cheap frame-side check covers active axes before/after that handshake.
|
||||
return True
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
class ConditionalModelGate:
|
||||
def __init__(self):
|
||||
from openpilot.cereal import messaging
|
||||
self.sm = messaging.SubMaster(['conditionalModelState'])
|
||||
self.pm = messaging.PubMaster(['conditionalModelAck'])
|
||||
self.hold = EngagementHold()
|
||||
|
||||
def alert(self):
|
||||
from openpilot.starpilot.models.conditional_alerts import conditional_model_alert
|
||||
state = self.sm['conditionalModelState']
|
||||
stamp = int(self.sm.logMonoTime['conditionalModelState'])
|
||||
now = time.monotonic_ns()
|
||||
valid = bool(self.sm.seen['conditionalModelState'] and self.sm.valid['conditionalModelState'] and fresh(stamp, now))
|
||||
return conditional_model_alert(state if valid else None, holding=self.hold.owner is not None,
|
||||
stalled=bool(self.hold.owner and now - self.hold.held_since >= SWITCH_TIMEOUT_NS))
|
||||
|
||||
def update_alerts(self, alerts, manager, frame=0):
|
||||
from openpilot.starpilot.models.conditional_alerts import ALERT_TYPES
|
||||
for name in ALERT_TYPES:
|
||||
manager.alerts.pop(name, None)
|
||||
notice = self.alert()
|
||||
retained = (entry.alert for entry in manager.alerts.values() if entry.alert is not None and entry.active(frame))
|
||||
if notice is not None and not any(alert.priority >= notice.priority for alert in (*alerts, *retained)):
|
||||
alerts.append(notice)
|
||||
|
||||
def step(self, drive, car) -> bool:
|
||||
from openpilot.cereal import log, messaging
|
||||
from openpilot.starpilot.aol.runtime import current_intent
|
||||
from openpilot.selfdrive.selfdrived.events import ET
|
||||
self.sm.update(0)
|
||||
now = time.monotonic_ns()
|
||||
state = self.sm['conditionalModelState']
|
||||
stamp = int(self.sm.logMonoTime['conditionalModelState'])
|
||||
valid = self.sm.seen['conditionalModelState'] and self.sm.valid['conditionalModelState'] and self.sm.alive['conditionalModelState']
|
||||
wire = State(str(state.session), str(state.requestId), str(state.phase), int(state.frameMonoTime), int(state.sessionStartMonoTime)) if valid else None
|
||||
axes = getattr(drive, 'aol_axis_decision', None)
|
||||
idle = (drive.initialized and getattr(drive, 'conditional_car_state_valid', False) and
|
||||
not drive.enabled and not drive.active and drive.state_machine.state == log.SelfdriveState.OpenpilotState.disabled and
|
||||
car.canValid and not car.canTimeout and not car.cruiseState.enabled and
|
||||
not any(getattr(axes, field, False) for field in
|
||||
('desired_lateral', 'desired_longitudinal', 'lateral_active', 'longitudinal_active')))
|
||||
if drive.aol_replay:
|
||||
intent = current_intent(drive.sm, car_state_ns=drive.aol_car_state_log_ns, now_ns=now,
|
||||
previous=getattr(drive, 'aol_last_intent', None), companion=getattr(drive, 'aol_intent_companion', None), drain=False)
|
||||
idle = bool(idle and intent is not None and not intent.allowedLatch and not intent.lateralArmed)
|
||||
model_valid = bool(drive.sm.valid['modelV2'] and drive.sm.alive['modelV2'])
|
||||
events = getattr(drive, 'events', None)
|
||||
holding = self.hold.step(wire, stamp, now, idle=idle, model_stamp=int(drive.sm.logMonoTime['modelV2']), model_valid=model_valid,
|
||||
release_allowed=events is None or not events.contains(ET.ENABLE))
|
||||
message = messaging.new_message('conditionalModelAck', valid=True)
|
||||
message.conditionalModelAck = {'session': str(state.session), 'requestId': str(state.requestId),
|
||||
'holding': holding and self.hold.owner == (str(state.session), str(state.requestId)),
|
||||
'stateMonoTime': stamp, 'idle': idle}
|
||||
self.pm.send('conditionalModelAck', message)
|
||||
return holding
|
||||
|
||||
|
||||
class ConditionalModelRuntime:
|
||||
"""Startup-only allocation, frame-boundary selection, one existing publisher."""
|
||||
def __init__(self, model, prepared, config, *, root, cam_w, cam_h, enabled):
|
||||
import os
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.starpilot.models.manager import catalog, verified_artifact, shipped_default
|
||||
from openpilot.starpilot.models.catalog import DEFAULT_SMALL, DEFAULT_SMALL_SHA256
|
||||
from openpilot.starpilot.models.receipt import process_start_ticks
|
||||
from openpilot.starpilot.models.runner import load_verified_model
|
||||
self.config, self.pid = config, os.getpid()
|
||||
self.ticks = process_start_ticks(self.pid)
|
||||
self.ack = messaging.SubMaster(['conditionalModelAck'])
|
||||
self.policy = SpeedPolicy(config['thresholdMph'])
|
||||
self.paused = False
|
||||
self.last_status = None
|
||||
self.unavailable_reason = ''
|
||||
models, error = {}, ''
|
||||
if enabled and config['enabled']:
|
||||
try:
|
||||
if model.model_id != config['city']:
|
||||
raise ValueError('Selected model fell back; resident switching unavailable for this drive')
|
||||
models[model.model_id] = model, prepared, model.handoff_reset()
|
||||
entries = catalog(root)
|
||||
for mid in {config['highway'], config['city']} - {model.model_id}:
|
||||
path = verified_artifact(mid, entries, root)
|
||||
shipped = mid == DEFAULT_SMALL and path is None
|
||||
if shipped:
|
||||
path = shipped_default()
|
||||
if path is None:
|
||||
raise ValueError('Alternate Small artifact is missing or corrupt')
|
||||
# Disk size does not qualify GPU residency. Preserve substantial host
|
||||
# headroom; target-device pressure/timing still needs bench evidence.
|
||||
from pathlib import Path
|
||||
memory = dict(line.split(':', 1) for line in Path('/proc/meminfo').read_text().splitlines())
|
||||
available = int(memory['MemAvailable'].split()[0]) * 1024
|
||||
if available < 512 * 1024**2 + 4 * path.stat().st_size:
|
||||
raise MemoryError('Insufficient memory headroom to preload the alternate model')
|
||||
other, artifact = load_verified_model(cam_w, cam_h, path, entries[mid]['version'], False, mid,
|
||||
DEFAULT_SMALL_SHA256 if shipped else entries[mid]['artifact_sha256'], root=root)
|
||||
models[mid] = other, artifact, other.handoff_reset()
|
||||
except Exception as exc:
|
||||
cloudlog.exception('Conditional Model preload failed; keeping the current Small model')
|
||||
models, error = {}, str(exc)[:300]
|
||||
elif config['enabled']:
|
||||
self.unavailable_reason = 'Conditional Model is inactive while an external or Split Model is in use'
|
||||
self.owner = ResidentSwitch(models, model.model_id, now=time.monotonic_ns(), error=error)
|
||||
|
||||
def before_frame(self, sm):
|
||||
self.ack.update(0)
|
||||
now = time.monotonic_ns()
|
||||
a = self.ack['conditionalModelAck']
|
||||
ack = (Ack(str(a.session), str(a.requestId), bool(a.holding), int(a.stateMonoTime), int(self.ack.logMonoTime['conditionalModelAck']), bool(a.idle))
|
||||
if self.ack.seen['conditionalModelAck'] and self.ack.valid['conditionalModelAck'] and self.ack.alive['conditionalModelAck'] else None)
|
||||
idle = bool(modeld_idle(sm, now) and ack and ack.idle and fresh(ack.stamp, now))
|
||||
desired = None
|
||||
if self.owner.models:
|
||||
# A failure pauses automation for the drive; no repeated load/reset loop.
|
||||
self.paused |= bool(self.owner.error)
|
||||
current = 'highway' if self.owner.active == self.config['highway'] else 'city'
|
||||
car = sm['carState']
|
||||
role = self.policy.sample(float(car.vEgo), int(sm.logMonoTime['carState']), now,
|
||||
valid=bool(sm.seen['carState'] and sm.valid['carState'] and sm.alive['carState'] and
|
||||
car.canValid and not car.canTimeout), current=current)
|
||||
if (role and not self.paused and self.owner.phase == 'ready' and idle and not ack.holding and
|
||||
fresh(self.owner.frame, now) and self.config[role] != self.owner.active):
|
||||
desired = {'session': self.owner.session, 'id': uuid.uuid4().hex, 'model': self.config[role]}
|
||||
changed = self.owner.before_frame(desired, now=now, idle=idle, ack=ack)
|
||||
if changed:
|
||||
self.policy.switched(now)
|
||||
status = (self.owner.request, self.owner.phase, self.owner.error)
|
||||
if status != self.last_status:
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
cloudlog.event('conditionalModelState', request=status[0], phase=status[1], error=status[2], model_id=self.owner.active)
|
||||
self.last_status = status
|
||||
return self.owner.models[self.owner.active] if changed else None
|
||||
|
||||
def publish(self, pm, sm, frame):
|
||||
from openpilot.cereal import messaging
|
||||
now = time.monotonic_ns()
|
||||
if frame:
|
||||
self.owner.published(frame, now)
|
||||
message = messaging.new_message('conditionalModelState', valid=True)
|
||||
owner = self.owner
|
||||
ack_idle = bool(self.ack.seen['conditionalModelAck'] and self.ack.valid['conditionalModelAck'] and self.ack.alive['conditionalModelAck'] and
|
||||
fresh(int(self.ack.logMonoTime['conditionalModelAck']), now) and
|
||||
self.ack['conditionalModelAck'].idle and not self.ack['conditionalModelAck'].holding)
|
||||
message.conditionalModelState = {'session': owner.session, 'requestId': owner.request, 'phase': owner.phase,
|
||||
'activeModel': owner.active, 'highwayModel': self.config['highway'], 'cityModel': self.config['city'],
|
||||
'error': owner.error, 'frameMonoTime': owner.frame,
|
||||
'canSwitch': bool(owner.models and owner.phase == 'ready' and modeld_idle(sm, now) and ack_idle),
|
||||
'processPid': self.pid, 'processStartTicks': self.ticks, 'sessionStartMonoTime': owner.born,
|
||||
'transitionSeconds': owner.elapsed, 'fallbackModel': owner.previous,
|
||||
'paused': self.paused or bool(owner.error),
|
||||
'targetMode': self.policy.hint, 'thresholdMph': self.config['thresholdMph'],
|
||||
'unavailableReason': self.unavailable_reason}
|
||||
if owner.phase == 'waiting' and not owner.announced:
|
||||
owner.announced = int(message.logMonoTime)
|
||||
pm.send('conditionalModelState', message)
|
||||
@@ -104,34 +104,7 @@ def _adapter_class():
|
||||
from openpilot.starpilot.models.runner import CatalogModelState
|
||||
if not isinstance(small, CatalogModelState):
|
||||
return None
|
||||
from tinygrad import Device
|
||||
import numpy as np
|
||||
|
||||
queues = [q for name, q in small.input_queues.items() if q.device != "NPY" and name not in FRAME_INPUTS]
|
||||
buffers = [q.uop.base.buffer for q in queues]
|
||||
views = []
|
||||
for buffer in buffers:
|
||||
if not buffer.is_allocated() or not hasattr(buffer.get_storage().host, "mv"):
|
||||
raise ValueError("Small model history has no allocated host mapping")
|
||||
view = buffer.as_memoryview(allow_zero_copy=True)
|
||||
if view.readonly or view.nbytes != buffer.nbytes:
|
||||
raise ValueError("Small model history mapping is not writable or complete")
|
||||
views.append(np.frombuffer(view, dtype=np.uint8))
|
||||
devices = tuple(Device[name] for name in dict.fromkeys(q.device for q in queues))
|
||||
arrays = tuple(small.npy.values())
|
||||
|
||||
def reset():
|
||||
# The local history is idle at a handover. Keep the existing buffers
|
||||
# and synchronize their device before zeroing their mapped storage.
|
||||
for device in devices:
|
||||
device.synchronize()
|
||||
for view in views:
|
||||
view.fill(0)
|
||||
small.prev_desire.fill(0)
|
||||
for array in arrays:
|
||||
array.fill(0)
|
||||
|
||||
return reset
|
||||
return small.handoff_reset()
|
||||
|
||||
return StarPilotAdapter
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ from openpilot.starpilot.models.catalog import (
|
||||
RESOURCE_URL = "https://huggingface.co/buckets/StarPilot-Driving/StarPilot-Resources/resolve"
|
||||
from openpilot.common.hardware import PC
|
||||
from openpilot.starpilot.storage import starpilot_storage_root
|
||||
from openpilot.starpilot.models import conditional_model
|
||||
|
||||
_HOST_MODELS = os.environ.get("STARPILOT_MODEL_DIR", "") if PC else ""
|
||||
ROOT = (Path(_HOST_MODELS) if _HOST_MODELS else starpilot_storage_root() / "models" if PC else Path("/data/models")) / GENERATION
|
||||
@@ -206,7 +207,7 @@ def catalog(root: Path = ROOT) -> dict[str, dict]:
|
||||
|
||||
def preferences(root: Path = ROOT) -> dict:
|
||||
default = {"small": DEFAULT_SMALL, "big": "", "userFavorites": [], "sortMode": "name",
|
||||
"randomizer": False, "blacklistedModels": []}
|
||||
"randomizer": False, "blacklistedModels": [], "conditionalModel": conditional_model.defaults()}
|
||||
try:
|
||||
saved = read_json(root / "preferences.json", 16384)
|
||||
entries = model_entries(root)
|
||||
@@ -222,6 +223,7 @@ def preferences(root: Path = ROOT) -> dict:
|
||||
default["randomizer"] = saved["randomizer"]
|
||||
if saved.get("sortMode") in ("name", "date", "date_oldest", "community", "series", "favorites", "released"):
|
||||
default["sortMode"] = saved["sortMode"]
|
||||
default["conditionalModel"] = conditional_model.configuration(saved | {"randomizer": default["randomizer"]}, entries)
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass
|
||||
return default
|
||||
@@ -309,7 +311,7 @@ class RuntimeSelection:
|
||||
|
||||
def requested_runtime_id(chestnut_available: bool, *, root: Path = ROOT) -> str:
|
||||
prefs = preferences(root)
|
||||
return prefs["big"] if chestnut_available and prefs["big"] else prefs["small"]
|
||||
return prefs["big"] if chestnut_available and prefs["big"] else conditional_model.starting_model(prefs)
|
||||
|
||||
|
||||
def randomize_next_start(chestnut_available: bool, *, root: Path = ROOT, chooser=random.choice) -> dict:
|
||||
@@ -330,10 +332,12 @@ def randomize_next_start(chestnut_available: bool, *, root: Path = ROOT, chooser
|
||||
return prefs
|
||||
|
||||
|
||||
def resolve_runtime(chestnut_available: bool, *, root: Path = ROOT, randomize: bool = False) -> RuntimeSelection:
|
||||
def resolve_runtime(chestnut_available: bool, *, root: Path = ROOT, randomize: bool = False, small_override: str | None = None) -> RuntimeSelection:
|
||||
prefs = randomize_next_start(chestnut_available, root=root) if randomize else preferences(root)
|
||||
entries = catalog(root)
|
||||
small, big = prefs["small"], prefs["big"]
|
||||
if small_override is not None and (small_override not in entries or entries[small_override].get('uses_external_gpu')):
|
||||
raise ModelError('Invalid recovery Small model')
|
||||
small, big = small_override or conditional_model.starting_model(prefs), prefs["big"]
|
||||
small_path = verified_artifact(small, entries, root)
|
||||
shipped = small == DEFAULT_SMALL and small_path is None
|
||||
if shipped:
|
||||
@@ -354,11 +358,13 @@ def resolve_runtime(chestnut_available: bool, *, root: Path = ROOT, randomize: b
|
||||
|
||||
class ModelManager:
|
||||
def __init__(self, *, root: Path = ROOT, parked: Callable[[], bool] | None = None,
|
||||
gpu_present: Callable[[], bool] | None = None, opener=urlopen, jetlink=None, refresh_catalog: bool = False):
|
||||
gpu_present: Callable[[], bool] | None = None, opener=urlopen, jetlink=None, refresh_catalog: bool = False,
|
||||
live_status: Callable[[], dict | None] = lambda: None):
|
||||
self.root, self.opener = root, opener
|
||||
self.refresh_catalog = refresh_catalog
|
||||
self.last_refresh_attempt: float | None = None
|
||||
self.jetlink = jetlink
|
||||
self.live_status = live_status
|
||||
self.parked = parked or (lambda: False)
|
||||
if gpu_present is None:
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_present
|
||||
@@ -614,6 +620,7 @@ class ModelManager:
|
||||
from openpilot.starpilot.models.laboratory import configuration
|
||||
entries, prefs = catalog(self.root), preferences(self.root)
|
||||
parked, gpu = self.parked(), self.gpu_present()
|
||||
live = self.live_status()
|
||||
job = self._job_status()
|
||||
owner = self.jetlink_owner()
|
||||
jetlink = owner.snapshot()
|
||||
@@ -637,9 +644,11 @@ class ModelManager:
|
||||
"unavailableReason": "" if installed else "Checking artifact" if checking else
|
||||
"Download required" if published else f"{GENERATION} download not published"})
|
||||
count = sum(bool(row["installed"]) for row in models)
|
||||
return {"schemaVersion": 1, "models": models, "activeSmallModel": prefs["small"], "activeBigModel": active_big,
|
||||
return {"schemaVersion": 1, "models": models, "activeSmallModel": conditional_model.starting_model(prefs), "activeBigModel": active_big,
|
||||
"conditionalModel": prefs["conditionalModel"],
|
||||
"conditionalModelState": live,
|
||||
"jetlinkBig": jetlink_big, "bigNoneLabel": big_none, "laboratory": configuration(self.root),
|
||||
"currentModel": prefs["big"] if gpu and prefs["big"] else prefs["small"], "userFavorites": prefs["userFavorites"],
|
||||
"currentModel": prefs["big"] if gpu and prefs["big"] else conditional_model.starting_model(prefs), "userFavorites": prefs["userFavorites"],
|
||||
"sortMode": prefs["sortMode"], "randomizer": prefs["randomizer"], "blacklistedModels": prefs["blacklistedModels"],
|
||||
"summary": {"total": len(models), "installed": count, "missing": len(models)-count},
|
||||
"jobId": job.get("jobId", ""), "cancelRequested": job.get("cancelRequested", False),
|
||||
@@ -649,6 +658,7 @@ class ModelManager:
|
||||
"downloadProgress": self._download_progress(job),
|
||||
"isOnroad": not parked, "gpuAvailable": gpu, "jetlink": jetlink,
|
||||
"capabilities": {"configureLaboratory": not job["downloading"], "select": True, "download": parked,
|
||||
"conditionalModel": parked and not job["downloading"] and not prefs["randomizer"],
|
||||
"downloadAll": parked, "cancel": True,
|
||||
"jetlink": parked, "refresh": parked, "favorites": True, "delete": parked, "randomizer": True, "exclusions": True}}
|
||||
|
||||
@@ -660,6 +670,8 @@ class ModelManager:
|
||||
if not isinstance(payload, dict):
|
||||
raise ModelError("Invalid model request")
|
||||
with self.lock:
|
||||
if action == "conditional_model":
|
||||
return self._configure_conditional_model(payload)
|
||||
if action == "jetlink":
|
||||
self._require_parked()
|
||||
return self.jetlink_owner().configure(payload)
|
||||
@@ -693,6 +705,8 @@ class ModelManager:
|
||||
raise ModelError("Invalid sort mode")
|
||||
with state_lock(self.root):
|
||||
saved = preferences(self.root)
|
||||
if payload.get("randomizer") is True and saved["conditionalModel"]["enabled"]:
|
||||
raise ModelError("Disable Conditional Model before enabling Model Randomizer")
|
||||
saved.update(payload)
|
||||
atomic_json(self.root / "preferences.json", saved)
|
||||
return {**self.snapshot(), "message": "Model preferences saved"}
|
||||
@@ -773,6 +787,8 @@ class ModelManager:
|
||||
if jetlink:
|
||||
self._require_parked()
|
||||
saved = preferences(self.root)
|
||||
if profile == "small" and saved["conditionalModel"]["enabled"]:
|
||||
raise ModelError("Choose a highway/city profile or disable profiles before choosing Active Small")
|
||||
if saved["randomizer"]:
|
||||
raise ModelError("Turn Model Randomizer off before choosing a model")
|
||||
job = self._read_job()
|
||||
@@ -795,7 +811,7 @@ class ModelManager:
|
||||
saved = preferences(self.root)
|
||||
if self._job_busy():
|
||||
raise ModelError("Wait for the model download to finish before deleting a model")
|
||||
if mid in (saved["small"], saved["big"]):
|
||||
if mid in (saved["small"], saved["big"], *(saved["conditionalModel"][role] for role in conditional_model.CONDITIONS)):
|
||||
raise ModelError("Select another model before deleting this one")
|
||||
self._require_parked()
|
||||
path.unlink(missing_ok=True)
|
||||
@@ -803,6 +819,31 @@ class ModelManager:
|
||||
return {"message": "Downloaded model deleted"}
|
||||
raise ModelError("Unknown model action")
|
||||
|
||||
def _configure_conditional_model(self, payload: dict) -> dict:
|
||||
self._require_parked()
|
||||
if not payload or set(payload) - set(conditional_model.defaults()):
|
||||
raise ModelError('Invalid Conditional Model configuration')
|
||||
with state_lock(self.root):
|
||||
saved = preferences(self.root)
|
||||
value = saved['conditionalModel'] | payload
|
||||
if not conditional_model.validate(value, model_entries(self.root)):
|
||||
raise ModelError('Choose local Small models and a speed from 10 to 100 mph')
|
||||
if saved['randomizer']:
|
||||
raise ModelError('Turn Model Randomizer off before configuring Conditional Model')
|
||||
if self._job_busy():
|
||||
raise ModelError('Wait for the model download to finish before configuring Conditional Model')
|
||||
entries = catalog(self.root)
|
||||
if value['enabled']:
|
||||
for mid in {value[name] for name in conditional_model.CONDITIONS}:
|
||||
if not self._installed(mid, entries):
|
||||
raise ModelError('Download and verify both Small models first')
|
||||
self._require_parked()
|
||||
saved['conditionalModel'] = value
|
||||
atomic_json(self.root / 'preferences.json', saved)
|
||||
logging.info('Conditional Model configured: enabled=%s city=%s highway=%s threshold_mph=%s',
|
||||
value['enabled'], value['city'], value['highway'], value['thresholdMph'])
|
||||
return {**self.snapshot(), 'message': 'Conditional Model saved for the next drive'}
|
||||
|
||||
def _refresh(self) -> None:
|
||||
url = f"{RESOURCE_URL}/manifests/model_names_{GENERATION}.json"
|
||||
with self.opener(url, timeout=30) as response:
|
||||
|
||||
@@ -23,7 +23,7 @@ MAX_RECEIPT_BYTES = 1024
|
||||
MAX_ARTIFACT_BYTES = 2 * 1024 * 1024 * 1024
|
||||
_PREFIX = re.compile(r"[A-Za-z0-9_-]{1,32}\Z")
|
||||
_DIGEST = re.compile(r"[0-9a-f]{64}\Z")
|
||||
_REASONS = {None, "chestnut-load-failed", "chestnut-run-stalled", "selected-load-failed"}
|
||||
_REASONS = {None, "chestnut-load-failed", "chestnut-run-stalled", "selected-load-failed", "conditional-switch-failed"}
|
||||
|
||||
|
||||
class ReceiptUnavailable(ValueError):
|
||||
|
||||
@@ -6,19 +6,24 @@ from multiprocessing import Process
|
||||
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.starpilot.models.receipt import process_start_ticks, read_receipt, read_pair_receipt
|
||||
from openpilot.starpilot.models.recovery import KILL_GRACE_NS, STARTUP_FALLBACK_EXIT, ModelRecoveryOwner, RecoveryEvidence
|
||||
from openpilot.starpilot.models.recovery import INT_GRACE_NS, KILL_GRACE_NS, STARTUP_FALLBACK_EXIT, ModelRecoveryOwner, RecoveryEvidence
|
||||
from openpilot.starpilot.models.conditional_protocol import PRELOAD_TIMEOUT_NS, SWITCH_TIMEOUT_NS, fresh
|
||||
from openpilot.starpilot.models.status import ModelVariant
|
||||
from openpilot.system.manager.process import PythonProcess, join_process, launcher
|
||||
|
||||
SMALL_ONLY_ENV = 'STARPILOT_MODELD_RECOVERY_SMALL_ONLY'
|
||||
|
||||
|
||||
def modeld_launcher(module, name, small_only):
|
||||
def modeld_launcher(module, name, small_only, recovery_model=None):
|
||||
# Set in this fresh child before importing modeld; never alter manager's env.
|
||||
if small_only:
|
||||
os.environ[SMALL_ONLY_ENV] = '1'
|
||||
else:
|
||||
os.environ.pop(SMALL_ONLY_ENV, None)
|
||||
if small_only and recovery_model is not None:
|
||||
os.environ['STARPILOT_CONDITIONAL_RECOVERY_MODEL'] = recovery_model
|
||||
else:
|
||||
os.environ.pop('STARPILOT_CONDITIONAL_RECOVERY_MODEL', None)
|
||||
launcher(module, name)
|
||||
|
||||
|
||||
@@ -28,6 +33,12 @@ class ModeldProcess(PythonProcess):
|
||||
self.recovery = ModelRecoveryOwner()
|
||||
self.context_ready = False
|
||||
self.launch_drive_id = 0
|
||||
self.launch_conditional = False
|
||||
self.launch_ns = 0
|
||||
self.launch_ticks = 0
|
||||
self.conditional_recovery_model = None
|
||||
self.last_conditional_cameras = ()
|
||||
self.launch_established = False
|
||||
|
||||
def observe(self, sm, started):
|
||||
now = time.monotonic_ns()
|
||||
@@ -35,8 +46,8 @@ class ModeldProcess(PythonProcess):
|
||||
pid = self.proc.pid if self.proc is not None else 0
|
||||
ticks = process_start_ticks(pid or 0) if alive else 0
|
||||
identity = (pid, ticks) if pid and ticks else None
|
||||
load = read_receipt() if alive else None
|
||||
pair = read_pair_receipt() if alive else None
|
||||
load = read_receipt() if self.proc is not None else None
|
||||
pair = read_pair_receipt() if self.proc is not None else None
|
||||
pair_matches = pair is not None and identity == (pair.pid, pair.process_start_ticks)
|
||||
matches = load is not None and identity == (load.pid, load.process_start_ticks)
|
||||
cameras = []
|
||||
@@ -53,11 +64,69 @@ class ModeldProcess(PythonProcess):
|
||||
device_fresh = (sm.seen['deviceState'] and sm.valid['deviceState'] and sm.alive['deviceState'] and
|
||||
0 < int(sm.logMonoTime['deviceState']) <= now <= int(sm.logMonoTime['deviceState']) + 1_000_000_000)
|
||||
self.context_ready = bool(device_fresh and started)
|
||||
conditional_identity = identity if alive else (pid, self.launch_ticks)
|
||||
established = bool((load is not None and conditional_identity == (load.pid, load.process_start_ticks)) or
|
||||
(pair is not None and conditional_identity == (pair.pid, pair.process_start_ticks)))
|
||||
self.launch_established |= established
|
||||
conditional_stalled = conditional_held = False
|
||||
try:
|
||||
conditional = sm['conditionalModelState']
|
||||
owned = (int(conditional.processPid), int(conditional.processStartTicks)) == conditional_identity
|
||||
if (owned and sm.seen['conditionalModelState'] and sm.valid['conditionalModelState'] and
|
||||
fresh(int(sm.logMonoTime['conditionalModelState']), now) and
|
||||
0 < int(conditional.sessionStartMonoTime) <= int(conditional.frameMonoTime) <= now and
|
||||
all(sm.valid[name] and fresh(int(sm.logMonoTime[name]), now) and
|
||||
int(conditional.frameMonoTime) <= int(sm.logMonoTime[name]) for name in ('modelV2', 'drivingModelData'))):
|
||||
self.launch_established = True
|
||||
ack = sm['conditionalModelAck']
|
||||
conditional_held = bool(sm.seen['conditionalModelState'] and sm.valid['conditionalModelState'] and
|
||||
owned and
|
||||
str(conditional.phase) in ('waiting', 'switching', 'recovering', 'ready') and bool(str(conditional.requestId)) and
|
||||
sm.seen['conditionalModelAck'] and sm.valid['conditionalModelAck'] and bool(ack.holding) and
|
||||
(str(ack.session), str(ack.requestId)) == (str(conditional.session), str(conditional.requestId)) and
|
||||
0 < int(conditional.sessionStartMonoTime) <= int(ack.stateMonoTime) <= int(sm.logMonoTime['conditionalModelState']) <= now and
|
||||
int(ack.stateMonoTime) <= int(sm.logMonoTime['conditionalModelAck']) and
|
||||
0 < int(sm.logMonoTime['conditionalModelAck']) <= now and now - int(sm.logMonoTime['conditionalModelAck']) <= 150_000_000)
|
||||
camera_progress = bool(cameras and len(cameras) == len(self.last_conditional_cameras) and
|
||||
all(t > old_t and frame > old_frame for (t, frame), (old_t, old_frame) in zip(cameras, self.last_conditional_cameras, strict=True)))
|
||||
conditional_stalled = bool(conditional_held and camera_progress and
|
||||
0 < int(conditional.sessionStartMonoTime) <= int(sm.logMonoTime['conditionalModelState']) <= now and
|
||||
now - max(int(sm.logMonoTime['modelV2']), int(sm.logMonoTime['drivingModelData'])) >= SWITCH_TIMEOUT_NS and
|
||||
all(0 < t <= now and now - t <= 200_000_000 for t, _ in cameras))
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
pass
|
||||
self.last_conditional_cameras = tuple(cameras) if conditional_held else ()
|
||||
if conditional_held:
|
||||
from openpilot.starpilot.models.catalog import model_entries
|
||||
mid = str(getattr(conditional, 'fallbackModel', ''))
|
||||
entries = model_entries()
|
||||
if mid in entries and not entries[mid].uses_external_gpu:
|
||||
self.conditional_recovery_model = mid
|
||||
else:
|
||||
conditional_stalled = conditional_held = False
|
||||
preload_stalled = (self.launch_conditional and not self.launch_established and
|
||||
self.launch_ns and now - self.launch_ns >= PRELOAD_TIMEOUT_NS)
|
||||
if self.context_ready and alive and self.recovery.phase == 'monitor' and (preload_stalled or conditional_stalled):
|
||||
# Preloading native models is synchronous. Timeout ownership stays in the
|
||||
# manager process; a Python/GPU loader is never cancelled in place.
|
||||
self.recovery.drive_id = evidence.drive_id
|
||||
self.recovery.identity = identity
|
||||
self.recovery.small_only = True
|
||||
self.recovery.phase = 'sigint'
|
||||
self.recovery.deadline_ns = now + INT_GRACE_NS
|
||||
try:
|
||||
self.signal(signal.SIGINT)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
cloudlog.error('Conditional Model %s timed out; requesting isolated single-model restart', 'handoff' if conditional_stalled else 'preload')
|
||||
return
|
||||
if (self.context_ready and self.proc is not None and not alive and not self.shutting_down and
|
||||
self.proc.exitcode == STARTUP_FALLBACK_EXIT and self.recovery.phase == 'monitor' and
|
||||
(self.proc.exitcode == STARTUP_FALLBACK_EXIT or
|
||||
self.launch_conditional and (not self.launch_established or conditional_held) and self.proc.exitcode not in (None, 0)) and
|
||||
self.recovery.phase == 'monitor' and
|
||||
not self.recovery.small_only and 0 < self.launch_drive_id == evidence.drive_id):
|
||||
# Only our explicitly failed startup may request this one fresh process.
|
||||
# Never reuse the old GPU context or retry an arbitrary Small crash.
|
||||
# An explicitly failed startup or an acknowledged held handoff may
|
||||
# request one fresh process. Never retry an arbitrary established Small crash.
|
||||
self.proc.join(timeout=0)
|
||||
self.proc = None
|
||||
self.recovery.drive_id = evidence.drive_id
|
||||
@@ -119,8 +188,17 @@ class ModeldProcess(PythonProcess):
|
||||
self.stop(block=False)
|
||||
if self.proc is not None:
|
||||
return
|
||||
if not self.recovery.small_only:
|
||||
self.conditional_recovery_model = None
|
||||
self.last_conditional_cameras = ()
|
||||
self.launch_established = False
|
||||
self.proc = Process(name=self.name, target=modeld_launcher,
|
||||
args=(self.module, self.name, self.recovery.small_only))
|
||||
args=(self.module, self.name, self.recovery.small_only),
|
||||
kwargs={'recovery_model': self.conditional_recovery_model} if self.recovery.small_only and self.conditional_recovery_model else {})
|
||||
self.launch_drive_id = self.recovery.drive_id
|
||||
from openpilot.starpilot.models.manager import preferences
|
||||
self.launch_conditional = not self.recovery.small_only and preferences()['conditionalModel']['enabled']
|
||||
self.launch_ns = time.monotonic_ns()
|
||||
self.proc.start()
|
||||
self.launch_ticks = process_start_ticks(self.proc.pid or 0)
|
||||
self.shutting_down = False
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
import resource
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
import weakref
|
||||
@@ -11,6 +13,7 @@ import numpy as np
|
||||
from tinygrad import Tensor, dtypes
|
||||
|
||||
from openpilot.cereal import log
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.selfdrive.controls.lib.drive_helpers import MIN_SPEED, smooth_value
|
||||
from openpilot.selfdrive.modeld.constants import ModelConstants, Plan
|
||||
from openpilot.selfdrive.modeld.helpers import load_oob
|
||||
@@ -51,18 +54,25 @@ def load_verified_model(cam_w: int, cam_h: int, artifact_path: Path, behavior_ve
|
||||
|
||||
if expected_sha256 is None:
|
||||
raise ValueError("selected catalog model has no verified digest")
|
||||
started = time.monotonic()
|
||||
with state_lock(ROOT if root is None else root):
|
||||
identity = artifact_identity(artifact_path)
|
||||
prepared = prepare_artifact(artifact_path, identity)
|
||||
if prepared.sha256 != expected_sha256:
|
||||
raise ValueError("selected catalog model changed before loading")
|
||||
verified_at = time.monotonic()
|
||||
model = CatalogModelState(cam_w, cam_h, artifact_path, behavior_version, chestnut)
|
||||
if coherent_warp is not None:
|
||||
model.move_warp_output(coherent_warp)
|
||||
loaded_at = time.monotonic()
|
||||
model.warmup()
|
||||
if artifact_identity(artifact_path) != identity:
|
||||
raise ValueError("selected catalog model changed while loading")
|
||||
model.model_id = model_id
|
||||
cloudlog.event("modeld.catalog_load", model_id=model_id, chestnut=chestnut,
|
||||
verify_seconds=verified_at - started, load_seconds=loaded_at - verified_at,
|
||||
warmup_seconds=time.monotonic() - loaded_at,
|
||||
process_peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
|
||||
return model, prepared
|
||||
|
||||
|
||||
@@ -241,6 +251,31 @@ class CatalogModelState:
|
||||
self._pending_frame: tuple | None = None
|
||||
self._last_shared_warp: SharedCameraWarp | None = None
|
||||
|
||||
def handoff_reset(self) -> Callable[[], None]:
|
||||
"""Prepare an in-place reset; captured JIT buffers must keep their addresses."""
|
||||
from tinygrad import Device
|
||||
queues = [q for name, q in self.input_queues.items() if q.device != 'NPY' and name != 'mapped_gpu_image']
|
||||
views = []
|
||||
for queue in queues:
|
||||
buffer = queue.uop.base.buffer
|
||||
if not buffer.is_allocated() or not hasattr(buffer.get_storage().host, 'mv'):
|
||||
raise ValueError('Small model history has no allocated host mapping')
|
||||
view = buffer.as_memoryview(allow_zero_copy=True)
|
||||
if view.readonly or view.nbytes != buffer.nbytes:
|
||||
raise ValueError('Small model history mapping is not writable or complete')
|
||||
views.append(np.frombuffer(view, dtype=np.uint8))
|
||||
devices = tuple(Device[name] for name in dict.fromkeys(q.device for q in queues))
|
||||
arrays = tuple(self.npy.values())
|
||||
def reset():
|
||||
for device in devices:
|
||||
device.synchronize()
|
||||
for view in views:
|
||||
view.fill(0)
|
||||
self.prev_desire.fill(0)
|
||||
for array in arrays:
|
||||
array.fill(0)
|
||||
return reset
|
||||
|
||||
def _validate_shared_warp(self, shared: SharedCameraWarp, pointers: tuple[int, int], transforms: tuple[bytes, bytes]) -> None:
|
||||
if (not isinstance(shared, SharedCameraWarp) or self.camera_warp_descriptor is None or
|
||||
shared.descriptor != self.camera_warp_descriptor):
|
||||
|
||||
@@ -11,7 +11,7 @@ from openpilot.starpilot.models.receipt import process_start_ticks, read_receipt
|
||||
from openpilot.starpilot.models.status import ModelLoad, ModelOutput, ModelProcess, ModelStatus, project_status, project_laboratory_status
|
||||
|
||||
|
||||
MODEL_SERVICES = ("managerState", "modelV2", "drivingModelData")
|
||||
MODEL_SERVICES = ("managerState", "modelV2", "drivingModelData", "conditionalModelState")
|
||||
|
||||
|
||||
def _stamp(sm: Any, service: str, now_mono_ns: int) -> tuple[int, bool]:
|
||||
@@ -80,7 +80,11 @@ class ModelStatusSource:
|
||||
self.sm.update(0)
|
||||
from openpilot.selfdrive.modeld.helpers import chestnut_present
|
||||
from openpilot.starpilot.models.manager import requested_runtime_id
|
||||
return snapshot(self.sm, self.params, self.clock(), requested_id=requested_runtime_id(chestnut_present()))
|
||||
requested = requested_runtime_id(chestnut_present())
|
||||
conditional = self.conditional_json()
|
||||
if conditional is not None and conditional['phase'] in ('ready', 'switching', 'recovering'):
|
||||
requested = conditional['activeModel']
|
||||
return snapshot(self.sm, self.params, self.clock(), requested_id=requested)
|
||||
|
||||
def json(self) -> dict[str, object]:
|
||||
status = self.snapshot()
|
||||
@@ -90,8 +94,30 @@ class ModelStatusSource:
|
||||
"variant": status.variant.value if status.variant is not None else None,
|
||||
"health": status.health.value, "fallbackReason": status.fallback_reason,
|
||||
"artifactSha256": status.artifact_sha256, "pendingNextStart": status.pending_next_start,
|
||||
"conditionalModelState": self.conditional_json(),
|
||||
"laboratory": self.laboratory_json(self.laboratory_configuration())}
|
||||
|
||||
def conditional_json(self) -> dict | None:
|
||||
now = self.clock()
|
||||
process = _process(self.sm, now, process_start_ticks)
|
||||
if process is None or not _stamp(self.sm, 'conditionalModelState', now)[1]:
|
||||
return None
|
||||
try:
|
||||
state = self.sm['conditionalModelState']
|
||||
if (int(state.processPid), int(state.processStartTicks)) != (process.pid, process.start_ticks):
|
||||
return None
|
||||
fresh_output = bool(0 < int(state.sessionStartMonoTime) <= int(state.frameMonoTime) <= now and
|
||||
all(_stamp(self.sm, name, now)[1] and int(state.frameMonoTime) <= self.sm.logMonoTime[name]
|
||||
for name in ('modelV2', 'drivingModelData')))
|
||||
return {'session': str(state.session), 'requestId': str(state.requestId), 'phase': str(state.phase),
|
||||
'activeModel': str(state.activeModel), 'highwayModel': str(state.highwayModel), 'cityModel': str(state.cityModel),
|
||||
'error': str(state.error), 'canSwitch': bool(fresh_output and state.canSwitch),
|
||||
'paused': bool(state.paused), 'targetMode': str(state.targetMode),
|
||||
'thresholdMph': int(state.thresholdMph), 'unavailableReason': str(state.unavailableReason),
|
||||
'transitionSeconds': float(state.transitionSeconds)}
|
||||
except (AttributeError, KeyError, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def laboratory_configuration() -> dict:
|
||||
from openpilot.starpilot.models.laboratory import configuration
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.selfdrive.selfdrived.alertmanager import AlertManager
|
||||
from openpilot.selfdrive.selfdrived.events import AlertStatus, AlertSize, Priority, VisualAlert, AudibleAlert, Alert
|
||||
from openpilot.starpilot.models.conditional_alerts import conditional_model_alert, ALERT_TYPES
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelGate
|
||||
|
||||
|
||||
@pytest.mark.parametrize('phase', ['waiting', 'switching', 'recovering'])
|
||||
def test_banner_describes_handoff_even_without_engagement_attempt(phase):
|
||||
alert = conditional_model_alert(NS(phase=phase, error=''), holding=True)
|
||||
assert alert.alert_text_1 == 'Switching conditional models'
|
||||
assert alert.alert_size == AlertSize.small
|
||||
assert alert.priority == Priority.LOWEST and alert.audible_alert == AudibleAlert.none
|
||||
|
||||
|
||||
def test_errors_and_stalls_are_visible_but_never_claim_ready():
|
||||
error = conditional_model_alert(NS(phase='ready', error='Candidate inference failed; previous model restored'), holding=False)
|
||||
assert error.alert_text_1 == 'Conditional Model unavailable'
|
||||
assert 'previous model restored' in error.alert_text_2
|
||||
stalled = conditional_model_alert(None, holding=True, stalled=True)
|
||||
assert stalled.alert_text_1 == 'Conditional model switch stalled'
|
||||
assert 'Engagement blocked' in stalled.alert_text_2
|
||||
assert conditional_model_alert(None, holding=False) is None
|
||||
assert conditional_model_alert(NS(phase='ready', error=''), holding=False) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('priority', [Priority.LOWEST, Priority.LOW, Priority.HIGHEST])
|
||||
def test_road_notice_does_not_replace_equal_or_higher_priority_vehicle_alert(priority):
|
||||
gate = ConditionalModelGate.__new__(ConditionalModelGate)
|
||||
gate.alert = Mock(return_value=conditional_model_alert(None, holding=True))
|
||||
native = Alert('TAKE CONTROL', '', AlertStatus.critical, AlertSize.full, priority, VisualAlert.steerRequired, AudibleAlert.warningImmediate, 1.)
|
||||
alerts, manager = [native], AlertManager()
|
||||
manager.alerts.update({key: object() for key in ALERT_TYPES})
|
||||
gate.update_alerts(alerts, manager)
|
||||
assert alerts == [native] and not manager.alerts
|
||||
manager.add_many(0, alerts)
|
||||
manager.process_alerts(0, set())
|
||||
assert manager.current_alert is native
|
||||
|
||||
|
||||
def test_completion_removes_only_conditional_model_notices():
|
||||
gate = ConditionalModelGate.__new__(ConditionalModelGate)
|
||||
gate.alert = Mock(return_value=None)
|
||||
manager = NS(alerts={ALERT_TYPES[0]: object(), 'vehicle-alert': object()})
|
||||
alerts = []
|
||||
gate.update_alerts(alerts, manager)
|
||||
assert not alerts and set(manager.alerts) == {'vehicle-alert'}
|
||||
|
||||
|
||||
def test_retained_native_alert_remains_visible_without_road_banner():
|
||||
gate = ConditionalModelGate.__new__(ConditionalModelGate)
|
||||
gate.alert = Mock(return_value=conditional_model_alert(None, holding=True))
|
||||
manager = AlertManager()
|
||||
native = Alert('Vehicle warning', '', AlertStatus.userPrompt, AlertSize.mid, Priority.LOW,
|
||||
VisualAlert.none, AudibleAlert.none, 1.)
|
||||
native.alert_type = 'native/warning'
|
||||
manager.add_many(0, [native])
|
||||
alerts = []
|
||||
gate.update_alerts(alerts, manager, frame=1)
|
||||
assert not alerts and 'native/warning' in manager.alerts
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Speed classification is deterministic and independent of inference/control."""
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.starpilot.models.conditional_policy import SpeedPolicy, MPH_TO_MS
|
||||
|
||||
BASE = 100_000_000_000
|
||||
|
||||
|
||||
def sample(policy, mph, t=0., *, current='highway', **kwargs):
|
||||
now = BASE + round(t * 1e9)
|
||||
return policy.sample(mph * MPH_TO_MS, kwargs.pop('stamp', now), now, current=current, valid=kwargs.pop('valid', True), **kwargs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mph,role', [(0, None), (45, None), (49, None), (49.99, None), (50, 'highway'), (54.99, 'highway'), (55, 'highway'), (60, 'highway')])
|
||||
def test_highway_entry_is_immediate_at_configured_speed(mph, role):
|
||||
assert sample(SpeedPolicy(), mph, current='city') == role
|
||||
|
||||
|
||||
def test_city_requires_thirty_continuous_seconds_and_deadband_resets_clock():
|
||||
policy = SpeedPolicy()
|
||||
for i in range(600):
|
||||
assert sample(policy, 45, i * .05) is None
|
||||
assert sample(policy, 45, 30.) == 'city'
|
||||
assert sample(policy, 46, 30.05) is None
|
||||
assert policy.low_since is None
|
||||
assert sample(policy, 45, 30.1) is None
|
||||
|
||||
|
||||
def test_oscillation_near_threshold_does_not_flap():
|
||||
policy = SpeedPolicy()
|
||||
current, changes = 'city', []
|
||||
for i in range(2400):
|
||||
role = sample(policy, 45 if i % 2 else 55, i * .05, current=current)
|
||||
if role:
|
||||
current = role
|
||||
changes.append(role)
|
||||
policy.switched(BASE + round(i * .05 * 1e9))
|
||||
assert changes == ['highway']
|
||||
|
||||
|
||||
def test_highway_merge_bypasses_city_cooldown_and_return_requires_another_dwell():
|
||||
policy = SpeedPolicy()
|
||||
policy.switched(BASE)
|
||||
assert sample(policy, 60, .05, current='city') == 'highway'
|
||||
policy.switched(BASE + 50_000_000)
|
||||
for i in range(1, 601):
|
||||
assert sample(policy, 40, .05 + i * .05) is None
|
||||
assert sample(policy, 40, 30.1) == 'city'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', [math.nan, math.inf, -math.inf, -1., 101., True, None, '60'])
|
||||
def test_invalid_speed_breaks_city_dwell(bad):
|
||||
policy = SpeedPolicy()
|
||||
sample(policy, 40)
|
||||
assert policy.sample(bad, BASE + 50_000_000, BASE + 50_000_000, valid=True, current='highway') is None
|
||||
assert policy.low_since is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', [{'stamp': 0}, {'stamp': BASE + 1_000_000_000}, {'stamp': BASE - 1}, {'valid': False}])
|
||||
def test_bad_or_reordered_sources_cannot_advance_dwell(change):
|
||||
policy = SpeedPolicy()
|
||||
sample(policy, 40)
|
||||
assert sample(policy, 40, .05, **change) is None
|
||||
assert policy.low_since is None
|
||||
|
||||
|
||||
def test_sampling_gap_requires_new_full_dwell():
|
||||
policy = SpeedPolicy()
|
||||
sample(policy, 40)
|
||||
assert sample(policy, 40, 31.) is None
|
||||
assert policy.low_since == BASE + 31_000_000_000
|
||||
|
||||
|
||||
@pytest.mark.parametrize('threshold', [True, 50., 9, 101, math.nan])
|
||||
def test_invalid_policy_settings_are_rejected(threshold):
|
||||
with pytest.raises(ValueError):
|
||||
SpeedPolicy(threshold)
|
||||
|
||||
|
||||
def test_user_speed_is_the_actual_highway_trigger_with_internal_return_delay():
|
||||
policy = SpeedPolicy(60)
|
||||
assert sample(policy, 59.99, current='city') is None
|
||||
assert sample(policy, 60, .05, current='city') == 'highway'
|
||||
for i in range(601):
|
||||
result = sample(policy, 55, .1 + i * .05)
|
||||
assert result == ('city' if i == 600 else None)
|
||||
@@ -0,0 +1,493 @@
|
||||
"""Protocol and owner tests; these do not qualify device memory or latency."""
|
||||
from types import SimpleNamespace as NS
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from openpilot.starpilot.models.conditional_protocol import (
|
||||
ACK_TIMEOUT_NS, SETTLE_FRAMES, SWITCH_TIMEOUT_NS, Ack, EngagementHold, ResidentSwitch, State,
|
||||
)
|
||||
from openpilot.starpilot.models.conditional_runtime import modeld_idle
|
||||
|
||||
BASE = 10_000_000_000
|
||||
|
||||
|
||||
def switcher():
|
||||
models = {name: (NS(model_id=name), name + '-receipt', Mock()) for name in ('highway', 'city')}
|
||||
owner = ResidentSwitch(models, 'highway', now=BASE)
|
||||
request = {'session': owner.session, 'id': 'a' * 32, 'model': 'city'}
|
||||
return owner, request
|
||||
|
||||
|
||||
def begin(owner, request):
|
||||
assert not owner.before_frame(request, now=BASE, idle=True, ack=None)
|
||||
assert owner.phase == 'waiting'
|
||||
owner.announced = BASE
|
||||
ack = Ack(owner.session, request['id'], True, BASE, BASE + 10_000_000)
|
||||
assert owner.before_frame(request, now=BASE + 20_000_000, idle=True, ack=ack)
|
||||
assert owner.active == 'city'
|
||||
|
||||
|
||||
def test_resident_swap_changes_only_after_matching_fresh_hold_and_keeps_separate_state():
|
||||
owner, request = switcher()
|
||||
begin(owner, request)
|
||||
owner.models['city'][2].assert_called_once()
|
||||
owner.models['highway'][2].assert_not_called()
|
||||
for i in range(SETTLE_FRAMES):
|
||||
owner.published(BASE + (i + 1) * 50_000_000, BASE + (i + 1) * 50_000_000)
|
||||
assert owner.phase == ('ready' if i == SETTLE_FRAMES - 1 else 'switching')
|
||||
assert owner.elapsed == .25
|
||||
assert not owner.before_frame(request, now=BASE + 300_000_000, idle=True, ack=None)
|
||||
# Returning to Highway resets its own original buffers, never City's state.
|
||||
request = request | {'id': 'b' * 32, 'model': 'highway'}
|
||||
assert not owner.before_frame(request, now=BASE + 300_000_000, idle=True, ack=None)
|
||||
owner.announced = BASE + 300_000_000
|
||||
assert owner.before_frame(request, now=BASE + 320_000_000, idle=True,
|
||||
ack=Ack(owner.session, request['id'], True, owner.announced, BASE + 310_000_000))
|
||||
owner.models['highway'][2].assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', [{'session': 'old'}, {'request': 'old'}, {'holding': False},
|
||||
{'source': BASE - 1}, {'stamp': BASE - 200_000_000}, {'stamp': BASE + 999_000_000}])
|
||||
def test_bad_ack_never_changes_runner(change):
|
||||
owner, request = switcher()
|
||||
owner.before_frame(request, now=BASE, idle=True, ack=None)
|
||||
owner.announced = BASE
|
||||
values = {'session': owner.session, 'request': request['id'], 'holding': True, 'source': BASE, 'stamp': BASE + 10_000_000}
|
||||
assert not owner.before_frame(request, now=BASE + 20_000_000, idle=True, ack=Ack(**(values | change)))
|
||||
assert owner.active == 'highway'
|
||||
owner.models['city'][2].assert_not_called()
|
||||
|
||||
|
||||
def test_engaged_request_denied_and_engagement_race_cancels_before_reset():
|
||||
owner, request = switcher()
|
||||
assert not owner.before_frame(request, now=BASE, idle=False, ack=None)
|
||||
assert owner.phase == 'ready' and owner.error
|
||||
request['id'] = 'b' * 32
|
||||
owner.before_frame(request, now=BASE, idle=True, ack=None)
|
||||
owner.announced = BASE
|
||||
assert not owner.before_frame(request, now=BASE + 10_000_000, idle=False,
|
||||
ack=Ack(owner.session, request['id'], True, BASE, BASE + 5_000_000))
|
||||
assert owner.active == 'highway' and not owner.error
|
||||
owner.models['city'][2].assert_not_called()
|
||||
|
||||
|
||||
def test_ack_timeout_consumes_request_token_and_retains_current_model():
|
||||
owner, request = switcher()
|
||||
owner.before_frame(request, now=BASE, idle=True, ack=None)
|
||||
owner.before_frame(request, now=BASE + ACK_TIMEOUT_NS, idle=True, ack=None)
|
||||
assert owner.active == 'highway' and owner.phase == 'ready' and 'timed out' in owner.error
|
||||
owner.before_frame(request, now=BASE + ACK_TIMEOUT_NS + 1, idle=True, ack=None)
|
||||
assert owner.phase == 'ready'
|
||||
|
||||
|
||||
def test_reset_failure_and_inference_failure_restore_previous_without_reloading():
|
||||
owner, request = switcher()
|
||||
owner.models['city'][2].side_effect = RuntimeError('mapping unavailable')
|
||||
owner.before_frame(request, now=BASE, idle=True, ack=None)
|
||||
owner.announced = BASE
|
||||
assert not owner.before_frame(request, now=BASE + 20_000_000, idle=True,
|
||||
ack=Ack(owner.session, request['id'], True, BASE, BASE + 10_000_000))
|
||||
assert owner.active == 'highway' and 'reset failed' in owner.error
|
||||
owner, request = switcher()
|
||||
begin(owner, request)
|
||||
owner.abort('Candidate inference failed', BASE + 40_000_000)
|
||||
assert owner.active == 'highway' and owner.phase == 'recovering'
|
||||
owner.models['highway'][2].assert_called_once()
|
||||
for i in range(SETTLE_FRAMES):
|
||||
owner.published(BASE + (i + 1) * 50_000_000, BASE + (i + 1) * 50_000_000)
|
||||
assert owner.phase == 'ready' and owner.error == 'Candidate inference failed'
|
||||
|
||||
|
||||
def test_handoff_timeout_rolls_back_but_unknown_engagement_keeps_hold():
|
||||
owner, request = switcher()
|
||||
begin(owner, request)
|
||||
assert not owner.before_frame(request, now=BASE + SWITCH_TIMEOUT_NS, idle=False, ack=None)
|
||||
for i in range(SETTLE_FRAMES + 1):
|
||||
owner.published(BASE + SWITCH_TIMEOUT_NS + i, BASE + SWITCH_TIMEOUT_NS + i)
|
||||
assert owner.phase == 'switching' and owner.active == 'city'
|
||||
assert owner.before_frame(request, now=BASE + SWITCH_TIMEOUT_NS + 100, idle=True, ack=None)
|
||||
assert owner.active == 'highway' and owner.phase == 'recovering'
|
||||
|
||||
|
||||
def test_wrong_session_and_nonresident_model_are_never_loaded():
|
||||
owner, request = switcher()
|
||||
assert not owner.before_frame(request | {'session': 'prior-drive'}, now=BASE, idle=True, ack=None)
|
||||
assert owner.request == ''
|
||||
assert not owner.before_frame(request | {'model': 'unloaded'}, now=BASE, idle=True, ack=None)
|
||||
assert owner.active == 'highway' and owner.error
|
||||
|
||||
|
||||
def test_engagement_hold_blocks_reengagement_until_post_handoff_output():
|
||||
hold = EngagementHold()
|
||||
waiting = State('session', 'request', 'waiting', BASE - 1, BASE - 100)
|
||||
assert hold.step(waiting, BASE, BASE, idle=True, model_stamp=BASE - 1, model_valid=True)
|
||||
assert hold.step(None, 0, BASE + 9_000_000_000, idle=True, model_stamp=0, model_valid=False)
|
||||
ready = State('session', 'request', 'ready', BASE + 50_000_000, BASE - 100)
|
||||
assert hold.step(ready, BASE + 60_000_000, BASE + 60_000_000, idle=True, model_stamp=BASE, model_valid=True)
|
||||
assert not hold.step(ready, BASE + 70_000_000, BASE + 70_000_000, idle=True, model_stamp=BASE + 50_000_000, model_valid=True)
|
||||
|
||||
|
||||
def test_hold_denies_engaged_and_stale_states_and_requires_new_publisher_after_restart():
|
||||
hold = EngagementHold()
|
||||
waiting = State('session', 'request', 'waiting', 0, BASE)
|
||||
assert not hold.step(waiting, BASE, BASE, idle=False, model_stamp=BASE, model_valid=True)
|
||||
assert not hold.step(waiting, BASE, BASE + 200_000_000, idle=True, model_stamp=BASE, model_valid=True)
|
||||
assert hold.step(waiting, BASE + 210_000_000, BASE + 210_000_000, idle=True, model_stamp=BASE, model_valid=True)
|
||||
restarted = State('new-process', '', 'disabled', BASE + 300_000_000, BASE + 250_000_000)
|
||||
assert hold.step(restarted, BASE + 310_000_000, BASE + 310_000_000, idle=True, model_stamp=BASE + 220_000_000, model_valid=True)
|
||||
assert not hold.step(restarted, BASE + 320_000_000, BASE + 320_000_000, idle=True,
|
||||
model_stamp=BASE + 300_000_000, model_valid=True)
|
||||
|
||||
|
||||
class Feed(dict):
|
||||
def __init__(self):
|
||||
super().__init__(selfdriveState=NS(enabled=False, active=False, state='disabled'),
|
||||
carControl=NS(enabled=False, latActive=False, longActive=False),
|
||||
carState=NS(cruiseState=NS(enabled=False), canValid=True, canTimeout=False, vEgo=0.))
|
||||
self.seen = self.valid = self.alive = dict.fromkeys(self, True)
|
||||
self.logMonoTime = dict.fromkeys(self, BASE)
|
||||
|
||||
|
||||
def test_disengagement_evidence_must_be_fresh_and_include_both_axes_and_stock_cruise():
|
||||
sm = Feed()
|
||||
assert modeld_idle(sm, BASE)
|
||||
for service, field in (('carControl', 'latActive'), ('carControl', 'longActive'), ('selfdriveState', 'enabled')):
|
||||
setattr(sm[service], field, True)
|
||||
assert not modeld_idle(sm, BASE)
|
||||
setattr(sm[service], field, False)
|
||||
sm['carState'].cruiseState.enabled = True
|
||||
assert not modeld_idle(sm, BASE)
|
||||
sm['carState'].cruiseState.enabled = False
|
||||
assert not modeld_idle(sm, BASE + 200_000_000)
|
||||
sm['selfdriveState'].state = 'preEnabled'
|
||||
assert not modeld_idle(sm, BASE)
|
||||
|
||||
|
||||
def test_live_handshake_over_real_typed_ipc_has_valid_state_and_ack():
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.selfdrive.selfdrived.state import StateMachine
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelRuntime, ConditionalModelGate
|
||||
|
||||
messaging.set_fake_prefix('conditional_runtime_' + uuid.uuid4().hex)
|
||||
gate = ConditionalModelGate()
|
||||
publisher = messaging.PubMaster(['conditionalModelState'])
|
||||
acknowledgments = messaging.SubMaster(['conditionalModelAck'])
|
||||
now = time.monotonic_ns()
|
||||
modes = ConditionalModelRuntime.__new__(ConditionalModelRuntime)
|
||||
modes.owner = ResidentSwitch({'highway': ()}, 'highway', now=now)
|
||||
modes.owner.phase, modes.owner.request = 'waiting', uuid.uuid4().hex
|
||||
modes.pid, modes.ticks = os.getpid(), 1
|
||||
modes.config = {'highway': 'highway', 'city': 'city', 'thresholdMph': 50}
|
||||
from openpilot.starpilot.models.conditional_policy import SpeedPolicy
|
||||
modes.paused, modes.policy, modes.unavailable_reason = False, SpeedPolicy(), ''
|
||||
modes.ack = NS(seen={'conditionalModelAck': False})
|
||||
sm = Feed()
|
||||
sm.logMonoTime = dict.fromkeys(sm, now)
|
||||
drive = NS(initialized=True, conditional_car_state_valid=True, enabled=False, active=False,
|
||||
state_machine=StateMachine(), aol_replay=False, aol_axis_decision=None,
|
||||
sm=NS(valid={'modelV2': True}, alive={'modelV2': True}, logMonoTime={'modelV2': now}), events=None)
|
||||
car = NS(canValid=True, canTimeout=False, cruiseState=NS(enabled=False))
|
||||
time.sleep(.05)
|
||||
# A subscriber started before its publisher may need another frame to attach
|
||||
# to the publisher generation. Production publishes continuously at 20 Hz.
|
||||
for _ in range(3):
|
||||
modes.publish(publisher, sm, 0)
|
||||
gate.sm.update(20)
|
||||
if gate.sm.seen['conditionalModelState']:
|
||||
break
|
||||
assert gate.sm.seen['conditionalModelState'] and gate.sm.valid['conditionalModelState']
|
||||
assert gate.step(drive, car)
|
||||
acknowledgments.update(100)
|
||||
assert acknowledgments.valid['conditionalModelAck']
|
||||
ack = acknowledgments['conditionalModelAck']
|
||||
assert ack.holding and ack.idle and ack.session == modes.owner.session
|
||||
assert ack.requestId == modes.owner.request and ack.stateMonoTime >= modes.owner.announced
|
||||
assert gate.alert().alert_text_1 == 'Switching conditional models'
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=gate.hold.held_since + SWITCH_TIMEOUT_NS + 1):
|
||||
assert gate.alert().alert_text_1 == 'Conditional model switch stalled'
|
||||
# Only a fresh ready boundary and output from this publisher can release it.
|
||||
modes.owner.phase = 'ready'
|
||||
frame = time.monotonic_ns()
|
||||
drive.sm.logMonoTime['modelV2'] = frame
|
||||
modes.publish(publisher, sm, frame)
|
||||
gate.sm.update(100)
|
||||
assert not gate.step(drive, car)
|
||||
assert gate.alert() is None
|
||||
|
||||
|
||||
def test_real_selfdrive_hold_ack_blocks_enable_and_both_axes_until_new_output():
|
||||
import ast
|
||||
from pathlib import Path
|
||||
from openpilot.cereal import messaging
|
||||
from openpilot.selfdrive.selfdrived.events import Events, EventName
|
||||
from openpilot.selfdrive.selfdrived.state import StateMachine
|
||||
from openpilot.starpilot.aol.runtime import AxisDecision
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelGate
|
||||
|
||||
message = messaging.new_message('conditionalModelState')
|
||||
message.conditionalModelState = {'session': 'a' * 32, 'requestId': 'b' * 32, 'phase': 'waiting', 'sessionStartMonoTime': BASE - 100}
|
||||
class Subscriber:
|
||||
seen = valid = alive = {'conditionalModelState': True}
|
||||
logMonoTime = {'conditionalModelState': BASE}
|
||||
def update(self, _):
|
||||
pass
|
||||
def __getitem__(self, _):
|
||||
return message.conditionalModelState
|
||||
gate = ConditionalModelGate.__new__(ConditionalModelGate)
|
||||
gate.sm, gate.pm, gate.hold = Subscriber(), Mock(), EngagementHold()
|
||||
sm = NS(valid={'modelV2': True}, alive={'modelV2': True}, logMonoTime={'modelV2': BASE - 1})
|
||||
car = NS(canValid=True, canTimeout=False, cruiseState=NS(enabled=False))
|
||||
drive = NS(initialized=True, conditional_car_state_valid=True, enabled=False, active=False,
|
||||
state_machine=StateMachine(), aol_replay=False, aol_axis_decision=AxisDecision(),
|
||||
sm=sm, conditional_model_gate=gate, events=Events(), CP=NS(passive=False))
|
||||
# Execute the production step's hold admission, state-machine update, and
|
||||
# final axis override. An ENABLE in the exact acknowledgment tick must lose.
|
||||
source = Path(__file__).resolve().parents[3] / 'selfdrive/selfdrived/selfdrived.py'
|
||||
tree = ast.parse(source.read_text())
|
||||
step = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == 'step')
|
||||
start = next(i for i, n in enumerate(step.body) if isinstance(n, ast.Assign) and ast.unparse(n.targets[0]) == 'conditional_gate')
|
||||
admission = step.body[start:start + 3]
|
||||
update = next(n for n in step.body if isinstance(n, ast.If) and ast.unparse(n.test) == 'not self.CP.passive and self.initialized')
|
||||
override = [n for n in step.body if isinstance(n, ast.If) and ast.unparse(n.test) == 'conditional_hold'][-1]
|
||||
env = {'self': drive, 'CS': car, 'EventName': EventName, 'AxisDecision': AxisDecision}
|
||||
drive.events.add(EventName.buttonEnable)
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE + 10):
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[*admission, update], type_ignores=[])), str(source), 'exec'), env)
|
||||
assert not drive.enabled and not drive.active
|
||||
ack = gate.pm.send.call_args.args[1].conditionalModelAck
|
||||
assert ack.holding and ack.session == 'a' * 32 and ack.requestId == 'b' * 32
|
||||
drive.aol_axis_decision = AxisDecision(desired_lateral=True, lateral_active=True, desired_longitudinal=True, longitudinal_active=True)
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[override], type_ignores=[])), str(source), 'exec'), env)
|
||||
assert drive.aol_axis_decision == AxisDecision()
|
||||
message.conditionalModelState.phase = 'ready'
|
||||
message.conditionalModelState.frameMonoTime = BASE + 20
|
||||
gate.sm.logMonoTime['conditionalModelState'] = BASE + 30
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE + 40):
|
||||
assert gate.step(drive, car) # previous model output cannot clear the hold
|
||||
sm.logMonoTime['modelV2'] = BASE + 20
|
||||
assert gate.step(drive, car) # do not carry an Enable attempt through the hold
|
||||
drive.events.clear()
|
||||
assert not gate.step(drive, car)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('armed,active', [(True, False), (False, True)])
|
||||
def test_independent_lateral_intent_or_axis_refuses_hold(armed, active):
|
||||
from openpilot.cereal import log, messaging
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelGate
|
||||
message = messaging.new_message('conditionalModelState')
|
||||
message.conditionalModelState = {'session': 'a' * 32, 'requestId': 'b' * 32, 'phase': 'waiting', 'sessionStartMonoTime': BASE - 100}
|
||||
class Subscriber:
|
||||
seen = valid = alive = {'conditionalModelState': True}
|
||||
logMonoTime = {'conditionalModelState': BASE}
|
||||
def update(self, _):
|
||||
pass
|
||||
def __getitem__(self, _):
|
||||
return message.conditionalModelState
|
||||
gate = ConditionalModelGate.__new__(ConditionalModelGate)
|
||||
gate.sm, gate.pm, gate.hold = Subscriber(), Mock(), EngagementHold()
|
||||
drive = NS(initialized=True, conditional_car_state_valid=True, enabled=False, active=False,
|
||||
state_machine=NS(state=log.SelfdriveState.OpenpilotState.disabled), aol_replay=True, aol_car_state_log_ns=BASE,
|
||||
aol_axis_decision=NS(lateral_active=active),
|
||||
sm=NS(valid={'modelV2': True}, alive={'modelV2': True}, logMonoTime={'modelV2': BASE}))
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE + 10), \
|
||||
patch('openpilot.starpilot.aol.runtime.current_intent', return_value=NS(allowedLatch=armed, lateralArmed=armed)):
|
||||
assert not gate.step(drive, NS(canValid=True, canTimeout=False, cruiseState=NS(enabled=False)))
|
||||
assert not gate.pm.send.call_args.args[1].conditionalModelAck.holding
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', [None, 'load', 'memory', 'missing', 'mapping'])
|
||||
def test_startup_preloads_alternate_once_or_retains_initial_runner(tmp_path, failure):
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelRuntime
|
||||
first_reset, other_reset = Mock(), Mock()
|
||||
first = NS(model_id='cheddar', handoff_reset=Mock(return_value=first_reset))
|
||||
other = NS(model_id='gwm8223', handoff_reset=Mock(return_value=other_reset))
|
||||
if failure == 'mapping':
|
||||
other.handoff_reset.side_effect = ValueError('unmapped history')
|
||||
artifact = tmp_path / 'alternate.pkl'
|
||||
artifact.write_bytes(b'fixture')
|
||||
config = {'enabled': True, 'city': 'cheddar', 'highway': 'gwm8223', 'thresholdMph': 50}
|
||||
entries = {'gwm8223': {'version': 'v15', 'artifact_sha256': 'a' * 64}}
|
||||
with patch('openpilot.cereal.messaging.SubMaster'), \
|
||||
patch('openpilot.starpilot.models.manager.catalog', return_value=entries), \
|
||||
patch('openpilot.starpilot.models.manager.verified_artifact', return_value=None if failure == 'missing' else artifact), \
|
||||
patch('openpilot.starpilot.models.runner.load_verified_model', return_value=(other, 'other-receipt')) as load, \
|
||||
patch('pathlib.Path.read_text', return_value='MemAvailable: 1 kB' if failure == 'memory' else 'MemAvailable: 9000000 kB'):
|
||||
if failure == 'load':
|
||||
load.side_effect = RuntimeError('native loading failed')
|
||||
runtime = ConditionalModelRuntime(first, 'first-receipt', config, root=tmp_path, cam_w=1928, cam_h=1208, enabled=True)
|
||||
assert runtime.owner.active == 'cheddar'
|
||||
first_reset.assert_not_called()
|
||||
other_reset.assert_not_called()
|
||||
if failure is None:
|
||||
assert runtime.owner.models['cheddar'] == (first, 'first-receipt', first_reset)
|
||||
assert runtime.owner.models['gwm8223'] == (other, 'other-receipt', other_reset)
|
||||
load.assert_called_once()
|
||||
else:
|
||||
assert not runtime.owner.models and runtime.owner.error
|
||||
|
||||
|
||||
@pytest.mark.parametrize('configured', [False, True])
|
||||
def test_expected_external_precedence_or_disabled_feature_is_not_a_driver_fault(tmp_path, configured):
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelRuntime
|
||||
from openpilot.starpilot.models.conditional_alerts import conditional_model_alert
|
||||
config = {'enabled': configured, 'city': 'cheddar', 'highway': 'gwm8223', 'thresholdMph': 50}
|
||||
with patch('openpilot.cereal.messaging.SubMaster'):
|
||||
runtime = ConditionalModelRuntime(NS(model_id='cheddar'), None, config,
|
||||
root=tmp_path, cam_w=1928, cam_h=1208, enabled=False)
|
||||
assert runtime.owner.phase == 'disabled' and not runtime.owner.error
|
||||
assert bool(runtime.unavailable_reason) == configured
|
||||
assert conditional_model_alert(NS(phase=runtime.owner.phase, error=runtime.owner.error), holding=False) is None
|
||||
|
||||
|
||||
def test_stale_or_armed_completion_does_not_release_hold():
|
||||
hold = EngagementHold()
|
||||
waiting = State('session', 'request', 'waiting', 0, BASE - 100)
|
||||
assert hold.step(waiting, BASE, BASE, idle=True, model_stamp=BASE, model_valid=True)
|
||||
ready = State('session', 'request', 'ready', BASE + 10, BASE - 100)
|
||||
assert hold.step(ready, BASE + 20, BASE + 20, idle=False, model_stamp=BASE + 10, model_valid=True)
|
||||
assert hold.step(ready, BASE + 30, BASE + 30, idle=True, model_stamp=BASE + 10, model_valid=True, release_allowed=False)
|
||||
assert not hold.step(ready, BASE + 40, BASE + 40, idle=True, model_stamp=BASE + 10, model_valid=True)
|
||||
|
||||
|
||||
def test_fresh_status_cannot_restart_the_hold_duration_clock():
|
||||
hold = EngagementHold()
|
||||
state = State('session', 'request', 'recovering', 0, BASE - 1)
|
||||
for i in range(50):
|
||||
now = BASE + i * 50_000_000
|
||||
assert hold.step(state, now, now, idle=True, model_stamp=now, model_valid=False)
|
||||
assert hold.held_since == BASE
|
||||
assert hold.last_stamp > hold.held_since + SWITCH_TIMEOUT_NS
|
||||
|
||||
|
||||
def conditional_runtime_fixture():
|
||||
from openpilot.starpilot.models.conditional_policy import SpeedPolicy
|
||||
from openpilot.starpilot.models.conditional_runtime import ConditionalModelRuntime
|
||||
owner, _ = switcher()
|
||||
owner.active = owner.previous = 'city'
|
||||
owner.frame = BASE
|
||||
modes = ConditionalModelRuntime.__new__(ConditionalModelRuntime)
|
||||
modes.owner, modes.policy = owner, SpeedPolicy()
|
||||
modes.paused, modes.last_status = False, None
|
||||
modes.config = {'highway': 'highway', 'city': 'city', 'thresholdMph': 50}
|
||||
class AckFeed(dict):
|
||||
def update(self, _):
|
||||
pass
|
||||
modes.ack = AckFeed(conditionalModelAck=NS(session=owner.session, requestId='', holding=False, stateMonoTime=BASE, idle=True))
|
||||
modes.ack.seen = modes.ack.valid = modes.ack.alive = {'conditionalModelAck': True}
|
||||
modes.ack.logMonoTime = {'conditionalModelAck': BASE}
|
||||
feed = Feed()
|
||||
feed['carState'].vEgo = 60 * .44704
|
||||
return modes, feed
|
||||
|
||||
|
||||
def test_automatic_highway_request_uses_same_held_handoff_and_separate_buffers():
|
||||
modes, feed = conditional_runtime_fixture()
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.owner.phase == 'waiting' and modes.owner.active == 'city'
|
||||
modes.owner.models['highway'][2].assert_not_called()
|
||||
modes.owner.announced = BASE
|
||||
ack = modes.ack['conditionalModelAck']
|
||||
ack.requestId, ack.holding = modes.owner.request, True
|
||||
modes.ack.logMonoTime['conditionalModelAck'] = BASE + 10_000_000
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE + 20_000_000):
|
||||
assert modes.before_frame(feed) == modes.owner.models['highway']
|
||||
modes.owner.models['highway'][2].assert_called_once()
|
||||
modes.owner.models['city'][2].assert_not_called()
|
||||
assert modes.owner.phase == 'switching'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('denial', ['engaged', 'lateral', 'armed', 'stale-ack', 'stale-output', 'invalid-can', 'invalid-speed'])
|
||||
def test_automatic_speed_never_bypasses_engagement_or_freshness(denial):
|
||||
modes, feed = conditional_runtime_fixture()
|
||||
if denial == 'engaged':
|
||||
feed['selfdriveState'].enabled = True
|
||||
elif denial == 'lateral':
|
||||
feed['carControl'].latActive = True
|
||||
elif denial == 'armed':
|
||||
modes.ack['conditionalModelAck'].idle = False
|
||||
elif denial == 'stale-ack':
|
||||
modes.ack.logMonoTime['conditionalModelAck'] = BASE - 1_000_000_000
|
||||
elif denial == 'stale-output':
|
||||
modes.owner.frame = BASE - 1_000_000_000
|
||||
elif denial == 'invalid-can':
|
||||
feed['carState'].canValid = False
|
||||
else:
|
||||
feed['carState'].vEgo = float('nan')
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.owner.phase == 'ready' and modes.owner.active == 'city'
|
||||
assert not modes.owner.error and not modes.paused
|
||||
modes.owner.models['highway'][2].assert_not_called()
|
||||
|
||||
|
||||
def test_engaging_before_hold_cancels_without_false_failure_or_disabling_automation():
|
||||
modes, feed = conditional_runtime_fixture()
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.owner.phase == 'waiting'
|
||||
feed['selfdriveState'].enabled = True
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE + 20_000_000):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.owner.phase == 'ready' and modes.owner.active == 'city'
|
||||
assert not modes.owner.error and not modes.paused
|
||||
modes.owner.models['highway'][2].assert_not_called()
|
||||
|
||||
|
||||
def test_auto_failure_pauses_for_drive_instead_of_retrying_every_frame():
|
||||
modes, feed = conditional_runtime_fixture()
|
||||
modes.owner.error = 'Candidate failed; previous model restored'
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=BASE):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.paused and modes.owner.phase == 'ready'
|
||||
modes.owner.error = ''
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.paused and modes.owner.active == 'city'
|
||||
|
||||
|
||||
def test_identical_model_roles_never_reset_or_request_a_noop_handoff():
|
||||
modes, feed = conditional_runtime_fixture()
|
||||
modes.config['highway'] = 'city'
|
||||
feed['carState'].vEgo = 0.
|
||||
for i in range(601):
|
||||
now = BASE + i * 50_000_000
|
||||
feed.logMonoTime = dict.fromkeys(feed, now)
|
||||
modes.ack.logMonoTime['conditionalModelAck'] = modes.owner.frame = now
|
||||
with patch('openpilot.starpilot.models.conditional_runtime.time.monotonic_ns', return_value=now):
|
||||
assert modes.before_frame(feed) is None
|
||||
assert modes.owner.phase == 'ready' and modes.owner.request == ''
|
||||
for _, _, reset in modes.owner.models.values():
|
||||
reset.assert_not_called()
|
||||
|
||||
|
||||
def test_previous_reset_failure_demands_isolated_recovery_instead_of_using_bad_history():
|
||||
owner, request = switcher()
|
||||
begin(owner, request)
|
||||
owner.models['highway'][2].side_effect = RuntimeError('device mapping failed')
|
||||
with pytest.raises(RuntimeError, match='isolated recovery required'):
|
||||
owner.abort('Candidate failed', BASE + 40_000_000)
|
||||
assert owner.phase == 'recovering' and owner.error
|
||||
|
||||
|
||||
def test_randomized_transition_trace_never_changes_runner_without_disengagement():
|
||||
import random
|
||||
rng = random.Random(42)
|
||||
owner, _ = switcher()
|
||||
for i in range(1, 2000):
|
||||
now = BASE + i * 50_000_000
|
||||
idle = rng.choice((True, False))
|
||||
desired = {'session': owner.session, 'id': f'{i:032x}', 'model': rng.choice(('highway', 'city'))}
|
||||
ack = Ack(owner.session, owner.request, True, owner.announced, now)
|
||||
previous = owner.active
|
||||
changed = owner.before_frame(desired, now=now, idle=idle, ack=ack)
|
||||
if changed:
|
||||
assert idle and previous != owner.active
|
||||
if not idle:
|
||||
assert owner.active == previous
|
||||
if owner.phase == 'waiting' and not owner.announced:
|
||||
owner.announced = now
|
||||
owner.published(now, now)
|
||||
@@ -401,6 +401,124 @@ class ModelManagerTest(unittest.TestCase):
|
||||
with patch.object(self.manager, 'jetlink_owner', return_value=owner), self.assertRaises(ModelError):
|
||||
self.manager.action('active', {'profile': 'big', 'model': ''})
|
||||
|
||||
def enable_conditional_model(self):
|
||||
self.download()
|
||||
return self.manager.action('conditional_model', {'enabled': True, 'highway': DEFAULT_SMALL, 'city': 'gwm8223'})
|
||||
|
||||
def test_conditional_model_always_starts_city_and_preserves_single_model_preference(self):
|
||||
self.manager.gpu_present = lambda: False
|
||||
result = self.enable_conditional_model()
|
||||
self.assertEqual(result['activeSmallModel'], 'gwm8223')
|
||||
self.assertEqual(preferences(self.root)['small'], DEFAULT_SMALL)
|
||||
for _ in range(3):
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, 'gwm8223')
|
||||
self.manager.action('conditional_model', {'enabled': False})
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, DEFAULT_SMALL)
|
||||
|
||||
def test_conditional_recovery_override_is_not_saved_as_next_drive_start(self):
|
||||
self.enable_conditional_model()
|
||||
before = (self.root / 'preferences.json').read_bytes()
|
||||
self.assertEqual(resolve_runtime(False, root=self.root, small_override=DEFAULT_SMALL).small_id, DEFAULT_SMALL)
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, 'gwm8223')
|
||||
self.assertEqual((self.root / 'preferences.json').read_bytes(), before)
|
||||
with self.assertRaises(ModelError):
|
||||
resolve_runtime(False, root=self.root, small_override='unknown-model')
|
||||
|
||||
def test_conditional_model_has_only_enabled_models_and_speed(self):
|
||||
result = self.enable_conditional_model()['conditionalModel']
|
||||
self.assertEqual(result, {'enabled': True, 'city': 'gwm8223', 'highway': DEFAULT_SMALL, 'thresholdMph': 50})
|
||||
self.manager.action('conditional_model', {'thresholdMph': 60})
|
||||
self.assertEqual(preferences(self.root)['conditionalModel']['thresholdMph'], 60)
|
||||
|
||||
def test_conditional_model_rejects_invalid_and_removed_settings_without_writes(self):
|
||||
before = preferences(self.root)
|
||||
for payload in ({}, {'unknown': True}, {'enabled': 1}, {'selected': 'highway'}, {'automatic': False},
|
||||
{'cityDelaySeconds': 10}, {'session': 'a' * 32}, {'city': '../escape'}, {'city': 'cinquev3'},
|
||||
{'city': None}, {'thresholdMph': True}, {'thresholdMph': 0}, {'thresholdMph': 101}, {'thresholdMph': 50.5}):
|
||||
with self.subTest(payload=payload), self.assertRaises(ModelError):
|
||||
self.manager.action('conditional_model', payload)
|
||||
self.assertEqual(preferences(self.root), before)
|
||||
|
||||
def test_conditional_model_defaults_to_fifty_mph_with_identical_models_allowed(self):
|
||||
payload = {'enabled': True, 'city': DEFAULT_SMALL, 'highway': DEFAULT_SMALL}
|
||||
result = self.manager.action('conditional_model', payload)
|
||||
self.assertEqual(result['conditionalModel']['thresholdMph'], 50)
|
||||
before = (self.root / 'preferences.json').read_bytes()
|
||||
self.manager.action('conditional_model', payload)
|
||||
self.assertEqual((self.root / 'preferences.json').read_bytes(), before)
|
||||
|
||||
def test_legacy_manual_configuration_migrates_to_city_start_and_automatic_only(self):
|
||||
self.download()
|
||||
legacy = {'enabled': True, 'highway': DEFAULT_SMALL, 'city': 'gwm8223', 'selected': 'highway',
|
||||
'automatic': False, 'thresholdMph': 60, 'cityDelaySeconds': 300}
|
||||
atomic_json(self.root / 'preferences.json', {'small': DEFAULT_SMALL, 'smallProfiles': legacy, 'liveRequest': {'model': DEFAULT_SMALL}})
|
||||
result = preferences(self.root)
|
||||
self.assertEqual(result['conditionalModel'], {'enabled': True, 'highway': DEFAULT_SMALL, 'city': 'gwm8223', 'thresholdMph': 60})
|
||||
self.assertNotIn('liveRequest', result)
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, 'gwm8223')
|
||||
self.manager.action('conditional_model', {'thresholdMph': 50})
|
||||
saved = json.loads((self.root / 'preferences.json').read_text())
|
||||
self.assertNotIn('smallProfiles', saved)
|
||||
self.assertNotIn('liveRequest', saved)
|
||||
|
||||
def test_conditional_model_rejects_onroad_and_boundary_race(self):
|
||||
self.enable_conditional_model()
|
||||
before = (self.root / 'preferences.json').read_bytes()
|
||||
for parked in (lambda: False, unittest.mock.Mock(side_effect=[True, False])):
|
||||
self.manager.parked = parked
|
||||
with self.assertRaisesRegex(ModelError, 'vehicle off'):
|
||||
self.manager.action('conditional_model', {'thresholdMph': 60})
|
||||
self.assertEqual((self.root / 'preferences.json').read_bytes(), before)
|
||||
|
||||
def test_conditional_model_verifies_both_and_preserves_corrupt_city_fallback(self):
|
||||
self.enable_conditional_model()
|
||||
(self.root / 'gwm8223/gwm8223_driving_tinygrad.pkl').write_bytes(b'corrupt')
|
||||
before = preferences(self.root)
|
||||
with self.assertRaisesRegex(ModelError, 'verify both'):
|
||||
self.manager.action('conditional_model', {'thresholdMph': 60})
|
||||
self.assertEqual(preferences(self.root), before)
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, DEFAULT_SMALL)
|
||||
|
||||
def test_conditional_model_arbitrates_randomizer_single_selection_and_delete(self):
|
||||
self.enable_conditional_model()
|
||||
for action, payload in (('preferences', {'randomizer': True}), ('active', {'profile': 'small', 'model': DEFAULT_SMALL}),
|
||||
('delete', {'model': 'gwm8223'})):
|
||||
with self.subTest(action=action), self.assertRaises(ModelError):
|
||||
self.manager.action(action, payload)
|
||||
self.manager.action('conditional_model', {'enabled': False})
|
||||
self.manager.action('preferences', {'randomizer': True})
|
||||
with self.assertRaisesRegex(ModelError, 'Randomizer off'):
|
||||
self.manager.action('conditional_model', {'enabled': True})
|
||||
|
||||
def test_conditional_model_failed_commit_and_busy_job_preserve_configuration(self):
|
||||
self.enable_conditional_model()
|
||||
before = (self.root / 'preferences.json').read_bytes()
|
||||
with patch('openpilot.starpilot.models.manager.atomic_json', side_effect=OSError('disk full')), self.assertRaises(OSError):
|
||||
self.manager.action('conditional_model', {'thresholdMph': 60})
|
||||
with patch.object(self.manager, '_job_busy', return_value=True), self.assertRaisesRegex(ModelError, 'download'):
|
||||
self.manager.action('conditional_model', {'thresholdMph': 60})
|
||||
self.assertEqual((self.root / 'preferences.json').read_bytes(), before)
|
||||
|
||||
def test_malformed_conditional_configuration_cannot_enable_from_legacy_fallback(self):
|
||||
self.enable_conditional_model()
|
||||
saved = preferences(self.root)
|
||||
for value in (None, [], {'enabled': True}, saved['conditionalModel'] | {'selected': 'highway'}):
|
||||
atomic_json(self.root / 'preferences.json', saved | {'conditionalModel': value, 'smallProfiles': saved['conditionalModel']})
|
||||
self.assertFalse(preferences(self.root)['conditionalModel']['enabled'])
|
||||
self.assertEqual(resolve_runtime(False, root=self.root).small_id, DEFAULT_SMALL)
|
||||
|
||||
def test_conditional_model_partial_updates_preserve_other_preferences(self):
|
||||
self.enable_conditional_model()
|
||||
other = ModelManager(root=self.root, parked=lambda: True, gpu_present=lambda: False)
|
||||
self.addCleanup(other.close)
|
||||
other.action('preferences', {'userFavorites': ['gwm8223']})
|
||||
other.action('conditional_model', {'thresholdMph': 60})
|
||||
self.manager.action('conditional_model', {'highway': 'gwm8223'})
|
||||
saved = preferences(self.root)
|
||||
self.assertEqual(saved['userFavorites'], ['gwm8223'])
|
||||
self.assertEqual(saved['conditionalModel'], {'enabled': True, 'city': 'gwm8223', 'highway': 'gwm8223', 'thresholdMph': 60})
|
||||
self.assertEqual(saved['small'], DEFAULT_SMALL)
|
||||
|
||||
def test_hardware_profiles_and_selected_delete(self):
|
||||
self.download()
|
||||
with self.assertRaises(ModelError):
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import ast
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -18,6 +18,31 @@ def main_body():
|
||||
return next(node for node in ast.parse(MODEL_SOURCE.read_text()).body if isinstance(node, ast.FunctionDef) and node.name == "main").body
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure_at', ['run', 'action'])
|
||||
def test_live_candidate_failure_restores_resident_previous_in_production_frame_path(failure_at):
|
||||
from openpilot.starpilot.models.conditional_protocol import ResidentSwitch
|
||||
statement = next(node for item in main_body() for node in ast.walk(item)
|
||||
if isinstance(node, ast.Try) and any(isinstance(child, ast.Call) and ast.unparse(child.func) == 'model.run'
|
||||
for child in ast.walk(node)))
|
||||
previous = SimpleNamespace(chestnut=False, model_id='highway', run=Mock(return_value={'good': True}))
|
||||
candidate = SimpleNamespace(chestnut=False, run=Mock(return_value={}), get_action_from_model=Mock())
|
||||
getattr(candidate, 'run' if failure_at == 'run' else 'get_action_from_model').side_effect = RuntimeError('candidate failed')
|
||||
reset = Mock()
|
||||
owner = ResidentSwitch({'highway': (previous, 'prepared', reset)}, 'highway', now=1)
|
||||
owner.active, owner.phase = 'city', 'switching'
|
||||
env = {'model': candidate, 'conditional_runtime': SimpleNamespace(owner=owner), 'cloudlog': Mock(),
|
||||
'chestnut_state': None, 'run_count': 0, 'bufs': {}, 'transforms': {}, 'inputs': {},
|
||||
'prev_action': None, 'lat_action_t': 0., 'long_action_t': 0., 'v_ego': 0.,
|
||||
'lat_delay': .1, 'frame_drop_ratio': 0., 'time': SimpleNamespace(monotonic_ns=lambda: 50),
|
||||
'log': SimpleNamespace(ModelDataV2=SimpleNamespace(Action=Mock())),
|
||||
'sm': {'controlsState': SimpleNamespace(curvature=.01)}, 'DesireHelper': Mock(), 'runtime_lane_policy': object()}
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[statement], type_ignores=[])), str(MODEL_SOURCE), 'exec'), env)
|
||||
assert env['model'] is previous and env['model_output'] == {'good': True}
|
||||
assert owner.phase == 'recovering' and owner.active == 'highway'
|
||||
reset.assert_called_once()
|
||||
previous.run.assert_called_once_with({}, {}, {})
|
||||
|
||||
|
||||
def test_realtime_starts_after_model_load_and_receipt():
|
||||
# Inspect startup without importing modeld's GPU runtime or loading artifacts.
|
||||
calls = [(node.lineno, ast.unparse(node.func)) for statement in main_body() for node in ast.walk(statement) if isinstance(node, ast.Call)]
|
||||
@@ -30,6 +55,28 @@ def test_realtime_starts_after_model_load_and_receipt():
|
||||
assert max(line("load_small") + line("loader.join")) < startup_receipt.lineno < line("config_realtime_process")[0] < line("PubMaster")[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('selected_missing', [False, True])
|
||||
def test_small_profile_startup_failure_uses_existing_verified_fallback(selected_missing):
|
||||
function = next(node for statement in main_body() for node in ast.walk(statement)
|
||||
if isinstance(node, ast.FunctionDef) and node.name == 'load_small')
|
||||
shipped = Path('/verified/shipped.pkl')
|
||||
selected = Path('/verified/city.pkl')
|
||||
runner, prepared = object(), object()
|
||||
load = Mock(side_effect=[(runner, prepared)] if selected_missing else [RuntimeError('warmup failed'), (runner, prepared)])
|
||||
env = {'selection': SimpleNamespace(small_id='city', small_path=None if selected_missing else selected,
|
||||
small_version='v15', small_sha256='b' * 64),
|
||||
'cam_w': 1928, 'cam_h': 1208, 'coherent_warp': None, 'load_verified_model': load,
|
||||
'DEFAULT_SMALL': 'cheddar', 'DEFAULT_SMALL_SHA256': 'a' * 64,
|
||||
'BY_ID': {'cheddar': SimpleNamespace(version='v15')}, 'cloudlog': Mock()}
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[function], type_ignores=[])), str(MODEL_SOURCE), 'exec'), env)
|
||||
with patch('openpilot.starpilot.models.manager.shipped_default', return_value=shipped):
|
||||
assert env['load_small']() == (runner, prepared, True)
|
||||
assert load.call_args.args[2:7] == (shipped, 'v15', False, 'cheddar', 'a' * 64)
|
||||
assert load.call_count == (1 if selected_missing else 2)
|
||||
with patch('openpilot.starpilot.models.manager.shipped_default', return_value=None), pytest.raises(RuntimeError, match='missing or corrupt'):
|
||||
env['load_small']()
|
||||
|
||||
|
||||
def test_jetlink_gets_the_frames_delay_before_every_run():
|
||||
# a model that joins starts on the current delay; check_seam holds the frame_drop_ratio write
|
||||
loop = [node for node in main_body() if isinstance(node, ast.While)][-1] # the frame loop
|
||||
@@ -71,6 +118,7 @@ def test_inference_failure_uses_runner_identity(runner_chestnut, stored_active):
|
||||
"chestnut_state": chestnut_state, "run_count": 1, "ModelConstants": SimpleNamespace(MODEL_RUN_FREQ=20),
|
||||
"SERVICE_LIST": {"chestnutGpuState": SimpleNamespace(frequency=1)}, "bufs": {}, "transforms": {}, "inputs": {},
|
||||
"small_prepared": object(), "ModelVariant": ModelVariant, "jetlink_model": None, "drop_chestnut": Mock(), "cloudlog": Mock()}
|
||||
env['conditional_runtime'] = SimpleNamespace(owner=SimpleNamespace(phase='disabled'))
|
||||
code = compile(ast.fix_missing_locations(ast.Module(body=[fallback], type_ignores=[])), str(MODEL_SOURCE), "exec")
|
||||
if runner_chestnut:
|
||||
exec(code, env)
|
||||
@@ -103,6 +151,7 @@ def test_remote_inference_failure_does_not_change_chestnut_status():
|
||||
env = {"model": failed_model, "small_model": small_model, "params": params, "receipt_owner": receipt,
|
||||
"chestnut_state": None, "run_count": 1, "bufs": {}, "transforms": {}, "inputs": {},
|
||||
"small_prepared": object(), "ModelVariant": ModelVariant, "jetlink_model": failed_model, "drop_chestnut": Mock(), "cloudlog": Mock()}
|
||||
env['conditional_runtime'] = SimpleNamespace(owner=SimpleNamespace(phase='disabled'))
|
||||
execute([fallback], env)
|
||||
failed_model.close.assert_called_once_with()
|
||||
env["drop_chestnut"].assert_not_called()
|
||||
@@ -177,6 +226,8 @@ def test_observed_availability_and_big_eligibility(monkeypatch, present, cable,
|
||||
def test_big_worker_waits_before_load_and_failure_requests_fresh_small_process(custom, timeout, worker_alive, laboratory, monkeypatch):
|
||||
from openpilot.starpilot.models import manager
|
||||
monkeypatch.setattr(manager, "shipped_default", lambda: Path("bundled-small"))
|
||||
from openpilot.starpilot.models import conditional_runtime
|
||||
monkeypatch.setattr(conditional_runtime, 'ConditionalModelRuntime', Mock())
|
||||
body = main_body()
|
||||
start = next(i for i, node in enumerate(body) if isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "st")
|
||||
end = next(i for i, node in enumerate(body) if ast.unparse(node).startswith("config_realtime_process("))
|
||||
@@ -233,7 +284,7 @@ def test_big_worker_waits_before_load_and_failure_requests_fresh_small_process(c
|
||||
"CP": SimpleNamespace(brand="mock"), "demo": False,
|
||||
"wait_for_chestnut_power": lambda CP, timeout: events.append("power"),
|
||||
"jetlink_adapter": SimpleNamespace(hooks=lambda: hooks, coherent_warp=lambda: None), "drop_chestnut": Mock(),
|
||||
"release_compile_pool": Mock(), "gc": Mock()}
|
||||
"release_compile_pool": Mock(), "gc": Mock(), 'MODEL_ROOT': Path('/test-models'), 'recovery_model': None}
|
||||
if laboratory:
|
||||
from openpilot.starpilot.models.laboratory_runner import LaboratoryPair
|
||||
pair = object.__new__(LaboratoryPair)
|
||||
@@ -363,7 +414,7 @@ def test_recovery_child_resolves_small_without_randomizer_or_amd(monkeypatch):
|
||||
params = Mock()
|
||||
env: dict = {"chestnut_present": lambda: True, "cable_connected": lambda: True,
|
||||
"chestnut_compiled": Mock(side_effect=AssertionError("Big compiled probe forbidden")),
|
||||
"Params": lambda: params, "os": SimpleNamespace(getenv=lambda key: "1")}
|
||||
"Params": lambda: params, "os": SimpleNamespace(getenv=lambda key: "1" if key == 'STARPILOT_MODELD_RECOVERY_SMALL_ONLY' else None)}
|
||||
execute(body[start:end], env)
|
||||
manager.resolve_runtime.assert_called_once_with(chestnut_available=False, randomize=False)
|
||||
manager.requested_runtime_id.assert_called_once_with(True)
|
||||
@@ -378,7 +429,7 @@ def test_recovery_small_receipt_reports_runtime_stall_not_load_failure():
|
||||
receipt = Mock()
|
||||
env: dict = {'model': SimpleNamespace(chestnut=False, model_id='bundled-current'), 'small_prepared': object(),
|
||||
'receipt_owner': receipt, 'ModelVariant': ModelVariant, 'initial_chestnut_fallback': False,
|
||||
'recovery_small_only': True, 'selected_small_failed': False, 'requested_model_id': 'requested-big'}
|
||||
'recovery_small_only': True, 'selected_small_failed': False, 'requested_model_id': 'requested-big', 'recovery_model': None}
|
||||
execute([statement], env)
|
||||
assert receipt.loaded.call_args.args[1:3] == (ModelVariant.SMALL, 'chestnut-run-stalled')
|
||||
assert receipt.loaded.call_args.kwargs['model_id'] == 'bundled-current'
|
||||
|
||||
@@ -48,6 +48,11 @@ class TestModelReceipt(unittest.TestCase):
|
||||
with self.assertRaises(ReceiptUnavailable):
|
||||
write_receipt(replace(self.load, model_id="unknown"), self.path)
|
||||
|
||||
def test_conditional_switch_recovery_has_its_own_reason(self):
|
||||
load = replace(self.load, fallback_reason='conditional-switch-failed')
|
||||
write_receipt(load, self.path)
|
||||
self.assertEqual(read_receipt(self.path), load)
|
||||
|
||||
def test_symlink_fifo_and_unowned_directory_are_unavailable(self):
|
||||
target = self.root / "outside"
|
||||
target.write_bytes(b"untouched")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from types import SimpleNamespace as NS
|
||||
from itertools import product
|
||||
from unittest.mock import Mock, patch
|
||||
import unittest
|
||||
|
||||
@@ -22,6 +23,112 @@ class Feed(dict):
|
||||
|
||||
|
||||
class TestRecoveryProcess(unittest.TestCase):
|
||||
def test_resident_preload_watchdog_kills_before_isolated_restart(self):
|
||||
from openpilot.starpilot.models.conditional_protocol import PRELOAD_TIMEOUT_NS
|
||||
owner = ModeldProcess('modeld', 'module', lambda *args: True)
|
||||
child = Mock(pid=123)
|
||||
child.is_alive.return_value = True
|
||||
owner.proc, owner.launch_conditional, owner.launch_ns = child, True, BASE
|
||||
elapsed = PRELOAD_TIMEOUT_NS / 1e9 + .1
|
||||
with patch('openpilot.starpilot.models.recovery_process.process_start_ticks', return_value=456), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_pair_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.time.monotonic_ns', return_value=BASE + int(elapsed * 1e9)), \
|
||||
patch.object(owner, 'signal') as send, patch('openpilot.starpilot.models.recovery_process.Process') as spawn:
|
||||
owner.observe(Feed(elapsed), True)
|
||||
assert owner.recovery.small_only and owner.recovery.phase == 'sigint'
|
||||
owner.start()
|
||||
spawn.assert_not_called()
|
||||
send.assert_called_once()
|
||||
|
||||
def test_native_handoff_stall_requires_held_ack_and_fresh_cameras(self):
|
||||
for held, camera_count, progressing, source_valid in product((False, True), (1, 2), (False, True), (False, True)):
|
||||
owner = ModeldProcess('modeld', 'module', lambda *args: True)
|
||||
child = Mock(pid=123)
|
||||
child.is_alive.return_value = True
|
||||
owner.proc = child
|
||||
previous = (BASE + 4_000_000_000, 80) if progressing else (BASE + 5_000_000_000, 100)
|
||||
owner.last_conditional_cameras = (previous,) * camera_count
|
||||
feed = Feed(5., output=False)
|
||||
if camera_count == 1:
|
||||
feed.seen['wideRoadCameraState'] = False
|
||||
feed['conditionalModelState'] = NS(processPid=123, processStartTicks=456, session='session', requestId='request',
|
||||
phase='switching', sessionStartMonoTime=BASE, frameMonoTime=0, fallbackModel='cheddar')
|
||||
feed['conditionalModelAck'] = NS(session='session', requestId='request', holding=held,
|
||||
stateMonoTime=BASE + 4_900_000_000 if source_valid else BASE - 1)
|
||||
feed.seen.update(conditionalModelState=True, conditionalModelAck=True)
|
||||
feed.valid.update(conditionalModelState=True, conditionalModelAck=True)
|
||||
# Status may still be publishing even when no valid model frames emerge.
|
||||
feed.logMonoTime.update(conditionalModelState=BASE + 5_000_000_000, conditionalModelAck=BASE + 5_000_000_000)
|
||||
load = NS(pid=123, process_start_ticks=456, loaded_mono_ns=BASE, variant=ModelVariant.SMALL)
|
||||
with patch('openpilot.starpilot.models.recovery_process.process_start_ticks', return_value=456), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_receipt', return_value=load), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_pair_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.time.monotonic_ns', return_value=BASE + 5_000_000_000), \
|
||||
patch.object(owner, 'signal') as send:
|
||||
owner.observe(feed, True)
|
||||
assert send.called == (held and progressing and source_valid)
|
||||
if held and source_valid:
|
||||
assert owner.conditional_recovery_model == 'cheddar'
|
||||
|
||||
def test_crash_after_ready_before_hold_release_recovers_previous_model_after_confirmed_exit(self):
|
||||
owner = ModeldProcess('modeld', 'module', lambda *args: True)
|
||||
child = Mock(pid=123, exitcode=-9)
|
||||
child.is_alive.return_value = False
|
||||
owner.proc, owner.launch_conditional, owner.launch_ticks, owner.launch_drive_id = child, True, 456, BASE
|
||||
feed = Feed(5.)
|
||||
feed['conditionalModelState'] = NS(processPid=123, processStartTicks=456, session='session', requestId='request',
|
||||
phase='ready', sessionStartMonoTime=BASE, frameMonoTime=0, fallbackModel='cheddar')
|
||||
feed['conditionalModelAck'] = NS(session='session', requestId='request', holding=True, stateMonoTime=BASE + 4_900_000_000)
|
||||
feed.seen.update(conditionalModelState=True, conditionalModelAck=True)
|
||||
feed.valid.update(conditionalModelState=True, conditionalModelAck=True)
|
||||
feed.logMonoTime.update(conditionalModelState=BASE + 4_900_000_000, conditionalModelAck=BASE + 5_000_000_000)
|
||||
load = NS(pid=123, process_start_ticks=456, loaded_mono_ns=BASE, variant=ModelVariant.SMALL)
|
||||
with patch('openpilot.starpilot.models.recovery_process.read_receipt', return_value=load), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_pair_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.time.monotonic_ns', return_value=BASE + 5_000_000_000), \
|
||||
patch('openpilot.starpilot.models.recovery_process.process_start_ticks', return_value=789), \
|
||||
patch('openpilot.starpilot.models.recovery_process.Process') as spawn:
|
||||
owner.observe(feed, True)
|
||||
child.join.assert_called_once_with(timeout=0)
|
||||
assert owner.proc is None and owner.recovery.small_only
|
||||
owner.start()
|
||||
assert spawn.call_args.kwargs['kwargs'] == {'recovery_model': 'cheddar'}
|
||||
|
||||
def test_established_runner_never_becomes_a_preload_timeout_when_receipt_is_lost(self):
|
||||
owner = ModeldProcess('modeld', 'module', lambda *args: True)
|
||||
child = Mock(pid=123)
|
||||
child.is_alive.return_value = True
|
||||
owner.proc, owner.launch_conditional, owner.launch_ns = child, True, BASE
|
||||
feed = Feed(121.)
|
||||
now = BASE + 121_000_000_000
|
||||
feed['conditionalModelState'] = NS(processPid=123, processStartTicks=456, sessionStartMonoTime=BASE, frameMonoTime=now)
|
||||
feed.seen['conditionalModelState'] = feed.valid['conditionalModelState'] = True
|
||||
feed.logMonoTime['conditionalModelState'] = now
|
||||
with patch('openpilot.starpilot.models.recovery_process.process_start_ticks', return_value=456), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_pair_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.time.monotonic_ns', return_value=now), \
|
||||
patch.object(owner, 'signal') as send:
|
||||
owner.observe(feed, True)
|
||||
assert owner.launch_established
|
||||
del feed['conditionalModelState']
|
||||
owner.observe(feed, True)
|
||||
send.assert_not_called()
|
||||
assert not owner.recovery.small_only
|
||||
|
||||
def test_established_native_crash_does_not_restart_a_different_model_while_engaged(self):
|
||||
owner = ModeldProcess('modeld', 'module', lambda *args: True)
|
||||
child = Mock(pid=123, exitcode=-9)
|
||||
child.is_alive.return_value = False
|
||||
owner.proc, owner.launch_conditional, owner.launch_ticks, owner.launch_drive_id = child, True, 456, BASE
|
||||
load = NS(pid=123, process_start_ticks=456, loaded_mono_ns=BASE, variant=ModelVariant.SMALL)
|
||||
with patch('openpilot.starpilot.models.recovery_process.read_receipt', return_value=load), \
|
||||
patch('openpilot.starpilot.models.recovery_process.read_pair_receipt', return_value=None), \
|
||||
patch('openpilot.starpilot.models.recovery_process.time.monotonic_ns', return_value=BASE + 2_000_000_000):
|
||||
owner.observe(Feed(2.), True)
|
||||
assert owner.proc is child and not owner.recovery.small_only
|
||||
|
||||
def test_adapter_never_spawns_before_confirmed_exit(self):
|
||||
owner = ModeldProcess('modeld', 'openpilot.selfdrive.modeld.modeld', lambda *args: True)
|
||||
child = Mock(pid=123)
|
||||
|
||||
@@ -3,9 +3,10 @@ import time
|
||||
import tempfile
|
||||
import unittest
|
||||
import uuid
|
||||
from unittest.mock import patch
|
||||
|
||||
from openpilot.starpilot.models.catalog import BUNDLED_CURRENT
|
||||
from openpilot.starpilot.models.runtime import snapshot
|
||||
from openpilot.starpilot.models.runtime import ModelStatusSource, snapshot
|
||||
from openpilot.starpilot.models.status import ModelHealth, ModelLoad, ModelVariant
|
||||
|
||||
|
||||
@@ -51,6 +52,29 @@ class TestRuntimeSnapshot(unittest.TestCase):
|
||||
self.sm.logMonoTime["managerState"] = 100
|
||||
self.assertEqual(self.status().health, ModelHealth.UNAVAILABLE)
|
||||
|
||||
def test_conditional_switch_permission_requires_owned_publisher_and_both_fresh_outputs(self):
|
||||
conditional = SimpleNamespace(processPid=421, processStartTicks=54321, session='session', requestId='request',
|
||||
phase='ready', activeModel='cheddar', highwayModel='cheddar', cityModel='city',
|
||||
error='', canSwitch=True, sessionStartMonoTime=1_800_000_000,
|
||||
frameMonoTime=1_990_000_000, transitionSeconds=.25, paused=False, targetMode='city', thresholdMph=50, unavailableReason='')
|
||||
self.sm.messages['conditionalModelState'] = conditional
|
||||
self.sm.logMonoTime['conditionalModelState'] = 1_995_000_000
|
||||
self.sm.valid['conditionalModelState'] = self.sm.alive['conditionalModelState'] = True
|
||||
source = ModelStatusSource(FakeParams(), sm=self.sm, clock=lambda: 2_000_000_000)
|
||||
with patch('openpilot.starpilot.models.runtime.process_start_ticks', return_value=54321):
|
||||
self.assertTrue(source.conditional_json()['canSwitch'])
|
||||
self.sm.valid['drivingModelData'] = False
|
||||
self.assertFalse(source.conditional_json()['canSwitch'])
|
||||
self.sm.valid['drivingModelData'] = True
|
||||
conditional.frameMonoTime = 1_799_000_000
|
||||
self.assertFalse(source.conditional_json()['canSwitch'])
|
||||
conditional.frameMonoTime = 1_990_000_000
|
||||
conditional.processStartTicks = 54322
|
||||
self.assertIsNone(source.conditional_json())
|
||||
conditional.processStartTicks = 54321
|
||||
self.sm.logMonoTime['conditionalModelState'] = 1_000_000_000
|
||||
self.assertIsNone(source.conditional_json())
|
||||
|
||||
def test_pid_reuse_or_actual_variant_mismatch_does_not_claim_identity(self):
|
||||
self.assertEqual(self.status(process_ticks=54322).health, ModelHealth.IDENTITY_UNAVAILABLE)
|
||||
self.assertEqual(self.status(process_ticks=0).health, ModelHealth.IDENTITY_UNAVAILABLE)
|
||||
|
||||
@@ -13,8 +13,8 @@ from openpilot.starpilot.ui.onroad_customization import (CEM_GAUGE_WIDGET, CLOCK
|
||||
validate_map_box, validate_widget_order)
|
||||
from openpilot.starpilot.ui.onroad_stopped_timer import timer_size
|
||||
from openpilot.starpilot.ui.onroad_torque_geometry import maximum_footprint
|
||||
from openpilot.starpilot.ui.onroad_customization import (SPEED_LAYOUT_V7, migrate_speed_layout, migrate_large_sign_layout, migrate_attached_actions_gap,
|
||||
place_attached_slc_actions, migrate_confirmation_layout)
|
||||
from openpilot.starpilot.ui.onroad_customization import (SPEED_LAYOUT_V7, migrate_speed_layout, migrate_large_sign_layout,
|
||||
migrate_confirmation_layout)
|
||||
from openpilot.starpilot.ui.large_speed_geometry import sources_extent
|
||||
|
||||
MAX_BYTES = 16384
|
||||
@@ -199,11 +199,9 @@ def default_layout(screen, display=None):
|
||||
def default_layout_for_viewport(viewport, display=None):
|
||||
metadata = layout_metadata_for_viewport(viewport)
|
||||
display = {**DISPLAY_DEFAULTS, **{key: value for key, value in (display or {}).items() if key in DISPLAY_DEFAULTS}}
|
||||
result = {'version': 7, 'clock24Hour': False, 'largeUiGammaTrial': False, **display, 'canvas': {key: metadata[key] for key in ('width', 'height')},
|
||||
return {'version': 7, 'clock24Hour': False, 'largeUiGammaTrial': False, **display, 'canvas': {key: metadata[key] for key in ('width', 'height')},
|
||||
'widgets': {key: {**widget['default'], **({'size': 192} if key == 'steering_wheel' else {})}
|
||||
for key, widget in metadata['widgets'].items()}}
|
||||
place_attached_slc_actions(result['widgets'], metadata['bounds'], sources_extent(result))
|
||||
return result
|
||||
|
||||
|
||||
def now_playing_size(placement):
|
||||
@@ -232,14 +230,14 @@ def validate_layout(value, screen):
|
||||
|
||||
def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
|
||||
metadata = layout_metadata_for_viewport(viewport)
|
||||
if type(value) is dict and type(value.get('widgets')) is dict and 'speed_limit_actions' in value['widgets']:
|
||||
# Speed limit actions are part of the speed limit sign now; older layouts still carry the widget.
|
||||
value = {**value, 'widgets': {key: placement for key, placement in value['widgets'].items() if key != 'speed_limit_actions'}}
|
||||
if type(value.get('widgetOrder')) is list:
|
||||
value['widgetOrder'] = [key for key in value['widgetOrder'] if key != 'speed_limit_actions']
|
||||
if type(value) is dict and type(value.get('version')) is int and value['version'] == 1 and not _legacy_geometry:
|
||||
result = validate_layout_for_viewport(value, viewport, _legacy_geometry=True)
|
||||
card, actions = result['widgets']['cruise_limits'], result['widgets']['speed_limit_actions']
|
||||
gap = actions['y'] - card['y']
|
||||
migrate_speed_layout(result['widgets'], 'large', metadata['bounds'], gap if gap in (372, 425) else 232, widgets=metadata['widgets'])
|
||||
# The intermediate v2 validator still uses its historical wider action box.
|
||||
actions['x'] = min(actions['x'], metadata['bounds']['x'] + metadata['bounds']['width'] -
|
||||
max(metadata['widgets']['speed_limit_actions']['width'], SPEED_LAYOUT_V7['large']['speed_limit_actions'][0]))
|
||||
migrate_speed_layout(result['widgets'], 'large', metadata['bounds'], widgets=metadata['widgets'])
|
||||
result['version'] = 2
|
||||
return validate_layout_for_viewport(result, viewport)
|
||||
fields = {'version', 'canvas', 'widgets'}
|
||||
@@ -365,10 +363,9 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
|
||||
old_gauge = key == CEM_GAUGE_WIDGET and value['version'] < 3 and key in value['widgets']
|
||||
if old_gauge:
|
||||
dimensions = CEM_GAUGE_FRAME
|
||||
if _legacy_geometry and key in ('cruise_limits', 'speed_limit_actions'):
|
||||
historic = {'cruise_limits': ((176, 483), (280, 412)), 'speed_limit_actions': ((176, 58), (280, 96))}
|
||||
if _legacy_geometry and key == 'cruise_limits':
|
||||
# Both shapes were published as v1; validate the whole footprint before migrating.
|
||||
dimensions = next((pair for pair in historic[key] if all(
|
||||
dimensions = next((pair for pair in ((176, 483), (280, 412)) if all(
|
||||
type(placement[axis]) in (int, float) and math.isfinite(placement[axis]) and
|
||||
bounds[axis] <= placement[axis] <= bounds[axis] + bounds[extent] - dimension
|
||||
for (axis, extent), dimension in zip((('x', 'width'), ('y', 'height')), pair, strict=True))), dimensions)
|
||||
@@ -386,24 +383,11 @@ def validate_layout_for_viewport(value, viewport, *, _legacy_geometry=False):
|
||||
placement.update(x=placement['x'] + CEM_GAUGE_INSET[0], y=placement['y'] + CEM_GAUGE_INSET[1])
|
||||
if not _legacy_geometry:
|
||||
if value['version'] < 4:
|
||||
card, actions = result['widgets']['cruise_limits'], result['widgets']['speed_limit_actions']
|
||||
gap = actions['y'] - card['y']
|
||||
migrate_speed_layout(result['widgets'], 'large', bounds, gap if gap in (232, 492) else 232, widgets=metadata['widgets'])
|
||||
migrate_speed_layout(result['widgets'], 'large', bounds, widgets=metadata['widgets'])
|
||||
if value['version'] < 5:
|
||||
migrate_large_sign_layout(result['widgets'], bounds, widgets=metadata['widgets'])
|
||||
actions = result['widgets']['speed_limit_actions']
|
||||
if (actions['x'], actions['y']) == (100, 296):
|
||||
actions.update(x=metadata['widgets']['speed_limit_actions']['default']['x'], y=metadata['widgets']['speed_limit_actions']['default']['y'])
|
||||
result['version'] = 7
|
||||
if value['version'] == 5 and result.get('speedSources') is True:
|
||||
card, actions = result['widgets']['cruise_limits'], result['widgets']['speed_limit_actions']
|
||||
old_gap = 284 + (8 if result.get('speedSourcesCard') is True else 0)
|
||||
if actions['x'] == card['x'] + 24 and actions['y'] == card['y'] + old_gap:
|
||||
actions['y'] = card['y'] + 192
|
||||
if value['version'] < 7:
|
||||
migrate_attached_actions_gap(result['widgets'], bounds)
|
||||
migrate_confirmation_layout(result['widgets'], 'large', metadata['widgets'], bounds, extra_height=sources_extent(result))
|
||||
place_attached_slc_actions(result['widgets'], bounds, sources_extent(result))
|
||||
if len(json.dumps(result, separators=(',', ':'), allow_nan=False).encode()) > MAX_BYTES:
|
||||
raise ValueError('Projection layout too large')
|
||||
return result
|
||||
|
||||
@@ -63,76 +63,50 @@ class TestProjectionLayout(unittest.TestCase):
|
||||
saved = [NAV_MAP, *(key for key in order if key != NAV_MAP)][::-1]
|
||||
self.assertEqual(projection_customization({**document, 'widgetOrder': saved}, default_document())['widgetOrder']['large'], saved)
|
||||
|
||||
def test_sources_save_actual_attached_actions_inside_each_projection_screen(self):
|
||||
from openpilot.starpilot.ui.onroad_customization import default_document, placement
|
||||
def test_sources_keep_the_card_where_it_fits_on_each_projection_screen(self):
|
||||
for viewport in ((1860, 1080), (2880, 1080), (1920, 1440)):
|
||||
for separate in (False, True):
|
||||
with self.subTest(viewport=viewport, separate=separate):
|
||||
document = default_layout_for_viewport(viewport, {'speedSources': True, 'speedSourcesCard': separate})
|
||||
actions = document['widgets']['speed_limit_actions']
|
||||
self.assertEqual(actions['y'], 457 if separate else 449)
|
||||
self.assertEqual(validate_layout_for_viewport(document, viewport), document)
|
||||
native = projection_customization(document, default_document())
|
||||
self.assertEqual(placement(native, 'large', 'speed_limit_actions'), actions)
|
||||
document['widgets']['cruise_limits']['y'] = 200
|
||||
actions['y'] = 574 + (8 if separate else 0)
|
||||
saved = validate_layout_for_viewport(document, viewport)
|
||||
card, actions = (saved['widgets'][key] for key in ('cruise_limits', 'speed_limit_actions'))
|
||||
self.assertEqual(card['y'], 200)
|
||||
self.assertEqual(actions['y'], card['y'] + 374 + (8 if separate else 0))
|
||||
self.assertLessEqual(actions['y'] + 168, viewport[1] - 30)
|
||||
self.assertEqual(saved['widgets']['cruise_limits']['y'], 200)
|
||||
self.assertEqual(validate_layout_for_viewport(saved, viewport), saved)
|
||||
|
||||
def test_v4_large_sign_migration_clamps_old_bottom_placement_without_losing_custom_actions(self):
|
||||
def test_v4_large_sign_migration_clamps_old_bottom_placement_and_drops_actions(self):
|
||||
document = default_layout(SCREEN)
|
||||
document['version'] = 4
|
||||
bounds = layout_metadata(SCREEN)['bounds']
|
||||
bottom = bounds['y'] + bounds['height']
|
||||
document['widgets']['cruise_limits']['y'] = bottom - 132
|
||||
document['widgets']['speed_limit_actions'].update(x=250, y=400)
|
||||
document['widgets']['speed_limit_actions'] = {'x': 250, 'y': 400, 'enabled': True}
|
||||
document['widgetOrder'] = [*layout_metadata(SCREEN)['widgetOrder'][:-1], 'speed_limit_actions', 'car_exit']
|
||||
before = copy.deepcopy(document)
|
||||
migrated = validate_layout(document, SCREEN)
|
||||
self.assertEqual(document, before)
|
||||
self.assertEqual(migrated['version'], 7)
|
||||
self.assertEqual(migrated['widgets']['cruise_limits']['y'], bottom - 309)
|
||||
self.assertEqual(migrated['widgets']['speed_limit_actions'], document['widgets']['speed_limit_actions'])
|
||||
self.assertNotIn('speed_limit_actions', migrated['widgets'])
|
||||
self.assertEqual(migrated['widgetOrder'], layout_metadata(SCREEN)['widgetOrder'])
|
||||
self.assertEqual(validate_layout(migrated, SCREEN), migrated)
|
||||
|
||||
def test_v4_moves_actions_only_when_they_follow_the_old_default_sign_position(self):
|
||||
document = default_layout(SCREEN)
|
||||
document['version'] = 4
|
||||
card = document['widgets']['cruise_limits']
|
||||
document['widgets']['speed_limit_actions'].update(x=card['x']+12, y=card['y']+173)
|
||||
migrated = validate_layout(document, SCREEN)
|
||||
self.assertEqual(migrated['widgets']['speed_limit_actions']['y'], card['y']+250)
|
||||
|
||||
def test_v5_portrait_upgrade_keeps_disabled_actions_and_clamps_only_the_resized_card(self):
|
||||
def test_v5_portrait_upgrade_with_hidden_actions_makes_room_for_the_sign_chooser(self):
|
||||
document = default_layout(SCREEN)
|
||||
document['version'] = 5
|
||||
bottom = sum(layout_metadata(SCREEN)['bounds'][key] for key in ('y', 'height'))
|
||||
document['widgets']['cruise_limits']['y'] = bottom - 168
|
||||
document['widgets']['speed_limit_actions'].update(x=250, y=400, enabled=False)
|
||||
document['widgets']['speed_limit_actions'] = {'x': 250, 'y': 400, 'enabled': False}
|
||||
before = copy.deepcopy(document)
|
||||
migrated = validate_layout(document, SCREEN)
|
||||
expected = copy.deepcopy(document)
|
||||
del expected['widgets']['speed_limit_actions']
|
||||
expected['version'] = 7
|
||||
expected['widgets']['cruise_limits']['y'] = bottom - 252
|
||||
expected['widgets']['cruise_limits']['y'] = bottom - 309
|
||||
self.assertEqual(document, before)
|
||||
self.assertEqual(migrated, expected)
|
||||
self.assertEqual(validate_layout(migrated, SCREEN), migrated)
|
||||
|
||||
def test_v5_source_attachment_follows_the_new_row_without_moving_custom_actions(self):
|
||||
for separate in (False, True):
|
||||
document = default_layout(SCREEN, {'speedSources': True, 'speedSourcesCard': separate})
|
||||
document['version'] = 5
|
||||
actions = document['widgets']['speed_limit_actions']
|
||||
actions['y'] = 367 if separate else 359
|
||||
updated = validate_layout(document, SCREEN)
|
||||
self.assertEqual(updated['widgets']['speed_limit_actions']['y'], 457 if separate else 449)
|
||||
self.assertEqual(validate_layout(updated, SCREEN), updated)
|
||||
actions.update(x=600, y=400)
|
||||
self.assertEqual(validate_layout(document, SCREEN)['widgets']['speed_limit_actions'], actions)
|
||||
|
||||
def test_jetlink_widget_migrates_and_preserves_placement_and_order(self):
|
||||
document = default_layout(SCREEN)
|
||||
expected = document['widgets'].pop('jetlink_status')
|
||||
|
||||
@@ -11,22 +11,12 @@ LARGE_SIGN_SCALE = PHYSICAL_SCALE * 1.3
|
||||
SIGN_WIDTH, SIGN_HEIGHT = 128, 144
|
||||
LIMIT_ROW_HEIGHT = math.ceil(SIGN_HEIGHT * LARGE_SIGN_SCALE)
|
||||
CARD_HEIGHT = LIMIT_ROW_HEIGHT
|
||||
ACTION_WIDTH = 308
|
||||
ACTION_HEIGHT = 168
|
||||
ACTION_X = 112
|
||||
# Attached just below the card.
|
||||
ACTION_Y = 75 + CARD_HEIGHT - 2
|
||||
GAP = 8
|
||||
SOURCE_ROW_HEIGHT = 76
|
||||
PADDING = 24
|
||||
|
||||
LIMIT_RECTS = {'large': (318, 75, math.ceil(SIGN_WIDTH * LARGE_SIGN_SCALE), LIMIT_ROW_HEIGHT),
|
||||
'compact': (320, 16, SIGN_WIDTH, SIGN_HEIGHT)}
|
||||
ACTION_BOUNDS = {
|
||||
'large': ((112, ACTION_Y, 420, ACTION_Y + 80), (112, ACTION_Y + 88, 420, ACTION_Y + ACTION_HEIGHT)),
|
||||
'compact': ((146, 44, 330, 102), (146, 106, 330, 164)),
|
||||
}
|
||||
ACTION_TEXT_SIZE = {'large': 64, 'compact': 48}
|
||||
|
||||
CONFIRMATION_SCALE = {'large': LARGE_SIGN_SCALE, 'compact': 1.0}
|
||||
# The open prompt's Accept/Reject buttons are sized for fingers, which do not change with viewing distance.
|
||||
|
||||
@@ -389,7 +389,7 @@ class _Canvas:
|
||||
else:
|
||||
# General edit shows a representative CEM sample even though its backdrop
|
||||
# remains engaged. Driving scenes always use their unmodified state.
|
||||
sample = {'cem_gauge': 'cem_curve', 'speed_limit_actions': 'slc_pending'}.get(key) if general else None
|
||||
sample = 'cem_curve' if general and key == 'cem_gauge' else None
|
||||
widget_state = sample_state(sample, state.customization) if sample is not None else state
|
||||
if key == "rear_fog":
|
||||
from openpilot.starpilot.car.ford.rear_fog import boot_time_ns
|
||||
|
||||
@@ -40,7 +40,6 @@ from openpilot.starpilot.ui.onroad_torque import TorqueBarWidget
|
||||
from openpilot.starpilot.ui.onroad_navigation import NavigationCard
|
||||
from openpilot.starpilot.ui.onroad_navigation_favorites import NavigationFavorites
|
||||
from openpilot.starpilot.ui.presentation import BitmapFonts, FontRole, Profile
|
||||
from openpilot.starpilot.ui.speed_limit_widget import MUTED, draw_ink
|
||||
from openpilot.starpilot.conditional_mode.policy import ModeChoice
|
||||
|
||||
|
||||
@@ -186,16 +185,8 @@ class OnroadView:
|
||||
self._compact(state)
|
||||
|
||||
def _slc_actions(self, state: OnroadState) -> None:
|
||||
if manual_slc_confirmation(self.fonts.profile, state):
|
||||
sign = self.unified_speed.sign if self.fonts.profile == Profile.LARGE else self.compact_hud._speed_limit_widget
|
||||
sign.render_confirmation(state, getattr(self, 'pressed_action', lambda: None)())
|
||||
return
|
||||
feedback = state.speed_limit.action_feedback
|
||||
if (self.fonts.profile == Profile.LARGE and feedback and state.alert.size == AlertSize.NONE and
|
||||
placement(state.customization, self.fonts.profile, 'speed_limit_actions')['enabled']):
|
||||
from openpilot.starpilot.ui.onroad_state import slc_action_bounds
|
||||
first, _ = slc_action_bounds(self.fonts.profile, state)
|
||||
draw_ink(self.fonts, feedback, FontRole.MEDIUM, 30, first[0], first[1] + 24, MUTED)
|
||||
sign = self.unified_speed.sign if self.fonts.profile == Profile.LARGE else self.compact_hud._speed_limit_widget
|
||||
sign.render_confirmation(state, getattr(self, 'pressed_action', lambda: None)())
|
||||
|
||||
def _preview_badge(self, state: OnroadState) -> None:
|
||||
"""Keep synthetic replay visibly identified even over a full alert."""
|
||||
@@ -333,7 +324,6 @@ class OnroadView:
|
||||
if state.alert.size != AlertSize.FULL:
|
||||
if placement(state.customization, profile, "cruise_limits")["enabled"]:
|
||||
submit("cruise_limits", lambda: self.unified_speed.render(content, state))
|
||||
submit("speed_limit_actions", lambda: self._slc_actions(state))
|
||||
if gauge := getattr(self, "cem_gauge", None):
|
||||
submit("cem_gauge", lambda: gauge.render(state))
|
||||
if placement(state.customization, profile, "current_speed")["enabled"]:
|
||||
@@ -352,7 +342,6 @@ class OnroadView:
|
||||
submit("speed_limit", lambda: self.compact_hud._speed_limit_sign(state))
|
||||
submit("max_speed", lambda: self.compact_hud.render_max_speed(state))
|
||||
submit("steering_wheel", lambda: self.compact_hud.render_steering_wheel(state))
|
||||
submit("speed_limit_actions", lambda: self._slc_actions(state))
|
||||
if placement(state.customization, profile, "torque_bar")["enabled"]:
|
||||
submit("torque_bar", lambda: self.torque_bar.render(content, state, 536))
|
||||
if state.stopped_duration_s is not None:
|
||||
@@ -375,8 +364,6 @@ class OnroadView:
|
||||
for key in widget_order(state.customization, profile):
|
||||
if only_widget is not None and key != only_widget:
|
||||
continue
|
||||
if pending and key == 'speed_limit_actions':
|
||||
continue
|
||||
if draw := callbacks.get(key):
|
||||
draw()
|
||||
if pending and (only_widget is None or only_widget == ('cruise_limits' if large else 'speed_limit')) and not driver_camera:
|
||||
@@ -413,8 +400,6 @@ class OnroadView:
|
||||
if state.alert.size != AlertSize.FULL:
|
||||
if placement(state.customization, "large", "cruise_limits")["enabled"]:
|
||||
self.unified_speed.render(content, state)
|
||||
if not manual_slc_confirmation(self.fonts.profile, state):
|
||||
self._slc_actions(state)
|
||||
if gauge := getattr(self, "cem_gauge", None):
|
||||
gauge.render(state)
|
||||
if placement(state.customization, "large", "current_speed")["enabled"]:
|
||||
@@ -536,8 +521,6 @@ class OnroadView:
|
||||
self.compact_hud.render(state)
|
||||
if placement(state.customization, "compact", "torque_bar")["enabled"]:
|
||||
self.torque_bar.render(frame, state, 536)
|
||||
if not manual_slc_confirmation(self.fonts.profile, state):
|
||||
self._slc_actions(state)
|
||||
if state.stopped_duration_s is not None:
|
||||
self._stopped_timer(state, state.stopped_duration_s)
|
||||
if self.extra_overlays is not None:
|
||||
|
||||
@@ -13,8 +13,7 @@ from openpilot.starpilot.ui.onroad_torque_geometry import maximum_footprint
|
||||
from openpilot.starpilot.ui.large_speed_geometry import LIMIT_RECTS, confirmation_footprint
|
||||
from openpilot.starpilot.ui.onroad_stopped_timer import timer_size
|
||||
from openpilot.starpilot.ui.onroad_favorites_geometry import shelf_metadata
|
||||
from openpilot.starpilot.ui.large_speed_geometry import (WIDTH, CARD_HEIGHT, ACTION_WIDTH, ACTION_HEIGHT, ACTION_X, ACTION_Y,
|
||||
GAP, SOURCE_ROW_HEIGHT, sources_extent)
|
||||
from openpilot.starpilot.ui.large_speed_geometry import WIDTH, CARD_HEIGHT, sources_extent
|
||||
|
||||
PARAM_KEY = "OnroadCustomizations"
|
||||
MAX_BYTES = 16384
|
||||
@@ -83,7 +82,6 @@ class LayoutProfile(TypedDict):
|
||||
bounds: Bounds
|
||||
widgets: dict[str, Widget]
|
||||
reservedZones: list[Bounds]
|
||||
protectedWidget: NotRequired[str]
|
||||
inputZones: NotRequired[list[dict[str, Any]]]
|
||||
inputZonePriority: NotRequired[str]
|
||||
widgetOrder: NotRequired[list[str]]
|
||||
@@ -103,36 +101,27 @@ PROFILES: dict[str, LayoutProfile] = {
|
||||
"widgets": {
|
||||
"current_speed": _widget("Current speed", "current_speed", 580, 300, 640, 30),
|
||||
"cruise_limits": _widget("Cruise and speed limit", "cruise_limits", WIDTH, CARD_HEIGHT, 88, 75),
|
||||
"speed_limit_actions": _widget("Speed limit actions", "speed_limit_actions", ACTION_WIDTH, ACTION_HEIGHT, ACTION_X, ACTION_Y),
|
||||
"steering_wheel": _widget("Steering wheel", "steering_wheel", 192, 192, 1588, 75),
|
||||
"driver_monitor": _widget("Driver monitoring", "driver_monitor", 128, 128, 270, 840),
|
||||
"following_distance": _widget("Following distance", "following_distance", 150, 200, 88, 804)}},
|
||||
"compact": {"label": "Small UI", "width": 536, "height": 240,
|
||||
"bounds": {"x": 0, "y": 0, "width": 476, "height": 240},
|
||||
"protectedWidget": "speed_limit_actions",
|
||||
"reservedZones": [],
|
||||
"widgets": {
|
||||
"max_speed": _widget("Set speed", "max_speed", 146, 162, 0, 0),
|
||||
"speed_limit": _widget("Speed limit", "speed_limit", *LIMIT_RECTS['compact'][2:], *LIMIT_RECTS['compact'][:2]),
|
||||
"speed_limit_actions": _widget("Speed limit actions", "speed_limit_actions", 184, 120, 146, 44),
|
||||
"steering_wheel": _widget("Steering wheel", "steering_wheel", 50, 50, 21, 176),
|
||||
"driver_monitor": _widget("Driver monitoring", "driver_monitor", 60, 60, 16, 10)}}}
|
||||
|
||||
for _profile in PROFILES:
|
||||
PROFILES[_profile]['widgets']['speed_limit_actions']['note'] = (
|
||||
'Accept / Reject appear inside a pending limit after tapping it.')
|
||||
_owner = 'cruise_limits' if _profile == 'large' else 'speed_limit'
|
||||
PROFILES[_profile]['widgets'][_owner]['confirmation'] = confirmation_footprint(_profile)
|
||||
|
||||
SPEED_LAYOUT_V7 = {
|
||||
'large': {'cruise_limits': (320, 210, 88, 75), 'speed_limit_actions': (320, 108, 88, 307)},
|
||||
'compact': {'max_speed': (162, 162, 0, 0), 'speed_limit': (118, 132, 174, 12),
|
||||
'speed_limit_actions': (282, 54, 174, 180)},
|
||||
}
|
||||
COMPACT_SPEED_LAYOUT_V8 = {
|
||||
'max_speed': (146, 114, 0, 0), 'speed_limit': (264, 82, 158, 18),
|
||||
'speed_limit_actions': (440, 52, 16, 122),
|
||||
'large': {'cruise_limits': (320, 210, 88, 75)},
|
||||
'compact': {'max_speed': (162, 162, 0, 0), 'speed_limit': (118, 132, 174, 12)},
|
||||
}
|
||||
COMPACT_SPEED_LAYOUT_V8 = {'max_speed': (146, 114, 0, 0), 'speed_limit': (264, 82, 158, 18)}
|
||||
|
||||
for profile, sizes in DM_SIZES.items():
|
||||
PROFILES[profile]['widgets']['driver_monitor']['default']['size'] = sizes[1]
|
||||
@@ -146,8 +135,6 @@ for _profile, _data in PROFILES.items():
|
||||
_data["widgets"]["torque_bar"] = {
|
||||
**_widget("Torque bar", "torque_bar", _width, _height, _x, _y), "layer": "underlay",
|
||||
"note": "Torque command or lateral-acceleration demand. Full width reflects the configured display scale."}
|
||||
ACTIONLESS_WIDGETS = {profile: set(data["widgets"]) - {"speed_limit_actions"} for profile, data in PROFILES.items()}
|
||||
|
||||
RAILLESS_WIDGETS = {profile: set(data["widgets"]) for profile, data in PROFILES.items()}
|
||||
RAIL_WIDGETS = ("model_confidence", "conditional_mode", "following_distance")
|
||||
for _index, (_key, _label) in enumerate(zip(RAIL_WIDGETS, ("Model confidence", "CEM and driving mode", "Following distance"), strict=True)):
|
||||
@@ -301,13 +288,12 @@ _torque['confirmationObstacle'] = {
|
||||
# These editor sprites use the runtime components and their canonical assets/fonts.
|
||||
RUNTIME_PREVIEW_WIDGETS = {
|
||||
"large": (WEATHER_WIDGET, "current_speed", "cruise_limits", CEM_GAUGE_WIDGET, "steering_wheel", "following_distance",
|
||||
"driver_monitor", "speed_limit_actions", "rear_fog", MODE_WIDGET, CLOCK_WIDGET),
|
||||
"driver_monitor", "rear_fog", MODE_WIDGET, CLOCK_WIDGET),
|
||||
"compact": (WEATHER_WIDGET, "max_speed", "speed_limit", "steering_wheel", "conditional_mode", "following_distance",
|
||||
"model_confidence", "driver_monitor", "speed_limit_actions", "rear_fog", MODE_WIDGET, CLOCK_WIDGET),
|
||||
"model_confidence", "driver_monitor", "rear_fog", MODE_WIDGET, CLOCK_WIDGET),
|
||||
}
|
||||
|
||||
_FRAME_COLORS = {"cardFill": "#00000000", "cardBorder": "#00000000"}
|
||||
_ACTION_COLORS = {"cardFill": "#0C1820EB", "cardBorder": "#A6DFBEFF", "text": "#FFFFFFFF"}
|
||||
WIDGET_COLORS = {
|
||||
"large": {
|
||||
MODE_WIDGET: {"text": "#FFFFFFFF"},
|
||||
@@ -316,7 +302,6 @@ WIDGET_COLORS = {
|
||||
CEM_GAUGE_WIDGET: {},
|
||||
"current_speed": {"text": None},
|
||||
"cruise_limits": {"cardFill": "#10191FFF", "cardBorder": "#35434DFF", "text": None},
|
||||
"speed_limit_actions": {"cardFill": "#10191FFF", "cardBorder": "#35434DFF", "text": "#F1F6F3FF"},
|
||||
"steering_wheel": {"cardFill": None, "cardBorder": "#00000000"},
|
||||
"driver_monitor": _FRAME_COLORS,
|
||||
"following_distance": _FRAME_COLORS,
|
||||
@@ -326,7 +311,6 @@ WIDGET_COLORS = {
|
||||
CLOCK_WIDGET: {"text": "#FFFFFFFF"},
|
||||
WEATHER_WIDGET: {"cardFill": "#0F0D17CC", "cardBorder": "#C7AEF744", "text": "#F5F2FCFF"},
|
||||
"max_speed": {"text": None},
|
||||
"speed_limit_actions": {**_ACTION_COLORS, "text": "#F1F6F3FF"},
|
||||
"driver_monitor": _FRAME_COLORS,
|
||||
"model_confidence": _FRAME_COLORS,
|
||||
"conditional_mode": _FRAME_COLORS,
|
||||
@@ -351,11 +335,11 @@ def _fit_legacy_signal(placement: dict, bounds: Bounds) -> None:
|
||||
|
||||
# Back-to-front order used when a layout first opts into custom layers.
|
||||
DEFAULT_WIDGET_ORDER = {
|
||||
"large": (NAV_MAP_WIDGET, "cruise_limits", "speed_limit_actions", CEM_GAUGE_WIDGET, "current_speed",
|
||||
"large": (NAV_MAP_WIDGET, "cruise_limits", CEM_GAUGE_WIDGET, "current_speed",
|
||||
"steering_wheel", "torque_bar", "following_distance", "driver_monitor", MODE_WIDGET, CLOCK_WIDGET, WEATHER_WIDGET,
|
||||
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, JETLINK_WIDGET, SIGNAL_WIDGET, "rear_fog", "pip_left", "pip_right"),
|
||||
"compact": ("speed_limit", "max_speed", "steering_wheel", "torque_bar",
|
||||
"speed_limit_actions", "driver_monitor", *RAIL_WIDGETS, MODE_WIDGET, CLOCK_WIDGET, WEATHER_WIDGET,
|
||||
"driver_monitor", *RAIL_WIDGETS, MODE_WIDGET, CLOCK_WIDGET, WEATHER_WIDGET,
|
||||
STOPPED_TIMER_WIDGET, NAV_CARD_WIDGET, "rear_fog", "pip_left", "pip_right"),
|
||||
}
|
||||
|
||||
@@ -381,11 +365,11 @@ def customization_metadata():
|
||||
profiles["large"]["widgets"]["following_distance"]["defaultAnchor"] = "driver_side"
|
||||
# The editor grows the cruise box by these while speed-limit sources are shown.
|
||||
profiles["large"]["widgets"]["cruise_limits"]["sourcesExtent"] = {
|
||||
"inline": sources_extent({'speedSources': True}), "card": sources_extent({'speedSources': True, 'speedSourcesCard': True}), 'actionGap': GAP}
|
||||
"inline": sources_extent({'speedSources': True}), "card": sources_extent({'speedSources': True, 'speedSourcesCard': True})}
|
||||
profiles["large"]["inputZones"] = [{"id": "favorites_drawer", "label": "Quick Select drawer",
|
||||
"x": 30, "y": 900, "width": 340, "height": 150,
|
||||
"excludes": [key for key in profiles["large"]["widgets"]
|
||||
if key not in ("torque_bar", "pip_left", "pip_right", "nav_map", "speed_limit_actions")]}]
|
||||
if key not in ("torque_bar", "pip_left", "pip_right", "nav_map")]}]
|
||||
profiles["large"]["quickSelectShelves"] = shelf_metadata()
|
||||
profiles["compact"]["inputZones"] = [
|
||||
{"id": f"favorite_{index + 1}", "label": f"Quick Select {index + 1}",
|
||||
@@ -411,7 +395,7 @@ def customization_metadata():
|
||||
|
||||
|
||||
def default_document():
|
||||
return {"version": 15, "clock24Hour": False, "reduceMotion": False, "palette": dict(PALETTE), "roadColors": {profile: {} for profile in PROFILES},
|
||||
return {"version": 16, "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()}
|
||||
@@ -426,12 +410,9 @@ def validate_map_box(placement, widget):
|
||||
raise ValueError("Invalid map overlay size or opacity")
|
||||
|
||||
|
||||
def migrate_speed_layout(layout, profile, bounds, old_gap=232, *, previous=None, widgets=None):
|
||||
def migrate_speed_layout(layout, profile, bounds, *, previous=None, widgets=None):
|
||||
widgets = PROFILES[profile]['widgets'] if widgets is None else widgets
|
||||
if profile == 'large':
|
||||
card, actions = layout['cruise_limits'], layout['speed_limit_actions']
|
||||
if actions['x'] == card['x'] and actions['y'] - card['y'] == old_gap:
|
||||
actions.update(x=card['x'] + ACTION_X - 88, y=card['y'] + ACTION_Y - 75)
|
||||
gauge = layout[CEM_GAUGE_WIDGET]
|
||||
if (gauge['x'], gauge['y']) == (480, 99):
|
||||
default = widgets[CEM_GAUGE_WIDGET]['default']
|
||||
@@ -445,73 +426,17 @@ def migrate_speed_layout(layout, profile, bounds, old_gap=232, *, previous=None,
|
||||
saved[axis] = max(area[axis], min(saved[axis], area[axis] + area[extent] - widget[extent]))
|
||||
|
||||
|
||||
def _migrate_action_collisions(layout):
|
||||
actions = layout['speed_limit_actions']
|
||||
area = PROFILES['compact']['widgets']['speed_limit_actions']
|
||||
# Move only placements made invalid by the new protected action area.
|
||||
for key, height in _compact_action_collisions(layout):
|
||||
saved, widget = layout[key], PROFILES['compact']['widgets'][key]
|
||||
width = saved['size'] if key in WIDGET_SIZES else widget['width']
|
||||
candidates = ((actions['x'] - width, saved['y']), (actions['x'] + area['width'], saved['y']),
|
||||
(saved['x'], actions['y'] - height), (saved['x'], actions['y'] + area['height']))
|
||||
valid = [(x, y) for x, y in candidates if 0 <= x <= 476 - width and 0 <= y <= 240 - height]
|
||||
if valid:
|
||||
x, y = min(valid, key=lambda xy: (xy[0] - saved['x']) ** 2 + (xy[1] - saved['y']) ** 2)
|
||||
saved.update(x=x, y=y)
|
||||
|
||||
|
||||
def _compact_action_collisions(layout):
|
||||
widgets = PROFILES['compact']['widgets']
|
||||
actions, area = layout['speed_limit_actions'], widgets['speed_limit_actions']
|
||||
for key, widget in widgets.items():
|
||||
saved = layout[key]
|
||||
if (not saved['enabled'] or key in ('speed_limit_actions', 'speed_limit', 'stopped_timer', NAV_CARD_WIDGET) or widget.get('layer') == 'underlay'):
|
||||
continue
|
||||
width, height = (saved['size'],) * 2 if key in WIDGET_SIZES else (widget['width'], widget['height'])
|
||||
if (saved['x'] < actions['x'] + area['width'] and saved['x'] + width > actions['x'] and
|
||||
saved['y'] < actions['y'] + area['height'] and saved['y'] + height > actions['y']):
|
||||
yield key, height
|
||||
|
||||
|
||||
def migrate_large_sign_layout(layout, bounds, *, widgets=None, extra_height=0):
|
||||
widgets = PROFILES['large']['widgets'] if widgets is None else widgets
|
||||
card, actions = layout['cruise_limits'], layout['speed_limit_actions']
|
||||
# Only the old attached arrangement follows the sign; independently placed actions stay put.
|
||||
paired = actions['x'] == card['x'] + 12 and actions['y'] == card['y'] + 173
|
||||
card = layout['cruise_limits']
|
||||
card['y'] = min(card['y'], bounds['y'] + bounds['height'] - widgets['cruise_limits']['height'] - extra_height)
|
||||
if paired:
|
||||
actions['x'] = card['x'] + ACTION_X - 88
|
||||
actions['y'] = min(card['y'] + ACTION_Y - 75,
|
||||
bounds['y'] + bounds['height'] - widgets['speed_limit_actions']['height'])
|
||||
|
||||
|
||||
# Attached action gaps below the card before the large speed group grew 1.3x: plain, inline sources, sources card.
|
||||
SMALL_CARD_ACTION_GAPS = (192, 284, 292)
|
||||
|
||||
|
||||
def migrate_attached_actions_gap(layout, bounds):
|
||||
"""Keep attached actions below the grown card; place_attached_slc_actions then adds any sources row."""
|
||||
card, actions = layout['cruise_limits'], layout['speed_limit_actions']
|
||||
if actions['x'] == card['x'] + ACTION_X - 88 and actions['y'] - card['y'] in SMALL_CARD_ACTION_GAPS:
|
||||
# Raise a low card so the moved actions still fit on screen and stay attached.
|
||||
card['y'] = min(card['y'], bounds['y'] + bounds['height'] - ACTION_HEIGHT - (ACTION_Y - 75))
|
||||
actions['y'] = card['y'] + ACTION_Y - 75
|
||||
|
||||
|
||||
def place_attached_slc_actions(layout, bounds, extra_height):
|
||||
card, actions = layout['cruise_limits'], layout['speed_limit_actions']
|
||||
if (actions['x'], actions['y']) == (card['x'] + ACTION_X - 88, card['y'] + ACTION_Y - 75):
|
||||
# Save the actual position so drawing, editor crops and input share coordinates.
|
||||
dy = CARD_HEIGHT + extra_height + GAP if extra_height else ACTION_Y - 75
|
||||
card['y'] = min(card['y'], bounds['y'] + bounds['height'] - ACTION_HEIGHT - dy)
|
||||
actions['y'] = card['y'] + dy
|
||||
|
||||
|
||||
def confirmation_layout_valid(layout, profile, widgets, bounds, *, extra_height=0):
|
||||
owner = 'cruise_limits' if profile == 'large' else 'speed_limit'
|
||||
bounds = widgets[owner].get('bounds', bounds)
|
||||
at = layout[owner]
|
||||
if not at['enabled'] or not layout['speed_limit_actions']['enabled']:
|
||||
if not at['enabled']:
|
||||
return True
|
||||
area = confirmation_footprint(profile)
|
||||
left, top = at['x'] + area['x'], at['y'] + area['y']
|
||||
@@ -534,13 +459,10 @@ def migrate_confirmation_layout(layout, profile, widgets, bounds, *, extra_heigh
|
||||
owner = 'cruise_limits' if profile == 'large' else 'speed_limit'
|
||||
bounds = widgets[owner].get('bounds', bounds)
|
||||
area, at = confirmation_footprint(profile), layout[owner]
|
||||
confirming = at['enabled'] and layout['speed_limit_actions']['enabled']
|
||||
actions = layout['speed_limit_actions']
|
||||
attached = profile == 'large' and actions['x'] == at['x'] + ACTION_X - 88 and actions['y'] == at['y'] + ACTION_Y - 75
|
||||
for axis, extent in (('x', 'width'), ('y', 'height')):
|
||||
low = bounds[axis]
|
||||
high = bounds[axis] + bounds[extent] - widgets[owner][extent]
|
||||
if confirming:
|
||||
if at['enabled']:
|
||||
low = max(low, bounds[axis] - area[axis])
|
||||
high = min(high, bounds[axis] + bounds[extent] - area[axis] - area[extent])
|
||||
if axis == 'y':
|
||||
@@ -552,13 +474,21 @@ def migrate_confirmation_layout(layout, profile, widgets, bounds, *, extra_heigh
|
||||
if not confirmation_layout_valid(layout, profile, widgets, bounds, extra_height=extra_height):
|
||||
for key in (('torque_bar',) if profile == 'large' else ('max_speed', 'torque_bar')):
|
||||
layout[key].update(x=widgets[key]['default']['x'], y=widgets[key]['default']['y'])
|
||||
if attached:
|
||||
actions.update(x=at['x'] + ACTION_X - 88, y=at['y'] + ACTION_Y - 75)
|
||||
|
||||
|
||||
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, 16):
|
||||
if type(value) is not dict or type(value.get("version")) is not int or value["version"] not in range(1, 17):
|
||||
raise ValueError("Invalid customization version")
|
||||
if value["version"] < 16:
|
||||
# Version 16 folded the separate speed limit actions widget into the speed limit sign.
|
||||
value = copy.deepcopy(value)
|
||||
for section in ("layouts", "widgetColors"):
|
||||
for widgets in value[section].values() if type(value.get(section)) is dict else ():
|
||||
if type(widgets) is dict:
|
||||
widgets.pop("speed_limit_actions", None)
|
||||
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()}
|
||||
fields = {"version", "palette", "layouts"} | ({"widgetColors"} if value["version"] >= 2 else set())
|
||||
if value["version"] >= 3:
|
||||
fields.add("roadColors")
|
||||
@@ -605,30 +535,10 @@ def validate_document(value):
|
||||
if any(all(type(layouts[profile]) is dict and
|
||||
(set(layouts[profile]) - {"vasm", *OPTIONAL_WIDGETS, *CAMERA_WIDGETS}) == keys
|
||||
for profile, keys in shape.items())
|
||||
for shape in (LEGACY_WIDGETS, DM_WIDGETS, ACTIONLESS_WIDGETS)):
|
||||
for shape in (LEGACY_WIDGETS, DM_WIDGETS)):
|
||||
layouts = copy.deepcopy(layouts)
|
||||
cruise = layouts["large"]["cruise_limits"]
|
||||
if (type(cruise) is not dict or set(cruise) != {"x", "y", "enabled"} or type(cruise["enabled"]) is not bool or
|
||||
any(type(cruise[axis]) not in (int, float) for axis in ("x", "y"))):
|
||||
raise ValueError("Invalid widget placement")
|
||||
try:
|
||||
if not all(math.isfinite(cruise[axis]) for axis in ("x", "y")):
|
||||
raise ValueError("Invalid widget placement")
|
||||
except OverflowError as exc:
|
||||
raise ValueError("Invalid widget placement") from exc
|
||||
cruise_default = PROFILES["large"]["widgets"]["cruise_limits"]["default"]
|
||||
actions_default = ({'x': 88, 'y': 500 if value['version'] < 5 else 447 if value['version'] < 6 else 307} if value['version'] < 8 else
|
||||
PROFILES["large"]["widgets"]["speed_limit_actions"]["default"])
|
||||
layouts["large"]["speed_limit_actions"] = {
|
||||
"x": actions_default["x"] + cruise["x"] - cruise_default["x"],
|
||||
"y": actions_default["y"] + cruise["y"] - cruise_default["y"],
|
||||
"enabled": cruise["enabled"],
|
||||
}
|
||||
if value['version'] == 8 and 'speed_limit_actions' not in layouts['compact']:
|
||||
_, _, x, y = COMPACT_SPEED_LAYOUT_V8['speed_limit_actions']
|
||||
layouts['compact']['speed_limit_actions'] = {'x': x, 'y': y, 'enabled': True}
|
||||
for profile in PROFILES:
|
||||
for key in ("driver_monitor", "torque_bar", "speed_limit_actions"):
|
||||
for key in ("driver_monitor", "torque_bar"):
|
||||
layouts[profile].setdefault(key, dict(PROFILES[profile]["widgets"][key]["default"]))
|
||||
if all(type(layouts[profile]) is dict and (set(layouts[profile]) - {"vasm", *OPTIONAL_WIDGETS, *CAMERA_WIDGETS}) == keys
|
||||
for profile, keys in RAILLESS_WIDGETS.items()):
|
||||
@@ -673,8 +583,7 @@ def validate_document(value):
|
||||
for optional in missing:
|
||||
layouts[profile][optional] = dict(data["widgets"][optional]["default"])
|
||||
if value['version'] < 11:
|
||||
old_defaults = {'large': {'speed_limit_actions': (100, 296), CEM_GAUGE_WIDGET: (56, 452)},
|
||||
'compact': {'speed_limit_actions': (128, 186), 'clock': (168, 92), MODE_WIDGET: (162, 22)}}
|
||||
old_defaults = {'large': {CEM_GAUGE_WIDGET: (56, 452)}, 'compact': {'clock': (168, 92), MODE_WIDGET: (162, 22)}}
|
||||
result = default_document()
|
||||
for key, color in palette.items():
|
||||
if type(color) is not str or re.fullmatch(r"#[0-9a-fA-F]{8}", color) is None:
|
||||
@@ -768,9 +677,8 @@ def validate_document(value):
|
||||
old_gauge = key == CEM_GAUGE_WIDGET and value["version"] < 7 and type(saved_layout) is dict and key in saved_layout
|
||||
for axis, extent in (("x", "width"), ("y", "height")):
|
||||
number = placement[axis]
|
||||
legacy = ({'cruise_limits': (176, 483), 'speed_limit_actions': (176, 58)} if value['version'] < 5 else
|
||||
{'cruise_limits': (280, 412), 'speed_limit_actions': (280, 96)})
|
||||
dimensions = legacy.get(key) if value['version'] < 6 and profile == 'large' else None
|
||||
legacy = (176, 483) if value['version'] < 5 else (280, 412)
|
||||
dimensions = legacy if value['version'] < 6 and profile == 'large' and key == 'cruise_limits' else None
|
||||
if dimensions is None and value['version'] < 8:
|
||||
dimensions = SPEED_LAYOUT_V7[profile].get(key)
|
||||
if value['version'] == 8 and profile == 'compact':
|
||||
@@ -782,11 +690,6 @@ def validate_document(value):
|
||||
dimensions = (WIDTH, 168)
|
||||
elif profile == 'compact' and key == 'speed_limit':
|
||||
dimensions = (118, 132)
|
||||
if dimensions is None and value['version'] < 11 and key == 'speed_limit_actions':
|
||||
default = widget['default']
|
||||
current_default = (placement['x'], placement['y']) == (default['x'], default['y'])
|
||||
if not current_default:
|
||||
dimensions = (576, 148) if profile == 'large' else (348, 54)
|
||||
dimension = (dimensions[0 if axis == 'x' else 1] if dimensions else
|
||||
size if key in WIDGET_SIZES else placement[extent] if widget.get("box") else
|
||||
signal_size(placement)[0 if axis == 'x' else 1] if key == SIGNAL_WIDGET else
|
||||
@@ -804,8 +707,6 @@ def validate_document(value):
|
||||
if (saved['x'], saved['y']) == old:
|
||||
default = data['widgets'][key]['default']
|
||||
saved.update(x=default['x'], y=default['y'])
|
||||
if profile == "compact" and value['version'] >= 11 and any(_compact_action_collisions(result['layouts'][profile])):
|
||||
raise ValueError("Widget overlaps protected speed limit actions")
|
||||
if 'widgetOrder' in value:
|
||||
orders = value['widgetOrder']
|
||||
if type(orders) is not dict or not orders.keys() <= PROFILES.keys():
|
||||
@@ -836,20 +737,11 @@ def validate_document(value):
|
||||
colors = result['widgetColors']['large'].setdefault('cruise_limits', {})
|
||||
for key in ('cardFill', 'cardBorder'):
|
||||
colors.setdefault(key, value['palette'][key])
|
||||
old_gap = 425 if value['version'] < 5 else 372 if value['version'] < 6 else 232
|
||||
for profile in PROFILES:
|
||||
migrate_speed_layout(result['layouts'][profile], profile, PROFILES[profile]['bounds'], old_gap)
|
||||
migrate_speed_layout(result['layouts'][profile], profile, PROFILES[profile]['bounds'])
|
||||
elif value['version'] == 8:
|
||||
migrate_speed_layout(result['layouts']['compact'], 'compact', PROFILES['compact']['bounds'], previous=COMPACT_SPEED_LAYOUT_V8)
|
||||
if value['version'] < 15:
|
||||
migrate_attached_actions_gap(result['layouts']['large'], PROFILES['large']['bounds'])
|
||||
if value['version'] < 11:
|
||||
for profile, data in PROFILES.items():
|
||||
actions = result['layouts'][profile]['speed_limit_actions']
|
||||
widget, bounds = data['widgets']['speed_limit_actions'], widget_bounds(profile, 'speed_limit_actions')
|
||||
for axis, extent in (('x', 'width'), ('y', 'height')):
|
||||
actions[axis] = min(actions[axis], bounds[axis] + bounds[extent] - widget[extent])
|
||||
_migrate_action_collisions(result['layouts']['compact'])
|
||||
for profile, data in PROFILES.items():
|
||||
migrate_confirmation_layout(result['layouts'][profile], profile, data['widgets'], data['bounds'],
|
||||
extra_height=sources_extent(result) if profile == 'large' else 0)
|
||||
@@ -860,19 +752,12 @@ def validate_document(value):
|
||||
sign = result['layouts'][profile]['speed_limit']
|
||||
if (sign['x'], sign['y']) == (330, 20):
|
||||
sign.update(x=LIMIT_RECTS['compact'][0], y=LIMIT_RECTS['compact'][1])
|
||||
if profile == 'large' and result.get('speedSources') is True:
|
||||
card, actions = result['layouts'][profile]['cruise_limits'], result['layouts'][profile]['speed_limit_actions']
|
||||
old_gap = 284 if value['version'] == 12 else 192 + SOURCE_ROW_HEIGHT
|
||||
old_gap += GAP if result.get('speedSourcesCard') is True else 0
|
||||
if actions['x'] == card['x'] + ACTION_X - 88 and actions['y'] == card['y'] + old_gap:
|
||||
actions['y'] = card['y'] + ACTION_Y - 75
|
||||
if value['version'] < 15:
|
||||
if value['version'] < 16:
|
||||
migrate_confirmation_layout(result['layouts'][profile], profile, data['widgets'], data['bounds'],
|
||||
extra_height=sources_extent(result) if profile == 'large' else 0)
|
||||
elif not confirmation_layout_valid(result['layouts'][profile], profile, data['widgets'], data['bounds'],
|
||||
extra_height=sources_extent(result) if profile == 'large' else 0):
|
||||
raise ValueError('Speed-limit confirmation overlaps set speed, torque, or screen bounds')
|
||||
place_attached_slc_actions(result['layouts']['large'], PROFILES['large']['bounds'], sources_extent(result))
|
||||
if len(json.dumps(result, separators=(",", ":")).encode()) > MAX_BYTES:
|
||||
raise ValueError("Customization too large")
|
||||
return result
|
||||
@@ -922,7 +807,7 @@ def fit_to_road(document, viewport_width):
|
||||
continue
|
||||
shift = widget.get("anchorShift", 0) * extra
|
||||
width = widget_size(document, "large", key)[0]
|
||||
if (area := widget.get('confirmation')) and placed['enabled'] and layout['speed_limit_actions']['enabled']:
|
||||
if (area := widget.get('confirmation')) and placed['enabled']:
|
||||
width = max(width, area['x'] + area['width'])
|
||||
x = max(30 - shift, min(placed["x"], viewport_width - 30 - width - shift))
|
||||
if x != placed["x"]:
|
||||
|
||||
@@ -119,7 +119,7 @@ class OnroadFavorites:
|
||||
bounds = {}
|
||||
for key, spec in PROFILES['large']['widgets'].items():
|
||||
saved = document['layouts']['large'].get(key)
|
||||
if saved is None or not saved['enabled'] or key in ('pip_left', 'pip_right', 'nav_map', 'torque_bar', 'speed_limit_actions'):
|
||||
if saved is None or not saved['enabled'] or key in ('pip_left', 'pip_right', 'nav_map', 'torque_bar'):
|
||||
continue
|
||||
x = saved['x'] + spec.get('anchorShift', 0) * (state.viewport_width - 1860)
|
||||
y = saved['y']
|
||||
|
||||
@@ -14,7 +14,7 @@ from typing import Protocol
|
||||
|
||||
from openpilot.starpilot.ui.presentation import Profile
|
||||
from openpilot.starpilot.ui.weather import WeatherReading
|
||||
from openpilot.starpilot.ui.large_speed_geometry import ACTION_BOUNDS, LIMIT_RECTS, confirmation_bounds, confirmation_buttons
|
||||
from openpilot.starpilot.ui.large_speed_geometry import LIMIT_RECTS, confirmation_bounds, confirmation_buttons
|
||||
from openpilot.starpilot.ui.appearance_preferences import CameraViewChoice, OnroadAppearance
|
||||
from openpilot.starpilot.curve_speed.status import CurveObservation
|
||||
from openpilot.starpilot.conditional_mode.policy import ModeChoice
|
||||
@@ -92,15 +92,12 @@ class SpeedLimitObservation:
|
||||
presentation_id: int | None = None
|
||||
status: str = ""
|
||||
action_enabled: bool = False
|
||||
action_sequence_id: int = 0
|
||||
action_status: str = ""
|
||||
source_readings: tuple[SourceReading, ...] = ()
|
||||
accepted_adjusted_limit_mps: float | None = None
|
||||
pending_adjusted_limit_mps: float | None = None
|
||||
presentation_adjusted_limit_mps: float | None = None
|
||||
override_basis: str = 'none'
|
||||
retained_override: bool = False
|
||||
action_feedback: str = ''
|
||||
automatic_adoption_pending: bool = False
|
||||
pending_since_ns: int = 0
|
||||
last_received_speed_limit_mps: float | None = None
|
||||
@@ -291,8 +288,7 @@ def manual_slc_confirmation(profile: Profile, state: OnroadState) -> bool:
|
||||
obs.pending_speed_limit_mps is not None and obs.pending_speed_limit_mps > 0 and
|
||||
obs.session_id and obs.decision_id and obs.decision_id > 0 and
|
||||
obs.presentation_id is not None and obs.presentation_id > 0 and
|
||||
placement(state.customization, profile, widget)['enabled'] and
|
||||
placement(state.customization, profile, 'speed_limit_actions')['enabled'])
|
||||
placement(state.customization, profile, widget)['enabled'])
|
||||
|
||||
|
||||
def slc_accept_available(state: OnroadState) -> bool:
|
||||
@@ -302,11 +298,6 @@ def slc_accept_available(state: OnroadState) -> bool:
|
||||
not obs.automatic_adoption_pending))
|
||||
|
||||
|
||||
def slc_action_bounds(profile: Profile, state: OnroadState):
|
||||
dx, dy = offset(state.customization, profile, 'speed_limit_actions')
|
||||
return tuple((left + dx, top + dy, right + dx, bottom + dy) for left, top, right, bottom in ACTION_BOUNDS[profile])
|
||||
|
||||
|
||||
def slc_controls(profile: Profile, state: OnroadState) -> tuple[SlcControl, ...]:
|
||||
if manual_slc_confirmation(profile, state) and state.slc_prompt_open:
|
||||
obs = state.speed_limit
|
||||
@@ -564,8 +555,6 @@ def speed_limit_from_message(message: SlcStateMessage | None) -> SpeedLimitObser
|
||||
session_id=message.sessionId, decision_id=message.decisionId if live or message.hasPending else None,
|
||||
presentation_id=message.presentationId if live or message.hasPending else None, status=message.status,
|
||||
action_enabled=bool(getattr(message, "enabled", False)),
|
||||
action_sequence_id=int(getattr(message, "actionSequenceId", 0)),
|
||||
action_status=str(getattr(message, "actionStatus", "")),
|
||||
automatic_adoption_pending=bool(getattr(message, 'automaticAdoptionPending', False)),
|
||||
pending_since_ns=int(getattr(message, 'pendingSinceMonoTime', 0)),
|
||||
last_received_speed_limit_mps=getattr(message, 'lastReceivedSpeedLimit', 0) or None,
|
||||
|
||||
@@ -1462,12 +1462,6 @@ class StarShellSession:
|
||||
self._mode = mode
|
||||
if mode == ShellMode.ONROAD:
|
||||
snapshot = replace(snapshot, onroad=self.input.onroad.present(snapshot.onroad))
|
||||
if mode == ShellMode.ONROAD and self.slc_actions is not None:
|
||||
observation = snapshot.onroad.speed_limit
|
||||
snapshot = replace(snapshot, onroad=replace(snapshot.onroad, speed_limit=replace(
|
||||
observation, action_feedback=self.slc_actions.feedback(observation))))
|
||||
elif mode != ShellMode.ONROAD and self.slc_actions is not None:
|
||||
self.slc_actions.clear_feedback()
|
||||
rendered = getattr(self, "_rendered_settings", None)
|
||||
if mode == ShellMode.SETTINGS and self.profile == Profile.LARGE and (rendered is None or rendered[1].selected != snapshot.selected):
|
||||
if pane := _FEATURE_SETTINGS_PANES.get(snapshot.selected):
|
||||
|
||||
@@ -38,8 +38,6 @@ class SlcActionDispatcher:
|
||||
self._last_sequence = 0
|
||||
self._last_context: tuple[str, int, int, SlcActionKind] | None = None
|
||||
self._last_context_ns = 0
|
||||
self._feedback_sequence = 0
|
||||
self._feedback_started_ns = 0
|
||||
|
||||
def dispatch(self, request: SlcUiRequest, *, wheel_observed_ns: int = 0) -> bool:
|
||||
if not _positive_number(request.candidate_speed_mps):
|
||||
@@ -105,27 +103,4 @@ class SlcActionDispatcher:
|
||||
self._last_sequence = sequence
|
||||
self._last_context = context
|
||||
self._last_context_ns = now_ns
|
||||
self._feedback_sequence = sequence
|
||||
self._feedback_started_ns = now_ns
|
||||
return True
|
||||
|
||||
def clear_feedback(self):
|
||||
self._feedback_sequence = 0
|
||||
|
||||
def feedback(self, observation) -> str:
|
||||
if observation.session_id != self._session:
|
||||
self._feedback_sequence = 0
|
||||
if not self._feedback_sequence:
|
||||
return ''
|
||||
if (observation.pending_speed_limit_mps is not None and self._last_context is not None and
|
||||
observation.decision_id != self._last_context[1]):
|
||||
self.clear_feedback()
|
||||
return ''
|
||||
age = self.clock() - self._feedback_started_ns
|
||||
if age > 4_000_000_000:
|
||||
self._feedback_sequence = 0
|
||||
return ''
|
||||
if observation.action_sequence_id != self._feedback_sequence:
|
||||
return 'Waiting…' if age < 2_000_000_000 else 'Not confirmed'
|
||||
return {'accept': 'Limit accepted', 'reject': 'Set speed kept', 'adopt': 'Limit adopted'}.get(
|
||||
observation.action_status, 'Not applied')
|
||||
|
||||
@@ -670,7 +670,7 @@ class AppearanceSettingsTests(unittest.TestCase):
|
||||
view.alert.render.assert_called()
|
||||
if profile == Profile.LARGE:
|
||||
self.assertEqual(view.unified_speed.render.call_count, 2)
|
||||
self.assertEqual(slc.call_count, 2)
|
||||
slc.assert_not_called() # No pending limit: feedback draws with the card, not the chooser.
|
||||
view.current_speed.render.assert_called_once()
|
||||
view.steering_wheel.render.assert_called_once()
|
||||
for alert_size in (AlertSize.SMALL, AlertSize.MID, AlertSize.FULL):
|
||||
|
||||
@@ -38,8 +38,8 @@ def test_numeric_subset_is_pinned_and_has_real_tabular_glyphs():
|
||||
assert bounds is not None and bounds[0] > 0
|
||||
|
||||
|
||||
def test_approved_limit_offset_and_action_sizes_fit_actual_fonts():
|
||||
from openpilot.starpilot.ui.large_speed_geometry import ACTION_TEXT_SIZE, LARGE_SIGN_SCALE, LIMIT_RECTS
|
||||
def test_approved_limit_and_offset_sizes_fit_actual_fonts():
|
||||
from openpilot.starpilot.ui.large_speed_geometry import LARGE_SIGN_SCALE, LIMIT_RECTS
|
||||
owns_context = not rl.is_window_ready()
|
||||
if owns_context:
|
||||
rl.init_window(128, 128, "Native speed-group font fixture")
|
||||
@@ -57,13 +57,9 @@ def test_approved_limit_offset_and_action_sizes_fit_actual_fonts():
|
||||
offset_width = b - a
|
||||
width = max(value_width, offset_width) + 20 * scale
|
||||
assert width <= LIMIT_RECTS[profile][2]
|
||||
action_width = 308 if large else 184
|
||||
assert all(fonts.measure(label, FontRole.MEDIUM, ACTION_TEXT_SIZE[profile]).width + 4 <= action_width
|
||||
for label in ('Accept', 'Decline'))
|
||||
ppi = (2160**2 + 1080**2)**.5 / 6 if large else 300
|
||||
for text, role, size, minimum in (('65', FontRole.BOLD, limit_size, 2.5 if large else 2.8),
|
||||
('+5', FontRole.MEDIUM, offset_size, 1.5 if large else 2.0),
|
||||
('H', FontRole.MEDIUM, ACTION_TEXT_SIZE[profile], 2.8)):
|
||||
('+5', FontRole.MEDIUM, offset_size, 1.5 if large else 2.0)):
|
||||
top, bottom = fonts.vertical_ink(text, role, size)
|
||||
assert (bottom - top) * 25.4 / ppi >= minimum
|
||||
finally:
|
||||
@@ -748,22 +744,19 @@ def test_sign_profiles_share_layout_and_keep_aligned_numbers():
|
||||
rl.close_window()
|
||||
|
||||
|
||||
def test_v5_geometry_migrates_and_keeps_custom_actions_independent():
|
||||
def test_v5_geometry_migrates_the_card():
|
||||
doc = default_document()
|
||||
doc['version'] = 5
|
||||
doc['speedSources'] = True
|
||||
doc['layouts']['large']['cruise_limits'].update(x=1550, y=638)
|
||||
doc['layouts']['large']['speed_limit_actions'].update(x=1550, y=954)
|
||||
doc['layouts']['large']['speed_limit_actions'] = {'x': 1550, 'y': 954, 'enabled': True}
|
||||
migrated = validate_document(doc)
|
||||
assert migrated['version'] == 15
|
||||
assert migrated['version'] == 16
|
||||
assert migrated['layouts']['large']['cruise_limits'] == default_document()['layouts']['large']['cruise_limits']
|
||||
assert migrated['layouts']['large']['speed_limit_actions'] == {'x': 1550, 'y': 882, 'enabled': True}
|
||||
assert 'speed_limit_actions' not in migrated['layouts']['large']
|
||||
assert migrated['speedSources'] is True
|
||||
assert doc['layouts']['large']['cruise_limits']['x'] == 1550
|
||||
assert validate_document(migrated) == migrated
|
||||
doc['layouts']['large']['cruise_limits'].update(x=88, y=75)
|
||||
doc['layouts']['large']['speed_limit_actions'].update(x=88, y=447)
|
||||
assert validate_document(doc)['layouts']['large']['speed_limit_actions']['y'] == 449
|
||||
|
||||
|
||||
def test_pending_choices_use_the_sign_with_separated_horizontal_targets():
|
||||
@@ -779,11 +772,11 @@ def test_projection_v1_layout_migrates_without_losing_other_widgets():
|
||||
viewport = (2880, 1080)
|
||||
doc = default_layout_for_viewport(viewport)
|
||||
doc['version'] = 1
|
||||
doc['widgets']['speed_limit_actions'].update(x=88, y=447)
|
||||
doc['widgets']['speed_limit_actions'] = {'x': 88, 'y': 447, 'enabled': True}
|
||||
doc['widgets']['current_speed'].update(x=1400, y=100)
|
||||
migrated = validate_layout_for_viewport(doc, viewport)
|
||||
assert migrated['version'] == 7
|
||||
assert migrated['widgets']['speed_limit_actions']['y'] == 325
|
||||
assert 'speed_limit_actions' not in migrated['widgets']
|
||||
assert migrated['widgets']['current_speed'] == doc['widgets']['current_speed']
|
||||
assert validate_layout_for_viewport(migrated, viewport) == migrated
|
||||
|
||||
@@ -793,12 +786,12 @@ def test_committed_projection_v1_right_edge_is_preserved_and_clamped():
|
||||
doc = default_layout_for_viewport(viewport)
|
||||
doc['version'] = 1
|
||||
doc['widgets']['cruise_limits'].update(x=1654, y=75)
|
||||
doc['widgets']['speed_limit_actions'].update(x=1654, y=500)
|
||||
doc['widgets']['speed_limit_actions'] = {'x': 1654, 'y': 500, 'enabled': True}
|
||||
migrated = validate_layout_for_viewport(doc, viewport)
|
||||
card = migrated['widgets']['cruise_limits']
|
||||
assert confirmation_bounds('large', card['x'], card['y'], opened=True)[2] <= 1830
|
||||
assert confirmation_bounds('large', card['x']+1, card['y'], opened=True)[2] > 1830
|
||||
assert migrated['widgets']['speed_limit_actions'] == {'x': 1510, 'y': 500, 'enabled': True}
|
||||
assert 'speed_limit_actions' not in migrated['widgets']
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ from openpilot.starpilot.ui.onroad import axis_status_color, driving_mode_descri
|
||||
from openpilot.starpilot.ui.onroad_cem_gauge import gauge_data
|
||||
from openpilot.starpilot.ui.onroad_customization import PROFILES, default_document
|
||||
from openpilot.starpilot.ui.onroad_dm import monitor_visible
|
||||
from openpilot.starpilot.ui.onroad_state import slc_controls
|
||||
from openpilot.starpilot.ui.presentation import Profile
|
||||
from openpilot.starpilot.ui.unified_speed_presentation import resolve_unified_speed
|
||||
|
||||
@@ -48,7 +47,6 @@ def test_every_scene_matches_native_border_mode_and_widget_visibility(target):
|
||||
if move and profile == Profile.COMPACT:
|
||||
layout['driver_monitor'].update(x=200, y=100)
|
||||
layout['speed_limit'].update(x=200, y=100)
|
||||
layout['speed_limit_actions'].update(x=16, y=0)
|
||||
result = subprocess.run([node, '--input-type=module', '-e', script], input=json.dumps({
|
||||
'profile': str(profile), 'layout': layout, 'widgets': PROFILES[str(profile)]['widgets'], 'ids': sorted(ids),
|
||||
}), text=True, capture_output=True, check=True)
|
||||
@@ -64,7 +62,6 @@ def test_every_scene_matches_native_border_mode_and_widget_visibility(target):
|
||||
if scene['id'] != 'general':
|
||||
expected['stopped_timer'] = state.stopped_duration_s is None
|
||||
expected['torque_bar'] = not state.lateral_active
|
||||
expected['speed_limit_actions'] = scene['id'] in ('slc_pending', 'slc_notice') or not slc_controls(profile, state)
|
||||
if profile == Profile.LARGE:
|
||||
expected['cem_gauge'] = gauge_data(state) is None
|
||||
else:
|
||||
|
||||
@@ -331,10 +331,10 @@ def test_default_cem_gauge_keeps_left_column_with_personality_monitor_pair(proje
|
||||
else:
|
||||
widgets = customization_metadata()['profiles']['large']['widgets']
|
||||
layout = default_document()['layouts']['large']
|
||||
gauge, monitor, actions = (layout[key] for key in (CEM_GAUGE_WIDGET, 'driver_monitor', 'speed_limit_actions'))
|
||||
gauge, monitor, card = (layout[key] for key in (CEM_GAUGE_WIDGET, 'driver_monitor', 'cruise_limits'))
|
||||
personality = layout['following_distance']
|
||||
assert gauge['x'] + widgets[CEM_GAUGE_WIDGET]['width'] / 2 == 184
|
||||
assert personality['x'] + widgets['following_distance']['width'] + 32 == monitor['x']
|
||||
assert personality['y'] + widgets['following_distance']['height'] / 2 == monitor['y'] + monitor['size'] / 2
|
||||
assert actions['y'] + widgets['speed_limit_actions']['height'] < gauge['y']
|
||||
assert card['y'] + widgets['cruise_limits']['height'] < gauge['y']
|
||||
assert gauge['y'] + widgets[CEM_GAUGE_WIDGET]['height'] < monitor['y']
|
||||
|
||||
@@ -54,24 +54,43 @@ def test_v12_portrait_upgrade_preserves_preferences_and_is_idempotent():
|
||||
before = copy.deepcopy(old)
|
||||
updated = validate_document(old)
|
||||
expected = copy.deepcopy(old)
|
||||
expected['version'] = 15
|
||||
expected['version'] = 16
|
||||
expected['layouts']['compact']['speed_limit'].update(x=320, y=16)
|
||||
assert old == before and updated == expected
|
||||
assert validate_document(updated) == updated
|
||||
|
||||
|
||||
def test_v12_edge_placements_remain_bounded_even_with_confirmation_disabled():
|
||||
def test_v12_layout_that_hid_speed_limit_actions_makes_room_for_the_sign_chooser():
|
||||
old = default_document()
|
||||
old['version'] = 12
|
||||
for layout in old['layouts'].values():
|
||||
layout['speed_limit_actions']['enabled'] = False
|
||||
layout['speed_limit_actions'] = {'x': 0, 'y': 0, 'enabled': False}
|
||||
old['layouts']['large']['cruise_limits']['y'] = 882
|
||||
old['layouts']['compact']['speed_limit'].update(x=358, y=108)
|
||||
updated = validate_document(old)
|
||||
assert updated['layouts']['large']['cruise_limits']['y'] == 798
|
||||
assert updated['layouts']['compact']['speed_limit'] == {'x': 348, 'y': 96, 'enabled': True}
|
||||
assert updated['layouts']['large']['cruise_limits'] == default_document()['layouts']['large']['cruise_limits']
|
||||
assert updated['layouts']['compact']['speed_limit'] == {'x': 320, 'y': 16, 'enabled': True}
|
||||
assert validate_document(updated) == updated
|
||||
assert all(not layout['speed_limit_actions']['enabled'] for layout in updated['layouts'].values())
|
||||
assert all('speed_limit_actions' not in layout for layout in updated['layouts'].values())
|
||||
|
||||
|
||||
def test_v15_drops_speed_limit_actions_and_keeps_everything_else():
|
||||
import copy
|
||||
current = default_document()
|
||||
current['layouts']['large']['current_speed'].update(x=700, enabled=False)
|
||||
current['widgetOrder'] = {profile: list(order) for profile, order in DEFAULT_WIDGET_ORDER.items()}
|
||||
old = copy.deepcopy(current)
|
||||
old['version'] = 15
|
||||
for profile, layout in old['layouts'].items():
|
||||
layout['speed_limit_actions'] = {'x': 146, 'y': 44, 'enabled': False}
|
||||
old['widgetColors'][profile]['speed_limit_actions'] = {'text': '#12345678'}
|
||||
old['widgetOrder'][profile].insert(1, 'speed_limit_actions')
|
||||
before = copy.deepcopy(old)
|
||||
assert validate_document(old) == current
|
||||
assert old == before
|
||||
current['layouts']['large']['speed_limit_actions'] = {'x': 146, 'y': 44, 'enabled': True}
|
||||
with pytest.raises(ValueError, match='widget IDs'):
|
||||
validate_document(current)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('sign_y', [12, 16, 20])
|
||||
@@ -86,7 +105,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'] = 15
|
||||
expected['version'] = 16
|
||||
expected['layouts']['compact']['speed_limit']['y'] = min(sign_y, 16)
|
||||
assert old == before and updated == expected
|
||||
assert validate_document(updated) == updated
|
||||
@@ -97,21 +116,6 @@ def test_compact_notice_is_reserved_even_when_the_shorter_buttons_would_fit():
|
||||
document['layouts']['compact']['speed_limit']['y'] = 20
|
||||
with pytest.raises(ValueError, match='confirmation'):
|
||||
validate_document(document)
|
||||
document['layouts']['compact']['speed_limit_actions']['enabled'] = False
|
||||
assert validate_document(document) == document
|
||||
|
||||
|
||||
@pytest.mark.parametrize('separate', [False, True])
|
||||
def test_v12_source_attachment_follows_the_new_row_without_moving_custom_actions(separate):
|
||||
old = default_document()
|
||||
old.update(version=12, speedSources=True, speedSourcesCard=separate)
|
||||
actions = old['layouts']['large']['speed_limit_actions']
|
||||
actions['y'] = 367 if separate else 359
|
||||
updated = validate_document(old)
|
||||
assert updated['layouts']['large']['speed_limit_actions']['y'] == (457 if separate else 449)
|
||||
assert validate_document(updated) == updated
|
||||
actions.update(x=600, y=400)
|
||||
assert validate_document(old)['layouts']['large']['speed_limit_actions'] == actions
|
||||
|
||||
|
||||
def test_current_portrait_layout_rejects_a_chooser_outside_the_compact_screen():
|
||||
@@ -155,22 +159,18 @@ def test_personality_upgrade_adds_large_widget_without_losing_saved_layout(custo
|
||||
@pytest.mark.parametrize('version', (10, 11))
|
||||
@pytest.mark.parametrize('separate', (False, True))
|
||||
@pytest.mark.parametrize('lower', (False, True))
|
||||
def test_source_attachment_saves_real_bounded_positions_without_changing_input(version, separate, lower):
|
||||
def test_sources_keep_the_card_on_screen_without_changing_input(version, separate, lower):
|
||||
import copy
|
||||
from openpilot.starpilot.ui.onroad_customization import placement
|
||||
document = default_document()
|
||||
document.update(version=version, speedSources=True, speedSourcesCard=separate)
|
||||
if lower:
|
||||
document['layouts']['large']['cruise_limits']['y'] = 690
|
||||
document['layouts']['large']['speed_limit_actions']['y'] = 882
|
||||
before = copy.deepcopy(document)
|
||||
saved = validate_document(document)
|
||||
card, actions = (saved['layouts']['large'][key] for key in ('cruise_limits', 'speed_limit_actions'))
|
||||
card = saved['layouts']['large']['cruise_limits']
|
||||
assert document == before and validate_document(saved) == saved
|
||||
assert placement(saved, 'large', 'speed_limit_actions') == actions
|
||||
assert actions['y'] == card['y'] + widget_size(saved, 'large', 'cruise_limits')[1] + 8
|
||||
assert actions['y'] + widget_size(saved, 'large', 'speed_limit_actions')[1] <= 1050
|
||||
assert actions['y'] == (457 if separate else 449)
|
||||
# A low card's chooser would cover the torque bar, so it returns to its default.
|
||||
assert card == default_document()['layouts']['large']['cruise_limits']
|
||||
|
||||
|
||||
def test_v7_speed_layout_migration_is_bounded_non_mutating_and_idempotent():
|
||||
@@ -183,7 +183,6 @@ def test_v7_speed_layout_migration_is_bounded_non_mutating_and_idempotent():
|
||||
document['layouts'][profile][key].update(x=x, y=y)
|
||||
document['layouts']['large']['cem_gauge'].update(x=480, y=99)
|
||||
document['layouts']['large']['cruise_limits']['x'] = 1510
|
||||
document['layouts']['large']['speed_limit_actions'].update(x=1510, y=900)
|
||||
document['layouts']['compact']['max_speed']['y'] = 60
|
||||
document['layouts']['compact']['speed_limit'].update(x=330, y=20)
|
||||
document['layouts']['large']['current_speed'].update(x=700, y=100, enabled=False)
|
||||
@@ -192,9 +191,8 @@ 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'] == 15 and validate_document(migrated) == migrated
|
||||
assert migrated['version'] == 16 and validate_document(migrated) == migrated
|
||||
assert migrated['layouts']['large']['cruise_limits']['x'] == 1391
|
||||
assert migrated['layouts']['large']['speed_limit_actions'] == {'x': 1510, 'y': 882, 'enabled': True}
|
||||
assert migrated['layouts']['large']['current_speed'] == original['layouts']['large']['current_speed']
|
||||
assert migrated['layouts']['large']['cem_gauge'] == {'x': 56, 'y': 536, 'enabled': True}
|
||||
assert migrated['layouts']['compact']['speed_limit']['x'] == 320
|
||||
@@ -222,14 +220,13 @@ 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'] == 15 and validate_document(migrated) == migrated
|
||||
assert migrated['version'] == 16 and validate_document(migrated) == migrated
|
||||
assert migrated['layouts']['large'] == document['layouts']['large']
|
||||
assert migrated['widgetColors'] == document['widgetColors']
|
||||
assert migrated['widgetOrder'] == document['widgetOrder']
|
||||
expected = document['layouts']['compact']['speed_limit'] if custom else {'x': 320, 'y': 16, 'enabled': True}
|
||||
assert migrated['layouts']['compact']['speed_limit'] == expected
|
||||
assert migrated['layouts']['compact']['max_speed']['x'] == 0
|
||||
assert migrated['layouts']['compact']['speed_limit_actions'] == {'x': 146, 'y': 44, 'enabled': True}
|
||||
assert migrated['layouts']['compact']['max_speed']['x'] == (50 if custom else 0)
|
||||
|
||||
|
||||
def test_v8_compact_speed_widgets_at_old_edges_stay_in_bounds_after_upgrade():
|
||||
@@ -246,15 +243,14 @@ def test_v8_compact_speed_widgets_at_old_edges_stay_in_bounds_after_upgrade():
|
||||
assert validate_document(migrated) == migrated
|
||||
|
||||
|
||||
def test_v8_actionless_layout_preserves_customizations_when_adding_compact_actions():
|
||||
def test_v8_layout_without_rails_preserves_customizations():
|
||||
import copy
|
||||
from openpilot.starpilot.ui.onroad_customization import COMPACT_SPEED_LAYOUT_V8, RAIL_WIDGETS
|
||||
document = default_document()
|
||||
document['version'] = 8
|
||||
for key, (_, _, x, y) in COMPACT_SPEED_LAYOUT_V8.items():
|
||||
document['layouts']['compact'][key].update(x=x, y=y)
|
||||
large_actions = document['layouts']['large'].pop('speed_limit_actions')
|
||||
for key in ('speed_limit_actions', *RAIL_WIDGETS):
|
||||
for key in RAIL_WIDGETS:
|
||||
del document['layouts']['compact'][key]
|
||||
document['layouts']['large']['current_speed']['x'] = 700
|
||||
document['layouts']['compact']['speed_limit'].update(x=100, y=40)
|
||||
@@ -263,10 +259,9 @@ def test_v8_actionless_layout_preserves_customizations_when_adding_compact_actio
|
||||
original = copy.deepcopy(document)
|
||||
migrated = validate_document(document)
|
||||
assert document == original
|
||||
assert migrated['version'] == 15 and validate_document(migrated) == migrated
|
||||
assert migrated['layouts']['large'] == {**original['layouts']['large'], 'speed_limit_actions': large_actions}
|
||||
assert migrated['version'] == 16 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['layouts']['compact']['speed_limit_actions'] == {'x': 146, 'y': 44, 'enabled': True}
|
||||
assert migrated['palette'] == original['palette']
|
||||
assert migrated['widgetColors'] == original['widgetColors']
|
||||
|
||||
@@ -300,22 +295,22 @@ def test_clock_format_preference_defaults_migrates_and_validates():
|
||||
validate_document(document)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("widget,x,y", [("max_speed", 174, 25), ("steering_wheel", 174, 137)])
|
||||
def test_protected_compact_actions_reject_actual_overlap(widget, x, y):
|
||||
def test_old_compact_action_area_is_free_but_set_speed_stays_clear_of_the_chooser():
|
||||
document = default_document()
|
||||
document["layouts"]["compact"][widget].update(x=x, y=y)
|
||||
with pytest.raises(ValueError, match="protected"):
|
||||
document["layouts"]["compact"]["steering_wheel"].update(x=174, y=137)
|
||||
assert validate_document(document) == document
|
||||
document["layouts"]["compact"]["max_speed"].update(x=174, y=25)
|
||||
with pytest.raises(ValueError, match="confirmation"):
|
||||
validate_document(document)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("widget,x,y", [("speed_limit", 320, 16), ("max_speed", 0, 0), ("steering_wheel", 78, 174)])
|
||||
def test_protected_zone_edge_touch_is_valid(widget, x, y):
|
||||
def test_compact_edge_placements_are_valid(widget, x, y):
|
||||
document = default_document()
|
||||
document["layouts"]["compact"][widget].update(x=x, y=y)
|
||||
assert validate_document(document) == document
|
||||
zones = customization_metadata()["profiles"]["compact"]["reservedZones"]
|
||||
assert zones == []
|
||||
assert customization_metadata()["profiles"]["compact"]["protectedWidget"] == "speed_limit_actions"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", [
|
||||
@@ -348,7 +343,6 @@ def test_mode_widget_defaults_off_without_resetting_saved_layouts():
|
||||
key = 'driving_mode_descriptions'
|
||||
document = default_document()
|
||||
document['layouts']['large']['current_speed'].update(x=700, y=100, enabled=False)
|
||||
document['layouts']['compact']['speed_limit_actions']['y'] = 44
|
||||
for layout in document['layouts'].values():
|
||||
assert layout.pop(key)['enabled'] is False
|
||||
migrated = validate_document(document)
|
||||
@@ -358,10 +352,6 @@ def test_mode_widget_defaults_off_without_resetting_saved_layouts():
|
||||
assert migrated['layouts'][profile][key]['enabled'] is False
|
||||
migrated['layouts']['large'][key].update(enabled=True, x=300, y=600)
|
||||
assert validate_document(migrated) == migrated
|
||||
migrated['layouts']['compact'][key]['enabled'] = True
|
||||
migrated['layouts']['compact'][key]['y'] = 130
|
||||
with pytest.raises(ValueError, match='protected speed limit actions'):
|
||||
validate_document(migrated)
|
||||
|
||||
|
||||
def test_saved_valid_layouts_survive_independently():
|
||||
@@ -382,7 +372,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"] == 15
|
||||
assert migrated["version"] == 16
|
||||
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}
|
||||
@@ -402,7 +392,6 @@ def test_pre_action_saved_layout_migrates_without_losing_positions_or_palette(re
|
||||
for key in ("model_confidence", "conditional_mode", "following_distance"):
|
||||
del document["layouts"]["compact"][key]
|
||||
for layout in document["layouts"].values():
|
||||
del layout["speed_limit_actions"]
|
||||
del layout["steering_wheel"]["size"]
|
||||
for key in removed:
|
||||
del layout[key]
|
||||
@@ -416,25 +405,12 @@ def test_pre_action_saved_layout_migrates_without_losing_positions_or_palette(re
|
||||
assert migrated["layouts"][profile][key] == {
|
||||
**position, **({"size": customization_metadata()["profiles"][profile]["widgets"][key]["width"]}
|
||||
if key == "steering_wheel" else {})}
|
||||
assert migrated["layouts"]["large"]["speed_limit_actions"] == {"x": 312, "y": 425, "enabled": False}
|
||||
assert migrated["layouts"]["compact"]["speed_limit_actions"] == default_document()["layouts"]["compact"]["speed_limit_actions"]
|
||||
|
||||
|
||||
def test_malformed_pre_action_cruise_placement_is_rejected():
|
||||
document = default_document()
|
||||
for key in ("model_confidence", "conditional_mode", "following_distance"):
|
||||
del document["layouts"]["compact"][key]
|
||||
for layout in document["layouts"].values():
|
||||
del layout["speed_limit_actions"]
|
||||
document["layouts"]["large"]["cruise_limits"]["x"] = "moved"
|
||||
with pytest.raises(ValueError, match="Invalid widget placement"):
|
||||
validate_document(document)
|
||||
|
||||
|
||||
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": 15', '"version": 11, "version": 11').encode()
|
||||
raw = json.dumps(document).replace('"version": 16', '"version": 11, "version": 11').encode()
|
||||
with patch("openpilot.starpilot.ui.onroad_customization.read_saved", return_value=(raw, True)):
|
||||
assert read_customization(Mock()) == default_document()
|
||||
|
||||
@@ -446,27 +422,15 @@ def test_v9_large_sign_migration_preserves_customizations_and_clamps_bottom_edge
|
||||
old['version'] = 9
|
||||
old['speedSources'] = sources
|
||||
old['layouts']['large']['cruise_limits'].update(y=918)
|
||||
old['layouts']['large']['speed_limit_actions'].update(x=250, y=400)
|
||||
before = deepcopy(old)
|
||||
updated = validate_document(old)
|
||||
assert old == before
|
||||
assert updated['version'] == 15
|
||||
assert updated['version'] == 16
|
||||
assert updated['layouts']['large']['cruise_limits']['y'] == default_document()['layouts']['large']['cruise_limits']['y']
|
||||
assert updated['layouts']['large']['speed_limit_actions'] == before['layouts']['large']['speed_limit_actions']
|
||||
assert updated['layouts']['compact'] == before['layouts']['compact']
|
||||
assert validate_document(updated) == updated
|
||||
|
||||
|
||||
def test_v9_moves_only_actions_paired_with_the_old_large_speed_group():
|
||||
old = default_document()
|
||||
old['version'] = 9
|
||||
old['layouts']['large']['cruise_limits'].update(x=188, y=95)
|
||||
old['layouts']['large']['speed_limit_actions'].update(x=200, y=268)
|
||||
updated = validate_document(old)
|
||||
assert updated['layouts']['large']['speed_limit_actions'] == {'x': 212, 'y': 345, 'enabled': True}
|
||||
assert validate_document(updated) == updated
|
||||
|
||||
|
||||
def test_wheel_hit_edges_match_default_draw_bounds():
|
||||
emit = Mock()
|
||||
inputs = OnroadInput(emit)
|
||||
@@ -505,16 +469,15 @@ def test_resized_wheel_draw_and_touch_share_large_bounds():
|
||||
assert emit.call_count == 2
|
||||
|
||||
|
||||
def test_compact_resize_rejects_protected_overlap_and_other_widget_sizes():
|
||||
def test_compact_resize_and_other_widget_sizes():
|
||||
document = default_document()
|
||||
document["layouts"]["compact"]["steering_wheel"].update(size=70, y=52)
|
||||
assert validate_document(document) == document
|
||||
assert widget_size(document, "compact", "steering_wheel") == (70, 70)
|
||||
document["layouts"]["compact"]["steering_wheel"].update(x=150, y=150)
|
||||
with pytest.raises(ValueError, match="protected"):
|
||||
validate_document(document)
|
||||
assert validate_document(document) == document
|
||||
document = default_document()
|
||||
document["layouts"]["compact"]["speed_limit_actions"]["size"] = 70
|
||||
document["layouts"]["compact"]["max_speed"]["size"] = 70
|
||||
with pytest.raises(ValueError, match="placement"):
|
||||
validate_document(document)
|
||||
|
||||
@@ -655,7 +618,6 @@ def test_saved_six_widget_layout_adds_only_default_rail_positions():
|
||||
document = default_document()
|
||||
for key in ("model_confidence", "conditional_mode", "following_distance"):
|
||||
del document["layouts"]["compact"][key]
|
||||
document["layouts"]["compact"]["speed_limit_actions"].update(x=162, enabled=False)
|
||||
document["palette"]["text"] = "#ABCD1234"
|
||||
migrated = validate_document(document)
|
||||
assert migrated["palette"] == document["palette"]
|
||||
@@ -682,9 +644,6 @@ def test_movable_rail_keeps_limits_and_does_not_cover_active_alerts():
|
||||
widget._conditional.reset_mock()
|
||||
widget.render(rl.Rectangle(0, 0, 536, 240), road(document, alert=OnroadAlert(size=AlertSize.FULL)))
|
||||
widget._conditional.assert_not_called()
|
||||
document["layouts"]["compact"]["conditional_mode"].update(x=200, y=107)
|
||||
with pytest.raises(ValueError, match="protected"):
|
||||
validate_document(document)
|
||||
document["layouts"]["compact"]["conditional_mode"].update(x=477, y=0)
|
||||
with pytest.raises(ValueError, match="bounds"):
|
||||
validate_document(document)
|
||||
@@ -706,7 +665,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'] == 15
|
||||
assert result['version'] == 16
|
||||
assert result['palette'] == old['palette']
|
||||
for profile, layout in old['layouts'].items():
|
||||
for key, position in layout.items():
|
||||
@@ -822,11 +781,10 @@ def test_driver_frame_matches_native_preview_and_keeps_face_renderer_separate(mo
|
||||
|
||||
|
||||
@pytest.mark.parametrize("enabled", [True, False])
|
||||
def test_small_sign_action_overlap_roundtrips_without_hiding_sign(enabled):
|
||||
def test_small_sign_roundtrips_without_hiding_sign(enabled):
|
||||
document = default_document()
|
||||
large = json.loads(json.dumps(document["layouts"]["large"]))
|
||||
document["layouts"]["compact"]["speed_limit"].update(x=320, y=16, enabled=enabled)
|
||||
document["layouts"]["compact"]["speed_limit_actions"].update(x=150, y=44)
|
||||
assert decode_document(json.dumps(validate_document(document))) == document
|
||||
assert document["layouts"]["large"] == large
|
||||
observation = SpeedLimitObservation(kind=ObservationKind.VALID, speed_limit_mps=20,
|
||||
@@ -840,7 +798,6 @@ def test_overlapping_sign_stays_visible_and_chooser_keeps_exact_input():
|
||||
from openpilot.starpilot.ui.onroad_state import SlcActionKind
|
||||
from openpilot.starpilot.ui.tests.test_slc_ui_actions import tap_sign, tap_control
|
||||
document = default_document()
|
||||
document['layouts']['compact']['speed_limit_actions'].update(x=150, y=44)
|
||||
observation = SpeedLimitObservation(kind=ObservationKind.VALID, speed_limit_mps=20,
|
||||
pending_speed_limit_mps=15, session_id='drive', decision_id=1,
|
||||
presentation_id=2, action_enabled=True)
|
||||
@@ -1009,7 +966,7 @@ def test_big_widgets_can_use_the_space_a_hidden_sidebar_adds():
|
||||
# Every widget reaches the right edge of the full screen, and not past it.
|
||||
for key in widgets:
|
||||
document = default_document()
|
||||
document["layouts"]["large"]["speed_limit_actions"]["enabled"] = False
|
||||
document["layouts"]["large"]["cruise_limits"]["enabled"] = False
|
||||
placed, width = document["layouts"]["large"][key], widget_size(document, "large", key)[0]
|
||||
placed["x"] = 2130 - width - ANCHOR_SHIFT.get(key, 0) * 300
|
||||
validate_document(document)
|
||||
@@ -1023,7 +980,7 @@ def test_every_large_widget_reaches_each_corner_and_fits_when_sidebar_returns(ri
|
||||
from openpilot.starpilot.ui.onroad_customization import ANCHOR_SHIFT, PROFILES, fit_to_road
|
||||
for key in PROFILES["large"]["widgets"]:
|
||||
document = default_document()
|
||||
document["layouts"]["large"]["speed_limit_actions"]["enabled"] = False
|
||||
document["layouts"]["large"]["cruise_limits"]["enabled"] = False
|
||||
width, height = widget_size(document, "large", key)
|
||||
shift = ANCHOR_SHIFT.get(key, 0) * 300
|
||||
x, y = (2130 - width if right else 30) - shift, 1050 - height if bottom else 30
|
||||
|
||||
@@ -54,7 +54,7 @@ class TestDriverMonitor(unittest.TestCase):
|
||||
def test_known_old_layout_migrates_without_losing_palette_positions_or_visibility(self):
|
||||
old = default_document()
|
||||
for layout in old['layouts'].values():
|
||||
for key in ('driver_monitor', 'torque_bar', 'speed_limit_actions', 'model_confidence', 'conditional_mode', 'following_distance'):
|
||||
for key in ('driver_monitor', 'torque_bar', 'model_confidence', 'conditional_mode', 'following_distance'):
|
||||
layout.pop(key, None)
|
||||
old['palette']['text'] = '#12345678'
|
||||
old['layouts']['large']['steering_wheel'].update(x=500.5, y=600.25, enabled=False)
|
||||
@@ -285,7 +285,7 @@ class TestDriverMonitor(unittest.TestCase):
|
||||
|
||||
old = default_document()
|
||||
for layout in old['layouts'].values():
|
||||
for key in ('driver_monitor', 'torque_bar', 'speed_limit_actions', 'model_confidence', 'conditional_mode', 'following_distance'):
|
||||
for key in ('driver_monitor', 'torque_bar', 'model_confidence', 'conditional_mode', 'following_distance'):
|
||||
layout.pop(key, None)
|
||||
old['palette']['text'] = '#12345678'
|
||||
old['layouts']['large']['current_speed'].update(x=700.5, y=200.25)
|
||||
|
||||
@@ -134,9 +134,7 @@ def test_slc_decision_keeps_its_touch_priority_only_where_it_overlaps():
|
||||
pending = SpeedLimitObservation(kind=ObservationKind.VALID, source='map', speed_limit_mps=22., pending_speed_limit_mps=22.,
|
||||
session_id='s', decision_id=1, presentation_id=1, action_enabled=True)
|
||||
observed = replace(state(), slc_prompt_open=True, longitudinal_active=True, speed_limit=pending)
|
||||
observed.customization['layouts']['compact']['speed_limit_actions']['y'] = 180
|
||||
assert card.bounds(observed) is None # The chooser now follows the sign, not this old action placement.
|
||||
observed.customization['layouts']['compact']['speed_limit_actions']['y'] = 4
|
||||
assert card.bounds(observed) is None
|
||||
observed.customization['layouts']['compact']['max_speed']['y'] = 58
|
||||
assert card.bounds(observed) is None
|
||||
assert card.bounds(replace(observed, longitudinal_active=False)) is not None # No confirmation chooser while LONG is disengaged.
|
||||
|
||||
@@ -222,10 +222,9 @@ def test_pending_confirmation_omits_redundant_speed_heading():
|
||||
assert [call.args[0] for call in foreground_calls(view.fonts.draw)] == ['NEW LIMIT', 'ACCEPT', '35', 'REJECT', 'NEW LIMIT']
|
||||
|
||||
|
||||
def test_compact_pending_label_and_button_follow_saved_action_placement():
|
||||
def test_compact_pending_label_and_buttons_follow_the_sign():
|
||||
from openpilot.starpilot.ui.onroad_state import slc_controls
|
||||
document = default_document()
|
||||
document['layouts']['compact']['speed_limit_actions']['x'] = 120
|
||||
observation = SpeedLimitObservation(kind=ObservationKind.VALID, speed_limit_mps=20,
|
||||
pending_speed_limit_mps=15, session_id='drive', decision_id=4,
|
||||
presentation_id=5, action_enabled=True)
|
||||
|
||||
@@ -6,7 +6,7 @@ from unittest.mock import patch
|
||||
import numpy as np
|
||||
from openpilot.starpilot.ui.raylib import rl
|
||||
|
||||
from openpilot.starpilot.ui.onroad_customization import PROFILES, default_document, validate_document, widget_size
|
||||
from openpilot.starpilot.ui.onroad_customization import PROFILES, default_document, validate_document
|
||||
from openpilot.starpilot.ui.onroad_state import OnroadState, SpeedLimitObservation
|
||||
from openpilot.starpilot.ui.onroad_torque import TorqueBarWidget
|
||||
from openpilot.starpilot.ui.tests.test_onroad_torque_draw import record_gpu
|
||||
@@ -97,22 +97,6 @@ class TestTorqueLayout(unittest.TestCase):
|
||||
self.assertLessEqual(dx + dot_radius, right)
|
||||
self.assertLessEqual(dy + dot_radius, bottom)
|
||||
|
||||
def test_only_torque_underlay_can_overlap_reserved_actions(self):
|
||||
document = default_document()
|
||||
self.assertEqual(validate_document(document), document)
|
||||
document['layouts']['compact']['torque_bar'].update(x=174, y=179)
|
||||
validate_document(document)
|
||||
for key in ('max_speed', 'driver_monitor', 'steering_wheel'):
|
||||
with self.subTest(key=key):
|
||||
invalid = default_document()
|
||||
actions = invalid['layouts']['compact']['speed_limit_actions']
|
||||
_, height = widget_size(invalid, 'compact', key)
|
||||
invalid['layouts']['compact'][key].update(x=actions['x'] - widget_size(invalid, 'compact', key)[0], y=min(actions['y'], 240 - height))
|
||||
self.assertEqual(validate_document(invalid), invalid) # Touching edges do not overlap.
|
||||
invalid['layouts']['compact'][key]['x'] += 1
|
||||
with self.assertRaises(ValueError):
|
||||
validate_document(invalid)
|
||||
|
||||
def test_complete_old_three_and_four_widget_shapes_migrate(self):
|
||||
for count in (3, 4):
|
||||
document = default_document()
|
||||
@@ -120,7 +104,6 @@ class TestTorqueLayout(unittest.TestCase):
|
||||
del document['layouts']['compact'][key]
|
||||
for layout in document['layouts'].values():
|
||||
del layout['torque_bar']
|
||||
del layout['speed_limit_actions']
|
||||
if count == 3:
|
||||
del layout['driver_monitor']
|
||||
document['palette']['text'] = '#12345678'
|
||||
@@ -133,13 +116,11 @@ class TestTorqueLayout(unittest.TestCase):
|
||||
for key, placement in layout.items():
|
||||
self.assertEqual(result['layouts'][profile][key], placement)
|
||||
self.assertEqual(result['layouts'][profile]['torque_bar'], default_document()['layouts'][profile]['torque_bar'])
|
||||
self.assertEqual(result['layouts'][profile]['speed_limit_actions'], default_document()['layouts'][profile]['speed_limit_actions'])
|
||||
|
||||
def test_mixed_legacy_shape_is_rejected(self):
|
||||
document = default_document()
|
||||
for layout in document['layouts'].values():
|
||||
del layout['torque_bar']
|
||||
del layout['speed_limit_actions']
|
||||
del document['layouts']['large']['driver_monitor']
|
||||
with self.assertRaises(ValueError):
|
||||
validate_document(document)
|
||||
|
||||
@@ -101,7 +101,7 @@ def test_live_compositor_keeps_widgets_below_the_shelf_and_alerts_above_it(monke
|
||||
monkeypatch.setattr(onroad, 'render_large_half_borders', lambda *args: None)
|
||||
monkeypatch.setattr(onroad, 'render_corner_hint', draw('corner'))
|
||||
onroad.OnroadView._large(view, drawer.present(state))
|
||||
for widget in ('cem_gauge', 'current_speed', 'driver_monitor', 'steering_wheel', 'torque_bar', 'timer', 'guidance'):
|
||||
for widget in ('unified_speed', 'cem_gauge', 'current_speed', 'driver_monitor', 'steering_wheel', 'torque_bar', 'timer'):
|
||||
assert seen.index(widget) < seen.index('shelf')
|
||||
assert seen.index('shelf') < seen.index('alert') < seen.index('border')
|
||||
assert 'corner' not in seen
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user