Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
feat: add browser action batching model
ldm04694c71a8492
diff --git a/Cargo.lock b/Cargo.lockindex 4430e2439..bb55af6b8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1978,6 +1978,10 @@ dependencies = ["url",]+[[package]]+name = "moli-action-window"+version = "0.1.0"+[[package]]name = "moli-bounded-buffer"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 9e3855530..ba68481bd 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -2,6 +2,7 @@resolver = "3"members = ["moli",+ "moli-action-window","moli-bounded-buffer","moli-bounded-json","moli-broadcast-channel",diff --git a/moli-action-window/Cargo.toml b/moli-action-window/Cargo.tomlnew file mode 100644index 000000000..3eb3dc02d--- /dev/null+++ b/moli-action-window/Cargo.toml@@ -0,0 +1,8 @@+[package]+license.workspace = true+name = "moli-action-window"+version = "0.1.0"+edition = "2024"++[lints]+workspace = truediff --git a/moli-action-window/README.md b/moli-action-window/README.mdnew file mode 100644index 000000000..5ceb0db5f--- /dev/null+++ b/moli-action-window/README.md@@ -0,0 +1,47 @@+# moli-action-window++`moli-action-window` models delayed, compacted browser actions without owning a+timer or depending on a renderer.++The first action opens a one-shot window. Its deadline is fixed at+`first_action_time + window_duration`; later actions join that window without+moving the deadline. Once a batch is taken, the queue becomes idle and no new+deadline exists until another action arrives.++Screenshot, screencast, and other read barriers call `flush` before reading+rendered state. This immediately returns the current batch and cancels its old+deadline. A later action starts a fresh window.++Compaction is deliberately semantic:++- adjacent scrolls in the same scope become one ordered `ScrollRun`;+- only the latest complete logical click in a scope is retained;+- ordered/opaque actions are never discarded;+- order between surviving action kinds and scopes is preserved.++A scroll run keeps every step instead of summing deltas. Applying each step in+order preserves clamping, scroll snap, delta modes, and target changes. The+host applies the whole returned batch and then performs derived work such as+IntersectionObserver delivery, layout, and rendering once.++The crate is synchronous and uses caller-provided `Instant`s. The Page/event+loop remains responsible for arming one timer for `next_deadline`, executing+ready batches, and flushing before capture barriers.++The generic scope should identify the smallest independently ordered input+target (for example a page/document pair). Clicks are replaced only within the+same scope, and scroll runs never cross scope boundaries.++Typical host flow is:++1. Call `push`. If the admission contains a ready batch, execute that older+ batch first.+2. Replace the Page timer with `next_deadline`, or cancel it when the result is+ `None`.+3. On timer wake, call `take_due`; execute the returned actions in order and+ commit derived rendering work once.+4. Before screenshot/screencast, call `flush`, execute the returned batch and+ its one derived-work commit, then capture.++All timestamps supplied to one queue must come from the same monotonic clock+and be admitted in event-loop order.diff --git a/moli-action-window/src/action.rs b/moli-action-window/src/action.rsnew file mode 100644index 000000000..a2871357c--- /dev/null+++ b/moli-action-window/src/action.rs@@ -0,0 +1,135 @@+use std::ops::{BitOr, BitOrAssign};++/// A viewport-space input coordinate.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct Point {+ pub x: f64,+ pub y: f64,+}++impl Point {+ #[must_use]+ pub const fn new(x: f64, y: f64) -> Self {+ Self { x, y }+ }+}++/// Modifier keys active for an input action.+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]+pub struct InputModifiers(u8);++impl InputModifiers {+ pub const NONE: Self = Self(0);+ pub const ALT: Self = Self(1 << 0);+ pub const CONTROL: Self = Self(1 << 1);+ pub const META: Self = Self(1 << 2);+ pub const SHIFT: Self = Self(1 << 3);++ #[must_use]+ pub const fn from_bits(bits: u8) -> Self {+ Self(bits)+ }++ #[must_use]+ pub const fn bits(self) -> u8 {+ self.0+ }++ #[must_use]+ pub const fn contains(self, other: Self) -> bool {+ self.0 & other.0 == other.0+ }+}++impl BitOr for InputModifiers {+ type Output = Self;++ fn bitor(self, rhs: Self) -> Self::Output {+ Self(self.0 | rhs.0)+ }+}++impl BitOrAssign for InputModifiers {+ fn bitor_assign(&mut self, rhs: Self) {+ self.0 |= rhs.0;+ }+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum ScrollDeltaMode {+ Pixel,+ Line,+ Page,+}++/// One scroll step.+///+/// Steps are retained in order inside a scroll run. Deltas are not summed,+/// because doing so can change clamping and scroll-snap behavior.+#[derive(Clone, Debug, PartialEq)]+pub struct ScrollAction {+ pub position: Point,+ pub delta_x: f64,+ pub delta_y: f64,+ pub delta_mode: ScrollDeltaMode,+ pub modifiers: InputModifiers,+}++impl ScrollAction {+ #[must_use]+ pub const fn pixels(position: Point, delta_x: f64, delta_y: f64) -> Self {+ Self {+ position,+ delta_x,+ delta_y,+ delta_mode: ScrollDeltaMode::Pixel,+ modifiers: InputModifiers::NONE,+ }+ }+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum MouseButton {+ Left,+ Middle,+ Right,+ Back,+ Forward,+}++/// One complete logical click.+///+/// This must represent the completed press/release gesture. Raw pointer-down+/// and pointer-up events must not be admitted independently, since click+/// compaction intentionally keeps only the latest click in a scope.+#[derive(Clone, Debug, PartialEq)]+pub struct ClickAction {+ pub position: Point,+ pub button: MouseButton,+ pub click_count: u32,+ pub modifiers: InputModifiers,+}++impl ClickAction {+ #[must_use]+ pub const fn new(position: Point, button: MouseButton, click_count: u32) -> Self {+ Self {+ position,+ button,+ click_count,+ modifiers: InputModifiers::NONE,+ }+ }+}++/// An action admitted to a batching window.+///+/// `Ordered` is an extension point for renderer-specific actions. Ordered+/// actions are retained verbatim and act as ordering boundaries between scroll+/// runs.+#[derive(Clone, Debug, PartialEq)]+pub enum WindowAction<O = ()> {+ Scroll(ScrollAction),+ Click(ClickAction),+ Ordered(O),+}diff --git a/moli-action-window/src/batch.rs b/moli-action-window/src/batch.rsnew file mode 100644index 000000000..ec4633b6e--- /dev/null+++ b/moli-action-window/src/batch.rs@@ -0,0 +1,247 @@+use std::time::Instant;++use crate::{ClickAction, ScrollAction};++#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]+pub struct ActionBatchId(u64);++impl ActionBatchId {+ #[must_use]+ pub const fn get(self) -> u64 {+ self.0+ }++ pub(crate) const fn new(value: u64) -> Self {+ Self(value)+ }+}++#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]+pub struct ActionSequence(u64);++impl ActionSequence {+ #[must_use]+ pub const fn get(self) -> u64 {+ self.0+ }++ pub(crate) const fn new(value: u64) -> Self {+ Self(value)+ }+}++/// Why a pending window was made ready for execution.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum ActionBatchCause {+ Deadline,+ Barrier(ActionBarrier),+ Capacity,+}++/// A read or synchronization operation that requires pending actions first.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum ActionBarrier {+ Screenshot,+ Screencast,+ Explicit,+}++/// One retained input with its original admission metadata.+#[derive(Clone, Debug, PartialEq)]+pub struct ScheduledAction<T> {+ sequence: ActionSequence,+ admitted_at: Instant,+ value: T,+}++impl<T> ScheduledAction<T> {+ pub(crate) const fn new(sequence: ActionSequence, admitted_at: Instant, value: T) -> Self {+ Self {+ sequence,+ admitted_at,+ value,+ }+ }++ #[must_use]+ pub const fn sequence(&self) -> ActionSequence {+ self.sequence+ }++ #[must_use]+ pub const fn admitted_at(&self) -> Instant {+ self.admitted_at+ }++ #[must_use]+ pub const fn value(&self) -> &T {+ &self.value+ }++ #[must_use]+ pub fn into_value(self) -> T {+ self.value+ }+}++/// Adjacent scroll steps for the same scope.+#[derive(Clone, Debug, PartialEq)]+pub struct ScrollRun {+ steps: Vec<ScheduledAction<ScrollAction>>,+}++impl ScrollRun {+ pub(crate) fn new(step: ScheduledAction<ScrollAction>) -> Self {+ Self { steps: vec![step] }+ }++ pub(crate) fn push(&mut self, step: ScheduledAction<ScrollAction>) {+ self.steps.push(step);+ }++ pub(crate) fn append(&mut self, other: &mut Self) {+ self.steps.append(&mut other.steps);+ }++ #[must_use]+ pub fn steps(&self) -> &[ScheduledAction<ScrollAction>] {+ &self.steps+ }++ #[must_use]+ pub const fn len(&self) -> usize {+ self.steps.len()+ }++ #[must_use]+ pub const fn is_empty(&self) -> bool {+ self.steps.is_empty()+ }+}++/// A compacted unit in execution order.+#[derive(Clone, Debug, PartialEq)]+pub enum PlannedAction<S, O = ()> {+ Scroll {+ scope: S,+ run: ScrollRun,+ },+ Click {+ scope: S,+ click: ScheduledAction<ClickAction>,+ },+ Ordered {+ scope: S,+ action: ScheduledAction<O>,+ },+}++impl<S, O> PlannedAction<S, O> {+ #[must_use]+ pub const fn scope(&self) -> &S {+ match self {+ Self::Scroll { scope, .. }+ | Self::Click { scope, .. }+ | Self::Ordered { scope, .. } => scope,+ }+ }++ pub(crate) fn retained_action_count(&self) -> usize {+ match self {+ Self::Scroll { run, .. } => run.len(),+ Self::Click { .. } | Self::Ordered { .. } => 1,+ }+ }+}++/// A closed window ready for ordered execution followed by one derived-work+/// commit.+#[derive(Clone, Debug, PartialEq)]+pub struct ActionBatch<S, O = ()> {+ id: ActionBatchId,+ opened_at: Instant,+ deadline: Instant,+ released_at: Instant,+ cause: ActionBatchCause,+ admitted_action_count: usize,+ retained_action_count: usize,+ actions: Vec<PlannedAction<S, O>>,+}++impl<S, O> ActionBatch<S, O> {+ pub(crate) const fn new(+ id: ActionBatchId,+ opened_at: Instant,+ deadline: Instant,+ released_at: Instant,+ cause: ActionBatchCause,+ admitted_action_count: usize,+ retained_action_count: usize,+ actions: Vec<PlannedAction<S, O>>,+ ) -> Self {+ Self {+ id,+ opened_at,+ deadline,+ released_at,+ cause,+ admitted_action_count,+ retained_action_count,+ actions,+ }+ }++ #[must_use]+ pub const fn id(&self) -> ActionBatchId {+ self.id+ }++ #[must_use]+ pub const fn opened_at(&self) -> Instant {+ self.opened_at+ }++ #[must_use]+ pub const fn deadline(&self) -> Instant {+ self.deadline+ }++ /// The time at which the caller observed the batch as ready.+ #[must_use]+ pub const fn released_at(&self) -> Instant {+ self.released_at+ }++ #[must_use]+ pub const fn cause(&self) -> ActionBatchCause {+ self.cause+ }++ /// Number of actions admitted, including clicks later superseded.+ #[must_use]+ pub const fn admitted_action_count(&self) -> usize {+ self.admitted_action_count+ }++ /// Number of retained logical inputs. Every scroll step counts once.+ #[must_use]+ pub const fn retained_action_count(&self) -> usize {+ self.retained_action_count+ }++ /// Number of compacted execution units. A scroll run counts once.+ #[must_use]+ pub const fn planned_action_count(&self) -> usize {+ self.actions.len()+ }++ #[must_use]+ pub fn actions(&self) -> &[PlannedAction<S, O>] {+ &self.actions+ }++ #[must_use]+ pub fn into_actions(self) -> Vec<PlannedAction<S, O>> {+ self.actions+ }+}diff --git a/moli-action-window/src/lib.rs b/moli-action-window/src/lib.rsnew file mode 100644index 000000000..d80b2d1a9--- /dev/null+++ b/moli-action-window/src/lib.rs@@ -0,0 +1,29 @@+//! One-shot batching and semantic compaction for browser actions.+//!+//! The queue owns no timer. A host admits actions with [`ActionWindow::push`],+//! arms at most one timer for [`ActionWindow::next_deadline`], and obtains work+//! with [`ActionWindow::take_due`]. Read barriers such as screenshots call+//! [`ActionWindow::flush`] first.+//!+//! A returned [`ActionBatch`] is an execution boundary: apply all of its+//! [`PlannedAction`] values in order, then commit derived work (for example+//! IntersectionObserver delivery, layout, and rendering) once.++mod action;+mod batch;+mod window;++pub use action::{+ ClickAction, InputModifiers, MouseButton, Point, ScrollAction, ScrollDeltaMode, WindowAction,+};+pub use batch::{+ ActionBarrier, ActionBatch, ActionBatchCause, ActionBatchId, ActionSequence, PlannedAction,+ ScheduledAction, ScrollRun,+};+pub use window::{+ ActionAdmission, ActionCompaction, ActionWindow, ActionWindowConfig, ActionWindowConfigError,+ AdmissionState,+};++#[cfg(test)]+mod tests;diff --git a/moli-action-window/src/tests.rs b/moli-action-window/src/tests.rsnew file mode 100644index 000000000..7fe8b558a--- /dev/null+++ b/moli-action-window/src/tests.rs@@ -0,0 +1,556 @@+use std::time::{Duration, Instant};++use crate::{+ ActionBarrier, ActionBatchCause, ActionCompaction, ActionWindow, ActionWindowConfig,+ ActionWindowConfigError, AdmissionState, ClickAction, InputModifiers, MouseButton,+ PlannedAction, Point, ScrollAction, WindowAction,+};++const SCOPE_A: u8 = 1;+const SCOPE_B: u8 = 2;++fn at(base: Instant, milliseconds: u64) -> Instant {+ base + Duration::from_millis(milliseconds)+}++fn scroll(delta_y: f64) -> WindowAction<&'static str> {+ WindowAction::Scroll(ScrollAction::pixels(Point::new(10.0, 20.0), 0.0, delta_y))+}++fn click(x: f64) -> WindowAction<&'static str> {+ WindowAction::Click(ClickAction::new(Point::new(x, 20.0), MouseButton::Left, 1))+}++fn ordered(value: &'static str) -> WindowAction<&'static str> {+ WindowAction::Ordered(value)+}++fn default_window() -> ActionWindow<u8, &'static str> {+ ActionWindow::default()+}++fn scroll_deltas(action: &PlannedAction<u8, &'static str>) -> Vec<f64> {+ let PlannedAction::Scroll { run, .. } = action else {+ panic!("expected scroll run");+ };+ run.steps()+ .iter()+ .map(|step| step.value().delta_y)+ .collect()+}++#[test]+fn default_config_is_a_one_second_bounded_window() {+ let config = ActionWindowConfig::default();+ assert_eq!(config.duration(), Duration::from_secs(1));+ assert_eq!(config.max_retained_actions(), 4_096);+}++#[test]+fn config_rejects_zero_duration() {+ assert_eq!(+ ActionWindowConfig::new(Duration::ZERO, 1),+ Err(ActionWindowConfigError::ZeroDuration)+ );+}++#[test]+fn config_rejects_zero_capacity() {+ assert_eq!(+ ActionWindowConfig::new(Duration::from_secs(1), 0),+ Err(ActionWindowConfigError::ZeroCapacity)+ );+}++#[test]+fn idle_window_has_no_timer_or_pending_work() {+ let base = Instant::now();+ let mut window = default_window();++ assert!(window.is_idle());+ assert_eq!(window.next_deadline(), None);+ assert_eq!(window.pending_admitted_action_count(), 0);+ assert_eq!(window.pending_retained_action_count(), 0);+ assert_eq!(window.pending_planned_action_count(), 0);+ assert!(window.take_due(at(base, 10_000)).is_none());+}++#[test]+fn first_action_opens_one_shot_window() {+ let base = Instant::now();+ let mut window = default_window();++ let admission = window.push(SCOPE_A, scroll(10.0), base);++ assert_eq!(admission.state(), AdmissionState::Opened);+ assert_eq!(admission.batch_id().get(), 1);+ assert_eq!(admission.deadline(), at(base, 1_000));+ assert_eq!(admission.compaction(), ActionCompaction::Added);+ assert!(admission.ready_batch().is_none());+ assert_eq!(window.next_deadline(), Some(at(base, 1_000)));+}++#[test]+fn later_actions_join_without_moving_fixed_deadline() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);++ let second = window.push(SCOPE_A, scroll(20.0), at(base, 400));+ let third = window.push(SCOPE_A, scroll(30.0), at(base, 900));++ assert_eq!(second.state(), AdmissionState::Joined);+ assert_eq!(third.state(), AdmissionState::Joined);+ assert_eq!(second.deadline(), at(base, 1_000));+ assert_eq!(third.deadline(), at(base, 1_000));+ assert_eq!(window.next_deadline(), Some(at(base, 1_000)));+}++#[test]+fn batch_is_not_due_before_deadline_and_is_due_at_deadline() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);++ assert!(window.take_due(at(base, 999)).is_none());+ let batch = window+ .take_due(at(base, 1_000))+ .expect("batch should be due at its deadline");++ assert_eq!(batch.cause(), ActionBatchCause::Deadline);+ assert_eq!(batch.opened_at(), base);+ assert_eq!(batch.deadline(), at(base, 1_000));+ assert_eq!(batch.released_at(), at(base, 1_000));+ assert!(window.is_idle());+ assert_eq!(window.next_deadline(), None);+}++#[test]+fn action_after_idle_period_starts_fresh_window_from_its_arrival() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ window.take_due(at(base, 1_000)).expect("first batch");++ let admission = window.push(SCOPE_A, scroll(20.0), at(base, 1_600));++ assert_eq!(admission.state(), AdmissionState::Opened);+ assert_eq!(admission.batch_id().get(), 2);+ assert_eq!(admission.deadline(), at(base, 2_600));+}++#[test]+fn screenshot_flushes_immediately_and_resets_deadline() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ window.push(SCOPE_A, scroll(20.0), at(base, 400));++ let batch = window+ .flush(ActionBarrier::Screenshot, at(base, 600))+ .expect("screenshot should flush pending work");++ assert_eq!(+ batch.cause(),+ ActionBatchCause::Barrier(ActionBarrier::Screenshot)+ );+ assert_eq!(batch.deadline(), at(base, 1_000));+ assert_eq!(batch.released_at(), at(base, 600));+ assert!(window.is_idle());+ assert_eq!(window.next_deadline(), None);++ let next = window.push(SCOPE_A, scroll(30.0), at(base, 700));+ assert_eq!(next.state(), AdmissionState::Opened);+ assert_eq!(next.deadline(), at(base, 1_700));++ // A timer wake already queued for the canceled 1.0s deadline is harmless.+ assert!(window.take_due(at(base, 1_000)).is_none());+ assert_eq!(window.next_deadline(), Some(at(base, 1_700)));+}++#[test]+fn screencast_flush_uses_its_own_barrier_cause() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);++ let batch = window+ .flush(ActionBarrier::Screencast, at(base, 200))+ .expect("screencast should flush pending work");++ assert_eq!(+ batch.cause(),+ ActionBatchCause::Barrier(ActionBarrier::Screencast)+ );+}++#[test]+fn barrier_while_idle_does_not_create_a_window() {+ let base = Instant::now();+ let mut window = default_window();++ assert!(window.flush(ActionBarrier::Screenshot, base).is_none());+ assert!(window.is_idle());+ assert_eq!(window.next_deadline(), None);+}++#[test]+fn late_action_rotates_due_batch_and_opens_fresh_window() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);++ let admission = window.push(SCOPE_A, scroll(20.0), at(base, 1_200));+ let ready = admission+ .ready_batch()+ .expect("late admission should return old batch");++ assert_eq!(admission.state(), AdmissionState::Rotated);+ assert_eq!(ready.id().get(), 1);+ assert_eq!(ready.cause(), ActionBatchCause::Deadline);+ assert_eq!(ready.released_at(), at(base, 1_200));+ assert_eq!(admission.batch_id().get(), 2);+ assert_eq!(admission.deadline(), at(base, 2_200));+ assert_eq!(window.pending_retained_action_count(), 1);+}++#[test]+fn action_exactly_at_deadline_belongs_to_next_window() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);++ let admission = window.push(SCOPE_A, scroll(20.0), at(base, 1_000));++ assert_eq!(admission.state(), AdmissionState::Rotated);+ assert_eq!(+ scroll_deltas(&admission.ready_batch().expect("old batch").actions()[0]),+ vec![10.0]+ );+ assert_eq!(admission.deadline(), at(base, 2_000));+}++#[test]+fn adjacent_scrolls_form_one_ordered_run_without_summing() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ let second = window.push(SCOPE_A, scroll(-3.0), at(base, 100));+ let third = window.push(SCOPE_A, scroll(20.0), at(base, 200));++ assert_eq!(second.compaction(), ActionCompaction::AppendedToScrollRun);+ assert_eq!(third.compaction(), ActionCompaction::AppendedToScrollRun);+ let batch = window.take_due(at(base, 1_000)).expect("batch");+ assert_eq!(batch.admitted_action_count(), 3);+ assert_eq!(batch.retained_action_count(), 3);+ assert_eq!(batch.planned_action_count(), 1);+ assert_eq!(scroll_deltas(&batch.actions()[0]), vec![10.0, -3.0, 20.0]);++ let PlannedAction::Scroll { run, .. } = &batch.actions()[0] else {+ panic!("expected scroll run");+ };+ assert_eq!(run.steps()[0].sequence().get(), 1);+ assert_eq!(run.steps()[1].sequence().get(), 2);+ assert_eq!(run.steps()[2].sequence().get(), 3);+ assert_eq!(run.steps()[1].admitted_at(), at(base, 100));+}++#[test]+fn scroll_run_retains_each_steps_mode_position_and_modifiers() {+ let base = Instant::now();+ let mut window = default_window();+ let first = ScrollAction::pixels(Point::new(1.0, 2.0), 3.0, 4.0);+ let second = ScrollAction {+ position: Point::new(5.0, 6.0),+ delta_x: 7.0,+ delta_y: 8.0,+ delta_mode: crate::ScrollDeltaMode::Line,+ modifiers: InputModifiers::CONTROL | InputModifiers::SHIFT,+ };+ window.push(SCOPE_A, WindowAction::Scroll(first.clone()), base);+ window.push(SCOPE_A, WindowAction::Scroll(second.clone()), at(base, 100));++ let batch = window.take_due(at(base, 1_000)).expect("batch");+ let PlannedAction::Scroll { run, .. } = &batch.actions()[0] else {+ panic!("expected scroll run");+ };++ assert_eq!(run.steps()[0].value(), &first);+ assert_eq!(run.steps()[1].value(), &second);+}++#[test]+fn scrolls_in_different_scopes_are_separate_runs() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ window.push(SCOPE_B, scroll(20.0), at(base, 100));+ window.push(SCOPE_A, scroll(30.0), at(base, 200));++ let batch = window.take_due(at(base, 1_000)).expect("batch");++ assert_eq!(batch.planned_action_count(), 3);+ assert_eq!(*batch.actions()[0].scope(), SCOPE_A);+ assert_eq!(*batch.actions()[1].scope(), SCOPE_B);+ assert_eq!(*batch.actions()[2].scope(), SCOPE_A);+}++#[test]+fn latest_click_replaces_older_click_in_same_scope() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, click(10.0), base);+ let replacement = window.push(SCOPE_A, click(30.0), at(base, 300));++ assert_eq!(replacement.compaction(), ActionCompaction::ReplacedClick);+ let batch = window.take_due(at(base, 1_000)).expect("batch");+ assert_eq!(batch.admitted_action_count(), 2);+ assert_eq!(batch.retained_action_count(), 1);+ assert_eq!(batch.planned_action_count(), 1);+ let PlannedAction::Click { click, .. } = &batch.actions()[0] else {+ panic!("expected click");+ };+ assert_eq!(click.value().position.x, 30.0);+ assert_eq!(click.sequence().get(), 2);+ assert_eq!(click.admitted_at(), at(base, 300));+}++#[test]+fn clicks_in_different_scopes_do_not_replace_each_other() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, click(10.0), base);+ window.push(SCOPE_B, click(20.0), at(base, 100));++ let batch = window.take_due(at(base, 1_000)).expect("batch");++ assert_eq!(batch.retained_action_count(), 2);+ assert_eq!(batch.planned_action_count(), 2);+ assert_eq!(*batch.actions()[0].scope(), SCOPE_A);+ assert_eq!(*batch.actions()[1].scope(), SCOPE_B);+}++#[test]+fn surviving_click_keeps_scroll_runs_separated() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ window.push(SCOPE_A, click(10.0), at(base, 100));+ window.push(SCOPE_A, scroll(20.0), at(base, 200));++ let batch = window.take_due(at(base, 1_000)).expect("batch");++ assert_eq!(batch.planned_action_count(), 3);+ assert!(matches!(batch.actions()[0], PlannedAction::Scroll { .. }));+ assert!(matches!(batch.actions()[1], PlannedAction::Click { .. }));+ assert!(matches!(batch.actions()[2], PlannedAction::Scroll { .. }));+}++#[test]+fn replacing_click_reorders_it_and_joins_newly_adjacent_scroll_runs() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ window.push(SCOPE_A, click(10.0), at(base, 100));+ window.push(SCOPE_A, scroll(20.0), at(base, 200));+ window.push(SCOPE_A, click(40.0), at(base, 300));++ let batch = window.take_due(at(base, 1_000)).expect("batch");++ assert_eq!(batch.admitted_action_count(), 4);+ assert_eq!(batch.retained_action_count(), 3);+ assert_eq!(batch.planned_action_count(), 2);+ assert_eq!(scroll_deltas(&batch.actions()[0]), vec![10.0, 20.0]);+ let PlannedAction::Click { click, .. } = &batch.actions()[1] else {+ panic!("expected latest click last");+ };+ assert_eq!(click.value().position.x, 40.0);+}++#[test]+fn ordered_actions_are_never_compacted_and_preserve_cross_type_order() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ window.push(SCOPE_A, ordered("key-a"), at(base, 100));+ window.push(SCOPE_A, scroll(20.0), at(base, 200));++ let batch = window.take_due(at(base, 1_000)).expect("batch");++ assert_eq!(batch.planned_action_count(), 3);+ assert!(matches!(batch.actions()[0], PlannedAction::Scroll { .. }));+ let PlannedAction::Ordered { action, .. } = &batch.actions()[1] else {+ panic!("expected ordered action");+ };+ assert_eq!(*action.value(), "key-a");+ assert!(matches!(batch.actions()[2], PlannedAction::Scroll { .. }));+}++#[test]+fn modifiers_are_a_composable_bit_set() {+ let modifiers = InputModifiers::CONTROL | InputModifiers::SHIFT;++ assert!(modifiers.contains(InputModifiers::CONTROL));+ assert!(modifiers.contains(InputModifiers::SHIFT));+ assert!(!modifiers.contains(InputModifiers::ALT));+ assert_eq!(modifiers.bits(), 0b1010);+}++#[test]+fn capacity_releases_old_batch_and_starts_new_window() {+ let base = Instant::now();+ let config = ActionWindowConfig::new(Duration::from_secs(1), 2).expect("valid config");+ let mut window = ActionWindow::<u8, &'static str>::new(config);+ window.push(SCOPE_A, scroll(10.0), base);+ window.push(SCOPE_A, scroll(20.0), at(base, 100));++ let admission = window.push(SCOPE_A, scroll(30.0), at(base, 200));+ let ready = admission.ready_batch().expect("capacity batch");++ assert_eq!(admission.state(), AdmissionState::Rotated);+ assert_eq!(ready.cause(), ActionBatchCause::Capacity);+ assert_eq!(ready.retained_action_count(), 2);+ assert_eq!(admission.deadline(), at(base, 1_200));+ assert_eq!(window.pending_retained_action_count(), 1);+}++#[test]+fn click_replacement_is_allowed_at_capacity() {+ 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(SCOPE_A, click(10.0), base);++ let admission = window.push(SCOPE_A, click(20.0), at(base, 100));++ assert_eq!(admission.state(), AdmissionState::Joined);+ assert_eq!(admission.compaction(), ActionCompaction::ReplacedClick);+ assert!(admission.ready_batch().is_none());+ assert_eq!(window.pending_admitted_action_count(), 2);+ assert_eq!(window.pending_retained_action_count(), 1);+}++#[test]+fn deadline_rotation_takes_precedence_over_capacity_rotation() {+ 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(SCOPE_A, scroll(10.0), base);++ let admission = window.push(SCOPE_A, scroll(20.0), at(base, 1_000));++ assert_eq!(+ admission.ready_batch().expect("old batch").cause(),+ ActionBatchCause::Deadline+ );+}++#[test]+fn clear_drops_work_and_cancels_deadline() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ window.push(SCOPE_A, click(10.0), at(base, 100));++ assert_eq!(window.clear(), 2);+ assert_eq!(window.clear(), 0);+ assert!(window.is_idle());+ assert_eq!(window.next_deadline(), None);+}++#[test]+fn cancel_scope_keeps_other_scope_and_original_deadline() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ window.push(SCOPE_A, click(10.0), at(base, 100));+ window.push(SCOPE_B, scroll(20.0), at(base, 200));++ assert_eq!(window.cancel_scope(&SCOPE_A), 2);+ assert_eq!(window.next_deadline(), Some(at(base, 1_000)));+ assert_eq!(window.pending_retained_action_count(), 1);+ let batch = window.take_due(at(base, 1_000)).expect("scope B batch");+ assert_eq!(*batch.actions()[0].scope(), SCOPE_B);+}++#[test]+fn canceling_last_scope_returns_to_idle() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);++ assert_eq!(window.cancel_scope(&SCOPE_A), 1);+ assert_eq!(window.cancel_scope(&SCOPE_A), 0);+ assert!(window.is_idle());+ assert_eq!(window.next_deadline(), None);+}++#[test]+fn canceling_an_intervening_scope_normalizes_scroll_runs() {+ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ window.push(SCOPE_B, ordered("separator"), at(base, 100));+ window.push(SCOPE_A, scroll(20.0), at(base, 200));++ assert_eq!(window.cancel_scope(&SCOPE_B), 1);+ assert_eq!(window.pending_planned_action_count(), 1);+ let batch = window.take_due(at(base, 1_000)).expect("batch");+ assert_eq!(scroll_deltas(&batch.actions()[0]), vec![10.0, 20.0]);+}++#[test]+fn batch_ids_and_action_sequences_continue_across_resets() {+ let base = Instant::now();+ let mut window = default_window();+ let first = window.push(SCOPE_A, scroll(10.0), base);+ let first_batch = window+ .flush(ActionBarrier::Explicit, at(base, 100))+ .expect("first batch");+ let second = window.push(SCOPE_A, scroll(20.0), at(base, 200));+ let second_batch = window.take_due(at(base, 1_200)).expect("second batch");++ assert_eq!(first.batch_id().get(), 1);+ assert_eq!(first_batch.id().get(), 1);+ assert_eq!(second.batch_id().get(), 2);+ assert_eq!(second_batch.id().get(), 2);+ let PlannedAction::Scroll { run, .. } = &second_batch.actions()[0] else {+ panic!("expected scroll");+ };+ assert_eq!(run.steps()[0].sequence().get(), 2);+}++#[test]+fn one_batch_maps_to_many_actions_and_one_derived_work_commit() {+ #[derive(Default)]+ struct FakeRenderer {+ applied_scrolls: Vec<f64>,+ clicks: Vec<f64>,+ derived_work_commits: usize,+ }++ let base = Instant::now();+ let mut window = default_window();+ window.push(SCOPE_A, scroll(10.0), base);+ window.push(SCOPE_A, scroll(20.0), at(base, 100));+ window.push(SCOPE_A, click(30.0), at(base, 200));+ let batch = window.take_due(at(base, 1_000)).expect("batch");+ let mut renderer = FakeRenderer::default();++ for action in batch.actions() {+ match action {+ PlannedAction::Scroll { run, .. } => renderer+ .applied_scrolls+ .extend(run.steps().iter().map(|step| step.value().delta_y)),+ PlannedAction::Click { click, .. } => {+ renderer.clicks.push(click.value().position.x);+ }+ PlannedAction::Ordered { .. } => {}+ }+ }+ renderer.derived_work_commits += 1;++ assert_eq!(renderer.applied_scrolls, vec![10.0, 20.0]);+ assert_eq!(renderer.clicks, vec![30.0]);+ assert_eq!(renderer.derived_work_commits, 1);+}diff --git a/moli-action-window/src/window.rs b/moli-action-window/src/window.rsnew file mode 100644index 000000000..87c0d2df1--- /dev/null+++ b/moli-action-window/src/window.rs@@ -0,0 +1,454 @@+use std::{+ error::Error,+ fmt,+ time::{Duration, Instant},+};++use crate::{+ ActionBarrier, ActionBatch, ActionBatchCause, ActionBatchId, ActionSequence, PlannedAction,+ ScheduledAction, ScrollRun, WindowAction,+};++const DEFAULT_MAX_RETAINED_ACTIONS: usize = 4_096;++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub struct ActionWindowConfig {+ duration: Duration,+ max_retained_actions: usize,+}++impl ActionWindowConfig {+ pub fn new(+ duration: Duration,+ max_retained_actions: usize,+ ) -> Result<Self, ActionWindowConfigError> {+ if duration.is_zero() {+ return Err(ActionWindowConfigError::ZeroDuration);+ }+ if max_retained_actions == 0 {+ return Err(ActionWindowConfigError::ZeroCapacity);+ }+ Ok(Self {+ duration,+ max_retained_actions,+ })+ }++ #[must_use]+ pub const fn duration(self) -> Duration {+ self.duration+ }++ #[must_use]+ pub const fn max_retained_actions(self) -> usize {+ self.max_retained_actions+ }+}++impl Default for ActionWindowConfig {+ fn default() -> Self {+ Self {+ duration: Duration::from_secs(1),+ max_retained_actions: DEFAULT_MAX_RETAINED_ACTIONS,+ }+ }+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum ActionWindowConfigError {+ ZeroDuration,+ ZeroCapacity,+}++impl fmt::Display for ActionWindowConfigError {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::ZeroDuration => formatter.write_str("action window duration must be non-zero"),+ Self::ZeroCapacity => formatter.write_str("action window capacity must be non-zero"),+ }+ }+}++impl Error for ActionWindowConfigError {}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum ActionCompaction {+ Added,+ AppendedToScrollRun,+ ReplacedClick,+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum AdmissionState {+ Opened,+ Joined,+ Rotated,+}++/// Result of admitting an action.+///+/// `ready_batch` is present when the previous window reached its deadline or+/// capacity. The caller must execute it before the newly admitted action.+#[derive(Clone, Debug, PartialEq)]+pub struct ActionAdmission<S, O = ()> {+ state: AdmissionState,+ batch_id: ActionBatchId,+ deadline: Instant,+ compaction: ActionCompaction,+ ready_batch: Option<ActionBatch<S, O>>,+}++impl<S, O> ActionAdmission<S, O> {+ #[must_use]+ pub const fn state(&self) -> AdmissionState {+ self.state+ }++ #[must_use]+ pub const fn batch_id(&self) -> ActionBatchId {+ self.batch_id+ }++ #[must_use]+ pub const fn deadline(&self) -> Instant {+ self.deadline+ }++ #[must_use]+ pub const fn compaction(&self) -> ActionCompaction {+ self.compaction+ }++ #[must_use]+ pub const fn ready_batch(&self) -> Option<&ActionBatch<S, O>> {+ self.ready_batch.as_ref()+ }++ #[must_use]+ pub fn into_ready_batch(self) -> Option<ActionBatch<S, O>> {+ self.ready_batch+ }+}++struct PendingWindow<S, O> {+ id: ActionBatchId,+ opened_at: Instant,+ deadline: Instant,+ admitted_action_count: usize,+ retained_action_count: usize,+ actions: Vec<PlannedAction<S, O>>,+}++impl<S: PartialEq, O> PendingWindow<S, O> {+ fn retained_increment(&self, scope: &S, action: &WindowAction<O>) -> usize {+ match action {+ WindowAction::Click(_) if self.has_click(scope) => 0,+ WindowAction::Scroll(_) | WindowAction::Click(_) | WindowAction::Ordered(_) => 1,+ }+ }++ fn has_click(&self, scope: &S) -> bool {+ self.actions.iter().any(|action| {+ matches!(action, PlannedAction::Click { scope: click_scope, .. } if click_scope == scope)+ })+ }++ fn admit(+ &mut self,+ scope: S,+ action: WindowAction<O>,+ sequence: ActionSequence,+ admitted_at: Instant,+ ) -> ActionCompaction {+ self.admitted_action_count += 1;++ match action {+ WindowAction::Scroll(scroll) => {+ self.retained_action_count += 1;+ let scheduled = ScheduledAction::new(sequence, admitted_at, scroll);+ if let Some(PlannedAction::Scroll {+ scope: previous_scope,+ run,+ }) = self.actions.last_mut()+ && previous_scope == &scope+ {+ run.push(scheduled);+ ActionCompaction::AppendedToScrollRun+ } else {+ self.actions.push(PlannedAction::Scroll {+ scope,+ run: ScrollRun::new(scheduled),+ });+ ActionCompaction::Added+ }+ }+ WindowAction::Click(click) => {+ let previous = self.actions.iter().position(|action| {+ matches!(action, PlannedAction::Click { scope: click_scope, .. } if click_scope == &scope)+ });+ if let Some(index) = previous {+ self.actions.remove(index);+ self.normalize_scroll_runs();+ } else {+ self.retained_action_count += 1;+ }+ self.actions.push(PlannedAction::Click {+ scope,+ click: ScheduledAction::new(sequence, admitted_at, click),+ });+ if previous.is_some() {+ ActionCompaction::ReplacedClick+ } else {+ ActionCompaction::Added+ }+ }+ WindowAction::Ordered(action) => {+ self.retained_action_count += 1;+ self.actions.push(PlannedAction::Ordered {+ scope,+ action: ScheduledAction::new(sequence, admitted_at, action),+ });+ ActionCompaction::Added+ }+ }+ }++ fn normalize_scroll_runs(&mut self) {+ let mut normalized = Vec::with_capacity(self.actions.len());+ for action in self.actions.drain(..) {+ match action {+ PlannedAction::Scroll { scope, mut run } => {+ if let Some(PlannedAction::Scroll {+ scope: previous_scope,+ run: previous_run,+ }) = normalized.last_mut()+ && previous_scope == &scope+ {+ previous_run.append(&mut run);+ } else {+ normalized.push(PlannedAction::Scroll { scope, run });+ }+ }+ other => normalized.push(other),+ }+ }+ self.actions = normalized;+ }++ fn remove_scope(&mut self, scope: &S) -> usize {+ let before = self.retained_action_count;+ self.actions.retain(|action| action.scope() != scope);+ self.retained_action_count = self+ .actions+ .iter()+ .map(PlannedAction::retained_action_count)+ .sum();+ self.normalize_scroll_runs();+ before - self.retained_action_count+ }++ fn into_batch(self, released_at: Instant, cause: ActionBatchCause) -> ActionBatch<S, O> {+ ActionBatch::new(+ self.id,+ self.opened_at,+ self.deadline,+ released_at,+ cause,+ self.admitted_action_count,+ self.retained_action_count,+ self.actions,+ )+ }+}++/// A timer-independent, one-shot action window.+pub struct ActionWindow<S, O = ()> {+ config: ActionWindowConfig,+ next_batch_id: u64,+ next_sequence: u64,+ open: Option<PendingWindow<S, O>>,+}++impl<S, O> Default for ActionWindow<S, O> {+ fn default() -> Self {+ Self::new(ActionWindowConfig::default())+ }+}++impl<S, O> ActionWindow<S, O> {+ #[must_use]+ pub const fn new(config: ActionWindowConfig) -> Self {+ Self {+ config,+ next_batch_id: 1,+ next_sequence: 1,+ open: None,+ }+ }++ #[must_use]+ pub const fn config(&self) -> ActionWindowConfig {+ self.config+ }++ #[must_use]+ pub const fn is_idle(&self) -> bool {+ self.open.is_none()+ }++ #[must_use]+ pub fn next_deadline(&self) -> Option<Instant> {+ self.open.as_ref().map(|window| window.deadline)+ }++ #[must_use]+ pub fn pending_admitted_action_count(&self) -> usize {+ self.open+ .as_ref()+ .map_or(0, |window| window.admitted_action_count)+ }++ #[must_use]+ pub fn pending_retained_action_count(&self) -> usize {+ self.open+ .as_ref()+ .map_or(0, |window| window.retained_action_count)+ }++ #[must_use]+ pub fn pending_planned_action_count(&self) -> usize {+ self.open.as_ref().map_or(0, |window| window.actions.len())+ }++ /// Drops the pending window and returns its retained action count.+ pub fn clear(&mut self) -> usize {+ self.open+ .take()+ .map_or(0, |window| window.retained_action_count)+ }+}++impl<S: PartialEq, O> ActionWindow<S, O> {+ /// Admits an action, possibly returning an older batch that must execute+ /// first.+ pub fn push(+ &mut self,+ scope: S,+ action: WindowAction<O>,+ admitted_at: Instant,+ ) -> ActionAdmission<S, O> {+ let should_rotate = self.open.as_ref().and_then(|window| {+ if admitted_at >= window.deadline {+ Some(ActionBatchCause::Deadline)+ } else if window.retained_action_count + window.retained_increment(&scope, &action)+ > self.config.max_retained_actions+ {+ Some(ActionBatchCause::Capacity)+ } else {+ None+ }+ });++ let ready_batch = should_rotate.map(|cause| {+ self.open+ .take()+ .expect("rotation requires an open action window")+ .into_batch(admitted_at, cause)+ });++ let state = if ready_batch.is_some() {+ AdmissionState::Rotated+ } else if self.open.is_some() {+ AdmissionState::Joined+ } else {+ AdmissionState::Opened+ };++ if self.open.is_none() {+ self.open_window(admitted_at);+ }++ let sequence = self.allocate_sequence();+ let window = self.open.as_mut().expect("action window was just opened");+ let compaction = window.admit(scope, action, sequence, admitted_at);++ ActionAdmission {+ state,+ batch_id: window.id,+ deadline: window.deadline,+ compaction,+ ready_batch,+ }+ }++ /// Returns a deadline batch when `now` is at or past the fixed deadline.+ pub fn take_due(&mut self, now: Instant) -> Option<ActionBatch<S, O>> {+ if self+ .open+ .as_ref()+ .is_some_and(|window| now >= window.deadline)+ {+ self.open+ .take()+ .map(|window| window.into_batch(now, ActionBatchCause::Deadline))+ } else {+ None+ }+ }++ /// Immediately releases pending actions before a read/synchronization+ /// barrier and resets the window to idle.+ pub fn flush(&mut self, barrier: ActionBarrier, now: Instant) -> Option<ActionBatch<S, O>> {+ self.open+ .take()+ .map(|window| window.into_batch(now, ActionBatchCause::Barrier(barrier)))+ }++ /// Cancels all pending actions for a scope.+ ///+ /// If no actions remain, the old deadline is canceled and the queue+ /// returns to idle.+ pub fn cancel_scope(&mut self, scope: &S) -> usize {+ let Some(window) = self.open.as_mut() else {+ return 0;+ };+ let removed = window.remove_scope(scope);+ if window.actions.is_empty() {+ self.open = None;+ }+ removed+ }++ fn open_window(&mut self, opened_at: Instant) {+ let deadline = opened_at+ .checked_add(self.config.duration)+ .expect("action window deadline exceeds Instant's range");+ let id = self.allocate_batch_id();+ self.open = Some(PendingWindow {+ id,+ opened_at,+ deadline,+ admitted_action_count: 0,+ retained_action_count: 0,+ actions: Vec::new(),+ });+ }++ fn allocate_batch_id(&mut self) -> ActionBatchId {+ let id = ActionBatchId::new(self.next_batch_id);+ self.next_batch_id = self+ .next_batch_id+ .checked_add(1)+ .expect("action batch id exhausted");+ id+ }++ fn allocate_sequence(&mut self) -> ActionSequence {+ let sequence = ActionSequence::new(self.next_sequence);+ self.next_sequence = self+ .next_sequence+ .checked_add(1)+ .expect("action sequence exhausted");+ sequence+ }+}