Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(history): share Window history across isolated worlds
ldm075e27973c37e
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rsindex 5f2e1f418..54ab3be4b 100644--- a/moli-renderer-v8/src/context_bootstrap.rs+++ b/moli-renderer-v8/src/context_bootstrap.rs@@ -23,6 +23,7 @@ mod form_data_runtime;mod geometry_runtime;mod history_mutation;mod history_runtime;+pub(crate) use history_runtime::state::bind_isolated_window_history_owner;mod idle_detection;mod image_data;mod javascript_url;diff --git a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs b/moli-renderer-v8/src/context_bootstrap/history_mutation.rsindex de66569a5..bd7e17b3f 100644--- a/moli-renderer-v8/src/context_bootstrap/history_mutation.rs+++ b/moli-renderer-v8/src/context_bootstrap/history_mutation.rs@@ -108,6 +108,12 @@ fn mutate_history_object<'s>(let Some(state) = structured_clone_value_for_storage(scope, parsed.state) else {return;};+ // Argument conversion/serialization belongs to the caller. Entry objects+ // and navigation events belong to the Window, regardless of the caller's world.+ let Some(context) = owner.get_creation_context(scope) else {+ return;+ };+ let scope = &mut v8::ContextScope::new(scope, context);let state_json = stringify_history_state(scope, state);let Some(location) = window_location_for_holder(scope, owner) else {return;diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime.rsindex 38fd89a2b..46af67426 100644--- a/moli-renderer-v8/src/context_bootstrap/history_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime.rs@@ -1,6 +1,7 @@mod admission;pub(super) mod apply;pub(super) mod results;+pub(super) mod state;pub(super) mod traversal;pub(super) use self::admission::require_fully_active_history_owner;diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rsnew file mode 100644index 000000000..11acdea62--- /dev/null+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/state.rs@@ -0,0 +1,199 @@+//! One History implementation per Window, with realm-local public wrappers.+//!+//! The private backing object keeps V8 payloads in the GC graph. Wrappers share+//! it rather than copying entry identities, the cursor, or restoration policy.+//! Only the deserialized `history.state` cache belongs to a particular wrapper.++use super::super::navigation_window::window_history_for_holder;+use super::super::structured_clone_value;+use crate::util::{get_private_value, private_key, set_private_value, v8_string};+use moli_webapi_declare::WebApiObject;++pub(in crate::context_bootstrap) const HISTORY_BACKING_SLOT: &str = "__moliHistoryBacking";+const WINDOW_HISTORY_OWNER_SLOT: &str = "__moliWindowHistoryOwner";+const ENTRIES_SLOT: &str = "entries";+const INDEX_SLOT: &str = "index";+const STATE_SLOT: &str = "state";+const SCROLL_RESTORATION_SLOT: &str = "scrollRestoration";+const CACHED_SNAPSHOT_SLOT: &str = "__moliHistoryCachedSnapshot";+const CACHED_STATE_SLOT: &str = "__moliHistoryCachedState";++#[derive(WebApiObject)]+#[webapi(plain)]+struct HistoryBackingDeclaration<'scope> {+ #[webapi(slot = ENTRIES_SLOT)]+ entries: v8::Local<'scope, v8::Array>,+ #[webapi(slot = INDEX_SLOT)]+ index: f64,+ #[webapi(slot = STATE_SLOT)]+ state: v8::Local<'scope, v8::Value>,+ #[webapi(slot = SCROLL_RESTORATION_SLOT)]+ scroll_restoration: &'static str,+}++/// Bind once during realm creation; never resolve an old wrapper to a new+/// document's current Window by looking up its frame at call time.+pub(crate) fn bind_isolated_window_history_owner<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ window: v8::Local<'s, v8::Object>,+ owner: v8::Local<'s, v8::Object>,+) {+ set_private_value(scope, window, WINDOW_HISTORY_OWNER_SLOT, owner.into());+}++pub(in crate::context_bootstrap) fn history_window_owner<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ window: v8::Local<'s, v8::Object>,+) -> v8::Local<'s, v8::Object> {+ get_private_value(scope, window, WINDOW_HISTORY_OWNER_SLOT)+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ .unwrap_or(window)+}++pub(in crate::context_bootstrap) fn window_has_shared_history<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ window: v8::Local<'s, v8::Object>,+) -> bool {+ !history_window_owner(scope, window).strict_equals(window.into())+}++pub(in crate::context_bootstrap) fn shared_history_backing<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ window: v8::Local<'s, v8::Object>,+) -> Option<v8::Local<'s, v8::Object>> {+ if !window_has_shared_history(scope, window) {+ return None;+ }+ let owner = history_window_owner(scope, window);+ let history = window_history_for_holder(scope, owner)?;+ backing(scope, history)+}++pub(in crate::context_bootstrap) fn new_history_backing<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ entries: v8::Local<'s, v8::Array>,+ index: u32,+) -> v8::Local<'s, v8::Object> {+ HistoryBackingDeclaration::new(entries, index as f64, v8::null(scope).into(), "auto")+ .bind(scope)+ .expect("History backing declaration should bind")+}++fn backing<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ history: v8::Local<'s, v8::Object>,+) -> Option<v8::Local<'s, v8::Object>> {+ get_private_value(scope, history, HISTORY_BACKING_SLOT)+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+}++pub(in crate::context_bootstrap) fn history_entries<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ history: v8::Local<'s, v8::Object>,+) -> Option<v8::Local<'s, v8::Array>> {+ let backing = backing(scope, history)?;+ get_private_value(scope, backing, ENTRIES_SLOT)+ .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())+}++pub(in crate::context_bootstrap) fn set_history_entries<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ history: v8::Local<'s, v8::Object>,+ entries: v8::Local<'s, v8::Array>,+) {+ if let Some(backing) = backing(scope, history) {+ set_private_value(scope, backing, ENTRIES_SLOT, entries.into());+ }+}++pub(in crate::context_bootstrap) fn history_index<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ history: v8::Local<'s, v8::Object>,+) -> u32 {+ backing(scope, history)+ .and_then(|backing| get_private_value(scope, backing, INDEX_SLOT))+ .and_then(|value| value.uint32_value(scope))+ .unwrap_or(0)+}++pub(in crate::context_bootstrap) fn set_history_index<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ history: v8::Local<'s, v8::Object>,+ index: u32,+) {+ if let Some(backing) = backing(scope, history) {+ set_private_value(+ scope,+ backing,+ INDEX_SLOT,+ v8::Integer::new_from_unsigned(scope, index).into(),+ );+ }+}++pub(in crate::context_bootstrap) fn history_scroll_restoration_value<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ history: v8::Local<'s, v8::Object>,+) -> Option<v8::Local<'s, v8::Value>> {+ let backing = backing(scope, history)?;+ get_private_value(scope, backing, SCROLL_RESTORATION_SLOT)+}++pub(in crate::context_bootstrap) fn set_history_scroll_restoration<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ history: v8::Local<'s, v8::Object>,+ value: &str,+) {+ if let Some(backing) = backing(scope, history)+ && let Some(value) = v8_string(scope, value)+ {+ set_private_value(scope, backing, SCROLL_RESTORATION_SLOT, value.into());+ }+}++pub(in crate::context_bootstrap) fn history_state_value<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ history: v8::Local<'s, v8::Object>,+) -> v8::Local<'s, v8::Value> {+ let snapshot = backing(scope, history)+ .and_then(|backing| {+ let key = private_key(scope, STATE_SLOT)?;+ backing.get_private(scope, key)+ })+ .unwrap_or_else(|| v8::null(scope).into());+ if !snapshot.is_object() {+ return snapshot;+ }+ if get_private_value(scope, history, CACHED_SNAPSHOT_SLOT)+ .is_some_and(|cached| cached.same_value(snapshot))+ && let Some(value) = get_private_value(scope, history, CACHED_STATE_SLOT)+ {+ return value;+ }+ let Some(context) = history.get_creation_context(scope) else {+ return v8::null(scope).into();+ };+ let scope = &mut v8::ContextScope::new(scope, context);+ let value = structured_clone_value(scope, snapshot).unwrap_or_else(|| v8::null(scope).into());+ set_private_value(scope, history, CACHED_SNAPSHOT_SLOT, snapshot);+ set_private_value(scope, history, CACHED_STATE_SLOT, value);+ value+}++pub(in crate::context_bootstrap) fn set_history_state<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ history: v8::Local<'s, v8::Object>,+ state: v8::Local<'s, v8::Value>,+) {+ let Some(backing) = backing(scope, history) else {+ return;+ };+ // The cache can be mutated by script (and is also popstate.state). Keep a+ // separate snapshot so another realm never deserializes those mutations.+ let snapshot = structured_clone_value(scope, state).unwrap_or_else(|| v8::null(scope).into());+ set_private_value(scope, backing, STATE_SLOT, snapshot);+ if history.get_creation_context(scope) == Some(scope.get_current_context()) {+ set_private_value(scope, history, CACHED_SNAPSHOT_SLOT, snapshot);+ set_private_value(scope, history, CACHED_STATE_SLOT, state);+ }+}diff --git a/moli-renderer-v8/src/context_bootstrap/location_history_storage.rs b/moli-renderer-v8/src/context_bootstrap/location_history_storage.rsindex 6fd828b7d..23a734495 100644--- a/moli-renderer-v8/src/context_bootstrap/location_history_storage.rs+++ b/moli-renderer-v8/src/context_bootstrap/location_history_storage.rs@@ -1,7 +1,3 @@-pub(super) const HISTORY_ENTRIES_SLOT: &str = "__lmHistoryEntries";-pub(super) const HISTORY_INDEX_SLOT: &str = "__lmHistoryIndex";-pub(super) const HISTORY_STATE_SLOT: &str = "__lmHistoryState";-pub(super) const HISTORY_SCROLL_RESTORATION_SLOT: &str = "__lmHistoryScrollRestoration";pub(super) const HISTORY_ENTRY_STATE_SNAPSHOT_SLOT: &str = "__lmHistoryEntryStateSnapshot";pub(super) const NAVIGATION_ENTRY_STATE_SNAPSHOT_SLOT: &str = "__lmNavigationEntryStateSnapshot";pub(super) const NAVIGATION_ENTRY_DOCUMENT_ID_SLOT: &str = "__lmNavigationEntryDocumentId";diff --git a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs b/moli-renderer-v8/src/context_bootstrap/location_navigation.rsindex 99568c4b2..8aa564beb 100644--- a/moli-renderer-v8/src/context_bootstrap/location_navigation.rs+++ b/moli-renderer-v8/src/context_bootstrap/location_navigation.rs@@ -212,6 +212,8 @@ fn navigate_location_object_with_source_element_and_child_navigate_event<'s>(dispatch_child_navigate_event_for_all_kinds: bool,force_exact_same_document_navigation: bool,) {+ let owner = runtime_window_owner(scope, location);+ let location = window_location_for_holder(scope, owner).unwrap_or(location);let current_href = location_href_slot(scope, location).unwrap_or_default();let current_url = url::Url::parse(¤t_href).ok();let raw_target_is_fragment_only = raw_targetdiff --git a/moli-renderer-v8/src/context_bootstrap/location_runtime/slots.rs b/moli-renderer-v8/src/context_bootstrap/location_runtime/slots.rsindex 0dc3843ae..20503dffb 100644--- a/moli-renderer-v8/src/context_bootstrap/location_runtime/slots.rs+++ b/moli-renderer-v8/src/context_bootstrap/location_runtime/slots.rs@@ -15,6 +15,17 @@ pub(in crate::context_bootstrap) fn location_href_slot<'s>(scope: &mut v8::PinScope<'s, '_>,object: v8::Local<'s, v8::Object>,) -> Option<String> {+ // Only a real Location wrapper may resolve the shared Window URL. The+ // generic owner helper falls back to the current global for unbound+ // objects, which would accidentally accept forged Location receivers.+ let object = get_private_value(+ scope,+ object,+ super::super::location_history_storage::WINDOW_RUNTIME_OWNER_SLOT,+ )+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())+ .and_then(|owner| super::super::navigation_window::window_location_for_holder(scope, owner))+ .unwrap_or(object);get_private_value(scope, object, WINDOW_LOCATION_HREF_SLOT).and_then(|value| value.to_string(scope)).map(|value| value.to_rust_string_lossy(scope))diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rsindex af2ecf844..1b2b94a19 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_activation.rs@@ -363,8 +363,8 @@ pub(super) fn navigation_current_entry_value<'s>(scope: &mut v8::PinScope<'s, '_>,navigation: v8::Local<'s, v8::Object>,) -> Option<v8::Local<'s, v8::Value>> {- get_private_value(scope, navigation, NAVIGATION_CURRENT_ENTRY_SLOT)- .filter(|value| !value.is_undefined())+ let owner = runtime_window_owner(scope, navigation);+ super::navigation_entry::navigation_current_entry(scope, owner).map(Into::into)}pub(super) fn navigation_activation_value<'s>(diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rsindex d94b604f2..5800bec3c 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_bootstrap.rs@@ -1,3 +1,4 @@+use super::history_runtime::state::{history_window_owner, window_has_shared_history};use super::location_history_storage::WINDOW_RUNTIME_OWNER_SLOT;use super::location_runtime::{build_location_runtime_object, install_location_runtime_state,@@ -38,7 +39,8 @@ fn new_location_runtime_object<'s>(href: &str,) -> Result<v8::Local<'s, v8::Object>> {let location = build_location_runtime_object(scope)?;- LocationRuntimeObjectDeclaration::new(window, href.to_owned())+ let owner = history_window_owner(scope, window);+ LocationRuntimeObjectDeclaration::new(owner, href.to_owned()).initialize(scope, location).map_err(|error| anyhow::anyhow!("failed to initialize Location object: {error}"))?;Ok(location)@@ -55,11 +57,12 @@ pub(crate) fn install_window_location_history_navigation_runtime_state<'s>(let initial_seed = initial_navigation_history_seed(scope, window, href);let history = build_history_runtime_state(scope, window, &initial_seed)?;- set_runtime_window_owner(scope, history, window);+ let owner = history_window_owner(scope, window);+ set_runtime_window_owner(scope, history, owner);set_private_value(scope, window, WINDOW_HISTORY_SLOT, history.into());let navigation = build_navigation_runtime_state(scope, window, &initial_seed)?;- set_runtime_window_owner(scope, navigation, window);+ set_runtime_window_owner(scope, navigation, owner);set_private_value(scope, window, WINDOW_NAVIGATION_SLOT, navigation.into());if crate::native_bridge::lightweight_popup_id_from_window(scope, window).is_some() {super::session_history::initialize(scope, window, &initial_seed);@@ -75,6 +78,11 @@ pub(crate) fn reset_window_location_history_navigation_runtime_state<'s>(window: v8::Local<'s, v8::Object>,href: &str,) -> Result<()> {+ // Creating/rebinding an isolated realm must never reset the Window's+ // shared history, including structured-clone state absent from JSON seeds.+ if window_has_shared_history(scope, window) {+ return Ok(());+ }let location = match window_runtime_object(scope, window, WINDOW_LOCATION_SLOT) {Some(location) => location,None => {diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rsindex 806539e0b..cb1ebaffb 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_entry.rs@@ -1,6 +1,9 @@+pub(super) use super::history_runtime::state::{+ history_entries, history_index, history_scroll_restoration_value, history_state_value,+ set_history_entries, set_history_index, set_history_scroll_restoration, set_history_state,+};use super::location_history_storage::{- HISTORY_ENTRIES_SLOT, HISTORY_ENTRY_STATE_SNAPSHOT_SLOT, HISTORY_INDEX_SLOT,- HISTORY_SCROLL_RESTORATION_SLOT, HISTORY_STATE_SLOT, NAVIGATION_CURRENT_ENTRY_SLOT,+ HISTORY_ENTRY_STATE_SNAPSHOT_SLOT, NAVIGATION_CURRENT_ENTRY_SLOT,NAVIGATION_ENTRY_DOCUMENT_ID_SLOT, NAVIGATION_ENTRY_EVENT_LISTENERS_SLOT,NAVIGATION_ENTRY_STATE_SNAPSHOT_SLOT,};@@ -112,13 +115,6 @@ fn finite_navigation_entry_number_slot<'s>(.filter(|value| value.is_finite())}-pub(super) fn history_state_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- history: v8::Local<'s, v8::Object>,-) -> v8::Local<'s, v8::Value> {- history_slot_value(scope, history, HISTORY_STATE_SLOT).unwrap_or_else(|| v8::null(scope).into())-}-pub(super) fn sync_navigation_current_entry_from_history_entry<'s>(scope: &mut v8::PinScope<'s, '_>,owner: v8::Local<'s, v8::Object>,@@ -545,25 +541,6 @@ fn set_navigation_entry_string_slot<'s>(}}-pub(super) fn history_entries<'s>(- scope: &mut v8::PinScope<'s, '_>,- history: v8::Local<'s, v8::Object>,-) -> Option<v8::Local<'s, v8::Array>> {- history_slot_value(scope, history, HISTORY_ENTRIES_SLOT)- .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())-}--pub(super) fn history_index<'s>(- scope: &mut v8::PinScope<'s, '_>,- history: v8::Local<'s, v8::Object>,-) -> u32 {- history_slot_value(scope, history, HISTORY_INDEX_SLOT)- .and_then(|value| value.integer_value(scope))- .filter(|value| *value >= 0)- .map(|value| value as u32)- .unwrap_or(0)-}-pub(super) fn navigation_current_entry_index<'s>(scope: &mut v8::PinScope<'s, '_>,owner: v8::Local<'s, v8::Object>,@@ -576,80 +553,12 @@ pub(super) fn navigation_current_entry<'s>(scope: &mut v8::PinScope<'s, '_>,owner: v8::Local<'s, v8::Object>,) -> Option<v8::Local<'s, v8::Object>> {+ let owner = super::history_runtime::state::history_window_owner(scope, owner);let navigation = window_navigation_for_holder(scope, owner)?;get_private_value(scope, navigation, NAVIGATION_CURRENT_ENTRY_SLOT).and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())}-fn history_slot_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- history: v8::Local<'s, v8::Object>,- slot: &str,-) -> Option<v8::Local<'s, v8::Value>> {- get_private_value(scope, history, slot)-}--fn set_history_slot_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- history: v8::Local<'s, v8::Object>,- slot: &str,- value: v8::Local<'s, v8::Value>,-) {- set_private_value(scope, history, slot, value);-}--pub(super) fn history_scroll_restoration_value<'s>(- scope: &mut v8::PinScope<'s, '_>,- history: v8::Local<'s, v8::Object>,-) -> Option<v8::Local<'s, v8::Value>> {- history_slot_value(scope, history, HISTORY_SCROLL_RESTORATION_SLOT)- .filter(|value| !value.is_undefined())-}--pub(super) fn set_history_entries<'s>(- scope: &mut v8::PinScope<'s, '_>,- history: v8::Local<'s, v8::Object>,- entries: v8::Local<'s, v8::Array>,-) {- set_history_slot_value(scope, history, HISTORY_ENTRIES_SLOT, entries.into());-}--pub(super) fn set_history_index<'s>(- scope: &mut v8::PinScope<'s, '_>,- history: v8::Local<'s, v8::Object>,- index: u32,-) {- set_history_slot_value(- scope,- history,- HISTORY_INDEX_SLOT,- v8::Number::new(scope, index as f64).into(),- );-}--pub(super) fn set_history_scroll_restoration<'s>(- scope: &mut v8::PinScope<'s, '_>,- history: v8::Local<'s, v8::Object>,- value: &str,-) {- if let Some(value) = v8_string(scope, value) {- set_history_slot_value(- scope,- history,- HISTORY_SCROLL_RESTORATION_SLOT,- value.into(),- );- }-}--pub(super) fn set_history_state<'s>(- scope: &mut v8::PinScope<'s, '_>,- history: v8::Local<'s, v8::Object>,- state: v8::Local<'s, v8::Value>,-) {- set_history_slot_value(scope, history, HISTORY_STATE_SLOT, state);-}-pub(super) fn stringify_history_state<'s>(scope: &mut v8::PinScope<'s, '_>,state: v8::Local<'s, v8::Value>,diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rs b/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rsindex 75e3839b1..1508403c4 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_entry_state.rs@@ -18,7 +18,9 @@ pub(super) fn history_entry_state_snapshot<'s>(scope: &mut v8::PinScope<'s, '_>,entry: v8::Local<'s, v8::Object>,) -> Option<v8::Local<'s, v8::Value>> {- navigation_entry_private_slot_value(scope, entry, HISTORY_ENTRY_STATE_SNAPSHOT_SLOT)+ // Unlike an absent optional slot, undefined is a valid History state.+ let key = crate::util::private_key(scope, HISTORY_ENTRY_STATE_SNAPSHOT_SLOT)?;+ entry.get_private(scope, key)}pub(super) fn clone_navigation_entry_state<'s>(diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs b/moli-renderer-v8/src/context_bootstrap/navigation_restore.rsindex 2d0d42d0d..be56c4104 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_restore.rs@@ -26,6 +26,9 @@ pub(crate) fn install_navigation_bootstrap_entry_for_holder<'s>(owner: v8::Local<'s, v8::Object>,entry_seed: &NavigationHistoryEntrySeed,) {+ if super::history_runtime::state::window_has_shared_history(scope, owner) {+ return;+ }install_navigation_entry_view_for_holder(scope, owner, entry_seed);commit_navigation_history_for_document(scope, owner, entry_seed);}@@ -50,6 +53,9 @@ pub(crate) fn install_navigation_entry_view_for_holder<'s>(owner: v8::Local<'s, v8::Object>,entry_seed: &NavigationHistoryEntrySeed,) {+ if super::history_runtime::state::window_has_shared_history(scope, owner) {+ return;+ }let Some(history) = window_history_for_holder(scope, owner) else {return;};diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_surface.rs b/moli-renderer-v8/src/context_bootstrap/navigation_surface.rsindex 378323439..d0bd8773c 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_surface.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_surface.rs@@ -1,6 +1,5 @@use super::history_mutation::{history_push_state_callback, history_replace_state_callback};use super::location_history_storage::{- HISTORY_ENTRIES_SLOT, HISTORY_INDEX_SLOT, HISTORY_SCROLL_RESTORATION_SLOT, HISTORY_STATE_SLOT,NAVIGATION_CURRENT_ENTRY_SLOT, NAVIGATION_EVENT_LISTENERS_SLOT,};use super::navigation_activation::install_navigation_activation_runtime_state;diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs b/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rsindex b79c970b7..c6f1d836c 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_surface/runtime.rs@@ -1,3 +1,6 @@+use super::super::history_runtime::state::{+ HISTORY_BACKING_SLOT, new_history_backing, shared_history_backing, window_has_shared_history,+};use super::super::navigation_entry::{history_entries, history_index, set_history_scroll_restoration, set_history_state,};@@ -13,17 +16,8 @@ use moli_webapi_declare::WebApiObject;#[derive(WebApiObject)]#[webapi(interface = web_api_interfaces::History)]struct HistoryRuntimeObjectDeclaration<'scope> {- #[webapi(slot = HISTORY_STATE_SLOT)]- state: v8::Local<'scope, v8::Value>,-- #[webapi(slot = HISTORY_SCROLL_RESTORATION_SLOT)]- scroll_restoration: &'static str,-- #[webapi(slot = HISTORY_ENTRIES_SLOT)]- entries: v8::Local<'scope, v8::Array>,-- #[webapi(slot = HISTORY_INDEX_SLOT)]- index: f64,+ #[webapi(slot = HISTORY_BACKING_SLOT)]+ backing: v8::Local<'scope, v8::Object>,}#[derive(WebApiObject)]@@ -53,15 +47,16 @@ pub(in crate::context_bootstrap) fn build_history_runtime_state<'s>(if let Some(prototype) = global_constructor_prototype(scope, "History") {install_history_prototype_accessors(scope, prototype);}- let entries = build_history_entries_array_from_seed(scope, window, initial_seed);- let history = HistoryRuntimeObjectDeclaration::new(- v8::null(scope).into(),- "auto",- entries,- initial_seed.current_index as f64,- )- .bind(scope)- .map_err(anyhow::Error::from)?;+ let backing = if window_has_shared_history(scope, window) {+ shared_history_backing(scope, window)+ .ok_or_else(|| anyhow::anyhow!("isolated History is missing its Window's backing"))?+ } else {+ let entries = build_history_entries_array_from_seed(scope, window, initial_seed);+ new_history_backing(scope, entries, initial_seed.current_index)+ };+ let history = HistoryRuntimeObjectDeclaration::new(backing)+ .bind(scope)+ .map_err(anyhow::Error::from)?;Ok(history)}diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rsindex ec05b979a..d154ce2df 100644--- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs@@ -184,9 +184,5 @@ pub(super) fn history_delta_traversal_plan<'s>(.pending_joint_history_step(&model).unwrap_or_else(|| model.current_step());let step = model.step_by_delta_from(source, delta)?;- // Queue entry identity from the same Window history used when applying- // the traversal, rather than an isolated world's independent JS view.- let owner =- super::session_history::owner_for_context(scope, host, binding.context, binding.popup)?;JointTraversalPlan::resolve(scope, owner, step)}diff --git a/moli-renderer-v8/src/script_vm/navigation_history.rs b/moli-renderer-v8/src/script_vm/navigation_history.rsindex 57d81a102..2cbba8a1e 100644--- a/moli-renderer-v8/src/script_vm/navigation_history.rs+++ b/moli-renderer-v8/src/script_vm/navigation_history.rs@@ -5,10 +5,6 @@ use anyhow::{Result, anyhow};#[derive(Clone, Copy, Debug)]enum NavigationHistoryRealm {TopDefault,- Isolated {- execution_context_id: i64,- child_handle: Option<DomHandle>,- },ChildDefault {execution_context_id: i64,child_handle: DomHandle,@@ -19,32 +15,16 @@ enum NavigationHistoryRealm {}impl NavigationHistoryRealm {- fn order_key(self) -> (usize, u8, i64) {+ fn order_key(self) -> (usize, i64) {match self {- Self::TopDefault => (0, 0, 0),- Self::Isolated {- execution_context_id,- child_handle: None,- } => (0, 1, execution_context_id),+ Self::TopDefault => (0, 0),Self::ChildDefault {execution_context_id,child_handle,- } => (- child_handle.index().saturating_add(1),- 0,- execution_context_id,- ),+ } => (child_handle.index().saturating_add(1), execution_context_id),Self::PrebootstrappedChildDefault { child_handle } => {- (child_handle.index().saturating_add(1), 0, i64::MIN)+ (child_handle.index().saturating_add(1), i64::MIN)}- Self::Isolated {- execution_context_id,- child_handle: Some(child_handle),- } => (- child_handle.index().saturating_add(1),- 1,- execution_context_id,- ),}}}@@ -117,20 +97,10 @@ impl ScriptVm {fn live_navigation_history_realms(&mut self) -> Vec<NavigationHistoryRealm> {self.prune_stale_child_default_execution_contexts();+ // Isolated worlds share these histories; prune each Window only once.let mut realms = vec![NavigationHistoryRealm::TopDefault];{let host = self._context_host.borrow();- realms.extend(- self.page_isolated_world_contexts- .contexts_with_ids()- .filter(|(_, world)| host.document_task_owner_is_current(world.document_owner))- .map(- |(execution_context_id, world)| NavigationHistoryRealm::Isolated {- execution_context_id,- child_handle: world.child_handle,- },- ),- );realms.extend(self.child_frame_realm_store.iter_by_execution_context_id()@@ -166,23 +136,6 @@ impl ScriptVm {) -> Option<*const v8::Global<v8::Context>> {match realm {NavigationHistoryRealm::TopDefault => Some(&self.page_default_context as *const _),- NavigationHistoryRealm::Isolated {- execution_context_id,- child_handle,- } => {- let world = self- .page_isolated_world_contexts- .context(execution_context_id)?;- if world.child_handle != child_handle- || !self- ._context_host- .borrow()- .document_task_owner_is_current(world.document_owner)- {- return None;- }- Some(&world.context as *const _)- }NavigationHistoryRealm::ChildDefault {execution_context_id,child_handle,diff --git a/moli-renderer-v8/src/script_vm/post_parse.rs b/moli-renderer-v8/src/script_vm/post_parse.rsindex a642f2fd5..c09aab2f6 100644--- a/moli-renderer-v8/src/script_vm/post_parse.rs+++ b/moli-renderer-v8/src/script_vm/post_parse.rs@@ -303,6 +303,19 @@ impl ScriptVmContextBootstrap {child_handle: None, ..} => unsafe { &*host_ptr }.document_url().clone(),};+ if let WindowContextBootstrapMode::Isolated { child_handle, .. } = mode {+ let owner_context = match child_handle {+ Some(handle) => unsafe { &mut *host_ptr }+ .ensure_prebootstrapped_child_default_context(scope, handle)?,+ None => unsafe { &*host_ptr }+ .page_default_context(scope)+ .ok_or_else(|| {+ anyhow::anyhow!("isolated History requires the default Window")+ })?,+ };+ let owner = owner_context.global(scope);+ crate::context_bootstrap::bind_isolated_window_history_owner(scope, global, owner);+ }finish_context_bootstrap(scope, unsafe { &mut *host_ptr }, &secure_context_url)?;match mode {WindowContextBootstrapMode::Isolated {diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rsnew file mode 100644index 000000000..6ad4d277c--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/history_worlds.rs@@ -0,0 +1,334 @@+use super::*;++#[tokio::test]+async fn history_worlds_share_mutations_but_keep_wrappers_and_state_caches_separate() {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");+ let mut vm =+ new_storage_page_task_executor_test_vm_with_loader("https://example.com/base", &loader);+ vm.eval(r##"+ globalThis.initialLength = history.length;+ globalThis.changes = [];+ navigation.addEventListener('currententrychange', () => changes.push(location.hash));+ history.replaceState({value: 1, map: new Map([['x', 2n]]), bytes: new Uint8Array([3])}, '', '#one');+ history.scrollRestoration = 'manual';+ globalThis.pageState = history.state;+ pageState.value = 99;+ history.expando = 'page';+ history.pushState = () => { throw new Error('page override'); };+ 'ready'+ "##).expect("default world setup");+ let isolated = vm+ .create_isolated_world("history-shared", false)+ .expect("isolated world");+ const READ_STATE: &str = r#"JSON.stringify([+ history.state.value,+ history.state.map instanceof Map,+ history.state.map.get('x') === 2n,+ history.state.bytes instanceof Uint8Array,+ history.state.bytes[0],+ Object.getPrototypeOf(history.state) === Object.prototype,+ history.state === history.state,+ history.scrollRestoration,+ location.hash,+ history instanceof History,+ history.expando === undefined+ ])"#;+ assert_eq!(+ vm.eval_in_isolated_context(isolated, READ_STATE).unwrap(),+ r##"[1,true,true,true,3,true,true,"manual","#one",true,true]"##+ );+ assert_eq!(+ vm.eval("String(history.state === pageState && history.state.value === 99)")+ .unwrap(),+ "true"+ );+ vm.eval_in_isolated_context(+ isolated,+ r##"+ globalThis.isolatedState = history.state;+ isolatedState.value = 42;+ history.pushState({value: 2}, '', '#two');+ history.scrollRestoration = 'auto';+ 'pushed'+ "##,+ )+ .expect("isolated mutation bypasses page override");+ const READ_CURRENT: &str = r#"JSON.stringify([+ history.state.value, location.hash, navigation.currentEntry.url,+ history.scrollRestoration, history.state === history.state,+ Object.getPrototypeOf(history.state) === Object.prototype+ ])"#;+ let expected = r##"[2,"#two","https://example.com/base#two","auto",true,true]"##;+ assert_eq!(vm.eval(READ_CURRENT).unwrap(), expected);+ assert_eq!(+ vm.eval_in_isolated_context(isolated, READ_CURRENT).unwrap(),+ expected+ );+ assert_eq!(+ vm.eval("String(history.length === initialLength + 1)")+ .unwrap(),+ "true"+ );+ let later = vm+ .create_isolated_world("history-later", false)+ .expect("later isolated world");+ assert_eq!(+ vm.eval_in_isolated_context(later, READ_CURRENT).unwrap(),+ expected+ );+ vm.eval("history.replaceState({value: 3}, '', '#three'); 'replaced'")+ .unwrap();+ assert_eq!(+ vm.eval_in_isolated_context(isolated, "String(history.state.value) + location.hash")+ .unwrap(),+ "3#three"+ );+ assert_eq!(+ vm.eval_in_isolated_context(later, "String(history.state.value) + location.hash")+ .unwrap(),+ "3#three"+ );+ assert_eq!(vm.eval("changes.join('|')").unwrap(), "#one|#two|#three");+ vm.advance_timers_until_deadline_for_test(&loader)+ .await+ .unwrap();+ vm.eval_in_isolated_context(isolated, "history.back(); 'queued'")+ .unwrap();+ assert!(+ vm.run_one_history_traversal_executor_turn(&loader)+ .await+ .unwrap()+ );+ assert_eq!(+ vm.eval_in_isolated_context(isolated, READ_STATE).unwrap(),+ r##"[1,true,true,true,3,true,true,"auto","#one",true,true]"##+ );+ assert_eq!(vm.eval("String(history.state.value)").unwrap(), "1");+ vm.eval_in_isolated_context(later, "history.forward(); 'queued'")+ .unwrap();+ assert!(+ vm.run_one_history_traversal_executor_turn(&loader)+ .await+ .unwrap()+ );+ assert_eq!(+ vm.eval("String(history.state.value) + location.hash")+ .unwrap(),+ "3#three"+ );+}++#[tokio::test]+async fn history_worlds_child_mutations_share_only_the_child_window_history() {+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");+ let mut vm =+ new_storage_page_task_executor_test_vm_with_loader("https://example.com/base", &loader);+ vm.eval(+ r##"+ history.replaceState({owner: 'top'}, '', '#top');+ const frame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(frame);+ void frame.contentWindow;+ 'created'+ "##,+ )+ .unwrap();+ assert!(+ vm.run_one_child_frame_task_executor_turn(+ ChildFrameSemanticTurnKind::RealmMaterialization,+ &loader,+ )+ .await+ .unwrap()+ );+ let child = vm+ .live_child_default_runtime_realm_inventory()+ .into_iter()+ .next()+ .unwrap()+ .context_id;+ let frame_id = vm+ .child_frame_realm_store+ .get(&child)+ .unwrap()+ .frame_id+ .clone();+ vm.eval_in_child_default_context(+ child,+ r##"+ history.replaceState({owner: 'child'}, '', '#child');+ history.scrollRestoration = 'manual';+ 'ready'+ "##,+ )+ .unwrap();+ let isolated = vm+ .create_isolated_world_for_frame(&frame_id, "child-history", false)+ .unwrap();+ assert_eq!(+ vm.eval_in_isolated_context(+ isolated,+ "history.state.owner + ':' + history.scrollRestoration + ':' + location.hash"+ )+ .unwrap(),+ "child:manual:#child"+ );+ vm.eval_in_isolated_context(+ isolated,+ r##"+ history.pushState({owner: 'isolated-child'}, '', '#next');+ history.scrollRestoration = 'auto';+ 'pushed'+ "##,+ )+ .unwrap();+ const READ_CHILD: &str =+ "history.state.owner + ':' + history.scrollRestoration + ':' + location.hash";+ assert_eq!(+ vm.eval_in_child_default_context(child, READ_CHILD).unwrap(),+ "isolated-child:auto:#next"+ );+ assert_eq!(+ vm.eval("history.state.owner + ':' + location.hash")+ .unwrap(),+ "top:#top"+ );+ assert_eq!(+ vm.eval("document.querySelector('iframe').contentWindow.history.state.owner")+ .unwrap(),+ "isolated-child"+ );+ vm.advance_timers_until_deadline_for_test(&loader)+ .await+ .unwrap();+ vm.eval("globalThis.topPops = 0; addEventListener('popstate', () => topPops++); 'listening'")+ .unwrap();+ vm.eval_in_child_default_context(child,+ "globalThis.childPops = 0; addEventListener('popstate', () => childPops++); history.back(); 'queued'").unwrap();+ assert!(+ vm.run_one_history_traversal_executor_turn(&loader)+ .await+ .unwrap()+ );+ assert_eq!(+ vm.eval_in_isolated_context(isolated, READ_CHILD).unwrap(),+ "child:auto:#child"+ );+ vm.eval_in_isolated_context(isolated, "history.forward(); 'queued'")+ .unwrap();+ assert!(+ vm.run_one_history_traversal_executor_turn(&loader)+ .await+ .unwrap()+ );+ assert_eq!(+ vm.eval_in_child_default_context(child, READ_CHILD).unwrap(),+ "isolated-child:auto:#next"+ );+ assert_eq!(vm.eval("String(topPops)").unwrap(), "0");+ assert_eq!(+ vm.eval_in_child_default_context(child, "String(childPops)")+ .unwrap(),+ "2"+ );+ vm.eval_in_child_default_context(child, "location.hash = '#fragment'; 'navigated'")+ .unwrap();+ assert_eq!(+ vm.eval_in_isolated_context(isolated, "location.hash")+ .unwrap(),+ "#fragment"+ );+ vm.eval_in_isolated_context(+ isolated,+ "location.hash = '#isolated-fragment'; 'navigated'",+ )+ .unwrap();+ assert_eq!(+ vm.eval_in_child_default_context(child, "location.hash")+ .unwrap(),+ "#isolated-fragment"+ );+ assert_eq!(vm.eval("location.hash").unwrap(), "#top");+ vm.eval_in_isolated_context(isolated, "parent.detachedHistory = history; 'saved'")+ .unwrap();+ assert_eq!(+ vm.eval(+ r#"+ document.querySelector('iframe').remove();+ try { detachedHistory.pushState({}, '', '#detached'); 'accepted'; }+ catch (error) { error.name; }+ "#+ )+ .unwrap(),+ "SecurityError"+ );+}++#[tokio::test]+async fn history_worlds_preserve_the_shared_backing_when_initial_child_window_is_reused() {+ let mut vm = new_storage_test_vm("https://example.com/base");+ vm.eval(+ r#"+ const frame = document.createElement('iframe');+ (document.body || document.documentElement || document).appendChild(frame);+ void frame.contentWindow;+ "#,+ )+ .unwrap();+ let child = materialize_single_child_default_realm_for_test(&mut vm, "History rebind");+ let frame_id = vm+ .child_frame_realm_store+ .get(&child)+ .unwrap()+ .frame_id+ .clone();+ let isolated = vm+ .create_isolated_world_for_frame(&frame_id, "rebound-history", false)+ .unwrap();+ vm.eval_in_isolated_context(isolated, "globalThis.originalHistory = history; 'saved'")+ .unwrap();+ vm.eval("frame.srcdoc = '<p>committed</p>'; 'navigating'")+ .unwrap();+ run_child_navigation_commit_and_host_load_for_test(&mut vm, "History rebind").await;+ vm.eval_in_isolated_context(+ isolated,+ r##"+ originalHistory.replaceState({rebound: true}, '', '#rebound');+ 'replaced'+ "##,+ )+ .unwrap();+ assert_eq!(+ vm.eval_in_child_default_context(+ child,+ "String(history.state.rebound) + ':' + location.hash"+ )+ .unwrap(),+ "true:#rebound"+ );+ assert_eq!(+ vm.eval_in_isolated_context(isolated, "String(history === originalHistory)")+ .unwrap(),+ "true"+ );+}++#[test]+fn history_worlds_share_primitive_state_without_coercion() {+ let mut vm = new_storage_test_vm("https://example.com/base");+ let isolated = vm+ .create_isolated_world("primitive-history", false)+ .unwrap();+ for state in ["undefined", "null", "-0", "0", "NaN", "1n", "false"] {+ let update = format!("history.replaceState({state}, ''); 'updated'");+ let check = format!("String(Object.is(history.state, {state}))");+ vm.eval(&update).unwrap();+ assert_eq!(+ vm.eval_in_isolated_context(isolated, &check).unwrap(),+ "true",+ "state: {state}"+ );+ vm.eval_in_isolated_context(isolated, &update).unwrap();+ assert_eq!(vm.eval(&check).unwrap(), "true", "state: {state}");+ }+}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rsindex 360226a40..3a2f7baca 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs@@ -21,6 +21,7 @@ mod event_listener_options;mod events_selection_storage;mod fontface_descriptors;mod gamepad;+mod history_worlds;mod ice_candidate;mod idle_callbacks;mod idle_detection;diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rsindex 8aa13eea5..44ff9ede1 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs@@ -4337,12 +4337,12 @@ JSON.stringify({assert_eq!(vm.eval(RESET_REALM_STATE).expect("top default reset state should evaluate"),- r#"{"historyLength":1,"navigationLength":1,"sameCurrent":true,"sameArrayEntry":true,"currentIndex":0,"stateRealm":"top-default","disposedAll":true,"disposedInReverseOrder":true}"#+ r#"{"historyLength":1,"navigationLength":1,"sameCurrent":true,"sameArrayEntry":true,"currentIndex":0,"stateRealm":"top-isolated","disposedAll":true,"disposedInReverseOrder":true}"#);assert_eq!(vm.eval_in_child_default_context(child_context_id, RESET_REALM_STATE).expect("child default reset state should evaluate"),- r#"{"historyLength":1,"navigationLength":1,"sameCurrent":true,"sameArrayEntry":true,"currentIndex":0,"stateRealm":"child-default","disposedAll":true,"disposedInReverseOrder":true}"#+ r#"{"historyLength":1,"navigationLength":1,"sameCurrent":true,"sameArrayEntry":true,"currentIndex":0,"stateRealm":"child-isolated","disposedAll":true,"disposedInReverseOrder":true}"#);assert_eq!(vm.eval_in_isolated_context(top_isolated_context_id, RESET_REALM_STATE)@@ -4357,7 +4357,7 @@ JSON.stringify({assert_eq!(vm.eval("JSON.stringify(__lmResetRealmOrder)").expect("cross-realm reset order should evaluate"),- r#"[{"listener":"top","sharedLengthPruned":true,"topEntries":1,"childEntries":2},{"listener":"child","sharedLengthPruned":true,"topEntries":1,"childEntries":1}]"#+ r#"[{"listener":"top","sharedLengthPruned":true,"topEntries":1,"childEntries":3},{"listener":"child","sharedLengthPruned":true,"topEntries":1,"childEntries":1}]"#);}