Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(cdp): keep DOM agent commands available while paused

ldm075b191092d17
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.md
index c0b2b41e6..05b91aaea 100644
--- a/moli-cdp-smoke/README.md
+++ b/moli-cdp-smoke/README.md
@@ -35,6 +35,10 @@ separate `urlFragment` field; Moli currently includes the fragment in `url`.
Deferred Promise evaluation must allow its later resolver to run,
ordinary pause must allow native queries and synchronous focus callback reentry,
and instrumentation pause must leave Main work pending while IO remains live.
+`DOM.getNodeForLocation`, `DOM.getNodeStackTraces`,
+`DOM.setNodeStackTracesEnabled`, and `DOM.disable` must also complete through
+their frontend native wrappers before the client sends resume. Disabling must
+invalidate the original node bindings while the outer evaluation stays paused.
All scenarios use local fixture documents, match the navigation's loader and
`DOMContentLoaded` before setup, track the original response session
and exactly one terminal per command, retain the full wire transcript, and use
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/cdp_ordering.py b/moli-cdp-smoke/moli_cdp_smoke/groups/cdp_ordering.py
index 5413c78aa..61ea9de66 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/cdp_ordering.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/cdp_ordering.py
@@ -18,7 +18,7 @@ from ..assertions import SmokeError, assert_equal, record_contract
from ..raw_cdp import RawCdpClient, connect_raw_cdp, discover_websocket_url
-CHROMIUM_SOURCE = "Chromium 145.0.7632.116 raw CDP calibration, 2026-09-30"
+CHROMIUM_SOURCE = "Chromium 145.0.7632.116 raw CDP calibration, 2026-10-01"
@dataclass
@@ -282,6 +282,42 @@ async def _normal_pause(wire: _Wire, page: _Page, _is_moli: bool) -> dict[str, A
return {"nestedReplyIndexes": [wire.index(rid) for rid in ids], "outerReplyIndex": wire.index(outer)}
+async def _paused_dom_agent(wire: _Wire, page: _Page, _is_moli: bool) -> dict[str, Any]:
+ point = await wire.evaluate(page.session,
+ "(() => { const r = document.getElementById('probe').getBoundingClientRect();"
+ "return {x: Math.floor(r.left + r.width / 2), y: Math.floor(r.top + r.height / 2)}; })()")
+ node = await wire.call("DOM.describeNode", {"nodeId": page.node}, page.session)
+ outer = await _pause(wire, page)
+ commands = [
+ ("DOM.getNodeForLocation", point),
+ ("DOM.getNodeStackTraces", {"nodeId": page.node}),
+ ("DOM.setNodeStackTracesEnabled", {"enable": True}),
+ ("DOM.disable", {}),
+ ]
+ ids = [await wire.send(method, params, page.session) for method, params in commands]
+ replies = [await wire.response(rid) for rid in ids]
+ assert_equal(replies[0]["result"]["backendNodeId"], node["node"]["backendNodeId"],
+ "paused hit test finds the fixture input")
+ assert_equal(replies[0]["result"]["frameId"], page.frame, "paused hit test frame")
+ for reply, (method, _params) in zip(replies[1:], commands[1:]):
+ assert_equal(reply["result"], {}, f"{method} completes during ordinary pause")
+ # Disabling must clear the old frontend bindings before acknowledging it.
+ stale = await wire.send("DOM.getAttributes", {"nodeId": page.node}, page.session)
+ stale_reply = await wire.response(stale, allow_error=True)
+ assert_equal(stale_reply.get("error", {}).get("code"), -32000,
+ "DOM.disable invalidates the original frontend node while paused")
+ if wire.has_response(outer):
+ raise SmokeError("DOM agent inspection must leave the outer evaluation paused")
+ # All four actual SessionSink replies must arrive before the client even
+ # sends resume. A typed backend query would miss the native-wrapper bug.
+ resume_send_index = len(wire.trace)
+ await wire.call("Debugger.resume", session=page.session)
+ reply = await wire.response(outer)
+ assert_equal(reply["result"]["result"].get("value"), 42, "outer evaluation resumes once")
+ return {"pausedReplyIndexes": [wire.index(rid) for rid in ids],
+ "resumeSendTraceIndex": resume_send_index, "outerReplyIndex": wire.index(outer)}
+
+
async def _instrumentation_pause(wire: _Wire, page: _Page, _is_moli: bool) -> dict[str, Any]:
outer = await _pause(wire, page, instrumentation=True)
query = await wire.send("Page.getFrameTree", session=page.session)
@@ -365,6 +401,7 @@ async def run_cdp_ordering_group(endpoint: str, fixture_url: str, results: list[
("isolated_world_notification_prefix", _world_prefix),
("deferred_reply_later_resolver", _deferred_reply),
("normal_pause_native_queries", _normal_pause),
+ ("normal_pause_dom_agent_commands", _paused_dom_agent),
("instrumentation_pause_io_only", _instrumentation_pause),
("native_focus_callback_reentry", _focus_reentry),
("paused_dom_attribute", _paused_mutation),
diff --git a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
index f9983011c..5a4ad218b 100644
--- a/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
+++ b/moli-protocol-server/src/protocol_server/tests/cdp_dynamic_page.rs
@@ -887,6 +887,164 @@ async fn cdp_ordering_normal_pause_allows_nested_main() {
assert_pause_command_ordering(false).await;
}
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn cdp_ordering_dom_agent_frontend_commands_complete_before_resume() {
+ let (fixture_addr, _fixture) = spawn_dedicated_fixture_server(
+ Router::new().route("/page", get(|| async {
+ axum::response::Html("<!doctype html><style>#probe {width:100px;height:100px}</style><div id=probe>probe</div>")
+ })),
+ "native-paused-dom-agent",
+ );
+ let (addr, server) = spawn_test_protocol_server().await;
+ let (mut browser, _) =
+ connect_async(format!("ws://{addr}/devtools/browser/{DEFAULT_BROWSER_ID}"))
+ .await
+ .unwrap();
+ let context = cdp_create_browser_context(&mut browser, 1).await;
+ let target = cdp_create_attached_target(&mut browser, 2, &context).await;
+ let session = Some(target.session_id.as_str());
+ navigate_fixture_document(
+ &mut browser,
+ 4,
+ &target,
+ &format!("http://{fixture_addr}/page"),
+ )
+ .await;
+ let document = send_cdp_command(&mut browser, 5, "DOM.getDocument", session, json!({})).await;
+ let query = send_cdp_command(
+ &mut browser,
+ 6,
+ "DOM.querySelector",
+ session,
+ json!({
+ "nodeId": response_by_id(&document, 5)["result"]["root"]["nodeId"], "selector": "#probe"
+ }),
+ )
+ .await;
+ let node = response_by_id(&query, 6)["result"]["nodeId"]
+ .as_u64()
+ .unwrap();
+ let describe = send_cdp_command(
+ &mut browser,
+ 7,
+ "DOM.describeNode",
+ session,
+ json!({"nodeId": node}),
+ )
+ .await;
+ let backend = response_by_id(&describe, 7)["result"]["node"]["backendNodeId"].clone();
+ let geometry = send_cdp_command(&mut browser, 8, "Runtime.evaluate", session, json!({
+ "expression": "(() => { const r = document.getElementById('probe').getBoundingClientRect(); return {x: Math.floor(r.left + r.width / 2), y: Math.floor(r.top + r.height / 2)}; })()",
+ "returnByValue": true
+ })).await;
+ let point = response_by_id(&geometry, 8)["result"]["result"]["value"].clone();
+ assert!(point["x"].is_number() && point["y"].is_number());
+ let enabled = send_cdp_command(&mut browser, 10, "Debugger.enable", session, json!({})).await;
+ assert!(response_by_id(&enabled, 10)["error"].is_null());
+ send_cdp_command_without_wait(
+ &mut browser,
+ 12,
+ "Runtime.evaluate",
+ session,
+ json!({
+ "expression": "(() => { debugger; return 42; })()", "returnByValue": true
+ }),
+ )
+ .await;
+ let paused = recv_until_match(&mut browser, |message| {
+ message["sessionId"] == target.session_id && message["method"] == "Debugger.paused"
+ })
+ .await;
+ assert!(paused.iter().all(|message| message["id"] != 12));
+
+ // Exercise the frontend SessionSink wrappers: the typed backend commands
+ // were already PageAgent, while their native wrappers incorrectly waited
+ // for the suspended outer evaluation to return. Do not send resume until
+ // every one of these actual wire replies has arrived.
+ let commands = [
+ (100, "DOM.getNodeForLocation", point),
+ (101, "DOM.getNodeStackTraces", json!({"nodeId": node})),
+ (
+ 102,
+ "DOM.setNodeStackTracesEnabled",
+ json!({"enable": true}),
+ ),
+ (103, "DOM.disable", json!({})),
+ ];
+ for (id, method, params) in &commands {
+ send_cdp_command_without_wait(&mut browser, *id, method, session, params.clone()).await;
+ }
+ let mut completed = std::collections::HashSet::new();
+ let inspected = recv_until_match(&mut browser, |message| {
+ if message["sessionId"] == target.session_id
+ && let Some(id) = message["id"].as_u64()
+ {
+ assert!(completed.insert(id), "duplicate terminal: {message}");
+ }
+ commands.iter().all(|(id, _, _)| completed.contains(id))
+ })
+ .await;
+ assert!(
+ inspected.iter().all(|message| message["id"] != 12
+ && !(message["sessionId"] == target.session_id
+ && message["method"] == "Debugger.resumed")),
+ "DOM inspection must retain the paused outer evaluation: {inspected:#?}"
+ );
+ for (id, method, _) in &commands {
+ let response = response_by_id(&inspected, *id);
+ assert_eq!(response["sessionId"], target.session_id);
+ assert!(response["error"].is_null(), "{method}: {response}");
+ if *id == 100 {
+ assert_eq!(response["result"]["backendNodeId"], backend);
+ assert_eq!(response["result"]["frameId"], target.target_id);
+ } else {
+ assert_eq!(response["result"], json!({}), "{method}");
+ }
+ }
+ let stale = send_cdp_command(
+ &mut browser,
+ 14,
+ "DOM.getAttributes",
+ session,
+ json!({"nodeId": node}),
+ )
+ .await;
+ assert_eq!(
+ response_by_id(&stale, 14)["error"]["code"],
+ -32000,
+ "DOM.disable must invalidate the frontend node before acknowledging it"
+ );
+ assert!(stale.iter().all(|message| message["id"] != 12));
+ assert!(completed.insert(14));
+
+ send_cdp_command_without_wait(&mut browser, 15, "Debugger.resume", session, json!({})).await;
+ let resumed = recv_until_match(&mut browser, |message| {
+ if message["sessionId"] == target.session_id
+ && let Some(id) = message["id"].as_u64()
+ {
+ assert!(completed.insert(id), "duplicate terminal: {message}");
+ }
+ completed.contains(&12) && completed.contains(&15)
+ })
+ .await;
+ assert_eq!(
+ response_by_id(&resumed, 12)["result"]["result"]["value"],
+ 42
+ );
+ assert!(response_by_id(&resumed, 15)["error"].is_null());
+ let follower =
+ send_cdp_command(&mut browser, 16, "Page.getFrameTree", session, json!({})).await;
+ assert!(
+ follower.iter().all(|message| message["id"]
+ .as_u64()
+ .is_none_or(|id| !completed.contains(&id))),
+ "duplicate terminal: {follower:?}"
+ );
+ assert!(response_by_id(&follower, 16)["error"].is_null());
+ browser.close(None).await.unwrap();
+ abort_test_cdp_server(server).await;
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cdp_ordering_instrumentation_pause_only_allows_io() {
assert_pause_command_ordering(true).await;
diff --git a/moli-protocol/src/domains/dom/resolve/native.rs b/moli-protocol/src/domains/dom/resolve/native.rs
index b4ed0435c..db20a3933 100644
--- a/moli-protocol/src/domains/dom/resolve/native.rs
+++ b/moli-protocol/src/domains/dom/resolve/native.rs
@@ -87,10 +87,7 @@ fn prepare(
return files::prepare(conn, cmd).map(Operation::require_owner_turn);
}
if mutation::handles(action) {
- // DOM edits/focus may invoke custom elements and user handlers through
- // a new isolate scope. Their composed node lookup does not make that
- // scope safe to enter from a suspended outer V8 call.
- return mutation::prepare(conn, cmd, action).map(Operation::require_owner_turn);
+ return mutation::prepare(conn, cmd, action);
}
let owner = CommandOwnerScope::capture(conn, cmd.session_id);
let session = conn.target_renderer_runtime_inspector_session_id_for_owner(&owner);
diff --git a/moli-protocol/src/domains/dom/resolve/native/mutation.rs b/moli-protocol/src/domains/dom/resolve/native/mutation.rs
index 4f2964f1d..d30356bbb 100644
--- a/moli-protocol/src/domains/dom/resolve/native/mutation.rs
+++ b/moli-protocol/src/domains/dom/resolve/native/mutation.rs
@@ -40,6 +40,9 @@ pub(super) fn prepare(
DomAction::RemoveNode => {
let params =
build_cdp_remove_node_command(conn, cmd)?.ok_or_else(StartError::invalid_params)?;
+ // The first step only resolves a native node binding, but removal
+ // enters V8. Keep the complete chain on its owner turn; agent-only
+ // operations below inherit their backend entry requirement.
Ok(with_backend(session, params.reference, |backend_node_id| {
Operation::new(
Command::RemoveDocumentBackendNodeId { backend_node_id },
@@ -52,7 +55,8 @@ pub(super) fn prepare(
_ => unreachable!("DOM remove node reply"),
},
)
- }))
+ })
+ .require_owner_turn())
}
DomAction::Focus => {
let params: NodeReferenceParams = cmd
@@ -84,7 +88,8 @@ pub(super) fn prepare(
Command::FocusDocumentBackendNode { backend_node_id },
move |reply| focus(reply, missing),
)
- }))
+ })
+ .require_owner_turn())
}
}
DomAction::SetAttributeValue | DomAction::RemoveAttribute => {
@@ -125,7 +130,8 @@ pub(super) fn prepare(
attribute,
)
},
- ))
+ )
+ .require_owner_turn())
}
DomAction::MoveTo
| DomAction::SetAttributesAsText
@@ -168,7 +174,8 @@ pub(super) fn prepare(
},
scroll,
)
- }))
+ })
+ .require_owner_turn())
}
}
DomAction::GetNodeForLocation => {