ferrostar 0.51.0

The core of modern turn-by-turn navigation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! The navigation state machine.

pub mod models;
pub mod step_advance;
pub mod waypoint_advance;

#[cfg(test)]
pub(crate) mod test_helpers;

#[cfg(feature = "wasm-bindgen")]
use crate::navigation_controller::models::{
    SerializableNavState, SerializableNavigationControllerConfig,
};
use crate::{
    algorithms::{
        advance_step, apply_snapped_course, calculate_trip_progress,
        index_of_closest_segment_origin, snap_user_location_to_line,
    },
    deviation_detection::RouteDeviation,
    models::{Route, RouteStep, UserLocation, Waypoint},
    navigation_controller::{
        models::TripSummary,
        waypoint_advance::{WaypointAdvanceChecker, WaypointAdvanceResult, WaypointCheckEvent},
    },
    navigation_session::{NavigationObserver, NavigationSession, recording::NavigationRecorder},
};
use chrono::Utc;
use geo::geometry::LineString;
use models::{NavState, NavigationControllerConfig, StepAdvanceStatus, TripState};
use std::clone::Clone;
use std::sync::Arc;
#[cfg(feature = "wasm-bindgen")]
use wasm_bindgen::{JsValue, prelude::wasm_bindgen};

/// Core interface for navigation functionalities.
///
/// This trait defines the essential operations for a navigation state manager.
/// This lets us build additional layers (e.g. event logging)
/// around [`NavigationController`] in a composable manner.
#[cfg_attr(feature = "uniffi", uniffi::export)]
pub trait Navigator: Send + Sync {
    fn route(&self) -> Route;
    fn get_initial_state(&self, location: UserLocation) -> NavState;
    fn advance_to_next_step(&self, state: NavState) -> NavState;
    fn update_user_location(&self, location: UserLocation, state: NavState) -> NavState;
}

/// Creates a new navigation controller for the given route and configuration.
///
/// It returns an Arc-wrapped trait object implementing `Navigator`.
/// If `should_record` is true, it creates a controller with event recording enabled.
#[cfg_attr(feature = "uniffi", uniffi::export)]
pub fn create_navigator(
    route: Route,
    config: NavigationControllerConfig,
    should_record: bool,
) -> Arc<dyn Navigator> {
    let observers: Vec<Arc<dyn NavigationObserver>> = if should_record {
        vec![Arc::new(NavigationRecorder::new(
            route.clone(),
            config.clone(),
        ))]
    } else {
        vec![]
    };

    // Creates a normal navigation controller.
    Arc::new(NavigationSession::new(
        Arc::new(NavigationController::new(route, config)),
        observers,
    ))
}

/// Manages the navigation lifecycle through a route,
/// returning an updated state given inputs like user location.
///
/// Notes for implementing a new platform:
/// - A controller is bound to a single route; if you want recalculation, create a new instance.
/// - This is a pure type (no interior mutability), so a core function of your platform code is responsibly managing mutable state.
#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
pub struct NavigationController {
    route: Route,
    config: NavigationControllerConfig,
}

#[cfg_attr(feature = "uniffi", uniffi::export)]
impl NavigationController {
    #[cfg_attr(feature = "uniffi", uniffi::constructor)]
    /// Create a navigation controller for a route and configuration.
    pub fn new(route: Route, config: NavigationControllerConfig) -> Self {
        Self { route, config }
    }
}

impl Navigator for NavigationController {
    /// The route associated with this controller.
    fn route(&self) -> Route {
        self.route.clone()
    }

