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): unify traversal coordination and native admission state

ldm03b24fb44f709
diff --git a/moli-protocol/src/domains/page/tests/navigation.rs b/moli-protocol/src/domains/page/tests/navigation.rs
index ba4642f34..bc23908c4 100644
--- a/moli-protocol/src/domains/page/tests/navigation.rs
+++ b/moli-protocol/src/domains/page/tests/navigation.rs
@@ -626,6 +626,16 @@ async fn joint_history_traversal_precommit_rejection_aborts_the_whole_step() {
assert_joint_history_precommit("reject").await;
}
+#[tokio::test(flavor = "multi_thread")]
+async fn joint_history_traversal_stop_during_pagehide_cancels_after_precommit() {
+ assert_joint_history_precommit("stop-pagehide").await;
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn joint_history_traversal_participant_replacement_rejects_surviving_api_promises() {
+ assert_joint_history_precommit("replace-participant").await;
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn joint_history_traversal_precommit_cannot_restore_a_pruned_step() {
assert_joint_history_precommit("prune").await;
@@ -840,16 +850,26 @@ async fn assert_joint_history_precommit(mode: &str) {
},
)
.await;
+ joint_history_test_evaluate(
+ &mut ctx,
+ if mode == "replace-participant" {
+ "globalThis.testTraversalApi = true"
+ } else {
+ "globalThis.testTraversalApi = false"
+ },
+ )
+ .await;
let pending=joint_history_test_evaluate(&mut ctx,r#"(async()=>{
history.replaceState('top0','');
globalThis.frame=document.createElement('iframe');frame.src='/a0';
await new Promise(resolve=>{frame.onload=resolve;document.body.append(frame)});
await new Promise(resolve=>setTimeout(resolve,0));
frame.contentWindow.history.replaceState('a0','');
+ if(testTraversalApi)history.pushState('top1','');
await new Promise(resolve=>{frame.onload=resolve;frame.contentWindow.location.assign('/a1')});
await new Promise(resolve=>setTimeout(resolve,0));
frame.contentWindow.history.replaceState('a1','');
- history.pushState('top1','');
+ if(!testTraversalApi)history.pushState('top1','');
globalThis.pagehides=0;frame.contentWindow.onpagehide=()=>pagehides++;
globalThis.snapshot=()=>[history.state,frame.contentWindow.history.state,
frame.contentWindow.location.pathname,history.length,frame.contentWindow.history.length,pagehides];
@@ -859,7 +879,15 @@ async fn assert_joint_history_precommit(mode: &str) {
navigation.onnavigate=event=>{
if(event.navigationType==='traverse')event.intercept({precommitHandler:()=>{admitted();return gate}});
};
- history.go(testTraversalDelta);await started;return snapshot();
+ globalThis.settlements=[];
+ if(testTraversalApi){
+ const result=navigation.back();
+ result.committed.catch(error=>settlements.push('committed:'+error.name));
+ result.finished.catch(error=>settlements.push('finished:'+error.name));
+ }else{
+ 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"}))
@@ -893,6 +921,17 @@ async fn assert_joint_history_precommit(mode: &str) {
}
"attach-single" => "new Promise(resolve=>{onpopstate=()=>resolve(snapshot());release()})",
"reject" => "block(new Error('blocked'));failed.then(()=>snapshot())",
+ "stop-pagehide" => {
+ r#"new Promise(resolve=>{
+ navigation.addEventListener('navigateerror',()=>resolve(snapshot()),{once:true});
+ frame.onload=()=>setTimeout(()=>resolve(snapshot()),0);
+ frame.contentWindow.onpagehide=()=>{pagehides++;stop()};
+ release();
+ })"#
+ }
+ "replace-participant" => {
+ "new Promise(resolve=>{frame.onload=()=>setTimeout(()=>resolve(snapshot()),0);frame.src='/successor'})"
+ }
_ => "release();failed.then(()=>snapshot())",
};
let after = joint_history_test_evaluate(&mut ctx, expression).await;
@@ -900,9 +939,25 @@ async fn assert_joint_history_precommit(mode: &str) {
"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),
+ "stop-pagehide" => (json!(["top1", "a1", "/a1", 4, 4, 1]), 3, 4),
+ "replace-participant" => (json!(["top1", null, "/successor", 5, 5, 1]), 4, 5),
_ => (json!(["top1", "a1", "/a1", 1, 1, 0]), 0, 1),
};
assert_eq!(after, expected, "{mode}");
+ if mode == "replace-participant" {
+ assert_eq!(
+ joint_history_test_evaluate(
+ &mut ctx,
+ "release();Promise.resolve().then(()=>snapshot())"
+ )
+ .await,
+ expected
+ );
+ assert_eq!(
+ joint_history_test_evaluate(&mut ctx, "settlements").await,
+ json!(["committed:AbortError", "finished:AbortError"])
+ );
+ }
ctx.process_async(json!({"id":9341,"method":"Page.getNavigationHistory","sessionId":"SID-1"}))
.await;
let browser = take_response_by_id(&mut ctx, 9341);
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs
index e60d5357b..05f1f4e53 100644
--- a/moli-renderer-v8/src/context_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap.rs
@@ -57,7 +57,6 @@ mod navigation_entry_state;
mod navigation_events;
mod navigation_handler_callbacks;
mod navigation_history_pruning;
-mod navigation_joint_traversal;
mod navigation_lifecycle;
mod navigation_mutation;
mod navigation_projection;
@@ -68,6 +67,7 @@ mod navigation_seed;
mod navigation_serialize;
mod navigation_surface;
mod navigation_traversal;
+mod navigation_traversal_coordinator;
mod navigation_traversal_execution;
mod navigation_traversal_plan;
mod navigation_window;
@@ -152,6 +152,7 @@ pub(crate) use navigation_history_pruning::{
pub(crate) use navigation_result::{
NavigationFinishedResultApplication, apply_pending_navigation_finished_result,
};
+pub(crate) use navigation_traversal_coordinator::cancel_history_traversals_for_retiring_window;
pub(crate) use navigation_traversal_execution::apply_authorized_history_traversal_task;
pub(crate) use performance_runtime::PERFORMANCE_TIME_ORIGIN_SLOT;
pub(crate) use performance_runtime::performance_slot_number;
diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime.rs
index 744475ca0..38fd89a2b 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime.rs
@@ -1,13 +1,12 @@
mod admission;
pub(super) mod apply;
-mod results;
+pub(super) mod results;
pub(super) mod traversal;
pub(super) use self::admission::require_fully_active_history_owner;
-pub(super) use self::apply::apply_history_entry;
-pub(super) use self::results::reject_pending_navigation_results;
pub(super) use self::traversal::{
apply_pending_history_traversal, cancel_active_history_traversal_intercept_settlement,
- cancel_pending_precommit_history_traversal, pending_history_traversal_target_index,
- route_history_traversal_task,
+ pending_history_traversal_target_index, route_history_traversal_task,
};
+
+pub(super) use super::navigation_traversal_coordinator::cancel_pending as cancel_pending_precommit_history_traversal;
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 564ab1a38..15e755a63 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/apply.rs
@@ -3,23 +3,20 @@ use super::super::location_runtime::{
};
use super::super::navigation_entry::{
history_entries, history_index, navigation_current_entry, navigation_entries_share_document,
- navigation_entry_url_value, restore_current_navigation_entry_scroll_position,
- set_history_index, set_history_state, sync_navigation_current_entry_from_history_entry,
+ navigation_entry_url_value, set_history_index, set_history_state,
+ sync_navigation_current_entry_from_history_entry,
};
use super::super::navigation_events::{
- dispatch_navigation_currententrychange, dispatch_navigation_success, dispatch_popstate_event,
- navigation_has_active_scroll_event, queue_hash_change_for_runtime_owner,
+ dispatch_navigation_currententrychange, dispatch_popstate_event,
+ queue_hash_change_for_runtime_owner,
};
use super::super::navigation_mutation::sync_local_document_front_from_window;
-use super::super::navigation_result::perform_navigation_scroll_if_needed;
use super::super::navigation_serialize::sync_child_navigation_entry_seed_from_owner;
use super::super::navigation_window::{
navigation_document_has_opaque_origin, runtime_window_is_global, runtime_window_owner,
window_location_for_holder, window_navigation_for_holder,
};
use super::super::*;
-use super::results::{resolve_pending_navigation_committed, resolve_pending_navigation_finished};
-use crate::native_bridge::PendingNavigationResult;
use crate::script_vm::perform_microtask_checkpoint_and_report_pending_promise_rejections;
pub(in crate::context_bootstrap) struct AppliedHistoryEntry<'s> {
@@ -41,103 +38,6 @@ pub(in crate::context_bootstrap) struct PreparedHistoryEntry<'s> {
applied: AppliedHistoryEntry<'s>,
}
-pub(in crate::context_bootstrap) fn apply_history_entry<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- history: v8::Local<'s, v8::Object>,
- index: u32,
- plan: Option<&moli_session_history::SessionHistoryTraversalPlan>,
- dispatch_popstate: bool,
- pending_results: Option<&[PendingNavigationResult]>,
-) {
- 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,
- "Navigation was canceled",
- "AbortError",
- );
- super::results::reject_pending_navigation_results(scope, results, error);
- }
- return;
- };
- if let Some(results) = pending_results {
- resolve_pending_navigation_committed(scope, results, applied.resolved_entry);
- }
- dispatch_history_entry_currententrychange(scope, &applied);
- if dispatch_popstate {
- perform_microtask_checkpoint_and_report_pending_promise_rejections(scope);
- }
- if !navigation_document_has_opaque_origin(scope, applied.owner)
- && let Some(navigation) = window_navigation_for_holder(scope, applied.owner)
- {
- let has_active_scroll_event = navigation_has_active_scroll_event(scope, navigation);
- if has_active_scroll_event
- || !restore_current_navigation_entry_scroll_position(scope, applied.owner)
- {
- perform_navigation_scroll_if_needed(scope, navigation, &applied.url, true);
- }
- dispatch_navigation_success(scope, navigation);
- }
- if let Some(results) = pending_results {
- resolve_pending_navigation_finished(scope, results, applied.resolved_entry);
- }
- if dispatch_popstate {
- perform_microtask_checkpoint_and_report_pending_promise_rejections(scope);
- }
- dispatch_history_entry_post_commit_events(scope, &applied, dispatch_popstate);
-}
-
-pub(in crate::context_bootstrap) fn apply_history_entry_commit<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- history: v8::Local<'s, v8::Object>,
- index: u32,
- plan: Option<&moli_session_history::SessionHistoryTraversalPlan>,
-) -> Option<AppliedHistoryEntry<'s>> {
- let owner = runtime_window_owner(scope, history);
- 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.
- // This path is only the specialized single same-Document executor.
- if targets
- .iter()
- .any(|target| !target.history.strict_equals(history.into()))
- {
- return None;
- }
- // Admission can run script, so validate the stable step again before any
- // local entry is changed. Forward pruning invalidates it atomically.
- 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 = 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 {
- return None;
- }
- }
- let prepared = prepare_local_history_entry_commit(scope, history, index)?;
- let delta = match plan {
- Some(plan) => Some(super::super::session_history::commit_traversal(
- scope, owner, plan,
- )?),
- None => None,
- };
- let applied = commit_prepared_history_entry(scope, prepared);
- if let Some(delta) = delta.filter(|delta| *delta != 0) {
- super::super::session_history::publish(
- scope,
- owner,
- moli_page_types::SessionHistoryUpdateKind::Traverse { delta },
- );
- }
- Some(applied)
-}
-
/// Resolve every fallible input before any participant changes its live view.
pub(in crate::context_bootstrap) fn prepare_local_history_entry_commit<'s>(
scope: &mut v8::PinScope<'s, '_>,
diff --git a/moli-renderer-v8/src/context_bootstrap/history_runtime/results.rs b/moli-renderer-v8/src/context_bootstrap/history_runtime/results.rs
index bc122ddd2..0b0b4c801 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/results.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/results.rs
@@ -2,7 +2,7 @@ use crate::native_bridge::PendingNavigationResult;
use super::super::navigation_result::suppress_unhandled_rejection;
-pub(super) fn resolve_pending_navigation_committed(
+pub(in crate::context_bootstrap) fn resolve_pending_navigation_committed(
scope: &mut v8::PinScope<'_, '_>,
results: &[PendingNavigationResult],
resolved_value: v8::Local<'_, v8::Value>,
@@ -13,7 +13,7 @@ pub(super) fn resolve_pending_navigation_committed(
}
}
-pub(super) fn resolve_pending_navigation_finished(
+pub(in crate::context_bootstrap) fn resolve_pending_navigation_finished(
scope: &mut v8::PinScope<'_, '_>,
results: &[PendingNavigationResult],
resolved_value: v8::Local<'_, v8::Value>,
@@ -24,15 +24,6 @@ pub(super) fn resolve_pending_navigation_finished(
}
}
-pub(super) fn resolve_pending_navigation_results(
- scope: &mut v8::PinScope<'_, '_>,
- results: Vec<PendingNavigationResult>,
- resolved_value: v8::Local<'_, v8::Value>,
-) {
- resolve_pending_navigation_committed(scope, &results, resolved_value);
- resolve_pending_navigation_finished(scope, &results, resolved_value);
-}
-
pub(in crate::context_bootstrap) fn reject_pending_navigation_results(
scope: &mut v8::PinScope<'_, '_>,
results: &[PendingNavigationResult],
@@ -42,7 +33,7 @@ pub(in crate::context_bootstrap) fn reject_pending_navigation_results(
reject_pending_navigation_finished(scope, results, error);
}
-pub(super) fn reject_pending_navigation_committed(
+pub(in crate::context_bootstrap) fn reject_pending_navigation_committed(
scope: &mut v8::PinScope<'_, '_>,
results: &[PendingNavigationResult],
error: v8::Local<'_, v8::Value>,
@@ -53,7 +44,7 @@ pub(super) fn reject_pending_navigation_committed(
}
}
-pub(super) fn reject_pending_navigation_finished(
+pub(in crate::context_bootstrap) fn reject_pending_navigation_finished(
scope: &mut v8::PinScope<'_, '_>,
results: &[PendingNavigationResult],
error: v8::Local<'_, v8::Value>,
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 c1d10c484..df5e9cad5 100644
--- a/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs
+++ b/moli-renderer-v8/src/context_bootstrap/history_runtime/traversal.rs
@@ -1,9 +1,6 @@
-use super::super::navigation_entry::{
- history_entries, history_index, navigation_current_entry, navigation_entry_key_value,
-};
+use super::super::navigation_entry::{history_entries, navigation_entry_key_value};
use super::super::navigation_events::{
NavigationDispatchOutcome, dispatch_navigation_success,
- dispatch_navigation_traverse_event_with_outcome, mark_navigation_outcome_default_prevented,
run_navigation_precommit_deferred_handlers,
};
use super::super::navigation_lifecycle::finish_navigation_error_events;
@@ -16,28 +13,12 @@ use super::super::navigation_window::{
window_navigation_for_holder, window_task_target_for_runtime_owner,
};
use super::super::*;
-use super::apply::{
- apply_history_entry, apply_history_entry_commit, dispatch_history_entry_currententrychange,
- dispatch_history_entry_post_commit_events,
-};
-use super::results::{reject_pending_navigation_results, resolve_pending_navigation_results};
+use super::apply::dispatch_history_entry_post_commit_events;
+use super::results::reject_pending_navigation_results;
use crate::native_bridge::PendingHistoryTraversal;
use crate::util::{get_private_value, set_private_value};
use moli_webapi_declare::WebApiObject;
-const TRAVERSAL_PRECOMMIT_ACTIVE_SLOT: &str = "__lmTraversalPrecommitActive";
-const TRAVERSAL_PRECOMMIT_NAVIGATION_SLOT: &str = "__lmTraversalPrecommitNavigation";
-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";
-const TRAVERSAL_PRECOMMIT_COMMITTED_RESOLVERS_SLOT: &str =
- "__lmTraversalPrecommitCommittedResolvers";
-const TRAVERSAL_PRECOMMIT_FINISHED_RESOLVERS_SLOT: &str = "__lmTraversalPrecommitFinishedResolvers";
-const NAVIGATION_PENDING_TRAVERSAL_PRECOMMIT_SLOT: &str = "__lmNavigationPendingTraversalPrecommit";
const TRAVERSAL_INTERCEPT_ACTIVE_SLOT: &str = "__lmTraversalInterceptActive";
const TRAVERSAL_INTERCEPT_NAVIGATION_SLOT: &str = "__lmTraversalInterceptNavigation";
const TRAVERSAL_INTERCEPT_SIGNAL_SLOT: &str = "__lmTraversalInterceptSignal";
@@ -47,43 +28,6 @@ const TRAVERSAL_INTERCEPT_URL_SLOT: &str = "__lmTraversalInterceptUrl";
const TRAVERSAL_INTERCEPT_PROMISE_SLOT: &str = "__lmTraversalInterceptPromise";
const NAVIGATION_ACTIVE_TRAVERSAL_INTERCEPT_SLOT: &str = "__lmNavigationActiveTraversalIntercept";
-#[derive(WebApiObject)]
-#[webapi(plain)]
-struct TraversalPrecommitDataDeclaration<'scope> {
- #[webapi(slot = TRAVERSAL_PRECOMMIT_ACTIVE_SLOT)]
- active: bool,
-
- #[webapi(slot = TRAVERSAL_PRECOMMIT_NAVIGATION_SLOT)]
- navigation: v8::Local<'scope, v8::Object>,
-
- #[webapi(slot = TRAVERSAL_PRECOMMIT_HISTORY_SLOT)]
- history: v8::Local<'scope, v8::Object>,
-
- #[webapi(slot = TRAVERSAL_PRECOMMIT_EVENT_SLOT)]
- event: v8::Local<'scope, v8::Object>,
-
- #[webapi(slot = TRAVERSAL_PRECOMMIT_SIGNAL_SLOT)]
- signal: Option<v8::Local<'scope, v8::Object>>,
-
- #[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,
-
- #[webapi(slot = TRAVERSAL_PRECOMMIT_PROMISE_SLOT)]
- promise: Option<v8::Local<'scope, v8::Value>>,
-
- #[webapi(slot = TRAVERSAL_PRECOMMIT_COMMITTED_RESOLVERS_SLOT)]
- committed_resolvers: v8::Local<'scope, v8::Array>,
-
- #[webapi(slot = TRAVERSAL_PRECOMMIT_FINISHED_RESOLVERS_SLOT)]
- finished_resolvers: v8::Local<'scope, v8::Array>,
-}
-
#[derive(WebApiObject)]
#[webapi(plain)]
struct TraversalInterceptSettlementDataDeclaration<'scope> {
@@ -106,55 +50,6 @@ struct TraversalInterceptSettlementDataDeclaration<'scope> {
url: v8::Local<'scope, v8::String>,
}
-fn navigation_pending_traversal_precommit<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- navigation: v8::Local<'s, v8::Object>,
-) -> Option<v8::Local<'s, v8::Object>> {
- get_private_value(
- scope,
- navigation,
- NAVIGATION_PENDING_TRAVERSAL_PRECOMMIT_SLOT,
- )
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
-}
-
-fn set_navigation_pending_traversal_precommit<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- navigation: v8::Local<'s, v8::Object>,
- data: v8::Local<'s, v8::Object>,
-) {
- set_private_value(
- scope,
- navigation,
- NAVIGATION_PENDING_TRAVERSAL_PRECOMMIT_SLOT,
- data.into(),
- );
-}
-
-fn clear_navigation_pending_traversal_precommit<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- navigation: v8::Local<'s, v8::Object>,
-) {
- set_private_value(
- scope,
- navigation,
- NAVIGATION_PENDING_TRAVERSAL_PRECOMMIT_SLOT,
- v8::undefined(scope).into(),
- );
-}
-
-fn clear_navigation_pending_traversal_precommit_if_current<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- navigation: v8::Local<'s, v8::Object>,
- data: v8::Local<'s, v8::Object>,
-) {
- if navigation_pending_traversal_precommit(scope, navigation)
- .is_some_and(|active| active.strict_equals(data.into()))
- {
- clear_navigation_pending_traversal_precommit(scope, navigation);
- }
-}
-
fn navigation_active_traversal_intercept<'s>(
scope: &mut v8::PinScope<'s, '_>,
navigation: v8::Local<'s, v8::Object>,
@@ -238,271 +133,39 @@ pub(in crate::context_bootstrap) fn route_history_traversal_task(
pub(in crate::context_bootstrap) fn apply_pending_history_traversal(
scope: &mut v8::PinScope<'_, '_>,
host: &mut JsContextHost,
- mut traversal: PendingHistoryTraversal,
+ 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");
- reject_pending_navigation_results(scope, &traversal.results, error);
- return;
- };
- let Some(plan) = super::super::navigation_traversal_plan::JointTraversalPlan::resolve(
- scope, owner, step,
- ) else {
- let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
- reject_pending_navigation_results(scope, &traversal.results, error);
- return;
- };
- if super::super::navigation_joint_traversal::requires_joint_execution(scope, &plan) {
- let info = traversal
- .info
- .as_ref()
- .map(|info| v8::Local::new(scope, info));
- super::super::navigation_joint_traversal::execute(
- scope,
- plan,
- info,
- &traversal.results,
- );
- return;
- }
- if traversal.results.is_empty()
- && let [target] = plan.targets.as_slice()
- && let Some(exact) = window_task_target_for_runtime_owner(scope, host, target.owner)
- {
- traversal.target = exact;
- traversal.target_index = target.target_index;
- traversal.target_key = history_entries(scope, target.history)
- .and_then(|entries| entries.get_index(scope, target.target_index))
- .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)
- .and_then(|window| window_history_for_holder(scope, window));
- let Some(history) = history else {
- let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
- 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))
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok());
- let owner = runtime_window_owner(scope, history);
- let navigation = if navigation_document_has_opaque_origin(scope, owner) {
- None
- } else {
- window_navigation_for_holder(scope, owner)
- };
- let info = traversal
- .info
+ let plan = history_traversal_target_window(scope, host, traversal.target).and_then(|owner| {
+ let history = window_history_for_holder(scope, owner)?;
+ let entry = history_entries(scope, history)?
+ .get_index(scope, traversal.target_index)?
+ .try_into()
+ .ok()?;
+ if traversal
+ .target_key
.as_ref()
- .map(|info| v8::Local::new(scope, info));
- let outcome = navigation
- .map(|navigation| {
- dispatch_navigation_traverse_event_with_outcome(
- scope,
- navigation,
- history,
- traversal.target_index,
- info,
- )
- })
- .unwrap_or_else(NavigationDispatchOutcome::proceed);
- let owner_still_active = navigation_document_is_active(scope, owner);
- let target_still_available = target_entry_is_still_available(
- scope,
- history,
- traversal.target_index,
- target_entry,
- traversal.target_key.as_deref(),
- );
- if let Some(error) = outcome.abort_error {
- reject_pending_navigation_results(scope, &results, error);
- return;
- }
- if let Some(error) = outcome.precommit_error {
- if let Some(navigation) = navigation {
- finish_navigation_error_events(scope, navigation, error, "");
- }
- reject_pending_navigation_results(scope, &results, error);
- return;
- }
- if !outcome.proceed || !owner_still_active || !target_still_available {
- let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
- mark_navigation_outcome_default_prevented(scope, &outcome);
- if let Some(signal) = outcome.signal
- && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
- {
- unsafe { &mut *host_ptr }.abort_signal(scope, signal, error);
- }
- if let Some(navigation) = navigation {
- let filename =
- super::super::navigation_window::window_location_for_holder(scope, owner)
- .and_then(|location| {
- super::super::location_runtime::location_href_slot(scope, location)
- })
- .unwrap_or_default();
- if outcome.proceed && owner_still_active && !target_still_available {
- reject_pending_navigation_results(scope, &results, error);
- return;
- }
- finish_navigation_error_events(scope, navigation, error, &filename);
- }
- reject_pending_navigation_results(scope, &results, error);
- return;
- }
- if outcome.intercepted
- && let Some(navigation) = navigation
+ .is_some_and(|key| navigation_entry_key_value(scope, entry).as_ref() != Some(key))
{
- if outcome.precommit_result.is_some() {
- let queued = queue_pending_precommit_history_traversal(
- scope,
- navigation,
- history,
- traversal.target_index,
- joint_plan.as_ref(),
- outcome,
- &results,
- );
- if !queued {
- let error =
- navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
- finish_navigation_error_events(scope, navigation, error, "");
- reject_pending_navigation_results(scope, &results, error);
- }
- return;
- }
- let Some(applied) = apply_history_entry_commit(
- scope,
- history,
- traversal.target_index,
- joint_plan.as_ref(),
- ) else {
- let error =
- navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
- finish_navigation_error_events(scope, navigation, error, "");
- reject_pending_navigation_results(scope, &results, error);
- return;
- };
- let (committed_resolvers, finished_resolvers) =
- pending_result_resolver_arrays(scope, &results);
- resolve_resolver_array(scope, committed_resolvers, applied.resolved_entry);
- let active_intercept = set_active_traversal_intercept_settlement(
- scope,
- navigation,
- outcome.signal,
- finished_resolvers,
- applied.resolved_entry,
- &applied.url,
- );
- dispatch_history_entry_currententrychange(scope, &applied);
- let (intercept_error, intercept_result) = if let Some(event) = outcome.precommit_event {
- run_navigation_precommit_deferred_handlers(scope, event)
- } else {
- (None, outcome.intercept_result)
- };
- suppress_intercept_result_unhandled_rejection(scope, intercept_result);
- dispatch_history_entry_post_commit_events(scope, &applied, true);
- if !traversal_intercept_is_active(scope, active_intercept.into()) {
- return;
- }
- if let Some(error) = intercept_error {
- set_traversal_intercept_inactive(scope, navigation, active_intercept.into());
- finish_navigation_error_events(scope, navigation, error, &applied.url);
- reject_resolver_array(scope, finished_resolvers, error, true);
- if let Some(signal) = outcome.signal
- && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
- {
- unsafe { &mut *host_ptr }.abort_signal(scope, signal, error);
- }
- return;
- }
- let Some(result) = intercept_result else {
- set_traversal_intercept_inactive(scope, navigation, active_intercept.into());
- perform_navigation_scroll_if_needed(scope, navigation, &applied.url, true);
- dispatch_navigation_success(scope, navigation);
- resolve_resolver_array(scope, finished_resolvers, applied.resolved_entry);
- return;
- };
- if !traversal_intercept_is_active(scope, active_intercept.into()) {
- return;
- }
- set_traversal_intercept_inactive(scope, navigation, active_intercept.into());
- if !queue_pending_traversal_intercept_settlement(
- scope,
- navigation,
- outcome.signal,
- finished_resolvers,
- applied.resolved_entry,
- &applied.url,
- result,
- ) {
- perform_navigation_scroll_if_needed(scope, navigation, &applied.url, true);
- dispatch_navigation_success(scope, navigation);
- resolve_resolver_array(scope, finished_resolvers, applied.resolved_entry);
- }
- return;
+ return None;
}
- let pending_results = (!results.is_empty()).then_some(results.as_slice());
- apply_history_entry(
- scope,
- history,
- traversal.target_index,
- joint_plan.as_ref(),
- true,
- pending_results,
- );
- return;
- }
- if traversal.target_key.is_some()
- && !target_entry_is_still_available(
- scope,
- history,
- traversal.target_index,
- None,
- traversal.target_key.as_deref(),
- )
- {
+ let step = traversal
+ .joint_step
+ .or_else(|| super::super::session_history::step_for_entry(scope, owner, entry))?;
+ super::super::navigation_traversal_plan::JointTraversalPlan::resolve(scope, owner, step)
+ });
+ let Some(plan) = plan else {
let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
- reject_pending_navigation_results(scope, &results, error);
+ reject_pending_navigation_results(scope, &traversal.results, error);
return;
- }
- let owner = runtime_window_owner(scope, history);
- 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);
- return;
- };
- if delta != 0 {
- super::super::session_history::publish(
- scope,
- owner,
- moli_page_types::SessionHistoryUpdateKind::Traverse { delta },
- );
- }
- }
- let resolved_entry = navigation_current_entry(scope, owner)
- .map(v8::Local::<v8::Value>::from)
- .unwrap_or_else(|| v8::undefined(scope).into());
- resolve_pending_navigation_results(scope, results, resolved_entry);
+ };
+ let info = traversal
+ .info
+ .as_ref()
+ .map(|value| v8::Local::new(scope, value));
+ super::super::navigation_traversal_coordinator::execute(scope, plan, info, traversal.results);
}
-pub(in crate::context_bootstrap) fn prepare_joint_history_participant<'s>(
+pub(in crate::context_bootstrap) fn prepare_history_participant<'s>(
scope: &mut v8::PinScope<'s, '_>,
applied: &super::apply::AppliedHistoryEntry<'s>,
outcome: &NavigationDispatchOutcome<'s>,
@@ -522,7 +185,7 @@ pub(in crate::context_bootstrap) fn prepare_joint_history_participant<'s>(
))
}
-pub(in crate::context_bootstrap) fn finish_joint_history_participant<'s>(
+pub(in crate::context_bootstrap) fn finish_history_participant<'s>(
scope: &mut v8::PinScope<'s, '_>,
applied: &super::apply::AppliedHistoryEntry<'s>,
outcome: NavigationDispatchOutcome<'s>,
@@ -532,6 +195,29 @@ pub(in crate::context_bootstrap) fn finish_joint_history_participant<'s>(
if settlement.is_some_and(|data| !traversal_intercept_is_active(scope, data.into())) {
return;
}
+ if !outcome.intercepted {
+ crate::script_vm::perform_microtask_checkpoint_and_report_pending_promise_rejections(scope);
+ if !navigation_document_has_opaque_origin(scope, applied.owner)
+ && let Some(navigation) = window_navigation_for_holder(scope, applied.owner)
+ {
+ let active_scroll = super::super::navigation_events::navigation_has_active_scroll_event(
+ scope, navigation,
+ );
+ if active_scroll
+ || !super::super::navigation_entry::restore_current_navigation_entry_scroll_position(
+ scope,
+ applied.owner,
+ )
+ {
+ perform_navigation_scroll_if_needed(scope, navigation, &applied.url, true);
+ }
+ dispatch_navigation_success(scope, navigation);
+ }
+ resolve_resolver_array(scope, finished_resolvers, applied.resolved_entry);
+ crate::script_vm::perform_microtask_checkpoint_and_report_pending_promise_rejections(scope);
+ dispatch_history_entry_post_commit_events(scope, applied, true);
+ return;
+ }
let Some(navigation) = window_navigation_for_holder(scope, applied.owner) else {
dispatch_history_entry_post_commit_events(scope, applied, true);
resolve_resolver_array(scope, finished_resolvers, applied.resolved_entry);
@@ -600,354 +286,16 @@ fn history_traversal_target_window<'s>(
}
}
-fn target_entry_is_still_available<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- history: v8::Local<'s, v8::Object>,
- target_index: u32,
- expected_entry: Option<v8::Local<'s, v8::Object>>,
- expected_key: Option<&str>,
-) -> bool {
- let current_entry = history_entries(scope, history)
- .and_then(|entries| entries.get_index(scope, target_index))
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok());
- if let Some(expected_key) = expected_key {
- return current_entry
- .and_then(|entry| navigation_entry_key_value(scope, entry))
- .is_some_and(|key| key == expected_key);
- }
- expected_entry.is_none_or(|expected_entry| {
- current_entry.is_some_and(|entry| entry.strict_equals(expected_entry.into()))
- })
-}
-
-fn queue_pending_precommit_history_traversal<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- navigation: v8::Local<'s, v8::Object>,
- history: v8::Local<'s, v8::Object>,
- target_index: u32,
- plan: Option<&moli_session_history::SessionHistoryTraversalPlan>,
- outcome: NavigationDispatchOutcome<'s>,
- results: &[crate::native_bridge::PendingNavigationResult],
-) -> bool {
- let Some(precommit_result) = outcome.precommit_result else {
- return false;
- };
- let Some(result_object) = v8::Local::<v8::Object>::try_from(precommit_result).ok() else {
- return false;
- };
- let Some(then) = result_object
- .get(scope, v8str(scope, "then").into())
- .and_then(|value| v8::Local::<v8::Function>::try_from(value).ok())
- else {
- return false;
- };
- let Some(event) = outcome.precommit_event else {
- return false;
- };
- let (committed_resolvers, finished_resolvers) = pending_result_resolver_arrays(scope, results);
- let promise = v8::Local::<v8::Promise>::try_from(precommit_result)
- .is_ok()
- .then_some(precommit_result);
- let data = TraversalPrecommitDataDeclaration {
- active: true,
- navigation,
- history,
- event,
- signal: outcome.signal,
- 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,
- finished_resolvers,
- }
- .bind(scope)
- .expect("traversal precommit data should bind");
- set_navigation_pending_traversal_precommit(scope, navigation, data);
- let Some(on_fulfilled) = v8::Function::builder(traversal_precommit_fulfilled_callback)
- .data(data.into())
- .build(scope)
- else {
- return false;
- };
- let Some(on_rejected) = v8::Function::builder(traversal_precommit_rejected_callback)
- .data(data.into())
- .build(scope)
- else {
- return false;
- };
- then.call(
- scope,
- precommit_result,
- &[on_fulfilled.into(), on_rejected.into()],
- )
- .is_some()
-}
-
-pub(in crate::context_bootstrap) fn pending_result_resolver_arrays<'s>(
+pub(in crate::context_bootstrap) fn finished_resolver_array<'s>(
scope: &mut v8::PinScope<'s, '_>,
results: &[crate::native_bridge::PendingNavigationResult],
-) -> (v8::Local<'s, v8::Array>, v8::Local<'s, v8::Array>) {
- let committed = v8::Array::new(scope, results.len() as i32);
+) -> v8::Local<'s, v8::Array> {
let finished = v8::Array::new(scope, results.len() as i32);
for (index, result) in results.iter().enumerate() {
- let committed_resolver = v8::Local::new(scope, &result.committed_resolver);
let finished_resolver = v8::Local::new(scope, &result.finished_resolver);
- let _ = committed.set_index(scope, index as u32, committed_resolver.into());
let _ = finished.set_index(scope, index as u32, finished_resolver.into());
}
- (committed, finished)
-}
-
-fn traversal_precommit_is_active<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- data: v8::Local<'s, v8::Value>,
-) -> bool {
- v8::Local::<v8::Object>::try_from(data)
- .ok()
- .is_some_and(|data| traversal_private_bool(scope, data, TRAVERSAL_PRECOMMIT_ACTIVE_SLOT))
-}
-
-fn set_traversal_precommit_active<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- data: v8::Local<'s, v8::Object>,
- active: bool,
-) {
- set_private_value(
- scope,
- data,
- TRAVERSAL_PRECOMMIT_ACTIVE_SLOT,
- v8::Boolean::new(scope, active).into(),
- );
-}
-
-fn set_traversal_precommit_inactive<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- data: v8::Local<'s, v8::Object>,
-) {
- set_traversal_precommit_active(scope, data, false);
- let Some(navigation) = get_private_value(scope, data, TRAVERSAL_PRECOMMIT_NAVIGATION_SLOT)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- else {
- return;
- };
- clear_navigation_pending_traversal_precommit_if_current(scope, navigation, data);
-}
-
-#[allow(clippy::type_complexity)]
-fn traversal_precommit_data<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- data: v8::Local<'s, v8::Value>,
-) -> Option<(
- v8::Local<'s, v8::Object>,
- v8::Local<'s, v8::Object>,
- v8::Local<'s, v8::Object>,
- Option<v8::Local<'s, v8::Object>>,
- u32,
- Option<v8::Local<'s, v8::Promise>>,
- v8::Local<'s, v8::Array>,
- v8::Local<'s, v8::Array>,
-)> {
- let data = v8::Local::<v8::Object>::try_from(data).ok()?;
- let navigation = get_private_value(scope, data, TRAVERSAL_PRECOMMIT_NAVIGATION_SLOT)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
- let history = get_private_value(scope, data, TRAVERSAL_PRECOMMIT_HISTORY_SLOT)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
- let event = get_private_value(scope, data, TRAVERSAL_PRECOMMIT_EVENT_SLOT)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())?;
- let signal = get_private_value(scope, data, TRAVERSAL_PRECOMMIT_SIGNAL_SLOT)
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok());
- let target_index = get_private_value(scope, data, TRAVERSAL_PRECOMMIT_TARGET_INDEX_SLOT)
- .and_then(|value| value.uint32_value(scope))?;
- let promise = get_private_value(scope, data, TRAVERSAL_PRECOMMIT_PROMISE_SLOT)
- .and_then(|value| v8::Local::<v8::Promise>::try_from(value).ok());
- let committed_resolvers =
- get_private_value(scope, data, TRAVERSAL_PRECOMMIT_COMMITTED_RESOLVERS_SLOT)
- .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())?;
- let finished_resolvers =
- get_private_value(scope, data, TRAVERSAL_PRECOMMIT_FINISHED_RESOLVERS_SLOT)
- .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())?;
- Some((
- navigation,
- history,
- event,
- signal,
- target_index,
- promise,
- committed_resolvers,
- finished_resolvers,
- ))
-}
-
-pub(in crate::context_bootstrap) fn cancel_pending_precommit_history_traversal<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- navigation: v8::Local<'s, v8::Object>,
-) -> bool {
- if super::super::navigation_joint_traversal::cancel_pending(scope, navigation) {
- return true;
- }
- let Some(data) = navigation_pending_traversal_precommit(scope, navigation)
- .filter(|data| traversal_precommit_is_active(scope, (*data).into()))
- else {
- return false;
- };
- let Some((navigation, _, _, signal, _, _, committed_resolvers, finished_resolvers)) =
- traversal_precommit_data(scope, data.into())
- else {
- return false;
- };
- set_traversal_precommit_inactive(scope, data);
- let error =
- navigation_dom_exception(scope, "Navigation was canceled before commit", "AbortError");
- if let Some(signal) = signal
- && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
- {
- unsafe { &mut *host_ptr }.abort_signal(scope, signal, error);
- }
- finish_navigation_error_events(scope, navigation, error, "");
- reject_resolver_array(scope, committed_resolvers, error, false);
- reject_resolver_array(scope, finished_resolvers, error, true);
- true
-}
-
-fn traversal_precommit_fulfilled_callback<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- args: v8::FunctionCallbackArguments<'s>,
- _rv: v8::ReturnValue<'_, v8::Value>,
-) {
- if !traversal_precommit_is_active(scope, args.data()) {
- return;
- }
- let Some((
- navigation,
- history,
- event,
- signal,
- target_index,
- _,
- committed_resolvers,
- finished_resolvers,
- )) = traversal_precommit_data(scope, args.data())
- else {
- return;
- };
- if let Ok(data) = v8::Local::<v8::Object>::try_from(args.data()) {
- set_traversal_precommit_inactive(scope, data);
- }
- let joint_step = v8::Local::<v8::Object>::try_from(args.data())
- .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_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);
- reject_resolver_array(scope, finished_resolvers, error, true);
- return;
- };
- resolve_resolver_array(scope, committed_resolvers, applied.resolved_entry);
- let active_intercept = set_active_traversal_intercept_settlement(
- scope,
- navigation,
- signal,
- finished_resolvers,
- applied.resolved_entry,
- &applied.url,
- );
- dispatch_history_entry_currententrychange(scope, &applied);
- let (intercept_error, intercept_result) =
- run_navigation_precommit_deferred_handlers(scope, event);
- suppress_intercept_result_unhandled_rejection(scope, intercept_result);
- dispatch_history_entry_post_commit_events(scope, &applied, true);
- if !traversal_intercept_is_active(scope, active_intercept.into()) {
- return;
- }
- if let Some(error) = intercept_error {
- set_traversal_intercept_inactive(scope, navigation, active_intercept.into());
- finish_navigation_error_events(scope, navigation, error, &applied.url);
- reject_resolver_array(scope, finished_resolvers, error, true);
- if let Some(signal) = signal
- && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
- {
- unsafe { &mut *host_ptr }.abort_signal(scope, signal, error);
- }
- return;
- }
- let Some(result) = intercept_result else {
- set_traversal_intercept_inactive(scope, navigation, active_intercept.into());
- perform_navigation_scroll_if_needed(scope, navigation, &applied.url, true);
- dispatch_navigation_success(scope, navigation);
- resolve_resolver_array(scope, finished_resolvers, applied.resolved_entry);
- return;
- };
- if !traversal_intercept_is_active(scope, active_intercept.into()) {
- return;
- }
- set_traversal_intercept_inactive(scope, navigation, active_intercept.into());
- if !queue_pending_traversal_intercept_settlement(
- scope,
- navigation,
- signal,
- finished_resolvers,
- applied.resolved_entry,
- &applied.url,
- result,
- ) {
- perform_navigation_scroll_if_needed(scope, navigation, &applied.url, true);
- dispatch_navigation_success(scope, navigation);
- resolve_resolver_array(scope, finished_resolvers, applied.resolved_entry);
- }
-}
-
-fn traversal_precommit_rejected_callback<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- args: v8::FunctionCallbackArguments<'s>,
- _rv: v8::ReturnValue<'_, v8::Value>,
-) {
- if !traversal_precommit_is_active(scope, args.data()) {
- return;
- }
- let Some((navigation, _, _, signal, _, promise, committed_resolvers, finished_resolvers)) =
- traversal_precommit_data(scope, args.data())
- else {
- return;
- };
- if let Ok(data) = v8::Local::<v8::Object>::try_from(args.data()) {
- set_traversal_precommit_inactive(scope, data);
- }
- let error = promise
- .filter(|promise| promise.state() == v8::PromiseState::Rejected)
- .map(|promise| promise.result(scope))
- .unwrap_or_else(|| args.get(0));
- if let Some(signal) = signal
- && let Some(host_ptr) = context_host_ptr_from_global_bridge(scope)
- {
- unsafe { &mut *host_ptr }.abort_signal(scope, signal, error);
- }
- finish_navigation_error_events(scope, navigation, error, "");
- reject_resolver_array(scope, committed_resolvers, error, false);
- reject_resolver_array(scope, finished_resolvers, error, true);
+ finished
}
fn suppress_intercept_result_unhandled_rejection<'s>(
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs
index 0b1a37950..89cdbdab4 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_events.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_events.rs
@@ -1212,16 +1212,6 @@ pub(crate) fn dispatch_srcdoc_navigation_navigate_event_for_window<'s>(
)
}
-pub(super) fn dispatch_navigation_traverse_event<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- navigation: v8::Local<'s, v8::Object>,
- history: v8::Local<'s, v8::Object>,
- target_index: u32,
-) -> bool {
- dispatch_navigation_traverse_event_with_outcome(scope, navigation, history, target_index, None)
- .proceed
-}
-
pub(super) fn dispatch_navigation_traverse_event_with_outcome<'s>(
scope: &mut v8::PinScope<'s, '_>,
navigation: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_joint_traversal.rs b/moli-renderer-v8/src/context_bootstrap/navigation_joint_traversal.rs
deleted file mode 100644
index ff52a8b3e..000000000
--- a/moli-renderer-v8/src/context_bootstrap/navigation_joint_traversal.rs
+++ /dev/null
@@ -1,607 +0,0 @@
-//! A joint step is admitted as a unit. No participant may independently move
-//! the shared cursor while its siblings are still running navigation script.
-
-use super::history_runtime::{apply, traversal};
-use super::navigation_entry::{history_entries, history_index, navigation_current_entry};
-use super::navigation_events::{
- NavigationDispatchOutcome, dispatch_beforeunload_for_runtime_owner,
- dispatch_navigation_traverse_event_with_outcome, dispatch_pagehide_for_runtime_owner,
- dispatch_unload_for_runtime_owner,
-};
-use super::navigation_result::navigation_dom_exception;
-use super::navigation_seed::history_entry_seed_for_traversal;
-use super::navigation_traversal_execution::{
- TraversalTarget, queue_history_traversal_without_result,
-};
-use super::navigation_traversal_plan::JointTraversalPlan;
-use super::navigation_window::{
- child_browsing_context_handle_for_runtime_owner, navigation_document_has_opaque_origin,
- navigation_document_is_active, window_history_for_holder, window_navigation_for_holder,
-};
-use crate::native_bridge::PendingNavigationResult;
-use crate::util::{context_host_ptr_from_global_bridge, get_private_value, set_private_value};
-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";
-const FINISHED: &str = "__lmJointFinished";
-const HISTORY: &str = "__lmJointHistory";
-const SOURCE: &str = "__lmJointSource";
-const DESTINATION: &str = "__lmJointDestination";
-const NAVIGATION: &str = "__lmJointNavigation";
-const SIGNAL: &str = "__lmJointSignal";
-const EVENT: &str = "__lmJointEvent";
-const INTERCEPTED: &str = "__lmJointIntercepted";
-const INTERCEPT_RESULT: &str = "__lmJointInterceptResult";
-const INTERCEPT_ERROR: &str = "__lmJointInterceptError";
-
-pub(super) fn queue_plan<'s>(scope: &mut v8::PinScope<'s, '_>, mut plan: JointTraversalPlan<'s>) {
- // A root Document replacement owns the whole descendant tree and must be
- // performed by its browser/popup loader. Otherwise queue the step on its caller, never
- // select one changing frame as a substitute for the joint operation.
- if let Some(index) = plan.cross_document_root_index(scope) {
- queue_history_traversal_without_result(scope, plan.targets.remove(index));
- return;
- }
- let Some(history) = window_history_for_holder(scope, plan.owner) else {
- return;
- };
- let index = history_index(scope, history);
- queue_history_traversal_without_result(
- scope,
- TraversalTarget {
- owner: plan.owner,
- history,
- current_index: index,
- target_index: index,
- joint_step: Some(plan.step()),
- },
- );
-}
-
-pub(super) fn requires_joint_execution<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- plan: &JointTraversalPlan<'s>,
-) -> bool {
- match plan.targets.as_slice() {
- [target] => history_entry_seed_for_traversal(
- scope,
- target.owner,
- target.current_index,
- target.target_index,
- )
- .is_some(),
- _ => true,
- }
-}
-
-fn object<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- data: v8::Local<'s, v8::Object>,
- key: &str,
-) -> Option<v8::Local<'s, v8::Object>> {
- get_private_value(scope, data, key).and_then(|value| value.try_into().ok())
-}
-
-fn array<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- data: v8::Local<'s, v8::Object>,
- key: &str,
-) -> Option<v8::Local<'s, v8::Array>> {
- get_private_value(scope, data, key).and_then(|value| value.try_into().ok())
-}
-
-fn active<'s>(scope: &mut v8::PinScope<'s, '_>, data: v8::Local<'s, v8::Object>) -> bool {
- get_private_value(scope, data, ACTIVE).is_some_and(|value| value.is_true())
-}
-
-fn entry_signature<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- history: v8::Local<'s, v8::Object>,
- index: u32,
-) -> Option<String> {
- let entry = history_entries(scope, history)?
- .get_index(scope, index)?
- .try_into()
- .ok()?;
- let entry = super::session_history::entry_reference(scope, entry)?;
- serde_json::to_string(&(entry.key.as_str(), entry.document.as_str())).ok()
-}
-
-fn signature_matches<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- data: v8::Local<'s, v8::Object>,
- key: &str,
- signature: Option<String>,
-) -> bool {
- let stored = get_private_value(scope, data, key)
- .and_then(|value| value.to_string(scope))
- .map(|value| value.to_rust_string_lossy(scope));
- stored.is_some() && stored == signature
-}
-
-/// All participants and their source/destination identities are captured
-/// before the first callback. Precommit promises delay the whole operation.
-pub(super) fn execute<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- plan: JointTraversalPlan<'s>,
- initiator_info: Option<v8::Local<'s, v8::Value>>,
- results: &[PendingNavigationResult],
-) {
- let data = v8::Object::new(scope);
- set_private_value(scope, data, ACTIVE, v8::Boolean::new(scope, true).into());
- set_private_value(scope, data, OWNER, plan.owner.into());
- set_private_value(
- scope,
- data,
- STEP,
- 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());
- let (committed, finished) = traversal::pending_result_resolver_arrays(scope, results);
- set_private_value(scope, data, COMMITTED, committed.into());
- set_private_value(scope, data, FINISHED, finished.into());
- for (index, target) in plan.targets.iter().enumerate() {
- let participant = v8::Object::new(scope);
- let _ = participants.set_index(scope, index as u32, participant.into());
- set_private_value(scope, participant, HISTORY, target.history.into());
- if !navigation_document_has_opaque_origin(scope, target.owner)
- && let Some(navigation) = window_navigation_for_holder(scope, target.owner)
- {
- set_private_value(scope, participant, NAVIGATION, navigation.into());
- }
- for (slot, index) in [
- (SOURCE, target.current_index),
- (DESTINATION, target.target_index),
- ] {
- let Some(signature) = entry_signature(scope, target.history, index) else {
- abort(scope, data, None);
- return;
- };
- set_private_value(
- scope,
- participant,
- slot,
- v8::String::new(scope, &signature).unwrap().into(),
- );
- }
- }
- let mut precommit = Vec::new();
- for (index, target) in plan.targets.iter().enumerate() {
- let participant = participants
- .get_index(scope, index as u32)
- .unwrap()
- .try_into()
- .unwrap();
- if history_entry_seed_for_traversal(
- scope,
- target.owner,
- target.current_index,
- target.target_index,
- )
- .is_some()
- {
- dispatch_beforeunload_for_runtime_owner(scope, target.owner);
- }
- if validate(scope, data).is_none() {
- abort(scope, data, None);
- return;
- }
- // Only the initiating Navigation owns this API method's info.
- let participant_info =
- initiator_info.filter(|_| target.owner.strict_equals(plan.owner.into()));
- let outcome = object(scope, participant, NAVIGATION)
- .map(|navigation| {
- dispatch_navigation_traverse_event_with_outcome(
- scope,
- navigation,
- target.history,
- target.target_index,
- participant_info,
- )
- })
- .unwrap_or_else(NavigationDispatchOutcome::proceed);
- for value in [outcome.precommit_result, outcome.intercept_result]
- .into_iter()
- .flatten()
- {
- if let Ok(promise) = v8::Local::<v8::Promise>::try_from(value) {
- super::navigation_result::suppress_unhandled_rejection(scope, promise);
- }
- }
- for (slot, value) in [
- (SIGNAL, outcome.signal.map(Into::into)),
- (EVENT, outcome.precommit_event.map(Into::into)),
- (INTERCEPT_RESULT, outcome.intercept_result),
- (INTERCEPT_ERROR, outcome.intercept_error),
- ] {
- if let Some(value) = value {
- set_private_value(scope, participant, slot, value);
- }
- }
- set_private_value(
- scope,
- participant,
- INTERCEPTED,
- v8::Boolean::new(scope, outcome.intercepted).into(),
- );
- if !outcome.proceed
- || outcome.abort_error.is_some()
- || outcome.precommit_error.is_some()
- || validate(scope, data).is_none()
- {
- super::navigation_events::mark_navigation_outcome_default_prevented(scope, &outcome);
- abort(scope, data, outcome.abort_error.or(outcome.precommit_error));
- return;
- }
- if let Some(promise) = outcome.precommit_result {
- precommit.push(promise);
- }
- }
- if precommit.is_empty() {
- commit(scope, data);
- return;
- }
- set_private_value(
- scope,
- data,
- REMAINING,
- v8::Integer::new_from_unsigned(scope, precommit.len() as u32).into(),
- );
- for index in 0..participants.length() {
- let participant = participants
- .get_index(scope, index)
- .unwrap()
- .try_into()
- .unwrap();
- if let Some(navigation) = object(scope, participant, NAVIGATION) {
- cancel_pending(scope, navigation);
- set_private_value(scope, navigation, PENDING, data.into());
- }
- }
- for value in precommit {
- let Some(resolver) = v8::PromiseResolver::new(scope) else {
- abort(scope, data, None);
- return;
- };
- let _ = resolver.resolve(scope, value);
- let promise = resolver.get_promise(scope);
- let fulfilled = v8::Function::builder(precommit_fulfilled)
- .data(data.into())
- .build(scope)
- .unwrap();
- let rejected = v8::Function::builder(precommit_rejected)
- .data(data.into())
- .build(scope)
- .unwrap();
- let _ = promise.then2(scope, fulfilled, rejected);
- }
-}
-
-fn validate<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- data: v8::Local<'s, v8::Object>,
-) -> Option<JointTraversalPlan<'s>> {
- if !active(scope, data) {
- return None;
- }
- let owner = object(scope, data, OWNER)?;
- if !navigation_document_is_active(scope, owner) {
- return None;
- }
- let step = get_private_value(scope, data, STEP)
- .and_then(|value| v8::Local::<v8::BigInt>::try_from(value).ok())?;
- let plan = JointTraversalPlan::resolve(
- scope,
- 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;
- }
- for (index, target) in plan.targets.iter().enumerate() {
- let participant = participants
- .get_index(scope, index as u32)?
- .try_into()
- .ok()?;
- if !navigation_document_is_active(scope, target.owner)
- || !object(scope, participant, HISTORY)?.strict_equals(target.history.into())
- {
- return None;
- }
- let source = entry_signature(scope, target.history, target.current_index);
- let destination = entry_signature(scope, target.history, target.target_index);
- if !signature_matches(scope, participant, SOURCE, source)
- || !signature_matches(scope, participant, DESTINATION, destination)
- {
- return None;
- }
- if let Some(signal) = object(scope, participant, SIGNAL)
- && let Some(host) = context_host_ptr_from_global_bridge(scope)
- && unsafe { &mut *host }.abort_signal_aborted(scope, signal)
- {
- return None;
- }
- }
- Some(plan)
-}
-
-fn deactivate<'s>(scope: &mut v8::PinScope<'s, '_>, data: v8::Local<'s, v8::Object>) {
- set_private_value(scope, data, ACTIVE, v8::Boolean::new(scope, false).into());
- if let Some(participants) = array(scope, data, PARTICIPANTS) {
- for index in 0..participants.length() {
- let Some(participant) = participants
- .get_index(scope, index)
- .and_then(|value| value.try_into().ok())
- else {
- continue;
- };
- if let Some(navigation) = object(scope, participant, NAVIGATION)
- && object(scope, navigation, PENDING)
- .is_some_and(|pending| pending.strict_equals(data.into()))
- {
- set_private_value(scope, navigation, PENDING, v8::undefined(scope).into());
- }
- }
- }
-}
-
-fn abort<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- data: v8::Local<'s, v8::Object>,
- error: Option<v8::Local<'s, v8::Value>>,
-) {
- if !active(scope, data) {
- return;
- }
- deactivate(scope, data);
- let error = error.unwrap_or_else(|| {
- navigation_dom_exception(scope, "Joint history traversal was canceled", "AbortError")
- });
- for slot in [COMMITTED, FINISHED] {
- if let Some(resolvers) = array(scope, data, slot) {
- traversal::reject_resolver_array(scope, resolvers, error, slot == FINISHED);
- }
- }
- if let Some(participants) = array(scope, data, PARTICIPANTS) {
- for index in 0..participants.length() {
- let Some(participant) = participants
- .get_index(scope, index)
- .and_then(|value| value.try_into().ok())
- else {
- continue;
- };
- if let Some(signal) = object(scope, participant, SIGNAL)
- && let Some(host) = context_host_ptr_from_global_bridge(scope)
- {
- unsafe { &mut *host }.abort_signal(scope, signal, error);
- }
- if let Some(navigation) = object(scope, participant, NAVIGATION) {
- super::navigation_lifecycle::finish_navigation_error_events(
- scope, navigation, error, "",
- );
- }
- }
- }
-}
-
-pub(super) fn cancel_pending<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- navigation: v8::Local<'s, v8::Object>,
-) -> bool {
- let Some(data) = object(scope, navigation, PENDING) else {
- return false;
- };
- if !active(scope, data) {
- return false;
- }
- abort(scope, data, None);
- true
-}
-
-fn precommit_fulfilled<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- args: v8::FunctionCallbackArguments<'s>,
- _: v8::ReturnValue<'_, v8::Value>,
-) {
- let Ok(data) = v8::Local::<v8::Object>::try_from(args.data()) else {
- return;
- };
- if !active(scope, data) {
- return;
- }
- let Some(remaining) =
- get_private_value(scope, data, REMAINING).and_then(|value| value.uint32_value(scope))
- else {
- return;
- };
- if remaining <= 1 {
- commit(scope, data);
- } else {
- set_private_value(
- scope,
- data,
- REMAINING,
- v8::Integer::new_from_unsigned(scope, remaining - 1).into(),
- );
- }
-}
-
-fn precommit_rejected<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- args: v8::FunctionCallbackArguments<'s>,
- _: v8::ReturnValue<'_, v8::Value>,
-) {
- if let Ok(data) = v8::Local::<v8::Object>::try_from(args.data()) {
- abort(scope, data, Some(args.get(0)));
- }
-}
-
-fn commit<'s>(scope: &mut v8::PinScope<'s, '_>, data: v8::Local<'s, v8::Object>) {
- let Some(plan) = validate(scope, data) else {
- abort(scope, data, None);
- return;
- };
- let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
- abort(scope, data, None);
- return;
- };
- let mut cross_document = Vec::new();
- for target in &plan.targets {
- if let Some((url, mut seed)) = history_entry_seed_for_traversal(
- scope,
- target.owner,
- target.current_index,
- target.target_index,
- ) {
- let Some(handle) = child_browsing_context_handle_for_runtime_owner(scope, target.owner)
- else {
- abort(scope, data, None);
- return;
- };
- 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())
- .and_then(|entry| super::session_history::entry_reference(scope, entry));
- cross_document.push((target.owner, handle, url, seed));
- }
- }
- // Unload is script too. Finish it for every participant and validate the
- // entire plan again before scheduling any replacement or changing a view.
- for (owner, _, _, _) in &cross_document {
- dispatch_pagehide_for_runtime_owner(scope, *owner);
- if validate(scope, data).is_none() {
- abort(scope, data, None);
- return;
- }
- dispatch_unload_for_runtime_owner(scope, *owner);
- if validate(scope, data).is_none() {
- abort(scope, data, None);
- return;
- }
- }
- let mut prepared = Vec::new();
- for (index, target) in plan.targets.iter().enumerate() {
- if cross_document
- .iter()
- .any(|(owner, _, _, _)| owner.strict_equals(target.owner.into()))
- {
- continue;
- }
- let Some(entry) =
- apply::prepare_local_history_entry_commit(scope, target.history, target.target_index)
- else {
- abort(scope, data, None);
- return;
- };
- prepared.push((index as u32, entry));
- }
- for (_, handle, url, seed) in &cross_document {
- let host = unsafe { &mut *host_ptr };
- let _ =
- host.mark_current_child_document_unload_dispatched_after_navigation_traversal(*handle);
- if !host.queue_deferred_child_browsing_context_navigation_from_entry_seed(
- *handle,
- url.as_str(),
- seed.clone(),
- ) {
- for (_, queued, _, _) in &cross_document {
- host.cancel_joint_child_history_navigation(*queued, plan.step());
- }
- abort(scope, data, None);
- return;
- }
- }
- // 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.core)
- else {
- for (_, handle, _, _) in &cross_document {
- unsafe { &mut *host_ptr }.cancel_joint_child_history_navigation(*handle, plan.step());
- }
- abort(scope, data, None);
- return;
- };
- let applied = prepared
- .into_iter()
- .map(|(index, entry)| (index, apply::commit_prepared_history_entry(scope, entry)))
- .collect::<Vec<_>>();
- deactivate(scope, data);
- if delta != 0 {
- super::session_history::publish(
- scope,
- plan.owner,
- moli_page_types::SessionHistoryUpdateKind::Traverse { delta },
- );
- }
- let participants = array(scope, data, PARTICIPANTS).unwrap();
- let committed = array(scope, data, COMMITTED).unwrap();
- let finished = array(scope, data, FINISHED).unwrap();
- let resolved_entry = navigation_current_entry(scope, plan.owner)
- .map(Into::into)
- .unwrap_or_else(|| v8::undefined(scope).into());
- let requester_replaces_document = cross_document
- .iter()
- .any(|(owner, _, _, _)| owner.strict_equals(plan.owner.into()));
- if !requester_replaces_document {
- traversal::resolve_resolver_array(scope, committed, resolved_entry);
- }
- let mut completions = Vec::new();
- for (index, entry) in &applied {
- let participant = participants
- .get_index(scope, *index)
- .unwrap()
- .try_into()
- .unwrap();
- let mut outcome = NavigationDispatchOutcome::proceed();
- outcome.intercepted =
- get_private_value(scope, participant, INTERCEPTED).is_some_and(|value| value.is_true());
- outcome.signal = object(scope, participant, SIGNAL);
- outcome.precommit_event = object(scope, participant, EVENT);
- outcome.intercept_result = get_private_value(scope, participant, INTERCEPT_RESULT);
- outcome.intercept_error = get_private_value(scope, participant, INTERCEPT_ERROR);
- let resolvers = if entry.owner.strict_equals(plan.owner.into()) {
- finished
- } else {
- v8::Array::new(scope, 0)
- };
- let settlement =
- traversal::prepare_joint_history_participant(scope, entry, &outcome, resolvers);
- completions.push((outcome, resolvers, settlement));
- }
- for (_, entry) in &applied {
- apply::dispatch_history_entry_currententrychange(scope, entry);
- }
- for ((_, entry), (outcome, resolvers, settlement)) in applied.iter().zip(completions) {
- traversal::finish_joint_history_participant(scope, entry, outcome, resolvers, settlement);
- }
- if !requester_replaces_document
- && !applied
- .iter()
- .any(|(_, entry)| entry.owner.strict_equals(plan.owner.into()))
- {
- traversal::resolve_resolver_array(scope, finished, resolved_entry);
- }
-}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs
index 00487c482..d20a4237d 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal.rs
@@ -530,7 +530,7 @@ fn history_traverse<'s>(
queue_browser_owned_top_level_history_traversal(scope, history, delta);
return;
};
- super::navigation_joint_traversal::queue_plan(scope, plan);
+ super::navigation_traversal_coordinator::queue_plan(scope, plan);
}
fn queue_browser_owned_top_level_history_traversal<'s>(
@@ -565,7 +565,7 @@ pub(crate) fn queue_top_level_history_traversal_by_delta(
if plan.has_cross_document_root(scope) {
return false;
}
- super::navigation_joint_traversal::queue_plan(scope, plan);
+ super::navigation_traversal_coordinator::queue_plan(scope, plan);
true
}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs
new file mode 100644
index 000000000..8d15b04a0
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_coordinator.rs
@@ -0,0 +1,553 @@
+//! Admit, reserve and commit complete traversal plans, including zero or one participant.
+
+use super::history_runtime::{apply, results, traversal};
+use super::navigation_entry::{history_entries, history_index, navigation_current_entry};
+use super::navigation_events::{
+ NavigationDispatchOutcome, dispatch_beforeunload_for_runtime_owner,
+ dispatch_navigation_traverse_event_with_outcome, dispatch_pagehide_for_runtime_owner,
+ dispatch_unload_for_runtime_owner,
+};
+use super::navigation_result::navigation_dom_exception;
+use super::navigation_seed::history_entry_seed_for_traversal;
+use super::navigation_traversal_execution::{
+ TraversalTarget, queue_history_traversal_without_result,
+};
+use super::navigation_traversal_plan::JointTraversalPlan;
+use super::navigation_window::{
+ child_browsing_context_handle_for_runtime_owner, navigation_document_has_opaque_origin,
+ navigation_document_is_active, window_history_for_holder, window_navigation_for_holder,
+ window_task_target_for_runtime_owner,
+};
+use crate::document_runtime::DomHandle;
+use crate::native_bridge::history_traversal::{
+ HistoryTraversalId, HistoryTraversalParticipant, PendingHistoryTraversalAdmission,
+ TraversalParticipantOutcome,
+};
+use crate::native_bridge::{NavigationHistoryEntrySeed, PendingNavigationResult};
+use crate::util::context_host_ptr_from_global_bridge;
+use moli_session_history::SessionHistoryEntry;
+
+pub(super) fn queue_plan<'s>(scope: &mut v8::PinScope<'s, '_>, mut plan: JointTraversalPlan<'s>) {
+ // Root Document replacement belongs to the browser/popup loader.
+ if let Some(index) = plan.cross_document_root_index(scope) {
+ queue_history_traversal_without_result(scope, plan.targets.remove(index));
+ return;
+ }
+ let Some(history) = window_history_for_holder(scope, plan.owner) else {
+ return;
+ };
+ let index = history_index(scope, history);
+ queue_history_traversal_without_result(
+ scope,
+ TraversalTarget {
+ owner: plan.owner,
+ history,
+ current_index: index,
+ target_index: index,
+ joint_step: Some(plan.step()),
+ },
+ );
+}
+
+fn entry_reference<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ history: v8::Local<'s, v8::Object>,
+ index: u32,
+) -> Option<SessionHistoryEntry> {
+ let entry = history_entries(scope, history)?
+ .get_index(scope, index)?
+ .try_into()
+ .ok()?;
+ super::session_history::entry_reference(scope, entry)
+}
+
+impl TraversalParticipantOutcome {
+ fn capture(scope: &mut v8::PinScope<'_, '_>, outcome: &NavigationDispatchOutcome<'_>) -> Self {
+ Self {
+ intercepted: outcome.intercepted,
+ signal: outcome.signal.map(|value| v8::Global::new(scope, value)),
+ event: outcome
+ .precommit_event
+ .map(|value| v8::Global::new(scope, value)),
+ intercept_result: outcome
+ .intercept_result
+ .map(|value| v8::Global::new(scope, value)),
+ intercept_error: outcome
+ .intercept_error
+ .map(|value| v8::Global::new(scope, value)),
+ }
+ }
+
+ fn local<'s>(&self, scope: &mut v8::PinScope<'s, '_>) -> NavigationDispatchOutcome<'s> {
+ let mut outcome = NavigationDispatchOutcome::proceed();
+ outcome.intercepted = self.intercepted;
+ outcome.signal = self
+ .signal
+ .as_ref()
+ .map(|value| v8::Local::new(scope, value));
+ outcome.precommit_event = self
+ .event
+ .as_ref()
+ .map(|value| v8::Local::new(scope, value));
+ outcome.intercept_result = self
+ .intercept_result
+ .as_ref()
+ .map(|value| v8::Local::new(scope, value));
+ outcome.intercept_error = self
+ .intercept_error
+ .as_ref()
+ .map(|value| v8::Local::new(scope, value));
+ outcome
+ }
+}
+
+fn capture_participants<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ plan: &JointTraversalPlan<'s>,
+) -> Option<Vec<HistoryTraversalParticipant>> {
+ let host = unsafe { &*context_host_ptr_from_global_bridge(scope)? };
+ plan.targets
+ .iter()
+ .map(|target| {
+ let navigation = (!navigation_document_has_opaque_origin(scope, target.owner))
+ .then(|| window_navigation_for_holder(scope, target.owner))
+ .flatten();
+ Some(HistoryTraversalParticipant {
+ execution_owner: window_task_target_for_runtime_owner(scope, host, target.owner)?
+ .owner(),
+ history: v8::Global::new(scope, target.history),
+ navigation: navigation.map(|value| v8::Global::new(scope, value)),
+ source: entry_reference(scope, target.history, target.current_index)?,
+ destination: entry_reference(scope, target.history, target.target_index)?,
+ outcome: Default::default(),
+ })
+ })
+ .collect()
+}
+
+pub(super) fn execute<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ plan: JointTraversalPlan<'s>,
+ initiator_info: Option<v8::Local<'s, v8::Value>>,
+ results: Vec<PendingNavigationResult>,
+) {
+ let captured = capture_participants(scope, &plan).and_then(|participants| {
+ let host = unsafe { &*context_host_ptr_from_global_bridge(scope)? };
+ let owner = window_task_target_for_runtime_owner(scope, host, plan.owner)?.owner();
+ Some((participants, owner))
+ });
+ let Some((participants, execution_owner)) = captured else {
+ let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
+ results::reject_pending_navigation_results(scope, &results, error);
+ return;
+ };
+ let mut admission = PendingHistoryTraversalAdmission {
+ id: HistoryTraversalId::allocate(),
+ active: true.into(),
+ plan: plan.core,
+ initiator: v8::Global::new(scope, plan.owner),
+ execution_owner,
+ participants,
+ results,
+ remaining_precommit: 0.into(),
+ };
+ let mut precommit = Vec::new();
+ for (index, target) in plan.targets.iter().enumerate() {
+ if history_entry_seed_for_traversal(
+ scope,
+ target.owner,
+ target.current_index,
+ target.target_index,
+ )
+ .is_some()
+ {
+ dispatch_beforeunload_for_runtime_owner(scope, target.owner);
+ }
+ if validate(scope, &admission).is_none() {
+ abort(scope, &admission, None);
+ return;
+ }
+ // Only the initiating Navigation owns this API method's info.
+ let info = initiator_info.filter(|_| target.owner.strict_equals(plan.owner.into()));
+ let navigation = admission.participants[index]
+ .navigation
+ .as_ref()
+ .map(|value| v8::Local::new(scope, value));
+ let outcome = navigation
+ .map(|navigation| {
+ dispatch_navigation_traverse_event_with_outcome(
+ scope,
+ navigation,
+ target.history,
+ target.target_index,
+ info,
+ )
+ })
+ .unwrap_or_else(NavigationDispatchOutcome::proceed);
+ for value in [outcome.precommit_result, outcome.intercept_result]
+ .into_iter()
+ .flatten()
+ {
+ if let Ok(promise) = v8::Local::<v8::Promise>::try_from(value) {
+ super::navigation_result::suppress_unhandled_rejection(scope, promise);
+ }
+ }
+ admission.participants[index].outcome =
+ TraversalParticipantOutcome::capture(scope, &outcome);
+ if !outcome.proceed
+ || outcome.abort_error.is_some()
+ || outcome.precommit_error.is_some()
+ || validate(scope, &admission).is_none()
+ {
+ super::navigation_events::mark_navigation_outcome_default_prevented(scope, &outcome);
+ abort(
+ scope,
+ &admission,
+ outcome.abort_error.or(outcome.precommit_error),
+ );
+ return;
+ }
+ if let Some(promise) = outcome.precommit_result {
+ precommit.push(promise);
+ }
+ }
+ if precommit.is_empty() {
+ commit(scope, &admission);
+ return;
+ }
+ for participant in &admission.participants {
+ if let Some(navigation) = &participant.navigation {
+ let navigation = v8::Local::new(scope, navigation);
+ cancel_pending(scope, navigation);
+ }
+ }
+ if validate(scope, &admission).is_none() {
+ abort(scope, &admission, None);
+ return;
+ }
+ admission.remaining_precommit.set(precommit.len());
+ let Some(host) = context_host_ptr_from_global_bridge(scope) else {
+ return;
+ };
+ let id = unsafe { &mut *host }
+ .pending_history_traversal_admissions
+ .insert(admission);
+ let data = v8::BigInt::new_from_u64(scope, id.raw());
+ for value in precommit {
+ let Some(resolver) = v8::PromiseResolver::new(scope) else {
+ if let Some(admission) = unsafe { &mut *host }
+ .pending_history_traversal_admissions
+ .take(id)
+ {
+ abort(scope, &admission, None);
+ }
+ return;
+ };
+ let _ = resolver.resolve(scope, value);
+ let fulfilled = v8::Function::builder(precommit_fulfilled)
+ .data(data.into())
+ .build(scope)
+ .unwrap();
+ let rejected = v8::Function::builder(precommit_rejected)
+ .data(data.into())
+ .build(scope)
+ .unwrap();
+ let _ = resolver
+ .get_promise(scope)
+ .then2(scope, fulfilled, rejected);
+ }
+}
+
+fn validate<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ admission: &PendingHistoryTraversalAdmission,
+) -> Option<Vec<TraversalTarget<'s>>> {
+ let owner = v8::Local::new(scope, &admission.initiator);
+ if !admission.active.get() || !navigation_document_is_active(scope, owner) {
+ return None;
+ }
+ let targets = super::session_history::project_traversal(scope, owner, &admission.plan)?;
+ if targets.len() != admission.participants.len() {
+ return None;
+ }
+ for (target, participant) in targets.iter().zip(&admission.participants) {
+ let history = v8::Local::new(scope, &participant.history);
+ if !navigation_document_is_active(scope, target.owner)
+ || !history.strict_equals(target.history.into())
+ || entry_reference(scope, history, target.current_index).as_ref()
+ != Some(&participant.source)
+ || entry_reference(scope, history, target.target_index).as_ref()
+ != Some(&participant.destination)
+ {
+ return None;
+ }
+ if let Some(signal) = &participant.outcome.signal {
+ let signal = v8::Local::new(scope, signal);
+ let host = context_host_ptr_from_global_bridge(scope)?;
+ if unsafe { &mut *host }.abort_signal_aborted(scope, signal) {
+ return None;
+ }
+ }
+ }
+ Some(targets)
+}
+
+fn deactivate(scope: &mut v8::PinScope<'_, '_>, admission: &PendingHistoryTraversalAdmission) {
+ admission.active.set(false);
+ if let Some(host) = context_host_ptr_from_global_bridge(scope) {
+ unsafe { &mut *host }
+ .pending_history_traversal_admissions
+ .take(admission.id);
+ }
+}
+
+fn abort<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ admission: &PendingHistoryTraversalAdmission,
+ error: Option<v8::Local<'s, v8::Value>>,
+) {
+ if !admission.active.get() {
+ return;
+ }
+ deactivate(scope, admission);
+ let error = error.unwrap_or_else(|| {
+ navigation_dom_exception(scope, "History traversal was canceled", "AbortError")
+ });
+ results::reject_pending_navigation_results(scope, &admission.results, error);
+ for participant in &admission.participants {
+ if let Some(signal) = &participant.outcome.signal
+ && let Some(host) = context_host_ptr_from_global_bridge(scope)
+ {
+ let signal = v8::Local::new(scope, signal);
+ unsafe { &mut *host }.abort_signal(scope, signal, error);
+ }
+ if let Some(navigation) = &participant.navigation {
+ let navigation = v8::Local::new(scope, navigation);
+ super::navigation_lifecycle::finish_navigation_error_events(
+ scope, navigation, error, "",
+ );
+ }
+ }
+}
+
+pub(super) fn cancel_pending<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ navigation: v8::Local<'s, v8::Object>,
+) -> bool {
+ let Some(host) = context_host_ptr_from_global_bridge(scope) else {
+ return false;
+ };
+ let admission = unsafe { &mut *host }
+ .pending_history_traversal_admissions
+ .take_for_navigation(scope, navigation);
+ let Some(admission) = admission else {
+ return false;
+ };
+ abort(scope, &admission, None);
+ true
+}
+
+fn callback_id(value: v8::Local<'_, v8::Value>) -> Option<HistoryTraversalId> {
+ let value = v8::Local::<v8::BigInt>::try_from(value).ok()?;
+ Some(HistoryTraversalId::from_raw(value.u64_value().0))
+}
+
+/// LocalWindow retirement must settle surviving callers before releasing handles.
+/// Drain first: rejecting promises and dispatching abort/error events can reenter.
+pub(crate) fn cancel_history_traversals_for_retiring_window(
+ scope: &mut v8::PinScope<'_, '_>,
+ owner: crate::native_bridge::WindowExecutionContextOwner,
+) {
+ let Some(host) = context_host_ptr_from_global_bridge(scope) else {
+ return;
+ };
+ let admissions = unsafe { &mut *host }
+ .pending_history_traversal_admissions
+ .take_for_owner(owner);
+ for admission in admissions {
+ abort(scope, &admission, None);
+ }
+}
+
+fn precommit_fulfilled<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ _: v8::ReturnValue<'_, v8::Value>,
+) {
+ let Some(id) = callback_id(args.data()) else {
+ return;
+ };
+ let Some(host) = context_host_ptr_from_global_bridge(scope) else {
+ return;
+ };
+ let admission = unsafe { &mut *host }
+ .pending_history_traversal_admissions
+ .fulfill_precommit(id);
+ if let Some(admission) = admission {
+ commit(scope, &admission);
+ }
+}
+
+fn precommit_rejected<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ _: v8::ReturnValue<'_, v8::Value>,
+) {
+ let Some(id) = callback_id(args.data()) else {
+ return;
+ };
+ let Some(host) = context_host_ptr_from_global_bridge(scope) else {
+ return;
+ };
+ let admission = unsafe { &mut *host }
+ .pending_history_traversal_admissions
+ .take(id);
+ if let Some(admission) = admission {
+ abort(scope, &admission, Some(args.get(0)));
+ }
+}
+
+struct CrossDocumentParticipant<'s> {
+ owner: v8::Local<'s, v8::Object>,
+ handle: DomHandle,
+ url: url::Url,
+ seed: NavigationHistoryEntrySeed,
+}
+
+fn commit(scope: &mut v8::PinScope<'_, '_>, admission: &PendingHistoryTraversalAdmission) {
+ let Some(targets) = validate(scope, admission) else {
+ abort(scope, admission, None);
+ return;
+ };
+ let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
+ return;
+ };
+ let owner = v8::Local::new(scope, &admission.initiator);
+ let step = admission.plan.target_step();
+ let mut cross_document = Vec::new();
+ for target in &targets {
+ if let Some((url, mut seed)) = history_entry_seed_for_traversal(
+ scope,
+ target.owner,
+ target.current_index,
+ target.target_index,
+ ) {
+ let Some(handle) = child_browsing_context_handle_for_runtime_owner(scope, target.owner)
+ else {
+ abort(scope, admission, None);
+ return;
+ };
+ seed.session_history.target_step = Some(step);
+ seed.session_history.admitted_entry =
+ entry_reference(scope, target.history, target.target_index);
+ cross_document.push(CrossDocumentParticipant {
+ owner: target.owner,
+ handle,
+ url,
+ seed,
+ });
+ }
+ }
+ for participant in &cross_document {
+ dispatch_pagehide_for_runtime_owner(scope, participant.owner);
+ if validate(scope, admission).is_none() {
+ abort(scope, admission, None);
+ return;
+ }
+ dispatch_unload_for_runtime_owner(scope, participant.owner);
+ if validate(scope, admission).is_none() {
+ abort(scope, admission, None);
+ return;
+ }
+ }
+ let mut prepared = Vec::new();
+ for (index, target) in targets.iter().enumerate() {
+ if cross_document
+ .iter()
+ .any(|participant| participant.owner.strict_equals(target.owner.into()))
+ {
+ continue;
+ }
+ let Some(entry) =
+ apply::prepare_local_history_entry_commit(scope, target.history, target.target_index)
+ else {
+ abort(scope, admission, None);
+ return;
+ };
+ prepared.push((index, entry));
+ }
+ for participant in &cross_document {
+ let host = unsafe { &mut *host_ptr };
+ let _ = host.mark_current_child_document_unload_dispatched_after_navigation_traversal(
+ participant.handle,
+ );
+ if !host.queue_deferred_child_browsing_context_navigation_from_entry_seed(
+ participant.handle,
+ participant.url.as_str(),
+ participant.seed.clone(),
+ ) {
+ for queued in &cross_document {
+ host.cancel_joint_child_history_navigation(queued.handle, step);
+ }
+ abort(scope, admission, None);
+ return;
+ }
+ }
+ // Acceptance point: every admission and reservation passed. Installing all
+ // same-Document views below runs no author callbacks and cannot fail.
+ let Some(delta) = super::session_history::commit_traversal(scope, owner, &admission.plan)
+ else {
+ for participant in &cross_document {
+ unsafe { &mut *host_ptr }
+ .cancel_joint_child_history_navigation(participant.handle, step);
+ }
+ abort(scope, admission, None);
+ return;
+ };
+ let applied = prepared
+ .into_iter()
+ .map(|(index, entry)| (index, apply::commit_prepared_history_entry(scope, entry)))
+ .collect::<Vec<_>>();
+ deactivate(scope, admission);
+ if delta != 0 {
+ super::session_history::publish(
+ scope,
+ owner,
+ moli_page_types::SessionHistoryUpdateKind::Traverse { delta },
+ );
+ }
+ let finished = traversal::finished_resolver_array(scope, &admission.results);
+ let resolved_entry = navigation_current_entry(scope, owner)
+ .map(Into::into)
+ .unwrap_or_else(|| v8::undefined(scope).into());
+ let requester_replaces_document = cross_document
+ .iter()
+ .any(|participant| participant.owner.strict_equals(owner.into()));
+ if !requester_replaces_document {
+ results::resolve_pending_navigation_committed(scope, &admission.results, resolved_entry);
+ }
+ let mut completions = Vec::new();
+ for (index, entry) in &applied {
+ let outcome = admission.participants[*index].outcome.local(scope);
+ let resolvers = if entry.owner.strict_equals(owner.into()) {
+ finished
+ } else {
+ v8::Array::new(scope, 0)
+ };
+ let settlement = traversal::prepare_history_participant(scope, entry, &outcome, resolvers);
+ completions.push((outcome, resolvers, settlement));
+ }
+ for (_, entry) in &applied {
+ apply::dispatch_history_entry_currententrychange(scope, entry);
+ }
+ for ((_, entry), (outcome, resolvers, settlement)) in applied.iter().zip(completions) {
+ traversal::finish_history_participant(scope, entry, outcome, resolvers, settlement);
+ }
+ if !requester_replaces_document
+ && !applied
+ .iter()
+ .any(|(_, entry)| entry.owner.strict_equals(owner.into()))
+ {
+ results::resolve_pending_navigation_finished(scope, &admission.results, resolved_entry);
+ }
+}
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 85c793d2c..2bbc82f9d 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_execution.rs
@@ -1,27 +1,16 @@
-use super::history_runtime::{
- apply_history_entry, reject_pending_navigation_results, route_history_traversal_task,
-};
-use super::navigation_entry::{history_entries, history_index, navigation_entry_key_value};
-use super::navigation_events::{
- dispatch_beforeunload_for_runtime_owner, dispatch_navigation_traverse_event,
- dispatch_navigation_traverse_event_with_outcome, dispatch_pagehide_for_runtime_owner,
- dispatch_unload_for_runtime_owner, mark_navigation_outcome_default_prevented,
-};
+use super::history_runtime::route_history_traversal_task;
+use super::navigation_entry::{history_entries, navigation_entry_key_value};
use super::navigation_result::{
- navigation_dom_exception, navigation_immediate_current_entry_result, navigation_pending_result,
- navigation_rejected_dom_exception_result,
+ navigation_pending_result, navigation_rejected_dom_exception_result,
};
use super::navigation_seed::history_entry_seed_for_traversal;
use super::navigation_window::{
child_browsing_context_handle_for_runtime_owner, runtime_window_is_global,
- window_history_for_holder, window_task_target_for_runtime_owner,
+ window_task_target_for_runtime_owner,
};
-use super::navigation_window::{navigation_document_is_active, window_navigation_for_holder};
use super::*;
use crate::document_runtime::DomHandle;
-use crate::native_bridge::{
- NavigationHistoryEntrySeed, PendingChildCrossDocumentTraversal, PendingHistoryTraversalAction,
-};
+use crate::native_bridge::PendingHistoryTraversalAction;
pub(super) struct TraversalTarget<'s> {
pub(super) owner: v8::Local<'s, v8::Object>,
@@ -42,17 +31,10 @@ pub(super) fn queue_navigation_traversal_with_result<'s>(
});
let child_handle = child_browsing_context_handle_for_traversal(scope, target.owner);
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
- if !dispatch_traverse_event(scope, &target) {
- return Some(navigation_rejected_dom_exception_result(
- scope,
- "Navigation was canceled",
- "AbortError",
- ));
- }
- apply_history_entry(scope, target.history, target.target_index, None, true, None);
- return Some(navigation_immediate_current_entry_result(
+ return Some(navigation_rejected_dom_exception_result(
scope,
- target.owner,
+ "Navigation was canceled",
+ "AbortError",
));
};
let host = unsafe { &mut *host_ptr };
@@ -86,7 +68,7 @@ pub(super) fn queue_navigation_traversal_with_result<'s>(
);
return Some(navigation_pending_result(scope));
}
- let Some(child_handle) = child_handle else {
+ if child_handle.is_none() {
return Some(navigation_pending_result(scope));
};
let target_key = traversal_target_entry(scope, &target)
@@ -99,10 +81,8 @@ pub(super) fn queue_navigation_traversal_with_result<'s>(
let (result, producer) = host.queue_child_cross_document_traversal_with_result(
receiver_scope,
exact_target,
- child_handle,
target.target_index,
target_key,
- target_url.as_str(),
seed,
info,
)?;
@@ -147,10 +127,6 @@ pub(super) fn queue_history_traversal_without_result<'s>(
});
let child_handle = child_browsing_context_handle_for_traversal(scope, target.owner);
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
- if !dispatch_traverse_event(scope, &target) {
- return;
- }
- apply_history_entry(scope, target.history, target.target_index, None, true, None);
return;
};
let host = unsafe { &mut *host_ptr };
@@ -187,7 +163,7 @@ pub(super) fn queue_history_traversal_without_result<'s>(
);
return;
}
- if let Some(child_handle) = child_handle {
+ if child_handle.is_some() {
let target_key = traversal_target_entry(scope, &target)
.and_then(|entry| navigation_entry_key_value(scope, entry));
let receiver_context = target
@@ -198,10 +174,8 @@ pub(super) fn queue_history_traversal_without_result<'s>(
if let Some(producer) = host.queue_child_cross_document_traversal(
receiver_scope,
exact_target,
- child_handle,
target.target_index,
target_key,
- target_url.as_str(),
seed,
) {
route_history_traversal_task(receiver_scope, host, producer);
@@ -254,118 +228,6 @@ fn traversal_target_entry_still_available<'s>(
.is_some_and(|entry| entry.strict_equals(expected_entry.into()))
}
-fn traversal_target_key_still_available<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- history: v8::Local<'s, v8::Object>,
- target_index: u32,
- expected_key: Option<&str>,
-) -> bool {
- let Some(expected_key) = expected_key else {
- return true;
- };
- history_entries(scope, history)
- .and_then(|entries| entries.get_index(scope, target_index))
- .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
- .and_then(|entry| navigation_entry_key_value(scope, entry))
- .is_some_and(|key| key == expected_key)
-}
-
-fn dispatch_traverse_event<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- target: &TraversalTarget<'s>,
-) -> bool {
- let Some(navigation) = window_navigation_for_holder(scope, target.owner) else {
- return true;
- };
- dispatch_navigation_traverse_event(scope, navigation, target.history, target.target_index)
-}
-
-fn dispatch_child_cross_document_traverse_event<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- target: &TraversalTarget<'s>,
- info: Option<v8::Local<'s, v8::Value>>,
-) -> bool {
- dispatch_beforeunload_for_runtime_owner(scope, target.owner);
- let proceed = window_navigation_for_holder(scope, target.owner).is_none_or(|navigation| {
- let outcome = dispatch_navigation_traverse_event_with_outcome(
- scope,
- navigation,
- target.history,
- target.target_index,
- info,
- );
- if !navigation_document_is_active(scope, target.owner) {
- mark_navigation_outcome_default_prevented(scope, &outcome);
- return false;
- }
- outcome.proceed
- });
- if proceed {
- dispatch_pagehide_for_runtime_owner(scope, target.owner);
- dispatch_unload_for_runtime_owner(scope, target.owner);
- }
- proceed
-}
-
-pub(in crate::context_bootstrap) fn apply_pending_child_cross_document_traversal(
- scope: &mut v8::PinScope<'_, '_>,
- host: &mut JsContextHost,
- traversal: PendingChildCrossDocumentTraversal,
-) {
- let Some(owner) = host.child_browsing_context_window_wrapper(scope, traversal.child_handle)
- else {
- reject_child_cross_document_traversal(scope, &traversal);
- return;
- };
- let Some(history) = window_history_for_holder(scope, owner) else {
- reject_child_cross_document_traversal(scope, &traversal);
- return;
- };
- let target = TraversalTarget {
- owner,
- history,
- current_index: history_index(scope, history),
- target_index: traversal.target_index,
- joint_step: traversal.seed.session_history.target_step,
- };
- if !traversal_target_key_still_available(
- scope,
- history,
- traversal.target_index,
- traversal.target_key.as_deref(),
- ) {
- reject_child_cross_document_traversal(scope, &traversal);
- return;
- }
- let info = traversal
- .info
- .as_ref()
- .map(|info| v8::Local::new(scope, info));
- if let Some(step) = traversal.seed.session_history.target_step {
- let Some(plan) =
- super::navigation_traversal_plan::JointTraversalPlan::resolve(scope, owner, step)
- else {
- reject_child_cross_document_traversal(scope, &traversal);
- return;
- };
- super::navigation_joint_traversal::execute(scope, plan, info, &traversal.results);
- return;
- }
- if !dispatch_child_cross_document_traverse_event(scope, &target, info) {
- reject_child_cross_document_traversal(scope, &traversal);
- return;
- }
- let _ = host.mark_current_child_document_unload_dispatched_after_navigation_traversal(
- traversal.child_handle,
- );
- queue_child_cross_document_traversal(
- host,
- traversal.child_handle,
- &traversal.target_url,
- traversal.seed,
- );
-}
-
pub(crate) fn apply_authorized_history_traversal_task(
scope: &mut v8::PinScope<'_, '_>,
host: &mut JsContextHost,
@@ -376,22 +238,22 @@ pub(crate) fn apply_authorized_history_traversal_task(
super::history_runtime::apply_pending_history_traversal(scope, host, traversal);
}
PendingHistoryTraversalAction::ChildCrossDocument(traversal) => {
- apply_pending_child_cross_document_traversal(scope, host, *traversal);
+ super::history_runtime::apply_pending_history_traversal(
+ scope,
+ host,
+ crate::native_bridge::PendingHistoryTraversal {
+ joint_step: traversal.seed.session_history.target_step,
+ target: traversal.target,
+ target_index: traversal.target_index,
+ target_key: traversal.target_key,
+ info: traversal.info,
+ results: traversal.results,
+ },
+ );
}
}
}
-fn reject_child_cross_document_traversal(
- scope: &mut v8::PinScope<'_, '_>,
- traversal: &PendingChildCrossDocumentTraversal,
-) {
- if traversal.results.is_empty() {
- return;
- }
- let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError");
- reject_pending_navigation_results(scope, &traversal.results, error);
-}
-
fn child_browsing_context_handle_for_traversal<'s>(
scope: &mut v8::PinScope<'s, '_>,
owner: v8::Local<'s, v8::Object>,
@@ -402,16 +264,3 @@ fn child_browsing_context_handle_for_traversal<'s>(
child_browsing_context_handle_for_runtime_owner(scope, owner)
}
}
-
-fn queue_child_cross_document_traversal(
- host: &mut JsContextHost,
- child_handle: DomHandle,
- target_url: &str,
- seed: NavigationHistoryEntrySeed,
-) {
- host.queue_deferred_child_browsing_context_navigation_from_entry_seed(
- child_handle,
- target_url,
- seed,
- );
-}
diff --git a/moli-renderer-v8/src/context_bootstrap/session_history.rs b/moli-renderer-v8/src/context_bootstrap/session_history.rs
index d01b570d7..b080fc578 100644
--- a/moli-renderer-v8/src/context_bootstrap/session_history.rs
+++ b/moli-renderer-v8/src/context_bootstrap/session_history.rs
@@ -419,34 +419,6 @@ pub(super) fn plan_traversal<'s>(
.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>,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs
index a45b476d3..c19977b42 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_runtime/isolated_world.rs
@@ -133,7 +133,12 @@ impl JsContextHost {
self.request_child_frame_realm_materialization(handle);
return Ok(context);
}
- if let Some(stale) = pending_contexts.borrow_mut().remove(&handle) {
+ let stale = pending_contexts.borrow_mut().remove(&handle);
+ if let Some(stale) = stale {
+ crate::context_bootstrap::cancel_history_traversals_for_retiring_window(
+ scope,
+ super::super::WindowExecutionContextOwner::Frame(stale.local_window_id),
+ );
self.retire_window_execution_contexts_for_context_token(
stale.runtime_observable_context_token,
);
diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs
index 4eeeabf7b..4fad6cea8 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs
@@ -196,6 +196,7 @@ impl JsContextHost {
super::visual_resource_generation::VisualResourceGeneration::default();
let mut host = Self {
session_histories: Default::default(),
+ pending_history_traversal_admissions: Default::default(),
runtime: runtime as *mut DocumentRuntime,
layout_policy: moli_page_types::LayoutPolicy::default(),
document_layout_state: RefCell::new(super::layout_state::DocumentLayoutState::default()),
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 66ce9e635..67268a09b 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
@@ -800,6 +800,8 @@ pub(crate) type JsContextHostPageTaskCapabilities =
pub(crate) struct JsContextHost {
pub(crate) session_histories: session_history::RendererSessionHistories,
+ pub(crate) pending_history_traversal_admissions:
+ super::history_traversal::PendingHistoryTraversalAdmissions,
runtime: *mut DocumentRuntime,
layout_policy: moli_page_types::LayoutPolicy,
document_layout_state: RefCell<layout_state::DocumentLayoutState>,
@@ -1244,6 +1246,7 @@ impl JsContextHost {
return;
}
self.page_context_resources_closed = true;
+ self.pending_history_traversal_admissions.clear();
self.retire_all_document_resource_loaders();
self.page_default_context = None;
self.v8_finalizers.clear_for_context_teardown();
diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
index cbb2614ce..729374e5a 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
@@ -1905,7 +1905,7 @@ impl JsContextHost {
);
}
if let Some(retired_local_window_id) = transition.retired_local_window_id {
- self.retire_lightweight_popup_local_window(popup_id, retired_local_window_id);
+ self.retire_lightweight_popup_local_window(scope, popup_id, retired_local_window_id);
}
self.refresh_lightweight_popup_indexed_db_factory(scope, popup_id, window);
tracing::debug!(
@@ -1929,6 +1929,7 @@ impl JsContextHost {
fn retire_lightweight_popup_local_window(
&mut self,
+ scope: &mut v8::PinScope<'_, '_>,
popup_id: u64,
local_window_id: LightweightPopupLocalWindowId,
) {
@@ -1936,6 +1937,10 @@ impl JsContextHost {
popup_id,
local_window_id,
};
+ crate::context_bootstrap::cancel_history_traversals_for_retiring_window(
+ scope,
+ execution_context_owner,
+ );
let retired_timer_count = unsafe { &mut *self.runtime }
.cancel_window_execution_context_timers(execution_context_owner);
let retired_webcrypto_count =
@@ -4316,7 +4321,7 @@ fn lightweight_popup_close_callback<'s>(
host.clear_custom_element_registry_associations_for_document(document_handle);
}
host.retire_lightweight_popup_document_owner(transition.retired_owner);
- host.retire_lightweight_popup_local_window(popup_id, transition.retired_local_window_id);
+ host.retire_lightweight_popup_local_window(scope, popup_id, transition.retired_local_window_id);
host.lightweight_popup_window_names
.retain(|_, named_popup_id| *named_popup_id != popup_id);
}
diff --git a/moli-renderer-v8/src/native_bridge/history_queue.rs b/moli-renderer-v8/src/native_bridge/history_queue.rs
index 7a2f3691c..c7935b869 100644
--- a/moli-renderer-v8/src/native_bridge/history_queue.rs
+++ b/moli-renderer-v8/src/native_bridge/history_queue.rs
@@ -1,5 +1,5 @@
use super::{
- DomHandle, JsContextHost, NavigationHistoryEntrySeed, WindowExecutionContextBinding,
+ JsContextHost, NavigationHistoryEntrySeed, WindowExecutionContextBinding,
WindowExecutionContextIdentity, WindowTaskTarget,
};
use crate::page_task_queue::{
@@ -64,10 +64,8 @@ pub(crate) struct PendingHistoryTraversal {
pub(crate) struct PendingChildCrossDocumentTraversal {
pub(crate) target: WindowTaskTarget,
- pub(crate) child_handle: DomHandle,
pub(crate) target_index: u32,
pub(crate) target_key: Option<String>,
- pub(crate) target_url: String,
pub(crate) seed: NavigationHistoryEntrySeed,
pub(crate) info: Option<v8::Global<v8::Value>>,
pub(crate) results: Vec<PendingNavigationResult>,
@@ -602,10 +600,8 @@ impl JsContextHost {
&mut self,
scope: &mut v8::PinScope<'s, '_>,
target: WindowTaskTarget,
- child_handle: DomHandle,
target_index: u32,
target_key: Option<String>,
- target_url: &str,
seed: NavigationHistoryEntrySeed,
) -> Option<RendererPageHistoryTraversalProducer> {
let execution_context = self.current_runtime_window_execution_context_identity(scope)?;
@@ -616,10 +612,8 @@ impl JsContextHost {
relevant_context,
PendingChildCrossDocumentTraversal {
target,
- child_handle,
target_index,
target_key,
- target_url: target_url.to_owned(),
seed,
info: None,
results: Vec::new(),
@@ -638,10 +632,8 @@ impl JsContextHost {
&mut self,
scope: &mut v8::PinScope<'s, '_>,
target: WindowTaskTarget,
- child_handle: DomHandle,
target_index: u32,
target_key: Option<String>,
- target_url: &str,
seed: NavigationHistoryEntrySeed,
info: Option<v8::Local<'s, v8::Value>>,
) -> Option<(
@@ -662,10 +654,8 @@ impl JsContextHost {
relevant_context,
PendingChildCrossDocumentTraversal {
target,
- child_handle,
target_index,
target_key,
- target_url: target_url.to_owned(),
seed,
info: info.map(|info| v8::Global::new(scope, info)),
results: vec![PendingNavigationResult {
diff --git a/moli-renderer-v8/src/native_bridge/history_traversal.rs b/moli-renderer-v8/src/native_bridge/history_traversal.rs
new file mode 100644
index 000000000..2560c7f73
--- /dev/null
+++ b/moli-renderer-v8/src/native_bridge/history_traversal.rs
@@ -0,0 +1,145 @@
+//! Rust-owned admission state. Promise callbacks retain only a transaction ID.
+
+use super::{PendingNavigationResult, WindowExecutionContextOwner};
+use moli_session_history::{SessionHistoryEntry, SessionHistoryTraversalPlan};
+use std::cell::Cell;
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::sync::atomic::{AtomicU64, Ordering};
+
+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
+pub(crate) struct HistoryTraversalId(u64);
+
+impl HistoryTraversalId {
+ pub(crate) fn allocate() -> Self {
+ static NEXT_ID: AtomicU64 = AtomicU64::new(1);
+ Self(
+ NEXT_ID
+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
+ .expect("history traversal ID overflow"),
+ )
+ }
+
+ pub(crate) fn raw(self) -> u64 {
+ self.0
+ }
+
+ pub(crate) fn from_raw(raw: u64) -> Self {
+ Self(raw)
+ }
+}
+
+#[derive(Default)]
+pub(crate) struct TraversalParticipantOutcome {
+ pub(crate) intercepted: bool,
+ pub(crate) signal: Option<v8::Global<v8::Object>>,
+ pub(crate) event: Option<v8::Global<v8::Object>>,
+ pub(crate) intercept_result: Option<v8::Global<v8::Value>>,
+ pub(crate) intercept_error: Option<v8::Global<v8::Value>>,
+}
+
+pub(crate) struct HistoryTraversalParticipant {
+ pub(crate) execution_owner: WindowExecutionContextOwner,
+ pub(crate) history: v8::Global<v8::Object>,
+ pub(crate) navigation: Option<v8::Global<v8::Object>>,
+ pub(crate) source: SessionHistoryEntry,
+ pub(crate) destination: SessionHistoryEntry,
+ pub(crate) outcome: TraversalParticipantOutcome,
+}
+
+pub(crate) struct PendingHistoryTraversalAdmission {
+ pub(crate) id: HistoryTraversalId,
+ pub(crate) active: Cell<bool>,
+ pub(crate) plan: SessionHistoryTraversalPlan,
+ pub(crate) initiator: v8::Global<v8::Object>,
+ pub(crate) execution_owner: WindowExecutionContextOwner,
+ pub(crate) participants: Vec<HistoryTraversalParticipant>,
+ pub(crate) results: Vec<PendingNavigationResult>,
+ pub(crate) remaining_precommit: Cell<usize>,
+}
+
+/// Pending admissions remain discoverable through unload script until acceptance.
+/// Callbacks clone an Rc before invoking script, never retaining a table borrow.
+#[derive(Default)]
+pub(crate) struct PendingHistoryTraversalAdmissions {
+ entries: HashMap<HistoryTraversalId, Rc<PendingHistoryTraversalAdmission>>,
+}
+
+impl PendingHistoryTraversalAdmissions {
+ pub(crate) fn is_empty(&self) -> bool {
+ self.entries.is_empty()
+ }
+
+ pub(crate) fn insert(
+ &mut self,
+ admission: PendingHistoryTraversalAdmission,
+ ) -> HistoryTraversalId {
+ let id = admission.id;
+ self.entries.insert(id, Rc::new(admission));
+ id
+ }
+
+ pub(crate) fn take(
+ &mut self,
+ id: HistoryTraversalId,
+ ) -> Option<Rc<PendingHistoryTraversalAdmission>> {
+ self.entries.remove(&id)
+ }
+
+ pub(crate) fn fulfill_precommit(
+ &mut self,
+ id: HistoryTraversalId,
+ ) -> Option<Rc<PendingHistoryTraversalAdmission>> {
+ let admission = self.entries.get(&id)?;
+ let remaining = admission.remaining_precommit.get().checked_sub(1)?;
+ admission.remaining_precommit.set(remaining);
+ (remaining == 0).then(|| Rc::clone(admission))
+ }
+
+ pub(crate) fn take_for_navigation(
+ &mut self,
+ scope: &mut v8::PinScope<'_, '_>,
+ navigation: v8::Local<'_, v8::Object>,
+ ) -> Option<Rc<PendingHistoryTraversalAdmission>> {
+ let id = self.entries.iter().find_map(|(id, admission)| {
+ admission
+ .participants
+ .iter()
+ .any(|participant| {
+ participant.navigation.as_ref().is_some_and(|candidate| {
+ v8::Local::new(scope, candidate).strict_equals(navigation.into())
+ })
+ })
+ .then_some(*id)
+ })?;
+ self.entries.remove(&id)
+ }
+
+ pub(crate) fn take_for_owner(
+ &mut self,
+ owner: WindowExecutionContextOwner,
+ ) -> Vec<Rc<PendingHistoryTraversalAdmission>> {
+ self.entries
+ .extract_if(|_, admission| {
+ admission.execution_owner == owner
+ || admission
+ .participants
+ .iter()
+ .any(|participant| participant.execution_owner == owner)
+ })
+ .map(|(_, admission)| admission)
+ .collect()
+ }
+
+ pub(crate) fn clear(&mut self) {
+ for admission in self.entries.values() {
+ admission.active.set(false);
+ }
+ self.entries.clear();
+ }
+
+ #[cfg(test)]
+ pub(crate) fn len(&self) -> usize {
+ self.entries.len()
+ }
+}
diff --git a/moli-renderer-v8/src/native_bridge/mod.rs b/moli-renderer-v8/src/native_bridge/mod.rs
index 5f9cdf755..e554107bc 100644
--- a/moli-renderer-v8/src/native_bridge/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/mod.rs
@@ -17,6 +17,7 @@ pub(crate) mod document;
pub(crate) mod element;
mod helpers;
mod history_queue;
+pub(crate) mod history_traversal;
pub(super) mod identity;
pub(crate) mod named_access;
mod node;
@@ -31,9 +32,8 @@ use super::{
use bindings::NativeBridgeBindings;
pub(crate) use history_queue::{
- NavigationAttemptId, PendingChildCrossDocumentTraversal, PendingHistoryTraversal,
- PendingHistoryTraversalAction, PendingNavigationApiTaskAction, PendingNavigationFinishedResult,
- PendingNavigationResult,
+ NavigationAttemptId, PendingHistoryTraversal, PendingHistoryTraversalAction,
+ PendingNavigationApiTaskAction, PendingNavigationFinishedResult, PendingNavigationResult,
};
use identity::{BridgeHandle, BridgeIdentityStore, DomTokenListKind, ReflectorId};
use identity::{CollectionKind, LiveCollectionDescriptor, LiveCollectionQueryKind};
diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs
index 835716ca3..001c28b4e 100644
--- a/moli-renderer-v8/src/script_vm.rs
+++ b/moli-renderer-v8/src/script_vm.rs
@@ -3576,6 +3576,11 @@ impl ScriptVm {
Some(context)
}
Some(context) => {
+ self.cancel_history_traversals_for_retiring_window(
+ crate::native_bridge::WindowExecutionContextOwner::Frame(
+ context.local_window_id,
+ ),
+ );
self._context_host
.borrow_mut()
.retire_window_execution_contexts_for_context_token(
@@ -3711,6 +3716,13 @@ impl ScriptVm {
.collect::<Vec<_>>()
};
if !stale_prebootstrapped_contexts.is_empty() {
+ for context in &stale_prebootstrapped_contexts {
+ self.cancel_history_traversals_for_retiring_window(
+ crate::native_bridge::WindowExecutionContextOwner::Frame(
+ context.local_window_id,
+ ),
+ );
+ }
{
let mut host = self._context_host.borrow_mut();
for context in &stale_prebootstrapped_contexts {
@@ -3759,6 +3771,9 @@ impl ScriptVm {
let Some(context) = self.child_frame_realm_store.remove(&execution_context_id) else {
return;
};
+ self.cancel_history_traversals_for_retiring_window(
+ crate::native_bridge::WindowExecutionContextOwner::Frame(context.local_window_id),
+ );
let retired_timer_count = self
.document_runtime
.cancel_timers_for_context_token(context.runtime_observable_context_token);
diff --git a/moli-renderer-v8/src/script_vm/child_document_modulator.rs b/moli-renderer-v8/src/script_vm/child_document_modulator.rs
index fadf98e08..66fc25d22 100644
--- a/moli-renderer-v8/src/script_vm/child_document_modulator.rs
+++ b/moli-renderer-v8/src/script_vm/child_document_modulator.rs
@@ -77,6 +77,9 @@ impl ScriptVm {
.is_none_or(|local_window_id| local_window_id == retired_owner.local_window_id),
"committed LocalWindow retirement must identify the retired document owner"
);
+ if execution_context_retired {
+ self.cancel_history_traversals_for_retiring_window(execution_context_owner);
+ }
if execution_context_retired
&& let Some(execution_context_id) = self
.child_frame_realm_store
diff --git a/moli-renderer-v8/src/script_vm/context_scope.rs b/moli-renderer-v8/src/script_vm/context_scope.rs
index 6fcd6b6e8..8c49fa1b5 100644
--- a/moli-renderer-v8/src/script_vm/context_scope.rs
+++ b/moli-renderer-v8/src/script_vm/context_scope.rs
@@ -8,6 +8,24 @@ use super::perform_microtask_checkpoint_and_report_pending_promise_rejections;
use crate::{frame_owner_model::FrameRealmId, native_bridge::JsContextHost};
impl ScriptVm {
+ pub(super) fn cancel_history_traversals_for_retiring_window(
+ &mut self,
+ owner: crate::native_bridge::WindowExecutionContextOwner,
+ ) {
+ if self
+ ._context_host
+ .borrow()
+ .pending_history_traversal_admissions
+ .is_empty()
+ {
+ return;
+ }
+ let _ = self.with_default_context_scope(|scope, _| {
+ crate::context_bootstrap::cancel_history_traversals_for_retiring_window(scope, owner);
+ Ok(())
+ });
+ }
+
pub(crate) fn start_scanned_image_preload(
&mut self,
request_url: url::Url,
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.rs
index 6fc4fcbf6..96cf2bcee 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
@@ -46,6 +46,7 @@ mod storage_access;
mod structured_clone;
mod transferable_streams;
mod traversal;
+mod traversal_coordinator;
mod trusted_types;
mod web_audio;
mod webrtc;
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/traversal_coordinator.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/traversal_coordinator.rs
new file mode 100644
index 000000000..25361159b
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/traversal_coordinator.rs
@@ -0,0 +1,151 @@
+use super::*;
+
+#[tokio::test]
+async fn history_traversal_canceled_precommit_callback_cannot_complete_successor() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ let mut vm =
+ new_storage_page_task_executor_test_vm_with_loader("https://example.com/base", &loader);
+ vm.eval(r#"
+ history.replaceState(0, ''); history.pushState(1, '');
+ globalThis.gates = []; globalThis.log = [];
+ navigation.onnavigate = event => {
+ if (event.navigationType === 'traverse') {
+ event.intercept({precommitHandler: () => new Promise(resolve => gates.push(resolve))});
+ }
+ };
+ const first = navigation.back();
+ first.committed.catch(error => log.push('oldCommitted:' + error.name));
+ first.finished.catch(error => log.push('oldFinished:' + error.name));
+ "#).unwrap();
+ assert!(
+ vm.run_one_history_traversal_executor_turn(&loader)
+ .await
+ .unwrap()
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .pending_history_traversal_admissions
+ .len(),
+ 1
+ );
+ vm.eval(
+ r#"
+ stop();
+ const second = navigation.back();
+ second.committed.then(() => log.push('newCommitted'));
+ second.finished.then(() => log.push('newFinished'));
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .pending_history_traversal_admissions
+ .len(),
+ 0
+ );
+ assert!(
+ vm.run_one_history_traversal_executor_turn(&loader)
+ .await
+ .unwrap()
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .pending_history_traversal_admissions
+ .len(),
+ 1
+ );
+ vm.eval("gates[0]();").unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify([history.state, log])").unwrap(),
+ r#"[1,["oldCommitted:AbortError","oldFinished:AbortError"]]"#
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .pending_history_traversal_admissions
+ .len(),
+ 1
+ );
+ vm.eval("gates[1]();").unwrap();
+ assert_eq!(
+ vm.eval("JSON.stringify([history.state, log])").unwrap(),
+ r#"[0,["oldCommitted:AbortError","oldFinished:AbortError","newCommitted","newFinished"]]"#
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .pending_history_traversal_admissions
+ .len(),
+ 0
+ );
+}
+
+#[tokio::test]
+async fn history_traversal_detach_releases_pending_admission_and_ignores_late_callback() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ let mut vm =
+ new_storage_page_task_executor_test_vm_with_loader("https://example.com/base", &loader);
+ vm.eval(
+ r#"
+ globalThis.frame = document.createElement('iframe');
+ (document.body || document.documentElement || document).appendChild(frame);
+ globalThis.child = frame.contentWindow;
+ "#,
+ )
+ .unwrap();
+ assert_eq!(vm.eval("child.document.readyState").unwrap(), "complete");
+ vm.eval(
+ r#"
+ globalThis.log = [];
+ child.history.replaceState(0, ''); history.replaceState(0, '');
+ history.pushState(1, ''); child.history.pushState(1, '');
+ navigation.onnavigate = event => event.intercept({
+ precommitHandler: () => new Promise(resolve => globalThis.release = resolve)
+ });
+ const result = navigation.back();
+ result.committed.catch(error => log.push('committed:' + error.name));
+ result.finished.catch(error => log.push('finished:' + error.name));
+ "#,
+ )
+ .unwrap();
+ assert!(
+ vm.run_one_history_traversal_executor_turn(&loader)
+ .await
+ .unwrap()
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .pending_history_traversal_admissions
+ .len(),
+ 1
+ );
+ vm.eval("frame.remove();").unwrap();
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .pending_history_traversal_admissions
+ .len(),
+ 0
+ );
+ assert_eq!(
+ vm.eval("JSON.stringify(log)").unwrap(),
+ r#"["committed:AbortError","finished:AbortError"]"#
+ );
+ vm.eval("release();").unwrap();
+ assert_eq!(vm.eval("history.state").unwrap(), "1");
+ assert_eq!(
+ vm.eval("JSON.stringify(log)").unwrap(),
+ r#"["committed:AbortError","finished:AbortError"]"#
+ );
+ assert_eq!(
+ vm._context_host
+ .borrow()
+ .pending_history_traversal_admissions
+ .len(),
+ 0
+ );
+}
diff --git a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs
index ce8680f27..855816146 100644
--- a/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs
+++ b/moli-renderer-v8/src/webidl_callback_source_boundary_tests.rs
@@ -85,7 +85,9 @@ const DIRECT_V8_CALL_ALLOWLIST: &[AllowedDirectCallFile] = &[
),
allowed(
"context_bootstrap/history_runtime/traversal.rs",
- 2,
+ // Post-commit settlement invokes the intercepted result's then method.
+ // Precommit adoption now uses PromiseResolver in the shared coordinator.
+ 1,
DirectCallOwner::BrowserAlgorithm,
),
allowed(