From 6874b9d9631ca145bb73e203c415427195cd05b9 Mon Sep 17 00:00:00 2001 From: GAJ3T Date: Fri, 30 Oct 2026 02:08:16 -0400 Subject: [PATCH] WIP 6 --- README.md | 24 +- docs/README.md | 17 +- docs/architecture.md | 16 +- docs/build-and-test.md | 59 ++- docs/live-dashboard.md | 73 +++- docs/simulation.md | 9 +- prompts/ROADMAP.md | 58 ++- prompts/STATE.md | 102 +++-- prompts/Step-06-Report.md | 165 ++++++++ prompts/Step-06A.md | 208 ++++++++++ .../DisplayUnits/DisplayUnitSettings.cs | 385 ++++++++++++++++++ .../MauiDisplayUnitPreferenceStore.cs | 45 ++ src/AutoForge.Client/MauiProgram.cs | 3 + .../DisplayUnits/DisplayUnitPresentation.cs | 53 +++ .../Features/Foundation/AddAutoForgeUi.cs | 2 + .../Diagnostics/DiagnosticsPage.razor | 19 +- .../Vehicles/Simulation/SimulationPage.razor | 46 ++- .../Simulation/SimulationPageViewModel.cs | 11 +- .../LiveDashboard/LiveDashboardPanel.razor | 201 ++++++++- src/AutoForge.UI/Layout/MainLayout.razor | 85 +++- src/AutoForge.UI/_Imports.razor | 2 + .../DiagnosticUiCompositionTests.cs | 1 + .../DynamicsWorkflowTests.cs | 174 +++++++- .../IsolatedDisplayUnitPreferenceStore.cs | 12 + .../LiveDashboardAcquisitionTests.cs | 1 + .../UiCompositionTests.cs | 2 + .../VehicleProfileCompositionTests.cs | 1 + .../DisplayUnitSettingsTests.cs | 291 +++++++++++++ 28 files changed, 1963 insertions(+), 102 deletions(-) create mode 100644 prompts/Step-06-Report.md create mode 100644 prompts/Step-06A.md create mode 100644 src/AutoForge.Application/Features/DisplayUnits/DisplayUnitSettings.cs create mode 100644 src/AutoForge.Client/DisplayUnits/MauiDisplayUnitPreferenceStore.cs create mode 100644 src/AutoForge.UI/Features/DisplayUnits/DisplayUnitPresentation.cs create mode 100644 src/tests/AutoForge.IntegrationTests/IsolatedDisplayUnitPreferenceStore.cs create mode 100644 src/tests/AutoForge.UnitTests/DisplayUnitSettingsTests.cs diff --git a/README.md b/README.md index f6c7447..708a163 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,8 @@ supported vehicle modules. ambiguity checks, complete reply validation and truthful trace outcomes. Step-03B preserves successful probe/service evidence separately from optional profile-verified identity and keeps expected/probed/identified counts distinct. - Read/clear actions remain gated on verified identity. Step-03 as a whole remains - subject to manual orchestrator acceptance. + Read/clear actions remain gated on verified identity. Step-03 with its + corrections was accepted by the orchestrator. - Step-04 adds immutable versioned dynamics configurations, a fixed-step coupled synthetic engine/transmission/longitudinal model, an explicit `autoforge.simulation.dynamics` provider using protocol v2, configuration @@ -46,8 +46,14 @@ supported vehicle modules. diagnostics and dynamics workflows. It reads only identity-verified signals from the explicitly opened session, exposes source/quality/range/sample context, and keeps acquisition session-owned while gauges are hidden or - removed. The corrective worker implementation is pending manual review; see - the [Step-05A corrective report](prompts/Step-05A-Report.md). + removed. Step-05 with Step-05A/Step-05B was accepted by the orchestrator. +- Step-06 adds a shared, persisted display preference with an Imperial (US) / + Road first-use default and Metric/Imperial (US) plus Road/Engineering choices. + Supported readouts convert only at presentation; SI source values, model + calculations, configuration fingerprints and canonical dashboard definitions + remain unchanged. See [display units](docs/live-dashboard.md#display-units). + Step-06 implementation and worker verification are complete; manual + orchestrator review remains pending. - UI routes: `/` foundation, `/execution-targets` explicit metadata selection, `/vehicle-profiles` explicit profile import/revision selection/inspection/export, `/diagnostics` static synthetic diagnostics, `/simulation` dynamics, and a @@ -66,10 +72,9 @@ supported vehicle modules. ### In progress -Manual orchestrator review and acceptance of Step-03B remain pending. Step-05A -completes the previously returned dashboard assignment, but its worker -implementation remains pending manual review and acceptance. The Step-04 -acceptance covers its Step-04A and Step-04B corrections. +Step-06 is complete on worker execution evidence and is awaiting manual +orchestrator review. The Step-04 and Step-05 acceptances include their listed +corrections. ### Planned @@ -90,7 +95,8 @@ browser-hosted WASM shell, Blazor Server host or second application executable. The application slices provide explicit target metadata resolution, vehicle-profile metadata import/list/select/export, dynamics configuration -catalog/import/export, and simulation-only diagnostic sessions. The Client +catalog/import/export, simulation-only diagnostic sessions, and a shared +display-unit preference with a native local-preference adapter. The Client composes separate static and dynamics synthetic providers through provider-neutral factory contracts and a session-lifetime in-memory profile/ configuration catalog. Import never opens a session; metadata resolution never diff --git a/docs/README.md b/docs/README.md index 524ef94..511598e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,11 +1,11 @@ # AutoForge documentation The implemented scope includes the accepted Step-01/Step-01A foundation, -accepted Step-02/Step-02A vehicle-profile metadata, the Step-03 synthetic -diagnostic vertical slice with its integrity corrections, and the accepted -Step-04/04A/04B synthetic dynamics work. Step-05 adds a configurable, -session-owned live dashboard to both static diagnostics and dynamics workflows; -its corrective worker implementation is pending manual review. +accepted Step-02/Step-02A vehicle-profile metadata, the accepted Step-03 +synthetic diagnostic vertical slice with its integrity corrections, the accepted +Step-04/04A/04B synthetic dynamics work, the accepted Step-05/05A/05B +session-owned live dashboard, and the worker-complete Step-06 Imperial-default +display-unit preference (pending manual orchestrator review). - [Architecture](architecture.md): actual nine-project graph, responsibilities, route ownership and provider/reference boundaries. @@ -18,7 +18,8 @@ its corrective worker implementation is pending manual review. inventory, fixed-step model, configuration identity, scenario and protocol boundaries. - [Live dashboard usage and contracts](live-dashboard.md): configuration limits, - verified bindings, quality/range/freshness, ownership and v1/v2 sample context. + verified bindings, quality/range/freshness, ownership, display-unit + preference/conversions and v1/v2 sample context. - [ADR-0001: Headless .NET 10 foundation](adr-0001-headless-foundation.md): historical foundation decisions; dual-shell/deferred-host decision superseded. - [ADR-0002: Single native shell and feature slices](adr-0002-single-shell-vsa.md): @@ -45,5 +46,7 @@ historical/worker reports for their own execution evidence: [Step-04 worker report](../prompts/Step-04-Report.md), [Step-04A corrective worker report](../prompts/Step-04A-Report.md), [Step-04B corrective worker report](../prompts/Step-04B-Report.md), and -[Step-05A corrective worker report](../prompts/Step-05A-Report.md). +[Step-05A corrective worker report](../prompts/Step-05A-Report.md), +[Step-05B corrective worker report](../prompts/Step-05B-Report.md), and +[Step-06 worker report](../prompts/Step-06-Report.md). Handoffs are manual; acceptance remains the orchestrator's responsibility. diff --git a/docs/architecture.md b/docs/architecture.md index 782bed0..08fa999 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,8 +9,9 @@ There is no web/server host, WASM host or backend process. ## Current milestone status -Step-04/04A/04B are accepted. Step-05's corrective worker implementation is -pending manual review and acceptance; this status does not authorize later work. +Steps 04/04A/04B and 05/05A/05B are accepted. Step-06's display-unit +implementation and worker verification are complete and awaiting manual +orchestrator review; this status does not authorize Step-07. ```mermaid flowchart TD @@ -45,10 +46,10 @@ All nine projects are in [AutoForge.slnx](../src/AutoForge.slnx): | [Core](../src/AutoForge.Core/AutoForge.Core.csproj) | `net10.0`; platform-neutral target/profile invariants and immutable dynamics configuration/status contracts | None | | [Diagnostics](../src/AutoForge.Diagnostics/AutoForge.Diagnostics.csproj) | `net10.0`; provider/session/transport/control contracts, strict synthetic protocol v1/v2 client, typed results and bounded trace | Core | | [Simulation](../src/AutoForge.Simulation/AutoForge.Simulation.csproj) | `net10.0`; validated static modules, fixed-step engine, isolated state, explicit provider factories and transports | Core, Diagnostics | -| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostic-session and dynamics-configuration feature slices | Core, Diagnostics | +| [Application](../src/AutoForge.Application/AutoForge.Application.csproj) | `net10.0`; target/profile/diagnostic-session, dynamics-configuration, display-unit conversion and preference-port feature slices | Core, Diagnostics | | [Components](../src/AutoForge.Components/AutoForge.Components.csproj) | `net10.0` RCL; generic `StatusNotice` and numeric/bar gauge with accessible state and safe rendering | None | | [UI](../src/AutoForge.UI/AutoForge.UI.csproj) | `net10.0` RCL; all application routes, navigation, layout and presentation, including shared live dashboard editor | Application, Components, Diagnostics | -| [Client](../src/AutoForge.Client/AutoForge.Client.csproj) | `net10.0-windows10.0.26100.0`; only MAUI Blazor Hybrid application executable | Application, Simulation, UI | +| [Client](../src/AutoForge.Client/AutoForge.Client.csproj) | `net10.0-windows10.0.26100.0`; only MAUI Blazor Hybrid application executable and native preference adapter | Application, Simulation, UI | | [UnitTests](../src/tests/AutoForge.UnitTests/AutoForge.UnitTests.csproj) | `net10.0`; Core/Application/contracts, protocol and reusable component tests | Application, Components, Core, Diagnostics, Simulation | | [IntegrationTests](../src/tests/AutoForge.IntegrationTests/AutoForge.IntegrationTests.csproj) | `net10.0`; real DI, fixtures, provider transport/session and rendered UI/project-graph tests | Application, Components, Core, Diagnostics, Simulation, UI | @@ -103,7 +104,12 @@ The shared live dashboard panel is UI composition over the Application numeric/bar renderer remains in Components and has no AutoForge dependency. Bindings are offered only after identity-verified signal reads by that feed. Definitions are in-memory (zero through eight gauges), use exact source units, -and are validated before replacing the current set. One feed polls once per +and are validated before replacing the current set. The shared display-unit +preference is persisted by the native Client through MAUI Preferences; portable +composition must supply an explicit store, and the UI-only unavailable store +reports failure rather than silently using memory. Conversions are a pure +presentation projection and never alter source snapshots, SI model state or +canonical gauge bounds. One feed polls once per eligible module every cycle, independent of gauge visibility or render count. The UI subscribes only for render notifications; hiding or disposing a panel does not stop acquisition. The owning session and feature scope cancel and drain diff --git a/docs/build-and-test.md b/docs/build-and-test.md index d29ef98..7c454d0 100644 --- a/docs/build-and-test.md +++ b/docs/build-and-test.md @@ -370,5 +370,60 @@ left untouched. These native observations confirm the dashboard baseline; the Uncertain and malformed-input cases are established by controlled tests, not claimed as native UI injection. -Step-05 worker implementation remains pending manual review; these worker -results are not an orchestrator acceptance. +Step-05 with Step-05A and Step-05B was accepted by the orchestrator on +2026-10-29. These historical worker results remain distinct from that manual +acceptance. + +## Step-06 display-unit verification + +The shared shell defaults to Imperial (US) / Road and persists explicit +Metric/Imperial (US) and Road/Engineering selections through the native MAUI +Preferences adapter. Portable tests inject an isolated store; controlled read, +write, corrupt-value and invalid-selection cases exercise the same application +service without modifying platform preferences. Pure tests cover the specified +forward/inverse conversion vectors, affine temperature bounds, finite/overflow +handling, exact pass-through/unknown units and conversion before rounding. +Rendered real-provider coverage toggles all speed modes repeatedly on a paused +dynamics session and verifies unchanged source snapshots, gauge definitions, +trace/request count, configuration export, model state and bar percentage. + +Current command outcomes and exact complete suite counts are recorded in the +[Step-06 worker report](../prompts/Step-06-Report.md). Native persistence and +draft-editor observations are reported separately from controlled storage +failure/error tests; headless verification does not substitute for the actual +Windows Client smoke. Step-07 recording/replay remains unimplemented and +blocked pending manual Step-06 review. + +The final sequential Release build completed all nine projects, including the +Windows Client, with 0 warnings and 0 errors. The full suite passed 178 unit and +92 integration tests (270 total; 0 failed/skipped), preserving the accepted +225-case Step-05B baseline and adding 44 unit plus one integration case. Focused +display-unit tests passed 44/44; the focused real static/dynamic/rendered +integration selection passed 3/3. + +The rebuilt Windows Client was launched with task-local WebView2 debug port 9361 +and an isolated temporary WebView profile. Its initial native shell showed the +Imperial (US) / Road first-use default before any session; the key had no saved +selection. A real static v1 session rendered 850 rpm unchanged after switching +the shared selectors. A real dynamics v2 session was paused at step 203 / +20.3 seconds and returned 20.1168 m/s. Its bar displayed 45 mph / 0..90 mph, +66 ft/s / 0..132 ft/s, 72 km/h / 0..144.84096 km/h, and 20 m/s / +0..40.2336 m/s; all modes kept 50% geometry, the exact 20.1168 m/s source +reading, and step 203. + +The native range editor saved 0..90 mph as canonical 0..40.2336 m/s. An open +10..110 mph draft retained its mph labels and values after the global system +changed to Metric; saving produced source bounds +4.470400000000001..49.174400000000006 m/s and the equivalent Metric/Road +display range. An invalid 200..100 range surfaced an alert and preserved the +prior gauge; an unedited Save retained its exact existing source bounds. +Protocol-v2 telemetry displayed Imperial numeric readings while retaining +source `kg/s`, `N*m`, `degC` and exact source speed alongside them. Exported +configuration remained 2,789 characters, contained the unchanged SI target +20.1168 and no display-unit labels, and kept its fingerprint. Reset opened a +new stopped step-0 session/run with an empty dashboard; close released it. +The native app was closed and reopened: Imperial (US) / Road restored as a +saved choice. Existing diagnostics, execution-target, profile, home and +not-found routes loaded without an error banner. Only the exact temporary +WebView profile was removed; the preference created by this smoke was left at +the sensible Imperial/Road default, and no unrelated preferences were changed. diff --git a/docs/live-dashboard.md b/docs/live-dashboard.md index 94163dc..8085054 100644 --- a/docs/live-dashboard.md +++ b/docs/live-dashboard.md @@ -29,18 +29,66 @@ case-insensitively; signal identifiers, units and origins are exact ordinal values. Labels and gauge identifiers cannot have surrounding whitespace. Minimum and maximum must be finite, ordered, and have a finite positive span; the precision is an integer 0..3. Binding validation requires the exact -session-observed module, signal and unit. No unit conversion, alias, role-based -guessing or fallback is performed. Definitions are process/session memory only; -there is no dashboard persistence or import/export format. +session-observed module, signal and source unit. Conversion never changes this +binding contract. Definitions are process/session memory only; there is no +dashboard persistence or import/export format. + +## Display units + +The shared shell exposes one **Unit system** selector (Metric or Imperial (US)) +and one **Speed presentation** selector (Road or Engineering), including before +a vehicle session opens. First use defaults to **Imperial (US) / Road**; +ordinary speed therefore displays mph. Road mode selects km/h or mph, while +Engineering selects source m/s or ft/s. Changing the system preserves the +selected speed mode. The native Client persists this small preference with +MAUI's local Preferences store, so it survives route navigation and app restart. +Missing data means the first-use default. Invalid or unreadable data is reported +visibly with the explicitly labeled Imperial/Road default; it is not silently +overwritten. A selection is published only after a successful write, so a +failed save leaves the prior active choice in effect and exposes an error. +Portable test compositions use an isolated store; the UI-only fallback is an +explicit unavailable store, not an in-memory native substitute. + +Conversion uses the exact source unit and raw numeric sample, before the +existing display precision. The supported mappings are: + +| Exact source unit | Metric | Imperial (US) | +|---|---|---| +| `m/s` | Road `km/h`; Engineering `m/s` | Road `mph`; Engineering `ft/s` | +| `m` | `m` | `ft` | +| `kg` | `kg` | `lb` | +| `kg/s` | `kg/s` | `lb/h` | +| `N*m` | `N*m` | `lbf*ft` | +| `degC` | `degC` | `degF` | +| `m/s^2` | `m/s^2` | `ft/s^2` | +| `rpm`, `V`, `ratio`, `count`, `gear`, `boolean` | Exact source unit | Exact source unit | + +The factors use 1 ft = 0.3048 m, 1 mile = 1609.344 m, 1 lb = 0.45359237 kg, +1 lbf = 4.4482216152605 N, and 3600 seconds per hour; temperature uses +`degF = degC * 9/5 + 32`. Other exact source units pass through with an explicit +unconverted notice and are never relabeled. No UK gallons, fuel economy or +other unassigned conversion is inferred. + +Dashboard values and display range labels are separate projections. Gauge +definitions, source values, quality/range/freshness, actual sample context and +bar percentage remain canonical. Editor bounds are shown in the draft's +captured units, then converted once to exact source units on a valid edit. +Unedited saves preserve the original source bounds exactly. A unit change while +an editor is open does not reinterpret typed values; the draft states its +captured unit until save/cancel/reset. Temperature bounds use the full affine +conversion, so 0..100 degC displays as 32..212 degF. Failed or overflowing +projections show an unavailable value/error rather than fabricated data or +invalid geometry. ## Readings, ranges and freshness The display preserves the actual finite numeric measurement. The horizontal bar alone is clamped to 0..100 percent; the configured low/high boundary is shown separately, and an out-of-range value is not rewritten into the range. -For example, `-10` remains `-10` with low-range status and zero-width geometry; -`1100` remains `1100` with high-range status and full-width geometry for a -0..1000 range. Numeric zero remains a real zero reading. +For example, `-10` remains the corresponding projected reading with low-range +status and zero-width geometry; `1100` remains the corresponding projected +reading with high-range status and full-width geometry for a 0..1000 source +range. Numeric zero remains a real zero reading. Measurement quality and range are independent. Good, Uncertain, Unknown, Pending, Stale, Error, Stopped and Unavailable states are visible as text as @@ -87,8 +135,10 @@ a new feed and empty source context; an old pending response is not published into it. The UI panel subscribes to immutable feed snapshots only to schedule rendering -on the component dispatcher. Hiding or disposing the panel detaches that -subscription; it neither starts a second poller nor stops the session owner. +on the component dispatcher. Display-preference notifications also rerender +mounted presentation without requesting data or changing the feed. Hiding or +disposing the panel detaches its feed subscription; it neither starts a second +poller nor stops the session owner. Explicit monitoring Stop or session/scope lifetime ends acquisition. Cleanup errors remain visible and do not skip source disposal. @@ -110,6 +160,7 @@ rendered DI composition, and the session-lifetime path. Headless results do not substitute for a native Client smoke. Current worker evidence and native status are recorded in the [Step-05A corrective report](../prompts/Step-05A-Report.md). -All signals and dynamics values remain synthetic. The dashboard adds no -recording, charts, unit conversion, vehicle compatibility, manufacturer -prediction, hardware access, calibration editing or physical writes. +all signals and dynamics values remain synthetic. Display units are a +presentation-only projection; the dashboard adds no recording, charts, vehicle +compatibility, manufacturer prediction, hardware access, calibration editing +or physical writes. diff --git a/docs/simulation.md b/docs/simulation.md index 678e964..d138f19 100644 --- a/docs/simulation.md +++ b/docs/simulation.md @@ -237,8 +237,13 @@ tuning guidance, validated manufacturer prediction or physical vehicle data. The route also hosts the shared configurable dashboard. It reads the same session-bound v2 source and reports per-response model step/time separately from diagnostic request ticks; polling and rendering do not advance the fixed-step -model. See the [live dashboard guide](live-dashboard.md) for its editor and -freshness contract. +model. Scenario target speeds and decoded numeric telemetry use the shared +Imperial (US)/Metric display preference; each decoded row retains its exact +source value and unit beside the display projection. Scenario definitions, +configuration JSON, SI model state and fingerprints are unchanged. Static trace +payloads and configuration interchange are source data, not converted output. +See the [live dashboard guide](live-dashboard.md) for mappings, preference +persistence/error handling, editor range policy and freshness contract. ## Reproducible faults and lifecycle diff --git a/prompts/ROADMAP.md b/prompts/ROADMAP.md index 2b63896..9c140aa 100644 --- a/prompts/ROADMAP.md +++ b/prompts/ROADMAP.md @@ -3,13 +3,13 @@ ## Status and authority - Initialized: 2026-10-28. -- Current phase: corrected configurable dashboard accepted; imperial-default display units next. -- Active assignment: [Step-06](Step-06.md), ready for manual worker execution. +- Current phase: Step-06 reviewed; preference-rejection and unavailable-readout correction required. +- Active assignment: [Step-06A](Step-06A.md), ready for manual worker execution. - Last accepted milestone: Step-05 with Step-05A/Step-05B, accepted 2026-10-29. - Last accepted correction: Step-05B; all Step-05 findings closed. -- Outstanding corrections: none. +- Outstanding corrections: Step-06 R-01 preference rejection and R-02 unavailable/non-numeric readouts. - Step-05 status: ACCEPTED after Step-05A/Step-05B, 2026-10-29. -- Step-06 status: READY FOR WORKER; display units/preference not implemented yet. +- Step-06 status: REQUIRES FOCUSED CORRECTION / NOT ACCEPTED, reviewed 2026-10-30. - Step-07 status: recording/replay moved from former Step-06; BLOCKED until display units are accepted. - Current state and handoff: [STATE.md](STATE.md). - Authority: the master charter, repository/handoff amendment, and the owner's @@ -353,9 +353,10 @@ Step-01, Step-01A, corrected Step-02 and corrected Step-03 remain accepted. Corrected Step-04 is accepted with original and corrective evidence preserved. Step-05 with Step-05A/05B is accepted: the configured static/dynamic workflow, single session owner, independent range/quality, safe gauges, decisive tests and -native evidence have been reviewed. Step-06 is the only active assignment for -newly approved display units. Recording/replay remains Step-07 and blocked until -that work is accepted. The units request did not alter prior frozen criteria. +native evidence have been reviewed. Step-06 now implements the shared units +feature, but its original preference-rejection and unavailable-readout criteria +need Step-06A. That is the only active assignment. Recording/replay remains +Step-07 and blocked until corrected units work is accepted. Dependencies indicate acceptance prerequisites, not permission for automatic handoff. Later assignments refine these scopes using actual implementation evidence; they must not silently discard required capabilities. @@ -375,8 +376,9 @@ evidence; they must not silently discard required capabilities. | 05 | First configurable live dashboard | 04 and corrections accepted; 01A foundation | ACCEPTED 2026-10-29 AFTER 05A/05B | Actual static/dynamic numeric/bar dashboard, validated in-memory configuration, one session owner, truthful states and controlled/native evidence inspected | | 05A | Complete and verify the assigned dashboard contract | 05 review R-01 through R-05 | ACCEPTED 2026-10-29 AFTER 05B | Host/editor/lifetime/failure/rendering/docs/native scope corrected; last range/test obligations closed by 05B | | 05B | Independent range status and decisive dashboard tests | Remaining 05A R-03/testing contract | ACCEPTED 2026-10-29 | Frozen five-case/five-criterion contract satisfied; reported 134 unit/91 integration passes, clean Release/native recheck and actual pre-fix failure | -| 06 | Imperial-default metric/imperial display units | 05 and corrections accepted; owner request 2026-10-29 | READY FOR WORKER | Shared persisted Imperial (US)/Road default, metric/engineering speed choices and exact display conversions; unchanged SI/source/canonical bounds | -| 07 | Telemetry recording and replay | 06 accepted | BLOCKED / NOT ASSIGNED | Persist raw messages and decoded signals with source units/time/quality; playback/seek/speed controls feed the same gauges without reconstructing missing data | +| 06 | Imperial-default metric/imperial display units | 05 and corrections accepted; owner request 2026-10-29 | REQUIRES FOCUSED CORRECTION / NOT ACCEPTED | Shared conversions/default/native persistence and 20-toggle source preservation inspected; rejected preference UI/state and unavailable readout paths remain | +| 06A | Preference rejection and unavailable display readouts | 06 review R-01/R-02 | READY FOR WORKER | Reject invalid preferences before initialization; rejected-save selectors match active state; missing/Unknown/non-numeric display handling remains explicit across assigned surfaces | +| 07 | Telemetry recording and replay | 06 and corrections accepted | BLOCKED / NOT ASSIGNED | Persist raw messages and decoded signals with source units/time/quality; playback/seek/speed controls feed the same gauges without reconstructing missing data | | 08 | Calibration management and simulated programming | 07 | PLANNED | Versioned definitions/diffs, verified baseline and backup, approved simulated write, readback/unrelated-data checks, audit and supported restore; no physical writes | | 09 | Local AI, knowledge, and validated runbooks | 08 | PLANNED | Replaceable local inference, applicable knowledge retrieval, structured logical runbook, independent validation/approval and simulation-only execution | | 10 | Comparative evaluation and complete synthetic demonstration | 09 | PLANNED | Complete demonstration below plus deterministic fault/regression matrix and independent verification of intended and unintended changes | @@ -745,20 +747,48 @@ history, not repeated redesign without evidence. all prior reports remain distinct. The orchestrator ran no application checks. - Accepted corrected Step-05/05A/05B and prepared [Step-06](Step-06.md) for the separately approved units work. No Step-05C is required. +- Reviewed returned Step-06 report, conversion/preference/native-adapter code, + shell/route/panel/editor paths, all added units tests, docs and Release artifacts. + Worker reports 178 unit + 92 integration passes (270 total, zero failed/skipped), + clean complete Release build and real native static/dynamic/four-speed-mode/ + editor/persistence smoke. The orchestrator ran no application checks. +- Correct mappings, first-use/restored preferences, source/canonical invariants, + pinned editor evidence and positive native behavior are supported. Withheld + acceptance for two consolidated existing-scope findings in + [Step-06A](Step-06A.md); no units redesign or recording work is assigned. ### Remaining -- Worker execution of Step-06, then one consolidated review against its frozen - display/preference/conversion/editor matrix and the shared quality gate. - Correct genuine unmet criteria as Step-06A before recording/replay. -- Step-07 recording/replay is blocked and not assigned. The new display preference - and conversions are assigned work, not implemented functionality. +- Worker execution of Step-06A, then one consolidated review against its focused + correction matrix, original Step-06 contract and shared quality gate. +- Step-07 recording/replay is blocked and not assigned. Display units exist but + remain unaccepted; preserve their supported positive behavior and evidence. - Profile/module metadata, synthetic virtual-module communication and deterministic dynamics/v2 and corrected dashboard are accepted; later features remain planned. Preserve the complete sequence/safety gates. ### Known blockers and uncertainties +Step-06 has two open findings against C-07/C-08/C-09 and the original rejection/ +all-surfaces requirements: + +- R-01: TrySet initializes before validating an undefined proposal, so a rejected + call on a fresh service can read persisted data and change active/initialized + state. Shell selectors use plain value/onchange, with no binding feedback for + a rejected browser selection; a failed write can leave the DOM option at the + rejected choice while the service/readouts retain the old selection. +- R-02: the display helpers echo every non-number JSON value or missing numeric + fallback text without availability/unit validation. Null becomes blank, wrong- + type numeric values appear as ordinary display text, and non-numeric unknown + units skip the explicit unconverted notice. Readout callers do not pass source + quality to suppress an Unknown current numeric reading. + +These are source-path findings, not orchestrator-executed reproductions. Existing +tests initialize before invalid preference calls, mutate preferences directly +rather than exercising failed selector events, and cover a Good converted speed +gauge rather than the missing/Unknown readout paths. Step-06A must reproduce the +applicable failures and close these existing requirements without new features. + No blocking Step-05 deficiency remains. The two Step-05A follow-up findings below are historical and closed by accepted Step-05B: diff --git a/prompts/STATE.md b/prompts/STATE.md index aacbed9..6eacb8f 100644 --- a/prompts/STATE.md +++ b/prompts/STATE.md @@ -4,25 +4,25 @@ | Field | Value | |---|---| -| Updated | 2026-10-29 | -| Phase | Corrected dashboard accepted; imperial-default display units next | -| Active step | Step-06 - Imperial-default metric/imperial display units | -| Assignment | [Step-06.md](Step-06.md) | +| Updated | 2026-10-30 | +| Phase | Step-06 reviewed; focused rejection/readout correction remains | +| Active step | Step-06A - Preference rejection and unavailable display readouts | +| Assignment | [Step-06A.md](Step-06A.md) | | Assignment status | READY FOR WORKER / AWAITING MANUAL HANDOFF | -| Expected worker report | `prompts/Step-06-Report.md` - not yet created | +| Expected worker report | `prompts/Step-06A-Report.md` - not yet created | | Last accepted correction | Step-05B - accepted 2026-10-29 | | Last accepted major milestone | Step-05 with Step-05A/Step-05B - accepted 2026-10-29 | -| Outstanding corrections | None | +| Outstanding corrections | Step-06 R-01 preference rejection and R-02 unavailable/non-numeric readouts | | Step-02 status | ACCEPTED after Step-02A | | Step-03 status | ACCEPTED after Step-03A/Step-03B | | Step-04 status | ACCEPTED after Step-04A/Step-04B | | Step-04A review | All original corrective criteria closed with Step-04B | | Step-05 status | ACCEPTED after Step-05A/Step-05B | | Step-05A review | All original corrective criteria closed with Step-05B | -| Step-06 status | READY FOR WORKER; Imperial (US) first-use default with metric toggle | +| Step-06 status | REQUIRES FOCUSED CORRECTION / NOT ACCEPTED | | Step-07 status | Recording/replay, formerly Step-06; BLOCKED until display-unit work is accepted | -| Worker execution | Step-05B returned and accepted; Step-06 not invoked | -| Immediate next action | User manually directs the worker to execute Step-06 and shared quality gate only | +| Worker execution | Step-06 returned; Step-06A not invoked | +| Immediate next action | User manually directs the worker to execute Step-06A with original Step-06 and shared quality gate | | Next orchestrator action | After manual return, inspect the assignment, report, implementation, tests, Git changes, documentation and recorded command evidence | ## Repository baseline at initialization @@ -749,8 +749,9 @@ builds/tests/native/workload commands and did not execute the reproduction. Original Step-05 findings and its Step-05A follow-up are closed. Preserve the 207-/224-/225-case reports and original dynamics numerical/native history. -Step-06 is the sole ready assignment for new display units, with one shared -preference/conversion contract and explicit editor/raw-data invariants. +At that acceptance Step-06 was prepared for new display units, with one shared +preference/conversion contract and explicit editor/raw-data invariants. Its +returned implementation is reviewed below. ## Owner decision - imperial-default display units @@ -776,12 +777,57 @@ navigation/restarts. Unsupported units remain explicitly unconverted, and no fuel mass-to-volume conversion may invent density. Apply consistently across current human-facing simulation/diagnostic/dashboard surfaces. -No display-unit implementation exists yet. Following Step-05B acceptance, -[Step-06](Step-06.md) is ready before recording/replay. It freezes the two unit -systems plus Road/Engineering speed presentation, first-use/saved/error behavior, -exact conversion vectors and stable source-unit gauge bounds. Open editor -drafts retain their explicitly captured input unit until saved/cancelled, so a -toggle cannot reinterpret unsaved numbers. +Following Step-05B acceptance, [Step-06](Step-06.md) assigned the two unit systems +plus Road/Engineering speed presentation, first-use/saved/error behavior, exact +conversion vectors and stable source-unit gauge bounds. Its implementation now +exists but is unaccepted pending the focused review findings below. The default +and unit mappings remain approved; this is not a request to redesign them. + +## Step-06 review and focused correction + +Decision: **REQUIRES FOCUSED CORRECTION / NOT ACCEPTED**, 2026-10-30. +Reviewed [Step-06](Step-06.md), its [report](Step-06-Report.md), all new conversion/ +preference/native-store/presentation code, changed shell/host/editor paths, +new unit and actual-provider tests, docs, nine-project references and artifacts. + +Positive evidence: exact forward/inverse mappings and rounding, Imperial/Road +default, explicit stored/corrupt/read/write states at the service boundary, +real MAUI adapter, pinned native editor behavior, 20 controlled toggles preserving +actual source/canonical/model/trace bytes and no extra reads. Worker reports +clean nine-project Release build, 178 unit + 92 integration passes (270 total, +zero failed/skipped), real native four-mode speed/range/editor/route smoke and +saved preference restoration. Existing artifacts/case inventory corroborate +that report, not independent orchestrator execution. + +| Finding | Evidence | Original contract | +|---|---|---| +| R-01 - incomplete rejection boundary | TrySet calls Initialize before checking IsValid; a fresh invalid request can load/change selection/initialized state. MainLayout uses plain value/onchange for both selectors, so rejected browser selection is not bound back to the unchanged service value. Existing negative tests initialize first and test service state, not the failed control event/DOM state. | C-09, section A reject-before-any-state/store-mutation, AC-01/AC-03/AC-04 | +| R-02 - unavailable/non-numeric readout bypass | DisplayUnitPresentation echoes JsonElement.ToString for every non-number or sourceText when NumericValue is absent. Null can be blank, wrong-type numeric values are echoed as normal readings, unsupported-unit text has no notice, and callers omit source quality when projecting Unknown numerics. The gauge path handles placeholders, but diagnostics/simulation readout paths do not apply the same contract. | C-07/C-08/C-10, section C all assigned surfaces, AC-02/AC-03/AC-04 | + +| Original criterion | Decision | Evidence/gap | +|---|---|---| +| AC-01 | PARTIAL / NOT ACCEPTED | Default/restoration/native storage work; fresh-invalid and failed-selector rejection are not fully atomic | +| AC-02 | PARTIAL / NOT ACCEPTED | Exact numeric vectors/inverses/rounding supported; non-numeric/unavailable paths bypass validation/notice | +| AC-03 | PARTIAL / NOT ACCEPTED | Source/bounds/draft and Good-speed toggle evidence supported; rejection and all-surface Unknown/missing outcomes remain unmet | +| AC-04 | PARTIAL / NOT ACCEPTED | Current surfaces are wired and raw data retained; primary readouts need consistent unavailable handling | +| AC-05 | WORKER EXECUTION EVIDENCE REVIEWED | Reported 270 passes/clean Release/native smoke are preservation/positive evidence; they do not prove the missing negative paths | +| AC-06 | PARTIAL / NOT ACCEPTED | Docs/report/self-review exist; C-07/C-09 claims need decisive event/readout evidence in the corrective report | +| AC-07 | PRESERVATION SUPPORTED | Original prompts/history/shared gate, nine projects/references and protected files preserved; no later step or package/system change reported | + +The static-v1 contract permits null/non-numeric JSON signal values; these do +reach the diagnostics display helper. Dynamic v2 remains strictly typed and must +not be weakened to create test inputs. Valid boolean false and numeric zero must +remain distinct from unavailable readings. + +The [official Blazor binding guidance](https://learn.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-10.0#use-bindgetbindset-modifiers-and-avoid-event-handlers-for-two-way-data-binding) +confirms why event-handler-only value attributes do not guarantee DOM/model +reconciliation after rejection. This is source/framework evidence, not a claim +that the orchestrator ran the failing native interaction. + +No application builds/tests/native/workload commands or runtime reproductions +were executed by the orchestrator. Preserve [Step-06-Report.md](Step-06-Report.md) +unchanged. [Step-06A](Step-06A.md) is limited to these two existing-scope findings +and their real regressions; no Step-07 assignment is created. ## Prerequisites, limitations, and known issues @@ -809,23 +855,24 @@ toggle cannot reinterpret unsaved numbers. Step-04B. Step-05's original and follow-up findings are closed. Preserve the 190-/ 202-/207-case reports and original numerical/native evidence distinctly. - Profile metadata/UI, synthetic diagnostics, deterministic dynamics/v2 and the - corrected dashboard are accepted. Display units, replay, calibration values, + corrected dashboard are accepted. Display units exist but are unaccepted. + Replay, calibration values, persistence, AI and physical hardware operations remain unimplemented. - No application build or test has been executed by the orchestrator. ## Review and progression gate -On manual return, evaluate Step-06 and its frozen display-unit contract/shared gate using the +On manual return, evaluate Step-06A and the original Step-06 display-unit contract/shared gate using the assignment, worker report, actual code/tests, dependency graph, Git changes, README/docs, and recorded build/test evidence. Do not accept solely on a success claim; do not claim independent runtime verification. -- Inspect shared default/saved preferences, conversion vectors, all assigned UI - surfaces, canonical bounds/draft invariants, raw/source preservation and real - provider/native evidence. Do not add deferred recording/layout/unit families. -- If accepted: accept Step-06, update roadmap/state, prepare Step-07 +- Inspect reject-before-initialize, actual selector rollback after failed saves, + shared unavailable/typed/quality handling, and preserved positive units/source/ + editor behavior. Do not add deferred recording/layout/unit families. +- If accepted: close Step-06A, accept corrected Step-06, update roadmap/state, prepare Step-07 recording/replay and stop for manual handoff. -- If deficient: issue narrowly scoped Step-06A only for a material unmet contract/ +- If deficient: issue narrowly scoped Step-06B only for a material unmet contract/ regression, then stop. Planned new features are not corrections. - If blocked: retain the active step, document the prerequisite and required worker evidence; do not advance or mark unexecuted checks as successful. @@ -881,12 +928,15 @@ claim; do not claim independent runtime verification. | 2026-10-29 | Step-05B returned and ACCEPTED | Frozen range/test/cleanup matrix satisfied; actual red regression, 225-case/clean Release/native recheck evidence and source-path self-review inspected | | 2026-10-29 | Corrected Step-05 ACCEPTED | Original and 05A/05B criteria closed; no 05C; reports/source/numerical history preserved | | 2026-10-29 | Step-06 prepared | Imperial-default shared presentation preference/conversions, stable canonical source bounds and explicit editor/raw-data policy; manual handoff pending, Step-07 blocked | +| 2026-10-30 | Step-06 returned and reviewed | Exact conversion/default/native persistence/editor/source-invariance paths and reported 270-case/clean Release/native evidence inspected | +| 2026-10-30 | Step-06 requires focused correction | R-01 fresh-invalid initialization and failed-selector reconciliation; R-02 null/non-numeric/Unknown display bypass; original C-07/C-08/C-09, not new product scope | +| 2026-10-30 | Step-06A prepared | Narrow rejection/readout correction with real pre-fix/event/provider tests; preserve approved imperial defaults/mappings, no Step-07 | ## Manual handoff instruction -Provide [Step-06.md](Step-06.md) and the shared +Provide [Step-06A.md](Step-06A.md), original [Step-06.md](Step-06.md) and the shared [worker gate](WORKER-QUALITY-GATE.md) to the separate worker and request execution -of that assignment only. The worker must produce `prompts/Step-06-Report.md` +of the focused correction only. The worker must produce `prompts/Step-06A-Report.md` and stop for review. Do not begin Step-07 recording/replay. Return manually to the orchestrator for review. Reports, including final chat reports, must follow the single plain triple-backtick copy-window requirement. diff --git a/prompts/Step-06-Report.md b/prompts/Step-06-Report.md new file mode 100644 index 0000000..bc8825c --- /dev/null +++ b/prompts/Step-06-Report.md @@ -0,0 +1,165 @@ +``` +# Step-06 - Imperial-default display units + +Status: COMPLETE on worker implementation and verification evidence; pending +manual orchestrator review. Step-07 was not started. + +## Summary + +Added one shared Imperial (US)/Metric and Road/Engineering selection, with +Imperial (US) / Road as the first-use default. The native Client persists this +small selection through MAUI Preferences. The pure conversion boundary projects +finite source numerics into supported display units without mutating source +signals, SI model state, configuration JSON/fingerprints, exact dashboard +bindings/bounds, source quality/range/time, or acquisition ownership. + +The shared shell exposes accessible controls and truthful first-use/restored/ +error state before a vehicle session opens. Diagnostics, simulation scenario +targets, simulation telemetry and live dashboard readings use the same +conversion logic. Dashboard edit bounds are displayed in a draft-pinned unit +and converted to source units only for changed inputs. Unknown units are +preserved with an explicit unconverted notice; conversion/storage failures are +visible and do not fabricate data or publish a failed selection. + +## Implemented code and documentation + +- `src/AutoForge.Application/Features/DisplayUnits/DisplayUnitSettings.cs` + defines the immutable selection, exact mapping/inverse/bounds conversions, + preference port/service, validation and visible storage-failure behavior. +- `src/AutoForge.Client/DisplayUnits/MauiDisplayUnitPreferenceStore.cs` adapts + the application port to MAUI `Preferences`; `MauiProgram.cs` registers it + before UI composition. +- `src/AutoForge.UI/Features/DisplayUnits/DisplayUnitPresentation.cs` converts + JSON/dynamics numeric values from their raw numeric representation before + formatting. `MainLayout.razor` owns the shared controls, status/error and + cascading selection. +- `LiveDashboardPanel.razor` projects values/ranges without changing canonical + definitions, preserves source reading state on projection failure, pins + editor selection, converts edited bounds once, retains exact unedited bounds, + and exposes explicit reset/cancel/error context. +- `DiagnosticsPage.razor`, `SimulationPage.razor` and + `SimulationPageViewModel.cs` retain raw/source columns and add display-only + projections for assigned human-readable measurements. +- `src/tests/AutoForge.UnitTests/DisplayUnitSettingsTests.cs` adds pure mapping, + inverse, bounds, overflow, unknown/pass-through, rounding and preference-store + cases. `src/tests/AutoForge.IntegrationTests/IsolatedDisplayUnitPreferenceStore.cs` + supplies explicit portable test persistence. Integration composition uses + that store rather than the unavailable UI fallback. +- Related composition tests and `DynamicsWorkflowTests.cs` cover real providers, + shared rendering, paused-session toggles and source/wire invariants. +- Updated `README.md`, `docs/README.md`, `docs/architecture.md`, + `docs/build-and-test.md`, `docs/live-dashboard.md` and `docs/simulation.md`. + Step-05/05A/05B are identified as accepted; Step-06 is worker-complete and + pending manual review. Step-07 remains blocked. + +No project, package, host, project reference, protocol, schema, physics, +configuration fingerprint, history file or automation was added or changed. +No commit/stage/push was performed. + +## Contract matrix and named evidence + +| ID | Result | Executed evidence | +|---|---|---| +| C-01 | PASSED | `PreferenceService_UsesImperialRoadDefaultAndRestoresPersistedChoice` and native first-use shell: selectors were present before a session, the missing-key state identified Imperial (US) / Road as the first-use default, and no ambient culture/region was used. | +| C-02 | PASSED | `Project_KnownMappingsMatchIndependentVectors` and `ConvertToSource_RoundTripsSupportedVectorsWithinTolerance`: exact independent vectors and inverse conversions, absolute target tolerance 1e-9. Covered 20.1168 m/s -> 45 mph / 66 ft/s / 72.42048 km/h; 0.3048 m -> 1 ft; 0.45359237 kg -> 1 lb; (0.45359237/3600) kg/s -> 1 lb/h; 1.3558179483314004 N*m -> 1 lbf*ft; 0/100/-40 degC -> 32/212/-40 degF; and 0.3048 m/s^2 -> 1 ft/s^2. | +| C-03 | PASSED | `SpeedBoundsAndValueProjectionPreserveCanonicalGeometry` asserts all four raw projections and 0..40.2336 m/s bounds yield 50% geometry. Native real dynamic v2 sample was exactly 20.1168 m/s; observed display/range pairs were 45 mph / 0..90 mph, 66 ft/s / 0..132 ft/s, 72 km/h / 0..144.84096 km/h at the gauge's configured precision 0, and 20 m/s / 0..40.2336 m/s. All showed 50% meter geometry and unchanged source range/value. Exact unrounded 72.42048 km/h is independently asserted by the pure vector test. | +| C-04 | PASSED | `DisplayUnitTogglesOnPausedDynamicsFeedRerenderWithoutSourceOrModelMutation` performs 20 shared-preference toggles/rerenders on an actual paused dynamics session. It compares definitions, feed source context/values/states/range/time, immutable dynamics status, exported configuration, trace entries and byte-for-byte request/response payloads; actual `ReadSignals` trace count does not increase. | +| C-05 | PASSED | `Bounds_ConvertOffsetsAndRoundTripWithoutRoundingCanonicalValues` asserts 32..212 degF -> 0..100 degC, and `InvalidDefinitionReplacementIsAtomicAndEnforcesZeroToEightLimit` preserves feed state on rejected definitions. Native editor saved 0..90 mph as 0..40.2336 m/s; rejected 200..100 with visible alert and unchanged gauge; an unedited Save retained prior canonical bounds exactly. | +| C-06 | PASSED | Native editor opened on a real dynamic gauge with 10..110 mph typed, then global units changed to Metric/Road. Labels and values remained mph / 10..110 until save; saved source bounds were 4.470400000000001..49.174400000000006 m/s. The rendered draft-context message identified captured Imperial/Road units. Cancel and unedited Save were also exercised. | +| C-07 | PASSED | Existing real-feed coverage in `LiveDashboardAcquisitionTests` and `DynamicsWorkflowTests` verifies Pending/Good/Stale/Stopped, source quality/range/time and actual source context. Projection failures now keep `gauge.State` and separately show an alert/unavailable display; no conversion changes quality or clamps the value. | +| C-08 | PASSED | `Project_PreservesAssignedPassThroughUnits`, `Project_PassesThroughKnownUnitsAndExplicitlyLabelsUnknownUnits`, `Project_RejectsNonFiniteInputAndOverflowWithoutFabricatedValue` and `UnknownBoundsRemainSourceUnitsAndInvalidSelectionRejects` cover exact unchanged units, unsupported pass-through/notice, invalid enums, infinities, conversion overflow and finite ordered bounds. Native invalid edited bounds displayed an alert without changing the prior definition. | +| C-09 | PASSED | `PreferenceService_CorruptStoredChoiceShowsDefaultAndDoesNotOverwrite`, `PreferenceService_ReadFailureIsVisibleAndExplicitSelectionCanRecover`, and `PreferenceService_InvalidChoiceAndFailedWritePreserveActiveSelection` use controlled read/corrupt/write failures on the real service/port, including write atomicity. Native MAUI adapter started with no saved key; after explicit selection, closing/reopening the rebuilt Client restored saved Imperial (US) / Road. | +| C-10 | PASSED | The dynamics route test asserts displayed Imperial values and retained source `degC`, `kg/s`, `m/s`; configuration export is byte/string-identical across selection changes. The 20-toggle integration test compares copied raw trace request/response byte arrays. Native telemetry retained source 20.1168 m/s and 88.82446676508809 degC while showing display values; exported configuration remained 2,789 characters with SI target 20.1168 and no mph/km/h text. | +| C-11 | PASSED | `Project_ConvertsBeforeDisplayRounding` verifies raw 0.4 m/s -> approximately 0.894774516821761 mph within 1e-9 before precision-zero formatting to `1`, not `0`. | +| C-12 | PASSED | `StaticProviderCannotOpenDynamicsControls`, `StaticSession_FirstStartGroupsReadsAndSharesOneOwner`, `RealApplicationAndRenderedRoute_RunAndReadDynamicTelemetryWithoutOracle`, and the paused dynamics toggle test exercise real static v1/dynamic v2 composition. Native Client smoke configured a static rpm gauge and a dynamic speed bar, exercised existing routes, reset and close. | + +## Acceptance criteria + +| ID | Result | Evidence | +|---|---|---| +| AC-01 | PASSED | C-01/C-09 tests above plus real MAUI Preferences save/restart evidence. | +| AC-02 | PASSED | C-02/C-03/C-08/C-11 vector, inverse, precision, bounds, invalid and native rendered evidence above. | +| AC-03 | PASSED | C-04..C-07 real-feed source/state/wire invariants and native pinned editor, invalid save, unedited save and reset evidence above. | +| AC-04 | PASSED | Diagnostics, simulation scenario/telemetry, shared dashboard, raw/source inspectors, configuration JSON and native static/dynamic paths all use or preserve the assigned source/display boundary. | +| AC-05 | PASSED | Final nine-project Release build and all 270 preserved/added tests passed. Rebuilt native Client smoke covered static/dynamic gauges, four speed modes, draft/save/failure, restart, reset/close and legacy routes. | +| AC-06 | PASSED | Frozen matrix and exact named evidence are recorded here. Self-review and documentation changes are below. | +| AC-07 | PASSED | No protected/history/orchestration files, dependencies, stage/commit/push, agent or future-step work. Only this assignment report was added under `prompts`. | + +## Commands and outcomes + +Focused unit selection: + +- `dotnet test .\src\tests\AutoForge.UnitTests\AutoForge.UnitTests.csproj --configuration Release --no-restore --filter FullyQualifiedName~DisplayUnitSettingsTests` — exit 0; 44 passed, 0 failed/skipped. + +Focused real-provider/rendered integration selection: + +- `dotnet test .\src\tests\AutoForge.IntegrationTests\AutoForge.IntegrationTests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~DisplayUnitTogglesOnPausedDynamicsFeedRerenderWithoutSourceOrModelMutation|FullyQualifiedName~RealApplicationAndRenderedRoute_RunAndReadDynamicTelemetryWithoutOracle|FullyQualifiedName~StaticSession_FirstStartGroupsReadsAndSharesOneOwner"` — exit 0; 3 passed, 0 failed/skipped. +- After adding byte-for-byte trace-payload assertions, the focused `DisplayUnitTogglesOnPausedDynamicsFeedRerenderWithoutSourceOrModelMutation` selection — exit 0; 1 passed, 0 failed/skipped. + +Required final sequential full checks: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` — exit 0; all nine solution projects including the Windows Client; 0 warnings, 0 errors. MAUI XAML source-generation emitted its standard informational notice. +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` — exit 0; AutoForge.UnitTests 178 passed; AutoForge.IntegrationTests 92 passed; 270 total, 0 failed, 0 skipped. The accepted Step-05B baseline was 134 unit + 91 integration = 225; all cases remain, with 44 new unit and one new integration case. + +An intermediate attempt to run focused unit and integration test builds in +parallel contended on the shared Application output. That invocation was not +counted as passing evidence; the standalone focused integration rerun and the +required final sequential build/test commands above all completed successfully. + +## Native Client smoke versus controlled evidence + +Native evidence used the actual rebuilt executable at +`src\AutoForge.Client\bin\Release\net10.0-windows10.0.26100.0\win-x64\AutoForge.Client.exe`, +task-local WebView2 debug port 9361 and an isolated temporary WebView profile. +The initial app showed the explicit first-use/default status before any session. +The static synthetic session rendered 850 rpm unchanged through preference +changes. The dynamic synthetic session was paused at step 203 / 20.3 s; protocol +v2 telemetry showed source 20.1168 m/s beside Imperial display, and source +temperature/fuel/torque units beside their converted display values. The native +dashboard/editor results and route checks are mapped in C-03..C-06 and C-10/C-12. + +Native persistence was checked by closing process 44360 and reopening process +48432 against the same temporary WebView profile. The stored Imperial/Road +selection appeared as saved after restart. The exact temporary WebView profile, +the only task-created profile folder, was removed. Because the preference key +was absent on first launch, the smoke's explicit save created the app's +`imperial-us|road` value; that sensible task-owned preference value is left in +place. No existing preference or unrelated user data was wiped or replaced. +Both native processes and listener port 9361 were closed. + +Storage read/write failure, corrupt values, undefined enum values and conversion +overflow are controlled tests using the real preference/conversion services +and explicit isolated/faulting stores. They are not represented as native +platform-failure observations. No platform storage fault injection was added to +the Client. Native gauge precision was 0 for the exact speed demonstration, so +the UI showed the rounded 72 km/h; the raw 72.42048 km/h mapping and tolerance +are independently asserted before display rounding in unit tests. + +## Source-path self-review and preservation + +After the first green focused run, I walked the store->service->shell/cascade, +raw source->pure conversion->each readout, and gauge edit->validate->replace +paths. This review found that an unavailable display projection could replace +the underlying dashboard source state with Error. The panel was corrected to +retain the original source state and show a distinct display-unavailable alert; +the conversion error remains explicit, the value is `--`, and geometry is not +fabricated. Repeated focused and full checks then passed. The review also +distinguished first-use default from a persisted default so native smoke can +truthfully report restoration. + +The native adapter is registered before `AddAutoForgeUi`; the UI fallback is +explicitly unavailable and reports storage failure, not memory-backed success. +Selection enum validation occurs before writes; writes precede publication. +Mappings use exact unit strings and raw numeric values. Source unit binding, +quality/range, diagnostic/model time, configuration identity/fingerprint, +exported SI JSON, raw trace bytes, one feed owner and paused model state remain +unchanged. Unedited gauge bounds use the original canonical values; conversion +and ordered finite-span validation happen before definition replacement. + +`git diff --check` passed. No dependency manifest, package, project, Core, +Diagnostics, Simulation, Components, `prompts/STATE.md`, `prompts/ROADMAP.md`, +historical report or protected instruction was changed. The repository began +clean; all remaining modifications are Step-06 implementation/tests/docs and +this required report. No stage, commit, push, restore/install or Step-07 work +was performed. +``` diff --git a/prompts/Step-06A.md b/prompts/Step-06A.md new file mode 100644 index 0000000..4d935e7 --- /dev/null +++ b/prompts/Step-06A.md @@ -0,0 +1,208 @@ +# Step-06A - Preference rejection and unavailable display readouts + +## STEP IDENTIFIER + +Step-06A, focused correction of original Step-06 R-01/R-02. +Step-06 is NOT ACCEPTED; corrected Step-05 and earlier milestones remain accepted. +This is the sole active assignment. Step-07 recording/replay is blocked. + +## STEP TITLE + +Make rejected unit preferences atomic at service/control boundaries and preserve +explicit unavailable/typed source semantics across display readouts. + +## OBJECTIVE + +Close two existing-scope failures in [Step-06](Step-06.md), principally its +C-07/C-08/C-09 and all-surfaces/validate-before-mutate requirements. +Do not redesign the conversions, preference storage, editor or unit UX. + +Read [STATE.md](STATE.md), original Step-06, its preserved +[report](Step-06-Report.md) and [WORKER-QUALITY-GATE.md](WORKER-QUALITY-GATE.md). +Reproduce the applicable failures, fix and self-review within this assignment, +write `prompts/Step-06A-Report.md`, and STOP. + +## ARCHITECTURAL CONTEXT + +Keep all nine projects, one MAUI Client, pure Components and the existing shared +Application conversion/preference port -> UI presentation -> native storage +boundary. No new package, host, general settings framework or unit family. +Source/tests remain under `src`, tests under `src/tests`. + +The actual Imperial (US)/Road default, Metric/Road/Engineering options and +approved exact mappings remain unchanged. SI model/configuration/raw source +data, canonical gauge bounds and one session owner remain authoritative. + +## CURRENT IMPLEMENTATION STATE + +Worker-reported Step-06 results: complete nine-project Release build zero +warnings/errors; 178 unit + 92 integration passes (270 total, zero failed/ +skipped), native default/restore/static/dynamic/four-speed-mode/editor/close +smoke. The 44 numeric/preference unit cases and Good-speed 20-toggle integration +preserve meaningful positive behavior. Retain all of it. + +The orchestrator source review found two gaps; it did not execute a reproduction, +build, test or native launch. Reinspect Git and preserve existing worker changes +and all assignments/reports before editing. + +## REQUIRED IMPLEMENTATION + +### R-01 - Validate before initialization and reconcile rejected controls + +[TrySet](../src/AutoForge.Application/Features/DisplayUnits/DisplayUnitSettings.cs:107) +calls Initialize before IsValid. With a fresh service backed by a saved Metric +selection, an undefined proposal returns false after reading the store and +changing Selection/IsInitialized. Original section A explicitly requires +undefined options to reject before any state/store mutation. + +[MainLayout](../src/AutoForge.UI/Layout/MainLayout.razor:17) uses plain +value/onchange for both selectors. A browser choice is already changed when +TrySet fails; rendering the same previous value does not guarantee that the +browser option is restored. The service/error/readouts may retain the prior +selection while the control shows the rejected one. + +Use the framework-supported binding/reconciliation mechanism, not a reload or +second settings state. See the +[official Blazor guidance](https://learn.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-10.0#use-bindgetbindset-modifiers-and-avoid-event-handlers-for-two-way-data-binding). +Keep persistence-before-publication, explicit failure messages and successful +retry. Validate undefined selections before initialization/read/write; changing +the visible error is allowed, but do not load/change active or initialized state +as a side effect of rejecting an invalid proposal. + +Prove both actual control selections and shared readouts remain consistent on +failed unit-system and speed-mode saves. A direct TrySet assertion or static +HTML value string alone is not proof of browser/event rollback. + +### R-02 - Do not echo unavailable/wrong-type values as normal display data + +[DisplayUnitPresentation](../src/AutoForge.UI/Features/DisplayUnits/DisplayUnitPresentation.cs:10) +returns JsonElement.ToString for every non-number and sourceText when a numeric +value is absent. Therefore null may display blank, wrong-type values for numeric +units bypass conversion/error handling, and unknown-unit text has no explicit +unconverted notice. Current readout callers do not supply source quality for +the Unknown-value placeholder contract. + +Apply the original availability/quality/typed/unit rules consistently to the +diagnostics and simulation primary readouts, retaining their raw source columns/ +inspectors. Reuse the shared boundary rather than adding per-page fallbacks. + +- Missing/null/undefined or Unknown current measurement -> explicit `--` and + appropriate source/unavailable context, not blank, zero or a current converted + numeric reading. Do not change the underlying source quality. +- A known numeric quantity with non-numeric data -> explicit unavailable/error + display, not ordinary echoed measurement text. Keep raw source text visible + in the separately labeled source inspector. +- Valid numeric zero and boolean false remain legitimate, distinct pass-through + values. Finite Uncertain values remain numeric and visibly Uncertain; retained + Stale/Stopped readings preserve their source state/time/range. +- Unsupported units, including valid non-numeric source content, preserve the + actual source value/unit with an explicit unconverted notice. Do not relabel + them, invent a conversion or convert them into a fabricated numeric zero. +- A display/conversion failure stays separate from original source state, as + the corrected dashboard path already requires. + +Static-v1 accepts null/non-numeric JSON source values, so these are reachable +real inputs. Use that existing contract for tests. Do not weaken strict v2 +signal validation or alter protocol/schema/model behavior to manufacture cases. + +### Frozen corrective matrix + +| ID | Input/precondition | Required result | +|---|---|---| +| C-01 | Fresh service, saved Metric selection or faulting read store; undefined system/speed proposal | Visible typed rejection before initialization/read/write; original Selection, IsInitialized and persisted-state flag unchanged; zero store calls | +| C-02 | Initialized active preference; user changes either selector while store write fails | Explicit error; service, actual selected options and shared readouts all show the previous active preference; no source/model/acquisition mutation | +| C-03 | Store recovers; repeat a valid control change | Selection saves/publishes once; both controls/readouts agree and error clears; restoration/default semantics remain intact | +| C-04 | Real v1 null/missing numeric or Unknown quality, including Unknown with a numeric source value | Primary readout is `--`, never blank/current numeric/zero; original raw value/unit/quality/time remain available separately | +| C-05 | Wrong-type data for a known numeric unit; valid zero/false; unsupported-unit numeric/text | Numeric type error is explicit; zero/false stay real; unsupported content/unit is retained with notice, not silently treated as a converted measurement | +| C-06 | Unit changes for converted Uncertain/Stale/Stopped/failed-display cases | Existing quality/range/reason/time and canonical bounds remain correct; no healthy-state substitution, fake bar or extra read/step | +| C-07 | Existing numeric/default/persistence/editor/raw-source and native baseline | All 270 cases and original vectors/source invariants preserved; positive native behavior still works; recording/replay remains unimplemented | + +## FILES OR PROJECTS EXPECTED TO CHANGE + +Existing preference service guard, shared shell selector binding, shared display +presentation and necessary diagnostic/simulation caller context, focused tests +and directly related docs/README/verification record. Native adapter or panel +changes only if an actual coupled assertion requires them; no redesign. +Only `prompts/Step-06A-Report.md` under `prompts`. + +## INTERFACE AND DEPENDENCY REQUIREMENTS + +Keep exact source binding/unit/canonical bounds and all 1e-9 representative +conversion vectors, Imperial first-use default, explicit persisted/error status, +one shared preference and native MAUI storage. No silent in-memory native +fallback, source alteration, engine oracle, new dependency or protocol relaxation. + +Preserve the nine-project graph, diagnostic/partial-discovery/verified-clear +gates and independent physics time. No workload/system install/restore/update/ +repair/rollback, staging/commit/push, destructive Git, or protected/history edit. + +## TESTING REQUIREMENTS + +Record actual pre-fix failures for C-01/C-02 and the reachable R-02 readout paths, +then verify corrected behavior. No compilation failure or invented browser +observation counts as reproduction. If an inspected path behaves differently +under actual event testing, record the decisive evidence, not an assumed failure. + +Use the real service plus explicit faulting store below its boundary. Exercise +the actual selector event/DOM or framework-supported event/render reconciliation, +not only direct service calls. No production platform-failure selector or +additional host/package is assigned. + +Use real v1 session/provider/rewrite transport and rendered diagnostics/readouts +for nullable/non-numeric/Unknown values; preserve v2's boolean/numeric shape. +Add meaningful shared-helper and converted quality-state assertions rather than +citing only the old Good/rpm tests. Retain source text/quality/time/trace bytes, +canonical definitions and request/model counts. Release resources in finally. + +Run focused cases, then sequentially: + +- `dotnet build .\src\AutoForge.slnx --configuration Release --no-restore` +- `dotnet test .\src\AutoForge.slnx --configuration Release --no-build` + +Preserve the 270 baseline cases (178 unit, 92 integration) plus meaningful new +coverage. Map intentional display-only assertion updates; do not remove source/ +safety/error checks. No dependency restore/install absent a real missing failure. + +Recheck the rebuilt native static/dynamic selector/readout/editor baseline and +persistence/close. Controlled fault-store/invalid-source tests establish error +paths; do not represent them as native platform-failure observations. +Preserve task-owned-only preference/profile cleanup and unrelated user data. +If required verification is blocked, report its exact unmet criterion honestly. + +## DOCUMENTATION REQUIREMENTS + +Align preference rejection, unavailable/source-quality/unsupported-unit display +semantics and verification evidence with actual behavior. Keep the approved +default/mapping/draft policy and positive Step-06 native report as history. +Do not claim Step-06 acceptance or Step-07 implementation. + +## ACCEPTANCE CRITERIA + +| ID | Criterion | Evidence | +|---|---|---| +| AC-01 | R-01/C-01..C-03 invalid/rejected preference changes are atomic through service and controls | Actual pre-fix/service/event failures and corrected control/readout/store assertions | +| AC-02 | R-02/C-04..C-06 all assigned primary readouts apply explicit typed/quality/availability/unit rules | Real v1/rendered/helper tests, correct zero/false/unsupported handling and preserved converted states/source | +| AC-03 | C-07 original numeric/preferences/editor/source/model behavior and 270 regressions preserved | Focused plus complete nine-project Release build/tests and native baseline evidence | +| AC-04 | Original C-07/C-08/C-09 and related acceptance mapping, self-review and docs are accurate | Named executed cases, exact inputs/results and source-path self-review after first green | +| AC-05 | Existing history/protection/dependencies/manual workflow preserved; report saved and worker stops | `prompts/Step-06A-Report.md` and preservation/Git review | + +## OUT-OF-SCOPE WORK + +Recording/replay, new unit families/pressure/volume/economy, preference/editor/ +layout redesign, charts/dashboard persistence, schema/protocol/physics/clock, +new host/project/package, AI/hardware and unrelated cleanup. +No agents/automatic handoff, future assignment, orchestration/shared-gate edit, +stage, commit or push. + +## REPORTING REQUIREMENTS + +Save `prompts/Step-06A-Report.md` entirely inside exactly one plain triple-backtick +fence, no language tag/outside content/nested fences. Include identifier/title/ +status, implementation/files/interfaces, R-01/R-02 and C-01..C-07/AC-01..AC-05 +mapping, named actual pre/post results, precise service versus control/browser +evidence, commands/exits/warnings/per-project counts, native versus controlled +coverage, docs/README, self-review after first green, limitations/deviations/ +blockers and preservation review. + +COMPLETE requires all assigned checks; otherwise report INCOMPLETE/BLOCKED and +the precise missing criterion. Save and STOP for manual review; no Step-07. diff --git a/src/AutoForge.Application/Features/DisplayUnits/DisplayUnitSettings.cs b/src/AutoForge.Application/Features/DisplayUnits/DisplayUnitSettings.cs new file mode 100644 index 0000000..0559f2e --- /dev/null +++ b/src/AutoForge.Application/Features/DisplayUnits/DisplayUnitSettings.cs @@ -0,0 +1,385 @@ +using System.Globalization; +using System.IO; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace AutoForge.Application.Features.DisplayUnits; + +public enum DisplayUnitSystem +{ + Metric, + ImperialUS +} + +public enum SpeedDisplayMode +{ + Road, + Engineering +} + +public readonly record struct DisplayUnitSelection( + DisplayUnitSystem UnitSystem, + SpeedDisplayMode SpeedMode) +{ + public static DisplayUnitSelection Default { get; } = + new(DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road); +} + +public sealed record DisplayMeasurement( + double? Value, + string Unit, + string? Notice = null, + string? Error = null) +{ + public bool IsAvailable => Value is not null && Error is null; +} + +public sealed class DisplayUnitConversionException(string message) : Exception(message); + +public sealed class DisplayUnitPreferenceStoreException(string message, Exception innerException) + : Exception(message, innerException); + +public interface IDisplayUnitPreferenceStore +{ + string? Read(); + void Write(string value); +} + +public sealed class UnavailableDisplayUnitPreferenceStore : IDisplayUnitPreferenceStore +{ + public string? Read() => + throw new InvalidOperationException("No platform display-preference store is registered."); + + public void Write(string value) => + throw new InvalidOperationException("No platform display-preference store is registered."); +} + +public sealed class DisplayUnitPreferenceService(IDisplayUnitPreferenceStore store) +{ + private bool _initialized; + + public DisplayUnitSelection Selection { get; private set; } = DisplayUnitSelection.Default; + public bool IsPersistedSelection { get; private set; } + public string? Error { get; private set; } + public bool IsInitialized => _initialized; + public event Action? Changed; + + public void Initialize() + { + if (_initialized) + { + return; + } + + _initialized = true; + try + { + var stored = store.Read(); + if (stored is null) + { + Selection = DisplayUnitSelection.Default; + IsPersistedSelection = false; + Error = null; + } + else if (TryParse(stored, out var selection)) + { + Selection = selection; + IsPersistedSelection = true; + Error = null; + } + else + { + Selection = DisplayUnitSelection.Default; + IsPersistedSelection = false; + Error = $"Saved display preference '{stored}' is invalid. Imperial (US) / Road is active as a default and has not been saved."; + } + } + catch (Exception exception) when (IsPreferenceStoreFailure(exception)) + { + Selection = DisplayUnitSelection.Default; + IsPersistedSelection = false; + Error = $"Could not load the saved display preference: {exception.Message} Imperial (US) / Road is active as a default and has not been saved."; + } + + Changed?.Invoke(); + } + + public bool TrySet(DisplayUnitSelection proposed) + { + Initialize(); + if (!IsValid(proposed)) + { + Error = "The selected display unit system or speed mode is undefined; the active preference was not changed."; + Changed?.Invoke(); + return false; + } + + var serialized = Serialize(proposed); + try + { + store.Write(serialized); + } + catch (Exception exception) when (IsPreferenceStoreFailure(exception)) + { + Error = $"Could not save the display preference: {exception.Message} The previous selection remains active."; + Changed?.Invoke(); + return false; + } + + Selection = proposed; + IsPersistedSelection = true; + Error = null; + Changed?.Invoke(); + return true; + } + + public static bool IsValid(DisplayUnitSelection selection) => + Enum.IsDefined(selection.UnitSystem) && Enum.IsDefined(selection.SpeedMode); + + public static string Serialize(DisplayUnitSelection selection) + { + if (!IsValid(selection)) + { + throw new DisplayUnitConversionException("The display unit selection contains an undefined option."); + } + + var system = selection.UnitSystem switch + { + DisplayUnitSystem.Metric => "metric", + DisplayUnitSystem.ImperialUS => "imperial-us", + _ => throw new DisplayUnitConversionException("The display unit system is undefined.") + }; + var speed = selection.SpeedMode switch + { + SpeedDisplayMode.Road => "road", + SpeedDisplayMode.Engineering => "engineering", + _ => throw new DisplayUnitConversionException("The speed presentation mode is undefined.") + }; + return $"{system}|{speed}"; + } + + private static bool TryParse(string value, out DisplayUnitSelection selection) + { + selection = default; + var parts = value.Split('|'); + if (parts.Length != 2) + { + return false; + } + + var system = parts[0] switch + { + "metric" => DisplayUnitSystem.Metric, + "imperial-us" => DisplayUnitSystem.ImperialUS, + _ => (DisplayUnitSystem?)null + }; + var speed = parts[1] switch + { + "road" => SpeedDisplayMode.Road, + "engineering" => SpeedDisplayMode.Engineering, + _ => (SpeedDisplayMode?)null + }; + if (system is null || speed is null) + { + return false; + } + + selection = new DisplayUnitSelection(system.Value, speed.Value); + return true; + } + + private static bool IsPreferenceStoreFailure(Exception exception) => + exception is DisplayUnitPreferenceStoreException or + InvalidOperationException or + UnauthorizedAccessException or + IOException or + ArgumentException; +} + +public static class DisplayUnitConverter +{ + private const double FeetPerMeter = 1d / 0.3048d; + private const double PoundsPerKilogram = 1d / 0.45359237d; + private const double PoundForcePerNewton = 1d / 4.4482216152605d; + private const double MetersPerSecondPerMilePerHour = 3600d / 1609.344d; + + public static DisplayMeasurement Project( + double sourceValue, + string sourceUnit, + DisplayUnitSelection selection) + { + ArgumentNullException.ThrowIfNull(sourceUnit); + EnsureValidSelection(selection); + if (!double.IsFinite(sourceValue)) + { + return new DisplayMeasurement(null, sourceUnit, Error: "The source value is not finite."); + } + + var projection = GetProjection(sourceUnit, selection); + if (projection is null) + { + return new DisplayMeasurement(sourceValue, sourceUnit, + $"Unit '{sourceUnit}' is not in the supported display mapping; showing the exact source value and unit."); + } + + var value = projection.Value.Forward(sourceValue); + return double.IsFinite(value) + ? new DisplayMeasurement(value, projection.Value.Unit) + : new DisplayMeasurement(null, projection.Value.Unit, Error: "The display conversion produced a non-finite value."); + } + + public static (double Minimum, double Maximum, string Unit) ProjectBounds( + double sourceMinimum, + double sourceMaximum, + string sourceUnit, + DisplayUnitSelection selection) + { + ValidateBounds(sourceMinimum, sourceMaximum); + var minimum = Project(sourceMinimum, sourceUnit, selection); + var maximum = Project(sourceMaximum, sourceUnit, selection); + if (!minimum.IsAvailable || !maximum.IsAvailable) + { + throw new DisplayUnitConversionException(minimum.Error ?? maximum.Error ?? "Could not convert gauge bounds."); + } + + var displayMinimum = minimum.Value!.Value; + var displayMaximum = maximum.Value!.Value; + ValidateBounds(displayMinimum, displayMaximum); + return (displayMinimum, displayMaximum, minimum.Unit); + } + + public static (double Minimum, double Maximum) ConvertBoundsToSource( + double displayMinimum, + double displayMaximum, + string sourceUnit, + DisplayUnitSelection selection) + { + ValidateBounds(displayMinimum, displayMaximum); + ArgumentNullException.ThrowIfNull(sourceUnit); + EnsureValidSelection(selection); + var sourceMinimum = ConvertToSource(displayMinimum, sourceUnit, selection); + var sourceMaximum = ConvertToSource(displayMaximum, sourceUnit, selection); + ValidateBounds(sourceMinimum, sourceMaximum); + return (sourceMinimum, sourceMaximum); + } + + public static double ConvertToSource( + double displayValue, + string sourceUnit, + DisplayUnitSelection selection) + { + ArgumentNullException.ThrowIfNull(sourceUnit); + EnsureValidSelection(selection); + if (!double.IsFinite(displayValue)) + { + throw new DisplayUnitConversionException("The display value must be finite."); + } + + var projection = GetProjection(sourceUnit, selection); + if (projection is null) + { + return displayValue; + } + + var sourceValue = projection.Value.Inverse(displayValue); + if (!double.IsFinite(sourceValue)) + { + throw new DisplayUnitConversionException("The source conversion produced a non-finite value."); + } + + return sourceValue; + } + + public static string Format(DisplayMeasurement measurement, int precision) + { + if (!measurement.IsAvailable) + { + return "--"; + } + + if (precision is < 0 or > 15) + { + throw new ArgumentOutOfRangeException(nameof(precision)); + } + + return measurement.Value!.Value.ToString($"F{precision}", CultureInfo.InvariantCulture); + } + + private static (string Unit, Func Forward, Func Inverse)? GetProjection( + string unit, + DisplayUnitSelection selection) + { + if (unit == "m/s") + { + return (selection.UnitSystem, selection.SpeedMode) switch + { + (DisplayUnitSystem.Metric, SpeedDisplayMode.Road) => + ("km/h", value => value * 3.6d, value => value / 3.6d), + (DisplayUnitSystem.Metric, SpeedDisplayMode.Engineering) => Identity(unit), + (DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road) => + ("mph", value => value * MetersPerSecondPerMilePerHour, value => value / MetersPerSecondPerMilePerHour), + (DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Engineering) => + ("ft/s", value => value * FeetPerMeter, value => value / FeetPerMeter), + _ => null + }; + } + + if (unit is "rpm" or "V" or "ratio" or "count" or "gear" or "boolean") + { + return Identity(unit); + } + + if (selection.UnitSystem == DisplayUnitSystem.Metric) + { + return unit is "m" or "kg" or "kg/s" or "N*m" or "degC" or "m/s^2" + ? Identity(unit) + : null; + } + + return unit switch + { + "m" => ("ft", value => value * FeetPerMeter, value => value / FeetPerMeter), + "kg" => ("lb", value => value * PoundsPerKilogram, value => value / PoundsPerKilogram), + "kg/s" => ("lb/h", value => value * PoundsPerKilogram * 3600d, value => value / (PoundsPerKilogram * 3600d)), + "N*m" => ("lbf*ft", value => value * PoundForcePerNewton * FeetPerMeter, + value => value / (PoundForcePerNewton * FeetPerMeter)), + "degC" => ("degF", value => value * 9d / 5d + 32d, value => (value - 32d) * 5d / 9d), + "m/s^2" => ("ft/s^2", value => value * FeetPerMeter, value => value / FeetPerMeter), + _ => null + }; + } + + private static (string Unit, Func Forward, Func Inverse) Identity(string unit) => + (unit, value => value, value => value); + + private static void ValidateBounds(double minimum, double maximum) + { + if (!double.IsFinite(minimum) || + !double.IsFinite(maximum) || + !double.IsFinite(maximum - minimum) || + maximum <= minimum) + { + throw new DisplayUnitConversionException("Display bounds must be finite and have a positive finite span."); + } + } + + private static void EnsureValidSelection(DisplayUnitSelection selection) + { + if (!DisplayUnitPreferenceService.IsValid(selection)) + { + throw new DisplayUnitConversionException("The display unit selection contains an undefined option."); + } + } + +} + +public static class DisplayUnitServiceCollectionExtensions +{ + public static IServiceCollection AddAutoForgeDisplayUnits(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddSingleton(); + services.TryAddSingleton(); + return services; + } +} diff --git a/src/AutoForge.Client/DisplayUnits/MauiDisplayUnitPreferenceStore.cs b/src/AutoForge.Client/DisplayUnits/MauiDisplayUnitPreferenceStore.cs new file mode 100644 index 0000000..30ede83 --- /dev/null +++ b/src/AutoForge.Client/DisplayUnits/MauiDisplayUnitPreferenceStore.cs @@ -0,0 +1,45 @@ +using AutoForge.Application.Features.DisplayUnits; +using System.IO; +using Microsoft.Maui.Storage; + +namespace AutoForge.Client.DisplayUnits; + +public sealed class MauiDisplayUnitPreferenceStore : IDisplayUnitPreferenceStore +{ + private const string PreferenceKey = "autoforge.display-units.v1"; + + public string? Read() + { + try + { + return Preferences.Default.Get(PreferenceKey, null); + } + catch (Exception exception) when (IsPreferenceFailure(exception)) + { + throw new DisplayUnitPreferenceStoreException( + "The platform preference could not be read.", + exception); + } + } + + public void Write(string value) + { + ArgumentNullException.ThrowIfNull(value); + try + { + Preferences.Default.Set(PreferenceKey, value); + } + catch (Exception exception) when (IsPreferenceFailure(exception)) + { + throw new DisplayUnitPreferenceStoreException( + "The platform preference could not be saved.", + exception); + } + } + + private static bool IsPreferenceFailure(Exception exception) => + exception is InvalidOperationException or + UnauthorizedAccessException or + IOException or + ArgumentException; +} diff --git a/src/AutoForge.Client/MauiProgram.cs b/src/AutoForge.Client/MauiProgram.cs index 6fe5e7a..32b1631 100644 --- a/src/AutoForge.Client/MauiProgram.cs +++ b/src/AutoForge.Client/MauiProgram.cs @@ -3,6 +3,8 @@ using AutoForge.Diagnostics; using AutoForge.Application.Features.Vehicles.Profiles; using AutoForge.Application.Features.Vehicles.Simulation; using AutoForge.Application.Features.Vehicles.Diagnostics; +using AutoForge.Application.Features.DisplayUnits; +using AutoForge.Client.DisplayUnits; using AutoForge.Simulation; using AutoForge.UI; @@ -24,6 +26,7 @@ public static class MauiProgram new DynamicsDiagnosticTransportFactory(SyntheticDiagnosticExamples.CreateDefinitions()) ]); builder.Services.AddAutoForgeDynamicsConfigurations(); + builder.Services.AddSingleton(); builder.Services.AddAutoForgeUi(); builder.Services.AddMauiBlazorWebView(); diff --git a/src/AutoForge.UI/Features/DisplayUnits/DisplayUnitPresentation.cs b/src/AutoForge.UI/Features/DisplayUnits/DisplayUnitPresentation.cs new file mode 100644 index 0000000..911797f --- /dev/null +++ b/src/AutoForge.UI/Features/DisplayUnits/DisplayUnitPresentation.cs @@ -0,0 +1,53 @@ +using System.Text.Json; +using AutoForge.Application.Features.DisplayUnits; + +namespace AutoForge.UI.Features.DisplayUnits; + +public sealed record DisplayUnitText(string Value, string Unit, string? Notice = null, string? Error = null); + +public static class DisplayUnitPresentation +{ + public static DisplayUnitText Project( + JsonElement sourceValue, + string sourceUnit, + DisplayUnitSelection selection, + int precision = 3) + { + if (sourceValue.ValueKind != JsonValueKind.Number) + { + return new DisplayUnitText(sourceValue.ToString(), sourceUnit); + } + + if (!sourceValue.TryGetDouble(out var number)) + { + return new DisplayUnitText("--", sourceUnit, Error: "The numeric source value is unavailable."); + } + + var measurement = DisplayUnitConverter.Project(number, sourceUnit, selection); + return new DisplayUnitText( + DisplayUnitConverter.Format(measurement, precision), + measurement.Unit, + measurement.Notice, + measurement.Error); + } + + public static DisplayUnitText Project( + double? sourceValue, + string sourceText, + string sourceUnit, + DisplayUnitSelection selection, + int precision = 3) + { + if (sourceValue is not { } numericValue) + { + return new DisplayUnitText(sourceText, sourceUnit); + } + + var measurement = DisplayUnitConverter.Project(numericValue, sourceUnit, selection); + return new DisplayUnitText( + DisplayUnitConverter.Format(measurement, precision), + measurement.Unit, + measurement.Notice, + measurement.Error); + } +} diff --git a/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs b/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs index ac97076..a9ba924 100644 --- a/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs +++ b/src/AutoForge.UI/Features/Foundation/AddAutoForgeUi.cs @@ -4,6 +4,7 @@ using AutoForge.UI.Features.Vehicles.Profiles; using AutoForge.UI.Features.Vehicles.Simulation; using AutoForge.Application.Features.Vehicles.Simulation; using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard; +using AutoForge.Application.Features.DisplayUnits; using Microsoft.Extensions.DependencyInjection; namespace AutoForge.UI; @@ -16,6 +17,7 @@ public static class ServiceCollectionExtensions services.AddAutoForgeDynamicsConfigurations(); services.AddAutoForgeLiveDashboard(); + services.AddAutoForgeDisplayUnits(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticsPage.razor b/src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticsPage.razor index 5353f37..251f4b0 100644 --- a/src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticsPage.razor +++ b/src/AutoForge.UI/Features/Vehicles/Diagnostics/DiagnosticsPage.razor @@ -218,10 +218,21 @@
    @foreach (var signal in signals.Signals) { + var display = DisplayUnitPresentation.Project(signal.Value, signal.Unit, DisplaySelection);
  • - @signal.SignalIdentifier: @signal.Value (@signal.Unit), @signal.Quality, + @signal.SignalIdentifier: + Display @display.Value @display.Unit (@signal.Quality); + source @signal.Value @signal.Unit, logical tick @signal.LogicalTimeTicks, origin @signal.Origin, source @signal.ModuleIdentifier. + @if (display.Notice is not null) + { + @display.Notice + } + @if (display.Error is not null) + { + @display.Error + }
  • }
@@ -255,6 +266,7 @@ }
Raw synthetic protocol v1 payloads +

