Skip to content

armgit / moli

Public Imported from GitHub
0

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

refactor(cdp): separate emulation session and target state

ldm09ccd9d0cc687
diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rs
index 1dd957da5..398f3d304 100644
--- a/moli-protocol/src/conn.rs
+++ b/moli-protocol/src/conn.rs
@@ -76,7 +76,7 @@ pub(crate) use bidi_channel_work::{
pub(crate) use body_spool::{CapturedBody, CapturedBodyWriter};
pub(crate) use browser_context::{
PageLifecycleEventsEnableResult, SessionOwnerInspectorEnableResult,
- SessionOwnerRuntimeFrontendEnableResult, TargetEmulationSessionStateMut,
+ SessionOwnerRuntimeFrontendEnableResult, TargetEmulationStateUpdate,
TargetNavigationLoadInputs,
};
pub(crate) use command_owner_scope::CommandOwnerScope;
@@ -557,14 +557,16 @@ pub(crate) use state::{
CommittedRendererDocumentBinding, CompletedDownloadBody, CompletedDownloadBodyArtifact,
DedicatedWorkerMainScriptOutcome, DedicatedWorkerMainScriptSnapshot,
DedicatedWorkerTargetState, DevToolsBrowserIdentityOverride, DevToolsConsoleOutputSessionState,
- DevToolsLogViolationThreshold, DocumentNavigationToken, DuplicatePendingRendererCommand,
- EmulatedNetworkConditions, EmulatedViewportSurface, InspectorCommandDispatch,
- NETWORK_ERROR_PAGE_URL, NavigationEngineHandoff, NavigationResultProjection,
- NavigationSourceDocumentSecurityContext, NetworkErrorPageNavigation, PageScreencastConfig,
- PageScreencastFormat, PendingBidiChannelListener, PendingInspectorAwait,
- PendingRendererCommandKey, PerformanceTimeDomain, PreparedRendererCallDispatch, ProfilerAction,
- ProfilerInspectorCommand, RendererCommandCorrelation, RendererCommandDescriptor,
- RendererCommandReplay, RendererDocumentLifecycleObservation, RendererDocumentLifecycleObserver,
+ DevToolsEmulationSessionState, DevToolsLogViolationThreshold, DocumentNavigationToken,
+ DuplicatePendingRendererCommand, EffectiveTargetEmulationState,
+ EffectiveTargetEmulationStateDelta, EmulatedNetworkConditions, EmulatedViewportSurface,
+ InspectorCommandDispatch, NETWORK_ERROR_PAGE_URL, NavigationEngineHandoff,
+ NavigationResultProjection, NavigationSourceDocumentSecurityContext,
+ NetworkErrorPageNavigation, PageScreencastConfig, PageScreencastFormat,
+ PendingBidiChannelListener, PendingInspectorAwait, PendingRendererCommandKey,
+ PerformanceTimeDomain, PreparedRendererCallDispatch, ProfilerAction, ProfilerInspectorCommand,
+ RendererCommandCorrelation, RendererCommandDescriptor, RendererCommandReplay,
+ RendererDocumentLifecycleObservation, RendererDocumentLifecycleObserver,
RendererMainDocumentCommitSeed, RendererPageResidenceIdentity,
ServiceWorkerRuntimeExceptionSnapshot, ServiceWorkerTargetState, SharedWorkerTargetState,
SiteDataClearOptions, TargetIdentityState, TargetInitialEmptyDocumentCreator, TargetOwnerState,
diff --git a/moli-protocol/src/conn/browser_context/emulation_owner.rs b/moli-protocol/src/conn/browser_context/emulation_owner.rs
index 52fdd8217..24e138fa2 100644
--- a/moli-protocol/src/conn/browser_context/emulation_owner.rs
+++ b/moli-protocol/src/conn/browser_context/emulation_owner.rs
@@ -1,42 +1,87 @@
use super::target_session_owner::{TargetSessionOwnerMut, TargetSessionOwnerRef};
use super::*;
use crate::conn::{
- EmulatedDeviceMetrics, EmulatedGeolocationOverrideState, EmulatedMediaOverrides,
- EmulatedNetworkConditions,
+ DevToolsEmulationSessionState, EffectiveTargetEmulationState,
+ EffectiveTargetEmulationStateDelta, EmulatedDeviceMetrics, EmulatedGeolocationOverrideState,
+ EmulatedMediaOverrides, EmulatedNetworkConditions,
};
-pub(crate) struct TargetEmulationSessionStateMut<'a> {
- pub(crate) network_conditions: &'a mut Option<EmulatedNetworkConditions>,
- pub(crate) geolocation_override: &'a mut Option<EmulatedGeolocationOverrideState>,
- pub(crate) emulated_media: &'a mut EmulatedMediaOverrides,
- pub(crate) emulated_device_metrics: &'a mut Option<EmulatedDeviceMetrics>,
- pub(crate) cpu_throttling_rate: &'a mut f64,
- pub(crate) touch_emulation_enabled: &'a mut bool,
- pub(crate) emit_touch_events_for_mouse: &'a mut bool,
- pub(crate) focus_emulation_enabled: &'a mut bool,
- pub(crate) script_execution_disabled: &'a mut bool,
+pub(crate) struct TargetEmulationStateUpdate<'a> {
+ raw: &'a mut DevToolsEmulationSessionState,
+ effective: &'a mut EffectiveTargetEmulationState,
+}
+
+impl TargetEmulationStateUpdate<'_> {
+ pub(crate) fn set_network_conditions(
+ &mut self,
+ network_conditions: Option<EmulatedNetworkConditions>,
+ ) {
+ self.raw.network_conditions = network_conditions;
+ self.effective.network_conditions = network_conditions;
+ }
+
+ pub(crate) fn set_geolocation_override(
+ &mut self,
+ geolocation_override: Option<EmulatedGeolocationOverrideState>,
+ ) {
+ self.raw.geolocation_override = geolocation_override.clone();
+ self.effective.geolocation_override = geolocation_override;
+ }
+
+ pub(crate) fn set_emulated_media(&mut self, emulated_media: EmulatedMediaOverrides) {
+ self.raw.emulated_media = emulated_media.clone();
+ self.effective.emulated_media = emulated_media;
+ }
+
+ pub(crate) fn set_emulated_device_metrics(
+ &mut self,
+ emulated_device_metrics: Option<EmulatedDeviceMetrics>,
+ ) {
+ self.raw.emulated_device_metrics = emulated_device_metrics.clone();
+ self.effective.emulated_device_metrics = emulated_device_metrics;
+ }
+
+ pub(crate) fn set_cpu_throttling_rate(&mut self, cpu_throttling_rate: f64) {
+ self.raw.cpu_throttling_rate = cpu_throttling_rate;
+ self.effective.cpu_throttling_rate = cpu_throttling_rate;
+ }
+
+ pub(crate) fn set_touch_emulation_enabled(&mut self, enabled: bool) {
+ self.raw.touch_emulation_enabled = enabled;
+ self.effective.touch_emulation_enabled = enabled;
+ }
+
+ pub(crate) fn set_emit_touch_events_for_mouse(&mut self, enabled: bool) {
+ self.raw.emit_touch_events_for_mouse = enabled;
+ self.effective.emit_touch_events_for_mouse = enabled;
+ }
+
+ pub(crate) fn set_focus_emulation_enabled(&mut self, enabled: bool) {
+ self.raw.focus_emulation_enabled = enabled;
+ self.effective.focus_emulation_enabled = enabled;
+ }
+
+ pub(crate) fn set_script_execution_disabled(&mut self, disabled: bool) {
+ self.raw.script_execution_disabled = disabled;
+ self.effective.script_execution_disabled = disabled;
+ }
}
impl TargetSessionOwnerMut<'_> {
- fn mutate_emulation_session_state(
+ fn update_emulation_state(
self,
- f: impl FnOnce(Option<TargetEmulationSessionStateMut<'_>>),
+ f: impl FnOnce(Option<TargetEmulationStateUpdate<'_>>),
) -> bool {
let Some(state) = self.browser_context.page_target_mut(&self.target_id) else {
f(None);
return false;
};
- f(Some(TargetEmulationSessionStateMut {
- network_conditions: &mut state.network_conditions,
- geolocation_override: &mut state.geolocation_override,
- emulated_media: &mut state.emulated_media,
- emulated_device_metrics: &mut state.emulated_device_metrics,
- cpu_throttling_rate: &mut state.cpu_throttling_rate,
- touch_emulation_enabled: &mut state.touch_emulation_enabled,
- emit_touch_events_for_mouse: &mut state.emit_touch_events_for_mouse,
- focus_emulation_enabled: &mut state.focus_emulation_enabled,
- script_execution_disabled: &mut state.script_execution_disabled,
- }));
+ let raw = &mut state
+ .devtools_sessions
+ .ensure_session(&self.session_key)
+ .emulation_session_state;
+ let effective = &mut state.effective_emulation_state;
+ f(Some(TargetEmulationStateUpdate { raw, effective }));
true
}
@@ -84,29 +129,36 @@ impl TargetSessionOwnerRef<'_> {
fn emit_touch_events_for_mouse(&self) -> Option<bool> {
self.browser_context
.page_target(&self.target_id)
- .map(|state| state.emit_touch_events_for_mouse)
+ .map(|state| state.effective_emulation_state.emit_touch_events_for_mouse)
+ }
+
+ #[cfg(test)]
+ fn emulation_session_state(&self) -> Option<&DevToolsEmulationSessionState> {
+ self.browser_context
+ .page_target(&self.target_id)?
+ .devtools_sessions
+ .session(&self.session_key)
+ .map(|session| &session.emulation_session_state)
}
}
impl CdpConnection {
- pub(crate) fn mutate_emulation_session_state_for_session_owner(
+ pub(crate) fn update_emulation_state_for_session_owner(
&mut self,
session_id: Option<&str>,
- f: impl FnOnce(Option<TargetEmulationSessionStateMut<'_>>),
+ f: impl FnOnce(Option<TargetEmulationStateUpdate<'_>>),
) -> bool {
let owner = crate::conn::CommandOwnerScope::capture(self, session_id);
- self.mutate_emulation_session_state_for_owner(&owner, f)
+ self.update_emulation_state_for_owner(&owner, f)
}
- pub(crate) fn mutate_emulation_session_state_for_owner(
+ pub(crate) fn update_emulation_state_for_owner(
&mut self,
owner: &crate::conn::CommandOwnerScope,
- f: impl FnOnce(Option<TargetEmulationSessionStateMut<'_>>),
+ f: impl FnOnce(Option<TargetEmulationStateUpdate<'_>>),
) -> bool {
- self.with_target_session_owner_mut_for_owner(owner, |owner| {
- owner.mutate_emulation_session_state(f)
- })
- .unwrap_or(false)
+ self.with_target_session_owner_mut_for_owner(owner, |owner| owner.update_emulation_state(f))
+ .unwrap_or(false)
}
pub(crate) fn set_devtools_locale_override_for_session_owner(
@@ -158,11 +210,40 @@ impl CdpConnection {
.and_then(|owner| owner.emit_touch_events_for_mouse())
.unwrap_or(false)
}
+
+ #[cfg(test)]
+ pub(crate) fn emulation_session_state_for_session_owner(
+ &self,
+ session_id: Option<&str>,
+ ) -> Option<DevToolsEmulationSessionState> {
+ self.target_session_owner_ref(session_id)?
+ .emulation_session_state()
+ .cloned()
+ }
+
+ pub(crate) fn disable_emulation_session_handler_for_session_owner(
+ &mut self,
+ session_id: &str,
+ ) -> Option<EffectiveTargetEmulationStateDelta> {
+ let mut owner = self.target_session_owner_mut(Some(session_id))?;
+ Some(owner.mutate_page_state(|target, session_key| {
+ let raw = std::mem::take(
+ &mut target
+ .devtools_sessions
+ .ensure_session(session_key)
+ .emulation_session_state,
+ );
+ target
+ .effective_emulation_state
+ .disable_session_handler(&raw)
+ }))
+ }
}
impl BrowserContext {
pub(crate) fn effective_active_emulated_device_metrics(&self) -> Option<EmulatedDeviceMetrics> {
self.active_page_target()
+ .effective_emulation_state
.emulated_device_metrics
.clone()
.or_else(|| self.default_emulated_device_metrics.clone())
diff --git a/moli-protocol/src/conn/browser_context/mod.rs b/moli-protocol/src/conn/browser_context/mod.rs
index ab16516f7..66bf89327 100644
--- a/moli-protocol/src/conn/browser_context/mod.rs
+++ b/moli-protocol/src/conn/browser_context/mod.rs
@@ -13,7 +13,7 @@ mod runtime_owner;
mod session_owner;
mod target_session_owner;
-pub(crate) use emulation_owner::TargetEmulationSessionStateMut;
+pub(crate) use emulation_owner::TargetEmulationStateUpdate;
pub(crate) use page_owner::PageLifecycleEventsEnableResult;
pub(crate) use runtime_owner::{
SessionOwnerInspectorEnableResult, SessionOwnerRuntimeFrontendEnableResult,
diff --git a/moli-protocol/src/conn/browser_context/target_session_owner.rs b/moli-protocol/src/conn/browser_context/target_session_owner.rs
index 59c4fddfc..b4c48ce44 100644
--- a/moli-protocol/src/conn/browser_context/target_session_owner.rs
+++ b/moli-protocol/src/conn/browser_context/target_session_owner.rs
@@ -265,10 +265,12 @@ impl TargetNavigationLoadInputs {
));
let effective_network_conditions = page_state
+ .effective_emulation_state
.network_conditions
.or(browser_context.default_network_conditions)
.or(browser_context.global_network_conditions);
let emulated_device_metrics = page_state
+ .effective_emulation_state
.emulated_device_metrics
.clone()
.or_else(|| browser_context.default_emulated_device_metrics.clone());
@@ -322,10 +324,12 @@ impl TargetNavigationLoadInputs {
.timezone_override()
.map(str::to_owned)
.or_else(|| browser_context.default_timezone_override.clone()),
- script_execution_disabled: page_state.script_execution_disabled,
+ script_execution_disabled: page_state
+ .effective_emulation_state
+ .script_execution_disabled,
bypass_content_security_policy: page_state.devtools_sessions.page_bypass_csp_enabled(),
- cpu_throttling_rate: page_state.cpu_throttling_rate,
- emulated_media: (&page_state.emulated_media).into(),
+ cpu_throttling_rate: page_state.effective_emulation_state.cpu_throttling_rate,
+ emulated_media: (&page_state.effective_emulation_state.emulated_media).into(),
viewport_surface: emulated_device_metrics
.as_ref()
.map(|metrics| metrics.viewport_surface().to_page_viewport_surface()),
@@ -590,6 +594,7 @@ impl<'a> TargetSessionOwnerRef<'a> {
pub(super) fn emulated_device_metrics(&self) -> Option<EmulatedDeviceMetrics> {
self.target()
+ .effective_emulation_state
.emulated_device_metrics
.clone()
.or_else(|| self.browser_context.default_emulated_device_metrics.clone())
@@ -3112,7 +3117,7 @@ mod tests {
state.http_proxy_override = Some("http://proxy.example:8080".to_owned());
state.http_no_proxy_override = Some("localhost,127.0.0.1".to_owned());
state.tls_verify_host_override = Some(false);
- state.script_execution_disabled = true;
+ state.effective_emulation_state.script_execution_disabled = true;
state
.network_policy
.set_user_agent_override("OwnerUA/1.0".to_owned());
@@ -3123,7 +3128,7 @@ mod tests {
state
.network_policy
.push_extra_header(("X-Owner".to_owned(), "background".to_owned()));
- state.emulated_media.media = Some("print".to_owned());
+ state.effective_emulation_state.emulated_media.media = Some("print".to_owned());
state.fetch_owner.configure(
Some("SID-background".to_owned()),
false,
diff --git a/moli-protocol/src/conn/page_state/page_targets.rs b/moli-protocol/src/conn/page_state/page_targets.rs
index 197dd81db..3e71277ea 100644
--- a/moli-protocol/src/conn/page_state/page_targets.rs
+++ b/moli-protocol/src/conn/page_state/page_targets.rs
@@ -372,7 +372,7 @@ impl BrowserContext {
return Ok(false);
};
let previous = target.effective_policy();
- target.clear_devtools_emulation_state(session_key);
+ target.clear_devtools_emulation_policy_state(session_key);
self.apply_effective_devtools_policy_delta_async(target_id, previous)
.await
}
diff --git a/moli-protocol/src/conn/page_state/surfaces.rs b/moli-protocol/src/conn/page_state/surfaces.rs
index 924adfca6..2dce1723c 100644
--- a/moli-protocol/src/conn/page_state/surfaces.rs
+++ b/moli-protocol/src/conn/page_state/surfaces.rs
@@ -25,8 +25,14 @@ impl SurfaceOverrideInputs {
network_conditions: browser_context.effective_active_network_conditions(),
geolocation_override: browser_context.effective_active_geolocation_override(),
emulated_device_metrics: browser_context.effective_active_emulated_device_metrics(),
- touch_emulation_enabled: browser_context.active_page_target().touch_emulation_enabled,
- focus_emulation_enabled: browser_context.active_page_target().focus_emulation_enabled,
+ touch_emulation_enabled: browser_context
+ .active_page_target()
+ .effective_emulation_state
+ .touch_emulation_enabled,
+ focus_emulation_enabled: browser_context
+ .active_page_target()
+ .effective_emulation_state
+ .focus_emulation_enabled,
active_target_surface: true,
window_document_hidden: browser_context
.active_page_target()
@@ -46,17 +52,22 @@ impl SurfaceOverrideInputs {
default_emulated_device_metrics: Option<EmulatedDeviceMetrics>,
) -> Self {
Self {
- network_conditions: state.network_conditions.or(default_network_conditions),
+ network_conditions: state
+ .effective_emulation_state
+ .network_conditions
+ .or(default_network_conditions),
geolocation_override: state
+ .effective_emulation_state
.geolocation_override
.clone()
.or(default_geolocation_override),
emulated_device_metrics: state
+ .effective_emulation_state
.emulated_device_metrics
.clone()
.or(default_emulated_device_metrics),
- touch_emulation_enabled: state.touch_emulation_enabled,
- focus_emulation_enabled: state.focus_emulation_enabled,
+ touch_emulation_enabled: state.effective_emulation_state.touch_emulation_enabled,
+ focus_emulation_enabled: state.effective_emulation_state.focus_emulation_enabled,
active_target_surface: false,
window_document_hidden: false,
window_fullscreen: false,
@@ -327,7 +338,11 @@ impl BrowserContext {
}
pub fn max_touch_points(&self) -> u32 {
- if self.active_page_target().touch_emulation_enabled {
+ if self
+ .active_page_target()
+ .effective_emulation_state
+ .touch_emulation_enabled
+ {
1
} else {
0
diff --git a/moli-protocol/src/conn/state/browser_context.rs b/moli-protocol/src/conn/state/browser_context.rs
index e554607dc..106c5a95a 100644
--- a/moli-protocol/src/conn/state/browser_context.rs
+++ b/moli-protocol/src/conn/state/browser_context.rs
@@ -1585,7 +1585,7 @@ impl BrowserContext {
pub(crate) fn effective_active_network_conditions(&self) -> Option<EmulatedNetworkConditions> {
self.page_targets
.active()
- .and_then(|host| host.network_conditions)
+ .and_then(|host| host.effective_emulation_state.network_conditions)
.or(self.default_network_conditions)
.or(self.global_network_conditions)
}
@@ -1616,7 +1616,7 @@ impl BrowserContext {
) -> Option<EmulatedGeolocationOverrideState> {
self.page_targets
.active()
- .and_then(|host| host.geolocation_override.clone())
+ .and_then(|host| host.effective_emulation_state.geolocation_override.clone())
.or_else(|| self.default_geolocation_override.clone())
.or_else(|| self.global_geolocation_override.clone())
}
@@ -1631,7 +1631,7 @@ impl BrowserContext {
target_id: &str,
) -> Option<EmulatedNetworkConditions> {
self.page_target(target_id)
- .and_then(|state| state.network_conditions)
+ .and_then(|state| state.effective_emulation_state.network_conditions)
.or(self.default_network_conditions)
.or(self.global_network_conditions)
}
diff --git a/moli-protocol/src/conn/state/devtools_session.rs b/moli-protocol/src/conn/state/devtools_session.rs
index adbd8b622..3bb5a75f6 100644
--- a/moli-protocol/src/conn/state/devtools_session.rs
+++ b/moli-protocol/src/conn/state/devtools_session.rs
@@ -391,9 +391,12 @@ impl DevToolsSessionRegistry {
}
}
- pub(crate) fn clear_emulation_state(&mut self, session_key: &DevToolsSessionKey) {
+ pub(crate) fn clear_emulation_policy_state(&mut self, session_key: &DevToolsSessionKey) {
if let Some(state) = self.states.get_mut(session_key) {
- state.emulation_session_state = DevToolsEmulationSessionState::default();
+ let emulation = &mut state.emulation_session_state;
+ emulation.browser_identity_override = None;
+ emulation.locale_override = None;
+ emulation.timezone_override = None;
}
}
@@ -658,13 +661,41 @@ pub(crate) struct DevToolsNetworkSessionState {
pub(crate) service_worker_fetch_diagnostic_entries: usize,
}
-#[derive(Clone, Debug, Default, PartialEq)]
+#[derive(Clone, Debug, PartialEq)]
pub(crate) struct DevToolsEmulationSessionState {
// UA, Accept-Language, and platform are independent handler contributions.
pub(crate) browser_identity_override: Option<DevToolsBrowserIdentityOverride>,
// Locale and timezone are exclusive controller claims, unlike UA fields.
pub(crate) locale_override: Option<String>,
pub(crate) timezone_override: Option<String>,
+ pub(crate) network_conditions: Option<super::EmulatedNetworkConditions>,
+ pub(crate) geolocation_override: Option<super::EmulatedGeolocationOverrideState>,
+ pub(crate) emulated_media: super::EmulatedMediaOverrides,
+ pub(crate) emulated_device_metrics: Option<super::EmulatedDeviceMetrics>,
+ pub(crate) cpu_throttling_rate: f64,
+ pub(crate) touch_emulation_enabled: bool,
+ pub(crate) emit_touch_events_for_mouse: bool,
+ pub(crate) focus_emulation_enabled: bool,
+ pub(crate) script_execution_disabled: bool,
+}
+
+impl Default for DevToolsEmulationSessionState {
+ fn default() -> Self {
+ Self {
+ browser_identity_override: None,
+ locale_override: None,
+ timezone_override: None,
+ network_conditions: None,
+ geolocation_override: None,
+ emulated_media: super::EmulatedMediaOverrides::default(),
+ emulated_device_metrics: None,
+ cpu_throttling_rate: 1.0,
+ touch_emulation_enabled: false,
+ emit_touch_events_for_mouse: false,
+ focus_emulation_enabled: false,
+ script_execution_disabled: false,
+ }
+ }
}
#[derive(Clone, Debug, PartialEq)]
diff --git a/moli-protocol/src/conn/state/emulation.rs b/moli-protocol/src/conn/state/emulation.rs
index 0118525a0..ef5b6e629 100644
--- a/moli-protocol/src/conn/state/emulation.rs
+++ b/moli-protocol/src/conn/state/emulation.rs
@@ -274,11 +274,120 @@ impl From<&EmulatedMediaOverrides> for moli_core::page::EmulatedMediaOverrides {
}
}
+/// Values currently exposed by the shared Page target.
+///
+/// A DevTools session keeps its own raw Emulation handler state separately.
+/// Commands copy the calling handler's value into this shared surface, just as
+/// Chromium's per-session Emulation handlers update one target-wide renderer.
+#[derive(Debug, Clone, PartialEq)]
+pub(crate) struct EffectiveTargetEmulationState {
+ pub(crate) network_conditions: Option<EmulatedNetworkConditions>,
+ pub(crate) geolocation_override: Option<EmulatedGeolocationOverrideState>,
+ pub(crate) emulated_media: EmulatedMediaOverrides,
+ pub(crate) emulated_device_metrics: Option<EmulatedDeviceMetrics>,
+ pub(crate) cpu_throttling_rate: f64,
+ pub(crate) touch_emulation_enabled: bool,
+ pub(crate) emit_touch_events_for_mouse: bool,
+ pub(crate) focus_emulation_enabled: bool,
+ pub(crate) script_execution_disabled: bool,
+}
+
+impl Default for EffectiveTargetEmulationState {
+ fn default() -> Self {
+ Self {
+ network_conditions: None,
+ geolocation_override: None,
+ emulated_media: EmulatedMediaOverrides::default(),
+ emulated_device_metrics: None,
+ cpu_throttling_rate: 1.0,
+ touch_emulation_enabled: false,
+ emit_touch_events_for_mouse: false,
+ focus_emulation_enabled: false,
+ script_execution_disabled: false,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub(crate) struct EffectiveTargetEmulationStateDelta {
+ pub(crate) network_conditions: bool,
+ pub(crate) geolocation_override: bool,
+ pub(crate) emulated_media: bool,
+ pub(crate) emulated_device_metrics: bool,
+ pub(crate) cpu_throttling_rate: bool,
+ pub(crate) touch_emulation_enabled: bool,
+ pub(crate) focus_emulation_enabled: bool,
+ pub(crate) script_execution_disabled: bool,
+}
+
+impl EffectiveTargetEmulationStateDelta {
+ pub(crate) fn surface_changed(self) -> bool {
+ self.network_conditions
+ || self.geolocation_override
+ || self.emulated_device_metrics
+ || self.touch_emulation_enabled
+ || self.focus_emulation_enabled
+ }
+}
+
+impl EffectiveTargetEmulationState {
+ /// Applies Chromium's per-handler disable contract to the shared target
+ /// surface. Decisions use the disconnecting session's raw values, never a
+ /// value last written by another session.
+ pub(crate) fn disable_session_handler(
+ &mut self,
+ raw: &super::devtools_session::DevToolsEmulationSessionState,
+ ) -> EffectiveTargetEmulationStateDelta {
+ let previous = self.clone();
+ if raw.network_conditions.is_some() {
+ self.network_conditions = None;
+ }
+ if raw.geolocation_override.is_some() {
+ self.geolocation_override = None;
+ }
+ // Blink clears media on every Emulation handler disable. Keep the
+ // target-wide side effect while retaining each handler's raw copy.
+ self.emulated_media = EmulatedMediaOverrides::default();
+ if raw.emulated_device_metrics.is_some() {
+ self.emulated_device_metrics = None;
+ }
+ if raw.cpu_throttling_rate != 1.0 {
+ self.cpu_throttling_rate = 1.0;
+ }
+ if raw.touch_emulation_enabled {
+ self.touch_emulation_enabled = false;
+ }
+ if raw.emit_touch_events_for_mouse {
+ self.emit_touch_events_for_mouse = false;
+ }
+ if raw.focus_emulation_enabled {
+ self.focus_emulation_enabled = false;
+ }
+ // Blink also sends the shared renderer an unconditional script
+ // execution reset when any Emulation handler is disabled.
+ self.script_execution_disabled = false;
+ EffectiveTargetEmulationStateDelta {
+ network_conditions: previous.network_conditions != self.network_conditions,
+ geolocation_override: previous.geolocation_override != self.geolocation_override,
+ emulated_media: previous.emulated_media != self.emulated_media,
+ emulated_device_metrics: previous.emulated_device_metrics
+ != self.emulated_device_metrics,
+ cpu_throttling_rate: previous.cpu_throttling_rate != self.cpu_throttling_rate,
+ touch_emulation_enabled: previous.touch_emulation_enabled
+ != self.touch_emulation_enabled,
+ focus_emulation_enabled: previous.focus_emulation_enabled
+ != self.focus_emulation_enabled,
+ script_execution_disabled: previous.script_execution_disabled
+ != self.script_execution_disabled,
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::{
- EmulatedDeviceMetrics, EmulatedViewportSurface, screen_avail_height_from_screen_height,
- viewport_surface_install_script,
+ EffectiveTargetEmulationState, EmulatedDeviceMetrics, EmulatedViewportSurface,
+ screen_avail_height_from_screen_height, viewport_surface_install_script,
};
#[test]
@@ -316,4 +425,33 @@ mod tests {
assert!(script.contains("['innerWidth', surface.innerWidth, true]"));
assert!(script.contains("if (topLevelOnly && !isTopLevelWindow)"));
}
+
+ #[test]
+ fn handler_disable_uses_raw_state_for_conditional_target_resets() {
+ let mut effective = EffectiveTargetEmulationState {
+ focus_emulation_enabled: true,
+ script_execution_disabled: true,
+ emulated_media: super::EmulatedMediaOverrides {
+ color_scheme: Some("dark".to_owned()),
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+ let raw = crate::conn::DevToolsEmulationSessionState::default();
+
+ let delta = effective.disable_session_handler(&raw);
+
+ assert!(
+ effective.focus_emulation_enabled,
+ "an untouched handler must not clear another session's focus setting"
+ );
+ assert!(
+ effective.emulated_media.color_scheme.is_none(),
+ "Blink clears the shared media override on every handler disable"
+ );
+ assert!(!delta.focus_emulation_enabled);
+ assert!(delta.emulated_media);
+ assert!(!effective.script_execution_disabled);
+ assert!(delta.script_execution_disabled);
+ }
}
diff --git a/moli-protocol/src/conn/state/mod.rs b/moli-protocol/src/conn/state/mod.rs
index e87d57b4d..993780df1 100644
--- a/moli-protocol/src/conn/state/mod.rs
+++ b/moli-protocol/src/conn/state/mod.rs
@@ -51,8 +51,9 @@ pub(crate) use dedicated_worker_target::{
};
pub(crate) use devtools_session::{
DevToolsBrowserIdentityOverride, DevToolsConsoleOutputSessionState,
- DevToolsLogViolationThreshold, DevToolsNetworkSessionState, DevToolsSessionState,
- PreparedRendererCallReplacements, SessionRendererCallReplay, SessionRendererCallTermination,
+ DevToolsEmulationSessionState, DevToolsLogViolationThreshold, DevToolsNetworkSessionState,
+ DevToolsSessionState, PreparedRendererCallReplacements, SessionRendererCallReplay,
+ SessionRendererCallTermination,
};
pub(crate) use document_lifecycle_observer::{
RendererDocumentLifecycleObservation, RendererDocumentLifecycleObserver,
@@ -117,13 +118,14 @@ pub(crate) use browser_context::{
pub use navigation::{PageNavigationHistoryEntry, PendingNavigationHistoryUpdate};
+pub(crate) use emulation::{
+ EffectiveTargetEmulationState, EffectiveTargetEmulationStateDelta, EmulatedNetworkConditions,
+ EmulatedViewportSurface, viewport_surface_install_script,
+};
pub use emulation::{
EmulatedDeviceMetrics, EmulatedGeolocationOverride, EmulatedGeolocationOverrideState,
EmulatedMediaOverrides,
};
-pub(crate) use emulation::{
- EmulatedNetworkConditions, EmulatedViewportSurface, viewport_surface_install_script,
-};
pub use page_target_host::PageTargetHost;
pub(crate) use target_state::{
PendingBidiChannelListener, PendingInspectorAwait, TargetInitialEmptyDocumentCreator,
diff --git a/moli-protocol/src/conn/state/page_target_host.rs b/moli-protocol/src/conn/state/page_target_host.rs
index d408a5a02..c13f85ef7 100644
--- a/moli-protocol/src/conn/state/page_target_host.rs
+++ b/moli-protocol/src/conn/state/page_target_host.rs
@@ -6,18 +6,10 @@ use moli_core::runtime::NavigationEngine;
use serde_json::Value;
use super::{
- devtools_session::DevToolsSessionRegistry,
- emulation::{
- EmulatedDeviceMetrics, EmulatedGeolocationOverrideState, EmulatedMediaOverrides,
- EmulatedNetworkConditions,
- },
- fetch::TargetFetchOwner,
- identity::TargetIdentityState,
- page_slot::TargetPageSlot,
- runtime_slot::TargetRuntimeSlot,
- session::TargetNetworkPolicyState,
- session_storage::TargetSessionStorageNamespace,
- target_state::TargetOwnerState,
+ devtools_session::DevToolsSessionRegistry, emulation::EffectiveTargetEmulationState,
+ fetch::TargetFetchOwner, identity::TargetIdentityState, page_slot::TargetPageSlot,
+ runtime_slot::TargetRuntimeSlot, session::TargetNetworkPolicyState,
+ session_storage::TargetSessionStorageNamespace, target_state::TargetOwnerState,
};
use crate::conn::cookie_manager_surface::BrowserContextCookieManagerSurface;
@@ -38,17 +30,9 @@ pub struct PageTargetHost {
pub(crate) tls_verify_host_override: Option<bool>,
pub(crate) base_locale_override: Option<String>,
pub(crate) base_timezone_override: Option<String>,
- pub(crate) network_conditions: Option<EmulatedNetworkConditions>,
- pub(crate) geolocation_override: Option<EmulatedGeolocationOverrideState>,
- pub(crate) emulated_media: EmulatedMediaOverrides,
- pub(crate) emulated_device_metrics: Option<EmulatedDeviceMetrics>,
- pub(crate) cpu_throttling_rate: f64,
+ pub(crate) effective_emulation_state: EffectiveTargetEmulationState,
pub(crate) input_intercept_drags_enabled: bool,
pub(crate) input_drag_intercepted: bool,
- pub(crate) touch_emulation_enabled: bool,
- pub(crate) emit_touch_events_for_mouse: bool,
- pub(crate) focus_emulation_enabled: bool,
- pub(crate) script_execution_disabled: bool,
pub(crate) css_enabled: bool,
pub(crate) document_cookie_manager_surface: BrowserContextCookieManagerSurface,
pub(crate) dom_remote_object_node_cache: HashMap<String, Value>,
@@ -71,17 +55,9 @@ impl PageTargetHost {
tls_verify_host_override: None,
base_locale_override: None,
base_timezone_override: None,
- network_conditions: None,
- geolocation_override: None,
- emulated_media: EmulatedMediaOverrides::default(),
- emulated_device_metrics: None,
- cpu_throttling_rate: 1.0,
+ effective_emulation_state: EffectiveTargetEmulationState::default(),
input_intercept_drags_enabled: false,
input_drag_intercepted: false,
- touch_emulation_enabled: false,
- emit_touch_events_for_mouse: false,
- focus_emulation_enabled: false,
- script_execution_disabled: false,
css_enabled: false,
document_cookie_manager_surface: BrowserContextCookieManagerSurface::default(),
dom_remote_object_node_cache: HashMap::new(),
diff --git a/moli-protocol/src/conn/state/session.rs b/moli-protocol/src/conn/state/session.rs
index 678fee8ef..2237f8679 100644
--- a/moli-protocol/src/conn/state/session.rs
+++ b/moli-protocol/src/conn/state/session.rs
@@ -1,5 +1,4 @@
use super::devtools_session::DevToolsNetworkSessionState;
-use super::emulation::EmulatedMediaOverrides;
use super::javascript_dialog::TargetJavaScriptDialogState;
use super::page_target_host::PageTargetHost;
use crate::domains::audits_output_state::TargetAuditsSessionState;
@@ -159,11 +158,12 @@ impl PageTargetHost {
self.devtools_sessions.clear_network_state(session_key);
}
- pub(crate) fn clear_devtools_emulation_state(
+ pub(crate) fn clear_devtools_emulation_policy_state(
&mut self,
session_key: &moli_page_types::DevToolsSessionKey,
) {
- self.devtools_sessions.clear_emulation_state(session_key);
+ self.devtools_sessions
+ .clear_emulation_policy_state(session_key);
}
pub(crate) fn has_pending_javascript_dialog(&self) -> bool {
@@ -184,17 +184,9 @@ impl PageTargetHost {
|| self.tls_verify_host_override.is_some()
|| self.base_locale_override.is_some()
|| self.base_timezone_override.is_some()
- || self.network_conditions.is_some()
- || self.geolocation_override.is_some()
- || self.emulated_media != EmulatedMediaOverrides::default()
- || self.emulated_device_metrics.is_some()
- || self.cpu_throttling_rate != 1.0
+ || self.effective_emulation_state != super::EffectiveTargetEmulationState::default()
|| self.input_intercept_drags_enabled
|| self.input_drag_intercepted
- || self.touch_emulation_enabled
- || self.emit_touch_events_for_mouse
- || self.focus_emulation_enabled
- || self.script_execution_disabled
|| self.css_enabled
|| self.fetch_owner.config_snapshot() != super::fetch::TargetFetchConfig::default()
}
@@ -209,15 +201,8 @@ impl PageTargetHost {
self.http_proxy_override = None;
self.http_no_proxy_override = None;
self.tls_verify_host_override = None;
- self.network_conditions = None;
- self.geolocation_override = None;
- self.emulated_device_metrics = None;
self.input_intercept_drags_enabled = false;
self.input_drag_intercepted = false;
- self.touch_emulation_enabled = false;
- self.emit_touch_events_for_mouse = false;
- self.focus_emulation_enabled = false;
- self.script_execution_disabled = false;
self.css_enabled = false;
}
}
@@ -746,6 +731,11 @@ mod tests {
None,
),
);
+ state
+ .devtools_sessions
+ .primary_mut()
+ .emulation_session_state
+ .cpu_throttling_rate = 4.0;
let effective = state.effective_policy();
assert_eq!(effective.locale_override(), Some("fr-FR"));
assert_eq!(effective.timezone_override(), Some("Europe/Paris"));
@@ -757,10 +747,19 @@ mod tests {
);
state.clear_devtools_network_state(&DevToolsSessionKey::Primary);
- state.clear_devtools_emulation_state(&DevToolsSessionKey::Primary);
+ state.clear_devtools_emulation_policy_state(&DevToolsSessionKey::Primary);
let effective = state.effective_policy();
assert_eq!(effective.locale_override(), Some("en-GB"));
assert_eq!(effective.timezone_override(), Some("Europe/London"));
+ assert_eq!(
+ state
+ .devtools_sessions
+ .primary()
+ .emulation_session_state
+ .cpu_throttling_rate,
+ 4.0,
+ "clearing policy contributions must leave the handler's renderer state intact"
+ );
assert_eq!(
effective
.browser_identity_override()
diff --git a/moli-protocol/src/domains/emulation.rs b/moli-protocol/src/domains/emulation.rs
index e5faad50c..6a324da23 100644
--- a/moli-protocol/src/domains/emulation.rs
+++ b/moli-protocol/src/domains/emulation.rs
@@ -256,8 +256,8 @@ fn focus_emulation_enabled_command_output_plan(
if conn.browser_context.is_none() {
return CommandOutputPlan::result(json!({}));
}
- match page_session::mutate_page_session_state(conn, cmd.session_id, |state| {
- *state.focus_emulation_enabled = params.enabled;
+ match page_session::update_page_emulation_state(conn, cmd.session_id, |mut state| {
+ state.set_focus_emulation_enabled(params.enabled);
}) {
Ok(()) => CommandOutputPlan::result(json!({})),
Err(message) if message == "BrowserContextNotLoaded" => {
@@ -278,8 +278,8 @@ fn touch_emulation_enabled_command_output_plan(
if conn.browser_context.is_none() {
return CommandOutputPlan::result(json!({}));
}
- match page_session::mutate_page_session_state(conn, cmd.session_id, |state| {
- *state.touch_emulation_enabled = params.enabled;
+ match page_session::update_page_emulation_state(conn, cmd.session_id, |mut state| {
+ state.set_touch_emulation_enabled(params.enabled);
}) {
Ok(()) => CommandOutputPlan::result(json!({})),
Err(message) if message == "BrowserContextNotLoaded" => {
@@ -306,9 +306,9 @@ fn start_cpu_throttling_rate_command(
if conn.browser_context.is_none() {
return EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})));
}
- if !conn.mutate_emulation_session_state_for_session_owner(cmd.session_id, |state| {
- if let Some(state) = state {
- *state.cpu_throttling_rate = params.rate;
+ if !conn.update_emulation_state_for_session_owner(cmd.session_id, |state| {
+ if let Some(mut state) = state {
+ state.set_cpu_throttling_rate(params.rate);
}
}) {
return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
@@ -345,8 +345,8 @@ fn emit_touch_events_for_mouse_command_output_plan(
if conn.browser_context.is_none() {
return CommandOutputPlan::result(json!({}));
}
- match page_session::mutate_page_session_state(conn, cmd.session_id, |state| {
- *state.emit_touch_events_for_mouse = params.enabled;
+ match page_session::update_page_emulation_state(conn, cmd.session_id, |mut state| {
+ state.set_emit_touch_events_for_mouse(params.enabled);
}) {
Ok(()) => CommandOutputPlan::result(json!({})),
Err(message) if message == "BrowserContextNotLoaded" => {
@@ -372,9 +372,9 @@ fn start_script_execution_disabled_command(
if conn.browser_context.is_none() {
return EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})));
}
- if !conn.mutate_emulation_session_state_for_session_owner(cmd.session_id, |state| {
- if let Some(state) = state {
- *state.script_execution_disabled = params.value;
+ if !conn.update_emulation_state_for_session_owner(cmd.session_id, |state| {
+ if let Some(mut state) = state {
+ state.set_script_execution_disabled(params.value);
}
}) {
return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
@@ -668,9 +668,9 @@ fn start_update_geolocation_override_command(
if conn.browser_context.is_none() {
return EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})));
}
- if !conn.mutate_emulation_session_state_for_session_owner(cmd.session_id, |state| {
- if let Some(state) = state {
- *state.geolocation_override = override_state.clone();
+ if !conn.update_emulation_state_for_session_owner(cmd.session_id, |state| {
+ if let Some(mut state) = state {
+ state.set_geolocation_override(override_state.clone());
}
}) {
return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
@@ -711,9 +711,9 @@ fn start_emulated_media_command(
return EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})));
}
let overrides = media::emulated_media_overrides_from_params(params);
- if !conn.mutate_emulation_session_state_for_session_owner(cmd.session_id, |state| {
- if let Some(state) = state {
- *state.emulated_media = overrides.clone();
+ if !conn.update_emulation_state_for_session_owner(cmd.session_id, |state| {
+ if let Some(mut state) = state {
+ state.set_emulated_media(overrides.clone());
}
}) {
return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
@@ -876,9 +876,9 @@ fn start_clear_device_metrics_override_command(
{
return EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})));
}
- if !conn.mutate_emulation_session_state_for_session_owner(cmd.session_id, |state| {
- if let Some(state) = state {
- *state.emulated_device_metrics = None;
+ if !conn.update_emulation_state_for_session_owner(cmd.session_id, |state| {
+ if let Some(mut state) = state {
+ state.set_emulated_device_metrics(None);
}
}) {
return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
@@ -947,9 +947,9 @@ fn start_devtools_set_viewport_command(
let had_existing_device_metrics = conn
.target_session_owner_emulated_device_metrics_for_owner(&owner_scope)
.is_some();
- if !conn.mutate_emulation_session_state_for_owner(&owner_scope, |state| {
- if let Some(state) = state {
- *state.emulated_device_metrics = Some(metrics.clone());
+ if !conn.update_emulation_state_for_owner(&owner_scope, |state| {
+ if let Some(mut state) = state {
+ state.set_emulated_device_metrics(Some(metrics.clone()));
}
}) {
return Err(DevToolsError::new(
@@ -1252,9 +1252,9 @@ fn start_geolocation_override_for_current_route(
override_state: Option<EmulatedGeolocationOverrideState>,
) -> Result<Vec<PendingEmulationPageCommand>, DevToolsError> {
let owner = CommandOwnerScope::for_route(route.clone());
- if !conn.mutate_emulation_session_state_for_owner(&owner, |state| {
- if let Some(state) = state {
- *state.geolocation_override = override_state;
+ if !conn.update_emulation_state_for_owner(&owner, |state| {
+ if let Some(mut state) = state {
+ state.set_geolocation_override(override_state);
}
}) {
return Err(devtools_emulation_owner_error(
@@ -1339,9 +1339,9 @@ fn start_network_conditions_for_current_route(
network_conditions: Option<DevToolsNetworkConditions>,
) -> Result<Vec<PendingEmulationPageCommand>, DevToolsError> {
let owner = CommandOwnerScope::for_route(route.clone());
- if !conn.mutate_emulation_session_state_for_owner(&owner, |state| {
- if let Some(state) = state {
- *state.network_conditions = network_conditions.map(emulated_network_conditions);
+ if !conn.update_emulation_state_for_owner(&owner, |state| {
+ if let Some(mut state) = state {
+ state.set_network_conditions(network_conditions.map(emulated_network_conditions));
}
}) {
return Err(devtools_emulation_owner_error(
@@ -2259,7 +2259,13 @@ fn browser_context_default_device_metrics_runtime_command_count(
browser_context
.page_targets
.iter()
- .filter(|target| target.emulated_device_metrics.is_none() && target.loaded_page().is_some())
+ .filter(|target| {
+ target
+ .effective_emulation_state
+ .emulated_device_metrics
+ .is_none()
+ && target.loaded_page().is_some()
+ })
.count()
}
@@ -2275,7 +2281,10 @@ fn start_browser_context_default_device_metrics_page_commands(
let viewport_surface = Some(metrics.viewport_surface().to_page_viewport_surface());
if let Some(active_target_id) = active_target_id
&& let Some(active_target) = browser_context.page_targets.active_mut()
- && active_target.emulated_device_metrics.is_none()
+ && active_target
+ .effective_emulation_state
+ .emulated_device_metrics
+ .is_none()
&& let Some(page) = active_target.runtime_slot.loaded_page_mut()
{
pending.push(PendingEmulationPageCommand {
@@ -2317,7 +2326,12 @@ fn start_browser_context_default_device_metrics_page_commands(
.to_owned();
let has_target_override = browser_context
.page_target(&target_id)
- .is_some_and(|state| state.emulated_device_metrics.is_some());
+ .is_some_and(|state| {
+ state
+ .effective_emulation_state
+ .emulated_device_metrics
+ .is_some()
+ });
if has_target_override {
continue;
}
@@ -2588,53 +2602,108 @@ pub(crate) async fn dispose_page_session_async(
.await
.err();
- // InspectorEmulationAgent::disable resets media and CPU throttling for
- // every renderer session, even though both settings are target-visible.
- // Keep that intentionally non-aggregated Chromium behavior here.
- let media = crate::conn::EmulatedMediaOverrides::default();
- let mut media_changed = false;
- let mut cpu_changed = false;
- if !conn.mutate_emulation_session_state_for_session_owner(Some(session_id), |state| {
- if let Some(state) = state {
- media_changed = *state.emulated_media != media;
- cpu_changed = *state.cpu_throttling_rate != 1.0;
- *state.emulated_media = media.clone();
- *state.cpu_throttling_rate = 1.0;
+ let Some(delta) = conn.disable_emulation_session_handler_for_session_owner(session_id) else {
+ return first_error.map_or(Ok(()), Err);
+ };
+ let owner = CommandOwnerScope::capture(conn, Some(session_id));
+ let load_inputs = conn.navigation_load_inputs_for_owner(&owner);
+ if let Some(page) = loaded_page_mut_for_target_configuration(conn, Some(session_id)) {
+ if delta.script_execution_disabled {
+ record_emulation_disposal_result(
+ &mut first_error,
+ "script execution",
+ page.set_script_execution_disabled_async(load_inputs.script_execution_disabled)
+ .await,
+ );
+ }
+ if delta.emulated_media {
+ record_emulation_disposal_result(
+ &mut first_error,
+ "emulated media",
+ page.set_emulated_media_async(&load_inputs.emulated_media)
+ .await,
+ );
+ }
+ if delta.cpu_throttling_rate {
+ record_emulation_disposal_result(
+ &mut first_error,
+ "CPU throttling",
+ page.set_cpu_throttling_rate_async(load_inputs.cpu_throttling_rate)
+ .await,
+ );
+ }
+ if delta.network_conditions {
+ record_emulation_disposal_result(
+ &mut first_error,
+ "network conditions",
+ page.set_network_offline_async(load_inputs.network_offline)
+ .await,
+ );
+ }
+ if delta.emulated_device_metrics {
+ record_emulation_disposal_result(
+ &mut first_error,
+ "device metrics viewport",
+ page.set_viewport_surface_async(load_inputs.viewport_surface)
+ .await,
+ );
+ record_emulation_disposal_result(
+ &mut first_error,
+ "device metrics script",
+ page.run_page_surface_override_script_async(
+ device::LIVE_DEVICE_METRICS_CLEAR_SCRIPT,
+ )
+ .await,
+ );
}
- }) {
- return match first_error {
- Some(error) => Err(error),
- None => Ok(()),
- };
}
- if !media_changed && !cpu_changed {
- return match first_error {
- Some(error) => Err(error),
- None => Ok(()),
- };
+ if delta.surface_changed() {
+ record_emulation_disposal_result(
+ &mut first_error,
+ "page surfaces",
+ apply_session_surface_state_async(conn, session_id).await,
+ );
}
+ first_error.map_or(Ok(()), Err)
+}
- let page_media: moli_core::page::EmulatedMediaOverrides = (&media).into();
- let Some(page) = loaded_page_mut_for_target_configuration(conn, Some(session_id)) else {
- return match first_error {
- Some(error) => Err(error),
- None => Ok(()),
- };
+async fn apply_session_surface_state_async(
+ conn: &mut CdpConnection,
+ session_id: &str,
+) -> anyhow::Result<()> {
+ let Some(CdpSessionRoute::PageTarget {
+ browser_context_id,
+ target_id,
+ ..
+ }) = conn.session_route(Some(session_id))
+ else {
+ return Ok(());
};
- if media_changed && let Err(error) = page.set_emulated_media_async(&page_media).await {
- first_error.get_or_insert_with(|| {
- anyhow::anyhow!("failed to clear detached session emulated media: {error}")
- });
+ let Some(browser_context) = conn.browser_context_by_id_mut(&browser_context_id) else {
+ return Ok(());
+ };
+ if browser_context.is_active_target(&target_id) {
+ browser_context
+ .apply_surface_overrides_to_loaded_page_async()
+ .await
+ } else {
+ browser_context
+ .apply_background_target_surface_overrides_async(&target_id)
+ .await
+ .map(|_applied| ())
}
- if cpu_changed && let Err(error) = page.set_cpu_throttling_rate_async(1.0).await {
+}
+
+fn record_emulation_disposal_result(
+ first_error: &mut Option<anyhow::Error>,
+ surface: &'static str,
+ result: anyhow::Result<()>,
+) {
+ if let Err(error) = result {
first_error.get_or_insert_with(|| {
- anyhow::anyhow!("failed to clear detached session CPU throttling: {error}")
+ anyhow::anyhow!("failed to clear detached session {surface}: {error}")
});
}
- match first_error {
- Some(error) => Err(error),
- None => Ok(()),
- }
}
fn single_pending_emulation_dispatch(
diff --git a/moli-protocol/src/domains/emulation/page_session.rs b/moli-protocol/src/domains/emulation/page_session.rs
index 3bd5e0dcf..9a17dc3d7 100644
--- a/moli-protocol/src/domains/emulation/page_session.rs
+++ b/moli-protocol/src/domains/emulation/page_session.rs
@@ -1,11 +1,11 @@
-use crate::conn::{CdpConnection, TargetEmulationSessionStateMut};
+use crate::conn::{CdpConnection, TargetEmulationStateUpdate};
-pub(super) fn mutate_page_session_state(
+pub(super) fn update_page_emulation_state(
conn: &mut CdpConnection,
session_id: Option<&str>,
- f: impl FnOnce(TargetEmulationSessionStateMut<'_>),
+ f: impl FnOnce(TargetEmulationStateUpdate<'_>),
) -> Result<(), String> {
- if conn.mutate_emulation_session_state_for_session_owner(session_id, |state| {
+ if conn.update_emulation_state_for_session_owner(session_id, |state| {
if let Some(state) = state {
f(state);
}
diff --git a/moli-protocol/src/domains/emulation/tests.rs b/moli-protocol/src/domains/emulation/tests.rs
index b72a25394..87f4ce3b9 100644
--- a/moli-protocol/src/domains/emulation/tests.rs
+++ b/moli-protocol/src/domains/emulation/tests.rs
@@ -274,6 +274,7 @@ async fn script_execution_disabled_completes_through_io_pending_dispatch() {
.as_ref()
.unwrap()
.active_page_target()
+ .effective_emulation_state
.script_execution_disabled
);
}
@@ -317,6 +318,7 @@ async fn attached_session_first_io_emulation_response_uses_its_session_host() {
.as_ref()
.expect("browser context")
.active_page_target()
+ .effective_emulation_state
.script_execution_disabled
);
}
@@ -390,6 +392,7 @@ async fn emulated_media_can_complete_through_pending_command_dispatch() {
.as_ref()
.unwrap()
.active_page_target()
+ .effective_emulation_state
.emulated_media;
assert_eq!(media.media.as_deref(), Some("screen"));
assert_eq!(media.color_scheme.as_deref(), Some("dark"));
@@ -829,15 +832,29 @@ async fn pure_state_emulation_commands_complete_through_command_dispatch() {
}
let browser_context = ctx.conn.browser_context.as_ref().unwrap();
- assert!(browser_context.active_page_target().focus_emulation_enabled);
- assert!(browser_context.active_page_target().touch_emulation_enabled);
assert!(
browser_context
.active_page_target()
+ .effective_emulation_state
+ .focus_emulation_enabled
+ );
+ assert!(
+ browser_context
+ .active_page_target()
+ .effective_emulation_state
+ .touch_emulation_enabled
+ );
+ assert!(
+ browser_context
+ .active_page_target()
+ .effective_emulation_state
.emit_touch_events_for_mouse
);
assert_eq!(
- browser_context.active_page_target().cpu_throttling_rate,
+ browser_context
+ .active_page_target()
+ .effective_emulation_state
+ .cpu_throttling_rate,
1.0
);
}
@@ -865,6 +882,7 @@ async fn set_cpu_throttling_rate_rejects_invalid_params() {
.as_ref()
.expect("browser context")
.active_page_target()
+ .effective_emulation_state
.cpu_throttling_rate,
1.0
);
@@ -935,6 +953,7 @@ async fn live_apply_emulation_commands_without_loaded_page_do_not_use_legacy_fal
.as_ref()
.expect("browser context")
.active_page_target()
+ .effective_emulation_state
.cpu_throttling_rate,
2.5
);
@@ -1070,6 +1089,7 @@ async fn live_cpu_throttling_rate_uses_pending_command_dispatch() {
.as_ref()
.expect("browser context")
.active_page_target()
+ .effective_emulation_state
.cpu_throttling_rate,
3.0
);
@@ -1295,6 +1315,141 @@ async fn multi_session_browser_identity_uses_attachment_order_and_field_contribu
);
}
+#[tokio::test(flavor = "multi_thread")]
+async fn multi_session_emulation_separates_handler_input_from_target_effective_state() {
+ let mut ctx = TestContext::new();
+ install_multi_session_page_state(&mut ctx);
+
+ expect_session_command_result(
+ &mut ctx,
+ 71_101,
+ "SID-primary",
+ "Emulation.setCPUThrottlingRate",
+ json!({ "rate": 4 }),
+ )
+ .await;
+ expect_session_command_result(
+ &mut ctx,
+ 71_102,
+ "SID-attached",
+ "Emulation.setCPUThrottlingRate",
+ json!({ "rate": 2 }),
+ )
+ .await;
+ expect_session_command_result(
+ &mut ctx,
+ 71_103,
+ "SID-primary",
+ "Emulation.setDeviceMetricsOverride",
+ json!({
+ "width": 800,
+ "height": 600,
+ "deviceScaleFactor": 1,
+ "mobile": false
+ }),
+ )
+ .await;
+ expect_session_command_result(
+ &mut ctx,
+ 71_104,
+ "SID-attached",
+ "Emulation.setDeviceMetricsOverride",
+ json!({
+ "width": 640,
+ "height": 480,
+ "deviceScaleFactor": 2,
+ "mobile": false
+ }),
+ )
+ .await;
+ expect_session_command_result(
+ &mut ctx,
+ 71_105,
+ "SID-primary",
+ "Emulation.setFocusEmulationEnabled",
+ json!({ "enabled": true }),
+ )
+ .await;
+
+ let primary = ctx
+ .conn
+ .emulation_session_state_for_session_owner(Some("SID-primary"))
+ .expect("primary Emulation handler state");
+ let attached = ctx
+ .conn
+ .emulation_session_state_for_session_owner(Some("SID-attached"))
+ .expect("attached Emulation handler state");
+ assert_eq!(primary.cpu_throttling_rate, 4.0);
+ assert_eq!(attached.cpu_throttling_rate, 2.0);
+ assert_eq!(
+ primary
+ .emulated_device_metrics
+ .as_ref()
+ .map(|metrics| (metrics.width, metrics.height)),
+ Some((800, 600))
+ );
+ assert_eq!(
+ attached
+ .emulated_device_metrics
+ .as_ref()
+ .map(|metrics| (metrics.width, metrics.height)),
+ Some((640, 480))
+ );
+ assert!(primary.focus_emulation_enabled);
+ assert!(!attached.focus_emulation_enabled);
+
+ let target = ctx
+ .conn
+ .browser_context
+ .as_ref()
+ .expect("browser context")
+ .active_page_target();
+ assert_eq!(target.effective_emulation_state.cpu_throttling_rate, 2.0);
+ assert_eq!(
+ target
+ .effective_emulation_state
+ .emulated_device_metrics
+ .as_ref()
+ .map(|metrics| (metrics.width, metrics.height)),
+ Some((640, 480))
+ );
+ assert!(target.effective_emulation_state.focus_emulation_enabled);
+
+ super::dispose_page_session_async(&mut ctx.conn, "SID-attached")
+ .await
+ .expect("attached Emulation handler disposal");
+ let target = ctx
+ .conn
+ .browser_context
+ .as_ref()
+ .expect("browser context")
+ .active_page_target();
+ assert_eq!(target.effective_emulation_state.cpu_throttling_rate, 1.0);
+ assert!(
+ target
+ .effective_emulation_state
+ .emulated_device_metrics
+ .is_none()
+ );
+ assert!(
+ target.effective_emulation_state.focus_emulation_enabled,
+ "disposing an untouched handler must not clear another session's focus input"
+ );
+ let primary = ctx
+ .conn
+ .emulation_session_state_for_session_owner(Some("SID-primary"))
+ .expect("primary Emulation handler state survives attached disposal");
+ assert_eq!(primary.cpu_throttling_rate, 4.0);
+ assert!(primary.emulated_device_metrics.is_some());
+ assert!(primary.focus_emulation_enabled);
+ assert_eq!(
+ ctx.conn
+ .emulation_session_state_for_session_owner(Some("SID-attached"))
+ .expect("disposed handler remains addressable until session detach commits"),
+ crate::conn::DevToolsEmulationSessionState::default()
+ );
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn async_emulation_device_state_updates_browser_context() {
let mut ctx = TestContext::new();
@@ -1313,6 +1468,7 @@ async fn async_emulation_device_state_updates_browser_context() {
.as_ref()
.unwrap()
.active_page_target()
+ .effective_emulation_state
.focus_emulation_enabled
);
@@ -1329,6 +1485,7 @@ async fn async_emulation_device_state_updates_browser_context() {
.as_ref()
.unwrap()
.active_page_target()
+ .effective_emulation_state
.touch_emulation_enabled
);
@@ -1345,6 +1502,7 @@ async fn async_emulation_device_state_updates_browser_context() {
.as_ref()
.unwrap()
.active_page_target()
+ .effective_emulation_state
.emit_touch_events_for_mouse
);
@@ -1359,7 +1517,12 @@ async fn async_emulation_device_state_updates_browser_context() {
.conn
.browser_context
.as_ref()
- .and_then(|bc| bc.active_page_target().geolocation_override.as_ref())
+ .and_then(|bc| {
+ bc.active_page_target()
+ .effective_emulation_state
+ .geolocation_override
+ .as_ref()
+ })
.and_then(EmulatedGeolocationOverrideState::position)
.expect("geolocation override should be set");
assert_eq!(geolocation.latitude, 37.33182);
@@ -1377,7 +1540,12 @@ async fn async_emulation_device_state_updates_browser_context() {
.conn
.browser_context
.as_ref()
- .and_then(|bc| bc.active_page_target().emulated_device_metrics.as_ref())
+ .and_then(|bc| {
+ bc.active_page_target()
+ .effective_emulation_state
+ .emulated_device_metrics
+ .as_ref()
+ })
.expect("device metrics should be set");
assert_eq!(metrics.width, 800);
assert_eq!(metrics.height, 600);
@@ -1395,6 +1563,7 @@ async fn async_emulation_device_state_updates_browser_context() {
.as_ref()
.unwrap()
.active_page_target()
+ .effective_emulation_state
.emulated_device_metrics
.is_none()
);
@@ -2344,6 +2513,7 @@ async fn clear_geolocation_override_restores_default_after_explicit_unavailable(
.as_ref()
.and_then(|browser_context| browser_context
.active_page_target()
+ .effective_emulation_state
.geolocation_override
.as_ref()),
Some(EmulatedGeolocationOverrideState::PositionUnavailable)
@@ -2366,6 +2536,7 @@ async fn clear_geolocation_override_restores_default_after_explicit_unavailable(
.as_ref()
.expect("browser context")
.active_page_target()
+ .effective_emulation_state
.geolocation_override
.is_none()
);
@@ -3009,6 +3180,7 @@ async fn session_emulation_routes_to_loaded_background_owner_without_activation(
assert!(
browser_context
.active_page_target()
+ .effective_emulation_state
.emulated_media
.color_scheme
.is_none(),
@@ -3027,7 +3199,11 @@ async fn session_emulation_routes_to_loaded_background_owner_without_activation(
.filter(|target| target.has_non_default_session_state())
.expect("background target state");
assert_eq!(
- background.emulated_media.color_scheme.as_deref(),
+ background
+ .effective_emulation_state
+ .emulated_media
+ .color_scheme
+ .as_deref(),
Some("dark")
);
assert_eq!(
@@ -3036,6 +3212,7 @@ async fn session_emulation_routes_to_loaded_background_owner_without_activation(
);
assert_eq!(
background
+ .effective_emulation_state
.geolocation_override
.as_ref()
.and_then(EmulatedGeolocationOverrideState::position)
@@ -3234,9 +3411,9 @@ async fn target_session_detach_disposes_non_aggregated_emulation_state_before_re
.as_ref()
.and_then(|browser_context| browser_context.page_target("TID-1"))
.expect("detached target remains addressable");
- assert_eq!(target.cpu_throttling_rate, 1.0);
+ assert_eq!(target.effective_emulation_state.cpu_throttling_rate, 1.0);
assert_eq!(
- target.emulated_media,
+ target.effective_emulation_state.emulated_media,
crate::conn::EmulatedMediaOverrides::default()
);
diff --git a/moli-protocol/src/domains/input/tests.rs b/moli-protocol/src/domains/input/tests.rs
index e9ce7e23a..328d84308 100644
--- a/moli-protocol/src/domains/input/tests.rs
+++ b/moli-protocol/src/domains/input/tests.rs
@@ -1692,6 +1692,7 @@ async fn coordinate_touch_commands_complete_through_pending_layout_dispatch() {
.as_mut()
.expect("loaded browser context")
.active_page_target_mut()
+ .effective_emulation_state
.emit_touch_events_for_mouse = true;
for (id, event_type, buttons) in [(4107, "mousePressed", 1), (4108, "mouseReleased", 0)] {
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/page/tests/capture.rs b/moli-protocol/src/domains/page/tests/capture.rs
index 09855f423..11d92d1c4 100644
--- a/moli-protocol/src/domains/page/tests/capture.rs
+++ b/moli-protocol/src/domains/page/tests/capture.rs
@@ -515,6 +515,7 @@ async fn capture_screenshot_targets_loaded_background_owner_without_activation()
.expect("browser context")
.background_target_mut("TID-background")
.expect("background target must exist")
+ .effective_emulation_state
.emulated_device_metrics = Some(EmulatedDeviceMetrics {
width: 320,
height: 240,
@@ -560,7 +561,10 @@ async fn capture_screenshot_targets_inactive_loaded_owner_without_activation() {
let mut inactive = BrowserContext::new("BID-inactive-screenshot".to_owned());
inactive.set_active_target_id("TID-inactive".to_owned());
inactive.attach_active_session("SID-inactive".to_owned());
- inactive.active_page_target_mut().emulated_device_metrics = Some(EmulatedDeviceMetrics {
+ inactive
+ .active_page_target_mut()
+ .effective_emulation_state
+ .emulated_device_metrics = Some(EmulatedDeviceMetrics {
width: 500,
height: 300,
device_scale_factor: 1.5,
diff --git a/moli-protocol/src/domains/target/tests/tests_background_staging.rs b/moli-protocol/src/domains/target/tests/tests_background_staging.rs
index 2b43818c5..9c705ca10 100644
--- a/moli-protocol/src/domains/target/tests/tests_background_staging.rs
+++ b/moli-protocol/src/domains/target/tests/tests_background_staging.rs
@@ -1321,6 +1321,7 @@ async fn same_context_background_session_can_stage_its_own_emulated_media_before
assert_eq!(
active
.active_page_target()
+ .effective_emulation_state
.emulated_media
.color_scheme
.as_deref(),
@@ -1330,7 +1331,14 @@ async fn same_context_background_session_can_stage_its_own_emulated_media_before
.background_target(&second_target_id)
.filter(|target| target.has_non_default_session_state())
.expect("second target should have staged background page session state");
- assert_eq!(staged.emulated_media.color_scheme.as_deref(), Some("light"));
+ assert_eq!(
+ staged
+ .effective_emulation_state
+ .emulated_media
+ .color_scheme
+ .as_deref(),
+ Some("light")
+ );
}
ctx.process_async(json!({
@@ -1460,6 +1468,7 @@ async fn same_context_background_session_can_clear_its_own_emulated_media_before
assert!(
active
.active_page_target()
+ .effective_emulation_state
.emulated_media
.color_scheme
.is_none(),
@@ -3512,6 +3521,7 @@ async fn same_context_background_session_can_stage_its_own_emulation_overrides_b
assert_eq!(
active
.active_page_target()
+ .effective_emulation_state
.emulated_device_metrics
.as_ref()
.map(|metrics| (
@@ -3523,25 +3533,39 @@ async fn same_context_background_session_can_stage_its_own_emulation_overrides_b
)),
Some((1280, 720, 2.0, 1440, 900))
);
- assert!(active.active_page_target().touch_emulation_enabled);
- assert!(active.active_page_target().focus_emulation_enabled);
+ assert!(
+ active
+ .active_page_target()
+ .effective_emulation_state
+ .touch_emulation_enabled
+ );
+ assert!(
+ active
+ .active_page_target()
+ .effective_emulation_state
+ .focus_emulation_enabled
+ );
let staged = active
.background_target(&second_target_id)
.filter(|target| target.has_non_default_session_state())
.expect("second target should have staged background page session state");
assert_eq!(
- staged.emulated_device_metrics.as_ref().map(|metrics| (
- metrics.width,
- metrics.height,
- metrics.device_scale_factor,
- metrics.screen_width,
- metrics.screen_height
- )),
+ staged
+ .effective_emulation_state
+ .emulated_device_metrics
+ .as_ref()
+ .map(|metrics| (
+ metrics.width,
+ metrics.height,
+ metrics.device_scale_factor,
+ metrics.screen_width,
+ metrics.screen_height
+ )),
Some((640, 360, 1.0, 800, 600))
);
- assert!(!staged.touch_emulation_enabled);
- assert!(!staged.focus_emulation_enabled);
+ assert!(!staged.effective_emulation_state.touch_emulation_enabled);
+ assert!(!staged.effective_emulation_state.focus_emulation_enabled);
}
ctx.process_async(json!({
@@ -3869,6 +3893,7 @@ async fn same_context_background_session_can_clear_its_own_device_metrics_before
assert!(
active
.active_page_target()
+ .effective_emulation_state
.emulated_device_metrics
.is_none(),
"active target should keep its default device metrics",
@@ -4043,11 +4068,17 @@ async fn same_context_background_session_can_clear_its_own_touch_and_focus_befor
.as_ref()
.expect("active browser context");
assert!(
- !active.active_page_target().touch_emulation_enabled,
+ !active
+ .active_page_target()
+ .effective_emulation_state
+ .touch_emulation_enabled,
"active target should keep default touch emulation"
);
assert!(
- !active.active_page_target().focus_emulation_enabled,
+ !active
+ .active_page_target()
+ .effective_emulation_state
+ .focus_emulation_enabled,
"active target should keep default focus emulation"
);
assert!(
@@ -4194,12 +4225,17 @@ async fn same_context_background_session_can_stage_its_own_script_execution_disa
.browser_context
.as_ref()
.expect("active browser context");
- assert!(!active.active_page_target().script_execution_disabled);
+ assert!(
+ !active
+ .active_page_target()
+ .effective_emulation_state
+ .script_execution_disabled
+ );
let staged = active
.background_target(&second_target_id)
.filter(|target| target.has_non_default_session_state())
.expect("second target should have staged background page session state");
- assert!(staged.script_execution_disabled);
+ assert!(staged.effective_emulation_state.script_execution_disabled);
}
ctx.process_async(json!({
@@ -4270,7 +4306,12 @@ async fn same_context_background_session_can_stage_its_own_script_execution_disa
.browser_context
.as_ref()
.expect("activated browser context");
- assert!(activated.active_page_target().script_execution_disabled);
+ assert!(
+ activated
+ .active_page_target()
+ .effective_emulation_state
+ .script_execution_disabled
+ );
}
ctx.process_async(json!({
@@ -4361,7 +4402,12 @@ async fn same_context_background_session_can_reenable_its_own_script_execution_b
.browser_context
.as_ref()
.expect("active browser context");
- assert!(!active.active_page_target().script_execution_disabled);
+ assert!(
+ !active
+ .active_page_target()
+ .effective_emulation_state
+ .script_execution_disabled
+ );
// A completed renderer call may retain its monotonic correlation
// allocator in the background session; only the effective setting must
// collapse back to the default.
@@ -4369,7 +4415,7 @@ async fn same_context_background_session_can_reenable_its_own_script_execution_b
active
.background_target(&second_target_id)
.filter(|target| target.has_non_default_session_state())
- .is_none_or(|state| !state.script_execution_disabled),
+ .is_none_or(|state| { !state.effective_emulation_state.script_execution_disabled }),
"script execution re-enable should clear the staged background setting: {:#?}",
active
.background_target(&second_target_id)
@@ -4445,7 +4491,12 @@ async fn same_context_background_session_can_reenable_its_own_script_execution_b
.browser_context
.as_ref()
.expect("activated browser context");
- assert!(!activated.active_page_target().script_execution_disabled);
+ assert!(
+ !activated
+ .active_page_target()
+ .effective_emulation_state
+ .script_execution_disabled
+ );
}
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs b/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs
index 97f063ee2..1fee7fb8f 100644
--- a/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs
+++ b/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs
@@ -5955,6 +5955,7 @@ async fn playwright_over_cdp_context_profile_surfaces_permissions_tls_and_metric
assert_eq!(
active
.active_page_target()
+ .effective_emulation_state
.emulated_device_metrics
.as_ref()
.map(|metrics| (metrics.width, metrics.height, metrics.device_scale_factor)),
@@ -6154,7 +6155,12 @@ async fn playwright_over_cdp_script_execution_disabled_blocks_page_scripts_but_n
.browser_context
.as_ref()
.expect("active browser context");
- assert!(active.active_page_target().script_execution_disabled);
+ assert!(
+ active
+ .active_page_target()
+ .effective_emulation_state
+ .script_execution_disabled
+ );
let script_runs = active
.active_page_target()
.runtime_slot
diff --git a/moli-protocol/src/domains/target/tests/tests_same_context_state.rs b/moli-protocol/src/domains/target/tests/tests_same_context_state.rs
index d87b915bf..20c0b3bc6 100644
--- a/moli-protocol/src/domains/target/tests/tests_same_context_state.rs
+++ b/moli-protocol/src/domains/target/tests/tests_same_context_state.rs
@@ -105,6 +105,7 @@ async fn same_context_targets_restore_their_own_script_execution_disabled_after_
.as_ref()
.expect("active browser context")
.active_page_target()
+ .effective_emulation_state
.script_execution_disabled
);
@@ -154,6 +155,7 @@ async fn same_context_targets_restore_their_own_script_execution_disabled_after_
.as_ref()
.expect("active browser context")
.active_page_target()
+ .effective_emulation_state
.script_execution_disabled
);