    /// Returns initial trip state as if the user had just started the route with no progress.
    fn get_initial_state(&self, location: UserLocation) -> NavState {
        let remaining_steps = self.route.steps.clone();

        let initial_summary = TripSummary {
            distance_traveled: 0.0,
            snapped_distance_traveled: 0.0,
            started_at: Utc::now(),
            ended_at: None,
        };

        let Some(current_route_step) = remaining_steps.first() else {
            // Bail early; if we don't have any steps, this is a useless route
            return NavState::complete(location, initial_summary);
        };

        // TODO: We could move this to the Route struct or NavigationController directly to only calculate it once.
        let current_step_linestring = current_route_step.get_linestring();
        let (current_step_geometry_index, snapped_user_location) =
            self.snap_user_to_line(location, &current_step_linestring);

        let progress = calculate_trip_progress(
            &snapped_user_location.into(),
            &current_step_linestring,
            &remaining_steps,
        );

        let visual_instruction = current_route_step
            .get_active_visual_instruction(progress.distance_to_next_maneuver)
            .cloned();
        let spoken_instruction = current_route_step
            .get_current_spoken_instruction(progress.distance_to_next_maneuver)
            .cloned();

        let annotation_json = current_step_geometry_index
            .and_then(|index| current_route_step.get_annotation_at_current_index(index));

        let initial_trip_state = TripState::Navigating {
            current_step_geometry_index,
            user_location: location,
            snapped_user_location,
            remaining_steps,
            // Skip the first waypoint, as it is the current one
            remaining_waypoints: self.route.waypoints.iter().skip(1).cloned().collect(),
            progress,
            summary: initial_summary,
            deviation: RouteDeviation::NoDeviation,
            visual_instruction,
            spoken_instruction,
            annotation_json,
        };

        let deviation = self
            .config
            .route_deviation_tracking
            .check_route_deviation(&self.route, &initial_trip_state);

        let trip_state = if let TripState::Navigating {
            current_step_geometry_index,
            user_location,
            snapped_user_location,
            remaining_steps,
            remaining_waypoints,
            progress,
            summary,
            visual_instruction,
            spoken_instruction,
            annotation_json,
            ..
        } = initial_trip_state
        {
            // If the user starts completely off the route, suppress instructions for the
            // same reason as in `create_intermediate_trip_state`: the snap-derived distance
            // to the next maneuver is geometrically unsound, so any countdown surfaced
            // from it would mislead the user. `OffStepOnRoute` is intentionally not
            // suppressed here — the user is still on the route polyline (just on a future
            // step), and the step-advance flow will reconcile shortly.
            let (visual_instruction, spoken_instruction) = if deviation.is_completely_off_route() {
                (None, None)
            } else {
                (visual_instruction, spoken_instruction)
            };
            TripState::Navigating {
                current_step_geometry_index,
                user_location,
                snapped_user_location,
                remaining_steps,
                remaining_waypoints,
                progress,
                summary,
                deviation, // Use the newly calculated deviation
                visual_instruction,
                spoken_instruction,
                annotation_json,
            }
        } else {
            unreachable!("initial_trip_state should always be Navigating variant")
        };

        let next_advance = Arc::clone(&self.config.step_advance_condition);
        NavState::new(trip_state, next_advance)
    }

    /// Advances navigation to the next step (or finishes the route).
    ///
    /// Depending on the advancement strategy, this may be automatic.
    /// For other cases, it is desirable to advance to the next step manually (ex: walking in an
    /// urban tunnel). We leave this decision to the app developer and provide this as a convenience.
    ///
    /// This method takes the intermediate state (e.g., from `update_user_location`) and advances if necessary,
    /// and does not handle anything like snapping.
    fn advance_to_next_step(&self, state: NavState) -> NavState {
        match state.trip_state() {
            TripState::Navigating {
                user_location,
                ref remaining_steps,
                ref remaining_waypoints,
                deviation,
                summary,
                ..
            } => {
                let update = advance_step(remaining_steps);
                match update {
                    StepAdvanceStatus::Advanced { step: current_step } => {
                        // Trim the remaining waypoints if needed.
                        let waypoints_result = self.get_new_waypoints(
                            &state.trip_state(),
                            WaypointCheckEvent::StepAdvanced(current_step.clone()),
                        );
                        let remaining_waypoints = match waypoints_result {
                            WaypointAdvanceResult::Unchanged => remaining_waypoints.clone(),
                            WaypointAdvanceResult::Changed(new_waypoints) => new_waypoints,
                        };

                        // Apply the updates
                        let mut remaining_steps = remaining_steps.clone();
                        remaining_steps.remove(0);

                        // Create a new trip state with the updated current_step
                        // and remaining_steps
                        let trip_state = self.create_intermediate_trip_state(
                            state.trip_state(),
                            user_location,
                            current_step,
                            remaining_steps,
                            remaining_waypoints,
                            deviation,
                        );

                        NavState::new(trip_state, state.step_advance_condition())
                    }
                    StepAdvanceStatus::EndOfRoute => NavState::complete(user_location, summary),
                }
            }
            // Pass through
            TripState::Idle { .. } | TripState::Complete { .. } => state.clone(),
        }
    }