These exact source payloads are not changed by the display preference.

Request: @System.Text.Encoding.UTF8.GetString(entry.RequestPayload.Span)
@if (entry.ResponsePayload is { } response) { @@ -270,3 +282,8 @@ } + + @code { + [CascadingParameter] + public DisplayUnitSelection DisplaySelection { get; set; } = DisplayUnitSelection.Default; + } diff --git a/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPage.razor b/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPage.razor index 1aa3d83..020d359 100644 --- a/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPage.razor +++ b/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPage.razor @@ -62,12 +62,26 @@
    @foreach (var phase in selectedConfiguration.Scenario) { + var targetDisplay = DisplayUnitConverter.Project( + phase.TargetSpeedMetersPerSecond, + "m/s", + DisplaySelection);
  1. - @phase.Kind — target @phase.TargetSpeedMetersPerSecond.ToString("F4", System.Globalization.CultureInfo.InvariantCulture) m/s; + @phase.Kind — target @DisplayUnitConverter.Format(targetDisplay, 2) @targetDisplay.Unit + (source @phase.TargetSpeedMetersPerSecond.ToString("F4", System.Globalization.CultureInfo.InvariantCulture) m/s); phase limit/hold @phase.DurationSeconds.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) s + @if (targetDisplay.Notice is not null) + { + @targetDisplay.Notice + } + @if (targetDisplay.Error is not null) + { + @targetDisplay.Error + }
  2. }
