Simplified tune backups to Download tune and Import; removed redundant Share code.

Standardized Galaxy notice and toast padding.
Renamed Selected Profile to Use global preset.
Clarified parked power behavior with Stock and Custom limits.
Reorganized settings:- Device & System is the last tab.
- Display moved to Visual.
- VOACC and Always Hold Enhanced Stops moved to Longitudinal.
- Merged cloud, remote access, and data uploads.
- Added separate Manage entries for StarPort, Browser preferences, and Localization.
Removed classic StarPort setup and its toggle; guided setup is now the default.
Consolidated backup, resets, and route deletion into concise groups, collapsed by default.
Improved mobile widget-editor scrolling.
Made PiP cameras render above other widgets and corrected right-camera placement for C3X.
Improved weather location handling, retry behavior, and missing-data display.
Standardized paired titles to use &.
This commit is contained in:
Prabhaav Pillai
2026-11-18 02:43:46 -05:00
parent f747dd4e01
commit a214a29163
77 changed files with 730 additions and 650 deletions
File diff suppressed because one or more lines are too long
@@ -1,12 +1,12 @@
"""Galaxy-only, next-drive developer preferences."""
"""Parked device maintenance, connection preferences and next-drive driving options."""
from openpilot.starpilot.longitudinal.voacc import KEY, DESCRIPTION
from openpilot.starpilot.longitudinal.enhanced_stop_hold import KEY as HOLD_KEY, LABEL as HOLD_LABEL, DESCRIPTION as HOLD_DESCRIPTION
from openpilot.starpilot.ui.calibration_reset import calibration_reset
from openpilot.starpilot.saved_document import commit_exact
from openpilot.starpilot.saved_source import read_saved
from openpilot.starpilot.system.starport import head_unit_fixes, new_setup
from openpilot.starpilot.ui.feature_settings_state import HEADING_PREFIX, FeatureRow, FeatureSettingsState
from openpilot.starpilot.system.starport import head_unit_fixes
from openpilot.starpilot.ui.feature_settings_state import FeatureRow, FeatureSettingsState
STARPORT_WIFI_KEY = "StarPortDedicatedWifi"
@@ -14,10 +14,6 @@ STARPORT_WIFI_DESCRIPTION = ("Experimental. Join the car's Wi-Fi on a second int
"phone hotspot during wireless StarPort. Applies from the next StarPort connection.")
CALIBRATION_RESET = "reset_calibration"
CALIBRATION_RESET_DESCRIPTION = "Clear camera and steering calibration. The device recalibrates on the next drive."
STARPORT_HEADING_KEY = HEADING_PREFIX + "starport"
STARPORT_NEW_SETUP_KEY = "StarPortNewSetup"
STARPORT_NEW_SETUP_DESCRIPTION = ("Guided StarPort setup with a live checklist of what is being tried. Turn off to use the classic " +
"setup screens. Applies the next time the setup screen opens.")
STARPORT_HEVC_KEY = "StarPortAllowHevc"
STARPORT_HEVC_DESCRIPTION = ("Experimental. Only for a car that offers H.265 and no H.264 video. Cars that offer H.264 are not " +
"affected. Applies from the next StarPort connection.")
@@ -44,7 +40,7 @@ DRIVER_MONITORING_RESET = "reset_driver_monitoring"
DRIVER_MONITORING_RESET_DESCRIPTION = "Clear saved wheel-side detection. Automatic detection restarts on the next drive."
class DeveloperSettingsOwner:
class DeviceSettingsOwner:
def __init__(self, params, authorized, *, starport=None):
self.params = params
self.authorized = authorized
@@ -60,13 +56,9 @@ class DeveloperSettingsOwner:
return None # the service is off; there is nothing to configure
def _starport_rows(self, parked):
"""The StarPort section. The switch back to classic setup is always listed; the daemon's settings only while it runs."""
new_setup_on = new_setup.enabled()
"""StarPort connection options, available while the daemon runs."""
held = "Park the vehicle to change this setting."
rows = [FeatureRow(STARPORT_HEADING_KEY, "StarPort", "", available=False),
FeatureRow(STARPORT_NEW_SETUP_KEY, "New pairing experience", "On" if new_setup_on else "Off",
b"1" if new_setup_on else b"0", ("Off", "On"), available=parked,
reason=STARPORT_NEW_SETUP_DESCRIPTION if parked else held, default_value="On")]
rows = []
status = self._starport_status()
if status is not None:
enabled, hevc = bool(status.get("dedicated_wifi_interface")), bool(status.get("allow_hevc"))
@@ -103,7 +95,7 @@ class DeveloperSettingsOwner:
rows.append(FeatureRow(STARPORT_EXPERIMENT_PREFIX + entry["id"], entry["label"], "On" if on else "Off", b"1" if on else b"0",
("Off", "On"), available=parked, default_value="Off",
reason=f"Experimental. {entry['evidence']} Applies from the next StarPort connection." if parked else held))
return tuple(rows)
return tuple(rows) if status is not None else ()
def _driver_monitoring_reset_allowed(self):
return self.authorized() and not self.params.get_bool("IsDriverViewEnabled")
@@ -111,10 +103,9 @@ class DeveloperSettingsOwner:
def _calibration_reset_allowed(self):
return self.authorized() and not calibration_reset.pending and not self.params.get_bool("OnroadCycleRequested")
def snapshot(self):
def _driving_rows(self, parked):
raw, readable = read_saved(self.params, KEY, 8)
valid = readable and raw in (None, b"0", b"1")
parked = self.authorized()
row = FeatureRow(KEY, "Use VOACC", ("On" if raw == b"1" else "Off") if valid else "Invalid saved value",
raw, ("Off", "On") if valid else (), available=parked and valid,
reason=(DESCRIPTION if parked else "Park the vehicle to change this setting.") if valid else
@@ -125,6 +116,9 @@ class DeveloperSettingsOwner:
hold_raw, ("Off", "On") if hold_valid else (), available=parked and hold_valid,
reason=(HOLD_DESCRIPTION if parked else "Park the vehicle to change this setting.") if hold_valid else
"Invalid saved value", default_value="Off")
return row, hold_row
def _reset_rows(self):
rhd_raw, rhd_readable = read_saved(self.params, "IsRhdDetected", 8)
reset_available = self._driver_monitoring_reset_allowed() and rhd_readable
reset_reason = (DRIVER_MONITORING_RESET_DESCRIPTION if reset_available else
@@ -137,10 +131,21 @@ class DeveloperSettingsOwner:
calibration_raw if calibration_readable else None, available=calibration_available,
reason=CALIBRATION_RESET_DESCRIPTION if calibration_available else
"Park the vehicle and wait for any pending reset to finish.")
starport_rows = self._starport_rows(parked)
summary = "Changes apply next drive."
return FeatureSettingsState("developer", "Developer driving options", summary,
(row, hold_row, reset_row, calibration_row, *starport_rows), parked)
return reset_row, calibration_row
def snapshot(self, page="starport_options"):
parked = self.authorized()
if page == "driving_options":
title, rows = "Longitudinal options", self._driving_rows(parked)
elif page == "resets":
title, rows = "Device resets", self._reset_rows()
elif page == "starport_options":
title, rows = "StarPort", self._starport_rows(parked)
else:
raise ValueError("Unknown device settings page")
return FeatureSettingsState(page, title, "Changes apply from the next StarPort connection." if page == "starport_options" else
"The device relearns these settings on the next drive." if page == "resets" else
"Changes apply next drive.", rows, parked)
def apply(self, request):
if request.key == CALIBRATION_RESET:
@@ -179,12 +184,10 @@ class DeveloperSettingsOwner:
return self._apply_starport(request, "head_unit_experiments", "set_head_unit_experiments")
if request.key.startswith(STARPORT_EXPERIMENT_PREFIX):
return self._apply_experiment_rule(request)
if request.key == STARPORT_NEW_SETUP_KEY:
return self._apply_new_setup(request)
if request.key not in (KEY, HOLD_KEY) or request.value not in ("Off", "On") or request.expected not in (None, b"0", b"1"):
return False
result = commit_exact(self.params, key=request.key, max_bytes=8, raw=b"1" if request.value == "On" else b"0",
expected=request.expected, authorized=self.authorized, temp_prefix=".developer-")
expected=request.expected, authorized=self.authorized, temp_prefix=".device-settings-")
return result.committed and result.verified
def _apply_starport(self, request, field, command):
@@ -214,9 +217,3 @@ class DeveloperSettingsOwner:
return False
status = self._starport_status()
return status is not None and (rule_id in (status.get("head_unit_experiment_rules") or ())) == (request.value == "On")
def _apply_new_setup(self, request):
current = new_setup.enabled()
if request.value not in ("Off", "On") or request.expected != (b"1" if current else b"0") or not self.authorized():
return False
return new_setup.set_enabled(request.value == "On")
-12
View File
@@ -2577,18 +2577,6 @@ def make_server(*, port=8082, host='127.0.0.1', monitor=None, owner=None, crashe
else:
self.json(401, {'error': 'Sign in to Galaxy'})
return
if action == 'new_setup' and set(payload) == {'action', 'enabled'} and type(payload['enabled']) is bool:
# The way back to the classic screens, so it works with the StarPort service off or broken.
from openpilot.starpilot.system.starport import new_setup
if not configuration_allowed():
self.json(403, {'error': 'Park before changing the setup screens'})
elif not new_setup.set_enabled(payload['enabled']):
self.json(503, {'error': 'Could not save the setup screen choice'})
elif self.settings_session() == identity:
self.json(200, {'newSetup': new_setup.enabled()})
else:
self.json(401, {'error': 'Sign in to Galaxy'})
return
if not starport_setup_owner().enabled():
self.json(409, {'error': 'Enable StarPort first'})
return
@@ -73,8 +73,8 @@ DESCRIPTIONS = {
'Selected acceleration profiles, stop detection and vehicle limits still apply.'),
'CustomPersonalities': 'Uses your following-time and jerk settings for the selected driving personality.',
'profile:stopped_gap': 'Adds this distance to the following gap behind a stopped lead vehicle.',
'profile:global_acceleration': 'Chooses the acceleration curve used by personalities set to Selected Profile.',
'profile:global_braking': 'Chooses the braking response used by personalities set to Selected Profile.',
'profile:global_acceleration': 'Chooses the acceleration curve used by personalities set to Use global preset.',
'profile:global_braking': 'Chooses the braking response used by personalities set to Use global preset.',
'reset_profiles': 'Restores the default acceleration, braking and following curves and presets.',
'CurveSpeedController': 'Adjusts cruise speed for curves ahead using available learned cornering preferences.',
'CurveSpeedControllerNoLead': 'Pauses curve-speed adjustments while following a lead vehicle.',
@@ -119,8 +119,6 @@ DESCRIPTIONS = {
'RemoteStartBootsComma': 'Wakes comma during GM remote start.',
'HKGRemoteStartBootsComma': 'Wakes comma during Hyundai, Kia or Genesis remote climate operation.',
'IgnoreIgnitionLine': 'Uses GM CAN ignition instead of the harness ignition signal.',
'heading:starport': 'Settings for connecting Android Auto to the car through StarPort.',
'StarPortNewSetup': 'Shows the guided StarPort setup with a live checklist instead of the classic setup screens.',
'StarPortAllowHevc': 'Lets a car that offers only H.265 video receive H.265; a car with an H.264 mode keeps H.264.',
'StarPortKeyframeTest': 'Sends every H.265 frame as a keyframe and logs the car\'s acknowledgments, to diagnose H.265-only cars.',
'StarPortTallHevc': 'Uses the car\'s 1080x1920 H.265 screen mode instead of 720x1280, to diagnose H.265-only cars. Needs Allow H.265 video on.',
@@ -196,7 +194,6 @@ DESCRIPTIONS = {
# These are initialization explanations, not a second defaults table.
INITIALIZATION = {
'StarPortNewSetup': 'Applies the next time the setup screen opens.',
'StarPortAllowHevc': 'Applies from the next StarPort connection.',
'StarPortKeyframeTest': 'Applies from the next StarPort connection.',
'StarPortTallHevc': 'Applies from the next StarPort connection.',
+21 -18
View File
@@ -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.developer_settings import CALIBRATION_RESET, DRIVER_MONITORING_RESET, DeveloperSettingsOwner
from openpilot.starpilot.galaxy.device_settings import CALIBRATION_RESET, DRIVER_MONITORING_RESET, 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", "localization", "developer", "vehicle", "slc", "lane", "lane_change", "profiles", "personalities",
PAGES = frozenset(("hub", "localization", "starport_options", "driving_options", "resets", "vehicle", "slc", "lane", "lane_change", "profiles", "personalities",
"traffic", "aggressive", "standard", "relaxed",
"curve", "torque", "torque/developer", "tuning", "torque/bluepilot", "aol", "wheel", "appearance", "display",
"data", "power", "sounds", "pip", "sentry", "vasm",
@@ -55,13 +55,11 @@ TTL = 60.0
CAR_CONTROL_SECTIONS = (
("lateral", "Lateral (Steering)", ("aol", "lane_change", "lane", "torque", "torque/developer")),
("longitudinal", "Longitudinal (Speed & Following)",
("profiles", "conditional", "curve", "slc", "aggressive", "standard", "relaxed", "traffic")),
("driving_options", "profiles", "conditional", "curve", "slc", "aggressive", "standard", "relaxed", "traffic")),
("wheel", "Wheel Controls", ("wheel",)),
("visual", "Visual (Display & UI)", ("appearance", "pip")),
("visual", "Visual (Display & UI)", ("display", "appearance", "pip")),
("sounds", "Sounds & Alerts", ("sounds",)),
("device", "Device & Data", ("display", "data")),
("localization", "Localization", ("localization",)),
("developer", "Developer", ("developer",)),
("device", "Device & System", ("data", "starport_options", "localization")),
)
@@ -148,7 +146,7 @@ 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 ("developer", "power") and key and key != SETUP_ACTION and key not in (
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",
"conditional:reset", "conditional:manual_reset",
) and not is_long_confirm_action(key) and not key.startswith("torque_repair:"))
@@ -482,7 +480,7 @@ def _question(row: FeatureRow, request: FeatureSettingsRequest) -> str:
if key == "reset_profiles":
return "Reset invalid saved profiles and turn their saved switch off?"
if key in ("profile:global_acceleration", "profile:global_braking"):
return (f"Save {row.label.lower()} as {request.value}? Personalities set to Selected Profile follow this choice; " +
return (f"Save {row.label.lower()} as {request.value}? Personalities set to Use global preset follow this choice; " +
"explicit personality overrides stay unchanged.")
if key == "torque:surface:reset":
return "Remove the thirty manual overrides for this vehicle? Saved Auto Learn history is kept."
@@ -630,15 +628,14 @@ class SettingsGateway:
return fresh.cp_raw == ctx.cp_raw
return VASMOwner(self.params, parked)
def _developer_owner(self, ctx: AuthorityContext, *, live: bool = False,
session_valid: Callable[[], bool] = lambda: True) -> DeveloperSettingsOwner:
def _device_settings_owner(self, ctx: AuthorityContext, *, live: bool = False,
session_valid: Callable[[], bool] = lambda: True) -> DeviceSettingsOwner:
def authorized() -> bool:
if not session_valid():
return False
fresh = self.context.sample() if live else ctx
return bool(fresh.parked and not fresh.editing_saved_vehicle and fresh.cp_raw == ctx.cp_raw)
return DeveloperSettingsOwner(self.params, authorized,
starport=self.starport)
return DeviceSettingsOwner(self.params, authorized, starport=self.starport)
def _localization_owner(self, ctx: AuthorityContext, *, live: bool = False,
session_valid: Callable[[], bool] = lambda: True) -> LocalizationSettingsOwner:
@@ -651,8 +648,8 @@ class SettingsGateway:
def _state(self, page: str, ctx: AuthorityContext):
if page == "localization":
return self._localization_owner(ctx).snapshot()
if page == "developer":
return self._developer_owner(ctx).snapshot()
if page in ("starport_options", "driving_options", "resets"):
return self._device_settings_owner(ctx).snapshot(page)
if page == "appearance":
return self._appearance_owner(ctx).snapshot(Profile.COMPACT, include_large=True)
if page == "sounds":
@@ -666,7 +663,7 @@ class SettingsGateway:
if row.key in (HOURS, VOLTS) else row for row in state.rows)
cooling = self._owner(ctx).snapshot("power", parked=ctx.parked, system_long=False, lateral_context=False,
metric=ctx.metric, configure_while_driving=True)
return replace(state, title="Power and Cooling", rows=rows + tuple(cooling.rows))
return replace(state, title="Power & Cooling", rows=rows + tuple(cooling.rows))
if page == "display":
return self._display_owner(ctx).snapshot(Profile.COMPACT if HARDWARE.get_device_type() == "mici" else Profile.LARGE)
if page == "pip":
@@ -679,6 +676,12 @@ class SettingsGateway:
system_long=_qualified(ctx, "long"),
lateral_context=_qualified(ctx, "lane") or (page == "lane" and _qualified(ctx, "lane_live")),
metric=ctx.metric, configure_while_driving=True)
if page == "data":
state = replace(state, title="Data & Connections")
if page == "hub":
state = replace(state, rows=state.rows + (
FeatureRow("", "Longitudinal options", "Vision-only cruise control and Enhanced Stops", page="driving_options", 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")))
if ctx.editing_saved_vehicle:
@@ -894,7 +897,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 == "developer":
return self._developer_owner(ctx, live=True, session_valid=session_valid).apply(intent.request)
if intent.page in ("starport_options", "driving_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)
+1 -2
View File
@@ -13,7 +13,7 @@ from pathlib import Path
from collections.abc import Callable
from typing import BinaryIO
from openpilot.starpilot.system.starport import apk_identity, apkpure, new_setup
from openpilot.starpilot.system.starport import apk_identity, apkpure
# Left behind by the removed Google sign-in: a saved refresh token and the resolver binary.
LEGACY_GOOGLE_FILES = (Path('/data/starpilot/starport_token'), Path('/data/starpilot/google-play'))
@@ -65,7 +65,6 @@ class StarPortSetup:
ident = self.identity_status()
return {
'enabled': self.enabled(), 'bluetoothEnabled': self.bluetooth_enabled(), 'parked': self.parked(),
'newSetup': new_setup.enabled(),
'installReady': self.install_ready(), 'serviceReady': self.service_ready(),
'identity': {key: ident[key] for key in ('installed', 'expires', 'days_left', 'warning', 'message', 'expired', 'error', 'app_version') if key in ident},
'import': self.job.status(),
@@ -526,27 +526,12 @@ def test_on_device_browser_api_is_gone(api):
assert request('POST', '/api/starport/google-browser', json.dumps(start), cookie=cookie, content_type='application/json')[0] != 200
def test_classic_setup_switch_needs_a_session_and_park_but_not_the_service(api, tmp_path, monkeypatch):
from openpilot.starpilot.system.starport import new_setup
monkeypatch.setattr(new_setup, 'FLAG_PATH', tmp_path / 'new_setup')
request, _, state, client = api
def test_legacy_setup_switch_is_no_longer_supported(api):
request, _, _, _ = api
body = json.dumps({'action': 'new_setup', 'enabled': False})
assert request('POST', '/api/starport/control', body, content_type='application/json')[0] == 401
code, _, headers = request('POST', '/api/auth/login', json.dumps({'password': 'password123'}), content_type='application/json')
assert code == 200
cookie = headers['Set-Cookie'].split(';', 1)[0]
assert new_setup.enabled()
state['parked'] = False
assert request('POST', '/api/starport/control', body, cookie=cookie, content_type='application/json')[0] == 403
assert new_setup.enabled()
state['parked'] = True
client.calls.clear()
code, result, _ = request('POST', '/api/starport/control', body, cookie=cookie, content_type='application/json')
assert (code, result) == (200, {'newSetup': False}) and not new_setup.enabled()
assert client.calls == [] # the daemon was never asked: this is the way back when it is down
assert request('GET', '/api/starport/setup', cookie=cookie)[1]['newSetup'] is False
code, result, _ = request('POST', '/api/starport/control', json.dumps({'action': 'new_setup', 'enabled': True}),
cookie=cookie, content_type='application/json')
assert (code, result) == (200, {'newSetup': True}) and new_setup.enabled()
for bad in ({'action': 'new_setup'}, {'action': 'new_setup', 'enabled': 'no'}, {'action': 'new_setup', 'enabled': True, 'x': 1}):
assert request('POST', '/api/starport/control', json.dumps(bad), cookie=cookie, content_type='application/json')[0] == 400
assert request('POST', '/api/starport/control', body, cookie=cookie, content_type='application/json')[0] != 200
assert 'newSetup' not in request('GET', '/api/starport/setup', cookie=cookie)[1]
@@ -1,98 +0,0 @@
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright')
const assert = require('node:assert/strict')
;(async () => {
const browser = await chromium.launch({ headless: true,
...(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {}) })
try {
const page = await browser.newPage()
const errors = [], saves = []
let enabled = false, parked = true
page.on('pageerror', error => errors.push(error.message))
await page.route('**/developer-settings-test', route => route.fulfill({ contentType: 'text/html', body:
'<link rel="stylesheet" href="css/galaxy.css"><link rel="stylesheet" href="css/setup.css"><link rel="stylesheet" href="css/settings.css"><div id="test"></div>' }))
await page.route('**/api/**', route => {
const path = new URL(route.request().url()).pathname
let data
if (path.endsWith('/connect/provider')) data = { active: 'comma', selected: 'comma', revision: 'a'.repeat(64),
restartRequired: false, canSelect: parked, providers: [
{ id: 'comma', label: 'comma', url: 'https://connect.comma.ai' },
{ id: 'konik', label: 'Konik', url: 'https://stable.konik.ai' }] }
else if (path.endsWith('/connect/proxy')) data = { enabled: false, address: '', origin: '', revision: 'proxy', canEdit: parked, passwordConfigured: true }
else if (path.endsWith('/pages/developer')) data = { page: 'developer', title: 'Developer driving options',
view: 'developer', parked, rows: [{ label: 'Use VOACC', value: enabled ? 'On' : 'Off', choices: ['Off', 'On'],
available: parked, action: true, reason: 'Vision-only lead selection. Applies next drive.', defaultValue: 'Off' }] }
else if (path.endsWith('/pages/hub')) data = { page: 'hub', title: 'Driving Controls', view: 'hub', parked,
rows: [['slc', 'Speed Limit Controller'], ['curve', 'Curve Speed Controller'], ['conditional', 'Conditional Driving Modes'],
['profiles', 'Long Planner'], ['aggressive', 'Aggressive Personality']].map(([page, label]) => ({ page, label, available: true })) }
else if (path.endsWith('/preview')) {
saves.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 return route.fulfill({ status: 404, json: { error: 'Unexpected endpoint' } })
return route.fulfill({ json: data })
})
await page.goto((process.env.GALAXY_URL || 'http://127.0.0.1:8765/') + 'developer-settings-test')
await page.evaluate(async () => {
const { createApp } = await import('./vendor/vue/vue.esm-browser.js')
const { SettingsPage } = await import('./js/settings.js')
window.mount = section => {
window.app?.unmount()
window.app = createApp(SettingsPage, { mode: 'local', unauthorized() {}, initialSection: section })
window.vm = window.app.mount('#test')
}
mount('developer')
})
const toggle = page.getByRole('switch', { name: 'Use VOACC', exact: true })
await toggle.waitFor()
assert.equal(await toggle.isChecked(), false)
await toggle.click()
await page.waitForFunction(() => vm.state.status === 'ready' && vm.state.data.rows[0].value === 'On')
assert.equal(await toggle.isChecked(), true)
assert.equal(saves[0].value, 'On')
for (const width of [320, 1280]) {
await page.setViewportSize({ width, height: 900 })
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false)
for (const label of ['Proxy IP address', 'Public HTTPS origin']) {
const field = page.getByLabel(label, { exact: true })
const layout = await field.evaluate(element => ({ width: element.getBoundingClientRect().width,
parent: element.closest('.gx-row').getBoundingClientRect().width }))
assert.ok(layout.width > layout.parent * .75, `${label} fills its settings row`)
}
const inset = await page.locator('form .gx-panel.gx-actions').evaluate(element => parseFloat(getComputedStyle(element).paddingLeft))
assert.ok(inset > 0, 'proxy Save uses the shared panel inset')
}
await page.getByRole('button', { name: 'Longitudinal (Speed & Following)', exact: true }).click()
await page.locator('.gx-panel-enter-active').waitFor()
assert.ok(await page.locator('.gx-panel-enter-active').evaluate(element => new DOMMatrix(getComputedStyle(element).transform).m41) < 0)
await page.getByText('Long Planner', { exact: true }).waitFor()
await page.waitForFunction(() => document.querySelectorAll('.gx-panel-stage .gx-row').length === 5)
const order = await page.locator('.gx-panel-stage .gx-row').allTextContents()
assert.equal(order.length, 5)
for (const [index, label] of ['Long Planner', 'Conditional Driving Modes', 'Curve Speed Controller',
'Speed Limit Controller', 'Aggressive Personality'].entries()) assert.ok(order[index].includes(label))
assert.equal(await toggle.count(), 0)
parked = false
await page.getByRole('button', { name: 'Developer', exact: true }).click()
const developerPanel = page.locator('.gx-panel-enter-active')
await developerPanel.waitFor()
assert.ok(await developerPanel.evaluate(element => new DOMMatrix(getComputedStyle(element).transform).m41) > 0)
assert.equal(await developerPanel.getByText('Reverse proxy', { exact: true }).count(), 1, 'the proxy card enters with Developer')
await toggle.waitFor()
assert.equal(await toggle.isDisabled(), true)
await page.waitForFunction(() => !document.querySelector('.gx-panel-enter-active, .gx-panel-leave-active'))
await page.getByRole('button', { name: 'Vehicle', exact: true }).click()
await page.locator('.gx-panel-enter-active').waitFor()
await page.waitForFunction(() => !document.querySelector('.gx-panel-enter-active, .gx-panel-leave-active'))
await page.getByRole('button', { name: 'Developer', exact: true }).click()
await page.locator('.gx-panel-enter-active').getByText('Reverse proxy', { exact: true }).waitFor()
await page.waitForFunction(() => !document.querySelector('.gx-panel-enter-active, .gx-panel-leave-active'))
await page.emulateMedia({ reducedMotion: 'reduce' })
await page.getByRole('button', { name: 'Longitudinal (Speed & Following)', exact: true }).click()
await page.getByText('Long Planner', { exact: true }).waitFor()
await page.waitForTimeout(50)
assert.equal(await page.locator('.gx-panel-enter-active, .gx-panel-leave-active').count(), 0)
assert.deepEqual(errors, [])
console.log('Developer VOACC: saved toggle, parked guard, phone/desktop layout and longitudinal ordering passed.')
} finally { await browser.close() }
})().catch(error => { console.error(error); process.exit(1) })
@@ -0,0 +1,99 @@
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright')
const assert = require('node:assert/strict')
;(async () => {
const browser = await chromium.launch({ headless: true })
try {
const page = await browser.newPage({ viewport: { width: 390, height: 844 } })
const errors = [], writes = [], requests = []
let parked = true, enabled = false
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>' }))
await page.route('**/api/**', route => {
const path = new URL(route.request().url()).pathname
requests.push(path)
let data
if (path.endsWith('/connect/provider')) data = { active: 'comma', selected: 'comma', revision: 'a'.repeat(64), restartRequired: false,
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 }] }
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/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 return route.fulfill({ status: 404, json: { error: 'Unexpected endpoint' } })
return route.fulfill({ json: data })
})
await page.goto((process.env.GALAXY_URL || 'http://127.0.0.1:8765/') + 'device-settings-test')
await page.evaluate(async () => {
const { createApp } = await import('./vendor/vue/vue.esm-browser.js')
const { SettingsPage } = await import('./js/settings.js')
window.mount = props => {
window.app?.unmount()
window.app = createApp(SettingsPage, { mode: 'local', unauthorized() {}, ...props })
window.vm = window.app.mount('#test')
}
mount({ initialSection: 'device' })
})
assert.equal(await page.getByRole('button', { name: 'Developer', exact: true }).count(), 0)
await page.locator('.gx-row').filter({has:page.getByText('Data & Connections', {exact:true})}).getByRole('button', {name:'Manage'}).click()
await page.getByText('Reverse proxy', { exact: true }).waitFor()
await page.getByRole('switch', {name:'Always Allow Uploads',exact:true}).waitFor()
assert.equal(await page.getByRole('switch',{name:'Hide app download reminder',exact:true}).count(),0)
assert.equal(await page.getByRole('switch', { name: 'Use VOACC', exact: true }).count(), 0)
for (const width of [320, 390, 1280]) {
await page.setViewportSize({ width, height: 900 })
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false)
assert.equal(await page.getByLabel('Proxy IP address', { exact: true }).isVisible(), true)
}
await page.evaluate(() => vm.back())
assert.equal(await page.locator('.gx-settings-tabs button').last().textContent(), 'Device & System')
assert.equal(await page.getByRole('button',{name:'Localization',exact:true}).count(),0)
const manage = label => page.locator('.gx-row').filter({has:page.getByText(label,{exact:true})}).getByRole('button',{name:'Manage'})
assert.equal(await manage('Display').count(), 0)
await page.getByRole('button', {name:'Visual (Display & UI)',exact:true}).click()
await manage('Display').click()
await page.getByText('Screen Brightness',{exact:true}).waitFor()
assert.equal(await page.evaluate(()=>vm.activeSection.id),'visual')
await page.evaluate(()=>vm.back())
await page.getByRole('button', {name:'Device & System',exact:true}).click()
await manage('StarPort').click()
await page.getByRole('switch',{name:'Stay on Wi-Fi',exact:true}).waitFor()
await page.getByText('Reverse proxy',{exact:true}).waitFor({state:'hidden'})
await page.evaluate(()=>vm.back())
await manage('Browser preferences').click()
const reminder = page.getByRole('switch',{name:'Hide app download reminder',exact:true})
await reminder.waitFor()
await reminder.check()
assert.equal(await page.evaluate(()=>localStorage.getItem('galaxy-hide-app-download-reminder')),'1')
assert(!requests.some(path=>path.includes('browser_preferences')))
await page.evaluate(()=>vm.back())
await manage('Localization').click()
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()
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')
parked = false
await page.evaluate(() => vm.feed.load('driving_options'))
assert.equal(await toggle.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()
assert.equal(await toggle.count(), 0)
assert.deepEqual(errors, [])
console.log('Device category ordering, merged data/cloud settings, separate StarPort, local browser preferences and Localization navigation passed.')
} finally { await browser.close() }
})().catch(error => { console.error(error); process.exit(1) })
@@ -18,6 +18,7 @@ const assert = require('node:assert/strict')
template: `<GxNotice tone="danger">This page could not finish loading.<template #actions><button class="gx-btn" @click="clicks++">Reload page</button></template></GxNotice>
<output>{{ clicks }}</output>
<GxNotice v-for="tone in ['info', 'success', 'warn', 'danger']" :tone="tone" :title="tone"><p>A message that wraps onto multiple lines on narrow screens, with enough detail to explain what happens next.</p><p>Additional guidance.</p><template #actions><button class="gx-btn gx-btn--tonal">Choose another file with a longer name</button><a class="gx-btn" href="#fixture">Open settings</a></template></GxNotice>
<section class="gx-card gx-tuner__section"><div class="gx-actions"><button class="gx-btn">Download tune</button></div><GxNotice tone="success">Tune backup download started.</GxNotice></section>
<GxNotice busy>Connecting to your comma…</GxNotice>
<GxNotice>Unable to load https://example.com/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz</GxNotice>
<BluetoothNotice feature="Replay"/>`,
@@ -34,6 +35,8 @@ const assert = require('node:assert/strict')
const icon = banner.querySelector('.gx-alert__icon').getBoundingClientRect()
const actions = banner.querySelector('.gx-alert__actions')
const issues = []
const style = getComputedStyle(banner)
if ([style.paddingTop, style.paddingRight, style.paddingBottom, style.paddingLeft].some(value => parseFloat(value) < 16)) issues.push('insufficient banner padding')
if (Math.abs((icon.top + icon.bottom) / 2 - (body.top + body.bottom) / 2) > 1) issues.push('icon vertical centering')
if (banner.scrollWidth > banner.clientWidth || body.right > box.right) issues.push('overflow')
if (actions) {
@@ -15,11 +15,11 @@ for (const width of [390,1280]) {
await page.setViewportSize({width,height:1100});
for(const [car_type,connection] of [['builtin','wireless'],['adapter','wireless'],['usb','wired'],['app','headunitpad'],['app','openheadunit']]){
await page.evaluate(({car_type,connection})=>{Object.assign(fixture.runtime,{car_type,connection,car_profile:'aawireless',car_profile_source:'override',state:connection==='wired'?'waiting_for_usb':connection==='headunitpad'?'waiting_for_ipad':connection==='openheadunit'?'waiting_for_tablet':'wifi_info'});}, {car_type,connection});
assert.equal(await page.locator('.gx-starport-progress:visible').count(),1);
assert.equal(await page.locator('[aria-label="Connection progress"]:visible').count(),1);
assert.equal(await page.getByRole('button',{name:'Disconnect',exact:true}).count(),1);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false,`${width} ${connection} overflow`);
await page.evaluate(()=>{fixture.showSteps=true;});
assert.equal(await page.locator('.gx-starport-progress:visible').count(),1,'expanded setup has one progress panel');
assert.equal(await page.locator('[aria-label="Connection progress"]:visible').count(),1,'expanded setup has one progress panel');
assert.equal(await page.getByRole('button',{name:'Disconnect',exact:true}).filter({visible:true}).count(),1);
await page.evaluate(()=>{fixture.showSteps=false;});
}
@@ -35,6 +35,6 @@ assert.equal(await page.locator('button').filter({hasText: /^\s*Find car\s*$/}).
assert.equal(await page.getByRole('button',{name:'Connect to car',exact:true}).isEnabled(),false);
await page.evaluate(()=>{fixture.runtime.state='wifi_info';fixture.runtime.running=true;});
await page.emulateMedia({reducedMotion:'reduce'});
assert.equal(await page.locator('.gx-starport-orbit:visible').evaluate(el=>getComputedStyle(el).animationName),'none');
assert.equal(await page.locator('.gx-guided [aria-label="Connection progress"] .gx-spinner:visible').evaluate(el=>getComputedStyle(el).animationName),'none');
assert.deepEqual(errors,[]);await browser.close();console.log('All five device options at phone/desktop sizes, confirmation, failure and single progress/action layout passed.');
})().catch(e=>{console.error(e);process.exit(1)});
@@ -0,0 +1,98 @@
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright')
const assert = require('node:assert/strict')
;(async () => {
const browser = await chromium.launch({ headless: true })
try {
const page = await browser.newPage({viewport:{width:1280,height:1000}})
const errors = [], mutations = []
let parked = true
page.on('pageerror', error => errors.push(error.message))
await page.route('**/maintenance-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>'}))
await page.route('**/api/**', route => {
const path = new URL(route.request().url()).pathname
if (route.request().method() === 'POST') mutations.push({path,body:route.request().postDataJSON()})
let data
if (path.endsWith('/pages/resets')) data = {page:'resets',view:'resets',parked,vehicleIdentified:false, rows:[
{label:'Reset Driver Monitoring',reason:'Clear saved wheel-side detection. Automatic detection restarts on the next drive.',available:parked},
{label:'Reset Calibration',reason:'Clear saved camera and steering calibration. The device recalibrates on the next drive.',available:parked}]}
else if (path.endsWith('/settings/preview')) data = {intent:'device-reset',question:'Clear saved calibration? The device recalibrates on the next drive.'}
else if (path.endsWith('/settings/confirm')) data = {saved:true}
else if (path.endsWith('/settings/backup')) data = {format:'galaxy-toggles',version:1,settings:[]}
else if (path.endsWith('/settings/restore')) data = {complete:true,restored:1,unchanged:0,skipped:[]}
else if (path.endsWith('/settings/non-defaults')) data = {view:'defaults',count:1,rows:[{id:'setting',resetAvailable:parked}]}
else if (path.endsWith('/recovery/preview')) data = {intent:'defaults',question:'Reset one saved setting to default?'}
else if (path.endsWith('/recovery/confirm')) data = {saved:true,applied:['setting']}
else if (path.endsWith('/recordings/action')) data = {deleted:2}
else return route.fulfill({status:404,json:{error:'Unexpected endpoint'}})
return route.fulfill({json:data})
})
await page.goto((process.env.GALAXY_URL || 'http://127.0.0.1:8765/')+'maintenance-test')
await page.evaluate(async () => {
const {createApp} = await import('./vendor/vue/vue.esm-browser.js')
const {SystemMaintenance} = await import('./js/system-maintenance.js')
window.maintenance = createApp(SystemMaintenance,{unauthorized(){}}).mount('#test')
})
const card = page.getByRole('region',{name:'Backup, reset and cleanup'})
assert.equal(await card.evaluate(element=>element.open),false)
const summary = card.locator('summary')
await summary.focus()
await page.keyboard.press('Enter')
await page.getByRole('button',{name:'Reset Calibration',exact:true}).waitFor()
await summary.click()
assert.equal(await card.evaluate(element=>element.open),false)
await summary.click()
assert.equal(await card.locator('.gx-maintenance__content').count(),3)
assert.equal(await card.locator('.gx-card').count(),0)
assert.equal(await card.getByText(/Vehicle not identified|Ready/).count(),0)
assert.equal(await card.getByRole('button',{name:/Search/}).count(),0)
for (const theme of ['light','dark']) for (const width of [320,390,1280]) {
await page.setViewportSize({width,height:1100})
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme)
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false)
const actions = card.locator('.gx-maintenance__content .gx-actions > button')
assert.equal(await actions.count(),6)
assert(await actions.evaluateAll(buttons=>buttons.every(button=>{
const rect=button.getBoundingClientRect()
return rect.left>=0 && rect.right<=innerWidth
})), 'grouped actions fit the viewport')
}
await page.screenshot({path:'/tmp/galaxy-system-maintenance-desktop.png',fullPage:true})
await page.setViewportSize({width:390,height:1100})
await page.screenshot({path:'/tmp/galaxy-system-maintenance-mobile.png',fullPage:true})
assert(await card.getByRole('button',{name:'Reset toggles to default',exact:true}).evaluate(button=>button.classList.contains('gx-btn--danger')))
const download = page.waitForEvent('download')
await card.getByRole('button',{name:'Back up toggles',exact:true}).click()
assert.equal((await download).suggestedFilename(),'toggle-backup.json')
assert.equal(mutations.length,0)
await card.locator('input[type=file]').setInputFiles({name:'backup.json',mimeType:'application/json',buffer:Buffer.from(JSON.stringify({format:'galaxy-toggles',version:1,settings:[]}))})
await page.getByRole('dialog',{name:'Restore toggles?'}).getByRole('button',{name:'Restore',exact:true}).click()
await page.getByText(/1 toggle restored/).waitFor()
await card.getByRole('button',{name:'Reset toggles to default',exact:true}).click()
await page.getByRole('dialog',{name:'Reset toggles to default?'}).getByRole('button',{name:'Reset toggles',exact:true}).click()
await page.getByText('1 setting reset to default.',{exact:true}).waitFor()
await card.getByRole('button',{name:'Reset Calibration',exact:true}).click()
const dialog = page.getByRole('dialog',{name:'Confirm reset'})
await dialog.waitFor()
assert(!mutations.some(item=>item.path.endsWith('/settings/confirm')))
await dialog.getByRole('button',{name:'Cancel',exact:true}).click()
assert(!mutations.some(item=>item.path.endsWith('/settings/confirm')))
await card.getByRole('button',{name:'Reset Driver Monitoring',exact:true}).click()
await dialog.getByRole('button',{name:'Reset',exact:true}).click()
await page.waitForFunction(()=>maintenance.state.status==='ready' && !maintenance.state.pending)
assert(mutations.some(item=>item.path.endsWith('/settings/confirm') && item.body.confirmed===true))
await card.getByRole('button',{name:'Delete all driving routes',exact:true}).click()
assert(!mutations.some(item=>item.path.endsWith('/recordings/action')))
await page.getByRole('alertdialog',{name:'Delete all driving routes?'}).getByRole('button',{name:'Delete routes',exact:true}).click()
await page.getByText('2 driving routes deleted.',{exact:true}).waitFor()
const deletion = mutations.find(item=>item.path.endsWith('/recordings/action'))
assert.deepEqual(deletion.body,{action:'delete-all',confirmed:true,includePreserved:true})
parked = false
await page.evaluate(()=>maintenance.feed.load('resets'))
assert.equal(await card.getByRole('button',{name:'Reset Calibration',exact:true}).isDisabled(),true)
assert.equal(await card.getByRole('button',{name:'Reset Driver Monitoring',exact:true}).isDisabled(),true)
assert.deepEqual(errors,[])
console.log('Unified maintenance layout, download/restore, reset previews, cancellation, deletion confirmation and parked guards passed.')
} finally { await browser.close() }
})().catch(error=>{console.error(error);process.exit(1)})
@@ -12,7 +12,7 @@ const { resolve } = require('node:path')
const catalog = JSON.parse(readFileSync(resolve(__dirname, '../../web/data/catalog.json')))
let local = false, delayed = false
const groups = [['aol', 'Always On Lateral'], ['lane_change', 'Lane Changes'],
['torque', 'Steering and Torque'], ['lane', 'Lane Centering'],
['torque', 'Steering & Torque'], ['lane', 'Lane Centering'],
['profiles','Long Planner'], ['standard','Standard Personality']]
await page.route('**/data/runtime.json', route => route.fulfill({
@@ -44,7 +44,7 @@ const projection = JSON.parse(execFileSync(process.env.PYTHON || 'python3', ['-c
assert.equal(await page.locator('.gx-layout__drag-ghost').isVisible(), true)
assert.equal(await page.locator('.gx-layout__outline').first().isVisible(), true)
assert.equal(await page.locator('.is-drop-target').count(), 1)
assert.equal(await page.evaluate(() => window.editor.renderWidgets.at(-1).id), 'pip_left')
assert.deepEqual(await page.evaluate(() => window.editor.renderWidgets.slice(-2).map(widget => widget.kind)), ['pip_camera', 'pip_camera'])
assert.equal(await page.evaluate(() => window.editor.state.history.undo.length), 0)
await page.screenshot({path:path.join(tmpdir(), 'theme-live-layer-drag.png')})
await page.mouse.up()
@@ -58,6 +58,8 @@ const projection = JSON.parse(execFileSync(process.env.PYTHON || 'python3', ['-c
.filter(id => window.editor.state.draft.layouts.large[id].enabled))
assert.equal(order.at(-1), 'pip_left')
assert.equal(await page.getByRole('button', {name:/Move .* (forward|backward)/}).count(), 0)
const client = await page.context().newCDPSession(page)
await client.send('Emulation.setTouchEmulationEnabled', {enabled:true})
await page.setViewportSize({width:390,height:844})
await rows.first().evaluate(row => row.scrollIntoView({block:'center'}))
const touchRows = await rows.evaluateAll(elements => {
@@ -66,12 +68,10 @@ const projection = JSON.parse(execFileSync(process.env.PYTHON || 'python3', ['-c
.slice(0, 2).map(row => ({ id: row.dataset.layerId, box: row.getBoundingClientRect().toJSON(),
grip: row.querySelector('.gx-layout__row-grip').getBoundingClientRect().toJSON() }))
})
assert.equal(touchRows.length, 2, 'two rows are visible below the pinned preview and tabs')
assert.equal(touchRows.length, 2, 'two widget rows remain visible while scrolling')
const handle = touchRows[0].grip, target = touchRows[1].box
const beforeTouch = await page.evaluate(() => window.editor.state.draft.widgetOrder.large
.filter(id => window.editor.state.draft.layouts.large[id].enabled))
const client = await page.context().newCDPSession(page)
await client.send('Emulation.setTouchEmulationEnabled', {enabled:true})
const touch = (x, y) => [{x, y, id:1}]
await client.send('Input.dispatchTouchEvent', {type:'touchStart', touchPoints:touch(handle.x + handle.width / 2, handle.y + handle.height / 2)})
await client.send('Input.dispatchTouchEvent', {type:'touchMove', touchPoints:touch(target.x + target.width / 2, target.y + target.height / 2)})
@@ -117,7 +117,6 @@
"StarPortDedicatedWifi",
"StarPortHeadUnitExperiments",
"StarPortKeyframeTest",
"StarPortNewSetup",
"StarPortPatientConnect",
"StarPortTallHevc",
"StarPortUnackedVideo",
@@ -182,7 +181,6 @@
"display:auto:ScreenBrightness",
"display:auto:ScreenBrightnessOnroad",
"enable_human_turn_detection_curv",
"heading:starport",
"lane_change:auto",
"lane_change:close_gap",
"lane_change:close_gap_seconds",
@@ -45,5 +45,5 @@ assert.equal(AppDownloadReminder.computed.visible.call(context), false)
const app = readFileSync(new URL('../web/js/app.js', import.meta.url), 'utf8')
assert.match(app, /<AppDownloadReminder v-if="route.path === '\/' && !state.loading && !state.updateRestarting/)
const settings = readFileSync(new URL('../web/js/settings.js', import.meta.url), 'utf8')
assert.match(settings, /<AppReminderSettings v-if="state.developerOpen"/)
console.log('App reminder platform, native exclusion, persistence and Developer wiring passed')
assert.match(settings, /<AppReminderSettings v-if="state.data\?\.page === 'browser_preferences'"/)
console.log('App reminder platform, native exclusion, persistence and browser preferences wiring passed')
@@ -17,7 +17,7 @@ class TestDelaySettings(TestCase):
self.context.value = AuthorityContext(True, cp, cp.to_bytes())
hub = self.page('hub')
lateral = [row['label'] for row in hub['rows'] if row.get('page') in ('aol', 'lane_change', 'lane', 'torque', 'torque/developer')]
self.assertEqual(lateral, ['Always On Lateral', 'Lane Changes', 'Lane Centering', 'Steering and Torque', 'Developer Parameters'])
self.assertEqual(lateral, ['Always On Lateral', 'Lane Changes', 'Lane Centering', 'Steering & Torque', 'Developer Parameters'])
page = self.page('torque/developer')
self.assertEqual(page['title'], 'Developer Parameters')
index = next(i for i, row in enumerate(page['rows']) if row['label'] == 'Actuator delay')
@@ -3,7 +3,7 @@
from dataclasses import replace
import json
import pytest
from openpilot.starpilot.galaxy.developer_settings import DeveloperSettingsOwner
from openpilot.starpilot.galaxy.device_settings import DeviceSettingsOwner
from openpilot.starpilot.galaxy.settings import AuthorityContext, SettingsGateway, SettingsChanged
from openpilot.starpilot.galaxy.tests.test_panda_wake_settings import setup as setup, vehicle
from openpilot.starpilot.panda_wake import FirmwareChoice, snapshot, resolve, startup_choice
@@ -12,8 +12,8 @@ from openpilot.starpilot.ui.feature_settings_state import row_request
from openpilot.starpilot.vehicle_selection import encode
def developer(params, state, owner):
return DeveloperSettingsOwner(params, lambda: state.parked)
def device_options(params, state, owner):
return DeviceSettingsOwner(params, lambda: state.parked)
def ignition_row(params, state, owner):
@@ -95,7 +95,7 @@ def test_actual_gateway_vehicle_confirm_and_no_developer_duplicate(setup, monkey
intent = gateway.preview(page['view'], index, 0, 'session', b'generation', value='On')
assert gateway.confirm(intent['intent'], 'session', b'generation')
assert params.get_bool('IgnoreIgnitionLine')
assert all(row['label'] != 'Use CAN Ignition Only' for row in gateway.page('developer', 'session', b'generation')['rows'])
assert all(row['label'] != 'Use CAN Ignition Only' for row in gateway.page('starport_options', 'session', b'generation')['rows'])
def test_startup_uses_exact_registered_cache_for_manual_and_auto(setup):
@@ -132,7 +132,7 @@ def test_2018_bolt_vehicle_ignition_auto_and_device_support(setup, monkeypatch,
index = next(i for i, row in enumerate(page['rows']) if row['label'] == 'Use CAN Ignition Only')
assert index == next(i for i, row in enumerate(page['rows']) if row['label'] == 'Remote Start Boots Comma') + 1
assert page['rows'][index]['available']
assert all(row['label'] != 'Use CAN Ignition Only' for row in gateway.page('developer', 'session', b'generation')['rows'])
assert all(row['label'] != 'Use CAN Ignition Only' for row in gateway.page('starport_options', 'session', b'generation')['rows'])
intent = gateway.preview(page['view'], index, 0, 'session', b'generation', value='On')
assert 'restart' in intent['question'] and 'Panda firmware' in intent['question']
assert gateway.confirm(intent['intent'], 'session', b'generation')
@@ -143,5 +143,5 @@ def test_developer_no_longer_accepts_ignition_requests(setup):
params, state, owner, _ = setup
request = replace(row_request(ignition_row(params, state, owner), 'On'), confirmation=True,
vehicle_fingerprint=state.cp.carFingerprint)
assert not developer(params, state, owner).apply(request)
assert not device_options(params, state, owner).apply(request)
assert not params.get_bool('IgnoreIgnitionLine')
@@ -1,22 +1,20 @@
"""Galaxy developer preference admission, exact saves and drive-start selection."""
"""Galaxy device and longitudinal preference admission, exact saves and drive-start selection."""
from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
from typing import cast
import tempfile
import unittest
from unittest.mock import patch
from openpilot.starpilot.galaxy.developer_settings import (CALIBRATION_RESET, DRIVER_MONITORING_RESET, STARPORT_EXPERIMENT_PREFIX,
from openpilot.starpilot.galaxy.device_settings import (CALIBRATION_RESET, DRIVER_MONITORING_RESET, STARPORT_EXPERIMENT_PREFIX,
STARPORT_EXPERIMENTS_KEY,
STARPORT_HEADING_KEY, STARPORT_HEVC_KEY, STARPORT_KEYFRAME_TEST_KEY,
STARPORT_HEVC_KEY, STARPORT_KEYFRAME_TEST_KEY,
STARPORT_TALL_HEVC_KEY, STARPORT_UNACKED_VIDEO_KEY, STARPORT_PATIENT_TCP_KEY,
STARPORT_NEW_SETUP_KEY, STARPORT_WIFI_KEY, DeveloperSettingsOwner)
from openpilot.starpilot.galaxy.settings import AuthorityContext, ContextSource, SettingsChanged, SettingsGateway
STARPORT_WIFI_KEY, DeviceSettingsOwner)
from openpilot.starpilot.galaxy.settings import AuthorityContext, ContextSource, SettingsChanged, SettingsGateway, PAGES
from openpilot.starpilot.longitudinal.voacc import KEY, selected
from openpilot.starpilot.system.starport import new_setup
from openpilot.starpilot.ui.feature_settings_state import FeatureSettingsRequest
@@ -82,7 +80,7 @@ class FakeStarPort:
"head_unit_experiments": self.experiments, "head_unit_experiment_rules": self.rules}}
class DeveloperSettingsTest(unittest.TestCase):
class DeviceSettingsTest(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
@@ -90,12 +88,17 @@ class DeveloperSettingsTest(unittest.TestCase):
self.path = Path(self.params.get_param_path(KEY))
self.cp = SimpleNamespace(openpilotLongitudinalControl=True, notCar=False, dashcamOnly=False, passive=False)
self.parked = True
self.owner = DeveloperSettingsOwner(self.params, lambda: self.parked)
flag = Path(directory.name) / "new_setup"
patch = mock.patch.object(new_setup, "FLAG_PATH", flag)
patch.start()
self.addCleanup(patch.stop)
self.flag = flag
self.owner = DeviceSettingsOwner(self.params, lambda: self.parked)
def test_pages_separate_driving_controls_services_and_resets(self):
from openpilot.starpilot.longitudinal.enhanced_stop_hold import KEY as HOLD_KEY
service = SimpleNamespace(call=unittest.mock.Mock(side_effect=RuntimeError("off")))
owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
self.assertEqual([row.key for row in owner.snapshot("driving_options").rows], [KEY, HOLD_KEY])
self.assertEqual([row.key for row in owner.snapshot("resets").rows], [DRIVER_MONITORING_RESET, CALIBRATION_RESET])
service.call.assert_not_called()
self.assertEqual(owner.snapshot("starport_options").rows, ())
self.assertNotIn("developer", PAGES)
def test_always_hold_default_registry_exact_save_and_parked_authority(self):
from openpilot.common.params import Params, ParamKeyType
@@ -104,14 +107,14 @@ class DeveloperSettingsTest(unittest.TestCase):
self.assertTrue(params.check_key(HOLD_KEY))
self.assertEqual(params.get_type(HOLD_KEY), ParamKeyType.BOOL)
self.assertIs(params.get_default_value(HOLD_KEY), False)
owner = DeveloperSettingsOwner(params, lambda: self.parked)
row = next(row for row in owner.snapshot().rows if row.key == HOLD_KEY)
owner = DeviceSettingsOwner(params, lambda: self.parked)
row = next(row for row in owner.snapshot("driving_options").rows if row.key == HOLD_KEY)
self.assertEqual((row.label, row.value, row.reason), (LABEL, "Off", DESCRIPTION))
self.assertTrue(owner.apply(FeatureSettingsRequest(HOLD_KEY, row.source, "On")))
self.assertTrue(hold_selected(params))
self.assertFalse(owner.apply(FeatureSettingsRequest(HOLD_KEY, row.source, "Off")))
self.parked = False
self.assertFalse(next(row for row in owner.snapshot().rows if row.key == HOLD_KEY).available)
self.assertFalse(next(row for row in owner.snapshot("driving_options").rows if row.key == HOLD_KEY).available)
self.assertFalse(owner.apply(FeatureSettingsRequest(HOLD_KEY, b"1", "Off")))
self.parked = True
self.assertTrue(owner.apply(FeatureSettingsRequest(HOLD_KEY, b"1", "Off")))
@@ -123,7 +126,7 @@ class DeveloperSettingsTest(unittest.TestCase):
self.assertFalse(owner.apply(FeatureSettingsRequest(HOLD_KEY, raw, "On")))
def test_default_off_strict_selection_and_vehicle_admission(self):
self.assertEqual(self.owner.snapshot().rows[0].value, "Off")
self.assertEqual(self.owner.snapshot("driving_options").rows[0].value, "Off")
self.assertFalse(selected(self.params, self.cp))
for raw in (b"0", b"", b"true", b"1\n", b"1" * 9):
with self.subTest(raw=raw):
@@ -145,8 +148,8 @@ class DeveloperSettingsTest(unittest.TestCase):
self.assertTrue(params.check_key(KEY))
self.assertEqual(params.get_type(KEY), ParamKeyType.BOOL)
self.assertIs(params.get_default_value(KEY), False)
owner = DeveloperSettingsOwner(params, lambda: True)
row = owner.snapshot().rows[0]
owner = DeviceSettingsOwner(params, lambda: True)
row = owner.snapshot("driving_options").rows[0]
self.assertEqual(row.value, "Off")
self.assertTrue(owner.apply(FeatureSettingsRequest(KEY, row.source, "On")))
self.assertTrue(params.get_bool(KEY))
@@ -157,7 +160,7 @@ class DeveloperSettingsTest(unittest.TestCase):
self.assertEqual(self.path.read_bytes(), b"1")
self.assertFalse(self.owner.apply(FeatureSettingsRequest(KEY, None, "Off")))
self.parked = False
self.assertFalse(self.owner.snapshot().rows[0].available)
self.assertFalse(self.owner.snapshot("driving_options").rows[0].available)
self.assertFalse(self.owner.apply(FeatureSettingsRequest(KEY, b"1", "Off")))
self.parked = True
self.assertFalse(self.owner.apply(FeatureSettingsRequest(KEY, b"1", "yes")))
@@ -165,7 +168,7 @@ class DeveloperSettingsTest(unittest.TestCase):
self.assertTrue(self.owner.apply(FeatureSettingsRequest(KEY, b"1", "Off")))
self.assertEqual(self.path.read_bytes(), b"0")
self.path.write_bytes(b"garbage")
self.assertFalse(self.owner.snapshot().rows[0].available)
self.assertFalse(self.owner.snapshot("driving_options").rows[0].available)
self.assertFalse(self.owner.apply(FeatureSettingsRequest(KEY, b"garbage", "On")))
def test_real_gateway_preview_save_default_and_authority_recheck(self):
@@ -175,7 +178,7 @@ class DeveloperSettingsTest(unittest.TestCase):
token, generation = "session", b"generation"
def preview(value):
page = gateway.page("developer", token, generation)
page = gateway.page("driving_options", 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"])
@@ -190,7 +193,7 @@ class DeveloperSettingsTest(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("developer", token, generation)
page = gateway.page("driving_options", 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")
@@ -199,28 +202,28 @@ class DeveloperSettingsTest(unittest.TestCase):
gateway.confirm(intent, token, generation, session_valid=lambda: False)
def test_starport_stay_on_wifi_toggle(self):
self.assertNotIn(STARPORT_WIFI_KEY, [row.key for row in self.owner.snapshot().rows])
self.assertNotIn(STARPORT_WIFI_KEY, [row.key for row in self.owner.snapshot("starport_options").rows])
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
row = next(row for row in owner.snapshot().rows if row.key == STARPORT_WIFI_KEY)
owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
row = next(row for row in owner.snapshot("starport_options").rows if row.key == STARPORT_WIFI_KEY)
self.assertEqual((row.value, row.choices, row.available), ("Off", ("Off", "On"), True))
self.assertTrue(owner.apply(FeatureSettingsRequest(STARPORT_WIFI_KEY, row.source, "On")))
self.assertTrue(service.enabled)
self.assertFalse(owner.apply(FeatureSettingsRequest(STARPORT_WIFI_KEY, row.source, "Off"))) # stale view
self.assertFalse(owner.apply(FeatureSettingsRequest(STARPORT_WIFI_KEY, b"1", "maybe")))
self.parked = False
self.assertFalse(next(row for row in owner.snapshot().rows if row.key == STARPORT_WIFI_KEY).available)
self.assertFalse(next(row for row in owner.snapshot("starport_options").rows if row.key == STARPORT_WIFI_KEY).available)
self.assertFalse(owner.apply(FeatureSettingsRequest(STARPORT_WIFI_KEY, b"1", "Off")))
self.parked = True
self.assertTrue(owner.apply(FeatureSettingsRequest(STARPORT_WIFI_KEY, b"1", "Off")))
self.assertFalse(service.enabled)
service.running = False
self.assertNotIn(STARPORT_WIFI_KEY, [row.key for row in owner.snapshot().rows])
self.assertNotIn(STARPORT_WIFI_KEY, [row.key for row in owner.snapshot("starport_options").rows])
self.assertFalse(owner.apply(FeatureSettingsRequest(STARPORT_WIFI_KEY, b"0", "On")))
def test_driver_monitoring_reset_matches_native_semantics_and_guards_preview(self):
self.params.put_bool("IsRhdDetected", True, block=True)
row = next(row for row in self.owner.snapshot().rows if row.key == DRIVER_MONITORING_RESET)
row = next(row for row in self.owner.snapshot("resets").rows if row.key == DRIVER_MONITORING_RESET)
self.assertTrue(row.available)
self.assertTrue(self.owner.apply(FeatureSettingsRequest(DRIVER_MONITORING_RESET, b"1", "confirm", confirmation=True)))
self.assertFalse(Path(self.params.get_param_path("IsRhdDetected")).exists())
@@ -228,48 +231,27 @@ class DeveloperSettingsTest(unittest.TestCase):
self.params.put_bool("IsRhdDetected", True, block=True)
self.params.put_bool("IsDriverViewEnabled", True, block=True)
row = next(row for row in self.owner.snapshot().rows if row.key == DRIVER_MONITORING_RESET)
row = next(row for row in self.owner.snapshot("resets").rows if row.key == DRIVER_MONITORING_RESET)
self.assertFalse(row.available)
self.assertFalse(self.owner.apply(FeatureSettingsRequest(DRIVER_MONITORING_RESET, b"1", "confirm", confirmation=True)))
self.assertTrue(Path(self.params.get_param_path("IsRhdDetected")).exists())
def test_starport_section_has_a_heading_and_the_escape_hatch_even_with_the_service_off(self):
rows = self.owner.snapshot().rows
def test_starport_section_has_no_legacy_setup_switch(self):
self.assertEqual(self.owner.snapshot("starport_options").rows, ())
service = FakeStarPort()
owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot("starport_options").rows
keys = [row.key for row in rows]
heading = rows[keys.index(STARPORT_HEADING_KEY)]
self.assertEqual((heading.label, heading.value, heading.available, heading.choices), ("StarPort", "", False, ()))
self.assertEqual(keys[keys.index(STARPORT_HEADING_KEY) + 1], STARPORT_NEW_SETUP_KEY) # the heading groups what follows
self.assertNotIn(STARPORT_WIFI_KEY, keys)
self.assertNotIn(STARPORT_HEVC_KEY, keys)
self.assertFalse(self.owner.apply(FeatureSettingsRequest(STARPORT_HEADING_KEY, b"", "On"))) # a heading is never a control
def test_new_pairing_experience_defaults_on_and_the_classic_screens_are_one_switch_away(self):
row = next(row for row in self.owner.snapshot().rows if row.key == STARPORT_NEW_SETUP_KEY)
self.assertEqual((row.value, row.source, row.choices, row.default_value, row.available), ("On", b"1", ("Off", "On"), "On", True))
self.assertFalse(self.owner.apply(FeatureSettingsRequest(STARPORT_NEW_SETUP_KEY, b"0", "On"))) # stale view
self.assertFalse(self.owner.apply(FeatureSettingsRequest(STARPORT_NEW_SETUP_KEY, b"1", "maybe")))
self.assertTrue(self.owner.apply(FeatureSettingsRequest(STARPORT_NEW_SETUP_KEY, b"1", "Off")))
self.assertFalse(new_setup.enabled())
self.assertEqual(next(r for r in self.owner.snapshot().rows if r.key == STARPORT_NEW_SETUP_KEY).value, "Off")
self.parked = False
self.assertFalse(self.owner.apply(FeatureSettingsRequest(STARPORT_NEW_SETUP_KEY, b"0", "On")))
self.parked = True
self.assertTrue(self.owner.apply(FeatureSettingsRequest(STARPORT_NEW_SETUP_KEY, b"0", "On")))
self.assertTrue(new_setup.enabled())
def test_unreadable_or_odd_flag_means_on(self):
self.flag.write_text("garbage")
self.assertTrue(new_setup.enabled())
self.flag.unlink()
self.assertTrue(new_setup.enabled())
self.assertEqual(keys[0], STARPORT_WIFI_KEY)
self.assertNotIn("StarPortNewSetup", keys)
def test_allow_h265_toggle_defaults_off_and_follows_the_daemon(self):
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot().rows
owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot("starport_options").rows
keys = [row.key for row in rows]
self.assertEqual(keys[keys.index(STARPORT_HEADING_KEY):keys.index(STARPORT_HEVC_KEY) + 1],
[STARPORT_HEADING_KEY, STARPORT_NEW_SETUP_KEY, STARPORT_WIFI_KEY, STARPORT_HEVC_KEY])
self.assertEqual(keys[:keys.index(STARPORT_HEVC_KEY) + 1],
[STARPORT_WIFI_KEY, STARPORT_HEVC_KEY])
row = rows[keys.index(STARPORT_HEVC_KEY)]
self.assertEqual((row.value, row.default_value, row.available), ("Off", "Off", True))
self.assertTrue(owner.apply(FeatureSettingsRequest(STARPORT_HEVC_KEY, row.source, "On")))
@@ -283,8 +265,8 @@ class DeveloperSettingsTest(unittest.TestCase):
def test_keyframe_test_defaults_off_and_follows_the_daemon(self):
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot().rows
owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot("starport_options").rows
keys = [row.key for row in rows]
self.assertEqual(keys.index(STARPORT_KEYFRAME_TEST_KEY), keys.index(STARPORT_HEVC_KEY) + 1)
row = rows[keys.index(STARPORT_KEYFRAME_TEST_KEY)]
@@ -295,12 +277,12 @@ class DeveloperSettingsTest(unittest.TestCase):
self.assertFalse(owner.apply(FeatureSettingsRequest(STARPORT_KEYFRAME_TEST_KEY, row.source, "Off"))) # stale view
self.parked = False
self.assertFalse(owner.apply(FeatureSettingsRequest(STARPORT_KEYFRAME_TEST_KEY, b"1", "Off")))
self.assertNotIn(STARPORT_KEYFRAME_TEST_KEY, [row.key for row in DeveloperSettingsOwner(self.params, lambda: True).snapshot().rows])
self.assertNotIn(STARPORT_KEYFRAME_TEST_KEY, [row.key for row in DeviceSettingsOwner(self.params, lambda: True).snapshot("starport_options").rows])
def test_tall_hevc_defaults_off_and_follows_the_daemon(self):
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot().rows
owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot("starport_options").rows
keys = [row.key for row in rows]
self.assertEqual(keys.index(STARPORT_TALL_HEVC_KEY), keys.index(STARPORT_KEYFRAME_TEST_KEY) + 1)
row = rows[keys.index(STARPORT_TALL_HEVC_KEY)]
@@ -312,8 +294,8 @@ class DeveloperSettingsTest(unittest.TestCase):
def test_unacked_video_defaults_off_and_follows_the_daemon(self):
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot().rows
owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot("starport_options").rows
keys = [row.key for row in rows]
row = rows[keys.index(STARPORT_UNACKED_VIDEO_KEY)]
self.assertEqual((row.value, row.default_value, row.available), ("Off", "Off", True))
@@ -323,8 +305,8 @@ class DeveloperSettingsTest(unittest.TestCase):
def test_patient_connect_defaults_off_and_follows_the_daemon(self):
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot().rows
owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = owner.snapshot("starport_options").rows
keys = [row.key for row in rows]
row = rows[keys.index(STARPORT_PATIENT_TCP_KEY)]
self.assertEqual((row.value, row.default_value, row.available), ("Off", "Off", True))
@@ -334,8 +316,8 @@ class DeveloperSettingsTest(unittest.TestCase):
def test_try_experimental_fixes_defaults_off_and_is_the_only_master_switch(self):
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = {row.key: row for row in owner.snapshot().rows}
owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
rows = {row.key: row for row in owner.snapshot("starport_options").rows}
self.assertEqual((rows[STARPORT_EXPERIMENTS_KEY].value, rows[STARPORT_EXPERIMENTS_KEY].default_value), ("Off", "Off"))
self.assertNotIn("StarPortHeadUnitFixes", rows)
self.assertTrue(owner.apply(FeatureSettingsRequest(STARPORT_EXPERIMENTS_KEY, b"0", "On")))
@@ -346,13 +328,13 @@ class DeveloperSettingsTest(unittest.TestCase):
def test_experiment_toggles_appear_only_under_try_experimental_fixes(self):
service = FakeStarPort()
owner = DeveloperSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
keys = [row.key for row in owner.snapshot().rows]
owner = DeviceSettingsOwner(self.params, lambda: self.parked, starport=lambda: service)
keys = [row.key for row in owner.snapshot("starport_options").rows]
self.assertIn(STARPORT_EXPERIMENTS_KEY, keys)
self.assertFalse([key for key in keys if key.startswith(STARPORT_EXPERIMENT_PREFIX)])
self.assertNotIn("heading:starport_experiments", keys)
self.assertTrue(owner.apply(FeatureSettingsRequest(STARPORT_EXPERIMENTS_KEY, b"0", "On")))
rows = owner.snapshot().rows
rows = owner.snapshot("starport_options").rows
keys = [row.key for row in rows]
self.assertEqual(keys[keys.index(STARPORT_EXPERIMENTS_KEY) + 1:],
[STARPORT_EXPERIMENT_PREFIX + "gm_mychevrolet_w28e", STARPORT_EXPERIMENT_PREFIX + "polestar_ps2_aar_301433653",
@@ -374,20 +356,21 @@ class DeveloperSettingsTest(unittest.TestCase):
self.assertFalse(owner.apply(FeatureSettingsRequest(STARPORT_EXPERIMENT_PREFIX + "unknown", b"0", "On")))
self.parked = False
self.assertFalse(owner.apply(FeatureSettingsRequest(rule_key, b"0", "On")))
self.assertFalse(next(r for r in owner.snapshot().rows if r.key == rule_key).available)
self.assertFalse(next(r for r in owner.snapshot("starport_options").rows if r.key == rule_key).available)
def test_experiment_rows_are_hidden_when_the_service_is_off(self):
keys = [row.key for row in self.owner.snapshot().rows]
keys = [row.key for row in self.owner.snapshot("starport_options").rows]
self.assertNotIn(STARPORT_EXPERIMENTS_KEY, keys)
self.assertNotIn(STARPORT_EXPERIMENTS_KEY, keys)
class CalibrationResetSettingsTest(unittest.TestCase):
setUp = DeveloperSettingsTest.setUp
setUp = DeviceSettingsTest.setUp
def test_calibration_reset_adjacent_and_uses_existing_reset_service(self):
with patch("openpilot.starpilot.galaxy.developer_settings.calibration_reset") as reset:
with patch("openpilot.starpilot.galaxy.device_settings.calibration_reset") as reset:
reset.pending = False
rows = self.owner.snapshot().rows
rows = self.owner.snapshot("resets").rows
keys = [row.key for row in rows]
self.assertEqual(keys[keys.index(DRIVER_MONITORING_RESET) + 1], CALIBRATION_RESET)
self.assertTrue(rows[keys.index(CALIBRATION_RESET)].available)
@@ -396,13 +379,13 @@ class CalibrationResetSettingsTest(unittest.TestCase):
reset.request.assert_called_once_with(self.params)
def test_calibration_reset_refuses_onroad_pending_stale_and_wrong_value(self):
with patch("openpilot.starpilot.galaxy.developer_settings.calibration_reset") as reset:
with patch("openpilot.starpilot.galaxy.device_settings.calibration_reset") as reset:
reset.pending = False
request = FeatureSettingsRequest(CALIBRATION_RESET, None, "confirm", confirmation=True)
self.assertFalse(self.owner.apply(replace(request, value="On")))
self.parked = False
self.assertFalse(self.owner.apply(request))
self.assertFalse(next(row for row in self.owner.snapshot().rows if row.key == CALIBRATION_RESET).available)
self.assertFalse(next(row for row in self.owner.snapshot("resets").rows if row.key == CALIBRATION_RESET).available)
self.parked = True
reset.pending = True
self.assertFalse(self.owner.apply(request))
@@ -415,14 +398,14 @@ class CalibrationResetSettingsTest(unittest.TestCase):
reset.request.assert_not_called()
def test_calibration_reset_gateway_requires_confirmation_and_fresh_parked_state(self):
with patch("openpilot.starpilot.galaxy.developer_settings.calibration_reset") as reset:
with patch("openpilot.starpilot.galaxy.device_settings.calibration_reset") as reset:
reset.pending = False
reset.request.return_value = True
context = SimpleNamespace(value=AuthorityContext(True, None, None))
context.sample = lambda: context.value
gateway = SettingsGateway(self.params, cast(ContextSource, context), clock=lambda: 10.)
def preview():
page = gateway.page("developer", "session", b"generation")
page = gateway.page("resets", "session", b"generation")
i = next(i for i,row in enumerate(page["rows"]) if row["label"] == "Reset Calibration")
self.assertTrue(page["rows"][i]["confirm"])
return gateway.preview(page["view"], i, 0, "session", b"generation")
@@ -437,3 +420,4 @@ class CalibrationResetSettingsTest(unittest.TestCase):
pending = preview()
self.assertTrue(gateway.confirm(pending["intent"], "session", b"generation"))
reset.request.assert_called_once()
@@ -64,7 +64,7 @@ assert.match(app, /<FlmPage v-else-if/)
assert.match(app, /:initial-view="route.path === '\/tuning\/plots' \? 'plots' : 'overview'"/)
assert.doesNotMatch(app, /<FlmPage embedded/)
const catalog = JSON.parse(readFileSync(new URL("../web/data/catalog.json", import.meta.url), "utf8"))
assert(catalog.tools.some(tool => tool.path === "/tuning" && tool.name === "Tuning and Analysis"))
assert(catalog.tools.some(tool => tool.path === "/tuning" && tool.name === "Tuning & Analysis"))
assert.equal(catalog.tools.filter(tool => tool.path.startsWith('/tuning')).length, 1)
const driving = readFileSync(new URL('../web/js/driving.js', import.meta.url), 'utf8')
assert.match(driving, /go\('\/tuning'\)/)
@@ -0,0 +1,22 @@
import assert from 'node:assert/strict'
import { File } from 'node:buffer'
import { FlmBackup } from '../web/js/flm-backup.js'
globalThis.File = File
const backup = { format: 'starpilot-flm-tune', version: 2, vehicle: 'test', manual: [], learned: {} }
let downloads = 0, fetched = 0
const link = { click() { downloads++ }, remove() {} }
globalThis.document = { body: { append() {} }, createElement: () => link }
const vm = { busy: false, bluetooth: false, error: '', notice: '', request: async () => { fetched++; return backup } }
await FlmBackup.methods.downloadTune.call(vm)
assert.equal(vm.notice, 'Tune backup download started.')
assert.equal(downloads, 1)
assert.equal(link.download, 'starpilot-flm-tune.json')
assert.deepEqual(await (await fetch(link.href)).json(), backup)
vm.bluetooth = true
await FlmBackup.methods.downloadTune.call(vm)
assert.equal(fetched, 1)
assert.equal(downloads, 1)
assert.doesNotMatch(FlmBackup.template, /Share tune|exportTune|canShare/)
assert.equal(FlmBackup.methods.exportTune, undefined)
console.log('Tune download preserves backup contents and transfer guards; sharing is removed')
@@ -56,9 +56,8 @@ class TestOffroadConfigurationPages(unittest.TestCase):
with self.subTest(page=name):
current = self.editable_inventory(self.page(name))
expected = saved[name]
if name == 'developer':
if name == 'driving_options':
# gated by Park, not by the vehicle
expected, current = ([row for row in rows if row[0] != 'New pairing experience'] for rows in (expected, current))
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])
@@ -16,7 +16,7 @@ class ParkedPowerSettingsTest(unittest.TestCase):
self.assertIsNone(self.params.get(KEY))
self.assertEqual([(r['value'], r['minimum'], r['maximum'], r['step'], r['unit']) for r in page['rows'][1:]],
[('30', 1, 30, 1, 'h'), ('11.8', 11.8, 12.5, 0.1, 'V')])
for index, value in ((1, 6), (2, 12.1), (0, 'On')):
for index, value in ((1, 6), (2, 12.1), (0, 'Custom limits')):
page = self.page('power')
intent = self.gateway.preview(page['view'], index, 0, self.session, self.generation, value=value)
self.assertTrue(self.gateway.confirm(intent['intent'], self.session, self.generation))
@@ -96,7 +96,7 @@ assert.equal(validDocument({...data.document, largeUiGammaTrial: 1}, data.metada
data.document.largeUiGammaTrial = false
assert.match(OnroadLayoutPage.template, /'Large UI Gamma Effect'/)
assert.doesNotMatch(OnroadLayoutPage.template, /Effect Trial|type="checkbox" :checked="state\.draft\.wheelPedalFeedback/)
assert.match(OnroadLayoutPage.template, /switchRow\('Brake and Acceleration Colors', state\.draft\.wheelPedalFeedback === true\)/)
assert.match(OnroadLayoutPage.template, /switchRow\('Brake & Acceleration Colors', state\.draft\.wheelPedalFeedback === true\)/)
const gammaChanges = []
const gammaVm = { projection: true, editable: true,
state: { draft: { largeUiGammaTrial: false }, drag: null, layerDrag: null, notice: '' },
@@ -101,7 +101,7 @@ def test_actual_owner_projections_have_no_uncovered_setting(tmp_path):
from openpilot.starpilot.ui.pip_owner import PiPOwner
from openpilot.starpilot.ui.vasm_owner import VASMOwner
from openpilot.starpilot.ui.sentry_owner import SentryOwner
from openpilot.starpilot.galaxy.developer_settings import DeveloperSettingsOwner
from openpilot.starpilot.galaxy.device_settings import DeviceSettingsOwner
from openpilot.starpilot.ui.presentation import Profile
params = Params(str(tmp_path))
@@ -111,7 +111,8 @@ def test_actual_owner_projections_have_no_uncovered_setting(tmp_path):
assert purpose(row), (page, row.key)
assert _projection(row)['reason'].startswith(purpose(row))
check(DeveloperSettingsOwner(params, lambda: True).snapshot().rows, 'developer')
for page in ('starport_options', 'driving_options', 'resets'):
check(DeviceSettingsOwner(params, lambda: True).snapshot(page).rows, page)
for candidate in (GM.CHEVROLET_BOLT_EUV, GM.CHEVROLET_VOLT, HYUNDAI.HYUNDAI_IONIQ_6,
TOYOTA.TOYOTA_RAV4_TSS2_2023, FORD.FORD_ESCAPE_MK4):
@@ -420,21 +420,14 @@ assert.equal(htmlStates.at(-1).error, "Galaxy could not load settings. Refresh t
htmlFeed.stop()
const sections = (await import('../web/js/settings.js')).SETTINGS_SECTIONS
assert.equal(sections.at(-1).id, 'developer')
const catalog = JSON.parse((await import('node:fs')).readFileSync(new URL('../web/data/catalog.json', import.meta.url), 'utf8'))
assert(!catalog.tools.some(tool => tool.path.startsWith('/developer')))
const category = {state:{section:'lateral',developerOpen:false,cloudOpen:false,data:{page:'hub'}},busy:false,
feed:{active:true,stop(){this.active=false},start(page){this.active=true;category.started=page},
load(page, options){category.loaded={page,options};category.state.data={page}}}}
SettingsPage.methods.selectSection.call(category, sections.at(-1))
assert.equal(category.state.developerOpen, true)
assert.equal(category.feed.active, true)
assert.deepEqual(category.loaded, {page: 'developer', options: {keepData: false, quiet: false}})
SettingsPage.methods.back.call(category)
assert.equal(category.state.developerOpen, true) // Developer is a direct section, with no cloud submenu.
SettingsPage.methods.selectSection.call(category, sections[0])
assert.equal(category.state.developerOpen, false)
assert.deepEqual(category.loaded, {page: 'hub', options: {keepData: false, quiet: false}})
assert(!sections.some(section => section.id === 'developer'))
assert.equal(sections.at(-1).id, 'device')
assert.equal(sections.at(-1).label, 'Device & System')
assert(!sections.some(section => section.id === 'localization'))
assert(sections.at(-1).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.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."]) {
assert.equal(sentryMonitorStatus({ subtitle }).label, "Disarmed")
@@ -474,3 +467,18 @@ const brakeRows = SettingsPage.computed.visibleRows.call({
] } },
})
assert.equal(brakeRows[0].row.label, "Disengage AOL on Brake")
// Browser settings cancel device polling and never require a device request.
{
const { feed, requests, timers } = fixture()
feed.active = true
await feed.load('browser_preferences')
assert.equal(feed.data.page, 'browser_preferences')
assert.equal(requests.length, 0)
feed.scheduleParkedRefresh()
assert.equal(timers.size, 0)
const device = SETTINGS_SECTIONS.at(-1)
const rows = SettingsPage.computed.visibleRows.call({initialPage:'hub', activeSection:device, state:{query:'', data:{page:'hub',rows:[]}}})
assert.deepEqual(rows.map(({row})=>row.page), ['power','data','starport_options','browser_preferences','localization'])
feed.stop()
}
@@ -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"])
"vehicle", "personalities", "driving_options"])
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",
@@ -311,6 +311,20 @@ class SettingsGatewayTest(unittest.TestCase):
self.assertFalse(self.gateway.confirm(intent["intent"], self.session, self.generation))
self.assertEqual(Path(self.params.get_param_path("BlindSpotMetrics")).read_bytes(), b"bad")
def test_data_connections_and_starport_keep_distinct_saved_settings(self):
self.context.value = replace(self.context.value,
cp=ToyotaInterface.get_non_essential_params(ToyotaCar.TOYOTA_COROLLA_TSS2))
data = self.page("data")
self.assertEqual(data["title"], "Data & Connections")
self.assertIn("Always Allow Uploads", [row["label"] for row in data["rows"]])
self.assertNotIn("Stay on Wi-Fi", [row["label"] for row in data["rows"]])
starport = self.page("starport_options")
self.assertEqual(starport["title"], "StarPort")
self.assertNotIn("Always Allow Uploads", [row["label"] for row in starport["rows"]])
sections = self.page("hub")["sections"]
self.assertEqual(sections[-1]["id"], "device")
self.assertNotIn("localization", [section["id"] for section in sections])
def test_developer_sidebar_uses_the_shared_saved_choice(self):
self.context.value = AuthorityContext(False, None, None)
for desired in ("Off", "On"):
@@ -880,7 +894,7 @@ class SettingsGatewayTest(unittest.TestCase):
self.assertEqual(page["rows"][index]["choices"], ["StarPilot Default", "Normal", "Comfort", "Sport"])
intent = self.gateway.preview(page["view"], index, 0, self.session, self.generation, value="Sport")
self.assertEqual(intent["proposed"], "Sport")
self.assertIn("Selected Profile", intent["question"])
self.assertIn("Use global preset", intent["question"])
self.assertTrue(self.gateway.confirm(intent["intent"], self.session, self.generation))
self.assertFalse(self.params.get_bool("CustomPersonalities"))
category = self.page("aggressive/braking")
@@ -204,39 +204,39 @@ assert.deepEqual(SettingsPage.computed.visibleRows.call(page).map(({ index }) =>
const destinations = []
const navigation = { busy: false, state: { query: "old", section: "lateral", data: { page: "lane" } },
feed: { active: true, load: (target) => destinations.push(target) } }
for (const id of ["wheel", "sounds", "device", "visual", "localization"]) {
for (const id of ["wheel", "sounds", "device", "visual"]) {
const section = SETTINGS_SECTIONS.find((item) => item.id === id)
SettingsPage.methods.selectSection.call(navigation, section)
assert.equal(navigation.state.section, id)
assert.equal(navigation.state.query, "")
}
assert.deepEqual(destinations, ["wheel", "sounds", "hub", "hub", "localization"])
assert.deepEqual(destinations, ["wheel", "sounds", "hub", "hub"])
navigation.busy = true
SettingsPage.methods.selectSection.call(navigation, lateral)
assert.equal(destinations.length, 5, "a save cannot be retired by section navigation")
for (const id of ["wheel", "sounds", "localization"]) {
assert.equal(destinations.length, 4, "a save cannot be retired by section navigation")
for (const id of ["wheel", "sounds"]) {
const section = SETTINGS_SECTIONS.find((item) => item.id === id)
assert.equal(SettingsPage.computed.atSectionRoot.call({ activeSection: section,
state: { data: { page: section.pages[0] } } }), true)
}
const deviceData = SETTINGS_SECTIONS.find((item) => item.id === "device")
assert.deepEqual(deviceData.pages, ["power", "display", "data"])
assert.deepEqual(deviceData.pages, ["power", "data", "starport_options", "browser_preferences", "localization"])
assert.equal(SettingsPage.computed.atSectionRoot.call({ activeSection: deviceData,
state: { data: { page: "hub" } } }), true)
assert.equal(SettingsPage.computed.atSectionRoot.call({ activeSection: deviceData,
state: { data: { page: "display" } } }), false)
state: { data: { page: "power" } } }), false)
const dataLinks = SettingsPage.computed.visibleRows.call({ initialPage: "hub", activeSection: deviceData,
state: { query: "", data: { page: "hub", rows: [] } } })
assert.deepEqual(dataLinks.map(({ row }) => row.page), ["power", "display", "data"])
assert.equal(dataLinks[2].row.label, "Data Uploads")
assert.deepEqual(dataLinks.map(({ row }) => row.page), ["power", "data", "starport_options", "browser_preferences", "localization"])
assert.equal(dataLinks[1].row.label, "Data & Connections")
const coolingLinks = SettingsPage.computed.visibleRows.call({ initialPage: "hub", activeSection: deviceData,
state: { query: "", data: { page: "hub", rows: [], coolingAvailable: true } } })
assert.deepEqual(coolingLinks.map(({ row }) => row.page), ["power", "display", "data"])
assert.equal(coolingLinks[2].row.label, "Data Uploads")
assert.equal(dataLinks[0].row.label, "Power and Cooling")
assert.equal(coolingLinks[0].row.label, "Power and Cooling")
assert.deepEqual(coolingLinks.map(({ row }) => row.page), ["power", "data", "starport_options", "browser_preferences", "localization"])
assert.equal(coolingLinks[1].row.label, "Data & Connections")
assert.equal(dataLinks[0].row.label, "Power & Cooling")
assert.equal(coolingLinks[0].row.label, "Power & Cooling")
assert.equal(SettingsPage.computed.atSectionRoot.call({initialPage:'hub',state:{data:null,parents:[]}}),true,
'section tabs stay mounted while loading a new section')
@@ -296,3 +296,10 @@ previewVolume.vm.disabled = true
previewVolume.vm.testAlert = () => { throw new Error("disabled preview must not run") }
await previewVolume.vm.previewSound()
assert.equal(previewVolume.vm.soundError, "Keep the comma offroad")
const visualSection = SETTINGS_SECTIONS.find(section => section.id === "visual")
assert(visualSection.pages.includes("display"))
assert(!deviceData.pages.includes("display"))
const visualLinks = SettingsPage.computed.visibleRows.call({ initialPage: "hub", activeSection: visualSection,
state: { query: "", data: { page: "hub", rows: [] } } })
assert.equal(visualLinks.find(({row}) => row.page === "display").row.label, "Display")
@@ -476,7 +476,7 @@ const starPortTool = catalog.tools.find(tool => tool.path === "/starport")
assert.equal(starPortTool.name, "StarPort")
const audioTool = starPortTool.children
.find(tool => tool.path === "/starport/audio")
assert.equal(audioTool.name, "Spotify and Phone Audio")
assert.equal(audioTool.name, "Spotify & Phone Audio")
assert.match(StarPortPage.template, /href="#\/starport\/audio"/)
assert.ok(app.includes(`SpotifyPage v-else-if="['/starport/audio', '/spotify'].includes(route.path)"`))
// Setup type: what is in the car decides which pairing steps appear.
@@ -500,7 +500,6 @@ typed.control = (action, extra) => typedCalls.push([action, extra])
typed.saveCarType(0, 'Wireless adapter')
typed.saveCarType(0, 'Not a type')
assert.deepEqual(typedCalls, [['car_type', { carType: 'adapter' }]])
assert.deepEqual(new Set(page(setup).carTypeRow.choices), new Set(['Built-in wireless', 'Wireless adapter', 'Wired AA', 'App']))
// A blocked wired port explains itself instead of silently refusing the pick.
const blocked = page(setup)
blocked.feed = { error: '', emit() {} }
@@ -516,8 +515,6 @@ assert.equal(blocked.wiredUnavailable, false, 'already wired: the pick is not bl
// The line names the chosen tablet app.
const named = page(setup)
named.runtime = { car_type: 'app', connection: 'openheadunit' }
assert.equal(named.carTypeRow.value, 'App (Open Headunit)')
assert.ok(named.carTypeRow.choices.includes('App (Open Headunit)'))
const namedCalls = []
named.control = (action, extra) => namedCalls.push([action, extra])
named.saveCarType(0, 'Wireless adapter')
@@ -525,22 +522,15 @@ assert.deepEqual(namedCalls, [['car_type', { carType: 'adapter' }]])
// The adapter model picks the AAWireless tuning; any other adapter keeps the regular pairing.
const dongle = page(setup)
dongle.runtime = { car_type: 'adapter', car_profile: 'default', car_profile_source: 'standard' }
assert.equal(dongle.adapterRow.value, 'Choose one', 'no default: the owner picks')
assert.equal(settingControl(dongle.adapterRow), 'select', 'the initial adapter prompt must open a picker')
assert.match(dongle.pairingReason, /adapter model/)
dongle.runtime = { car_type: 'adapter', car_profile: 'default', car_profile_source: 'override' }
assert.equal(dongle.adapterRow.value, 'Motorola MA1')
assert.deepEqual(dongle.adapterRow.choices, ['AAWireless', 'Motorola MA1', 'Unofficial dongle'])
dongle.runtime = { car_type: 'adapter', car_profile: 'aawireless', car_profile_source: 'override' }
assert.equal(dongle.adapterRow.value, 'AAWireless')
const dongleCalls = []
dongle.control = (action, extra) => dongleCalls.push([action, extra])
dongle.saveAdapter(0, 'Motorola MA1')
dongle.saveAdapter(0, 'AAWireless')
dongle.saveAdapter(0, 'Unofficial dongle')
assert.deepEqual(dongleCalls, [['car_profile', { profile: 'default' }], ['car_profile', { profile: 'aawireless' }], ['car_profile', { profile: 'unofficial' }]])
assert.match(StarPortPage.template, /adapterSetup" :row="adapterRow"/)
assert.match(StarPortPage.template, /What’s in your car\?|carTypeRow/)
assert.match(StarPortPage.template, /runtime\?\.pairing_note/)
assert.match(StarPortPage.template, /'Find ' \+ findLabel/)
// A session that is only waiting or retrying never locks the pickers or Find; it is stopped first.
@@ -552,7 +542,6 @@ idle.runtime = { car_type: 'builtin', running: true, state: 'streaming' }
assert.equal(idle.appDisabled, true)
assert.match(idle.pairingReason, /Disconnect/)
// The home card offers the setup type; the app picker belongs to App only.
assert.match(StarPortPage.template, /v-if="app" :row="appRow"/)
assert.equal(page(setup).homeTitle, 'car')
const wiredHome = page(setup); wiredHome.runtime = { car_type: 'usb', connection: 'wired' }
assert.equal(wiredHome.homeTitle, 'Wired Android Auto')
@@ -118,34 +118,15 @@ assert.equal(guidedState({ setup: null, runtime: running("rfcomm") }).show, fals
// The component emits the page's actions and never invents state.
{
assert.deepEqual(StarPortGuidedSetup.emits, ["choose-type", "choose-adapter", "choose-app", "use-car", "classic", "reset-handshake", "continue-ladder", "dismiss-suggestion", "done"])
assert.deepEqual(StarPortGuidedSetup.emits, ["choose-type", "choose-adapter", "choose-app", "use-car", "reset-handshake", "continue-ladder", "dismiss-suggestion", "done"])
assert.match(StarPortGuidedSetup.template, /v-if="state\.canResetHandshake"[^>]*@click="\$emit\('reset-handshake'\)"/)
const template = StarPortGuidedSetup.template
assert.match(template, /\$emit\('choose-type', choice\.key\)/)
assert.match(template, /\$emit\('use-car', car\.address\)/)
assert.match(template, /\$emit\('classic'\)/)
assert.match(template, /Use classic setup/)
assert.doesNotMatch(template, /\$emit\('classic'\)/)
assert.doesNotMatch(template, /Use classic setup/)
assert.doesNotMatch(template, /v-html/)
}
// The way back to the classic screens posts one narrow action, even when the StarPort service is off.
{
const calls = []
const reply = (body, code = 200) => ({ status: code, ok: code < 300, json: async () => structuredClone(body) })
const feed = new StarPortFeed({ publish: () => {}, fetcher: async (path, options) => {
calls.push([path, options])
return reply(path.endsWith("/setup") ? { enabled: false, bluetoothEnabled: false, parked: true, installReady: true, serviceReady: false,
identity: { installed: true }, import: {}, maxUploadBytes: 1000, newSetup: true } : { newSetup: false })
}, later: () => 1, cancelTimer: () => {} })
assert.equal(await feed.setNewSetup(false), false) // not started yet
feed.active = true
assert.equal(await feed.setNewSetup("no"), false)
assert.equal(await feed.setNewSetup(false), true)
const [path, options] = calls.find(([target]) => target.endsWith("/control"))
assert.equal(path, "./api/starport/control")
assert.deepEqual(JSON.parse(options.body), { action: "new_setup", enabled: false })
assert.equal(options.method, "POST")
}
// Resetting the handshake is one narrow control action.
{
const calls = []
@@ -163,16 +144,11 @@ assert.equal(guidedState({ setup: null, runtime: running("rfcomm") }).show, fals
assert.deepEqual(JSON.parse(options.body), { action: "reset_handshake" })
}
// The page uses the guided card by default and only when the setup response does not say newSetup is off.
// Guided setup is the only setup path, including servers with a stale legacy flag.
{
const template = StarPortPage.template
assert.match(template, /<StarPortGuidedSetup v-if="setup && newSetup && guided\.show"/)
assert.match(template, /@choose-type="chooseType" @choose-adapter="chooseAdapter" @choose-app="chooseApp" @use-car="useCar" @classic="useClassic"/)
assert.match(template, /Try the guided setup/)
const vm = { setup: { newSetup: false } }
assert.equal(StarPortPage.computed.newSetup.call(vm), false)
assert.equal(StarPortPage.computed.newSetup.call({ setup: {} }), true) // default on, including an older server
assert.equal(StarPortPage.computed.newSetup.call({ setup: null }), true)
assert.match(StarPortPage.template, /<StarPortGuidedSetup v-if="setup && guided\.show"/)
assert.doesNotMatch(StarPortPage.template, /newSetup|id="gx-steps"|useClassic|useGuided/)
assert.equal(StarPortFeed.prototype.setNewSetup, undefined)
}
// A car-specific fix is only ever advice on the setup screen: shown when the daemon names one, never otherwise.
{
@@ -261,7 +237,7 @@ console.log("StarPort guided setup: Bluetooth-first hint passed")
assert.match(StarPortGuidedSetup.template, /\$emit\('done'\)/)
}
// Dropdowns belong to the classic screens only; the guided card replaces them and keeps pairing, steps and Connect.
// Guided setup keeps pairing, progress and Connect without the legacy dropdown screens.
{
const template = StarPortPage.template
const guidedBlock = template.slice(template.indexOf("<StarPortGuidedSetup"), template.indexOf("</StarPortGuidedSetup>"))
@@ -270,9 +246,9 @@ console.log("StarPort guided setup: Bluetooth-first hint passed")
assert.match(guidedBlock, /beginPairing/) // Find car / Find adapter
assert.match(guidedBlock, /@click="connect"/) // the Connect button
assert.match(guidedBlock, /Stuck pairing\?/) // the pairing help stays
assert.match(template, /<ol v-if="setup && !newSetup" id="gx-steps"/) // the classic step 2, with its dropdown
assert.doesNotMatch(template, /id="gx-steps"/)
const home = template.slice(template.indexOf("gx-starport-home\" aria-labelledby"))
assert.match(home, /<template v-if="!newSetup">\s*<GalaxySettingRow :row="carTypeRow"/)
assert.doesNotMatch(home, /carTypeRow|adapterRow|appRow/)
assert.match(StarPortGuidedSetup.template, /gx-guided__steps/)
assert.match(StarPortGuidedSetup.template, /<slot name="car" \/>/)
assert.match(StarPortGuidedSetup.template, /<slot name="connect" \/>/)
@@ -289,7 +265,7 @@ console.log("StarPort guided setup: Bluetooth-first hint passed")
StarPortPage.methods.dismissSuggestion.call({ control: (action, extra) => calls.push([action, extra]) }, "gm_mychevrolet_w28e")
assert.deepEqual(calls, [["dismiss_fix_suggestion", { rule: "gm_mychevrolet_w28e" }]])
}
console.log("StarPort guided setup: steps, adapter and app choices, reopening and classic-only dropdowns passed")
console.log("StarPort guided setup: steps, adapter and app choices, reopening and guided-only controls passed")
// Choosing a cable or an app finishes the setup at once; a choice made in the card must not close the card.
{
@@ -848,7 +848,8 @@ border-radius: var(--radius-full); color: var(--text-muted);
.gx-view > *, .gx-driving > *, .gx-long-curves > *, .gx-vehicle > * { margin-block: 0; }
.gx-view h2, .gx-monitor h2 { margin-top: 0; }
.gx-note { color: var(--text-muted); font-size: var(--fs-sm); }
.gx-alert { --notice-accent: var(--primary); align-items: center; backdrop-filter: var(--glass-blur); -webkit-backdrop-filter: var(--glass-blur); border: 1px solid var(--glass-border); border-left: 4px solid var(--notice-accent); border-radius: var(--radius-md); display: flex; gap: var(--sp-3); width: 100%; margin: 0 0 var(--sp-4); padding: var(--sp-4); background: color-mix(in srgb, var(--notice-accent) 12%, transparent); }
.gx-alert { --notice-accent: var(--primary); align-items: center; backdrop-filter: var(--glass-blur); -webkit-backdrop-filter: var(--glass-blur); border: 1px solid var(--glass-border); border-left: 4px solid var(--notice-accent); border-radius: var(--radius-md); display: flex; gap: var(--sp-3); box-sizing: border-box; min-width: 0; width: 100%; margin: 0; padding: var(--sp-4); background: color-mix(in srgb, var(--notice-accent) 12%, transparent); }
* + .gx-alert { margin-top: var(--sp-4); }
.gx-alert--warn { --notice-accent: var(--warning); }
.gx-alert--danger { --notice-accent: var(--error); }
.gx-alert--success { --notice-accent: var(--success); }
@@ -864,7 +865,10 @@ border-radius: var(--radius-full); color: var(--text-muted);
.gx-alert__actions { margin: 0; justify-content: flex-start; }
.gx-alert__actions .gx-btn { max-width: 100%; white-space: normal; overflow-wrap: anywhere; padding-block: var(--sp-2); box-shadow: none; }
.gx-alert .gx-spinner { border-top-color: var(--notice-accent); }
.gx-settings > .gx-card, .gx-settings > .gx-alert, .gx-stack > .gx-card, .gx-stack > .gx-alert { margin-bottom: 0; }
.gx-alert:first-child { margin-top: 0; }
.gx-alert:last-child { margin-bottom: 0; }
.gx-settings > .gx-card, .gx-stack > .gx-card { margin-bottom: 0; }
.gx-settings > .gx-alert, .gx-stack > .gx-alert { margin-block: 0; }
.gx-menu-tile {
align-items: center;
background: var(--surface-container);
@@ -15,7 +15,7 @@
.gx-navigation__trip {padding:8px 12px;border-radius:20px;background:var(--glass-active-bg);font-size:.85rem;font-weight:650;color:var(--primary)}
.gx-navigation__preview .gx-navigation-map {margin:0;border-radius:0;background:var(--navigation-land)}
.gx-navigation__preview .gx-navigation-map canvas {height:clamp(320px,52vh,640px);background:var(--navigation-land)}
.gx-navigation__preview .gx-navigation-map>.gx-alert {position:absolute;left:8px;right:8px;bottom:36px;margin:0;padding:8px 10px;font-size:.8rem}
.gx-navigation__preview .gx-navigation-map>.gx-alert {position:absolute;left:8px;right:8px;bottom:36px;width:auto;margin:0;font-size:.8rem}
.gx-navigation__empty {display:grid;justify-items:center;text-align:center;align-content:center;min-height:340px;padding:32px;background:radial-gradient(ellipse at center,color-mix(in srgb,var(--primary) 12%,transparent),transparent 70%)}
.gx-navigation__empty>i {font-size:3rem;color:var(--primary);margin-bottom:20px}
.gx-navigation__empty h3 {margin:0}
@@ -12,7 +12,7 @@
.gx-settings__section .gx-section__header--toggle { width: 100%; border: 0; color: inherit; font: inherit; text-align: left; cursor: pointer; }
.gx-settings__developer-body { display: grid; gap: var(--sp-3); }
.gx-settings__developer-provider { display: grid; gap: var(--sp-2); font-weight: var(--fw-medium); }
.gx-settings__save-status { position: fixed; bottom: calc(var(--bottomnav-clearance) + 8px); left: 50%; transform: translateX(-50%); z-index: var(--z-snackbar); padding: var(--sp-2) var(--sp-4); border-radius: var(--radius-full); background: var(--surface-container-high); box-shadow: var(--elev-2); }
.gx-settings__save-status { position: fixed; bottom: calc(var(--bottomnav-clearance) + 8px); left: 50%; transform: translateX(-50%); z-index: var(--z-snackbar); max-width: calc(100vw - 32px); overflow-wrap: anywhere; padding: var(--sp-4); border-radius: var(--radius-full); background: var(--surface-container-high); box-shadow: var(--elev-2); }
.gx-settings__save-status--animated { max-width: calc(100vw - 32px); margin: 0; text-align: center; opacity: 0; visibility: hidden; pointer-events: none; transition: opacity 220ms ease, visibility 0s 220ms; }
.gx-settings__save-status--animated.is-visible { opacity: 1; visibility: visible; transition-delay: 0s; }
@media (prefers-reduced-motion: reduce) { .gx-settings__save-status--animated { transition: none; } }
@@ -939,3 +939,25 @@ html.gx-maker-open, html.gx-maker-open body { touch-action: manipulation; }
.gx-hotspot__field { min-width: 0; max-width: none; }
.gx-hotspot__controls { justify-content: flex-start; }
}
@media (pointer: coarse) {
.gx-layout__preview-card { position: static; }
.gx-layout__sections { position: static; }
.gx-layout__widget-list { gap: 12px; padding-inline: 12px; }
.gx-layout__inspector { padding-bottom: 32px; }
.gx-layout__layer-name { min-height: 48px; }
.gx-layout__tray { padding-block: 16px; }
}
/* Compact groups keep related maintenance actions together. */
.gx-maintenance__content { padding: var(--sp-4); border-bottom: 1px solid var(--outline-variant); }
.gx-route-cleanup .gx-maintenance__content { border-bottom: 0; }
.gx-maintenance__content h3 { margin: 0; }
.gx-maintenance__content .gx-note { margin: var(--sp-2) 0 var(--sp-3); }
.gx-maintenance__content .gx-actions { flex-wrap: wrap; }
.gx-maintenance__group > .gx-alert, .gx-maintenance__feedback { margin: var(--sp-3) var(--sp-4); width: auto; }
.gx-maintenance > summary { cursor: pointer; list-style: none; }
.gx-maintenance > summary::-webkit-details-marker { display: none; }
.gx-maintenance__chevron { margin-left: auto; }
.gx-maintenance[open] .gx-maintenance__chevron { transform: rotate(180deg); }
@@ -16,7 +16,7 @@
"availability": "local-only",
"children": [
{
"name": "Blind Spot Camera and Preview",
"name": "Blind Spot Camera & Preview",
"path": "/cameras/pip",
"icon": "bi-camera-video",
"description": "Adjust the camera crop with a live cabin preview.",
@@ -163,7 +163,7 @@
"availability": "local-only"
},
{
"name": "Tuning and Analysis",
"name": "Tuning & Analysis",
"path": "/tuning",
"icon": "bi-sliders2",
"description": "Automatic steering tuning, measured corrections and live plots",
@@ -178,7 +178,7 @@
"visibility": "authenticated",
"children": [
{
"name": "Spotify and Phone Audio",
"name": "Spotify & Phone Audio",
"path": "/starport/audio",
"icon": "bi-spotify",
"description": "Play Spotify or forward phone music through your comma to your car",
+1 -1
View File
@@ -82,7 +82,7 @@ export const CamerasPage = {
beforeUnmount() { document.removeEventListener("visibilitychange", this.visibility); this.snapshots.stop() },
watch: { mode() { this.snapshots.stop() } },
template: `
<div class="gx-view gx-settings" aria-label="Cameras and Monitoring">
<div class="gx-view gx-settings" aria-label="Cameras & Monitoring">
<h2>Cameras &amp; Monitoring</h2>
<div class="gx-grid">
<MenuTile v-for="tool in tools" :key="tool.path" :icon="tool.icon" :title="tool.name" :description="tool.description"
+3 -3
View File
@@ -13,13 +13,13 @@ export const DRIVING_PAGES = Object.freeze({
})
export const DRIVING_GROUPS = Object.freeze([
{ title: "Steering and buttons", items: [
{ title: "Steering & buttons", items: [
{ page: "aol", title: "Always On Lateral", detail: "Steering assistance independent of cruise control" },
{ page: "lane", title: "Lane centering", detail: "Saved steering behavior" },
{ page: "lane_change", title: "Lane changes", detail: "Saved lane-change choices" },
{ page: "torque", title: "Torque tuning", detail: "Saved steering tune and vehicle-source selection" },
] },
{ title: "Speed and longitudinal", items: [
{ title: "Speed & longitudinal", items: [
{ page: "conditional", title: "Driving Modes", detail: "Automatic, Chill and Experimental" },
{ page: "curve", title: "Curve Speed Controller", detail: "Saved curve-speed choices" },
{ page: "slc", title: "Speed Limit Controller", detail: "Dashboard and qualified vision source choices" },
@@ -51,7 +51,7 @@ export const DrivingPage = {
</section>
<div class="gx-driving__extras gx-actions"><button type="button" class="gx-btn gx-btn--tonal" @click="go('/driving/longitudinal-curves')">Edit longitudinal curves</button>
<button type="button" class="gx-btn gx-btn--tonal" @click="go('/tuning/plots')">Live plots</button>
<button type="button" class="gx-btn gx-btn--tonal" @click="go('/tuning')">Tuning and Analysis</button></div>
<button type="button" class="gx-btn gx-btn--tonal" @click="go('/tuning')">Tuning & Analysis</button></div>
</template>
</section>`,
}
@@ -162,7 +162,7 @@ export const FavoritesPage = {
</GalaxySelect></label>
<label v-if="slot.key === '__starpilot_controller_action__:set_speed'">Set speed (device units)<input class="gx-field" type="number" min="5" max="145" step="1" :value="slot.value ?? 30" :disabled="disabled" @change="speed(index, $event)"></label>
<label>Label<input class="gx-field" type="text" maxlength="32" :aria-label="'Quick Select ' + (index + 1) + ' label'" :value="slot.label" :disabled="disabled || !slot.key" @change="label(index, $event)"></label>
<div class="gx-row"><div class="gx-row__info"><span class="gx-row__label">Show onroad · Big and Small UI</span></div>
<div class="gx-row"><div class="gx-row__info"><span class="gx-row__label">Show onroad · Big & Small UI</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" :aria-label="'Show favorite ' + (index + 1) + ' onroad'" :checked="slot.show_onroad" :disabled="disabled || !slot.enabled || !slot.key" @change="toggle(index, 'show_onroad', $event)"><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<p v-if="slot.key" class="gx-note">{{ state.data.states[index].stateLabel }}<template v-if="state.data.states[index].reason"> · {{ state.data.states[index].reason }}</template></p>
<button class="gx-btn gx-btn--tonal" type="button" :disabled="disabled || !slot.key" @click="feed.update(index, {key:null})">Clear slot</button>
@@ -24,22 +24,18 @@ export const FlmBackup = {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } }) }
catch (error) { if (error.status === 401) this.unauthorized();throw error }
},
async exportTune(share = false) {
async downloadTune() {
if (this.busy || this.bluetooth) return
this.busy = true;this.error = this.notice = ''
try {
const text = JSON.stringify(await this.request('./api/flm/backup'))
parseTune(text)
const file = new File([text], 'starpilot-flm-tune.json', { type: 'application/json' })
if (share && navigator.canShare?.({ files: [file] })) {
await navigator.share({ files: [file], title: 'FLM tune backup' });this.notice = 'Tune shared.'
} else {
const url = URL.createObjectURL(file), link = document.createElement('a')
try { link.href = url;link.download = file.name;document.body.append(link);link.click() }
finally { link.remove();setTimeout(() => URL.revokeObjectURL(url), 1000) }
this.notice = share ? 'Backup download started. Share the file from your downloads.' : 'Tune backup download started.'
}
} catch (error) { if (error.name !== 'AbortError') this.error = error.message || 'Could not export the tune.' }
const url = URL.createObjectURL(file), link = document.createElement('a')
try { link.href = url;link.download = file.name;document.body.append(link);link.click() }
finally { link.remove();setTimeout(() => URL.revokeObjectURL(url), 1000) }
this.notice = 'Tune backup download started.'
} catch (error) { this.error = error.message || 'Could not download the tune.' }
finally { this.busy = false }
},
async chooseFile(event) {
@@ -74,11 +70,10 @@ export const FlmBackup = {
finally { this.busy = false }
},
},
template: `<details class="gx-card gx-tuner__section gx-tuner__disclosure" data-role="flm-backup"><summary>Back up, share or restore your tune</summary>
<p>Export manual sliders and saved Auto Learn setups as a file. Import reviews compatibility before anything changes. Files are shared only when you choose.</p>
template: `<details class="gx-card gx-tuner__section gx-tuner__disclosure" data-role="flm-backup"><summary>Back up or restore your tune</summary>
<p>Download manual sliders and saved Auto Learn setups as a backup file. Import reviews compatibility before anything changes.</p>
<p v-if="bluetooth">Connect over Wi-Fi to transfer tune files.</p><div v-else class="gx-actions">
<button type="button" class="gx-btn gx-btn--tonal" :disabled="busy" @click="exportTune()">Export tune</button>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="busy" @click="exportTune(true)">Share tune</button>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="busy" @click="downloadTune()">Download tune</button>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="busy || !parked" @click="$refs.file.click()">Import tune</button>
<input ref="file" class="gx-sr-only" type="file" accept=".json,application/json" aria-label="Choose FLM tune backup" @change="chooseFile"></div>
<p v-if="!parked">Park and switch off the vehicle to restore settings.</p><p v-if="busy" role="status">Working…</p>
@@ -0,0 +1,9 @@
// Shared compact layout for related System Tools actions.
export const MaintenanceGroup = {
props: { title: String, description: String },
template: `<section class="gx-maintenance__content">
<h3 class="gx-row__label">{{ title }}</h3>
<p class="gx-note">{{ description }}</p>
<div class="gx-actions"><slot /></div>
</section>`,
}
@@ -192,7 +192,7 @@ export const ONROAD_LAYOUT_TEMPLATE = `
<div ref="widgetsHelp" class="gx-layout__subhead gx-layout__help-anchor"><h3>Widgets</h3><span>{{ activeWidgets.length }} active</span>
<button class="gx-icon-btn gx-layout__info" type="button" :aria-expanded="state.widgetsHelpOpen" aria-controls="gx-layout-widgets-help" aria-label="How the widget list works" title="How the widget list works" @click="toggleFloating('widgetsHelpOpen', 'widgetsHelp')"><i class="bi bi-info-circle" aria-hidden="true"></i></button>
<GxCollapse><div v-show="state.widgetsHelpOpen" id="gx-layout-widgets-help" class="gx-layout__popover" @click="closeFloating('widgetsHelpOpen')" @keydown.esc="closeFloating('widgetsHelpOpen')">
<p>Tap a widget to edit it.</p><p>Drag ⠿ to reorder. The top row is in front, and alerts stay above all widgets.</p><p>The eyes follow the chosen scene. Choose General edit to arrange every enabled widget. Hiding a widget with the eye affects only this scene's preview.</p>
<p>Tap a widget to edit it.</p><p>Drag ⠿ to reorder. The top row is in front. Side cameras always overlay other widgets; alerts remain above them.</p><p>The eyes follow the chosen scene. Choose General edit to arrange every enabled widget. Hiding a widget with the eye affects only this scene's preview.</p>
</div></GxCollapse>
</div>
<div class="gx-layout__widget-list"><div v-for="widget in listWidgets" :key="widget.id" class="gx-layout__layer" :data-layer-id="widget.id"
@@ -274,9 +274,9 @@ export const ONROAD_LAYOUT_TEMPLATE = `
:disabled="!editAvailable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setSpeedSources('speedSourcesCard', value === 'On')" />
<div v-if="!projection && selectedWidget.kind === 'cruise_limits'" class="gx-row"><div class="gx-row__info"><span class="gx-row__label">Show set speed</span></div>
<label class="gx-switch"><input type="checkbox" role="switch" aria-label="Show set speed" :checked="state.draft.showMaxSpeed !== false" :disabled="!editAvailable || !!state.drag || !!state.layerDrag" @change="setShowMaxSpeed"><span class="gx-switch__track"></span><span class="gx-switch__thumb"></span></label></div>
<GalaxySettingRow feedback="draft" v-if="projection && selectedWidget.kind === 'steering_wheel'" :row="switchRow('Brake and Acceleration Colors', state.draft.wheelPedalFeedback === true)" :index="0"
<GalaxySettingRow feedback="draft" v-if="projection && selectedWidget.kind === 'steering_wheel'" :row="switchRow('Brake & Acceleration Colors', state.draft.wheelPedalFeedback === true)" :index="0"
:disabled="!editAvailable || !!state.drag || !!state.layerDrag" :save-value="(index, value) => setProjectionDisplay('wheelPedalFeedback', value)" />
<GalaxySettingRow feedback="draft" v-if="!projection && selectedWidget.kind === 'steering_wheel' && displayRow('ShowBrakeStatus')" :row="switchRow('Brake and Acceleration Colors', displayValue('ShowBrakeStatus') === 'On')" :index="0"
<GalaxySettingRow feedback="draft" v-if="!projection && selectedWidget.kind === 'steering_wheel' && displayRow('ShowBrakeStatus')" :row="switchRow('Brake & Acceleration Colors', displayValue('ShowBrakeStatus') === 'On')" :index="0"
:disabled="!editAvailable || !!state.drag || !!state.layerDrag || !displayAvailable(displayRow('ShowBrakeStatus'))" :save-value="(index, value) => setDisplay('ShowBrakeStatus', value)" />
<div v-if="!projection && selectedWidget.kind === 'model_confidence' && displayRow('StockConfidenceBallWidget')" class="gx-layout__favorite-display">
<span>Style</span>
@@ -594,7 +594,8 @@ export const OnroadLayoutPage = {
},
activeWidgets() { return this.widgets.filter(({ id }) => this.layout[id].enabled) },
renderWidgets() {
return this.layerWidgets.filter(item => !this.previewHidden(item.id)).reverse().map((item) => {
return this.layerWidgets.filter(item => !this.previewHidden(item.id)).reverse()
.sort((a, b) => Number(a.kind === "pip_camera") - Number(b.kind === "pip_camera")).map((item) => {
const below = item.visualInsetTop && this.layout[item.id].y < item.visualInsetTop
const widget = {
...item, visualInsetTop: below ? 0 : item.visualInsetTop || 0,
+2 -2
View File
@@ -174,8 +174,8 @@ export const PipPage = {
},
},
template: `
<section class="gx-settings gx-pip" aria-label="Blind Spot Camera and Preview saved settings" :inert="busy" :aria-busy="busy || undefined">
<header class="gx-settings__header gx-page-header"><div><h2>Blind Spot Camera and Preview</h2>
<section class="gx-settings gx-pip" aria-label="Blind Spot Camera & Preview saved settings" :inert="busy" :aria-busy="busy || undefined">
<header class="gx-settings__header gx-page-header"><div><h2>Blind Spot Camera & Preview</h2>
<p>Shows a close-up of the cabin window as you drive. Whether it appears on your turn signal or when a car is in your blind spot depends on your settings. Choose which window each side covers and how much to zoom in.</p></div>
<div class="gx-actions"><a class="gx-btn gx-btn--tonal" href="https://wiki.firestar.link/exclusive/cameras-and-monitoring/#pip-blind-spot-camera-preview" target="_blank" rel="noopener noreferrer"><i class="bi bi-book" aria-hidden="true"></i> PiP guide</a>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="bluetooth || state.cameraWarming" @click="liveCamera.refresh()"><i class="bi bi-camera" aria-hidden="true"></i> Take new snapshot</button><button type="button" class="gx-icon-btn" aria-label="Position side cameras" title="Position side cameras" @click="go('/theme_maker')"><i class="bi bi-layout-wtf" aria-hidden="true"></i></button></div></header>
@@ -1,9 +1,10 @@
import { MaintenanceGroup } from "./maintenance-group.js"
import { GxDialog } from "./dialog.js"
import { GxNotice } from "./notice.js"
import { requestJson } from "./startup.js"
export const RouteCleanup = {
components: { GxDialog, GxNotice },
components: { GxDialog, GxNotice, MaintenanceGroup },
props: { unauthorized: { type: Function, required: true } },
data: () => ({ confirmOpen: false, busy: false, error: "", notice: "" }),
methods: {
@@ -27,17 +28,17 @@ export const RouteCleanup = {
},
},
template: `
<section class="gx-card gx-panel gx-stack gx-route-cleanup" :inert="busy" :aria-busy="busy || undefined">
<div class="gx-section__header"><i class="bi bi-trash3" aria-hidden="true"></i><span class="gx-section__title">Driving routes</span></div>
<p class="gx-note">Remove all saved driving routes and their logs. This does not reset settings or software.</p>
<div class="gx-maintenance__group gx-route-cleanup" :inert="busy" :aria-busy="busy || undefined">
<MaintenanceGroup title="Driving routes" description="Delete all saved routes and logs, including preserved routes.">
<button type="button" class="gx-btn gx-btn--danger" :disabled="busy" @click="confirmOpen=true">Delete all driving routes</button>
</MaintenanceGroup>
<GxNotice v-if="error" tone="danger">{{ error }}</GxNotice>
<GxNotice v-if="notice" tone="success">{{ notice }}</GxNotice>
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--danger" @click="confirmOpen=true" :disabled="busy">Delete all driving routes</button></div>
<GxDialog v-if="confirmOpen" labelledby="gx-route-cleanup-title" :alert="true" @close="!busy && (confirmOpen=false)">
<h3 id="gx-route-cleanup-title">Delete all driving routes?</h3>
<p>This permanently removes every saved route, including preserved routes and their logs. Settings and software are not changed.</p>
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--tonal" @click="confirmOpen=false" :disabled="busy">Cancel</button>
<button type="button" class="gx-btn gx-btn--danger" @click="removeAll" :disabled="busy">Delete routes</button></div>
</GxDialog>
</section>`,
</div>`,
}
+41 -27
View File
@@ -23,14 +23,12 @@ 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: ["profiles", "conditional", "curve", "slc", "personalities", "aggressive", "standard", "relaxed", "traffic"] },
{ id: "longitudinal", label: "Longitudinal (Speed & Following)", icon: "bi-speedometer2", pages: ["driving_options", "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: ["appearance", "ui_layout", "favorites", "pip"] },
{ 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"] },
{ id: "device", label: "Device & Data", icon: "bi-hdd", pages: ["power", "display", "data"] },
{ id: "localization", label: "Localization", icon: "bi-globe", pages: ["localization"] },
{ id: "vehicle", label: "Vehicle", icon: "bi-car-front", pages: ["vehicle"] },
{ id: "developer", label: "Developer", icon: "bi-code-slash", pages: ["developer"] },
{ id: "device", label: "Device & System", icon: "bi-hdd", pages: ["power", "data", "starport_options", "browser_preferences", "localization"] },
])
// Crop numeric rows and the inline editor row are controlled from the dedicated
@@ -40,8 +38,19 @@ export const isPipCropRow = (row) => ["Visual camera crop editor", "Camera crop
/^Vehicle (left|right) crop/.test(row.label || "")
const SECTION_LINKS = {
device: [{ label: "Power and Cooling", page: "power", value: "Adjust parked shutdown limits and supported fan cooling" }, { label: "Display", page: "display", value: "Adjust screen brightness and display timing" }, { label: "Data Uploads", page: "data", value: "Choose mobile-data uploads and usage-statistics sharing" }],
visual: [{ label: "Driving Screen Widgets, Colors & Layout", page: "ui_layout" }, { label: "Quick Select", page: "favorites" }, { label: "Blind Spot Camera and Preview", page: "pip" }],
device: [
{ label: "Power & Cooling", page: "power", value: "Adjust parked shutdown limits and supported fan cooling" },
{ label: "Data & Connections", page: "data", value: "Cloud services, remote access, mobile-data uploads and usage-statistics sharing" },
{ label: "StarPort", page: "starport_options", value: "Manage Android Auto connection options" },
{ label: "Browser preferences", page: "browser_preferences", value: "Choose preferences saved for this browser" },
{ label: "Localization", page: "localization", value: "Choose language, units and regional preferences" },
],
visual: [
{ label: "Display", page: "display", value: "Adjust screen brightness and display timing" },
{ label: "Driving Screen Widgets, Colors & Layout", page: "ui_layout" },
{ label: "Quick Select", page: "favorites" },
{ label: "Blind Spot Camera & Preview", page: "pip" },
],
}
const activeSettings = new Set()
@@ -171,7 +180,7 @@ export class SettingsFeed {
}
scheduleParkedRefresh() {
if (!this.active || this.pending || this.request || this.saving || this.pollTimer !== null) return
if (!this.active || this.page === "browser_preferences" || this.pending || this.request || this.saving || this.pollTimer !== null) return
const generation = this.generation
this.pollTimer = this.later(() => {
this.pollTimer = null
@@ -182,6 +191,16 @@ export class SettingsFeed {
async load(page = this.page, { keepData = page === this.page && this.data !== null, quiet = keepData } = {}) {
if (!this.active || this.saving || (quiet && (this.pending || this.request))) return
if (page === "browser_preferences") {
// Browser preferences are local: cancel device requests and polling while this page is open.
this.stop()
this.active = true
activeSettings.add(this)
this.page = page
this.data = { page, title: "Browser preferences", rows: [] }
this.publish({ status: "ready", data: this.data, pending: null, error: "" })
return
}
this.page = page
this.pending = null
if (!keepData) this.data = null
@@ -285,8 +304,8 @@ export const SettingsPage = {
const navigation = route.view
const navigationKey = `${props.initialPage}:${props.initialSection || ""}`
const saved = navigation.settings?.key === navigationKey ? navigation.settings : null
const state = reactive({ status: "idle", data: null, pending: null, error: "", query: "", searchOpen: false, section: props.initialSection || "lateral", layoutOpen: false, layoutPanel: "widgets", favoritesOpen: false, soundChoicesDirty: false, testingSound: false, openCards: [], parents: [], developerOpen: props.initialSection === "developer", panelDirection: 1 })
if (saved) Object.assign(state, { section: saved.section, query: saved.query, searchOpen: saved.searchOpen, parents: saved.parents.slice(), developerOpen: saved.developerOpen })
const state = reactive({ status: "idle", data: null, pending: null, error: "", query: "", searchOpen: false, section: props.initialSection || "lateral", layoutOpen: false, layoutPanel: "widgets", favoritesOpen: false, soundChoicesDirty: false, testingSound: false, openCards: [], parents: [], panelDirection: 1 })
if (saved) Object.assign(state, { section: saved.section, query: saved.query, searchOpen: saved.searchOpen, parents: saved.parents.slice() })
const feed = new SettingsFeed({ publish: (update) => Object.assign(state, update), unauthorized: props.unauthorized })
return { state, feed, sections: SETTINGS_SECTIONS, navigation, navigationKey, restoredPage: saved?.page }
},
@@ -295,12 +314,11 @@ export const SettingsPage = {
busy() { return settingsBusy(this.state) || !!this.state.testingSound || !!this.$refs?.vehicleEditor?.busy },
vehicleSection() { return this.initialPage === "hub" && this.activeSection.id === "vehicle" },
activeSection() {
if (this.state.developerOpen) return this.sections.at(-1)
const page = (this.state.data?.page || "hub").split("/")[0]
return this.sections.find((section) => page === "hub" ? section.id === this.state.section : section.pages.includes(page)) || this.sections[0]
},
atSectionRoot() {
if (this.state.developerOpen || (!this.state.data && this.initialPage === "hub" && !this.state.parents?.length)) return true
if (!this.state.data && this.initialPage === "hub" && !this.state.parents?.length) return true
return this.state.data?.page === "hub" ||
(this.activeSection.pages.length === 1 && this.state.data?.page === this.activeSection.pages[0])
},
@@ -344,14 +362,14 @@ export const SettingsPage = {
},
async mounted() {
if (this.mode !== "local") return
await this.feed.start(this.restoredPage || (this.state.developerOpen ? "developer" : this.initialPage))
await this.feed.start(this.restoredPage || this.initialPage)
await nextTick()
if (this.feed.active && this.navigation.scroll) window.scrollTo(this.navigation.scroll.x, this.navigation.scroll.y)
},
beforeUnmount() {
const { data, section, query, searchOpen, parents, developerOpen } = this.state
const { data, section, query, searchOpen, parents } = this.state
this.navigation.settings = {
key: this.navigationKey, page: data?.page || this.restoredPage || this.initialPage, section, query, searchOpen, parents: parents.slice(), developerOpen,
key: this.navigationKey, page: data?.page || this.restoredPage || this.initialPage, section, query, searchOpen, parents: parents.slice(),
}
this.navigation.searchPage = this.initialPage === "hub" ? "" : this.initialPage
this.feed.stop()
@@ -411,7 +429,6 @@ export const SettingsPage = {
}
this.state.parents = []
this.state.section = section.id
this.state.developerOpen = section.id === "developer"
if (!this.feed.active) { this.feed.start(section.pages.length === 1 ? section.pages[0] : "hub"); return }
this.state.query = ""
const page = section.pages.length === 1 ? section.pages[0] : "hub"
@@ -429,14 +446,12 @@ export const SettingsPage = {
if (this.busy) return true
if (this.state.layoutOpen) { this.$refs.layoutEditor.requestLeave("back"); return true }
if (this.state.favoritesOpen) { if (!this.$refs.favoritesEditor?.busy) this.closeFavorites(); return true }
if (this.state.developerOpen) return false
const nested = this.initialPage === "hub" ? !this.atSectionRoot : this.state.data?.page !== this.initialPage
if (!nested) return false
this.back()
return true
},
back() {
if (this.state.developerOpen) return
this.state.panelDirection = -1
const page = this.state.data?.page || this.initialPage
this.state.section = this.activeSection?.id || this.state.section
@@ -461,12 +476,12 @@ export const SettingsPage = {
template: `
<OnroadLayoutPage ref="layoutEditor" v-if="state.layoutOpen" :mode="mode" :unauthorized="unauthorized" :initial-panel="state.layoutPanel" @target="openLayoutTarget" @close="closeLayout" />
<FavoritesPage ref="favoritesEditor" v-else-if="state.favoritesOpen" :mode="mode" :unauthorized="unauthorized" @close="closeFavorites" />
<section v-else class="gx-settings" :aria-label="title" :inert="busy" :aria-busy="busy || undefined">
<section v-else class="gx-settings" :aria-label="title || state.data?.title || 'Settings'" :inert="busy" :aria-busy="busy || undefined">
<div v-if="title && (initialPage !== 'hub' || atSectionRoot)" class="gx-settings__header gx-page-header"><h2>{{ title }}</h2></div>
<div v-if="mode === 'local' && initialPage === 'hub' && atSectionRoot" class="gx-settings-tabs" aria-label="Settings sections">
<button v-for="section in sections" :key="section.id" type="button" class="gx-chip" :aria-pressed="section.id === activeSection.id" @click="selectSection(section)">{{ section.label }}</button>
</div>
<p class="gx-page-description" v-if="state.developerOpen">Choose developer driving options and cloud services.</p>
<p class="gx-page-description" v-if="state.data?.page === 'data'">Configure cloud services, remote access and data uploads.</p>
<p class="gx-page-description" v-else-if="initialPage === 'pip'">Choose when to show the camera and adjust its saved crop. Use the crop editor for a live preview.</p>
<p class="gx-page-description" v-else-if="(state.data?.page || initialPage) === 'sounds'">Adjust alert and chime volumes. Test alert plays on your comma while offroad; Auto previews a quiet-cabin starting level. Immediate warnings keep their safety volume ramp.</p>
<p class="gx-page-description" v-else-if="(state.data?.page || initialPage) === 'display'">Adjust brightness and screen timing when custom display settings are on.</p>
@@ -482,7 +497,6 @@ export const SettingsPage = {
<div v-else-if="state.data?.page === 'slc'"><p class="gx-page-description">Control how speed limits change your set speed.</p>
<a class="gx-btn gx-btn--tonal" href="https://wiki.firestar.link/exclusive/speed-limit-controller/#vision-speed-limits" target="_blank" rel="noopener noreferrer"><i class="bi bi-book" aria-hidden="true"></i> Vision speed limits guide</a></div>
<p class="gx-page-description" v-else-if="state.data?.page === 'wheel'">Assign what the steering-wheel controls do.</p>
<p class="gx-page-description" v-else-if="state.data?.page === 'data'">Choose what uploads when the vehicle uses mobile data.</p>
<p class="gx-page-description" v-else-if="['aggressive','standard','relaxed'].includes(state.data?.page)">Adjust acceleration, braking and following for this driving style.</p>
<GxState v-if="mode !== 'local'">Local settings are unavailable in preview.</GxState>
<template v-else>
@@ -493,12 +507,12 @@ export const SettingsPage = {
</GxNotice>
<div class="gx-panel-stage" :style="{'--panel-direction': state.panelDirection}">
<Transition name="gx-panel" @before-enter="$event.inert = false" @before-leave="$event.inert = true">
<div v-if="state.data || state.developerOpen || vehicleSection" :key="state.developerOpen ? 'developer' : vehicleSection ? 'vehicle' : state.data.page + activeSection.id" class="gx-settings__body">
<div v-if="state.data || vehicleSection" :key="vehicleSection ? 'vehicle' : state.data.page + activeSection.id" class="gx-settings__body">
<VehicleControlsPage ref="vehicleEditor" v-if="vehicleSection" :mode="mode" :unauthorized="unauthorized" />
<CloudProviderPage ref="cloudProvider" v-if="state.developerOpen" :mode="mode" :unauthorized="unauthorized" />
<ReverseProxySettings v-if="state.developerOpen" :mode="mode" :unauthorized="unauthorized" />
<AppReminderSettings v-if="state.developerOpen" />
<template v-if="!vehicleSection && state.data && (!state.developerOpen || state.data.page === 'developer')">
<CloudProviderPage ref="cloudProvider" v-if="state.data?.page === 'data'" :mode="mode" :unauthorized="unauthorized" />
<ReverseProxySettings v-if="state.data?.page === 'data'" :mode="mode" :unauthorized="unauthorized" />
<AppReminderSettings v-if="state.data?.page === 'browser_preferences'" />
<template v-if="!vehicleSection && state.data && state.data.page !== 'browser_preferences'">
<div v-if="state.data.page === 'pip'" class="gx-settings__actions gx-actions">
<button type="button" class="gx-btn gx-btn--tonal" @click="openCropEditor"><i class="bi bi-crop" aria-hidden="true"></i> Crop editor</button>
</div>
@@ -518,7 +532,7 @@ export const SettingsPage = {
:busy="busy" :disabled="!!state.error || !row.available" :save-value="(index, value) => feed.previewValue(index, value)" :test-alert="state.data.page === 'sounds' ? testAlert : null"
@open="open" @review="(index, direction) => feed.preview(index, direction)" @reset-default="index => feed.resetDefault(index)" />
</div></GxCollapse>
<div v-if="!cardIndex && !visibleRows.length" class="gx-empty">No matching settings.</div>
<div v-if="!cardIndex && !visibleRows.length" class="gx-empty"><template v-if="state.data.page === 'starport_options' && !state.query">Turn on StarPort to manage connection options. <a class="gx-link" href="#/starport">Open StarPort setup</a></template><template v-else>No matching settings.</template></div>
</section>
<SoundPacks v-if="state.data.page === 'sounds'" :unauthorized="unauthorized" :busy="busy" @installed="refreshSoundChoices" />
</template>
@@ -1,11 +1,10 @@
import { SystemMaintenance } from "./system-maintenance.js"
import { DriveStatePanel } from "./drive-state.js"
import { GxDialog } from "./dialog.js"
import { GxState } from "./state.js"
import { GxNotice } from "./notice.js"
import { ToggleBackup } from "./toggle-backup.js"
import { GalaxySelect } from "./galaxy-select.js"
import { GalaxySettingRow, switchRow } from "./galaxy-setting-row.js"
import { RouteCleanup } from "./route-cleanup.js"
const ACTIONS = new Set(["check", "download", "select", "install", "preferences", "install-preferences", "update", "fast", "rollback", "versions", "version", "download-version"])
const REQUEST_STATES = new Set(["pending", "complete", "failed"])
@@ -365,7 +364,7 @@ export class SoftwareStatusFeed {
}
export const SoftwarePage = {
components: { DriveStatePanel, GxDialog, GxState, GxNotice, GalaxySelect, GalaxySettingRow, ToggleBackup, RouteCleanup },
components: { DriveStatePanel, GxDialog, GxState, GxNotice, GalaxySelect, GalaxySettingRow, SystemMaintenance },
name: "SoftwarePage",
props: { mode: { type: String, required: true }, unauthorized: { type: Function, required: true }, restarting: { type: Function, default: () => {} },
preparing: { type: Function, default: () => {} }, cancelPreparation: { type: Function, default: () => {} } },
@@ -799,8 +798,7 @@ export const SoftwarePage = {
</form>
</div></details>
</section>
<ToggleBackup :unauthorized="unauthorized" />
<RouteCleanup :unauthorized="unauthorized" />
<SystemMaintenance :unauthorized="unauthorized" />
<GxDialog v-if="dialog" labelledby="gx-software-status-confirm-title" @close="closeDialog"><h3 id="gx-software-status-confirm-title">{{ dialog.title }}</h3><p>{{ dialog.message }}</p>
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--tonal" @click="closeDialog">Cancel</button><button type="button" class="gx-btn" @click="confirmDialog">{{ dialog.label }}</button></div>
</GxDialog>
+3 -3
View File
@@ -419,7 +419,7 @@ export const SpotifyPage = {
template: `
<section class="gx-driving gx-spotify" aria-label="Spotify" :aria-busy="busy || undefined">
<header class="gx-page-header">
<h2>Spotify and Phone Audio</h2>
<h2>Spotify & Phone Audio</h2>
<p>Play Spotify on your comma, or send music from your phone through the comma to your car.</p>
</header>
<GxNotice tone="danger" v-if="error && setup">{{ error }}</GxNotice>
@@ -512,7 +512,7 @@ export const SpotifyPage = {
:index="0" :busy="busy" :save-value="(index, value) => setEnabled(value === 'On')" />
<div class="gx-actions">
<button type="button" class="gx-btn gx-btn--tonal" :aria-expanded="showSetup" aria-controls="gx-spotify-steps" @click="showSetup = !showSetup">
<i :class="showSetup ? 'bi bi-chevron-up' : 'bi bi-gear'" aria-hidden="true"></i> {{ showSetup ? 'Hide Setup' : 'Setup and Settings' }}</button>
<i :class="showSetup ? 'bi bi-chevron-up' : 'bi bi-gear'" aria-hidden="true"></i> {{ showSetup ? 'Hide Setup' : 'Setup & Settings' }}</button>
</div>
</section>
@@ -610,7 +610,7 @@ export const SpotifyPage = {
</ol>
<section v-if="setup && !phoneSource && (setupDone ? showSetup : setup.release.installed)" class="gx-card gx-step" aria-labelledby="gx-spotify-manage-title">
<h3 id="gx-spotify-manage-title">Storage and Account</h3>
<h3 id="gx-spotify-manage-title">Storage & Account</h3>
<label class="gx-stack"><span>Music cache</span>
<select class="gx-field" :value="setup.preferences.cacheMb" :disabled="busy" @change="saveCache">
<option v-for="size in setup.cacheChoices" :key="size" :value="size">{{ size >= 1024 ? (size / 1024) + ' GB' : size + ' MB' }}</option>
@@ -159,7 +159,7 @@ export function guidedState({ setup = null, runtime = null, selected = null, rec
export const StarPortGuidedSetup = {
props: { state: { type: Object, required: true }, busy: { type: Boolean, default: false },
choicesDisabled: { type: Boolean, default: false } },
emits: ["choose-type", "choose-adapter", "choose-app", "use-car", "classic", "reset-handshake", "continue-ladder", "dismiss-suggestion", "done"],
emits: ["choose-type", "choose-adapter", "choose-app", "use-car", "reset-handshake", "continue-ladder", "dismiss-suggestion", "done"],
template: `
<section class="gx-card gx-guided" :data-phase="state.phase" aria-label="Guided StarPort setup">
<ol class="gx-guided__steps" aria-label="Setup progress">
@@ -275,7 +275,6 @@ export const StarPortGuidedSetup = {
<div class="gx-guided__footer">
<slot name="connect" />
<button v-if="state.editing" type="button" class="gx-guided__link" :disabled="busy" @click="$emit('done')">Done</button>
<button type="button" class="gx-guided__link" :disabled="busy" @click="$emit('classic')">Use classic setup</button>
</div>
</section>`,
}
+6 -81
View File
@@ -397,18 +397,6 @@ export class StarPortFeed {
return true
}
// The guided setup's way back to the classic screens (and back). It never needs the StarPort service, so it is not a control().
async setNewSetup(enabled) {
if (!this.active || this.busy || typeof enabled !== "boolean") return false
const result = await this.request("./api/starport/control", {
method: "POST",
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "new_setup", enabled })
})
if (result === null) return false
await this.refresh()
return true
}
async setEnabled(enabled, enableBluetooth = false) {
if (!this.active || this.busy || typeof enabled !== "boolean" ||
typeof enableBluetooth !== "boolean" || enableBluetooth && !enabled || enabled && !this.setup?.installReady) return false
@@ -635,7 +623,6 @@ export const StarPortPage = {
return !!(this.supportReady && (this.selected || this.wired || this.app) && !this.pairing?.active &&
!(this.adapterSetup && this.runtime?.car_profile_source !== "override"))
},
newSetup() { return this.setup?.newSetup !== false },
canResetHandshake() { return !this.wired && !this.app && !!this.selected && handshakeResettable(this.runtime?.setup_ladder) },
guided() {
return guidedState({ setup: this.setup, runtime: this.runtime, selected: this.selected, receivers: this.receivers, wired: this.wired,
@@ -649,10 +636,6 @@ export const StarPortPage = {
if (!this.setup?.enabled) return { tone: "expired", label: "Wired StarPort not enabled", detail: "Turn on StarPort in step 1." }
return { tone: "ready", label: "Wired StarPort enabled", detail: "Connect the car’s Android Auto USB data port to the comma’s USB-C port with a data-capable cable." }
},
appRow() {
return { label: "App", value: this.app || "Off", choices: ["Off", ...Object.values(HEAD_UNIT_APPS)], available: true, action: true,
reason: "Project to a tablet app on the same Wi-Fi as the comma or the Galaxy Wi-Fi Hotspot instead of the car." }
},
carType() { return this.runtime?.car_type || (this.wired ? "usb" : this.app ? "app" : "builtin") },
adapterSetup() { return this.carType === "adapter" },
deviceWord() { return this.adapterSetup ? "adapter" : "car" },
@@ -660,17 +643,6 @@ export const StarPortPage = {
findLabel() { return this.adapterSetup ? "adapter" : "car" },
carTypeLabels() { return { ...CAR_TYPES, app: this.app ? `App (${this.app})` : CAR_TYPES.app } },
wiredUnavailable() { return !this.wired && !!this.runtime?.wired_blocked },
carTypeRow() {
const labels = this.carTypeLabels
return { label: "What’s your device?", value: labels[this.carType], choices: Object.values(labels), available: true, action: true,
reason: this.wired ? "Use a data cable from the car to your comma." : this.app ? "Use a tablet on the same Wi-Fi as your comma." : this.adapterSetup ? "Pair the USB adapter, such as AAWireless or Motorola MA1." : "Pair directly with your car’s wireless Android Auto." }
},
adapterRow() {
const chosen = this.runtime?.car_profile_source === "override"
return { label: "Adapter", value: !chosen ? "Choose one" : ADAPTER_MODELS[this.runtime.car_profile] || ADAPTER_MODELS.default,
choices: [...(!chosen ? ["Choose one"] : []), ...Object.values(ADAPTER_MODELS)], available: true, action: true,
reason: "AAWireless gets video and car-data settings tuned for that dongle. Motorola MA1 uses the regular pairing. Pick Unofficial dongle for other wireless dongles that will not connect; it tries alternate handshakes and logs more." }
},
appDisabled() {
return !this.setup?.enabled || !this.setup.parked || !!this.pairing?.active || this.linked
},
@@ -789,11 +761,9 @@ export const StarPortPage = {
chooseType(key) { this.showSteps = true; return this.saveCarType(0, this.carTypeLabels[key]) },
chooseAdapter(key) { this.showSteps = true; return this.saveAdapter(0, ADAPTER_MODELS[key]) },
chooseApp(key) { this.showSteps = true; return this.saveApp(0, HEAD_UNIT_APPS[key]) },
useClassic() { return this.feed.setNewSetup(false) },
resetHandshake() { return this.control("reset_handshake") },
continueLadder() { return this.control("continue_ladder") },
dismissSuggestion(rule) { return this.control("dismiss_fix_suggestion", { rule }) },
useGuided() { return this.feed.setNewSetup(true) },
saveCarType(index, value) {
const labels = this.carTypeLabels
const carType = Object.keys(labels).find(key => labels[key] === value)
@@ -971,8 +941,8 @@ export const StarPortPage = {
</details>
</div></GxCollapse>
</section>
<StarPortGuidedSetup v-if="setup && newSetup && guided.show" id="gx-starport-guided" :state="guided" :busy="busy" :choices-disabled="appDisabled"
@choose-type="chooseType" @choose-adapter="chooseAdapter" @choose-app="chooseApp" @use-car="useCar" @classic="useClassic" @reset-handshake="resetHandshake" @continue-ladder="continueLadder" @dismiss-suggestion="dismissSuggestion" @done="showSteps = false">
<StarPortGuidedSetup v-if="setup && guided.show" id="gx-starport-guided" :state="guided" :busy="busy" :choices-disabled="appDisabled"
@choose-type="chooseType" @choose-adapter="chooseAdapter" @choose-app="chooseApp" @use-car="useCar" @reset-handshake="resetHandshake" @continue-ladder="continueLadder" @dismiss-suggestion="dismissSuggestion" @done="showSteps = false">
<template #car>
<GxNotice v-if="wiredUnavailable" tone="warn">Wired AA is unavailable: {{ runtime.wired_blocked }}.</GxNotice>
<template v-if="carType === 'usb'">
@@ -991,47 +961,7 @@ export const StarPortPage = {
<p v-if="connectReason" class="gx-guided__hint" role="status">{{ connectReason }}</p>
</template>
</StarPortGuidedSetup>
<p v-else-if="setup && !newSetup && !setupDone" class="gx-note"><button type="button" class="gx-btn gx-btn--tonal" :disabled="busy" @click="useGuided">Try the guided setup</button></p>
<ol v-if="setup && !newSetup" id="gx-steps" class="gx-steps">
<li v-show="!setupDone || showSteps" class="gx-card gx-step" :class="{ 'gx-step--done': !!selected && !pairing?.active }">
<div class="gx-step__head">
<span class="gx-step__num" aria-hidden="true"><i v-if="selected && !pairing?.active" class="bi bi-check-lg"></i><template v-else>2</template></span>
<div><h3>{{ carType === 'usb' ? 'Set Up Wired AA' : carType === 'app' ? 'Set Up Your App' : adapterSetup ? 'Pair Your Adapter' : 'Pair Your Car' }}</h3><p>{{ adapterSetup ? 'Put the adapter in pairing mode, then tap Find adapter. Your car doesn’t need to be paired.' : pairsHere ? 'Open your car’s phone pairing screen, then tap Find car. You can do this before step 1 is finished.' : 'No Bluetooth pairing is needed for this setup.' }}</p></div>
</div>
<div class="gx-step__body">
<button v-if="setupDone && showSteps" class="gx-btn gx-btn--tonal" @click="showSteps = false">Hide Setup</button>
<GalaxySettingRow :row="carTypeRow" :index="0" :busy="busy" :disabled="appDisabled" :save-value="saveCarType" />
<GxNotice v-if="wiredUnavailable" tone="warn">Wired AA is unavailable: {{ runtime.wired_blocked }}.</GxNotice>
<GalaxySettingRow v-if="carType === 'app'" :row="appRow" :index="0" :busy="busy" :disabled="appDisabled" :save-value="saveApp" />
<GalaxySettingRow v-if="adapterSetup" :row="adapterRow" :index="0" :busy="busy" :disabled="appDisabled" :save-value="saveAdapter" />
${AUTO_CONNECT}
<template v-if="carType === 'usb'">
${WIRED_STATUS}
</template>
<template v-else-if="carType === 'app'">
${APP_SETUP}
</template>
<template v-if="pairsHere">
${PAIR_UI}
</template>
${CONNECTION_PROGRESS}
${CONNECT}
<p v-if="connectReason" class="gx-note" role="status">{{ connectReason }}</p>
<p v-else-if="!setup.identity.installed" class="gx-note">Finish step 1 first — Connect will walk you through it.</p>
<details class="gx-starport-wiki"><summary>Stuck connecting? Wi-Fi and screen troubleshooting</summary>
<ul>
<li v-if="!wired && !app"><strong>How it connects:</strong> after Bluetooth, the car (or adapter) creates its own hidden 5 GHz Wi-Fi network and tells the comma how to join. The picture streams over that Wi-Fi.</li>
<li><strong>First connection:</strong> stay in Park or offroad mode, and keep the car’s screen on.</li>
<li><strong>Black or frozen screen:</strong> tap Disconnect, wait a few seconds, then connect again. If it keeps happening, turn the car off and on.</li>
<li><strong>Car says the phone isn’t compatible:</strong> make sure wireless Android Auto (sometimes called “smartphone connection”) is turned on in the car’s settings, and that step 1 shows Ready.</li>
<li><strong>Wired AA:</strong> turn on Wired AA in step 2, plug the car’s data USB port into the comma’s USB-C port with a data-capable cable, and drive. Bluetooth pairing is not needed.</li>
</ul>
</details>
</div>
</li>
</ol>
<section v-if="setup && setupDone && !showSteps && (!newSetup || !guided.show)" class="gx-card gx-step gx-starport-home" aria-labelledby="gx-starport-home-title">
<section v-if="setup && setupDone && !showSteps && !guided.show" class="gx-card gx-step gx-starport-home" aria-labelledby="gx-starport-home-title">
<div class="gx-step__head">
<span class="gx-step__num" :class="{ 'gx-starport-home__icon--live': projecting }" aria-hidden="true"><i class="bi bi-car-front"></i></span>
<div><h3 id="gx-starport-home-title">{{ homeTitle }}</h3>
@@ -1039,11 +969,6 @@ export const StarPortPage = {
</div>
<div class="gx-step__body">
<p v-if="expiry.level === 'soon'" class="gx-starport-pill gx-starport-pill--soon" role="status">{{ expiry.label }}</p>
<template v-if="!newSetup">
<GalaxySettingRow :row="carTypeRow" :index="0" :busy="busy" :disabled="appDisabled" :save-value="saveCarType" />
<GalaxySettingRow v-if="adapterSetup" :row="adapterRow" :index="0" :busy="busy" :disabled="appDisabled" :save-value="saveAdapter" />
<GalaxySettingRow v-if="app" :row="appRow" :index="0" :busy="busy" :disabled="appDisabled" :save-value="saveApp" />
</template>
${AUTO_CONNECT}
<ul v-if="wirelessHome" class="gx-starport-list" aria-label="Setup steps">
<li class="gx-starport-row"><i class="bi bi-shield-check" aria-hidden="true"></i>
@@ -1062,8 +987,8 @@ export const StarPortPage = {
${CONNECT}
<div class="gx-actions">
<a class="gx-btn gx-btn--tonal" href="#/theme_maker/starport"><i class="bi bi-layout-text-window" aria-hidden="true"></i> Customize Layout</a>
<button type="button" class="gx-btn gx-btn--tonal" :aria-expanded="showSteps" :aria-controls="newSetup ? 'gx-starport-guided' : 'gx-steps'" @click="showSteps = !showSteps">
<i :class="showSteps ? 'bi bi-chevron-up' : 'bi bi-gear'" aria-hidden="true"></i> {{ showSteps ? 'Hide Setup' : newSetup ? 'Change how your car connects' : 'Setup and Pairing' }}</button>
<button type="button" class="gx-btn gx-btn--tonal" :aria-expanded="showSteps" aria-controls="gx-starport-guided" @click="showSteps = !showSteps">
<i :class="showSteps ? 'bi bi-chevron-up' : 'bi bi-gear'" aria-hidden="true"></i> {{ showSteps ? 'Hide Setup' : 'Change how your car connects' }}</button>
<button v-if="canResetHandshake" type="button" class="gx-btn gx-btn--tonal" :disabled="busy" @click="resetHandshake"
title="Go back to the standard handshake. Your Bluetooth pairing is kept.">
<i class="bi bi-arrow-counterclockwise" aria-hidden="true"></i> Reset handshake</button>
@@ -1077,7 +1002,7 @@ export const StarPortPage = {
<div><h3>Customize Your Dashboard</h3><p>Once connected, customize your dashboard setup.</p></div>
</div>
<div class="gx-step__body">
<a class="gx-btn gx-btn--tonal gx-starport-cta" href="#/starport/audio"><i class="bi bi-spotify" aria-hidden="true"></i> Spotify and Phone Audio</a>
<a class="gx-btn gx-btn--tonal gx-starport-cta" href="#/starport/audio"><i class="bi bi-spotify" aria-hidden="true"></i> Spotify & Phone Audio</a>
<a class="gx-btn gx-btn--tonal gx-starport-cta" href="#/theme_maker/starport">Customize Layout</a>
<a class="gx-btn gx-btn--tonal gx-starport-cta" href="#/navigation/maps"><i class="bi bi-map" aria-hidden="true"></i> Offline Road Maps</a>
<p class="gx-note">Save road lines for the map overlay so it keeps drawing roads with no signal.</p>
@@ -0,0 +1,39 @@
import { SettingsFeed, settingsBusy } from './settings.js'
import { ToggleBackup } from './toggle-backup.js'
import { RouteCleanup } from './route-cleanup.js'
import { MaintenanceGroup } from './maintenance-group.js'
import { GxDialog } from './dialog.js'
import { GxNotice } from './notice.js'
export const SystemMaintenance = {
components: { ToggleBackup, RouteCleanup, MaintenanceGroup, GxDialog, GxNotice },
props: { unauthorized: { type: Function, required: true } },
data() {
const state = { status: 'idle', data: null, pending: null, error: '' }
return { state, feed: null }
},
computed: { busy() { return settingsBusy(this.state) } },
mounted() {
this.feed = new SettingsFeed({ publish: update => Object.assign(this.state, update), unauthorized: this.unauthorized })
this.feed.start('resets')
},
beforeUnmount() { this.feed?.stop() },
template: `<details role="region" class="gx-card gx-maintenance" aria-label="Backup, reset and cleanup">
<summary class="gx-section__header"><i class="bi bi-arrow-counterclockwise" aria-hidden="true"></i><span class="gx-section__title">Backup, Reset &amp; Cleanup</span><i class="bi bi-chevron-down gx-maintenance__chevron" aria-hidden="true"></i></summary>
<ToggleBackup :unauthorized="unauthorized" />
<div class="gx-maintenance__group" :aria-busy="busy || undefined">
<p v-if="!state.data && !state.error" class="gx-note gx-maintenance__feedback" role="status">Loading device resets…</p>
<MaintenanceGroup v-if="state.data" title="Device resets" description="Clear saved driver monitoring or calibration. Relearns on the next drive.">
<button v-for="(row, index) in state.data.rows" :key="row.label" type="button" class="gx-btn gx-btn--tonal"
:disabled="busy || !!state.error || !row.available" @click="feed.preview(index, 0)">{{ row.label }}</button>
</MaintenanceGroup>
<GxNotice v-if="state.error" tone="danger">{{ state.error }}</GxNotice>
</div>
<RouteCleanup :unauthorized="unauthorized" />
<GxDialog v-if="state.pending" labelledby="gx-maintenance-confirm-title" @close="feed.cancel()">
<h3 id="gx-maintenance-confirm-title">Confirm reset</h3><p>{{ state.pending.question }}</p>
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--tonal" @click="feed.cancel()">Cancel</button>
<button type="button" class="gx-btn" @click="feed.confirm()">Reset</button></div>
</GxDialog>
</details>`,
}
@@ -1,3 +1,4 @@
import { MaintenanceGroup } from "./maintenance-group.js"
import { GxDialog } from "./dialog.js"
import { GxNotice } from "./notice.js"
import { requestJson } from "./startup.js"
@@ -6,7 +7,7 @@ import { decodeLayoutBackup, MAX_LAYOUT_BACKUP_BYTES } from "./layout-backup.js"
export const MAX_TOGGLE_BACKUP_BYTES = 256 * 1024
export const ToggleBackup = {
name: "ToggleBackup",
components: { GxDialog, GxNotice },
components: { GxDialog, GxNotice, MaintenanceGroup },
props: { unauthorized: { type: Function, required: true } },
data: () => ({ busy: false, draft: null, resetDraft: null, legacy: false, error: "", notice: "" }),
methods: {
@@ -97,13 +98,14 @@ export const ToggleBackup = {
finally { this.busy = false }
},
},
template: `<section class="gx-card gx-panel gx-stack" :inert="busy" :aria-busy="busy || undefined">
<div class="gx-section__header"><i class="bi bi-cloud-arrow-down" aria-hidden="true"></i><span class="gx-section__title">Toggle backup</span></div><p class="gx-note">Save your editable toggles, onroad layout and colors. Restore compatible settings while parked.</p>
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--tonal" @click="exportBackup">Back up toggles</button>
<button type="button" class="gx-btn gx-btn--tonal" @click="$refs.file.click()">Restore toggles</button>
<button type="button" class="gx-btn gx-btn--tonal" @click="reviewResetDefaults">Reset toggles to default</button>
<input ref="file" type="file" accept=".json,application/json" class="gx-sr-only" tabindex="-1" aria-label="Choose toggle backup" @change="chooseFile"></div>
<p v-if="busy" class="gx-note" role="status"><span class="gx-spinner" aria-hidden="true"></span> Working…</p>
template: `<div class="gx-maintenance__group" :inert="busy" :aria-busy="busy || undefined">
<MaintenanceGroup title="Toggle backup" description="Save your editable toggles, onroad layout and colors. Restore compatible settings while parked.">
<button type="button" class="gx-btn gx-btn--tonal" :disabled="busy" @click="exportBackup">Back up toggles</button>
<button type="button" class="gx-btn gx-btn--tonal" :disabled="busy" @click="$refs.file.click()">Restore toggles</button>
<button type="button" class="gx-btn gx-btn--danger" :disabled="busy" @click="reviewResetDefaults">Reset toggles to default</button>
</MaintenanceGroup>
<input ref="file" type="file" accept=".json,application/json" class="gx-sr-only" tabindex="-1" aria-label="Choose toggle backup" @change="chooseFile">
<p v-if="busy" class="gx-note gx-maintenance__feedback" role="status"><span class="gx-spinner" aria-hidden="true"></span> Working…</p>
<GxNotice v-if="notice" tone="success">{{ notice }}</GxNotice><GxNotice v-if="error" tone="danger">{{ error }}</GxNotice>
<GxDialog v-if="draft" :inert="busy" labelledby="gx-toggle-restore-title" @close="draft=null"><h3 id="gx-toggle-restore-title">Restore {{ legacy ? 'layout' : 'toggles' }}?</h3>
<p>{{ legacy ? 'Replace your saved layout and colors?' : 'Apply the compatible saved toggles, layout and colors from this backup? Unavailable settings will be skipped.' }} Keep the vehicle parked.</p>
@@ -114,7 +116,7 @@ export const ToggleBackup = {
<p>{{ resetDraft.question }}</p>
<p>Keep the vehicle parked. Settings unavailable for this vehicle are left unchanged. Calibration, downloaded models, accounts and network credentials are kept.</p>
<div class="gx-actions"><button type="button" class="gx-btn gx-btn--tonal" @click="resetDraft=null">Cancel</button>
<button type="button" class="gx-btn" @click="resetDefaults">Reset toggles</button></div>
<button type="button" class="gx-btn gx-btn--danger" @click="resetDefaults">Reset toggles</button></div>
</GxDialog>
</section>`,
</div>`,
}
@@ -46,7 +46,7 @@ class TestSteeringDelay(unittest.TestCase):
def test_all_controllers_visible_adjacent_and_default_is_total(self):
hub = self.owner.snapshot('hub', parked=True, system_long=False, lateral_context=True, metric=False).rows
lateral = [row.label for row in hub if row.page in ('aol', 'lane_change', 'lane', 'torque', 'torque/developer')]
self.assertEqual(lateral, ['Always On Lateral', 'Lane Changes', 'Lane Centering', 'Steering and Torque', 'Developer Parameters'])
self.assertEqual(lateral, ['Always On Lateral', 'Lane Changes', 'Lane Centering', 'Steering & Torque', 'Developer Parameters'])
for identity in ('HYUNDAI_IONIQ_6', 'HONDA_CIVIC', 'NISSAN_LEAF', 'CHEVROLET_BOLT_CC_2022_2023'):
self.cp = interfaces[identity].get_non_essential_params(identity)
rows = self.owner.snapshot('torque/developer', parked=True, system_long=False, lateral_context=True, metric=False).rows
+2 -2
View File
@@ -103,7 +103,7 @@ Ordinary personalities keep their existing 45/70 mph follow curve. The global
**Selected Deceleration Profile** and explicit personality braking presets use
different historical scales:
| UI selection | Global or inherited through Selected Profile | Explicit personality preset |
| UI selection | Global or inherited through Use global preset | Explicit personality preset |
| --- | --- | --- |
| Comfort (`eco`) | 0.6 m/s² | 0.5 m/s² |
| Normal (`standard`) | 1.2 m/s² | 1.0 m/s² |
@@ -115,7 +115,7 @@ including a changed SLC cap. Global values preserve the historical
presets retain their original physical values. The distinction preserves
existing tuning and saved-document compatibility.
Comfort is the fresh global default. A personality set to **Selected Profile**
Comfort is the fresh global default. A personality set to **Use global preset**
inherits the global choice; an explicit preset or Custom curve overrides it.
For example, changing from inherited global Sport to explicit personality
Sport changes the cruise braking magnitude from 2.4 to 2.0 m/s².
@@ -1,26 +0,0 @@
"""Persist the setup UI choice independently of the StarPort daemon."""
from pathlib import Path
from openpilot.common.utils import atomic_write
from openpilot.starpilot.system.starport.identity import DATA_DIR
FLAG_PATH = DATA_DIR / "new_setup"
def enabled(path: Path | None = None) -> bool:
"""Absent, unreadable or unrecognized means on; only an explicit 0 turns the new flow off."""
try:
return (path or FLAG_PATH).read_text().strip() != "0"
except (OSError, UnicodeError):
return True
def set_enabled(value: bool, path: Path | None = None) -> bool:
target = path or FLAG_PATH
try:
target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
with atomic_write(str(target), overwrite=True) as handle:
handle.write("1" if value else "0")
except OSError:
return False
return enabled(target) == value
@@ -33,7 +33,7 @@ from pathlib import Path
from typing import Any
from openpilot.common.hardware import COMMA_HARDWARE
from openpilot.starpilot.system.starport import (car_profiles, device_health, head_unit_fixes, identity as identity_store, new_setup, quirk_state,
from openpilot.starpilot.system.starport import (car_profiles, device_health, head_unit_fixes, identity as identity_store, quirk_state,
reachability, setup_ladder, system_slice)
from openpilot.starpilot.system.starport import reconnect_notice
from openpilot.starpilot.system.starport.adapter_syslog import AdapterSyslog
@@ -546,7 +546,6 @@ class Supervisor:
status["experimental_fixes"] = head_unit_fixes.experimental_entries()
status["fix_suggestion"] = self._fix_suggestion()
status["car_candidates"] = list(getattr(self, "_candidates", []))[:8] # paired Android Auto devices to choose between
status["new_setup"] = new_setup.enabled()
status["setup_ladder"] = self._ladder.snapshot(self.config["receiver_address"], self.car_type() == "adapter", self._unofficial_dongle())
status["auto_paused"] = self.auto.suppressed
status["recent"] = list(self.log.recent)[-8:]
@@ -203,9 +203,9 @@ def test_a_session_that_never_got_video_learns_nothing(sup):
assert not sup._video_seen and not sup._ladder.snapshot(RECEIVER)["learned"]
def test_status_shows_the_ladder_the_switch_and_the_cars_to_choose_between(sup):
def test_status_shows_the_ladder_and_the_cars_to_choose_between(sup):
status = sup.status()
assert status["new_setup"] in (True, False) and status["car_candidates"] == []
assert "new_setup" not in status and status["car_candidates"] == []
assert [step["id"] for step in status["setup_ladder"]["steps"]][:2] == ["standard", "other_reply"]
assert status["setup_ladder"]["max_passes"] == sl.MAX_PASSES and not status["setup_ladder"]["learned"]
@@ -882,7 +882,7 @@ class FeatureSettingsOwner:
rows = [self._bool_row("AlwaysAllowUploads", "Always Allow Uploads", self.authority("preferences"),
"Allow queued full logs and videos on metered networks. Uses mobile data.")]
elif page == "power":
title = "Power and Cooling"
title = "Power & Cooling"
if cooling_available():
rows.append(self._bool_row(AGGRESSIVE_COOLING_KEY, "Aggressive Cooling", self.authority("preferences"),
AGGRESSIVE_COOLING_DESCRIPTION))
@@ -890,7 +890,7 @@ class FeatureSettingsOwner:
rows = [FeatureRow("", "Always On Lateral", "Keep steering assistance active independently of cruise control", page=FeaturePage.AOL, available=True),
FeatureRow("", "Lane Changes", "Configure lane-change speed, automatic timing, and driver nudges", page=FeaturePage.LANE_CHANGE, available=True),
FeatureRow("", "Lane Centering", "Adjust lane positioning, lane detection, and steering alerts", page=FeaturePage.LANE, available=True),
FeatureRow("", "Steering and Torque", "Select the steering controller and tune its response", page=FeaturePage.TORQUE, available=True),
FeatureRow("", "Steering & Torque", "Select the steering controller and tune its response", page=FeaturePage.TORQUE, available=True),
FeatureRow('', 'Developer Parameters', 'Advanced steering parameters and total actuator delay',
page=FeaturePage.DEVELOPER_LATERAL, available=True),
FeatureRow("", "Curve Speed Controller", "Adjust how speed is reduced for curves ahead", page=FeaturePage.CURVE, available=True),
@@ -1096,7 +1096,7 @@ class FeatureSettingsOwner:
rows.extend(self.torque.manual_rows(capability, parked and self.authority("torque") and
self.authority("parked_preferences") and capability is not None))
elif page == FeaturePage.TORQUE:
title = "Steering and Torque"
title = "Steering & Torque"
rows.extend(FordBluePilotFeature(self).rows(parked))
controller_row = self.controller.row()
if controller_row is not None:
@@ -1283,7 +1283,7 @@ class FeatureSettingsOwner:
tuple(preset_label(choice) for choice in choices) if valid else (),
available=allowed and valid,
reason=(CATEGORY_HELP[category] if category == 'braking' else
'Personalities set to Selected Profile follow this choice; explicit overrides stay unchanged.'),
'Personalities set to Use global preset follow this choice; explicit overrides stay unchanged.'),
default_value=preset_label('dom_default' if category == 'acceleration' else DEFAULT_DECELERATION_PROFILE)))
unit_value, unit_raw, unit_valid = self._value("IsMetric")
unit_valid = unit_valid and unit_value in ("0", "1") and self._readable("IsMetric")
@@ -317,7 +317,7 @@ def feature_parent_page(page: str) -> str | None:
def feature_parent_title(page: str) -> str:
parent = feature_parent_page(page)
return {None: "StarPilot", FeaturePage.HUB: "Driving Controls", FeaturePage.PROFILES: "Long Planner",
FeaturePage.CONDITIONAL: "Conditional Driving Modes", FeaturePage.TORQUE: "Steering and Torque"}.get(parent, (parent or "").replace("_", " ").title())
FeaturePage.CONDITIONAL: "Conditional Driving Modes", FeaturePage.TORQUE: "Steering & Torque"}.get(parent, (parent or "").replace("_", " ").title())
def boolean_value(row: FeatureRow) -> bool | None:
@@ -278,7 +278,8 @@ class _Canvas:
continue
widget = PROFILES[str(self.profile)]["widgets"][key]
radius = widget["width"] / 2
center = rl.Vector2(position["x"] + radius, position["y"] + radius)
shift = state.viewport_width - 1860 if self.profile == Profile.LARGE and key == "pip_right" and self.viewport is None else 0
center = rl.Vector2(position["x"] + shift + radius, position["y"] + radius)
rl.draw_circle_v(center, radius, rl.Color(21, 44, 57, 230))
rl.draw_ring(center, radius - 3, radius, 0, 360, 64, rl.Color(94, 229, 238, 255))
@@ -14,7 +14,7 @@ LABELS = {
"JerkAcceleration": "acceleration jerk", "JerkDeceleration": "deceleration jerk",
"JerkSpeed": "speed jerk", "JerkSpeedDecrease": "speed decrease jerk", "JerkDanger": "danger jerk",
}
PRESET_LABELS = {"selected_profile": "Selected Profile","dom_default": "StarPilot Default", "standard": "Normal", "eco": "Comfort", "sport": "Sport",
PRESET_LABELS = {"selected_profile": "Use global preset","dom_default": "StarPilot Default", "standard": "Normal", "eco": "Comfort", "sport": "Sport",
"sport_plus": "Sport+", "custom": "Custom", "close": "Close", "medium": "Medium", "far": "Far",
"traffic": "Traffic", "legacy_close": "Legacy Close", "legacy_medium": "Legacy Medium", "legacy_far": "Legacy Far"}
VALUE_HELP = {
@@ -28,10 +28,10 @@ VALUE_HELP = {
}
CATEGORY_HELP = {
"acceleration": "Limits acceleration by speed. Comfort is gentler; Sport and Sport+ allow stronger acceleration. " +
"Selected Profile follows the global choice. " +
"Use global preset follows the global choice. " +
"An explicit choice overrides it; StarPilot Default keeps vehicle behavior.",
"braking": "Comfort/Normal/Sport (m/s²): global 0.6/1.2/2.4; explicit personality 0.5/1.0/2.0. " +
"Selected Profile inherits global values. These separate scales preserve existing tuning. " +
"Use global preset inherits global values. These separate scales preserve existing tuning. " +
"StarPilot Default keeps native cruise braking. Lead and stop braking retain priority.",
"following": "Sets following time by speed and overrides the low/high-speed values. Default uses those values; higher times leave more space.",
}
+6 -3
View File
@@ -19,7 +19,7 @@ from openpilot.starpilot.ui.onroad_rear_fog import render_rear_fog
from openpilot.starpilot.ui import clip
from openpilot.system.ui.lib.application import gui_app
from openpilot.starpilot.ui.onroad_customization import (CLOCK_WIDGET, MODE_WIDGET, RAIL_WIDGETS, STOPPED_TIMER_WIDGET, placement, rgba,
widget_order, widget_size)
rendered_widget_order, widget_size)
from openpilot.starpilot.ui.appearance_preferences import CameraViewChoice
from openpilot.starpilot.ui.onroad_alerts import AlertRenderer
@@ -367,15 +367,18 @@ class OnroadView:
if state.alert.size != AlertSize.FULL:
submit("rear_fog", lambda: render_rear_fog(state, profile))
pending = manual_slc_confirmation(self.fonts.profile, state)
for key in widget_order(state.customization, profile):
for key in rendered_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):
if key not in ('pip_left', 'pip_right') and (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:
self._slc_actions(state)
for key in rendered_widget_order(state.customization, profile):
if key in ('pip_left', 'pip_right') and (only_widget is None or key == only_widget) and (draw := callbacks.get(key)):
draw()
def _large(self, state: OnroadState) -> None:
width, height = self.projection_viewport or (state.viewport_width, 1080)
@@ -230,7 +230,7 @@ for _profile, _geometry in {"large": (112, 70, 165, 294), "compact": (45, 28, 22
ROAD_BASE_WIDTH = 1860
SIDEBAR_EXTRA = 300
ANCHOR_SHIFT = {"steering_wheel": 1.0, NAV_CARD_WIDGET: 1.0, NAV_MAP_WIDGET: 1.0,
ANCHOR_SHIFT = {"steering_wheel": 1.0, "pip_right": 1.0, NAV_CARD_WIDGET: 1.0, NAV_MAP_WIDGET: 1.0,
"current_speed": .5, "torque_bar": .5, MODE_WIDGET: .5, CLOCK_WIDGET: .5, WEATHER_WIDGET: .5}
for _key, _widget_data in PROFILES["large"]["widgets"].items():
if _key in ANCHOR_SHIFT:
@@ -311,6 +311,12 @@ def widget_order(document, profile):
return document.get("widgetOrder", {}).get(str(profile), DEFAULT_WIDGET_ORDER[str(profile)])
def rendered_widget_order(document, profile):
"""Side cameras cover widgets regardless of the saved editor layer order."""
order = widget_order(document, profile)
return [key for key in order if key not in CAMERA_WIDGETS] + [key for key in order if key in CAMERA_WIDGETS]
def widget_bounds(profile, widget):
return PROFILES[profile]["widgets"][widget].get("bounds", PROFILES[profile]["bounds"])
+5 -4
View File
@@ -65,9 +65,10 @@ def render_weather(fonts, state, client, center_shift=0):
icon_size = height * .76
draw_weather_icon(x + height * .09, y + height * .1, icon_size,
reading.code if reading else None, reading.is_day if reading else True)
text = '--°' if reading is None else f'{reading.temperature_c if state.metric else reading.temperature_c * 1.8 + 32:.0f}°'
text += 'C' if state.metric else 'F'
text = 'No data' if reading is None else f'{reading.temperature_c if state.metric else reading.temperature_c * 1.8 + 32:.0f}°'
if reading is not None:
text += 'C' if state.metric else 'F'
color = rl.Color(*rgba(state.customization, 'text', profile, 'weather'))
fonts.draw(text, FontRole.SEMI_BOLD, size, x + height, y + height * .09, color)
fonts.draw('Open-Meteo' if reading else 'Outside', FontRole.NORMAL, 16 if large else 8,
fonts.draw(text, FontRole.SEMI_BOLD, size if reading else size * .65, x + height, y + height * .09, color)
fonts.draw('Open-Meteo' if reading else 'Weather', FontRole.NORMAL, 16 if large else 8,
x + height, y + height * .69, rl.Color(199, 174, 247, min(color.a, 220)))
+1 -1
View File
@@ -186,7 +186,7 @@ class PiPOwner:
reason="" if live else "Open the live crop preview while parked to check the camera."))
defaults = dict.fromkeys(BOOL_KEYS, 'Off')
rows = [replace(row, default_value=defaults[row.key]) if row.key in defaults else row for row in rows]
return FeatureSettingsState(page="pip", title="Blind Spot Camera and Preview",
return FeatureSettingsState(page="pip", title="Blind Spot Camera & Preview",
subtitle="Choose when to show the camera and adjust its crop from the live preview. " +
"Resolution follows the camera automatically.",
rows=tuple(rows), parked=parked)
+8 -6
View File
@@ -10,6 +10,8 @@ from openpilot.starpilot.ui.feature_settings_state import FeatureRow, FeatureSet
ENABLED = "power:enabled"
HOURS = "power:hours"
VOLTS = "power:volts"
POWER_DESCRIPTION = ("Stock uses the standard shutdown policy. Custom limits use the maximum parked time and voltage cutoff below; " +
"other protections can shut down earlier.")
POWER_KEYS = frozenset((ENABLED, HOURS, VOLTS))
HOUR_CHOICES = tuple(f"{hour} h" for hour in range(1, 31))
VOLT_CHOICES = tuple(f"{tenths / 10:.1f} V" for tenths in range(118, 126))
@@ -25,7 +27,7 @@ def power_row_change(row: FeatureRow, direction: int = 1) -> FeatureSettingsRequ
def confirm_question(request: FeatureSettingsRequest) -> str:
if request.key == ENABLED:
if request.value == "On":
if request.value == "Custom limits":
policy = decode(request.expected) if request.expected is not None else PowerPolicy()
if policy is None:
return "Review saved parked-power limits before enabling."
@@ -50,9 +52,9 @@ class PowerOwner:
"Invalid saved policy; choose Stock to repair" if not saved.valid else
"Stock limits apply until a custom policy is saved" if saved.raw is None else "")
inactive = "Saved; stock power policy applies" if saved.valid and not policy.enabled else ""
rows = (FeatureRow(ENABLED, "Parked Power", "Invalid" if not saved.valid else "On" if policy.enabled else "Stock",
source=saved.raw, choices=("Stock", "On"), available=parked and saved.readable,
repair_value="Stock" if not saved.valid else "", reason=reason),
rows = (FeatureRow(ENABLED, "Parked Power", "Invalid" if not saved.valid else "Custom limits" if policy.enabled else "Stock",
source=saved.raw, choices=("Stock", "Custom limits"), available=parked and saved.readable,
repair_value="Stock" if not saved.valid else "", reason=f"{POWER_DESCRIPTION} {reason}".strip()),
FeatureRow(HOURS, "Maximum Parked Time", f"{policy.delay_hours} h" if saved.valid else "Invalid",
source=saved.raw, choices=HOUR_CHOICES, available=parked and saved.readable and saved.valid,
reason=inactive or "Other protections may act sooner"),
@@ -69,11 +71,11 @@ class PowerOwner:
def _desired(saved: SavedPower, request: FeatureSettingsRequest) -> PowerPolicy | None:
policy = saved.policy
if request.key == ENABLED:
if request.value not in ("Stock", "On"):
if request.value not in ("Stock", "Custom limits"):
return None
if not saved.valid and request.value != "Stock":
return None
return replace(policy, enabled=request.value == "On")
return replace(policy, enabled=request.value == "Custom limits")
if not saved.valid:
return None
if request.key == HOURS and request.value in HOUR_CHOICES:
+4 -4
View File
@@ -76,7 +76,7 @@ def reference_feature_scene(scene: str) -> tuple[Destination, str, FeatureSettin
rows = tuple(FeatureRow("", label, "Saved settings", page=page, available=True) for page, label in (
("slc", "Speed Limit Controller"), ("lane", "Lane Centering"), ("lane_change", "Lane Changes"),
("profiles", "Long Planner"), ("conditional", "Conditional Driving Modes"), ("curve", "Curve Speed Controller"),
("torque", "Steering and Torque"), ("aol", "Always On Lateral"), ("wheel", "Wheel Controls")))
("torque", "Steering & Torque"), ("aol", "Always On Lateral"), ("wheel", "Wheel Controls")))
destination, field, page, title = Destination.DRIVING_CONTROLS, "features", "hub", "Driving Controls"
elif scene == "settings_sounds":
rows = (FeatureRow("soundpack", "Sound Pack", "Standard", choices=("Standard", "Classic"), available=True),
@@ -103,7 +103,7 @@ def reference_feature_scene(scene: str) -> tuple[Destination, str, FeatureSettin
presets=(("10 s", "10 s"),)),
FeatureRow(SCREEN_OFF, "Turn Off Comma Screen", "Off", choices=("Off", "On"), available=True,
reason=SCREEN_OFF_DESCRIPTION),
FeatureRow("power:enabled", "Parked Power", "Stock", choices=("Stock", "On"), available=True),
FeatureRow("power:enabled", "Parked Power", "Stock", choices=("Stock", "Custom limits"), available=True),
FeatureRow("power:hours", "Maximum Parked Time", "30 h", page="power:hours", available=True,
reason="Saved; stock power policy applies", presets=(("30 h", "30 h"),)),
FeatureRow("power:volts", "Low-Voltage Cutoff", "11.8 V", page="power:volts", available=True,
@@ -122,7 +122,7 @@ def reference_feature_scene(scene: str) -> tuple[Destination, str, FeatureSettin
elif scene == "settings_pip":
rows = (boolean("pip:enabled", "On"), boolean("pip:blinker", "Off"), number, reset,
FeatureRow("", "Camera availability", "No fresh cabin frame", reason="Check the live crop preview while parked"))
destination, field, page, title = Destination.APPEARANCE, "appearance", "pip", "Blind Spot Camera and Preview"
destination, field, page, title = Destination.APPEARANCE, "appearance", "pip", "Blind Spot Camera & Preview"
else:
rows = (boolean("enabled_off", "Off"), boolean("enabled_on", "On"),
boolean("disabled_off", "Off", available=False), boolean("disabled_on", "On", available=False),
@@ -131,7 +131,7 @@ def reference_feature_scene(scene: str) -> tuple[Destination, str, FeatureSettin
FeatureRow("unreadable", "Saved preference", "Unreadable", reason="Saved source cannot be read"),
FeatureRow("", "Following", ""), number, reset,
FeatureRow("", "Child settings", "Saved settings", page="lane", available=True),
FeatureRow("stock", "Parked Power", "Stock", choices=("Stock", "On"), available=True),
FeatureRow("stock", "Parked Power", "Stock", choices=("Stock", "Custom limits"), available=True),
boolean("last_off", "Off"), boolean("last_on", "On"))
destination, field, page, title = Destination.DRIVING_CONTROLS, "features", "lane", "Feature States"
if scene == "settings_appearance":
+2 -1
View File
@@ -863,7 +863,8 @@ class StarShellSession:
position = placement(state.customization, self.profile, key)
if position["enabled"]:
width, height = widget_size(state.customization, self.profile, key)
camera_positions[side] = Rect(position["x"], position["y"], width, height)
shift = (state.viewport_width - 1860) if self.profile == Profile.LARGE and key == "pip_right" else 0
camera_positions[side] = Rect(position["x"] + shift, position["y"], width, height)
status = self.pip_renderer.render(rect, saved.mask, signals, enabled=True,
on_blinker=saved.on_blinker, on_bsm=saved.on_bsm, invert=saved.invert,
placements=camera_positions, **({"submit": submit} if submit is not None else {}))
+8 -5
View File
@@ -706,11 +706,14 @@ class RuntimeSnapshotAdapter:
weather_location = None
if (started and getattr(ui, 'replay_clock', None) is None and
any(layout.get('weather', {}).get('enabled', False) for layout in self._customization_value['layouts'].values())):
from openpilot.starpilot.ui.weather import valid_location
for service in ('gpsLocationExternal', 'gpsLocation'):
gps = current_message(sm, service, now_ns, after_frame=after)
if gps is not None and gps.hasFix and valid_location((gps.latitude, gps.longitude)):
weather_location = (gps.latitude, gps.longitude)
from openpilot.starpilot.gps.source import GPS_SOURCES, SOURCE_SERVICES, observation
# Weather needs a recent location, not the high-frequency driving-message age gate.
# Include car/phone fixes when this device has no native GNSS receiver.
for service in GPS_SOURCES:
carrier = SOURCE_SERVICES.get(service, service)
fix = observation(sm, service, now_ns)
if fix is not None and int(sm.recv_frame.get(carrier, 0)) > after:
weather_location = (fix[1].latitude, fix[1].longitude)
break
aol_latched = (display_aol_latch(sm, now_ns, after_frame=after)
if started and getattr(ui, "aol_runtime", False) else None)
@@ -263,7 +263,7 @@ class FeatureSettingsOwnerTests(unittest.TestCase):
self.assertTrue(self.owner.apply(request))
self.assertFalse(self.owner.apply(request))
preset = self._row("standard/acceleration", "profile:standard:acceleration")
self.assertEqual(preset.default_value, "Selected Profile")
self.assertEqual(preset.default_value, "Use global preset")
self.assertEqual(self._row("profiles", "profile:global_braking").default_value, "Comfort")
def test_strength_has_actual_runtime_admission_percent_range_and_source_guard(self):
@@ -452,8 +452,8 @@ class FeatureSettingsOwnerTests(unittest.TestCase):
def test_readable_presets_keep_saved_tokens_and_numeric_help(self):
preset = self._row("aggressive/acceleration", "profile:aggressive:acceleration")
self.assertEqual(preset.value, "Selected Profile")
self.assertEqual(preset.choices, ("Selected Profile", "StarPilot Default", "Normal", "Comfort", "Sport", "Sport+"))
self.assertEqual(preset.value, "Use global preset")
self.assertEqual(preset.choices, ("Use global preset", "StarPilot Default", "Normal", "Comfort", "Sport", "Sport+"))
self.assertTrue(self.owner.apply(FeatureSettingsRequest(preset.key, preset.source, "Sport+",
vehicle_fingerprint=preset.vehicle_fingerprint)))
document = required_document(Path(self.params.get_param_path("LongitudinalPersonalityProfiles")).read_bytes())
@@ -61,7 +61,7 @@ def test_compact_menu_has_three_controllers_and_versioned_options_page(tmp_path)
assert options.label == "BluePilot Controller Options" and options.value == BLUEPILOT_VERSION
assert options.page == FeaturePage.BLUEPILOT and options.available
assert feature_parent_page(options.page) == FeaturePage.TORQUE
assert feature_parent_title(options.page) == "Steering and Torque"
assert feature_parent_title(options.page) == "Steering & Torque"
assert PINION not in {row.key for row in FordBluePilotFeature(o).rows(True)}
assert rows(o)[PINION].available
@@ -317,20 +317,22 @@ if __name__ == "__main__":
def test_native_preview_draws_independent_camera_circles_without_camera_input():
canvas = _Canvas.__new__(_Canvas)
canvas.profile = Profile.COMPACT
document = default_document()
state = sample_state('engaged', document)
with patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_circle_v') as circle, \
patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_ring') as ring:
canvas._render_side_cameras(state)
assert circle.call_count == ring.call_count == 2
right_center = circle.call_args.args[0]
document['layouts']['compact']['pip_left']['enabled'] = False
document['layouts']['compact']['pip_left']['x'] = 150
circle.reset_mock()
ring.reset_mock()
canvas._render_side_cameras(sample_state('engaged', document))
assert circle.call_count == ring.call_count == 1
assert circle.call_args.args[0].x == right_center.x
assert circle.call_args.args[0].y == right_center.y
for profile, width in ((Profile.COMPACT, 536), (Profile.LARGE, 1860), (Profile.LARGE, 2160)):
canvas = _Canvas.__new__(_Canvas)
canvas.profile, canvas.viewport = profile, None
document = default_document()
state = replace(sample_state('engaged', document), viewport_width=width)
with patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_circle_v') as circle, \
patch('openpilot.starpilot.ui.layout_preview_renderer.rl.draw_ring') as ring:
canvas._render_side_cameras(state)
assert circle.call_count == ring.call_count == 2
right_center, radius = circle.call_args.args[:2]
assert right_center.x + radius == (width - 54 if profile == Profile.LARGE else 460)
document['layouts'][str(profile)]['pip_left']['enabled'] = False
document['layouts'][str(profile)]['pip_left']['x'] = 150
circle.reset_mock()
ring.reset_mock()
canvas._render_side_cameras(replace(state, customization=document))
assert circle.call_count == ring.call_count == 1
assert circle.call_args.args[0].x == right_center.x
assert circle.call_args.args[0].y == right_center.y
@@ -78,7 +78,7 @@ class PiPSettingsTests(unittest.TestCase):
path = Path(self.params.get_param_path(MASK))
path.write_bytes(original)
page = self.owner.snapshot(include_editor=True)
self.assertEqual(page.title, 'Blind Spot Camera and Preview')
self.assertEqual(page.title, 'Blind Spot Camera & Preview')
self.assertFalse(any(row.key.startswith(FORMAT_PREFIX) for row in page.rows))
self.assertEqual(path.read_bytes(), original)
editor, source = self.owner.editor_with_source()
@@ -148,7 +148,7 @@ def test_native_pip_passes_only_qualified_visual_sides_without_replacing_oem_bsm
fingerprint="b" * 64)
car = SimpleNamespace(leftBlinker=False, rightBlinker=False, leftBlindspot=False, rightBlindspot=True,
canValid=True, gearShifter=runtime_app.car_schema.CarState.GearShifter.drive)
state = SimpleNamespace(customization=default_document(), alert=SimpleNamespace(size=None))
state = SimpleNamespace(customization=default_document(), alert=SimpleNamespace(size=None), viewport_width=2160)
with patch.object(runtime_app, "ui_state", SimpleNamespace(params=object(), sm=object(), started_frame=0)), \
patch.object(runtime_app, "read_pip", return_value=saved), \
patch.object(runtime_app, "read_vasm_preferences", return_value=vasm), \
@@ -157,6 +157,9 @@ def test_native_pip_passes_only_qualified_visual_sides_without_replacing_oem_bsm
patch.object(runtime_app.time, "monotonic_ns", return_value=100), \
patch.dict("os.environ", {"STARPILOT_PIP_DEV": "1", "STARPILOT_VASM_DEVELOPMENT": "1"}):
shell._render_pip(SimpleNamespace(x=0), state)
placements = shell.pip_renderer.render.call_args.kwargs["placements"]
assert placements["right"].x == state.customization["layouts"]["large"]["pip_right"]["x"] + 300
assert placements["left"].x == state.customization["layouts"]["large"]["pip_left"]["x"]
signals = shell.pip_renderer.render.call_args.args[2]
assert signals.vasm_left and not signals.vasm_right
assert signals.right_blindspot and not signals.left_blindspot
@@ -233,7 +233,7 @@ class PowerSettingsTests(unittest.TestCase):
self.assertTrue(state.editor)
self.assertEqual(state.save_hint, 'Changes require confirmation')
row = state.rows[0]
index = next(i for i, button in enumerate(value_buttons(state, row)) if button[0] == 'On')
index = next(i for i, button in enumerate(value_buttons(state, row)) if button[0] == 'Custom limits')
session._display_ui(FeatureUiAction('action', row, index))
def fake_dialog(_question, _button, callback):
@@ -306,7 +306,7 @@ class PowerSettingsTests(unittest.TestCase):
dialog = pushed.call_args.args[0]
dialog._callback(DialogResult.CONFIRM)
self.assertTrue(read_saved(self.params).policy.enabled)
self.assertEqual(page._scroller.items[1].description, "on")
self.assertTrue(page._scroller.items[1].description.startswith("custom limits."))
page._scroller.items[2].click()
picker = pushed.call_args.args[0]
self.assertIn("6 h", picker.options)
+10 -5
View File
@@ -89,7 +89,7 @@ def test_failed_request_backs_off_and_keeps_a_still_current_reading():
client.observe((0, 0))
assert fetch.call_count == 1
assert not client._running
now[0] += 600
now[0] += 60
client.observe((0, 0))
assert fetch.call_count == 2
@@ -152,7 +152,7 @@ def test_disabled_and_alerted_widget_never_constructs_a_client():
client.assert_not_called()
@pytest.mark.parametrize('case', ('off', 'valid', 'invalid', 'no_fix', 'stale', 'future', 'bad_latitude', 'replay', 'fallback'))
@pytest.mark.parametrize('case', ('off', 'valid', 'invalid', 'no_fix', 'stale', 'future', 'bad_latitude', 'replay', 'fallback', 'car', 'phone'))
def test_runtime_uses_only_current_fixed_gps_and_never_fetches(case, tmp_path):
from types import SimpleNamespace as NS
from openpilot.starpilot.ui.tests.test_runtime_snapshot import ui_fake, RuntimeSnapshotAdapter, NOW
@@ -163,17 +163,22 @@ def test_runtime_uses_only_current_fixed_gps_and_never_fetches(case, tmp_path):
ui.params.values['OnroadCustomizations'] = json.dumps(document).encode()
ui.params.get_param_path = lambda key: str(tmp_path / key)
(tmp_path / 'OnroadCustomizations').write_bytes(ui.params.values['OnroadCustomizations'])
gps = NS(hasFix=case != 'no_fix', latitude=91. if case == 'bad_latitude' else 41., longitude=-87.)
gps = NS(hasFix=case != 'no_fix', latitude=91. if case == 'bad_latitude' else 41., longitude=-87., horizontalAccuracy=5., source='ublox')
ui.sm.put('gpsLocationExternal', gps, age_ns=3_000_000_000 if case in ('stale', 'fallback') else -1_000_000_000 if case == 'future' else 0)
if case in ('car', 'phone'):
ui.sm.valid['gpsLocationExternal'] = False
fix = NS(hasFix=True, latitude=42., longitude=-86., horizontalAccuracy=5., sourceMonoTime=NOW)
ui.sm.put('starpilotCarState' if case == 'car' else 'starpilotNavigation',
NS(**{'gps' if case == 'car' else 'phoneGps': fix}))
if case == 'invalid':
ui.sm.valid['gpsLocationExternal'] = False
if case == 'fallback':
ui.sm.put('gpsLocation', NS(hasFix=True, latitude=40., longitude=-88.))
ui.sm.put('gpsLocation', NS(hasFix=True, latitude=40., longitude=-88., horizontalAccuracy=5., source='qcomdiag'))
if case == 'replay':
ui.replay_clock = object()
with patch('openpilot.starpilot.ui.weather.WeatherClient') as client:
state = RuntimeSnapshotAdapter(ui).build(ShellMode.ONROAD, now_ns=NOW).onroad
expected = (41., -87.) if case == 'valid' else (40., -88.) if case == 'fallback' else None
expected = (41., -87.) if case == 'valid' else (40., -88.) if case == 'fallback' else (42., -86.) if case in ('car', 'phone') else None
assert state.customization['layouts']['compact']['weather']['enabled'] == (case != 'off')
assert state.weather_location == expected
client.assert_not_called()
@@ -105,12 +105,12 @@ def test_renderer_dispatches_each_widget_in_saved_order(profile, viewport):
from pathlib import Path
from types import SimpleNamespace as NS
from unittest.mock import Mock
from openpilot.starpilot.ui.onroad_customization import MODE_WIDGET, STOPPED_TIMER_WIDGET, placement, widget_order, RAIL_WIDGETS
from openpilot.starpilot.ui.onroad_customization import MODE_WIDGET, STOPPED_TIMER_WIDGET, placement, rendered_widget_order, RAIL_WIDGETS
source = Path(__file__).parents[1] / 'onroad.py'
tree = ast.parse(source.read_text())
method = next(node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef) and node.name == '_ordered_widgets')
namespace: dict[str, Any] = {'CLOCK_WIDGET': CLOCK_WIDGET, 'MODE_WIDGET': MODE_WIDGET, 'placement': placement, 'widget_order': widget_order,
namespace: dict[str, Any] = {'CLOCK_WIDGET': CLOCK_WIDGET, 'MODE_WIDGET': MODE_WIDGET, 'placement': placement, 'rendered_widget_order': rendered_widget_order,
'RAIL_WIDGETS': RAIL_WIDGETS, 'STOPPED_TIMER_WIDGET': STOPPED_TIMER_WIDGET,
'render_rear_fog': lambda *args: seen.append('rear_fog'),
'manual_slc_confirmation': lambda profile, state: False, 'AlertSize': NS(NONE='none', FULL='full'), 'CameraViewChoice': NS(NONE='none'),
@@ -154,7 +154,7 @@ def test_renderer_dispatches_each_widget_in_saved_order(profile, viewport):
state = NS(customization=document, camera_available=True, viewport_width=1860, alert=NS(size='none'), stopped_duration_s=65,
appearance=NS(camera_view='road'))
namespace['_ordered_widgets'](view, NS(x=30, y=30, width=1800, height=1020), state)
assert seen == order
assert seen == [key for key in order if key not in ("pip_left", "pip_right")] + [key for key in order if key in ("pip_left", "pip_right")]
view.pip_layer.assert_called_once() # Acquire the camera frame once, then draw each side at its layer.
for selected in order:
seen.clear()
@@ -1456,7 +1456,7 @@
]
},
{
"source": "Blind Spot Camera and Preview",
"source": "Blind Spot Camera & Preview",
"refs": [
"openpilot/starpilot/galaxy/web/js/pip.js",
"openpilot/starpilot/galaxy/web/js/settings.js",
@@ -1464,7 +1464,7 @@
]
},
{
"source": "Blind Spot Camera and Preview saved settings",
"source": "Blind Spot Camera & Preview saved settings",
"refs": [
"openpilot/starpilot/galaxy/web/js/pip.js"
]
@@ -2015,7 +2015,7 @@
]
},
{
"source": "Cameras and Monitoring",
"source": "Cameras & Monitoring",
"refs": [
"openpilot/starpilot/galaxy/web/js/cameras.js"
]
@@ -15544,7 +15544,7 @@
]
},
{
"source": "Setup and Settings",
"source": "Setup & Settings",
"refs": [
"openpilot/starpilot/galaxy/web/js/spotify.js"
]
@@ -15663,7 +15663,7 @@
]
},
{
"source": "Show onroad · Big and Small UI",
"source": "Show onroad · Big & Small UI",
"refs": [
"openpilot/starpilot/galaxy/web/js/favorites.js"
]
@@ -16158,7 +16158,7 @@
]
},
{
"source": "Speed and longitudinal",
"source": "Speed & longitudinal",
"refs": [
"openpilot/starpilot/galaxy/web/js/driving.js"
]
@@ -16269,7 +16269,7 @@
]
},
{
"source": "Spotify and Phone Audio",
"source": "Spotify & Phone Audio",
"refs": [
"openpilot/starpilot/galaxy/web/js/spotify.js",
"openpilot/starpilot/galaxy/web/js/starport.js"
@@ -16737,13 +16737,13 @@
]
},
{
"source": "Steering and Torque",
"source": "Steering & Torque",
"refs": [
"openpilot/starpilot/ui/feature_settings_owner.py"
]
},
{
"source": "Steering and buttons",
"source": "Steering & buttons",
"refs": [
"openpilot/starpilot/galaxy/web/js/driving.js"
]
@@ -16972,7 +16972,7 @@
]
},
{
"source": "Storage and Account",
"source": "Storage & Account",
"refs": [
"openpilot/starpilot/galaxy/web/js/spotify.js"
]
+3 -1
View File
@@ -19,6 +19,7 @@ CODES = frozenset((0, 1, 2, 3, 45, 48, 51, 53, 55, 56, 57, 61, 63, 65, 66, 67,
71, 73, 75, 77, 80, 81, 82, 85, 86, 95, 96, 99))
REFRESH_SECONDS = 600
MAX_AGE_SECONDS = 1800
RETRY_SECONDS = 60
def valid_location(point) -> bool:
@@ -91,7 +92,8 @@ class WeatherClient:
with self._lock:
self._reading, self._position, self._received = reading, point, self._clock()
except (OSError, ValueError, TypeError, KeyError, OverflowError):
pass
with self._lock:
self._next_request = self._clock() + RETRY_SECONDS
finally:
with self._lock:
self._running = False