    /// Updates the user's current location and updates the navigation state accordingly.
    ///
    /// # Panics
    ///
    /// If there is no current step ([`TripState::Navigating`] has an empty `remainingSteps` value),
    /// this function will panic.
    fn update_user_location(&self, location: UserLocation, state: NavState) -> NavState {
        match state.trip_state() {
            TripState::Navigating {
                remaining_steps,
                ref remaining_waypoints,
                summary,
                ..
            } => {
                // Remaining steps is empty, the route is finished.
                let Some(current_step) = remaining_steps.first().cloned() else {
                    return NavState::complete(location, summary);
                };

                // Trim the remaining waypoints if needed.
                let waypoints_result = self
                    .get_new_waypoints(&state.trip_state(), WaypointCheckEvent::LocationUpdated);
                let remaining_waypoints = match waypoints_result {
                    WaypointAdvanceResult::Unchanged => remaining_waypoints.clone(),
                    WaypointAdvanceResult::Changed(new_waypoints) => new_waypoints,
                };

                let deviation = self
                    .config
                    .route_deviation_tracking
                    .check_route_deviation(&self.route, &state.trip_state());

                let is_arriving = remaining_steps.len() <= 2;
                let intermediate_trip_state = self.create_intermediate_trip_state(
                    state.trip_state(),
                    location,
                    current_step,
                    remaining_steps,
                    remaining_waypoints,
                    deviation,
                );

                // Get the step advance condition result.
                let step_advance_result = if is_arriving {
                    self.config
                        .arrival_step_advance_condition
                        .should_advance_step(intermediate_trip_state.clone())
                } else {
                    state
                        .step_advance_condition()
                        .should_advance_step(intermediate_trip_state.clone())
                };

                let should_advance = step_advance_result.should_advance();
                let intermediate_nav_state =
                    NavState::new(intermediate_trip_state, step_advance_result.next_iteration);

                if should_advance {
                    // Advance to the next step
                    let updated_state = self.advance_to_next_step(intermediate_nav_state);

                    return if is_arriving {
                        updated_state
                    } else {
                        // Recurse ("speed run" behavior)
                        self.update_user_location(location, updated_state)
                    };
                }

                intermediate_nav_state
            }
            // Pass through
            TripState::Idle { .. } | TripState::Complete { .. } => state.clone(),
        }
    }
}

