Skip to content

armgit / moli

Public Imported from GitHub
0

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

feat(emulation): override native hardware concurrency

ldm00013b7925ca3
diff --git a/moli-page-types/src/lib.rs b/moli-page-types/src/lib.rs
index 69064c89b..f122932a5 100644
--- a/moli-page-types/src/lib.rs
+++ b/moli-page-types/src/lib.rs
@@ -52,7 +52,10 @@ pub use inspector_identity::{
RendererInspectorResponseDelivery,
};
pub use layout::LayoutPolicy;
-pub use navigator_overrides::{GeolocationPositionOverride, NavigatorOverrides};
+pub use navigator_overrides::{
+ GeolocationPositionOverride, NavigatorEmulationSessions, NavigatorOverrides,
+ NavigatorQueryOverrides,
+};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocumentNodeAttributeSnapshot {
diff --git a/moli-page-types/src/navigator_overrides.rs b/moli-page-types/src/navigator_overrides.rs
index 379a93e43..9eb1f16f5 100644
--- a/moli-page-types/src/navigator_overrides.rs
+++ b/moli-page-types/src/navigator_overrides.rs
@@ -8,6 +8,7 @@ pub struct NavigatorOverrides {
/// None uses the renderer's actual network state.
pub online: Option<bool>,
pub max_touch_points: u32,
+ pub queries: NavigatorQueryOverrides,
/// None means that no emulated coordinate source is available.
pub geolocation: Option<GeolocationPositionOverride>,
}
@@ -22,3 +23,52 @@ pub struct GeolocationPositionOverride {
pub heading: Option<f64>,
pub speed: Option<f64>,
}
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct NavigatorQueryOverrides {
+ pub hardware_concurrency: Option<std::num::NonZeroU32>,
+}
+
+/// Native query overrides in Inspector agent activation order. Page and Worker
+/// sessions use the same precedence, but each target owns its own registry.
+#[derive(Debug, Default, PartialEq, Eq)]
+pub struct NavigatorEmulationSessions {
+ sessions: Vec<(crate::DevToolsSessionKey, NavigatorQueryOverrides)>,
+}
+
+impl NavigatorEmulationSessions {
+ /// The first probe-using Emulation command activates an agent. Subsequent
+ /// commands preserve its position, even after clearing an individual value.
+ pub fn session_mut(&mut self, key: &crate::DevToolsSessionKey) -> &mut NavigatorQueryOverrides {
+ let index = match self
+ .sessions
+ .iter()
+ .position(|(existing, _)| existing == key)
+ {
+ Some(index) => index,
+ None => {
+ self.sessions
+ .push((key.clone(), NavigatorQueryOverrides::default()));
+ self.sessions.len() - 1
+ }
+ };
+ &mut self.sessions[index].1
+ }
+
+ pub fn remove(&mut self, key: &crate::DevToolsSessionKey) {
+ self.sessions.retain(|(existing, _)| existing != key);
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.sessions.is_empty()
+ }
+
+ pub fn effective(&self) -> NavigatorQueryOverrides {
+ let mut effective = NavigatorQueryOverrides::default();
+ for (_, settings) in &self.sessions {
+ effective.hardware_concurrency = settings
+ .hardware_concurrency
+ .or(effective.hardware_concurrency);
+ }
+ effective
+ }
+}
diff --git a/moli-protocol/src/conn/browser_context/emulation_owner.rs b/moli-protocol/src/conn/browser_context/emulation_owner.rs
index 61c54a96a..066a44186 100644
--- a/moli-protocol/src/conn/browser_context/emulation_owner.rs
+++ b/moli-protocol/src/conn/browser_context/emulation_owner.rs
@@ -237,6 +237,25 @@ impl CdpConnection {
.cloned()
}
+ pub(crate) fn update_navigator_queries_for_session_owner(
+ &mut self,
+ session_id: Option<&str>,
+ update: impl FnOnce(&mut moli_page_types::NavigatorQueryOverrides),
+ ) -> Result<(), &'static str> {
+ let mut owner = self
+ .target_session_owner_mut(session_id)
+ .ok_or("BrowserContextNotLoaded")?;
+ owner.mutate_page_state(|target, key| {
+ update(
+ target
+ .devtools_sessions
+ .navigator_emulation
+ .session_mut(key),
+ )
+ });
+ Ok(())
+ }
+
pub(crate) fn disable_emulation_session_handler_for_session_owner(
&mut self,
session_id: &str,
@@ -249,9 +268,17 @@ impl CdpConnection {
.ensure_session(session_key)
.emulation_session_state,
);
+ let previous_queries = target.devtools_sessions.navigator_emulation.effective();
target
+ .devtools_sessions
+ .navigator_emulation
+ .remove(session_key);
+ let mut delta = target
.effective_emulation_state
- .disable_session_handler(&raw)
+ .disable_session_handler(&raw);
+ delta.navigator_queries =
+ previous_queries != target.devtools_sessions.navigator_emulation.effective();
+ delta
}))
}
}
diff --git a/moli-protocol/src/conn/dispatch.rs b/moli-protocol/src/conn/dispatch.rs
index 562171684..0fb7f28fb 100644
--- a/moli-protocol/src/conn/dispatch.rs
+++ b/moli-protocol/src/conn/dispatch.rs
@@ -840,6 +840,12 @@ impl CdpConnection {
}
},
),
+ "Emulation" if let Some(step) = crate::domains::runtime::try_start_worker_emulation_command_dispatch(self, &cmd) => {
+ Some(match step {
+ crate::domains::runtime::RuntimeCommandTaskStep::Pending(pending) => self.pending_step(PendingCdpCommandDispatchKind::Runtime(pending)),
+ crate::domains::runtime::RuntimeCommandTaskStep::Complete(plan) => self.complete_with_output_plan(command_context, plan, cmd.id, cmd.session_id),
+ })
+ }
"Emulation" => crate::domains::emulation::try_start_emulation_command_dispatch(
self, &cmd,
)
diff --git a/moli-protocol/src/conn/page_state/surfaces.rs b/moli-protocol/src/conn/page_state/surfaces.rs
index 7ba47b389..46f9c1317 100644
--- a/moli-protocol/src/conn/page_state/surfaces.rs
+++ b/moli-protocol/src/conn/page_state/surfaces.rs
@@ -10,6 +10,7 @@ struct SurfaceOverrideInputs {
network_conditions: Option<EmulatedNetworkConditions>,
geolocation_override: Option<EmulatedGeolocationOverrideState>,
max_touch_points: u32,
+ navigator_queries: moli_page_types::NavigatorQueryOverrides,
focus_emulation_enabled: bool,
active_target_surface: bool,
window_document_hidden: bool,
@@ -18,6 +19,11 @@ struct SurfaceOverrideInputs {
impl SurfaceOverrideInputs {
fn from_active(browser_context: &BrowserContext) -> Self {
Self {
+ navigator_queries: browser_context
+ .active_page_target()
+ .devtools_sessions
+ .navigator_emulation
+ .effective(),
network_conditions: browser_context.effective_active_network_conditions(),
geolocation_override: browser_context.effective_active_geolocation_override(),
max_touch_points: browser_context
@@ -52,6 +58,7 @@ impl SurfaceOverrideInputs {
.clone()
.or(default_geolocation_override),
max_touch_points: state.effective_emulation_state.max_touch_points,
+ navigator_queries: state.devtools_sessions.navigator_emulation.effective(),
focus_emulation_enabled: state.effective_emulation_state.focus_emulation_enabled,
active_target_surface: false,
window_document_hidden: false,
@@ -91,6 +98,7 @@ impl SurfaceOverrideInputs {
.network_conditions
.map(|conditions| conditions.navigator_online()),
max_touch_points: self.max_touch_points(),
+ queries: self.navigator_queries,
geolocation: self
.geolocation_override
.as_ref()
diff --git a/moli-protocol/src/conn/state/devtools_session.rs b/moli-protocol/src/conn/state/devtools_session.rs
index f49117358..9822d7ea8 100644
--- a/moli-protocol/src/conn/state/devtools_session.rs
+++ b/moli-protocol/src/conn/state/devtools_session.rs
@@ -63,6 +63,7 @@ pub(crate) struct DevToolsSessionRegistry {
primary_session_id: Option<String>,
states: BTreeMap<DevToolsSessionKey, DevToolsSessionState>,
attached_order: Vec<String>,
+ pub(crate) navigator_emulation: moli_page_types::NavigatorEmulationSessions,
// Live, non-cloneable authority stays outside DevToolsSessionState, whose
// snapshots may outlive attachment. Removing an entry releases its claims.
environment_owners: BTreeMap<DevToolsSessionKey, moli_core::ProcessEnvironmentOwner>,
@@ -77,6 +78,7 @@ impl Default for DevToolsSessionRegistry {
DevToolsSessionState::default(),
)]),
attached_order: Vec::new(),
+ navigator_emulation: Default::default(),
environment_owners: BTreeMap::new(),
}
}
@@ -153,6 +155,7 @@ impl DevToolsSessionRegistry {
pub(crate) fn remove_attached(&mut self, session_id: &str) -> Option<DevToolsSessionState> {
let key = DevToolsSessionKey::Attached(session_id.to_owned());
self.environment_owners.remove(&key);
+ self.navigator_emulation.remove(&key);
let removed = self.states.remove(&key);
if removed.is_some() {
self.attached_order
@@ -178,6 +181,7 @@ impl DevToolsSessionRegistry {
}
self.primary_session_id = None;
self.environment_owners.remove(session_key);
+ self.navigator_emulation.remove(session_key);
Some(std::mem::take(self.primary_mut()))
}
DevToolsSessionKey::Attached(attached_session_id)
@@ -330,6 +334,9 @@ impl DevToolsSessionRegistry {
session_key: &DevToolsSessionKey,
browser_identity_override: Option<DevToolsBrowserIdentityOverride>,
) {
+ if browser_identity_override.is_some() {
+ self.navigator_emulation.session_mut(session_key);
+ }
let state = self.ensure_session(session_key);
state.emulation_session_state.browser_identity_override = browser_identity_override;
}
@@ -405,7 +412,8 @@ impl DevToolsSessionRegistry {
}
pub(crate) fn has_non_default_state(&self) -> bool {
- self.primary() != &DevToolsSessionState::default()
+ !self.navigator_emulation.is_empty()
+ || self.primary() != &DevToolsSessionState::default()
|| !self.attached_is_empty()
|| self
.environment_owners
diff --git a/moli-protocol/src/conn/state/emulation.rs b/moli-protocol/src/conn/state/emulation.rs
index 8a50edc74..95dcd7047 100644
--- a/moli-protocol/src/conn/state/emulation.rs
+++ b/moli-protocol/src/conn/state/emulation.rs
@@ -193,6 +193,7 @@ pub(crate) struct EffectiveTargetEmulationStateDelta {
pub(crate) emulated_media: bool,
pub(crate) emulated_device_metrics: bool,
pub(crate) max_touch_points: bool,
+ pub(crate) navigator_queries: bool,
pub(crate) focus_emulation_enabled: bool,
pub(crate) script_execution_disabled: bool,
}
@@ -203,6 +204,7 @@ impl EffectiveTargetEmulationStateDelta {
|| self.geolocation_override
|| self.emulated_device_metrics
|| self.max_touch_points
+ || self.navigator_queries
|| self.focus_emulation_enabled
}
}
@@ -248,6 +250,7 @@ impl EffectiveTargetEmulationState {
emulated_device_metrics: previous.emulated_device_metrics
!= self.emulated_device_metrics,
max_touch_points: previous.max_touch_points != self.max_touch_points,
+ navigator_queries: false,
focus_emulation_enabled: previous.focus_emulation_enabled
!= self.focus_emulation_enabled,
script_execution_disabled: previous.script_execution_disabled
diff --git a/moli-protocol/src/domains/actions.rs b/moli-protocol/src/domains/actions.rs
index 358991aec..4a1339207 100644
--- a/moli-protocol/src/domains/actions.rs
+++ b/moli-protocol/src/domains/actions.rs
@@ -176,6 +176,7 @@ pub(crate) enum EmulationAction {
#[strum(serialize = "setCPUThrottlingRate")]
SetCpuThrottlingRate,
SetTouchEmulationEnabled,
+ SetHardwareConcurrencyOverride,
SetEmitTouchEventsForMouse,
SetScriptExecutionDisabled,
SetGeolocationOverride,
diff --git a/moli-protocol/src/domains/emulation.rs b/moli-protocol/src/domains/emulation.rs
index aa3c1e6fe..066703268 100644
--- a/moli-protocol/src/domains/emulation.rs
+++ b/moli-protocol/src/domains/emulation.rs
@@ -198,6 +198,9 @@ pub(crate) fn try_start_emulation_command_dispatch(
Some(EmulationAction::SetCpuThrottlingRate) => Some(EmulationCommandTaskStep::Complete(
cpu_throttling_rate_command_output_plan(cmd),
)),
+ Some(EmulationAction::SetHardwareConcurrencyOverride) => {
+ Some(start_hardware_concurrency_override_command(conn, cmd))
+ }
Some(EmulationAction::SetTouchEmulationEnabled) => {
Some(start_touch_emulation_enabled_command(conn, cmd))
}
@@ -319,6 +322,46 @@ fn start_touch_emulation_enabled_command(
};
return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(code, message));
}
+ start_navigator_override_page_command(conn, cmd)
+}
+
+fn start_hardware_concurrency_override_command(
+ conn: &mut CdpConnection,
+ cmd: &Cmd<'_>,
+) -> EmulationCommandTaskStep {
+ let value = match cmd.get_params::<params::SetHardwareConcurrencyOverrideParams>() {
+ Ok(Some(params)) => params.hardware_concurrency,
+ _ => {
+ return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
+ -32602,
+ "InvalidParams",
+ ));
+ }
+ };
+ let Some(value) = u32::try_from(value)
+ .ok()
+ .filter(|value| *value <= i32::MAX as u32)
+ .and_then(std::num::NonZeroU32::new)
+ else {
+ return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
+ -32602,
+ "HardwareConcurrency must be a positive int32",
+ ));
+ };
+ if let Err(message) =
+ conn.update_navigator_queries_for_session_owner(cmd.session_id, |queries| {
+ queries.hardware_concurrency = Some(value);
+ })
+ {
+ return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(-31998, message));
+ }
+ start_navigator_override_page_command(conn, cmd)
+}
+
+fn start_navigator_override_page_command(
+ conn: &mut CdpConnection,
+ cmd: &Cmd<'_>,
+) -> EmulationCommandTaskStep {
let owner_scope = CommandOwnerScope::capture(conn, cmd.session_id);
let overrides = conn
.navigation_load_inputs_for_owner(&owner_scope)
diff --git a/moli-protocol/src/domains/emulation/params.rs b/moli-protocol/src/domains/emulation/params.rs
index 836ac3fc8..565e1ee4b 100644
--- a/moli-protocol/src/domains/emulation/params.rs
+++ b/moli-protocol/src/domains/emulation/params.rs
@@ -2,6 +2,7 @@ pub(super) use chromiumoxide_cdp::cdp::browser_protocol::emulation::{
ClearGeolocationOverrideParams, ClearIdleOverrideParams, SetCpuThrottlingRateParams,
SetDefaultBackgroundColorOverrideParams, SetDeviceMetricsOverrideParams,
SetEmitTouchEventsForMouseParams, SetEmulatedMediaParams, SetFocusEmulationEnabledParams,
- SetGeolocationOverrideParams, SetIdleOverrideParams, SetLocaleOverrideParams,
- SetScriptExecutionDisabledParams, SetTimezoneOverrideParams, SetTouchEmulationEnabledParams,
+ SetGeolocationOverrideParams, SetHardwareConcurrencyOverrideParams, SetIdleOverrideParams,
+ SetLocaleOverrideParams, SetScriptExecutionDisabledParams, SetTimezoneOverrideParams,
+ SetTouchEmulationEnabledParams,
};
diff --git a/moli-protocol/src/domains/emulation/tests/native_navigator.rs b/moli-protocol/src/domains/emulation/tests/native_navigator.rs
index 45d33359a..1a853b3e8 100644
--- a/moli-protocol/src/domains/emulation/tests/native_navigator.rs
+++ b/moli-protocol/src/domains/emulation/tests/native_navigator.rs
@@ -609,3 +609,124 @@ async fn clearing_target_metrics_restores_browser_context_viewport_defaults() {
json!([900, 700, 3])
);
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn hardware_concurrency_override_is_native_and_precedes_document_scripts() {
+ let mut ctx = setup().await;
+ evaluate(&mut ctx, "globalThis.hardwareGetter = Object.getOwnPropertyDescriptor(Navigator.prototype, 'hardwareConcurrency').get; undefined").await;
+ for value in [2, i32::MAX] {
+ expect_session_command_result(
+ &mut ctx,
+ 88100,
+ "SID-1",
+ "Emulation.setHardwareConcurrencyOverride",
+ json!({"hardwareConcurrency":value}),
+ )
+ .await;
+ assert_eq!(evaluate(&mut ctx, r#"[
+ navigator.hardwareConcurrency,
+ hardwareGetter.call(navigator),
+ hardwareGetter === Object.getOwnPropertyDescriptor(Navigator.prototype, 'hardwareConcurrency').get,
+ !Object.hasOwn(navigator, 'hardwareConcurrency')
+ ]"#).await, json!([value, value, true, true]));
+ }
+ for value in [
+ json!(0),
+ json!(-1),
+ json!(2147483648_u64),
+ json!(1.5),
+ json!("2"),
+ json!(null),
+ ] {
+ ctx.process_async(json!({"id":88101,"sessionId":"SID-1", "method":"Emulation.setHardwareConcurrencyOverride", "params":{"hardwareConcurrency":value}})).await;
+ let reply = ctx.take_response_by_id(88101);
+ assert_eq!(reply["error"]["code"], -32602, "{reply}");
+ assert_eq!(
+ evaluate(&mut ctx, "navigator.hardwareConcurrency").await,
+ json!(i32::MAX)
+ );
+ }
+ expect_session_command_result(
+ &mut ctx,
+ 88102,
+ "SID-1",
+ "Emulation.setHardwareConcurrencyOverride",
+ json!({"hardwareConcurrency":3}),
+ )
+ .await;
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<script>globalThis.childReady=new Promise(r=>globalThis.childDone=r);globalThis.initialHardware=navigator.hardwareConcurrency</script><iframe srcdoc='<script>globalThis.initialHardware=navigator.hardwareConcurrency;parent.childDone()</script>'></iframe>", Some("SID-1")
+ ).await;
+ assert_eq!(
+ evaluate(
+ &mut ctx,
+ "childReady.then(() => [initialHardware, frames[0].initialHardware, frames[0].navigator.hardwareConcurrency])"
+ )
+ .await,
+ json!([3, 3, 3])
+ );
+ expect_session_command_result(
+ &mut ctx,
+ 88103,
+ "SID-1",
+ "Emulation.setHardwareConcurrencyOverride",
+ json!({"hardwareConcurrency":5}),
+ )
+ .await;
+ assert_eq!(
+ evaluate(
+ &mut ctx,
+ "[navigator.hardwareConcurrency, frames[0].navigator.hardwareConcurrency]"
+ )
+ .await,
+ json!([5, 5])
+ );
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn hardware_concurrency_sessions_follow_agent_activation_and_detach() {
+ let mut ctx = setup().await;
+ ctx.conn.register_top_level_page_target("TID-1");
+ let baseline = evaluate(&mut ctx, "navigator.hardwareConcurrency").await;
+ let mut sessions = Vec::new();
+ for id in [88110, 88111] {
+ ctx.process_async(json!({"id":id,"method":"Target.attachToTarget", "params":{"targetId":"TID-1","flatten":true}})).await;
+ sessions.push(
+ ctx.take_response_by_id(id)["result"]["sessionId"]
+ .as_str()
+ .unwrap()
+ .to_owned(),
+ );
+ }
+ // The second attached session activates first, through a different Emulation API.
+ expect_session_command_result(
+ &mut ctx,
+ 88112,
+ &sessions[1],
+ "Emulation.setUserAgentOverride",
+ json!({"userAgent":"emulation-query-test"}),
+ )
+ .await;
+ for (session, value, effective) in [(0, 2, 2), (1, 8, 2), (0, 3, 3)] {
+ expect_session_command_result(
+ &mut ctx,
+ 88113,
+ &sessions[session],
+ "Emulation.setHardwareConcurrencyOverride",
+ json!({"hardwareConcurrency":value}),
+ )
+ .await;
+ assert_eq!(
+ evaluate(&mut ctx, "navigator.hardwareConcurrency").await,
+ json!(effective)
+ );
+ }
+ for (session, expected) in [(0, json!(8)), (1, baseline)] {
+ ctx.process_async(json!({"id":88114,"method":"Target.detachFromTarget","params":{"sessionId":sessions[session]}})).await;
+ ctx.expect_result(88114, json!({}), None);
+ assert_eq!(
+ evaluate(&mut ctx, "navigator.hardwareConcurrency").await,
+ expected
+ );
+ }
+}
diff --git a/moli-protocol/src/domains/runtime.rs b/moli-protocol/src/domains/runtime.rs
index 984dda395..a2e335c99 100644
--- a/moli-protocol/src/domains/runtime.rs
+++ b/moli-protocol/src/domains/runtime.rs
@@ -176,6 +176,7 @@ pub(crate) use dispatcher::{
start_console_inspector_command_dispatch, start_debugger_inspector_command_dispatch,
start_heap_profiler_inspector_command_dispatch, start_moli_diagnostics_command_dispatch,
start_profiler_inspector_command_dispatch, try_start_runtime_command_dispatch,
+ try_start_worker_emulation_command_dispatch,
};
pub use dispatcher::{
CompletedDevToolsRuntimeCommandDispatch, DevToolsRuntimeCommandTaskStep,
diff --git a/moli-protocol/src/domains/runtime/dispatcher.rs b/moli-protocol/src/domains/runtime/dispatcher.rs
index 831c88ec3..c854ba3c7 100644
--- a/moli-protocol/src/domains/runtime/dispatcher.rs
+++ b/moli-protocol/src/domains/runtime/dispatcher.rs
@@ -913,6 +913,57 @@ fn runtime_command_awaits_promise(cmd: &Cmd<'_>, action: RuntimeAction) -> bool
.unwrap_or(false)
}
+/// Worker Emulation methods are implemented beside the native Navigator, not
+/// by V8's Inspector. Use the same session transport and completion routing.
+pub(crate) fn try_start_worker_emulation_command_dispatch(
+ conn: &mut CdpConnection,
+ cmd: &Cmd<'_>,
+) -> Option<RuntimeCommandTaskStep> {
+ let action = match cmd.action {
+ "setHardwareConcurrencyOverride" => "Emulation.setHardwareConcurrencyOverride",
+ _ => return None,
+ };
+ let pending = match conn.session_route(cmd.session_id) {
+ Some(
+ CdpSessionRoute::DedicatedWorkerTarget { .. }
+ | CdpSessionRoute::SharedWorkerTarget { .. },
+ ) => start_shared_worker_frontend_inspector_dispatch(
+ conn,
+ cmd,
+ cmd.json.to_owned(),
+ cmd.terminal_response_delivery(),
+ )
+ .map(|pending| PendingRuntimeCommandKind::SharedWorkerInspector {
+ pending,
+ binding_effect: None,
+ }),
+ Some(CdpSessionRoute::ServiceWorkerTarget { .. }) => {
+ start_service_worker_frontend_inspector_dispatch(
+ conn,
+ cmd,
+ cmd.json.to_owned(),
+ cmd.terminal_response_delivery(),
+ )
+ .map(|pending| PendingRuntimeCommandKind::ServiceWorkerInspector { pending })
+ }
+ _ => return None,
+ };
+ Some(match pending {
+ Ok(pending) => RuntimeCommandTaskStep::Pending(Box::new(PendingRuntimeCommandDispatch {
+ command_id: cmd.id,
+ action,
+ owner_scope: CommandOwnerScope::capture(conn, cmd.session_id),
+ object_group: None,
+ release_object_ids: Vec::new(),
+ release_object_group: None,
+ await_promise: false,
+ wait_for_deferred_reply: false,
+ pending,
+ })),
+ Err(message) => RuntimeCommandTaskStep::Complete(CommandOutputPlan::error(-32000, message)),
+ })
+}
+
pub(crate) fn try_start_runtime_command_dispatch(
conn: &mut CdpConnection,
cmd: &Cmd<'_>,
diff --git a/moli-protocol/src/domains/runtime/tests/shared_worker.rs b/moli-protocol/src/domains/runtime/tests/shared_worker.rs
index b3a1df65e..442fa61dc 100644
--- a/moli-protocol/src/domains/runtime/tests/shared_worker.rs
+++ b/moli-protocol/src/domains/runtime/tests/shared_worker.rs
@@ -3658,3 +3658,41 @@ async fn shared_worker_discard_console_entries_is_target_local() {
ctx.sent
);
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn worker_hardware_concurrency_override_is_independent_of_the_page() {
+ let mut ctx = TestContext::new();
+ with_loaded_document_async(&mut ctx, "<!doctype html><body></body>").await;
+ ctx.process_and_wait_for_response_async(json!({"id":99000,"method":"Emulation.setHardwareConcurrencyOverride","params":{"hardwareConcurrency":2}})).await;
+ ctx.expect_result(99000, json!({}), None);
+ let worker = start_attached_shared_worker_session(
+ &mut ctx,
+ 99001,
+ "native-hardware",
+ "onconnect = () => {};",
+ )
+ .await;
+ for (id, session, expected) in [(99010, None, 2), (99011, Some(worker.as_str()), 4)] {
+ ctx.process_and_wait_for_response_async(json!({"id":id,"sessionId":session,"method":"Runtime.evaluate","params":{"expression":"navigator.hardwareConcurrency","returnByValue":true}})).await;
+ assert_eq!(
+ take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
+ json!(expected)
+ );
+ }
+ for (value, valid) in [(3, true), (0, false)] {
+ ctx.process_and_wait_for_response_async(json!({"id":99012,"sessionId":worker,"method":"Emulation.setHardwareConcurrencyOverride","params":{"hardwareConcurrency":value}})).await;
+ let reply = take_response_by_id(&mut ctx, 99012);
+ if valid {
+ assert_eq!(reply["result"], json!({}), "{reply}");
+ } else {
+ assert_eq!(reply["error"]["code"], -32602, "{reply}");
+ }
+ for (id, session, expected) in [(99013, None, 2), (99014, Some(worker.as_str()), 3)] {
+ ctx.process_and_wait_for_response_async(json!({"id":id,"sessionId":session,"method":"Runtime.evaluate","params":{"expression":"navigator.hardwareConcurrency","returnByValue":true}})).await;
+ assert_eq!(
+ take_response_by_id(&mut ctx, id)["result"]["result"]["value"],
+ json!(expected)
+ );
+ }
+ }
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
index 540d7637a..becbc58db 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
@@ -670,12 +670,30 @@ fn navigator_runtime_data_getter_callback<'s>(
_ => {}
}
}
+ if key == "hardwareConcurrency"
+ && let Some(value) = navigator_query_overrides(scope).hardware_concurrency
+ {
+ rv.set_uint32(value.get());
+ return;
+ }
match backing.get(scope, v8str(scope, key).into()) {
Some(value) => rv.set(value),
None => rv.set(v8::undefined(scope).into()),
}
}
+fn navigator_query_overrides(
+ scope: &mut v8::PinScope<'_, '_>,
+) -> moli_page_types::NavigatorQueryOverrides {
+ if let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) {
+ return unsafe { &*host_ptr }.navigator_overrides().queries;
+ }
+ scope
+ .get_slot::<std::rc::Rc<std::cell::RefCell<moli_page_types::NavigatorEmulationSessions>>>()
+ .map(|sessions| sessions.borrow().effective())
+ .unwrap_or_default()
+}
+
fn navigator_cookie_enabled_getter_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
diff --git a/moli-renderer-v8/src/worker/thread/runtime_inspector.rs b/moli-renderer-v8/src/worker/thread/runtime_inspector.rs
index 7ab3f9efc..78eea6769 100644
--- a/moli-renderer-v8/src/worker/thread/runtime_inspector.rs
+++ b/moli-renderer-v8/src/worker/thread/runtime_inspector.rs
@@ -364,6 +364,7 @@ impl v8::inspector::V8InspectorClientImpl for WorkerInspectorClient {
pub(super) struct WorkerRuntimeInspector {
sessions: RefCell<HashMap<String, Rc<v8::inspector::V8InspectorSession>>>,
detached_sessions: RefCell<HashSet<String>>,
+ navigator_emulation: Rc<RefCell<moli_page_types::NavigatorEmulationSessions>>,
inspector: v8::inspector::V8Inspector,
outbound: WorkerInspectorOutbound,
default_context: Rc<RefCell<Option<v8::Global<v8::Context>>>>,
@@ -428,6 +429,10 @@ impl WorkerRuntimeInspector {
) -> Rc<Self> {
let isolate_ptr = unsafe { isolate.as_raw_isolate_ptr() };
let default_context = Rc::new(RefCell::new(None));
+ let navigator_emulation = Rc::new(RefCell::new(
+ moli_page_types::NavigatorEmulationSessions::default(),
+ ));
+ isolate.set_slot(navigator_emulation.clone());
Rc::new_cyclic(|weak_inspector| {
let executor = Rc::new(WorkerInspectorExecutor {
isolate: UnsafeCell::new(isolate_ptr),
@@ -446,6 +451,7 @@ impl WorkerRuntimeInspector {
inspector: v8::inspector::V8Inspector::create(isolate, inspector_client),
sessions: RefCell::new(HashMap::new()),
detached_sessions: RefCell::new(HashSet::new()),
+ navigator_emulation,
outbound: WorkerInspectorOutbound::default(),
default_context,
default_execution_context_id: Cell::new(None),
@@ -492,6 +498,11 @@ impl WorkerRuntimeInspector {
pub(super) fn detach_session(&self, inspector_session_id: Option<&str>) {
let session_key = worker_inspector_session_key(inspector_session_id);
self.sessions.borrow_mut().remove(&session_key);
+ self.navigator_emulation.borrow_mut().remove(
+ &inspector_session_id
+ .map(|id| moli_page_types::DevToolsSessionKey::Attached(id.to_owned()))
+ .unwrap_or(moli_page_types::DevToolsSessionKey::Primary),
+ );
self.detached_sessions.borrow_mut().insert(session_key);
}
@@ -547,19 +558,53 @@ impl WorkerRuntimeInspector {
}
let dispatch_scope = self.outbound.push_dispatch_scope(&session_key, None);
let session = self.ensure_session(&session_key);
- dispatch_with_runtime_defaults(
- &session,
- raw_json,
- &WorkerInspectorSessionOutput {
- outbound: &self.outbound,
- session_key: &session_key,
- },
- )?;
+ if let Some(response) = self.dispatch_emulation(inspector_session_id, raw_json) {
+ if let Some(call_id) = response["id"]
+ .as_i64()
+ .and_then(|id| i32::try_from(id).ok())
+ {
+ self.outbound
+ .push_response_value(&session_key, call_id, response);
+ }
+ } else {
+ dispatch_with_runtime_defaults(
+ &session,
+ raw_json,
+ &WorkerInspectorSessionOutput {
+ outbound: &self.outbound,
+ session_key: &session_key,
+ },
+ )?;
+ }
let messages = dispatch_scope.finish();
self.record_execution_context_state(&messages);
Ok(messages)
}
+ fn dispatch_emulation(&self, session_id: Option<&str>, raw_json: &str) -> Option<Value> {
+ let command: Value = serde_json::from_str(raw_json).ok()?;
+ if command["method"] != "Emulation.setHardwareConcurrencyOverride" {
+ return None;
+ }
+ let value = command["params"]["hardwareConcurrency"]
+ .as_u64()
+ .filter(|value| *value <= i32::MAX as u64)
+ .and_then(|value| std::num::NonZeroU32::new(value as u32));
+ let Some(value) = value else {
+ return Some(
+ json!({"id": command["id"], "error": {"code": -32602, "message": "HardwareConcurrency must be a positive int32"}}),
+ );
+ };
+ let key = session_id
+ .map(|id| moli_page_types::DevToolsSessionKey::Attached(id.to_owned()))
+ .unwrap_or(moli_page_types::DevToolsSessionKey::Primary);
+ self.navigator_emulation
+ .borrow_mut()
+ .session_mut(&key)
+ .hardware_concurrency = Some(value);
+ Some(json!({"id": command["id"], "result": {}}))
+ }
+
pub(super) fn execute_task(&self, isolate: &mut v8::Isolate, task: WorkerInspectorTask) {
// Owner messages for the two Inspector modes use separate queues. An
// already-published notification must also precede DontInterrupt work