Restore explicit guarded Excessive Actuation recovery in both native UIs

Add the missing compact acknowledgement action and confirm recovery in both UIs. Require fresh ignition-off noOutput Panda and stopped-device evidence, preserving the persistent safety latch until explicit acknowledgement. Qualify with 47 focused tests and native headless renders.
This commit is contained in:
Dom
2026-11-18 11:19:52 -06:00
parent b47931d71d
commit cfb0cd61d1
7 changed files with 244 additions and 4 deletions
@@ -17,6 +17,11 @@ from openpilot.system.ui.widgets.scroller import Scroller
from openpilot.system.ui.lib.application import gui_app, FontWeight, TextAlignment, TextAlignmentVertical
from openpilot.system.ui.lib.multilang import tr
from openpilot.starpilot.drive_state.evidence import PhysicalSource
from openpilot.starpilot.ui.actuation_recovery import acknowledge, KEY
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog, BigDialog
REFRESH_INTERVAL = 5.0 # seconds
@@ -206,6 +211,7 @@ class MiciOffroadAlerts(Scroller):
# Create vertical scroller
super().__init__(horizontal=False, spacing=12, pad=0)
self.params = Params()
self._actuation_physical = PhysicalSource(ui_state.sm)
self.sorted_alerts: list[AlertData] = []
self.alert_items: list[AlertItem] = []
@@ -258,9 +264,19 @@ class MiciOffroadAlerts(Scroller):
# Create alert item widget
alert_item = AlertItem(alert_data)
if key == KEY:
alert_item.set_click_callback(self._acknowledge_actuation)
self.alert_items.append(alert_item)
self._scroller.add_widget(alert_item)
def _acknowledge_actuation(self):
expected = self.params.get(KEY)
def confirmed():
if not acknowledge(self.params, self._actuation_physical, expected):
gui_app.push_widget(BigDialog(tr("Unable to acknowledge"), tr("Turn off the vehicle ignition and try again.")))
gui_app.push_widget(BigConfirmationDialog(tr("Clear alert"),
gui_app.texture("icons_mici/offroad_alerts/red_warning.png", 64, 64), confirmed, red=True))
def _params_worker(self):
drop_realtime()
while True:
@@ -312,6 +328,8 @@ class MiciOffroadAlerts(Scroller):
widget = next(w for w in self._scroller.items if w.alert_data is alert_data)
self._scroller.items.remove(widget)
self._scroller.items.insert(0, widget)
if alert_data.key == KEY and text:
text = text.split(".", 1)[0] + ". " + tr("Turn ignition off, then tap to acknowledge. Have the cause checked before re-engaging.")
alert_data.text = text
alert_data.visible = bool(text)
@@ -13,6 +13,11 @@ from openpilot.system.ui.lib.wrap_text import wrap_text
from openpilot.system.ui.widgets import Widget
from openpilot.system.ui.widgets.html_render import HtmlRenderer
from openpilot.selfdrive.selfdrived.alertmanager import OFFROAD_ALERTS
from openpilot.starpilot.drive_state.evidence import PhysicalSource
from openpilot.starpilot.ui.actuation_recovery import acknowledge, KEY
from openpilot.selfdrive.ui.ui_state import ui_state
from openpilot.system.ui.widgets import DialogResult
from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog, alert_dialog
class AlertColors:
@@ -88,6 +93,7 @@ class AbstractAlert(Widget, ABC):
def __init__(self, has_reboot_btn: bool = False):
super().__init__()
self.params = Params()
self._actuation_physical = PhysicalSource(ui_state.sm)
self.has_reboot_btn = has_reboot_btn
self.dismiss_callback: Callable | None = None
@@ -97,9 +103,19 @@ class AbstractAlert(Widget, ABC):
self.dismiss_callback()
def excessive_actuation_callback():
self.params.remove("Offroad_ExcessiveActuation")
if self.dismiss_callback:
self.dismiss_callback()
expected = self.params.get(KEY)
def confirmed(result):
if result != DialogResult.CONFIRM:
return
if acknowledge(self.params, self._actuation_physical, expected):
if self.dismiss_callback:
self.dismiss_callback()
else:
gui_app.push_widget(alert_dialog(tr("Turn off the vehicle ignition and try again.")))
gui_app.push_widget(ConfirmDialog(
tr("Acknowledge the previous drive's excessive actuation alert? This does not fix its cause. " +
"Do not re-engage until the cause has been checked."),
tr("Acknowledge Excessive Actuation"), callback=confirmed))
self.dismiss_btn = ActionButton(lambda: tr("Close"))
+3 -1
View File
@@ -22,7 +22,7 @@ class PhysicalSource:
def allowed(self) -> bool:
return self.status()['allowed']
def status(self, *, updating_offroad=False, require_park=False):
def status(self, *, updating_offroad=False, require_park=False, require_ignition_off=False):
def result(allowed, reason=None):
return {'allowed': bool(allowed), 'reason': reason}
with self.lock:
@@ -66,6 +66,8 @@ class PhysicalSource:
if len(pandas) == 0 or any(str(p.pandaType) == 'unknown' for p in pandas):
return result(False, 'No recognized Panda is reporting vehicle status')
ignition = any(p.ignitionLine or p.ignitionCan for p in pandas)
if require_ignition_off and ignition:
return result(False, 'Turn off the vehicle ignition before acknowledging excessive actuation')
if not require_park and (not ignition or updating_offroad and all(str(p.safetyModel) == 'noOutput' and not p.controlsAllowed for p in pandas)):
safe = all(str(p.safetyModel) == 'noOutput' and not p.controlsAllowed for p in pandas)
return result(safe, None if safe else 'Panda must confirm noOutput safety and controls disabled')
@@ -192,3 +192,15 @@ def test_galaxy_requires_fresh_explicit_park_even_with_ignition_off(fixture, ign
assert f.source.status(require_park=True)['allowed'] == (gear == 'park')
f.sm.logMonoTime['carState'] = 1
assert not f.source.status(require_park=True)['allowed']
def test_actuation_recovery_requires_ignition_off_even_in_park(fixture):
f = fixture
assert f.source.status(require_ignition_off=True)['allowed']
for field in ('ignitionLine', 'ignitionCan'):
setattr(f.sm.values['pandaStates'][0], field, True)
assert f.source.allowed() # Other callers retain normal parked semantics.
assert not f.source.status(require_ignition_off=True)['allowed']
setattr(f.sm.values['pandaStates'][0], field, False)
f.sm.alive['pandaStates'] = False
assert not f.source.status(require_ignition_off=True)['allowed']
@@ -0,0 +1,17 @@
"""Explicit recovery from a prior-drive actuation alert; never an onroad bypass."""
KEY = "Offroad_ExcessiveActuation"
def acknowledge(params, physical, expected):
# Recheck at confirmation time. A dialog opened while parked may outlive that state.
if expected is None or params.get(KEY) != expected:
return False
if not params.get_bool("IsOffroad") or not physical.status(require_ignition_off=True)["allowed"]:
return False
if physical.effective() is not False:
return False
if not params.get_bool("IsOffroad") or params.get(KEY) != expected:
return False
params.remove(KEY)
return True
@@ -0,0 +1,98 @@
from unittest.mock import Mock
import pytest
from openpilot.starpilot.ui.actuation_recovery import KEY, acknowledge
@pytest.fixture
def state():
params = Mock()
alert = {'text': 'Excessive actuation', 'extra': 'longitudinal'}
params.get.return_value = alert
params.get_bool.return_value = True
physical = Mock()
physical.status.return_value = {'allowed': True}
physical.effective.return_value = False
return params, physical, alert
def test_explicit_offroad_ack_clears_only_latch(state):
params, physical, alert = state
assert acknowledge(params, physical, alert)
physical.status.assert_called_once_with(require_ignition_off=True)
params.remove.assert_called_once_with(KEY)
params.put.assert_not_called()
@pytest.mark.parametrize('case', ['onroad', 'physical', 'absent', 'changed'])
def test_refuses_unsafe_or_superseded_confirmation(state, case):
params, physical, alert = state
if case == 'onroad':
params.get_bool.return_value = False
elif case == 'physical':
physical.status.return_value = {'allowed': False}
elif case == 'absent':
alert = None
else:
params.get.return_value = {'extra': 'lateral'}
assert not acknowledge(params, physical, alert)
params.remove.assert_not_called()
@pytest.mark.parametrize('change', ['mode', 'alert'])
def test_rechecks_after_physical_admission(state, change):
params, physical, alert = state
if change == 'mode':
params.get_bool.side_effect = [True, False]
else:
params.get.side_effect = [alert, {'extra': 'lateral'}]
assert not acknowledge(params, physical, alert)
params.remove.assert_not_called()
def test_repeated_ack_does_not_clear_new_event(state):
params, physical, alert = state
assert acknowledge(params, physical, alert)
params.get.return_value = None
assert not acknowledge(params, physical, alert)
assert params.remove.call_count == 1
@pytest.mark.parametrize('started', [True, None])
def test_requires_fresh_device_offroad(state, started):
params, physical, alert = state
physical.effective.return_value = started
assert not acknowledge(params, physical, alert)
params.remove.assert_not_called()
@pytest.mark.parametrize('fault', [None, 'ignition', 'controls', 'stale_panda', 'stale_device', 'started'])
def test_real_physical_evidence_after_driving_processes_stop(state, fault):
from types import SimpleNamespace as NS
from openpilot.starpilot.drive_state.evidence import PhysicalSource
from openpilot.starpilot.drive_state.tests.test_evidence import Messages
params, _, alert = state
messages = Messages()
messages.values['deviceState'] = NS(started=fault == 'started')
for table in (messages.seen, messages.alive, messages.valid):
table['deviceState'] = True
# These processes are deliberately absent offroad. Recovery must not need them.
table['carState'] = table['selfdriveState'] = False
messages.logMonoTime['deviceState'] = 2_000_000_000
messages.recv_time['deviceState'] = 2.0
now = [1_000_000_000]
physical = PhysicalSource(messages, mono=lambda: now[0], boot=lambda: now[0] + 10_000_000_000)
now[0] = 2_100_000_000
panda = messages.values['pandaStates'][0]
if fault == 'ignition':
panda.ignitionLine = True
elif fault == 'controls':
panda.controlsAllowed = True
elif fault == 'stale_panda':
messages.recv_time['pandaStates'] = 1.0
elif fault == 'stale_device':
messages.recv_time['deviceState'] = 1.0
assert acknowledge(params, physical, alert) is (fault is None)
assert params.remove.call_count == int(fault is None)
@@ -0,0 +1,77 @@
"""Execute production UI callbacks without GPU/native drawing dependencies."""
import ast
from pathlib import Path
from types import SimpleNamespace as NS
from unittest.mock import Mock
from openpilot.starpilot.ui.actuation_recovery import acknowledge, KEY
ROOT = Path(__file__).resolve().parents[3]
def methods(path, name, selected, env):
tree = ast.parse((ROOT / path).read_text())
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == name)
for node in cls.body:
if isinstance(node, ast.FunctionDef) and node.name in selected:
exec(compile(ast.Module(body=[node], type_ignores=[]), str(path), 'exec'), env)
return env
def setup():
params = Mock()
params.get.return_value = {'extra': 'longitudinal'}
params.get_bool.return_value = True
physical = Mock()
physical.status.return_value = {'allowed': True}
physical.effective.return_value = False
return params, physical
def test_mici_alert_wires_explicit_slide_and_rechecks_at_confirmation():
params, physical = setup()
env = {'KEY': KEY, 'acknowledge': acknowledge, 'tr': lambda s: s, 'gui_app': Mock(),
'BigConfirmationDialog': Mock(), 'BigDialog': Mock()}
methods('selfdrive/ui/mici/layouts/offroad_alerts.py', 'MiciOffroadAlerts', ['_acknowledge_actuation'], env)
obj = NS(params=params, _actuation_physical=physical)
env['_acknowledge_actuation'](obj)
params.remove.assert_not_called()
confirmed = env['BigConfirmationDialog'].call_args.args[2]
physical.status.return_value = {'allowed': False}
confirmed()
params.remove.assert_not_called()
physical.status.return_value = {'allowed': True}
confirmed()
params.remove.assert_called_once_with(KEY)
def test_mici_build_registers_only_actuation_and_update_callbacks():
env = {'KEY': KEY, 'AlertData': lambda **k: NS(**k), 'AlertItem': Mock(side_effect=lambda _: Mock()),
'OFFROAD_ALERTS': {KEY: {'severity': 1}, 'Other': {'severity': 0}}, 'HARDWARE': Mock()}
methods('selfdrive/ui/mici/layouts/offroad_alerts.py', 'MiciOffroadAlerts', ['_build_alerts'], env)
obj = NS(alert_items=[], _scroller=Mock(), _acknowledge_actuation=Mock())
env['_build_alerts'](obj)
obj.alert_items[1].set_click_callback.assert_called_once_with(obj._acknowledge_actuation)
obj.alert_items[2].set_click_callback.assert_not_called()
def test_large_confirmation_cancel_and_mode_change_do_not_clear():
params, physical = setup()
# Execute the actual nested callback extracted from the constructor.
path = ROOT / 'selfdrive/ui/widgets/offroad_alerts.py'
tree = ast.parse(path.read_text())
callback = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == 'excessive_actuation_callback')
env = {'self': NS(params=params, _actuation_physical=physical, dismiss_callback=Mock()),
'KEY': KEY, 'acknowledge': acknowledge, 'DialogResult': NS(CONFIRM=1, CANCEL=0),
'tr': lambda s: s, 'gui_app': Mock(), 'ConfirmDialog': Mock(), 'alert_dialog': Mock()}
exec(compile(ast.Module(body=[callback], type_ignores=[]), str(path), 'exec'), env)
env['excessive_actuation_callback']()
confirmed = env['ConfirmDialog'].call_args.kwargs['callback']
confirmed(0)
params.remove.assert_not_called()
params.get_bool.return_value = False
confirmed(1)
params.remove.assert_not_called()
params.get_bool.return_value = True
confirmed(1)
params.remove.assert_called_once_with(KEY)