Skip to content

Truly independent web browser

LibWebView: Keep a tab audible a while after an audible page leaves it

Luke Wilde369038bf5ba5
diff --git a/Libraries/LibAudio/Audibility.h b/Libraries/LibAudio/Audibility.h
index d584e0eda86..465b3797384 100644
--- a/Libraries/LibAudio/Audibility.h
+++ b/Libraries/LibAudio/Audibility.h
@@ -6,6 +6,7 @@
#pragma once
+#include <AK/Time.h>
#include <AK/Types.h>
namespace Audio {
@@ -16,4 +17,7 @@ enum class Audibility : u8 {
Audible,
};
+// How long a group goes on counting as audible after its sound stops.
+static constexpr AK::Duration AUDIBILITY_LINGER = AK::Duration::from_seconds(3);
+
}
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 420a011d8de..d60ea95fe30 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -2128,6 +2128,11 @@ bool Internals::tab_is_playing_audio()
return window().associated_document().page().client().page_did_request_tab_is_playing_audio_for_testing();
}
+WebIDL::UnsignedLongLong Internals::tab_audibility_change_count()
+{
+ return window().associated_document().page().client().page_did_request_tab_audibility_change_count_for_testing();
+}
+
bool Internals::media_element_video_sink_is_ticking(HTML::HTMLMediaElement& element)
{
return element.m_video_sink_is_ticking;
diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.h
index c33583d446a..324b87ee405 100644
--- a/Libraries/LibWeb/Internals/Internals.h
+++ b/Libraries/LibWeb/Internals/Internals.h
@@ -321,6 +321,7 @@ public:
bool media_element_is_playing_audio(HTML::HTMLMediaElement&);
bool document_is_playing_audio(DOM::Document&);
bool tab_is_playing_audio();
+ WebIDL::UnsignedLongLong tab_audibility_change_count();
bool media_element_video_sink_is_ticking(HTML::HTMLMediaElement&);
void set_media_element_ready_state(HTML::HTMLMediaElement&, u16 ready_state);
void set_media_element_paused(HTML::HTMLMediaElement&, bool paused);
diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idl
index eb5d730e835..c59f6cd4466 100644
--- a/Libraries/LibWeb/Internals/Internals.idl
+++ b/Libraries/LibWeb/Internals/Internals.idl
@@ -396,6 +396,8 @@ interface Internals {
boolean documentIsPlayingAudio(Document document);
// Whether the UI process shows this window's tab as playing audio, which the AudioServer decides by what it hears.
boolean tabIsPlayingAudio();
+ // How many times the UI process has changed whether this window's tab is shown as playing audio.
+ unsigned long long tabAudibilityChangeCount();
boolean mediaElementVideoSinkIsTicking(HTMLMediaElement element);
undefined setMediaElementReadyState(HTMLMediaElement element, unsigned short readyState);
undefined setMediaElementPaused(HTMLMediaElement element, boolean paused);
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index bb6ccc09738..974c4d05092 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -845,6 +845,7 @@ public:
virtual String page_did_request_ui_process_session_history_for_testing() { return "{}"_string; }
virtual bool page_did_request_has_populated_document_for_testing([[maybe_unused]] HTML::CrossProcessId navigable_id) { return false; }
virtual bool page_did_request_tab_is_playing_audio_for_testing() { return false; }
+ virtual u64 page_did_request_tab_audibility_change_count_for_testing() { return 0; }
virtual bool page_did_request_capture_session_history_snapshot_for_testing() { return false; }
virtual bool page_did_request_restore_session_history_snapshot_for_testing() { return false; }
virtual bool page_did_request_register_session_store_tab_for_testing() { return false; }
diff --git a/Libraries/LibWebView/AudibilityHold.cpp b/Libraries/LibWebView/AudibilityHold.cpp
new file mode 100644
index 00000000000..d8998b6216d
--- /dev/null
+++ b/Libraries/LibWebView/AudibilityHold.cpp
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibAudio/Audibility.h>
+#include <LibWebView/AudibilityHold.h>
+
+namespace WebView {
+
+void AudibilityHold::page_began_hosting(Web::PageId page_id)
+{
+ m_left_pages.remove(page_id);
+}
+
+bool AudibilityHold::page_left(Web::PageId page_id, MonotonicTime now)
+{
+ if (m_left_pages.set(page_id) != HashSetResult::InsertedNewEntry)
+ return false;
+ auto held_until = now + Audio::AUDIBILITY_LINGER;
+ if (m_held_until.has_value() && *m_held_until >= held_until)
+ return false;
+ m_held_until = held_until;
+ return true;
+}
+
+void AudibilityHold::page_closed(Web::PageId page_id)
+{
+ m_left_pages.remove(page_id);
+}
+
+bool AudibilityHold::is_held(MonotonicTime now) const
+{
+ return m_held_until.has_value() && now < *m_held_until;
+}
+
+}
diff --git a/Libraries/LibWebView/AudibilityHold.h b/Libraries/LibWebView/AudibilityHold.h
new file mode 100644
index 00000000000..61ed0480a15
--- /dev/null
+++ b/Libraries/LibWebView/AudibilityHold.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/HashTable.h>
+#include <AK/Optional.h>
+#include <AK/Time.h>
+#include <LibWebCommon/Page/PageId.h>
+#include <LibWebView/Export.h>
+
+namespace WebView {
+
+// Keeps a tab audible after an audible page leaves it, for as long as the page would have lingered had its sound stopped
+// as it left. A page leaves once each time it begins hosting the tab's documents. Closing isn't leaving: a closed page
+// holds nothing, and ends no hold.
+class WEBVIEW_API AudibilityHold {
+public:
+ void page_began_hosting(Web::PageId);
+ bool page_left(Web::PageId, MonotonicTime now);
+ void page_closed(Web::PageId);
+
+ bool is_held(MonotonicTime now) const;
+ Optional<MonotonicTime> held_until() const { return m_held_until; }
+
+private:
+ HashTable<Web::PageId> m_left_pages;
+ Optional<MonotonicTime> m_held_until;
+};
+
+}
diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txt
index 8b47d7a8a0f..75f32321cbc 100644
--- a/Libraries/LibWebView/CMakeLists.txt
+++ b/Libraries/LibWebView/CMakeLists.txt
@@ -2,6 +2,7 @@ set(SOURCES
AccessibilityTreeManager.cpp
Application.cpp
ApplyHistoryStep.cpp
+ AudibilityHold.cpp
AudioServerAudibility.cpp
AudioServerControlClient.cpp
Autocomplete.cpp
diff --git a/Libraries/LibWebView/CanonicalTraversable.cpp b/Libraries/LibWebView/CanonicalTraversable.cpp
index 84381400d18..884df1061d1 100644
--- a/Libraries/LibWebView/CanonicalTraversable.cpp
+++ b/Libraries/LibWebView/CanonicalTraversable.cpp
@@ -402,6 +402,8 @@ void CanonicalTraversable::release_page_if_unused(NonnullRefPtr<WebContentPage>
return;
if (auto* bidi = WebDriverBiDi::the())
bidi->push_session_state_for_client(page->client());
+ if (auto view = this->view(); view.has_value())
+ view->did_release_page({}, page);
page->client().revoke_audio_playback(page->id());
// A page left hosting none of the tab's documents goes on representing the tab to a process holding part of
// another tab of its group, whose documents can hold the tab's WindowProxies.
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index f8a1b7fc533..7752d2e2076 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -97,6 +97,16 @@ ViewImplementation::ViewImplementation(IsPrivate is_private)
// happen to be visiting crashy websites a lot.
this->m_crash_count = 0;
});
+
+ m_audibility_hold_timer = Core::Timer::create_single_shot(AK::Duration::zero(), [this] {
+ // The hold, not the timer's resolution, decides when it has ended.
+ auto now = MonotonicTime::now();
+ if (m_audibility_hold.is_held(now)) {
+ m_audibility_hold_timer->restart(*m_audibility_hold.held_until() - now);
+ return;
+ }
+ update_audibility();
+ });
}
ViewImplementation::~ViewImplementation()
@@ -2636,6 +2646,8 @@ void ViewImplementation::toggle_page_mute_state()
void ViewImplementation::update_audibility()
{
auto audibility = Audio::Audibility::Inaudible;
+ if (m_audibility_hold.is_held(MonotonicTime::now()))
+ audibility = Audio::Audibility::Audible;
traversable().for_each_hosting_page([&](WebContentPage& page) {
if (page.audibility() == Audio::Audibility::Audible)
audibility = Audio::Audibility::Audible;
@@ -2643,10 +2655,20 @@ void ViewImplementation::update_audibility()
if (m_audibility == audibility)
return;
m_audibility = audibility;
+ ++m_audibility_change_count;
if (on_audibility_changed)
on_audibility_changed(m_audibility);
}
+void ViewImplementation::page_left(WebContentPage const& page)
+{
+ if (page.audibility() != Audio::Audibility::Audible)
+ return;
+ auto now = MonotonicTime::now();
+ if (m_audibility_hold.page_left(page.id(), now))
+ m_audibility_hold_timer->restart(*m_audibility_hold.held_until() - now);
+}
+
void ViewImplementation::reset_page_media_state()
{
update_audibility();
@@ -3194,6 +3216,7 @@ void ViewImplementation::prepare_page_for_navigable(WebContentPage& page)
// The page's sound plays while it hosts the tab's documents, unless the tab is muted.
page.client().set_audio_playback_mute_state(page.id(), m_mute_state);
page.client().authorize_audio_playback(page.id());
+ m_audibility_hold.page_began_hosting(page.id());
if (Application::browser_options().webdriver_browser_endpoint.has_value())
Application::the().push_webdriver_session_config(page);
Application::the().apply_view_options({}, *this, page);
@@ -3251,6 +3274,15 @@ void ViewImplementation::display_page_changed(RefPtr<WebContentPage> previous_pa
m_debugger_overlay_pointer_state.reset();
fail_pending_debugger_requests();
reject_pending_selection_requests();
+
+ // The previous page leaves the tab now, before it is let go of, unless it goes on hosting some of it.
+ auto previous_page_goes_on_hosting = false;
+ traversable().for_each_hosting_page([&](WebContentPage& page) {
+ if (&page == previous_page.ptr())
+ previous_page_goes_on_hosting = true;
+ });
+ if (!previous_page_goes_on_hosting)
+ page_left(*previous_page);
reset_page_media_state();
// Keep showing the outgoing page until the page paints its first frame.
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index 8ff0c301a19..d19459378d3 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -67,6 +67,7 @@
#include <LibWebCommon/WebView/PageInfo.h>
#include <LibWebCommon/WebView/StorageSetResult.h>
#include <LibWebCommon/WebView/ZoomLevel.h>
+#include <LibWebView/AudibilityHold.h>
#include <LibWebView/BookmarkStore.h>
#include <LibWebView/BrowsingSession.h>
#include <LibWebView/CanonicalTraversable.h>
@@ -418,9 +419,13 @@ public:
Web::HTML::MuteState page_mute_state() const { return m_mute_state; }
void toggle_page_mute_state();
- // The tab is audible while the AudioServer has recently heard any page of it.
+ // The tab is audible while the AudioServer has recently heard any page of it, and for a while after a page leaves it
+ // while heard. A page lost along with its process doesn't leave.
void update_audibility(Badge<WebContentPage>) { update_audibility(); }
+ void did_release_page(Badge<CanonicalTraversable>, WebContentPage const& page) { page_left(page); }
+ void did_close_page(Badge<WebContentPage>, Web::PageId page_id) { m_audibility_hold.page_closed(page_id); }
Audio::Audibility audibility() const { return m_audibility; }
+ u64 audibility_change_count() const { return m_audibility_change_count; }
void did_change_screen_wake_lock_state(Badge<WebContentPage>, Web::ScreenWakeLockState);
void did_reset_state_for_testing(Badge<WebContentPage>, Web::HTML::SessionHistoryEntryDescriptor);
@@ -720,6 +725,7 @@ protected:
WebContentPage& focused_navigable_host() const;
void reset_page_media_state();
void update_audibility();
+ void page_left(WebContentPage const&);
// A navigation to make again on reload: one the user stopped before its document was activated, or one a crash cut
// short. It's made again from the source it was first made from, when it has one (a javascript: URL has none).
@@ -1026,6 +1032,9 @@ protected:
Optional<Web::HTML::CrossProcessId> m_webdriver_current_parent_navigable_id;
Audio::Audibility m_audibility { Audio::Audibility::Inaudible };
+ u64 m_audibility_change_count { 0 };
+ AudibilityHold m_audibility_hold;
+ RefPtr<Core::Timer> m_audibility_hold_timer;
Web::ScreenWakeLockState m_screen_wake_lock_state { Web::ScreenWakeLockState::Released };
Web::HTML::MuteState m_mute_state { Web::HTML::MuteState::Unmuted };
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 136522eac18..289f0575511 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -649,6 +649,10 @@ void WebContentPage::close()
bidi->push_session_state_for_client(*m_client);
m_client->forget_audio_playback(m_id);
}
+ if (m_traversable) {
+ if (auto view = m_traversable->view(); view.has_value())
+ view->did_close_page({}, m_id);
+ }
set_audibility(Audio::Audibility::Inaudible);
m_web_ui = nullptr;
auto owed_replies = move(m_owed_replies);
@@ -2922,6 +2926,12 @@ Messages::WebContentTestClient::DidRequestTabIsPlayingAudioForTestingResponse We
return view.has_value() && view->audibility() == Audio::Audibility::Audible;
}
+Messages::WebContentTestClient::DidRequestTabAudibilityChangeCountForTestingResponse WebContentPage::did_request_tab_audibility_change_count_for_testing()
+{
+ auto view = traversable().view();
+ return view.has_value() ? view->audibility_change_count() : 0;
+}
+
void WebContentPage::did_request_crash_of_remote_frame_processes_for_testing()
{
traversable().for_each_in_subtree([](CanonicalNavigable& child_frame) {
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index 5f438d2547f..d7e7f045954 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -373,6 +373,7 @@ private:
Messages::WebContentTestClient::DidRequestUiProcessSessionHistoryForTestingResponse did_request_ui_process_session_history_for_testing();
Messages::WebContentTestClient::DidRequestSiteIsolationProcessTreeForTestingResponse did_request_site_isolation_process_tree_for_testing();
Messages::WebContentTestClient::DidRequestTabIsPlayingAudioForTestingResponse did_request_tab_is_playing_audio_for_testing();
+ Messages::WebContentTestClient::DidRequestTabAudibilityChangeCountForTestingResponse did_request_tab_audibility_change_count_for_testing();
virtual void did_request_crash_of_remote_frame_processes_for_testing() override;
virtual void did_request_stop_loading_for_testing() override;
virtual void did_request_reload_for_testing(bool bypass_cache) override;
diff --git a/Libraries/LibWebView/WebContentTestClient.cpp b/Libraries/LibWebView/WebContentTestClient.cpp
index eaaabc38342..9f3a88157c0 100644
--- a/Libraries/LibWebView/WebContentTestClient.cpp
+++ b/Libraries/LibWebView/WebContentTestClient.cpp
@@ -84,6 +84,14 @@ Messages::WebContentTestClient::DidRequestTabIsPlayingAudioForTestingResponse We
return false;
}
+Messages::WebContentTestClient::DidRequestTabAudibilityChangeCountForTestingResponse WebContentTestClient::did_request_tab_audibility_change_count_for_testing(Web::PageId page_id)
+{
+ if (auto* page = m_client.page(page_id))
+ return page->did_request_tab_audibility_change_count_for_testing();
+
+ return 0;
+}
+
Messages::WebContentTestClient::DidRequestHasPopulatedDocumentForTestingResponse WebContentTestClient::did_request_has_populated_document_for_testing(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id)
{
if (auto* page = m_client.page(page_id))
diff --git a/Libraries/LibWebView/WebContentTestClient.h b/Libraries/LibWebView/WebContentTestClient.h
index 7fa880a368a..816bfde98fb 100644
--- a/Libraries/LibWebView/WebContentTestClient.h
+++ b/Libraries/LibWebView/WebContentTestClient.h
@@ -38,6 +38,7 @@ private:
virtual Messages::WebContentTestClient::DidRequestUiProcessSessionHistoryForTestingResponse did_request_ui_process_session_history_for_testing(Web::PageId page_id) override;
virtual Messages::WebContentTestClient::DidRequestSiteIsolationProcessTreeForTestingResponse did_request_site_isolation_process_tree_for_testing(Web::PageId page_id) override;
virtual Messages::WebContentTestClient::DidRequestTabIsPlayingAudioForTestingResponse did_request_tab_is_playing_audio_for_testing(Web::PageId page_id) override;
+ virtual Messages::WebContentTestClient::DidRequestTabAudibilityChangeCountForTestingResponse did_request_tab_audibility_change_count_for_testing(Web::PageId page_id) override;
virtual Messages::WebContentTestClient::DidRequestHasPopulatedDocumentForTestingResponse did_request_has_populated_document_for_testing(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) override;
virtual Messages::WebContentTestClient::DidRequestCaptureSessionHistorySnapshotForTestingResponse did_request_capture_session_history_snapshot_for_testing(Web::PageId page_id) override;
virtual Messages::WebContentTestClient::DidRequestRestoreSessionHistorySnapshotForTestingResponse did_request_restore_session_history_snapshot_for_testing(Web::PageId page_id) override;
diff --git a/Services/AudioServer/PlaybackStreamMixer.h b/Services/AudioServer/PlaybackStreamMixer.h
index f36593408c9..29545f6d2d2 100644
--- a/Services/AudioServer/PlaybackStreamMixer.h
+++ b/Services/AudioServer/PlaybackStreamMixer.h
@@ -39,8 +39,6 @@ enum class PlaybackGroupMuteState : u8 {
// The peak, about -72 dBFS, at which an authorized group's combined sound counts as audible, after its streams' gain
// and whether or not the group is muted.
static constexpr float AUDIBLE_PEAK = 1.0f / 4096;
-// How long a group goes on counting as audible after its sound stops.
-static constexpr AK::Duration AUDIBILITY_LINGER = AK::Duration::from_seconds(3);
// Mixes the shared rings of one tab's client streams into one output device stream, which plays only while some
// client is playing or draining.
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index 814eacb9942..f21a76f6dc4 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -1794,6 +1794,13 @@ bool PageClient::page_did_request_tab_is_playing_audio_for_testing()
return false;
}
+u64 PageClient::page_did_request_tab_audibility_change_count_for_testing()
+{
+ if (auto* test_connection = client().test_connection())
+ return test_connection->did_request_tab_audibility_change_count_for_testing(m_id);
+ return 0;
+}
+
String PageClient::dump_site_isolation_process_tree_for_testing()
{
if (auto* test_connection = client().test_connection())
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index dc50a036f4c..9c49ceea9c3 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -331,6 +331,7 @@ private:
virtual String page_did_request_ui_process_session_history_for_testing() override;
virtual bool page_did_request_has_populated_document_for_testing(Web::HTML::CrossProcessId navigable_id) override;
virtual bool page_did_request_tab_is_playing_audio_for_testing() override;
+ virtual u64 page_did_request_tab_audibility_change_count_for_testing() override;
virtual bool page_did_request_capture_session_history_snapshot_for_testing() override;
virtual bool page_did_request_restore_session_history_snapshot_for_testing() override;
virtual bool page_did_request_register_session_store_tab_for_testing() override;
diff --git a/Services/WebContent/WebContentTestClient.ipc b/Services/WebContent/WebContentTestClient.ipc
index e38bcdd95ea..f59325c701a 100644
--- a/Services/WebContent/WebContentTestClient.ipc
+++ b/Services/WebContent/WebContentTestClient.ipc
@@ -22,6 +22,7 @@ endpoint WebContentTestClient routed by Web::PageId page_id
[NotRouted] did_request_ui_process_session_history_for_testing(Web::PageId page_id) => (String session_history)
[NotRouted] did_request_site_isolation_process_tree_for_testing(Web::PageId page_id) => (String process_tree)
[NotRouted] did_request_tab_is_playing_audio_for_testing(Web::PageId page_id) => (bool is_playing_audio)
+ [NotRouted] did_request_tab_audibility_change_count_for_testing(Web::PageId page_id) => (u64 change_count)
[NotRouted] did_request_has_populated_document_for_testing(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) => (bool has_populated_document)
did_request_crash_of_remote_frame_processes_for_testing(Web::PageId page_id) =|
did_request_stop_loading_for_testing(Web::PageId page_id) =|
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 722bfd5087e..063976b0393 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -61,6 +61,7 @@ Text/input/HTML/window-open-noopener-popup-keeps-its-name.html
Text/input/SiteIsolation/iframe/window-open-finds-a-popups-remote-iframe-by-target-name.html
Text/input/SiteIsolation/iframe/isolated-iframe-finds-a-popup-of-its-top-level-by-target-name.html
Text/input/wpt-import/html/semantics/embedded-content/the-iframe-element/sandbox-top-close.sub.window.html
+Text/input/SiteIsolation/tab-keeps-playing-audio-a-while-after-a-cross-site-navigation.html
; Hear from a same-origin opener policy page over a BroadcastChannel.
Text/input/SiteIsolation/popup-navigating-to-a-coop-page-leaves-its-opener.html
diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-keeps-playing-audio-heard-after-an-isolated-iframe-leaves.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-keeps-playing-audio-heard-after-an-isolated-iframe-leaves.txt
new file mode 100644
index 00000000000..3176d90a3d0
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-keeps-playing-audio-heard-after-an-isolated-iframe-leaves.txt
@@ -0,0 +1,4 @@
+plays audio heard in the isolated iframe: true
+plays audio heard after the hold: true
+stops playing audio once nothing is heard: true
+changed whether it plays audio once: true
diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-keeps-playing-audio-of-a-navigated-isolated-iframe-through-a-crash.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-keeps-playing-audio-of-a-navigated-isolated-iframe-through-a-crash.txt
new file mode 100644
index 00000000000..2c182a88efc
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-keeps-playing-audio-of-a-navigated-isolated-iframe-through-a-crash.txt
@@ -0,0 +1,6 @@
+plays audio heard in the isolated iframe: true
+the iframe's next process is gone: true
+plays audio: true
+stops playing audio a while later: true
+about three seconds after navigating: true
+changed whether it plays audio once: true
diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-plays-audio-heard-in-an-isolated-iframe.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-plays-audio-heard-in-an-isolated-iframe.txt
index c6d5fb3f53b..e985bf0ccba 100644
--- a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-plays-audio-heard-in-an-isolated-iframe.txt
+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-plays-audio-heard-in-an-isolated-iframe.txt
@@ -2,4 +2,5 @@ plays audio heard in the isolated iframe: true
WebContent#0
iframe#0: remote WebContent#1
stops playing audio once the iframe is gone: true
-before the sound would have been forgotten: true
+about three seconds later: true
+changed whether it plays audio once: true
diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-stops-playing-audio-of-a-crashed-isolated-iframe.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-stops-playing-audio-of-a-crashed-isolated-iframe.txt
new file mode 100644
index 00000000000..ac6889876b5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/tab-stops-playing-audio-of-a-crashed-isolated-iframe.txt
@@ -0,0 +1,8 @@
+plays audio heard in the isolated iframe: true
+stops playing audio once the iframe's process is gone: true
+before the sound would have been forgotten: true
+changed whether it plays audio once: true
+plays audio heard in another isolated iframe: true
+its process is gone: true
+plays audio heard in this document: true
+went on playing audio: true
diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/tab-keeps-playing-audio-a-while-after-a-cross-site-navigation.txt b/Tests/LibWeb/Text/expected/SiteIsolation/tab-keeps-playing-audio-a-while-after-a-cross-site-navigation.txt
new file mode 100644
index 00000000000..117d58372f8
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SiteIsolation/tab-keeps-playing-audio-a-while-after-a-cross-site-navigation.txt
@@ -0,0 +1,5 @@
+the popup's tab plays audio heard in another process
+plays audio once navigated to this site: true
+stops playing audio a while later: true
+about three seconds after navigating: true
+changed whether it plays audio once: true
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-keeps-playing-audio-heard-after-an-isolated-iframe-leaves.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-keeps-playing-audio-heard-after-an-isolated-iframe-leaves.html
new file mode 100644
index 00000000000..6662dbc44f7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-keeps-playing-audio-heard-after-an-isolated-iframe-leaves.html
@@ -0,0 +1,42 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<script>
+ function play() {
+ const context = new AudioContext();
+ const oscillator = new OscillatorNode(context);
+ oscillator.connect(context.destination);
+ oscillator.start();
+ return context;
+ }
+
+ promiseTest(async () => {
+ internals.setTestTimeout(30_000);
+ // The tab can still be remembered as playing a previous test's sound.
+ await waitForCondition(() => !internals.tabIsPlayingAudio());
+ const httpServer = httpTestServer();
+ const childUrl = new URL(
+ await httpServer.createEcho("GET", "/tab-keeps-playing-audio-heard-after-an-isolated-iframe-leaves-child", {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>${play}play();<\/script>`,
+ })
+ );
+ childUrl.hostname = uniqueLocalhostHostname("tab-keeps-playing-audio-heard-after-an-isolated-iframe-leaves");
+
+ const iframe = document.createElement("iframe");
+ iframe.src = childUrl;
+ document.body.appendChild(iframe);
+ println(`plays audio heard in the isolated iframe: ${await waitForCondition(() => internals.tabIsPlayingAudio())}`);
+
+ // This document's sound starts while the iframe's page holds the tab, and goes on after the hold has ended.
+ const changes = internals.tabAudibilityChangeCount();
+ iframe.remove();
+ const context = play();
+ await new Promise(resolve => setTimeout(resolve, 4000));
+ println(`plays audio heard after the hold: ${internals.tabIsPlayingAudio()}`);
+
+ await context.close();
+ println(`stops playing audio once nothing is heard: ${await waitForCondition(() => !internals.tabIsPlayingAudio())}`);
+ println(`changed whether it plays audio once: ${internals.tabAudibilityChangeCount() - changes === 1}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-keeps-playing-audio-of-a-navigated-isolated-iframe-through-a-crash.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-keeps-playing-audio-of-a-navigated-isolated-iframe-through-a-crash.html
new file mode 100644
index 00000000000..258fda8348c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-keeps-playing-audio-of-a-navigated-isolated-iframe-through-a-crash.html
@@ -0,0 +1,51 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<script>
+ promiseTest(async () => {
+ internals.setTestTimeout(30_000);
+ // The tab can still be remembered as playing a previous test's sound.
+ await waitForCondition(() => !internals.tabIsPlayingAudio());
+ const httpServer = httpTestServer();
+ const nextMessage = () => new Promise(resolve => addEventListener("message", event => resolve(event.data), { once: true }));
+
+ const echo = async (name, body) => {
+ const url = new URL(
+ await httpServer.createEcho("GET", `/${name}`, {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>${body}<\/script>`,
+ })
+ );
+ url.hostname = uniqueLocalhostHostname(name);
+ return url;
+ };
+
+ const playingUrl = await echo("tab-keeps-playing-audio-through-a-crash-playing", `
+ const context = new AudioContext();
+ const oscillator = new OscillatorNode(context);
+ oscillator.connect(context.destination);
+ oscillator.start();
+ `);
+ const nextUrl = await echo("tab-keeps-playing-audio-through-a-crash-next", `parent.postMessage("arrived", "*");`);
+
+ const iframe = document.createElement("iframe");
+ iframe.src = playingUrl;
+ document.body.appendChild(iframe);
+ println(`plays audio heard in the isolated iframe: ${await waitForCondition(() => internals.tabIsPlayingAudio())}`);
+
+ // The iframe's page leaves the tab while it is heard, as the iframe navigates to another site. Losing the process
+ // of the iframe's next document doesn't end the hold.
+ const changes = internals.tabAudibilityChangeCount();
+ const arrived = nextMessage();
+ const navigatedAt = performance.now();
+ iframe.src = nextUrl;
+ await arrived;
+ internals.crashRemoteFrameProcesses();
+ println(`the iframe's next process is gone: ${await waitForCondition(() => remoteFrameCount() === 0)}`);
+ println(`plays audio: ${internals.tabIsPlayingAudio()}`);
+ println(`stops playing audio a while later: ${await waitForCondition(() => !internals.tabIsPlayingAudio())}`);
+ const heldFor = performance.now() - navigatedAt;
+ println(`about three seconds after navigating: ${heldFor >= 2500 && heldFor < 5000}`);
+ println(`changed whether it plays audio once: ${internals.tabAudibilityChangeCount() - changes === 1}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-plays-audio-heard-in-an-isolated-iframe.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-plays-audio-heard-in-an-isolated-iframe.html
index 64a9c9a9e8c..7d241ddd1c2 100644
--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-plays-audio-heard-in-an-isolated-iframe.html
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-plays-audio-heard-in-an-isolated-iframe.html
@@ -26,10 +26,14 @@
println(`plays audio heard in the isolated iframe: ${await waitForCondition(() => internals.tabIsPlayingAudio())}`);
println(internals.dumpSiteIsolationProcessTree().trimEnd());
- // The iframe's page stops hosting its document, and is no longer heard at all.
+ // The iframe's page leaves the tab while it is heard, so the tab goes on playing audio as though the page's
+ // sound had stopped as it left.
+ const changes = internals.tabAudibilityChangeCount();
const removedAt = performance.now();
iframe.remove();
println(`stops playing audio once the iframe is gone: ${await waitForCondition(() => !internals.tabIsPlayingAudio())}`);
- println(`before the sound would have been forgotten: ${performance.now() - removedAt < 2000}`);
+ const heldFor = performance.now() - removedAt;
+ println(`about three seconds later: ${heldFor >= 2500 && heldFor < 5000}`);
+ println(`changed whether it plays audio once: ${internals.tabAudibilityChangeCount() - changes === 1}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-stops-playing-audio-of-a-crashed-isolated-iframe.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-stops-playing-audio-of-a-crashed-isolated-iframe.html
new file mode 100644
index 00000000000..82e8e9734dd
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/tab-stops-playing-audio-of-a-crashed-isolated-iframe.html
@@ -0,0 +1,53 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<script>
+ function play() {
+ const context = new AudioContext();
+ const oscillator = new OscillatorNode(context);
+ oscillator.connect(context.destination);
+ oscillator.start();
+ return context;
+ }
+
+ promiseTest(async () => {
+ internals.setTestTimeout(30_000);
+ // The tab can still be remembered as playing a previous test's sound.
+ await waitForCondition(() => !internals.tabIsPlayingAudio());
+ const httpServer = httpTestServer();
+ const appendPlayingIframe = async name => {
+ const url = new URL(
+ await httpServer.createEcho("GET", `/${name}`, {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>${play}play();<\/script>`,
+ })
+ );
+ url.hostname = uniqueLocalhostHostname(name);
+ const iframe = document.createElement("iframe");
+ iframe.src = url;
+ document.body.appendChild(iframe);
+ };
+
+ // A page lost along with its process doesn't leave the tab, so its sound is forgotten at once.
+ await appendPlayingIframe("tab-stops-playing-audio-of-a-crashed-isolated-iframe");
+ println(`plays audio heard in the isolated iframe: ${await waitForCondition(() => internals.tabIsPlayingAudio())}`);
+ let changes = internals.tabAudibilityChangeCount();
+ const crashedAt = performance.now();
+ internals.crashRemoteFrameProcesses();
+ println(`stops playing audio once the iframe's process is gone: ${await waitForCondition(() => !internals.tabIsPlayingAudio())}`);
+ println(`before the sound would have been forgotten: ${performance.now() - crashedAt < 2000}`);
+ println(`changed whether it plays audio once: ${internals.tabAudibilityChangeCount() - changes === 1}`);
+
+ // The sound of the tab's other pages goes on being heard.
+ await appendPlayingIframe("tab-stops-playing-audio-of-a-crashed-isolated-iframe-again");
+ println(`plays audio heard in another isolated iframe: ${await waitForCondition(() => internals.tabIsPlayingAudio())}`);
+ const context = play();
+ await waitForCondition(() => context.currentTime >= 0.5);
+ changes = internals.tabAudibilityChangeCount();
+ internals.crashRemoteFrameProcesses();
+ println(`its process is gone: ${await waitForCondition(() => remoteFrameCount() === 0)}`);
+ println(`plays audio heard in this document: ${internals.tabIsPlayingAudio()}`);
+ println(`went on playing audio: ${internals.tabAudibilityChangeCount() === changes}`);
+ await context.close();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/tab-keeps-playing-audio-a-while-after-a-cross-site-navigation.html b/Tests/LibWeb/Text/input/SiteIsolation/tab-keeps-playing-audio-a-while-after-a-cross-site-navigation.html
new file mode 100644
index 00000000000..d990597d1ee
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SiteIsolation/tab-keeps-playing-audio-a-while-after-a-cross-site-navigation.html
@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ internals.setTestTimeout(30_000);
+ const httpServer = httpTestServer();
+ const nextMessage = () => new Promise(resolve => addEventListener("message", event => resolve(event.data), { once: true }));
+
+ const echo = async (name, body) => httpServer.createEcho("GET", `/${name}`, {
+ status: 200,
+ headers: { "Content-Type": "text/html" },
+ body: `<!DOCTYPE html><script>${body}<\/script>`,
+ });
+
+ // The popup's document plays audio in another process, and says so once its tab is heard.
+ const crossSiteUrl = new URL(await echo("tab-keeps-playing-audio-cross-site", `
+ const context = new AudioContext();
+ const oscillator = new OscillatorNode(context);
+ oscillator.connect(context.destination);
+ oscillator.start();
+ (async () => {
+ while (!internals.tabIsPlayingAudio())
+ await new Promise(resolve => setTimeout(resolve, 25));
+ opener.postMessage(internals.tabAudibilityChangeCount(), "*");
+ })();
+ `));
+ crossSiteUrl.hostname = uniqueLocalhostHostname("tab-keeps-playing-audio-cross-site");
+ const sameSiteUrl = await echo("tab-keeps-playing-audio-same-site", `opener.postMessage("arrived", "*");`);
+
+ const heard = nextMessage();
+ const popup = window.open(crossSiteUrl.href);
+ const changes = await heard;
+ println("the popup's tab plays audio heard in another process");
+
+ // The popup's page leaves its tab while it is heard, as the popup's next document is displayed by this process.
+ const arrived = nextMessage();
+ const navigatedAt = performance.now();
+ popup.location.href = sameSiteUrl;
+ await arrived;
+ println(`plays audio once navigated to this site: ${popup.internals.tabIsPlayingAudio()}`);
+ println(`stops playing audio a while later: ${await waitForCondition(() => !popup.internals.tabIsPlayingAudio())}`);
+ const heldFor = performance.now() - navigatedAt;
+ println(`about three seconds after navigating: ${heldFor >= 2500 && heldFor < 5000}`);
+ println(`changed whether it plays audio once: ${popup.internals.tabAudibilityChangeCount() - changes === 1}`);
+ popup.close();
+ });
+</script>
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index 9d611cb695d..b60f2a07d40 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -139,6 +139,7 @@ endif()
set(TEST_SOURCES
TestAccessibilityTreeManager.cpp
+ TestAudibilityHold.cpp
TestAudioServerAudibility.cpp
TestBackgroundNetworking.cpp
TestAutocompleteMuxer.cpp
diff --git a/Tests/LibWebView/TestAudibilityHold.cpp b/Tests/LibWebView/TestAudibilityHold.cpp
new file mode 100644
index 00000000000..ece17dfdc6e
--- /dev/null
+++ b/Tests/LibWebView/TestAudibilityHold.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibAudio/Audibility.h>
+#include <LibTest/TestCase.h>
+#include <LibWebView/AudibilityHold.h>
+
+static constexpr Web::PageId PAGE { 1 };
+static constexpr Web::PageId OTHER_PAGE { 2 };
+static constexpr auto LINGER = Audio::AUDIBILITY_LINGER;
+
+static AK::Duration seconds(i64 seconds)
+{
+ return AK::Duration::from_seconds(seconds);
+}
+
+TEST_CASE(a_page_that_leaves_holds_the_tab_until_its_linger_has_passed)
+{
+ WebView::AudibilityHold hold;
+ auto left_at = MonotonicTime::now();
+ EXPECT(!hold.is_held(left_at));
+
+ EXPECT(hold.page_left(PAGE, left_at));
+ EXPECT(hold.is_held(left_at));
+ EXPECT(hold.is_held(left_at + LINGER - AK::Duration::from_milliseconds(1)));
+ EXPECT(!hold.is_held(left_at + LINGER));
+}
+
+TEST_CASE(a_page_leaves_once_each_time_it_begins_hosting)
+{
+ WebView::AudibilityHold hold;
+ auto left_at = MonotonicTime::now();
+ EXPECT(hold.page_left(PAGE, left_at));
+
+ // The page is let go of after it stops being displayed, or is let go of again.
+ EXPECT(!hold.page_left(PAGE, left_at + seconds(1)));
+ EXPECT(hold.held_until() == left_at + LINGER);
+
+ hold.page_began_hosting(PAGE);
+ EXPECT(hold.page_left(PAGE, left_at + seconds(1)));
+ EXPECT(hold.held_until() == left_at + seconds(1) + LINGER);
+}
+
+TEST_CASE(the_tab_is_held_until_the_last_page_to_leave_has_lingered)
+{
+ WebView::AudibilityHold hold;
+ auto left_at = MonotonicTime::now();
+ EXPECT(hold.page_left(PAGE, left_at));
+ EXPECT(hold.page_left(OTHER_PAGE, left_at + seconds(1)));
+ EXPECT(hold.is_held(left_at + LINGER));
+ EXPECT(!hold.is_held(left_at + seconds(1) + LINGER));
+
+ // A page whose linger would end sooner doesn't shorten the hold.
+ hold.page_began_hosting(PAGE);
+ EXPECT(!hold.page_left(PAGE, left_at));
+ EXPECT(hold.held_until() == left_at + seconds(1) + LINGER);
+}
+
+TEST_CASE(a_closed_page_holds_nothing_but_keeps_the_hold_it_left)
+{
+ WebView::AudibilityHold hold;
+ auto now = MonotonicTime::now();
+ hold.page_closed(PAGE);
+ EXPECT(!hold.is_held(now));
+
+ EXPECT(hold.page_left(PAGE, now));
+ hold.page_closed(PAGE);
+ EXPECT(hold.is_held(now + LINGER - AK::Duration::from_milliseconds(1)));
+ EXPECT(hold.held_until() == now + LINGER);
+}