// Shared functionality for the navigation controller that is not exported by `UniFFI`.
impl NavigationController {
    /// Create an intermediate trip state with updated values,
    /// but does _not_ advance to the next step or handle arrival.
    ///
    /// Parameters:
    /// - `trip_state`: The existing/last trip state.
    /// - `location`: The user's current location.
    /// - `current_step`: The current route step.
    /// - `remaining_steps`: The remaining route steps.
    /// - `remaining_waypoints`: The remaining waypoints.
    ///
    /// Returns:
    /// - `TripState`: The intermediate trip state.
    fn create_intermediate_trip_state(
        &self,
        trip_state: TripState,
        current_user_location: UserLocation,
        current_step: RouteStep,
        remaining_steps: Vec<RouteStep>,
        remaining_waypoints: Vec<Waypoint>,
        deviation: RouteDeviation,
    ) -> TripState {
        match trip_state {
            TripState::Navigating {
                user_location: previous_user_location,
                snapped_user_location: previous_snapped_user_location,
                summary: previous_summary,
                ..
            } => {
                // Find the nearest point on the route line
                let current_step_linestring = current_step.get_linestring();
                let (current_step_geometry_index, snapped_user_location) =
                    self.snap_user_to_line(current_user_location, &current_step_linestring);

                // Update trip summary with accumulated distance
                let updated_summary = previous_summary.update(
                    &previous_user_location,
                    &current_user_location,
                    &previous_snapped_user_location,
                    &snapped_user_location,
                );

                let progress = calculate_trip_progress(
                    &snapped_user_location.into(),
                    &current_step_linestring,
                    &remaining_steps,
                );

                // Visual + spoken instructions are derived from the *snapped* distance to
                // the next maneuver. When the user is completely off the route, that snap
                // is geometrically unsound: a user laterally far from the route still
                // projects onto it somewhere, and the resulting "distance to next maneuver"
                // is the phantom snap's distance, not the user's. Surfacing instructions
                // paced off that phantom distance produces wrong countdowns to maneuvers
                // the user can't take from their current position. Suppress both while
                // completely off-route — the deviation flag (and the consumer's own alert)
                // is the right cue to surface; resume normal instruction emission on
                // return. `OffStepOnRoute` is intentionally not suppressed: the user is
                // still on the route polyline, and the step-advance flow will reconcile
                // shortly. Apps that don't want any of this policy can configure
                // `RouteDeviationTracking::None`.
                let (visual_instruction, spoken_instruction) =
                    if deviation.is_completely_off_route() {
                        (None, None)
                    } else {
                        (
                            current_step
                                .get_active_visual_instruction(progress.distance_to_next_maneuver)
                                .cloned(),
                            current_step
                                .get_current_spoken_instruction(progress.distance_to_next_maneuver)
                                .cloned(),
                        )
                    };
                let annotation_json = current_step_geometry_index
                    .and_then(|index| current_step.get_annotation_at_current_index(index));

                TripState::Navigating {
                    current_step_geometry_index,
                    user_location: current_user_location,
                    snapped_user_location,
                    remaining_steps,
                    remaining_waypoints,
                    progress,
                    summary: updated_summary,
                    deviation,
                    visual_instruction,
                    spoken_instruction,
                    annotation_json,
                }
            }
            // Pass through
            TripState::Idle { .. } | TripState::Complete { .. } => trip_state,
        }
    }

    /// Snaps the user's location to the route line and updates the user's course if necessary.
    ///
    /// This bundles all work related to snapping the user's location to the route line and is not intended to be exported.
    ///
    /// Returns the index of the closest segment origin to the snapped user location as well as the snapped user location.
    fn snap_user_to_line(
        &self,
        location: UserLocation,
        line: &LineString,
    ) -> (Option<u64>, UserLocation) {
        // Snap the user's latitude and longitude to the line.
        let snapped_user_location = snap_user_location_to_line(location, line);

        // Get the index of the closest segment origin to the snapped user location.
        let current_step_geometry_index =
            index_of_closest_segment_origin(snapped_user_location, line);

        // Snap the user's course to the line if the configuration specifies it.
        let snapped_with_course: UserLocation = match &self.config.snapped_location_course_filtering
        {
            models::CourseFiltering::SnapToRoute => {
                apply_snapped_course(snapped_user_location, current_step_geometry_index, line)
            }
            models::CourseFiltering::Raw => snapped_user_location,
        };

        (current_step_geometry_index, snapped_with_course)
    }

    /// Process waypoint advance
    fn get_new_waypoints(
        &self,
        state: &TripState,
        event: WaypointCheckEvent,
    ) -> WaypointAdvanceResult {
        let checker = WaypointAdvanceChecker {
            mode: self.config.waypoint_advance,
        };
        checker.get_new_waypoints(state, event)
    }
}