+

Scenario targets and exported configuration remain canonical SI source data; display conversion does not change the model inputs or fingerprint.

} +

Imported and exported configuration JSON remains exact canonical SI source data, unaffected by display units.

@if (Simulation.ActiveSession is { } session && session.DynamicsControl is { } control) @@ -146,8 +161,10 @@ Source module Signal - Value - Unit + Display value + Display unit + Source value + Source unit Quality Origin Model step/time @@ -157,9 +174,26 @@ @foreach (var row in Simulation.Telemetry) { + var display = DisplayUnitPresentation.Project( + row.NumericValue, + row.Value, + row.Unit, + DisplaySelection); @row.ModuleIdentifier @row.SignalIdentifier + @display.Value + + @display.Unit + @if (display.Notice is not null) + { + @display.Notice + } + @if (display.Error is not null) + { + @display.Error + } + @row.Value @row.Unit @row.Quality @@ -171,9 +205,15 @@ } +

Source-value columns preserve exact protocol-v2 readings; displayed values are presentation only.

}

The model is deliberately synthetic and does not provide manufacturer-validated performance, safe tuning guidance, or physical operations.

+ +@code { + [CascadingParameter] + public DisplayUnitSelection DisplaySelection { get; set; } = DisplayUnitSelection.Default; +} diff --git a/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs b/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs index 7b1ea32..882b309 100644 --- a/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs +++ b/src/AutoForge.UI/Features/Vehicles/Simulation/SimulationPageViewModel.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Text.Json; using AutoForge.Application.ExecutionTargets; using AutoForge.Application.Features.Vehicles.Diagnostics; using AutoForge.Application.Features.Vehicles.Profiles; @@ -21,7 +22,8 @@ public sealed record DynamicsTelemetryRow( long StepIndex, double ModelTimeSeconds, string ConfigurationIdentifier, - string RunIdentifier); + string RunIdentifier, + double? NumericValue); public sealed class SimulationPageViewModel( IVehicleProfileService profiles, @@ -347,7 +349,12 @@ public sealed class SimulationPageViewModel( step, modelTime, configurationIdentifier, - runIdentifier))); + runIdentifier, + signal.Value.ValueKind == JsonValueKind.Number && + signal.Value.TryGetDouble(out var number) && + double.IsFinite(number) + ? number + : null))); } if (!IsCurrent(session, generation)) diff --git a/src/AutoForge.UI/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardPanel.razor b/src/AutoForge.UI/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardPanel.razor index f1ead9e..a1a33a1 100644 --- a/src/AutoForge.UI/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardPanel.razor +++ b/src/AutoForge.UI/Features/Vehicles/Telemetry/LiveDashboard/LiveDashboardPanel.razor @@ -87,10 +87,10 @@ } - - + + - + @@ -99,6 +99,10 @@ { } + else if (_draftSelection is not null) + { + + } @if (_error is not null) { @@ -107,6 +111,18 @@ {

Start monitoring to acquire identity-verified signal choices from this session.

} + else if (_draftSelection is { } draftSelection) + { +

+ Range input is pinned to @draftSelection.UnitSystem / @draftSelection.SpeedMode; + values stay in @DraftUnit even if the global display preference changes. + Saved gauge bounds remain in source units. +

+ @if (DraftUnitNotice is { } notice) + { +

@notice

+ } + } } @@ -120,22 +136,34 @@ @foreach (var gauge in feed.Snapshot.Values) { var rangeState = gauge.RangeState; + var display = ProjectGauge(gauge); + var hasDisplayValue = gauge.NumericValue is not null && display.IsAvailable;
+ StateDescription="@DisplayStateDescription(gauge.State, display.Error)" + RangeDescription="@(rangeState is null ? null : RangeDescription(rangeState.Value, gauge.Definition, DisplaySelection))" + Reason="@JoinReason(gauge.Reason, display.Error ?? display.Notice)" + Percent="@(hasDisplayValue ? gauge.BarPercent : null)" /> + @if (display.Error is not null) + { + + } @if (gauge.Signal is { } signal) {
Module / signal
@signal.ModuleIdentifier / @signal.SignalIdentifier
+
Exact source value / unit
+
@signal.Value @signal.Unit
+
Display range
+
@DisplayBounds(gauge.Definition, DisplaySelection)
Origin and diagnostic request time
@signal.Origin; logical tick @signal.LogicalTimeTicks
@if (signal.ModelStepIndex is { } modelStep && signal.ModelTimeSeconds is { } modelTime) @@ -175,6 +203,9 @@ [Parameter] public string HeadingId { get; set; } = "live-dashboard-heading"; + [CascadingParameter] + public DisplayUnitSelection DisplaySelection { get; set; } = DisplayUnitSelection.Default; + private LiveDashboardFeed? _feed; private DiagnosticSession? _boundSession; private bool _disposed; @@ -191,6 +222,18 @@ private string _maximum = "1000"; private string _precision = "0"; private string? _editingGaugeId; + private DashboardGaugeDefinition? _editingOriginalDefinition; + private string? _originalDisplayMinimum; + private string? _originalDisplayMaximum; + private DisplayUnitSelection? _draftSelection; + + private string DraftUnit => _moduleIdentifier is not null && _signalIdentifier is not null + ? DisplayUnitConverter.Project(0, _unit, _draftSelection ?? DisplaySelection).Unit + : _unit; + + private string? DraftUnitNotice => _moduleIdentifier is not null && _signalIdentifier is not null + ? DisplayUnitConverter.Project(0, _unit, _draftSelection ?? DisplaySelection).Notice + : null; private IReadOnlyList AvailableBindings => _feed?.Snapshot.AvailableSignals @@ -292,7 +335,13 @@ StringComparer.Ordinal.Equals(item.SignalIdentifier, _signalIdentifier)); if (binding is not null) { + _editingOriginalDefinition = null; + _draftSelection = DisplaySelection; _unit = binding.Unit; + _minimum = "0"; + _maximum = "1000"; + _originalDisplayMinimum = null; + _originalDisplayMaximum = null; } } @@ -313,10 +362,52 @@ } var proposed = _feed.Snapshot.Definitions.ToList(); + var sourceMinimum = minimum; + var sourceMaximum = maximum; if (_editingGaugeId is not null) { + if (_editingOriginalDefinition is { } original && + StringComparer.Ordinal.Equals(_minimum, _originalDisplayMinimum) && + StringComparer.Ordinal.Equals(_maximum, _originalDisplayMaximum)) + { + sourceMinimum = original.Minimum; + sourceMaximum = original.Maximum; + } + else + { + try + { + (sourceMinimum, sourceMaximum) = DisplayUnitConverter.ConvertBoundsToSource( + minimum, + maximum, + _unit, + _draftSelection ?? DisplaySelection); + } + catch (DisplayUnitConversionException exception) + { + _error = exception.Message; + return; + } + } + proposed.RemoveAll(item => StringComparer.OrdinalIgnoreCase.Equals(item.GaugeIdentifier, _editingGaugeId)); } + else + { + try + { + (sourceMinimum, sourceMaximum) = DisplayUnitConverter.ConvertBoundsToSource( + minimum, + maximum, + _unit, + _draftSelection ?? DisplaySelection); + } + catch (DisplayUnitConversionException exception) + { + _error = exception.Message; + return; + } + } proposed.Add(new DashboardGaugeDefinition( _gaugeId, @@ -325,8 +416,8 @@ _moduleIdentifier ?? string.Empty, _signalIdentifier ?? string.Empty, _unit, - minimum, - maximum, + sourceMinimum, + sourceMaximum, precision)); try @@ -343,15 +434,35 @@ private void EditGauge(DashboardGaugeDefinition definition) { + var draftSelection = DisplaySelection; + (double Minimum, double Maximum, string Unit) bounds; + try + { + bounds = DisplayUnitConverter.ProjectBounds( + definition.Minimum, + definition.Maximum, + definition.Unit, + draftSelection); + } + catch (DisplayUnitConversionException exception) + { + _error = exception.Message; + return; + } + _editingGaugeId = definition.GaugeIdentifier; + _editingOriginalDefinition = definition; + _draftSelection = draftSelection; _gaugeId = definition.GaugeIdentifier; _label = definition.Label; _kind = definition.Kind; _moduleIdentifier = definition.ModuleIdentifier; _signalIdentifier = definition.SignalIdentifier; _unit = definition.Unit; - _minimum = definition.Minimum.ToString("R", CultureInfo.InvariantCulture); - _maximum = definition.Maximum.ToString("R", CultureInfo.InvariantCulture); + _minimum = bounds.Minimum.ToString("R", CultureInfo.InvariantCulture); + _maximum = bounds.Maximum.ToString("R", CultureInfo.InvariantCulture); + _originalDisplayMinimum = _minimum; + _originalDisplayMaximum = _maximum; _precision = definition.DecimalPrecision.ToString(CultureInfo.InvariantCulture); _showEditor = true; _error = null; @@ -391,6 +502,10 @@ private void ResetEditor() { _editingGaugeId = null; + _editingOriginalDefinition = null; + _originalDisplayMinimum = null; + _originalDisplayMaximum = null; + _draftSelection = null; _gaugeId = string.Empty; _label = string.Empty; _kind = DashboardGaugeKind.Numeric; @@ -415,12 +530,62 @@ _ => state.ToString() }; - private static string RangeDescription(DashboardReadingState state) => state switch + private static string DisplayStateDescription(DashboardReadingState state, string? displayError) => + displayError is null + ? StateDescription(state) + : $"{StateDescription(state)}; display conversion unavailable"; + + private static string RangeDescription( + DashboardReadingState state, + DashboardGaugeDefinition definition, + DisplayUnitSelection selection) { - DashboardReadingState.OutOfRangeLow => "Below configured range", - DashboardReadingState.OutOfRangeHigh => "Above configured range", - _ => state.ToString() - }; + try + { + var bounds = DisplayUnitConverter.ProjectBounds( + definition.Minimum, + definition.Maximum, + definition.Unit, + selection); + var position = state switch + { + DashboardReadingState.OutOfRangeLow => "Below", + DashboardReadingState.OutOfRangeHigh => "Above", + _ => state.ToString() + }; + return $"{position} configured range {bounds.Minimum.ToString("G", CultureInfo.InvariantCulture)}–{bounds.Maximum.ToString("G", CultureInfo.InvariantCulture)} {bounds.Unit}"; + } + catch (DisplayUnitConversionException) + { + return $"{state} range; display conversion unavailable."; + } + } + + private static string DisplayBounds(DashboardGaugeDefinition definition, DisplayUnitSelection selection) + { + try + { + var bounds = DisplayUnitConverter.ProjectBounds( + definition.Minimum, + definition.Maximum, + definition.Unit, + selection); + return $"{bounds.Minimum.ToString("G", CultureInfo.InvariantCulture)}–{bounds.Maximum.ToString("G", CultureInfo.InvariantCulture)} {bounds.Unit} (source {definition.Minimum.ToString("G", CultureInfo.InvariantCulture)}–{definition.Maximum.ToString("G", CultureInfo.InvariantCulture)} {definition.Unit})"; + } + catch (DisplayUnitConversionException exception) + { + return $"Display bounds unavailable: {exception.Message} Source range {definition.Minimum.ToString("G", CultureInfo.InvariantCulture)}–{definition.Maximum.ToString("G", CultureInfo.InvariantCulture)} {definition.Unit}."; + } + } + + private DisplayMeasurement ProjectGauge(DashboardGaugeValue gauge) => + gauge.NumericValue is { } value + ? DisplayUnitConverter.Project(value, gauge.Definition.Unit, DisplaySelection) + : DisplayUnitConverter.Project(0, gauge.Definition.Unit, DisplaySelection) with { Value = null }; + + private static string JoinReason(string? reason, string? additional) => + string.IsNullOrWhiteSpace(additional) ? reason ?? string.Empty : + string.IsNullOrWhiteSpace(reason) ? additional : $"{reason} {additional}"; public void Dispose() { diff --git a/src/AutoForge.UI/Layout/MainLayout.razor b/src/AutoForge.UI/Layout/MainLayout.razor index 5fc2f52..a8badf5 100644 --- a/src/AutoForge.UI/Layout/MainLayout.razor +++ b/src/AutoForge.UI/Layout/MainLayout.razor @@ -1,4 +1,6 @@ @inherits LayoutComponentBase +@implements IDisposable +@inject AutoForge.Application.Features.DisplayUnits.DisplayUnitPreferenceService DisplayUnits
- @Body + + @Body +
Target selection is metadata only; it does not connect to a vehicle or authorize an operation.
+ +@code { + private bool _disposed; + + protected override void OnInitialized() + { + DisplayUnits.Changed += OnDisplayUnitsChanged; + DisplayUnits.Initialize(); + } + + private void OnUnitSystemChanged(ChangeEventArgs args) + { + if (Enum.TryParse( + args.Value?.ToString(), + out var unitSystem) && + Enum.IsDefined(unitSystem)) + { + DisplayUnits.TrySet(DisplayUnits.Selection with { UnitSystem = unitSystem }); + } + } + + private void OnSpeedModeChanged(ChangeEventArgs args) + { + if (Enum.TryParse( + args.Value?.ToString(), + out var speedMode) && + Enum.IsDefined(speedMode)) + { + DisplayUnits.TrySet(DisplayUnits.Selection with { SpeedMode = speedMode }); + } + } + + private void OnDisplayUnitsChanged() => _ = InvokeAsync(() => + { + if (!_disposed) + { + StateHasChanged(); + } + }); + + public void Dispose() + { + _disposed = true; + DisplayUnits.Changed -= OnDisplayUnitsChanged; + } +} diff --git a/src/AutoForge.UI/_Imports.razor b/src/AutoForge.UI/_Imports.razor index 2804c72..23b1bec 100644 --- a/src/AutoForge.UI/_Imports.razor +++ b/src/AutoForge.UI/_Imports.razor @@ -5,6 +5,7 @@ @using AutoForge.Components @using AutoForge.Application.Features.Vehicles.Diagnostics @using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard +@using AutoForge.Application.Features.DisplayUnits @using AutoForge.UI.Features.Vehicles.Telemetry.LiveDashboard @using AutoForge.Core.ExecutionTargets @using AutoForge.Diagnostics @@ -13,3 +14,4 @@ @using AutoForge.UI.Features.Vehicles.Diagnostics @using AutoForge.UI.Features.Vehicles.Profiles @using AutoForge.UI.Features.Vehicles.Simulation +@using AutoForge.UI.Features.DisplayUnits diff --git a/src/tests/AutoForge.IntegrationTests/DiagnosticUiCompositionTests.cs b/src/tests/AutoForge.IntegrationTests/DiagnosticUiCompositionTests.cs index eed8651..153e851 100644 --- a/src/tests/AutoForge.IntegrationTests/DiagnosticUiCompositionTests.cs +++ b/src/tests/AutoForge.IntegrationTests/DiagnosticUiCompositionTests.cs @@ -321,6 +321,7 @@ public sealed class DiagnosticUiCompositionTests services.AddAutoForgeDiagnostics([factory ?? new SimulatedDiagnosticTransportFactory( SyntheticDiagnosticExamples.CreateDefinitions())]); services.AddAutoForgeUi(); + services.AddSingleton(); services.AddSingleton(new TestNavigationManager(uri)); services.AddSingleton(); services.AddSingleton(); diff --git a/src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs b/src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs index 4216fcc..36ac0fa 100644 --- a/src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs +++ b/src/tests/AutoForge.IntegrationTests/DynamicsWorkflowTests.cs @@ -5,12 +5,16 @@ using AutoForge.Components; using AutoForge.Application.Features.Vehicles.Diagnostics; using AutoForge.Application.Features.Vehicles.Profiles; using AutoForge.Application.Features.Vehicles.Simulation; +using AutoForge.Application.Features.DisplayUnits; +using AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard; using AutoForge.Core.ExecutionTargets; using AutoForge.Core.Simulation; using AutoForge.Diagnostics; using AutoForge.Simulation; using AutoForge.UI; using AutoForge.UI.Features.Vehicles.Simulation; +using AutoForge.UI.Features.Vehicles.Telemetry.LiveDashboard; +using AutoForge.UI.Layout; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Routing; using Microsoft.AspNetCore.Components.Web; @@ -21,6 +25,136 @@ namespace AutoForge.IntegrationTests; public sealed class DynamicsWorkflowTests { + [Fact] + public async Task DisplayUnitTogglesOnPausedDynamicsFeedRerenderWithoutSourceOrModelMutation() + { + using var provider = CreateProvider(dashboardScheduler: new NoPollDashboardScheduler()); + provider.GetRequiredService().Import(ReadFixture("synthetic-truck-baseline.json")); + var configurations = provider.GetRequiredService(); + var configuration = configurations.CreateExample("autoforge.synthetic.test-truck", 1); + var page = provider.GetRequiredService(); + page.SelectedProfileIdentifier = configuration.ProfileIdentifier; + page.SelectedProfileRevision = configuration.ProfileRevision; + page.SelectedProviderIdentifier = DynamicsDiagnosticTransportFactory.ProviderIdentifier; + page.SelectedConfigurationIdentifier = configuration.ConfigurationIdentifier; + + await page.OpenSessionAsync(); + var session = Assert.IsType(page.ActiveSession); + try + { + await page.StartAsync(); + await page.PauseAsync(); + page.StepCountInput = 100; + await page.StepAsync(); + Assert.Equal(DynamicsLifecycleState.Paused, session.DynamicsControl!.Status.State); + + var feed = provider.GetRequiredService().Create(session); + await feed.StartAsync(); + var speed = Assert.Single(feed.Snapshot.AvailableSignals, signal => + signal.ModuleIdentifier == "module.engine.primary" && + signal.SignalIdentifier == "vehicle.speed" && + signal.Unit == "m/s"); + feed.ReplaceDefinitions( + [ + new DashboardGaugeDefinition( + "display-speed", + "Vehicle speed", + DashboardGaugeKind.HorizontalBar, + speed.ModuleIdentifier, + speed.SignalIdentifier, + speed.Unit, + 0, + 40.2336, + 2) + ]); + + var sourceValues = feed.Snapshot.Values + .Select(value => (value.Definition, value.NumericValue, value.State, value.RangeState, value.BarPercent, value.Signal)) + .ToArray(); + var definitions = feed.Snapshot.Definitions.ToArray(); + var sourceContext = feed.Snapshot.Source; + var runStatus = session.DynamicsControl.Status; + var traceEntries = session.Trace.Entries.ToArray(); + var tracePayloads = traceEntries + .Select(entry => (Request: entry.RequestPayload.ToArray(), Response: entry.ResponsePayload?.ToArray())) + .ToArray(); + var readCount = CountSignalReads(session); + var exportedConfiguration = configurations.Export(configuration.ConfigurationIdentifier); + var preference = provider.GetRequiredService(); + + await using var renderer = new HtmlRenderer(provider, provider.GetRequiredService()); + var body = (RenderFragment)(builder => + { + builder.OpenComponent(0); + builder.AddAttribute(1, nameof(LiveDashboardPanel.Session), session); + builder.AddAttribute(2, nameof(LiveDashboardPanel.HeadingId), "display-unit-dashboard"); + builder.CloseComponent(); + }); + var layout = await renderer.Dispatcher.InvokeAsync(() => + renderer.RenderComponentAsync( + ParameterView.FromDictionary(new Dictionary + { + [nameof(MainLayout.Body)] = body + }))); + + Assert.Contains("ImperialUS / Road", await renderer.Dispatcher.InvokeAsync(layout.ToHtmlString)); + Assert.Contains("mph", await renderer.Dispatcher.InvokeAsync(layout.ToHtmlString)); + var percentBefore = Assert.Single(feed.Snapshot.Values).BarPercent; + var modes = new[] + { + new DisplayUnitSelection(DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Engineering), + new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Engineering), + new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Road), + DisplayUnitSelection.Default + }; + + for (var index = 0; index < 20; index++) + { + var selection = modes[index % modes.Length]; + await renderer.Dispatcher.InvokeAsync(() => Assert.True(preference.TrySet(selection))); + var html = await renderer.Dispatcher.InvokeAsync(layout.ToHtmlString); + var value = Assert.Single(feed.Snapshot.Values); + var projected = DisplayUnitConverter.Project(value.NumericValue!.Value, "m/s", selection); + + Assert.Contains(DisplayUnitConverter.Format(projected, 2) + " " + projected.Unit, html); + Assert.Contains("aria-valuenow=\"" + percentBefore!.Value.ToString(System.Globalization.CultureInfo.InvariantCulture) + "\"", html); + Assert.Equal(readCount, CountSignalReads(session)); + Assert.Equal(runStatus, session.DynamicsControl.Status); + Assert.Equal(exportedConfiguration, configurations.Export(configuration.ConfigurationIdentifier)); + Assert.Equal(definitions, feed.Snapshot.Definitions); + Assert.Equal(sourceContext, feed.Snapshot.Source); + Assert.Equal(sourceValues, feed.Snapshot.Values + .Select(item => (item.Definition, item.NumericValue, item.State, item.RangeState, item.BarPercent, item.Signal)) + .ToArray()); + Assert.Equal(traceEntries, session.Trace.Entries); + Assert.Equal(tracePayloads.Length, session.Trace.Entries.Count); + for (var traceIndex = 0; traceIndex < tracePayloads.Length; traceIndex++) + { + var responsePayload = session.Trace.Entries[traceIndex].ResponsePayload; + if (tracePayloads[traceIndex].Response is { } expectedResponse) + { + Assert.Equal(expectedResponse, responsePayload!.Value.ToArray()); + } + else + { + Assert.Null(responsePayload); + } + + Assert.Equal(tracePayloads[traceIndex].Request, session.Trace.Entries[traceIndex].RequestPayload.ToArray()); + } + } + + await feed.StopAsync(); + } + finally + { + if (page.ActiveSession is not null) + { + await page.CloseSessionAsync(); + } + } + } + [Fact] public async Task RealApplicationAndRenderedRoute_RunAndReadDynamicTelemetryWithoutOracle() { @@ -76,10 +210,20 @@ public sealed class DynamicsWorkflowTests Assert.Equal(0, reset.DynamicsControl!.Status.StepIndex); await page.RefreshTelemetryAsync(); + var displayPreferences = provider.GetRequiredService(); + var configurationJson = configurations.Export(original.ConfigurationIdentifier); + var sourceTelemetry = page.Telemetry.ToArray(); + var sourceTrace = reset.Trace.Entries.ToArray(); + Assert.True(displayPreferences.TrySet( + new DisplayUnitSelection(DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road))); var html = await RenderRoutesAsync(provider); Assert.Contains("Deterministic synthetic vehicle simulation", html); Assert.Contains("dynamics-telemetry", html); Assert.Contains("SYNTHETIC_DYNAMIC", html); + Assert.Contains("mph", html); + Assert.Contains("degF", html); + Assert.Contains("degC", html); + Assert.Contains("kg/s", html); Assert.Contains("dynamics-run-status", html); Assert.Contains("WarmIdle (0.0%)", html); Assert.Contains("Model autoforge.synthetic.longitudinal v1;", html); @@ -87,6 +231,18 @@ public sealed class DynamicsWorkflowTests Assert.Contains("Session live dashboard", html); Assert.Contains("Start monitoring", html); + Assert.True(displayPreferences.TrySet( + new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Engineering))); + var metricHtml = await RenderRoutesAsync(provider); + Assert.Contains("vehicle.speed", metricHtml); + Assert.Contains("m/s", metricHtml); + Assert.Contains("degC", metricHtml); + Assert.Equal(sourceTelemetry, page.Telemetry); + Assert.Equal(sourceTrace, reset.Trace.Entries); + Assert.Equal(DynamicsLifecycleState.Stopped, reset.DynamicsControl.Status.State); + Assert.Equal(0, reset.DynamicsControl.Status.StepIndex); + Assert.Equal(configurationJson, configurations.Export(original.ConfigurationIdentifier)); + await page.CloseSessionAsync(); Assert.Null(page.ActiveSession); Assert.True(reset.IsClosed); @@ -418,7 +574,8 @@ public sealed class DynamicsWorkflowTests private static ServiceProvider CreateProvider( IDynamicsPacer? pacer = null, - BlockingDynamicsOpen? openGate = null) + BlockingDynamicsOpen? openGate = null, + ILiveDashboardPollScheduler? dashboardScheduler = null) { var services = new ServiceCollection(); services.AddLogging(); @@ -444,13 +601,28 @@ public sealed class DynamicsWorkflowTests } services.AddAutoForgeDynamicsConfigurations(); + if (dashboardScheduler is not null) + { + services.AddSingleton(dashboardScheduler); + } + services.AddAutoForgeUi(); + services.AddSingleton(); services.AddSingleton(new TestNavigationManager("http://localhost/simulation")); services.AddSingleton(); services.AddSingleton(); return services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true }); } + private static int CountSignalReads(DiagnosticSession session) => + session.Trace.Entries.Count(entry => entry.Service == DiagnosticServices.ReadSignals); + + private sealed class NoPollDashboardScheduler : ILiveDashboardPollScheduler + { + public Task WaitAsync(TimeSpan interval, CancellationToken cancellationToken) => + Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + } + private sealed record PendingDelay(TimeSpan Delay, TaskCompletionSource Completion) { public bool IsCancelled => Completion.Task.IsCanceled; diff --git a/src/tests/AutoForge.IntegrationTests/IsolatedDisplayUnitPreferenceStore.cs b/src/tests/AutoForge.IntegrationTests/IsolatedDisplayUnitPreferenceStore.cs new file mode 100644 index 0000000..4848864 --- /dev/null +++ b/src/tests/AutoForge.IntegrationTests/IsolatedDisplayUnitPreferenceStore.cs @@ -0,0 +1,12 @@ +using AutoForge.Application.Features.DisplayUnits; + +namespace AutoForge.IntegrationTests; + +internal sealed class IsolatedDisplayUnitPreferenceStore : IDisplayUnitPreferenceStore +{ + public string? Value { get; set; } + + public string? Read() => Value; + + public void Write(string value) => Value = value; +} diff --git a/src/tests/AutoForge.IntegrationTests/LiveDashboardAcquisitionTests.cs b/src/tests/AutoForge.IntegrationTests/LiveDashboardAcquisitionTests.cs index a5437c2..34157cd 100644 --- a/src/tests/AutoForge.IntegrationTests/LiveDashboardAcquisitionTests.cs +++ b/src/tests/AutoForge.IntegrationTests/LiveDashboardAcquisitionTests.cs @@ -766,6 +766,7 @@ public sealed class LiveDashboardAcquisitionTests ]); services.AddSingleton(scheduler); services.AddAutoForgeUi(); + services.AddSingleton(); return services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true }); } diff --git a/src/tests/AutoForge.IntegrationTests/UiCompositionTests.cs b/src/tests/AutoForge.IntegrationTests/UiCompositionTests.cs index 31e0f4b..75964db 100644 --- a/src/tests/AutoForge.IntegrationTests/UiCompositionTests.cs +++ b/src/tests/AutoForge.IntegrationTests/UiCompositionTests.cs @@ -149,6 +149,7 @@ public sealed class UiCompositionTests services.AddAutoForgeTargetSelection(registrations); services.AddAutoForgeVehicleProfiles(); services.AddAutoForgeUi(); + services.AddSingleton(); services.AddSingleton(new TestNavigationManager(uri)); services.AddSingleton(); services.AddSingleton(); @@ -164,6 +165,7 @@ public sealed class UiCompositionTests [new AutoForge.Simulation.SimulatedDiagnosticTransportFactory( AutoForge.Simulation.SyntheticDiagnosticExamples.CreateDefinitions())]); services.AddAutoForgeUi(); + services.AddSingleton(); services.AddSingleton(new TestNavigationManager(uri)); services.AddSingleton(); services.AddSingleton(); diff --git a/src/tests/AutoForge.IntegrationTests/VehicleProfileCompositionTests.cs b/src/tests/AutoForge.IntegrationTests/VehicleProfileCompositionTests.cs index fd69dff..e9856a9 100644 --- a/src/tests/AutoForge.IntegrationTests/VehicleProfileCompositionTests.cs +++ b/src/tests/AutoForge.IntegrationTests/VehicleProfileCompositionTests.cs @@ -356,6 +356,7 @@ public sealed class VehicleProfileCompositionTests services.AddAutoForgeVehicleProfiles(); services.AddAutoForgeUi(); + services.AddSingleton(); services.AddSingleton(new TestNavigationManager("http://localhost/vehicle-profiles")); services.AddSingleton(); services.AddSingleton(); diff --git a/src/tests/AutoForge.UnitTests/DisplayUnitSettingsTests.cs b/src/tests/AutoForge.UnitTests/DisplayUnitSettingsTests.cs new file mode 100644 index 0000000..50e1f51 --- /dev/null +++ b/src/tests/AutoForge.UnitTests/DisplayUnitSettingsTests.cs @@ -0,0 +1,291 @@ +using AutoForge.Application.Features.DisplayUnits; + +namespace AutoForge.UnitTests; + +public sealed class DisplayUnitSettingsTests +{ + [Theory] + [InlineData(20.1168, "m/s", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 45, "mph")] + [InlineData(20.1168, "m/s", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Engineering, 66, "ft/s")] + [InlineData(20.1168, "m/s", DisplayUnitSystem.Metric, SpeedDisplayMode.Road, 72.42048, "km/h")] + [InlineData(20.1168, "m/s", DisplayUnitSystem.Metric, SpeedDisplayMode.Engineering, 20.1168, "m/s")] + [InlineData(0.3048, "m", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 1, "ft")] + [InlineData(0.45359237, "kg", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 1, "lb")] + [InlineData(0.45359237 / 3600, "kg/s", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 1, "lb/h")] + [InlineData(1.3558179483314004, "N*m", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 1, "lbf*ft")] + [InlineData(0, "degC", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 32, "degF")] + [InlineData(100, "degC", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 212, "degF")] + [InlineData(-40, "degC", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, -40, "degF")] + [InlineData(0.3048, "m/s^2", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 1, "ft/s^2")] + public void Project_KnownMappingsMatchIndependentVectors( + double sourceValue, + string sourceUnit, + DisplayUnitSystem system, + SpeedDisplayMode speedMode, + double expectedValue, + string expectedUnit) + { + var result = DisplayUnitConverter.Project( + sourceValue, + sourceUnit, + new DisplayUnitSelection(system, speedMode)); + + Assert.True(result.IsAvailable); + Assert.Equal(expectedUnit, result.Unit); + Assert.InRange(Math.Abs(result.Value!.Value - expectedValue), 0, 1e-9); + } + + [Theory] + [InlineData("rpm")] + [InlineData("V")] + [InlineData("ratio")] + [InlineData("count")] + [InlineData("gear")] + [InlineData("boolean")] + public void Project_PreservesAssignedPassThroughUnits(string sourceUnit) + { + var result = DisplayUnitConverter.Project( + 12.5, + sourceUnit, + new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Engineering)); + + Assert.Equal(12.5, result.Value); + Assert.Equal(sourceUnit, result.Unit); + Assert.Null(result.Notice); + Assert.Null(result.Error); + } + + [Theory] + [InlineData(20.1168, "m/s", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 45)] + [InlineData(20.1168, "m/s", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Engineering, 66)] + [InlineData(20.1168, "m/s", DisplayUnitSystem.Metric, SpeedDisplayMode.Road, 72.42048)] + [InlineData(0.3048, "m", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 1)] + [InlineData(0.45359237, "kg", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 1)] + [InlineData(0.45359237 / 3600, "kg/s", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 1)] + [InlineData(1.3558179483314004, "N*m", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 1)] + [InlineData(0, "degC", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 32)] + [InlineData(100, "degC", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 212)] + [InlineData(-40, "degC", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, -40)] + [InlineData(0.3048, "m/s^2", DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road, 1)] + public void ConvertToSource_RoundTripsSupportedVectorsWithinTolerance( + double sourceValue, + string sourceUnit, + DisplayUnitSystem system, + SpeedDisplayMode speedMode, + double _) + { + var selection = new DisplayUnitSelection(system, speedMode); + var projected = DisplayUnitConverter.Project(sourceValue, sourceUnit, selection); + var inverse = DisplayUnitConverter.ConvertToSource(projected.Value!.Value, sourceUnit, selection); + + Assert.InRange(Math.Abs(inverse - sourceValue), 0, 1e-9); + } + + [Fact] + public void Project_PassesThroughKnownUnitsAndExplicitlyLabelsUnknownUnits() + { + var selection = DisplayUnitSelection.Default; + var known = DisplayUnitConverter.Project(900, "rpm", selection); + var unknown = DisplayUnitConverter.Project(12.5, "widgets", selection); + + Assert.Equal(900, known.Value); + Assert.Equal("rpm", known.Unit); + Assert.Null(known.Notice); + Assert.Equal(12.5, unknown.Value); + Assert.Equal("widgets", unknown.Unit); + Assert.Contains("not in the supported display mapping", unknown.Notice); + } + + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + [InlineData(double.MaxValue)] + public void Project_RejectsNonFiniteInputAndOverflowWithoutFabricatedValue(double value) + { + var projection = DisplayUnitConverter.Project( + value, + "m/s", + new DisplayUnitSelection(DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road)); + + Assert.False(projection.IsAvailable); + Assert.Null(projection.Value); + Assert.NotNull(projection.Error); + } + + [Fact] + public void Project_ConvertsBeforeDisplayRounding() + { + var measurement = DisplayUnitConverter.Project( + 0.4, + "m/s", + new DisplayUnitSelection(DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road)); + + Assert.InRange(Math.Abs(measurement.Value!.Value - 0.894774516821761), 0, 1e-9); + Assert.Equal("1", DisplayUnitConverter.Format(measurement, 0)); + } + + [Fact] + public void Bounds_ConvertOffsetsAndRoundTripWithoutRoundingCanonicalValues() + { + var selection = new DisplayUnitSelection(DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road); + var fahrenheit = DisplayUnitConverter.ProjectBounds(0, 100, "degC", selection); + var celsius = DisplayUnitConverter.ConvertBoundsToSource(32, 212, "degC", selection); + var speed = DisplayUnitConverter.ProjectBounds(0, 40.2336, "m/s", selection); + + Assert.Equal((32, 212, "degF"), fahrenheit); + Assert.Equal((0, 100), celsius); + Assert.Equal((0, 90, "mph"), speed); + var nonRounded = DisplayUnitConverter.ConvertToSource( + 45.123456789, + "m/s", + selection); + Assert.NotEqual(Math.Round(nonRounded, 0), nonRounded); + } + + [Fact] + public void SpeedBoundsAndValueProjectionPreserveCanonicalGeometry() + { + var sourceValue = 20.1168; + var sourceMinimum = 0d; + var sourceMaximum = 40.2336; + var sourcePercent = (sourceValue - sourceMinimum) / (sourceMaximum - sourceMinimum) * 100; + var selections = new[] + { + (new DisplayUnitSelection(DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Road), 45d, "mph", 0d, 90d), + (new DisplayUnitSelection(DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Engineering), 66d, "ft/s", 0d, 132d), + (new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Road), 72.42048d, "km/h", 0d, 144.84096d), + (new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Engineering), 20.1168d, "m/s", 0d, 40.2336d) + }; + + foreach (var (selection, expectedValue, expectedUnit, expectedMinimum, expectedMaximum) in selections) + { + var value = DisplayUnitConverter.Project(sourceValue, "m/s", selection); + var bounds = DisplayUnitConverter.ProjectBounds(sourceMinimum, sourceMaximum, "m/s", selection); + var displayPercent = (value.Value!.Value - bounds.Minimum) / (bounds.Maximum - bounds.Minimum) * 100; + + Assert.Equal(expectedUnit, value.Unit); + Assert.InRange(Math.Abs(value.Value.Value - expectedValue), 0, 1e-9); + Assert.InRange(Math.Abs(bounds.Minimum - expectedMinimum), 0, 1e-9); + Assert.InRange(Math.Abs(bounds.Maximum - expectedMaximum), 0, 1e-9); + Assert.Equal(sourcePercent, displayPercent, 12); + } + } + + [Fact] + public void UnknownBoundsRemainSourceUnitsAndInvalidSelectionRejects() + { + var selection = DisplayUnitSelection.Default; + var bounds = DisplayUnitConverter.ProjectBounds(2, 8, "widgets", selection); + + Assert.Equal((2, 8, "widgets"), bounds); + Assert.Throws(() => DisplayUnitConverter.Project( + 1, + "m/s", + new DisplayUnitSelection((DisplayUnitSystem)99, SpeedDisplayMode.Road))); + Assert.Throws(() => DisplayUnitConverter.ConvertBoundsToSource( + 0, + double.PositiveInfinity, + "m/s", + selection)); + } + + [Fact] + public void PreferenceService_UsesImperialRoadDefaultAndRestoresPersistedChoice() + { + var missing = new IsolatedPreferenceStore(); + var firstUse = new DisplayUnitPreferenceService(missing); + firstUse.Initialize(); + + Assert.Equal(DisplayUnitSelection.Default, firstUse.Selection); + Assert.False(firstUse.IsPersistedSelection); + Assert.Null(firstUse.Error); + Assert.True(firstUse.TrySet(new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Engineering))); + Assert.True(firstUse.IsPersistedSelection); + Assert.Equal("metric|engineering", missing.Value); + + var restored = new DisplayUnitPreferenceService(missing); + restored.Initialize(); + Assert.Equal(new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Engineering), restored.Selection); + Assert.True(restored.IsPersistedSelection); + Assert.Null(restored.Error); + } + + [Theory] + [InlineData("unknown|road")] + [InlineData("metric|unknown")] + [InlineData("not-a-preference")] + public void PreferenceService_CorruptStoredChoiceShowsDefaultAndDoesNotOverwrite(string stored) + { + var store = new IsolatedPreferenceStore { Value = stored }; + var service = new DisplayUnitPreferenceService(store); + service.Initialize(); + + Assert.Equal(DisplayUnitSelection.Default, service.Selection); + Assert.False(service.IsPersistedSelection); + Assert.Contains("invalid", service.Error); + Assert.Equal(stored, store.Value); + Assert.Equal(0, store.WriteCount); + } + + [Fact] + public void PreferenceService_ReadFailureIsVisibleAndExplicitSelectionCanRecover() + { + var store = new IsolatedPreferenceStore { ReadFailure = true }; + var service = new DisplayUnitPreferenceService(store); + service.Initialize(); + + Assert.Equal(DisplayUnitSelection.Default, service.Selection); + Assert.False(service.IsPersistedSelection); + Assert.Contains("Could not load", service.Error); + Assert.Equal(0, store.WriteCount); + + Assert.True(service.TrySet(new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Road))); + Assert.Null(service.Error); + Assert.Equal(new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Road), service.Selection); + Assert.True(service.IsPersistedSelection); + } + + [Fact] + public void PreferenceService_InvalidChoiceAndFailedWritePreserveActiveSelection() + { + var store = new IsolatedPreferenceStore(); + var service = new DisplayUnitPreferenceService(store); + service.Initialize(); + var initial = service.Selection; + Assert.False(service.TrySet(new DisplayUnitSelection((DisplayUnitSystem)99, SpeedDisplayMode.Road))); + Assert.Equal(initial, service.Selection); + Assert.Equal(0, store.WriteCount); + + Assert.True(service.TrySet(new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Road))); + store.WriteFailure = true; + Assert.False(service.TrySet(new DisplayUnitSelection(DisplayUnitSystem.ImperialUS, SpeedDisplayMode.Engineering))); + Assert.Equal(new DisplayUnitSelection(DisplayUnitSystem.Metric, SpeedDisplayMode.Road), service.Selection); + Assert.True(service.IsPersistedSelection); + Assert.Contains("Could not save", service.Error); + Assert.Equal("metric|road", store.Value); + } + + private sealed class IsolatedPreferenceStore : IDisplayUnitPreferenceStore + { + public string? Value { get; set; } + public bool ReadFailure { get; set; } + public bool WriteFailure { get; set; } + public int WriteCount { get; private set; } + + public string? Read() => ReadFailure + ? throw new InvalidOperationException("controlled read failure") + : Value; + + public void Write(string value) + { + WriteCount++; + if (WriteFailure) + { + throw new InvalidOperationException("controlled write failure"); + } + + Value = value; + } + } +}