From e4e3e945b238f4444b94635d9f03ccf84b06d7b9 Mon Sep 17 00:00:00 2001 From: Prabhaav Pillai Date: Thu, 19 Nov 2026 22:49:43 -0500 Subject: [PATCH] conditional models, policies, and runtime --- openpilot/cereal/custom.capnp | 29 ++ openpilot/cereal/log.capnp | 2 + openpilot/cereal/services.py | 2 + openpilot/selfdrive/modeld/modeld.py | 86 ++- openpilot/selfdrive/selfdrived/selfdrived.py | 10 + .../tests/test_jetlink_event_faults.py | 3 +- openpilot/starpilot/galaxy/server.py | 5 +- .../galaxy/tests/test_model_laboratory.mjs | 14 +- .../starpilot/galaxy/tests/test_models.mjs | 84 ++- .../starpilot/galaxy/tests/test_models.py | 8 + .../starpilot/galaxy/web/css/settings.css | 7 +- openpilot/starpilot/galaxy/web/js/models.js | 126 +++-- openpilot/starpilot/models/README.md | 134 ++++- .../starpilot/models/conditional_alerts.py | 21 + .../starpilot/models/conditional_model.py | 39 ++ .../starpilot/models/conditional_policy.py | 49 ++ .../starpilot/models/conditional_protocol.py | 138 +++++ .../starpilot/models/conditional_runtime.py | 189 +++++++ openpilot/starpilot/models/jetlink_adapter.py | 29 +- openpilot/starpilot/models/manager.py | 57 +- openpilot/starpilot/models/receipt.py | 2 +- .../starpilot/models/recovery_process.py | 94 +++- openpilot/starpilot/models/runner.py | 35 ++ openpilot/starpilot/models/runtime.py | 30 +- .../models/tests/test_conditional_alerts.py | 64 +++ .../models/tests/test_conditional_policy.py | 88 ++++ .../models/tests/test_conditional_runtime.py | 493 ++++++++++++++++++ .../starpilot/models/tests/test_manager.py | 118 +++++ .../tests/test_modeld_startup_fallback.py | 59 ++- .../starpilot/models/tests/test_receipt.py | 5 + .../models/tests/test_recovery_process.py | 107 ++++ .../starpilot/models/tests/test_runtime.py | 26 +- openpilot/system/manager/manager.py | 2 +- 33 files changed, 2027 insertions(+), 128 deletions(-) create mode 100644 openpilot/starpilot/models/conditional_alerts.py create mode 100644 openpilot/starpilot/models/conditional_model.py create mode 100644 openpilot/starpilot/models/conditional_policy.py create mode 100644 openpilot/starpilot/models/conditional_protocol.py create mode 100644 openpilot/starpilot/models/conditional_runtime.py create mode 100644 openpilot/starpilot/models/tests/test_conditional_alerts.py create mode 100644 openpilot/starpilot/models/tests/test_conditional_policy.py create mode 100644 openpilot/starpilot/models/tests/test_conditional_runtime.py diff --git a/openpilot/cereal/custom.capnp b/openpilot/cereal/custom.capnp index 3762da6983..20182baf3d 100644 --- a/openpilot/cereal/custom.capnp +++ b/openpilot/cereal/custom.capnp @@ -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; +} + diff --git a/openpilot/cereal/log.capnp b/openpilot/cereal/log.capnp index cf69ce44c3..f37e434e63 100644 --- a/openpilot/cereal/log.capnp +++ b/openpilot/cereal/log.capnp @@ -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) diff --git a/openpilot/cereal/services.py b/openpilot/cereal/services.py index 566449cb3a..8e1f4a52ad 100755 --- a/openpilot/cereal/services.py +++ b/openpilot/cereal/services.py @@ -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), diff --git a/openpilot/selfdrive/modeld/modeld.py b/openpilot/selfdrive/modeld/modeld.py index fbb00af1ee..0985345fc9 100755 --- a/openpilot/selfdrive/modeld/modeld.py +++ b/openpilot/selfdrive/modeld/modeld.py @@ -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__": diff --git a/openpilot/selfdrive/selfdrived/selfdrived.py b/openpilot/selfdrive/selfdrived/selfdrived.py index 8937f4b55f..f55acb5c24 100755 --- a/openpilot/selfdrive/selfdrived/selfdrived.py +++ b/openpilot/selfdrive/selfdrived/selfdrived.py @@ -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 @@ -1300,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 @@ -2312,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. @@ -2406,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)) diff --git a/openpilot/selfdrive/selfdrived/tests/test_jetlink_event_faults.py b/openpilot/selfdrive/selfdrived/tests/test_jetlink_event_faults.py index c7e9cd0310..f83cfc71e5 100644 --- a/openpilot/selfdrive/selfdrived/tests/test_jetlink_event_faults.py +++ b/openpilot/selfdrive/selfdrived/tests/test_jetlink_event_faults.py @@ -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.): diff --git a/openpilot/starpilot/galaxy/server.py b/openpilot/starpilot/galaxy/server.py index d06be5681c..ae4ffae51d 100644 --- a/openpilot/starpilot/galaxy/server.py +++ b/openpilot/starpilot/galaxy/server.py @@ -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', diff --git a/openpilot/starpilot/galaxy/tests/test_model_laboratory.mjs b/openpilot/starpilot/galaxy/tests/test_model_laboratory.mjs index f47a4b9066..15648320c1 100644 --- a/openpilot/starpilot/galaxy/tests/test_model_laboratory.mjs +++ b/openpilot/starpilot/galaxy/tests/test_model_laboratory.mjs @@ -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')"> Model pair`)) +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')"> Split Model`)) +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) diff --git a/openpilot/starpilot/galaxy/tests/test_models.mjs b/openpilot/starpilot/galaxy/tests/test_models.mjs index 6e7b80aedc..1b0ef2769b 100644 --- a/openpilot/starpilot/galaxy/tests/test_models.mjs +++ b/openpilot/starpilot/galaxy/tests/test_models.mjs @@ -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(`