/// JavaScript wrapper for `NavigationController`.
/// This wrapper is required because `NavigationController` cannot be directly converted to a JavaScript object
/// and requires serialization/deserialization of its methods' inputs and outputs.
#[cfg(feature = "wasm-bindgen")]
#[wasm_bindgen(js_name = NavigationController)]
pub struct JsNavigationController(Arc<dyn Navigator>);

#[cfg(feature = "wasm-bindgen")]
#[wasm_bindgen(js_class = NavigationController)]
impl JsNavigationController {
    #[wasm_bindgen(constructor)]
    pub fn new(
        route: JsValue,
        config: JsValue,
        should_record: JsValue,
    ) -> Result<JsNavigationController, JsValue> {
        let route: Route = serde_wasm_bindgen::from_value(route)?;
        let config: SerializableNavigationControllerConfig =
            serde_wasm_bindgen::from_value(config)?;
        let should_record: bool = serde_wasm_bindgen::from_value(should_record)?;

        Ok(JsNavigationController(create_navigator(
            route,
            config.into(),
            should_record,
        )))
    }

    #[wasm_bindgen(js_name = getInitialState)]
    pub fn get_initial_state(&self, location: JsValue) -> Result<JsValue, JsValue> {
        let location: UserLocation = serde_wasm_bindgen::from_value(location)?;
        let nav_state = self.0.get_initial_state(location);
        let result: SerializableNavState = nav_state.into();

        serde_wasm_bindgen::to_value(&result).map_err(|e| JsValue::from_str(&format!("{:?}", e)))
    }

    #[wasm_bindgen(js_name = advanceToNextStep)]
    pub fn advance_to_next_step(&self, state: JsValue) -> Result<JsValue, JsValue> {
        let state: SerializableNavState = serde_wasm_bindgen::from_value(state)?;
        let new_state = self.0.advance_to_next_step(state.into());

        serde_wasm_bindgen::to_value(&SerializableNavState::from(new_state))
            .map_err(|e| JsValue::from_str(&format!("{:?}", e)))
    }

    #[wasm_bindgen(js_name = updateUserLocation)]
    pub fn update_user_location(
        &self,
        location: JsValue,
        state: JsValue,
    ) -> Result<JsValue, JsValue> {
        let location: UserLocation = serde_wasm_bindgen::from_value(location)?;
        let state: SerializableNavState = serde_wasm_bindgen::from_value(state)?;
        let new_state = self.0.update_user_location(location, state.into());

        serde_wasm_bindgen::to_value(&SerializableNavState::from(new_state))
            .map_err(|e| JsValue::from_str(&format!("{:?}", e)))
    }
}

#[cfg(test)]
mod tests {
    use super::step_advance::StepAdvanceCondition;
    use super::*;
    use crate::navigation_controller::step_advance::conditions::{
        DistanceEntryAndExitCondition, DistanceToEndOfStepCondition,
    };
    use crate::navigation_controller::test_helpers::{
        get_test_navigation_controller_config, nav_controller_insta_settings,
    };
    use crate::routing_adapters::osrm::models::OsrmWaypointProperties;
    use crate::simulation::{
        LocationBias, advance_location_simulation, location_simulation_from_route,
    };
    use crate::test_utils::{TestRoute, redact_properties};
    use std::sync::Arc;

