Skip to content

Truly independent web browser

LibWeb+LibWebView+WebContent: Implement the WebDriver BiDi input module

Andreas Klinga9b998af8e4f
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index a1e3050d59c..840e4ee7db6 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1037,6 +1037,7 @@ set(SOURCES
WebDriver/Actions.cpp
WebDriver/BiDi/BiDi.cpp
WebDriver/BiDi/BrowsingContext.cpp
+ WebDriver/BiDi/Input.cpp
WebDriver/BiDi/RemoteValue.cpp
WebDriver/BiDi/Script.cpp
WebDriver/Contexts.cpp
diff --git a/Libraries/LibWeb/WebDriver/Actions.cpp b/Libraries/LibWeb/WebDriver/Actions.cpp
index bb165490433..ccc76b8e093 100644
--- a/Libraries/LibWeb/WebDriver/Actions.cpp
+++ b/Libraries/LibWeb/WebDriver/Actions.cpp
@@ -115,8 +115,11 @@ static Optional<ActionObject::Origin> determine_origin(ActionsOptions const& act
}
if (origin->is_object()) {
- if (actions_options.is_element_origin(origin->as_object()))
+ if (actions_options.is_element_origin(origin->as_object())) {
+ if (actions_options.extract_element_origin)
+ return actions_options.extract_element_origin(origin->as_object());
return extract_web_element_reference(origin->as_object());
+ }
}
return {};
diff --git a/Libraries/LibWeb/WebDriver/Actions.h b/Libraries/LibWeb/WebDriver/Actions.h
index f598f7ad8cb..fc75143b4c4 100644
--- a/Libraries/LibWeb/WebDriver/Actions.h
+++ b/Libraries/LibWeb/WebDriver/Actions.h
@@ -120,9 +120,14 @@ struct WEB_API ActionObject {
struct ActionsOptions {
using IsElementOrigin = bool (*)(JsonValue const&);
using GetElementOrigin = ErrorOr<GC::Ref<DOM::Element>, WebDriver::Error> (*)(HTML::BrowsingContext const&, StringView);
+ using ExtractElementOrigin = String (*)(JsonObject const&);
IsElementOrigin is_element_origin { nullptr };
GetElementOrigin get_element_origin { nullptr };
+
+ // NB: Extract the reference passed to the get element origin steps. By default, use a WebDriver classic web
+ // element reference.
+ ExtractElementOrigin extract_element_origin { nullptr };
};
using OnActionsComplete = GC::Ref<GC::Function<void(Web::WebDriver::Response)>>;
diff --git a/Libraries/LibWeb/WebDriver/BiDi/Input.cpp b/Libraries/LibWeb/WebDriver/BiDi/Input.cpp
new file mode 100644
index 00000000000..193e5053037
--- /dev/null
+++ b/Libraries/LibWeb/WebDriver/BiDi/Input.cpp
@@ -0,0 +1,237 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/NeverDestroyed.h>
+#include <AK/RefCounted.h>
+#include <LibCore/EventLoop.h>
+#include <LibGC/Function.h>
+#include <LibGC/Heap.h>
+#include <LibGC/Root.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/Element.h>
+#include <LibWeb/HTML/BrowsingContext.h>
+#include <LibWeb/HTML/LocalNavigable.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
+#include <LibWeb/WebDriver/Actions.h>
+#include <LibWeb/WebDriver/BiDi/Input.h>
+#include <LibWeb/WebDriver/BiDi/RemoteValue.h>
+#include <LibWeb/WebDriver/InputState.h>
+
+namespace Web::WebDriver::BiDi {
+
+// https://w3c.github.io/webdriver-bidi/#is-inputelementorigin
+static bool is_input_element_origin(JsonValue const& object)
+{
+ // input.ElementOrigin = {
+ // type: "element",
+ // element: script.SharedReference
+ // }
+
+ // 1. If object is a map matching the input.ElementOrigin production, return true.
+ // 2. Return false.
+ if (!object.is_object() || object.as_object().get_string("type"sv) != "element"sv)
+ return false;
+ auto element = object.as_object().get_object("element"sv);
+ if (!element.has_value() || !element->get_string("sharedId"sv).has_value())
+ return false;
+ if (auto handle = element->get("handle"sv); handle.has_value() && !handle->is_string())
+ return false;
+ return true;
+}
+
+// NB: The actions keep the shared id of the element an input.ElementOrigin names.
+static String extract_input_element_origin(JsonObject const& origin)
+{
+ return *origin.get_object("element"sv)->get_string("sharedId"sv);
+}
+
+// https://w3c.github.io/webdriver-bidi/#get-element-from-inputelementorigin-steps
+static ErrorOr<GC::Ref<DOM::Element>, Error> get_element_from_input_element_origin(HTML::BrowsingContext const& browsing_context, StringView shared_id)
+{
+ // 1. Assert: origin matches input.ElementOrigin.
+ // 2. Let document be navigable's active document.
+ auto document = browsing_context.active_document();
+
+ // 3. Let reference be origin["element"]
+ JsonObject reference;
+ reference.set("sharedId"sv, shared_id);
+
+ // 4. Let environment settings be the environment settings object whose relevant global object's associated
+ // Document is document.
+ // 5. Let realm be environment settings' realm execution context's Realm component.
+ auto& settings = document->relevant_settings_object();
+
+ // 6. Let element be the result of trying to deserialize remote reference with reference, realm, and session.
+ auto element_value = TRY(deserialize_shared_reference(reference, settings));
+
+ // 7. If element doesn't implement Element return error with error code no such element.
+ auto* element = element_value.is_object() ? Bindings::impl_from<DOM::Element>(&element_value.as_object()) : nullptr;
+ if (!element)
+ return Error::from_code(ErrorCode::NoSuchElement, "The origin is not an element"sv);
+
+ // 8. Return success with data element.
+ return GC::Ref { *element };
+}
+
+static ActionsOptions actions_options()
+{
+ return {
+ .is_element_origin = &is_input_element_origin,
+ .get_element_origin = &get_element_from_input_element_origin,
+ .extract_element_origin = &extract_input_element_origin,
+ };
+}
+
+// NB: The actions running for a command stay alive until they complete.
+struct ActionsInFlight : RefCounted<ActionsInFlight> {
+ AK_ALLOC_WITH_KMALLOC;
+
+ Optional<GC::Root<JS::Cell>> executor;
+ bool completed { false };
+};
+
+// NB: The actions of a top-level traversable wait in its input state's actions queue until the actions before them
+// are dispatched. Commands for a traversable run one at a time here, so that only one of them waits in the queue.
+using InputCommand = Function<void(OnCommandComplete)>;
+static HashMap<HTML::CrossProcessId, Vector<InputCommand>>& input_command_queues()
+{
+ static NeverDestroyed<HashMap<HTML::CrossProcessId, Vector<InputCommand>>> queues;
+ return *queues;
+}
+
+static void run_the_first_input_command(HTML::CrossProcessId top_level_traversable_id)
+{
+ auto& queue = input_command_queues().find(top_level_traversable_id)->value;
+ auto command = move(queue.first());
+ command([top_level_traversable_id](Response) {
+ auto queue = input_command_queues().find(top_level_traversable_id);
+ queue->value.take_first();
+ if (queue->value.is_empty())
+ input_command_queues().remove(queue);
+ else {
+ // NB: An empty action sequence completes before dispatch_actions() dequeues its action queue token.
+ Core::deferred_invoke([top_level_traversable_id] {
+ run_the_first_input_command(top_level_traversable_id);
+ });
+ }
+ });
+}
+
+static void enqueue_an_input_command(HTML::Navigable& navigable, OnCommandComplete on_complete, Function<void(HTML::Navigable&, OnCommandComplete)> steps)
+{
+ auto top_level_traversable_id = navigable.top_level_traversable()->id();
+ auto& queue = input_command_queues().ensure(top_level_traversable_id);
+ queue.append([navigable = GC::make_root(navigable), on_complete = move(on_complete), steps = move(steps)](OnCommandComplete on_command_complete) mutable {
+ steps(*navigable, [on_complete = move(on_complete), on_command_complete = move(on_command_complete)](Response response) {
+ on_complete(move(response));
+ on_command_complete(JsonValue {});
+ });
+ });
+ if (queue.size() == 1)
+ run_the_first_input_command(top_level_traversable_id);
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-input-performActions
+static void perform_actions_steps(HTML::Navigable& navigable, JsonObject const& params, OnCommandComplete on_complete)
+{
+ // 1. Let navigable id be the value of the context field of command parameters.
+ // 2. Let navigable be the result of trying to get a navigable with navigable id.
+ auto* local_navigable = as_if<HTML::LocalNavigable>(navigable);
+ if (!local_navigable || local_navigable->has_been_destroyed() || !local_navigable->active_browsing_context() || !local_navigable->active_document())
+ return on_complete(Error::from_code(ErrorCode::NoSuchFrame, "Browsing context not found"sv));
+
+ HTML::TemporaryExecutionContext execution_context { local_navigable->active_document()->relevant_settings_object() };
+
+ // 3. Let input state be get the input state with session and navigable's top-level traversable.
+ auto& input_state = get_input_state(*navigable.top_level_traversable());
+
+ // 4. Let actions options be a new actions options with the is element origin steps set to is input.ElementOrigin,
+ // and the get element origin steps set to the result of get Element from input.ElementOrigin steps given session.
+ auto options = actions_options();
+
+ // 5. Let actions by tick be the result of trying to extract an action sequence with input state, command parameters,
+ // and actions options.
+ auto actions_by_tick = extract_an_action_sequence(input_state, JsonValue { params }, options);
+ if (actions_by_tick.is_error())
+ return on_complete(actions_by_tick.release_error());
+
+ // 6. Try to dispatch actions with input state, actions by tick, navigable, and actions options.
+ // 7. Return success with data null.
+ auto in_flight = adopt_ref(*new ActionsInFlight);
+ auto on_actions_complete = GC::create_function(GC::Heap::the(), [in_flight, on_complete = move(on_complete)](Response result) {
+ in_flight->completed = true;
+ in_flight->executor.clear();
+ on_complete(move(result));
+ });
+
+ auto executor = dispatch_actions(input_state, actions_by_tick.release_value(), *local_navigable->active_browsing_context(), options, on_actions_complete);
+ if (!in_flight->completed)
+ in_flight->executor = GC::make_root(executor);
+}
+
+void perform_actions(HTML::Navigable& navigable, JsonObject const& params, OnCommandComplete on_complete)
+{
+ enqueue_an_input_command(navigable, move(on_complete), [params](HTML::Navigable& navigable, OnCommandComplete on_complete) {
+ perform_actions_steps(navigable, params, move(on_complete));
+ });
+}
+
+// https://w3c.github.io/webdriver-bidi/#command-input-releaseActions
+static void release_actions_steps(HTML::Navigable& navigable, OnCommandComplete on_complete)
+{
+ // 1. Let navigable id be the value of the context field of command parameters.
+ // 2. Let navigable be the result of trying to get a navigable with navigable id.
+ auto* local_navigable = as_if<HTML::LocalNavigable>(navigable);
+ if (!local_navigable || local_navigable->has_been_destroyed() || !local_navigable->active_browsing_context() || !local_navigable->active_document())
+ return on_complete(Error::from_code(ErrorCode::NoSuchFrame, "Browsing context not found"sv));
+
+ HTML::TemporaryExecutionContext execution_context { local_navigable->active_document()->relevant_settings_object() };
+
+ // 3. Let top-level traversable be navigable's top-level traversable.
+ GC::Ref top_level_traversable = *navigable.top_level_traversable();
+
+ // 4. Let input state be get the input state with session and top-level traversable.
+ auto& input_state = get_input_state(top_level_traversable);
+
+ // 5. Let actions options be a new actions options with the is element origin steps set to is input.ElementOrigin,
+ // and the get element origin steps set to get Element from input.ElementOrigin steps given session.
+ auto options = actions_options();
+
+ // 6. Let undo actions be input state’s input cancel list in reverse order.
+ auto undo_actions = input_state.input_cancel_list;
+ undo_actions.reverse();
+
+ // 7. Try to dispatch tick actions with undo actions, 0, navigable, and actions options.
+ // NB: The actions are dispatched the way WebDriver's Release Actions command dispatches them, which waits for an
+ // action queue token first.
+ wait_for_an_action_queue_token(input_state);
+ input_state.actions_queue.take_first();
+
+ auto in_flight = adopt_ref(*new ActionsInFlight);
+ auto on_actions_complete = GC::create_function(GC::Heap::the(), [in_flight, top_level_traversable, on_complete = move(on_complete)](Response result) {
+ in_flight->completed = true;
+ in_flight->executor.clear();
+
+ // 8. Reset the input state with session and top-level traversable.
+ reset_input_state(top_level_traversable);
+
+ // 9. Return success with data null.
+ on_complete(move(result));
+ });
+
+ auto executor = dispatch_actions(input_state, { move(undo_actions) }, *local_navigable->active_browsing_context(), options, on_actions_complete);
+ if (!in_flight->completed)
+ in_flight->executor = GC::make_root(executor);
+}
+
+void release_actions(HTML::Navigable& navigable, OnCommandComplete on_complete)
+{
+ enqueue_an_input_command(navigable, move(on_complete), [](HTML::Navigable& navigable, OnCommandComplete on_complete) {
+ release_actions_steps(navigable, move(on_complete));
+ });
+}
+
+}
diff --git a/Libraries/LibWeb/WebDriver/BiDi/Input.h b/Libraries/LibWeb/WebDriver/BiDi/Input.h
new file mode 100644
index 00000000000..cf831604d51
--- /dev/null
+++ b/Libraries/LibWeb/WebDriver/BiDi/Input.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/JsonObject.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/WebDriver/BiDi/Script.h>
+
+// https://w3c.github.io/webdriver-bidi/#module-input
+namespace Web::WebDriver::BiDi {
+
+// https://w3c.github.io/webdriver-bidi/#command-input-performActions
+WEB_API void perform_actions(HTML::Navigable&, JsonObject const& params, OnCommandComplete);
+
+// https://w3c.github.io/webdriver-bidi/#command-input-releaseActions
+WEB_API void release_actions(HTML::Navigable&, OnCommandComplete);
+
+}
diff --git a/Libraries/LibWeb/WebDriver/InputState.cpp b/Libraries/LibWeb/WebDriver/InputState.cpp
index fe403232c3c..902544a799a 100644
--- a/Libraries/LibWeb/WebDriver/InputState.cpp
+++ b/Libraries/LibWeb/WebDriver/InputState.cpp
@@ -4,6 +4,8 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/JsonArray.h>
+#include <AK/Math.h>
#include <AK/NeverDestroyed.h>
#include <LibWeb/HTML/Navigable.h>
#include <LibWeb/WebDriver/Actions.h>
@@ -48,4 +50,228 @@ void reset_input_state(HTML::Navigable& top_level_traversable)
browsing_context_input_state_map().remove(top_level_traversable);
}
+// NB: The browser treats this private snapshot as opaque. Sources carry their type and state; cancellation records
+// carry an id, a type (key or pointer), and the fields of the corresponding keyUp or pointerUp action. Pointer
+// positions use raw CSS fixed-point values so that moving between processes does not round their coordinates.
+static StringView pointer_type_name(PointerInputSource::Subtype type)
+{
+ switch (type) {
+ case PointerInputSource::Subtype::Mouse:
+ return "mouse"sv;
+ case PointerInputSource::Subtype::Pen:
+ return "pen"sv;
+ case PointerInputSource::Subtype::Touch:
+ return "touch"sv;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+static Error invalid_input_state()
+{
+ return Error::from_code(ErrorCode::UnknownError, "Invalid internal input state snapshot"sv);
+}
+
+template<typename T>
+static void serialize_optional_field(JsonObject& object, StringView name, Optional<T> const& value)
+{
+ if (value.has_value())
+ object.set(name, *value);
+}
+
+template<typename T>
+static ErrorOr<void, Error> restore_optional_field(JsonObject const& object, StringView name, Optional<T>& output)
+{
+ auto value = object.get(name);
+ if (!value.has_value())
+ return {};
+ Optional<T> number;
+ if constexpr (IsFloatingPoint<T>) {
+ number = value->get_number_with_precision_loss<T>();
+ if (number.has_value() && !isfinite(*number))
+ return invalid_input_state();
+ } else {
+ number = value->get_integer<T>();
+ }
+ if (!number.has_value())
+ return invalid_input_state();
+ output = *number;
+ return {};
+}
+
+JsonObject serialize_input_state(InputState const& input_state)
+{
+ JsonArray sources;
+ for (auto const& [id, source] : input_state.input_state_map) {
+ JsonObject object;
+ object.set("id"sv, id);
+ source.visit(
+ [&](NullInputSource const&) { object.set("type"sv, "none"sv); },
+ [&](KeyInputSource const& key) {
+ object.set("type"sv, "key"sv);
+ JsonArray pressed;
+ for (auto const& value : key.pressed)
+ pressed.must_append(value);
+ object.set("pressed"sv, move(pressed));
+ object.set("alt"sv, key.alt);
+ object.set("ctrl"sv, key.ctrl);
+ object.set("meta"sv, key.meta);
+ object.set("shift"sv, key.shift);
+ },
+ [&](PointerInputSource const& pointer) {
+ object.set("type"sv, "pointer"sv);
+ object.set("pointerType"sv, pointer_type_name(pointer.subtype));
+ object.set("pointerId"sv, pointer.pointer_id);
+ object.set("pressed"sv, to_underlying(pointer.pressed));
+ object.set("x"sv, pointer.position.x().raw_value());
+ object.set("y"sv, pointer.position.y().raw_value());
+ },
+ [&](WheelInputSource const&) { object.set("type"sv, "wheel"sv); });
+ sources.must_append(move(object));
+ }
+
+ JsonArray cancel;
+ for (auto const& action : input_state.input_cancel_list) {
+ JsonObject object;
+ object.set("id"sv, action.id);
+ if (action.subtype == ActionObject::Subtype::KeyUp) {
+ VERIFY(action.type == InputSourceType::Key);
+ object.set("type"sv, "key"sv);
+ object.set("value"sv, action.key_fields().value);
+ } else {
+ VERIFY(action.type == InputSourceType::Pointer && action.subtype == ActionObject::Subtype::PointerUp);
+ auto const& pointer = action.pointer_up_down_fields();
+ object.set("type"sv, "pointer"sv);
+ object.set("pointerType"sv, pointer_type_name(pointer.pointer_type));
+ object.set("button"sv, to_underlying(pointer.button));
+ serialize_optional_field(object, "width"sv, pointer.width);
+ serialize_optional_field(object, "height"sv, pointer.height);
+ serialize_optional_field(object, "pressure"sv, pointer.pressure);
+ serialize_optional_field(object, "tangentialPressure"sv, pointer.tangential_pressure);
+ serialize_optional_field(object, "tiltX"sv, pointer.tilt_x);
+ serialize_optional_field(object, "tiltY"sv, pointer.tilt_y);
+ serialize_optional_field(object, "twist"sv, pointer.twist);
+ serialize_optional_field(object, "altitudeAngle"sv, pointer.altitude_angle);
+ serialize_optional_field(object, "azimuthAngle"sv, pointer.azimuth_angle);
+ }
+ cancel.must_append(move(object));
+ }
+
+ JsonObject snapshot;
+ snapshot.set("sources"sv, move(sources));
+ snapshot.set("cancel"sv, move(cancel));
+ return snapshot;
+}
+
+ErrorOr<void, Error> restore_input_state(HTML::Navigable& top_level_traversable, JsonValue const& snapshot)
+{
+ auto& input_state = get_input_state(top_level_traversable);
+ if (!input_state.actions_queue.is_empty())
+ return Error::from_code(ErrorCode::UnknownError, "Cannot restore input state during action dispatch"sv);
+
+ InputState restored;
+ if (!snapshot.is_null()) {
+ if (!snapshot.is_object())
+ return invalid_input_state();
+ auto sources = snapshot.as_object().get_array("sources"sv);
+ auto cancel = snapshot.as_object().get_array("cancel"sv);
+ if (!sources.has_value() || !cancel.has_value())
+ return invalid_input_state();
+
+ for (auto const& value : sources->values()) {
+ if (!value.is_object())
+ return invalid_input_state();
+ auto const& object = value.as_object();
+ auto id = object.get_string("id"sv);
+ auto type = object.get_string("type"sv);
+ if (!id.has_value() || !type.has_value() || restored.input_state_map.contains(*id))
+ return invalid_input_state();
+ if (*type == "none"sv) {
+ restored.input_state_map.set(*id, NullInputSource {});
+ } else if (*type == "wheel"sv) {
+ restored.input_state_map.set(*id, WheelInputSource {});
+ } else if (*type == "key"sv) {
+ auto pressed = object.get_array("pressed"sv);
+ auto alt = object.get_bool("alt"sv);
+ auto ctrl = object.get_bool("ctrl"sv);
+ auto meta = object.get_bool("meta"sv);
+ auto shift = object.get_bool("shift"sv);
+ if (!pressed.has_value() || !alt.has_value() || !ctrl.has_value() || !meta.has_value() || !shift.has_value())
+ return invalid_input_state();
+ KeyInputSource source;
+ for (auto const& key : pressed->values()) {
+ if (!key.is_string())
+ return invalid_input_state();
+ source.pressed.set(key.as_string());
+ }
+ source.alt = *alt;
+ source.ctrl = *ctrl;
+ source.meta = *meta;
+ source.shift = *shift;
+ restored.input_state_map.set(*id, move(source));
+ } else if (*type == "pointer"sv) {
+ auto pointer_type = object.get_string("pointerType"sv);
+ auto subtype = pointer_type.has_value() ? pointer_input_source_subtype_from_string(*pointer_type) : Optional<PointerInputSource::Subtype> {};
+ auto pointer_id = object.get_u32("pointerId"sv);
+ auto pressed = object.get_u32("pressed"sv);
+ auto x = object.get_i32("x"sv);
+ auto y = object.get_i32("y"sv);
+ if (!subtype.has_value() || !pointer_id.has_value() || !pressed.has_value() || *pressed > 31 || !x.has_value() || !y.has_value())
+ return invalid_input_state();
+ PointerInputSource source { restored, *subtype };
+ source.pointer_id = *pointer_id;
+ source.pressed = static_cast<UIEvents::MouseButton>(*pressed);
+ source.position = { CSSPixels::from_raw(*x), CSSPixels::from_raw(*y) };
+ restored.input_state_map.set(*id, move(source));
+ } else {
+ return invalid_input_state();
+ }
+ }
+
+ for (auto const& value : cancel->values()) {
+ if (!value.is_object())
+ return invalid_input_state();
+ auto const& object = value.as_object();
+ auto id = object.get_string("id"sv);
+ auto type = object.get_string("type"sv);
+ if (!id.has_value() || !type.has_value())
+ return invalid_input_state();
+ // NB: Classic commands can remove a temporary source while its cancellation record remains in the list.
+ if (*type == "key"sv) {
+ auto key = object.get_u32("value"sv);
+ if (!key.has_value())
+ return invalid_input_state();
+ ActionObject action { *id, InputSourceType::Key, ActionObject::Subtype::KeyUp };
+ action.key_fields().value = *key;
+ restored.input_cancel_list.append(move(action));
+ } else if (*type == "pointer"sv) {
+ auto pointer_type = object.get_string("pointerType"sv);
+ auto subtype = pointer_type.has_value() ? pointer_input_source_subtype_from_string(*pointer_type) : Optional<PointerInputSource::Subtype> {};
+ auto button = object.get_u32("button"sv);
+ if (!subtype.has_value() || !button.has_value() || !(*button == 0 || *button == 1 || *button == 2 || *button == 4 || *button == 8 || *button == 16))
+ return invalid_input_state();
+ ActionObject action { *id, InputSourceType::Pointer, ActionObject::Subtype::PointerUp };
+ action.set_pointer_type(*subtype);
+ auto& pointer = action.pointer_up_down_fields();
+ pointer.button = static_cast<UIEvents::MouseButton>(*button);
+ TRY(restore_optional_field(object, "width"sv, pointer.width));
+ TRY(restore_optional_field(object, "height"sv, pointer.height));
+ TRY(restore_optional_field(object, "pressure"sv, pointer.pressure));
+ TRY(restore_optional_field(object, "tangentialPressure"sv, pointer.tangential_pressure));
+ TRY(restore_optional_field(object, "tiltX"sv, pointer.tilt_x));
+ TRY(restore_optional_field(object, "tiltY"sv, pointer.tilt_y));
+ TRY(restore_optional_field(object, "twist"sv, pointer.twist));
+ TRY(restore_optional_field(object, "altitudeAngle"sv, pointer.altitude_angle));
+ TRY(restore_optional_field(object, "azimuthAngle"sv, pointer.azimuth_angle));
+ restored.input_cancel_list.append(move(action));
+ } else {
+ return invalid_input_state();
+ }
+ }
+ }
+
+ input_state.input_state_map = move(restored.input_state_map);
+ input_state.input_cancel_list = move(restored.input_cancel_list);
+ return {};
+}
+
}
diff --git a/Libraries/LibWeb/WebDriver/InputState.h b/Libraries/LibWeb/WebDriver/InputState.h
index cbc4e8c0aa1..88c0b94906b 100644
--- a/Libraries/LibWeb/WebDriver/InputState.h
+++ b/Libraries/LibWeb/WebDriver/InputState.h
@@ -7,6 +7,7 @@
#pragma once
#include <AK/HashMap.h>
+#include <AK/JsonObject.h>
#include <AK/String.h>
#include <AK/Vector.h>
#include <LibWeb/Export.h>
@@ -33,4 +34,8 @@ struct InputState {
WEB_API InputState& get_input_state(HTML::Navigable& top_level_traversable);
WEB_API void reset_input_state(HTML::Navigable& top_level_traversable);
+// Private command-boundary snapshots contain sources and cancellation records, never live action queue tokens.
+WEB_API JsonObject serialize_input_state(InputState const&);
+WEB_API ErrorOr<void, Error> restore_input_state(HTML::Navigable& top_level_traversable, JsonValue const&);
+
}
diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txt
index ffb126ecd59..bc50496b8f8 100644
--- a/Libraries/LibWebCommon/CMakeLists.txt
+++ b/Libraries/LibWebCommon/CMakeLists.txt
@@ -67,6 +67,7 @@ set(SOURCES
WebDriver/Capabilities.cpp
WebDriver/Client.cpp
WebDriver/Error.cpp
+ WebDriver/Input.cpp
WebDriver/Proxy.cpp
WebDriver/Response.cpp
WebDriver/TimeoutsConfiguration.cpp
diff --git a/Libraries/LibWebCommon/WebDriver/Input.cpp b/Libraries/LibWebCommon/WebDriver/Input.cpp
new file mode 100644
index 00000000000..4d0f1ca97b3
--- /dev/null
+++ b/Libraries/LibWebCommon/WebDriver/Input.cpp
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/JsonObject.h>
+#include <LibWebCommon/WebDriver/Input.h>
+
+namespace Web::WebDriver {
+
+Response unwrap_input_command_response(JsonValue const& value, JsonValue& input_state)
+{
+ auto malformed_response = [] {
+ return Error::from_code(ErrorCode::UnknownError, "Malformed input command response"sv);
+ };
+ if (!value.is_object())
+ return malformed_response();
+ auto const& envelope = value.as_object();
+ auto state = envelope.get_object("__webdriver_input_state"sv);
+ if (!state.has_value() || !state->get_array("sources"sv).has_value() || !state->get_array("cancel"sv).has_value())
+ return malformed_response();
+
+ auto result = envelope.get("value"sv);
+ auto error_value = envelope.get("error"sv);
+ if (result.has_value() == error_value.has_value())
+ return malformed_response();
+
+ Response response;
+ if (error_value.has_value()) {
+ if (!error_value->is_object())
+ return malformed_response();
+ auto const& error = error_value->as_object();
+ auto http_status = error.get_u32("httpStatus"sv);
+ auto error_code = error.get_string("error"sv);
+ auto message = error.get_string("message"sv);
+ if (!http_status.has_value() || *http_status < 400 || *http_status > 599 || !error_code.has_value() || error_code->is_empty() || !message.has_value())
+ return malformed_response();
+ Optional<JsonValue> data;
+ if (auto data_value = error.get("data"sv); data_value.has_value())
+ data = *data_value;
+ response = Error { *http_status, *error_code, *message, move(data) };
+ } else {
+ response = JsonValue { *result };
+ }
+
+ input_state = JsonValue { *state };
+ return response;
+}
+
+}
diff --git a/Libraries/LibWebCommon/WebDriver/Input.h b/Libraries/LibWebCommon/WebDriver/Input.h
new file mode 100644
index 00000000000..4c7e55284e0
--- /dev/null
+++ b/Libraries/LibWebCommon/WebDriver/Input.h
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/StringView.h>
+#include <LibWebCommon/WebDriver/Response.h>
+
+namespace Web::WebDriver {
+
+// Commands which share the session's input state, regardless of protocol.
+inline bool is_input_state_command(StringView name)
+{
+ return name == "input.performActions"sv || name == "input.releaseActions"sv
+ || name == "perform_actions"sv || name == "release_actions"sv
+ || name == "element_click"sv || name == "element_send_keys"sv;
+}
+
+// Decode the renderer's private input-command envelope. Commit the snapshot only after the whole reply is valid.
+WEBCOMMON_API Response unwrap_input_command_response(JsonValue const&, JsonValue& input_state);
+
+}
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index 6eb8e152343..0886253a3c1 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -26,6 +26,7 @@
#include <LibWebCommon/Infra/Strings.h>
#include <LibWebCommon/Loader/ContentBlocking.h>
#include <LibWebCommon/WebDriver/Error.h>
+#include <LibWebCommon/WebDriver/Input.h>
#include <LibWebCommon/WebView/SiteIsolation.h>
#include <LibWebView/Application.h>
#include <LibWebView/BookmarkStore.h>
@@ -128,6 +129,7 @@ ViewImplementation::~ViewImplementation()
// A headless parent can own and destroy its child view without the child receiving a browsing-context-close
// notification. Do not strand a WebDriver command which raced with that teardown.
+ discard_webdriver_input_commands();
fail_webdriver_content_commands_after_window_close(m_pending_webdriver_commands);
fail_webdriver_content_commands_after_window_close(m_pending_webdriver_crash_commands);
fail_webdriver_content_commands_after_window_close(m_webdriver_commands_waiting_for_a_document);
@@ -3015,9 +3017,71 @@ void ViewImplementation::run_webdriver_bidi_content_command(u64 command_id, Web:
}
void ViewImplementation::run_webdriver_content_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments, WebDriverProtocol protocol)
+{
+ if (Web::WebDriver::is_input_state_command(name)) {
+ m_webdriver_input_commands.append({ command_id, { navigable_id, name, move(payload), move(arguments), protocol } });
+ if (m_webdriver_input_commands.size() == 1)
+ dispatch_next_webdriver_input_command();
+ return;
+ }
+ dispatch_webdriver_content_command(command_id, navigable_id, name, move(payload), move(arguments), protocol);
+}
+
+void ViewImplementation::discard_webdriver_input_commands(bool process_crashed)
+{
+ auto queued = move(m_webdriver_input_commands);
+ m_webdriver_input_command_running = false;
+ m_webdriver_input_state = JsonValue {};
+ for (auto const& command : queued) {
+ m_pending_webdriver_commands.remove(command.command_id);
+ m_webdriver_commands_waiting_for_a_document.remove(command.command_id);
+ Application::the().complete_webdriver_content_command(command.command_id, Web::WebDriver::Error::from_code(process_crashed ? Web::WebDriver::ErrorCode::UnknownError : error_code_for_a_navigable_that_is_gone(command.command.protocol), process_crashed ? "WebContent crashed while waiting for input"sv : "Browsing context was discarded while waiting for input"sv));
+ }
+}
+
+void ViewImplementation::dispatch_next_webdriver_input_command()
+{
+ if (m_webdriver_input_commands.is_empty() || m_webdriver_input_command_running)
+ return;
+ m_webdriver_input_command_running = true;
+ m_webdriver_input_state_was_lost = false;
+ auto const& queued = m_webdriver_input_commands.first();
+ auto const& command = queued.command;
+ JsonObject envelope;
+ envelope.set("__webdriver_input_state"sv, m_webdriver_input_state);
+ envelope.set("__webdriver_input_payload"sv, command.payload);
+ dispatch_webdriver_content_command(queued.command_id, command.navigable_id, command.name, move(envelope), command.arguments, command.protocol);
+}
+
+void ViewImplementation::complete_webdriver_input_command(u64 command_id, Web::WebDriver::Response response)
+{
+ if (!m_webdriver_input_commands.is_empty() && m_webdriver_input_commands.first().command_id == command_id) {
+ if (!response.is_error()) {
+ // NB: A click's navigation wait can finish in the browser or a replacement page without an envelope.
+ bool is_navigation_completion = m_webdriver_input_commands.first().command.name == "element_click"sv && response.value().is_null();
+ if (!is_navigation_completion) {
+ JsonValue discarded_state;
+ auto& input_state = m_webdriver_input_state_was_lost ? discarded_state : m_webdriver_input_state;
+ response = Web::WebDriver::unwrap_input_command_response(response.value(), input_state);
+ }
+ }
+ if (m_webdriver_input_state_was_lost)
+ response = Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Input state was lost while executing the command"sv);
+ m_webdriver_input_commands.take_first();
+ m_webdriver_input_command_running = false;
+ // The content executor may complete before removing its local action-queue token.
+ Core::deferred_invoke([weak_this = make_weak_ptr()] {
+ if (weak_this)
+ weak_this->dispatch_next_webdriver_input_command();
+ });
+ }
+ Application::the().complete_webdriver_content_command(command_id, move(response));
+}
+
+void ViewImplementation::dispatch_webdriver_content_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments, WebDriverProtocol protocol)
{
if (m_crash_state.has_value() && !m_crash_state->recovery_started) {
- Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "WebContent has crashed"sv));
+ complete_webdriver_input_command(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "WebContent has crashed"sv));
return;
}
@@ -3029,7 +3093,7 @@ void ViewImplementation::run_webdriver_content_command(u64 command_id, Optional<
// A browsing context is said to be no longer open if its navigable has been destroyed.
navigable = traversable().find(*navigable_id);
if (!navigable.has_value()) {
- Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(error_code_for_a_navigable_that_is_gone(protocol), "Window not found"sv));
+ complete_webdriver_input_command(command_id, Web::WebDriver::Error::from_code(error_code_for_a_navigable_that_is_gone(protocol), "Window not found"sv));
return;
}
target = traversable().page_hosting(*navigable);
@@ -3043,7 +3107,7 @@ void ViewImplementation::run_webdriver_content_command(u64 command_id, Optional<
}
if (!target || !target->is_open()) {
- Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(error_code_for_a_navigable_that_is_gone(protocol), "Window not found"sv));
+ complete_webdriver_input_command(command_id, Web::WebDriver::Error::from_code(error_code_for_a_navigable_that_is_gone(protocol), "Window not found"sv));
return;
}
@@ -3064,7 +3128,7 @@ void ViewImplementation::run_webdriver_commands_waiting_for_a_document(Badge<Can
{
auto commands = move(m_webdriver_commands_waiting_for_a_document);
for (auto& [command_id, command] : commands)
- run_webdriver_content_command(command_id, command.navigable_id, command.name, move(command.payload), move(command.arguments), command.protocol);
+ dispatch_webdriver_content_command(command_id, command.navigable_id, command.name, move(command.payload), move(command.arguments), command.protocol);
}
void ViewImplementation::prepare_page_for_navigable(WebContentPage& page)
@@ -3190,6 +3254,24 @@ void ViewImplementation::display_page_changed(RefPtr<WebContentPage> previous_pa
void ViewImplementation::did_lose_page(Badge<CanonicalTraversable>, WebContentPage& page, WebContentProcessLost process_lost)
{
+ bool lost_active_input_host = process_lost == WebContentProcessLost::Yes && !m_webdriver_input_commands.is_empty()
+ && m_webdriver_input_commands.first().command.name != "element_click"sv
+ && m_pending_webdriver_commands.contains(m_webdriver_input_commands.first().command_id)
+ && m_pending_webdriver_commands.get(m_webdriver_input_commands.first().command_id)->page.ptr() == &page;
+ if (lost_active_input_host) {
+ m_webdriver_input_state = JsonValue {};
+ m_webdriver_input_state_was_lost = true;
+ auto queued = move(m_webdriver_input_commands);
+ // Keep an executing command serialized until its host completes or is discarded.
+ if (m_webdriver_input_command_running)
+ m_webdriver_input_commands.append(queued.take_first());
+ for (auto const& command : queued)
+ Application::the().complete_webdriver_content_command(command.command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Input state was lost while waiting for input"sv));
+ auto command_id = m_webdriver_input_commands.first().command_id;
+ m_pending_webdriver_commands.remove(command_id);
+ m_webdriver_commands_waiting_for_a_document.remove(command_id);
+ complete_webdriver_input_command(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "Input host was lost while executing the command"sv));
+ }
Vector<u64> lost_close_preflight_requests;
for (auto const& [request_id, request] : m_pending_close_preflight_requests) {
if (request.page_id == page.id())
@@ -3209,7 +3291,7 @@ void ViewImplementation::did_lose_page(Badge<CanonicalTraversable>, WebContentPa
return false;
if (process_lost == WebContentProcessLost::No && complete_webdriver_content_command_after_navigation(command_id, command))
return true;
- Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(error_code_for_a_navigable_that_is_gone(command.protocol), "Browsing context was discarded while executing the command"sv));
+ complete_webdriver_input_command(command_id, Web::WebDriver::Error::from_code(error_code_for_a_navigable_that_is_gone(command.protocol), "Browsing context was discarded while executing the command"sv));
return true;
});
}
@@ -3235,6 +3317,8 @@ void ViewImplementation::move_pending_webdriver_commands_to_new_host(Badge<Canon
// for that navigation to complete, remains.
bool ViewImplementation::webdriver_content_command_outlives_its_page(StringView name)
{
+ // NB: Element Click only mutates a fresh temporary pointer source and removes that source and its cancel
+ // records before waiting for navigation. The canonical input state remains unchanged across this handoff.
return name == "element_click"sv;
}
@@ -3243,8 +3327,10 @@ bool ViewImplementation::complete_webdriver_content_command_after_navigation(u64
if (!webdriver_content_command_outlives_its_page(command.name))
return false;
- wait_for_webdriver_navigation_completion(Application::the().webdriver_page_load_timeout(), [command_id](Web::WebDriver::Response response) {
- Application::the().complete_webdriver_content_command(command_id, move(response));
+ wait_for_webdriver_navigation_completion(Application::the().webdriver_page_load_timeout(), [weak_this = make_weak_ptr(), command_id](Web::WebDriver::Response response) {
+ if (!weak_this || weak_this->m_webdriver_input_commands.is_empty() || weak_this->m_webdriver_input_commands.first().command_id != command_id)
+ return;
+ weak_this->complete_webdriver_input_command(command_id, move(response));
});
return true;
}
@@ -3255,7 +3341,7 @@ void ViewImplementation::complete_webdriver_content_commands_after_process_repla
if (complete_webdriver_content_command_after_navigation(command_id, command))
continue;
- Application::the().complete_webdriver_content_command(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "WebContent was replaced while executing the command"sv));
+ complete_webdriver_input_command(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "WebContent was replaced while executing the command"sv));
}
}
@@ -3342,19 +3428,20 @@ void ViewImplementation::did_complete_webdriver_content_command(WebContentPage&
// crash handler has obtained the page standing in for the crashed document and started session-history recovery.
if (response.is_error()) {
m_pending_webdriver_crash_commands.remove(command_id);
- Application::the().complete_webdriver_content_command(command_id, move(response));
+ complete_webdriver_input_command(command_id, move(response));
}
return;
}
if (is_running_command(m_pending_webdriver_commands)) {
m_pending_webdriver_commands.remove(command_id);
- Application::the().complete_webdriver_content_command(command_id, move(response));
+ complete_webdriver_input_command(command_id, move(response));
}
}
void ViewImplementation::did_close_browsing_context(Badge<WebContentPage>)
{
+ discard_webdriver_input_commands();
reject_pending_selection_requests();
// https://html.spec.whatwg.org/multipage/document-sequences.html#destroy-a-top-level-traversable
@@ -3763,10 +3850,11 @@ void ViewImplementation::handle_web_content_process_crash()
for (auto& request : pending_user_prompt_requests)
request.value(Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "WebContent crashed while handling user prompts"sv));
+ discard_webdriver_input_commands(true);
auto pending_commands = move(m_pending_webdriver_commands);
auto pending_crash_commands = move(m_pending_webdriver_crash_commands);
for (auto const& command : pending_commands)
- Application::the().complete_webdriver_content_command(command.key, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "WebContent crashed while executing the command"sv));
+ complete_webdriver_input_command(command.key, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnknownError, "WebContent crashed while executing the command"sv));
if (auto* webdriver_bidi = WebDriverBiDi::the())
webdriver_bidi->top_level_traversable_did_crash(traversable());
@@ -3823,7 +3911,7 @@ void ViewImplementation::handle_web_content_process_crash()
}
for (auto const& command : pending_crash_commands)
- Application::the().complete_webdriver_content_command(command.key, JsonValue {});
+ complete_webdriver_input_command(command.key, JsonValue {});
}
void ViewImplementation::respawn_web_content_process_after_crash()
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index bcbf5f5471d..47d92356048 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -997,6 +997,18 @@ protected:
};
HashMap<u64, WebDriverCommandWaitingForADocument> m_webdriver_commands_waiting_for_a_document;
void run_webdriver_content_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments, WebDriverProtocol = WebDriverProtocol::Classic);
+ struct QueuedWebDriverInputCommand {
+ u64 command_id;
+ WebDriverCommandWaitingForADocument command;
+ };
+ Vector<QueuedWebDriverInputCommand> m_webdriver_input_commands;
+ JsonValue m_webdriver_input_state;
+ bool m_webdriver_input_command_running { false };
+ bool m_webdriver_input_state_was_lost { false };
+ void discard_webdriver_input_commands(bool process_crashed = false);
+ void dispatch_webdriver_content_command(u64, Optional<Web::HTML::CrossProcessId>, String const&, JsonValue, Vector<String>, WebDriverProtocol);
+ void complete_webdriver_input_command(u64, Web::WebDriver::Response);
+ void dispatch_next_webdriver_input_command();
static bool webdriver_content_command_outlives_its_page(StringView name);
bool complete_webdriver_content_command_after_navigation(u64 command_id, PendingWebDriverCommand const&);
void complete_webdriver_content_commands_after_process_replacement(HashMap<u64, PendingWebDriverCommand> const&);
diff --git a/Libraries/LibWebView/WebDriverBiDi.cpp b/Libraries/LibWebView/WebDriverBiDi.cpp
index 035e006ef00..b368ed7fab1 100644
--- a/Libraries/LibWebView/WebDriverBiDi.cpp
+++ b/Libraries/LibWebView/WebDriverBiDi.cpp
@@ -941,7 +941,7 @@ void WebDriverBiDi::run_command(u64 command_id, String const& method, JsonValue
return browsing_context_set_viewport(params, move(on_complete));
if (method == "browsingContext.traverseHistory"sv)
return browsing_context_traverse_history(params, move(on_complete));
- if (method.is_one_of("browsingContext.captureScreenshot"sv, "browsingContext.locateNodes"sv))
+ if (method.is_one_of("browsingContext.captureScreenshot"sv, "browsingContext.locateNodes"sv, "input.performActions"sv, "input.releaseActions"sv))
return route_to_navigable(method, params, move(on_complete));
if (method == "script.addPreloadScript"sv)
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index f6b531d3c0e..2fcdcdffabe 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -59,9 +59,11 @@
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
#include <LibWeb/WebDriver/BiDi/BiDi.h>
+#include <LibWeb/WebDriver/InputState.h>
#include <LibWeb/WebDriver/UserPrompt.h>
#include <LibWeb/WebIDL/Promise.h>
#include <LibWebCommon/HTML/NavigationPopulationRequest.h>
+#include <LibWebCommon/WebDriver/Input.h>
#include <LibWebCommon/WebView/Debugger.h>
#include <LibWebCommon/WebView/ZoomLevel.h>
#include <WebContent/ConnectionFromClient.h>
@@ -165,6 +167,8 @@ void PageClient::visit_edges(JS::Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(m_page);
+ for (auto& command : m_webdriver_input_commands)
+ visitor.visit(command.value);
visitor.visit(m_top_level_document_console_client);
for (auto& range : m_pending_text_fragment_generation_ranges)
visitor.visit(range.value);
@@ -2133,6 +2137,8 @@ WebDriverConnection& PageClient::ensure_webdriver_session()
void PageClient::run_webdriver_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments)
{
+ if (Web::WebDriver::is_input_state_command(name) && !prepare_webdriver_input_command(command_id, navigable_id, payload))
+ return;
ensure_webdriver_session().run_command(command_id, navigable_id, name, move(payload), move(arguments));
}
@@ -2141,8 +2147,44 @@ void PageClient::webdriver_did_set_current_browsing_context(u64 command_id, Web:
client().async_webdriver_did_set_current_browsing_context(m_id, command_id, navigable_id);
}
+bool PageClient::prepare_webdriver_input_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, JsonValue& payload)
+{
+ auto navigable = navigable_id.has_value() ? page().navigable_with_id(*navigable_id) : GC::Ptr { page().top_level_traversable() };
+ if (!navigable) {
+ webdriver_command_complete(command_id, Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchFrame, "Browsing context not found"sv));
+ return false;
+ }
+ auto envelope = move(payload).as_object();
+ auto top = navigable->top_level_traversable();
+ auto result = Web::WebDriver::restore_input_state(*top, *envelope.get("__webdriver_input_state"sv));
+ if (result.is_error()) {
+ webdriver_command_complete(command_id, result.release_error());
+ return false;
+ }
+ m_webdriver_input_commands.set(command_id, *top);
+ payload = *envelope.get("__webdriver_input_payload"sv);
+ return true;
+}
+
void PageClient::webdriver_command_complete(u64 command_id, Web::WebDriver::Response response)
{
+ if (auto top = m_webdriver_input_commands.take(command_id); top.has_value()) {
+ JsonObject envelope;
+ envelope.set("__webdriver_input_state"sv, Web::WebDriver::serialize_input_state(Web::WebDriver::get_input_state(**top)));
+ if (response.is_error()) {
+ auto error = response.release_error();
+ JsonObject serialized_error;
+ serialized_error.set("httpStatus"sv, error.http_status);
+ serialized_error.set("error"sv, error.error);
+ serialized_error.set("message"sv, error.message);
+ if (error.data.has_value())
+ serialized_error.set("data"sv, error.data.release_value());
+ envelope.set("error"sv, move(serialized_error));
+ } else {
+ envelope.set("value"sv, response.release_value());
+ }
+ response = JsonValue { move(envelope) };
+ }
client().async_webdriver_command_complete(m_id, command_id, move(response));
}
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index ec0f0ebc033..980440f1f1c 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -62,6 +62,7 @@ public:
void run_webdriver_command(u64 command_id, Optional<Web::HTML::CrossProcessId> navigable_id, String const& name, JsonValue payload, Vector<String> arguments);
void webdriver_did_set_current_browsing_context(u64 command_id, Web::HTML::CrossProcessId navigable_id);
void did_handle_webdriver_mouse_event(u64 request_id);
+ bool prepare_webdriver_input_command(u64, Optional<Web::HTML::CrossProcessId>, JsonValue&);
void webdriver_command_complete(u64 command_id, Web::WebDriver::Response);
void webdriver_bidi_event(Web::HTML::CrossProcessId navigable_id, String const& name, JsonValue params);
void webdriver_bidi_navigation_event(Web::HTML::CrossProcessId navigable_id, StringView name, Optional<Utf16String> const& navigation_id, URL::URL const&);
@@ -424,6 +425,7 @@ private:
Core::AnonymousBuffer m_document_cookie_version_buffer;
RefPtr<WebDriverConnection> m_webdriver;
+ HashMap<u64, GC::Ref<Web::HTML::Navigable>> m_webdriver_input_commands;
HashMap<u64, GC::Ref<GC::Function<void()>>> m_pending_webdriver_mouse_events;
u64 m_next_webdriver_mouse_event_request_id { 0 };
RefPtr<WebUIConnection> m_web_ui;
diff --git a/Services/WebContent/WebDriverBiDi.cpp b/Services/WebContent/WebDriverBiDi.cpp
index 27cec5306c1..8c15883c8e8 100644
--- a/Services/WebContent/WebDriverBiDi.cpp
+++ b/Services/WebContent/WebDriverBiDi.cpp
@@ -14,7 +14,9 @@
#include <LibWeb/Page/Page.h>
#include <LibWeb/WebDriver/BiDi/BiDi.h>
#include <LibWeb/WebDriver/BiDi/BrowsingContext.h>
+#include <LibWeb/WebDriver/BiDi/Input.h>
#include <LibWeb/WebDriver/BiDi/Script.h>
+#include <LibWebCommon/WebDriver/Input.h>
#include <WebContent/ConnectionFromClient.h>
#include <WebContent/PageClient.h>
#include <WebContent/WebDriverBiDi.h>
@@ -78,6 +80,9 @@ static Web::WebDriver::Response create_a_new_top_level_traversable(Web::HTML::Na
void run_webdriver_bidi_command(PageClient& page_client, u64 command_id, Web::HTML::CrossProcessId navigable_id, String const& method, JsonValue params_value)
{
+ if (Web::WebDriver::is_input_state_command(method) && !page_client.prepare_webdriver_input_command(command_id, navigable_id, params_value))
+ return;
+
auto on_complete = [page_client = GC::make_root(page_client), command_id](Web::WebDriver::Response response) {
page_client->webdriver_command_complete(command_id, move(response));
};
@@ -105,6 +110,10 @@ void run_webdriver_bidi_command(PageClient& page_client, u64 command_id, Web::HT
return Web::WebDriver::BiDi::capture_screenshot(*navigable, params, move(on_complete));
if (method == "browsingContext.locateNodes"sv)
return on_complete(Web::WebDriver::BiDi::locate_nodes(*navigable, params));
+ if (method == "input.performActions"sv)
+ return Web::WebDriver::BiDi::perform_actions(*navigable, params, move(on_complete));
+ if (method == "input.releaseActions"sv)
+ return Web::WebDriver::BiDi::release_actions(*navigable, move(on_complete));
if (method == "browsingContext.create"sv)
return on_complete(create_a_new_top_level_traversable(*navigable));
diff --git a/Tests/LibWebCommon/CMakeLists.txt b/Tests/LibWebCommon/CMakeLists.txt
index b76b20f7e24..7657085cb0b 100644
--- a/Tests/LibWebCommon/CMakeLists.txt
+++ b/Tests/LibWebCommon/CMakeLists.txt
@@ -7,6 +7,7 @@ set(TEST_SOURCES
TestSiteCompatibility.cpp
TestStorageEndpoint.cpp
TestStrings.cpp
+ TestWebDriverInputResponse.cpp
)
foreach(source IN LISTS TEST_SOURCES)
diff --git a/Tests/LibWebCommon/TestWebDriverInputResponse.cpp b/Tests/LibWebCommon/TestWebDriverInputResponse.cpp
new file mode 100644
index 00000000000..fa2326b00e9
--- /dev/null
+++ b/Tests/LibWebCommon/TestWebDriverInputResponse.cpp
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/JsonObject.h>
+#include <LibTest/TestCase.h>
+#include <LibWebCommon/WebDriver/Input.h>
+
+static JsonValue parse(StringView json)
+{
+ return MUST(JsonValue::from_string(json));
+}
+
+TEST_CASE(malformed_input_replies_preserve_the_previous_snapshot)
+{
+ auto state = parse(R"({"sources":[],"cancel":[],"previous":true})"sv);
+ auto original_state = state.serialized();
+ StringView const malformed_replies[] = {
+ "null"sv,
+ "[]"sv,
+ "{}"sv,
+ R"({"value":null})"sv,
+ R"({"__webdriver_input_state":null,"value":null})"sv,
+ R"({"__webdriver_input_state":{},"value":null})"sv,
+ R"({"__webdriver_input_state":{"sources":null,"cancel":[]},"value":null})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":null},"value":null})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":null})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":[]})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"error":"invalid argument","message":"bad"}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"httpStatus":400,"message":"bad"}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"httpStatus":400,"error":"invalid argument"}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"httpStatus":"400","error":"invalid argument","message":"bad"}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"httpStatus":400.5,"error":"invalid argument","message":"bad"}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"httpStatus":200,"error":"invalid argument","message":"bad"}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"httpStatus":600,"error":"invalid argument","message":"bad"}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"httpStatus":400,"error":false,"message":"bad"}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"httpStatus":400,"error":"","message":"bad"}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"httpStatus":400,"error":"invalid argument","message":null}})"sv,
+ R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"value":null,"error":{"httpStatus":400,"error":"invalid argument","message":"bad"}})"sv,
+ };
+ for (auto const& json : malformed_replies) {
+ auto response = Web::WebDriver::unwrap_input_command_response(parse(json), state);
+ EXPECT(response.is_error());
+ if (response.is_error()) {
+ EXPECT_EQ(response.error().http_status, 500u);
+ EXPECT_EQ(response.error().error, "unknown error"sv);
+ }
+ EXPECT_EQ(state.serialized(), original_state);
+ }
+
+ // A valid reply following malformed replies still completes and commits its own snapshot.
+ auto response = Web::WebDriver::unwrap_input_command_response(parse(R"({"__webdriver_input_state":{"sources":[],"cancel":[],"next":true},"value":null})"sv), state);
+ EXPECT(!response.is_error());
+ EXPECT(response.value().is_null());
+ EXPECT_EQ(state.as_object().get_bool("next"sv), true);
+ EXPECT(!state.as_object().has("previous"sv));
+}
+
+TEST_CASE(valid_error_reply_commits_state_and_preserves_error_data)
+{
+ JsonValue state;
+ auto response = Web::WebDriver::unwrap_input_command_response(parse(R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"error":{"httpStatus":400,"error":"invalid argument","message":"","data":{"partial":true}}})"sv), state);
+ EXPECT(response.is_error());
+ EXPECT_EQ(response.error().http_status, 400u);
+ EXPECT_EQ(response.error().error, "invalid argument"sv);
+ EXPECT_EQ(response.error().message, ""sv);
+ EXPECT(response.error().data.has_value());
+ EXPECT_EQ(response.error().data->as_object().get_bool("partial"sv), true);
+ EXPECT(state.is_object());
+ EXPECT(state.as_object().get_array("sources"sv).has_value());
+}
+
+TEST_CASE(success_reply_preserves_value_without_interpreting_its_fields)
+{
+ JsonValue state;
+ auto response = Web::WebDriver::unwrap_input_command_response(parse(R"({"__webdriver_input_state":{"sources":[],"cancel":[]},"value":{"error":42}})"sv), state);
+ EXPECT(!response.is_error());
+ EXPECT_EQ(response.value().as_object().get_u32("error"sv), 42u);
+ EXPECT(state.is_object());
+}
diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.py
index f9fb8531280..f351e3924c4 100755
--- a/Tests/LibWebView/test-webdriver-bidi.py
+++ b/Tests/LibWebView/test-webdriver-bidi.py
@@ -130,7 +130,18 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):
server.request_received.set()
if not server.release_response.wait(30):
raise TimeoutError("The test did not release the reload response")
- body = b"<!doctype html><title>Reload target</title>"
+ if self.path == "/input-parent":
+ body = (
+ '<!doctype html><title>Input parent</title><input id="target">'
+ f'<iframe id="input-child" src="http://localhost:{server.server_port}/input-child"></iframe>'
+ ).encode()
+ elif self.path == "/input-child":
+ body = (
+ '<!doctype html><title>Input child</title><input id="target">'
+ f'<a id="navigate-top" target="_top" href="http://localhost:{server.server_port}/input-child">Navigate top</a>'
+ ).encode()
+ else:
+ body = b"<!doctype html><title>Reload target</title>"
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
@@ -162,6 +173,359 @@ def check_screenshot_handles(bidi, context):
assert base64.b64decode(result["data"]).startswith(b"\x89PNG\r\n\x1a\n"), result
+def check_input_handles(bidi, context):
+ element = bidi.evaluate(context, "document.body")["result"]
+ for source_type, action in [
+ ("pointer", {"type": "pointerMove", "x": 0, "y": 0}),
+ ("wheel", {"type": "scroll", "x": 0, "y": 0, "deltaX": 0, "deltaY": 0}),
+ ]:
+ origin = {"type": "element", "element": {"sharedId": element["sharedId"]}}
+ params = {
+ "context": context,
+ "actions": [{"type": source_type, "id": source_type, "actions": [{**action, "origin": origin}]}],
+ }
+ try:
+ for handle in [42, None, {}]:
+ origin["element"]["handle"] = handle
+ result = bidi.response(bidi.send("input.performActions", params))
+ assert result["type"] == "error" and result["error"] == "invalid argument", result
+ for reference in [
+ {"sharedId": element["sharedId"]},
+ {"sharedId": element["sharedId"], "handle": "ignored"},
+ ]:
+ origin["element"] = reference
+ bidi.command("input.performActions", params)
+ finally:
+ bidi.command("input.releaseActions", {"context": context})
+
+
+def check_input_queue(bidi, context):
+ bidi.evaluate(
+ context,
+ "window.inputEvents = []; document.onkeydown = event => inputEvents.push(event.type); document.onkeyup = event => inputEvents.push(event.type)",
+ )
+ try:
+ commands = [
+ bidi.send(
+ "input.performActions",
+ {
+ "context": context,
+ "actions": [{"type": "key", "id": "keyboard", "actions": [{"type": "keyDown", "value": "a"}]}],
+ },
+ ),
+ bidi.send("input.performActions", {"context": context, "actions": []}),
+ bidi.send("input.releaseActions", {"context": context}),
+ ]
+ for command in commands:
+ result = bidi.response(command)
+ assert result["type"] == "success", result
+ assert bidi.evaluate(context, "inputEvents.join(',')")["result"]["value"] == "keydown,keyup"
+ finally:
+ bidi.evaluate(context, "document.onkeydown = document.onkeyup = null; delete window.inputEvents")
+ bidi.command("input.releaseActions", {"context": context})
+
+
+def check_input_cross_context(bidi, connection, session_id, parent, server):
+ parent_url = f"http://127.0.0.1:{server.server_port}/input-parent"
+ child_url = f"http://localhost:{server.server_port}/input-child"
+ bidi.command("browsingContext.navigate", {"context": parent, "url": parent_url, "wait": "complete"})
+ tree = bidi.command("browsingContext.getTree", {"root": parent})["contexts"][0]
+ assert len(tree["children"]) == 1, tree
+ child = tree["children"][0]["context"]
+ assert tree["children"][0]["url"] == child_url, tree
+ other = bidi.command("browsingContext.create", {"type": "tab", "background": True})["context"]
+ bidi.command(
+ "browsingContext.navigate",
+ {"context": other, "url": f"http://127.0.0.1:{server.server_port}/input-child", "wait": "complete"},
+ )
+
+ def focus(target):
+ bidi.command("browsingContext.activate", {"context": parent if target == child else target})
+ if target == child:
+ bidi.evaluate(parent, "document.getElementById('input-child').focus(); 0")
+ result = bidi.evaluate(target, "document.getElementById('target').focus(); document.hasFocus()")
+ assert result["result"]["value"] is True, result
+
+ def events(target):
+ return json.loads(bidi.evaluate(target, "JSON.stringify(inputEvents)")["result"]["value"])
+
+ def clear_events():
+ for target in [parent, child, other]:
+ bidi.evaluate(target, "inputEvents = []; 0")
+
+ def key_sequence(*actions, source_id="shared-keyboard"):
+ return [
+ {"type": "key", "id": source_id, "actions": [{"type": kind, "value": value} for kind, value in actions]}
+ ]
+
+ def keys(target, *actions, source_id="shared-keyboard"):
+ bidi.command(
+ "input.performActions", {"context": target, "actions": key_sequence(*actions, source_id=source_id)}
+ )
+
+ def release(target):
+ bidi.command("input.releaseActions", {"context": target})
+
+ def classic(method, suffix, payload=None):
+ status, result, _ = helpers.request(connection, method, f"/session/{session_id}/{suffix}", payload)
+ assert status == 200, result
+ return result["value"]
+
+ for target in [parent, child, other]:
+ bidi.evaluate(
+ target,
+ """window.inputEvents = [];
+ for (const type of ['keydown', 'keyup']) {
+ document.addEventListener(type, event => inputEvents.push([
+ event.type, event.key, event.shiftKey, event.repeat
+ ]));
+ }""",
+ )
+
+ try:
+ # Releasing from an OOP child must release keys pressed in its parent and reset the shared source.
+ focus(parent)
+ keys(parent, ("keyDown", "a"))
+ assert events(parent) == [["keydown", "a", False, False]], events(parent)
+ focus(child)
+ release(child)
+ assert events(child) == [["keyup", "a", False, False]], (events(parent), events(child))
+ focus(parent)
+ keys(parent, ("keyDown", "a"))
+ assert events(parent) == [["keydown", "a", False, False], ["keydown", "a", False, False]], events(parent)
+ release(parent)
+
+ # Updates from both processes accumulate, including the reverse-order cancel list.
+ clear_events()
+ keys(parent, ("keyDown", "a"))
+ focus(child)
+ keys(child, ("keyDown", "b"))
+ focus(parent)
+ release(parent)
+ assert events(parent) == [
+ ["keydown", "a", False, False],
+ ["keyup", "b", False, False],
+ ["keyup", "a", False, False],
+ ], events(parent)
+ focus(child)
+ keys(child, ("keyDown", "b"))
+ assert events(child) == [["keydown", "b", False, False], ["keydown", "b", False, False]], events(child)
+ release(child)
+
+ # Modifiers cross frame processes, but another top-level tab has an independent input state.
+ clear_events()
+ focus(parent)
+ keys(parent, ("keyDown", "\ue008"))
+ focus(other)
+ keys(other, ("keyDown", "a"))
+ assert events(other) == [["keydown", "a", False, False]], events(other)
+ release(other)
+ focus(child)
+ keys(child, ("keyDown", "a"))
+ assert events(child) == [["keydown", "A", True, False]], events(child)
+ release(child)
+ assert events(child) == [
+ ["keydown", "A", True, False],
+ ["keyup", "A", True, False],
+ ["keyup", "Shift", False, False],
+ ], events(child)
+ focus(parent)
+ keys(parent, ("keyDown", "a"))
+ assert events(parent)[-1] == ["keydown", "a", False, False], events(parent)
+ release(parent)
+
+ # A source ID has one type throughout a tab, including when a different process parses the next command.
+ clear_events()
+ keys(parent, ("keyDown", "c"), source_id="cross-context-source")
+ conflicting = [{"type": "pointer", "id": "cross-context-source", "actions": [{"type": "pause"}]}]
+ result = bidi.response(bidi.send("input.performActions", {"context": child, "actions": conflicting}))
+ assert result["type"] == "error" and result["error"] == "invalid argument", result
+ bidi.command("input.performActions", {"context": other, "actions": conflicting})
+ release(other)
+ focus(child)
+ release(child)
+ assert events(child) == [["keyup", "c", False, False]], events(child)
+
+ # Mutations before a dispatch error must still reach the shared state and its cancel list.
+ clear_events()
+ focus(parent)
+ result = bidi.response(
+ bidi.send(
+ "input.performActions",
+ {
+ "context": parent,
+ "actions": [
+ {
+ "type": "key",
+ "id": "partial-keyboard",
+ "actions": [{"type": "keyDown", "value": "d"}, {"type": "pause"}],
+ },
+ {
+ "type": "pointer",
+ "id": "partial-pointer",
+ "actions": [{"type": "pause"}, {"type": "pointerMove", "x": -1, "y": 0}],
+ },
+ ],
+ },
+ )
+ )
+ assert result["type"] == "error" and result["error"] == "move target out of bounds", result
+ assert events(parent) == [["keydown", "d", False, False]], events(parent)
+ focus(child)
+ release(child)
+ assert events(child) == [["keyup", "d", False, False]], events(child)
+ focus(parent)
+ keys(parent, ("keyDown", "d"), source_id="partial-keyboard")
+ assert events(parent)[-1] == ["keydown", "d", False, False], events(parent)
+ release(parent)
+
+ # Classic actions in the child and BiDi actions in the parent use the same state in both directions.
+ classic("POST", "window", {"handle": parent})
+ classic("POST", "frame", {"id": None})
+ frame = classic("POST", "element", {"using": "css selector", "value": "#input-child"})
+ classic("POST", "frame", {"id": frame})
+ clear_events()
+ focus(parent)
+ keys(parent, ("keyDown", "e"))
+ focus(child)
+ classic("DELETE", "actions")
+ assert events(child) == [["keyup", "e", False, False]], events(child)
+ focus(parent)
+ keys(parent, ("keyDown", "e"), ("keyUp", "e"))
+ assert events(parent)[-2:] == [["keydown", "e", False, False], ["keyup", "e", False, False]], events(parent)
+ clear_events()
+ focus(child)
+ classic("POST", "actions", {"actions": key_sequence(("keyDown", "f"))})
+ focus(parent)
+ release(parent)
+ assert events(parent) == [["keyup", "f", False, False]], events(parent)
+ focus(child)
+ classic("POST", "actions", {"actions": key_sequence(("keyDown", "f"), ("keyUp", "f"))})
+ assert events(child)[-2:] == [["keydown", "f", False, False], ["keyup", "f", False, False]], events(child)
+ release(child)
+ classic("POST", "frame", {"id": None})
+
+ # Wait for a DOM event before submitting the child command during the parent's protocol pause.
+ # The assertions concern event/state order, not how long the pause or the IPC takes.
+ clear_events()
+ focus(parent)
+ bidi.evaluate(
+ parent,
+ "window.inputKeydown = new Promise(resolve => document.addEventListener('keydown', event => resolve(event.key), {once: true})); 0",
+ )
+ barrier = bidi.send(
+ "script.evaluate",
+ {"target": {"context": parent}, "expression": "inputKeydown", "awaitPromise": True},
+ )
+ first = bidi.send(
+ "input.performActions",
+ {
+ "context": parent,
+ "actions": [
+ {
+ "type": "key",
+ "id": "queued-keyboard",
+ "actions": [{"type": "keyDown", "value": "q"}, {"type": "pause", "duration": 1000}],
+ }
+ ],
+ },
+ )
+ result = bidi.response(barrier)
+ assert result["type"] == "success" and result["result"]["result"]["value"] == "q", result
+ focus(child)
+ queued_release = bidi.send("input.releaseActions", {"context": child})
+ for command in [first, queued_release]:
+ result = bidi.response(command)
+ assert result["type"] == "success", result
+ assert events(child) == [["keyup", "q", False, False]], events(child)
+ focus(parent)
+ keys(parent, ("keyDown", "q"), source_id="queued-keyboard")
+ assert events(parent)[-1] == ["keydown", "q", False, False], events(parent)
+ release(parent)
+ finally:
+ classic("POST", "window", {"handle": parent})
+ classic("POST", "frame", {"id": None})
+ for target in [child, parent, other]:
+ release(target)
+ bidi.command("browsingContext.close", {"context": other})
+ bidi.command("browsingContext.activate", {"context": parent})
+ bidi.command("browsingContext.navigate", {"context": parent, "url": "about:blank", "wait": "complete"})
+
+
+def check_input_click_navigation(bidi, connection, session_id, parent, server):
+ parent_url = f"http://127.0.0.1:{server.server_port}/input-parent"
+ child_url = f"http://localhost:{server.server_port}/input-child"
+ replacement_url = f"http://localhost:{server.server_port}/input-child"
+ bidi.command("browsingContext.navigate", {"context": parent, "url": parent_url, "wait": "complete"})
+ tree = bidi.command("browsingContext.getTree", {"root": parent})["contexts"][0]
+ assert len(tree["children"]) == 1, tree
+ child = tree["children"][0]["context"]
+ assert tree["children"][0]["url"] == child_url, tree
+
+ def classic(method, suffix, payload=None):
+ status, result, _ = helpers.request(connection, method, f"/session/{session_id}/{suffix}", payload)
+ assert status == 200, result
+ return result["value"]
+
+ def record_keys():
+ bidi.evaluate(
+ parent,
+ """window.navigationInputEvents = [];
+ for (const type of ['keydown', 'keyup']) {
+ document.addEventListener(type, event => navigationInputEvents.push([
+ event.type, event.key, event.shiftKey, event.repeat
+ ]));
+ }
+ document.getElementById('target').focus();""",
+ )
+
+ def events():
+ return json.loads(bidi.evaluate(parent, "JSON.stringify(navigationInputEvents)")["result"]["value"])
+
+ actions = [{"type": "key", "id": "navigation-keyboard", "actions": [{"type": "keyDown", "value": "g"}]}]
+ bidi.command("browsingContext.activate", {"context": parent})
+ record_keys()
+ bidi.command("input.performActions", {"context": parent, "actions": actions})
+ assert events() == [["keydown", "g", False, False]], events()
+
+ # The localhost OOP child navigates the 127.0.0.1 top-level context to its own site.
+ classic("POST", "window", {"handle": parent})
+ classic("POST", "frame", {"id": None})
+ frame = classic("POST", "element", {"using": "css selector", "value": "#input-child"})
+ classic("POST", "frame", {"id": frame})
+ bidi.evaluate(parent, "document.getElementById('input-child').focus(); 0")
+ bidi.evaluate(child, "document.getElementById('target').focus(); 0")
+ link = classic("POST", "element", {"using": "css selector", "value": "#navigate-top"})
+ subscription = bidi.command("session.subscribe", {"events": ["browsingContext.load"], "contexts": [parent]})[
+ "subscription"
+ ]
+ classic("POST", f"element/{link['element-6066-11e4-a52e-4f735466cecf']}/click", {})
+ # The click succeeds and its actual cross-site navigation completes before checking the retained input state.
+ while True:
+ loaded = bidi.event("browsingContext.load")
+ if loaded["context"] == parent and loaded["url"] == replacement_url:
+ break
+ assert isinstance(loaded["navigation"], str), loaded
+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})
+ result = bidi.evaluate(parent, "document.URL")
+ assert result["result"]["value"] == replacement_url, result
+ tree = bidi.command("browsingContext.getTree", {"root": parent})["contexts"][0]
+ assert tree["context"] == parent and tree["children"] == [], tree
+
+ record_keys()
+ bidi.command("input.releaseActions", {"context": parent})
+ assert events() == [["keyup", "g", False, False]], events()
+ bidi.command("input.performActions", {"context": parent, "actions": actions})
+ assert events()[-1] == ["keydown", "g", False, False], events()
+
+ # The old child no longer exists. Only the stable top-level ID participates in success cleanup;
+ # failures use the enclosing session cleanup, which preserves the original error.
+ classic("POST", "window", {"handle": parent})
+ classic("POST", "frame", {"id": None})
+ bidi.command("input.releaseActions", {"context": parent})
+ bidi.command("browsingContext.navigate", {"context": parent, "url": "about:blank", "wait": "complete"})
+
+
def check_screenshot_lifecycle(bidi, context, cases=("hidden", "hide", "navigate")):
def wait_visibility(target, visible):
expected_hidden = "false" if visible else "true"
@@ -390,7 +754,7 @@ def cleanup_resources(server, webdriver, connection, bidi, session_id, *, primar
raise errors[0]
-def run_test(webdriver_binary):
+def run_test(webdriver_binary, *, input_cross_context_only=False):
with tempfile.TemporaryDirectory(prefix="ladybird-webdriver-bidi-") as profile:
server = ReloadServer()
threading.Thread(target=server.serve_forever, daemon=True).start()
@@ -405,6 +769,7 @@ def run_test(webdriver_binary):
webdriver_binary,
"--headless",
"--expose-internals-object",
+ "--site-isolation=iframe",
f"--profile-path={profile}",
"-l",
"127.0.0.1",
@@ -435,7 +800,18 @@ def run_test(webdriver_binary):
rejected.close()
bidi = BiDiConnection(websocket_url)
context = bidi.command("browsingContext.getTree", {})["contexts"][0]["context"]
+ if input_cross_context_only:
+ check_input_cross_context(bidi, connection, session_id, context, server)
+ check_input_click_navigation(bidi, connection, session_id, context, server)
+ status, payload, _ = helpers.request(connection, "DELETE", f"/session/{session_id}")
+ assert status == 200, payload
+ session_id = None
+ return
check_screenshot_handles(bidi, context)
+ check_input_handles(bidi, context)
+ check_input_queue(bidi, context)
+ check_input_cross_context(bidi, connection, session_id, context, server)
+ check_input_click_navigation(bidi, connection, session_id, context, server)
check_screenshot_lifecycle(bidi, context)
check_screenshot_frame_order(bidi, context)
@@ -619,4 +995,6 @@ def run_test(webdriver_binary):
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("webdriver_binary")
- run_test(parser.parse_args().webdriver_binary)
+ parser.add_argument("--input-cross-context-only", action="store_true")
+ args = parser.parse_args()
+ run_test(args.webdriver_binary, input_cross_context_only=args.input_cross_context_only)