From e84cc8c453d36d90cfdff63ef639273f5e479ef4 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:03:24 +0100 Subject: [PATCH] Bound the wait for a window that is not ready and align WebView2 reopening (#616) invokeOnUIThreadWhenReady gives up after a limit (one minute by default), WebView2 refuses a page once the first window closed before looking it up, and the secondary-window documentation moves to its own section. --- docs/CHANGELOG.md | 1 + docs/FRONTENDS.md | 15 ++++++++-- docs/PROJECT_STATUS.md | 1 + include/webfront/frontend/UIExecutor.hpp | 10 +++++-- include/webfront/frontend/WebKitGTK.hpp | 1 + include/webfront/frontend/WebView2.hpp | 9 +++--- test/unit/UIExecutorTests.cpp | 36 ++++++++++++++++++++++++ 7 files changed, 65 insertions(+), 8 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 41744f64..6f595d04 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -29,6 +29,7 @@ these entries stays in the GitHub releases and the Git history. - Run the MSVC code analysis in a pull request into `develop` that changes Windows code, and list the reruns each job needed before going green with `FlakeReport.py --days` (#628, `docs/TEST_TIERS.md`, `docs/TEST_PERFORMANCE.md`). ### Fixed +- Bound the wait of `openSecondaryWindow()` for a first window that is not ready (one minute), and refuse reopening a page under WebView2 once the first window closed, as the other frontends do (#616, `docs/FRONTENDS.md`). - Check the leftover STA of a WebView2 window only after a page that ran to its end, not after one that closes the window on a load failure: the runtime can keep a COM initialization of its own then, in about one `show()` in 500 under load, and the limit is documented with its measurements (#638, `docs/PROJECT_STATUS.md`). - Refuse every `Sec-Fetch-*` request header on the MCP listener, including `Sec-Fetch-Dest`, in both authenticated and unauthenticated modes (#637). - Pass the compiler analysis on the Windows pseudoterminal when it cannot prove the attribute list non-null (C6387), stop a unit test from opening the developer's real browser (the directory of its replacement opener was removed before the shell found it), and keep an accepted connection whose `TCP_NODELAY` the system refuses, as macOS does after a reset (#628). diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index dea164fa..653cd874 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -17,7 +17,7 @@ A frontend is a type with: | `static constexpr Action action` | What `BasicWF` does once `open()` returns. | | `static void launch(address, port, page)` (optional) | Opens the interface and returns without waiting for it (the system browser spawns its opener command and does not wait for it to end). `BasicWF::start()` requires it; only a frontend without a window loop offers it (the system browser). A `launch(address, port, page, const ContentPolicy&)` overload is preferred when present; neither receives window options or the view-association proof. | | `static constexpr bool endsOnRequest` (optional) | `false` when `requestClose()` cannot end every session (`NativeOrBrowserFrontend` with the plain system browser as fallback); `webfront::UIThread` then refuses the frontend. | -| `static void openSecondaryWindow(address, port, file, policy, window, launch)` and `static bool closeSecondaryWindow(file)` (optional) | A second window beside the one `open()` runs (#616), callable from any thread while it runs; `invokeOnUIThread()` (UIExecutor.hpp) hops to the interface thread. Opening a page a secondary window already shows brings it to the front (a hidden window stays hidden and does not take the focus); the first window's end closes the others. A window is identified by the `file` string as given, query included. `WebKitGTKFrontend`, `WKWebViewFrontend` and `WebView2Frontend` implement it: `BasicWF::openSecondaryWindow()` throws `std::logic_error` for a frontend without it (CEF, the system browser), never opening a browser. `BasicWF::supportsSecondaryWindow` tells it from the frontend type; an optional `static bool secondaryWindowsAvailable()` tells it at run time, and `BasicWF::canShowSecondaryWindow()` combines both. `NativeOrBrowserFrontendFor` offers the functions only when its native frontend does, and reports them unavailable once it fell back to the system browser. The call waits for the interface thread (it runs at once on that thread): a `cppFunction` callback, which runs on the server's thread, schedules it with `app.uiExecutor()` instead of holding every exchange of the application while it waits. A window that cannot start throws the failure to the caller; one that fails to load later closes and writes the failure to stderr (the call has returned: nothing can throw it). A request that runs after the first window closed is refused with `std::logic_error`. A frontend whose first window cannot host another yet throws `frontend::WindowNotReady` (a `std::logic_error`): `BasicWF` and `invokeOnUIThreadWhenReady()` try again from another thread, and pass it to a caller on the interface thread. WebKitGTK shares the first window's network session (cookies, storage; downloads are tracked by the first window) and ignores `WindowOptions::media`. WKWebView shares its nonpersistent website data store and follows the first window's visibility (a hidden application shows no window and does not take the focus). WebView2 creates the second browser from the first window's environment, so the profile (storage, cookies) and the browser process are shared; it follows the first window's visibility, and has its own startup watchdog, with the first window's delay (the one `WebView2FrontendWithOptions` configured). A call made while the first window's environment is still being created waits for it (bounded by that window's watchdog); on the interface thread it throws `std::logic_error`. Placement is left to the toolkit. | +| `static void openSecondaryWindow(address, port, file, policy, window, launch)` and `static bool closeSecondaryWindow(file)` (optional) | A second window beside the one `open()` runs (#616), callable from any thread while it runs; `invokeOnUIThread()` (UIExecutor.hpp) hops to the interface thread. See [Secondary windows](#secondary-windows). | | `static bool requestClose()` (optional) | Asks, from any thread, the session that `open()` runs to end as if the user had closed the window; false when nothing is open. `BasicWF::requestClose()` forwards it only for the application whose `show()` owns that session (its thread is the frontend's published interface thread). A frontend with an executor takes `requestClose(std::optional)` and drops the request, on its interface thread, if another loop runs by then. | | `static constexpr bool requiresMainThread` (optional) | `open()` belongs to the process main thread; `webfront::UIThread` refuses the frontend at compile time. Undeclared means any thread. | @@ -28,6 +28,17 @@ A frontend is a type with: - **URL.** Built-in frontends also provide `open(address, port, file)`, which `BasicWF` prefers when available. Build the URL with `frontend::detail::applicationUrl(address, port, file)` in `frontend/Url.hpp`: it uses the configured address and preserves URI query/fragment syntax and existing percent escapes. Spaces and UTF-8 bytes are encoded. For literal filename delimiters use `%23`, `%3F` and `%25`. The two-argument overload uses `127.0.0.1`; wildcard binds open their matching loopback address. - **Selection.** `webfront::WebFront` always uses the system browser. An application opts into another frontend with `webfront::WebFrontWithFrontend<...>`; enabling an embedded engine at configuration time never changes the default. +## Secondary windows + +Opening a page that a secondary window already shows brings it to the front: a hidden window stays hidden and does not take the focus (WebKitGTK has no hidden mode and always raises it). The first window's end closes the others. A window is identified by the `file` string as given, query included. `WebKitGTKFrontend`, `WKWebViewFrontend` and `WebView2Frontend` implement the functions: `BasicWF::openSecondaryWindow()` throws `std::logic_error` for a frontend without them (CEF, the system browser), never opening a browser. `BasicWF::supportsSecondaryWindow` tells it from the frontend type; an optional `static bool secondaryWindowsAvailable()` tells it at run time, and `BasicWF::canShowSecondaryWindow()` combines both. `NativeOrBrowserFrontendFor` offers the functions only when its native frontend does, and reports them unavailable once it fell back to the system browser. + +The call waits for the interface thread (it runs at once on that thread): a `cppFunction` callback, which runs on the server's thread, schedules it with `app.uiExecutor()` instead of holding every exchange of the application while it waits. A window that cannot start throws the failure to the caller; one that fails to load later closes and writes the failure to stderr (the call has returned: nothing can throw it). A request that runs after the first window closed is refused with `std::logic_error`, whether or not the page is already open. A frontend whose first window cannot host another yet throws `frontend::WindowNotReady` (a `std::logic_error`): `BasicWF` and `invokeOnUIThreadWhenReady()` try again from another thread (for at most one minute, then throw `std::logic_error`), and pass it to a caller on the interface thread. + +- **WebKitGTK** shares the first window's network session (cookies, storage; downloads are tracked by the first window) and ignores `WindowOptions::media`. +- **WKWebView** shares its nonpersistent website data store and follows the first window's visibility (a hidden application shows no window and does not take the focus). +- **WebView2** creates the second browser from the first window's environment, so the profile (storage, cookies) and the browser process are shared; it follows the first window's visibility and has its own startup watchdog, with the first window's delay (the one `WebView2FrontendWithOptions` configured). A call made while the first window's environment is still being created waits for it (bounded by that window's watchdog); on the interface thread it throws `std::logic_error`. The browser is created asynchronously, so a failure after the window exists closes it and is written to stderr. +- Placement is left to the toolkit. `ui.nativeWindow()` and the native dialogs of a secondary connection refer to the first window: per-window native handles are not implemented. + ## View association `UI::isEmbeddedView()` tells whether a connection comes from the view of an embedded frontend of this application, and @@ -210,7 +221,7 @@ Registry order determines the initial cache default: the first enabled embedded - `path-encoding`: load `encoded path #.html` and verify that its query and fragment survived. - `content-policy`: block a popup and a foreign-origin top-level navigation while keeping the original page alive. - `navigation-allow-list`: permit the same top-level destination through the explicit navigation allow-list. -- `second-window` (#616): a second window shares storage, a `cppFunction` and a pushed `jsFunction` with the first and carries the embedded-view proof; the same page again opens nothing; closing the second leaves the first usable and it can reopen; closing the first closes the second; a window opened as soon as the loop runs, before the first page connected, opens; a request that runs in the pass where the first window closed is refused (WebKitGTK, WKWebView). Frontends without the capability must refuse with `std::logic_error`. +- `second-window` (#616): a second window shares storage, a `cppFunction` and a pushed `jsFunction` with the first and carries the embedded-view proof; the same page again opens nothing; closing the second leaves the first usable and it can reopen; closing the first closes the second; a window opened as soon as the loop runs, before the first page connected, opens; a request that runs in the pass where the first window closed is refused (every frontend with the capability). Frontends without the capability must refuse with `std::logic_error`. - `host-close`: a host thread exchanges with the page while `show()` runs, then `requestClose()` ends the session; a request before and after the window is refused. - `host-thread` (not CEF): `webfront::UIThread` runs the application on a secondary thread where the frontend allows it; elsewhere a window opened on a secondary thread must be refused with the main-thread diagnostic. - `view-association`: the page of the view connects with the secret of the launch and `UI::isEmbeddedView()` is true; a second connection of that page, from the same loopback address and without the secret, is not associated. diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 40db4fcd..284bc958 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -30,6 +30,7 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer A second native window of the same application (`app.openSecondaryWindow()`, #616) exists on WebKitGTK, WKWebView and WebView2; CEF and the system browser refuse it with `std::logic_error` (`app.canShowSecondaryWindow()` tells it beforehand, also after `NativeOrBrowserFrontend` fell back to the browser), and the position of the window is left to the toolkit. The call waits for the interface thread: a `cppFunction` callback runs it on `app.uiExecutor()` rather than hold the server's thread. + `ui.nativeWindow()` and the native dialogs of a secondary window's connection still refer to the first window: per-window native handles are not implemented. - **Native pseudoterminals (opt-in).** `webfront::Pty` uses a Unix PTY on Linux and macOS or ConPTY on Windows 10 version 1809 and later. The page adapter requires a loopback bind and the application’s own browser origin. See the [PTY guide and standalone example](PTY.md). - **Developer environment.** `NativeApp::bootstrap("developer")` loads the verified, pinned environment selected by `DeveloperReleaseData.hpp`. Its terminal provides `wf init`, `create`, diff --git a/include/webfront/frontend/UIExecutor.hpp b/include/webfront/frontend/UIExecutor.hpp index d2c579cd..0d1da3b0 100644 --- a/include/webfront/frontend/UIExecutor.hpp +++ b/include/webfront/frontend/UIExecutor.hpp @@ -419,6 +419,8 @@ struct UIInvocation { using receiver_concept = ex::receiver_tag; UIInvocation* self; void finish(std::exception_ptr error) noexcept { + // The operation state holds this receiver and is deleted from its own completion: only the moved-out promise is + // touched afterwards. auto completion = std::move(self->done); delete self; completion.set_value(std::move(error)); @@ -466,9 +468,11 @@ void invokeOnUIThread(const UIExecutor& executor, Function function) { /// @brief invokeOnUIThread(), run again every 10 ms while `function` throws WindowNotReady (#646). The interface thread /// cannot wait for itself: there, WindowNotReady reaches the caller. The frontend bounds the wait: a first window that -/// never becomes ready closes, and the call then fails as invokeOnUIThread() does. +/// never becomes ready closes, and the call then fails as invokeOnUIThread() does. A frontend that does not bound it is +/// bounded here: after `limit` (one minute by default) the call throws std::logic_error. template -void invokeOnUIThreadWhenReady(const UIExecutor& executor, Function function) { +void invokeOnUIThreadWhenReady(const UIExecutor& executor, Function function, std::chrono::milliseconds limit = std::chrono::minutes(1)) { + const auto deadline = std::chrono::steady_clock::now() + limit; for (;;) { try { invokeOnUIThread(executor, function); @@ -476,6 +480,8 @@ void invokeOnUIThreadWhenReady(const UIExecutor& executor, Function function) { } catch (const WindowNotReady&) { if (executor.onUIThread()) throw; + if (std::chrono::steady_clock::now() >= deadline) + throw std::logic_error("the first window did not become ready in time to host another"); } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index 094700b6..c906f6c2 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -1038,6 +1038,7 @@ inline void openSecondary(const std::string& address, const std::string& port, c if (!windows.primary || windows.primary->closed) throw std::logic_error("WebKitGTKFrontend: no window of the application is open; show() it before opening another"); if (const auto found = windows.secondary.find(file); found != windows.secondary.end()) { + // WebKitGTK has no hidden mode (its windows are always presented): raising the window is the right answer. api().windowPresent(found->second->window); return; } diff --git a/include/webfront/frontend/WebView2.hpp b/include/webfront/frontend/WebView2.hpp index 22708607..1cf896f3 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -1073,6 +1073,9 @@ inline void openSecondary(std::string_view address, std::string_view port, std:: auto& windows = Windows::instance(); if (!windows.primary) throw std::logic_error("WebView2Frontend: no window of the application is open; show() it before opening another"); + // Refused first, as the other frontends do: a first window that closed no longer raises or opens anything. + if (windows.primary->closed) + throw std::logic_error("WebView2Frontend: no window of the application is open; show() it before opening another"); const std::string key(page); if (const auto found = windows.secondary.find(key); found != windows.secondary.end()) { // A hidden window stays hidden and does not take the focus. @@ -1083,8 +1086,6 @@ inline void openSecondary(std::string_view address, std::string_view port, std:: } return; } - if (windows.primary->closed) - throw std::logic_error("WebView2Frontend: no window of the application is open; show() it before opening another"); if (!windows.primary->environment) throw WindowNotReady("WebView2Frontend: the first window is not ready (its browser is being created); call it later"); // The first window's delay, which the application configured (WebView2FrontendWithOptions), not this call's default. @@ -1099,8 +1100,8 @@ inline void openSecondary(std::string_view address, std::string_view port, std:: session->createWindow(windows.primary->shown(), options.window); session->startSecondary(windows.primary->environment.Get()); // Registered only once started: a window whose start throws is not left in the table, and its page can be opened again. - // One that closed during the start retired itself from a table that did not hold it yet, without a word: the caller is - // still waiting, so the failure is thrown to it. + // The browser is created asynchronously: this test only catches a window that closed synchronously (a refused creation), + // which retired itself from a table that did not hold it yet, without a word. A later failure is written by retire(). if (session->closed) { if (session->failure) std::rethrow_exception(session->failure); diff --git a/test/unit/UIExecutorTests.cpp b/test/unit/UIExecutorTests.cpp index 8c5370b1..62c89815 100644 --- a/test/unit/UIExecutorTests.cpp +++ b/test/unit/UIExecutorTests.cpp @@ -884,3 +884,39 @@ const Scenario invokeBlocking{"invokeOnUIThread runs a function on the interface }); }); }}; + +const Scenario invokeWhenReady{"invokeOnUIThreadWhenReady tries again while the window is not ready, and gives up after its limit", [] { + given("a frontend loop attached to an executor", [&] { + FakeLoop loop; + loop.start(); + const auto executor = loop.host.executor(); + when("the function is refused twice as not ready", [&] { + int attempts = 0; + invokeOnUIThreadWhenReady(executor, [&] { + if (++attempts < 3) + throw WindowNotReady("not ready"); + }); + then("it ran again until the window was ready", [&] { + check(attempts == 3); + }); + }); + when("the window never becomes ready", [&] { + int attempts = 0; + then("the call throws once its limit elapsed instead of waiting forever", [&] { + requireThrows([&] { + invokeOnUIThreadWhenReady(executor, [&] { ++attempts; throw WindowNotReady("never"); }, 50ms); + }); + check(attempts > 1); + }); + }); + when("the interface thread itself is refused as not ready", [&] { + then("the refusal reaches the caller at once", [&] { + requireThrows([&] { + invokeOnUIThread(executor, [&] { + invokeOnUIThreadWhenReady(executor, [] { throw WindowNotReady("now"); }); + }); + }); + }); + }); + }); +}};