Skip to content

armgit / moli

Public Imported from GitHub
0

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

refactor(history): extract pure session history state machine

ldm07e40b1728445
diff --git a/Cargo.lock b/Cargo.lock
index 711a2e81d..996d79e7b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2889,6 +2889,7 @@ dependencies = [
"moli-dom",
"moli-fetch",
"moli-parkable-image",
+ "moli-session-history",
"moli-web-mime",
"regex",
"serde",
@@ -2964,6 +2965,7 @@ dependencies = [
"moli-image",
"moli-page-types",
"moli-protocol-cdp",
+ "moli-session-history",
"moli-shared-worker",
"moli-site",
"moli-storage-key",
@@ -3111,6 +3113,7 @@ dependencies = [
"moli-protocol-cdp",
"moli-script",
"moli-selector",
+ "moli-session-history",
"moli-shared-worker",
"moli-storage-key",
"moli-storage-service",
@@ -3196,6 +3199,10 @@ dependencies = [
"url",
]
+[[package]]
+name = "moli-session-history"
+version = "0.1.0"
+
[[package]]
name = "moli-shared-worker"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index b95609f73..2cabafaad 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -47,6 +47,7 @@ members = [
"moli-protocol-server",
"moli-script",
"moli-selector",
+ "moli-session-history",
"moli-site",
"moli-shared-worker",
"moli-storage-service",
diff --git a/moli-page-types/Cargo.toml b/moli-page-types/Cargo.toml
index 13f6cfcd6..6e40b840b 100644
--- a/moli-page-types/Cargo.toml
+++ b/moli-page-types/Cargo.toml
@@ -15,6 +15,7 @@ moli-dom = { path = "../moli-dom" }
moli-disk-pool = { path = "../moli-disk-pool" }
moli-fetch = { path = "../moli-fetch" }
moli-parkable-image = { path = "../moli-parkable-image" }
+moli-session-history = { path = "../moli-session-history" }
moli-web-mime = { path = "../moli-web-mime" }
http-auth = { version = "0.1.10", default-features = false }
regex = "1.12.3"
diff --git a/moli-page-types/src/lib.rs b/moli-page-types/src/lib.rs
index 23d007dd6..035247ba0 100644
--- a/moli-page-types/src/lib.rs
+++ b/moli-page-types/src/lib.rs
@@ -13,10 +13,7 @@ mod navigator_overrides;
mod renderer_transport_memory;
mod session_history;
-pub use session_history::{
- JointSessionHistory, SessionHistoryCommit, SessionHistoryContextId, SessionHistoryEntry,
- SessionHistoryPosition, SessionHistorySeed, SessionHistoryStepId, SessionHistoryUpdate,
-};
+pub use session_history::{SessionHistoryCommit, SessionHistorySeed, SessionHistoryUpdate};
use std::{
borrow::Cow,
@@ -192,10 +189,9 @@ pub use inspector_state::{
renderer_inspector_protocol_configuration_command_from_method,
};
pub use navigation_history::{
- NavigationActivationSeed, NavigationHistoryDocumentId, NavigationHistoryEntryId,
- NavigationHistoryEntryKey, NavigationHistoryEntrySeed, NavigationHistoryMutation,
- NavigationHistorySerializedEntry, NavigationTraversalSeedCandidate, SessionHistoryUpdateKind,
- apply_child_browsing_context_javascript_url_navigation_to_entry_seed,
+ NavigationActivationSeed, NavigationHistoryEntryId, NavigationHistoryEntrySeed,
+ NavigationHistoryMutation, NavigationHistorySerializedEntry, NavigationTraversalSeedCandidate,
+ SessionHistoryUpdateKind, apply_child_browsing_context_javascript_url_navigation_to_entry_seed,
apply_child_browsing_context_navigation_to_entry_seed,
child_browsing_context_single_entry_seed, cross_document_navigation_seed,
initial_navigation_history_seed, reload_navigation_seed,
diff --git a/moli-page-types/src/navigation_history.rs b/moli-page-types/src/navigation_history.rs
index 2147b66cf..bd32d135d 100644
--- a/moli-page-types/src/navigation_history.rs
+++ b/moli-page-types/src/navigation_history.rs
@@ -1,43 +1,8 @@
+use moli_session_history::{NavigationHistoryDocumentId, NavigationHistoryEntryKey};
use std::sync::atomic::{AtomicU64, Ordering};
use url::Url;
-static NEXT_NAVIGATION_HISTORY_DOCUMENT_ID: AtomicU64 = AtomicU64::new(1);
static NEXT_NAVIGATION_HISTORY_ENTRY_ID: AtomicU64 = AtomicU64::new(1);
-static NEXT_NAVIGATION_HISTORY_ENTRY_KEY: AtomicU64 = AtomicU64::new(1);
-
-/// Opaque identity shared by session-history entries that belong to the same
-/// `Document`.
-///
-/// The serialized token is carried through the renderer's hidden Navigation
-/// slots, but its contents have no meaning. In particular, callers must not
-/// derive a new identity from a URL, a history index, or a previous token.
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub struct NavigationHistoryDocumentId(String);
-
-impl NavigationHistoryDocumentId {
- pub fn allocate() -> Self {
- allocate_navigation_history_document_id(&NEXT_NAVIGATION_HISTORY_DOCUMENT_ID)
- }
-
- /// Restores an identity previously stored in a renderer-owned runtime
- /// slot. Equality remains opaque; the token is never parsed.
- pub fn from_serialized(token: String) -> Self {
- Self(token)
- }
-
- pub fn as_str(&self) -> &str {
- &self.0
- }
-}
-
-fn allocate_navigation_history_document_id(counter: &AtomicU64) -> NavigationHistoryDocumentId {
- let raw = counter
- .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
- current.checked_add(1)
- })
- .expect("Navigation History Document id allocator exhausted");
- NavigationHistoryDocumentId(format!("document-{raw}"))
-}
/// Opaque identity for one Navigation API entry incarnation.
///
@@ -79,49 +44,6 @@ fn allocate_navigation_history_entry_id(counter: &AtomicU64) -> NavigationHistor
NavigationHistoryEntryId(format!("entry-{raw}"))
}
-/// Opaque identity for one session-history slot exposed to Navigation API.
-///
-/// Same-origin replacement retains the key; push and cross-origin
-/// replacement allocate a fresh key. The token is never derived from a URL,
-/// history index, or Document id.
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub struct NavigationHistoryEntryKey(String);
-
-impl NavigationHistoryEntryKey {
- pub fn allocate() -> Self {
- allocate_navigation_history_entry_key(&NEXT_NAVIGATION_HISTORY_ENTRY_KEY)
- }
-
- pub fn from_serialized(token: String) -> Self {
- Self(token)
- }
-
- pub fn as_str(&self) -> &str {
- &self.0
- }
-
- fn is_empty(&self) -> bool {
- self.0.is_empty()
- }
-}
-
-impl std::ops::Deref for NavigationHistoryEntryKey {
- type Target = str;
-
- fn deref(&self) -> &Self::Target {
- self.as_str()
- }
-}
-
-fn allocate_navigation_history_entry_key(counter: &AtomicU64) -> NavigationHistoryEntryKey {
- let raw = counter
- .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
- current.checked_add(1)
- })
- .expect("Navigation History entry key allocator exhausted");
- NavigationHistoryEntryKey(format!("key-{raw}"))
-}
-
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NavigationHistorySerializedEntry {
pub url: String,
@@ -742,16 +664,6 @@ mod tests {
);
}
- #[test]
- fn document_id_allocator_rejects_exhaustion_without_wrapping() {
- let counter = AtomicU64::new(u64::MAX);
- let exhausted =
- std::panic::catch_unwind(|| allocate_navigation_history_document_id(&counter));
-
- assert!(exhausted.is_err());
- assert_eq!(counter.load(Ordering::Relaxed), u64::MAX);
- }
-
#[test]
fn entry_identity_allocators_reject_exhaustion_without_wrapping() {
let id_counter = AtomicU64::new(u64::MAX);
@@ -759,12 +671,6 @@ mod tests {
std::panic::catch_unwind(|| allocate_navigation_history_entry_id(&id_counter));
assert!(id_exhausted.is_err());
assert_eq!(id_counter.load(Ordering::Relaxed), u64::MAX);
-
- let key_counter = AtomicU64::new(u64::MAX);
- let key_exhausted =
- std::panic::catch_unwind(|| allocate_navigation_history_entry_key(&key_counter));
- assert!(key_exhausted.is_err());
- assert_eq!(key_counter.load(Ordering::Relaxed), u64::MAX);
}
#[test]
diff --git a/moli-page-types/src/session_history.rs b/moli-page-types/src/session_history.rs
index e9ecb9de2..319bf276e 100644
--- a/moli-page-types/src/session_history.rs
+++ b/moli-page-types/src/session_history.rs
@@ -1,81 +1,8 @@
-//! The history of a traversable, independent of any Document's Navigation API
-//! view. A step records the active entry of each participating browsing context.
-//! Indices are positions, never identities: pushing after traversal discards the
-//! forward steps, whereas replacement preserves the current step.
+//! Seeds and committed updates exchanged across page/renderer boundaries.
-use std::collections::BTreeMap;
-use std::sync::atomic::{AtomicU64, Ordering};
-
-use crate::{NavigationHistoryDocumentId, NavigationHistoryEntryKey};
-
-static NEXT_CONTEXT: AtomicU64 = AtomicU64::new(1);
-static NEXT_STEP: AtomicU64 = AtomicU64::new(1);
-
-fn allocate(counter: &AtomicU64) -> u64 {
- counter
- .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
- value.checked_add(1)
- })
- .expect("session history identity allocator exhausted")
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
-pub struct SessionHistoryContextId(u64);
-
-impl SessionHistoryContextId {
- pub const ROOT: Self = Self(0);
-
- pub fn allocate() -> Self {
- Self(allocate(&NEXT_CONTEXT))
- }
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct SessionHistoryStepId(u64);
-
-impl SessionHistoryStepId {
- pub fn raw(self) -> u64 {
- self.0
- }
-
- /// Restore an opaque identity held by a renderer's private task slot.
- pub fn from_raw(raw: u64) -> Self {
- Self(raw)
- }
-}
-
-/// Browser supplied position. It includes steps outside the current renderer's
-/// Navigation API view, including entries in other Documents and origins.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct SessionHistoryPosition {
- index: usize,
- length: usize,
-}
-
-impl SessionHistoryPosition {
- pub const INITIAL: Self = Self {
- index: 0,
- length: 1,
- };
-
- pub fn new(index: usize, length: usize) -> Option<Self> {
- (index < length).then_some(Self { index, length })
- }
-
- pub fn index(self) -> usize {
- self.index
- }
-
- pub fn length(self) -> usize {
- self.length
- }
-}
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct SessionHistoryEntry {
- pub key: NavigationHistoryEntryKey,
- pub document: NavigationHistoryDocumentId,
-}
+use moli_session_history::{
+ JointSessionHistory, SessionHistoryEntry, SessionHistoryPosition, SessionHistoryStepId,
+};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SessionHistoryCommit {
@@ -110,340 +37,3 @@ pub struct SessionHistoryUpdate {
/// changes the URL exposed by steps introduced by child navigations.
pub root_entry_steps: Vec<usize>,
}
-
-#[derive(Clone, Debug, PartialEq, Eq)]
-struct SessionHistoryStep {
- id: SessionHistoryStepId,
- entries: BTreeMap<SessionHistoryContextId, SessionHistoryEntry>,
-}
-
-/// Page-owned authority for joint history. No URL, Navigation API index, or
-/// per-Window cached length participates in history bookkeeping.
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct JointSessionHistory {
- steps: Vec<SessionHistoryStep>,
- current: usize,
- parents: BTreeMap<SessionHistoryContextId, SessionHistoryContextId>,
-}
-
-impl Default for JointSessionHistory {
- fn default() -> Self {
- Self::new(SessionHistoryPosition::INITIAL)
- }
-}
-
-impl JointSessionHistory {
- pub fn new(position: SessionHistoryPosition) -> Self {
- Self {
- steps: (0..position.length)
- .map(|_| SessionHistoryStep {
- id: SessionHistoryStepId(allocate(&NEXT_STEP)),
- entries: BTreeMap::new(),
- })
- .collect(),
- current: position.index,
- parents: BTreeMap::new(),
- }
- }
-
- pub fn position(&self) -> SessionHistoryPosition {
- SessionHistoryPosition {
- index: self.current,
- length: self.steps.len(),
- }
- }
-
- pub fn current_step(&self) -> SessionHistoryStepId {
- self.steps[self.current].id
- }
-
- pub fn entry(&self, context: SessionHistoryContextId) -> Option<&SessionHistoryEntry> {
- self.steps[self.current].entries.get(&context)
- }
-
- /// Attaching an initial document adds no step. Its entry is also active at
- /// other steps in the same parent Document, including its forward history.
- pub fn attach(
- &mut self,
- context: SessionHistoryContextId,
- parent: Option<SessionHistoryContextId>,
- entry: SessionHistoryEntry,
- ) {
- if self.entry(context).is_some() {
- return;
- }
- let parent_document =
- parent.and_then(|parent| self.entry(parent).map(|e| e.document.clone()));
- if let Some(parent) = parent {
- self.parents.insert(context, parent);
- }
- for (index, step) in self.steps.iter_mut().enumerate() {
- let same_parent_document =
- parent
- .zip(parent_document.as_ref())
- .is_some_and(|(parent, document)| {
- step.entries
- .get(&parent)
- .is_some_and(|e| &e.document == document)
- });
- if index == self.current || same_parent_document {
- step.entries.entry(context).or_insert_with(|| entry.clone());
- }
- }
- }
-
- pub fn push(&mut self, context: SessionHistoryContextId, entry: SessionHistoryEntry) {
- let mut next = self.steps[self.current].clone();
- next.id = SessionHistoryStepId(allocate(&NEXT_STEP));
- self.remove_replaced_document_children(&mut next, context, &entry);
- next.entries.insert(context, entry);
- self.steps.truncate(self.current + 1);
- self.steps.push(next);
- self.current += 1;
- }
-
- pub fn replace(&mut self, context: SessionHistoryContextId, entry: SessionHistoryEntry) {
- let old_key = self.entry(context).map(|entry| entry.key.clone());
- let descendants = self.descendants(context);
- for (index, step) in self.steps.iter_mut().enumerate() {
- if index == self.current
- || old_key
- .as_ref()
- .is_some_and(|key| step.entries.get(&context).is_some_and(|e| &e.key == key))
- {
- if step
- .entries
- .get(&context)
- .is_some_and(|old| old.document != entry.document)
- {
- step.entries.retain(|id, _| !descendants.contains(id));
- }
- step.entries.insert(context, entry.clone());
- }
- }
- }
-
- pub fn step_by_delta(&self, delta: i64) -> Option<SessionHistoryStepId> {
- let index = i64::try_from(self.current).ok()?.checked_add(delta)?;
- self.steps
- .get(usize::try_from(index).ok()?)
- .map(|step| step.id)
- }
-
- pub fn delta_to(&self, target: SessionHistoryStepId) -> Option<i64> {
- let next = self.steps.iter().position(|step| step.id == target)?;
- Some(i64::try_from(next).ok()? - i64::try_from(self.current).ok()?)
- }
-
- pub fn steps_for_entry(
- &self,
- context: SessionHistoryContextId,
- key: &NavigationHistoryEntryKey,
- ) -> Vec<usize> {
- self.steps
- .iter()
- .enumerate()
- .filter_map(|(index, step)| {
- step.entries
- .get(&context)
- .is_some_and(|entry| &entry.key == key)
- .then_some(index)
- })
- .collect()
- }
-
- /// An entry can span several joint steps made by other frames. Traversal
- /// chooses the nearest such step, preserving intervening frame history.
- pub fn step_for_entry(
- &self,
- context: SessionHistoryContextId,
- key: &NavigationHistoryEntryKey,
- ) -> Option<SessionHistoryStepId> {
- let matches = |step: &&SessionHistoryStep| {
- step.entries
- .get(&context)
- .is_some_and(|entry| &entry.key == key)
- };
- self.steps[..=self.current]
- .iter()
- .rev()
- .find(matches)
- .or_else(|| self.steps[self.current + 1..].iter().find(matches))
- .map(|step| step.id)
- }
-
- pub fn entries_at(
- &self,
- target: SessionHistoryStepId,
- ) -> Option<&BTreeMap<SessionHistoryContextId, SessionHistoryEntry>> {
- self.steps
- .iter()
- .find(|step| step.id == target)
- .map(|step| &step.entries)
- }
-
- /// Commit by identity so queued traversals cannot land in a newly pushed
- /// entry that happens to reuse an index after forward-history pruning.
- pub fn traverse(&mut self, target: SessionHistoryStepId) -> Option<i64> {
- let next = self.steps.iter().position(|step| step.id == target)?;
- let delta = i64::try_from(next).ok()? - i64::try_from(self.current).ok()?;
- self.current = next;
- Some(delta)
- }
-
- pub fn contains_entry(
- &self,
- context: SessionHistoryContextId,
- key: &NavigationHistoryEntryKey,
- ) -> bool {
- self.steps.iter().any(|step| {
- step.entries
- .get(&context)
- .is_some_and(|entry| &entry.key == key)
- })
- }
-
- pub fn prune_all_but_current(&mut self) {
- let current = self.steps[self.current].clone();
- self.steps = vec![current];
- self.current = 0;
- }
-
- pub fn detach(&mut self, context: SessionHistoryContextId) {
- let mut removed = self.descendants(context);
- removed.push(context);
- for step in &mut self.steps {
- step.entries.retain(|id, _| !removed.contains(id));
- }
- self.parents.retain(|id, _| !removed.contains(id));
- }
-
- fn descendants(&self, context: SessionHistoryContextId) -> Vec<SessionHistoryContextId> {
- let mut found = vec![context];
- let mut index = 0;
- while index < found.len() {
- let parent = found[index];
- found.extend(
- self.parents
- .iter()
- .filter_map(|(child, candidate)| (*candidate == parent).then_some(*child)),
- );
- index += 1;
- }
- found.remove(0);
- found
- }
-
- fn remove_replaced_document_children(
- &self,
- step: &mut SessionHistoryStep,
- context: SessionHistoryContextId,
- entry: &SessionHistoryEntry,
- ) {
- if step
- .entries
- .get(&context)
- .is_some_and(|old| old.document != entry.document)
- {
- let descendants = self.descendants(context);
- step.entries.retain(|id, _| !descendants.contains(id));
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn entry(key: &str, document: &str) -> SessionHistoryEntry {
- SessionHistoryEntry {
- key: NavigationHistoryEntryKey::from_serialized(key.into()),
- document: NavigationHistoryDocumentId::from_serialized(document.into()),
- }
- }
-
- #[test]
- fn branch_truncates_forward_steps_and_invalidates_queued_targets() {
- let mut history = JointSessionHistory::default();
- let root = SessionHistoryContextId::ROOT;
- history.attach(root, None, entry("a", "top"));
- for key in ["b", "c", "d"] {
- history.push(root, entry(key, "top"));
- }
- let stale = history.current_step();
- let b = history.step_by_delta(-2).unwrap();
- assert_eq!(history.traverse(b), Some(-2));
- history.push(root, entry("e", "top"));
- assert_eq!(
- history.position(),
- SessionHistoryPosition::new(2, 3).unwrap()
- );
- assert_eq!(history.traverse(stale), None);
- assert_eq!(history.entry(root), Some(&entry("e", "top")));
- }
-
- #[test]
- fn joint_steps_follow_commit_order_and_navigation_traversal_uses_nearest_step() {
- let mut history = JointSessionHistory::default();
- let root = SessionHistoryContextId::ROOT;
- let a = SessionHistoryContextId::allocate();
- let b = SessionHistoryContextId::allocate();
- history.attach(root, None, entry("top", "top"));
- history.attach(a, Some(root), entry("a0", "a"));
- history.attach(b, Some(root), entry("b0", "b"));
- history.push(a, entry("a1", "a"));
- history.push(b, entry("b1", "b"));
- history.push(a, entry("a2", "a"));
- let target = history.step_for_entry(a, &entry("a1", "a").key).unwrap();
- assert_eq!(history.traverse(target), Some(-1));
- assert_eq!(history.entry(b), Some(&entry("b1", "b")));
- history.traverse(history.step_by_delta(-1).unwrap());
- assert_eq!(history.entry(b), Some(&entry("b0", "b")));
- history.push(b, entry("b2", "b"));
- assert_eq!(
- history.position(),
- SessionHistoryPosition::new(2, 3).unwrap()
- );
- assert!(!history.contains_entry(a, &entry("a2", "a").key));
- assert!(!history.contains_entry(b, &entry("b1", "b").key));
- }
-
- #[test]
- fn replace_preserves_steps_and_updates_shared_entry_references() {
- let mut history = JointSessionHistory::default();
- let root = SessionHistoryContextId::ROOT;
- let child = SessionHistoryContextId::allocate();
- history.attach(root, None, entry("top", "top"));
- history.attach(child, Some(root), entry("child0", "child"));
- history.push(child, entry("child1", "child"));
- let position = history.position();
- history.replace(root, entry("top-replaced", "top"));
- assert_eq!(history.position(), position);
- history.traverse(history.step_by_delta(-1).unwrap());
- assert_eq!(history.entry(root), Some(&entry("top-replaced", "top")));
- history.replace(root, entry("new-document", "new-document"));
- assert!(history.entry(child).is_none());
- assert_eq!(history.position().length(), 2);
- }
-
- #[test]
- fn browser_position_includes_opaque_steps_and_push_uses_the_cursor() {
- let mut history = JointSessionHistory::new(SessionHistoryPosition::new(1, 4).unwrap());
- let root = SessionHistoryContextId::ROOT;
- history.attach(root, None, entry("current", "document"));
- history.push(root, entry("next", "document"));
- assert_eq!(
- history.position(),
- SessionHistoryPosition::new(2, 3).unwrap()
- );
- assert_eq!(
- history
- .entries_at(history.step_by_delta(-2).unwrap())
- .unwrap()
- .len(),
- 0
- );
- assert!(SessionHistoryPosition::new(0, 0).is_none());
- assert!(SessionHistoryPosition::new(3, 3).is_none());
- }
-}
diff --git a/moli-protocol/Cargo.toml b/moli-protocol/Cargo.toml
index 70af91bf8..655a18c4e 100644
--- a/moli-protocol/Cargo.toml
+++ b/moli-protocol/Cargo.toml
@@ -24,6 +24,7 @@ moli-fetch = { path = "../moli-fetch" }
moli-css-parse = { path = "../moli-css-parse" }
moli-shared-worker = { path = "../moli-shared-worker" }
moli-site = { path = "../moli-site" }
+moli-session-history = { path = "../moli-session-history" }
moli-storage-key = { path = "../moli-storage-key" }
moli-trace = { path = "../moli-trace" }
moli-url = { path = "../moli-url" }
diff --git a/moli-protocol/src/conn/browser_context/target_session_owner.rs b/moli-protocol/src/conn/browser_context/target_session_owner.rs
index e2573f3d1..1a6dfa1d7 100644
--- a/moli-protocol/src/conn/browser_context/target_session_owner.rs
+++ b/moli-protocol/src/conn/browser_context/target_session_owner.rs
@@ -180,7 +180,7 @@ pub(crate) struct TargetNavigationLoadInputs {
(bool, Option<moli_core::page::SubresourceResourceType>),
pub(crate) permission_overrides: Vec<moli_core::page::PermissionOverrideRegistration>,
main_document_commit_seed: Option<RendererMainDocumentCommitSeed>,
- session_history_position: Option<moli_page_types::SessionHistoryPosition>,
+ session_history_position: Option<moli_session_history::SessionHistoryPosition>,
}
impl TargetNavigationLoadInputs {
diff --git a/moli-protocol/src/conn/state/navigation.rs b/moli-protocol/src/conn/state/navigation.rs
index db5d1b67c..281169d28 100644
--- a/moli-protocol/src/conn/state/navigation.rs
+++ b/moli-protocol/src/conn/state/navigation.rs
@@ -47,7 +47,7 @@ impl TargetNavigationHistoryState {
self.entries.is_empty()
}
- pub(crate) fn position_after_navigation(&self) -> moli_page_types::SessionHistoryPosition {
+ pub(crate) fn position_after_navigation(&self) -> moli_session_history::SessionHistoryPosition {
let (index, length) = match self.pending_update {
Some(
PendingNavigationHistoryUpdate::ReplaceCurrent
@@ -66,7 +66,7 @@ impl TargetNavigationHistoryState {
(index, index + 1)
}
};
- moli_page_types::SessionHistoryPosition::new(index, length)
+ moli_session_history::SessionHistoryPosition::new(index, length)
.expect("browser session history position must be valid")
}
diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rs
index 6991122ed..46df74645 100644
--- a/moli-protocol/src/domains/page.rs
+++ b/moli-protocol/src/domains/page.rs
@@ -4973,7 +4973,7 @@ mod producer_tests {
navigation.owner().clone(),
navigation.source_document(),
moli_page_types::SessionHistoryUpdate {
- position: moli_page_types::SessionHistoryPosition::INITIAL,
+ position: moli_session_history::SessionHistoryPosition::INITIAL,
update: moli_page_types::SessionHistoryUpdateKind::Push,
root_url: navigation.clone().into_navigation().url,
root_entry_steps: vec![0],
diff --git a/moli-protocol/src/domains/page/tests/navigation.rs b/moli-protocol/src/domains/page/tests/navigation.rs
index f780fe00f..a5d8a86fb 100644
--- a/moli-protocol/src/domains/page/tests/navigation.rs
+++ b/moli-protocol/src/domains/page/tests/navigation.rs
@@ -521,6 +521,16 @@ async fn joint_history_traversal_precommit_cannot_restore_a_pruned_step() {
assert_joint_history_precommit("prune").await;
}
+#[tokio::test]
+async fn joint_history_traversal_precommit_keeps_an_unchanged_attached_context() {
+ assert_joint_history_precommit("attach").await;
+}
+
+#[tokio::test]
+async fn joint_history_single_target_precommit_keeps_an_unchanged_attached_context() {
+ assert_joint_history_precommit("attach-single").await;
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn joint_history_traversal_late_response_cannot_overwrite_a_successor_entry() {
assert_joint_history_late_response(false).await;
@@ -711,6 +721,15 @@ async fn assert_joint_history_precommit(mode: &str) {
|message| message["method"] == json!("Page.domContentEventFired"),
)
.await;
+ joint_history_test_evaluate(
+ &mut ctx,
+ if mode == "attach-single" {
+ "globalThis.testTraversalDelta = -1"
+ } else {
+ "globalThis.testTraversalDelta = -2"
+ },
+ )
+ .await;
let pending=joint_history_test_evaluate(&mut ctx,r#"(async()=>{
history.replaceState('top0','');
globalThis.frame=document.createElement('iframe');frame.src='/a0';
@@ -730,7 +749,7 @@ async fn assert_joint_history_precommit(mode: &str) {
navigation.onnavigate=event=>{
if(event.navigationType==='traverse')event.intercept({precommitHandler:()=>{admitted();return gate}});
};
- history.go(-2);await started;return snapshot();
+ history.go(testTraversalDelta);await started;return snapshot();
})()"#).await;
assert_eq!(pending, json!(["top1", "a1", "/a1", 4, 4, 0]), "{mode}");
ctx.process_async(json!({"id":9341,"method":"Page.getNavigationHistory","sessionId":"SID-1"}))
@@ -749,16 +768,27 @@ async fn assert_joint_history_precommit(mode: &str) {
.await;
assert!(take_response_by_id(&mut ctx, 9342)["error"].is_null());
}
+ if matches!(mode, "attach" | "attach-single") {
+ let lengths = joint_history_test_evaluate(&mut ctx, r#"(async()=>{
+ const added=document.createElement('iframe');added.src='/attached';
+ await new Promise(resolve=>{added.onload=resolve;document.body.append(added)});
+ await new Promise(resolve=>setTimeout(resolve,0));
+ return [history.length,frame.contentWindow.history.length,added.contentWindow.history.length];
+ })()"#).await;
+ assert_eq!(lengths, json!([4, 4, 4]), "{mode}");
+ }
let expression = match mode {
- "resolve" => {
+ "resolve" | "attach" => {
"new Promise(resolve=>{frame.onload=()=>setTimeout(()=>resolve(snapshot()),0);release()})"
}
+ "attach-single" => "new Promise(resolve=>{onpopstate=()=>resolve(snapshot());release()})",
"reject" => "block(new Error('blocked'));failed.then(()=>snapshot())",
_ => "release();failed.then(()=>snapshot())",
};
let after = joint_history_test_evaluate(&mut ctx, expression).await;
let (expected, index, length) = match mode {
- "resolve" => (json!(["top0", "a0", "/a0", 4, 4, 1]), 1, 4),
+ "resolve" | "attach" => (json!(["top0", "a0", "/a0", 4, 4, 1]), 1, 4),
+ "attach-single" => (json!(["top0", "a1", "/a1", 4, 4, 0]), 2, 4),
"reject" => (json!(["top1", "a1", "/a1", 4, 4, 0]), 3, 4),
_ => (json!(["top1", "a1", "/a1", 1, 1, 0]), 0, 1),
};
diff --git a/moli-renderer-v8/Cargo.toml b/moli-renderer-v8/Cargo.toml
index e85c61aa2..39d56a0f0 100644
--- a/moli-renderer-v8/Cargo.toml
+++ b/moli-renderer-v8/Cargo.toml
@@ -68,6 +68,7 @@ moli-module-syntax = { path = "../moli-module-syntax" }
moli-owner-queue = { path = "../moli-owner-queue" }
moli-paint = { path = "../moli-paint" }
moli-script = { path = "../moli-script" }
+moli-session-history = { path = "../moli-session-history" }
moli-stylesheet-blocking = { path = "../moli-stylesheet-blocking" }
moli-storage-key = { path = "../moli-storage-key" }
moli-streams = { path = "../moli-streams" }
diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs
index 1a98ec14f..564ab1a38 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs
@@ -45,11 +45,11 @@ pub(in crate::context_bootstrap) fn apply_history_entry<'s>(
scope: &mut v8::PinScope<'s, '_>,
history: v8::Local<'s, v8::Object>,
index: u32,
- joint_step: Option<moli_page_types::SessionHistoryStepId>,
+ plan: Option<&moli_session_history::SessionHistoryTraversalPlan>,
dispatch_popstate: bool,
pending_results: Option<&[PendingNavigationResult]>,
) {
- let Some(applied) = apply_history_entry_commit(scope, history, index, joint_step) else {
+ let Some(applied) = apply_history_entry_commit(scope, history, index, plan) else {
if let Some(results) = pending_results {
let error = super::super::navigation_result::navigation_dom_exception(
scope,
@@ -91,16 +91,11 @@ pub(in crate::context_bootstrap) fn apply_history_entry_commit<'s>(
scope: &mut v8::PinScope<'s, '_>,
history: v8::Local<'s, v8::Object>,
index: u32,
- joint_step: Option<moli_page_types::SessionHistoryStepId>,
+ plan: Option<&moli_session_history::SessionHistoryTraversalPlan>,
) -> Option<AppliedHistoryEntry<'s>> {
let owner = runtime_window_owner(scope, history);
- let entry = history_entries(scope, history)?
- .get_index(scope, index)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
- let step =
- joint_step.or_else(|| super::super::session_history::step_for_entry(scope, owner, entry));
- let targets = match step {
- Some(step) => super::super::session_history::targets_at(scope, owner, step)?,
+ let targets = match plan {
+ Some(plan) => super::super::session_history::project_traversal(scope, owner, plan)?,
None => Vec::new(),
};
// The multi-participant coordinator admits and commits complete plans.
@@ -113,27 +108,22 @@ pub(in crate::context_bootstrap) fn apply_history_entry_commit<'s>(
}
// Admission can run script, so validate the stable step again before any
// local entry is changed. Forward pruning invalidates it atomically.
- if let Some(step) = step {
+ if let Some(plan) = plan {
let host = unsafe { &mut *context_host_ptr_from_global_bridge(scope)? };
let binding = super::super::session_history::binding(scope, host, owner);
- let expected = host
- .session_histories
- .get_mut(binding.popup)
- .entries_at(step)?
- .get(&binding.context)?
- .clone();
+ let expected = plan.target_entries().get(&binding.context)?;
let live = history_entries(scope, history)?
.get_index(scope, index)
.and_then(|entry| v8::Local::<v8::Object>::try_from(entry).ok())
.and_then(|entry| super::super::session_history::entry_reference(scope, entry))?;
- if live != expected {
+ if &live != expected {
return None;
}
}
let prepared = prepare_local_history_entry_commit(scope, history, index)?;
- let delta = match step {
- Some(step) => Some(super::super::session_history::commit_traversal(
- scope, owner, step,
+ let delta = match plan {
+ Some(plan) => Some(super::super::session_history::commit_traversal(
+ scope, owner, plan,
)?),
None => None,
};
diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs
index ea91e454e..c1d10c484 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs
@@ -30,6 +30,7 @@ const TRAVERSAL_PRECOMMIT_NAVIGATION_SLOT: &str = "__lmTraversalPrecommitNavigat
const TRAVERSAL_PRECOMMIT_HISTORY_SLOT: &str = "__lmTraversalPrecommitHistory";
const TRAVERSAL_PRECOMMIT_EVENT_SLOT: &str = "__lmTraversalPrecommitEvent";
const TRAVERSAL_PRECOMMIT_SIGNAL_SLOT: &str = "__lmTraversalPrecommitSignal";
+const TRAVERSAL_PRECOMMIT_ADMISSION_SLOT: &str = "__lmTraversalPrecommitAdmission";
const TRAVERSAL_PRECOMMIT_JOINT_STEP_SLOT: &str = "__lmTraversalPrecommitJointStep";
const TRAVERSAL_PRECOMMIT_TARGET_INDEX_SLOT: &str = "__lmTraversalPrecommitTargetIndex";
const TRAVERSAL_PRECOMMIT_PROMISE_SLOT: &str = "__lmTraversalPrecommitPromise";
@@ -67,6 +68,9 @@ struct TraversalPrecommitDataDeclaration<'scope> {
#[webapi(slot = TRAVERSAL_PRECOMMIT_JOINT_STEP_SLOT)]
joint_step: Option<v8::Local<'scope, v8::Value>>,
+ #[webapi(slot = TRAVERSAL_PRECOMMIT_ADMISSION_SLOT)]
+ admission: Option<v8::Local<'scope, v8::Value>>,
+
#[webapi(slot = TRAVERSAL_PRECOMMIT_TARGET_INDEX_SLOT)]
target_index: u32,
@@ -236,6 +240,7 @@ pub(in crate::context_bootstrap) fn apply_pending_history_traversal(
host: &mut JsContextHost,
mut traversal: PendingHistoryTraversal,
) {
+ let mut joint_plan = None;
if let Some(step) = traversal.joint_step {
let Some(owner) = history_traversal_target_window(scope, host, traversal.target) else {
let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
@@ -273,6 +278,7 @@ pub(in crate::context_bootstrap) fn apply_pending_history_traversal(
.and_then(|entry| v8::Local::<v8::Object>::try_from(entry).ok())
.and_then(|entry| navigation_entry_key_value(scope, entry));
}
+ joint_plan = Some(plan.core);
}
let results = traversal.results;
let history = history_traversal_target_window(scope, host, traversal.target)
@@ -282,6 +288,14 @@ pub(in crate::context_bootstrap) fn apply_pending_history_traversal(
reject_pending_navigation_results(scope, &results, error);
return;
};
+ if joint_plan.is_none() {
+ let owner = runtime_window_owner(scope, history);
+ joint_plan = history_entries(scope, history)
+ .and_then(|entries| entries.get_index(scope, traversal.target_index))
+ .and_then(|entry| v8::Local::<v8::Object>::try_from(entry).ok())
+ .and_then(|entry| super::super::session_history::step_for_entry(scope, owner, entry))
+ .and_then(|step| super::super::session_history::plan_traversal(scope, owner, step));
+ }
if history_index(scope, history) != traversal.target_index {
let target_entry = history_entries(scope, history)
.and_then(|entries| entries.get_index(scope, traversal.target_index))
@@ -359,7 +373,7 @@ pub(in crate::context_bootstrap) fn apply_pending_history_traversal(
navigation,
history,
traversal.target_index,
- traversal.joint_step,
+ joint_plan.as_ref(),
outcome,
&results,
);
@@ -375,7 +389,7 @@ pub(in crate::context_bootstrap) fn apply_pending_history_traversal(
scope,
history,
traversal.target_index,
- traversal.joint_step,
+ joint_plan.as_ref(),
) else {
let error =
navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
@@ -447,7 +461,7 @@ pub(in crate::context_bootstrap) fn apply_pending_history_traversal(
scope,
history,
traversal.target_index,
- traversal.joint_step,
+ joint_plan.as_ref(),
true,
pending_results,
);
@@ -467,8 +481,8 @@ pub(in crate::context_bootstrap) fn apply_pending_history_traversal(
return;
}
let owner = runtime_window_owner(scope, history);
- if let Some(step) = traversal.joint_step {
- let Some(delta) = super::super::session_history::commit_traversal(scope, owner, step)
+ if let Some(plan) = &joint_plan {
+ let Some(delta) = super::super::session_history::commit_traversal(scope, owner, plan)
else {
let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
reject_pending_navigation_results(scope, &results, error);
@@ -611,7 +625,7 @@ fn queue_pending_precommit_history_traversal<'s>(
navigation: v8::Local<'s, v8::Object>,
history: v8::Local<'s, v8::Object>,
target_index: u32,
- joint_step: Option<moli_page_types::SessionHistoryStepId>,
+ plan: Option<&moli_session_history::SessionHistoryTraversalPlan>,
outcome: NavigationDispatchOutcome<'s>,
results: &[crate::native_bridge::PendingNavigationResult],
) -> bool {
@@ -640,7 +654,12 @@ fn queue_pending_precommit_history_traversal<'s>(
history,
event,
signal: outcome.signal,
- joint_step: joint_step.map(|step| v8::BigInt::new_from_u64(scope, step.raw()).into()),
+ joint_step: plan
+ .map(|plan| v8::BigInt::new_from_u64(scope, plan.target_step().raw()).into()),
+ admission: plan.map(|plan| {
+ let signature = super::super::session_history::traversal_admission_signature(plan);
+ v8::String::new(scope, &signature).unwrap().into()
+ }),
target_index,
promise,
committed_resolvers,
@@ -823,8 +842,24 @@ fn traversal_precommit_fulfilled_callback<'s>(
.ok()
.and_then(|data| get_private_value(scope, data, TRAVERSAL_PRECOMMIT_JOINT_STEP_SLOT))
.and_then(|value| v8::Local::<v8::BigInt>::try_from(value).ok())
- .map(|value| moli_page_types::SessionHistoryStepId::from_raw(value.u64_value().0));
- let Some(applied) = apply_history_entry_commit(scope, history, target_index, joint_step) else {
+ .map(|value| moli_session_history::SessionHistoryStepId::from_raw(value.u64_value().0));
+ let admission = v8::Local::<v8::Object>::try_from(args.data())
+ .ok()
+ .and_then(|data| get_private_value(scope, data, TRAVERSAL_PRECOMMIT_ADMISSION_SLOT))
+ .and_then(|value| value.to_string(scope))
+ .map(|value| value.to_rust_string_lossy(scope));
+ let owner = runtime_window_owner(scope, history);
+ let plan = joint_step
+ .and_then(|step| super::super::session_history::plan_traversal(scope, owner, step))
+ .filter(|plan| {
+ Some(super::super::session_history::traversal_admission_signature(plan)) == admission
+ });
+ let applied = if joint_step.is_some() && plan.is_none() {
+ None
+ } else {
+ apply_history_entry_commit(scope, history, target_index, plan.as_ref())
+ };
+ let Some(applied) = applied else {
let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
finish_navigation_error_events(scope, navigation, error, "");
reject_resolver_array(scope, committed_resolvers, error, false);
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs
index 16993d01e..806539e0b 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs
@@ -15,7 +15,8 @@ use super::navigation_window::{
use super::*;
use crate::util::{get_private_value, set_private_value};
use crate::web_api_interfaces;
-use moli_page_types::{NavigationHistoryEntryId, NavigationHistoryEntryKey};
+use moli_page_types::NavigationHistoryEntryId;
+use moli_session_history::NavigationHistoryEntryKey;
use moli_webapi_declare::WebApiObject;
const NAVIGATION_ENTRY_INITIAL_INDEX_SLOT: &str = "__lmNavigationEntryInitialIndex";
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_joint_traversal.rs b/moli-renderer-v8/src/context_bootstrap/navigation_joint_traversal.rs
index 411157cbd..cd08ee838 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_joint_traversal.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_joint_traversal.rs
@@ -20,12 +20,13 @@ use super::navigation_window::{
};
use crate::native_bridge::PendingNavigationResult;
use crate::util::{context_host_ptr_from_global_bridge, get_private_value, set_private_value};
-use moli_page_types::SessionHistoryStepId;
+use moli_session_history::SessionHistoryStepId;
const PENDING: &str = "__lmPendingJointTraversal";
const ACTIVE: &str = "__lmJointActive";
const OWNER: &str = "__lmJointOwner";
const STEP: &str = "__lmJointStep";
+const ADMISSION: &str = "__lmJointAdmission";
const PARTICIPANTS: &str = "__lmJointParticipants";
const REMAINING: &str = "__lmJointRemaining";
const COMMITTED: &str = "__lmJointCommitted";
@@ -59,7 +60,7 @@ pub(super) fn queue_plan<'s>(scope: &mut v8::PinScope<'s, '_>, mut plan: JointTr
history,
current_index: index,
target_index: index,
- joint_step: Some(plan.step),
+ joint_step: Some(plan.step()),
},
);
}
@@ -140,7 +141,14 @@ pub(super) fn execute<'s>(
scope,
data,
STEP,
- v8::BigInt::new_from_u64(scope, plan.step.raw()).into(),
+ v8::BigInt::new_from_u64(scope, plan.step().raw()).into(),
+ );
+ let signature = super::session_history::traversal_admission_signature(&plan.core);
+ set_private_value(
+ scope,
+ data,
+ ADMISSION,
+ v8::String::new(scope, &signature).unwrap().into(),
);
let participants = v8::Array::new(scope, plan.targets.len() as i32);
set_private_value(scope, data, PARTICIPANTS, participants.into());
@@ -299,6 +307,12 @@ fn validate<'s>(
owner,
SessionHistoryStepId::from_raw(step.u64_value().0),
)?;
+ let signature = get_private_value(scope, data, ADMISSION)?
+ .to_string(scope)?
+ .to_rust_string_lossy(scope);
+ if signature != super::session_history::traversal_admission_signature(&plan.core) {
+ return None;
+ }
let participants = array(scope, data, PARTICIPANTS)?;
if participants.length() as usize != plan.targets.len() {
return None;
@@ -463,7 +477,7 @@ fn commit<'s>(scope: &mut v8::PinScope<'s, '_>, data: v8::Local<'s, v8::Object>)
abort(scope, data, None);
return;
};
- seed.session_history.target_step = Some(plan.step);
+ seed.session_history.target_step = Some(plan.step());
seed.session_history.admitted_entry = history_entries(scope, target.history)
.and_then(|entries| entries.get_index(scope, target.target_index))
.and_then(|entry| entry.try_into().ok())
@@ -511,7 +525,7 @@ fn commit<'s>(scope: &mut v8::PinScope<'s, '_>, data: v8::Local<'s, v8::Object>)
seed.clone(),
) {
for (_, queued, _, _) in &cross_document {
- host.cancel_joint_child_history_navigation(*queued, plan.step);
+ host.cancel_joint_child_history_navigation(*queued, plan.step());
}
abort(scope, data, None);
return;
@@ -519,9 +533,10 @@ fn commit<'s>(scope: &mut v8::PinScope<'s, '_>, data: v8::Local<'s, v8::Object>)
}
// Acceptance point: all admissions passed, all child navigations have
// reservations, and same-Document views can commit without script or failure.
- let Some(delta) = super::session_history::commit_traversal(scope, plan.owner, plan.step) else {
+ let Some(delta) = super::session_history::commit_traversal(scope, plan.owner, &plan.core)
+ else {
for (_, handle, _, _) in &cross_document {
- unsafe { &mut *host_ptr }.cancel_joint_child_history_navigation(*handle, plan.step);
+ unsafe { &mut *host_ptr }.cancel_joint_child_history_navigation(*handle, plan.step());
}
abort(scope, data, None);
return;
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs b/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs
index 17e56eb85..7037586ee 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_mutation/local.rs
@@ -38,7 +38,7 @@ pub(crate) fn apply_local_window_location_navigation<'s>(
&new_navigation_entry_id(),
&new_navigation_entry_key(),
);
- let document_id = moli_page_types::NavigationHistoryDocumentId::allocate();
+ let document_id = moli_session_history::NavigationHistoryDocumentId::allocate();
set_navigation_entry_document_id(scope, next_entry, document_id.as_str());
bind_navigation_entry_runtime_owner(scope, next_entry, owner);
let _ = next_entries.set_index(scope, next_index, next_entry.into());
@@ -76,7 +76,7 @@ pub(crate) fn apply_local_window_location_navigation<'s>(
&new_navigation_entry_id(),
&key,
);
- let document_id = moli_page_types::NavigationHistoryDocumentId::allocate();
+ let document_id = moli_session_history::NavigationHistoryDocumentId::allocate();
set_navigation_entry_document_id(scope, entry, document_id.as_str());
bind_navigation_entry_runtime_owner(scope, entry, owner);
let _ = entries.set_index(scope, current_index, entry.into());
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs b/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs
index 42935bb07..2d0d42d0d 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs
@@ -10,9 +10,8 @@ use super::navigation_entry_state::clone_history_entry_state;
use super::navigation_result::clear_active_cross_document_navigation_if_matches;
use super::navigation_window::{window_history_for_holder, window_navigation_for_holder};
use crate::native_bridge::NavigationHistoryEntrySeed;
-use moli_page_types::{
- NavigationHistoryDocumentId, NavigationHistoryEntryId, NavigationHistoryEntryKey,
-};
+use moli_page_types::NavigationHistoryEntryId;
+use moli_session_history::{NavigationHistoryDocumentId, NavigationHistoryEntryKey};
pub(crate) fn install_navigation_bootstrap_entry(
scope: &mut v8::PinScope<'_, '_>,
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs b/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs
index cb38c9ef3..2a947e206 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_seed.rs
@@ -12,10 +12,11 @@ use super::navigation_window::{
};
use crate::native_bridge::NavigationHistoryEntrySeed;
use moli_page_types::{
- NavigationHistoryDocumentId, NavigationHistoryEntryId, NavigationHistoryEntryKey,
+ NavigationHistoryEntryId,
initial_navigation_history_seed as page_initial_navigation_history_seed,
reload_navigation_seed, traversal_navigation_seed_candidate,
};
+use moli_session_history::{NavigationHistoryDocumentId, NavigationHistoryEntryKey};
pub(super) fn initial_navigation_history_seed<'s>(
scope: &mut v8::PinScope<'s, '_>,
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs
index 6b27ed39b..85c793d2c 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs
@@ -28,7 +28,7 @@ pub(super) struct TraversalTarget<'s> {
pub(super) history: v8::Local<'s, v8::Object>,
pub(super) current_index: u32,
pub(super) target_index: u32,
- pub(super) joint_step: Option<moli_page_types::SessionHistoryStepId>,
+ pub(super) joint_step: Option<moli_session_history::SessionHistoryStepId>,
}
pub(super) fn queue_navigation_traversal_with_result<'s>(
@@ -49,14 +49,7 @@ pub(super) fn queue_navigation_traversal_with_result<'s>(
"AbortError",
));
}
- apply_history_entry(
- scope,
- target.history,
- target.target_index,
- target.joint_step,
- true,
- None,
- );
+ apply_history_entry(scope, target.history, target.target_index, None, true, None);
return Some(navigation_immediate_current_entry_result(
scope,
target.owner,
@@ -157,14 +150,7 @@ pub(super) fn queue_history_traversal_without_result<'s>(
if !dispatch_traverse_event(scope, &target) {
return;
}
- apply_history_entry(
- scope,
- target.history,
- target.target_index,
- target.joint_step,
- true,
- None,
- );
+ apply_history_entry(scope, target.history, target.target_index, None, true, None);
return;
};
let host = unsafe { &mut *host_ptr };
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs
index 83446ad21..df6132e59 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs
@@ -12,7 +12,7 @@ use super::navigation_window::{
};
pub(super) struct JointTraversalPlan<'s> {
- pub(super) step: moli_page_types::SessionHistoryStepId,
+ pub(super) core: moli_session_history::SessionHistoryTraversalPlan,
pub(super) owner: v8::Local<'s, v8::Object>,
pub(super) targets: Vec<TraversalTarget<'s>>,
}
@@ -21,15 +21,21 @@ impl<'s> JointTraversalPlan<'s> {
pub(super) fn resolve(
scope: &mut v8::PinScope<'s, '_>,
owner: v8::Local<'s, v8::Object>,
- step: moli_page_types::SessionHistoryStepId,
+ step: moli_session_history::SessionHistoryStepId,
) -> Option<Self> {
+ let core = super::session_history::plan_traversal(scope, owner, step)?;
+ let targets = super::session_history::project_traversal(scope, owner, &core)?;
Some(Self {
- step,
+ core,
owner,
- targets: super::session_history::targets_at(scope, owner, step)?,
+ targets,
})
}
+ pub(super) fn step(&self) -> moli_session_history::SessionHistoryStepId {
+ self.core.target_step()
+ }
+
pub(super) fn has_cross_document_root(&self, scope: &mut v8::PinScope<'s, '_>) -> bool {
self.cross_document_root_index(scope).is_some()
}
@@ -165,10 +171,10 @@ pub(super) fn history_delta_traversal_plan<'s>(
let owner = runtime_window_owner(scope, history);
let host = unsafe { &mut *crate::util::context_host_ptr_from_global_bridge(scope)? };
let binding = super::session_history::binding(scope, host, owner);
- let mut model = host.session_histories.get_mut(binding.popup).clone();
- if let Some(step) = host.pending_joint_history_step(&model) {
- model.traverse(step);
- }
- let step = model.step_by_delta(delta)?;
+ let model = host.session_histories.get_mut(binding.popup).clone();
+ let source = host
+ .pending_joint_history_step(&model)
+ .unwrap_or_else(|| model.current_step());
+ let step = model.step_by_delta_from(source, delta)?;
JointTraversalPlan::resolve(scope, owner, step)
}
diff --git a/moli-renderer-v8/src/context_bootstrap/session_history.rs b/moli-renderer-v8/src/context_bootstrap/session_history.rs
index ac08d15c8..d01b570d7 100644
--- a/moli-renderer-v8/src/context_bootstrap/session_history.rs
+++ b/moli-renderer-v8/src/context_bootstrap/session_history.rs
@@ -7,10 +7,11 @@ use super::navigation_window::{
};
use crate::native_bridge::{JsContextHost, NavigationHistoryEntrySeed, OwnerDispatchScope};
use crate::util::context_host_ptr_from_global_bridge;
-use moli_page_types::{
+use moli_page_types::SessionHistoryCommit;
+use moli_session_history::{
JointSessionHistory, NavigationHistoryDocumentId, NavigationHistoryEntryKey,
- SessionHistoryCommit, SessionHistoryContextId, SessionHistoryEntry, SessionHistoryPosition,
- SessionHistoryStepId,
+ SessionHistoryContextId, SessionHistoryEntry, SessionHistoryPosition, SessionHistoryStepId,
+ SessionHistoryTraversalPlan,
};
#[derive(Clone, Copy)]
@@ -135,7 +136,8 @@ pub(super) fn restore<'s>(
.session_history
.target_step
.or_else(|| history.step_for_entry(binding.context, &entry.key))
- .and_then(|step| history.traverse(step))
+ .and_then(|step| history.plan_traversal(step))
+ .and_then(|plan| history.commit_traversal(&plan))
.filter(|delta| *delta != 0)
.map(|delta| moli_page_types::SessionHistoryUpdateKind::Traverse { delta }),
};
@@ -225,8 +227,10 @@ pub(super) fn commit<'s>(
history.replace(binding.context, entry)
}
SessionHistoryCommit::Traverse => {
- if let Some(target) = history.step_for_entry(binding.context, &entry.key) {
- history.traverse(target);
+ if let Some(target) = history.step_for_entry(binding.context, &entry.key)
+ && let Some(plan) = history.plan_traversal(target)
+ {
+ history.commit_traversal(&plan);
}
}
}
@@ -279,8 +283,9 @@ pub(super) fn capture_for_navigation<'s>(
.session_history
.target_step
.or_else(|| history.step_for_entry(binding.context, &entry.key))
+ && let Some(plan) = history.plan_traversal(target)
{
- history.traverse(target);
+ history.commit_traversal(&plan);
}
}
}
@@ -402,24 +407,69 @@ pub(crate) fn prune_joint_session_history(scope: &mut v8::PinScope<'_, '_>) {
);
}
-pub(super) fn targets_at<'s>(
+pub(super) fn plan_traversal<'s>(
scope: &mut v8::PinScope<'s, '_>,
owner: v8::Local<'s, v8::Object>,
step: SessionHistoryStepId,
+) -> Option<SessionHistoryTraversalPlan> {
+ let host = unsafe { &mut *context_host_ptr_from_global_bridge(scope)? };
+ let binding = binding(scope, host, owner);
+ host.session_histories
+ .get_mut(binding.popup)
+ .plan_traversal(step)
+}
+
+/// Preserve the admitted transition across V8 continuations without storing
+/// native pointers. Unchanged contexts may attach/detach while admission waits;
+/// a new changing participant or timeline mutation requires fresh admission.
+pub(super) fn traversal_admission_signature(plan: &SessionHistoryTraversalPlan) -> String {
+ fn identity(entry: &SessionHistoryEntry) -> (&str, &str) {
+ (entry.key.as_str(), entry.document.as_str())
+ }
+ let changes = plan
+ .changes()
+ .iter()
+ .map(|change| {
+ (
+ change.context.raw(),
+ change.from.as_ref().map(identity),
+ change.to.as_ref().map(identity),
+ )
+ })
+ .collect::<Vec<_>>();
+ serde_json::to_string(&(
+ plan.revision().raw(),
+ plan.source_step().raw(),
+ plan.target_step().raw(),
+ plan.delta(),
+ changes,
+ ))
+ .expect("history admission identities serialize without loss")
+}
+
+pub(super) fn project_traversal<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ owner: v8::Local<'s, v8::Object>,
+ plan: &SessionHistoryTraversalPlan,
) -> Option<Vec<super::navigation_traversal_execution::TraversalTarget<'s>>> {
let host = unsafe { &mut *context_host_ptr_from_global_bridge(scope)? };
let binding = binding(scope, host, owner);
- let entries = host
+ if !host
.session_histories
.get_mut(binding.popup)
- .entries_at(step)?
- .clone();
- // An opaque browser-owned step must go back to the browser controller.
+ .is_traversal_plan_current(plan)
+ {
+ return None;
+ }
+ let entries = plan.target_entries();
+ // Opaque browser-owned steps return to the browser controller. Project
+ // the complete destination because live Documents may still be loading a
+ // previously accepted step, even for a context unchanged in this plan.
if !entries.contains_key(&SessionHistoryContextId::ROOT) {
return None;
}
let mut targets = Vec::new();
- for (context, entry) in entries {
+ for (&context, entry) in entries {
let Some(owner) = owner_for_context(scope, host, context, binding.popup) else {
continue;
};
@@ -447,7 +497,7 @@ pub(super) fn targets_at<'s>(
history,
current_index,
target_index,
- joint_step: Some(step),
+ joint_step: Some(plan.target_step()),
});
}
}
@@ -457,11 +507,13 @@ pub(super) fn targets_at<'s>(
pub(super) fn commit_traversal<'s>(
scope: &mut v8::PinScope<'s, '_>,
owner: v8::Local<'s, v8::Object>,
- step: SessionHistoryStepId,
+ plan: &SessionHistoryTraversalPlan,
) -> Option<i64> {
let host = unsafe { &mut *context_host_ptr_from_global_bridge(scope)? };
let binding = binding(scope, host, owner);
- host.session_histories.get_mut(binding.popup).traverse(step)
+ host.session_histories
+ .get_mut(binding.popup)
+ .commit_traversal(plan)
}
pub(super) fn publish<'s>(
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents.rs
index fd33127ae..5f691b6c9 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents.rs
@@ -42,7 +42,7 @@ fn configure_child_document_navigation_request(
#[derive(Debug, Clone)]
pub(super) struct PendingChildDocumentNavigation {
- pub(super) admitted_history_entry: Option<moli_page_types::SessionHistoryEntry>,
+ pub(super) admitted_history_entry: Option<moli_session_history::SessionHistoryEntry>,
pub(super) target: ChildDocumentNavigationFetchTarget,
pub(super) target_url: Url,
pub(super) resource_loader: crate::network::navigation::NavigationResourceLoader,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs
index 9707a0c2b..9af3dd82f 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_navigation/commands.rs
@@ -122,7 +122,7 @@ impl JsContextHost {
pub(crate) fn cancel_joint_child_history_navigation(
&mut self,
handle: DomHandle,
- step: moli_page_types::SessionHistoryStepId,
+ step: moli_session_history::SessionHistoryStepId,
) {
if self
.child_browsing_contexts
diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
index 65c1f0114..66ce9e635 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
@@ -197,9 +197,10 @@ pub(crate) use messages::{
PendingWindowMessage, PendingWindowMessageEndpoint, PendingWindowMessageSource,
};
pub(crate) use moli_page_types::{
- NavigationActivationSeed, NavigationHistoryDocumentId, NavigationHistoryEntryId,
- NavigationHistoryEntryKey, NavigationHistoryEntrySeed, NavigationHistorySerializedEntry,
+ NavigationActivationSeed, NavigationHistoryEntryId, NavigationHistoryEntrySeed,
+ NavigationHistorySerializedEntry,
};
+pub(crate) use moli_session_history::{NavigationHistoryDocumentId, NavigationHistoryEntryKey};
pub(crate) use navigation::{
PendingLocationNavigation, PendingLocationNavigationKind, PendingTopLevelNavigation,
};
diff --git a/moli-renderer-v8/src/native_bridge/context_host/session_history.rs b/moli-renderer-v8/src/native_bridge/context_host/session_history.rs
index 91be59e20..c353d8168 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/session_history.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/session_history.rs
@@ -1,5 +1,5 @@
use super::OwnerDispatchScope;
-use moli_page_types::{JointSessionHistory, SessionHistoryContextId};
+use moli_session_history::{JointSessionHistory, SessionHistoryContextId};
use std::collections::HashMap;
/// Each traversable owns one history. Lightweight popup Windows share a V8
@@ -15,7 +15,7 @@ impl RendererSessionHistories {
pub(crate) fn entry_is_current(
&self,
owner: OwnerDispatchScope,
- entry: &moli_page_types::SessionHistoryEntry,
+ entry: &moli_session_history::SessionHistoryEntry,
) -> bool {
let Some(context) = self.contexts.get(&owner).copied() else {
return false;
diff --git a/moli-renderer-v8/src/native_bridge/history_queue.rs b/moli-renderer-v8/src/native_bridge/history_queue.rs
index 1a781059b..7a2f3691c 100644
--- a/moli-renderer-v8/src/native_bridge/history_queue.rs
+++ b/moli-renderer-v8/src/native_bridge/history_queue.rs
@@ -54,7 +54,7 @@ pub(crate) struct QueuedNavigationApiTask {
}
pub(crate) struct PendingHistoryTraversal {
- pub(crate) joint_step: Option<moli_page_types::SessionHistoryStepId>,
+ pub(crate) joint_step: Option<moli_session_history::SessionHistoryStepId>,
pub(crate) target: WindowTaskTarget,
pub(crate) target_index: u32,
pub(crate) target_key: Option<String>,
@@ -135,7 +135,7 @@ impl HistoryQueueState {
relevant_context: WindowExecutionContextBinding,
target: WindowTaskTarget,
target_index: u32,
- joint_step: Option<moli_page_types::SessionHistoryStepId>,
+ joint_step: Option<moli_session_history::SessionHistoryStepId>,
target_key: Option<String>,
info: Option<v8::Global<v8::Value>>,
result: Option<PendingNavigationResult>,
@@ -393,8 +393,8 @@ impl JsContextHost {
pub(crate) fn pending_joint_history_step(
&self,
- history: &moli_page_types::JointSessionHistory,
- ) -> Option<moli_page_types::SessionHistoryStepId> {
+ history: &moli_session_history::JointSessionHistory,
+ ) -> Option<moli_session_history::SessionHistoryStepId> {
self.history_queue
.pending_history_traversal_tasks
.iter()
@@ -415,7 +415,7 @@ impl JsContextHost {
scope: &mut v8::PinScope<'s, '_>,
target: WindowTaskTarget,
target_index: u32,
- joint_step: Option<moli_page_types::SessionHistoryStepId>,
+ joint_step: Option<moli_session_history::SessionHistoryStepId>,
target_key: Option<String>,
) -> Option<RendererPageHistoryTraversalProducer> {
let execution_context = self.current_runtime_window_execution_context_identity(scope)?;
@@ -525,7 +525,7 @@ impl JsContextHost {
scope: &mut v8::PinScope<'s, '_>,
target: WindowTaskTarget,
target_index: u32,
- joint_step: Option<moli_page_types::SessionHistoryStepId>,
+ joint_step: Option<moli_session_history::SessionHistoryStepId>,
target_key: Option<String>,
info: Option<v8::Local<'s, v8::Value>>,
) -> Option<(
diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rs
index 9c6e10d05..3472300cd 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -818,7 +818,7 @@ pub struct RendererMainDocumentCommit {
pub secure_context_type: String,
pub timestamp: f64,
/// Browser-owned session-history cursor and length at this document's commit.
- pub session_history_position: Option<moli_page_types::SessionHistoryPosition>,
+ pub session_history_position: Option<moli_session_history::SessionHistoryPosition>,
}
#[derive(Debug, Clone, Default, PartialEq)]
diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs
index 4bcb0b0ee..835716ca3 100644
--- a/moli-renderer-v8/src/script_vm.rs
+++ b/moli-renderer-v8/src/script_vm.rs
@@ -5852,7 +5852,7 @@ impl ScriptVm {
pub(super) fn install_session_history_position(
&mut self,
- position: moli_page_types::SessionHistoryPosition,
+ position: moli_session_history::SessionHistoryPosition,
) {
let _ = self.with_default_context_scope(|scope, _runtime_ptr| {
super::context_bootstrap::install_session_history_position(scope, position);
diff --git a/moli-session-history/Cargo.toml b/moli-session-history/Cargo.toml
new file mode 100644
index 000000000..a6384b524
--- /dev/null
+++ b/moli-session-history/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+license.workspace = true
+name = "moli-session-history"
+version = "0.1.0"
+edition = "2024"
+
+[lints]
+workspace = true
diff --git a/moli-session-history/src/entry.rs b/moli-session-history/src/entry.rs
new file mode 100644
index 000000000..1aa6fbee2
--- /dev/null
+++ b/moli-session-history/src/entry.rs
@@ -0,0 +1,34 @@
+use crate::{NavigationHistoryDocumentId, NavigationHistoryEntryKey};
+
+/// Browser supplied position. It includes steps outside the current renderer's
+/// Navigation API view, including entries in other Documents and origins.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SessionHistoryPosition {
+ pub(crate) index: usize,
+ pub(crate) length: usize,
+}
+
+impl SessionHistoryPosition {
+ pub const INITIAL: Self = Self {
+ index: 0,
+ length: 1,
+ };
+
+ pub fn new(index: usize, length: usize) -> Option<Self> {
+ (index < length).then_some(Self { index, length })
+ }
+
+ pub fn index(self) -> usize {
+ self.index
+ }
+
+ pub fn length(self) -> usize {
+ self.length
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct SessionHistoryEntry {
+ pub key: NavigationHistoryEntryKey,
+ pub document: NavigationHistoryDocumentId,
+}
diff --git a/moli-session-history/src/identity.rs b/moli-session-history/src/identity.rs
new file mode 100644
index 000000000..8c7d76ebe
--- /dev/null
+++ b/moli-session-history/src/identity.rs
@@ -0,0 +1,166 @@
+use std::sync::atomic::{AtomicU64, Ordering};
+
+static NEXT_NAVIGATION_HISTORY_DOCUMENT_ID: AtomicU64 = AtomicU64::new(1);
+static NEXT_NAVIGATION_HISTORY_ENTRY_KEY: AtomicU64 = AtomicU64::new(1);
+
+/// Opaque identity shared by session-history entries that belong to the same
+/// `Document`.
+///
+/// The serialized token is carried through the renderer's hidden Navigation
+/// slots, but its contents have no meaning. In particular, callers must not
+/// derive a new identity from a URL, a history index, or a previous token.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct NavigationHistoryDocumentId(String);
+
+impl NavigationHistoryDocumentId {
+ pub fn allocate() -> Self {
+ allocate_navigation_history_document_id(&NEXT_NAVIGATION_HISTORY_DOCUMENT_ID)
+ }
+
+ /// Restores an identity previously stored in a renderer-owned runtime
+ /// slot. Equality remains opaque; the token is never parsed.
+ pub fn from_serialized(token: String) -> Self {
+ Self(token)
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+fn allocate_navigation_history_document_id(counter: &AtomicU64) -> NavigationHistoryDocumentId {
+ let raw = counter
+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
+ current.checked_add(1)
+ })
+ .expect("Navigation History Document id allocator exhausted");
+ NavigationHistoryDocumentId(format!("document-{raw}"))
+}
+
+/// Opaque identity for one session-history slot exposed to Navigation API.
+///
+/// Same-origin replacement retains the key; push and cross-origin
+/// replacement allocate a fresh key. The token is never derived from a URL,
+/// history index, or Document id.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct NavigationHistoryEntryKey(String);
+
+impl NavigationHistoryEntryKey {
+ pub fn allocate() -> Self {
+ allocate_navigation_history_entry_key(&NEXT_NAVIGATION_HISTORY_ENTRY_KEY)
+ }
+
+ pub fn from_serialized(token: String) -> Self {
+ Self(token)
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl std::ops::Deref for NavigationHistoryEntryKey {
+ type Target = str;
+
+ fn deref(&self) -> &Self::Target {
+ self.as_str()
+ }
+}
+
+fn allocate_navigation_history_entry_key(counter: &AtomicU64) -> NavigationHistoryEntryKey {
+ let raw = counter
+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
+ current.checked_add(1)
+ })
+ .expect("Navigation History entry key allocator exhausted");
+ NavigationHistoryEntryKey(format!("key-{raw}"))
+}
+
+static NEXT_CONTEXT: AtomicU64 = AtomicU64::new(1);
+static NEXT_STEP: AtomicU64 = AtomicU64::new(1);
+static NEXT_REVISION: AtomicU64 = AtomicU64::new(1);
+
+fn allocate(counter: &AtomicU64) -> u64 {
+ counter
+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
+ value.checked_add(1)
+ })
+ .expect("session history identity allocator exhausted")
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct SessionHistoryContextId(u64);
+
+impl SessionHistoryContextId {
+ pub const ROOT: Self = Self(0);
+
+ pub fn allocate() -> Self {
+ Self(allocate(&NEXT_CONTEXT))
+ }
+
+ /// Opaque equality token for an adapter's private admission snapshot.
+ pub fn raw(self) -> u64 {
+ self.0
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SessionHistoryStepId(u64);
+
+impl SessionHistoryStepId {
+ pub(crate) fn allocate() -> Self {
+ Self(allocate(&NEXT_STEP))
+ }
+
+ pub fn raw(self) -> u64 {
+ self.0
+ }
+
+ /// Restore an opaque identity held by a renderer's private task slot.
+ pub fn from_raw(raw: u64) -> Self {
+ Self(raw)
+ }
+}
+
+/// Opaque version of the joint timeline and entry identities. Context topology
+/// is checked against the plan's transitions separately: attaching an unchanged
+/// context must not cancel an admitted navigation in another frame. Independent
+/// timeline mutations get distinct revisions even if they return to the same cursor.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct SessionHistoryRevision(u64);
+
+impl SessionHistoryRevision {
+ pub(crate) fn allocate() -> Self {
+ Self(allocate(&NEXT_REVISION))
+ }
+
+ /// Store the token in an adapter's private continuation slot. It is only
+ /// meaningful for equality, never as a cursor, counter, or time value.
+ pub fn raw(self) -> u64 {
+ self.0
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn identity_allocators_reject_exhaustion_without_wrapping() {
+ for allocate_id in [
+ |counter: &AtomicU64| {
+ allocate(counter);
+ },
+ |counter: &AtomicU64| {
+ allocate_navigation_history_document_id(counter);
+ },
+ |counter: &AtomicU64| {
+ allocate_navigation_history_entry_key(counter);
+ },
+ ] {
+ let counter = AtomicU64::new(u64::MAX);
+ assert!(std::panic::catch_unwind(|| allocate_id(&counter)).is_err());
+ assert_eq!(counter.load(Ordering::Relaxed), u64::MAX);
+ }
+ }
+}
diff --git a/moli-session-history/src/joint.rs b/moli-session-history/src/joint.rs
new file mode 100644
index 000000000..b5f0c074f
--- /dev/null
+++ b/moli-session-history/src/joint.rs
@@ -0,0 +1,326 @@
+use std::collections::{BTreeMap, BTreeSet};
+
+use crate::{
+ NavigationHistoryEntryKey, SessionHistoryContextId, SessionHistoryEntry,
+ SessionHistoryPosition, SessionHistoryStepId,
+};
+use crate::{SessionHistoryContextChange, SessionHistoryRevision, SessionHistoryTraversalPlan};
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct SessionHistoryStep {
+ id: SessionHistoryStepId,
+ entries: BTreeMap<SessionHistoryContextId, SessionHistoryEntry>,
+}
+
+/// Page-owned authority for joint history. No URL, Navigation API index, or
+/// per-Window cached length participates in history bookkeeping.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct JointSessionHistory {
+ revision: SessionHistoryRevision,
+ steps: Vec<SessionHistoryStep>,
+ current: usize,
+ parents: BTreeMap<SessionHistoryContextId, SessionHistoryContextId>,
+}
+
+impl Default for JointSessionHistory {
+ fn default() -> Self {
+ Self::new(SessionHistoryPosition::INITIAL)
+ }
+}
+
+impl JointSessionHistory {
+ pub fn new(position: SessionHistoryPosition) -> Self {
+ Self {
+ revision: SessionHistoryRevision::allocate(),
+ steps: (0..position.length)
+ .map(|_| SessionHistoryStep {
+ id: SessionHistoryStepId::allocate(),
+ entries: BTreeMap::new(),
+ })
+ .collect(),
+ current: position.index,
+ parents: BTreeMap::new(),
+ }
+ }
+
+ pub fn position(&self) -> SessionHistoryPosition {
+ SessionHistoryPosition {
+ index: self.current,
+ length: self.steps.len(),
+ }
+ }
+
+ pub fn current_step(&self) -> SessionHistoryStepId {
+ self.steps[self.current].id
+ }
+
+ pub fn entry(&self, context: SessionHistoryContextId) -> Option<&SessionHistoryEntry> {
+ self.steps[self.current].entries.get(&context)
+ }
+
+ /// Attaching an initial document adds no step. Its entry is also active at
+ /// other steps in the same parent Document, including its forward history.
+ pub fn attach(
+ &mut self,
+ context: SessionHistoryContextId,
+ parent: Option<SessionHistoryContextId>,
+ entry: SessionHistoryEntry,
+ ) {
+ if self.entry(context).is_some() {
+ return;
+ }
+ let parent_document =
+ parent.and_then(|parent| self.entry(parent).map(|e| e.document.clone()));
+ if let Some(parent) = parent {
+ self.parents.insert(context, parent);
+ }
+ for (index, step) in self.steps.iter_mut().enumerate() {
+ let same_parent_document =
+ parent
+ .zip(parent_document.as_ref())
+ .is_some_and(|(parent, document)| {
+ step.entries
+ .get(&parent)
+ .is_some_and(|e| &e.document == document)
+ });
+ if index == self.current || same_parent_document {
+ step.entries.entry(context).or_insert_with(|| entry.clone());
+ }
+ }
+ }
+
+ pub fn push(&mut self, context: SessionHistoryContextId, entry: SessionHistoryEntry) {
+ let mut next = self.steps[self.current].clone();
+ next.id = SessionHistoryStepId::allocate();
+ self.remove_replaced_document_children(&mut next, context, &entry);
+ next.entries.insert(context, entry);
+ self.steps.truncate(self.current + 1);
+ self.steps.push(next);
+ self.current += 1;
+ self.revision = SessionHistoryRevision::allocate();
+ }
+
+ pub fn replace(&mut self, context: SessionHistoryContextId, entry: SessionHistoryEntry) {
+ if self.entry(context) == Some(&entry) {
+ return;
+ }
+ let old_key = self.entry(context).map(|entry| entry.key.clone());
+ let descendants = self.descendants(context);
+ for (index, step) in self.steps.iter_mut().enumerate() {
+ if index == self.current
+ || old_key
+ .as_ref()
+ .is_some_and(|key| step.entries.get(&context).is_some_and(|e| &e.key == key))
+ {
+ if step
+ .entries
+ .get(&context)
+ .is_some_and(|old| old.document != entry.document)
+ {
+ step.entries.retain(|id, _| !descendants.contains(id));
+ }
+ step.entries.insert(context, entry.clone());
+ }
+ }
+ self.revision = SessionHistoryRevision::allocate();
+ }
+
+ pub fn step_by_delta(&self, delta: i64) -> Option<SessionHistoryStepId> {
+ self.step_by_delta_from(self.current_step(), delta)
+ }
+
+ /// Resolve queued relative work without changing even a temporary cursor.
+ pub fn step_by_delta_from(
+ &self,
+ source: SessionHistoryStepId,
+ delta: i64,
+ ) -> Option<SessionHistoryStepId> {
+ let source = self.steps.iter().position(|step| step.id == source)?;
+ let index = i64::try_from(source).ok()?.checked_add(delta)?;
+ self.steps
+ .get(usize::try_from(index).ok()?)
+ .map(|step| step.id)
+ }
+
+ pub fn delta_to(&self, target: SessionHistoryStepId) -> Option<i64> {
+ let next = self.steps.iter().position(|step| step.id == target)?;
+ Some(i64::try_from(next).ok()? - i64::try_from(self.current).ok()?)
+ }
+
+ pub fn steps_for_entry(
+ &self,
+ context: SessionHistoryContextId,
+ key: &NavigationHistoryEntryKey,
+ ) -> Vec<usize> {
+ self.steps
+ .iter()
+ .enumerate()
+ .filter_map(|(index, step)| {
+ step.entries
+ .get(&context)
+ .is_some_and(|entry| &entry.key == key)
+ .then_some(index)
+ })
+ .collect()
+ }
+
+ /// An entry can span several joint steps made by other frames. Traversal
+ /// chooses the nearest such step, preserving intervening frame history.
+ pub fn step_for_entry(
+ &self,
+ context: SessionHistoryContextId,
+ key: &NavigationHistoryEntryKey,
+ ) -> Option<SessionHistoryStepId> {
+ let matches = |step: &&SessionHistoryStep| {
+ step.entries
+ .get(&context)
+ .is_some_and(|entry| &entry.key == key)
+ };
+ self.steps[..=self.current]
+ .iter()
+ .rev()
+ .find(matches)
+ .or_else(|| self.steps[self.current + 1..].iter().find(matches))
+ .map(|step| step.id)
+ }
+
+ pub fn entries_at(
+ &self,
+ target: SessionHistoryStepId,
+ ) -> Option<&BTreeMap<SessionHistoryContextId, SessionHistoryEntry>> {
+ self.steps
+ .iter()
+ .find(|step| step.id == target)
+ .map(|step| &step.entries)
+ }
+
+ /// Capture the complete joint transition before an adapter runs admission.
+ pub fn plan_traversal(
+ &self,
+ target: SessionHistoryStepId,
+ ) -> Option<SessionHistoryTraversalPlan> {
+ let next = self.steps.iter().position(|step| step.id == target)?;
+ let delta = i64::try_from(next).ok()? - i64::try_from(self.current).ok()?;
+ let source = &self.steps[self.current].entries;
+ let destination = &self.steps[next].entries;
+ let contexts = source
+ .keys()
+ .chain(destination.keys())
+ .copied()
+ .collect::<BTreeSet<_>>();
+ let changes = contexts
+ .into_iter()
+ .filter_map(|context| {
+ let from = source.get(&context);
+ let to = destination.get(&context);
+ (from != to).then(|| SessionHistoryContextChange {
+ context,
+ from: from.cloned(),
+ to: to.cloned(),
+ })
+ })
+ .collect();
+ Some(SessionHistoryTraversalPlan {
+ revision: self.revision,
+ source_step: self.current_step(),
+ target_step: target,
+ delta,
+ changes,
+ target_entries: destination.clone(),
+ })
+ }
+
+ pub fn is_traversal_plan_current(&self, plan: &SessionHistoryTraversalPlan) -> bool {
+ self.revision == plan.revision
+ && self.current_step() == plan.source_step
+ && self
+ .plan_traversal(plan.target_step)
+ .is_some_and(|current| current.changes == plan.changes)
+ }
+
+ /// Commit exactly the admitted proposal. A stale plan cannot be repaired
+ /// by silently resolving its target again; admission must be restarted.
+ pub fn commit_traversal(&mut self, plan: &SessionHistoryTraversalPlan) -> Option<i64> {
+ if !self.is_traversal_plan_current(plan) {
+ return None;
+ }
+ let next = self
+ .steps
+ .iter()
+ .position(|step| step.id == plan.target_step)?;
+ self.current = next;
+ self.revision = SessionHistoryRevision::allocate();
+ Some(plan.delta)
+ }
+
+ pub fn contains_entry(
+ &self,
+ context: SessionHistoryContextId,
+ key: &NavigationHistoryEntryKey,
+ ) -> bool {
+ self.steps.iter().any(|step| {
+ step.entries
+ .get(&context)
+ .is_some_and(|entry| &entry.key == key)
+ })
+ }
+
+ pub fn prune_all_but_current(&mut self) {
+ if self.steps.len() == 1 {
+ return;
+ }
+ let current = self.steps[self.current].clone();
+ self.steps = vec![current];
+ self.current = 0;
+ self.revision = SessionHistoryRevision::allocate();
+ }
+
+ pub fn detach(&mut self, context: SessionHistoryContextId) {
+ let mut removed = self.descendants(context);
+ removed.push(context);
+ if !self.parents.keys().any(|id| removed.contains(id))
+ && !self
+ .steps
+ .iter()
+ .any(|step| step.entries.keys().any(|id| removed.contains(id)))
+ {
+ return;
+ }
+ for step in &mut self.steps {
+ step.entries.retain(|id, _| !removed.contains(id));
+ }
+ self.parents.retain(|id, _| !removed.contains(id));
+ }
+
+ fn descendants(&self, context: SessionHistoryContextId) -> Vec<SessionHistoryContextId> {
+ let mut found = vec![context];
+ let mut index = 0;
+ while index < found.len() {
+ let parent = found[index];
+ found.extend(
+ self.parents
+ .iter()
+ .filter_map(|(child, candidate)| (*candidate == parent).then_some(*child)),
+ );
+ index += 1;
+ }
+ found.remove(0);
+ found
+ }
+
+ fn remove_replaced_document_children(
+ &self,
+ step: &mut SessionHistoryStep,
+ context: SessionHistoryContextId,
+ entry: &SessionHistoryEntry,
+ ) {
+ if step
+ .entries
+ .get(&context)
+ .is_some_and(|old| old.document != entry.document)
+ {
+ let descendants = self.descendants(context);
+ step.entries.retain(|id, _| !descendants.contains(id));
+ }
+ }
+}
diff --git a/moli-session-history/src/lib.rs b/moli-session-history/src/lib.rs
new file mode 100644
index 000000000..b83b0f6de
--- /dev/null
+++ b/moli-session-history/src/lib.rs
@@ -0,0 +1,23 @@
+//! The pure state machine of a traversable's joint session history.
+//!
+//! This crate owns identities, joint steps, and validated traversal plans. It
+//! does not own Documents, renderer objects, URLs, event dispatch, or protocol
+//! projections. A renderer admits and schedules every participant before
+//! committing the plan. Timeline mutations or changed participant transitions
+//! invalidate it; an unchanged context can attach without canceling traversal.
+
+mod entry;
+mod identity;
+mod joint;
+mod traversal;
+
+pub use entry::{SessionHistoryEntry, SessionHistoryPosition};
+pub use identity::{
+ NavigationHistoryDocumentId, NavigationHistoryEntryKey, SessionHistoryContextId,
+ SessionHistoryRevision, SessionHistoryStepId,
+};
+pub use joint::JointSessionHistory;
+pub use traversal::{SessionHistoryContextChange, SessionHistoryTraversalPlan};
+
+#[cfg(test)]
+mod tests;
diff --git a/moli-session-history/src/tests.rs b/moli-session-history/src/tests.rs
new file mode 100644
index 000000000..a382ebd64
--- /dev/null
+++ b/moli-session-history/src/tests.rs
@@ -0,0 +1,331 @@
+use super::*;
+
+#[test]
+fn traversal_plan_contains_the_entire_mixed_transition_in_either_context_order() {
+ for cross_created_first in [true, false] {
+ let mut history = JointSessionHistory::default();
+ let root = SessionHistoryContextId::ROOT;
+ let first = SessionHistoryContextId::allocate();
+ let second = SessionHistoryContextId::allocate();
+ let (cross, same) = if cross_created_first {
+ (first, second)
+ } else {
+ (second, first)
+ };
+ history.attach(root, None, entry("top", "top"));
+ history.attach(cross, Some(root), entry("a0", "a-document-0"));
+ history.attach(same, Some(root), entry("b0", "b-document"));
+ let target = history.current_step();
+ history.push(cross, entry("a1", "a-document-1"));
+ history.push(same, entry("b1", "b-document"));
+ let before = history.clone();
+ let plan = history.plan_traversal(target).unwrap();
+ assert_eq!(history, before, "planning must not change the cursor");
+ assert_eq!(plan.source_step(), before.current_step());
+ assert_eq!(plan.target_step(), target);
+ assert_eq!(plan.delta(), -2);
+ assert_eq!(plan.changes().len(), 2);
+ for (context, from, to) in [
+ (
+ cross,
+ entry("a1", "a-document-1"),
+ entry("a0", "a-document-0"),
+ ),
+ (same, entry("b1", "b-document"), entry("b0", "b-document")),
+ ] {
+ assert_eq!(
+ plan.changes()
+ .iter()
+ .find(|change| change.context == context),
+ Some(&SessionHistoryContextChange {
+ context,
+ from: Some(from),
+ to: Some(to)
+ })
+ );
+ }
+ assert_eq!(plan.target_entries().get(&root), Some(&entry("top", "top")));
+ assert_eq!(history.commit_traversal(&plan), Some(-2));
+ assert_eq!(history.entry(cross), Some(&entry("a0", "a-document-0")));
+ assert_eq!(history.entry(same), Some(&entry("b0", "b-document")));
+ assert_eq!(
+ history.position(),
+ SessionHistoryPosition::new(0, 3).unwrap()
+ );
+ assert_eq!(
+ history.commit_traversal(&plan),
+ None,
+ "an accepted plan cannot be replayed"
+ );
+ }
+}
+
+#[test]
+fn intervening_mutations_reject_the_whole_plan_without_modifying_history() {
+ let root = SessionHistoryContextId::ROOT;
+ let child = SessionHistoryContextId::allocate();
+ let mut source = JointSessionHistory::default();
+ source.attach(root, None, entry("top", "top"));
+ source.attach(child, Some(root), entry("child-0", "child-0"));
+ let target = source.current_step();
+ source.push(child, entry("child-1", "child-1"));
+ for mutation in ["push", "replace", "attach", "detach", "prune", "traverse"] {
+ let mut history = source.clone();
+ let plan = history.plan_traversal(target).unwrap();
+ match mutation {
+ "push" => history.push(root, entry("top-2", "top")),
+ "replace" => history.replace(child, entry("replacement", "child")),
+ "attach" => history.attach(
+ SessionHistoryContextId::allocate(),
+ Some(child),
+ entry("new", "new"),
+ ),
+ "detach" => history.detach(child),
+ "prune" => history.prune_all_but_current(),
+ "traverse" => {
+ history
+ .commit_traversal(&history.plan_traversal(target).unwrap())
+ .unwrap();
+ }
+ _ => unreachable!(),
+ }
+ let after_mutation = history.clone();
+ assert_eq!(history.commit_traversal(&plan), None, "{mutation}");
+ assert_eq!(
+ history, after_mutation,
+ "a stale {mutation} plan must have no effects"
+ );
+ }
+}
+
+#[test]
+fn returning_to_the_same_cursor_does_not_revive_an_old_plan() {
+ let root = SessionHistoryContextId::ROOT;
+ let mut history = JointSessionHistory::default();
+ history.attach(root, None, entry("a", "top"));
+ let a = history.current_step();
+ history.push(root, entry("b", "top"));
+ let b = history.current_step();
+ history.push(root, entry("c", "top"));
+ let c = history.current_step();
+ let stale = history.plan_traversal(b).unwrap();
+ for target in [a, c] {
+ let plan = history.plan_traversal(target).unwrap();
+ history.commit_traversal(&plan).unwrap();
+ }
+ assert_eq!(history.commit_traversal(&stale), None);
+ assert_eq!(history.entry(root), Some(&entry("c", "top")));
+}
+
+#[test]
+fn independently_mutated_snapshots_cannot_accept_each_others_plans() {
+ let root = SessionHistoryContextId::ROOT;
+ let mut first = JointSessionHistory::default();
+ first.attach(root, None, entry("a", "top"));
+ let target = first.current_step();
+ first.push(root, entry("b", "top"));
+ let mut second = first.clone();
+ for history in [&mut first, &mut second] {
+ history.replace(root, entry("b-replaced", "top"));
+ }
+ assert_eq!(first.position(), second.position());
+ assert_eq!(first.entry(root), second.entry(root));
+ let plan = first.plan_traversal(target).unwrap();
+ assert_eq!(second.commit_traversal(&plan), None);
+ assert_eq!(first.commit_traversal(&plan), Some(-1));
+}
+
+#[test]
+fn replacement_keeps_the_step_identity_but_invalidates_its_plans() {
+ let root = SessionHistoryContextId::ROOT;
+ let child = SessionHistoryContextId::allocate();
+ let mut history = JointSessionHistory::default();
+ history.attach(root, None, entry("top", "top"));
+ history.attach(child, Some(root), entry("child-0", "child"));
+ let target = history.current_step();
+ history.push(child, entry("child-1", "child"));
+ let plan = history.plan_traversal(target).unwrap();
+ history.replace(root, entry("top-replaced", "top"));
+ assert!(history.entries_at(target).is_some());
+ assert_eq!(history.commit_traversal(&plan), None);
+ assert_eq!(plan.target_entries().get(&root), Some(&entry("top", "top")));
+ assert_eq!(
+ history
+ .plan_traversal(target)
+ .unwrap()
+ .target_entries()
+ .get(&root),
+ Some(&entry("top-replaced", "top"))
+ );
+}
+
+#[test]
+fn parent_document_replacement_plans_descendant_removal_and_restoration() {
+ let root = SessionHistoryContextId::ROOT;
+ let child = SessionHistoryContextId::allocate();
+ let grandchild = SessionHistoryContextId::allocate();
+ let mut history = JointSessionHistory::default();
+ history.attach(root, None, entry("top-0", "document-0"));
+ history.attach(child, Some(root), entry("child", "child"));
+ history.attach(grandchild, Some(child), entry("grandchild", "grandchild"));
+ let previous = history.current_step();
+ history.push(root, entry("top-1", "document-1"));
+ let next = history.current_step();
+ let back = history.plan_traversal(previous).unwrap();
+ for context in [child, grandchild] {
+ let change = back
+ .changes()
+ .iter()
+ .find(|change| change.context == context)
+ .unwrap();
+ assert!(change.from.is_none());
+ assert!(change.to.is_some());
+ }
+ history.commit_traversal(&back).unwrap();
+ let forward = history.plan_traversal(next).unwrap();
+ for context in [child, grandchild] {
+ let change = forward
+ .changes()
+ .iter()
+ .find(|change| change.context == context)
+ .unwrap();
+ assert!(change.from.is_some());
+ assert!(change.to.is_none());
+ }
+}
+
+#[test]
+fn idempotent_projection_updates_do_not_invalidate_a_plan() {
+ let root = SessionHistoryContextId::ROOT;
+ let mut history = JointSessionHistory::default();
+ history.attach(root, None, entry("a", "top"));
+ let previous = history.current_step();
+ history.push(root, entry("b", "top"));
+ let plan = history.plan_traversal(previous).unwrap();
+ history.attach(root, None, entry("b", "top"));
+ history.replace(root, entry("b", "top"));
+ history.detach(SessionHistoryContextId::allocate());
+ assert_eq!(history.commit_traversal(&plan), Some(-1));
+}
+
+#[test]
+fn unchanged_context_attachment_preserves_admission_and_survives_commit() {
+ let root = SessionHistoryContextId::ROOT;
+ let child = SessionHistoryContextId::allocate();
+ let mut history = JointSessionHistory::default();
+ history.attach(root, None, entry("a", "top"));
+ let target = history.current_step();
+ history.push(root, entry("b", "top"));
+ let plan = history.plan_traversal(target).unwrap();
+ history.attach(child, Some(root), entry("child", "child"));
+ assert!(history.is_traversal_plan_current(&plan));
+ assert_eq!(history.commit_traversal(&plan), Some(-1));
+ assert_eq!(history.entry(child), Some(&entry("child", "child")));
+
+ let forward = history
+ .plan_traversal(history.step_by_delta(1).unwrap())
+ .unwrap();
+ history.detach(child);
+ assert_eq!(history.commit_traversal(&forward), Some(1));
+ assert!(history.entry(child).is_none());
+}
+
+fn entry(key: &str, document: &str) -> SessionHistoryEntry {
+ SessionHistoryEntry {
+ key: NavigationHistoryEntryKey::from_serialized(key.into()),
+ document: NavigationHistoryDocumentId::from_serialized(document.into()),
+ }
+}
+
+#[test]
+fn branch_truncates_forward_steps_and_invalidates_queued_targets() {
+ let mut history = JointSessionHistory::default();
+ let root = SessionHistoryContextId::ROOT;
+ history.attach(root, None, entry("a", "top"));
+ for key in ["b", "c", "d"] {
+ history.push(root, entry(key, "top"));
+ }
+ let stale = history.current_step();
+ let b = history.step_by_delta(-2).unwrap();
+ let plan = history.plan_traversal(b).unwrap();
+ assert_eq!(history.commit_traversal(&plan), Some(-2));
+ history.push(root, entry("e", "top"));
+ assert_eq!(
+ history.position(),
+ SessionHistoryPosition::new(2, 3).unwrap()
+ );
+ assert!(history.plan_traversal(stale).is_none());
+ assert_eq!(history.entry(root), Some(&entry("e", "top")));
+}
+
+#[test]
+fn joint_steps_follow_commit_order_and_navigation_traversal_uses_nearest_step() {
+ let mut history = JointSessionHistory::default();
+ let root = SessionHistoryContextId::ROOT;
+ let a = SessionHistoryContextId::allocate();
+ let b = SessionHistoryContextId::allocate();
+ history.attach(root, None, entry("top", "top"));
+ history.attach(a, Some(root), entry("a0", "a"));
+ history.attach(b, Some(root), entry("b0", "b"));
+ history.push(a, entry("a1", "a"));
+ history.push(b, entry("b1", "b"));
+ history.push(a, entry("a2", "a"));
+ let target = history.step_for_entry(a, &entry("a1", "a").key).unwrap();
+ let plan = history.plan_traversal(target).unwrap();
+ assert_eq!(history.commit_traversal(&plan), Some(-1));
+ assert_eq!(history.entry(b), Some(&entry("b1", "b")));
+ let plan = history
+ .plan_traversal(history.step_by_delta(-1).unwrap())
+ .unwrap();
+ history.commit_traversal(&plan).unwrap();
+ assert_eq!(history.entry(b), Some(&entry("b0", "b")));
+ history.push(b, entry("b2", "b"));
+ assert_eq!(
+ history.position(),
+ SessionHistoryPosition::new(2, 3).unwrap()
+ );
+ assert!(!history.contains_entry(a, &entry("a2", "a").key));
+ assert!(!history.contains_entry(b, &entry("b1", "b").key));
+}
+
+#[test]
+fn replace_preserves_steps_and_updates_shared_entry_references() {
+ let mut history = JointSessionHistory::default();
+ let root = SessionHistoryContextId::ROOT;
+ let child = SessionHistoryContextId::allocate();
+ history.attach(root, None, entry("top", "top"));
+ history.attach(child, Some(root), entry("child0", "child"));
+ history.push(child, entry("child1", "child"));
+ let position = history.position();
+ history.replace(root, entry("top-replaced", "top"));
+ assert_eq!(history.position(), position);
+ let plan = history
+ .plan_traversal(history.step_by_delta(-1).unwrap())
+ .unwrap();
+ history.commit_traversal(&plan).unwrap();
+ assert_eq!(history.entry(root), Some(&entry("top-replaced", "top")));
+ history.replace(root, entry("new-document", "new-document"));
+ assert!(history.entry(child).is_none());
+ assert_eq!(history.position().length(), 2);
+}
+
+#[test]
+fn browser_position_includes_opaque_steps_and_push_uses_the_cursor() {
+ let mut history = JointSessionHistory::new(SessionHistoryPosition::new(1, 4).unwrap());
+ let root = SessionHistoryContextId::ROOT;
+ history.attach(root, None, entry("current", "document"));
+ history.push(root, entry("next", "document"));
+ assert_eq!(
+ history.position(),
+ SessionHistoryPosition::new(2, 3).unwrap()
+ );
+ assert_eq!(
+ history
+ .entries_at(history.step_by_delta(-2).unwrap())
+ .unwrap()
+ .len(),
+ 0
+ );
+ assert!(SessionHistoryPosition::new(0, 0).is_none());
+ assert!(SessionHistoryPosition::new(3, 3).is_none());
+}
diff --git a/moli-session-history/src/traversal.rs b/moli-session-history/src/traversal.rs
new file mode 100644
index 000000000..1a3a6c8e0
--- /dev/null
+++ b/moli-session-history/src/traversal.rs
@@ -0,0 +1,56 @@
+use std::collections::BTreeMap;
+
+use crate::{
+ SessionHistoryContextId, SessionHistoryEntry, SessionHistoryRevision, SessionHistoryStepId,
+};
+
+/// One context's state change in a joint traversal. A missing destination
+/// belongs to a context removed by an ancestor Document replacement.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct SessionHistoryContextChange {
+ pub context: SessionHistoryContextId,
+ pub from: Option<SessionHistoryEntry>,
+ pub to: Option<SessionHistoryEntry>,
+}
+
+/// An immutable proposal against one timeline revision and set of context
+/// transitions. Only the history can construct it; commit revalidates both.
+/// Script admission and document loading remain the adapter's responsibility.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct SessionHistoryTraversalPlan {
+ pub(crate) revision: SessionHistoryRevision,
+ pub(crate) source_step: SessionHistoryStepId,
+ pub(crate) target_step: SessionHistoryStepId,
+ pub(crate) delta: i64,
+ pub(crate) changes: Vec<SessionHistoryContextChange>,
+ pub(crate) target_entries: BTreeMap<SessionHistoryContextId, SessionHistoryEntry>,
+}
+
+impl SessionHistoryTraversalPlan {
+ pub fn revision(&self) -> SessionHistoryRevision {
+ self.revision
+ }
+
+ pub fn source_step(&self) -> SessionHistoryStepId {
+ self.source_step
+ }
+
+ pub fn target_step(&self) -> SessionHistoryStepId {
+ self.target_step
+ }
+
+ pub fn delta(&self) -> i64 {
+ self.delta
+ }
+
+ pub fn changes(&self) -> &[SessionHistoryContextChange] {
+ &self.changes
+ }
+
+ /// Complete destination projection, including unchanged contexts. An
+ /// adapter may still be materializing an earlier accepted Document load,
+ /// so its live views can lag behind the model's source entries.
+ pub fn target_entries(&self) -> &BTreeMap<SessionHistoryContextId, SessionHistoryEntry> {
+ &self.target_entries
+ }
+}