    fn test_full_route_state_snapshot(
        route: Route,
        step_advance_condition: Arc<dyn StepAdvanceCondition>,
        should_record: bool,
    ) -> (Arc<dyn Navigator>, Vec<NavState>) {
        let mut simulation_state =
            location_simulation_from_route(&route, Some(10.0), LocationBias::None)
                .expect("Unable to create simulation");

        let controller = create_navigator(
            route,
            get_test_navigation_controller_config(step_advance_condition),
            should_record,
        );

        let mut state = controller.get_initial_state(simulation_state.current_location);
        let mut states = vec![state.clone()];
        loop {
            let new_simulation_state = advance_location_simulation(&simulation_state);
            let new_state =
                controller.update_user_location(new_simulation_state.current_location, state);

            match new_state.trip_state() {
                TripState::Idle { .. } => {}
                TripState::Navigating {
                    current_step_geometry_index,
                    ref remaining_steps,
                    ref deviation,
                    ..
                } => {
                    if let Some(index) = current_step_geometry_index {
                        let geom_length = remaining_steps[0].geometry.len() as u64;
                        // Regression test that the geometry index is valid
                        assert!(
                            index < geom_length,
                            "index = {index}, geom_length = {geom_length}"
                        );
                    }

                    // Regression test that we are never marked as completely off the route.
                    // We used to encounter this with relative step advance on self-intersecting
                    // routes, for example. OffStepOnRoute is acceptable
                    // (on the route, just a different step).
                    assert!(
                        !deviation.is_completely_off_route(),
                        "User should never be completely off route during simulation, got: {deviation:?}"
                    );
                }
                TripState::Complete { .. } => {
                    states.push(new_state);
                    break;
                }
            }

            simulation_state = new_simulation_state;
            state = new_state.clone();
            states.push(new_state);
        }

        (controller, states)
    }

    // Full simulations for several routes with different settings

    #[test]
    fn test_extended_exact_distance() {
        nav_controller_insta_settings().bind(|| {
            let (_, states) = test_full_route_state_snapshot(
                TestRoute::ValhallaExtended.first_route(),
                Arc::new(DistanceToEndOfStepCondition {
                    distance: 0,
                    minimum_horizontal_accuracy: 0,
                }),
                false,
            );
            insta::assert_yaml_snapshot!(states
                .into_iter()
                .map(|state| state.trip_state())
                .collect::<Vec<_>>(), {
                    ".**.remaining_waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
                });
        });
    }

    #[test]
    fn test_extended_relative_linestring() {
        nav_controller_insta_settings().bind(|| {
            let (_, states) = test_full_route_state_snapshot(
                TestRoute::ValhallaExtended.first_route(),
                Arc::new(DistanceEntryAndExitCondition::exact()),
                false,
            );
            insta::assert_yaml_snapshot!(states
                .into_iter()
                .map(|state| state.trip_state())
                .collect::<Vec<_>>(), {
                    ".**.remaining_waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
                });
        });
    }

    #[test]
    fn test_self_intersecting_exact_distance() {
        nav_controller_insta_settings().bind(|| {
            let (_, states) = test_full_route_state_snapshot(
                TestRoute::ValhallaSelfIntersecting.first_route(),
                Arc::new(DistanceToEndOfStepCondition {
                    distance: 0,
                    minimum_horizontal_accuracy: 0,
                }),
                false,
            );
            insta::assert_yaml_snapshot!(states
                .into_iter()
                .map(|state| state.trip_state())
                .collect::<Vec<_>>(), {
                    ".**.remaining_waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
                });
        });
    }

    #[test]
    fn test_self_intersecting_relative_linestring() {
        nav_controller_insta_settings().bind(|| {
            let (_, states) = test_full_route_state_snapshot(
                TestRoute::ValhallaSelfIntersecting.first_route(),
                Arc::new(DistanceEntryAndExitCondition::exact()),
                false,
            );
            insta::assert_yaml_snapshot!(states
                .into_iter()
                .map(|state| state.trip_state())
                .collect::<Vec<_>>(), {
                    ".**.remaining_waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
                });
        });
    }

    #[test]
    fn test_self_intersecting_relative_linestring_min_line_distance() {
        nav_controller_insta_settings().bind(|| {
            let (_, states) = test_full_route_state_snapshot(
                TestRoute::ValhallaSelfIntersecting.first_route(),
                Arc::new(DistanceToEndOfStepCondition {
                    distance: 0,
                    minimum_horizontal_accuracy: 0,
                }),
                false,
            );
            insta::assert_yaml_snapshot!(states
                .into_iter()
                .map(|state| state.trip_state())
                .collect::<Vec<_>>(), {
                    ".**.remaining_waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
                });
        });
    }

