Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

## Unreleased

- 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
the specs cause. The trace comes from the specs only; the published environment is unchanged. `docs/TEST_TIERS.md`
Expand Down
99 changes: 92 additions & 7 deletions js/developer/tools/WebFrontAgent.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,20 @@
#include <webfront/automation/Stdio.hpp>
#include <webfront/DeveloperApp.hpp>

#include <webfront/automation/Platform.hpp>

#include <algorithm>
#include <atomic>
#include <chrono>
#include <csignal>
#include <cstdint>
#include <iostream>
#ifndef _WIN32
#include <memory>
#include <thread>
#include <vector>
#ifdef _WIN32
#include <tlhelp32.h>
#else
#include <fcntl.h>
#endif

Expand Down Expand Up @@ -46,13 +56,84 @@ struct Files {
}
};

#ifdef _WIN32
using ProcessHandle = std::unique_ptr<void, decltype(&CloseHandle)>;

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<ProcessHandle> webViewProcesses() {
std::vector<ProcessHandle> result;
const HANDLE raw = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (raw == INVALID_HANDLE_VALUE)
return result;
const ProcessHandle snapshot{raw, CloseHandle};
std::vector<PROCESSENTRY32W> 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<Parent> 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<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now());
return static_cast<DWORD>(std::max<std::chrono::milliseconds::rep>(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() 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.
/// @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
releaseWebView(grace);
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2};
#endif
for (;;) {
Expand All @@ -72,7 +153,7 @@ struct Profile {
}
}
~Profile() {
cleanup();
cleanup(std::chrono::seconds{5});
}
};

Expand Down Expand Up @@ -384,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(); // _Exit skips the destructors
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;
}
Expand Down
39 changes: 27 additions & 12 deletions test/tools/AutomationClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down Expand Up @@ -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=15) == 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)
assert cli.returncode == 71, cli.stdout + pathlib.Path(log.name).read_text()
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
Expand Down Expand Up @@ -374,7 +384,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", f"Unexpected run state: {cancelled}"
client.run("test", {"pattern": "passes"})
finally:
client.close()
Expand Down Expand Up @@ -423,7 +434,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", f"Unexpected run state: {cancelled}"
finally:
first.close()
second.close()
Expand All @@ -433,16 +445,19 @@ 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
assert owner.wait(timeout=10) == 0
assert not list(profiles.glob("webfront-agent-*")), "The owner left its native profile behind"
# 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()
# 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"],
capture_output=True, text=True, timeout=5)
Expand Down
3 changes: 2 additions & 1 deletion test/unit/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,8 @@ 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)
# 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.
find_program(WEBFRONT_TEST_NINJA_EXECUTABLE ninja)
Expand Down
Loading