Truly independent web browser
LibWebView: Never wait without limit for a browser that already runs
Andreas Kling0aab1eb04382
diff --git a/Libraries/LibIPC/TransportBootstrapMach.cpp b/Libraries/LibIPC/TransportBootstrapMach.cppindex d966ca54c03..9d5dd480c87 100644--- a/Libraries/LibIPC/TransportBootstrapMach.cpp+++ b/Libraries/LibIPC/TransportBootstrapMach.cpp@@ -22,7 +22,7 @@namespace IPC {-ErrorOr<TransportBootstrapMachPorts> bootstrap_transport_from_server_port(Core::MachPort const& server_port)+ErrorOr<TransportBootstrapMachPorts> bootstrap_transport_from_server_port(Core::MachPort const& server_port, AK::Duration reply_timeout){auto reply_port = TRY(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));@@ -51,9 +51,8 @@ ErrorOr<TransportBootstrapMachPorts> bootstrap_transport_from_server_port(Core::return Core::mach_error_to_error(send_result);ReceivedIPCChannelPortsMessage reply {};- mach_msg_timeout_t const reply_timeout = 5000;auto const recv_result = mach_msg(&reply.header, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, sizeof(reply),- reply_port.port(), reply_timeout, MACH_PORT_NULL);+ reply_port.port(), static_cast<mach_msg_timeout_t>(reply_timeout.to_milliseconds()), MACH_PORT_NULL);if (recv_result != KERN_SUCCESS)return Core::mach_error_to_error(recv_result);diff --git a/Libraries/LibIPC/TransportBootstrapMach.h b/Libraries/LibIPC/TransportBootstrapMach.hindex c65f2f5a317..1e5706c9e19 100644--- a/Libraries/LibIPC/TransportBootstrapMach.h+++ b/Libraries/LibIPC/TransportBootstrapMach.h@@ -9,6 +9,7 @@#include <AK/HashMap.h>#include <AK/Platform.h>#include <AK/StringView.h>+#include <AK/Time.h>#include <AK/Variant.h>#if !defined(AK_OS_MACH)@@ -28,7 +29,7 @@ struct TransportBootstrapMachPorts {};ErrorOr<TransportBootstrapMachPorts> bootstrap_transport_from_mach_server(StringView server_name);-ErrorOr<TransportBootstrapMachPorts> bootstrap_transport_from_server_port(Core::MachPort const& server_port);+ErrorOr<TransportBootstrapMachPorts> bootstrap_transport_from_server_port(Core::MachPort const& server_port, AK::Duration reply_timeout = AK::Duration::from_seconds(5));class TransportBootstrapMachServer {AK_MAKE_NONCOPYABLE(TransportBootstrapMachServer);diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex e52cec1c920..d084961ee3e 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -326,6 +326,7 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)Optional<u32> screenshot_delay;Optional<StringView> screenshot_path;bool new_window = false;+ Optional<i64> replace_browser_from_before;StringView stats_log_directory;Optional<StringView> profile_name;Optional<StringView> profile_path;@@ -430,6 +431,10 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments).hide_mode = Core::ArgsParser::OptionHideMode::CommandLineAndMarkdown,});args_parser.add_option(new_window, "Force opening in a new window", "new-window", 'n');+#if !defined(AK_OS_WINDOWS)+ // FIXME: Offer this on Windows as well, once an unresponsive browser can be ended there.+ args_parser.add_option(replace_browser_from_before, "End a browser that is running for the profile if it is unresponsive and started before this time, and start in its place", "replace-unresponsive-browser-from-before", 0, "unix-time-in-milliseconds");+#endif#if !defined(AK_OS_ANDROID)args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");args_parser.add_option(profile_name, "Select or create a named profile", "profile", 0, "name");@@ -680,9 +685,11 @@ ErrorOr<void> Application::initialize(Main::Arguments const& arguments)m_browser_process = make<BrowserProcess>();if (coordinate_browser_process) {- auto disposition = TRY(m_browser_process->connect(m_browser_options.raw_urls, m_browser_options.new_window, profile().paths().runtime, profile_identity));- if (disposition == BrowserProcess::ProcessDisposition::ExitProcess) {+ auto replace_from_before = replace_browser_from_before.map([](auto milliseconds) { return UnixDateTime::from_milliseconds_since_epoch(milliseconds); });+ auto disposition = TRY(m_browser_process->connect(m_browser_options.raw_urls, m_browser_options.new_window, profile().paths().runtime, profile_identity, ui_process_id(), replace_from_before));+ if (disposition != BrowserProcess::ProcessDisposition::ContinueMainProcess) {m_should_exit_after_profile_coordination = true;+ m_browser_is_unresponsive = disposition == BrowserProcess::ProcessDisposition::BrowserIsUnresponsive;return {};}}diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.hindex 0d8308f2e82..af23532a8fc 100644--- a/Libraries/LibWebView/Application.h+++ b/Libraries/LibWebView/Application.h@@ -98,6 +98,9 @@ public:static Profile const& profile() { return *the().m_profile; }BrowserProcess& browser_process() { return *m_browser_process; }bool should_exit_after_profile_coordination() const { return m_should_exit_after_profile_coordination; }+ // Whether the process exits because a browser is running for the profile, but does not take what we were asked to+ // open.+ bool browser_is_unresponsive() const { return m_browser_is_unresponsive; }static BrowserOptions const& browser_options() { return the().m_browser_options; }static RequestServerOptions const& request_server_options() { return the().m_request_server_options; }@@ -426,6 +429,8 @@ protected:virtual NonnullOwnPtr<MicrophoneAuthorizer> create_microphone_authorizer();virtual bool should_coordinate_browser_process() const { return true; }+ // The process that shows this browser to the user, if that is not this process.+ virtual Optional<pid_t> ui_process_id() const { return {}; }virtual bool captures_browser_crashes() const { return false; }virtual bool should_use_os_geolocation() const { return true; }virtual SiteIsolationMode default_site_isolation_mode() const { return SiteIsolationMode::IFrame; }@@ -594,6 +599,7 @@ private:OwnPtr<Settings> m_settings;OwnPtr<BrowserProcess> m_browser_process;bool m_should_exit_after_profile_coordination { false };+ bool m_browser_is_unresponsive { false };OwnPtr<ApplicationSettingsObserver> m_settings_observer;OwnPtr<ApplicationPermissionManagerObserver> m_permission_manager_observer;RefPtr<Core::Timer> m_permission_expiry_timer;diff --git a/Libraries/LibWebView/BrowserProcess.cpp b/Libraries/LibWebView/BrowserProcess.cppindex 5455667152d..9b371a01605 100644--- a/Libraries/LibWebView/BrowserProcess.cpp+++ b/Libraries/LibWebView/BrowserProcess.cpp@@ -6,6 +6,7 @@#include <AK/ByteString.h>#include <AK/NeverDestroyed.h>+#include <AK/Time.h>#include <LibCore/Process.h>#include <LibCore/Socket.h>#include <LibCore/System.h>@@ -13,6 +14,7 @@#include <LibIPC/ConnectionToServer.h>#include <LibIPC/Transport.h>#if defined(AK_OS_MACOS)+# include <LibCore/MachPort.h># include <LibIPC/TransportBootstrapMach.h>#endif#include <LibWebView/Application.h>@@ -20,10 +22,19 @@#include <LibWebView/URL.h>#include <LibWebView/Utilities.h>+#if defined(AK_OS_MACOS)+# include <sys/proc.h>+# include <sys/sysctl.h>+#endif+#if defined(AK_OS_WINDOWS)# include <AK/Windows.h>#else+# include <errno.h>+# include <limits.h>+# include <signal.h># include <sys/file.h>+# include <unistd.h>#endifnamespace WebView {@@ -34,38 +45,324 @@ static HashMap<int, RefPtr<UIProcessConnectionFromClient>>& connections()return *connections;}+// How long a browser that is already running gets to take what this process was asked to open.+static constexpr auto handover_timeout = AK::Duration::from_seconds(5);+// How long a browser that the user chose to replace gets to show that it answers again.+static constexpr auto replaced_browser_handover_timeout = AK::Duration::from_milliseconds(500);+// How long a browser may take to start, during which it does not answer yet.+static constexpr auto browser_startup_time = AK::Duration::from_seconds(30);++// NB: A browser writes its PID file as it starts.+static Optional<UnixDateTime> start_time_of_browser_with(StringView pid_path)+{+ auto pid_file_status = Core::File::stat(pid_path);+ if (pid_file_status.is_error())+ return {};+#if defined(AK_OS_MACOS)+ return UnixDateTime::from_unix_timespec(pid_file_status.value().st_mtimespec);+#elif !defined(AK_OS_WINDOWS)+ return UnixDateTime::from_unix_timespec(pid_file_status.value().st_mtim);+#else+ return UnixDateTime::from_seconds_since_epoch(pid_file_status.value().st_mtime);+#endif+}++// NB: A browser may be busy starting for a while after it wrote its PID file. A launch that comes right after it, as+// when the user opens two links at once, waits for it longer.+static AK::Duration remaining_startup_time_of_browser(Optional<UnixDateTime> start_time)+{+ if (!start_time.has_value())+ return AK::Duration::zero();+ auto time_since_start = UnixDateTime::now() - *start_time;+ if (time_since_start < AK::Duration::zero() || time_since_start >= browser_startup_time)+ return AK::Duration::zero();+ return browser_startup_time - time_since_start;+}+class UIProcessClient final: public IPC::ConnectionToServer<UIProcessClientEndpoint, UIProcessServerEndpoint> {C_OBJECT(UIProcessClient);+public:+ // A browser that ends while we hand over to it leaves the profile to us.+ virtual void die() override { }+private:explicit UIProcessClient(NonnullOwnPtr<IPC::Transport>);};-ErrorOr<BrowserProcess::ProcessDisposition> BrowserProcess::connect(Vector<ByteString> const& raw_urls, NewWindow new_window, StringView runtime_directory, [[maybe_unused]] StringView profile_identity)+#if !defined(AK_OS_WINDOWS)+// How long another process that is starting on the profile gets to finish. That takes it no longer than a handover to+// a browser that is still starting and the end of an unresponsive browser do.+static constexpr auto startup_lock_timeout = AK::Duration::from_seconds(40);+static constexpr auto browser_exit_timeout = AK::Duration::from_seconds(5);++static bool process_is_gone(pid_t pid)+{+ if (kill(pid, 0) < 0 && errno == ESRCH)+ return true;++ // NB: A process that has ended keeps its PID until its parent takes note, and a parent that is stuck never does.+# if defined(AK_OS_MACOS)+ struct kinfo_proc info {};+ size_t size = sizeof(info);+ int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };+ if (sysctl(name, 4, &info, &size, nullptr, 0) == 0 && size == sizeof(info))+ return info.kp_proc.p_stat == SZOMB;+# elif defined(AK_OS_LINUX)+ if (auto file = Core::File::open(ByteString::formatted("/proc/{}/stat", pid), Core::File::OpenMode::Read); !file.is_error()) {+ if (auto contents = file.value()->read_until_eof(); !contents.is_error()) {+ // The state follows the name of the process, which is in parentheses and may itself contain any character.+ auto stat = StringView { contents.value() };+ if (auto end_of_name = stat.find_last(')'); end_of_name.has_value() && *end_of_name + 2 < stat.length())+ return stat[*end_of_name + 2] == 'Z';+ }+ }+# endif+ return false;+}++# if defined(AK_OS_MACOS)+// Whether the process with this PID was there when the file was written. A browser writes its PID file after it+// starts, so a process that started later only got the PID of a browser that is gone. We only say yes when we know.+static bool process_may_have_written_file(pid_t pid, StringView path)+{+ auto file_status = Core::System::stat(path);+ if (file_status.is_error())+ return false;+ struct kinfo_proc info {};+ size_t size = sizeof(info);+ int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };+ if (sysctl(name, 4, &info, &size, nullptr, 0) != 0 || size != sizeof(info))+ return false;+ auto const& start_time = info.kp_proc.p_starttime;+ auto process_started_at = UnixDateTime::from_microseconds_since_epoch(static_cast<i64>(start_time.tv_sec) * 1'000'000 + start_time.tv_usec);+ return process_started_at <= UnixDateTime::from_unix_timespec(file_status.value().st_mtimespec);+}+# endif++# if !defined(AK_OS_MACOS)+// Whether the process with this PID can be a browser, as far as we can tell. A process that runs another program is+// not, and only got the PID of a browser that is gone.+static bool process_may_be_a_browser([[maybe_unused]] pid_t pid)+{+# if defined(AK_OS_LINUX)+ auto executable_of = [](StringView process_directory) -> Optional<ByteString> {+ char path[PATH_MAX] = {};+ auto length = ::readlink(ByteString::formatted("{}/exe", process_directory).characters(), path, sizeof(path));+ if (length <= 0 || static_cast<size_t>(length) >= sizeof(path))+ return {};+ return ByteString { path, static_cast<size_t>(length) };+ };+ auto our_executable = executable_of("/proc/self"sv);+ auto process_directory = ByteString::formatted("/proc/{}", pid);+ auto its_executable = executable_of(process_directory);+ if (our_executable.has_value() && its_executable.has_value())+ return *our_executable == *its_executable;+# endif+ return true;+}+# endif++static ErrorOr<bool> lock_until(int fd, MonotonicTime deadline)+{+ for (;;) {+ if (flock(fd, LOCK_EX | LOCK_NB) == 0)+ return true;+ if (errno != EWOULDBLOCK && errno != EINTR)+ return Error::from_syscall("flock"sv, errno);+ if (MonotonicTime::now() >= deadline)+ return false;+ usleep(10'000);+ }+}++static bool wait_for_process_to_be_gone(pid_t pid, AK::Duration timeout)+{+ auto deadline = MonotonicTime::now() + timeout;+ while (!process_is_gone(pid)) {+ if (MonotonicTime::now() >= deadline)+ return false;+ usleep(10'000);+ }+ return true;+}++// Whether the browser is gone after this. One that is not still has the profile.+static bool end_browser(pid_t pid)+{+ warnln("Ending the unresponsive browser with PID {}", pid);+ (void)kill(pid, SIGKILL);+ // NB: The browser lets go of the profile as it ends, and its helpers end soon after it.+ return wait_for_process_to_be_gone(pid, browser_exit_timeout);+}++// Whether the browser with this PID wrote that it has a UI in another process, and that process is gone.+static bool ui_of_browser_is_gone(StringView ui_pid_path, pid_t browser_pid)+{+ auto file = Core::File::open(ui_pid_path, Core::File::OpenMode::Read);+ if (file.is_error())+ return false;+ auto contents = file.value()->read_until_eof();+ if (contents.is_error())+ return false;+ auto pids = StringView { contents.value() }.split_view(' ');+ if (pids.size() != 2)+ return false;+ auto written_browser_pid = pids[0].to_number<pid_t>();+ auto ui_pid = pids[1].to_number<pid_t>();+ if (!written_browser_pid.has_value() || !ui_pid.has_value() || *written_browser_pid != browser_pid || *ui_pid <= 0)+ return false;+ return process_is_gone(*ui_pid);+}+#endif++// Reads the PID file and leaves it as it is, which is all that a process without the startup lock may do to it.+static Optional<pid_t> read_pid_file(StringView pid_path)+{+ auto file = Core::File::open(pid_path, Core::File::OpenMode::Read);+ if (file.is_error())+ return {};+ auto contents = file.value()->read_until_eof();+ if (contents.is_error())+ return {};+ return StringView { contents.value() }.to_number<pid_t>();+}++ErrorOr<BrowserProcess::ProcessDisposition> BrowserProcess::connect(Vector<ByteString> const& raw_urls, NewWindow new_window, StringView runtime_directory, [[maybe_unused]] StringView profile_identity, Optional<pid_t> ui_pid, Optional<UnixDateTime> replace_browser_from_before){static constexpr auto process_name = "Ladybird"sv;auto startup_lock_path = LexicalPath::join(runtime_directory, "startup.lock"sv).string();auto startup_lock = TRY(Core::File::open(startup_lock_path, Core::File::OpenMode::ReadWrite));+ bool has_startup_lock = true;#if defined(AK_OS_WINDOWS)+ // FIXME: Stop waiting after a while, as on the other platforms.OVERLAPPED overlapped {};if (!LockFileEx(to_handle(startup_lock->fd()), LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD, &overlapped))return Error::from_windows_error();#else- if (flock(startup_lock->fd(), LOCK_EX) < 0)- return Error::from_syscall("flock"sv, errno);+ // NB: Whoever has the lock is starting on this profile as well. We do not wait for it here, as one that is stuck+ // would keep every later launch waiting, with nothing to show the user. Without the lock, we can still reach+ // a browser that is already running. Becoming the browser of the profile takes the lock, or two processes+ // could both do it, so that is what we wait for the lock for.+ has_startup_lock = TRY(lock_until(startup_lock->fd(), MonotonicTime::now()));#endif+ auto wait_for_startup_lock = [&]() -> ErrorOr<void> {+#if !defined(AK_OS_WINDOWS)+ if (!TRY(lock_until(startup_lock->fd(), MonotonicTime::now() + startup_lock_timeout)))+ return Error::from_string_literal("Another process has been starting on this profile for too long");+ has_startup_lock = true;+#endif+ return {};+ };auto [socket_path, pid_path] = TRY(Process::paths_for_process(process_name, runtime_directory));+ auto ui_pid_path = ByteString::formatted("{}.ui", pid_path);++ // NB: Each round finds a browser that is gone, or ends one. Other launches wait for the lock meanwhile, so rounds+ // only run out if something keeps bringing the PID file back.+ static constexpr size_t maximum_rounds = 8;+ for (size_t round = 0;; ++round) {+ // NB: Only the process with the lock changes the PID file. Whoever has the lock may be writing its own PID+ // file right now, so without the lock, a file that is empty or left over is not ours to remove. All we do+ // with a browser that we found gone, or ended, is to look again with the lock, for a browser that started+ // meanwhile.+ auto pid = has_startup_lock ? TRY(Process::get_process_pid(process_name, pid_path)) : read_pid_file(pid_path);+ if (!pid.has_value()) {+ if (has_startup_lock)+ break;+ TRY(wait_for_startup_lock());+ continue;+ }+ if (round == maximum_rounds)+ return Error::from_string_literal("Unable to take over the profile from a browser that is gone");++ // NB: The user has already waited for the browser that they decided to replace, so it only gets a moment to+ // show that it answers again. A browser that started after the user was asked is not that browser.+ auto start_time = start_time_of_browser_with(pid_path);+ auto user_wants_to_replace_browser = replace_browser_from_before.has_value() && start_time.has_value() && *start_time < *replace_browser_from_before;+ auto timeout = user_wants_to_replace_browser+ ? replaced_browser_handover_timeout+ : max(handover_timeout, remaining_startup_time_of_browser(start_time));+#if defined(AK_OS_MACOS)+ auto result = TRY(connect_as_client(*pid, raw_urls, new_window, profile_identity, timeout));+#else+ auto result_or_error = connect_as_client(socket_path, raw_urls, new_window, timeout);+ if (result_or_error.is_error()) {+ if (!has_startup_lock) {+ TRY(wait_for_startup_lock());+ continue;+ }+ // NB: A browser that ends removes its PID file and then its socket, so we may have read the one and missed+ // the other. A browser that is still in the PID file is running without a socket that we can reach,+ // and nothing may start on its profile then.+ if (TRY(Process::get_process_pid(process_name, pid_path)) != pid)+ continue;+ return result_or_error.release_error();+ }+ auto result = result_or_error.release_value();+ // NB: A socket that is missing, or that nothing listens on, does not tell whether the process in the PID file+ // is gone. That process has to be gone before its files are taken to be left over, unless we know that it+ // is some other process that got the PID of a browser that is gone.+# if !defined(AK_OS_WINDOWS)+ if (result.handover == Handover::BrowserIsGone && !result.browser_pid.has_value() && process_may_be_a_browser(*pid))+ result.browser_pid = *pid;+# endif+#endif+ if (result.handover == Handover::Done)+ return ProcessDisposition::ExitProcess;- if (auto pid = TRY(Process::get_process_pid(process_name, pid_path)); pid.has_value()) {#if defined(AK_OS_MACOS)- TRY(connect_as_client(*pid, raw_urls, new_window, profile_identity));+ // NB: A browser that is ending lets go of its Mach server a while before it removes its PID file. So a process+ // that is in the PID file without a server may be that browser, and it gets a moment to end. One that is+ // still there after that has the profile and cannot be reached, like an unresponsive browser. A process+ // that started after the file was written is some other process that got the PID of a browser that is gone.+ if (result.handover == Handover::BrowserIsGone && !result.browser_pid.has_value() && process_may_have_written_file(*pid, pid_path)) {+ auto deadline = MonotonicTime::now() + browser_exit_timeout;+ while (read_pid_file(pid_path) == pid && !process_is_gone(*pid) && MonotonicTime::now() < deadline)+ usleep(10'000);+ // NB: The PID may have gone to another process while we waited.+ if (read_pid_file(pid_path) == pid && !process_is_gone(*pid) && process_may_have_written_file(*pid, pid_path))+ result = { Handover::BrowserIsUnresponsive, *pid };+ }+#endif++ if (result.handover == Handover::BrowserIsUnresponsive) {+#if defined(AK_OS_WINDOWS)+ // FIXME: End the unresponsive browser when asked to.+ return ProcessDisposition::BrowserIsUnresponsive;#else- TRY(connect_as_client(socket_path, raw_urls, new_window));+ if (!result.browser_pid.has_value())+ return ProcessDisposition::BrowserIsUnresponsive;+ if (!user_wants_to_replace_browser && !ui_of_browser_is_gone(ui_pid_path, *result.browser_pid))+ return ProcessDisposition::BrowserIsUnresponsive;+ // NB: The browser that we reached is ended on what the PID file told us before we reached it. If another+ // browser took the profile in between, the file has changed, and we look again.+ if (user_wants_to_replace_browser && (read_pid_file(pid_path) != result.browser_pid || start_time_of_browser_with(pid_path) != start_time))+ continue;+ if (!end_browser(*result.browser_pid))+ return Error::from_string_literal("Unable to end the unresponsive browser that is already running");+#endif+ }++#if !defined(AK_OS_WINDOWS)+ // NB: A browser that turned us away without ending still has the profile, and nothing may start on it then.+ // One that is ending takes a moment from closing its connections until it is gone.+ if (result.handover == Handover::BrowserIsGone && result.browser_pid.has_value()) {+ if (!wait_for_process_to_be_gone(*result.browser_pid, browser_exit_timeout))+ return Error::from_string_literal("The browser that is already running did not take what it was asked to open");+ }#endif- return ProcessDisposition::ExitProcess;++ if (!has_startup_lock) {+ TRY(wait_for_startup_lock());+ continue;+ }++ // The PID file is left over from a browser that is gone, which may have the PID of some other process by now.+ if (auto removal = FileSystem::remove(pid_path, FileSystem::RecursionMode::Disallowed); removal.is_error() && FileSystem::exists(pid_path))+ return removal.release_error();}#if defined(AK_OS_MACOS)@@ -74,52 +371,89 @@ ErrorOr<BrowserProcess::ProcessDisposition> BrowserProcess::connect(Vector<ByteSTRY(connect_as_server(socket_path));#endif+ m_startup_lock_path = startup_lock_path;m_pid_path = pid_path;m_pid_file = TRY(Core::File::open(pid_path, Core::File::OpenMode::Write));TRY(m_pid_file->write_until_depleted(ByteString::number(Core::System::getpid())));+ // NB: A UI file that an earlier browser left behind names that browser, so it is never taken for ours.+ (void)FileSystem::remove(ui_pid_path, FileSystem::RecursionMode::Disallowed);+ if (ui_pid.has_value()) {+ auto ui_pid_file = TRY(Core::File::open(ui_pid_path, Core::File::OpenMode::Write));+ TRY(ui_pid_file->write_until_depleted(ByteString::formatted("{} {}", Core::System::getpid(), *ui_pid)));+ m_ui_pid_path = move(ui_pid_path);+ }+return ProcessDisposition::ContinueMainProcess;}-#if defined(AK_OS_MACOS)-ErrorOr<void> BrowserProcess::connect_as_client(pid_t pid, Vector<ByteString> const& raw_urls, NewWindow new_window, StringView profile_identity)+static BrowserProcess::Handover hand_over(UIProcessClient& client, Vector<ByteString> const& raw_urls, NewWindow new_window, AK::Duration timeout){- auto process_name = ByteString::formatted("Ladybird-{}", profile_identity);- auto transport_ports = TRY(IPC::bootstrap_transport_from_mach_server(mach_server_name_for_process(process_name, pid)));- auto client = UIProcessClient::construct(make<IPC::Transport>(move(transport_ports.receive_right), move(transport_ports.send_right)));-+ auto deadline = MonotonicTime::now() + timeout;+ bool done = false;switch (new_window) {case NewWindow::Yes:- if (!client->send_sync_but_allow_failure<Messages::UIProcessServer::CreateNewWindow>(raw_urls))- dbgln("Failed to send CreateNewWindow message to UIProcess");- return {};+ done = client.send_sync_until<Messages::UIProcessServer::CreateNewWindow>(deadline, raw_urls);+ break;case NewWindow::No:- if (!client->send_sync_but_allow_failure<Messages::UIProcessServer::CreateNewTab>(raw_urls))- dbgln("Failed to send CreateNewTab message to UIProcess");- return {};+ done = client.send_sync_until<Messages::UIProcessServer::CreateNewTab>(deadline, raw_urls);+ break;}+ if (done)+ return BrowserProcess::Handover::Done;+ // NB: A wait that ends before its deadline found the browser gone. The connection does not tell, as a socket+ // stays open until its closing is handled, which is after the wait.+ if (client.is_open() && MonotonicTime::now() >= deadline)+ return BrowserProcess::Handover::BrowserIsUnresponsive;+ return BrowserProcess::Handover::BrowserIsGone;+}- VERIFY_NOT_REACHED();+#if defined(AK_OS_MACOS)+ErrorOr<BrowserProcess::HandoverResult> BrowserProcess::connect_as_client(pid_t pid, Vector<ByteString> const& raw_urls, NewWindow new_window, StringView profile_identity, AK::Duration handover_timeout)+{+ // NB: Only the browser of this profile with this PID has a server of this name. A PID file that an earlier browser+ // left behind does not lead to one, whichever process has that PID now.+ auto process_name = ByteString::formatted("Ladybird-{}", profile_identity);+ auto server_port = Core::MachPort::look_up_from_bootstrap_server(mach_server_name_for_process(process_name, pid));+ if (server_port.is_error())+ return HandoverResult { Handover::BrowserIsGone };++ auto transport_ports = IPC::bootstrap_transport_from_server_port(server_port.value(), min(handover_timeout, AK::Duration::from_seconds(5)));+ if (transport_ports.is_error())+ return HandoverResult { process_is_gone(pid) ? Handover::BrowserIsGone : Handover::BrowserIsUnresponsive, pid };++ auto client = UIProcessClient::construct(make<IPC::Transport>(move(transport_ports.value().receive_right), move(transport_ports.value().send_right)));+ return HandoverResult { hand_over(*client, raw_urls, new_window, handover_timeout), pid };}#else-ErrorOr<void> BrowserProcess::connect_as_client(ByteString const& socket_path, Vector<ByteString> const& raw_urls, NewWindow new_window)+ErrorOr<BrowserProcess::HandoverResult> BrowserProcess::connect_as_client(ByteString const& socket_path, Vector<ByteString> const& raw_urls, NewWindow new_window, AK::Duration handover_timeout){- auto socket = TRY(Core::LocalSocket::connect(socket_path));- auto transport = TRY(IPC::Transport::from_socket(move(socket)));- auto client = UIProcessClient::construct(move(transport));-- switch (new_window) {- case NewWindow::Yes:- if (!client->send_sync_but_allow_failure<Messages::UIProcessServer::CreateNewWindow>(raw_urls))- dbgln("Failed to send CreateNewWindow message to UIProcess");- return {};- case NewWindow::No:- if (!client->send_sync_but_allow_failure<Messages::UIProcessServer::CreateNewTab>(raw_urls))- dbgln("Failed to send CreateNewTab message to UIProcess");- return {};+ auto socket = Core::LocalSocket::connect(socket_path);+ if (socket.is_error()) {+ // Nothing listens on a socket that a browser left behind. A browser makes its socket before its PID file and+ // removes it after, so a PID file without a socket is left behind as well.+ if (socket.error().is_errno() && (socket.error().code() == ECONNREFUSED || socket.error().code() == ENOENT))+ return HandoverResult { Handover::BrowserIsGone };+ return socket.release_error();}- VERIFY_NOT_REACHED();+ Optional<pid_t> browser_pid;+# if !defined(AK_OS_WINDOWS)+ // NB: A peer in another PID namespace has no PID here, and is reported as 0.+ if (auto peer_pid = socket.value()->peer_pid(); !peer_pid.is_error() && peer_pid.value() > 0)+ browser_pid = peer_pid.value();+# endif++ auto transport = TRY(IPC::Transport::from_socket(socket.release_value()));+ auto client = UIProcessClient::construct(move(transport));+ auto handover = hand_over(*client, raw_urls, new_window, handover_timeout);+# if defined(AK_OS_WINDOWS)+ // FIXME: Find out whether a browser that turned us away is gone, as on the other platforms. Until then, nothing+ // starts on its profile.+ if (handover == Handover::BrowserIsGone)+ return Error::from_string_literal("The browser that is already running did not take what it was asked to open");+# endif+ return HandoverResult { handover, browser_pid };}#endif@@ -173,18 +507,49 @@ BrowserProcess::~BrowserProcess()Application::the().set_browser_process_transport_handler({});#endif+#if !defined(AK_OS_WINDOWS)+ // NB: A launch only changes the files of the profile while it has the startup lock, so with the lock we know whose+ // they are for as long as we remove ours. A launch that has the lock right now is busy with this profile, and+ // takes what we leave behind to be left over once we are gone. We do not wait for it.+ OwnPtr<Core::File> startup_lock;+ if (m_pid_file) {+ auto lock_file = Core::File::open(m_startup_lock_path, Core::File::OpenMode::ReadWrite);+ if (lock_file.is_error() || flock(lock_file.value()->fd(), LOCK_EX | LOCK_NB) != 0)+ return;+ startup_lock = lock_file.release_value();+ }+#endif++ // NB: A launch that found this browser ending may have taken the PID file to be left over, and put the files of+ // its own browser in their place. Those files are not ours to remove.+ auto pid_file_is_ours = m_pid_file && read_pid_file(m_pid_path) == Core::System::getpid();++ // NB: The UI file goes first. No other browser starts on the profile for as long as the PID file names us.+ if (pid_file_is_ours && !m_ui_pid_path.is_empty())+ (void)FileSystem::remove(m_ui_pid_path, FileSystem::RecursionMode::Disallowed);+if (m_pid_file) {- MUST(m_pid_file->truncate(0));#if defined(AK_OS_WINDOWS)+ MUST(m_pid_file->truncate(0));// NOTE: On Windows, be conservative and close the pid file's handle before// removing the file; removal of an open file requires cooperative sharing modes.m_pid_file->close();#endif- MUST(FileSystem::remove(m_pid_path, FileSystem::RecursionMode::Disallowed));+ // NB: The file names us until it is removed, and is not emptied first. A launch does not start on the profile+ // while a file names a browser that is still there, but it does when it finds an empty file.+ // NB: That launch may also remove the file right now, so the file can be gone by the time we remove it.+ if (pid_file_is_ours)+ (void)FileSystem::remove(m_pid_path, FileSystem::RecursionMode::Disallowed);}- if (!m_socket_path.is_empty())+ if (!m_socket_path.is_empty()) {+#if defined(AK_OS_WINDOWS)MUST(FileSystem::remove(m_socket_path, FileSystem::RecursionMode::Disallowed));+#else+ if (pid_file_is_ours)+ (void)FileSystem::remove(m_socket_path, FileSystem::RecursionMode::Disallowed);+#endif+ }}UIProcessClient::UIProcessClient(NonnullOwnPtr<IPC::Transport> transport)diff --git a/Libraries/LibWebView/BrowserProcess.h b/Libraries/LibWebView/BrowserProcess.hindex c182a7cae95..b52a09f39ef 100644--- a/Libraries/LibWebView/BrowserProcess.h+++ b/Libraries/LibWebView/BrowserProcess.h@@ -10,6 +10,7 @@#include <AK/Function.h>#include <AK/OwnPtr.h>#include <AK/RefPtr.h>+#include <AK/Time.h>#include <AK/Types.h>#include <LibCore/LocalServer.h>#include <LibIPC/ConnectionFromClient.h>@@ -50,29 +51,52 @@ public:enum class ProcessDisposition : u8 {ContinueMainProcess,ExitProcess,+ // A browser is running for the profile, but it does not take what this process was asked to open.+ BrowserIsUnresponsive,};+ // How handing what this process was asked to open to the browser that is already running went.+ enum class Handover : u8 {+ Done,+ BrowserIsGone,+ BrowserIsUnresponsive,+ };++ // What a process ends with when it found ProcessDisposition::BrowserIsUnresponsive.+ static constexpr int unresponsive_browser_exit_status = 86;+BrowserProcess() = default;~BrowserProcess();- ErrorOr<ProcessDisposition> connect(Vector<ByteString> const& raw_urls, NewWindow new_window, StringView runtime_directory, StringView profile_identity);+ // NB: ui_pid is the process that shows this browser to the user, if that is not this process. A browser whose UI+ // is gone cannot be seen or closed by the user, so a later launch ends it without asking if it is unresponsive.+ // An unresponsive browser that started before replace_browser_from_before is ended as well. That is the time+ // at which the user was asked about a browser, so one that started after it is not the one they agreed to end.+ ErrorOr<ProcessDisposition> connect(Vector<ByteString> const& raw_urls, NewWindow new_window, StringView runtime_directory, StringView profile_identity, Optional<pid_t> ui_pid, Optional<UnixDateTime> replace_browser_from_before);Function<void(Vector<URL::URL> const&)> on_new_tab;Function<void(Vector<URL::URL> const&)> on_new_window;private:void accept_transport(NonnullOwnPtr<IPC::Transport>);+ struct HandoverResult {+ Handover handover { Handover::BrowserIsGone };+ // The process that was found to be the browser, which is not taken from the PID file alone.+ Optional<pid_t> browser_pid {};+ };#if defined(AK_OS_MACOS)- ErrorOr<void> connect_as_client(pid_t pid, Vector<ByteString> const& raw_urls, NewWindow new_window, StringView profile_identity);+ ErrorOr<HandoverResult> connect_as_client(pid_t pid, Vector<ByteString> const& raw_urls, NewWindow new_window, StringView profile_identity, AK::Duration handover_timeout);ErrorOr<void> connect_as_server();#else- ErrorOr<void> connect_as_client(ByteString const& socket_path, Vector<ByteString> const& raw_urls, NewWindow new_window);+ ErrorOr<HandoverResult> connect_as_client(ByteString const& socket_path, Vector<ByteString> const& raw_urls, NewWindow new_window, AK::Duration handover_timeout);ErrorOr<void> connect_as_server(ByteString const& socket_path);#endifRefPtr<Core::LocalServer> m_local_server;OwnPtr<Core::File> m_pid_file;+ ByteString m_startup_lock_path;ByteString m_pid_path;+ ByteString m_ui_pid_path;ByteString m_socket_path;int m_next_client_id { 0 };};diff --git a/Services/Hub/Application.cpp b/Services/Hub/Application.cppindex 3cb7e9ced9b..bfb4e470203 100644--- a/Services/Hub/Application.cpp+++ b/Services/Hub/Application.cpp@@ -31,6 +31,14 @@ void Application::create_platform_arguments(Core::ArgsParser& args_parser)args_parser.add_option(m_ui_pid, "Process of the UI, which the Hub ends with", "ui-pid", 0, "pid");}+Optional<pid_t> Application::ui_process_id() const+{+ auto pid = m_ui_pid.to_number<pid_t>();+ if (!pid.has_value() || *pid <= 0)+ return {};+ return pid;+}+Hub::UIInfo const* Application::ui_info() const{if (!m_ui_info.has_value() && !m_encoded_ui_info.is_empty()) {diff --git a/Services/Hub/Application.h b/Services/Hub/Application.hindex 427cbca5835..4dbbcc77f98 100644--- a/Services/Hub/Application.h+++ b/Services/Hub/Application.h@@ -77,6 +77,7 @@ private:// ^WebView::Applicationvirtual Core::EventLoop& create_platform_event_loop() override;virtual void create_platform_arguments(Core::ArgsParser&) override;+ virtual Optional<pid_t> ui_process_id() const override;virtual Optional<WebView::ViewImplementation&> active_web_view() const override;virtual Optional<WebView::ViewImplementation&> open_blank_new_tab(Web::HTML::ActivateTab, WebView::ViewImplementation const* related_view = nullptr) const override;virtual void open_url_in_new_tab(URL::URL const&, Web::HTML::ActivateTab, WebView::ViewImplementation const* source_view = nullptr) const override;diff --git a/Services/Hub/main.cpp b/Services/Hub/main.cppindex 7a404b8fa40..7f7a42ab0bc 100644--- a/Services/Hub/main.cpp+++ b/Services/Hub/main.cpp@@ -12,6 +12,7 @@#include <LibIPC/StartupTransport.h>#include <LibMain/Main.h>#include <LibThreading/Thread.h>+#include <LibWebView/BrowserProcess.h>#if defined(AK_OS_MACOS) || defined(AK_OS_BSD_GENERIC)# include <sys/event.h>@@ -107,6 +108,10 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)end_with_ui_process(arguments);auto application = TRY(Hub::Application::create(arguments, nullptr));+ if (application->browser_is_unresponsive()) {+ warnln("Ladybird is already running with this profile, but it is not responding");+ return WebView::BrowserProcess::unresponsive_browser_exit_status;+ }if (application->should_exit_after_profile_coordination()) {outln("Opening in existing process");return 0;diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cppindex ed4de5f3390..2af30e6c2a5 100644--- a/UI/Qt/Application.cpp+++ b/UI/Qt/Application.cpp@@ -25,6 +25,7 @@#include <LibWebCommon/MimeSniff/MimeType.h>#include <LibWebCommon/WebView/Utilities.h>#include <LibWebView/AutocompleteService.h>+#include <LibWebView/BrowserProcess.h>#include <LibWebView/CanonicalTraversable.h>#include <LibWebView/CrashReport.h>#include <LibWebView/CrashReportStore.h>@@ -284,6 +285,10 @@ static bool has_visible_browser_window()}#endif+// Whether this process is a browser by now, rather than a launch that may still hand over to another browser and end.+static bool s_browser_has_started = false;+static Vector<ByteString> s_urls_opened_before_browser_started;+class LadybirdQApplication : public QApplication {public:AK_ALLOC_WITH_KMALLOC;@@ -309,6 +314,18 @@ public:virtual bool event(QEvent* event) override{+ // NB: Events also arrive while the launch asks the user what to do about a browser that is already running.+ // There is no browser to handle them then, so what the user opens meanwhile waits for the browser.+ if (!s_browser_has_started) {+ if (event->type() == QEvent::FileOpen) {+ auto const& open_event = *static_cast<QFileOpenEvent const*>(event);+ auto const qurl = open_event.url();+ s_urls_opened_before_browser_started.append(qurl.isEmpty() ? ak_byte_string_from_qstring(open_event.file()) : ByteString { qurl.toEncoded().constData() });+ return true;+ }+ return QApplication::event(event);+ }+auto& application = Application::the();auto const event_type = event->type();@@ -735,6 +752,7 @@ ErrorOr<NonnullOwnPtr<Application>> Application::create(Main::Arguments const& aTRY(application->connect_to_hub(arguments));#elseapplication->m_hub = TRY(Hub::Application::create(arguments, static_cast<Hub::ApplicationHost*>(application.ptr())));+ s_browser_has_started = true;// Headless mode has no UI to connect to the Hub.if (browser_options().headless_mode.has_value())@@ -797,6 +815,25 @@ Hub::UIInfo Application::current_ui_info() constreturn info;}+[[maybe_unused]] static bool user_wants_to_replace_unresponsive_browser()+{+ QMessageBox dialog;+ dialog.setIcon(QMessageBox::Warning);+ dialog.setText(QObject::tr("Ladybird is already running, but it is not responding."));+ dialog.setInformativeText(QObject::tr("To open Ladybird with this profile, the Ladybird that is running must be closed first. What its pages have not saved will be lost."));+ auto* close_button = dialog.addButton(QObject::tr("Close Ladybird"), QMessageBox::DestructiveRole);+ dialog.setDefaultButton(dialog.addButton(QMessageBox::Cancel));+ // NB: Nothing else of this launch is on the screen yet, so the question has to be where the user sees it.+ dialog.setWindowFlag(Qt::WindowStaysOnTopHint);+ QTimer::singleShot(0, &dialog, [&dialog] {+ dialog.raise();+ dialog.activateWindow();+ QApplication::alert(&dialog);+ });+ dialog.exec();+ return dialog.clickedButton() == close_button;+}+ErrorOr<void> Application::connect_to_hub(Main::Arguments const& arguments){auto hub_path = TRY(hub_executable_path());@@ -832,14 +869,9 @@ ErrorOr<void> Application::connect_to_hub(Main::Arguments const& arguments)hub_arguments.append(ByteString::formatted("--ui-info={}", encode_hex(ui_info_buffer.data().span())));hub_arguments.append(ByteString::formatted("--ui-pid={}", Core::System::getpid()));- Core::ProcessSpawnOptions spawn_options {- .name = "Hub"sv,- .executable = hub_path,- .arguments = hub_arguments,- };-# if defined(AK_OS_MACOS)// NB: This must answer while the main thread waits for the Hub to initialize, so it answers on its own thread.+ // Every round uses the same server, as its name cannot be registered again right after it was let go of.auto hub_bootstrap = adopt_ref(*new HubBootstrap);IPC::MachBootstrapListener bootstrap_listener { WebView::mach_server_name_for_process("Ladybird-UI"sv, Core::System::getpid()) };if (!bootstrap_listener.is_initialized())@@ -849,49 +881,85 @@ ErrorOr<void> Application::connect_to_hub(Main::Arguments const& arguments)dbgln("Unable to bootstrap the Hub: {}", result.error());};hub_arguments.append(ByteString::formatted("--ui-mach-server={}", bootstrap_listener.server_port_name()));- spawn_options.arguments = hub_arguments;-- auto port_a_recv = TRY(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));- auto port_a_send = TRY(port_a_recv.insert_right(Core::MachPort::MessageRight::MakeSend));- auto port_b_recv = TRY(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));- auto port_b_send = TRY(port_b_recv.insert_right(Core::MachPort::MessageRight::MakeSend));+# endif- // The Hub may receive startup messages before it has constructed its transport.- IPC::TransportMachPort::raise_receive_queue_limit(port_b_recv);+ // NB: A browser that is already running for the profile takes what we were asked to open. One that does not answer+ // can be ended to start in its place, which is for the user to decide.+ Optional<Hub::InitialState> initial_state;+ // NB: The user agrees to end the browser that they were asked about. One that started after that, as when another+ // launch replaced the first one meanwhile, is not ended without asking again.+ Optional<UnixDateTime> replace_browser_from_before;+ while (!initial_state.has_value()) {+ auto round_arguments = hub_arguments;+ if (replace_browser_from_before.has_value())+ round_arguments.append(ByteString::formatted("--replace-unresponsive-browser-from-before={}", replace_browser_from_before->milliseconds_since_epoch()));+ round_arguments.extend(s_urls_opened_before_browser_started);+ // NB: A browser that this round finds unresponsive was there before the round began.+ [[maybe_unused]] auto time_before_round = UnixDateTime::now();++ Core::ProcessSpawnOptions spawn_options {+ .name = "Hub"sv,+ .executable = hub_path,+ .arguments = round_arguments,+ };- Optional<Core::Process> spawned_process;- {- MutexLocker child_registration_locker(hub_bootstrap->server.child_registration_lock());- spawned_process = TRY(Core::Process::spawn(spawn_options));- hub_bootstrap->server.register_child_transport(spawned_process->pid(), IPC::TransportBootstrapMachPorts { move(port_b_recv), move(port_a_send) });- }- auto process = spawned_process.release_value();+# if defined(AK_OS_MACOS)+ auto port_a_recv = TRY(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));+ auto port_a_send = TRY(port_a_recv.insert_right(Core::MachPort::MessageRight::MakeSend));+ auto port_b_recv = TRY(Core::MachPort::create_with_right(Core::MachPort::PortRight::Receive));+ auto port_b_send = TRY(port_b_recv.insert_right(Core::MachPort::MessageRight::MakeSend));++ // The Hub may receive startup messages before it has constructed its transport.+ IPC::TransportMachPort::raise_receive_queue_limit(port_b_recv);++ Optional<Core::Process> spawned_process;+ {+ MutexLocker child_registration_locker(hub_bootstrap->server.child_registration_lock());+ spawned_process = TRY(Core::Process::spawn(spawn_options));+ hub_bootstrap->server.register_child_transport(spawned_process->pid(), IPC::TransportBootstrapMachPorts { move(port_b_recv), move(port_a_send) });+ }+ auto process = spawned_process.release_value();- auto transport = make<IPC::Transport>(move(port_a_recv), move(port_b_send));+ auto transport = make<IPC::Transport>(move(port_a_recv), move(port_b_send));# else- int socket_fds[2] {};- TRY(Core::System::socketpair(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, socket_fds));-- spawn_options.file_actions.append(Core::FileAction::DupFd { .write_fd = socket_fds[1], .fd = socket_fds[1] });- TRY(Core::Environment::set("SOCKET_TAKEOVER"sv, ByteString::formatted("ipc:{}", socket_fds[1]), Core::Environment::Overwrite::Yes));- auto process = TRY(Core::Process::spawn(spawn_options));- TRY(Core::Environment::unset("SOCKET_TAKEOVER"sv));- TRY(Core::System::close(socket_fds[1]));-- auto ipc_socket = TRY(Core::LocalSocket::adopt_fd(socket_fds[0]));- TRY(ipc_socket->set_blocking(true));- auto transport = make<IPC::Transport>(move(ipc_socket));+ int socket_fds[2] {};+ TRY(Core::System::socketpair(AF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, socket_fds));++ spawn_options.file_actions.append(Core::FileAction::DupFd { .write_fd = socket_fds[1], .fd = socket_fds[1] });+ TRY(Core::Environment::set("SOCKET_TAKEOVER"sv, ByteString::formatted("ipc:{}", socket_fds[1]), Core::Environment::Overwrite::Yes));+ auto process = TRY(Core::Process::spawn(spawn_options));+ TRY(Core::Environment::unset("SOCKET_TAKEOVER"sv));+ TRY(Core::System::close(socket_fds[1]));++ auto ipc_socket = TRY(Core::LocalSocket::adopt_fd(socket_fds[0]));+ TRY(ipc_socket->set_blocking(true));+ auto transport = make<IPC::Transport>(move(ipc_socket));# endif- m_hub_connection = adopt_ref(*new HubConnection(move(transport)));+ m_hub_connection = adopt_ref(*new HubConnection(move(transport)));++ // The Hub can find that there is nothing for us to do, as when another process has this profile and takes our+ // URLs, or when asked for its usage. It ends right away then, and how it ended is how we end.+ auto state_or_error = m_hub_connection->try_initialize();+ if (!state_or_error.is_error()) {+ initial_state = state_or_error.release_value();+ m_restart_command.hub = move(process);+ break;+ }- // The Hub can find that there is nothing for us to do, as when another process has this profile and takes our URLs,- // or when asked for its usage. It ends right away then, and how it ended is how we end.- auto initial_state = m_hub_connection->try_initialize();- if (initial_state.is_error()) {- m_exit_status_if_done = TRY(process.wait_for_termination());+ m_hub_connection = nullptr;+ auto exit_status = TRY(process.wait_for_termination());+# if !defined(AK_OS_WINDOWS)+ // FIXME: Ask on Windows as well, once the Hub can end an unresponsive browser there.+ if (exit_status == WebView::BrowserProcess::unresponsive_browser_exit_status) {+ if (user_wants_to_replace_unresponsive_browser()) {+ replace_browser_from_before = time_before_round;+ continue;+ }+ }+# endif+ m_exit_status_if_done = exit_status;return {};}- m_restart_command.hub = move(process);auto state = initial_state.release_value();m_hub_connection->did_initialize();@@ -970,6 +1038,7 @@ ErrorOr<void> Application::connect_to_hub(Main::Arguments const& arguments)};QObject::connect(&SystemAppearance::the(), &SystemAppearance::changed, send_ui_info);QObject::connect(&SystemAppearance::the(), &SystemAppearance::interface_appearance_changed, send_ui_info);+ s_browser_has_started = true;return {};}@@ -1014,6 +1083,11 @@ Optional<int> Application::exit_status_if_done() const{if (!hub().should_exit_after_profile_coordination())return {};+ if (hub().browser_is_unresponsive()) {+ // FIXME: Offer to end the unresponsive browser, as is done when the Hub is in its own process.+ warnln("Ladybird is already running with this profile, but it is not responding");+ return WebView::BrowserProcess::unresponsive_browser_exit_status;+ }outln("Opening in existing process");return 0;}diff --git a/UI/Qt/HubConnection.cpp b/UI/Qt/HubConnection.cppindex 7bb5da24331..903a2773d03 100644--- a/UI/Qt/HubConnection.cpp+++ b/UI/Qt/HubConnection.cpp@@ -30,7 +30,9 @@ HubConnection::HubConnection(NonnullOwnPtr<IPC::Transport> transport)HubConnection::~HubConnection(){- s_the = nullptr;+ // NB: A connection can outlive the one that took its place, as when a launch connects to a second Hub.+ if (s_the == this)+ s_the = nullptr;}HubConnection& HubConnection::the()