    #[test]
    fn test_roundabout_exact_distance() {
        nav_controller_insta_settings().bind(|| {
            let (_, states) = test_full_route_state_snapshot(
                TestRoute::ValhallaWithRoundabouts.first_route(),
                Arc::new(DistanceToEndOfStepCondition {
                    distance: 0,
                    minimum_horizontal_accuracy: 0,
                }),
                false,
            );
            insta::assert_yaml_snapshot!(states
                .into_iter()
                .map(|state| state.trip_state())
                .collect::<Vec<_>>(), {
                    ".**.remaining_waypoints[].properties" => insta::dynamic_redaction(redact_properties::<OsrmWaypointProperties>),
                });
        });
    }

    /// Off-route should suppress visual + spoken instructions, because they are derived
    /// from the snapped distance to the next maneuver — which is geometrically unsound
    /// when the user is laterally far from the route. Returning to the route should
    /// resume normal emission.
    #[test]
    fn test_off_route_suppresses_instructions() {
        use crate::deviation_detection::RouteDeviationTracking;
        use crate::navigation_controller::models::{CourseFiltering, WaypointAdvanceMode};
        use crate::navigation_controller::step_advance::conditions::ManualStepCondition;
        use crate::test_utils::make_user_location;
        use geo::coord;

        let route = TestRoute::Valhalla.first_route();
        let start_coord = route.geometry[0];

        // ManualStepCondition keeps the test focused on instruction emission — no automatic
        // step advancement can perturb the current step across calls.
        // StaticThreshold with tight thresholds: any noticeable lateral offset trips deviation.
        let config = NavigationControllerConfig {
            waypoint_advance: WaypointAdvanceMode::WaypointWithinRange(100.0),
            route_deviation_tracking: RouteDeviationTracking::StaticThreshold {
                minimum_horizontal_accuracy: 20,
                max_acceptable_deviation: 30.0,
            },
            snapped_location_course_filtering: CourseFiltering::Raw,
            step_advance_condition: Arc::new(ManualStepCondition),
            arrival_step_advance_condition: Arc::new(ManualStepCondition),
        };

        let controller = create_navigator(route, config, false);

        let on_route_loc = make_user_location(coord!(x: start_coord.lng, y: start_coord.lat), 5.0);

        // 1. Initial state at the route start: on-route, instructions populated.
        let initial = controller.get_initial_state(on_route_loc.clone());
        let (initial_visual, initial_spoken) = match initial.trip_state() {
            TripState::Navigating {
                deviation,
                visual_instruction,
                spoken_instruction,
                ..
            } => {
                assert_eq!(
                    deviation,
                    RouteDeviation::NoDeviation,
                    "initial state at the route start should be on-route"
                );
                assert!(
                    visual_instruction.is_some() || spoken_instruction.is_some(),
                    "Valhalla fixture's first step has voice + banner instructions; \
                     at least one should be populated when on-route at the start"
                );
                (visual_instruction, spoken_instruction)
            }
            other => panic!("expected Navigating, got {other:?}"),
        };

        // 2. Update with a wildly off-route location.
        // Offset by ~0.5° (~55 km) so the location is unambiguously far from every step
        // in the route, regardless of where the route winds. The deviation check scans all
        // remaining steps and returns NoDeviation if the user is close to any of them.
        //
        // Note: `update_user_location` computes deviation against the *previous* trip
        // state's user_location (mod.rs:289), so the deviation flag lags one tick. The
        // first off-route update therefore still reports NoDeviation; the second flips it
        // to `Deviation { kind: CompletelyOffRoute }` (the user is 55km from every step),
        // and that is when instruction suppression activates.
        let off_route_loc = make_user_location(
            coord!(x: start_coord.lng + 0.5, y: start_coord.lat + 0.5),
            5.0,
        );
        let off_state_lagged = controller.update_user_location(off_route_loc.clone(), initial);
        let off_state = controller.update_user_location(off_route_loc, off_state_lagged);
        match off_state.trip_state() {
            TripState::Navigating {
                deviation,
                visual_instruction,
                spoken_instruction,
                ..
            } => {
                assert!(
                    deviation.is_completely_off_route(),
                    "expected CompletelyOffRoute on second off-route tick, got {deviation:?}"
                );
                assert!(
                    visual_instruction.is_none(),
                    "visual_instruction must be None while completely off-route, got {visual_instruction:?}"
                );
                assert!(
                    spoken_instruction.is_none(),
                    "spoken_instruction must be None while completely off-route, got {spoken_instruction:?}"
                );
            }
            other => panic!("expected Navigating, got {other:?}"),
        };

        // 3. Update back to the on-route location. The first return tick still carries
        // the lagged CompletelyOffRoute flag (deviation is computed from the previous
        // user_location, which was off-route), so update twice to clear the lag.
        let recovered_lagged = controller.update_user_location(on_route_loc.clone(), off_state);
        let recovered = controller.update_user_location(on_route_loc, recovered_lagged);
        match recovered.trip_state() {
            TripState::Navigating {
                deviation,
                visual_instruction,
                spoken_instruction,
                ..
            } => {
                assert_eq!(
                    deviation,
                    RouteDeviation::NoDeviation,
                    "expected to be back on route at the same starting coordinate"
                );
                assert_eq!(
                    visual_instruction, initial_visual,
                    "visual_instruction should resume emission on return to route"
                );
                assert_eq!(
                    spoken_instruction, initial_spoken,
                    "spoken_instruction should resume emission on return to route"
                );
            }
            other => panic!("expected Navigating, got {other:?}"),
        };
    }

