Truly independent web browser
LibWeb+WebContent: Report network requests to DevTools from the fetch
Luke Wildeb89b0637e27a
diff --git a/Libraries/LibWeb/Fetch/Engine/EngineEvent.h b/Libraries/LibWeb/Fetch/Engine/EngineEvent.hindex 4b47c50a5e1..39519f4bc71 100644--- a/Libraries/LibWeb/Fetch/Engine/EngineEvent.h+++ b/Libraries/LibWeb/Fetch/Engine/EngineEvent.h@@ -10,6 +10,7 @@#include <LibWeb/Fetch/Engine/BodyPresentation.h>#include <LibWeb/Fetch/Engine/FetchTimingSeed.h>#include <LibWeb/Fetch/Engine/Ids.h>+#include <LibWeb/Fetch/Engine/NetworkActivity.h>#include <LibWeb/Fetch/Engine/RequestEnd.h>#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>@@ -102,6 +103,7 @@ using EngineEvent = Variant<Event::RequestBodyProgress,Event::RequestBodyEndOfBody,Event::ReadRequestBodyStream,- Event::RequestBodySentFromSource>;+ Event::RequestBodySentFromSource,+ Event::NetworkActivity>;}diff --git a/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.hindex ef89cb8d72b..ba8425d3cf2 100644--- a/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h+++ b/Libraries/LibWeb/Fetch/Engine/FetchEngineRecord.h@@ -10,26 +10,39 @@#include <AK/NonnullRefPtr.h>#include <AK/RefCounted.h>#include <LibWeb/Fetch/Engine/EngineEventSink.h>+#include <LibWeb/Fetch/Engine/NetworkActivity.h>+#include <LibWeb/Fetch/Engine/NetworkActivityObservers.h>namespace Web::Fetch::Engine {// What the fetch engine keeps of a fetch it has started.class FetchEngineRecord final : public RefCounted<FetchEngineRecord> {public:- [[nodiscard]] static NonnullRefPtr<FetchEngineRecord> create(NonnullOwnPtr<EngineEventSink> event_sink)+ [[nodiscard]] static NonnullRefPtr<FetchEngineRecord> create(NonnullOwnPtr<EngineEventSink> event_sink, NonnullRefPtr<NetworkActivityObservers const> network_activity_observers){- return adopt_ref(*new FetchEngineRecord(move(event_sink)));+ return adopt_ref(*new FetchEngineRecord(move(event_sink), move(network_activity_observers)));}[[nodiscard]] EngineEventSink& event_sink() { return *m_event_sink; }+ // Reports what happened to one of the fetch's RequestServer requests to the agent that started the fetch.+ void report_network_activity(RequestId request_id, Event::NetworkActivity::Activity activity)+ {+ m_event_sink->handle_event(Event::NetworkActivity { .request_id = request_id, .activity = move(activity) });+ }++ // Those of the agent that started the fetch.+ [[nodiscard]] NetworkActivityObservers const& network_activity_observers() const { return m_network_activity_observers; }+private:- explicit FetchEngineRecord(NonnullOwnPtr<EngineEventSink> event_sink)+ FetchEngineRecord(NonnullOwnPtr<EngineEventSink> event_sink, NonnullRefPtr<NetworkActivityObservers const> network_activity_observers): m_event_sink(move(event_sink))+ , m_network_activity_observers(move(network_activity_observers)){}NonnullOwnPtr<EngineEventSink> m_event_sink;+ NonnullRefPtr<NetworkActivityObservers const> m_network_activity_observers;};}diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkActivity.h b/Libraries/LibWeb/Fetch/Engine/NetworkActivity.hnew file mode 100644index 00000000000..6cadf486383--- /dev/null+++ b/Libraries/LibWeb/Fetch/Engine/NetworkActivity.h@@ -0,0 +1,58 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/ByteString.h>+#include <AK/Optional.h>+#include <AK/String.h>+#include <AK/Variant.h>+#include <AK/Vector.h>+#include <LibCore/ImmutableBytes.h>+#include <LibHTTP/Header.h>+#include <LibRequests/CacheState.h>+#include <LibRequests/NetworkError.h>+#include <LibRequests/RequestTimingInfo.h>+#include <LibURL/URL.h>+#include <LibWeb/Fetch/Engine/Ids.h>+#include <LibWebCommon/Fetch/Infrastructure/HTTP/RequestPriority.h>+#include <LibWebCommon/ReferrerPolicy/ReferrerPolicy.h>++namespace Web::Fetch::Engine::Event {++// What happened to one of a fetch's RequestServer requests, as DevTools reads it.+struct NetworkActivity {+ struct RequestStarted {+ URL::URL url;+ ByteString method;+ Vector<HTTP::Header> headers;+ Core::ImmutableBytes body;+ Optional<String> initiator_type;+ ReferrerPolicy::ReferrerPolicy referrer_policy { ReferrerPolicy::ReferrerPolicy::EmptyString };+ bool is_navigation_request { false };+ Infrastructure::RequestPriority priority { Infrastructure::RequestPriority::Auto };+ };+ struct ResponseHeaders {+ u32 status_code { 0 };+ Optional<String> reason_phrase;+ Vector<HTTP::Header> headers;+ Requests::CacheState cache_state { Requests::CacheState::NotCached };+ };+ struct ResponseBodyBytes {+ Core::ImmutableBytes bytes;+ };+ struct RequestFinished {+ u64 total_size { 0 };+ Requests::RequestTimingInfo timing_info;+ Optional<Requests::NetworkError> network_error;+ };+ using Activity = Variant<RequestStarted, ResponseHeaders, ResponseBodyBytes, RequestFinished>;++ RequestId request_id;+ Activity activity;+};++}diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkActivityObservers.h b/Libraries/LibWeb/Fetch/Engine/NetworkActivityObservers.hnew file mode 100644index 00000000000..99c9f1a6d05--- /dev/null+++ b/Libraries/LibWeb/Fetch/Engine/NetworkActivityObservers.h@@ -0,0 +1,36 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Atomic.h>+#include <AK/AtomicRefCounted.h>+#include <AK/NonnullRefPtr.h>++namespace Web::Fetch::Engine {++// Which observers of network activity an agent has. The agent writes it, and its fetch engine reads it before it+// copies a response's body bytes for them.+class NetworkActivityObservers final : public AtomicRefCounted<NetworkActivityObservers> {+public:+ [[nodiscard]] static NonnullRefPtr<NetworkActivityObservers> create() { return adopt_ref(*new NetworkActivityObservers); }++ // Whether a page of the agent has a DevTools client.+ [[nodiscard]] bool has_devtools_client() const { return m_pages_with_devtools_client.load() > 0; }+ void page_did_gain_devtools_client() { m_pages_with_devtools_client.fetch_add(1); }+ void page_did_lose_devtools_client()+ {+ auto previous_count = m_pages_with_devtools_client.fetch_sub(1);+ VERIFY(previous_count > 0);+ }++private:+ NetworkActivityObservers() = default;++ Atomic<size_t, AK::MemoryOrder::memory_order_relaxed> m_pages_with_devtools_client { 0 };+};++}diff --git a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.hindex a63749c6dc7..10c26854a6c 100644--- a/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h+++ b/Libraries/LibWeb/Fetch/Engine/NetworkTransportHandle.h@@ -10,6 +10,7 @@#include <LibRequests/Request.h>#include <LibWeb/Export.h>#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>+#include <LibWeb/Fetch/Engine/Ids.h>namespace Web::Fetch::Engine {@@ -19,6 +20,8 @@ class WEB_API NetworkTransportHandle final : public FetchBodyDeliveryGate::Transpublic:[[nodiscard]] static NonnullRefPtr<NetworkTransportHandle> create(NonnullRefPtr<Requests::Request>);+ [[nodiscard]] RequestId request_id() const { return RequestId { m_request->id() }; }+// The key another client adopts the request by, while this process holds its lease.[[nodiscard]] Optional<Requests::RequestTransferLeaseKey> const& transfer_lease() const { return m_request->transfer_lease(); }[[nodiscard]] ByteString const& http_version() const { return m_request->http_version(); }diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cppindex aa424f7630b..32a83c99d40 100644--- a/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/FetchEngine.cpp@@ -12,11 +12,16 @@namespace Web::Fetch::Fetching {+FetchEngine::FetchEngine(NonnullRefPtr<Engine::NetworkActivityObservers const> network_activity_observers)+ : m_network_activity_observers(move(network_activity_observers))+{+}+void FetchEngine::handle_command(Engine::EngineCommand command){command.visit(- [](Engine::Command::StartFetch& start_fetch) {- auto record = Engine::FetchEngineRecord::create(move(start_fetch.input.event_sink));+ [this](Engine::Command::StartFetch& start_fetch) {+ auto record = Engine::FetchEngineRecord::create(move(start_fetch.input.event_sink), m_network_activity_observers);run_deferred_main_fetch_steps(start_fetch.input.fetch_id, move(record));},[](Engine::Command::Abort const&) { VERIFY_NOT_REACHED(); },@@ -28,10 +33,10 @@ void FetchEngine::handle_command(Engine::EngineCommand command)[](Engine::Command::AdoptNetworkTransport const&) { VERIFY_NOT_REACHED(); });}-NonnullRefPtr<Engine::FetchExecutor> create_inline_fetch_executor()+NonnullRefPtr<Engine::FetchExecutor> create_inline_fetch_executor(NonnullRefPtr<Engine::NetworkActivityObservers const> network_activity_observers){Engine::FetchExecutorServices services { .event_loop = Core::EventLoop::current_weak() };- return Engine::InlineFetchExecutor::create(move(services), make<FetchEngine>());+ return Engine::InlineFetchExecutor::create(move(services), make<FetchEngine>(move(network_activity_observers)));}}diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchEngine.h b/Libraries/LibWeb/Fetch/Fetching/FetchEngine.hindex eb4ea39ea13..b5483aac1cb 100644--- a/Libraries/LibWeb/Fetch/Fetching/FetchEngine.h+++ b/Libraries/LibWeb/Fetch/Fetching/FetchEngine.h@@ -10,16 +10,22 @@#include <LibWeb/Export.h>#include <LibWeb/Fetch/Engine/EngineCommandSink.h>#include <LibWeb/Fetch/Engine/FetchExecutor.h>+#include <LibWeb/Fetch/Engine/NetworkActivityObservers.h>namespace Web::Fetch::Fetching {// Handles the commands posted for the fetches of the agent on whose thread it runs.class FetchEngine final : public Engine::EngineCommandSink {public:+ explicit FetchEngine(NonnullRefPtr<Engine::NetworkActivityObservers const>);+virtual void handle_command(Engine::EngineCommand) override;++private:+ NonnullRefPtr<Engine::NetworkActivityObservers const> m_network_activity_observers;};// Creates an executor that runs a fetch engine on the current thread's event loop.-WEB_API NonnullRefPtr<Engine::FetchExecutor> create_inline_fetch_executor();+WEB_API NonnullRefPtr<Engine::FetchExecutor> create_inline_fetch_executor(NonnullRefPtr<Engine::NetworkActivityObservers const>);}diff --git a/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp b/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cppindex cced6b276c1..00ebcf9e3c1 100644--- a/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/FetchEventSink.cpp@@ -13,6 +13,7 @@#include <LibWeb/Fetch/Infrastructure/Task.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>+#include <LibWeb/Page/Page.h>#include <LibWeb/WebIDL/DOMException.h>namespace Web::Fetch::Fetching {@@ -166,6 +167,9 @@ void FetchEventSink::handle_event(Engine::EngineEvent event)[&](Engine::Event::RequestBodySentFromSource const&) {drain_request_body_stream(controller);},+ [&](Engine::Event::NetworkActivity const& network_activity) {+ controller->page()->did_receive_network_activity(network_activity);+ },[](Engine::Event::ResponseDelivery const&) { VERIFY_NOT_REACHED(); },[](Engine::Event::EndOfBody const&) { VERIFY_NOT_REACHED(); },[](Engine::Event::ConsumeBodyResult const&) { VERIFY_NOT_REACHED(); },diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex 193e6c6d15d..69530ca343b 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -384,6 +384,8 @@ GC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure:auto fetch_params = Infrastructure::FetchParams::create(controller, request, algorithms, timing_info, current_loader_config());controller->set_task_destination(task_destination);controller->set_keepalive(request.keepalive());+ // AD-HOC: A fetch's network requests are loaded and reported for the page of the realm that starts it.+ controller->set_page(Bindings::principal_host_defined_page(realm));fetch_params->set_cross_origin_isolated_capability(cross_origin_isolated_capability);fetch_params->set_has_response_body_transfer_lease(create_response_body_transfer_lease == CreateResponseBodyTransferLease::Yes);@@ -2846,6 +2848,28 @@ GC::Ptr<Infrastructure::Body> adopt_navigation_response_body(JS::Realm& realm, Ireturn create_body_view(realm, response, nullptr);}+static Engine::Event::NetworkActivity::RequestStarted network_request_started(LoadRequest const& load_request, Infrastructure::Request const& request)+{+ Core::ImmutableBytes body;+ if (auto const* fetch_body = request.body().get_pointer<Infrastructure::FetchBody>(); fetch_body && fetch_body->source().has_value())+ body = *fetch_body->source();++ Optional<String> initiator_type;+ if (load_request.initiator_type().has_value())+ initiator_type = MUST(Infrastructure::initiator_type_to_string(*load_request.initiator_type()).view().to_utf8());++ return {+ .url = load_request.url().value(),+ .method = load_request.method(),+ .headers = load_request.headers().headers(),+ .body = move(body),+ .initiator_type = move(initiator_type),+ .referrer_policy = load_request.referrer_policy(),+ .is_navigation_request = load_request.is_navigation_request(),+ .priority = load_request.priority(),+ };+}+// https://fetch.spec.whatwg.org/#concept-http-network-fetch// Drop-in replacement for 'HTTP-network fetch', but obviously non-standard :^)// It also handles file:// URLs since those can also go through ResourceLoader.@@ -2860,8 +2884,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch((void)is_new_connection_fetch;auto request = fetch_params.request();-- auto& page = Bindings::principal_host_defined_page(realm);+ auto* engine_record = fetch_params.engine_record();+ VERIFY(engine_record);auto load_request_headers = request->header_list();if (g_disk_cache_enabled_for_navigations_for_testing && request->mode() == Infrastructure::Request::Mode::Navigate) {@@ -2871,7 +2895,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(LoadRequest load_request { move(load_request_headers) };load_request.set_url(request->current_url());- load_request.set_page(page);+ load_request.set_page(fetch_params.controller()->page());load_request.set_method(request->method());load_request.set_cache_mode(request->cache_mode());load_request.set_include_credentials(include_credentials);@@ -2921,7 +2945,17 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(// A load without a RequestServer request, such as one for a file: URL, hands over its whole body at once.auto whole_body_transport = create_whole_body_transport(*delivery_gate, *channel);- auto on_headers_received = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }, pending_response, request, body_pump, channel, delivery_gate, whole_body_transport, http_cache), [](auto& fetch_params, auto& pending_response, auto& request, auto& body_pump, auto& channel, auto& delivery_gate, auto& whole_body_transport, auto& http_cache, Engine::NetworkTransportHandle* network_transport, HTTP::HeaderList const& response_headers, Optional<u32> status_code, Optional<String> const& reason_phrase, Requests::CacheState cache_state) {+ auto on_headers_received = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { fetch_params }, NonnullRefPtr { *engine_record }, pending_response, request, body_pump, channel, delivery_gate, whole_body_transport, http_cache), [](auto& fetch_params, auto& engine_record, auto& pending_response, auto& request, auto& body_pump, auto& channel, auto& delivery_gate, auto& whole_body_transport, auto& http_cache, Engine::NetworkTransportHandle* network_transport, HTTP::HeaderList const& response_headers, Optional<u32> status_code, Optional<String> const& reason_phrase, Requests::CacheState cache_state) {+ if (network_transport) {+ Engine::Event::NetworkActivity::ResponseHeaders headers {+ .status_code = status_code.value_or(0),+ .reason_phrase = reason_phrase,+ .headers = response_headers.headers(),+ .cache_state = cache_state,+ };+ engine_record->report_network_activity(network_transport->request_id(), move(headers));+ }+if (pending_response->is_resolved()) {// RequestServer will send us the response headers twice, the second time being for HTTP trailers. This// fetch algorithm is not interested in trailers, so just drop them here.@@ -2998,7 +3032,12 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(body_pump->handle_network_data(move(data));});- auto on_data_received = GC::create_function(GC::Heap::the(), GC::captures(deliver_body_data, whole_body_transport), [](auto& deliver_body_data, auto& whole_body_transport, Requests::ResponseData data) {+ auto on_data_received = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { *engine_record }, deliver_body_data, whole_body_transport), [](auto& engine_record, auto& deliver_body_data, auto& whole_body_transport, Engine::NetworkTransportHandle* network_transport, Requests::ResponseData data) {+ if (network_transport && engine_record->network_activity_observers().has_devtools_client()) {+ Engine::Event::NetworkActivity::ResponseBodyBytes body_bytes { MUST(Core::ImmutableBytes::copy(data.bytes())) };+ engine_record->report_network_activity(network_transport->request_id(), move(body_bytes));+ }+if (!whole_body_transport->is_attached()) {deliver_body_data->function()(move(data));return;@@ -3030,7 +3069,16 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(}});- auto on_complete = GC::create_function(GC::Heap::the(), GC::captures(complete_load, whole_body_transport), [](auto& complete_load, auto& whole_body_transport, bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message) {+ auto on_complete = GC::create_function(GC::Heap::the(), GC::captures(NonnullRefPtr { *engine_record }, complete_load, whole_body_transport), [](auto& engine_record, auto& complete_load, auto& whole_body_transport, bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message, Optional<ResourceLoader::NetworkRequestEnd> const& network_request_end) {+ if (network_request_end.has_value()) {+ Engine::Event::NetworkActivity::RequestFinished finished {+ .total_size = network_request_end->total_size,+ .timing_info = timing_info,+ .network_error = network_request_end->network_error,+ };+ engine_record->report_network_activity(network_request_end->request_id, move(finished));+ }+if (!success || !whole_body_transport->is_attached()) {complete_load->function()(success, timing_info, error_message);return;@@ -3045,6 +3093,7 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(: Requests::RequestClient::TransferLease::No;auto network_transport = ResourceLoader::the().load(load_request, on_headers_received, on_data_received, on_cached_body_available, on_complete, transfer_lease);if (network_transport) {+ engine_record->report_network_activity(network_transport->request_id(), network_request_started(load_request, *request));delivery_gate->attach_transport(*network_transport);network_transport->set_on_teardown([delivery_gate, channel, body_pump = GC::Root { body_pump }](Requests::Request::TeardownReason reason) {tear_down_network_body(*delivery_gate, *channel, reason);@@ -3061,8 +3110,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(}// To transmit request’s body body, run these steps:- // NB: Only a CORS preflight's fetch params lack an engine record, and a preflight has no request body algorithms.- if (auto* engine_record = fetch_params.engine_record()) {+ // NB: A CORS preflight's fetch params have no request body algorithms.+ if (!fetch_params.is_cors_preflight()) {auto& event_sink = engine_record->event_sink();// 1. If body is null and fetchParams’s process request end-of-body is non-null, then queue a fetch task given@@ -3164,6 +3213,13 @@ GC::Ref<PendingResponse> cors_preflight_fetch(JS::Realm& realm, Infrastructure::auto preflight_controller = GC::make_root(Infrastructure::FetchController::create(controller_registry));auto preflight_algorithms = Infrastructure::FetchAlgorithms::create(Infrastructure::FetchAlgorithms::Input { Engine::BodyIntent::DrainAndDiscard });auto preflight_fetch_params = Infrastructure::FetchParams::create(*preflight_controller, preflight, preflight_algorithms, timing_info, fetch_params.loader_config_snapshot());+ // AD-HOC: The preflight's network request is loaded for the page of the fetch it is for, and reported as one of+ // that fetch's network requests.+ preflight_controller->set_page(fetch_params.controller()->page());+ preflight_controller->set_preflighted_fetch_controller(fetch_params.controller());+ VERIFY(fetch_params.engine_record());+ preflight_fetch_params->set_engine_record(*fetch_params.engine_record());+ preflight_fetch_params->set_is_cors_preflight();auto returned_pending_response = PendingResponse::create(fetch_params);diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cppindex a177067f427..b313a6131be 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp@@ -16,6 +16,7 @@#include <LibWeb/HTML/Scripting/Agent.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/StructuredSerialize.h>+#include <LibWeb/Page/Page.h>#include <LibWeb/Page/RenderingStats.h>#include <LibWeb/WebDriver/BiDi/BiDi.h>#include <LibWeb/WebDriver/BiDi/Network.h>@@ -56,6 +57,8 @@ void FetchController::visit_edges(JS::Cell::Visitor& visitor)visitor.visit(m_next_manual_redirect_steps);visitor.visit(m_algorithms);visitor.visit(m_task_destination);+ visitor.visit(m_page);+ visitor.visit(m_preflighted_fetch_controller);visitor.visit(m_pending_preloaded_response);visitor.visit(m_stop_steps);visitor.visit(m_pending_responses);@@ -121,6 +124,12 @@ GC::Ref<FetchAlgorithms const> FetchController::algorithms() constreturn *m_algorithms;}+GC::Ref<Page> FetchController::page() const+{+ VERIFY(m_page);+ return *m_page;+}+void FetchController::set_network_transport(Engine::NetworkTransportHandle& network_transport){set_body_transport(network_transport);diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.hindex 5cc67d25fea..8ab768baeee 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchController.h@@ -81,6 +81,12 @@ public:[[nodiscard]] TaskDestination const& task_destination() const { return m_task_destination; }void set_task_destination(TaskDestination task_destination) { m_task_destination = move(task_destination); }+ // The page of the realm that started the fetch.+ [[nodiscard]] GC::Ref<Page> page() const;+ void set_page(Page& page) { m_page = page; }++ void set_preflighted_fetch_controller(FetchController& controller) { m_preflighted_fetch_controller = controller; }+// Moves the fetch, before its response has arrived, to another task destination and body intent.void retarget(TaskDestination, Engine::BodyIntent);@@ -168,6 +174,12 @@ private:// task destination (default null)// Null, a global object, or a parallel queue.TaskDestination m_task_destination;+ GC::Ptr<Page> m_page;++ // A CORS preflight's controller keeps alive the controller of the fetch the preflight is for, which the+ // preflight's requests report to.+ GC::Ptr<FetchController> m_preflighted_fetch_controller;+bool m_is_keepalive { false };// NB: Assumes one waiting consumer for a pending preloaded response.diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cppindex 7b1ad17fdd2..27a3c868dc2 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.cpp@@ -35,6 +35,7 @@ FetchParams::FetchParams(FetchParams const& params), m_blob_url_entry(params.m_blob_url_entry), m_loader_config(params.m_loader_config), m_engine_record(params.m_engine_record)+ , m_is_cors_preflight(params.m_is_cors_preflight){}diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.hindex abd858f38bd..d4ccbb60610 100644--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchParams.h@@ -66,10 +66,14 @@ public:[[nodiscard]] Engine::StartFetchInput start_fetch_input(Engine::FetchId, NonnullOwnPtr<Engine::EngineEventSink>) const;- // Set by the fetch engine when it runs main fetch's in-parallel steps, and shared with copies made after that.+ // Set by the fetch engine when it runs main fetch's in-parallel steps, and shared with copies made after that. A+ // CORS preflight's fetch params share the record of the fetch the preflight is for.[[nodiscard]] Engine::FetchEngineRecord* engine_record() const { return m_engine_record; }void set_engine_record(NonnullRefPtr<Engine::FetchEngineRecord> engine_record) const { m_engine_record = move(engine_record); }+ [[nodiscard]] bool is_cors_preflight() const { return m_is_cors_preflight; }+ void set_is_cors_preflight() { m_is_cors_preflight = true; }+private:FetchParams(NonnullRefPtr<Request>, GC::Ref<FetchAlgorithms const>, FetchController&, NonnullRefPtr<FetchTimingInfo>, NonnullRefPtr<LoaderConfigSnapshot const>);FetchParams(FetchParams const&);@@ -114,6 +118,8 @@ private:NonnullRefPtr<LoaderConfigSnapshot const> m_loader_config;mutable RefPtr<Engine::FetchEngineRecord> m_engine_record;++ bool m_is_cors_preflight { false };};}diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 13dc85ca8de..0dab9f004d2 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -33,6 +33,7 @@ namespace Web::Fetch::Engine {class FetchBodyDeliveryGate;class FetchByteChannel;+class FetchEngineRecord;class WholeBodyTransport;}@@ -41,6 +42,7 @@ class WholeBodyTransport;// that fetch gives it, which hold the cells they use in roots.GC_UNTRACED_CAPTURE(Web::Fetch::Engine::FetchBodyDeliveryGate);GC_UNTRACED_CAPTURE(Web::Fetch::Engine::FetchByteChannel);+GC_UNTRACED_CAPTURE(Web::Fetch::Engine::FetchEngineRecord);GC_UNTRACED_CAPTURE_WITH_ROOTED_CALLBACKS(Web::Fetch::Engine::WholeBodyTransport);GC_UNTRACED_CAPTURE(Gfx::Typeface);GC_UNTRACED_CAPTURE(HTTP::HeaderList);@@ -589,6 +591,12 @@ class WholeBodyTransport;}+namespace Web::Fetch::Engine::Event {++struct NetworkActivity;++}+namespace Web::Fetch::Fetching {class PendingResponse;diff --git a/Libraries/LibWeb/HTML/Scripting/Agent.h b/Libraries/LibWeb/HTML/Scripting/Agent.hindex 380d3e4ef3c..02635cc5ed0 100644--- a/Libraries/LibWeb/HTML/Scripting/Agent.h+++ b/Libraries/LibWeb/HTML/Scripting/Agent.h@@ -11,6 +11,7 @@#include <LibJS/Forward.h>#include <LibJS/Runtime/Agent.h>#include <LibWeb/Fetch/Engine/FetchExecutor.h>+#include <LibWeb/Fetch/Engine/NetworkActivityObservers.h>#include <LibWeb/Fetch/Infrastructure/FetchControllerRegistry.h>#include <LibWeb/Forward.h>#include <LibWeb/HTML/EventLoop/Task.h>@@ -37,6 +38,8 @@ struct WEB_API Agent : public JS::Agent {// Set by whatever runs the agent's thread, before the agent fetches anything.RefPtr<Fetch::Engine::FetchExecutor> fetch_executor;+ NonnullRefPtr<Fetch::Engine::NetworkActivityObservers> network_activity_observers { Fetch::Engine::NetworkActivityObservers::create() };+// Rooted by Bindings::create_global_object_wrapper() until Bindings::cache_global_object_wrapper() runs.Vector<GC::Root<JS::HostObject>> global_object_wrappers_of_realms_being_set_up;diff --git a/Libraries/LibWeb/Loader/ResourceLoader.cpp b/Libraries/LibWeb/Loader/ResourceLoader.cppindex 6e482ec8984..ca0878b8d83 100644--- a/Libraries/LibWeb/Loader/ResourceLoader.cpp+++ b/Libraries/LibWeb/Loader/ResourceLoader.cpp@@ -486,7 +486,7 @@ RefPtr<Fetch::Engine::NetworkTransportHandle> ResourceLoader::load(LoadRequest&request.start_timer();if (should_block_request(request)) {- on_complete->function()(false, {}, "Request was blocked"sv);+ on_complete->function()(false, {}, "Request was blocked"sv, {});return nullptr;}@@ -496,13 +496,13 @@ RefPtr<Fetch::Engine::NetworkTransportHandle> ResourceLoader::load(LoadRequest&[on_headers_received = move(on_headers_received), on_data_received = move(on_data_received), on_complete, request](ReadonlyBytes data, Requests::RequestTimingInfo const& timing_info, HTTP::HeaderList const& response_headers) {log_success(request);on_headers_received->function()(nullptr, response_headers, {}, {}, Requests::CacheState::NotCached);- on_data_received->function()(Requests::ResponseData::from_bytes(data));- on_complete->function()(true, timing_info, {});+ on_data_received->function()(nullptr, Requests::ResponseData::from_bytes(data));+ on_complete->function()(true, timing_info, {}, {});},GC::create_function(m_heap, GC::captures(on_complete, request), [](auto& on_complete, auto& request, ByteString const& message) {log_failure(request, message);Requests::RequestTimingInfo fixme_implement_timing_info {};- on_complete->function()(false, fixme_implement_timing_info, StringView(message));+ on_complete->function()(false, fixme_implement_timing_info, StringView(message), {});}));return nullptr;}@@ -512,12 +512,12 @@ RefPtr<Fetch::Engine::NetworkTransportHandle> ResourceLoader::load(LoadRequest&request,[on_headers_received = move(on_headers_received), on_data_received = move(on_data_received), on_complete](FileLoadResult const& load_result) {on_headers_received->function()(nullptr, load_result.response_headers, {}, {}, Requests::CacheState::NotCached);- on_data_received->function()(Requests::ResponseData::from_bytes(load_result.data));- on_complete->function()(true, load_result.timing_info, {});+ on_data_received->function()(nullptr, Requests::ResponseData::from_bytes(load_result.data));+ on_complete->function()(true, load_result.timing_info, {}, {});},[on_complete](ByteString const& message) {Requests::RequestTimingInfo fixme_implement_timing_info {};- on_complete->function()(false, fixme_implement_timing_info, StringView(message));+ on_complete->function()(false, fixme_implement_timing_info, StringView(message), {});});return nullptr;}@@ -528,12 +528,12 @@ RefPtr<Fetch::Engine::NetworkTransportHandle> ResourceLoader::load(LoadRequest&[request, on_headers_received = move(on_headers_received), on_data_received = move(on_data_received), on_complete](FileLoadResult const& load_result) {log_success(request);on_headers_received->function()(nullptr, load_result.response_headers, {}, {}, Requests::CacheState::NotCached);- on_data_received->function()(Requests::ResponseData::from_bytes(load_result.data));- on_complete->function()(true, load_result.timing_info, {});+ on_data_received->function()(nullptr, Requests::ResponseData::from_bytes(load_result.data));+ on_complete->function()(true, load_result.timing_info, {}, {});},[on_complete, request](ByteString const& message) {log_failure(request, message);- on_complete->function()(false, {}, StringView(message));+ on_complete->function()(false, {}, StringView(message), {});});return nullptr;@@ -542,7 +542,7 @@ RefPtr<Fetch::Engine::NetworkTransportHandle> ResourceLoader::load(LoadRequest&if (!url.scheme().is_one_of("http"sv, "https"sv)) {auto not_implemented_error = ByteString::formatted("Protocol not implemented: {}", url.scheme());log_failure(request, not_implemented_error);- on_complete->function()(false, {}, not_implemented_error);+ on_complete->function()(false, {}, not_implemented_error, {});return nullptr;}@@ -551,46 +551,43 @@ RefPtr<Fetch::Engine::NetworkTransportHandle> ResourceLoader::load(LoadRequest&dbgln("FIXME: Evaluate the PAC file to find the proxy for {}; failing the request", url);auto error = "PAC proxy configurations are not supported"sv;log_failure(request, error);- on_complete->function()(false, {}, error);+ on_complete->function()(false, {}, error, {});return nullptr;}auto protocol_request = start_network_request(request, transfer_lease);if (!protocol_request) {- on_complete->function()(false, {}, "Failed to start network request"sv);+ on_complete->function()(false, {}, "Failed to start network request"sv, {});return nullptr;}auto network_transport = Fetch::Engine::NetworkTransportHandle::create(*protocol_request);- auto protocol_headers_received = [on_headers_received = move(on_headers_received), request, &protocol_request = *protocol_request, network_transport](auto const& response_headers, auto status_code, auto const& reason_phrase, auto cache_state) {- if (auto page = request.page())- page->client().page_did_receive_network_response_headers(protocol_request.id(), status_code.value_or(0), reason_phrase, response_headers->headers(), cache_state);-+ auto protocol_headers_received = [on_headers_received = move(on_headers_received), network_transport](auto const& response_headers, auto status_code, auto const& reason_phrase, auto cache_state) {on_headers_received->function()(network_transport.ptr(), response_headers, move(status_code), reason_phrase, cache_state);};- auto protocol_data_received = [on_data_received = move(on_data_received), request, request_id = protocol_request->id()](auto data) {- if (auto page = request.page())- page->client().page_did_receive_network_response_body(request_id, data.bytes());- on_data_received->function()(move(data));+ auto protocol_data_received = [on_data_received = move(on_data_received), network_transport](auto data) {+ on_data_received->function()(network_transport.ptr(), move(data));};- auto protocol_complete = [this, on_complete = move(on_complete), request, &protocol_request = *protocol_request](u64 total_size, Requests::RequestTimingInfo const& timing_info, Optional<Requests::NetworkError> const& network_error) {+ auto protocol_complete = [this, on_complete = move(on_complete), request, &protocol_request = *protocol_request, network_transport](u64 total_size, Requests::RequestTimingInfo const& timing_info, Optional<Requests::NetworkError> const& network_error) {finish_network_request(protocol_request);- if (auto page = request.page())- page->client().page_did_finish_network_request(protocol_request.id(), total_size, timing_info, network_error);-+ NetworkRequestEnd network_request_end {+ .request_id = network_transport->request_id(),+ .total_size = total_size,+ .network_error = network_error,+ };if (!network_error.has_value()) {log_success(request);- on_complete->function()(true, timing_info, {});+ on_complete->function()(true, timing_info, {}, network_request_end);} else {auto error_description = MUST(String::formatted("Request finished with error: {}",network_error_to_string(*network_error)));log_failure(request, error_description);- on_complete->function()(false, timing_info, error_description);+ on_complete->function()(false, timing_info, error_description, network_request_end);}};@@ -638,14 +635,6 @@ RefPtr<Requests::Request> ResourceLoader::start_network_request(LoadRequest consreturn nullptr;}- if (auto page = request.page()) {- Optional<String> initiator_type_string;- if (request.initiator_type().has_value())- initiator_type_string = MUST(Fetch::Infrastructure::initiator_type_to_string(request.initiator_type().value()).view().to_utf8());- auto referrer_policy = MUST(String::from_utf8(ReferrerPolicy::to_string(request.referrer_policy())));- page->client().page_did_start_network_request(protocol_request->id(), request.url().value(), request.method(), request.headers().headers(), request.body(), move(initiator_type_string), referrer_policy, request.is_navigation_request(), request.priority());- }-m_active_requests.set(*protocol_request);return protocol_request;}diff --git a/Libraries/LibWeb/Loader/ResourceLoader.h b/Libraries/LibWeb/Loader/ResourceLoader.hindex 3329ad060cd..1ef97872317 100644--- a/Libraries/LibWeb/Loader/ResourceLoader.h+++ b/Libraries/LibWeb/Loader/ResourceLoader.h@@ -18,10 +18,12 @@#include <LibHTTP/HeaderList.h>#include <LibRequests/CacheState.h>#include <LibRequests/Forward.h>+#include <LibRequests/NetworkError.h>#include <LibRequests/Request.h>#include <LibRequests/RequestClient.h>#include <LibRequests/RequestTimingInfo.h>#include <LibURL/URL.h>+#include <LibWeb/Fetch/Engine/Ids.h>#include <LibWeb/Forward.h>#include <LibWebCommon/Loader/NavigatorCompatibilityMode.h>@@ -47,10 +49,19 @@ public:// for requests without a site or without a client for that site.void set_client(Optional<Utf16String> const& top_level_site, NonnullRefPtr<Requests::RequestClient>);+ // A callback's transport is that of the RequestServer request the load started, or null for a load that started+ // none.using OnHeadersReceived = GC::Function<void(Fetch::Engine::NetworkTransportHandle*, HTTP::HeaderList const& response_headers, Optional<u32> status_code, Optional<String> const& reason_phrase, Requests::CacheState cache_state)>;- using OnDataReceived = GC::Function<void(Requests::ResponseData data)>;+ using OnDataReceived = GC::Function<void(Fetch::Engine::NetworkTransportHandle*, Requests::ResponseData data)>;using OnCachedBodyAvailable = GC::Function<void(Core::ImmutableBytes data)>;- using OnComplete = GC::Function<void(bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message)>;++ // What RequestServer reported at the end of the request a load started.+ struct NetworkRequestEnd {+ Fetch::Engine::RequestId request_id;+ u64 total_size { 0 };+ Optional<Requests::NetworkError> network_error;+ };+ using OnComplete = GC::Function<void(bool success, Requests::RequestTimingInfo const& timing_info, Optional<StringView> error_message, Optional<NetworkRequestEnd> const& network_request_end)>;// A request keeps roots into the heap of the agent that made it.void stop_all_requests();diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cppindex 88dc5d6e11d..5ea99315df4 100644--- a/Libraries/LibWeb/Page/Page.cpp+++ b/Libraries/LibWeb/Page/Page.cpp@@ -26,6 +26,7 @@#include <LibWeb/Editing/SpellCheckController.h>#include <LibWeb/Editing/SpellingMarkers.h>#include <LibWeb/Editing/WritingSuggestionController.h>+#include <LibWeb/Fetch/Engine/NetworkActivity.h>#include <LibWeb/HTML/BrowsingContext.h>#include <LibWeb/HTML/CheckUnloadingCanceledState.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>@@ -1246,6 +1247,25 @@ void Page::did_complete_window_rect_request(u64 completion_id)m_window_rect_observer->function()({ window_position(), window_size() }, completion_id);}+void Page::did_receive_network_activity(Fetch::Engine::Event::NetworkActivity const& network_activity)+{+ auto request_id = network_activity.request_id.value();+ network_activity.activity.visit(+ [&](Fetch::Engine::Event::NetworkActivity::RequestStarted const& started) {+ auto referrer_policy = MUST(String::from_utf8(ReferrerPolicy::to_string(started.referrer_policy)));+ client().page_did_start_network_request(request_id, started.url, started.method, started.headers, started.body.bytes(), started.initiator_type, referrer_policy, started.is_navigation_request, started.priority);+ },+ [&](Fetch::Engine::Event::NetworkActivity::ResponseHeaders const& headers) {+ client().page_did_receive_network_response_headers(request_id, headers.status_code, headers.reason_phrase, headers.headers, headers.cache_state);+ },+ [&](Fetch::Engine::Event::NetworkActivity::ResponseBodyBytes const& body_bytes) {+ client().page_did_receive_network_response_body(request_id, body_bytes.bytes.bytes());+ },+ [&](Fetch::Engine::Event::NetworkActivity::RequestFinished const& finished) {+ client().page_did_finish_network_request(request_id, finished.total_size, finished.timing_info, finished.network_error);+ });+}+// NB: The response is named as a member of the page, so that the function waiting for it captures only the page.template<auto response>static auto spin_event_loop_until_dialog_closed(Page& page, HTML::EventLoop* event_loop = nullptr, SourceLocation location = SourceLocation::current())diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex 81fa8c13c3b..cd1b5f9445a 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -289,6 +289,8 @@ public:void did_complete_window_rect_request(u64 completion_id);void set_window_rect_observer(GC::Ptr<GC::Function<void(DevicePixelRect, u64)>> window_rect_observer) { m_window_rect_observer = window_rect_observer; }+ void did_receive_network_activity(Fetch::Engine::Event::NetworkActivity const&);+void did_request_alert(Utf16String const& message);void alert_closed();diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 8b2e25af4f3..bc3cddfa471 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -50,6 +50,7 @@#include <LibWeb/HTML/LocalTraversableNavigable.h>#include <LibWeb/HTML/NavigableContainer.h>#include <LibWeb/HTML/RemoteNavigable.h>+#include <LibWeb/HTML/Scripting/Agent.h>#include <LibWeb/HTML/Scripting/ClassicScript.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/RemoteEnvironmentSettings.h>@@ -152,6 +153,7 @@ PageClient::PageClient(PageHost& owner, Web::PageId id, Optional<Web::HTML::Cros, m_page(Web::Page::create(*this)), m_id(id), m_pending_root_navigable_id(pending_root_navigable_id)+ , m_network_activity_observers(Web::HTML::surrounding_agent().network_activity_observers){setup_palette();@@ -176,6 +178,13 @@ PageClient::PageClient(PageHost& owner, Web::PageId id, Optional<Web::HTML::CrosPageClient::~PageClient() = default;+void PageClient::finalize()+{+ Base::finalize();+ if (m_has_devtools_client)+ m_network_activity_observers->page_did_lose_devtools_client();+}+void PageClient::visit_edges(JS::Cell::Visitor& visitor){Base::visit_edges(visitor);@@ -1797,6 +1806,10 @@ void PageClient::page_did_close()// The heap sweeps a closed page in slices, so its timers can still fire once the cells they would use are gone.m_is_closed = true;+ // A closed page has no DevTools client.+ if (exchange(m_has_devtools_client, false))+ m_network_activity_observers->page_did_lose_devtools_client();+// NOTE: This only removes the strong reference the PageHost has for this PageClient.// It will be GC'd 'later'.m_owner.remove_page({}, m_id);@@ -2547,6 +2560,10 @@ void PageClient::set_has_devtools_client(bool has_devtools_client)if (m_has_devtools_client == has_devtools_client)return;m_has_devtools_client = has_devtools_client;+ if (has_devtools_client)+ m_network_activity_observers->page_did_gain_devtools_client();+ else+ m_network_activity_observers->page_did_lose_devtools_client();for (auto& navigable : Web::HTML::all_local_navigables()) {if (&navigable->page() != &page())diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex 80eacced103..53397632d9c 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -17,6 +17,7 @@#include <LibWeb/CSS/StyleSheetIdentifier.h>#include <LibWeb/ContentSecurityPolicy/Directives/Directive.h>#include <LibWeb/DOM/AccessibilityChangeTracker.h>+#include <LibWeb/Fetch/Engine/NetworkActivityObservers.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/SameDocumentNavigationEntry.h>#include <LibWeb/HTML/Scripting/ConsoleInputCompletion.h>@@ -183,6 +184,7 @@ private:PageClient(PageHost&, Web::PageId id, Optional<Web::HTML::CrossProcessId>);virtual void visit_edges(JS::Cell::Visitor&) override;+ virtual void finalize() override;enum class FrameTimerPurpose {Inactive,@@ -507,6 +509,7 @@ private:Optional<i64> m_pending_accessibility_focus;bool m_has_devtools_client { false };+ NonnullRefPtr<Web::Fetch::Engine::NetworkActivityObservers> m_network_activity_observers;bool m_devtools_takes_console_messages { false };bool m_devtools_takes_console_errors { false };diff --git a/Services/WebContent/Worker/WorkerThread.cpp b/Services/WebContent/Worker/WorkerThread.cppindex 67865d45915..c8efbde4b4a 100644--- a/Services/WebContent/Worker/WorkerThread.cpp+++ b/Services/WebContent/Worker/WorkerThread.cpp@@ -62,7 +62,8 @@ static intptr_t run_worker_thread(IPC::TransportHandle const& worker_handle, WebCore::EventLoop event_loop;Web::Bindings::initialize_agent(agent_type);- Web::HTML::surrounding_agent().fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor();+ auto& agent = Web::HTML::surrounding_agent();+ agent.fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor(agent.network_activity_observers);auto event_loop_reference = Core::EventLoop::current_weak();{diff --git a/Services/WebContent/main.cpp b/Services/WebContent/main.cppindex 74ee5530358..ae131af5340 100644--- a/Services/WebContent/main.cpp+++ b/Services/WebContent/main.cpp@@ -283,7 +283,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)Web::Bindings::set_collect_garbage_on_every_allocation_in_new_agents(collect_garbage_on_every_allocation);Web::Bindings::initialize_agent(Web::HTML::AgentType::SimilarOriginWindow);- Web::HTML::surrounding_agent().fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor();+ auto& agent = Web::HTML::surrounding_agent();+ agent.fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor(agent.network_activity_observers);if (stats_log)Web::Bindings::main_thread_vm().heap().enable_stats();diff --git a/Tests/LibWeb/TestAgentThreads.cpp b/Tests/LibWeb/TestAgentThreads.cppindex 59339376a6e..f9bf9ec06e0 100644--- a/Tests/LibWeb/TestAgentThreads.cpp+++ b/Tests/LibWeb/TestAgentThreads.cpp@@ -24,6 +24,8 @@#include <LibWeb/Fetch/Fetching/FetchEngine.h>#include <LibWeb/Fetch/Fetching/Fetching.h>#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>+#include <LibWeb/Fetch/Infrastructure/FetchController.h>+#include <LibWeb/Fetch/Infrastructure/FetchParams.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>#include <LibWeb/FileAPI/BlobURLStore.h>#include <LibWeb/HTML/DedicatedWorkerGlobalScope.h>@@ -411,7 +413,8 @@ public:TestAgent(){Web::Bindings::initialize_agent(Web::HTML::AgentType::DedicatedWorker);- Web::HTML::surrounding_agent().fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor();+ auto& agent = Web::HTML::surrounding_agent();+ agent.fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor(agent.network_activity_observers);Web::HTML::current_event_loop().set_on_destroyed([] {Core::EventLoop::current().quit(0);});@@ -485,6 +488,27 @@ public:return request;}+ // Fetches the URL, and runs the worker's tasks until the fetch's request is done. Returns the fetch's params.+ NonnullRefPtr<Web::Fetch::Infrastructure::FetchParams> fetch_until_done(StringView url)+ {+ auto request = Web::Fetch::Infrastructure::Request::create();+ request->set_url_list({ *URL::Parser::basic_parse(url) });+ request->set_client(m_settings->address());+ auto algorithms = Web::Fetch::Infrastructure::FetchAlgorithms::create(Web::Fetch::Infrastructure::FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard });++ GC::Ptr<Web::Fetch::Infrastructure::FetchController> controller;+ {+ Web::HTML::TemporaryExecutionContext execution_context { m_settings->realm(), Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };+ controller = Web::Fetch::Fetching::fetch(m_settings->realm(), request, algorithms);+ }+ auto fetch_params = controller->original_fetch_params();+ VERIFY(fetch_params);+ Web::HTML::current_event_loop().spin_until(GC::create_function(GC::Heap::the(), GC::captures(request), [](auto& request) {+ return request->done();+ }));+ return fetch_params.release_nonnull();+ }+// What the host of a worker does once the worker's event loop is destroyed.void shut_down(){@@ -651,6 +675,25 @@ TEST_CASE(a_fetch_started_just_before_close_never_runs_its_in_parallel_steps)});}+TEST_CASE(a_worker_agents_fetch_reads_the_network_activity_observers_of_that_agent)+{+ set_up_process();+ run_on_agent_threads(1, [](size_t) {+ Core::EventLoop event_loop;+ TestAgent agent;++ {+ auto fetch_params = agent.fetch_until_done("about:blank"sv);+ auto const& observers = *Web::HTML::surrounding_agent().network_activity_observers;+ VERIFY(fetch_params->engine_record());+ EXPECT_EQ(&fetch_params->engine_record()->network_activity_observers(), &observers);+ EXPECT(!observers.has_devtools_client());+ }++ agent.close_and_shut_down();+ });+}+TEST_CASE(navigator_compatibility_reaches_every_agent){set_up_process();diff --git a/Tests/LibWeb/TestFaviconDecoding.cpp b/Tests/LibWeb/TestFaviconDecoding.cppindex e7d73d739a2..97d523f7b30 100644--- a/Tests/LibWeb/TestFaviconDecoding.cpp+++ b/Tests/LibWeb/TestFaviconDecoding.cpp@@ -54,7 +54,8 @@ TEST_CASE(each_favicon_is_decoded_once)Web::Platform::ImageCodecPlugin::install(image_codec);auto realm = Web::Bindings::create_a_principal_javascript_realm();- Web::HTML::surrounding_agent().fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor();+ auto& agent = Web::HTML::surrounding_agent();+ agent.fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor(agent.network_activity_observers);auto& page = Web::Bindings::principal_host_defined_page(*realm);auto traversable = Web::HTML::LocalTraversableNavigable::create_a_new_top_level_traversable(page, nullptr, {});page.set_top_level_traversable(traversable);diff --git a/Tests/LibWeb/TestFetchAlgorithms.cpp b/Tests/LibWeb/TestFetchAlgorithms.cppindex d2cbb29daf8..d7ba1e8591e 100644--- a/Tests/LibWeb/TestFetchAlgorithms.cpp+++ b/Tests/LibWeb/TestFetchAlgorithms.cpp@@ -22,6 +22,7 @@#include <LibWeb/Fetch/Fetching/Fetching.h>#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>#include <LibWeb/Fetch/Infrastructure/FetchController.h>+#include <LibWeb/Fetch/Infrastructure/FetchParams.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>@@ -31,11 +32,13 @@#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/Loader/ResourceLoader.h>+#include <LibWeb/Page/Page.h>#include <LibWeb/Streams/ReadableStream.h>#include <LibWeb/Streams/ReadableStreamDefaultReader.h>#include <LibWeb/WebDriver/BiDi/BiDi.h>#include <LibWeb/WebIDL/DOMException.h>+using Web::Fetch::Engine::Event::NetworkActivity;using Web::Fetch::Engine::Event::ReadRequestBodyStream;using Web::Fetch::Engine::Event::RequestBodyEndOfBody;using Web::Fetch::Engine::Event::RequestBodyProgress;@@ -65,7 +68,8 @@ struct FetchHarness {, realm(document->relevant_settings_object().realm()){// Each case has an event loop of its own, which the window agent's fetches have to run on.- Web::HTML::surrounding_agent().fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor();+ auto& agent = Web::HTML::surrounding_agent();+ agent.fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor(agent.network_activity_observers);}// An unknown scheme: scheme fetch returns a network error, which has no body.@@ -85,15 +89,18 @@ struct FetchHarness {return request;}- GC::Ref<Web::Fetch::Infrastructure::FetchController> fetch(Request& request, FetchAlgorithms::Input input) const+ // Fetches from the harness's document, or from the given one.+ GC::Ref<Web::Fetch::Infrastructure::FetchController> fetch(Request& request, FetchAlgorithms::Input input, GC::Ptr<Web::DOM::Document> from_document = {}) const{- return fetch_with(request, FetchAlgorithms::create(move(input)));+ return fetch_with(request, FetchAlgorithms::create(move(input)), from_document);}- GC::Ref<Web::Fetch::Infrastructure::FetchController> fetch_with(Request& request, FetchAlgorithms const& algorithms) const+ GC::Ref<Web::Fetch::Infrastructure::FetchController> fetch_with(Request& request, FetchAlgorithms const& algorithms, GC::Ptr<Web::DOM::Document> from_document = {}) const{- Web::HTML::TemporaryExecutionContext execution_context { *realm, Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };- return Web::Fetch::Fetching::fetch(*realm, request, algorithms);+ auto& settings = (from_document ? *from_document : *document).relevant_settings_object();+ request.set_client(settings.address());+ Web::HTML::TemporaryExecutionContext execution_context { settings.realm(), Web::HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };+ return Web::Fetch::Fetching::fetch(settings.realm(), request, algorithms);}// Runs the fetch's steps and the tasks they queue until the condition holds, or for ten seconds.@@ -616,3 +623,234 @@ TEST_CASE(a_request_fetched_again_keeps_its_webdriver_bidi_request_id)EXPECT_EQ(events->request_ids[3], events->request_ids[2]);EXPECT_NE(events->request_ids[2], events->request_ids[0]);}++namespace {++// A page client that records the network activity reported to it.+class NetworkActivityPageClient final : public Web::PageClient {+ GC_CELL(NetworkActivityPageClient, Web::PageClient);+ GC_DECLARE_ALLOCATOR(NetworkActivityPageClient);++public:+ static GC::Ref<NetworkActivityPageClient> create(GC::Heap& heap, Web::PageId id)+ {+ auto client = heap.allocate<NetworkActivityPageClient>(id);+ client->m_page = Web::Page::create(client);+ return client;+ }++ virtual Web::PageId id() const override { return m_id; }+ virtual Web::Page& page() override { return *m_page; }+ virtual Web::Page const& page() const override { return *m_page; }+ virtual bool is_connection_open() const override { return true; }+ virtual Gfx::Palette palette() const override { VERIFY_NOT_REACHED(); }+ virtual Web::DevicePixelRect screen_rect() const override { return {}; }+ virtual double zoom_level() const override { return 1; }+ virtual double device_pixel_ratio() const override { return 1; }+ virtual double device_pixels_per_css_pixel() const override { return 1; }+ virtual Web::CSS::PreferredColorScheme preferred_color_scheme() const override { return Web::CSS::PreferredColorScheme::Auto; }+ virtual Web::CSS::PreferredContrast preferred_contrast() const override { return Web::CSS::PreferredContrast::Auto; }+ virtual Web::CSS::PreferredMotion preferred_motion() const override { return Web::CSS::PreferredMotion::NoPreference; }+ virtual size_t screen_count() const override { return 1; }+ virtual Queue<Web::QueuedInputEvent>& input_event_queue() override { VERIFY_NOT_REACHED(); }+ virtual void report_finished_handling_input_event(Web::PageId, u64, Web::EventResult) override { }+ virtual Web::HTML::CrossProcessId allocate_cross_process_id() override { return { 2, s_next_cross_process_id++ }; }+ virtual void request_frame() override { }+ virtual void request_file(Web::FileRequest) override { }+ virtual bool is_headless() const override { return true; }++ virtual void page_did_start_network_request(u64 request_id, URL::URL const& url, ByteString const& method, Vector<HTTP::Header> const& request_headers, ReadonlyBytes request_body, Optional<String> initiator_type, String const& referrer_policy, bool is_navigation_request, Web::Fetch::Infrastructure::Request::Priority priority) override+ {+ VERIFY(request_headers.size() == 1);+ calls.append(ByteString::formatted("start {} {} {} {}: {} body {} initiator {} referrer policy {} navigation {} priority {}", request_id, method, url, request_headers[0].name, request_headers[0].value, StringView { request_body }, initiator_type.value_or("none"_string), referrer_policy, is_navigation_request, to_underlying(priority)));+ }++ virtual void page_did_receive_network_response_headers(u64 request_id, u32 status_code, Optional<String> reason_phrase, Vector<HTTP::Header> const& response_headers, Requests::CacheState cache_state) override+ {+ VERIFY(response_headers.size() == 1);+ calls.append(ByteString::formatted("headers {} {} {} {}: {} cache state {}", request_id, status_code, reason_phrase.value_or("none"_string), response_headers[0].name, response_headers[0].value, to_underlying(cache_state)));+ }++ virtual void page_did_receive_network_response_body(u64 request_id, ReadonlyBytes data) override+ {+ calls.append(ByteString::formatted("body {} {}", request_id, StringView { data }));+ }++ virtual void page_did_finish_network_request(u64 request_id, u64 body_size, Requests::RequestTimingInfo const& timing_info, Optional<Requests::NetworkError> const& network_error) override+ {+ auto error = network_error.has_value() ? Requests::network_error_to_string(*network_error) : "none"sv;+ calls.append(ByteString::formatted("finish {} {} encoded {} error {}", request_id, body_size, timing_info.encoded_body_size, error));+ }++ Vector<ByteString> calls;++private:+ explicit NetworkActivityPageClient(Web::PageId id)+ : m_id(id)+ {+ }++ virtual void visit_edges(Visitor& visitor) override+ {+ Base::visit_edges(visitor);+ visitor.visit(m_page);+ }++ GC::Ptr<Web::Page> m_page;+ Web::PageId m_id;+ static inline u64 s_next_cross_process_id { 1 };+};++GC_DEFINE_ALLOCATOR(NetworkActivityPageClient);++}++// The active document of a new top-level traversable of the page.+static GC::Ref<Web::DOM::Document> create_document_of_page(Web::Page& page)+{+ auto traversable = Web::HTML::LocalTraversableNavigable::create_a_new_top_level_traversable(page, nullptr, {});+ page.set_top_level_traversable(traversable);+ return *traversable->active_document();+}++// One of each network activity, of the RequestServer request with the id.+static Vector<NetworkActivity> each_network_activity(u64 request_id)+{+ Vector<NetworkActivity> activities;+ activities.append({+ .request_id = Web::Fetch::Engine::RequestId { request_id },+ .activity = NetworkActivity::RequestStarted {+ .url = URL::Parser::basic_parse("https://example.com/upload"sv).release_value(),+ .method = "POST",+ .headers = { { "Accept"sv, "*/*"sv } },+ .body = Core::ImmutableBytes::adopt(MUST(ByteBuffer::copy("hello"sv.bytes()))),+ .initiator_type = "fetch"_string,+ .referrer_policy = Web::ReferrerPolicy::ReferrerPolicy::NoReferrer,+ .is_navigation_request = false,+ .priority = Web::Fetch::Infrastructure::RequestPriority::High,+ },+ });+ activities.append({+ .request_id = Web::Fetch::Engine::RequestId { request_id },+ .activity = NetworkActivity::ResponseHeaders {+ .status_code = 200,+ .reason_phrase = "OK"_string,+ .headers = { { "Content-Type"sv, "text/plain"sv } },+ .cache_state = Requests::CacheState::Local,+ },+ });+ activities.append({+ .request_id = Web::Fetch::Engine::RequestId { request_id },+ .activity = NetworkActivity::ResponseBodyBytes { Core::ImmutableBytes::adopt(MUST(ByteBuffer::copy("world"sv.bytes()))) },+ });+ activities.append({+ .request_id = Web::Fetch::Engine::RequestId { request_id },+ .activity = NetworkActivity::RequestFinished {+ .total_size = 5,+ .timing_info = { .encoded_body_size = 5 },+ .network_error = Requests::NetworkError::IncompleteContent,+ },+ });+ return activities;+}++TEST_CASE(network_activity_is_reported_to_the_page_of_the_realm_that_started_the_fetch)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ auto& heap = harness.realm->heap();+ auto first_page_client = NetworkActivityPageClient::create(heap, Web::PageId { 1 });+ auto second_page_client = NetworkActivityPageClient::create(heap, Web::PageId { 2 });+ auto first_document = create_document_of_page(first_page_client->page());+ auto second_document = create_document_of_page(second_page_client->page());++ auto first_request = harness.create_request();+ auto first_controller = harness.fetch(first_request, FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard }, first_document);+ auto second_request = harness.create_request();+ auto second_controller = harness.fetch(second_request, FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard }, second_document);++ FetchEventSink first_event_sink { first_controller };+ for (auto& activity : each_network_activity(7))+ first_event_sink.handle_event(move(activity));+ FetchEventSink { second_controller }.handle_event(each_network_activity(8).take_first());++ EXPECT_EQ(first_page_client->calls, (Vector<ByteString> {+ "start 7 POST https://example.com/upload Accept: */* body hello initiator fetch referrer policy no-referrer navigation false priority 0",+ "headers 7 200 OK Content-Type: text/plain cache state 1",+ "body 7 world",+ "finish 7 5 encoded 5 error Connection was closed before entire response was received",+ }));+ EXPECT_EQ(second_page_client->calls, (Vector<ByteString> { "start 8 POST https://example.com/upload Accept: */* body hello initiator fetch referrer policy no-referrer navigation false priority 0" }));++ harness.run_tasks_until(GC::create_function(heap, GC::captures(first_request, second_request), [](auto& first_request, auto& second_request) {+ return first_request->done() && second_request->done();+ }));+}++TEST_CASE(loads_that_start_no_network_request_report_no_network_activity)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;+ ResourceLoaderWithoutRequestServer resource_loader { harness.realm->heap() };++ auto& heap = harness.realm->heap();+ auto page_client = NetworkActivityPageClient::create(heap, Web::PageId { 1 });+ auto document = create_document_of_page(page_client->page());++ // Each load reaches the loader and fails there: one finds no RequestServer, the other no resource.+ auto record = make_ref_counted<AlgorithmCalls>();+ for (auto url : { "http://127.0.0.1:8000/"sv, "resource://ladybird/no-such-resource"sv }) {+ FetchAlgorithms::Input input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard };+ input.process_response = GC::create_function(heap, GC::captures(record), [](auto& record, GC::Ref<ResponseView> response) {+ auto const& message = response->network_error_message();+ record->calls.append(message.has_value() && message->starts_with_bytes("Load failed: "sv) ? "failed in the loader"sv : "other"sv);+ });+ auto request = harness.create_request_for(url);+ request->set_destination(Request::Destination::Image);+ (void)harness.fetch(request, move(input), document);+ }++ harness.run_tasks_until(GC::create_function(heap, GC::captures(record), [](auto& record) { return record->calls.size() == 2; }));+ EXPECT_EQ(record->calls, (Vector<StringView> { "failed in the loader"sv, "failed in the loader"sv }));+ EXPECT(page_client->calls.is_empty());+}++TEST_CASE(an_agent_has_a_devtools_client_while_any_page_of_it_has_one)+{+ auto observers = Web::Fetch::Engine::NetworkActivityObservers::create();+ EXPECT(!observers->has_devtools_client());++ observers->page_did_gain_devtools_client();+ observers->page_did_gain_devtools_client();+ observers->page_did_lose_devtools_client();+ EXPECT(observers->has_devtools_client());++ observers->page_did_lose_devtools_client();+ EXPECT(!observers->has_devtools_client());+}++TEST_CASE(a_fetch_reads_the_network_activity_observers_of_its_agent)+{+ Core::EventLoop event_loop;+ install_font_plugin();+ FetchHarness harness;++ auto& heap = harness.realm->heap();+ auto request = harness.create_request();+ auto controller = harness.fetch(request, FetchAlgorithms::Input { Web::Fetch::Engine::BodyIntent::DrainAndDiscard });+ auto fetch_params = controller->original_fetch_params();+ VERIFY(fetch_params);+ harness.run_tasks_until(GC::create_function(heap, GC::captures(request), [](auto& request) { return request->done(); }));++ auto& agent = Web::HTML::surrounding_agent();+ VERIFY(fetch_params->engine_record());+ EXPECT_EQ(&fetch_params->engine_record()->network_activity_observers(), agent.network_activity_observers.ptr());++ agent.network_activity_observers->page_did_gain_devtools_client();+ EXPECT(fetch_params->engine_record()->network_activity_observers().has_devtools_client());+ agent.network_activity_observers->page_did_lose_devtools_client();+ EXPECT(!fetch_params->engine_record()->network_activity_observers().has_devtools_client());+}diff --git a/Tests/LibWeb/TestFetchControllerRegistry.cpp b/Tests/LibWeb/TestFetchControllerRegistry.cppindex cf767d478a7..61c5944f299 100644--- a/Tests/LibWeb/TestFetchControllerRegistry.cpp+++ b/Tests/LibWeb/TestFetchControllerRegistry.cpp@@ -27,6 +27,20 @@ static NEVER_INLINE FetchControllerToken create_unreferenced_controller(FetchConreturn FetchController::create(registry)->token();}+// Returns the token of a controller that only the given CORS preflight's controller references.+static NEVER_INLINE FetchControllerToken create_preflighted_fetch_controller(FetchControllerRegistry& registry, GC::Root<FetchController>& preflight_controller)+{+ auto controller = FetchController::create(registry);+ preflight_controller = GC::make_root(FetchController::create(registry));+ preflight_controller->set_preflighted_fetch_controller(controller);+ return controller->token();+}++static NEVER_INLINE bool is_registered(FetchControllerRegistry const& registry, FetchControllerToken token)+{+ return !!registry.find(token);+}+TEST_SETUP{GC::Heap::set_default_heap_for_testing(test_heap());@@ -60,6 +74,22 @@ TEST_CASE(a_collected_controller_is_not_found)EXPECT(!registry.find(token));}+TEST_CASE(a_cors_preflights_controller_keeps_the_controller_of_its_fetch)+{+ FetchControllerRegistry registry;+ GC::Root<FetchController> preflight_controller;+ auto token = create_preflighted_fetch_controller(registry, preflight_controller);+ GC::scrub_stack_for_testing();++ test_heap().collect_garbage();+ EXPECT(is_registered(registry, token));++ preflight_controller = {};+ GC::scrub_stack_for_testing();+ test_heap().collect_garbage();+ EXPECT(!is_registered(registry, token));+}+TEST_CASE(a_controller_can_be_collected_after_its_registry_is_gone){{diff --git a/Tests/LibWeb/TestFetchEngineMessages.cpp b/Tests/LibWeb/TestFetchEngineMessages.cppindex 63c06b97d44..757e54a1203 100644--- a/Tests/LibWeb/TestFetchEngineMessages.cpp+++ b/Tests/LibWeb/TestFetchEngineMessages.cpp@@ -7,6 +7,7 @@#include <AK/StdLibExtras.h>#include <LibIPC/Transport.h>#include <LibTest/TestCase.h>+#include <LibURL/Parser.h>#include <LibWeb/Fetch/Engine/EngineCommand.h>#include <LibWeb/Fetch/Engine/EngineEvent.h>@@ -140,9 +141,44 @@ TEST_CASE(events_round_trip_their_payloads)events.append(Event::RequestBodyEndOfBody { .body_is_null = true });events.append(Event::ReadRequestBodyStream {});events.append(Event::RequestBodySentFromSource {});+ events.append(Event::NetworkActivity {+ .request_id = RequestId(8),+ .activity = Event::NetworkActivity::RequestStarted {+ .url = URL::Parser::basic_parse("https://example.com/upload"sv).release_value(),+ .method = "POST",+ .headers = { { "Accept"sv, "*/*"sv } },+ .body = Core::ImmutableBytes::adopt(MUST(ByteBuffer::copy("request"sv.bytes()))),+ .initiator_type = "fetch"_string,+ .referrer_policy = Web::ReferrerPolicy::ReferrerPolicy::NoReferrer,+ .is_navigation_request = true,+ .priority = Web::Fetch::Infrastructure::RequestPriority::High,+ },+ });+ events.append(Event::NetworkActivity {+ .request_id = RequestId(9),+ .activity = Event::NetworkActivity::ResponseHeaders {+ .status_code = 203,+ .reason_phrase = "Non-Authoritative"_string,+ .headers = { { "Content-Type"sv, "text/plain"sv } },+ .cache_state = Requests::CacheState::Validated,+ },+ });+ events.append(Event::NetworkActivity {+ .request_id = RequestId(10),+ .activity = Event::NetworkActivity::ResponseBodyBytes { Core::ImmutableBytes::adopt(MUST(ByteBuffer::copy("response"sv.bytes()))) },+ });+ events.append(Event::NetworkActivity {+ .request_id = RequestId(11),+ .activity = Event::NetworkActivity::RequestFinished {+ .total_size = 8,+ .timing_info = { .request_start_microseconds = 40, .encoded_body_size = 8 },+ .network_error = Requests::NetworkError::IncompleteContent,+ },+ });Vector<u64> seen_ids;Vector<StringView> seen_request_body_events;+ Vector<u64> seen_network_request_ids;for (auto const& event : events) {event.visit([&](Event::ResponseDelivery const& delivery) {@@ -184,8 +220,41 @@ TEST_CASE(events_round_trip_their_payloads)seen_request_body_events.append("end of body"sv);},[&](Event::ReadRequestBodyStream const&) { seen_request_body_events.append("read stream"sv); },- [&](Event::RequestBodySentFromSource const&) { seen_request_body_events.append("sent from source"sv); });+ [&](Event::RequestBodySentFromSource const&) { seen_request_body_events.append("sent from source"sv); },+ [&](Event::NetworkActivity const& network_activity) {+ network_activity.activity.visit(+ [&](Event::NetworkActivity::RequestStarted const& started) {+ EXPECT_EQ(started.url.serialize(), "https://example.com/upload"sv);+ EXPECT_EQ(started.method, "POST"sv);+ VERIFY(started.headers.size() == 1);+ EXPECT_EQ(started.headers[0].name, "Accept"sv);+ EXPECT_EQ(started.headers[0].value, "*/*"sv);+ EXPECT_EQ(started.body.bytes(), "request"sv.bytes());+ EXPECT_EQ(started.initiator_type, "fetch"sv);+ EXPECT_EQ(started.referrer_policy, Web::ReferrerPolicy::ReferrerPolicy::NoReferrer);+ EXPECT(started.is_navigation_request);+ EXPECT_EQ(started.priority, Web::Fetch::Infrastructure::RequestPriority::High);+ },+ [&](Event::NetworkActivity::ResponseHeaders const& headers) {+ EXPECT_EQ(headers.status_code, 203u);+ EXPECT_EQ(headers.reason_phrase, "Non-Authoritative"sv);+ VERIFY(headers.headers.size() == 1);+ EXPECT_EQ(headers.headers[0].value, "text/plain"sv);+ EXPECT_EQ(headers.cache_state, Requests::CacheState::Validated);+ },+ [&](Event::NetworkActivity::ResponseBodyBytes const& body_bytes) {+ EXPECT_EQ(body_bytes.bytes.bytes(), "response"sv.bytes());+ },+ [&](Event::NetworkActivity::RequestFinished const& finished) {+ EXPECT_EQ(finished.total_size, 8u);+ EXPECT_EQ(finished.timing_info.request_start_microseconds, 40);+ EXPECT_EQ(finished.timing_info.encoded_body_size, 8);+ EXPECT(finished.network_error == Requests::NetworkError::IncompleteContent);+ });+ seen_network_request_ids.append(network_activity.request_id.value());+ });}EXPECT_EQ(seen_ids, (Vector<u64> { 1, 2, 3, 4, 5, 6, 7 }));EXPECT_EQ(seen_request_body_events, (Vector<StringView> { "progress"sv, "end of body"sv, "read stream"sv, "sent from source"sv }));+ EXPECT_EQ(seen_network_request_ids, (Vector<u64> { 8, 9, 10, 11 }));}diff --git a/Tests/WebContent/TestWorkerPageHost.cpp b/Tests/WebContent/TestWorkerPageHost.cppindex b5b6390e07c..bdc83498305 100644--- a/Tests/WebContent/TestWorkerPageHost.cpp+++ b/Tests/WebContent/TestWorkerPageHost.cpp@@ -34,7 +34,8 @@ static void run_on_worker_thread(Callback const& callback)IPC::ScopedSharedIOThread shared_io_thread;Core::EventLoop event_loop;Web::Bindings::initialize_agent(Web::HTML::AgentType::SharedWorker);- Web::HTML::surrounding_agent().fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor();+ auto& agent = Web::HTML::surrounding_agent();+ agent.fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor(agent.network_activity_observers);auto pair = MUST(IPC::Transport::create_paired());auto client = WebWorker::ConnectionFromClient::construct(move(pair.local), nullptr);diff --git a/UI/Android/src/main/cpp/WebContentService.cpp b/UI/Android/src/main/cpp/WebContentService.cppindex cb6a9ef6cbf..b71123a26fe 100644--- a/UI/Android/src/main/cpp/WebContentService.cpp+++ b/UI/Android/src/main/cpp/WebContentService.cpp@@ -49,7 +49,8 @@ ErrorOr<int> service_main(int ipc_socket)Web::Platform::ImageCodecPlugin::install(*new Web::Platform::RemoteImageCodecPlugin(bind_image_decoder_service));Web::Bindings::initialize_agent(Web::HTML::AgentType::SimilarOriginWindow);- Web::HTML::surrounding_agent().fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor();+ auto& agent = Web::HTML::surrounding_agent();+ agent.fetch_executor = Web::Fetch::Fetching::create_inline_fetch_executor(agent.network_activity_observers);auto request_server_client = TRY(bind_request_server_service());Web::ResourceLoader::initialize(Web::Bindings::main_thread_vm().heap());