Skip to content

Truly independent web browser

LibWebView: Discard background tabs when memory runs out

Andreas Kling59fdd30a97f0
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index 6af01a32a47..75fb5ccc4f8 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -72,6 +72,7 @@
#include <LibWebView/SpellChecker.h>
#include <LibWebView/StorageAreaRegistry.h>
#include <LibWebView/SystemProbeClient.h>
+#include <LibWebView/TabDiscarder.h>
#include <LibWebView/TabPerformanceMonitor.h>
#include <LibWebView/Translator.h>
#include <LibWebView/URL.h>
@@ -1897,6 +1898,10 @@ ErrorOr<void> Application::launch_services()
};
m_process_manager->set_web_content_memory_limit(m_browser_options.web_content_memory_limit_in_bytes.value_or(ProcessManager::default_web_content_memory_limit()));
+ // NB: A tab that WebDriver drives, or that runs without a UI, must stay as it is.
+ if (!m_browser_options.headless_mode.has_value() && !m_browser_options.webdriver_browser_endpoint.has_value())
+ m_tab_discarder = make<TabDiscarder>();
+
if (m_browser_options.disable_sql_database == DisableSQLDatabase::No) {
auto database_path = profile().paths().data;
auto database = TRY(Database::Database::create(database_path, "Ladybird"sv));
diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.h
index 4e4728fb917..dff6b3fac7b 100644
--- a/Libraries/LibWebView/Application.h
+++ b/Libraries/LibWebView/Application.h
@@ -715,6 +715,7 @@ private:
OwnPtr<IPC::HandleBrokerServer> m_handle_broker_server;
#endif
OwnPtr<ProcessManager> m_process_manager;
+ OwnPtr<TabDiscarder> m_tab_discarder;
Web::CSS::PreferredColorScheme m_color_scheme { Web::CSS::PreferredColorScheme::Auto };
Web::CSS::PreferredContrast m_contrast { Web::CSS::PreferredContrast::Auto };
diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txt
index 9a0e7889fed..4169a352f8c 100644
--- a/Libraries/LibWebView/CMakeLists.txt
+++ b/Libraries/LibWebView/CMakeLists.txt
@@ -61,6 +61,7 @@ set(SOURCES
Process.cpp
ProcessManager.cpp
ProcessSnapshot.cpp
+ TabDiscarder.cpp
TabIndicators.cpp
TabPerformanceStats.cpp
TabPerformanceMonitor.cpp
diff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.h
index 348351b05cc..ab6016cf53e 100644
--- a/Libraries/LibWebView/Forward.h
+++ b/Libraries/LibWebView/Forward.h
@@ -63,6 +63,7 @@ class SettingsUI;
class SpellChecker;
class Translator;
class StorageJar;
+class TabDiscarder;
class SystemProbeClient;
class TraversableSessionHistory;
class UpdateChecker;
diff --git a/Libraries/LibWebView/TabDiscarder.cpp b/Libraries/LibWebView/TabDiscarder.cpp
new file mode 100644
index 00000000000..e351678e2e1
--- /dev/null
+++ b/Libraries/LibWebView/TabDiscarder.cpp
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCore/Platform/MemoryPressure.h>
+#include <LibCore/Timer.h>
+#include <LibWebView/TabDiscarder.h>
+#include <LibWebView/ViewImplementation.h>
+
+namespace WebView {
+
+static constexpr auto check_interval = AK::Duration::from_seconds(5);
+
+// A tab that the user saw a short while ago is likely to be one they come back to soon.
+static constexpr auto minimum_time_hidden_under_memory_pressure = AK::Duration::from_seconds(10 * 60);
+
+TabDiscarder::TabDiscarder()
+ : m_timer(Core::Timer::create_repeating(check_interval, [this] { check_tabs(); }))
+{
+ m_timer->start();
+}
+
+TabDiscarder::~TabDiscarder() = default;
+
+void TabDiscarder::check_tabs()
+{
+ auto now = MonotonicTime::now();
+
+ // NB: The memory of a discarded tab comes back as its processes exit, so one tab is discarded at a time, and the
+ // next check sees whether the system still needs more. The tab the user saw least recently goes first, but a
+ // tab whose processes all host other tabs too frees little, so one that lets a process exit goes before it.
+ if (Core::Platform::system_memory_pressure() == Core::Platform::MemoryPressure::Critical) {
+ ViewImplementation* least_recently_seen = nullptr;
+ ViewImplementation* least_recently_seen_ending_a_process = nullptr;
+ auto seen_less_recently = [](ViewImplementation& view, ViewImplementation* other) {
+ return !other || *view.hidden_since() < *other->hidden_since();
+ };
+ ViewImplementation::for_each_view([&](ViewImplementation& view) {
+ if (!view.may_be_discarded(ViewImplementation::DiscardReason::MemoryPressure, minimum_time_hidden_under_memory_pressure, now))
+ return IterationDecision::Continue;
+ if (seen_less_recently(view, least_recently_seen))
+ least_recently_seen = &view;
+ if (seen_less_recently(view, least_recently_seen_ending_a_process) && view.discarding_ends_a_process())
+ least_recently_seen_ending_a_process = &view;
+ return IterationDecision::Continue;
+ });
+ if (auto* view = least_recently_seen_ending_a_process ? least_recently_seen_ending_a_process : least_recently_seen) {
+ dbgln("Discarding tab {}, as the system is about to run out of memory", view->url());
+ view->request_discard();
+ }
+ }
+}
+
+}
diff --git a/Libraries/LibWebView/TabDiscarder.h b/Libraries/LibWebView/TabDiscarder.h
new file mode 100644
index 00000000000..3ed68b22fcb
--- /dev/null
+++ b/Libraries/LibWebView/TabDiscarder.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Noncopyable.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/kmalloc.h>
+#include <LibCore/Forward.h>
+#include <LibWebView/Export.h>
+
+namespace WebView {
+
+// Discards the tabs that the user doesn't see, and wouldn't miss for now, when the system is about to run out of
+// memory.
+class WEBVIEW_API TabDiscarder {
+ AK_MAKE_NONCOPYABLE(TabDiscarder);
+ AK_MAKE_NONMOVABLE(TabDiscarder);
+
+public:
+ AK_ALLOC_WITH_KMALLOC;
+
+ TabDiscarder();
+ ~TabDiscarder();
+
+private:
+ void check_tabs();
+
+ NonnullRefPtr<Core::Timer> m_timer;
+};
+
+}
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index b7d2c97b159..320297e2113 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -666,6 +666,29 @@ bool ViewImplementation::may_be_discarded(DiscardReason reason, AK::Duration min
// its documents to its session history. A process that doesn't answer in time leaves its documents as they were saved.
static constexpr auto time_to_save_session_history_entry_states = AK::Duration::from_seconds(1);
+// NB: A process may host pages of several tabs, such as tabs of one origin, or the cross-site frames of one site in
+// several tabs. A page of another tab, even one only representing a frame, keeps the process alive.
+bool ViewImplementation::discarding_ends_a_process() const
+{
+ if (!m_top_level_traversable)
+ return false;
+
+ auto ends_a_process = false;
+ traversable().for_each_hosting_page([&](WebContentPage& page) {
+ if (ends_a_process)
+ return;
+ auto hosts_only_this_view = true;
+ page.client().for_each_page([&](WebContentPage& other_page) {
+ if (other_page.has_traversable() && &other_page.traversable() == &traversable())
+ return IterationDecision::Continue;
+ hosts_only_this_view = false;
+ return IterationDecision::Break;
+ });
+ ends_a_process = hosts_only_this_view;
+ });
+ return ends_a_process;
+}
+
void ViewImplementation::request_discard()
{
m_discard_requested = true;
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index c314fdbf747..caf4533e11b 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -239,6 +239,8 @@ public:
Inactivity,
};
bool may_be_discarded(DiscardReason, AK::Duration minimum_time_hidden, MonotonicTime now) const;
+ // Whether discarding the view would let a process exit, which is how its memory comes back.
+ bool discarding_ends_a_process() const;
void set_pinned(bool pinned);
void set_current_tab_of_window(bool current_tab_of_window) { m_current_tab_of_window = current_tab_of_window; }
// When the user last stopped seeing the view, if they don't see it now.