Lightpanda: the headless browser designed for AI and automation
crash: Capture ExecutionTerminated and propagate it
Karl Seguin8023f6e1da13
diff --git a/src/browser/EventManager.zig b/src/browser/EventManager.zigindex 3928236ba..28e4fb993 100644--- a/src/browser/EventManager.zig+++ b/src/browser/EventManager.zig@@ -352,6 +352,9 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event, comptime opts// don't propagate" rule as addEventListener listeners — see Listener.run.var caught: js.TryCatch.Caught = undefined;const handler_return: ?js.Value = ls.toLocal(inline_handler).tryCallWithThis(js.Value, target_et, .{event}, &caught) catch |err| ret: {+ if (err == error.ExecutionTerminated) {+ return error.ExecutionTerminated;+ }frame._page.recordJsError(err);log.warn(.event, "inline handler", .{ .err = err, .caught = caught });break :ret null;@@ -409,6 +412,9 @@ fn dispatchNode(self: *EventManager, target: *Node, event: *Event, comptime optsvar caught: js.TryCatch.Caught = undefined;const handler_return: ?js.Value = ls.toLocal(inline_handler).tryCallWithThis(js.Value, current_target, .{event}, &caught) catch |err| ret: {+ if (err == error.ExecutionTerminated) {+ return error.ExecutionTerminated;+ }frame._page.recordJsError(err);log.warn(.event, "inline handler", .{ .err = err, .caught = caught });break :ret null;diff --git a/src/browser/EventManagerBase.zig b/src/browser/EventManagerBase.zigindex bfbd926f0..9b5c13464 100644--- a/src/browser/EventManagerBase.zig+++ b/src/browser/EventManagerBase.zig@@ -215,6 +215,7 @@ pub const DispatchError = error{StringTooLarge,CompilationError,JsException,+ ExecutionTerminated,};pub const DispatchDirectOptions = struct {@@ -290,6 +291,9 @@ pub fn dispatchDirect(event._current_target = target;var caught: js.TryCatch.Caught = undefined;_ = func.tryCallWithThis(void, target, .{event}, &caught) catch |err| {+ if (err == error.ExecutionTerminated) {+ return error.ExecutionTerminated;+ }page.recordJsError(err);if (err == error.JsException) {event._listeners_did_throw = true;@@ -435,7 +439,7 @@ pub const Listener = struct {local: *const js.Local,event: *Event,comptime context: []const u8,- ) error{OutOfMemory}!void {+ ) error{ OutOfMemory, ExecutionTerminated }!void {switch (self.function) {.value => |value| {var try_catch: js.TryCatch = undefined;@@ -448,12 +452,16 @@ pub const Listener = struct {event._listeners_did_throw = true;reportException(&try_catch, local);},+ error.ExecutionTerminated => return error.ExecutionTerminated,else => log.warn(.event, context, .{ .err = err }),};},.string => |string| {const str = try arena.dupeZ(u8, string.str());local.eval(str, null) catch |err| {+ if (err == error.ExecutionTerminated) {+ return error.ExecutionTerminated;+ }local.ctx.page.recordJsError(err);if (err == error.JsException) {event._listeners_did_throw = true;@@ -501,6 +509,7 @@ pub const Listener = struct {event._listeners_did_throw = true;reportException(&try_catch, local);},+ error.ExecutionTerminated => return error.ExecutionTerminated,else => log.warn(.event, context, .{ .err = err }),};},diff --git a/src/browser/ScriptManagerBase.zig b/src/browser/ScriptManagerBase.zigindex b10676e62..e7015c352 100644--- a/src/browser/ScriptManagerBase.zig+++ b/src/browser/ScriptManagerBase.zig@@ -960,6 +960,10 @@ pub const Script = struct {log.debug(.browser, "executed script", .{ .src = url, .success = success });}+ if (!success and frame.js.env.isExecutionTerminating()) {+ return;+ }+defer {local.runMacrotasks(); // also runs microtasks_ = frame.js.scheduler.run() catch |err| {diff --git a/src/browser/frame/observers.zig b/src/browser/frame/observers.zigindex 8fadf65be..dd69fcae6 100644--- a/src/browser/frame/observers.zig+++ b/src/browser/frame/observers.zig@@ -276,6 +276,9 @@ pub fn deliverResizes(frame: *Frame) void {const observer = frame._resize.observers.items[i];observer.deliverEntries(frame) catch |err| {log.err(.frame, "frame.deliverResizes", .{ .err = err, .type = frame._type, .url = frame.url });+ if (err == error.ExecutionTerminated) {+ return;+ }};}}@@ -303,6 +306,9 @@ pub fn deliverIntersections(frame: *Frame) void {const observer = frame._intersection.observers.items[i];observer.deliverEntries(frame) catch |err| {log.err(.frame, "frame.deliverIntersections", .{ .err = err, .type = frame._type, .url = frame.url });+ if (err == error.ExecutionTerminated) {+ return;+ }};}}@@ -353,6 +359,9 @@ pub fn deliverMutations(frame: *Frame) void {for (notify.items) |observer| {observer.deliverRecords(frame) catch |err| {log.err(.frame, "frame.deliverMutations", .{ .err = err, .type = frame._type, .url = frame.url });+ if (err == error.ExecutionTerminated) {+ return;+ }};}@@ -365,6 +374,9 @@ pub fn deliverMutations(frame: *Frame) void {const target = slot.asNode().asEventTarget();frame._event_manager.dispatch(target, event) catch |err| {log.err(.frame, "deliverSlotchange.dispatch", .{ .err = err, .type = frame._type, .url = frame.url });+ if (err == error.ExecutionTerminated) {+ return;+ }};}}diff --git a/src/browser/js/Caller.zig b/src/browser/js/Caller.zigindex 6444152cb..9908ef8a5 100644--- a/src/browser/js/Caller.zig+++ b/src/browser/js/Caller.zig@@ -578,6 +578,9 @@ fn handleError(comptime T: type, comptime F: type, local: *const Local, err: any// toString threw during argument conversion); throwing anything here// would replace the original exception the script expects to see.error.JsException => return,+ // The termination exception is pending; throwing here would replace+ // it with a catchable Error, letting the killed script keep running.+ error.ExecutionTerminated => return,else => {},}diff --git a/src/browser/js/Function.zig b/src/browser/js/Function.zigindex dfb39a320..83fb86c57 100644--- a/src/browser/js/Function.zig+++ b/src/browser/js/Function.zig@@ -66,6 +66,11 @@ pub fn newInstance(self: *const Function, caught: *js.TryCatch.Caught) !js.Objec}}+ // See _tryCallWithThis for why a pending termination blocks V8 entry.+ if (v8.v8__Isolate__IsExecutionTerminating(local.isolate.handle)) {+ return error.ExecutionTerminated;+ }+var try_catch: js.TryCatch = undefined;try_catch.init(local);defer try_catch.deinit();@@ -73,6 +78,9 @@ pub fn newInstance(self: *const Function, caught: *js.TryCatch.Caught) !js.Objec// This creates a new instance using this Function as a constructor.// const c_args = @as(?[*]const ?*c.Value, @ptrCast(&.{}));const handle = v8.v8__Function__NewInstance(self.handle, local.handle, 0, null) orelse {+ if (v8.v8__Isolate__IsExecutionTerminating(local.isolate.handle)) {+ return error.ExecutionTerminated;+ }caught.* = try_catch.caughtOrError(local.call_arena, error.Unknown);return error.JsConstructorFailed;};@@ -148,6 +156,13 @@ fn _tryCallWithThis(self: *const Function, comptime T: type, this: anytype, args}}+ // A pending termination (watchdog / CDP-disconnect kill) must not be+ // followed by another V8 entry. Callers must treat ExecutionTerminated as+ // stop running JS and unwind".+ if (v8.v8__Isolate__IsExecutionTerminating(local.isolate.handle)) {+ return error.ExecutionTerminated;+ }+// When we're calling a function from within JavaScript itself, this isn't// necessary. We're within a Caller instantiation, which will already have// incremented the call_depth and it won't decrement it until the Caller is@@ -198,6 +213,10 @@ fn _tryCallWithThis(self: *const Function, comptime T: type, this: anytype, argsdefer try_catch.deinit();const handle = v8.v8__Function__Call(self.handle, local.handle, js_this.handle, @as(c_int, @intCast(js_args.len)), c_args) orelse {+ if (v8.v8__Isolate__IsExecutionTerminating(local.isolate.handle)) {+ // Terminated mid-call, not a JS throw: no rethrow, no reporting.+ return error.ExecutionTerminated;+ }if ((comptime opts.rethrow) and try_catch.hasCaught()) {try_catch.rethrow();return error.TryCatchRethrow;@@ -246,6 +265,72 @@ pub fn persistWithThis(self: *const Function, value: anytype) !Global {return with_this.persist();}+const testing = @import("../../testing.zig");+test "Function: termination is classified and blocks re-entry" {+ const frame = try testing.createFrame();+ defer testing.test_session.closeAllPages();++ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ const local = &ls.local;++ const env = frame.js.env;+ defer env.cancelTerminate();++ const State = struct {+ env: *js.Env,+ f_kill: ?Function = null,+ f_probe: ?Function = null,+ probe_ran: bool = false,+ kill_err: ?anyerror = null,+ probe_err: ?anyerror = null,++ fn kill(self: *@This()) void {+ self.env.terminate();+ }++ fn probed(self: *@This()) void {+ self.probe_ran = true;+ }++ // Runs at call depth >= 1: the killed inner call must leave the+ // termination pending, and the follow-up call must refuse to enter V8+ // (running it would silently clear the pending termination).+ fn nested(self: *@This()) void {+ var caught: js.TryCatch.Caught = undefined;+ _ = self.f_kill.?.tryCall(void, .{}, &caught) catch |err| {+ self.kill_err = err;+ };+ _ = self.f_probe.?.tryCall(void, .{}, &caught) catch |err| {+ self.probe_err = err;+ };+ }+ };+ var state = State{ .env = env };++ const kill_cb = local.newCallback(State.kill, &state);+ const mk = try local.exec("(function(k){ return function(){ k(); for(;;){} }; })", null);+ const mk_fn = Function{ .local = local, .handle = @ptrCast(mk.handle) };+ const f_kill = try mk_fn.call(js.Value, .{kill_cb});+ state.f_kill = .{ .local = local, .handle = @ptrCast(f_kill.handle) };+ state.f_probe = local.newCallback(State.probed, &state);++ const nested_cb = local.newCallback(State.nested, &state);+ const driver = try local.exec("(function(n){ n(); })", null);+ const driver_fn = Function{ .local = local, .handle = @ptrCast(driver.handle) };++ var caught: js.TryCatch.Caught = undefined;+ try testing.expectError(error.ExecutionTerminated, driver_fn.tryCall(void, .{nested_cb}, &caught));+ try testing.expectEqual(error.ExecutionTerminated, state.kill_err.?);+ try testing.expectEqual(error.ExecutionTerminated, state.probe_err.?);+ try testing.expectEqual(false, state.probe_ran);++ // a top-level cancel restores normal execution+ env.cancelTerminate();+ try testing.expectEqual(3, try (try local.exec("1 + 2", null)).toI32());+}+// A cheap, copyable handle to a persisted function. See js.GlobalSlot.pub const Global = struct {slot: *js.GlobalSlot,diff --git a/src/browser/js/Script.zig b/src/browser/js/Script.zigindex 7dbe89c74..94404851e 100644--- a/src/browser/js/Script.zig+++ b/src/browser/js/Script.zig@@ -30,7 +30,18 @@ local: *const js.Local,handle: *const v8.Script,pub fn run(self: Script) !js.Value {- const result = v8.v8__Script__Run(self.handle, self.local.handle) orelse return error.JsException;+ // See Function._tryCallWithThis for why a pending termination blocks V8+ // entry and is distinct from a JS throw.+ const isolate_handle = self.local.isolate.handle;+ if (v8.v8__Isolate__IsExecutionTerminating(isolate_handle)) {+ return error.ExecutionTerminated;+ }+ const result = v8.v8__Script__Run(self.handle, self.local.handle) orelse {+ if (v8.v8__Isolate__IsExecutionTerminating(isolate_handle)) {+ return error.ExecutionTerminated;+ }+ return error.JsException;+ };return .{ .local = self.local, .handle = result };}diff --git a/src/browser/webapi/Node.zig b/src/browser/webapi/Node.zigindex 2519df1a6..a011678d3 100644--- a/src/browser/webapi/Node.zig+++ b/src/browser/webapi/Node.zig@@ -1164,6 +1164,7 @@ const CloneError = error{TypeError,CompilationError,JsException,+ ExecutionTerminated,};pub fn cloneNode(self: *Node, deep_: ?bool, frame: *Frame) CloneError!*Node {const deep = deep_ orelse false;