    /// Starting a route with an off-route initial location should also suppress instructions —
    /// covers the `get_initial_state` path in addition to the `update_user_location` path.
    #[test]
    fn test_off_route_initial_state_suppresses_instructions() {
        use crate::deviation_detection::RouteDeviationTracking;
        use crate::navigation_controller::models::{CourseFiltering, WaypointAdvanceMode};
        use crate::navigation_controller::step_advance::conditions::ManualStepCondition;
        use crate::test_utils::make_user_location;
        use geo::coord;

        let route = TestRoute::Valhalla.first_route();
        let start_coord = route.geometry[0];

        let config = NavigationControllerConfig {
            waypoint_advance: WaypointAdvanceMode::WaypointWithinRange(100.0),
            route_deviation_tracking: RouteDeviationTracking::StaticThreshold {
                minimum_horizontal_accuracy: 20,
                max_acceptable_deviation: 30.0,
            },
            snapped_location_course_filtering: CourseFiltering::Raw,
            step_advance_condition: Arc::new(ManualStepCondition),
            arrival_step_advance_condition: Arc::new(ManualStepCondition),
        };

        let controller = create_navigator(route, config, false);

        // User opens the app already off-route from the planned start.
        // Offset by ~0.5° (~55 km) so the location is unambiguously far from every step
        // in the route, regardless of where the route winds. The deviation check scans all
        // remaining steps and returns NoDeviation if the user is close to any of them.
        let off_route_loc = make_user_location(
            coord!(x: start_coord.lng + 0.5, y: start_coord.lat + 0.5),
            5.0,
        );
        let initial = controller.get_initial_state(off_route_loc);
        match initial.trip_state() {
            TripState::Navigating {
                deviation,
                visual_instruction,
                spoken_instruction,
                ..
            } => {
                assert!(
                    deviation.is_completely_off_route(),
                    "expected CompletelyOffRoute on initial state at off-route location, got {deviation:?}"
                );
                assert!(
                    visual_instruction.is_none(),
                    "initial visual_instruction must be None when starting off-route"
                );
                assert!(
                    spoken_instruction.is_none(),
                    "initial spoken_instruction must be None when starting off-route"
                );
            }
            other => panic!("expected Navigating, got {other:?}"),
        };
    }
}