Truly independent web browser
LibWeb: Report WebDriver BiDi network events
Andreas Kling3a8356e98f9d
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex aeed4dc7b1d..e0fbea45c99 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -1034,6 +1034,7 @@ set(SOURCESWebDriver/BiDi/BiDi.cppWebDriver/BiDi/BrowsingContext.cppWebDriver/BiDi/Input.cpp+ WebDriver/BiDi/Network.cppWebDriver/BiDi/RemoteValue.cppWebDriver/BiDi/Script.cppWebDriver/Contexts.cppdiff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 1684d7f15a5..dd83cb11521 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -75,6 +75,7 @@#include <LibWeb/Streams/ReadableStreamDefaultReader.h>#include <LibWeb/Streams/TransformStream.h>#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>+#include <LibWeb/WebDriver/BiDi/Network.h>#include <LibWeb/WebIDL/DOMException.h>#include <LibWeb/WebIDL/ExceptionOrUtils.h>#include <LibWebCommon/Fetch/Infrastructure/DataURL.h>@@ -501,6 +502,9 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam// 1. Let request be fetchParams’s request.auto request = fetch_params.request();+ if (WebDriver::BiDi::g_network_events_enabled)+ WebDriver::BiDi::initialize_network_request(*request);+// 2. Let response be null.GC::Ptr<Infrastructure::Response> response;@@ -888,6 +892,17 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// 1. Let timingInfo be fetchParams’s timing info.auto timing_info = fetch_params.timing_info();+ if (WebDriver::BiDi::g_network_events_enabled) {+ if (response.is_network_error())+ WebDriver::BiDi::network_fetch_error(fetch_params, response.network_error_message().value_or("Network error"_string));+ else {+ auto internal_response = response.unsafe_response();+ WebDriver::BiDi::network_response_started(fetch_params, *internal_response);+ if (fetch_params.request()->is_navigation_request() && !internal_response->request_server_request().has_value())+ WebDriver::BiDi::network_response_completed(fetch_params, *internal_response);+ }+ }+// 2. If response is not a network error and fetchParams’s request’s client is a secure context, then set// timingInfo’s server-timing headers to the result of getting, decoding, and splitting `Server-Timing` from// response’s internal response’s header list.@@ -1000,6 +1015,8 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams constauto process_response_end_of_body = [&fetch_params, &response, setup_report_timing_steps, report_timing_if_appropriate] {// 1-2. (See setup_report_timing_steps above)setup_report_timing_steps();+ if (WebDriver::BiDi::g_network_events_enabled && !response.is_network_error())+ WebDriver::BiDi::network_response_completed(fetch_params, *response.unsafe_response());// 3. Let processResponseEndOfBodyTask be the following steps:auto process_response_end_of_body_task = GC::create_function(GC::Heap::the(), [&fetch_params, &response, report_timing_if_appropriate] {@@ -1032,10 +1049,12 @@ void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const// NB: The network can finish while an unread response body still has buffered bytes. Its timing must not// wait for the consumer to drain the stream.- if (internal_response->body() && fetch_params.request()->initiator_type().has_value()) {- internal_response->body()->when_network_complete(GC::create_function(GC::Heap::the(), [setup_report_timing_steps, report_timing_if_appropriate] {+ if (internal_response->body() && (fetch_params.request()->initiator_type().has_value() || (WebDriver::BiDi::g_network_events_enabled && !fetch_params.request()->is_navigation_request()))) {+ internal_response->body()->when_network_complete(GC::create_function(GC::Heap::the(), [&fetch_params, &response, setup_report_timing_steps, report_timing_if_appropriate] {setup_report_timing_steps();report_timing_if_appropriate();+ if (WebDriver::BiDi::g_network_events_enabled)+ WebDriver::BiDi::network_response_completed(fetch_params, *response.unsafe_response());}));}@@ -1515,6 +1534,8 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParamif (request->service_workers_mode() == Infrastructure::Request::ServiceWorkersMode::All) {// 1. Let requestForServiceWorker be a clone of request.auto request_for_service_worker = request->clone(realm, Infrastructure::Request::BodyCloning::FromSource);+ if (WebDriver::BiDi::g_network_events_enabled)+ request_for_service_worker->set_webdriver_bidi_network_request(request->webdriver_bidi_network_request());// 2. If requestForServiceWorker’s body is non-null, then:if (!request_for_service_worker->body().has<Empty>()) {@@ -1674,6 +1695,8 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam// 6. If internalResponse’s status is a redirect status:if (Infrastructure::is_redirect_status(internal_response->status())) {+ if (WebDriver::BiDi::g_network_events_enabled)+ WebDriver::BiDi::network_response_completed(fetch_params, *internal_response);// 1. If request is a navigation request, then append to request's navigation timing allow values list// given request and internalResponse.if (request->is_navigation_request())@@ -1882,6 +1905,9 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru// 1. Let request be fetchParams’s request.auto request = fetch_params.request();+ if (WebDriver::BiDi::g_network_events_enabled)+ WebDriver::BiDi::initialize_network_request(*request);+// 2. Let httpFetchParams be null.GC::Ptr<Infrastructure::FetchParams const> http_fetch_params;@@ -1926,6 +1952,8 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru// source is null as only a single body is needed in that case. E.g., when request’s body’s source// is null, redirects and authentication will end up failing the fetch.http_request = request->clone(realm, Infrastructure::Request::BodyCloning::FromSource);+ if (WebDriver::BiDi::g_network_events_enabled)+ http_request->set_webdriver_bidi_network_request(request->webdriver_bidi_network_request());// 2. Set httpFetchParams to a copy of fetchParams.auto new_http_fetch_params = Infrastructure::FetchParams::copy(fetch_params);@@ -2179,6 +2207,9 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru}}+ if (WebDriver::BiDi::g_network_events_enabled)+ WebDriver::BiDi::network_before_request_sent(*http_fetch_params);+// 9. If aborted, then return the appropriate network error for fetchParams.if (aborted)return PendingResponse::create(request, Infrastructure::Response::appropriate_network_error(fetch_params));@@ -2204,7 +2235,7 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastruauto returned_pending_response = PendingResponse::create(request);- pending_forward_response->when_loaded([&realm, &fetch_params, request, response, stored_response, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, response_was_null = !response, http_cache](GC::Ref<Infrastructure::Response> resolved_forward_response) mutable {+ pending_forward_response->when_loaded([&realm, &fetch_params, request, response, stored_response, http_request, http_fetch_params, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, include_credentials, response_was_null = !response, http_cache](GC::Ref<Infrastructure::Response> resolved_forward_response) mutable {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' pending_forward_response load callback");if (response_was_null) {auto forward_response = resolved_forward_response;@@ -2245,6 +2276,9 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru// 11. Set response’s URL list to a clone of httpRequest’s URL list.response->set_url_list(http_request->url_list());+ if (WebDriver::BiDi::g_network_events_enabled)+ WebDriver::BiDi::network_response_started(*http_fetch_params, *response);+// 12. If httpRequest’s header list contains `Range`, then set response’s range-requested flag.if (http_request->header_list()->contains("Range"sv))response->set_range_requested(true);@@ -2792,6 +2826,14 @@ GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm& realm, Infrastructure::preflight_response->when_loaded([&request, returned_pending_response, preflight_controller = fetch_params->controller()](GC::Ref<Infrastructure::Response> response) {dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' preflight_response load callback");+ if (WebDriver::BiDi::g_network_events_enabled) {+ auto params = preflight_controller->fetch_params();+ if (response->is_network_error())+ WebDriver::BiDi::network_fetch_error(*params, response->network_error_message().value_or("Preflight failed"_string));+ else+ WebDriver::BiDi::network_response_completed(*params, *response);+ }+// NB: Only the preflight response's headers are read.preflight_controller->stop_body_transport();diff --git a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cppindex 52ffa03eabb..639f04f586e 100644--- a/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/NetworkBodyPump.cpp@@ -11,6 +11,7 @@#include <LibWeb/Fetch/Infrastructure/FetchParams.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>+#include <LibWeb/WebDriver/BiDi/Network.h>namespace Web::Fetch::Fetching {@@ -156,6 +157,8 @@ void NetworkBodyPump::handle_network_complete(Optional<u64> encoded_body_size)void NetworkBodyPump::handle_network_error(StringView error_message){m_network_failed = true;+ if (WebDriver::BiDi::g_network_events_enabled && m_fetch_params)+ WebDriver::BiDi::network_fetch_error(*m_fetch_params, error_message);// A response that died mid-body must not satisfy a sniff waiter with partial bytes.if (m_body)m_body->set_sniff_bytes_failed();diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cppindex 74f7fe03392..4096a456ee6 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp@@ -15,6 +15,7 @@#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/StructuredSerialize.h>#include <LibWeb/Page/RenderingStats.h>+#include <LibWeb/WebDriver/BiDi/Network.h>#include <LibWeb/WebIDL/DOMException.h>namespace Web::Fetch::Infrastructure {@@ -113,6 +114,8 @@ void FetchController::abort(JS::Realm& realm, Optional<JS::Value> error){// 1. Set controller’s state to "aborted".m_state = State::Aborted;+ if (WebDriver::BiDi::g_network_events_enabled && m_fetch_params)+ WebDriver::BiDi::network_fetch_error(*m_fetch_params, "Fetch was aborted"sv);// 2. Let fallbackError be an "AbortError" DOMException.auto fallback_error = WebIDL::AbortError::create("Fetch was aborted"_utf16);@@ -140,6 +143,8 @@ void FetchController::terminate(){// To terminate a fetch controller controller, set controller’s state to "terminated".m_state = State::Terminated;+ if (WebDriver::BiDi::g_network_events_enabled && m_fetch_params)+ WebDriver::BiDi::network_fetch_error(*m_fetch_params, "Fetch was terminated"sv);stop_request();}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cppindex 7c0fc58a4ea..60b39857791 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp@@ -19,6 +19,7 @@#include <LibWeb/HTML/LocalTraversableNavigable.h>#include <LibWeb/HTML/PolicyContainers.h>#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/WebDriver/BiDi/Network.h>namespace Web::Fetch::Infrastructure {@@ -48,6 +49,17 @@ void Request::visit_edges(JS::Cell::Visitor& visitor)visitor.visit(m_reserved_client);visitor.visit(m_traversable_for_user_prompts);visitor.visit(m_pending_responses);+ visitor.visit(m_webdriver_bidi_network_request);+}++GC::Ptr<WebDriver::BiDi::NetworkRequest> Request::webdriver_bidi_network_request() const+{+ return m_webdriver_bidi_network_request;+}++void Request::set_webdriver_bidi_network_request(GC::Ptr<WebDriver::BiDi::NetworkRequest> state)+{+ m_webdriver_bidi_network_request = state;}// https://fetch.spec.whatwg.org/#concept-request-urldiff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.hindex 49839fd5229..9e45049e100 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h@@ -33,6 +33,12 @@#include <LibWebCommon/Fetch/Infrastructure/HTTP/RequestReferrer.h>#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>+namespace Web::WebDriver::BiDi {++class NetworkRequest;++}+namespace Web::Fetch::Infrastructure {class Response;@@ -346,6 +352,9 @@ public:UnixDateTime request_time() const { return m_request_time; }+ GC::Ptr<WebDriver::BiDi::NetworkRequest> webdriver_bidi_network_request() const;+ void set_webdriver_bidi_network_request(GC::Ptr<WebDriver::BiDi::NetworkRequest>);+private:explicit Request(NonnullRefPtr<HTTP::HeaderList>);@@ -558,6 +567,7 @@ private:// Non-standardVector<GC::Ref<Fetching::PendingResponse>> m_pending_responses;UnixDateTime m_request_time;+ GC::Ptr<WebDriver::BiDi::NetworkRequest> m_webdriver_bidi_network_request;};WEB_API StringView request_destination_to_string(Request::Destination);diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cppindex da2013674ae..c342da5f3f9 100644--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp@@ -99,6 +99,7 @@#include <LibWeb/UIEvents/InputTypes.h>#include <LibWeb/UpgradeInsecureRequests/AbstractOperations.h>#include <LibWeb/WebDriver/BiDi/BiDi.h>+#include <LibWeb/WebDriver/BiDi/Network.h>#include <LibWeb/WebIDL/Promise.h>#include <LibWeb/XHR/FormData.h>#include <LibWebCommon/CSS/SystemColor.h>@@ -551,10 +552,36 @@ static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> navif (!response || !response->body())return true;+ JsonValue network_response = navigation_params->webdriver_bidi_network_response;+ if (WebDriver::BiDi::g_network_events_enabled && response->request_server_request().has_value() && !network_response.is_object() && navigation_params->request) {+ RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info = navigation_params->fetch_timing_info;+ if (navigation_params->fetch_controller)+ timing_info = navigation_params->fetch_controller->timing_info();+ if (timing_info) {+ auto metadata = WebDriver::BiDi::network_response_for_navigation(+ *navigation_params->request, *timing_info, *response);+ if (metadata.has_value())+ network_response = metadata.release_value();+ }+ }+ if (auto& state = navigation_params->webdriver_bidi_network_response_state; state) {+ if (state->owner != NavigationResponseNetworkEventState::Owner::Renderer)+ network_response = JsonValue {};+ else+ state->owner = NavigationResponseNetworkEventState::Owner::Download;+ }+ auto report_download_rejected = [&] {+ if (network_response.is_object() && navigation_params->navigable)+ WebDriver::BiDi::network_navigation_response_finished(+ *navigation_params->navigable, network_response.as_object(),+ *response, nullptr, "Navigation download was rejected"sv);+ };+// FIXME: Implement the WebDriver BiDi download will begin/end hooks.// uaAllowsDownloading is currently always true.auto target_allows_downloading = !has_flag(navigation_params->final_sandboxing_flag_set, SandboxingFlagSet::SandboxedDownloads);if (!source_allows_downloading || !target_allows_downloading) {+ report_download_rejected();if (navigation_params->fetch_controller)navigation_params->fetch_controller->stop_fetch();else@@ -565,6 +592,7 @@ static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> navVERIFY(navigation_params->navigable);auto active_window = navigation_params->navigable->active_window();if (!active_window) {+ report_download_rejected();stop_or_resume_response_body_delivery(navigation_params);return true;}@@ -577,7 +605,8 @@ static bool handle_navigation_response_as_download(GC::Ref<NavigationParams> navif (initial_data.has_value() && !initial_data->is_empty() && !response_body_will_be_transferred_in_full)initial_data_buffer = MUST(ByteBuffer::copy(*initial_data));- auto download_id = navigation_params->navigable->page().client().page_did_start_download(navigation_params->navigable->id(), navigation_params->id, download_url, suggested_filename, response_content_length(*response->header_list()), request_server_request->client_id, request_server_request->request_id, move(initial_data_buffer));+ auto download_id = navigation_params->navigable->page().client().page_did_start_download(navigation_params->navigable->id(), navigation_params->id, download_url, suggested_filename, response_content_length(*response->header_list()), request_server_request->client_id, request_server_request->request_id, move(initial_data_buffer),+ move(network_response));if (!download_id.has_value()) {if (navigation_params->fetch_controller)navigation_params->fetch_controller->stop_fetch();@@ -2518,6 +2547,8 @@ static void create_navigation_params_by_fetching(request->set_redirect_mode(Fetch::Infrastructure::Request::RedirectMode::Manual);request->set_replaces_client_id(active_document.relevant_settings_object().id);request->set_mode(Fetch::Infrastructure::Request::Mode::Navigate);+ if (WebDriver::BiDi::g_network_events_enabled)+ WebDriver::BiDi::initialize_network_request(*request, navigable, navigation_id);request->set_referrer(document_state.request_referrer);request->set_referrer_policy(document_state.request_referrer_policy);request->set_policy_container(source_snapshot_params->source_policy_container);diff --git a/Libraries/LibWeb/HTML/NavigationParams.h b/Libraries/LibWeb/HTML/NavigationParams.hindex 165790c6513..cd0a1497a48 100644--- a/Libraries/LibWeb/HTML/NavigationParams.h+++ b/Libraries/LibWeb/HTML/NavigationParams.h@@ -7,6 +7,7 @@#pragma once#include <AK/Optional.h>+#include <AK/RefCounted.h>#include <AK/Utf16String.h>#include <LibGC/CellAllocator.h>#include <LibGC/Ptr.h>@@ -28,6 +29,18 @@namespace Web::HTML {+// NB: Reconstructed response callbacks and download adoption share one terminal-event owner.+struct NavigationResponseNetworkEventState : RefCounted<NavigationResponseNetworkEventState> {+ AK_ALLOC_WITH_KMALLOC;++ enum class Owner {+ Renderer,+ Download,+ Completed,+ };+ Owner owner { Owner::Renderer };+};+// https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigation-paramsstruct NavigationParams : GC::Cell {GC_CELL(NavigationParams, GC::Cell);@@ -53,6 +66,11 @@ struct NavigationParams : GC::Cell {// still sees it.RefPtr<Fetch::Infrastructure::FetchTimingInfo> fetch_timing_info { nullptr };+ // AD-HOC: The terminal network event follows the owner of a transferred+ // response, including a download.+ JsonValue webdriver_bidi_network_response;+ RefPtr<NavigationResponseNetworkEventState> webdriver_bidi_network_response_state;+// AD-HOC: The agent cluster of the agent the UI process obtained for the new Document's window, and that agent// cluster's cross-origin isolation mode.Optional<u64> agent_cluster_id;diff --git a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cppindex 8e41c54ba7c..16a4d573d31 100644--- a/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp+++ b/Libraries/LibWeb/HTML/NavigationParamsDescriptor.cpp@@ -25,6 +25,7 @@#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/Loader/ResourceLoader.h>#include <LibWeb/Streams/ReadableStream.h>+#include <LibWeb/WebDriver/BiDi/Network.h>#include <LibWeb/WebIDL/Promise.h>namespace Web::HTML {@@ -64,7 +65,7 @@ static Optional<ByteBuffer> copy_body_source(Fetch::Infrastructure::Body const&return {};}-static NavigationResponseDescriptor create_navigation_response_descriptor(Fetch::Infrastructure::Response const& response)+static NavigationResponseDescriptor create_navigation_response_descriptor(Fetch::Infrastructure::Response const& response, Fetch::Infrastructure::Request const* request, Fetch::Infrastructure::FetchTimingInfo const* timing_info){Vector<HTTP::Header> headers;headers.ensure_capacity(response.header_list()->headers().size());@@ -84,6 +85,7 @@ static NavigationResponseDescriptor create_navigation_response_descriptor(Fetch:body = body_bytes.release_value();}+ auto network_response = request && timing_info && response.request_server_request().has_value() ? WebDriver::BiDi::network_response_for_navigation(*request, *timing_info, response) : Optional<JsonObject> {};return {.url_list = response.url_list(),.status = response.status(),@@ -95,6 +97,7 @@ static NavigationResponseDescriptor create_navigation_response_descriptor(Fetch:.navigation_timing_allow_values_list = response.navigation_timing_allow_values_list(),.redirect_taint = response.redirect_taint(),.body = move(body),+ .webdriver_bidi_network_response = network_response.has_value() ? JsonValue(network_response.release_value()) : JsonValue {},};}@@ -164,7 +167,7 @@ static NavigationParamsDescriptor create_navigation_params_descriptor(Navigation.id = params.id,.navigable_id = params.navigable->id(),.request = move(request),- .response = create_navigation_response_descriptor(*params.response),+ .response = create_navigation_response_descriptor(*params.response, params.request.ptr(), params.fetch_controller ? params.fetch_controller->timing_info().ptr() : params.fetch_timing_info.ptr()),.fetch_timing_info = move(fetch_timing_info),.coop_enforcement_result = params.coop_enforcement_result,.reserved_environment = move(reserved_environment),@@ -246,7 +249,7 @@ static GC::Ptr<Fetch::Infrastructure::Request> create_navigation_request_from_dereturn request;}-static GC::Ptr<Fetch::Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, NavigationResponseBodyHandle handle, Fetch::Infrastructure::Response& response, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info)+static GC::Ptr<Fetch::Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, LocalNavigable& navigable, NavigationResponseBodyHandle handle, Fetch::Infrastructure::Response& response, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info, Optional<JsonObject> network_response, RefPtr<NavigationResponseNetworkEventState> network_response_state){if (!ResourceLoader::is_initialized() || !ResourceLoader::the().request_client())return {};@@ -281,7 +284,9 @@ static GC::Ptr<Fetch::Infrastructure::Body> adopt_navigation_response_body(JS::Rauto receiver_root = GC::make_root(receiver);auto cross_origin_isolated_capability = Bindings::principal_host_defined_environment_settings_object(realm).cross_origin_isolated_capability();- // NB: receiver_root traces response.+ auto observed_navigable = network_response.has_value() ? GC::Weak<LocalNavigable> { navigable } : GC::Weak<LocalNavigable> {};++ // NB: receiver_root traces response. Observing its navigable must not keep the navigable alive.request->set_unbuffered_request_callbacks([](NonnullRefPtr<HTTP::HeaderList>, Optional<u32>, Optional<String> const&, Optional<Core::ImmutableBytes>, Optional<u64>, Requests::CacheState) { },[receiver_root, &realm](Requests::ResponseData data) {@@ -290,7 +295,7 @@ static GC::Ptr<Fetch::Infrastructure::Body> adopt_navigation_response_body(JS::R[receiver_root](Core::ImmutableBytes data) {receiver_root->set_cached_response_body(move(data));},- [receiver_root, stream = GC::make_root(stream), body = GC::make_root(body), response = GC::Ptr { &response }, timing_info, cross_origin_isolated_capability, &realm](u64, Requests::RequestTimingInfo const& request_timing_info, Optional<Requests::NetworkError> network_error) {+ [receiver_root, stream = GC::make_root(stream), body = GC::make_root(body), response = GC::Ptr { &response }, observed_navigable = move(observed_navigable), timing_info, network_response = move(network_response), network_response_state = move(network_response_state), cross_origin_isolated_capability, &realm](u64, Requests::RequestTimingInfo const& request_timing_info, Optional<Requests::NetworkError> network_error) {TemporaryExecutionContext execution_context { realm, TemporaryExecutionContext::CallbacksEnabled::Yes };if (!network_error.has_value()) {// AD-HOC: Nothing reports timing for a navigation fetch, so record the network phases and end time here@@ -303,9 +308,17 @@ static GC::Ptr<Fetch::Infrastructure::Body> adopt_navigation_response_body(JS::Rbody_info.encoded_size = max(request_timing_info.encoded_body_size, 0);response->set_body_info(move(body_info));receiver_root->handle_network_data(realm, Requests::ResponseData::from_bytes({}), Fetch::Fetching::FetchedDataReceiver::NetworkState::Complete);+ if (network_response.has_value() && observed_navigable && network_response_state->owner == NavigationResponseNetworkEventState::Owner::Renderer) {+ network_response_state->owner = NavigationResponseNetworkEventState::Owner::Completed;+ WebDriver::BiDi::network_navigation_response_finished(*observed_navigable, *network_response, *response, timing_info);+ }return;}+ if (network_response.has_value() && observed_navigable && network_response_state->owner == NavigationResponseNetworkEventState::Owner::Renderer) {+ network_response_state->owner = NavigationResponseNetworkEventState::Owner::Completed;+ WebDriver::BiDi::network_navigation_response_finished(*observed_navigable, *network_response, *response, timing_info, "Transferred navigation response failed"sv);+ }body->set_sniff_bytes_failed();if (stream->is_readable())stream->error(JS::TypeError::create(realm, "Transferred navigation response failed"_utf16));@@ -319,7 +332,7 @@ static GC::Ptr<Fetch::Infrastructure::Body> adopt_navigation_response_body(JS::Rreturn body;}-static ErrorOr<GC::Ref<Fetch::Infrastructure::Response>> create_navigation_response_from_descriptor(JS::Realm& realm, NavigationResponseDescriptor descriptor, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info)+static ErrorOr<GC::Ref<Fetch::Infrastructure::Response>> create_navigation_response_from_descriptor(JS::Realm& realm, LocalNavigable& navigable, NavigationResponseDescriptor descriptor, RefPtr<Fetch::Infrastructure::FetchTimingInfo> timing_info, RefPtr<NavigationResponseNetworkEventState> network_response_state){auto response = descriptor.network_error_message.has_value()? Fetch::Infrastructure::Response::network_error(realm.vm(), move(*descriptor.network_error_message))@@ -336,7 +349,7 @@ static ErrorOr<GC::Ref<Fetch::Infrastructure::Response>> create_navigation_respoif (descriptor.body.has<ByteBuffer>()) {response->set_body(Fetch::Infrastructure::byte_sequence_as_body(realm, descriptor.body.get<ByteBuffer>().bytes()));} else if (descriptor.body.has<NavigationResponseBodyHandle>()) {- auto body = adopt_navigation_response_body(realm, descriptor.body.get<NavigationResponseBodyHandle>(), response, timing_info);+ auto body = adopt_navigation_response_body(realm, navigable, descriptor.body.get<NavigationResponseBodyHandle>(), response, timing_info, descriptor.webdriver_bidi_network_response.is_object() ? Optional<JsonObject>(descriptor.webdriver_bidi_network_response.as_object()) : Optional<JsonObject> {}, move(network_response_state));if (!body)return Error::from_string_literal("Unable to adopt transferred navigation response body");response->set_body(body);@@ -369,7 +382,11 @@ ErrorOr<NavigationParamsVariant> create_navigation_params_from_descriptor(JS::ReRefPtr<Fetch::Infrastructure::FetchTimingInfo> fetch_timing_info;if (params.fetch_timing_info.has_value())fetch_timing_info = create_navigation_fetch_timing_info_from_descriptor(*params.fetch_timing_info);- auto response = TRY(create_navigation_response_from_descriptor(realm, move(params.response), fetch_timing_info));+ auto network_response = params.response.webdriver_bidi_network_response;+ RefPtr<NavigationResponseNetworkEventState> network_response_state;+ if (network_response.is_object())+ network_response_state = adopt_ref(*new NavigationResponseNetworkEventState);+ auto response = TRY(create_navigation_response_from_descriptor(realm, navigable, move(params.response), fetch_timing_info, network_response_state));GC::Ptr<Environment> reserved_environment;if (params.reserved_environment.has_value()) {reserved_environment = Environment::create(@@ -398,6 +415,8 @@ ErrorOr<NavigationParamsVariant> create_navigation_params_from_descriptor(JS::Remove(params.about_base_url),params.user_involvement);navigation_params->fetch_timing_info = fetch_timing_info;+ navigation_params->webdriver_bidi_network_response = move(network_response);+ navigation_params->webdriver_bidi_network_response_state = move(network_response_state);navigation_params->agent_cluster_id = params.agent_cluster_id;navigation_params->agent_cluster_cross_origin_isolation_mode = params.agent_cluster_cross_origin_isolation_mode;navigation_params->new_browsing_context_group_id = params.new_browsing_context_group_id;diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex c56fc81071f..a9a99a3aec7 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -751,7 +751,7 @@ public:virtual void page_did_change_picture_in_picture_player_controls_visibility(bool) { }virtual void page_did_change_active_document_in_top_level_browsing_context(Web::DOM::Document&) { }virtual void page_did_finish_loading(HTML::CrossProcessId, HTML::CrossProcessId) { }- virtual Optional<u64> page_did_start_download(HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data)+ virtual Optional<u64> page_did_start_download(HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response){(void)navigable_id;(void)navigation_id;@@ -760,6 +760,7 @@ public:(void)request_server_client_id;(void)request_server_request_id;(void)initial_data;+ (void)network_response;return {};}virtual Optional<u64> page_did_start_download(URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size)diff --git a/Libraries/LibWeb/WebDriver/BiDi/BiDi.cpp b/Libraries/LibWeb/WebDriver/BiDi/BiDi.cppindex f8505c9fa0a..d947e5ca88c 100644--- a/Libraries/LibWeb/WebDriver/BiDi/BiDi.cpp+++ b/Libraries/LibWeb/WebDriver/BiDi/BiDi.cpp@@ -20,6 +20,7 @@#include <LibWeb/HTML/Window.h>#include <LibWeb/WebDriver/BiDi/BiDi.h>#include <LibWeb/WebDriver/BiDi/BindingsGlue.h>+#include <LibWeb/WebDriver/BiDi/Network.h>#include <LibWeb/WebDriver/BiDi/RemoteValue.h>#include <LibWeb/WebDriver/BiDi/Script.h>@@ -64,6 +65,7 @@ void set_session_state(BiDiSessionState session_state)state() = move(session_state);g_is_active = state().is_active;+ g_network_events_enabled = g_is_active && any_of(state().enabled_events, [](auto const& name) { return name.starts_with_bytes("network."sv); });// NB: The documents that existed before the session started run the console steps from now on.if (g_is_active && !was_active)diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp b/Libraries/LibWeb/WebDriver/BiDi/Network.cppnew file mode 100644index 00000000000..dec76dd78b0--- /dev/null+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp@@ -0,0 +1,377 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Base64.h>+#include <AK/GenericLexer.h>+#include <AK/JsonArray.h>+#include <AK/Random.h>+#include <AK/StringBuilder.h>+#include <AK/Time.h>+#include <LibGC/Heap.h>+#include <LibRequests/Request.h>+#include <LibWeb/DOM/Document.h>+#include <LibWeb/Fetch/Infrastructure/FetchParams.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>+#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>+#include <LibWeb/HTML/LocalNavigable.h>+#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Window.h>+#include <LibWeb/HighResolutionTime/TimeOrigin.h>+#include <LibWeb/WebDriver/BiDi/BiDi.h>+#include <LibWeb/WebDriver/BiDi/Network.h>++namespace Web::WebDriver::BiDi {++using namespace Fetch::Infrastructure;++GC_DEFINE_ALLOCATOR(NetworkRequest);++bool g_network_events_enabled { false };++NetworkRequest::NetworkRequest()+ : id(generate_random_uuid())+{+}++void initialize_network_request(Request& request, GC::Ptr<HTML::Navigable> navigable, Optional<Utf16String> const& navigation)+{+ if (!g_network_events_enabled || request.webdriver_bidi_network_request())+ return;+ auto state = GC::Heap::the().allocate<NetworkRequest>();+ if (navigable) {+ state->navigable = navigable;+ } else if (auto client = request.client()) {+ if (auto* window = HTML::window_from_global_object(client->global_object()))+ state->navigable = window->associated_document().navigable();+ }+ if (navigation.has_value())+ state->navigation = navigation->to_utf8();+ request.set_webdriver_bidi_network_request(state);+}++// https://w3c.github.io/webdriver-bidi/#serialize-protocol-bytes+static JsonObject serialize_protocol_bytes(StringView bytes)+{+ JsonObject result;+ if (auto string = String::from_utf8(bytes); !string.is_error()) {+ result.set("type"sv, "string"sv);+ result.set("value"sv, string.release_value());+ } else {+ result.set("type"sv, "base64"sv);+ result.set("value"sv, MUST(encode_base64(bytes.bytes())));+ }+ return result;+}++// https://w3c.github.io/webdriver-bidi/#serialize-header+static JsonArray serialize_headers(HTTP::HeaderList const& headers)+{+ JsonArray result;+ for (auto const& header : headers) {+ JsonObject entry;+ // 1. Let name be the result of UTF-8 decode with name bytes.+ entry.set("name"sv, String::from_utf8_with_replacement_character(header.name.view()));+ // 2. Let value be serialize protocol bytes with value bytes.+ entry.set("value"sv, serialize_protocol_bytes(header.value));+ MUST(result.append(move(entry)));+ }+ return result;+}++static u64 headers_size(HTTP::HeaderList const& headers)+{+ u64 size = 2;+ for (auto const& header : headers)+ size += header.name.length() + header.value.length() + 4;+ return size;+}++// https://w3c.github.io/webdriver-bidi/#get-the-fetch-timings+static JsonObject get_the_fetch_timings(FetchTimingInfo const& timings, Optional<double> time_origin, double epoch_origin)+{+ JsonObject result;+ result.set("timeOrigin"sv, epoch_origin);+ auto convert = [&](double time) {+ if (!time_origin.has_value() || time == 0)+ return 0.0;+ return HighResolutionTime::coarsen_time(time) - *time_origin;+ };+ auto connection = timings.final_connection_timing_info().value_or(ConnectionTimingInfo {});+ result.set("requestTime"sv, convert(timings.start_time()));+ result.set("redirectStart"sv, convert(timings.redirect_start_time()));+ result.set("redirectEnd"sv, convert(timings.redirect_end_time()));+ result.set("fetchStart"sv, convert(timings.post_redirect_start_time()));+ result.set("dnsStart"sv, convert(connection.domain_lookup_start_time));+ result.set("dnsEnd"sv, convert(connection.domain_lookup_end_time));+ result.set("connectStart"sv, convert(connection.connection_start_time));+ result.set("connectEnd"sv, convert(connection.connection_end_time));+ result.set("tlsStart"sv, convert(connection.secure_connection_start_time));+ result.set("requestStart"sv, convert(timings.final_network_request_start_time()));+ result.set("responseStart"sv, convert(timings.final_network_response_start_time()));+ result.set("responseEnd"sv, convert(timings.end_time()));+ return result;+}++static JsonObject get_the_fetch_timings(Request const& request, FetchTimingInfo const& timings)+{+ auto client = request.client();+ return get_the_fetch_timings(timings, client ? Optional<double>(client->time_origin()) : Optional<double> {}, client ? HighResolutionTime::get_time_origin_timestamp(client->global_object()) : 0);+}++// https://w3c.github.io/webdriver-bidi/#get-the-request-data+static JsonObject get_the_request_data(Request const& request, FetchTimingInfo const& timings)+{+ JsonObject result;+ result.set("request"sv, request.webdriver_bidi_network_request()->id);+ result.set("url"sv, request.current_url().serialize());+ result.set("method"sv, MUST(String::from_utf8(request.method().view())));+ result.set("headers"sv, serialize_headers(request.header_list()));+ // FIXME: Include the cookies attached by RequestServer.+ result.set("cookies"sv, JsonArray {});+ result.set("headersSize"sv, headers_size(request.header_list()));+ JsonValue body_size;+ if (auto const* bytes = request.body().get_pointer<ByteBuffer>())+ body_size = bytes->size();+ else if (auto const* body = request.body().get_pointer<GC::Ref<Body>>(); body && (*body)->length().has_value())+ body_size = *(*body)->length();+ result.set("bodySize"sv, move(body_size));+ result.set("destination"sv, request.destination().has_value() ? request_destination_to_string(*request.destination()) : ""sv);+ result.set("initiatorType"sv, request.initiator_type().has_value() ? JsonValue(initiator_type_to_string(*request.initiator_type()).to_utf16_string().to_utf8()) : JsonValue {});+ result.set("timings"sv, get_the_fetch_timings(request, timings));+ return result;+}++// https://w3c.github.io/webdriver-bidi/#extract-challenges+static JsonArray extract_challenges(Response const& response)+{+ JsonArray challenges;+ auto header_name = response.status() == 407 ? "Proxy-Authenticate"sv : "WWW-Authenticate"sv;+ for (auto const& header : *response.header_list()) {+ if (!header.name.equals_ignoring_ascii_case(header_name))+ continue;+ GenericLexer lexer(header.value.view());+ Optional<JsonObject> challenge;+ while (!lexer.is_eof()) {+ lexer.ignore_while([](char ch) { return ch == ' ' || ch == '\t' || ch == ','; });+ auto name = lexer.consume_while([](char ch) { return HTTP::is_header_name({ &ch, 1 }); });+ lexer.ignore_while([](char ch) { return ch == ' ' || ch == '\t'; });+ if (name.is_empty()) {+ if (!lexer.is_eof())+ lexer.ignore();+ continue;+ }+ if (!lexer.consume_specific('=')) {+ if (challenge.has_value())+ MUST(challenges.append(challenge.release_value()));+ challenge = JsonObject {};+ challenge->set("scheme"sv, MUST(String::from_utf8(name)));+ challenge->set("realm"sv, ""sv);+ continue;+ }+ lexer.ignore_while([](char ch) { return ch == ' ' || ch == '\t'; });+ StringBuilder value;+ if (lexer.consume_specific('"')) {+ while (!lexer.is_eof() && lexer.peek() != '"') {+ if (lexer.consume_specific('\\') && lexer.is_eof())+ break;+ value.append(lexer.consume());+ }+ lexer.consume_specific('"');+ } else {+ value.append(lexer.consume_until([](char ch) { return ch == ',' || ch == ' ' || ch == '\t'; }));+ }+ if (challenge.has_value() && name.equals_ignoring_ascii_case("realm"sv))+ challenge->set("realm"sv, String::from_utf8_with_replacement_character(value.string_view()));+ }+ if (challenge.has_value())+ MUST(challenges.append(challenge.release_value()));+ }+ return challenges;+}++// https://w3c.github.io/webdriver-bidi/#get-the-response-data+static JsonObject get_the_response_data(Response const& response, FetchTimingInfo const& timings)+{+ JsonObject result;+ auto url = response.url();+ result.set("url"sv, url.has_value() ? url->serialize() : String {});+ ByteString protocol;+ if (timings.final_connection_timing_info().has_value())+ protocol = timings.final_connection_timing_info()->alpn_negotiated_protocol;+ if (protocol.is_empty()) {+ if (auto const& network_request = response.request_server_request(); network_request.has_value() && network_request->request)+ protocol = network_request->request->http_version();+ }+ if (protocol.is_empty())+ protocol = url.has_value() ? url->scheme().to_byte_string() : ByteString {};+ if (protocol == "http/2"sv)+ protocol = "h2"sv;+ else if (protocol == "http/3"sv)+ protocol = "h3"sv;+ result.set("protocol"sv, MUST(String::from_utf8(protocol.view())));+ result.set("status"sv, response.status());+ // INTEROP: Data URL responses have an "OK" status text in Chromium and Firefox.+ auto status_text = response.status_message();+ if (status_text.is_empty() && url.has_value() && url->scheme() == "data"sv)+ status_text = "OK"sv;+ result.set("statusText"sv, String::from_utf8_with_replacement_character(status_text.view()));+ result.set("fromCache"sv, response.cache_state() == Response::CacheState::Local);+ result.set("headers"sv, serialize_headers(response.header_list()));+ auto mime_type = extract_mime_type(response.header_list());+ result.set("mimeType"sv, mime_type.has_value() ? mime_type->essence() : String {});+ auto body_info = response.body_info();+ if (auto body = response.body(); body && body->source().has_value() && body_info.decoded_size == 0) {+ body_info.decoded_size = body->source()->size();+ if (url.has_value() && url->scheme() == "data"sv)+ body_info.encoded_size = body_info.decoded_size;+ }+ auto header_size = headers_size(response.header_list());+ result.set("bytesReceived"sv, body_info.encoded_size + header_size);+ result.set("headersSize"sv, header_size);+ result.set("bodySize"sv, body_info.encoded_size);+ JsonObject content;+ content.set("size"sv, body_info.decoded_size);+ result.set("content"sv, move(content));+ if (response.status() == 401 || response.status() == 407)+ result.set("authChallenges"sv, extract_challenges(response));+ return result;+}++// https://w3c.github.io/webdriver-bidi/#process-a-network-event+static JsonObject process_a_network_event(Request const& request, FetchTimingInfo const& timing_info)+{+ auto state = request.webdriver_bidi_network_request();+ JsonObject params;+ params.set("context"sv, navigable_id(*state->navigable));+ params.set("userContext"sv, "default"sv);+ params.set("isBlocked"sv, false);+ params.set("navigation"sv, state->navigation.has_value() ? JsonValue(*state->navigation) : JsonValue {});+ params.set("redirectCount"sv, request.redirect_count());+ JsonObject request_data;+ if (auto cached = state->request_data.get(request.redirect_count()); cached.has_value())+ request_data = *cached;+ else+ request_data = get_the_request_data(request, timing_info);+ request_data.set("timings"sv, get_the_fetch_timings(request, timing_info));+ params.set("request"sv, move(request_data));+ params.set("timestamp"sv, UnixDateTime::now().milliseconds_since_epoch());+ return params;+}++// https://w3c.github.io/webdriver-bidi/#webdriver-bidi-before-request-sent+void network_before_request_sent(FetchParams const& fetch_params)+{+ auto request = fetch_params.request();+ initialize_network_request(*request);+ auto state = request->webdriver_bidi_network_request();+ if (!state || !state->navigable || state->before_request_sent.contains(request->redirect_count()))+ return;+ // 4. Let redirect count be request's redirect count.+ // 5. Add redirect count to before request sent map[request].+ state->before_request_sent.set(request->redirect_count());+ state->request_data.set(request->redirect_count(), get_the_request_data(*request, *fetch_params.timing_info()));+ if (is_event_enabled("network.beforeRequestSent"sv))+ emit_event(*state->navigable, "network.beforeRequestSent"_string, process_a_network_event(*fetch_params.request(), *fetch_params.timing_info()));+}++// https://w3c.github.io/webdriver-bidi/#event-network-responseStarted+void network_response_started(FetchParams const& fetch_params, Response& response)+{+ network_before_request_sent(fetch_params);+ auto request = fetch_params.request();+ auto state = request->webdriver_bidi_network_request();+ if (!state || !state->navigable || state->response_started.contains(request->redirect_count()) || response.is_network_error())+ return;+ state->response_started.set(request->redirect_count());+ // 5. Let sessions be the set of sessions for which an event is enabled given "network.responseStarted" and related navigables.+ if (is_event_enabled("network.responseStarted"sv)) {+ auto params = process_a_network_event(*fetch_params.request(), *fetch_params.timing_info());+ params.set("response"sv, get_the_response_data(response, *fetch_params.timing_info()));+ emit_event(*state->navigable, "network.responseStarted"_string, move(params));+ }+}++// https://w3c.github.io/webdriver-bidi/#event-network-responseCompleted+void network_response_completed(FetchParams const& fetch_params, Response const& response)+{+ auto request = fetch_params.request();+ auto state = request->webdriver_bidi_network_request();+ if (!state || !state->navigable || (state->completed.contains(request->redirect_count()) || state->transferred.contains(request->redirect_count())))+ return;+ state->completed.set(request->redirect_count());+ if (!fetch_params.timing_info()->end_time())+ fetch_params.timing_info()->set_end_time(HighResolutionTime::unsafe_shared_current_time());+ // 5. Let sessions be the set of sessions for which an event is enabled given "network.responseCompleted" and related navigables.+ if (!is_event_enabled("network.responseCompleted"sv))+ return;+ auto params = process_a_network_event(*fetch_params.request(), *fetch_params.timing_info());+ params.set("response"sv, get_the_response_data(response, *fetch_params.timing_info()));+ emit_event(*state->navigable, "network.responseCompleted"_string, move(params));+}++// https://w3c.github.io/webdriver-bidi/#event-network-fetchError+void network_fetch_error(FetchParams const& fetch_params, StringView error_text)+{+ // 1. If before request sent map[request] does not contain request's redirect count, then run the WebDriver BiDi before request sent steps with request.+ network_before_request_sent(fetch_params);+ auto request = fetch_params.request();+ auto state = request->webdriver_bidi_network_request();+ if (!state || !state->navigable || (state->completed.contains(request->redirect_count()) || state->transferred.contains(request->redirect_count())))+ return;+ state->completed.set(request->redirect_count());+ if (!is_event_enabled("network.fetchError"sv))+ return;+ auto params = process_a_network_event(*fetch_params.request(), *fetch_params.timing_info());+ // 4.2. Set the errorText field of params to an implementation-defined string describing the error which caused the request to be aborted.+ params.set("errorText"sv, String::from_utf8_with_replacement_character(error_text));+ emit_event(*state->navigable, "network.fetchError"_string, move(params));+}++Optional<JsonObject> network_response_for_navigation(Request const& request, FetchTimingInfo const& timing_info,+ Response const& response)+{+ if (!g_network_events_enabled)+ return {};+ auto state = request.webdriver_bidi_network_request();+ if (!state || !state->navigable || state->completed.contains(request.redirect_count()))+ return {};+ state->transferred.set(request.redirect_count());+ JsonObject result;+ result.set("parameters"sv, process_a_network_event(request, timing_info));+ result.set("response"sv, get_the_response_data(response, timing_info));+ result.set("postRedirectStartTime"sv, timing_info.post_redirect_start_time());+ result.set("timeOrigin"sv, request.client() ? JsonValue(request.client()->time_origin()) : JsonValue {});+ return result;+}++void network_navigation_response_finished(HTML::Navigable const& navigable, JsonObject const& metadata, Response const& response, FetchTimingInfo const* timing_info, Optional<StringView> error)+{+ auto name = error.has_value() ? "network.fetchError"sv : "network.responseCompleted"sv;+ if (!g_network_events_enabled || !is_event_enabled(name))+ return;+ auto parameters = metadata.get_object("parameters"sv);+ if (!parameters.has_value())+ return;+ auto params = *parameters;+ params.set("timestamp"sv, UnixDateTime::now().milliseconds_since_epoch());+ if (error.has_value()) {+ params.set("errorText"sv, String::from_utf8_with_replacement_character(*error));+ } else {+ auto fallback_timings = FetchTimingInfo::create();+ auto const& timings = timing_info ? *timing_info : *fallback_timings;+ if (auto request = params.get_object("request"sv); request.has_value()) {+ auto old_timings = request->get_object("timings"sv);+ auto epoch_origin = old_timings->get("timeOrigin"sv)->get_double_with_precision_loss().value();+ auto origin = metadata.get("timeOrigin"sv);+ request->set("timings"sv, get_the_fetch_timings(timings, origin->is_null() ? Optional<double> {} : origin->get_double_with_precision_loss(), epoch_origin));+ }+ params.set("response"sv, get_the_response_data(response, timings));+ }+ emit_event(navigable, MUST(String::from_utf8(name)), move(params));+}++}diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.h b/Libraries/LibWeb/WebDriver/BiDi/Network.hnew file mode 100644index 00000000000..2c9601fa902--- /dev/null+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.h@@ -0,0 +1,55 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/HashMap.h>+#include <AK/HashTable.h>+#include <AK/JsonObject.h>+#include <AK/Optional.h>+#include <AK/String.h>+#include <AK/Utf16String.h>+#include <LibGC/Weak.h>+#include <LibJS/Heap/Cell.h>+#include <LibWeb/Forward.h>++namespace Web::WebDriver::BiDi {++// https://w3c.github.io/webdriver-bidi/#request-id+// NB: Fetch's internal request clones and redirects share this identity.+class NetworkRequest final : public JS::Cell {+ GC_CELL(NetworkRequest, JS::Cell);+ GC_DECLARE_ALLOCATOR(NetworkRequest);++public:+ String id;+ // NB: An observed request must not keep a navigable or its load-event delayer alive.+ GC::Weak<HTML::Navigable> navigable;+ Optional<String> navigation;+ HashTable<u8> before_request_sent;+ HashTable<u8> response_started;+ HashTable<u8> completed;+ HashTable<u8> transferred;+ HashMap<u8, JsonObject> request_data;++private:+ NetworkRequest();+};++// NB: Fetch checks this cached flag before doing any network instrumentation.+WEB_API extern bool g_network_events_enabled;++void initialize_network_request(Fetch::Infrastructure::Request&, GC::Ptr<HTML::Navigable> = nullptr, Optional<Utf16String> const& navigation = {});+void network_before_request_sent(Fetch::Infrastructure::FetchParams const&);+void network_response_started(Fetch::Infrastructure::FetchParams const&, Fetch::Infrastructure::Response&);+void network_response_completed(Fetch::Infrastructure::FetchParams const&, Fetch::Infrastructure::Response const&);+void network_fetch_error(Fetch::Infrastructure::FetchParams const&, StringView);++Optional<JsonObject> network_response_for_navigation(Fetch::Infrastructure::Request const&, Fetch::Infrastructure::FetchTimingInfo const&,+ Fetch::Infrastructure::Response const&);+void network_navigation_response_finished(HTML::Navigable const&, JsonObject const&, Fetch::Infrastructure::Response const&, Fetch::Infrastructure::FetchTimingInfo const*, Optional<StringView> error = {});++}diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txtindex 55008c590bf..b0abc1589a9 100644--- a/Libraries/LibWebCommon/CMakeLists.txt+++ b/Libraries/LibWebCommon/CMakeLists.txt@@ -109,6 +109,7 @@ invoke_py_generator("${LADYBIRD_SOURCE_DIR}/Meta/Utils/utils.py")+compile_ipc(HTML/NavigationResponse.ipc HTML/NavigationResponseCodecs.h)compile_ipc(Page/InputEvent.ipc Page/InputEventCodecs.h)compile_ipc(Page/TextEditingCommand.ipc Page/TextEditingCommandCodecs.h)compile_ipc(PixelUnits.ipc PixelUnitsCodecs.h)diff --git a/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.cpp b/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.cppindex eb941bb322d..99a2e435ed3 100644--- a/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.cpp+++ b/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.cpp@@ -7,6 +7,7 @@#include <LibIPC/Decoder.h>#include <LibIPC/Encoder.h>#include <LibWebCommon/HTML/NavigationParamsDescriptor.h>+#include <LibWebCommon/HTML/NavigationResponseCodecs.h>namespace IPC {@@ -106,39 +107,6 @@ ErrorOr<Web::HTML::NavigationResponseBodyHandle> decode(Decoder& decoder)};}-template<>-ErrorOr<void> encode(Encoder& encoder, Web::HTML::NavigationResponseDescriptor const& response)-{- TRY(encoder.encode(response.url_list));- TRY(encoder.encode(response.status));- TRY(encoder.encode(response.status_message));- TRY(encoder.encode(response.headers));- TRY(encoder.encode(response.network_error_message));- TRY(encoder.encode(response.timing_allow_passed));- TRY(encoder.encode(response.cache_state));- TRY(encoder.encode(response.navigation_timing_allow_values_list));- TRY(encoder.encode(response.redirect_taint));- TRY(encoder.encode(response.body));- return {};-}--template<>-ErrorOr<Web::HTML::NavigationResponseDescriptor> decode(Decoder& decoder)-{- return Web::HTML::NavigationResponseDescriptor {- .url_list = TRY(decoder.decode<Vector<URL::URL>>()),- .status = TRY(decoder.decode<u16>()),- .status_message = TRY(decoder.decode<ByteString>()),- .headers = TRY(decoder.decode<Vector<HTTP::Header>>()),- .network_error_message = TRY(decoder.decode<Optional<String>>()),- .timing_allow_passed = TRY(decoder.decode<bool>()),- .cache_state = TRY(decoder.decode<Optional<Web::Fetch::Infrastructure::ResponseCacheState>>()),- .navigation_timing_allow_values_list = TRY(decoder.decode<Vector<Vector<String>>>()),- .redirect_taint = TRY(decoder.decode<Web::Fetch::Infrastructure::RedirectTaint>()),- .body = TRY(decoder.decode<Web::HTML::NavigationResponseBody>()),- };-}-template<>ErrorOr<void> encode(Encoder& encoder, Web::HTML::NavigationEnvironmentDescriptor const& environment){diff --git a/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.h b/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.hindex bcc86bf272e..093f63dae25 100644--- a/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.h+++ b/Libraries/LibWebCommon/HTML/NavigationParamsDescriptor.h@@ -9,6 +9,7 @@#include <AK/ByteBuffer.h>#include <AK/ByteString.h>#include <AK/Error.h>+#include <AK/JsonValue.h>#include <AK/Optional.h>#include <AK/String.h>#include <AK/Utf16String.h>@@ -89,6 +90,8 @@ struct NavigationResponseDescriptor {Fetch::Infrastructure::RedirectTaint redirect_taint { Fetch::Infrastructure::RedirectTaint::SameOrigin };NavigationResponseBody body;++ JsonValue webdriver_bidi_network_response;};struct NavigationFetchTimingInfoDescriptor {diff --git a/Libraries/LibWebCommon/HTML/NavigationResponse.ipc b/Libraries/LibWebCommon/HTML/NavigationResponse.ipcnew file mode 100644index 00000000000..a88d112288c--- /dev/null+++ b/Libraries/LibWebCommon/HTML/NavigationResponse.ipc@@ -0,0 +1,18 @@+// Copyright (c) 2026-present, the Ladybird developers.++#include <LibWebCommon/HTML/NavigationParamsDescriptor.h>++[ExistingCpp]+struct Web::HTML::NavigationResponseDescriptor {+ Vector<URL::URL> url_list;+ u16 status;+ ByteString status_message;+ Vector<HTTP::Header> headers;+ Optional<String> network_error_message;+ bool timing_allow_passed;+ Optional<Web::Fetch::Infrastructure::ResponseCacheState> cache_state;+ Vector<Vector<String>> navigation_timing_allow_values_list;+ Web::Fetch::Infrastructure::RedirectTaint redirect_taint;+ Web::HTML::NavigationResponseBody body;+ JsonValue webdriver_bidi_network_response;+}diff --git a/Libraries/LibWebView/FileDownloader.cpp b/Libraries/LibWebView/FileDownloader.cppindex 1c7209a0e8f..aa25e7dcd33 100644--- a/Libraries/LibWebView/FileDownloader.cpp+++ b/Libraries/LibWebView/FileDownloader.cpp@@ -9,6 +9,8 @@#include <AK/NumericLimits.h>#include <AK/QuickSort.h>#include <AK/Random.h>+#include <AK/RefCounted.h>+#include <AK/ScopeGuard.h>#include <LibCore/DirIterator.h>#include <LibCore/ElapsedTimer.h>#include <LibCore/EventLoop.h>@@ -67,6 +69,33 @@ struct FileDownloader::Segment {}};+// NB: An adopted response follows the download across intentional request stops and restarts.+class AdoptedResponseObserver : public RefCounted<AdoptedResponseObserver> {+ AK_ALLOC_WITH_KMALLOC;++public:+ explicit AdoptedResponseObserver(FileDownloader::ResponseFinished on_finish)+ : m_on_finish(move(on_finish))+ {+ }++ void set_timing_info(Requests::RequestTimingInfo const& timing) { m_timing_info = timing; }+ Requests::RequestTimingInfo const* timing_info() const { return m_timing_info.has_value() ? &*m_timing_info : nullptr; }++ void finish(u64 decoded_size, Requests::RequestTimingInfo const* timing,+ Optional<StringView> error)+ {+ NonnullRefPtr protect { *this };+ auto on_finish = move(m_on_finish);+ if (on_finish)+ on_finish(decoded_size, timing, error);+ }++private:+ FileDownloader::ResponseFinished m_on_finish;+ Optional<Requests::RequestTimingInfo> m_timing_info;+};+struct FileDownloader::ActiveDownload {AK_ALLOC_WITH_KMALLOC;@@ -84,6 +113,7 @@ struct FileDownloader::ActiveDownload {Vector<Segment> segments;Function<void()> on_cancel;+ RefPtr<AdoptedResponseObserver> response_observer;OwnPtr<Core::File> file;RefPtr<Core::Timer> stall_timer;@@ -248,8 +278,14 @@ void FileDownloader::follow_download_redirect(u64 download_id, HTTP::HeaderListstart_download_request(download_id, redirect_url.release_value());}-u64 FileDownloader::adopt_download(IsPrivate is_private, URL::URL const& url, LexicalPath destination, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ReadonlyBytes initial_data)+u64 FileDownloader::adopt_download(IsPrivate is_private, URL::URL const& url, LexicalPath destination, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ReadonlyBytes initial_data,+ ResponseFinished on_response_finished){+ ScopeGuard report_failure = [&] {+ if (on_response_finished)+ on_response_finished(0, nullptr,+ "Unable to adopt the download response"sv);+ };auto download_id = start_download(is_private, url, move(destination), total_size);auto* active = active_download(download_id);if (!active)@@ -274,15 +310,26 @@ u64 FileDownloader::adopt_download(IsPrivate is_private, URL::URL const& url, Lereturn download_id;}- attach_request_to_download(download_id, 0, request.release_nonnull());+ attach_request_to_download(download_id, 0, request.release_nonnull(),+ move(on_response_finished));return download_id;}-void FileDownloader::attach_request_to_download(u64 download_id, size_t segment_index, NonnullRefPtr<Requests::Request> request)+void FileDownloader::attach_request_to_download(u64 download_id, size_t segment_index, NonnullRefPtr<Requests::Request> request,+ ResponseFinished on_response_finished){auto* active = active_download(download_id);- if (!active || segment_index >= active->segments.size())+ if (!active || segment_index >= active->segments.size()) {+ if (on_response_finished)+ on_response_finished(+ 0, nullptr, "Download was stopped before adopting its response"sv);return;+ }+ RefPtr<AdoptedResponseObserver> observer;+ if (on_response_finished) {+ observer = adopt_ref(*new AdoptedResponseObserver(move(on_response_finished)));+ active->response_observer = observer;+ }auto& segment = active->segments[segment_index];auto request_generation = ++active->last_request_generation;@@ -305,7 +352,15 @@ void FileDownloader::attach_request_to_download(u64 download_id, size_t segment_},[](Core::ImmutableBytes) {},- [this, download_id, segment_index, request_generation](u64 delivered_size, Requests::RequestTimingInfo const&, Optional<Requests::NetworkError> network_error) {+ [this, download_id, segment_index, request_generation, observer](u64 delivered_size, Requests::RequestTimingInfo const& timing_info, Optional<Requests::NetworkError> network_error) {+ if (observer) {+ auto* active = active_download(download_id);+ // NB: Offsets from a replacement or split request do not share the original fetch's start time.+ if (active && active->segments.size() == 1 && segment_index == 0+ && active->segments[0].request_generation == request_generation+ && !active->segments[0].request_is_ranged)+ observer->set_timing_info(timing_info);+ }handle_segment_finished(download_id, segment_index, request_generation, delivered_size, network_error);});}@@ -1656,8 +1711,23 @@ void FileDownloader::notify_download_added(Download const& download)void FileDownloader::notify_download_updated(Download const& download){+ RefPtr<AdoptedResponseObserver> response_observer;+ Optional<Download> finished_download;+ if (!status_is_active(download.status)) {+ if (auto* active = active_download(download.id); active && active->response_observer) {+ // NB: Take the terminal owner before notifying observers, which may reenter or remove the download.+ response_observer = move(active->response_observer);+ finished_download = download;+ }+ }for (auto& observer : m_observers)observer.download_updated(download);+ if (response_observer) {+ Optional<StringView> error;+ if (finished_download->status != DownloadStatus::Completed)+ error = finished_download->error.has_value() ? finished_download->error->bytes_as_string_view() : "Download was canceled"sv;+ response_observer->finish(finished_download->downloaded_size, response_observer->timing_info(), error);+ }}void FileDownloader::notify_download_removed(u64 id, IsPrivate is_private)diff --git a/Libraries/LibWebView/FileDownloader.h b/Libraries/LibWebView/FileDownloader.hindex 73547f67e1c..88e7ac77df2 100644--- a/Libraries/LibWebView/FileDownloader.h+++ b/Libraries/LibWebView/FileDownloader.h@@ -89,7 +89,9 @@ public:};u64 download_file(IsPrivate, URL::URL const&, LexicalPath, MayReplaceDestination = MayReplaceDestination::No);- u64 adopt_download(IsPrivate, URL::URL const&, LexicalPath, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ReadonlyBytes initial_data = {});+ using ResponseFinished = Function<void(u64 decoded_body_size, Requests::RequestTimingInfo const*,+ Optional<StringView> error)>;+ u64 adopt_download(IsPrivate, URL::URL const&, LexicalPath, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ReadonlyBytes initial_data = {}, ResponseFinished = {});u64 start_download(IsPrivate, URL::URL const&, LexicalPath, Optional<u64> total_size = {}, MayReplaceDestination = MayReplaceDestination::No);bool has_active_downloads() const;bool has_unresumable_downloads() const;@@ -126,7 +128,8 @@ private:ActiveDownload* active_download(u64 id);void start_download_request(u64 id, URL::URL const&);void follow_download_redirect(u64 id, HTTP::HeaderList const&);- void attach_request_to_download(u64 id, size_t segment_index, NonnullRefPtr<Requests::Request>);+ void attach_request_to_download(u64 id, size_t segment_index, NonnullRefPtr<Requests::Request>,+ ResponseFinished = {});void maybe_redistribute_segments(u64 id);void start_stall_watchdog(u64 id);void check_for_stalled_segments(u64 id);diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex 81107389deb..7666e216bd0 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -754,10 +754,10 @@ Messages::WebContentClient::DidStartDownloadWithoutRequestResponse WebContentClireturn Optional<u64> {};}-Messages::WebContentClient::DidStartDownloadResponse WebContentClient::did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data)+Messages::WebContentClient::DidStartDownloadResponse WebContentClient::did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response){if (auto* page = this->page(page_id))- return page->did_start_download(navigable_id, move(navigation_id), move(url), move(suggested_filename), total_size, request_server_client_id, request_server_request_id, move(initial_data));+ return page->did_start_download(navigable_id, move(navigation_id), move(url), move(suggested_filename), total_size, request_server_client_id, request_server_request_id, move(initial_data), move(network_response));return Optional<u64> {};}diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.hindex d7c7422e6f9..944ae7b5a52 100644--- a/Libraries/LibWebView/WebContentClient.h+++ b/Libraries/LibWebView/WebContentClient.h@@ -200,7 +200,7 @@ private:virtual void storage_area_write_refused(Web::StorageAPI::StorageAreaId, Vector<StorageItem>) override;virtual void storage_area_reset(Web::StorageAPI::StorageAreaId, Vector<StorageItem>) override;virtual Messages::WebContentClient::DidStartDownloadWithoutRequestResponse did_start_download_without_request(Web::PageId page_id, URL::URL, ByteString suggested_filename, Optional<u64> total_size) override;- virtual Messages::WebContentClient::DidStartDownloadResponse did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data) override;+ virtual Messages::WebContentClient::DidStartDownloadResponse did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) override;virtual Messages::WebContentClient::DidRequestNewWebViewResponse did_request_new_web_view(Web::PageId page_id, Web::HTML::ActivateTab, Web::HTML::WebViewHints, Optional<Web::HTML::CrossProcessId> opener_navigable_id, Optional<URL::URL> opener_base_url, Utf16String target_name, Web::HTML::SandboxingFlagSet popup_sandboxing_flag_set) override;virtual Messages::WebContentClient::StartWorkerAgentResponse start_worker_agent(Web::PageId page_id, Web::HTML::WorkerAgentStartRequest request) override;virtual void did_update_cookie(HTTP::Cookie::Cookie) override;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex db59a235617..6dba807a17d 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -2292,14 +2292,28 @@ Messages::WebContentClient::DidStartDownloadWithoutRequestResponse WebContentPagreturn { download_id };}-Messages::WebContentClient::DidStartDownloadResponse WebContentPage::did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data)+Messages::WebContentClient::DidStartDownloadResponse WebContentPage::did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response){// A download taking over an in-flight population's response body ends that navigation without a document;// the reporting process ends its side when its population output says the download was handled. The body// identifiers preserve the original RequestServer transfer lease, so only the process and navigation that// received that response may claim it, and only while its population is in flight.+ FileDownloader::ResponseFinished on_response_finished;bool matches_in_flight_navigation = false;if (auto navigable = population_worker_navigable(navigable_id); navigable.has_value()) {+ if (auto* bidi = WebDriverBiDi::the();+ bidi && network_response.is_object()) {+ on_response_finished = [weak_bidi = bidi->make_weak_ptr(),+ context = WebDriverBiDi::navigable_id(*navigable),+ metadata = network_response.as_object()](+ u64 decoded_size,+ Requests::RequestTimingInfo const* timing,+ Optional<StringView> error) {+ if (weak_bidi)+ weak_bidi->download_response_finished(context, metadata, decoded_size,+ timing, error);+ };+ }auto ongoing_navigation = navigation_id.has_value() ? navigable->navigation_with_id(*navigation_id) : nullptr;if (ongoing_navigation&& (ongoing_navigation->state.has<CanonicalNavigation::CreatingNavigationParams>() || ongoing_navigation->state.has<CanonicalNavigation::Populating>())@@ -2308,15 +2322,25 @@ Messages::WebContentClient::DidStartDownloadResponse WebContentPage::did_start_dnavigable->did_cancel_navigation(*navigation_id);}}- if (!matches_in_flight_navigation)+ if (!matches_in_flight_navigation) {+ if (on_response_finished)+ on_response_finished(+ 0, nullptr,+ "Navigation response is no longer available for download"sv);return { Optional<u64> {} };+ }auto destination = choose_download_destination_or_report_error(url, suggested_filename);- if (!destination.has_value())+ if (!destination.has_value()) {+ if (on_response_finished)+ on_response_finished(0, nullptr,+ "Download destination was not selected"sv);return { Optional<u64> {} };+ }auto& file_downloader = Application::the().file_downloader();- auto download_id = file_downloader.adopt_download(client().is_private(), url, destination.release_value(), total_size, request_server_client_id, request_server_request_id, initial_data.bytes());+ auto download_id = file_downloader.adopt_download(client().is_private(), url, destination.release_value(), total_size, request_server_client_id, request_server_request_id, initial_data.bytes(),+ move(on_response_finished));if (!is_download_in_progress(file_downloader, download_id))return { Optional<u64> {} };diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex 898c1e800e4..e8ba1b3420c 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -321,7 +321,8 @@ private:virtual void did_forward_mouse_event_to_child_frame(Web::HTML::CrossProcessId frame_id, Web::MouseEvent) override;virtual void did_destroy_child_frame(Web::HTML::CrossProcessId frame_id) override;Messages::WebContentClient::DidStartDownloadWithoutRequestResponse did_start_download_without_request(URL::URL url, ByteString suggested_filename, Optional<u64> total_size);- Messages::WebContentClient::DidStartDownloadResponse did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data);+ Messages::WebContentClient::DidStartDownloadResponse did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data,+ JsonValue network_response);virtual void did_receive_download_data(u64 download_id, ByteBuffer data) override;virtual void did_finish_download(u64 download_id) override;virtual void did_fail_download(u64 download_id, String error) override;diff --git a/Libraries/LibWebView/WebDriverBiDi.cpp b/Libraries/LibWebView/WebDriverBiDi.cppindex d1db8d0e391..94bd81bcce2 100644--- a/Libraries/LibWebView/WebDriverBiDi.cpp+++ b/Libraries/LibWebView/WebDriverBiDi.cpp@@ -6,12 +6,14 @@#include <AK/AnyOf.h>#include <AK/JsonArray.h>+#include <AK/Math.h>#include <AK/QuickSort.h>#include <AK/Random.h>#include <AK/ScopeGuard.h>#include <AK/Time.h>#include <AK/WeakPtr.h>#include <LibCore/EventLoop.h>+#include <LibRequests/RequestTimingInfo.h>#include <LibURL/Parser.h>#include <LibWebView/CanonicalNavigable.h>#include <LibWebView/CanonicalTraversable.h>@@ -737,6 +739,84 @@ void WebDriverBiDi::did_receive_navigation_event(WebContentPage& page, Web::HTML}}+void WebDriverBiDi::download_response_finished(+ String const& context, JsonObject const& metadata, u64 decoded_body_size,+ Requests::RequestTimingInfo const* timing_info,+ Optional<StringView> error)+{+ auto name = error.has_value() ? "network.fetchError"sv+ : "network.responseCompleted"sv;+ if (!is_event_enabled(name))+ return;+ auto navigable = get_a_navigable(context);+ auto parameters = metadata.get_object("parameters"sv);+ if (navigable.is_error() || !parameters.has_value())+ return;+ auto params = *parameters;+ params.set("context"sv, context);+ params.set("timestamp"sv, UnixDateTime::now().milliseconds_since_epoch());+ if (error.has_value()) {+ params.set("errorText"sv,+ String::from_utf8_with_replacement_character(*error));+ } else {+ auto response_data = metadata.get_object("response"sv);+ if (!response_data.has_value())+ return;+ auto response = *response_data;+ auto header_size = response.get_u64("headersSize"sv);+ if (!header_size.has_value())+ return;+ auto encoded_size = timing_info ? static_cast<u64>(max(timing_info->encoded_body_size, 0))+ : decoded_body_size;+ response.set("bodySize"sv, encoded_size);+ response.set("bytesReceived"sv, encoded_size + *header_size);+ JsonObject content;+ content.set("size"sv, decoded_body_size);+ response.set("content"sv, move(content));+ params.set("response"sv, move(response));+ if (auto request = params.get_object("request"sv); request.has_value()) {+ if (auto timings = request->get_object("timings"sv);+ timings.has_value()) {+ auto start = metadata.get("postRedirectStartTime"sv);+ auto origin = metadata.get("timeOrigin"sv);+ auto absolute_start = start.has_value() ? start->get_double_with_precision_loss() : Optional<double> {};+ auto time_origin = origin.has_value() ? origin->get_double_with_precision_loss() : Optional<double> {};+ if (absolute_start.has_value() && time_origin.has_value()) {+ // NB: Use the same final-hop origin and coarsening as the renderer's BiDi timings.+ auto set_time = [&](StringView key, double time) {+ auto bucket = floor(time * 10.0);+ auto coarse_time = bucket / 10.0;+ if (floor(coarse_time * 10.0) < bucket)+ coarse_time = nextafter(coarse_time, AK::Infinity<double>);+ timings->set(key, coarse_time - *time_origin);+ };+ if (timing_info) {+ auto set_timing = [&](StringView key, i64 microseconds) {+ set_time(key, *absolute_start + static_cast<double>(microseconds) / 1000.0);+ };+ set_timing("dnsStart"sv,+ timing_info->domain_lookup_start_microseconds);+ set_timing("dnsEnd"sv, timing_info->domain_lookup_end_microseconds);+ set_timing("connectStart"sv, timing_info->connect_start_microseconds);+ set_timing("connectEnd"sv, timing_info->connect_end_microseconds);+ if (timing_info->secure_connect_start_microseconds)+ set_timing("tlsStart"sv,+ timing_info->secure_connect_start_microseconds);+ set_timing("requestStart"sv, timing_info->request_start_microseconds);+ set_timing("responseStart"sv,+ timing_info->response_start_microseconds);+ set_timing("responseEnd"sv, timing_info->response_end_microseconds);+ } else {+ // NB: A split response finishes across several transports, not at the original segment's EOF.+ set_time("responseEnd"sv, MonotonicTime::now().to_seconds_f64() * 1000.0);+ }+ }+ }+ }+ }+ emit_event_for_navigable(name, move(params), *navigable.value());+}+void WebDriverBiDi::did_receive_event(WebContentPage& page, Web::HTML::CrossProcessId navigable_id, String const& name, JsonValue params){// NB: A process hosting web content only reports on the navigables it hosts, and only the events that run there.@@ -753,6 +833,10 @@ void WebDriverBiDi::did_receive_event(WebContentPage& page, Web::HTML::CrossProc"script.message"sv,"script.realmCreated"sv,"script.realmDestroyed"sv,+ "network.beforeRequestSent"sv,+ "network.responseStarted"sv,+ "network.responseCompleted"sv,+ "network.fetchError"sv,});if (!any_of(content_events, [&](auto event_name) { return event_name == name; }))return;@@ -772,7 +856,7 @@ void WebDriverBiDi::did_receive_event(WebContentPage& page, Web::HTML::CrossProcif (name.is_one_of("log.entryAdded"sv, "script.message"sv)) {if (auto source = params.as_object().get_object("source"sv); source.has_value())set_context(*source);- } else if (name == "script.realmCreated"sv) {+ } else if (name == "script.realmCreated"sv || name.starts_with_bytes("network."sv)) {set_context(params.as_object());}diff --git a/Libraries/LibWebView/WebDriverBiDi.h b/Libraries/LibWebView/WebDriverBiDi.hindex 5aeae69e264..da0b208f3dc 100644--- a/Libraries/LibWebView/WebDriverBiDi.h+++ b/Libraries/LibWebView/WebDriverBiDi.h@@ -15,7 +15,9 @@#include <AK/String.h>#include <AK/Utf16String.h>#include <AK/Vector.h>+#include <AK/Weakable.h>#include <LibGfx/Size.h>+#include <LibRequests/Forward.h>#include <LibURL/URL.h>#include <LibWebCommon/HTML/CrossProcessId.h>#include <LibWebCommon/WebDriver/BiDi.h>@@ -30,7 +32,7 @@ class WebDriverBiDiNetwork;// https://w3c.github.io/webdriver-bidi/// NB: The browser process runs the commands of a BiDi session that involve navigables, and routes those that run in the// process hosting a navigable's document to it. It exists only while WebDriver drives the browser.-class WebDriverBiDi {+class WebDriverBiDi : public Weakable<WebDriverBiDi> {AK_MAKE_NONCOPYABLE(WebDriverBiDi);AK_ALLOC_WITH_KMALLOC;AK_MAKE_NONMOVABLE(WebDriverBiDi);@@ -90,6 +92,11 @@ public:void navigation_failed(CanonicalNavigable const&, NavigationStatus const&);void did_receive_navigation_event(WebContentPage&, Web::HTML::CrossProcessId navigable_id, String const& name, Optional<Utf16String> navigation_id, URL::URL url);+ void download_response_finished(String const& context,+ JsonObject const& metadata,+ u64 decoded_body_size,+ Requests::RequestTimingInfo const*,+ Optional<StringView> error);void did_receive_event(WebContentPage&, Web::HTML::CrossProcessId navigable_id, String const& name, JsonValue params);private:diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 5d3afc19f94..81d3f94a1cf 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -1044,9 +1044,9 @@ void PageClient::page_did_finish_loading(Web::HTML::CrossProcessId navigable_id,client().async_did_finish_loading(m_id, navigable_id, document_id);}-Optional<u64> PageClient::page_did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const& url, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data)+Optional<u64> PageClient::page_did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const& url, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response){- auto response = client().send_sync<Messages::WebContentClient::DidStartDownload>(m_id, navigable_id, navigation_id, url, suggested_filename, total_size, request_server_client_id, request_server_request_id, move(initial_data));+ auto response = client().send_sync<Messages::WebContentClient::DidStartDownload>(m_id, navigable_id, navigation_id, url, suggested_filename, total_size, request_server_client_id, request_server_request_id, move(initial_data), move(network_response));return response->download_id();}diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex b8a549d5a22..b346d696762 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -268,7 +268,7 @@ private:virtual void page_did_request_media_context_menu(Web::HTML::CrossProcessId local_root_id, Web::CSSPixelPoint, ByteString const& target, unsigned modifiers, Web::Page::MediaContextMenu const&, Optional<Web::HTML::PreparedNavigationDescriptor>) override;virtual void page_did_change_active_document_in_top_level_browsing_context(Web::DOM::Document&) override;virtual void page_did_finish_loading(Web::HTML::CrossProcessId, Web::HTML::CrossProcessId) override;- virtual Optional<u64> page_did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data) override;+ virtual Optional<u64> page_did_start_download(Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> const& navigation_id, URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) override;virtual Optional<u64> page_did_start_download(URL::URL const&, ByteString const& suggested_filename, Optional<u64> total_size) override;virtual void page_did_receive_download_data(u64 download_id, ByteBuffer data) override;virtual void page_did_finish_download(u64 download_id) override;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex 5ab4f8c082c..8fe0fe00601 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -109,7 +109,7 @@ endpoint WebContentClient routed by Web::PageId page_iddid_destroy_child_frame(Web::PageId page_id, Web::HTML::CrossProcessId frame_id) =|did_finish_loading(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Web::HTML::CrossProcessId document_id) =|[NotRouted] did_start_download_without_request(Web::PageId page_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size) => (Optional<u64> download_id)- [NotRouted] did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data) => (Optional<u64> download_id)+ [NotRouted] did_start_download(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id, Optional<Utf16String> navigation_id, URL::URL url, ByteString suggested_filename, Optional<u64> total_size, int request_server_client_id, u64 request_server_request_id, ByteBuffer initial_data, JsonValue network_response) => (Optional<u64> download_id)did_receive_download_data(Web::PageId page_id, u64 download_id, ByteBuffer data) =|did_finish_download(Web::PageId page_id, u64 download_id) =|did_fail_download(Web::PageId page_id, u64 download_id, String error) =|diff --git a/Tests/LibWebView/test-webdriver-bidi.py b/Tests/LibWebView/test-webdriver-bidi.pyindex f351e3924c4..e1ff3b2e7f7 100755--- a/Tests/LibWebView/test-webdriver-bidi.py+++ b/Tests/LibWebView/test-webdriver-bidi.py@@ -120,12 +120,82 @@ class ReloadServer(http.server.ThreadingHTTPServer):self.block_reload: bool = Falseself.request_received: threading.Event = threading.Event()self.release_response: threading.Event = threading.Event()+ self.download_headers_sent: threading.Event = threading.Event()+ self.release_download: threading.Event = threading.Event()+ self.download_body: bytes = b"BiDi navigation download\n" * 128+ self.segmented_download_body: bytes = b""+ self.range_request_received: threading.Event = threading.Event()+ self.release_initial_download: threading.Event = threading.Event()+ self.initial_download_stopped: threading.Event = threading.Event()class ReloadHandler(http.server.BaseHTTPRequestHandler):def do_GET(self):server = self.serverassert isinstance(server, ReloadServer)+ if self.path == "/network-download/split":+ body = server.segmented_download_body+ range_header = self.headers.get("Range")+ start, end = 0, len(body) - 1+ if range_header is not None:+ assert range_header.startswith("bytes="), range_header+ start_text, end_text = range_header.removeprefix("bytes=").split("-", 1)+ start, end = int(start_text), min(int(end_text), len(body) - 1)+ else:+ # Keep the original transfer from buffering the whole body before its segment is stopped.+ self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 16384)+ self.send_response(206 if range_header is not None else 200)+ self.send_header("Content-Type", "application/octet-stream")+ self.send_header("Content-Disposition", 'attachment; filename="bidi-split.bin"')+ self.send_header("Content-Length", str(end - start + 1))+ self.send_header("Accept-Ranges", "bytes")+ self.send_header("ETag", '"bidi-split"')+ if range_header is not None:+ self.send_header("Content-Range", f"bytes {start}-{end}/{len(body)}")+ self.send_header("Cache-Control", "no-store")+ self.send_header("Connection", "close")+ self.end_headers()+ self.close_connection = True+ self.wfile.write(body[start : start + 1024])+ self.wfile.flush()+ if range_header is not None:+ server.range_request_received.set()+ release = server.release_download+ else:+ server.download_headers_sent.set()+ release = server.release_initial_download+ try:+ if not release.wait(30):+ raise TimeoutError("The test did not release the segmented download response")+ self.wfile.write(body[start + 1024 : end + 1])+ self.wfile.flush()+ except (BrokenPipeError, ConnectionResetError):+ if range_header is None:+ server.initial_download_stopped.set()+ return+ if self.path.startswith("/network-download/"):+ kind = self.path.rsplit("/", 1)[-1]+ truncated = kind == "truncated"+ self.send_response(200)+ self.send_header("Content-Type", "application/octet-stream")+ self.send_header("Content-Disposition", f'attachment; filename="bidi-{kind}.bin"')+ self.send_header("Content-Length", str(len(server.download_body) + (16 if truncated else 0)))+ self.send_header("Cache-Control", "no-store")+ self.send_header("Connection", "close")+ self.end_headers()+ self.close_connection = True+ try:+ self.wfile.write(server.download_body[:1024])+ self.wfile.flush()+ server.download_headers_sent.set()+ if not server.release_download.wait(30):+ raise TimeoutError("The test did not release the download response")+ if not truncated:+ self.wfile.write(server.download_body[1024:])+ self.wfile.flush()+ except (BrokenPipeError, ConnectionResetError):+ pass+ returnif server.block_reload:server.request_received.set()if not server.release_response.wait(30):@@ -155,6 +225,106 @@ class ReloadHandler(http.server.BaseHTTPRequestHandler):pass+def check_network_download_events(bidi, context, server, downloads):+ if sys.platform == "win32":+ print("Skipping download event tests: Windows does not support the temporary download directory override.")+ return+ terminal_methods = {"network.responseCompleted", "network.fetchError"}+ subscription = bidi.command(+ "session.subscribe",+ {+ "events": ["network.beforeRequestSent", "network.responseStarted", *sorted(terminal_methods)],+ "contexts": [context],+ },+ )["subscription"]+ try:+ for kind in ["success", "truncated", "split"]:+ url = f"http://127.0.0.1:{server.server_port}/network-download/{kind}"+ server.download_headers_sent.clear()+ server.release_download.clear()+ if kind == "split":+ server.segmented_download_body = bytes(range(256)) * (8 * 1024 * 1024 // 256)+ server.range_request_received.clear()+ server.release_initial_download.clear()+ server.initial_download_stopped.clear()+ expected_body = server.segmented_download_body if kind == "split" else server.download_body++ def is_our_event(event, expected_url=url):+ return event["params"].get("request", {}).get("url") == expected_url++ def next_event(methods):+ while True:+ for index, event in enumerate(bidi.events):+ if event["method"] in methods and is_our_event(event):+ return bidi.events.pop(index)+ bidi.read_message()++ try:+ # Downloads do not commit documents; observe network events without awaiting the commit waiter.+ bidi.send("browsingContext.navigate", {"context": context, "url": url, "wait": "none"})+ before = next_event({"network.beforeRequestSent"})["params"]+ started = next_event({"network.responseStarted", *terminal_methods})+ assert started["method"] == "network.responseStarted", started+ started = started["params"]+ assert server.download_headers_sent.wait(10)+ request_id = started["request"]["request"]+ assert isinstance(request_id, str) and request_id, started+ assert before["request"]["request"] == request_id, (before, started)+ assert isinstance(started["navigation"], str), started+ assert started["navigation"] == before["navigation"], (before, started)++ if kind == "split":+ assert server.range_request_received.wait(10), (+ "The downloader did not split its range-capable response"+ )+ server.release_initial_download.set()+ assert server.initial_download_stopped.wait(10), "The initial segment did not stop"++ # The initial segment may be stopped, but completion must wait for the held remaining ranges.+ bidi.evaluate(context, "0")+ assert not any(event["method"] in terminal_methods and is_our_event(event) for event in bidi.events), (+ bidi.events+ )+ assert not server.release_download.is_set()++ server.release_download.set()+ terminal = next_event(terminal_methods)+ expected_method = "network.fetchError" if kind == "truncated" else "network.responseCompleted"+ assert terminal["method"] == expected_method, terminal+ params = terminal["params"]+ assert params["context"] == context, params+ assert params["request"]["request"] == request_id, params+ assert params["navigation"] == started["navigation"], params+ assert params["redirectCount"] == started["redirectCount"] == 0, params+ if kind != "truncated":+ response = params["response"]+ assert response["bodySize"] == len(expected_body), response+ assert response["content"]["size"] == len(expected_body), response+ assert response["bytesReceived"] == response["headersSize"] + len(expected_body), response+ timings = params["request"]["timings"]+ assert timings["responseEnd"] >= timings["responseStart"] >= timings["fetchStart"], timings+ else:+ assert isinstance(params["errorText"], str) and params["errorText"], params++ # The transport's finish callback also finalizes the download before the next UI/renderer barrier.+ bidi.evaluate(context, "0")+ assert not any(event["method"] in terminal_methods and is_our_event(event) for event in bidi.events), (+ bidi.events+ )+ path = os.path.join(downloads, f"bidi-{kind}.bin")+ if kind != "truncated":+ with open(path, "rb") as downloaded:+ assert downloaded.read() == expected_body+ else:+ assert not os.path.exists(path), path+ finally:+ server.release_initial_download.set()+ server.release_download.set()+ finally:+ if sys.exc_info()[0] is None:+ bidi.command("session.unsubscribe", {"subscriptions": [subscription]})++def check_screenshot_handles(bidi, context):bidi.command("browsingContext.activate", {"context": context})element = bidi.evaluate(context, "document.body.style.height = '20px'; document.body")["result"]@@ -754,8 +924,10 @@ def cleanup_resources(server, webdriver, connection, bidi, session_id, *, primarraise errors[0]-def run_test(webdriver_binary, *, input_cross_context_only=False):+def run_test(webdriver_binary, *, input_cross_context_only=False, network_download_only=False):with tempfile.TemporaryDirectory(prefix="ladybird-webdriver-bidi-") as profile:+ downloads = os.path.join(profile, "downloads")+ os.mkdir(downloads)server = ReloadServer()threading.Thread(target=server.serve_forever, daemon=True).start()port = helpers.unused_port()@@ -775,7 +947,8 @@ def run_test(webdriver_binary, *, input_cross_context_only=False):"127.0.0.1","-p",str(port),- ]+ ],+ env={**os.environ, "XDG_DOWNLOAD_DIR": downloads},)helpers.wait_for_port(port)connection = http.client.HTTPConnection("127.0.0.1", port, timeout=30)@@ -800,6 +973,12 @@ def run_test(webdriver_binary, *, input_cross_context_only=False):rejected.close()bidi = BiDiConnection(websocket_url)context = bidi.command("browsingContext.getTree", {})["contexts"][0]["context"]+ if network_download_only:+ check_network_download_events(bidi, context, server, downloads)+ status, payload, _ = helpers.request(connection, "DELETE", f"/session/{session_id}")+ assert status == 200, payload+ session_id = None+ returnif input_cross_context_only:check_input_cross_context(bidi, connection, session_id, context, server)check_input_click_navigation(bidi, connection, session_id, context, server)@@ -807,6 +986,7 @@ def run_test(webdriver_binary, *, input_cross_context_only=False):assert status == 200, payloadsession_id = Nonereturn+ check_network_download_events(bidi, context, server, downloads)check_screenshot_handles(bidi, context)check_input_handles(bidi, context)check_input_queue(bidi, context)@@ -996,5 +1176,10 @@ if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument("webdriver_binary")parser.add_argument("--input-cross-context-only", action="store_true")+ parser.add_argument("--network-download-only", action="store_true")args = parser.parse_args()- run_test(args.webdriver_binary, input_cross_context_only=args.input_cross_context_only)+ run_test(+ args.webdriver_binary,+ input_cross_context_only=args.input_cross_context_only,+ network_download_only=args.network_download_only,+ )