From c2cf7eb1aed38877bbb82f27875a175094d6da50 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:36:20 +0100 Subject: [PATCH 1/5] Stabilise desktop-native automation tests [#416] Retry the WebView2 profile removal for up to 10 s, wait for it in the automation tests, report the observed state in failures and give NativeAutodetectReconfiguration a 180 s timeout. --- docs/CHANGELOG.md | 5 +++++ js/developer/tools/WebFrontAgent.cpp | 2 +- test/tools/AutomationClient.py | 14 +++++++++----- test/unit/CMakeLists.txt | 2 +- 4 files changed, 16 insertions(+), 7 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index ea173bc5..cb0de666 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- Stabilise the desktop-native tier (#416): the automation owner retries removing its temporary + WebView2 profile for up to 10 s (was 2 s) while the browser process exits, the automation tests wait + for that cleanup instead of assuming it is immediate, their failure messages report the observed run + state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. + - Add awaitable DOM events (#384): `co_await node.next(name, options)` completes with the value of the element's next event, for sequential dialogs and wizards. Starting the sender subscribes with the flags declared then; the event unsubscribes. It completes stopped through the task's stop token, diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index 641f8185..a3494875 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -53,7 +53,7 @@ struct Profile { // WebView2 closes its browser process asynchronously after the controller is released. // Retry only sharing violations during that short exit; POSIX can unlink open files. #ifdef _WIN32 - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2}; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{10}; #endif for (;;) { std::error_code error; diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index e5fa87ff..acda553b 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -268,7 +268,7 @@ def watchdog(args): else: cli = subprocess.run([args.agent, *command, "--listen", str(endpoint), "--operation", "build"], stdout=subprocess.PIPE, stderr=log, text=True, timeout=45) - assert cli.returncode == 71, cli.stdout + pathlib.Path(log.name).read_text() + assert cli.returncode == 71, (cli.returncode, cli.stdout, pathlib.Path(log.name).read_text()) assert (project / "renderer.started").is_file(), "The deadline expired before the renderer actually blocked" assert not endpoint.exists(), "The forced exit left its attachment capability behind" if args.scenario == "cli-watchdog": @@ -374,7 +374,8 @@ def main(): break time.sleep(0.02) client.tool("cancel", {"session": client.session, "runId": run}) - assert client.wait(run)["state"] == "cancelled" + cancelled = client.wait(run) + assert cancelled["state"] == "cancelled", cancelled client.run("test", {"pattern": "passes"}) finally: client.close() @@ -423,7 +424,8 @@ def main(): run = first.start("test", {"pattern": "waits for cancellation"}) second.tool("start", {"session": second.session, "operation": "build"}, error=True) second.tool("cancel", {"session": second.session, "runId": run}) - assert first.wait(run)["state"] == "cancelled" + cancelled = first.wait(run) + assert cancelled["state"] == "cancelled", cancelled finally: first.close() second.close() @@ -441,8 +443,10 @@ def main(): shutdown = subprocess.run([args.agent, "--attach", str(endpoint), "--shutdown"], capture_output=True, text=True, timeout=10) assert shutdown.returncode == 0, shutdown.stderr - assert owner.wait(timeout=10) == 0 - assert not list(profiles.glob("webfront-agent-*")), "The owner left its native profile behind" + # The owner retries removing the WebView2 profile for up to 10 s after the browser exits. + assert owner.wait(timeout=30) == 0, pathlib.Path(log.name).read_text() + left = list(profiles.glob("webfront-agent-*")) + assert not left, ("The owner left its native profile behind", left, pathlib.Path(log.name).read_text()) assert not endpoint.exists(), "The owner left its attachment capability behind" unavailable = subprocess.run([args.agent, "--attach", str(endpoint), "--operation", "build"], capture_output=True, text=True, timeout=5) diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 9e35ce6d..7822d230 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -203,7 +203,7 @@ add_test(NAME NativeAutodetectReconfiguration COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/native-autodetect -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckNativeAutodetect.cmake) -set_tests_properties(NativeAutodetectReconfiguration PROPERTIES TIMEOUT 60) +set_tests_properties(NativeAutodetectReconfiguration PROPERTIES TIMEOUT 180) # Exercise configuration-dependent CTest discovery and generator switches on single-config CI hosts. # The fixture configures no compiler and builds nothing; Ninja is optional for contributor builds. find_program(WEBFRONT_TEST_NINJA_EXECUTABLE ninja) From 06d0365a487c104c5db25fd01366a3a3ff48afdf Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:57:41 +0100 Subject: [PATCH 2/5] Bound the profile cleanup after a forced exit [#416] The 10 s retry added to the normal exit also applied after the 5 s shutdown deadline, so a forced exit outlasted the watchdog tests' wait. Only the normal exit keeps the long patience; a forced one retries 1 s. --- docs/CHANGELOG.md | 2 +- js/developer/tools/WebFrontAgent.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index cb0de666..a04399f8 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,7 +3,7 @@ ## Unreleased - Stabilise the desktop-native tier (#416): the automation owner retries removing its temporary - WebView2 profile for up to 10 s (was 2 s) while the browser process exits, the automation tests wait + WebView2 profile for up to 10 s (was 2 s; 1 s after a forced exit) while the browser process exits, the automation tests wait for that cleanup instead of assuming it is immediate, their failure messages report the observed run state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index a3494875..d019e337 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -49,11 +49,11 @@ struct Files { struct Profile { channel::PrivateDirectory directory{std::filesystem::temp_directory_path() / ("webfront-agent-" + channel::nonce())}; const std::filesystem::path path{directory.path}; - void cleanup() const noexcept { + void cleanup(std::chrono::seconds patience = std::chrono::seconds{10}) const noexcept { // WebView2 closes its browser process asynchronously after the controller is released. // Retry only sharing violations during that short exit; POSIX can unlink open files. #ifdef _WIN32 - const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{10}; + const auto deadline = std::chrono::steady_clock::now() + patience; #endif for (;;) { std::error_code error; @@ -384,7 +384,7 @@ int main(int argc, char** argv) { const int code = status.load() ? status.load() : finished.load() ? 0 : 72; if (channel) channel->stop(); - profile.cleanup(); // _Exit skips the destructors + profile.cleanup(std::chrono::seconds{1}); // _Exit skips the destructors; the deadline is already spent std::_Exit(code); } return; From 55f1340b672267fbf6af0ce5f3a038b4f81871e3 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 11:51:05 +0100 Subject: [PATCH 3/5] Apply the review of the profile cleanup [#416] Retry the profile removal for 10 s also after a forced exit, limit a refused access to 2 s, poll for the profile in the owner shutdown test and report the failure details as readable messages. --- docs/CHANGELOG.md | 4 ++-- js/developer/tools/WebFrontAgent.cpp | 15 ++++++++++----- test/tools/AutomationClient.py | 17 ++++++++++------- test/unit/CMakeLists.txt | 1 + 4 files changed, 23 insertions(+), 14 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a04399f8..894f1c6c 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,8 +3,8 @@ ## Unreleased - Stabilise the desktop-native tier (#416): the automation owner retries removing its temporary - WebView2 profile for up to 10 s (was 2 s; 1 s after a forced exit) while the browser process exits, the automation tests wait - for that cleanup instead of assuming it is immediate, their failure messages report the observed run + WebView2 profile for up to 10 s (was 2 s, also after a forced exit; a refused access is retried for 2 s only) while the + browser process exits, the automation tests poll for that cleanup instead of assuming it is immediate, their failure messages report the observed run state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. - Add awaitable DOM events (#384): `co_await node.next(name, options)` completes with the value of diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index d019e337..169f98b6 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -49,11 +49,15 @@ struct Files { struct Profile { channel::PrivateDirectory directory{std::filesystem::temp_directory_path() / ("webfront-agent-" + channel::nonce())}; const std::filesystem::path path{directory.path}; - void cleanup(std::chrono::seconds patience = std::chrono::seconds{10}) const noexcept { + void cleanup() const noexcept { // WebView2 closes its browser process asynchronously after the controller is released. // Retry only sharing violations during that short exit; POSIX can unlink open files. + // A refused access is rarely transient: it gets a shorter patience so that a profile which can never be + // removed does not delay the exit for the whole window. #ifdef _WIN32 - const auto deadline = std::chrono::steady_clock::now() + patience; + const auto start = std::chrono::steady_clock::now(); + const auto deadline = start + std::chrono::seconds{10}; + const auto accessDeadline = start + std::chrono::seconds{2}; #endif for (;;) { std::error_code error; @@ -61,8 +65,9 @@ struct Profile { if (!error) return; #ifdef _WIN32 - if ((error.value() == ERROR_SHARING_VIOLATION || error.value() == ERROR_ACCESS_DENIED || error.value() == ERROR_DIR_NOT_EMPTY) - && std::chrono::steady_clock::now() < deadline) { + const auto now = std::chrono::steady_clock::now(); + if (((error.value() == ERROR_SHARING_VIOLATION || error.value() == ERROR_DIR_NOT_EMPTY) && now < deadline) + || (error.value() == ERROR_ACCESS_DENIED && now < accessDeadline)) { std::this_thread::sleep_for(std::chrono::milliseconds{20}); continue; } @@ -384,7 +389,7 @@ int main(int argc, char** argv) { const int code = status.load() ? status.load() : finished.load() ? 0 : 72; if (channel) channel->stop(); - profile.cleanup(std::chrono::seconds{1}); // _Exit skips the destructors; the deadline is already spent + profile.cleanup(); // _Exit skips the destructors std::_Exit(code); } return; diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index acda553b..474ef332 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -268,7 +268,7 @@ def watchdog(args): else: cli = subprocess.run([args.agent, *command, "--listen", str(endpoint), "--operation", "build"], stdout=subprocess.PIPE, stderr=log, text=True, timeout=45) - assert cli.returncode == 71, (cli.returncode, cli.stdout, pathlib.Path(log.name).read_text()) + assert cli.returncode == 71, f"exit {cli.returncode}\n{cli.stdout}\n{pathlib.Path(log.name).read_text()}" assert (project / "renderer.started").is_file(), "The deadline expired before the renderer actually blocked" assert not endpoint.exists(), "The forced exit left its attachment capability behind" if args.scenario == "cli-watchdog": @@ -375,7 +375,7 @@ def main(): time.sleep(0.02) client.tool("cancel", {"session": client.session, "runId": run}) cancelled = client.wait(run) - assert cancelled["state"] == "cancelled", cancelled + assert cancelled["state"] == "cancelled", f"Unexpected run state: {cancelled}" client.run("test", {"pattern": "passes"}) finally: client.close() @@ -425,7 +425,7 @@ def main(): second.tool("start", {"session": second.session, "operation": "build"}, error=True) second.tool("cancel", {"session": second.session, "runId": run}) cancelled = first.wait(run) - assert cancelled["state"] == "cancelled", cancelled + assert cancelled["state"] == "cancelled", f"Unexpected run state: {cancelled}" finally: first.close() second.close() @@ -435,18 +435,21 @@ def main(): assert cli.returncode == 0 and json.loads(cli.stdout)["state"] == "succeeded", cli.stdout + cli.stderr assert list(profiles.glob("webfront-agent-*")), "The test must observe the actual native profile" if os.name == "posix": - assert owner.poll() is None, ("Owner exited before SIGTERM", owner.returncode, pathlib.Path(log.name).read_text()) + assert owner.poll() is None, f"Owner exited before SIGTERM: {owner.returncode}\n{pathlib.Path(log.name).read_text()}" owner.send_signal(signal.SIGTERM) status = owner.wait(timeout=15) - assert status == 128 + signal.SIGTERM, (status, pathlib.Path(log.name).read_text()) + assert status == 128 + signal.SIGTERM, f"exit {status}\n{pathlib.Path(log.name).read_text()}" else: shutdown = subprocess.run([args.agent, "--attach", str(endpoint), "--shutdown"], capture_output=True, text=True, timeout=10) assert shutdown.returncode == 0, shutdown.stderr # The owner retries removing the WebView2 profile for up to 10 s after the browser exits. assert owner.wait(timeout=30) == 0, pathlib.Path(log.name).read_text() - left = list(profiles.glob("webfront-agent-*")) - assert not left, ("The owner left its native profile behind", left, pathlib.Path(log.name).read_text()) + # The browser process may outlive the owner by a moment: poll instead of reading the directory once. + profile_deadline = time.monotonic() + 10 + while (left := list(profiles.glob("webfront-agent-*"))) and time.monotonic() < profile_deadline: + time.sleep(0.1) + assert not left, f"The owner left its native profile behind: {left}\n{pathlib.Path(log.name).read_text()}" assert not endpoint.exists(), "The owner left its attachment capability behind" unavailable = subprocess.run([args.agent, "--attach", str(endpoint), "--operation", "build"], capture_output=True, text=True, timeout=5) diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 7822d230..d02fd04e 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -203,6 +203,7 @@ add_test(NAME NativeAutodetectReconfiguration COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/native-autodetect -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckNativeAutodetect.cmake) +# The test takes about 5 s; the wide bound only absorbs a loaded runner (one unexplained stall at 60 s, #416). set_tests_properties(NativeAutodetectReconfiguration PROPERTIES TIMEOUT 180) # Exercise configuration-dependent CTest discovery and generator switches on single-config CI hosts. # The fixture configures no compiler and builds nothing; Ninja is optional for contributor builds. From 187e63830b791b7cfac186794563b9142356e505 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 13:20:43 +0100 Subject: [PATCH 4/5] Mark the cleanup patience as unused outside Windows [#416] --- js/developer/tools/WebFrontAgent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index 42c90f6e..71d9d9f7 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -49,7 +49,7 @@ struct Files { struct Profile { channel::PrivateDirectory directory{std::filesystem::temp_directory_path() / ("webfront-agent-" + channel::nonce())}; const std::filesystem::path path{directory.path}; - void cleanup(std::chrono::seconds patience = std::chrono::seconds{10}) const noexcept { + void cleanup([[maybe_unused]] std::chrono::seconds patience = std::chrono::seconds{10}) const noexcept { // WebView2 closes its browser process asynchronously after the controller is released. // Retry only sharing violations during that short exit; POSIX can unlink open files. // A refused access is rarely transient: it gets a shorter patience so that a profile which can never be From 20e63a843ce6b9aa25af395978e493492b0d88fb Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Fri, 30 Oct 2026 13:38:14 +0100 Subject: [PATCH 5/5] End the WebView2 browser before removing the agent profile [#416] Retrying the removal could not outlast the browser process that keeps the profile open, notably after a forced exit. The agent now waits up to 5 s for the WebView2 processes it launched, ends those still running (at once after a forced exit), then retries files pending deletion for 2 s. A forced exit keeps the status of an exit that completes meanwhile. The watchdog tests check that a forced exit removes the profile and report the exit status and log; the window test reads the profile once the owner exited. --- docs/CHANGELOG.md | 9 ++- js/developer/tools/WebFrontAgent.cpp | 110 +++++++++++++++++++++++---- test/tools/AutomationClient.py | 28 ++++--- 3 files changed, 118 insertions(+), 29 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 800cb414..714fb022 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,10 +2,11 @@ ## Unreleased -- Stabilise the desktop-native tier (#416): the automation owner retries removing its temporary - WebView2 profile for up to 10 s (was 2 s; 5 s after a forced exit; a refused access is retried for 2 s only) while the - browser process exits, the automation tests poll for that cleanup instead of assuming it is immediate, their failure messages report the observed run - state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. +- Stabilise the desktop-native tier (#416): before removing its temporary WebView2 profile, the automation owner + waits up to 5 s for the browser processes it launched to exit and ends those still running (at once after a forced + exit, which also keeps the status of an exit that completes meanwhile), then retries files pending deletion for 2 s. + The watchdog tests check that a forced exit removes the profile, the automation failure messages report the observed + run state, exit status and owner log, and `NativeAutodetectReconfiguration` has a 180 s timeout. - Show the `wf` commands of the developer browser test in its window (#415): `DeveloperBrowserIntegration` shows, in place of its terminal, each command it runs with its outcome and duration, labelling the timeouts and cancellations diff --git a/js/developer/tools/WebFrontAgent.cpp b/js/developer/tools/WebFrontAgent.cpp index 71d9d9f7..987b66c7 100644 --- a/js/developer/tools/WebFrontAgent.cpp +++ b/js/developer/tools/WebFrontAgent.cpp @@ -9,10 +9,20 @@ #include #include +#include + +#include #include +#include #include +#include #include -#ifndef _WIN32 +#include +#include +#include +#ifdef _WIN32 +#include +#else #include #endif @@ -46,18 +56,85 @@ struct Files { } }; +#ifdef _WIN32 +using ProcessHandle = std::unique_ptr; + +std::uint64_t creationTime(HANDLE process) noexcept { + FILETIME created{}, exited{}, kernel{}, user{}; + if (!GetProcessTimes(process, &created, &exited, &kernel, &user)) + return 0; + return (std::uint64_t{created.dwHighDateTime} << 32) | created.dwLowDateTime; +} + +// The WebView2 browser processes this agent launched, then their descendants. A process created before its recorded +// parent belongs to an unrelated process that reused the parent's identifier. +std::vector webViewProcesses() { + std::vector result; + const HANDLE raw = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if (raw == INVALID_HANDLE_VALUE) + return result; + const ProcessHandle snapshot{raw, CloseHandle}; + std::vector entries; + PROCESSENTRY32W entry{.dwSize = sizeof(PROCESSENTRY32W)}; + for (bool more = Process32FirstW(raw, &entry); more; more = Process32NextW(raw, &entry)) + entries.push_back(entry); + struct Parent { + DWORD id; + std::uint64_t created; + }; + std::vector parents{{GetCurrentProcessId(), creationTime(GetCurrentProcess())}}; + for (std::size_t next = 0; next < parents.size(); ++next) { + for (const auto& candidate : entries) { + if (candidate.th32ParentProcessID != parents[next].id) + continue; + if (next == 0 && CompareStringOrdinal(candidate.szExeFile, -1, L"msedgewebview2.exe", -1, TRUE) != CSTR_EQUAL) + continue; + ProcessHandle process{OpenProcess(PROCESS_TERMINATE | SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, candidate.th32ProcessID), + CloseHandle}; + if (!process) + continue; + const auto created = creationTime(process.get()); + if (created < parents[next].created) + continue; + parents.push_back({candidate.th32ProcessID, created}); + result.push_back(std::move(process)); + } + } + return result; +} + +// WebView2 closes its browser process asynchronously after the controller is released, and that process keeps the +// profile open until it exits. Retrying the removal cannot outlast it: let it exit during the grace, then end it. +void releaseWebView(std::chrono::milliseconds grace) noexcept { + try { + const auto processes = webViewProcesses(); + const auto remaining = [](std::chrono::steady_clock::time_point deadline) { + const auto left = std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()); + return static_cast(std::max(left.count(), 0)); + }; + const auto exited = std::chrono::steady_clock::now() + grace; + for (const auto& process : processes) + if (WaitForSingleObject(process.get(), remaining(exited)) != WAIT_OBJECT_0) + TerminateProcess(process.get(), 1); + const auto terminated = std::chrono::steady_clock::now() + std::chrono::seconds{2}; + for (const auto& process : processes) + WaitForSingleObject(process.get(), remaining(terminated)); + } catch (...) { + // Without the process list, the removal below still retries the transient errors. + } +} +#endif + struct Profile { channel::PrivateDirectory directory{std::filesystem::temp_directory_path() / ("webfront-agent-" + channel::nonce())}; const std::filesystem::path path{directory.path}; - void cleanup([[maybe_unused]] std::chrono::seconds patience = std::chrono::seconds{10}) const noexcept { - // WebView2 closes its browser process asynchronously after the controller is released. - // Retry only sharing violations during that short exit; POSIX can unlink open files. - // A refused access is rarely transient: it gets a shorter patience so that a profile which can never be - // removed does not delay the exit for the whole window. + /// @param grace how long the WebView2 browser may take to exit on its own before it is ended (Windows only) + void cleanup([[maybe_unused]] std::chrono::milliseconds grace) const noexcept { + // POSIX can unlink open files. On Windows, the files of a process that has just exited can stay pending + // deletion for a moment, which reports a sharing violation, a refused access or a non-empty directory. #ifdef _WIN32 - const auto start = std::chrono::steady_clock::now(); - const auto deadline = start + patience; - const auto accessDeadline = start + std::min(patience, std::chrono::seconds{2}); + releaseWebView(grace); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2}; #endif for (;;) { std::error_code error; @@ -65,9 +142,8 @@ struct Profile { if (!error) return; #ifdef _WIN32 - const auto now = std::chrono::steady_clock::now(); - if (((error.value() == ERROR_SHARING_VIOLATION || error.value() == ERROR_DIR_NOT_EMPTY) && now < deadline) - || (error.value() == ERROR_ACCESS_DENIED && now < accessDeadline)) { + if ((error.value() == ERROR_SHARING_VIOLATION || error.value() == ERROR_ACCESS_DENIED || error.value() == ERROR_DIR_NOT_EMPTY) + && std::chrono::steady_clock::now() < deadline) { std::this_thread::sleep_for(std::chrono::milliseconds{20}); continue; } @@ -77,7 +153,7 @@ struct Profile { } } ~Profile() { - cleanup(); + cleanup(std::chrono::seconds{5}); } }; @@ -389,8 +465,12 @@ int main(int argc, char** argv) { const int code = status.load() ? status.load() : finished.load() ? 0 : 72; if (channel) channel->stop(); - profile.cleanup(std::chrono::seconds{5}); // _Exit skips the destructors; the watchdog tests allow for this bound - std::_Exit(code); + // _Exit skips the destructors. The browser already had the close grace above: end it now. + profile.cleanup(std::chrono::milliseconds{0}); + // Ending the browser can release a blocked main thread: an exit completed meanwhile keeps its + // own status and destructors. + if (!done.load()) + std::_Exit(code); } return; } diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index c8933e87..f3c807b2 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -19,11 +19,11 @@ class Client: - def __init__(self, command, stderr, timeout=30): + def __init__(self, command, stderr, timeout=30, env=None): self.timeout = timeout # seconds for the session to become ready and for one operation to finish self.log_path = pathlib.Path(stderr.name) if isinstance(getattr(stderr, "name", None), str) else None self.child = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=stderr, text=True, encoding="utf-8") + stderr=stderr, text=True, encoding="utf-8", env=env) self.messages = queue.Queue() self.counter = 0 def read(): @@ -255,22 +255,32 @@ def watchdog(args): "--integrity", "sha512-" + base64.b64encode(hashlib.sha512(environment.read_bytes()).digest()).decode(), "--registry-dir", args.registry, "--startup-timeout", "30", "--timeout", "2", "--allow", "build"] endpoint = root / "forced-window" + # A private temporary directory isolates the native profile, which the forced exit must still remove. + profiles = root / "profiles" + profiles.mkdir() + forced_environment = dict(os.environ, TMPDIR=str(profiles), TEMP=str(profiles), TMP=str(profiles)) with (pathlib.Path(args.work) / "watchdog.log").open("w") as log: if args.scenario == "mcp-watchdog": - client = Client([args.agent, *command, "--mcp", "--listen", str(endpoint)], log) + client = Client([args.agent, *command, "--mcp", "--listen", str(endpoint)], log, env=forced_environment) try: client.initialize() client.start("build") - assert client.child.wait(timeout=30) == 71 + try: + status = client.child.wait(timeout=30) + except subprocess.TimeoutExpired: + raise AssertionError(f"The forced exit did not happen\n{pathlib.Path(log.name).read_text()}") from None + assert status == 71, f"exit {status}\n{pathlib.Path(log.name).read_text()}" assert isinstance(client.messages.get(timeout=2), EOFError), "A renderer retained MCP stdout" finally: client.close() else: cli = subprocess.run([args.agent, *command, "--listen", str(endpoint), "--operation", "build"], - stdout=subprocess.PIPE, stderr=log, text=True, timeout=45) + stdout=subprocess.PIPE, stderr=log, text=True, timeout=45, env=forced_environment) assert cli.returncode == 71, f"exit {cli.returncode}\n{cli.stdout}\n{pathlib.Path(log.name).read_text()}" assert (project / "renderer.started").is_file(), "The deadline expired before the renderer actually blocked" assert not endpoint.exists(), "The forced exit left its attachment capability behind" + left = list(profiles.glob("webfront-agent-*")) + assert not left, f"The forced exit left its native profile behind: {left}\n{pathlib.Path(log.name).read_text()}" if args.scenario == "cli-watchdog": # This same-path relaunch must reach its authenticated page before the intentional error. # It checks directory reuse and Unicode failure reporting in one process; normal builds @@ -443,12 +453,10 @@ def main(): shutdown = subprocess.run([args.agent, "--attach", str(endpoint), "--shutdown"], capture_output=True, text=True, timeout=10) assert shutdown.returncode == 0, shutdown.stderr - # The owner retries removing the WebView2 profile for up to 10 s after the browser exits. + # Before it exits, the owner waits up to 5 s for the WebView2 browser, ends it, then removes the profile. assert owner.wait(timeout=30) == 0, pathlib.Path(log.name).read_text() - # The browser process may outlive the owner by a moment: poll instead of reading the directory once. - profile_deadline = time.monotonic() + 10 - while (left := list(profiles.glob("webfront-agent-*"))) and time.monotonic() < profile_deadline: - time.sleep(0.1) + # Only the owner removes the profile: once it has exited, the directory no longer changes. + left = list(profiles.glob("webfront-agent-*")) assert not left, f"The owner left its native profile behind: {left}\n{pathlib.Path(log.name).read_text()}" assert not endpoint.exists(), "The owner left its attachment capability behind" unavailable = subprocess.run([args.agent, "--attach", str(endpoint), "--operation", "build"],