Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

test: expand action window coverage

ldm024fb7151f3b5
diff --git a/moli-action-window/README.md b/moli-action-window/README.md
index 5ceb0db5f..f33d746c4 100644
--- a/moli-action-window/README.md
+++ b/moli-action-window/README.md
@@ -45,3 +45,17 @@ Typical host flow is:
All timestamps supplied to one queue must come from the same monotonic clock
and be admitted in event-loop order.
+
+## Test layers
+
+- Unit tests pin every state transition, deadline edge, compaction rule,
+ counter, cancellation, and capacity behavior with a virtual clock.
+- Public API tests compile the crate as an external consumer, including owned
+ scopes, non-`Clone` payloads, consuming batches, all mouse buttons, and
+ scroll metadata.
+- Model tests compare the implementation with an independent flat reference
+ compactor for all 9,331 mixed sequences up to five actions, plus a
+ deterministic 1,000-action capacity stream.
+- End-to-end host tests model Page execution, one observer/render commit per
+ batch, screenshot and screencast barriers, stale timer wakes, late input,
+ capacity rotation, and a real timer armed from `next_deadline`.
diff --git a/moli-action-window/tests/end_to_end.rs b/moli-action-window/tests/end_to_end.rs
new file mode 100644
index 000000000..06c37ad40
--- /dev/null
+++ b/moli-action-window/tests/end_to_end.rs
@@ -0,0 +1,292 @@
+use std::{thread, time::Duration, time::Instant};
+
+use moli_action_window::{
+ ActionBarrier, ActionBatch, ActionBatchCause, ActionWindow, ActionWindowConfig, ClickAction,
+ MouseButton, PlannedAction, Point, ScrollAction, WindowAction,
+};
+
+const PAGE: &str = "page-1/document-1";
+
+#[derive(Clone, Debug, PartialEq)]
+enum HostCommand {
+ Marker(&'static str),
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct CapturedFrame {
+ barrier: ActionBarrier,
+ scroll_offset: f64,
+ last_click_x: Option<f64>,
+ render_commit: usize,
+}
+
+#[derive(Default)]
+struct FakePage {
+ scroll_offset: f64,
+ last_click_x: Option<f64>,
+ ordered_log: Vec<(&'static str, f64)>,
+ observer_samples: Vec<f64>,
+ applied_causes: Vec<ActionBatchCause>,
+ render_commits: usize,
+ frames: Vec<CapturedFrame>,
+}
+
+impl FakePage {
+ fn apply(&mut self, batch: ActionBatch<&'static str, HostCommand>) {
+ self.applied_causes.push(batch.cause());
+ for action in batch.into_actions() {
+ match action {
+ PlannedAction::Scroll { run, .. } => {
+ for step in run.steps() {
+ self.scroll_offset =
+ (self.scroll_offset + step.value().delta_y).clamp(0.0, 100.0);
+ }
+ }
+ PlannedAction::Click { click, .. } => {
+ self.last_click_x = Some(click.value().position.x);
+ }
+ PlannedAction::Ordered { action, .. } => match action.into_value() {
+ HostCommand::Marker(marker) => {
+ self.ordered_log.push((marker, self.scroll_offset));
+ }
+ },
+ }
+ }
+
+ // This is the host contract represented by one ActionBatch boundary.
+ self.observer_samples.push(self.scroll_offset);
+ self.render_commits += 1;
+ }
+
+ fn capture(
+ &mut self,
+ queue: &mut ActionWindow<&'static str, HostCommand>,
+ barrier: ActionBarrier,
+ now: Instant,
+ ) -> CapturedFrame {
+ if let Some(batch) = queue.flush(barrier, now) {
+ self.apply(batch);
+ }
+ let frame = CapturedFrame {
+ barrier,
+ scroll_offset: self.scroll_offset,
+ last_click_x: self.last_click_x,
+ render_commit: self.render_commits,
+ };
+ self.frames.push(frame.clone());
+ frame
+ }
+}
+
+fn at(base: Instant, milliseconds: u64) -> Instant {
+ base + Duration::from_millis(milliseconds)
+}
+
+fn scroll(delta_y: f64) -> WindowAction<HostCommand> {
+ WindowAction::Scroll(ScrollAction::pixels(Point::new(10.0, 20.0), 0.0, delta_y))
+}
+
+fn click(x: f64) -> WindowAction<HostCommand> {
+ WindowAction::Click(ClickAction::new(Point::new(x, 20.0), MouseButton::Left, 1))
+}
+
+fn run_armed_timer(
+ queue: &mut ActionWindow<&'static str, HostCommand>,
+) -> ActionBatch<&'static str, HostCommand> {
+ loop {
+ let deadline = queue.next_deadline().expect("timer must be armed");
+ let now = Instant::now();
+ if now < deadline {
+ // The wait is derived from the production deadline. Spurious early
+ // wakeups are handled by the state predicate below.
+ thread::park_timeout(deadline.duration_since(now));
+ }
+ if let Some(batch) = queue.take_due(Instant::now()) {
+ return batch;
+ }
+ thread::yield_now();
+ }
+}
+
+#[test]
+fn user_timeline_applies_three_scrolls_at_fixed_one_second_deadline() {
+ let base = Instant::now();
+ let mut queue = ActionWindow::<&'static str, HostCommand>::default();
+ let mut page = FakePage::default();
+
+ queue.push(PAGE, scroll(10.0), base);
+ queue.push(PAGE, scroll(20.0), at(base, 400));
+ queue.push(PAGE, scroll(30.0), at(base, 900));
+
+ assert_eq!(queue.next_deadline(), Some(at(base, 1_000)));
+ assert!(queue.take_due(at(base, 999)).is_none());
+ page.apply(queue.take_due(at(base, 1_000)).expect("first batch"));
+
+ assert_eq!(page.scroll_offset, 60.0);
+ assert_eq!(page.observer_samples, vec![60.0]);
+ assert_eq!(page.render_commits, 1);
+ assert_eq!(queue.next_deadline(), None);
+
+ queue.push(PAGE, scroll(15.0), at(base, 1_600));
+ assert_eq!(queue.next_deadline(), Some(at(base, 2_600)));
+ assert!(queue.take_due(at(base, 2_599)).is_none());
+ page.apply(queue.take_due(at(base, 2_600)).expect("second batch"));
+
+ assert_eq!(page.scroll_offset, 75.0);
+ assert_eq!(page.observer_samples, vec![60.0, 75.0]);
+ assert_eq!(page.render_commits, 2);
+}
+
+#[test]
+fn screenshot_flushes_actions_before_capture_and_stale_timer_is_harmless() {
+ let base = Instant::now();
+ let mut queue = ActionWindow::<&'static str, HostCommand>::default();
+ let mut page = FakePage::default();
+ queue.push(PAGE, scroll(25.0), base);
+ queue.push(PAGE, click(10.0), at(base, 400));
+ queue.push(PAGE, click(40.0), at(base, 500));
+
+ let frame = page.capture(&mut queue, ActionBarrier::Screenshot, at(base, 600));
+
+ assert_eq!(frame.scroll_offset, 25.0);
+ assert_eq!(frame.last_click_x, Some(40.0));
+ assert_eq!(frame.render_commit, 1);
+ assert_eq!(page.observer_samples, vec![25.0]);
+ assert_eq!(
+ page.applied_causes,
+ vec![ActionBatchCause::Barrier(ActionBarrier::Screenshot)]
+ );
+ assert!(queue.take_due(at(base, 1_000)).is_none());
+
+ queue.push(PAGE, scroll(5.0), at(base, 1_600));
+ assert_eq!(queue.next_deadline(), Some(at(base, 2_600)));
+}
+
+#[test]
+fn screencast_frames_flush_only_when_pending_work_exists() {
+ let base = Instant::now();
+ let mut queue = ActionWindow::<&'static str, HostCommand>::default();
+ let mut page = FakePage::default();
+
+ let idle_frame = page.capture(&mut queue, ActionBarrier::Screencast, base);
+ assert_eq!(idle_frame.render_commit, 0);
+
+ queue.push(PAGE, scroll(12.0), at(base, 100));
+ let changed_frame = page.capture(&mut queue, ActionBarrier::Screencast, at(base, 200));
+ let unchanged_frame = page.capture(&mut queue, ActionBarrier::Screencast, at(base, 300));
+
+ assert_eq!(changed_frame.scroll_offset, 12.0);
+ assert_eq!(changed_frame.render_commit, 1);
+ assert_eq!(unchanged_frame.scroll_offset, 12.0);
+ assert_eq!(unchanged_frame.render_commit, 1);
+ assert_eq!(page.frames.len(), 3);
+ assert_eq!(page.render_commits, 1);
+}
+
+#[test]
+fn mixed_actions_preserve_surviving_order_and_apply_observers_once() {
+ let base = Instant::now();
+ let mut queue = ActionWindow::<&'static str, HostCommand>::default();
+ let mut page = FakePage::default();
+
+ queue.push(PAGE, scroll(-50.0), base);
+ queue.push(PAGE, click(10.0), at(base, 100));
+ queue.push(
+ PAGE,
+ WindowAction::Ordered(HostCommand::Marker("between-scrolls")),
+ at(base, 200),
+ );
+ queue.push(PAGE, scroll(100.0), at(base, 300));
+ queue.push(PAGE, click(90.0), at(base, 400));
+
+ page.apply(queue.take_due(at(base, 1_000)).expect("mixed batch"));
+
+ assert_eq!(page.ordered_log, vec![("between-scrolls", 0.0)]);
+ assert_eq!(page.scroll_offset, 100.0);
+ assert_eq!(page.last_click_x, Some(90.0));
+ assert_eq!(page.observer_samples, vec![100.0]);
+ assert_eq!(page.render_commits, 1);
+}
+
+#[test]
+fn capacity_batch_executes_before_later_pending_actions() {
+ let base = Instant::now();
+ let config = ActionWindowConfig::new(Duration::from_secs(1), 2).expect("valid config");
+ let mut queue = ActionWindow::<&'static str, HostCommand>::new(config);
+ let mut page = FakePage::default();
+ queue.push(PAGE, scroll(10.0), base);
+ queue.push(PAGE, scroll(20.0), at(base, 100));
+
+ let admission = queue.push(
+ PAGE,
+ WindowAction::Ordered(HostCommand::Marker("after-capacity")),
+ at(base, 200),
+ );
+ page.apply(
+ admission
+ .into_ready_batch()
+ .expect("capacity must release first batch"),
+ );
+ assert_eq!(page.scroll_offset, 30.0);
+ assert_eq!(page.render_commits, 1);
+ assert!(page.ordered_log.is_empty());
+
+ let frame = page.capture(&mut queue, ActionBarrier::Screenshot, at(base, 300));
+
+ assert_eq!(page.ordered_log, vec![("after-capacity", 30.0)]);
+ assert_eq!(page.render_commits, 2);
+ assert_eq!(frame.render_commit, 2);
+ assert_eq!(
+ page.applied_causes,
+ vec![
+ ActionBatchCause::Capacity,
+ ActionBatchCause::Barrier(ActionBarrier::Screenshot)
+ ]
+ );
+}
+
+#[test]
+fn late_input_returns_due_batch_before_opening_new_window() {
+ let base = Instant::now();
+ let mut queue = ActionWindow::<&'static str, HostCommand>::default();
+ let mut page = FakePage::default();
+ queue.push(PAGE, scroll(35.0), base);
+
+ let admission = queue.push(PAGE, click(80.0), at(base, 1_200));
+ page.apply(
+ admission
+ .into_ready_batch()
+ .expect("late input must release due batch"),
+ );
+
+ assert_eq!(page.scroll_offset, 35.0);
+ assert_eq!(page.last_click_x, None);
+ assert_eq!(queue.next_deadline(), Some(at(base, 2_200)));
+
+ page.capture(&mut queue, ActionBarrier::Screenshot, at(base, 1_300));
+ assert_eq!(page.last_click_x, Some(80.0));
+ assert_eq!(page.render_commits, 2);
+}
+
+#[test]
+fn real_timer_driver_uses_public_deadline_and_releases_one_batch() {
+ let config = ActionWindowConfig::new(Duration::from_millis(20), 16).expect("valid config");
+ let mut queue = ActionWindow::<&'static str, HostCommand>::new(config);
+ let mut page = FakePage::default();
+ let started_at = Instant::now();
+ queue.push(PAGE, scroll(4.0), started_at);
+ let expected_deadline = queue.next_deadline().expect("deadline");
+ // Use the same event-loop timestamp for both inputs so host preemption
+ // cannot accidentally rotate the model before the real timer is armed.
+ queue.push(PAGE, scroll(6.0), started_at);
+
+ let batch = run_armed_timer(&mut queue);
+
+ assert_eq!(batch.cause(), ActionBatchCause::Deadline);
+ assert_eq!(batch.deadline(), expected_deadline);
+ assert!(batch.released_at() >= expected_deadline);
+ page.apply(batch);
+ assert_eq!(page.scroll_offset, 10.0);
+ assert_eq!(page.render_commits, 1);
+ assert!(queue.is_idle());
+}
diff --git a/moli-action-window/tests/model_based.rs b/moli-action-window/tests/model_based.rs
new file mode 100644
index 000000000..000743340
--- /dev/null
+++ b/moli-action-window/tests/model_based.rs
@@ -0,0 +1,327 @@
+use std::time::{Duration, Instant};
+
+use moli_action_window::{
+ ActionBarrier, ActionBatch, ActionBatchCause, ActionWindow, ActionWindowConfig, ClickAction,
+ MouseButton, PlannedAction, Point, ScrollAction, WindowAction,
+};
+
+#[derive(Clone, Debug, PartialEq)]
+enum FlatKind {
+ Scroll(u64),
+ Click(u64),
+ Ordered(u64),
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct FlatAction {
+ scope: u8,
+ sequence: u64,
+ kind: FlatKind,
+}
+
+#[derive(Clone, Copy)]
+enum Choice {
+ Scroll(u8),
+ Click(u8),
+ Ordered(u8),
+}
+
+const CHOICES: [Choice; 6] = [
+ Choice::Scroll(0),
+ Choice::Scroll(1),
+ Choice::Click(0),
+ Choice::Click(1),
+ Choice::Ordered(0),
+ Choice::Ordered(1),
+];
+
+fn action_for(choice: Choice, marker: u64) -> (u8, WindowAction<u64>, FlatKind) {
+ match choice {
+ Choice::Scroll(scope) => (
+ scope,
+ WindowAction::Scroll(ScrollAction::pixels(
+ Point::new(marker as f64, scope.into()),
+ 0.0,
+ marker as f64,
+ )),
+ FlatKind::Scroll(marker),
+ ),
+ Choice::Click(scope) => (
+ scope,
+ WindowAction::Click(ClickAction::new(
+ Point::new(marker as f64, scope.into()),
+ MouseButton::Left,
+ 1,
+ )),
+ FlatKind::Click(marker),
+ ),
+ Choice::Ordered(scope) => (
+ scope,
+ WindowAction::Ordered(marker),
+ FlatKind::Ordered(marker),
+ ),
+ }
+}
+
+fn reference_admit(actions: &mut Vec<FlatAction>, action: FlatAction) {
+ if matches!(action.kind, FlatKind::Click(_)) {
+ actions.retain(|existing| {
+ existing.scope != action.scope || !matches!(existing.kind, FlatKind::Click(_))
+ });
+ }
+ actions.push(action);
+}
+
+fn expected_planned_count(actions: &[FlatAction]) -> usize {
+ let mut count = 0;
+ let mut previous_scroll_scope = None;
+ for action in actions {
+ match action.kind {
+ FlatKind::Scroll(_) if previous_scroll_scope == Some(action.scope) => {}
+ FlatKind::Scroll(_) => {
+ count += 1;
+ previous_scroll_scope = Some(action.scope);
+ }
+ FlatKind::Click(_) | FlatKind::Ordered(_) => {
+ count += 1;
+ previous_scroll_scope = None;
+ }
+ }
+ }
+ count
+}
+
+fn flatten(batch: &ActionBatch<u8, u64>) -> Vec<FlatAction> {
+ let mut flattened = Vec::new();
+ for action in batch.actions() {
+ match action {
+ PlannedAction::Scroll { scope, run } => {
+ for step in run.steps() {
+ flattened.push(FlatAction {
+ scope: *scope,
+ sequence: step.sequence().get(),
+ kind: FlatKind::Scroll(step.value().delta_y as u64),
+ });
+ }
+ }
+ PlannedAction::Click { scope, click } => flattened.push(FlatAction {
+ scope: *scope,
+ sequence: click.sequence().get(),
+ kind: FlatKind::Click(click.value().position.x as u64),
+ }),
+ PlannedAction::Ordered { scope, action } => flattened.push(FlatAction {
+ scope: *scope,
+ sequence: action.sequence().get(),
+ kind: FlatKind::Ordered(*action.value()),
+ }),
+ }
+ }
+ flattened
+}
+
+fn assert_matches_reference(
+ batch: &ActionBatch<u8, u64>,
+ reference: &[FlatAction],
+ admitted_count: usize,
+) {
+ assert_eq!(batch.admitted_action_count(), admitted_count);
+ assert_eq!(batch.retained_action_count(), reference.len());
+ assert_eq!(
+ batch.planned_action_count(),
+ expected_planned_count(reference)
+ );
+ assert_eq!(flatten(batch), reference);
+
+ let sequences: Vec<_> = reference.iter().map(|action| action.sequence).collect();
+ assert!(sequences.windows(2).all(|pair| pair[0] < pair[1]));
+
+ for pair in batch.actions().windows(2) {
+ assert!(
+ !matches!(
+ pair,
+ [
+ PlannedAction::Scroll {
+ scope: left_scope,
+ ..
+ },
+ PlannedAction::Scroll {
+ scope: right_scope,
+ ..
+ }
+ ] if left_scope == right_scope
+ ),
+ "adjacent same-scope scroll runs must be normalized"
+ );
+ }
+}
+
+#[test]
+fn exhaustive_sequences_up_to_five_actions_match_reference_compactor() {
+ let base = Instant::now();
+ let mut checked_cases = 0;
+
+ for length in 0..=5_u32 {
+ for encoded in 0..CHOICES.len().pow(length) {
+ let mut digits = encoded;
+ let mut window = ActionWindow::<u8, u64>::default();
+ let mut reference = Vec::new();
+
+ for index in 0..length as usize {
+ let choice = CHOICES[digits % CHOICES.len()];
+ digits /= CHOICES.len();
+ let marker = index as u64 + 1;
+ let (scope, action, kind) = action_for(choice, marker);
+ window.push(scope, action, base + Duration::from_micros(index as u64));
+ reference_admit(
+ &mut reference,
+ FlatAction {
+ scope,
+ sequence: marker,
+ kind,
+ },
+ );
+ }
+
+ if length == 0 {
+ assert!(window.flush(ActionBarrier::Explicit, base).is_none());
+ } else {
+ let batch = window
+ .flush(ActionBarrier::Explicit, base + Duration::from_millis(1))
+ .expect("non-empty sequence must flush");
+ assert_matches_reference(&batch, &reference, length as usize);
+ }
+ checked_cases += 1;
+ }
+ }
+
+ assert_eq!(checked_cases, 9_331);
+}
+
+#[test]
+fn capacity_rotation_matches_independent_reference_across_long_mixed_stream() {
+ let base = Instant::now();
+ let capacity = 7;
+ let config = ActionWindowConfig::new(Duration::from_secs(60), capacity).expect("valid config");
+ let mut window = ActionWindow::<u8, u64>::new(config);
+ let mut reference = Vec::new();
+ let mut admitted_in_window = 0;
+ let mut emitted_batches = 0;
+
+ let mut random = 0x4d59_5df4_d0f3_3173_u64;
+ for index in 0..1_000_u64 {
+ random = random
+ .wrapping_mul(6_364_136_223_846_793_005)
+ .wrapping_add(1_442_695_040_888_963_407);
+ let choice = CHOICES[(random as usize) % CHOICES.len()];
+ let marker = index + 1;
+ let (scope, action, kind) = action_for(choice, marker);
+ let replaces_click = matches!(kind, FlatKind::Click(_))
+ && reference.iter().any(|existing: &FlatAction| {
+ existing.scope == scope && matches!(existing.kind, FlatKind::Click(_))
+ });
+ let should_rotate = reference.len() + usize::from(!replaces_click) > capacity;
+
+ let admission = window.push(scope, action, base + Duration::from_micros(index));
+
+ if should_rotate {
+ let ready = admission
+ .ready_batch()
+ .expect("reference capacity rotation must produce a batch");
+ assert_eq!(ready.cause(), ActionBatchCause::Capacity);
+ assert_matches_reference(ready, &reference, admitted_in_window);
+ assert!(ready.retained_action_count() <= capacity);
+ reference.clear();
+ admitted_in_window = 0;
+ emitted_batches += 1;
+ } else {
+ assert!(admission.ready_batch().is_none());
+ }
+
+ reference_admit(
+ &mut reference,
+ FlatAction {
+ scope,
+ sequence: marker,
+ kind,
+ },
+ );
+ admitted_in_window += 1;
+ }
+
+ let final_batch = window
+ .flush(ActionBarrier::Explicit, base + Duration::from_secs(1))
+ .expect("stream should leave a final batch");
+ assert_matches_reference(&final_batch, &reference, admitted_in_window);
+ assert!(emitted_batches > 100, "stream must exercise many rotations");
+}
+
+#[test]
+fn every_retained_sequence_is_globally_unique_across_deadline_barrier_and_capacity_batches() {
+ let base = Instant::now();
+ let config = ActionWindowConfig::new(Duration::from_millis(10), 3).expect("valid config");
+ let mut window = ActionWindow::<u8, u64>::new(config);
+ let mut emitted_sequences = Vec::new();
+ let mut causes = Vec::new();
+
+ for (index, choice) in [Choice::Ordered(0), Choice::Ordered(1), Choice::Scroll(0)]
+ .into_iter()
+ .enumerate()
+ {
+ let marker = index as u64 + 1;
+ let (scope, action, _) = action_for(choice, marker);
+ let admission = window.push(scope, action, base + Duration::from_millis(marker));
+ assert!(admission.ready_batch().is_none());
+ }
+
+ // The fourth retained action crosses capacity before the deadline.
+ let (scope, action, _) = action_for(Choice::Scroll(1), 4);
+ let capacity_batch = window
+ .push(scope, action, base + Duration::from_millis(4))
+ .into_ready_batch()
+ .expect("fourth action must rotate the capacity-three window");
+ causes.push(capacity_batch.cause());
+ emitted_sequences.extend(
+ flatten(&capacity_batch)
+ .into_iter()
+ .map(|action| action.sequence),
+ );
+
+ // This action arrives after the replacement window's fixed 14ms deadline.
+ let (scope, action, _) = action_for(Choice::Click(0), 5);
+ let deadline_batch = window
+ .push(scope, action, base + Duration::from_millis(15))
+ .into_ready_batch()
+ .expect("late action must rotate the deadline batch");
+ causes.push(deadline_batch.cause());
+ emitted_sequences.extend(
+ flatten(&deadline_batch)
+ .into_iter()
+ .map(|action| action.sequence),
+ );
+
+ let (scope, action, _) = action_for(Choice::Ordered(0), 6);
+ window.push(scope, action, base + Duration::from_millis(16));
+ let barrier_batch = window
+ .flush(ActionBarrier::Screenshot, base + Duration::from_millis(17))
+ .expect("barrier must release final window");
+ causes.push(barrier_batch.cause());
+ emitted_sequences.extend(
+ flatten(&barrier_batch)
+ .into_iter()
+ .map(|action| action.sequence),
+ );
+
+ let mut sorted = emitted_sequences.clone();
+ sorted.sort_unstable();
+ sorted.dedup();
+ assert_eq!(sorted.len(), emitted_sequences.len());
+ assert_eq!(sorted, (1..=6).collect::<Vec<_>>());
+ assert_eq!(
+ causes,
+ vec![
+ ActionBatchCause::Capacity,
+ ActionBatchCause::Deadline,
+ ActionBatchCause::Barrier(ActionBarrier::Screenshot),
+ ]
+ );
+}
diff --git a/moli-action-window/tests/public_api.rs b/moli-action-window/tests/public_api.rs
new file mode 100644
index 000000000..64cf3f0ea
--- /dev/null
+++ b/moli-action-window/tests/public_api.rs
@@ -0,0 +1,189 @@
+use std::time::{Duration, Instant};
+
+use moli_action_window::{
+ ActionBarrier, ActionBatchCause, ActionCompaction, ActionWindow, ActionWindowConfig,
+ ActionWindowConfigError, AdmissionState, ClickAction, InputModifiers, MouseButton,
+ PlannedAction, Point, ScrollAction, ScrollDeltaMode, WindowAction,
+};
+
+#[test]
+fn default_public_surface_starts_idle_with_one_second_policy() {
+ let window = ActionWindow::<String>::default();
+
+ assert!(window.is_idle());
+ assert_eq!(window.next_deadline(), None);
+ assert_eq!(window.config().duration(), Duration::from_secs(1));
+ assert_eq!(window.config().max_retained_actions(), 4_096);
+}
+
+#[test]
+fn invalid_config_errors_are_stable_and_actionable() {
+ let zero_duration =
+ ActionWindowConfig::new(Duration::ZERO, 1).expect_err("zero duration must be rejected");
+ let zero_capacity = ActionWindowConfig::new(Duration::from_secs(1), 0)
+ .expect_err("zero capacity must be rejected");
+
+ assert_eq!(zero_duration, ActionWindowConfigError::ZeroDuration);
+ assert_eq!(
+ zero_duration.to_string(),
+ "action window duration must be non-zero"
+ );
+ assert_eq!(zero_capacity, ActionWindowConfigError::ZeroCapacity);
+ assert_eq!(
+ zero_capacity.to_string(),
+ "action window capacity must be non-zero"
+ );
+}
+
+#[test]
+fn public_api_accepts_owned_scope_and_non_clone_ordered_payload() {
+ #[derive(Debug, PartialEq)]
+ struct NonClonePayload(u32);
+
+ let base = Instant::now();
+ let mut window = ActionWindow::<String, NonClonePayload>::default();
+ window.push(
+ "document-a".to_owned(),
+ WindowAction::Ordered(NonClonePayload(42)),
+ base,
+ );
+
+ let batch = window
+ .flush(ActionBarrier::Explicit, base)
+ .expect("ordered action should flush");
+ let mut actions = batch.into_actions();
+ assert_eq!(actions.len(), 1);
+
+ let PlannedAction::Ordered { scope, action } = actions.remove(0) else {
+ panic!("expected ordered payload");
+ };
+ assert_eq!(scope, "document-a");
+ assert_eq!(action.into_value(), NonClonePayload(42));
+}
+
+#[test]
+fn admission_can_be_consumed_to_execute_capacity_batch() {
+ let base = Instant::now();
+ let config = ActionWindowConfig::new(Duration::from_secs(1), 1).expect("valid config");
+ let mut window = ActionWindow::<u8, &'static str>::new(config);
+ window.push(1, WindowAction::Ordered("first"), base);
+
+ let admission = window.push(
+ 1,
+ WindowAction::Ordered("second"),
+ base + Duration::from_millis(10),
+ );
+
+ assert_eq!(admission.state(), AdmissionState::Rotated);
+ assert_eq!(admission.batch_id().get(), 2);
+ let ready = admission
+ .into_ready_batch()
+ .expect("capacity rotation must return the first batch");
+ assert_eq!(ready.id().get(), 1);
+ assert_eq!(ready.cause(), ActionBatchCause::Capacity);
+ assert_eq!(ready.admitted_action_count(), 1);
+ assert_eq!(ready.retained_action_count(), 1);
+}
+
+#[test]
+fn consuming_batch_preserves_all_scroll_step_metadata() {
+ let base = Instant::now();
+ let mut window = ActionWindow::<u8, ()>::default();
+ let scroll = ScrollAction {
+ position: Point::new(12.5, 17.5),
+ delta_x: -4.0,
+ delta_y: 9.0,
+ delta_mode: ScrollDeltaMode::Page,
+ modifiers: InputModifiers::ALT | InputModifiers::META,
+ };
+ window.push(7, WindowAction::Scroll(scroll.clone()), base);
+
+ let mut actions = window
+ .flush(ActionBarrier::Explicit, base)
+ .expect("batch")
+ .into_actions();
+ let PlannedAction::Scroll { scope, run } = actions.remove(0) else {
+ panic!("expected scroll run");
+ };
+
+ assert_eq!(scope, 7);
+ assert_eq!(run.len(), 1);
+ assert!(!run.is_empty());
+ assert_eq!(run.steps()[0].sequence().get(), 1);
+ assert_eq!(run.steps()[0].admitted_at(), base);
+ assert_eq!(run.steps()[0].value(), &scroll);
+}
+
+#[test]
+fn all_mouse_buttons_and_click_counts_survive_public_model() {
+ let buttons = [
+ MouseButton::Left,
+ MouseButton::Middle,
+ MouseButton::Right,
+ MouseButton::Back,
+ MouseButton::Forward,
+ ];
+
+ for (index, button) in buttons.into_iter().enumerate() {
+ let base = Instant::now();
+ let mut window = ActionWindow::<u8, ()>::default();
+ let click = ClickAction {
+ position: Point::new(index as f64, 2.0),
+ button,
+ click_count: (index + 1) as u32,
+ modifiers: InputModifiers::CONTROL,
+ };
+ window.push(1, WindowAction::Click(click.clone()), base);
+
+ let batch = window
+ .flush(ActionBarrier::Explicit, base)
+ .expect("click batch");
+ let PlannedAction::Click {
+ click: scheduled, ..
+ } = &batch.actions()[0]
+ else {
+ panic!("expected click");
+ };
+ assert_eq!(scheduled.value(), &click);
+ }
+}
+
+#[test]
+fn canceling_unknown_scope_is_a_noop_and_preserves_deadline() {
+ let base = Instant::now();
+ let mut window = ActionWindow::<String, ()>::default();
+ window.push(
+ "kept".to_owned(),
+ WindowAction::Scroll(ScrollAction::pixels(Point::default(), 0.0, 1.0)),
+ base,
+ );
+ let deadline = window.next_deadline();
+
+ assert_eq!(window.cancel_scope(&"missing".to_owned()), 0);
+ assert_eq!(window.next_deadline(), deadline);
+ assert_eq!(window.pending_admitted_action_count(), 1);
+ assert_eq!(window.pending_retained_action_count(), 1);
+ assert_eq!(window.pending_planned_action_count(), 1);
+}
+
+#[test]
+fn click_replacement_reports_public_compaction_without_capacity_rotation() {
+ let base = Instant::now();
+ let config = ActionWindowConfig::new(Duration::from_secs(1), 1).expect("valid config");
+ let mut window = ActionWindow::<u8, ()>::new(config);
+ window.push(
+ 1,
+ WindowAction::Click(ClickAction::new(Point::new(1.0, 1.0), MouseButton::Left, 1)),
+ base,
+ );
+
+ let replacement = window.push(
+ 1,
+ WindowAction::Click(ClickAction::new(Point::new(2.0, 2.0), MouseButton::Left, 2)),
+ base + Duration::from_millis(1),
+ );
+
+ assert_eq!(replacement.state(), AdmissionState::Joined);
+ assert_eq!(replacement.compaction(), ActionCompaction::ReplacedClick);
+ assert!(replacement.ready_batch().is_none());
+}