From 440e0c5f1758de6507fd7385cf5aeeaf0546eddf Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 18 Nov 2026 13:58:05 -0600 Subject: [PATCH] Show parked analysis progress and refresh findings before explicit acceptance --- .github/workflows/flm-offroad.yaml | 2 + openpilot/starpilot/flm/offroad_daemon.py | 19 +++++- openpilot/starpilot/flm/offroad_processor.py | 22 +++--- openpilot/starpilot/flm/offroad_route.py | 13 +++- openpilot/starpilot/flm/offroad_worker.py | 4 ++ .../tests/test_offroad_analysis_progress.py | 68 +++++++++++++++++++ openpilot/starpilot/galaxy/tests/test_flm.mjs | 68 +++++++++++++------ .../tests/test_flm_training_results.mjs | 25 ++++++- .../galaxy/tests/test_flm_ux_browser.mjs | 62 ++++++++++++++++- openpilot/starpilot/galaxy/web/css/flm.css | 8 +++ .../galaxy/web/js/flm-training-results.js | 17 +++++ openpilot/starpilot/galaxy/web/js/flm.js | 68 +++++++++++++++---- prebuilt.json | 2 +- 13 files changed, 329 insertions(+), 49 deletions(-) create mode 100644 openpilot/starpilot/flm/tests/test_offroad_analysis_progress.py diff --git a/.github/workflows/flm-offroad.yaml b/.github/workflows/flm-offroad.yaml index 2c45f264ec..d33921155f 100644 --- a/.github/workflows/flm-offroad.yaml +++ b/.github/workflows/flm-offroad.yaml @@ -75,6 +75,7 @@ jobs: openpilot/starpilot/flm/tests/test_offroad_coordinate_policy.py \ openpilot/starpilot/flm/tests/test_offroad_retained_trials.py \ openpilot/starpilot/flm/tests/test_offroad_process_lifecycle.py \ + openpilot/starpilot/flm/tests/test_offroad_analysis_progress.py \ openpilot/starpilot/flm/tests/test_route_recording_clocks.py \ openpilot/starpilot/flm/tests/test_configured_route_recording.py \ openpilot/starpilot/flm/tests/test_observed_maneuvers.py \ @@ -82,6 +83,7 @@ jobs: openpilot/starpilot/flm/tests/test_offroad_equal_native_output.py \ openpilot/starpilot/flm/tests/test_offroad_fault_isolation.py \ openpilot/starpilot/galaxy/tests/test_drive_history.py \ + openpilot/starpilot/galaxy/tests/test_flm_acceptance.py \ --json-output ci-results/flm-offroad.json .venv/bin/python -m pytest -q --import-mode=importlib \ openpilot/starpilot/flm/tests/test_observed_maneuvers.py \ diff --git a/openpilot/starpilot/flm/offroad_daemon.py b/openpilot/starpilot/flm/offroad_daemon.py index 831d297ae1..0e3b7a86b6 100644 --- a/openpilot/starpilot/flm/offroad_daemon.py +++ b/openpilot/starpilot/flm/offroad_daemon.py @@ -52,7 +52,15 @@ class StatusReport: for key in ('configuration_state', 'configured_values', 'saved_adjustments', 'qualification_summary'): if key in self.previous: previous[key] = self.previous[key] - self.set({**(previous or value), 'status': 'fitting', 'reason': value['reason'], 'retained_analysis': bool(previous)}, diagnostic_value=value) + counts = value.get('analysis_counts', {}) + if type(counts) is not dict: + counts = {} + phase = ('preparing' if value['reason'] == 'loading_parked_analysis' else + 'reading' if value['reason'] == 'analyzing_last_completed_drive' else 'checking') + progress = value.get('analysis_progress', {'phase': phase, + 'completed': counts.get('original_segments_reviewed'), 'total': counts.get('original_segments_available')}) + self.set({**(previous or value), 'status': 'fitting', 'reason': value['reason'], 'retained_analysis': bool(previous), + 'analysis_progress': progress}, diagnostic_value=value) def restore(self, cache): """Recover historical display data, never a current tune or permission.""" @@ -114,6 +122,12 @@ class StatusReport: return value if type(value) is int and 0 <= value < 2**63 else 0 details: dict[str, Any] = {'Analysis runs while parked': True, 'Next-drive trial is reversible': True, 'Physical road improvement proven': False} + progress = value.get('analysis_progress') + if value.get('status') == 'fitting' and type(progress) is dict and progress.get('phase') in ('preparing', 'reading', 'verifying', 'checking'): + completed, total = progress.get('completed'), progress.get('total') + if not (type(completed) is int and type(total) is int and 0 <= completed <= total <= 180 and total > 0): + completed = total = None + details['Parked analysis progress'] = [progress['phase'], completed, total] if value.get('vehicle_identity') == 'unavailable': details['Recorded vehicle identity'] = 'unavailable' if self.diagnostics is not None and self.diagnostics.error: @@ -410,6 +424,9 @@ def _run(): cache, permitted=permitted, on_analysis=lambda: report.analyzing({'status': 'fitting', 'reason': 'analyzing_last_completed_drive'}), + on_progress=lambda progress: report.analyzing({'status': 'fitting', 'reason': + 'checking_recorded_steering_recommendations' if progress['phase'] == 'checking' else 'analyzing_last_completed_drive', + 'analysis_progress': progress}), on_assessment=lambda a: report.analyzing( { 'status': 'fitting', diff --git a/openpilot/starpilot/flm/offroad_processor.py b/openpilot/starpilot/flm/offroad_processor.py index 14ea366643..8c4dee663f 100644 --- a/openpilot/starpilot/flm/offroad_processor.py +++ b/openpilot/starpilot/flm/offroad_processor.py @@ -214,7 +214,7 @@ class RecordedInputs: observed_sources: dict = field(default_factory=dict) -def collect_route_inputs(root, route, *, permitted, walker=None, isolate_segments=False): +def collect_route_inputs(root, route, *, permitted, walker=None, isolate_segments=False, on_progress=None): from openpilot.starpilot.flm.offroad_control_metadata import read_control_metadata as read_control state = {'cp': None, 'cp_sha': None, 'context': None} @@ -405,13 +405,14 @@ def collect_route_inputs(root, route, *, permitted, walker=None, isolate_segment if sum(map(len, windows.values())) + sum(map(len, stable_windows.values())) + sum(map(len, baseline_tracking.values())) > MAX_WINDOWS: raise ValueError('Whole-drive tracking window bound exceeded') - receipt = (walk_completed_route if walker is None else walker)(root, route, permitted=permitted, consume=consume) + progress = {'on_progress': on_progress} if on_progress is not None and walker is None else {} + receipt = (walk_completed_route if walker is None else walker)(root, route, permitted=permitted, consume=consume, **progress) counts['original_segments_reviewed'] = len(getattr(receipt, 'decoded_segments', receipt.segments)) counts['original_segments_available'] = len(receipt.segments) return RecordedInputs(receipt, state, windows, stable_windows, baseline_tracking, bookends, raw_windows, context_metadata, counts, quality_stops, observed) -def collect_latest_steering_inputs(params, root, *, permitted, selected_route=None): +def collect_latest_steering_inputs(params, root, *, permitted, selected_route=None, on_progress=None): route = latest_route(params, root, permitted=permitted) if selected_route is None else selected_route import time from openpilot.starpilot.flm.offroad_route import MAX_ANALYSIS_SECONDS, LOCAL_ID @@ -421,7 +422,8 @@ def collect_latest_steering_inputs(params, root, *, permitted, selected_route=No def allowed(): return permitted() and time.monotonic() - started <= MAX_ANALYSIS_SECONDS - collected = collect_route_inputs(root, route, permitted=allowed) + progress = {'on_progress': on_progress} if on_progress is not None else {} + collected = collect_route_inputs(root, route, permitted=allowed, **progress) current_cp = collected.receipt.cp_sha256 skipped = 0 @@ -446,7 +448,7 @@ def collect_latest_steering_inputs(params, root, *, permitted, selected_route=No from openpilot.starpilot.flm.offroad_route import RouteInputError try: - earlier = collect_route_inputs(root, candidate, permitted=allowed) + earlier = collect_route_inputs(root, candidate, permitted=allowed, **progress) except RouteInputError as error: import logging @@ -462,12 +464,16 @@ def collect_latest_steering_inputs(params, root, *, permitted, selected_route=No return route, collected -def analyze_latest(params, root, previous, *, permitted, selected_route=None, evidence_bank=None, history_identity=None): +def analyze_latest(params, root, previous, *, permitted, selected_route=None, evidence_bank=None, history_identity=None, on_progress=None): permitted = route_permission(permitted) + progress = {'on_progress': on_progress} if on_progress is not None else {} if selected_route is None: - route, collected = collect_latest_steering_inputs(params, root, permitted=permitted) + route, collected = collect_latest_steering_inputs(params, root, permitted=permitted, **progress) else: - route, collected = collect_latest_steering_inputs(params, root, permitted=permitted, selected_route=selected_route) + route, collected = collect_latest_steering_inputs(params, root, permitted=permitted, selected_route=selected_route, **progress) + if on_progress is not None: + from openpilot.starpilot.flm.offroad_route import _reading_progress + _reading_progress(on_progress, 'checking', len(collected.receipt.segments), len(collected.receipt.segments)) single = _assess_inputs(route, collected, previous, permitted=permitted) if evidence_bank is None: return single diff --git a/openpilot/starpilot/flm/offroad_route.py b/openpilot/starpilot/flm/offroad_route.py index 5a100825e8..fc71d5b665 100644 --- a/openpilot/starpilot/flm/offroad_route.py +++ b/openpilot/starpilot/flm/offroad_route.py @@ -239,8 +239,16 @@ class PartialRouteReceipt(RouteReceipt): last_intact_wall_ns: int = 0 +def _reading_progress(callback, phase, completed, total): + if callback is not None: + try: + callback({'phase': phase, 'completed': completed, 'total': total}) + except (OSError, ValueError, TypeError, RuntimeError): + pass # Optional display reporting cannot invalidate original recording evidence. + + @route_reader -def walk_completed_route(root, route, *, permitted, consume): +def walk_completed_route(root, route, *, permitted, consume, on_progress=None): """Process complete segments one at a time, then revalidate all source identities. consume receives original readers only during a segment. It must not write or @@ -270,6 +278,7 @@ def walk_completed_route(root, route, *, permitted, consume): for number, name in enumerate(names): if not allowed(): raise ValueError('Parked analysis cancelled') + _reading_progress(on_progress, 'reading', number, len(names)) expected = route['segments'][number]['files'] with _closed_source(root, name, expected, allowed, prefer_rlog=True) as (raw, codec, current, revision): total += len(raw) @@ -305,6 +314,8 @@ def walk_completed_route(root, route, *, permitted, consume): raise ValueError('Recording changed during analysis') receipts.append((name, digest, len(raw))) revisions.append(revision) + _reading_progress(on_progress, 'reading', number + 1, len(names)) + _reading_progress(on_progress, 'verifying', len(receipts), len(names)) if not ended or cp_hash is None or source_start is None or not source_start < source_end: raise ValueError('Incomplete original drive or missing vehicle identity') if last_clock is None or not 0 <= source_end - last_clock[0] <= 10_000_000_000: diff --git a/openpilot/starpilot/flm/offroad_worker.py b/openpilot/starpilot/flm/offroad_worker.py index b84d86cb9d..08eedbf7ac 100644 --- a/openpilot/starpilot/flm/offroad_worker.py +++ b/openpilot/starpilot/flm/offroad_worker.py @@ -681,6 +681,7 @@ class OffroadWorker: on_analysis=None, on_assessment=None, on_recommendations=None, + on_progress=None, prior_provider=None, stable_prior_provider=None, ): @@ -696,6 +697,7 @@ class OffroadWorker: self.on_analysis = on_analysis self.on_assessment = on_assessment self.on_recommendations = on_recommendations + self.on_progress = on_progress self.prior_provider = prior_provider self.stable_prior_provider = stable_prior_provider self.evidence_bank = None @@ -833,6 +835,8 @@ class OffroadWorker: if self.on_analysis is not None: self.on_analysis() options: dict[str, Any] = {} if self.evidence_bank is None else {'evidence_bank': self.evidence_bank, 'history_identity': self._history_identity} + if self.on_progress is not None and self.assessor is RECORDED_ASSESSOR: + options['on_progress'] = self.on_progress if route != latest: options['selected_route'] = route try: diff --git a/openpilot/starpilot/flm/tests/test_offroad_analysis_progress.py b/openpilot/starpilot/flm/tests/test_offroad_analysis_progress.py new file mode 100644 index 0000000000..ff31b0d18f --- /dev/null +++ b/openpilot/starpilot/flm/tests/test_offroad_analysis_progress.py @@ -0,0 +1,68 @@ +"""Actual reader boundaries and retained reports; no actuator or road claims.""" +import json +from pathlib import Path +import tempfile +import unittest + +from openpilot.starpilot.flm.offroad_daemon import StatusReport +from openpilot.starpilot.flm.offroad_route import RouteInputError, route_inventory, walk_completed_route +from openpilot.starpilot.flm.tests.test_offroad_fault_isolation import recording + + +class TestAnalysisProgress(unittest.TestCase): + def test_real_closed_recording_reports_only_consumed_sections_then_verification(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + recording(root, 8) + route = route_inventory(root)['routes'][0] + events = [] + receipt = walk_completed_route(root, route, permitted=lambda: True, + consume=lambda number, rows: events.append(('consumed', number)), on_progress=lambda value: events.append(value)) + self.assertEqual(len(receipt.segments), 1) + self.assertEqual(events, [ + {'phase': 'reading', 'completed': 0, 'total': 1}, ('consumed', 0), + {'phase': 'reading', 'completed': 1, 'total': 1}, {'phase': 'verifying', 'completed': 1, 'total': 1}]) + + def test_corruption_cannot_report_a_section_as_read_or_verified(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + recording(root, 8, corrupt=True) + route = route_inventory(root)['routes'][0] + events = [] + with self.assertRaises(RouteInputError): + walk_completed_route(root, route, permitted=lambda: True, + consume=lambda *args: self.fail('Corrupt source escaped'), on_progress=events.append) + self.assertEqual(events, [{'phase': 'reading', 'completed': 0, 'total': 1}]) + + def test_optional_display_failure_does_not_turn_valid_source_into_a_corrupt_route(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + recording(root, 8) + route = route_inventory(root)['routes'][0] + def unavailable(value): + raise OSError('Display unavailable') + receipt = walk_completed_route(root, route, permitted=lambda: True, consume=lambda *args: None, on_progress=unavailable) + self.assertEqual(len(receipt.segments), 1) + + def test_new_progress_never_uses_retained_drive_counts_or_erases_its_findings(self): + with tempfile.TemporaryDirectory() as root: + report = StatusReport(path=Path(root) / 'report.json', clock_ns=lambda: 10_000_000_000) + report.previous = {'completed_route': 'earlier-drive', 'vehicle': 'declared', 'recommendations': [], + 'analysis_counts': {'original_segments_reviewed': 99, 'original_segments_available': 99}} + report.analyzing({'status': 'fitting', 'reason': 'analyzing_last_completed_drive', + 'analysis_progress': {'phase': 'reading', 'completed': 2, 'total': 10}}) + report.publish() + details = json.loads(report.path.read_text())['current']['details'] + self.assertEqual(details['Parked analysis progress'], ['reading', 2, 10]) + self.assertEqual(details['Completed drive analyzed'], 'earlier-drive') + self.assertTrue(details['Earlier analysis shown while updating']) + report.analyzing({'status': 'fitting', 'reason': 'loading_parked_analysis'}) + report.publish() + self.assertEqual(json.loads(report.path.read_text())['current']['details']['Parked analysis progress'], ['preparing', None, None]) + report.analyzing({'status': 'fitting', 'reason': 'checking_recorded_steering_recommendations', + 'analysis_counts': {'original_segments_reviewed': 10, 'original_segments_available': 10}}) + report.publish() + self.assertEqual(json.loads(report.path.read_text())['current']['details']['Parked analysis progress'], ['checking', 10, 10]) + report.set({'status': 'collecting', 'reason': 'more_independent_eligible_tracking_required'}) + report.publish() + self.assertNotIn('Parked analysis progress', json.loads(report.path.read_text())['current']['details']) diff --git a/openpilot/starpilot/galaxy/tests/test_flm.mjs b/openpilot/starpilot/galaxy/tests/test_flm.mjs index 427f4a3423..223d6efd8d 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm.mjs @@ -97,7 +97,7 @@ for (const invalid of [null, {}, { ...choice, version: true }, { ...choice, vali function instance() { const vm = { ...FlmPage.data(), activePage: true, mode: "local", unauthorized: () => vm.auth++, auth: 0, - poller: { stop() {} }, $nextTick: callback => Promise.resolve().then(callback) } + poller: { stop() {}, start() {} }, $nextTick: callback => Promise.resolve().then(callback) } for (const [name, method] of Object.entries(FlmPage.methods)) vm[name] = method.bind(vm) for (const [name, method] of Object.entries(FlmPage.computed)) Object.defineProperty(vm, name, { get: () => method.call(vm) }) return vm @@ -140,6 +140,7 @@ try { let resolve globalThis.fetch = () => new Promise(done => { resolve = done }) const closed = instance(), pending = closed.load() + assert.equal(closed.load(), pending, "Confirmation and polling share an in-flight read") FlmPage.beforeUnmount.call(closed) resolve({ ok: true, json: async () => value }); await pending assert.equal(closed.report, null) @@ -152,44 +153,71 @@ assert.match(FlmPage.template, /

Your steering<\/h2>/) assert.match(FlmPage.template, /]+:active="view === 'plots'"[^>]+embedded/) assert.doesNotMatch(FlmPage.template, /gx-tuner__plots-link/) -// An explicit acceptance uses its own endpoint; slider editing remains manual. +// Reviewing survives heartbeat gaps; writing still requires fresh matching authority. const acceptanceContext = { mode: 'local', preference: { valid: true, enabled: true, parked: true, controller: 'torque' }, current: { fresh: true }, error: '', manualBusy: false } -assert.equal(FlmPage.computed.canAcceptFindings.call(acceptanceContext), true) -for (const change of [{ current: { fresh: true, reason: 'vehicle_identity_unavailable' } }, - { manualBusy: true }, { current: { fresh: false } }, { mode: 'remote' }, +assert.equal(FlmPage.computed.canReviewFindings.call(acceptanceContext), true) +assert.equal(FlmPage.computed.canReviewFindings.call({ ...acceptanceContext, current: { fresh: false } }), true) +for (const change of [{ current: { reason: 'vehicle_identity_unavailable' } }, { manualBusy: true }, { mode: 'remote' }, ...['parked', 'enabled', 'valid'].map(key => ({ preference: { ...acceptanceContext.preference, [key]: false } })), { preference: { ...acceptanceContext.preference, controller: 'pid' } }]) - assert.equal(FlmPage.computed.canAcceptFindings.call({ ...acceptanceContext, ...change }), false) + assert.equal(FlmPage.computed.canReviewFindings.call({ ...acceptanceContext, ...change }), false) +const authority = { canReviewFindings: true, reportFresh: true, choiceLive: true, error: '' } +assert.equal(FlmPage.computed.canAcceptFindings.call(authority), true) +for (const change of [{ canReviewFindings: false }, { reportFresh: false }, { choiceLive: false }, { error: 'offline' }]) + assert.equal(FlmPage.computed.canAcceptFindings.call({ ...authority, ...change }), false) const acceptanceFetch = globalThis.fetch try { const idea = { parameter: 'ff_gain_left', target: .005 } - const vm = { ...FlmPage.data(), canAcceptFindings: true, review: { findings: [idea] }, - current: { details: { 'Offroad assessment hash': 'a'.repeat(64) } }, - manualFeed: { active: false }, parameterLabel: name => name, unauthorized: () => {} } - vm.reviewFinding = FlmPage.methods.reviewFinding.bind(vm) - vm.acceptFinding = FlmPage.methods.acceptFinding.bind(vm) + function accepting() { + const vm = { ...FlmPage.data(), activePage: true, mode: 'local', canReviewFindings: true, canAcceptFindings: true, + review: { findings: [idea] }, current: { details: { 'Offroad assessment hash': 'a'.repeat(64) } }, + manualFeed: { active: false }, parameterLabel: name => name, unauthorized: () => {}, + load: async () => true, waitFindingRefresh: async () => {}, poller: { stop() {}, start() {} } } + for (const name of ['reviewFinding', 'acceptFinding', 'freshFinding']) vm[name] = FlmPage.methods[name].bind(vm) + vm.reviewFinding(idea) + return vm + } const calls = [] globalThis.fetch = async (url, options) => { calls.push({ url, options }) return { ok: true, json: async () => ({ status: 'saved', parameter: idea.parameter, value: idea.target, learning: 'automatic', for_next_drive: true }) } } - vm.reviewFinding(idea) + const vm = accepting() assert.equal(calls.length, 0, 'Reviewing acceptance never writes') + let reads = 0 + vm.canAcceptFindings = false + vm.load = async () => { vm.canAcceptFindings = ++reads === 2;return true } await vm.acceptFinding() + assert.equal(reads, 2, 'Confirmation waits for a fresh report rather than a fast click') assert.equal(calls.length, 1) assert.equal(calls[0].url, './api/settings/flm-finding/accept') assert.deepEqual(JSON.parse(calls[0].options.body), { parameter: idea.parameter, target: idea.target, assessment: 'a'.repeat(64) }) assert.equal(vm.findingDraft, null) assert.match(vm.findingNotice, /Auto Learn stays on/) - vm.reviewFinding(idea) + for (const fail of ['stale', 'changed-assessment', 'changed-target', 'driving', 'read-error', 'closed']) { + const item = accepting();let attempts = 0 + item.load = async () => { + attempts++ + if (fail === 'stale') item.canAcceptFindings = false + if (fail === 'changed-assessment') item.current.details['Offroad assessment hash'] = 'b'.repeat(64) + if (fail === 'changed-target') item.review.findings = [{ ...idea, target: .01 }] + if (fail === 'driving') item.canReviewFindings = false + return fail !== 'read-error' + } + if (fail === 'closed') item.activePage = false + await item.acceptFinding() + assert.equal(calls.length, 1, fail + ': no write without matching fresh authority') + assert(item.findingError) + assert.equal(attempts, fail === 'stale' ? 3 : fail === 'closed' ? 0 : 1) + } + const unknown = accepting() globalThis.fetch = async () => { calls.push('failed');throw new TypeError('offline') } - await vm.acceptFinding() + await unknown.acceptFinding() assert.equal(calls.length, 2, 'An unknown write outcome is not retried automatically') - assert.equal(vm.findingNotice, '') - assert.match(vm.findingError, /Could not confirm/) - vm.canAcceptFindings = false - vm.reviewFinding(idea) - assert.equal(vm.findingDraft, null) + assert.equal(unknown.findingNotice, '') + assert.match(unknown.findingError, /Could not confirm/) + unknown.canReviewFindings = false;unknown.reviewFinding(idea) + assert.equal(unknown.findingDraft, null) } finally { globalThis.fetch = acceptanceFetch } -console.log('Accept finding keeps learning enabled, requires parked authority, and preserves uncertain write outcomes') +console.log('Accept finding survives stale polling, refreshes exact authority, refuses changed/driving/offline data and never retries a write') diff --git a/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs b/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs index d38b5bd2a3..42c498f449 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm_training_results.mjs @@ -1,5 +1,5 @@ import assert from "node:assert/strict" -import { validTrainingResults, trainingSummary, detailText, learningReason, offroadView, tunerStatus, SURFACE_NAMES, FRICTION_NAMES, surfaceRows, offroadCoordinateEvidence } from "../web/js/flm-training-results.js" +import { parkedAnalysisProgress, validTrainingResults, trainingSummary, detailText, learningReason, offroadView, tunerStatus, SURFACE_NAMES, FRICTION_NAMES, surfaceRows, offroadCoordinateEvidence } from "../web/js/flm-training-results.js" const report = () => ({ version: 1, current: { fresh: true, ageSeconds: .1, enabled: true, status: "collecting", reason: "independent_evidence", progress: { samples: 140, blocks: 3, requiredBlocks: 16 }, @@ -192,3 +192,26 @@ adjustedSlider.current.details['Full surface coordinates'][0][1] = .005 assert.match(offroadCoordinateEvidence(adjustedSlider, SURFACE_NAMES[0]), /Auto Learn saved: \+0.005 for the next drive/) assert(surfaceRows(adjustedSlider, false).every(row => row.applied === null)) console.log('Saved curve and slider adjustments, unsaved recommendations, absent history and current application reconcile without writes') + +// Current scan counts must never come from an earlier retained assessment. +const scan = report();scan.current.status = 'fitting';scan.current.reason = 'analyzing_last_completed_drive' +scan.current.details['Original route segments reviewed'] = [99, 99] +assert.equal(parkedAnalysisProgress(scan).percent, null) +for (const [phase, percent] of [['reading', 20], ['verifying', 20], ['checking', null]]) { + scan.current.details['Parked analysis progress'] = [phase, 2, 10] + assert(validTrainingResults(scan)) + assert.equal(parkedAnalysisProgress(scan).percent, percent) + assert.equal(parkedAnalysisProgress(scan).detail, '2 of 10 sections read in this recording') +} +for (const counts of [[11, 10], [-1, 10], [true, 10], [1, 181], [1.5, 10], [null, null]]) { + scan.current.details['Parked analysis progress'] = ['reading', ...counts] + assert.equal(parkedAnalysisProgress(scan).percent, null) + assert.equal(parkedAnalysisProgress(scan).total, null) +} +scan.current.details = {};scan.current.reason = 'loading_parked_analysis' +assert.equal(parkedAnalysisProgress(scan).phase, 'preparing') +for (const reason of ['not_a_phase', 'constructor', 'toString']) { + scan.current.reason = reason;assert.equal(parkedAnalysisProgress(scan), null) +} +scan.current.status = 'collecting';assert.equal(parkedAnalysisProgress(scan), null) +console.log('Current section progress, indeterminate checks, retained-count separation and malformed-count refusal passed') diff --git a/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs b/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs index 8bb8e3e601..3c405478ac 100644 --- a/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs +++ b/openpilot/starpilot/galaxy/tests/test_flm_ux_browser.mjs @@ -18,6 +18,7 @@ const running = child => child.exitCode === null && child.signalCode === null assert.equal(running({ exitCode: null, signalCode: 'SIGTERM' }), false, 'A signal-reaped child must not be awaited for a second exit') let scenario = 'ideas', parked = true, saveError = false, reportError = false, pending = null let steeringController = 'torque' +let freshReports = [], freshOverride = null, lastReportFresh = true let backupReject = false, backupRecovery = false, manualRecovered = false const tuneBackup = { format: 'starpilot-flm-tune', version: 1, vehicle: 'DECLARED_UI_CAR', metric: false, controllerMode: 'starpilot', cpSha256: 'a'.repeat(64), createdAt: '2026-11-16T03:00:00Z', checksum: 'declared-ui-checksum', @@ -93,6 +94,15 @@ function report() { if (scenario === 'earlier-saved-no-report') value.current = null } if (scenario === 'history-unavailable') value.savedHistory = { status: 'unavailable', historicalOnly: true, profiles: [] } + if (scenario.startsWith('analysis-')) { + const phase = scenario.slice('analysis-'.length) + value.current.status = 'fitting';value.current.reason = 'analyzing_last_completed_drive' + value.current.details['Earlier analysis shown while updating'] = true + value.current.details['Parked analysis progress'] = [phase, phase === 'preparing' ? null : phase === 'reading' ? 23 : 101, phase === 'preparing' ? null : 101] + } + if (freshReports.length) freshOverride = freshReports.shift() + if (freshOverride !== null) { value.current.fresh = freshOverride;value.current.ageSeconds = freshOverride ? 0 : 5 } + lastReportFresh = value.current.fresh assert(validTrainingResults(value), 'Browser fixtures must pass the real report validator') return value } @@ -138,7 +148,7 @@ const server = createServer(async (req, res) => { if (!parked || saveError) return json({ error: 'Declared save refusal' }, 503) if (pathname === '/api/settings/flm-finding/accept') { const hint = hints.find(([name, target]) => body.parameter === name && body.target === target) - if (!hint || body.assessment !== 'a'.repeat(64)) return json({ error: 'Finding changed' }, 409) + if (!lastReportFresh || !hint || body.assessment !== 'a'.repeat(64)) return json({ error: 'Finding changed' }, 409) acceptedFindings.add(body.parameter);manual[body.parameter] = body.target * 100 return json({ status: 'saved', parameter: body.parameter, value: body.target, learning: 'automatic', for_next_drive: true }) } @@ -217,7 +227,7 @@ async function clickVisible(selector) { } async function change(name, options = {}) { await until(() => execute('return !window.flm.request')) - scenario = name;parked = options.parked ?? true;saveError = false;reportError = false + scenario = name;parked = options.parked ?? true;saveError = false;reportError = false;freshReports = [];freshOverride = null await execute('window.flm.manualFeed?.stop();window.flm.view="overview";window.flm.syncManualControls();window.scrollTo(0,0);return window.flm.load()') await until(() => execute('return window.flm.report && !window.flm.request')) } @@ -629,6 +639,54 @@ try { await click('dialog[aria-labelledby=accept-finding-title] .gx-dialog__actions button:first-child') checks.push('finding/explicit-accept/cancel/learning-on/no-auto-qualification/error/no-retry/driving-lockout') + // A heartbeat expiring during a parked scan must not turn review into a timing game. + await viewport(416);await change('ideas');await click('#tuner-tab-tune') + await click('.gx-tuner__curve-summary > details > summary') + const flickerButton = '[data-coordinate=friction_threshold_fast] [data-action=accept-finding]' + await execute('window.flm.poller.stop()') + const beforeRefresh = requests.length + for (const fresh of [false, true, false, true, false]) { + freshOverride = fresh;await execute('return window.flm.load()') + assert.equal(await execute('return window.flm.canAcceptFindings'), fresh, 'Write gate follows genuine freshness') + assert.equal(await execute('return document.querySelector(arguments[0]).disabled', flickerButton), false, 'Read-only review stays usable across polling') + } + await click(flickerButton) + assert.equal(requests.length, beforeRefresh) + freshReports = [false, true] + await click('dialog[aria-labelledby=accept-finding-title] .gx-dialog__actions button:last-child') + await until(() => execute('return window.flm.findingPhase === "checking"')) + assert.equal(requests.length, beforeRefresh, 'No save before fresh authority arrives') + await capture('finding-refresh-checking') + await until(() => execute('return !window.flm.findingBusy')) + assert.equal(requests.length, beforeRefresh + 1, 'One explicit confirmation sends exactly one save after refresh') + assert.equal(requests.at(-1).body.parameter, 'friction_threshold_fast') + assert(acceptedFindings.has('friction_threshold_fast')) + await execute('window.flm.poller.stop()') + const lowButton = '[data-coordinate=friction_threshold_low] [data-action=accept-finding]' + freshOverride = false;await execute('return window.flm.load()') + await click(lowButton) + const beforeStale = requests.length + await click('dialog[aria-labelledby=accept-finding-title] .gx-dialog__actions button:last-child') + await until(() => execute('return !window.flm.findingBusy && !!window.flm.findingError')) + assert.equal(requests.length, beforeStale, 'Persistent stale reports never reach a write') + assert(!acceptedFindings.has('friction_threshold_low')) + await show('[data-role=finding-error]');await capture('finding-refresh-unavailable') + checks.push('finding/polling-stale-fresh/no-flicker/fresh-confirmation/one-write/stale-no-write') + for (const [width, height, phase] of [[320, 844, 'reading'], [416, 844, 'checking'], [720, 480, 'preparing'], [1280, 900, 'verifying']]) { + await viewport(width, height);await change('analysis-' + phase) + const progress = await execute('const e=document.querySelector("[data-role=analysis-progress]"),p=e.querySelector("[role=progressbar]");return {text:e.textContent,now:p.getAttribute("aria-valuenow"),indeterminate:p.classList.contains("is-indeterminate"),animation:getComputedStyle(p.firstElementChild).animationName}') + assert.equal(progress.indeterminate, ['checking','preparing'].includes(phase)) + assert.equal(progress.now === null, progress.indeterminate, 'Unknown work has no invented percentage') + assert.match(progress.text, phase === 'preparing' ? /Preparing drive analysis/ : phase === 'reading' ? /23 of 101 sections read/ : /101 of 101 sections read/) + if (progress.indeterminate) assert.equal(progress.animation, 'none', 'Reduced motion disables the waiting animation') + assert.equal(await execute('return window.flm.review.count'), 5, 'Scan progress preserves earlier findings') + await layout('analysis/' + phase + '/' + width);await tabsClear('analysis/' + phase + '/' + width + '/tabs') + await capture('analysis-' + phase + '-' + width) + } + await change('ideas') + assert.equal(await execute('return !!document.querySelector("[data-role=analysis-progress]")'), false, 'Finished analysis removes processing progress') + assert.deepEqual(errors, []) + console.log(`Real Chromium FLM UI: ${checks.length} responsive/theme/state checks, 5 findings/7 destinations, parked save/reset, driving lockout, errors and retained evidence passed`) } catch (error) { failure = error.stack diff --git a/openpilot/starpilot/galaxy/web/css/flm.css b/openpilot/starpilot/galaxy/web/css/flm.css index 6d36d3a100..4fbad3822c 100644 --- a/openpilot/starpilot/galaxy/web/css/flm.css +++ b/openpilot/starpilot/galaxy/web/css/flm.css @@ -1,4 +1,12 @@ /* A driving report first; exact tuning evidence remains available on demand. */ +.gx-tuner__analysis { display: grid;gap: 12px;padding: 16px 20px; } +.gx-tuner__analysis h3 { font-size: 16px;line-height: 1.4;margin: 0 0 4px; } +.gx-tuner__analysis p { font-size: 13px;line-height: 1.5;color: var(--on-surface-variant);margin: 0; } +.gx-tuner__analysis-track { height: 5px;overflow: hidden;border-radius: 8px;background: var(--tuner-raised); } +.gx-tuner__analysis-track > span { display: block;height: 100%;border-radius: inherit;background: var(--primary);transition: width .25s ease; } +.gx-tuner__analysis-track.is-indeterminate > span { width: 28%;animation: flm-analysis-progress 2.4s ease-in-out infinite; } +@keyframes flm-analysis-progress { from { transform: translateX(-100%); } to { transform: translateX(360%); } } +@media (prefers-reduced-motion: reduce) { .gx-tuner__analysis-track.is-indeterminate > span { animation: none;width: 100%;opacity: .35; } } .gx-tuner { --tuner-panel: #151426;--tuner-raised: #1d1b32;--tuner-review: #ffd08a;--tuner-review-bg: #2c251f;--tuner-saved: #79e4d9;--tuner-border: #3a374e;gap: 16px;padding-bottom: max(32px, env(safe-area-inset-bottom)); } [data-theme="light"] .gx-tuner { --tuner-panel: #fff;--tuner-raised: #f4f2fa;--tuner-review: #865000;--tuner-review-bg: #fff5e3;--tuner-saved: #076c63;--tuner-border: #d9d5e4; } .gx-tuner .gx-card { background: var(--tuner-panel);box-shadow: none;border-color: var(--tuner-border); } diff --git a/openpilot/starpilot/galaxy/web/js/flm-training-results.js b/openpilot/starpilot/galaxy/web/js/flm-training-results.js index 68cbf7e542..c85e7bced9 100644 --- a/openpilot/starpilot/galaxy/web/js/flm-training-results.js +++ b/openpilot/starpilot/galaxy/web/js/flm-training-results.js @@ -377,6 +377,23 @@ export function recordedSteeringView(value) { points: value.points.map(([ns, desired, actual]) => ({ at: (ns - value.source_start_ns) / 1e6, desired, actual })) } } +export function parkedAnalysisProgress(report) { + const current = report?.current + if (current?.status !== 'fitting') return null + const labels = { preparing: 'Preparing drive analysis', reading: 'Reading a recorded drive', + verifying: 'Verifying the recording', checking: 'Checking steering suggestions' } + const fallback = { loading_parked_analysis: 'preparing', analyzing_last_completed_drive: 'reading', + checking_recorded_steering_recommendations: 'checking' }[current.reason] + const value = current.details?.['Parked analysis progress'] + const phase = Array.isArray(value) && value.length === 3 && Object.hasOwn(labels, value[0]) ? value[0] : fallback + if (!Object.hasOwn(labels, phase)) return null + const [, done, total] = Array.isArray(value) ? value : [] + const counted = Array.isArray(value) && value.length === 3 && Object.hasOwn(labels, value[0]) && Number.isSafeInteger(done) && Number.isSafeInteger(total) && done >= 0 && total > 0 && done <= total && total <= 180 + return { phase, label: labels[phase], completed: counted ? done : null, total: counted ? total : null, + percent: counted && ['reading', 'verifying'].includes(phase) ? done / total * 100 : null, + detail: counted ? `${done} of ${total} sections read in this recording` : 'Progress is reported as each step finishes.' } +} + export function tunerStatus(report, live = false, choiceLive = false, error = "", reportFresh = live) { const preference = choiceLive && validLearningPreference(report?.preference) ? report.preference : null const current = report?.current diff --git a/openpilot/starpilot/galaxy/web/js/flm.js b/openpilot/starpilot/galaxy/web/js/flm.js index eb721bce26..61f1be13ae 100644 --- a/openpilot/starpilot/galaxy/web/js/flm.js +++ b/openpilot/starpilot/galaxy/web/js/flm.js @@ -11,6 +11,7 @@ import { PlotGraph, PlotsPage, chartGeometry } from "./plots.js" import { validTrainingResults, readable, detailText, surfaceRows, coordinateText, trackingView, measurementText, validTrackingValues, trackingPlotView, sourceSeconds, validLearningPreference, SURFACE_GROUPS, tunerStatus, learningReason, sourceCaptureCounts, historyTitle, offroadView, FRICTION_NAMES, offroadCoordinateEvidence, recommendationText } from "./flm-training-results.js" import { reviewModel, dialPercent, ideaStatus, ideaExplanation, ideaValue, ideaHeading, curvePointLabel, ideaDetails } from "./flm-review.js" +import { parkedAnalysisProgress } from './flm-training-results.js' const VIEWS = ["overview", "tune", "activity", "plots"] const GROUP_DESCRIPTIONS = { @@ -49,7 +50,7 @@ export const FlmPage = { go: { type: Function, default: path => { window.location.hash = path } } }, data: () => ({ report: null, error: "", loading: false, request: null, receivedAt: 0, now: 0, bluetooth: bluetoothConnection(), manualState: { status: "idle", data: null, pending: null, error: "" }, manualResetRequested: false, manualWrite: null, - findingDraft: null, findingBusy: false, findingError: '', findingNotice: '', acceptedFindingNames: [], + findingDraft: null, findingBusy: false, findingPhase: '', findingError: '', findingNotice: '', acceptedFindingNames: [], reportRead: null, headerOffset: 88, view: "overview", group: "balance", showAllHistory: false, groups: SURFACE_GROUPS }), watch: { initialView(view) { this.selectView(view) }, mode() { this.syncManualControls() }, @@ -86,9 +87,11 @@ export const FlmPage = { document.removeEventListener("visibilitychange", this.visibility) }, computed: { - canAcceptFindings() { return this.current?.reason !== 'vehicle_identity_unavailable' && this.mode === 'local' && + canReviewFindings() { return this.current?.reason !== 'vehicle_identity_unavailable' && this.mode === 'local' && this.preference?.valid === true && this.preference.enabled === true && - this.preference.parked === true && this.preference.controller === 'torque' && this.current?.fresh === true && !this.error && !this.manualBusy }, + this.preference.parked === true && this.preference.controller === 'torque' && !this.manualBusy }, + canAcceptFindings() { return this.canReviewFindings && this.reportFresh && this.choiceLive && !this.error }, + analysisProgress() { return parkedAnalysisProgress(this.report) }, manualRows() { return (this.manualState.data?.rows || []).map((row, index) => ({ row, index })).filter(({ row }) => this.selectedGroup.names.includes(row.coordinate)) }, recoveredManualCurve() { return (this.manualState.data?.rows || []).filter(row => FRICTION_NAMES.includes(row.coordinate)) }, manualActions() { return (this.manualState.data?.rows || []).map((row, index) => ({ row, index })).filter(({ row }) => row.confirm) }, @@ -185,17 +188,20 @@ export const FlmPage = { }, methods: { reviewFinding(idea) { - if (!this.canAcceptFindings || this.findingBusy || !Number.isFinite(idea.target) || + if (!this.canReviewFindings || this.findingBusy || !Number.isFinite(idea.target) || !this.review.findings.some(row => row.parameter === idea.parameter && row.target === idea.target)) return const assessment = this.current?.details?.['Offroad assessment hash'] if (!/^[0-9a-f]{64}$/.test(assessment || '')) { this.findingError = 'Refresh the drive review before accepting a finding.'; return } this.findingError = '';this.findingDraft = { parameter: idea.parameter, target: idea.target, assessment } }, async acceptFinding() { - if (!this.findingDraft || this.findingBusy || !this.canAcceptFindings) return + if (!this.findingDraft || this.findingBusy || !this.canReviewFindings) return const draft = { ...this.findingDraft } - this.findingBusy = true;this.findingError = '';this.findingNotice = '' + this.findingBusy = true;this.findingPhase = 'checking';this.findingError = '';this.findingNotice = '' + this.poller?.stop() try { + await this.freshFinding(draft) + this.findingPhase = 'saving' const result = await requestJson('./api/settings/flm-finding/accept', { request: { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(draft) } }) if (result.status !== 'saved' || result.parameter !== draft.parameter || result.value !== draft.target || result.learning !== 'automatic') @@ -206,10 +212,32 @@ export const FlmPage = { if (this.manualFeed?.active) await this.manualFeed.load('tuning') } catch (error) { if (error.status === 401) this.unauthorized() - this.findingError = error.status ? error.message : 'Could not confirm this finding was saved. Refresh the saved settings before trying again.' + this.findingError = this.findingPhase === 'checking' ? error.message : error.status ? error.message : + 'Could not confirm this finding was saved. Refresh the saved settings before trying again.' this.findingDraft = null - } finally { this.findingBusy = false } + } finally { + this.findingBusy = false;this.findingPhase = '' + if (this.activePage && this.mode === 'local') this.poller?.start() + } }, + async freshFinding(draft) { + for (let attempt = 0; attempt < 3; attempt++) { + if (!this.activePage || this.mode !== 'local') throw new Error('Connect to the parked device before accepting a finding.') + const read = await this.load() + if (!read) throw new Error('Could not refresh the device report. No change was sent. Reconnect and try again.') + if (!this.activePage || this.mode !== 'local') throw new Error('Connect to the parked device before accepting a finding.') + if (read) { + if (this.current?.details?.['Offroad assessment hash'] !== draft.assessment || + !this.review.findings.some(row => row.parameter === draft.parameter && row.target === draft.target)) + throw new Error('The drive findings changed. Review the latest finding before accepting it.') + if (!this.canReviewFindings) throw new Error('The vehicle or settings changed. Review this finding again while parked.') + if (this.canAcceptFindings) return + } + if (attempt < 2) await this.waitFindingRefresh() + } + throw new Error('A fresh device report is not available yet. Your tune has not changed. Try again when the connection is ready.') + }, + waitFindingRefresh() { return new Promise(resolve => setTimeout(resolve, 1000)) }, backupRestored() { this.manualWrite = null;this.manualResetRequested = false;this.manualFeed?.load('tuning');return this.load() }, dialPercent, ideaStatus, ideaValue, ideaHeading, curvePointLabel, ideaDetails, readable, detailText, coordinateText, measurementText, sourceSeconds, learningReason, historyTitle, recommendationText, findingAccepted(idea) { return this.acceptedFindingNames.includes(idea.parameter) || @@ -324,24 +352,30 @@ export const FlmPage = { this.selectView(VIEWS[next]) event.currentTarget.parentElement.querySelectorAll('[role="tab"]')[next]?.focus() }, - async load() { + load() { + if (!this.reportRead) this.reportRead = this.readReport().finally(() => { this.reportRead = null }) + return this.reportRead + }, + async readReport() { this.now = Date.now() - if (!this.activePage || this.mode !== "local" || this.request || document.hidden) return + if (!this.activePage || this.mode !== "local" || this.request || document.hidden) return false const controller = new AbortController() this.request = controller; this.loading = true try { const value = await requestJson("./api/flm/training-results", { request: { signal: controller.signal } }) - if (this.request !== controller || !this.activePage) return + if (this.request !== controller || !this.activePage) return false if (!validTrainingResults(value)) throw new Error("The device returned an unsupported training report.") if (this.report?.current?.details?.['Offroad assessment hash'] !== value.current?.details?.['Offroad assessment hash']) this.acceptedFindingNames = [] this.report = value; this.error = ""; this.receivedAt = this.now = Date.now() clearTimeout(this.freshnessTimer) const age = value.current?.fresh ? value.current.ageSeconds * 1000 : 0 this.freshnessTimer = setTimeout(() => { this.now = Date.now() }, Math.max(0, 2000 - age) + 1) + return true } catch (error) { - if (this.request !== controller || !this.activePage) return + if (this.request !== controller || !this.activePage) return false if (error.status === 401 || ["access_unavailable", "setup_required"].includes(error.code)) this.unauthorized() else this.error = connectionError(error, "Live update unavailable. Reconnecting automatically…") + return false } finally { if (this.request === controller) { this.request = null; this.loading = false } } @@ -358,12 +392,16 @@ export const FlmPage = {

Accept this finding?

{{ parameterLabel(findingDraft.parameter) }}: {{ dialPercent(findingDraft.target) }}

Use this value for your next drive. Auto Learn can keep improving this setting.

-
+
{{ connectionLabel }}{{ currentApplied ? 'Learned tune in use' : preference?.parked ? 'Parked' : live ? 'Driving · use not confirmed' : 'State not confirmed' }}

Reset manual tune?

{{ manualState.pending.question }}

+
+

{{ analysisProgress.label }}

{{ analysisProgress.detail }}

+
+
@@ -394,8 +432,8 @@ export const FlmPage = {

SUGGESTIONS FROM RECENT DRIVING

{{ review.count ? 'Suggestions · needs more evidence' : 'No new suggestions' }}

Accepted findings stay eligible for Auto Learn. Review the other suggested values below.

These suggestions are not saved. Auto Learn needs more evidence before saving them automatically.

No additional suggestions were reported for this drive.

{{ review.count ? 'Review only' : 'No new change' }}

{{ review.manual.length }} steering {{ review.manual.length === 1 ? 'finding' : 'findings' }} · {{ review.curve.length }} speed-range {{ review.curve.length === 1 ? 'finding' : 'findings' }}. Viewing an idea does not change your tune.

-
-
{{ review.curve.length }} speed-range findings · suggested changes

Small steering corrections at different speeds

Auto Learn manages this curve; your manual sliders are separate.

See all {{ review.curve.length }} findings
{{ curvePointLabel(idea.parameter) }}{{ findingAccepted(idea) ? 'Accepted for next drive' : ideaStatus(idea) }}
+
+
{{ review.curve.length }} speed-range findings · suggested changes

Small steering corrections at different speeds

Auto Learn manages this curve; your manual sliders are separate.

See all {{ review.curve.length }} findings
{{ curvePointLabel(idea.parameter) }}{{ findingAccepted(idea) ? 'Accepted for next drive' : ideaStatus(idea) }}
{{ review.other.length }} earlier grouped findings

This older report does not identify a single dial or absolute target for these findings. They are not changes to apply.

{{ readable(idea.parameter) }} · {{ recommendationText(idea) }} · {{ amount(idea.windows) }} recorded windows.

diff --git a/prebuilt.json b/prebuilt.json index 3f53db6146..1cd7df512b 100644 --- a/prebuilt.json +++ b/prebuilt.json @@ -1 +1 @@ -{"protected_inventory_sha256": "871b792fbcb5489bea2dcdf4e293b3358e921839ba2ecad4d9dbfe0d56c37e85", "schema_version": 1} +{"protected_inventory_sha256": "98afac62a2936202a52e3bcb3df3944dabe58f3ed68be3f539d03fd76f0c4cf0", "schema_version": 1}