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
7 changes: 4 additions & 3 deletions docs/AUTOMATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down
5 changes: 3 additions & 2 deletions include/webfront/automation/Enable.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
25 changes: 18 additions & 7 deletions include/webfront/automation/Session.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down Expand Up @@ -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;
}

Expand All @@ -249,22 +249,32 @@ 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;
}

bool isClosed() const {
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;
}

private:
SessionOptions options;
std::string identity, failure;
std::string identity, failure, revocation;
mutable std::mutex mutex;
std::deque<Run> runs;
std::deque<std::string> auditEntries;
Expand Down Expand Up @@ -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();
Expand Down
94 changes: 62 additions & 32 deletions test/tools/AutomationClient.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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:
Expand Down
13 changes: 13 additions & 0 deletions test/unit/AutomationTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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})");
});
Expand All @@ -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"));
});
Expand Down
Loading
Loading