Lightpanda: the headless browser designed for AI and automation
design: Runner supports multi-pages
Karl Seguin39046492f103
diff --git a/src/browser/Runner.zig b/src/browser/Runner.zigindex eb3d0fff0..2b4d6a19c 100644--- a/src/browser/Runner.zig+++ b/src/browser/Runner.zig@@ -22,6 +22,7 @@ const builtin = @import("builtin");const js = @import("js/js.zig");const Frame = @import("Frame.zig");+const Browser = @import("Browser.zig");const Session = @import("Session.zig");const HttpClient = @import("HttpClient.zig");@@ -33,69 +34,87 @@ const IS_DEBUG = builtin.mode == .Debug;const Runner = @This();-// The "main" or "primary" frame which is used against our `until` checks. This-// is, hopefully, temporary during our transition to multi-page sessions. It-// helps preserve existing behavior for single-page sessions (which CDP and-// fetch use exclusively). But once we start adding multi-page to Agent, and-// maybe CDP and fetch, then "completeness" should gain a clearer meaning.-frame: *Frame,-session: *Session,+browser: *Browser,http_client: *HttpClient,pub const Opts = struct {};-pub fn init(session: *Session, _: Opts) !Runner {- const frame = firstFrame(session) orelse return error.NoPage;-+pub fn init(session: *Session, _: Opts) Runner {return .{- .frame = frame,.session = session,+ .browser = session.browser,.http_client = &session.browser.http_client,};}-// See the `frame` field. Hopefully this goes away and we make Runner truly-// multi-page aware.-fn firstFrame(session: *Session) ?*Frame {- const page = (session.primaryPage() orelse return null).page().?;- const target = session.replacementOf(page) orelse page;- return &target.frame;-}+pub const WaitCondition = struct {+ frame_id: u32,+ until: lp.Config.WaitUntil = .done,+ status: Status = .pending,-pub const WaitOpts = struct {- ms: u32,+ const Status = union(enum) {+ pending,+ complete,+ err: anyerror,+ };+};++const WaitForFrameOpts = struct {until: lp.Config.WaitUntil = .done,};+pub fn waitForFrame(self: *Runner, frame_id: u32, timeout_ms: u32, opts: WaitForFrameOpts) !void {+ const condition = WaitCondition{ .frame_id = frame_id, .until = opts.until };+ var conditions = [_]WaitCondition{condition};+ _ = try self._wait(false, timeout_ms, &conditions);+}-pub const WaitResult = enum { completed, timeout };+pub fn waitForFrameCDP(self: *Runner, frame_id: u32, timeout_ms: u32, until: lp.Config.WaitUntil) !void {+ const condition = WaitCondition{ .frame_id = frame_id, .until = until };+ var conditions = [_]WaitCondition{condition};+ _ = try self._wait(true, timeout_ms, &conditions);+}++// Helper to wait for all currently loaded frames+pub fn waitForAll(self: *Runner, timeout_ms: u32, opts: WaitForFrameOpts) !void {+ const session = self.session;+ const arena = try session.getArena(.tiny, "Runner.waitForAll");+ defer session.releaseArena(arena);++ var pages_to_wait: usize = 0;+ for (session.pages.items) |page| {+ if (page.replacement == null) {+ pages_to_wait += 1;+ }+ }-pub fn wait(self: *Runner, opts: WaitOpts) !void {- _ = try self._wait(false, opts);+ const conditions = try arena.alloc(WaitCondition, pages_to_wait);+ var i: usize = 0;+ for (session.pages.items) |page| {+ if (page.replacement == null) {+ conditions[i] = .{ .frame_id = page.frame._frame_id, .until = opts.until };+ i += 1;+ }+ }+ _ = try self._wait(false, timeout_ms, conditions);}-pub fn waitCDP(self: *Runner, opts: WaitOpts) !void {- _ = try self._wait(true, opts);+pub fn wait(self: *Runner, timeout_ms: u32, conditions: []WaitCondition) !void {+ try self._wait(false, timeout_ms, conditions);}-// `wait` that surfaces whether the goal was reached or the timeout fired.-pub fn waitResult(self: *Runner, opts: WaitOpts) !WaitResult {- return self._wait(false, opts);+pub const WaitResult = enum { completed, timeout };+pub fn waitResult(self: *Runner, timeout_ms: u32, conditions: []WaitCondition) !WaitResult {+ return self._wait(false, timeout_ms, conditions);}// Wait until either a parse-state / load goal is reached or `opts.ms`// elapses. Returns as soon as _tick reports .done.-fn _wait(self: *Runner, comptime is_cdp: bool, opts: WaitOpts) !WaitResult {- const session = self.session;- const browser = session.browser;+fn _wait(self: *Runner, comptime is_cdp: bool, timeout_ms: u32, conditions: []WaitCondition) !WaitResult {+ const browser = self.browser;var timer = try std.time.Timer.start();- const tick_opts = TickOpts{- .ms = 200,- .until = opts.until,- };-// Periodic V8 GC hint during long waits. V8 is otherwise only nudged on// session/page teardown (Browser.zig, Page.zig), so a page that stays// alive for seconds while running heavy JS accumulates wrappers and@@ -105,9 +124,21 @@ fn _wait(self: *Runner, comptime is_cdp: bool, opts: WaitOpts) !WaitResult {var gc_hint_timer = std.time.Timer.start() catch unreachable;while (true) {+ // The CDP path can have its session closed mid-wait: a command+ // dispatched by the previous tick (e.g. disposeBrowserContext) can call+ // browser.closeSession (see the `browser` field comment). So re-derive+ // the live session each pass there and end the wait once it's gone.+ // Non-CDP callers hold a stable session, so they skip the check.+ const session = if (comptime is_cdp)+ (if (browser.session) |*s| s else return .completed)+ else+ self.session;+// Cooperative cancellation. Set by the agent so SIGINT can break// out of a long wait without the user sitting through the timeout.- if (session.isCancelled()) return error.Cancelled;+ if (session.isCancelled()) {+ return error.Cancelled;+ }if (gc_hint_timer.read() >= gc_hint_period_ns) {gc_hint_timer.reset();@@ -115,14 +146,11 @@ fn _wait(self: *Runner, comptime is_cdp: bool, opts: WaitOpts) !WaitResult {}session.processDestroyQueues();- const tick_result = self._tick(is_cdp, tick_opts) catch |err| {+ const tick_result = self._tick(is_cdp, 200, conditions) catch |err| {switch (err) {error.JsError => {}, // already logged (with hopefully more context)error.ClientDisconnected => {}, // CDP layer already logged this- else => log.err(.browser, "session wait", .{- .err = err,- .url = self.frame.url,- }),+ else => log.err(.browser, "session wait", .{ .err = err }),}return err;};@@ -138,16 +166,16 @@ fn _wait(self: *Runner, comptime is_cdp: bool, opts: WaitOpts) !WaitResult {// can observe CDP commands. We have nothing useful to do here// but we can ask the http_client to wait for CDP messages.const elapsed: u32 = @intCast(timer.read() / std.time.ns_per_ms);- if (elapsed >= opts.ms) {+ if (elapsed >= timeout_ms) {return .timeout;}- try self.http_client.tick(@min(opts.ms - elapsed, 200), .all);+ try self.http_client.tick(@min(timeout_ms - elapsed, 200), .all);break :done_blk 0;},};const ms_elapsed: u32 = @intCast(timer.read() / std.time.ns_per_ms);- if (ms_elapsed >= opts.ms) {+ if (ms_elapsed >= timeout_ms) {return .timeout;}if (next_ms > 0) {@@ -156,156 +184,132 @@ fn _wait(self: *Runner, comptime is_cdp: bool, opts: WaitOpts) !WaitResult {}}-pub const TickOpts = struct {- ms: u32,- until: lp.Config.WaitUntil = .done,-};-pub const TickResult = union(enum) {done,ok: u32,};-pub fn tick(self: *Runner, opts: TickOpts) !TickResult {- return self._tick(false, opts);+pub fn tickForFrame(self: *Runner, frame_id: u32, timeout_ms: u32, opts: WaitForFrameOpts) !TickResult {+ const condition = WaitCondition{ .frame_id = frame_id, .until = opts.until };+ var conditions = [_]WaitCondition{condition};+ return self.tick(timeout_ms, &conditions);+}+pub fn tick(self: *Runner, timeout_ms: u32, conditions: []WaitCondition) !TickResult {+ return self._tick(false, timeout_ms, conditions);}-fn _tick(self: *Runner, comptime is_cdp: bool, opts: TickOpts) !TickResult {+fn _tick(self: *Runner, comptime is_cdp: bool, timeout_ms: u32, conditions: []WaitCondition) !TickResult {const session = self.session;+ const browser = self.browser;const http_client = self.http_client;// Drain queued navigations across every live page (one page per call)// A navigation can swap a frame pointer or the page set,// so restart the tick to re-resolve cleanly.if (try session.processQueuedNavigation()) {- self.frame = firstFrame(session) orelse return .done;return .{ .ok = 0 };}- // Refresh self.frame from session. In case of pending page, we want to- // take its state while loading. If we use only the current frame, we will- // return a .done result immediately.- const frame = firstFrame(session) orelse return .done;- self.frame = frame;-- switch (frame._parse_state) {- .pre, .raw, .text, .image, .download => {- // The main frame hasn't started/finished navigating.- // There's no JS to run, and no reason to run the scheduler- // — unless we're the CDP worker, in which case we want- // http_client.tick to drain the inbox.- if (http_client.http_active == 0 and http_client.next_tick_count == 0 and (comptime is_cdp) == false) {- // haven't started navigating, I guess.- return .done;- }- try http_client.tick(@intCast(opts.ms), .all);- return .{ .ok = 0 };- },- .html, .complete => {- const browser = session.browser;-- // The HTML page was parsed. We now either have JS scripts to- // download, or scheduled tasks to execute, or both.-- // scheduler.run could trigger new http transfers, so do not- // store http_client.http_active BEFORE this call and then use- // it AFTER.- try browser.runMacrotasks();-- const http_active = http_client.http_active;- const http_next_tick = http_client.next_tick_count;- const total_network_activity = http_active + http_next_tick + http_client.interception_layer.intercepted;- if (frame._notified_network_almost_idle.check(total_network_activity <= 2)) {- frame.notifyNetworkAlmostIdle();- }- if (frame._notified_network_idle.check(total_network_activity == 0)) {- frame.notifyNetworkIdle();- }+ try browser.runMacrotasks();- switch (opts.until) {- .done => {},- .domcontentloaded => if (frame._load_state == .load or frame._load_state == .complete) {- return .done;- },- .load => if (frame._load_state == .complete) {- return .done;- },- .networkidle => if (frame._notified_network_idle == .done) {- return .done;- },- .networkalmostidle => if (frame._notified_network_almost_idle == .done) {- return .done;- },- }+ const http_active = http_client.http_active;+ const http_next_tick = http_client.next_tick_count;+ const total_http_activity = http_active + http_next_tick + http_client.interception_layer.intercepted;+ const total_network_activity = total_http_activity + http_client.ws_active;- if (http_active == 0 and http_next_tick == 0 and http_client.ws_active == 0 and http_client.queue.first == null and http_client.ready_queue.first == null and (comptime is_cdp) == false) {- // ready_queue is also part of the check: makeRequest now- // wraps its handles.perform() in a performing=true window,- // and any synchronous libcurl callback that ends up- // calling trackConn during that window (e.g. JS creating- // a WebSocket) will append to ready_queue. Without this- // check we could observe it non-empty after- // http_client.tick returns.- //- // intercepted is only non-zero in serve mode, and- // serve mode implies cdp_client != null — so if we got- // here, intercepted == 0.- if (comptime IS_DEBUG) {- std.debug.assert(http_client.interception_layer.intercepted == 0);- }+ const ms_to_next_microtask = browser.msToNextMacrotask();+ const is_done = ms_to_next_microtask == null and total_network_activity == 0 and http_client.queue.first == null and http_client.ready_queue.first == null;- if (browser.hasBackgroundTasks()) {- // _we_ have nothing to run, but v8 is working on- // background tasks. We'll wait for them.- browser.waitForBackgroundTasks();+ var want_http_tick = false;++ for (conditions) |*condition| {+ if (condition.status != .pending) {+ // this condition is at a termianl state+ continue;+ }++ const page = session.pendingOrLivePage(condition.frame_id) orelse {+ condition.status = .{ .err = error.FrameNotFound };+ continue;+ };++ const frame = &page.frame;+ switch (frame._parse_state) {+ .err => |err| {+ frame._parse_state = .{ .raw_done = @errorName(err) };+ condition.status = .{ .err = err };+ },+ .raw_done => {+ condition.status = .complete;+ },+ .pre, .raw, .text, .image, .download => {+ if (total_network_activity == 0) {+ condition.status = .complete;+ } else {+ want_http_tick = true;+ }+ },+ .html, .complete => {+ if (frame._notified_network_almost_idle.check(total_http_activity <= 2)) {+ frame.notifyNetworkAlmostIdle();+ }+ if (frame._notified_network_idle.check(total_http_activity == 0)) {+ frame.notifyNetworkIdle();}- // We never advertise a wait time of more than 20, there can- // always be new background tasks to run.- if (browser.msToNextMacrotask()) |ms_to_next_task| {- return .{ .ok = @min(ms_to_next_task, 20) };+ const met = switch (condition.until) {+ .done => is_done,+ .domcontentloaded => frame._load_state == .load or frame._load_state == .complete,+ .load => frame._load_state == .complete,+ .networkidle => frame._notified_network_idle == .done,+ .networkalmostidle => frame._notified_network_almost_idle == .done,+ };++ // `met` resolves the condition. Otherwise, as long as there's+ // still work in flight (network or pending macrotasks), keep+ // ticking. `is_done` means the page went fully idle without+ // reaching the goal — there's nothing left to wait on, so+ // resolve rather than spin forever.+ if (met or is_done) {+ condition.status = .complete;+ } else {+ want_http_tick = true;}- return .done;- }+ },+ }+ }- // We're here because we either have active HTTP- // connections, or there's a CDP client whose inbox we have- // to drain via http_client.tick. We should continue to run- // tasks, so we minimize how long we'll poll for network I/O.- var ms_to_wait = @min(opts.ms, browser.msToNextMacrotask() orelse 200);- if (ms_to_wait > 10 and browser.hasBackgroundTasks()) {- // if we have background tasks, we don't want to wait too- // long for a message from the client. We want to go back- // to the top of the loop and run macrotasks.- ms_to_wait = 10;- }- try http_client.tick(@intCast(@min(opts.ms, ms_to_wait)), .all);- return .{ .ok = 0 };- },- .err => |err| {- frame._parse_state = .{ .raw_done = @errorName(err) };- return err;- },- .raw_done => {- if (comptime is_cdp) {- try http_client.tick(@intCast(opts.ms), .all);- return .{ .ok = 0 };- }- return .done;- },+ if ((comptime is_cdp) or want_http_tick) {+ var ms_to_wait = @min(timeout_ms, ms_to_next_microtask orelse 200);+ if (browser.hasBackgroundTasks()) {+ // background work will queue more to do soon — don't block long+ // for a client message; loop back and run macrotasks instead.+ ms_to_wait = @min(ms_to_wait, 10);+ }+ try http_client.tick(@intCast(ms_to_wait), .all);+ return .{ .ok = 0 };}++ return .done;}-pub fn waitForSelector(self: *Runner, selector: [:0]const u8, timeout_ms: u32) !*Node.Element {- const arena = try self.session.getArena(.small, "Runner.waitForSelector");- defer self.session.releaseArena(arena);+pub fn waitForSelector(self: *Runner, frame_id: u32, selector: [:0]const u8, timeout_ms: u32) !*Node.Element {+ const session = self.session;+ const arena = try session.getArena(.small, "Runner.waitForSelector");+ defer session.releaseArena(arena);var timer = try std.time.Timer.start();const parsed_selector = try Selector.parseLeaky(arena, selector);while (true) {- if (self.session.isCancelled()) return error.Cancelled;- // self.frame can change between ticks- const frame = self.frame;+ if (session.isCancelled()) {+ return error.Cancelled;+ }++ const page = session.pendingOrLivePage(frame_id) orelse {+ return error.FrameNotFound;+ };+ const frame = &page.frame;+if (try parsed_selector.query(frame.document.asNode(), frame)) |el| {return el;}@@ -314,7 +318,7 @@ pub fn waitForSelector(self: *Runner, selector: [:0]const u8, timeout_ms: u32) !if (elapsed >= timeout_ms) {return error.Timeout;}- switch (try self.tick(.{ .ms = timeout_ms - elapsed })) {+ switch (try self.tickForFrame(frame_id, timeout_ms - elapsed, .{ .until = .done })) {// Idle: poll so `timeout_ms` means "wait up to N ms", not "fail now"..done => std.Thread.sleep(std.time.ns_per_ms * @as(u64, @min(timeout_ms - elapsed, 50))),.ok => |recommended_sleep_ms| {@@ -326,7 +330,8 @@ pub fn waitForSelector(self: *Runner, selector: [:0]const u8, timeout_ms: u32) !}}-pub fn waitForScript(runner: *Runner, src: [:0]const u8, timeout_ms: u32) !void {+pub fn waitForScript(self: *Runner, frame_id: u32, src: [:0]const u8, timeout_ms: u32) !void {+ const session = self.session;var timer = try std.time.Timer.start();// Compile the script once and re-use the compiled form. A tick can create a@@ -335,8 +340,13 @@ pub fn waitForScript(runner: *Runner, src: [:0]const u8, timeout_ms: u32) !void// each tick. Compilation is context-independent, so we can do it up front// in whatever context the frame currently has.var compiled: js.Script.Unbound.Global = blk: {+ const page = session.pendingOrLivePage(frame_id) orelse {+ return error.FrameNotFound;+ };+ const frame = &page.frame;+var ls: js.Local.Scope = undefined;- runner.frame.js.localScope(&ls);+ frame.js.localScope(&ls);defer ls.deinit();var try_catch: js.TryCatch = undefined;@@ -344,7 +354,7 @@ pub fn waitForScript(runner: *Runner, src: [:0]const u8, timeout_ms: u32) !voiddefer try_catch.deinit();const s = ls.local.compile(src, "wait_script") catch |err| {- const caught = try_catch.caughtOrError(runner.frame.call_arena, err);+ const caught = try_catch.caughtOrError(frame.call_arena, err);log.err(.app, "wait script error", .{ .err = caught });return error.ScriptError;};@@ -353,8 +363,14 @@ pub fn waitForScript(runner: *Runner, src: [:0]const u8, timeout_ms: u32) !voiddefer compiled.deinit();while (true) {- if (runner.session.isCancelled()) return error.Cancelled;- const frame = runner.frame;+ if (session.isCancelled()) {+ return error.Cancelled;+ }++ const page = session.pendingOrLivePage(frame_id) orelse {+ return error.FrameNotFound;+ };+ const frame = &page.frame;var ls: js.Local.Scope = undefined;frame.js.localScope(&ls);@@ -379,7 +395,7 @@ pub fn waitForScript(runner: *Runner, src: [:0]const u8, timeout_ms: u32) !voidif (elapsed >= timeout_ms) {return error.Timeout;}- switch (try runner.tick(.{ .ms = timeout_ms - elapsed })) {+ switch (try self.tickForFrame(frame_id, timeout_ms - elapsed, .{ .until = .done })) {// Idle: poll so `timeout_ms` means "wait up to N ms", not "fail now"..done => std.Thread.sleep(std.time.ns_per_ms * @as(u64, @min(timeout_ms - elapsed, 50))),.ok => |recommended_sleep_ms| {@@ -392,24 +408,20 @@ pub fn waitForScript(runner: *Runner, src: [:0]const u8, timeout_ms: u32) !void}const testing = @import("../testing.zig");-test "Runner: no page" {- try testing.expectError(error.NoPage, Runner.init(testing.test_session, .{}));-}-test "Runner: waitForSelector timeout" {const page = try testing.pageTest("runner/runner1.html", .{});defer page.close();- var runner = try page.session.runner(.{});- try testing.expectError(error.Timeout, runner.waitForSelector("#nope", 10));+ var runner = page.session.runner(.{});+ try testing.expectError(error.Timeout, runner.waitForSelector(page.frame_id, "#nope", 10));}test "Runner: waitForSelector" {defer testing.reset();const page = try testing.pageTest("runner/runner1.html", .{});- var runner = try page.session.runner(.{});- const el = try runner.waitForSelector("#sel1", 10);+ var runner = page.session.runner(.{});+ const el = try runner.waitForSelector(page.frame_id, "#sel1", 10);try testing.expectEqual("selector-1-content", try el.asNode().getTextContentAlloc(testing.arena_allocator));}@@ -417,14 +429,14 @@ test "Runner: waitForScript timeout" {const page = try testing.pageTest("runner/runner1.html", .{});defer page.close();- var runner = try page.session.runner(.{});- try testing.expectError(error.Timeout, runner.waitForScript("document.querySelector('#nope')", 10));+ var runner = page.session.runner(.{});+ try testing.expectError(error.Timeout, runner.waitForScript(page.frame_id, "document.querySelector('#nope')", 10));}test "Runner: waitForScript" {const page = try testing.pageTest("runner/runner1.html", .{});defer page.close();- var runner = try page.session.runner(.{});- try runner.waitForScript("document.querySelector('#sel1')", 10);+ var runner = page.session.runner(.{});+ try runner.waitForScript(page.frame_id, "document.querySelector('#sel1')", 10);}diff --git a/src/browser/Session.zig b/src/browser/Session.zigindex 5bdcedae8..4cab1caaf 100644--- a/src/browser/Session.zig+++ b/src/browser/Session.zig@@ -396,6 +396,15 @@ pub fn livePage(self: *Session, frame_id: u32) ?*Page {return null;}+pub fn pendingOrLivePage(self: *Session, frame_id: u32) ?*Page {+ for (self.pages.items) |page| {+ if (page.frame._frame_id == frame_id) {+ return page.replacement orelse page;+ }+ }+ return null;+}+// The in-flight replacement for `page`pub fn replacementOf(self: *Session, page: *Page) ?*Page {const replacement = page.replacement;@@ -457,7 +466,7 @@ pub fn findFrameByFrameId(self: *Session, frame_id: u32) ?*Frame {return null;}-pub fn runner(self: *Session, opts: Runner.Opts) !Runner {+pub fn runner(self: *Session, opts: Runner.Opts) Runner {return Runner.init(self, opts);}@@ -467,8 +476,14 @@ pub fn runner(self: *Session, opts: Runner.Opts) !Runner {pub fn idleSlice(self: *Session) u31 {const quiet_ms = 250;self.processDestroyQueues();- var r = self.runner(.{}) catch return quiet_ms; // error.NoPage when pageless- const result = r.tick(.{ .ms = 25 }) catch return quiet_ms;++ if (self.pages.items.len == 0) {+ return quiet_ms;+ }+ const page = self.pages.items[0];++ var r = self.runner(.{});+ const result = r.tickForFrame(page.frame._frame_id, 25, .{ .until = .done }) catch return quiet_ms;return switch (result) {.done => quiet_ms,.ok => |next_ms| @intCast(@min(next_ms, quiet_ms)),diff --git a/src/browser/actions.zig b/src/browser/actions.zigindex 9a5b24715..9ed544c9c 100644--- a/src/browser/actions.zig+++ b/src/browser/actions.zig@@ -272,24 +272,24 @@ fn remainingMs(timeout_ms: u32, timer: *std.time.Timer) u32 {return @max(1, timeout_ms -| elapsed);}-pub fn waitForSelector(selector: [:0]const u8, timeout_ms: u32, session: *Session) !*DOMNode {+pub fn waitForSelector(selector: [:0]const u8, timeout_ms: u32, frame_id: u32, session: *Session) !*DOMNode {var timer = try std.time.Timer.start();- var runner = try session.runner(.{});- try runner.wait(.{ .ms = timeout_ms, .until = .load });+ var runner = session.runner(.{});+ try runner.waitForFrame(frame_id, timeout_ms, .{ .until = .load });- const el = try runner.waitForSelector(selector, remainingMs(timeout_ms, &timer));+ const el = try runner.waitForSelector(frame_id, selector, remainingMs(timeout_ms, &timer));return el.asNode();}-pub fn waitForScript(script: [:0]const u8, timeout_ms: u32, session: *Session) !void {+pub fn waitForScript(script: [:0]const u8, timeout_ms: u32, frame_id: u32, session: *Session) !void {var timer = try std.time.Timer.start();- var runner = try session.runner(.{});- try runner.wait(.{ .ms = timeout_ms, .until = .load });+ var runner = session.runner(.{});+ try runner.waitForFrame(frame_id, timeout_ms, .{ .until = .load });- return runner.waitForScript(script, remainingMs(timeout_ms, &timer));+ return runner.waitForScript(frame_id, script, remainingMs(timeout_ms, &timer));}-pub fn waitForState(state: lp.Config.WaitUntil, timeout_ms: u32, session: *Session) !void {- var runner = try session.runner(.{});- try runner.wait(.{ .ms = timeout_ms, .until = state });+pub fn waitForState(state: lp.Config.WaitUntil, timeout_ms: u32, frame_id: u32, session: *Session) !void {+ var runner = session.runner(.{});+ try runner.waitForFrame(frame_id, timeout_ms, .{ .until = state });}diff --git a/src/browser/tools.zig b/src/browser/tools.zigindex fa80b0fec..0da7f71c2 100644--- a/src/browser/tools.zig+++ b/src/browser/tools.zig@@ -1205,7 +1205,7 @@ fn execEvaluate(arena: std.mem.Allocator, session: *lp.Session, registry: *CDPNo}// Script may have queued a navigation (e.g. `top.location = …`).- try awaitQueuedNavigation(session);+ try awaitQueuedNavigation(session, page._frame_id);const after = session.currentFrame() orelse return result;if (before == null or before.? == after) return result;@@ -1260,9 +1260,7 @@ fn runEval(arena: std.mem.Allocator, page: *lp.Frame, script: [:0]const u8, fallconst promise = js_result.toPromise();promise.markAsHandled();- var runner = page._session.runner(.{}) catch {- return .{ .text = "promise: no runner available", .is_error = true };- };+ var runner = page._session.runner(.{});var timer = std.time.Timer.start() catch unreachable;while (promise.state() == .pending) {const elapsed_ms: u32 = @intCast(timer.read() / std.time.ns_per_ms);@@ -1270,7 +1268,7 @@ fn runEval(arena: std.mem.Allocator, page: *lp.Frame, script: [:0]const u8, fallreturn .{ .text = "promise: timed out waiting for resolution", .is_error = true };}const budget = @min(eval_promise_timeout_ms - elapsed_ms, 50);- _ = runner.tick(.{ .ms = budget }) catch |err| switch (err) {+ _ = runner.tickForFrame(page._frame_id, budget, .{ .until = .done }) catch |err| switch (err) {error.Cancelled => return .{ .text = "promise: cancelled", .is_error = true },else => return .{ .text = "promise: tick failed", .is_error = true },};@@ -1422,13 +1420,13 @@ fn mapActionError(err: anytype) ToolError {/// If the previous action queued a navigation (form submit, link click,/// Enter on an input), drive the runner until it completes or times out.-fn awaitQueuedNavigation(session: *lp.Session) ToolError!void {+fn awaitQueuedNavigation(session: *lp.Session, frame_id: u32) ToolError!void {const navigated = session.processQueuedNavigation() catch return ToolError.InternalError;if (navigated == false) {return;}- var runner = session.runner(.{}) catch return ToolError.InternalError;- runner.wait(.{ .ms = 10000, .until = .done }) catch |err|+ var runner = session.runner(.{});+ runner.waitForFrame(frame_id, 10000, .{ .until = .done }) catch |err|return if (err == error.Cancelled) ToolError.Cancelled else ToolError.NavigationFailed;}@@ -1446,7 +1444,9 @@ fn formatActionResult(/// caller (LLM, MCP client) can see whether the action triggered navigation.fn finalizeAction(arena: std.mem.Allocator, session: *lp.Session, registry: *CDPNode.Registry, body: []const u8) ToolError![]const u8 {const before = session.currentFrame();- try awaitQueuedNavigation(session);+ if (before) |b| {+ try awaitQueuedNavigation(session, b._frame_id);+ }const page = try requireFrame(session);// A queued navigation that swaps the root frame tears down the previous// Page (`Session.replaceRootImmediate` / `commitPendingPage`), so every@@ -1521,11 +1521,11 @@ fn execWaitForSelector(arena: std.mem.Allocator, session: *lp.Session, registry:};const args = try parseArgs(Params, arena, arguments);- _ = try requireFrame(session);+ const frame = try requireFrame(session);const timeout_ms = args.timeout orelse default_wait_timeout_ms;- const node = lp.actions.waitForSelector(args.selector, timeout_ms, session) catch |err| switch (err) {+ const node = lp.actions.waitForSelector(args.selector, timeout_ms, frame._frame_id, session) catch |err| switch (err) {error.InvalidSelector => return ToolError.InvalidParams,error.Cancelled => return ToolError.Cancelled,// Timeout w/o a match: same outcome as `/hover selector=…` on a missing@@ -1548,11 +1548,11 @@ fn execWaitForScript(arena: std.mem.Allocator, session: *lp.Session, arguments:};const args = try parseArgs(Params, arena, arguments);- _ = try requireFrame(session);+ const frame = try requireFrame(session);const timeout_ms = args.timeout orelse default_wait_timeout_ms;- lp.actions.waitForScript(args.script, timeout_ms, session) catch |err| switch (err) {+ lp.actions.waitForScript(args.script, timeout_ms, frame._frame_id, session) catch |err| switch (err) {error.Cancelled => return ToolError.Cancelled,error.Timeout => return ToolError.Timeout,error.ScriptError => return ToolError.InvalidParams,@@ -1564,7 +1564,7 @@ fn execWaitForScript(arena: std.mem.Allocator, session: *lp.Session, arguments:// script may have queued a navigation (e.g. top.location=…); drain it so// the next command reads post-navigation state- try awaitQueuedNavigation(session);+ try awaitQueuedNavigation(session, frame._frame_id);return "Script returned truthy.";}@@ -1576,11 +1576,11 @@ fn execWaitForState(arena: std.mem.Allocator, session: *lp.Session, arguments: ?};const args = try parseArgs(Params, arena, arguments);- _ = try requireFrame(session);+ const frame = try requireFrame(session);const timeout_ms = args.timeout orelse default_wait_timeout_ms;- lp.actions.waitForState(args.state, timeout_ms, session) catch |err| switch (err) {+ lp.actions.waitForState(args.state, timeout_ms, frame._frame_id, session) catch |err| switch (err) {error.Cancelled => return ToolError.Cancelled,error.Timeout => return ToolError.Timeout,else => {@@ -1840,11 +1840,12 @@ fn performGoto(session: *lp.Session, registry: *CDPNode.Registry, url: [:0]const.kind = .{ .push = null },}) catch return ToolError.NavigationFailed;- var runner = session.runner(.{}) catch return ToolError.NavigationFailed;- const result = runner.waitResult(.{- .ms = timeout orelse 10000,- .until = default_nav_wait,- }) catch |err| return if (err == error.Cancelled) ToolError.Cancelled else ToolError.NavigationFailed;+ var runner = session.runner(.{});+ const condition = lp.Session.Runner.WaitCondition{ .frame_id = page.frame_id, .until = default_nav_wait };+ var conditions = [_]lp.Session.Runner.WaitCondition{condition};+ const result = runner.waitResult(timeout orelse 10000, &conditions) catch |err| {+ return if (err == error.Cancelled) ToolError.Cancelled else ToolError.NavigationFailed;+ };// re-fetch frame, navigate might have changed it.const frame = page.frame() orelse return ToolError.NavigationFailed;diff --git a/src/browser/webapi/navigation/Navigation.zig b/src/browser/webapi/navigation/Navigation.zigindex 0ce614380..d50874882 100644--- a/src/browser/webapi/navigation/Navigation.zig+++ b/src/browser/webapi/navigation/Navigation.zig@@ -503,9 +503,7 @@ test "Navigation: about:blank commits entry" {testing.test_session.navigation._index = 0;try frame.navigate("about:blank", .{});-- var runner = try testing.test_session.runner(.{});- try runner.wait(.{ .ms = 1000 });+ try testing.waitForFrame();// about:blank / blob: handling in Frame.navigate bypasses rameDoneCallback,// so commitNavigation never runs and _entries stays empty. Reading@@ -535,9 +533,7 @@ test "Navigation: reload on empty stack seeds an entry" {// .reload, so without the empty-stack guard this would assert// `len: 0` in getCurrentEntry.try frame.navigate("about:blank", .{ .kind = .reload });-- var runner = try testing.test_session.runner(.{});- try runner.wait(.{ .ms = 1000 });+ try testing.waitForFrame();var ls: js.Local.Scope = undefined;frame.js.localScope(&ls);diff --git a/src/cdp/CDP.zig b/src/cdp/CDP.zigindex 77041f5d7..8c780163e 100644--- a/src/cdp/CDP.zig+++ b/src/cdp/CDP.zig@@ -264,8 +264,9 @@ pub fn tick(self: *CDP) !bool {fn pageWait(self: *CDP, ms: u32) !void {const bc = &(self.browser_context orelse return error.NoPage);- var runner = try bc.session.runner(.{});- return runner.waitCDP(.{ .ms = ms });+ const page = bc.page_handle orelse return error.NoPage;+ var runner = bc.session.runner(.{});+ return runner.waitForFrameCDP(page.frame_id, ms, .done);}// Parse-then-dispatch entry point. Used by:diff --git a/src/cdp/domains/browser.zig b/src/cdp/domains/browser.zigindex 3eb29cb56..9d66082fd 100644--- a/src/cdp/domains/browser.zig+++ b/src/cdp/domains/browser.zig@@ -390,8 +390,7 @@ test "cdp.browser: setDownloadBehavior writes an attachment to disk and emits evconst frame = (try bc.session.createPage()).frame().?;try frame.navigate("http://127.0.0.1:9582/download/report.csv", .{});- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);// The guid is random, so it's omitted from these subset matches.try ctx.expectSentEvent("Browser.downloadWillBegin", .{diff --git a/src/cdp/domains/input.zig b/src/cdp/domains/input.zigindex 44994deba..88f808302 100644--- a/src/cdp/domains/input.zig+++ b/src/cdp/domains/input.zig@@ -160,8 +160,7 @@ test "cdp.input: dispatchMouseEvent mouseMoved fires hover events" {const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);var ls: lp.js.Local.Scope = undefined;frame.js.localScope(&ls);@@ -202,8 +201,7 @@ test "cdp.input: dispatchMouseEvent mouseReleased fires mouseup" {const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);var ls: lp.js.Local.Scope = undefined;frame.js.localScope(&ls);@@ -241,8 +239,7 @@ test "cdp.input: dispatchMouseEvent mouseWheel fires wheel event" {const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);var ls: lp.js.Local.Scope = undefined;frame.js.localScope(&ls);@@ -280,8 +277,7 @@ test "cdp.input: dispatchMouseEvent right button fires contextmenu, double-clickconst url = "http://localhost:9582/src/browser/tests/mcp_actions.html";try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);var ls: lp.js.Local.Scope = undefined;frame.js.localScope(&ls);@@ -334,8 +330,7 @@ test "cdp.input: dispatchKeyEvent Tab runs sequential focus navigation" {const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);var ls: lp.js.Local.Scope = undefined;frame.js.localScope(&ls);diff --git a/src/cdp/domains/lp.zig b/src/cdp/domains/lp.zigindex 43c615e2b..be69776be 100644--- a/src/cdp/domains/lp.zig+++ b/src/cdp/domains/lp.zig@@ -321,12 +321,12 @@ fn waitForSelector(cmd: anytype) !void {const params = (try cmd.params(Params)) orelse return error.InvalidParam;const bc = cmd.browser_context orelse return error.NoBrowserContext;- _ = bc.mainFrame() orelse return error.FrameNotLoaded;+ const frame = bc.mainFrame() orelse return error.FrameNotLoaded;const timeout_ms = params.timeout orelse 5000;const selector_z = try cmd.arena.dupeZ(u8, params.selector);- const node = lp.actions.waitForSelector(selector_z, timeout_ms, bc.session) catch |err| {+ const node = lp.actions.waitForSelector(selector_z, timeout_ms, frame._frame_id, bc.session) catch |err| {if (err == error.InvalidSelector) return error.InvalidParam;if (err == error.Timeout) return error.InternalError;return error.InternalError;@@ -463,8 +463,7 @@ test "cdp.lp: action tools" {const url = "http://localhost:9582/src/browser/tests/mcp_actions.html";try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);// Test Clickconst btn = frame.document.getElementById("btn", frame).?.asNode();@@ -526,8 +525,7 @@ test "cdp.lp: waitForSelector" {const url = "http://localhost:9582/src/browser/tests/mcp_wait_for_selector.html";try frame.navigate(url, .{ .reason = .address_bar, .kind = .{ .push = null } });- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);// 1. Existing elementtry ctx.processMessage(.{diff --git a/src/cdp/domains/page.zig b/src/cdp/domains/page.zigindex 808a2fa70..155dc2d4d 100644--- a/src/cdp/domains/page.zig+++ b/src/cdp/domains/page.zig@@ -1164,15 +1164,13 @@ test "cdp.frame: reload" {// reload with no params — should not error (navigation is async,// so no result is sent synchronously; we just verify no error)try ctx.processMessage(.{ .id = 31, .method = "Page.reload" });- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);}{// reload with ignoreCache paramtry ctx.processMessage(.{ .id = 32, .method = "Page.reload", .params = .{ .ignoreCache = true } });- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);}}@@ -1197,8 +1195,7 @@ test "cdp.frame: reload replays POST navigation" {.body = "key=value",.header = "Content-Type: application/x-www-form-urlencoded",});- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);}// Sanity: the body confirms a POST round-tripped.@@ -1215,11 +1212,7 @@ test "cdp.frame: reload replays POST navigation" {// prior POST method/body/header and replays them. Without it (regression// guard), the second request would silently fall back to GET.try ctx.processMessage(.{ .id = 50, .method = "Page.reload" });-- {- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });- }+ try testing.waitForPage(bc);{const f = bc.mainFrame() orelse unreachable;@@ -1254,8 +1247,7 @@ test "cdp.frame: reload after POST→redirect drops the POST" {.body = "key=value",.header = "Content-Type: application/x-www-form-urlencoded",});- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);}// Sanity: after the redirect, the loaded page is /echo_method via GET.@@ -1271,11 +1263,7 @@ test "cdp.frame: reload after POST→redirect drops the POST" {// Reload. The request that produced the current page was GET, so the// reload must also be GET — not a re-POST of the original form data.try ctx.processMessage(.{ .id = 60, .method = "Page.reload" });-- {- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });- }+ try testing.waitForPage(bc);{const f = bc.mainFrame() orelse unreachable;@@ -1302,9 +1290,7 @@ test "cdp.frame: navigate inherits original fragment across redirect" {.method = "Page.navigate",.params = .{ .url = "http://127.0.0.1:9582/redirect-no-fragment#myfrag" },});-- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);const frame = bc.mainFrame() orelse unreachable;try testing.expectEqualSlices(u8, "http://127.0.0.1:9582/redirect-target#myfrag", frame.url);@@ -1317,9 +1303,7 @@ test "cdp.frame: navigate inherits original fragment across redirect" {.method = "Page.navigate",.params = .{ .url = "http://127.0.0.1:9582/redirect-with-fragment#requested" },});-- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);const frame = bc.mainFrame() orelse unreachable;try testing.expectEqualSlices(u8, "http://127.0.0.1:9582/redirect-target#target_fragment", frame.url);@@ -1332,9 +1316,7 @@ test "cdp.frame: navigate inherits original fragment across redirect" {.method = "Page.navigate",.params = .{ .url = "http://127.0.0.1:9582/redirect-no-fragment" },});-- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);const frame = bc.mainFrame() orelse unreachable;try testing.expectEqualSlices(u8, "http://127.0.0.1:9582/redirect-target", frame.url);@@ -1355,9 +1337,7 @@ test "cdp.frame: navigate renders body of 3xx response without Location" {.method = "Page.navigate",.params = .{ .url = "http://127.0.0.1:9582/303-no-location" },});-- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);const frame = bc.mainFrame() orelse unreachable;try testing.expectEqualSlices(u8, "http://127.0.0.1:9582/303-no-location", frame.url);@@ -1384,9 +1364,7 @@ test "cdp.frame: navigate does not follow Location on a non-redirect 3xx" {.method = "Page.navigate",.params = .{ .url = "http://127.0.0.1:9582/300-with-location" },});-- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);const frame = bc.mainFrame() orelse unreachable;try testing.expectEqualSlices(u8, "http://127.0.0.1:9582/300-with-location", frame.url);@@ -1414,9 +1392,7 @@ test "cdp.frame: navigate answers with errorText when the navigation fails" {.method = "Page.navigate",.params = .{ .url = "http://127.0.0.1:1/unreachable" },});-- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);// The pending page was discarded; the active document is untouched.const frame = bc.mainFrame() orelse unreachable;@@ -1447,10 +1423,7 @@ test "cdp.frame: navigate to about:blank replaces a non-blank document" {}try ctx.processMessage(.{ .id = 70, .method = "Page.navigate", .params = .{ .url = "about:blank" } });- {- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });- }+ try testing.waitForPage(bc);// The active frame must now point at the replaced about:blank document.const frame = bc.mainFrame() orelse unreachable;@@ -1485,8 +1458,7 @@ test "cdp.frame: anchor click sends Referer matching the originating page" {{const page = try bc.session.createPage();try page.navigate("http://127.0.0.1:9582/referer_link.html", .{});- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);}// Click the anchor via JS. The click goes through Frame.scheduleNavigation@@ -1498,8 +1470,7 @@ test "cdp.frame: anchor click sends Referer matching the originating page" {f.js.localScope(&ls);defer ls.deinit();_ = try ls.local.exec("document.getElementById('link').click()", null);- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);}// After the click navigation completes, the loaded page is /echo_referer@@ -1534,8 +1505,7 @@ test "cdp.frame: address-bar Page.navigate sends no Referer" {{const page = try bc.session.createPage();try page.navigate("http://127.0.0.1:9582/echo_referer", .{});- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);}{@@ -1623,8 +1593,7 @@ test "cdp.frame: getNavigationHistory + navigateToHistoryEntry" {.method = "Page.navigate",.params = .{ .url = "http://127.0.0.1:9582/src/browser/tests/cdp/dom2.html" },});- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);}{try ctx.processMessage(.{@@ -1632,8 +1601,7 @@ test "cdp.frame: getNavigationHistory + navigateToHistoryEntry" {.method = "Page.navigate",.params = .{ .url = "http://127.0.0.1:9582/src/browser/tests/cdp/dom3.html" },});- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);}// Three entries (ids 0, 1, 2), currentIndex points at the most-recent.@@ -1674,8 +1642,7 @@ test "cdp.frame: getNavigationHistory + navigateToHistoryEntry" {.method = "Page.navigateToHistoryEntry",.params = .{ .entryId = 0 },});- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);const f = bc.mainFrame() orelse unreachable;try testing.expectEqualSlices(u8, "http://127.0.0.1:9582/src/browser/tests/cdp/dom1.html", f.url);@@ -1688,8 +1655,7 @@ test "cdp.frame: getNavigationHistory + navigateToHistoryEntry" {.method = "Page.navigateToHistoryEntry",.params = .{ .entryId = 1 },});- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try testing.waitForPage(bc);const f = bc.mainFrame() orelse unreachable;try testing.expectEqualSlices(u8, "http://127.0.0.1:9582/src/browser/tests/cdp/dom2.html", f.url);diff --git a/src/cdp/testing.zig b/src/cdp/testing.zigindex d8acc2929..bed8a4ff2 100644--- a/src/cdp/testing.zig+++ b/src/cdp/testing.zig@@ -102,8 +102,7 @@ const TestContext = struct {0,);try page.navigate(full_url, .{});- var runner = try bc.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ try waitForPage(bc);}return bc;}@@ -205,8 +204,8 @@ const TestContext = struct {if (self.cdp_.browser_context) |*bc| {if (bc.session.hasPage()) {- var runner = try bc.session.runner(.{});- _ = try runner.tick(.{ .ms = 1000 });+ var runner = bc.session.runner(.{});+ _ = try runner.tickForFrame(bc.page_handle.?.frame_id, 1000, .{ .until = .done });}}std.Thread.sleep(5 * std.time.ns_per_ms);@@ -319,3 +318,8 @@ pub fn context() !TestContext {.socket = pair[0],};}++pub fn waitForPage(bc: *CDP.BrowserContext) !void {+ var runner = bc.session.runner(.{});+ try runner.waitForFrame(bc.page_handle.?.frame_id, 2000, .{ .until = .done });+}diff --git a/src/lightpanda.zig b/src/lightpanda.zigindex 39e6aff9d..59519a407 100644--- a/src/lightpanda.zig+++ b/src/lightpanda.zig@@ -110,31 +110,43 @@ pub fn fetch(app: *App, browser: *Browser, url: [:0]const u8, opts: FetchOpts) !.kind = .{ .push = null },});}- var runner = try session.runner(.{});+ var runner = session.runner(.{});var timer = try std.time.Timer.start();if (opts.wait_until) |wu| {- try runner.wait(.{ .ms = opts.wait_ms, .until = wu });+ try runner.waitForAll(opts.wait_ms, .{ .until = wu });} else if (opts.wait_selector == null and opts.wait_script == null) {// We default to .done if both wait_selector and wait_script are null// This allows the caller to ONLY --wait-selector or ONLY --wait-script// or combine --wait-until WITH --wait-selector/script- try runner.wait(.{ .ms = opts.wait_ms, .until = .done });+ try runner.waitForAll(opts.wait_ms, .{ .until = .done });}if (opts.wait_selector) |selector| {const elapsed: u32 = @intCast(timer.read() / std.time.ns_per_ms);const remaining = opts.wait_ms -| elapsed;- if (remaining == 0) return error.Timeout;- _ = try runner.waitForSelector(selector, remaining);+ if (remaining == 0) {+ return error.Timeout;+ }+ for (session.pages.items) |p| {+ if (p.replacement == null) {+ _ = try runner.waitForSelector(p.frame._frame_id, selector, remaining);+ }+ }}if (opts.wait_script) |wait_script| {const elapsed: u32 = @intCast(timer.read() / std.time.ns_per_ms);const remaining = opts.wait_ms -| elapsed;- if (remaining == 0) return error.Timeout;- try runner.waitForScript(wait_script, remaining);+ if (remaining == 0) {+ return error.Timeout;+ }+ for (session.pages.items) |p| {+ if (p.replacement == null) {+ try runner.waitForScript(p.frame._frame_id, wait_script, remaining);+ }+ }}const writer = opts.writer orelse return;diff --git a/src/mcp/tools.zig b/src/mcp/tools.zigindex 0fd86c1e7..f03cc35f5 100644--- a/src/mcp/tools.zig+++ b/src/mcp/tools.zig@@ -1365,7 +1365,7 @@ fn testLoadPage(url: [:0]const u8, writer: *std.Io.Writer) !*Server {const page = try server.session.createPage();try page.navigate(url, .{});- var runner = try server.session.runner(.{});- try runner.wait(.{ .ms = 2000 });+ var runner = server.session.runner(.{});+ try runner.waitForFrame(page.frame_id, 2000, .{ .until = .done });return server;}diff --git a/src/testing.zig b/src/testing.zigindex 35dba8296..a4ee48eb7 100644--- a/src/testing.zig+++ b/src/testing.zig@@ -336,6 +336,13 @@ pub var test_browser: Browser = undefined;pub var test_notification: *Notification = undefined;pub var test_session: *Session = undefined;+const WEB_API_TEST_ROOT = "src/browser/tests/";+const HtmlRunnerOpts = struct {+ timeout_ms: u32 = 2000,+ inject_script: ?[]const u8 = null,+ load_external_stylesheets: bool = false,+};+// Create a fresh page on `test_session` and return its root frame — for tests// that just need a frame to build a DOM in. The page lives on the session;// release it with `defer testing.test_session.closeAllPages()`.@@ -343,12 +350,11 @@ pub fn createFrame() !*Frame {return (try test_session.createPage()).frame().?;}-const WEB_API_TEST_ROOT = "src/browser/tests/";-const HtmlRunnerOpts = struct {- timeout_ms: u32 = 2000,- inject_script: ?[]const u8 = null,- load_external_stylesheets: bool = false,-};+pub fn waitForFrame() !void {+ var runner = test_session.runner(.{});+ const frame_id = test_session.pages.items[0].frame._frame_id;+ return runner.waitForFrame(frame_id, 2000, .{ .until = .done });+}pub fn htmlRunner(comptime path: []const u8, opts: HtmlRunnerOpts) !void {defer reset();@@ -436,8 +442,8 @@ fn runWebApiTest(test_file: [:0]const u8, timeout_ms: u32) !void {try frame.navigate(url, .{});}- var runner = try test_session.runner(.{});- try runner.wait(.{ .ms = 2000, .until = .load });+ var runner = test_session.runner(.{});+ try runner.waitForFrame(page.frame_id, 2000, .{ .until = .load });var wait_ms: u32 = timeout_ms;var timer = try std.time.Timer.start();@@ -454,7 +460,7 @@ fn runWebApiTest(test_file: [:0]const u8, timeout_ms: u32) !void {if (js_val.isTrue()) {return;}- const sleep_ms: usize = switch (try runner.tick(.{ .ms = 20 })) {+ const sleep_ms: usize = switch (try runner.tickForFrame(page.frame_id, 20, .{ .until = .done })) {.done => 20,.ok => |next_ms| @min(next_ms, 20),};@@ -484,9 +490,9 @@ pub fn pageTest(comptime test_file: []const u8, opts: PageTestOpts) !Session.Pag);try page.navigate(url, .{});- var runner = try test_session.runner(.{});if (opts.wait_until_done) {- try runner.wait(.{ .ms = 2000 });+ var runner = test_session.runner(.{});+ try runner.waitForFrame(page.frame_id, 2000, .{ .until = .done });}return page;}