From b9478f1cb5255d40dc7cebb8809cd44e9e595b58 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:49:30 +0100 Subject: [PATCH 1/4] Automation: give each launch its own WebView2 profile and answer clients while the MCP listener closes (#720) Every automation_host launched by AutomationClient.py took WebView2's default user data folder, derived from its executable: the concurrent automation scenarios and the two launches of the stable one shared one WebView2 browser process. A launch that joined the browser process of a host being closed lost its window with it; the session closed, and the MCP listener closed with the client's request still unanswered, which the client read as a reset (WinError 10054). Each launch now has its own WEBFRONT_TEST_WEBVIEW2_PROFILE, as the wf driver and the Jasmine runner already do. The listener no longer resets its clients when it closes: it takes its backlog, closes, then serves the requests already sent for up to a second (a closed session says so). A peer's request is read before its two-second deadline is applied, and what a dropped peer sent is read first, so that its close is not a reset. The stable scenario names the failing launch, its port and the host's exit status, and attaches stable.log. --- docs/AUTOMATION.md | 5 +- docs/CHANGELOG.md | 1 + include/webfront/automation/McpHttp.hpp | 131 +++++++++++++++--------- test/tools/AutomationClient.py | 40 +++++++- test/tools/AutomationClientTest.py | 21 +++- test/unit/AutomationMcpHttpTests.cpp | 33 ++++++ 6 files changed, 178 insertions(+), 53 deletions(-) diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 6c93cd5a..04d481ee 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -139,7 +139,8 @@ operation of `webfront.start`, not one MCP tool per callback, so the tool list s - **Token.** By default every request carries `Authorization: Bearer `, a 256-bit value from the OS. Before parsing the body, the listener compares equal-length tokens in constant time and rejects a length mismatch immediately; a failed check gets 401 with `WWW-Authenticate: Bearer` (no OAuth server is announced). The token lives as - long as the session by default: closing it, a deadline or a lost window closes the listener and removes the file. A supplied + long as the session by default: closing it, a deadline or a lost window closes the listener and removes the file; a client + already connected then still reads its answer, which says the session is closed, within a second. A supplied `mcpToken` remains valid across launches until the application changes it; authentication can be explicitly disabled. - **Client configuration.** `mcp.json` (mode 0600 in a 0700 directory on POSIX, owner-only ACL on Windows) holds the URL and the header, ready for a client that takes a configuration file (`claude --mcp-config PATH/mcp.json`). The token appears in @@ -369,7 +370,7 @@ control need their own reviewed authorization/isolation design. `AutomationMcpHttpTests.cpp` covers the listener: screening of Host, Origin, Sec-Fetch, path, method, token, media types and lengths; MCP sessions, revisions, batches, notifications and eviction; real sockets with refusals read before a reset, -`Expect: 100-continue`, silent peers, a taken port and revocation; two activations side by side and the cleanup of a vanished +`Expect: 100-continue`, silent peers, a taken port, revocation and a client answered while the listener closes; two activations side by side and the cleanup of a vanished instance. The other unit tests cover native grants, cross-session rejection, path/option refusal, cancellation races, deadline revocation, the MCP lifecycle and identifiers, and hostile JSON. `AutomationAbsentFromDistribution` checks that `Enable.hpp` does not compile with `WEBFRONT_DISTRIBUTION`. Browser Jasmine specs cover shared dispatch arbitration and the diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index aa988f23..56962ed4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -50,6 +50,7 @@ these entries stays in the GitHub releases and the Git history. - A `+` in the path of a file request is a literal `+`, as for the routes, the spaces and `ui.path()`: `/a+b.html` serves `a+b.html`, no longer `a b.html`, which `/a%20b.html` names (#672). ### Fixed +- A client connected to the MCP listener when it closes, because the session closed or the application stopped, reads its answer (a closed session says so) instead of a connection reset; a request that arrived just before its peer's two-second deadline is served rather than reset (#720, `docs/AUTOMATION.md`). - A closed WKWebView secondary window, or one that another window covered, no longer leaves its page suspended and connected to the application: on macOS 14+ a secondary window is never suspended while inactive (#681, `docs/WKWEBVIEW.md`). - A closed WKWebView secondary window disconnects as soon as it is released, even while the system still holds its view: its page is closed explicitly instead of when the view's last reference goes, which kept the detached inspector window connected for more than thirty seconds (#702, `docs/WKWEBVIEW.md`). - A closed WebView2 secondary window disconnects at once: its page navigates to `about:blank` before its controller closes, instead of ending whenever the renderer of the shared environment got to it, which once kept the detached inspector window connected for more than thirty seconds (#708, `docs/WEBVIEW2.md`). diff --git a/include/webfront/automation/McpHttp.hpp b/include/webfront/automation/McpHttp.hpp index 94ed3797..5899ecae 100644 --- a/include/webfront/automation/McpHttp.hpp +++ b/include/webfront/automation/McpHttp.hpp @@ -15,7 +15,8 @@ // session Bearer token compared in constant time, then the media types and the announced length. The token is written // with the URL in `mcp.json`, a private client configuration in the instance's private directory, never in the project. // Admission bounds the peers that have not authenticated: a bounded queue of unauthenticated peers with a two-second deadline, -// and separate workers for the authenticated requests. +// and separate workers for the authenticated requests. When the listener closes (the session closed, or `stop()`), the +// clients it had accepted, or that wait in its backlog, still get their answer for up to a second instead of a reset. #pragma once #if defined(WEBFRONT_DISTRIBUTION) && WEBFRONT_DISTRIBUTION @@ -27,6 +28,7 @@ #include #include +#include #include #include #include @@ -407,7 +409,7 @@ class BindError : public std::system_error { }; /// The loopback listener. It writes `mcp.json` into `directory` (an existing private directory outside the project) and -/// removes it when it stops. Closing the session stops it; so does `stop()`. +/// removes it when it stops. Closing the session stops it; so does `stop()`. Either answers the connected clients first. template class Server { public: @@ -454,7 +456,8 @@ class Server { const std::filesystem::path& configuration() const { return file; } - /// Closes the listener, waits for the requests in progress and removes `mcp.json`. Idempotent. + /// Closes the listener, removes `mcp.json`, answers the clients already connected (for up to a second) and waits for + /// the requests in progress. Idempotent. void stop() { worker.request_stop(); if (worker.joinable()) @@ -476,6 +479,8 @@ class Server { std::jthread worker; static constexpr std::size_t maxConnections = 32, maxPending = 64; + // How long a closing listener still serves the requests of the clients it had accepted. + static constexpr std::chrono::milliseconds closingGrace{1000}; struct Connection { std::atomic finished{false}; std::jthread thread; @@ -583,59 +588,93 @@ class Server { owner.withdraw(); } } revoke{*this}; - while (!stop.stop_requested() && !backend->isClosed()) { - std::erase_if(connections, [](const Connection& connection) { - return connection.finished.load(); - }); + while (!stop.stop_requested() && !backend->isClosed()) + step(connections, pending, true, std::chrono::steady_clock::time_point::max()); + // Closing (#720): a client connected before the listener closes is answered (a closed session says so) rather + // than reset. The backlog is taken first, then the listener closes; the requests already sent are served for + // a bounded time, whatever stopped the listener, since the session's closing also asks to stop it. + for (std::size_t accepted = 0; accepted < maxPending && pending.size() < maxPending; ++accepted) { + const auto handle = channel::acceptSocket(listener.value); + if (handle == channel::invalid) + break; + pending.emplace_back(handle); + } + listener.reset(); + withdraw(); + const auto closing = std::chrono::steady_clock::now() + closingGrace; + while (!pending.empty() && std::chrono::steady_clock::now() < closing) + step(connections, pending, false, closing); + for (auto& peer : pending) + discard(peer); + } + // One round: reads the readable peers, dispatches their complete requests and, while `accepting`, takes a batch of + // connections. A peer is closed at its deadline or at `limit`, after what it sent has been read: bytes left unread + // would make the system answer it with a reset instead of the end of the stream. + void step(std::list& connections, std::list& pending, bool accepting, std::chrono::steady_clock::time_point limit) { + std::erase_if(connections, [](const Connection& connection) { + return connection.finished.load(); + }); #ifdef _WIN32 - std::vector items; + std::vector items; #else - std::vector items; + std::vector items; #endif + if (accepting) items.push_back({listener.value, POLLIN, 0}); - for (const auto& peer : pending) - items.push_back({peer.socket.value, POLLIN, 0}); + for (const auto& peer : pending) + items.push_back({peer.socket.value, POLLIN, 0}); #ifdef _WIN32 - if (::WSAPoll(items.data(), static_cast(items.size()), 20) < 0) - continue; + if (::WSAPoll(items.data(), static_cast(items.size()), 20) < 0) + return; #else - if (::poll(items.data(), static_cast(items.size()), 20) < 0) - continue; + if (::poll(items.data(), static_cast(items.size()), 20) < 0) + return; #endif - std::size_t index = 1; - for (auto peer = pending.begin(); peer != pending.end(); ++index) { - bool keep = std::chrono::steady_clock::now() < peer->deadline; - if (keep && items[index].revents) { - char bytes[4096]; - const auto count = channel::SocketRead{}(peer->socket.value, bytes, sizeof bytes); - if (count > 0 && !peer->refused) { - if (feed(*peer, std::string_view(bytes, static_cast(count)))) { - if (connections.size() >= maxConnections) - refuse(*peer, refusal(503, "The MCP listener is busy")); - else { - dispatch(connections, *peer); - keep = false; - } + std::size_t index = accepting ? 1 : 0; + for (auto peer = pending.begin(); peer != pending.end(); ++index) { + bool keep = true; + // Read before the deadline applies: a request that arrived while this thread was not scheduled is served. + if (items[index].revents) { + char bytes[4096]; + const auto count = channel::SocketRead{}(peer->socket.value, bytes, sizeof bytes); + if (count > 0 && !peer->refused) { + if (feed(*peer, std::string_view(bytes, static_cast(count)))) { + if (connections.size() >= maxConnections) + refuse(*peer, refusal(503, "The MCP listener is busy")); + else { + dispatch(connections, *peer); + keep = false; } - } else if (count == 0 || (count < 0 && !channel::retryableSocketError(channel::socketError()))) - keep = false; - } - if (keep) - ++peer; - else - peer = pending.erase(peer); + } + } else if (count == 0 || (count < 0 && !channel::retryableSocketError(channel::socketError()))) + keep = false; } - // Drain a bounded batch, then serve the readable peers before accepting another batch. - if (items.front().revents) - for (std::size_t accepted = 0; accepted < maxPending; ++accepted) { - const auto handle = channel::acceptSocket(listener.value); - if (handle == channel::invalid) - break; - if (pending.size() >= maxPending) - pending.pop_front(); - pending.emplace_back(handle); - } + if (keep && std::chrono::steady_clock::now() >= std::min(peer->deadline, limit)) { + discard(*peer); + keep = false; + } + if (keep) + ++peer; + else + peer = pending.erase(peer); } + // Drain a bounded batch, then serve the readable peers before accepting another batch. + if (accepting && items.front().revents) + for (std::size_t accepted = 0; accepted < maxPending; ++accepted) { + const auto handle = channel::acceptSocket(listener.value); + if (handle == channel::invalid) + break; + if (pending.size() >= maxPending) + pending.pop_front(); + pending.emplace_back(handle); + } + } + // Reads, without waiting, what a peer about to be closed has already sent. + static void discard(Pending& peer) noexcept { + char bytes[4096]; + for (int reads = 0; reads < 16; ++reads) + if (channel::SocketRead{}(peer.socket.value, bytes, sizeof bytes) <= 0) + break; } void dispatch(std::list& connections, Pending& peer) { auto& connection = connections.emplace_back(); diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 0c4110f2..8ea1ff16 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -168,6 +168,21 @@ def raw_request(port, text): return int(answer.split(b" ", 2)[1]) +def host_environment(base, profile, temporary): + """The environment of one launch: every browser profile private to it. + + WebView2 shares one browser process between the applications that use the same user data folder, and without + WEBFRONT_TEST_WEBVIEW2_PROFILE every automation_host takes the same default folder (derived from its executable). + A launch then joined the browser process of a host that another scenario, or the previous launch, was closing, and + lost its window with that process: the session closed and its MCP listener with it (#720).""" + profile = pathlib.Path(profile) + environment = dict(base, XDG_DATA_HOME=str(profile / "data"), XDG_CACHE_HOME=str(profile / "cache"), + WEBFRONT_TEST_CEF_PROFILE=str(profile / "cef"), WEBFRONT_TEST_WEBVIEW2_PROFILE=str(profile / "webview2")) + # Chromium puts its singleton Unix socket in TMPDIR: a short private directory keeps it below sockaddr_un's limit. + environment.update(TMPDIR=str(temporary), TEMP=str(temporary), TMP=str(temporary)) + return environment + + class Host: """automation_host: an application that enabled automation, launched with its own browser profile.""" @@ -182,10 +197,10 @@ def __init__(self, args, project, root, name, log, extra=(), environment=None, i self.base = ["--project", str(project), "--environment", environment or args.environment, "--integrity", integrity or json.loads(pathlib.Path(args.provision).read_text())["integrity"], "--registry-dir", args.registry] - env = dict(os.environ, XDG_DATA_HOME=str(profile / "data"), XDG_CACHE_HOME=str(profile / "cache"), - WEBFRONT_TEST_CEF_PROFILE=str(profile / "cef")) - # Chromium puts its singleton Unix socket in TMPDIR: a short private directory keeps it below sockaddr_un's limit. - env.update(TMPDIR=temporary, TEMP=temporary, TMP=temporary) + env = host_environment(os.environ, profile, temporary) + # Each launch is announced in the log that the hosts of a scenario share, so that a failure names its own lines. + log.write(f"--- {name} ---\n") + log.flush() # Closing its standard input closes the application's window (stop()). self.process = subprocess.Popen([args.host, *self.base, "--sessions", str(self.sessions), *extra], stdin=subprocess.PIPE, stdout=log, stderr=log, text=True, env=env) @@ -635,6 +650,13 @@ def port_conflict_after_failure(process, timeout=1): return False +def launch_failure(name, run, port, failure, status, log): + """The report of a failed launch of the stable scenario: which launch, on which port, why, how the host ended and + the hosts' log.""" + return (f"{name}: launch {run + 1} of 2 on the fixed MCP port {port} failed: {type(failure).__name__}: {failure}\n" + f"host exit status: {status}\n--- stable.log ---\n{log}") + + def stable(args): pathlib.Path(args.work).mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(dir=args.work, prefix="stable-") as temporary: @@ -683,6 +705,16 @@ def stable(args): client.close() host.stop() assert host.wait() == 0, host.logs() + except Exception as failure: + # Say which launch failed, with the whole log of the hosts (the failing one last), once the host + # has written its last lines: a host whose session closed exits by itself. + try: + status = host.process.wait(timeout=5) + except subprocess.TimeoutExpired: + status = "still running, killed" + host.process.kill() + host.process.wait() + raise AssertionError(launch_failure(host.name, run, port, failure, status, host.full_log())) from failure finally: host.close() else: diff --git a/test/tools/AutomationClientTest.py b/test/tools/AutomationClientTest.py index 0da1a17f..6066f7f5 100644 --- a/test/tools/AutomationClientTest.py +++ b/test/tools/AutomationClientTest.py @@ -1,4 +1,5 @@ -"""Port-collision status can arrive just after discovery fails.""" +"""Port-collision status can arrive just after discovery fails; each launch has its own profiles and names itself on failure.""" +import pathlib import subprocess import sys import unittest @@ -28,5 +29,23 @@ def test_still_running_is_not_retried(self): process.terminate() +class LaunchIsolation(unittest.TestCase): + def test_each_launch_has_its_own_webview2_profile(self): + # Without it every automation_host shares WebView2's default user data folder, hence one browser process (#720). + first = AutomationClient.host_environment({"PATH": "x"}, pathlib.Path("one") / "profile", "one") + second = AutomationClient.host_environment({"PATH": "x"}, pathlib.Path("two") / "profile", "two") + self.assertEqual(first["WEBFRONT_TEST_WEBVIEW2_PROFILE"], str(pathlib.Path("one") / "profile" / "webview2")) + for name in ("WEBFRONT_TEST_WEBVIEW2_PROFILE", "WEBFRONT_TEST_CEF_PROFILE", "XDG_DATA_HOME", "XDG_CACHE_HOME", "TMP"): + self.assertNotEqual(first[name], second[name], name) + self.assertEqual(first["PATH"], "x") + + def test_launch_failure_names_the_launch_and_carries_the_log(self): + report = AutomationClient.launch_failure("stable-0-1", 1, 4242, ConnectionResetError(10054, "reset"), 1, + "--- stable-0-1 ---\nautomation_host: listening\n") + self.assertIn("stable-0-1: launch 2 of 2 on the fixed MCP port 4242 failed: ConnectionResetError", report) + self.assertIn("host exit status: 1", report) + self.assertIn("--- stable.log ---\n--- stable-0-1 ---\nautomation_host: listening", report) + + if __name__ == "__main__": unittest.main() diff --git a/test/unit/AutomationMcpHttpTests.cpp b/test/unit/AutomationMcpHttpTests.cpp index a98b217e..4fd9cab5 100644 --- a/test/unit/AutomationMcpHttpTests.cpp +++ b/test/unit/AutomationMcpHttpTests.cpp @@ -560,6 +560,39 @@ const Scenario mcpHttpListener{ }); }}; +// #720: the session closing closed the listener with the clients it had accepted, whose requests then met a reset. +const Scenario mcpHttpClosingListener{"A closing MCP listener answers the clients it had accepted", [] { + using namespace mcphttptests; + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + auto controller = std::make_shared(SessionOptions{root.path() / "project", {"build"}}); + controller->poll(); + channel::PrivateDirectory directory{root.path() / "private"}; + mcphttp::Server server{controller, directory.path}; + const auto port = server.port(); + const auto secret = bearer(directory.path); + [[maybe_unused]] channel::Runtime runtime; + given("a client whose request is not complete when the session closes", [&] { + const auto text = post(port, initialize, {}, secret); + channel::Socket peer{channel::createSocket()}; + connectTo(peer, port); + channel::send(peer.value, text.substr(0, 20)); + when("the session closes, then the client sends the rest of its request", [&] { + controller->close("Developer window disconnected"); + std::this_thread::sleep_for(std::chrono::milliseconds{150}); + channel::send(peer.value, text.substr(20)); + then("it reads an answer instead of a reset, and the listener is closed", [&] { + const auto received = drain(peer.value); + require(received.starts_with("HTTP/1.1 ")); + checkEqual(reply(received).status, 200); + channel::Socket late{channel::createSocket()}; + const auto address = channel::address(port); + require(::connect(late.value, reinterpret_cast(&address), sizeof address) != 0); + }); + }); + }); + }}; + const Scenario mcpHttpActivation{"An application that enables automation serves its own MCP URL", [] { using namespace mcphttptests; webfront::test::TemporaryDirectory root; From 6f3b3bae44a695e0707b6c45d6035fe7ef5b0672 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:07:39 +0100 Subject: [PATCH 2/4] Read the WebView2 test profile in UTF-16 and serve a buffered request at its deadline (#720) The automation client's profiles live under a temporary directory whose name holds a character outside the ANSI code page on Windows: read through _dupenv_s, it became '?' and the host could not create its WebView2 profile. DriverWebView2Options reads WEBFRONT_TEST_WEBVIEW2_PROFILE with _wdupenv_s. A pending peer reaching its deadline, or the end of the closing grace, is first fed what it already sent (up to the largest acceptable request), so that a complete request larger than one read is answered rather than dropped. The documentation says that a client has up to a second to complete its request while the listener closes, not that it is answered within that second. --- docs/AUTOMATION.md | 3 +- docs/CHANGELOG.md | 2 +- include/webfront/automation/McpHttp.hpp | 51 +++++++++++++++---------- test/driver/WfDriver.hpp | 19 +++++++-- test/unit/WfDriverTests.cpp | 18 ++++++++- 5 files changed, 66 insertions(+), 27 deletions(-) diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 04d481ee..666981ad 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -140,7 +140,8 @@ operation of `webfront.start`, not one MCP tool per callback, so the tool list s body, the listener compares equal-length tokens in constant time and rejects a length mismatch immediately; a failed check gets 401 with `WWW-Authenticate: Bearer` (no OAuth server is announced). The token lives as long as the session by default: closing it, a deadline or a lost window closes the listener and removes the file; a client - already connected then still reads its answer, which says the session is closed, within a second. A supplied + already connected has up to a second to complete its request, within the admission bounds, and is then answered as the + closed session answers rather than reset. A supplied `mcpToken` remains valid across launches until the application changes it; authentication can be explicitly disabled. - **Client configuration.** `mcp.json` (mode 0600 in a 0700 directory on POSIX, owner-only ACL on Windows) holds the URL and the header, ready for a client that takes a configuration file (`claude --mcp-config PATH/mcp.json`). The token appears in diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 56962ed4..9e086f24 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -50,7 +50,7 @@ these entries stays in the GitHub releases and the Git history. - A `+` in the path of a file request is a literal `+`, as for the routes, the spaces and `ui.path()`: `/a+b.html` serves `a+b.html`, no longer `a b.html`, which `/a%20b.html` names (#672). ### Fixed -- A client connected to the MCP listener when it closes, because the session closed or the application stopped, reads its answer (a closed session says so) instead of a connection reset; a request that arrived just before its peer's two-second deadline is served rather than reset (#720, `docs/AUTOMATION.md`). +- A client connected to the MCP listener when it closes, because the session closed or the application stopped, and completes its request within a second reads its answer (a closed session says so) instead of a connection reset; a request that arrived just before its peer's two-second deadline is served rather than reset (#720, `docs/AUTOMATION.md`). - A closed WKWebView secondary window, or one that another window covered, no longer leaves its page suspended and connected to the application: on macOS 14+ a secondary window is never suspended while inactive (#681, `docs/WKWEBVIEW.md`). - A closed WKWebView secondary window disconnects as soon as it is released, even while the system still holds its view: its page is closed explicitly instead of when the view's last reference goes, which kept the detached inspector window connected for more than thirty seconds (#702, `docs/WKWEBVIEW.md`). - A closed WebView2 secondary window disconnects at once: its page navigates to `about:blank` before its controller closes, instead of ending whenever the renderer of the shared environment got to it, which once kept the detached inspector window connected for more than thirty seconds (#708, `docs/WEBVIEW2.md`). diff --git a/include/webfront/automation/McpHttp.hpp b/include/webfront/automation/McpHttp.hpp index 5899ecae..d4a5bcfb 100644 --- a/include/webfront/automation/McpHttp.hpp +++ b/include/webfront/automation/McpHttp.hpp @@ -16,7 +16,8 @@ // with the URL in `mcp.json`, a private client configuration in the instance's private directory, never in the project. // Admission bounds the peers that have not authenticated: a bounded queue of unauthenticated peers with a two-second deadline, // and separate workers for the authenticated requests. When the listener closes (the session closed, or `stop()`), the -// clients it had accepted, or that wait in its backlog, still get their answer for up to a second instead of a reset. +// clients it had accepted, or that wait in its backlog, have up to a second to complete their requests, which are then +// answered instead of reset. #pragma once #if defined(WEBFRONT_DISTRIBUTION) && WEBFRONT_DISTRIBUTION @@ -456,8 +457,8 @@ class Server { const std::filesystem::path& configuration() const { return file; } - /// Closes the listener, removes `mcp.json`, answers the clients already connected (for up to a second) and waits for - /// the requests in progress. Idempotent. + /// Closes the listener, removes `mcp.json`, serves the requests that the clients already connected complete within a + /// second, and waits for the requests in progress. Idempotent. void stop() { worker.request_stop(); if (worker.joinable()) @@ -481,6 +482,8 @@ class Server { static constexpr std::size_t maxConnections = 32, maxPending = 64; // How long a closing listener still serves the requests of the clients it had accepted. static constexpr std::chrono::milliseconds closingGrace{1000}; + // Enough reads of 4 KiB for the largest acceptable request: its headers and a body of `messageLimit` bytes. + static constexpr std::size_t wholeRequestReads = (headerLimit + messageLimit) / 4096 + 2; struct Connection { std::atomic finished{false}; std::jthread thread; @@ -632,25 +635,12 @@ class Server { #endif std::size_t index = accepting ? 1 : 0; for (auto peer = pending.begin(); peer != pending.end(); ++index) { - bool keep = true; // Read before the deadline applies: a request that arrived while this thread was not scheduled is served. - if (items[index].revents) { - char bytes[4096]; - const auto count = channel::SocketRead{}(peer->socket.value, bytes, sizeof bytes); - if (count > 0 && !peer->refused) { - if (feed(*peer, std::string_view(bytes, static_cast(count)))) { - if (connections.size() >= maxConnections) - refuse(*peer, refusal(503, "The MCP listener is busy")); - else { - dispatch(connections, *peer); - keep = false; - } - } - } else if (count == 0 || (count < 0 && !channel::retryableSocketError(channel::socketError()))) - keep = false; - } + bool keep = !items[index].revents || receive(connections, *peer, 1); + // At its deadline, a peer is served if the rest of its request is already there; otherwise it is closed. if (keep && std::chrono::steady_clock::now() >= std::min(peer->deadline, limit)) { - discard(*peer); + if (receive(connections, *peer, wholeRequestReads)) + discard(*peer); keep = false; } if (keep) @@ -669,6 +659,27 @@ class Server { pending.emplace_back(handle); } } + // Feeds a peer up to `reads` reads of what it already sent, without waiting. Returns whether it stays pending: false + // once its request is dispatched, or when its client closed or failed. + bool receive(std::list& connections, Pending& peer, std::size_t reads) { + char bytes[4096]; + for (std::size_t read = 0; read < reads; ++read) { + const auto count = channel::SocketRead{}(peer.socket.value, bytes, sizeof bytes); + if (count == 0 || (count < 0 && !channel::retryableSocketError(channel::socketError()))) + return false; + if (count < 0) + return true; + if (!peer.refused && feed(peer, std::string_view(bytes, static_cast(count)))) { + if (connections.size() >= maxConnections) + refuse(peer, refusal(503, "The MCP listener is busy")); + else { + dispatch(connections, peer); + return false; + } + } + } + return true; + } // Reads, without waiting, what a peer about to be closed has already sent. static void discard(Pending& peer) noexcept { char bytes[4096]; diff --git a/test/driver/WfDriver.hpp b/test/driver/WfDriver.hpp index 18f91d51..d0fb7aca 100644 --- a/test/driver/WfDriver.hpp +++ b/test/driver/WfDriver.hpp @@ -50,10 +50,12 @@ namespace webfront::testdriver { struct DriverWebView2Options { static frontend::WebView2Options get() { #ifdef _MSC_VER - char* raw = nullptr; - std::size_t length = 0; - const auto status = _dupenv_s(&raw, &length, "WEBFRONT_TEST_WEBVIEW2_PROFILE"); - const std::unique_ptr profile(raw, std::free); + // Read in UTF-16: a profile under a temporary directory may hold characters that the ANSI code page cannot + // represent, which the narrow environment would turn into '?' (#720). + wchar_t* raw = nullptr; + std::size_t length = 0; + const auto status = _wdupenv_s(&raw, &length, L"WEBFRONT_TEST_WEBVIEW2_PROFILE"); + const std::unique_ptr profile(raw, std::free); if (status != 0) throw std::runtime_error("Cannot read the WebView2 test profile"); return get(profile.get()); @@ -62,6 +64,15 @@ struct DriverWebView2Options { #endif } static frontend::WebView2Options get(const char* profile) { + return withProfile(profile); + } + static frontend::WebView2Options get(const wchar_t* profile) { + return withProfile(profile); + } + +private: + template + static frontend::WebView2Options withProfile(const Character* profile) { frontend::WebView2Options options; options.visible = visibleWindows; if (profile && *profile) diff --git a/test/unit/WfDriverTests.cpp b/test/unit/WfDriverTests.cpp index 3f284b93..dfe45ccb 100644 --- a/test/unit/WfDriverTests.cpp +++ b/test/unit/WfDriverTests.cpp @@ -120,8 +120,24 @@ const Scenario driverWebView2{ const auto second = testdriver::DriverWebView2Options::get("second-session"); require(first.userDataFolder == std::filesystem::path("first-session")); require(second.userDataFolder != first.userDataFolder); - require(testdriver::DriverWebView2Options::get(nullptr).userDataFolder.empty()); + require(testdriver::DriverWebView2Options::get(static_cast(nullptr)).userDataFolder.empty()); require(testdriver::DriverWebView2Options::get("").userDataFolder.empty()); + // #720: the automation client's profiles live under a directory whose name holds characters outside the ANSI + // code page on Windows; the profile read from the environment keeps them. + const std::filesystem::path unicode{u8"wf-profile- &%!^ \u96ea /webview2"}; +#ifdef _WIN32 + require(_wputenv_s(L"WEBFRONT_TEST_WEBVIEW2_PROFILE", unicode.c_str()) == 0); +#else + require(::setenv("WEBFRONT_TEST_WEBVIEW2_PROFILE", unicode.c_str(), 1) == 0); +#endif + const auto read = testdriver::DriverWebView2Options::get().userDataFolder; +#ifdef _WIN32 + (void)_wputenv_s(L"WEBFRONT_TEST_WEBVIEW2_PROFILE", L""); +#else + (void)::unsetenv("WEBFRONT_TEST_WEBVIEW2_PROFILE"); +#endif + require(read == unicode); + require(testdriver::DriverWebView2Options::get(L"profile").userDataFolder == std::filesystem::path(L"profile")); }}; const Scenario singleCommand{"A single-command watchdog has a separate budget after bootstrap", [] { From f36e2d0e26f11e054c554d4a71c6621f50a594a7 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:00:48 +0100 Subject: [PATCH 3/4] Leave a cold WebView2 profile time to load the developer page (#720) Each automation_host now starts its own WebView2 browser process on a new profile. On the loaded Windows runner its first page can take far longer than the shared, warm browser process did: in the PR run, AutomationMcpWatchdog's last host reached its 30-second startup deadline before loading the page (71 instead of 70), and AutomationConsumerWindow's hosts were not ready within the client's 30 seconds. The client waits up to 90 seconds for a session to become ready (operations keep their own timeout), and the hosts of the scenarios get the application's default 90-second startup deadline. No case expects that deadline to expire. --- test/tools/AutomationClient.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 8ea1ff16..7761469f 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -25,8 +25,11 @@ class Client: """MCP over the Streamable HTTP listener of an application, from its private mcp.json.""" - def __init__(self, configuration, timeout=30): - self.timeout = timeout # seconds for the session to become ready and for one operation to finish + def __init__(self, configuration, timeout=30, startup=90): + self.timeout = timeout # seconds for one operation to finish + # Seconds for the session to become ready. Each launch starts its own WebView2 browser process on a new profile + # (host_environment): on a loaded Windows runner its first page takes far longer than a warm one (#720). + self.startup = max(startup, timeout) server = json.loads(pathlib.Path(configuration).read_text())["mcpServers"]["webfront"] assert server["type"] == "http", server self.url = urllib.parse.urlsplit(server["url"]) @@ -87,7 +90,7 @@ def initialize(self, tools=4): assert "webfront.session" in result["instructions"], result self.send("notifications/initialized", notification=True) assert len(self.send("tools/list")["tools"]) == tools - end = time.monotonic() + self.timeout + end = time.monotonic() + self.startup while time.monotonic() < end: state = self.tool("session") if state["state"] == "ready": @@ -321,7 +324,8 @@ def watchdog(args): project = root / "project" shutil.copytree(args.fixture, project) directory = root / "forced-window" - options = ["--directory", str(directory), "--grants", "build", "--timeout", "2", "--startup-timeout", "30"] + # The startup deadline leaves a cold browser profile time to load the page (#720); no case here expects it to expire. + options = ["--directory", str(directory), "--grants", "build", "--timeout", "2", "--startup-timeout", "90"] # An operation that never completes in a renderer that stays responsive: the deadline revokes the session, the # page runs the request to close, show() returns and the host reports the deadline with 71, before any grace (#709). environment, integrity = operation_archive(args, root, "waiting", @@ -374,7 +378,7 @@ def watchdog(args): with (pathlib.Path(args.work) / "watchdog-failed.log").open("w", encoding="utf-8") as log: host = Host(args, project, root, "failed", log, options, str(failed_environment), failed_integrity) try: - assert host.wait(timeout=45) == 70, host.logs() + assert host.wait(timeout=120) == 70, host.logs() finally: host.close() assert "Automation startup: B" + "é" * 511 + "\n" in host.logs(), host.logs() @@ -585,7 +589,7 @@ def session(args): setup.mkdir() with (root / "setup.log").open("w") as log: host = Host(args, setup, root, "setup", log, - ["--grants", "init,create,install,restore,embed,packages,state", "--timeout", "60", "--startup-timeout", "60"]) + ["--grants", "init,create,install,restore,embed,packages,state", "--timeout", "60", "--startup-timeout", "90"]) try: client = host.client(timeout=60) client.initialize(tools=14) # the four tools of the session and the ten reads of the state From fc754089e25ccdc9126c016130ef7f1638ba2162 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:03:37 +0100 Subject: [PATCH 4/4] MCP listener: serve the requests completed within the closing grace when its thread runs late (#720) The pending peers left when the grace ends were discarded at once. A last pass without waiting now feeds each one what it already sent and dispatches a complete request, as the per-peer deadline already does. --- include/webfront/automation/McpHttp.hpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/include/webfront/automation/McpHttp.hpp b/include/webfront/automation/McpHttp.hpp index d4a5bcfb..1f000314 100644 --- a/include/webfront/automation/McpHttp.hpp +++ b/include/webfront/automation/McpHttp.hpp @@ -607,8 +607,10 @@ class Server { const auto closing = std::chrono::steady_clock::now() + closingGrace; while (!pending.empty() && std::chrono::steady_clock::now() < closing) step(connections, pending, false, closing); + // A last pass without waiting: a request completed within the grace is served even if this thread ran late. for (auto& peer : pending) - discard(peer); + if (receive(connections, peer, wholeRequestReads)) + discard(peer); } // One round: reads the readable peers, dispatches their complete requests and, while `accepting`, takes a batch of // connections. A peer is closed at its deadline or at `limit`, after what it sent has been read: bytes left unread