From 9e011d61ad7e5a78abe5d09fef287f14c73edfce Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:44:11 +0100 Subject: [PATCH] Automation: the session names the deadline that revoked it, so the host exits with 71 (#709) Session::expire and expireStartup close the session with their own reason, which the supervisor's later close could not replace: automation_host compared the failure with a reason no deadline ever wrote, and a window that closed after the deadline exited with 0. The session now records which deadline revoked it (revokedBy(), and revocation in webfront.session), the host reads that state, and AutomationMcpWatchdog first runs an operation that never completes in a responsive renderer, whose window closes after the deadline: status 71, deterministically. --- docs/AUTOMATION.md | 7 +- docs/CHANGELOG.md | 1 + include/webfront/automation/Enable.hpp | 5 +- include/webfront/automation/Session.hpp | 25 +++++-- test/tools/AutomationClient.py | 94 ++++++++++++++++--------- test/unit/AutomationTests.cpp | 13 ++++ test/web/AutomationHost.cpp | 10 ++- 7 files changed, 108 insertions(+), 47 deletions(-) diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 5adbccbb..6c93cd5a 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -200,7 +200,7 @@ Tool results include both `structuredContent` and its JSON spelling as text. | Tool | Arguments | Result | | --- | --- | --- | -| `webfront.session` | `{}` | API version, session ID, canonical project, state, native grants, failure reason and bounded audit metadata. | +| `webfront.session` | `{}` | API version, session ID, canonical project, state, native grants, failure reason, the native deadline that revoked the session (`revocation`: `operation-deadline`, `startup-deadline`, or empty) and bounded audit metadata. | | `webfront.start` | `{session, operation, arguments?}` | A new run ID and initial state, returned immediately. | | `webfront.result` | `{session, runId}` | Run state, bounded streamed output and final result. | | `webfront.cancel` | `{session, runId}` | Cooperative cancellation request and current state. | @@ -381,8 +381,9 @@ Python's standard library HTTP client: - `AutomationMcpWindow`: structured errors, file correction, check/build/test, preview inspection and actions, cross-frame rejection, a second client sharing the session and cancelling the first one's run, a project set up from nothing (`create`, `init`, `install`, `restore`, `embed`), and the withdrawal of the listener, record and directory when the window closes. -- `AutomationMcpWatchdog`: a real renderer blocked inside a test-archive operation body, without loading Jasmine to provoke - the hang. It exercises the production signed callback and runner, the native two-second deadline, the five-second close +- `AutomationMcpWatchdog`: first an operation that never completes in a responsive renderer, whose window closes after the + deadline revoked the session (status 71, the deadline named by `revocation`); then a real renderer blocked inside a + test-archive operation body, without loading Jasmine to provoke the hang. It exercises the production signed callback and runner, the native two-second deadline, the five-second close grace and the withdrawal of the listener, record and directory; a relaunch on the same directory then checks its reuse and Unicode failure reporting. It delays bootstrap by three seconds to verify that the operation deadline starts after startup. - `AutomationConsumerWindow`: two applications side by side, each driven through its own URL: refusals of web pages, diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index b4d0162a..81029161 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -51,6 +51,7 @@ these entries stays in the GitHub releases and the Git history. ### Fixed - 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`). +- `webfront.session` names the native deadline that revoked a session (`revocation`: `operation-deadline` or `startup-deadline`, empty otherwise), and `Session::revokedBy()` gives it in C++: `AutomationMcpWatchdog` no longer fails when the window closes after the deadline, since its host recognised only a reason that the deadline never wrote (#709, `docs/AUTOMATION.md`). - An invalid content policy (an origin of `bridgeAllowedOrigins` or `navigationAllowedOrigins`, a `referrerPolicy`, a `htmlCacheControl`) throws `std::invalid_argument` before the server binds its port, as documented, instead of an "address already in use" error when that port is taken (#674). - `DeveloperBrowserIntegration-workspace` gives the relaunched bootstrap page the same 60 s to start as the first one, instead of 10 s, which a loaded runner exceeded while the page verified its cached environment (#660). - Applications started from the terminal of a Snap-packaged editor (VSCodium) now run on WebKitGTK without cleaning the environment by hand; `WEBFRONT_KEEP_SNAP_ENVIRONMENT=1` opts out (#662, `docs/WEBKITGTK.md`). diff --git a/include/webfront/automation/Enable.hpp b/include/webfront/automation/Enable.hpp index 22551285..f4201f40 100644 --- a/include/webfront/automation/Enable.hpp +++ b/include/webfront/automation/Enable.hpp @@ -151,8 +151,9 @@ class Automation { // A renderer in a loop never runs that request: after the grace the window is declared unresponsive. supervisor = std::jthread([this](std::stop_token stop) { while (!stop.stop_requested()) { - if (session->expire(Clock::now()) || session->expireStartup(startupDeadline(launched, startup), Clock::now())) - session->close("Native automation deadline exceeded"); + // Each expiry closes the session with its own reason and names its deadline (`Session::revokedBy()`). + if (!session->expire(Clock::now())) + session->expireStartup(startupDeadline(launched, startup), Clock::now()); if (session->isClosed()) { // The grace starts when the window is asked to close, so a closeBrowser() that blocks does not extend it. const auto deadline = deadlineAfter(Clock::now(), grace); diff --git a/include/webfront/automation/Session.hpp b/include/webfront/automation/Session.hpp index aff230cc..0e17360a 100644 --- a/include/webfront/automation/Session.hpp +++ b/include/webfront/automation/Session.hpp @@ -73,7 +73,7 @@ class Session { : ready ? "ready" : "starting") + ",\"allow\":" + stringArray(options.allow) + ",\"callbacks\":" + stringArray(options.callbacks) + ",\"failure\":" + json::quote(failure) - + ",\"audit\":" + auditJson() + "}"; + + ",\"revocation\":" + json::quote(revocation) + ",\"audit\":" + auditJson() + "}"; } std::string start(const Object& request, Clock::time_point now = Clock::now()) { @@ -240,7 +240,7 @@ class Session { auto& run = find(*active); run.state = "timeout"; active.reset(); - closeLocked("Native operation deadline exceeded; session revoked"); + closeLocked("Native operation deadline exceeded; session revoked", operationDeadline); return true; } @@ -249,7 +249,7 @@ class Session { std::scoped_lock lock{mutex}; if (closed || ready || now < deadline) return false; - closeLocked("Native automation startup deadline exceeded"); + closeLocked("Native automation startup deadline exceeded", startupDeadline); return true; } @@ -257,6 +257,16 @@ class Session { std::scoped_lock lock{mutex}; return closed; } + /// The deadlines that revoke a session, as `revokedBy()` and the `revocation` member of `describe()` name them. + static constexpr std::string_view operationDeadline = "operation-deadline", startupDeadline = "startup-deadline"; + + /// Which native deadline revoked the session: `operationDeadline`, `startupDeadline`, or empty when none did (the session + /// is open, or was closed for another reason). The first closing fixes it, like the failure reason. + std::string revokedBy() const { + std::scoped_lock lock{mutex}; + return revocation; + } + bool wasReady() const { std::scoped_lock lock{mutex}; return ready; @@ -264,7 +274,7 @@ class Session { private: SessionOptions options; - std::string identity, failure; + std::string identity, failure, revocation; mutable std::mutex mutex; std::deque runs; std::deque auditEntries; @@ -379,11 +389,12 @@ class Session { return "{\"runId\":" + json::quote(run.id) + ",\"operation\":" + json::quote(run.operation) + ",\"state\":" + json::quote(run.state) + ",\"cancelRequested\":" + (run.cancel ? "true" : "false") + ",\"output\":" + json::quote(run.output) + ",\"result\":" + run.result + "}"; } - void closeLocked(std::string reason) { + void closeLocked(std::string reason, std::string_view deadline = {}) { if (closed) return; - closed = true; - failure = std::move(reason); + closed = true; + failure = std::move(reason); + revocation = deadline; if (active) { find(*active).state = "disconnected"; active.reset(); diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 6416e72b..0c4110f2 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -250,6 +250,49 @@ def install(args, project): assert installed.returncode == 0, installed.stdout + installed.stderr +def operation_archive(args, root, name, body, startup_gap): + """The environment archive with the operation body replaced by `body`; with `startup_gap`, its startup is delayed past + the operation's deadline and a bridge RangeError consumes a JS sequence first. Returns (archive, integrity).""" + environment = root / f"{name}-environment.tgz" + replaced = False + with tarfile.open(args.environment, "r:gz") as archive, tarfile.open(environment, "w:gz", compresslevel=1) as output: + for member in archive.getmembers(): + data = archive.extractfile(member).read() if member.isfile() else None + if member.name == "package/runtime.mjs": + # Locate the named export, rather than hard-coding a minifier's local identifier. + exports = re.findall(rb"([A-Za-z_$][A-Za-z0-9_$]*) as runNonInteractive(?=[,}])", data) + assert len(exports) == 1, "The watchdog fixture needs the real runNonInteractive export" + data += b"\n" + exports[0] + body + if startup_gap: + connect = re.findall(rb"([A-Za-z_$][A-Za-z0-9_$]*) as connectAutomation(?=[,}])", data) + assert len(connect) == 1 + # A bridge RangeError (a message past the bridge's maximum, lowered for this call) consumes a JS + # sequence without reaching native code. + data += (b"\nconst beforeGap=" + connect[0] + b";" + connect[0] + + b"=context=>{const limit=context.bridge.maxMessageBytes;context.bridge.maxMessageBytes=70000;" + b"void context.call('poll','x'.repeat(70000)).then(()=>window.close()," + b"()=>{context.bridge.maxMessageBytes=limit;beforeGap(context);});};") + # Only this startup test needs a delay longer than the operation's two-second deadline. + data = b"await new Promise(resolve => setTimeout(resolve,3000));\n" + data + member.size = len(data) + replaced = True + output.addfile(member, io.BytesIO(data) if data is not None else None) + assert replaced + return environment, "sha512-" + base64.b64encode(hashlib.sha512(environment.read_bytes()).digest()).decode() + + +def operation_body(marker, wait): + """An operation that records `marker` in the project through the real signed writes, then never completes: `wait` is + the JavaScript that keeps it running.""" + return (b""" = async (_argv,context) => { + const call=(name,...args) => context.bridge.cppFunction('webfront.developer.'+name)(...args); + const id=await call('begin','""" + marker + b"""',false); + await call('write',id,'output',0,new Uint8Array([1])); + await call('commit',id); + """ + wait + b""" + };""") + + def watchdog(args): """Exercise native revocation with a real blocked renderer, without compiling Jasmine first. @@ -262,40 +305,27 @@ def watchdog(args): root = pathlib.Path(temporary) project = root / "project" shutil.copytree(args.fixture, project) - environment = root / "watchdog-environment.tgz" - blocked = b""" = async (_argv,context) => { - const call=(name,...args) => context.bridge.cppFunction('webfront.developer.'+name)(...args); - const id=await call('begin','renderer.started',false); - await call('write',id,'output',0,new Uint8Array([1])); - await call('commit',id); - while(true) {} - };""" - replaced = False - with tarfile.open(args.environment, "r:gz") as archive, tarfile.open(environment, "w:gz", compresslevel=1) as output: - for member in archive.getmembers(): - data = archive.extractfile(member).read() if member.isfile() else None - if member.name == "package/runtime.mjs": - # Locate the named export, rather than hard-coding a minifier's local identifier. - exports = re.findall(rb"([A-Za-z_$][A-Za-z0-9_$]*) as runNonInteractive(?=[,}])", data) - assert len(exports) == 1, "The watchdog fixture needs the real runNonInteractive export" - data += b"\n" + exports[0] + blocked - connect = re.findall(rb"([A-Za-z_$][A-Za-z0-9_$]*) as connectAutomation(?=[,}])", data) - assert len(connect) == 1 - # A bridge RangeError (a message past the bridge's maximum, lowered for this call) consumes a JS - # sequence without reaching native code. - data += (b"\nconst beforeGap=" + connect[0] + b";" + connect[0] + - b"=context=>{const limit=context.bridge.maxMessageBytes;context.bridge.maxMessageBytes=70000;" - b"void context.call('poll','x'.repeat(70000)).then(()=>window.close()," - b"()=>{context.bridge.maxMessageBytes=limit;beforeGap(context);});};") - # Only this startup test needs a delay longer than the operation's two-second deadline. - data = b"await new Promise(resolve => setTimeout(resolve,3000));\n" + data - member.size = len(data) - replaced = True - output.addfile(member, io.BytesIO(data) if data is not None else None) - assert replaced - integrity = "sha512-" + base64.b64encode(hashlib.sha512(environment.read_bytes()).digest()).decode() directory = root / "forced-window" options = ["--directory", str(directory), "--grants", "build", "--timeout", "2", "--startup-timeout", "30"] + # 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", + operation_body(b"renderer.waiting", b"await new Promise(() => {});"), False) + with (pathlib.Path(args.work) / "watchdog-waiting.log").open("w") as log: + host = Host(args, project, root, "waiting", log, options, str(environment), integrity) + try: + record = host.record() + client = host.client() + client.initialize() + client.start("build") + status = host.wait(timeout=30) + assert status == 71, f"exit {status}\n{host.logs()}" + assert "Automation operation-deadline: Native operation deadline exceeded" in host.full_log(), host.logs() + finally: + host.close() + assert (project / "renderer.waiting").is_file(), "The deadline expired before the operation started" + check_withdrawn(record, client.url.port, host.sessions) + environment, integrity = operation_archive(args, root, "blocked", operation_body(b"renderer.started", b"while(true) {}"), True) with (pathlib.Path(args.work) / "watchdog.log").open("w") as log: host = Host(args, project, root, "blocked", log, options, str(environment), integrity) try: diff --git a/test/unit/AutomationTests.cpp b/test/unit/AutomationTests.cpp index 369f6f64..f69fada3 100644 --- a/test/unit/AutomationTests.cpp +++ b/test/unit/AutomationTests.cpp @@ -382,6 +382,13 @@ const Scenario automationCancellation{"Automation cancellation and native deadli require(session.expire(std::chrono::steady_clock::now() + std::chrono::seconds{2})); require(session.isClosed()); require(Object(session.result(query(session, id))).string("state") == "timeout"); + // What automation_host reads to exit with 71 (#709): the deadline, not a copy of its reason. + requireEqual(session.revokedBy(), std::string{Session::operationDeadline}); + requireEqual(Object(session.describe()).string("revocation"), std::string{Session::operationDeadline}); + session.close("Native automation deadline exceeded"); + requireEqual(session.revokedBy(), std::string{Session::operationDeadline}); + requireEqual(Object(session.describe()).string("failure"), + std::string{"Native operation deadline exceeded; session revoked"}); requireThrows([&] { session.complete(id, R"({"exitCode":0,"output":"","report":null})"); }); @@ -402,10 +409,16 @@ const Scenario automationStartup{"Automation startup expiry respects readiness a session.poll(); require(!session.expireStartup(deadline, deadline)); require(!session.isClosed()); + // Closed for another reason: no deadline revoked it, so the host does not report one. + session.close("Developer window disconnected"); + require(session.revokedBy().empty()); + require(Object(session.describe()).string("revocation").empty()); }); given("the renderer has not polled at the deadline", [&] { require(session.expireStartup(deadline, deadline)); require(session.isClosed()); + requireEqual(session.revokedBy(), std::string{Session::startupDeadline}); + requireEqual(Object(session.describe()).string("revocation"), std::string{Session::startupDeadline}); requireThrows([&] { session.start(command(session, "build")); }); diff --git a/test/web/AutomationHost.cpp b/test/web/AutomationHost.cpp index 10e0628b..69c23b34 100644 --- a/test/web/AutomationHost.cpp +++ b/test/web/AutomationHost.cpp @@ -19,7 +19,8 @@ // With --called, the application registers `consumer.render` (which appends its argument to the file) and // `consumer.secret` (never allow-listed by the tests). Closing its standard input closes the window, on every platform and // whatever the engine does with signals. The status is 0 after a normal closing, 70 when the developer environment failed -// to start (its reason on stderr), 71 when the native deadline of an operation revoked the session; a window that does not +// to start (its reason on stderr), 71 when a native deadline (of an operation, or of the startup) revoked the session and the +// window then closed; a window that does not // close after a deadline ends the process with enableAutomation's own status 72. An occupied MCP port exits with 73 so // the test client can retry a port lost between reservation and bind. @@ -196,9 +197,12 @@ int main(int argc, char** argv) { const webfront::automation::Object state{automation->controller()->describe()}; const auto failure = state.string("failure"); int status = 0; - if (failure == "Native automation deadline exceeded") + // A native deadline revoked the session and the window closed before the grace ended. The session names that + // deadline; its reason text differs from one deadline to the other (#709). + if (const auto deadline = automation->controller()->revokedBy(); !deadline.empty()) { + std::cerr << "Automation " << deadline << ": " << failure << '\n'; status = 71; - else if (!automation->controller()->wasReady() && !failure.empty()) { + } else if (!automation->controller()->wasReady() && !failure.empty()) { std::cerr << "Automation startup: " << failure << '\n'; status = 70; }