Skip to main content

blitz_control_protocol/
in_process.rs

1//! The in-process transport: a request in, a response out, no socket.
2//!
3//! # Why there are two transports
4//!
5//! The core in [`crate::document`] answers a request against a document. How
6//! the request arrives is a separate question, and it has two answers.
7//!
8//! [`crate::server`] is one of them: a Unix socket, MCP framing, a listener on
9//! its own thread. That is how a QA harness and an agent outside the process
10//! reach a running application, and it is the transport eleven fleet sites are
11//! driven over.
12//!
13//! This is the other. An embedder that already holds the document calls
14//! straight in. There is no socket to bind, no descriptor to publish, no
15//! serialisation, and no second thread. AgencyZero is about to be both at once:
16//! agents drive it over the socket while it drives a browser it embeds, in
17//! process, through this.
18//!
19//! # What this adds over calling the core directly
20//!
21//! State that one request leaves for the next, and which the core deliberately
22//! does not hold: the document revision an `Inspect` reports, the pointer
23//! position an injected wheel event needs, which buttons an injected pointer is
24//! holding down, and the reusable offscreen surface a capture draws into.
25//!
26//! It also holds the action dispatch itself. That existed twice, once in the
27//! Tauri runtime and once in the headless browser, and the two had already
28//! diverged: one replaced a text field's contents by selecting them and the
29//! other by counting bytes, and only the second works with no font catalogue
30//! installed. See [`DocumentControl::act`].
31
32use blitz_traits::events::{
33    BlitzImeEvent, BlitzInputEvent, BlitzWheelDelta, BlitzWheelEvent, BlitzWheelPhase, DomEvent,
34    DomEventData, MouseEventButton, MouseEventButtons, Point, UiEvent,
35};
36use keyboard_types::{Code, Key};
37
38use crate::document::{
39    activate_agent_node, control_error, debug_error, element_attr, hover_agent_node,
40    inspect_document, key_event, keyboard_modifiers, resolve_agent_node,
41};
42use crate::{
43    AgentAction, AgentControlRequest, DebugError, DebugResponse, InputCommand, KeyPhase,
44    PointerPhase, WheelPhase,
45};
46
47/// How many polls an action gets to settle before it is reported as unsettled.
48///
49/// DOM event handlers enqueue a reactive framework.s work on the document poll
50/// hook. Acknowledging before that hook runs makes the next `Inspect` observe
51/// the tree from before the click, and a tight harness loop keeps reading that
52/// stale tree until it disconnects.
53///
54/// Timers and animation frames remain asynchronous and are observed normally.
55/// A poll hook that stays runnable is different: reporting the exhaustion lets
56/// a caller fail the interaction instead of compensating with a sleep.
57pub(crate) const MAX_SETTLE_POLLS: usize = 100;
58
59/// One document, driven in process.
60///
61/// Not `Send`: a `blitz-dom` document is not, and neither is anything that
62/// carries one. The socket transport crosses that boundary with a channel
63/// rather than by making the document shareable, which is why
64/// [`crate::server::ControlBridge`] is a closure returning a receiver.
65#[derive(Default)]
66pub struct DocumentControl {
67    revision: u64,
68    /// Where the last action left the pointer.
69    ///
70    /// A wheel event carries no coordinates and is delivered to whatever the
71    /// document last saw hovered. Without this, injected scrolling had no
72    /// target and moved nothing, which reads as an accepted command that did
73    /// not happen.
74    pointer: (f32, f32),
75    buttons: MouseEventButtons,
76    #[cfg(feature = "capture")]
77    capture: crate::document::DocumentCapture,
78}
79
80impl DocumentControl {
81    pub fn new() -> Self {
82        Self::default()
83    }
84
85    /// The revision the last `Inspect` or action reported.
86    ///
87    /// A host that also serves diagnostics stamps its snapshots with this, so
88    /// the two surfaces agree about which version of the document a client is
89    /// looking at.
90    pub fn revision(&self) -> u64 {
91        self.revision
92    }
93
94    /// Advance the revision without answering a request.
95    ///
96    /// A diagnostic snapshot is a second reader of the same document and
97    /// carries the same counter.
98    pub fn next_revision(&mut self) -> u64 {
99        self.revision += 1;
100        self.revision
101    }
102
103    /// Where an injected pointer currently is.
104    pub fn pointer(&self) -> (f32, f32) {
105        self.pointer
106    }
107
108    /// Answer one agent-control request.
109    ///
110    /// `Inspect` reads the tree. `Act` performs the action, settles the
111    /// synchronous script work it caused, and acknowledges. `Navigate`,
112    /// `Relaunch` and `Quit` are refused here on purpose: they need a loader
113    /// or a process, and only the embedder that started it can honour them.
114    pub fn agent(
115        &mut self,
116        document: &mut (impl crate::ControlScriptBackend + ?Sized),
117        request: AgentControlRequest,
118    ) -> DebugResponse {
119        match request {
120            AgentControlRequest::Inspect { root, max_depth } => {
121                self.revision += 1;
122                inspect_document(document, root, max_depth, self.revision)
123            }
124            AgentControlRequest::Act(action) => match self.act(document, action) {
125                Ok(()) => match settle(document) {
126                    Ok(()) => {
127                        self.revision += 1;
128                        DebugResponse::Ack
129                    }
130                    Err(error) => DebugResponse::Error(error),
131                },
132                Err(error) => DebugResponse::Error(error),
133            },
134            AgentControlRequest::Condense { level, options } => {
135                self.revision += 1;
136                match inspect_document(document, None, 0, self.revision) {
137                    DebugResponse::AgentSnapshot(snapshot) => {
138                        let page = crate::condense::condense(&snapshot.nodes, options);
139                        DebugResponse::Condensation(level.select(page))
140                    }
141                    _ => control_error(
142                        "unsupportedRequest",
143                        "the document has no semantic tree to condense",
144                    ),
145                }
146            }
147            AgentControlRequest::ListTargets
148            | AgentControlRequest::Navigate { .. }
149            | AgentControlRequest::Relaunch
150            | AgentControlRequest::Quit => control_error(
151                "unsupportedRequest",
152                "navigation and process lifecycle belong to the embedder, not to the document",
153            ),
154        }
155    }
156
157    /// Perform one action, without settling and without acknowledging.
158    ///
159    /// Separate from [`Self::agent`] because settling is the host's business:
160    /// a windowed runtime drains the poll hook, and a headless host that owns
161    /// an animation clock has to advance that too before the document is
162    /// stable. Both want the same actions.
163    pub fn act(
164        &mut self,
165        document: &mut (impl crate::ControlScriptBackend + ?Sized),
166        action: AgentAction,
167    ) -> Result<(), DebugError> {
168        match action {
169            AgentAction::Focus { node_id } => {
170                crate::document::focus_agent_node(document, blitz_dom::NodeId::from_u64(node_id))?;
171            }
172            AgentAction::Click { node_id } => {
173                self.pointer = activate_agent_node(document, node_id, 1)?;
174            }
175            AgentAction::DoubleClick { node_id } => {
176                self.pointer = activate_agent_node(document, node_id, 2)?;
177            }
178            AgentAction::Hover { node_id } => {
179                // Resolved first so the pointer is recorded even though the
180                // move is dispatched at the node rather than by coordinate.
181                self.pointer = resolve_agent_node(document, node_id)?.1;
182                hover_agent_node(document, node_id)?;
183            }
184            AgentAction::SetValue { node_id, value } => {
185                set_node_value(document, blitz_dom::NodeId::from_u64(node_id), value)?;
186            }
187            AgentAction::ScrollIntoView { node_id } => {
188                let node_id = blitz_dom::NodeId::from_u64(node_id);
189                if document.inner().get_node(node_id).is_none() {
190                    return Err(debug_error("unknownNode", "node does not exist"));
191                }
192                let mut events = Vec::new();
193                document
194                    .inner_mut()
195                    .scroll_to_node_centered_with_events(node_id, |event| events.push(event));
196                for event in events {
197                    document.dispatch_dom_event(event);
198                }
199            }
200            AgentAction::ScrollBy {
201                node_id,
202                delta_x,
203                delta_y,
204            } => {
205                let node_id = blitz_dom::NodeId::from_u64(node_id);
206                if document.inner().get_node(node_id).is_none() {
207                    return Err(debug_error("unknownNode", "node does not exist"));
208                }
209                let mut events = Vec::new();
210                document
211                    .inner_mut()
212                    .scroll_nearest_container_by_with_events(node_id, delta_x, delta_y, |event| {
213                        events.push(event)
214                    });
215                for event in events {
216                    document.dispatch_dom_event(event);
217                }
218            }
219            AgentAction::Input(input) => self.input(document, input)?,
220        }
221        Ok(())
222    }
223
224    fn input(
225        &mut self,
226        document: &mut (impl crate::ControlScriptBackend + ?Sized),
227        input: InputCommand,
228    ) -> Result<(), DebugError> {
229        match input {
230            InputCommand::Key {
231                phase,
232                key,
233                code,
234                modifiers,
235            } => {
236                let parsed_key = key.parse::<Key>().unwrap_or(Key::Character(key));
237                let parsed_code = code.parse::<Code>().unwrap_or(Code::Unidentified);
238                let event = key_event(
239                    phase,
240                    parsed_key,
241                    parsed_code,
242                    keyboard_modifiers(modifiers),
243                );
244                document.handle_ui_event(match phase {
245                    KeyPhase::Down => UiEvent::KeyDown(event),
246                    KeyPhase::Up => UiEvent::KeyUp(event),
247                });
248            }
249            InputCommand::Pointer {
250                phase,
251                x,
252                y,
253                button,
254                modifiers,
255            } => {
256                let button = mouse_button(button)?;
257                self.pointer = (x as f32, y as f32);
258                match phase {
259                    PointerPhase::Down => self.buttons.insert(button.into()),
260                    PointerPhase::Up | PointerPhase::Cancel => self.buttons.remove(button.into()),
261                    PointerPhase::Move => {}
262                }
263                let event = crate::document::pointer_event_for_document(
264                    document,
265                    self.pointer,
266                    button,
267                    self.buttons,
268                    keyboard_modifiers(modifiers),
269                );
270                document.handle_ui_event(match phase {
271                    PointerPhase::Move => UiEvent::PointerMove(event),
272                    PointerPhase::Down => UiEvent::PointerDown(event),
273                    PointerPhase::Up => UiEvent::PointerUp(event),
274                    PointerPhase::Cancel => UiEvent::PointerCancel(event),
275                });
276            }
277            InputCommand::Wheel {
278                delta_x,
279                delta_y,
280                phase,
281                modifiers,
282            } => {
283                let event = BlitzWheelEvent {
284                    delta: BlitzWheelDelta::Pixels(delta_x, delta_y),
285                    phase: match phase {
286                        WheelPhase::Started => BlitzWheelPhase::Started,
287                        WheelPhase::Moved => BlitzWheelPhase::Moved,
288                        WheelPhase::Ended => BlitzWheelPhase::Ended,
289                    },
290                    coords: crate::document::pointer_coords_for_document(document, self.pointer),
291                    buttons: self.buttons,
292                    mods: keyboard_modifiers(modifiers),
293                    element: Point::default(),
294                };
295                // A wheel event targets the hovered node, and hover is resolved
296                // by the shell from real cursor movement. An injected pointer
297                // move never touches it, so an injected wheel had no target and
298                // scrolled nothing, making remote wheel input look accepted
299                // while the document remained unchanged.
300                document
301                    .inner_mut()
302                    .set_hover_to(self.pointer.0, self.pointer.1);
303                document.handle_ui_event(UiEvent::Wheel(event));
304            }
305        }
306        Ok(())
307    }
308
309    /// Draw the document offscreen, reusing this control's surface.
310    #[cfg(feature = "capture")]
311    pub fn capture(
312        &mut self,
313        document: &mut (impl crate::ControlScriptBackend + ?Sized),
314        request: crate::CaptureRequest,
315    ) -> Result<crate::CapturedImage, DebugError> {
316        request.validate().map_err(|why| DebugError {
317            code: "invalidArgument".into(),
318            message: why.into(),
319        })?;
320        self.capture.capture(document, request)
321    }
322}
323
324/// Drain the synchronous script work an action caused.
325pub fn settle(
326    document: &mut (impl crate::ControlScriptBackend + ?Sized),
327) -> Result<(), DebugError> {
328    for _ in 0..MAX_SETTLE_POLLS {
329        if !document.poll(None) {
330            document.inner_mut().resolve(0.0);
331            return Ok(());
332        }
333    }
334    document.inner_mut().resolve(0.0);
335    Err(debug_error(
336        "actionDidNotSettle",
337        "the action kept synchronous script work runnable past the settlement budget",
338    ))
339}
340
341/// Replace a text input's contents.
342///
343/// # Why this counts bytes instead of selecting the text
344///
345/// The other implementation of this called `select_all` first. That builds its
346/// selection with `move_lines(&layout, isize::MAX)` and resolves its ends
347/// through `Cursor::from_byte_index(&layout, ..)`, so both halves read the laid
348/// out text and both depend on a font catalogue being present. With none
349/// registered every glyph shapes to nothing, the selection comes back
350/// collapsed, and the commit below inserts at the caret instead of replacing:
351/// the typed string lands after the old one.
352///
353/// `delete_bytes_before_selection` and `delete_bytes_after_selection` clamp to
354/// the ends of the buffer, so between them they empty it from wherever the
355/// caret is, with no layout involved. A host that behaves differently depending
356/// on which fonts the machine has is a harness that reports different verdicts
357/// on CI and on a laptop.
358pub(crate) fn set_node_value(
359    document: &mut (impl crate::ControlScriptBackend + ?Sized),
360    node_id: blitz_dom::NodeId,
361    value: String,
362) -> Result<(), DebugError> {
363    let current = document
364        .inner()
365        .get_node(node_id)
366        .and_then(|node| node.element_data())
367        .and_then(|element| element.text_input_data())
368        .map(|input| input.editor.text().to_string());
369    let Some(current) = current else {
370        // A native <select> takes the option whose value (or, failing that,
371        // label) matches, through the same path as choosing it with the
372        // keyboard: selectedness, restyle, then the input/change events.
373        let is_select = document
374            .inner()
375            .get_node(node_id)
376            .and_then(|node| node.element_data())
377            .is_some_and(|element| element.name.local.as_ref() == "select");
378        if is_select {
379            let index = {
380                let doc = document.inner();
381                let options = doc.select_options(node_id);
382                options
383                    .iter()
384                    .position(|option| doc.option_value(*option) == value)
385                    .or_else(|| {
386                        options
387                            .iter()
388                            .position(|option| doc.option_label(*option).trim() == value.trim())
389                    })
390            };
391            let Some(index) = index else {
392                return Err(debug_error(
393                    "noSuchOption",
394                    "the select has no option with that value",
395                ));
396            };
397            document.inner_mut().set_focus_to(node_id);
398            let changed = document
399                .inner_mut()
400                .set_select_selected_index(node_id, index);
401            if changed {
402                document.inner_mut().snapshot_node(node_id);
403                let value = document.inner().select_value(node_id);
404                document.dispatch_dom_event(DomEvent::new(
405                    node_id,
406                    DomEventData::Input(BlitzInputEvent { value }),
407                ));
408            }
409            return Ok(());
410        }
411        let is_value_input = document
412            .inner()
413            .get_node(node_id)
414            .and_then(|node| node.element_data())
415            .is_some_and(|element| {
416                element.name.local.as_ref() == "input"
417                    && matches!(
418                        element_attr(element, "type").unwrap_or("text"),
419                        "date" | "datetime-local" | "month" | "time" | "week" | "color"
420                    )
421            });
422        if !is_value_input {
423            return Err(debug_error("notEditable", "node is not a text input"));
424        }
425
426        document.inner_mut().set_focus_to(node_id);
427        document.inner_mut().mutate().set_attribute(
428            node_id,
429            blitz_dom::qual_name!("value"),
430            &value,
431        );
432        document.dispatch_dom_event(DomEvent::new(
433            node_id,
434            DomEventData::Input(BlitzInputEvent { value }),
435        ));
436        return Ok(());
437    };
438    document.inner_mut().set_focus_to(node_id);
439    if let Some(len) = std::num::NonZeroUsize::new(current.len()) {
440        document.inner_mut().with_text_input(node_id, |mut editor| {
441            editor.delete_bytes_before_selection(len);
442            editor.delete_bytes_after_selection(len);
443        });
444    }
445    document.handle_ui_event(UiEvent::Ime(BlitzImeEvent::Commit(value)));
446    Ok(())
447}
448
449fn mouse_button(button: u16) -> Result<MouseEventButton, DebugError> {
450    match button {
451        0 => Ok(MouseEventButton::Main),
452        1 => Ok(MouseEventButton::Auxiliary),
453        2 => Ok(MouseEventButton::Secondary),
454        3 => Ok(MouseEventButton::Fourth),
455        4 => Ok(MouseEventButton::Fifth),
456        _ => Err(debug_error(
457            "unsupportedButton",
458            "pointer button must be 0 through 4",
459        )),
460    }
461}
462
463#[cfg(test)]
464mod tests {
465    use blitz_dom::{Document as _, DocumentConfig};
466    use blitz_traits::events::DomEventData;
467
468    use super::*;
469    use crate::test_document::TestDocument;
470    use crate::{AgentSnapshot, Modifiers};
471
472    /// A page with something to press, something to type into, and something
473    /// to scroll, driven with no socket anywhere.
474    fn document() -> TestDocument {
475        let mut document = TestDocument::from_html(
476            r#"<style>
477                 #scroller { height: 40px; overflow: auto; }
478                 #tall { height: 400px; }
479               </style>
480               <button id="press">Press me</button>
481               <input id="field" value="before">
482               <input id="date" type="date" value="2025-01-01">
483               <div id="scroller"><div id="tall">tall</div></div>
484               <output id="log"></output>
485               <output id="date-log"></output>"#,
486            DocumentConfig::default(),
487        );
488        document.on("#press", "click", |document, _event, _state| {
489            set_text_content(document, "#log", "pressed")
490        });
491        document.on("#date", "input", |document, event, _state| {
492            if let DomEventData::Input(input) = &event.data {
493                set_text_content(document, "#date-log", &input.value);
494            }
495        });
496        // A viewport, or every box lays out at zero width and a pointer has
497        // nowhere to land.
498        document
499            .inner_mut()
500            .set_viewport(blitz_traits::shell::Viewport::new(
501                800,
502                600,
503                1.0,
504                blitz_traits::shell::ColorScheme::Light,
505            ));
506        document.inner_mut().resolve(0.0);
507        settle(&mut document).expect("the fixture settles");
508        document
509    }
510
511    fn set_text_content(document: &mut blitz_dom::BaseDocument, selector: &str, value: &str) {
512        let output = document
513            .query_selector(selector)
514            .unwrap()
515            .unwrap_or_else(|| panic!("the fixture has no {selector}"));
516        let mut mutator = document.mutate();
517        mutator.remove_and_drop_all_children(output);
518        let text = mutator.create_text_node(value);
519        mutator.append_children(output, &[text]);
520    }
521
522    fn node(control: &mut DocumentControl, document: &mut TestDocument, dom_id: &str) -> u64 {
523        let DebugResponse::AgentSnapshot(AgentSnapshot { nodes, .. }) = control.agent(
524            document,
525            AgentControlRequest::Inspect {
526                root: None,
527                max_depth: 0,
528            },
529        ) else {
530            panic!("inspection did not answer with a tree")
531        };
532        nodes
533            .iter()
534            .find(|node| node.dom_id.as_deref() == Some(dom_id))
535            .unwrap_or_else(|| panic!("the fixture has no #{dom_id}"))
536            .id
537    }
538
539    /// What the document says an element holds, read straight from the tree
540    /// rather than through the semantic surface. The point of these tests is
541    /// that an action happened, not what the surface calls the result.
542    fn text(document: &TestDocument, selector: &str) -> String {
543        let id = document
544            .inner()
545            .query_selector(selector)
546            .unwrap()
547            .unwrap_or_else(|| panic!("the fixture has no {selector}"));
548        document.inner().get_node(id).unwrap().text_content()
549    }
550
551    /// The whole point of the second transport: a full request and response
552    /// cycle with no listener, no descriptor and no framing.
553    #[test]
554    fn an_embedder_drives_a_document_with_no_socket() {
555        let mut document = document();
556        let mut control = DocumentControl::new();
557        let press = node(&mut control, &mut document, "press");
558
559        let response = control.agent(
560            &mut document,
561            AgentControlRequest::Act(AgentAction::Click { node_id: press }),
562        );
563
564        assert_eq!(response, DebugResponse::Ack);
565        // The click ran the page's handler and the response waited for it, so
566        // the very next read sees the consequence rather than the tree from
567        // before.
568        assert_eq!(text(&document, "#log"), "pressed");
569    }
570
571    #[test]
572    fn a_revision_advances_with_every_answer() {
573        let mut document = document();
574        let mut control = DocumentControl::new();
575        let before = control.revision();
576        let press = node(&mut control, &mut document, "press");
577        control.agent(
578            &mut document,
579            AgentControlRequest::Act(AgentAction::Click { node_id: press }),
580        );
581        assert!(
582            control.revision() > before,
583            "a client watching the revision must see that something happened"
584        );
585    }
586
587    /// Replacing a field's contents must not depend on the machine's fonts.
588    ///
589    /// This document has no font catalogue registered, which is the condition
590    /// under which `select_all` silently selects nothing and the typed string
591    /// is appended rather than substituted.
592    #[test]
593    fn setting_a_value_replaces_what_was_there_with_no_fonts_installed() {
594        let mut document = document();
595        let mut control = DocumentControl::new();
596        let field = node(&mut control, &mut document, "field");
597
598        assert_eq!(
599            control.agent(
600                &mut document,
601                AgentControlRequest::Act(AgentAction::SetValue {
602                    node_id: field,
603                    value: "after".into(),
604                }),
605            ),
606            DebugResponse::Ack
607        );
608
609        let value = document
610            .inner()
611            .get_node(blitz_dom::NodeId::from_u64(field))
612            .and_then(|node| node.element_data())
613            .and_then(|element| element.text_input_data())
614            .map(|input| input.editor.text().to_string())
615            .expect("the field is a text input");
616        assert_eq!(
617            value, "after",
618            "the old contents were appended to rather than replaced"
619        );
620    }
621
622    /// Date and time controls expose values to accessibility clients even
623    /// though Blitz does not give them a text editor. They still need the same
624    /// observable SetValue contract as a text box: update the DOM value and
625    /// deliver an input event to the application.
626    #[test]
627    fn setting_a_date_value_updates_the_dom_and_dispatches_input() {
628        let mut document = document();
629        let mut control = DocumentControl::new();
630        let date = node(&mut control, &mut document, "date");
631
632        assert_eq!(
633            control.agent(
634                &mut document,
635                AgentControlRequest::Act(AgentAction::SetValue {
636                    node_id: date,
637                    value: "2025-06-24".into(),
638                }),
639            ),
640            DebugResponse::Ack
641        );
642
643        let value = document
644            .inner()
645            .get_node(blitz_dom::NodeId::from_u64(date))
646            .and_then(|node| node.element_data())
647            .and_then(|element| element_attr(element, "value").map(str::to_owned));
648        assert_eq!(value.as_deref(), Some("2025-06-24"));
649        assert_eq!(text(&document, "#date-log"), "2025-06-24");
650    }
651
652    /// Focus is a state change the protocol reports back, so this asserts the
653    /// action landed rather than that it was acknowledged.
654    ///
655    /// Keyboard setup must not be a click: focusing a submit, delete or fork
656    /// button by clicking it performs the action before the key under test is
657    /// ever delivered.
658    #[test]
659    fn focus_moves_the_focused_node_without_activating_it() {
660        let mut document = document();
661        let mut control = DocumentControl::new();
662        let field = node(&mut control, &mut document, "field");
663
664        assert_eq!(
665            control.agent(
666                &mut document,
667                AgentControlRequest::Act(AgentAction::Focus { node_id: field }),
668            ),
669            DebugResponse::Ack
670        );
671
672        let DebugResponse::AgentSnapshot(snapshot) = control.agent(
673            &mut document,
674            AgentControlRequest::Inspect {
675                root: None,
676                max_depth: 0,
677            },
678        ) else {
679            panic!("inspection did not answer with a tree")
680        };
681        assert_eq!(snapshot.focused_node, Some(field));
682        assert_eq!(
683            text(&document, "#log"),
684            "",
685            "focusing a control must not activate it"
686        );
687    }
688
689    /// The refusals are part of the contract.
690    ///
691    /// A host that answered `Ack` to a request it did not perform is worse
692    /// than one that says so: a check then reports the page as broken.
693    #[test]
694    fn the_process_lifecycle_is_refused_rather_than_acknowledged() {
695        let mut document = document();
696        let mut control = DocumentControl::new();
697        for request in [
698            AgentControlRequest::Navigate {
699                url: "/second.html".into(),
700            },
701            AgentControlRequest::Relaunch,
702            AgentControlRequest::Quit,
703        ] {
704            let DebugResponse::Error(error) = control.agent(&mut document, request) else {
705                panic!("a document cannot restart its own process or fetch a URL")
706            };
707            assert_eq!(error.code, "unsupportedRequest");
708        }
709    }
710
711    #[test]
712    fn an_unknown_node_is_an_error_and_not_a_panic() {
713        let mut document = document();
714        let mut control = DocumentControl::new();
715        let DebugResponse::Error(error) = control.agent(
716            &mut document,
717            AgentControlRequest::Act(AgentAction::ScrollIntoView {
718                node_id: u64::MAX - 1,
719            }),
720        ) else {
721            panic!("a node that is not there cannot be scrolled to")
722        };
723        assert_eq!(error.code, "unknownNode");
724    }
725
726    #[test]
727    fn a_pointer_button_outside_the_range_is_refused() {
728        let mut document = document();
729        let mut control = DocumentControl::new();
730        let DebugResponse::Error(error) = control.agent(
731            &mut document,
732            AgentControlRequest::Act(AgentAction::Input(InputCommand::Pointer {
733                phase: PointerPhase::Down,
734                x: 1.0,
735                y: 1.0,
736                button: 9,
737                modifiers: Modifiers::default(),
738            })),
739        ) else {
740            panic!("button 9 does not exist")
741        };
742        assert_eq!(error.code, "unsupportedButton");
743    }
744}