Skip to main content

blitz_control_protocol/
lib.rs

1//! The Blitz agent-control and diagnostics surface: one vocabulary, one core,
2//! two transports.
3//!
4//! # The shape of this crate
5//!
6//! This module is the **vocabulary**: the request, response and event types,
7//! and the MCP framing that carries them. It is what a client needs and all it
8//! needs, it costs serde and endpoint-libs, and it is what you get with no
9//! features enabled.
10//!
11//! [`document`] is the **core**, behind `engine`. It answers a request against
12//! a `blitz-dom` document: the semantic tree, the capture surface, input
13//! injection. It knows nothing about sockets.
14//!
15//! [`in_process`] and [`server`] are the **two transports** over that core. An
16//! embedder holding the document calls the first one directly; a harness or an
17//! agent outside the process reaches the second one over a Unix socket.
18//! [`client`] is the connecting half of that socket, and it is a sibling of the
19//! server rather than a layer on top of it, because a peer can be both: an
20//! application driven by agents while it drives a browser it embeds is a client
21//! and a server at once.
22//!
23//! [`lifecycle`] is the one answer neither transport nor core can give.
24//! `Relaunch` and `Quit` are about the process, so the embedder that started it
25//! registers what they mean; it is here rather than in a host because more than
26//! one host serves the same request.
27//!
28//! There were three copies of this vocabulary before, in three repositories,
29//! and two of them were transports rather than duplicates: an in-process
30//! interface in the browser and a socket in the Tauri runtime, each with its
31//! own spelling of the same commands. The transports are both still here. The
32//! spelling is not.
33//!
34//! # Typed local debugging protocol carried by endpoint-libs framing.
35//!
36//! This is deliberately not WebDriver. It models the native renderer and app
37//! lifecycle directly, supports observation by more than one client, and has
38//! no authentication handshake. Agent control binds only to a local transport;
39//! expensive diagnostics collection remains an explicit compile-time feature
40//! *of the server*, `izumo/diagnostics`.
41//!
42//! # Why this is its own crate
43//!
44//! These are the server's own definitions, and a client that hand-rolls the
45//! JSON gets them wrong in ways that do not look like encoding mistakes.
46//! `AgentAction` is adjacently tagged, so `{"action":"click","nodeId":9}` is
47//! malformed where `{"action":"click","params":{"nodeId":9}}` is correct, and
48//! the difference used to present as a hung application. Sharing the types
49//! makes that a compile error.
50//!
51//! Speaking the protocol must not cost a renderer. `izumo` pulls
52//! in tauri, winit, wgpu and blitz, so a measurement tool that depended on it
53//! for these types would build a browser engine to send a wheel event. Nothing
54//! here needs any of that: it is serde plus endpoint-libs' framing.
55//!
56//! # No `diagnostics` feature, on purpose
57//!
58//! The types are inert data definitions and cost nothing to compile, whereas
59//! gating them creates feature skew: cargo unifies features across a build, so
60//! one workspace member asking for diagnostics types while the server crate is
61//! built without them turned `DebugResponse` into a non-exhaustive match in
62//! code nobody had touched. What stays gated in the server is *collection*,
63//! which is where the expense actually is. A build that cannot serve
64//! diagnostics says so by omitting the tool from `tools/list`; see
65//! [`encode_tools_list_response`].
66
67/// The socket transport, connecting half.
68#[cfg(feature = "client")]
69pub mod client;
70
71/// Condensing a settled page into levels a caller can widen from.
72///
73/// Types and ranking only, no transport: a caller with a snapshot already has
74/// everything this needs, and the cache is keyed on settle rather than fetch.
75pub mod condense;
76#[cfg(all(unix, any(feature = "server", feature = "client")))]
77mod control_directory;
78/// The core: reading, capturing and driving a document.
79#[cfg(feature = "engine")]
80pub mod document;
81/// Secret-aware file output shared by every workspace crate.
82#[allow(clippy::disallowed_methods)]
83pub mod guarded_writer;
84/// The in-process transport.
85#[cfg(feature = "engine")]
86pub mod in_process;
87
88/// A script-capable backend for the control protocol.
89///
90/// Implementations provide a [`blitz_dom::Document`] for protocol observation and
91/// implement the event delivery that the document alone cannot perform. Event
92/// methods must preserve target-directed delivery, bubbling, cancellation and
93/// native default actions. Pointer movement must preserve hover event ordering.
94///
95/// Observation calls [`blitz_dom::Document::poll_for_settle`] with timers
96/// disabled and a bounded budget. Action settlement uses bounded calls to
97/// [`blitz_dom::Document::poll`], preserving the backend's normal timer policy.
98/// Backends must report whether each poll leaves immediate work runnable.
99///
100/// Hosts implement this contract on their document owner or an adapter that
101/// delegates `Document` and event delivery to the selected script backend.
102#[cfg(feature = "engine")]
103pub trait ControlScriptBackend: blitz_dom::Document {
104    /// Dispatch a DOM event through the backend's scripted event handling.
105    fn dispatch_dom_event(&mut self, event: blitz_traits::events::DomEvent);
106
107    /// Deliver pointer movement to a target node, preserving hover event order.
108    fn handle_pointer_move_to_node(
109        &mut self,
110        event: blitz_traits::events::BlitzPointerEvent,
111        node: blitz_dom::NodeId,
112    );
113
114    /// Deliver a UI event to its target node with native defaults and bubbling.
115    fn handle_ui_event_to_node(
116        &mut self,
117        event: blitz_traits::events::UiEvent,
118        node: blitz_dom::NodeId,
119    );
120
121    /// Return script runtime metrics when the backend can provide them.
122    fn script_metrics(&self) -> Option<ScriptMetrics> {
123        None
124    }
125}
126/// Latest-value and one-shot handoffs built on nagoya, replacing tokio channels.
127#[cfg(any(feature = "server", feature = "client"))]
128pub mod latest;
129/// The embedder's answer to a request about the process, not the document.
130pub mod lifecycle;
131pub mod target;
132pub use target::*;
133#[cfg(any(feature = "server", feature = "client"))]
134pub mod journal;
135/// Page-owned WebGPU diagnostic reports.
136pub mod webgpu;
137pub use webgpu::*;
138/// The socket transport, listening half.
139///
140/// Unix only. The transport is a Unix domain socket with owner-only
141/// permissions, which is the access control: there is no handshake and no
142/// token, because the file mode already says who may connect.
143#[cfg(all(feature = "server", unix))]
144pub mod server;
145#[cfg(all(feature = "server", unix))]
146mod server_stream;
147
148use std::collections::BTreeMap;
149
150use endpoint_libs::libs::ws::mcp_wire::{INVALID_PARAMS, INVALID_REQUEST, parse};
151pub use endpoint_libs::libs::ws::{
152    MessageStream, WireMessage,
153    mcp_wire::{
154        JsonRpcError, JsonRpcId, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse,
155        MCP_PROTOCOL_VERSION,
156    },
157    transport::{FramedError, Transport, TransportStream, framed_json_neutral},
158};
159use schemars::JsonSchema;
160use serde::{Deserialize, Serialize, de::DeserializeOwned};
161
162/// Version 2 names every field inside a command camelCase (`nodeId`,
163/// `maxDepth`, `deltaX`). Version 1 field names are still accepted on input,
164/// so a version 2 host serves version 1 clients; a version 2 client refuses a
165/// version 1 descriptor instead of sending names that host cannot read.
166pub const DEBUG_PROTOCOL_VERSION: u32 = 2;
167/// Largest single frame either side may send or accept. Shared by every
168/// host, client and relay, so a supervisor never forwards a frame its peer
169/// would refuse.
170pub const MAX_DEBUG_FRAME_BYTES: usize = 16 * 1024 * 1024;
171pub const MCP_INITIALIZE: &str = "initialize";
172pub const MCP_INITIALIZED_NOTIFICATION: &str = "notifications/initialized";
173pub const MCP_TOOLS_LIST: &str = "tools/list";
174pub const MCP_TOOLS_CALL: &str = "tools/call";
175pub const AGENT_CONTROL_TOOL: &str = "blitz.agent.control";
176pub const AGENT_EVENT_NOTIFICATION: &str = "notifications/blitz/agent";
177pub const DIAGNOSTICS_TOOL: &str = "blitz.diagnostics";
178pub const DIAGNOSTICS_EVENT_NOTIFICATION: &str = "notifications/blitz/diagnostics";
179
180#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
181#[serde(rename_all = "camelCase")]
182pub struct DebugDescriptor {
183    pub protocol_version: u32,
184    pub pid: u32,
185    pub instance_id: String,
186    pub address: String,
187    pub renderer: String,
188    pub renderer_revision: String,
189}
190
191#[derive(Debug, Clone, PartialEq)]
192#[non_exhaustive]
193pub enum IncomingRequest {
194    Initialize {
195        id: JsonRpcId,
196    },
197    Initialized,
198    ToolsList {
199        id: JsonRpcId,
200    },
201    Agent {
202        id: JsonRpcId,
203        request: AgentControlRequest,
204    },
205    Diagnostics {
206        id: JsonRpcId,
207        request: DiagnosticsRequest,
208    },
209    Targeted {
210        id: JsonRpcId,
211        request: TargetRequest,
212    },
213}
214
215#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
216#[serde(
217    tag = "command",
218    content = "params",
219    rename_all = "camelCase",
220    rename_all_fields = "camelCase"
221)]
222#[non_exhaustive]
223pub enum AgentControlRequest {
224    ListTargets,
225    Inspect {
226        root: Option<u64>,
227        #[serde(alias = "max_depth")]
228        max_depth: u32,
229    },
230    Act(AgentAction),
231    /// Load a URL in the standing document.
232    ///
233    /// Relative values resolve against the page that is up. The host that
234    /// owns the loader answers this; a document core cannot, any more than it
235    /// can relaunch the process.
236    Navigate {
237        url: String,
238    },
239    /// Condense the settled page into one level, with an account of what the
240    /// level dropped.
241    ///
242    /// The document core can answer this: it needs the tree that is already
243    /// there and no loader, no compositor and no second renderer pass. See
244    /// [`condense`], which is where the ranking lives.
245    Condense {
246        #[serde(default)]
247        level: condense::Level,
248        #[serde(default)]
249        options: condense::CondenseOptions,
250    },
251    Relaunch,
252    Quit,
253}
254
255#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
256#[serde(
257    tag = "command",
258    content = "params",
259    rename_all = "camelCase",
260    rename_all_fields = "camelCase"
261)]
262#[non_exhaustive]
263pub enum DiagnosticsRequest {
264    Observe {
265        streams: Vec<DebugStream>,
266    },
267    Snapshot(SnapshotRequest),
268    Metrics,
269    WaitForIdle,
270    /// The native window layers which sit outside the renderer's document.
271    ///
272    /// A renderer capture cannot see whether an opaque platform window or a
273    /// tinted native glass view was placed behind its transparent root. This
274    /// response makes that compositor boundary observable without pretending
275    /// pixels from an unknown desktop prove which native layer produced them.
276    WindowComposition,
277    /// Render the current document to an RGBA8 image and return the pixels.
278    ///
279    /// The one question the rest of this protocol cannot answer. A snapshot
280    /// reports the boxes and colours the engine *resolved*, which is not the
281    /// same as what it drew: an element can hold a correct box, a correct
282    /// computed colour and an accessible role while painting nothing at all.
283    /// That gap is not hypothetical. An entire icon set rendered blank in a
284    /// shipping application while every snapshot, every layout box and every
285    /// accessibility node read exactly right, and no tool in this protocol
286    /// could see it.
287    ///
288    /// Rendered offscreen rather than read back from the window surface. The
289    /// protocol requires no swapchain, compositor, or display server; concrete
290    /// host availability still depends on the renderer backend for that
291    /// platform.
292    Capture(CaptureRequest),
293    /// Inspect page-owned devices, live resources, errors and submitted frames.
294    ///
295    /// Asking renews a ten-second lease for pass and draw bookkeeping.
296    /// Hosts without a page WebGPU inspector return their unsupported
297    /// diagnostics error; absence of support is not an empty report.
298    WebGpuInspect,
299    /// Copy one page-owned texture or canvas drawing buffer to RGBA8.
300    ///
301    /// `target` is `texture:<label>` or `canvas:#id`. The answer is
302    /// [`DebugResponse::Captured`], the same image a document Capture returns.
303    WebGpuCapture {
304        target: String,
305    },
306    /// Read bytes from one labeled page-owned GPUBuffer.
307    ///
308    /// The target is buffer:<label>, with * matching any run of characters.
309    /// Zero or multiple matches are errors naming the label or matching labels.
310    /// Offset and length are bytes and must be multiples of four. An absent
311    /// length reads to the end. Hosts return the previous completed write
312    /// while a newer submit is pending, or error code pending when no
313    /// completed write is available. They do not wait for that newer submit.
314    WebGpuBuffer {
315        target: String,
316        offset: u64,
317        length: Option<u64>,
318    },
319    /// Run a script in the page and return its completion value as JSON.
320    ///
321    /// The same evaluation a page console offers, so an agent driving a
322    /// headless page can read state no tree or capture exposes, such as a
323    /// media element's `currentTime`. Hosts that run no page script answer
324    /// with their unsupported diagnostics error.
325    Evaluate {
326        script: String,
327    },
328}
329
330/// What to draw, and how large.
331#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
332#[serde(rename_all = "camelCase")]
333pub struct CaptureRequest {
334    /// The subtree to draw, or the whole document when absent.
335    ///
336    /// Capturing one node is the difference between a test that says "the
337    /// window is not blank" and one that says "this button's icon is drawn",
338    /// and the second is the one worth writing.
339    pub node_id: Option<u64>,
340    /// Pixel scale, so a small control can be inspected at a useful size.
341    ///
342    /// A 16px icon is a handful of pixels at 1x, and antialiasing dominates
343    /// them; asking for it at 4x makes "is anything there" answerable without
344    /// making the threshold a guess.
345    pub scale: f32,
346}
347
348impl Default for CaptureRequest {
349    fn default() -> Self {
350        Self {
351            node_id: None,
352            scale: 1.0,
353        }
354    }
355}
356
357impl CaptureRequest {
358    pub fn validate(&self) -> Result<(), &'static str> {
359        if !self.scale.is_finite() || !(0.25..=8.0).contains(&self.scale) {
360            return Err("capture scale must be finite and between 0.25 and 8");
361        }
362        Ok(())
363    }
364}
365
366/// An RGBA8 image, as the renderer actually drew it.
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
368#[serde(rename_all = "camelCase")]
369pub struct CapturedImage {
370    pub width: u32,
371    pub height: u32,
372    /// Row-major RGBA8, four bytes per pixel, base64 over the wire.
373    ///
374    /// Base64 rather than raw bytes because the transport is line-delimited
375    /// JSON, and a full window at 2x is a few megabytes: large enough to be
376    /// worth encoding compactly, not large enough to justify a second channel.
377    pub rgba_base64: String,
378    /// The node this shows, when the request named one.
379    pub node_id: Option<u64>,
380}
381
382#[cfg(feature = "capture")]
383impl CapturedImage {
384    /// Encode tightly packed straight RGBA8 as a document capture payload.
385    pub fn from_rgba(width: u32, height: u32, rgba: &[u8]) -> Result<Self, DebugError> {
386        let expected = u64::from(width)
387            .saturating_mul(u64::from(height))
388            .saturating_mul(4);
389        if width == 0 || height == 0 || expected != rgba.len() as u64 {
390            return Err(DebugError {
391                code: "invalidArgument".to_owned(),
392                message: format!(
393                    "RGBA8 capture is {width}x{height} but holds {} bytes",
394                    rgba.len()
395                ),
396            });
397        }
398        // Same frame ceiling as document capture: leave room for the JSON
399        // envelope inside the transport's fixed frame limit.
400        const FRAME_ENVELOPE_RESERVE: usize = 64 * 1024;
401        const MAX_BASE64_BYTES: usize = MAX_DEBUG_FRAME_BYTES - FRAME_ENVELOPE_RESERVE;
402        const MAX_RAW_BYTES: usize = (MAX_BASE64_BYTES / 4) * 3;
403        if rgba.len() > MAX_RAW_BYTES {
404            return Err(DebugError {
405                code: "captureTooLarge".to_owned(),
406                message: format!(
407                    "{width}x{height} cannot fit in one diagnostic frame; capture a smaller texture"
408                ),
409            });
410        }
411        Ok(Self {
412            width,
413            height,
414            rgba_base64: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, rgba),
415            node_id: None,
416        })
417    }
418}
419
420#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
421#[serde(tag = "result", content = "value", rename_all = "camelCase")]
422#[allow(clippy::large_enum_variant)] // wire shape is public; boxing would break consumers
423#[non_exhaustive]
424pub enum DebugResponse {
425    Ack,
426    Targets(Vec<TargetInfo>),
427    Targeted(TargetReply),
428    AgentSnapshot(AgentSnapshot),
429    Snapshot(DebugSnapshot),
430    Metrics(RendererMetrics),
431    Idle(RevisionSet),
432    WindowComposition(WindowComposition),
433    Captured(CapturedImage),
434    WebGpu(WebGpuReport),
435    WebGpuBuffer(WebGpuBufferSnapshot),
436    /// One condensation level over the settled page, level-shaped so a caller
437    /// asking for keywords is not handed the page's full text.
438    Condensation(condense::Condensation),
439    /// The JSON completion value of an [`DiagnosticsRequest::Evaluate`].
440    Evaluated(serde_json::Value),
441    Error(DebugError),
442}
443
444/// Effective native composition selected for the application window.
445///
446/// `supported` is false for a headless host or a runtime which has no native
447/// window integration. The remaining fields describe the path the runtime
448/// actually installed, not merely values requested by application CSS.
449#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
450#[serde(rename_all = "camelCase")]
451pub struct WindowComposition {
452    pub supported: bool,
453    pub surface_transparent: bool,
454    pub glass_enabled: bool,
455    #[serde(default, skip_serializing_if = "Option::is_none")]
456    pub glass_backend: Option<String>,
457    #[serde(default, skip_serializing_if = "Option::is_none")]
458    pub tint_rgba: Option<[u8; 4]>,
459    #[serde(default, skip_serializing_if = "Option::is_none")]
460    pub radius: Option<f64>,
461}
462
463#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
464#[serde(tag = "event", content = "value", rename_all = "camelCase")]
465#[allow(clippy::large_enum_variant)] // wire shape is public; boxing would break consumers
466#[non_exhaustive]
467pub enum DebugEvent {
468    DiagnosticLoss {
469        stream: DebugStream,
470        lost: u64,
471    },
472    Snapshot(DebugSnapshot),
473    Metrics(RendererMetrics),
474    Console(ConsoleEntry),
475    RuntimeError(RuntimeErrorEntry),
476    /// A real window frame completed after style, layout and paint.
477    ///
478    /// The event carries only a monotonic revision. Consumers pull a snapshot
479    /// or capture if they need one; pushing images or trees on every frame
480    /// would turn observation into an unbounded second renderer workload.
481    PaintCommitted {
482        revision: u64,
483    },
484}
485
486#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
487#[serde(tag = "event", content = "value", rename_all = "camelCase")]
488#[non_exhaustive]
489pub enum AgentControlEvent {
490    Ready(DebugDescriptor),
491    TreeChanged { revision: u64 },
492    Lifecycle(LifecycleEvent),
493}
494
495#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
496#[serde(rename_all = "camelCase")]
497pub enum DebugStream {
498    Snapshots,
499    Metrics,
500    Console,
501    RuntimeErrors,
502    Paint,
503}
504
505#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
506#[serde(rename_all = "camelCase")]
507pub struct SnapshotRequest {
508    pub include_dom: bool,
509    pub include_layout: bool,
510    pub include_computed_style: bool,
511    /// Restrict DOM, layout, and computed-style collection to these nodes.
512    /// Empty preserves the full-snapshot behavior used by inspection reports.
513    #[serde(default, skip_serializing_if = "Vec::is_empty")]
514    pub node_ids: Vec<u64>,
515}
516
517/// A node's live border box, encoded on the wire as `[x, y, width, height]`.
518///
519/// Named fields keep consumers out of positional indexing while the custom
520/// array conversion preserves compatibility with existing inspectors.
521#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
522#[serde(from = "[f64; 4]", into = "[f64; 4]")]
523pub struct LayoutBounds {
524    pub x: f64,
525    pub y: f64,
526    pub width: f64,
527    pub height: f64,
528}
529
530impl From<[f64; 4]> for LayoutBounds {
531    fn from([x, y, width, height]: [f64; 4]) -> Self {
532        Self {
533            x,
534            y,
535            width,
536            height,
537        }
538    }
539}
540
541impl From<LayoutBounds> for [f64; 4] {
542    fn from(bounds: LayoutBounds) -> Self {
543        [bounds.x, bounds.y, bounds.width, bounds.height]
544    }
545}
546
547/// A two-dimensional layout size, encoded as `[width, height]`.
548#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
549#[serde(from = "[f64; 2]", into = "[f64; 2]")]
550pub struct LayoutSize {
551    pub width: f64,
552    pub height: f64,
553}
554
555impl From<[f64; 2]> for LayoutSize {
556    fn from([width, height]: [f64; 2]) -> Self {
557        Self { width, height }
558    }
559}
560
561impl From<LayoutSize> for [f64; 2] {
562    fn from(size: LayoutSize) -> Self {
563        [size.width, size.height]
564    }
565}
566
567/// A live scroll offset, encoded as `[x, y]`.
568#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
569#[serde(from = "[f64; 2]", into = "[f64; 2]")]
570pub struct LayoutOffset {
571    pub x: f64,
572    pub y: f64,
573}
574
575impl From<[f64; 2]> for LayoutOffset {
576    fn from([x, y]: [f64; 2]) -> Self {
577        Self { x, y }
578    }
579}
580
581impl From<LayoutOffset> for [f64; 2] {
582    fn from(offset: LayoutOffset) -> Self {
583        [offset.x, offset.y]
584    }
585}
586
587/// Computed CSS edges, encoded in shorthand order `[top, right, bottom, left]`.
588#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
589#[serde(from = "[f64; 4]", into = "[f64; 4]")]
590pub struct LayoutEdges {
591    pub top: f64,
592    pub right: f64,
593    pub bottom: f64,
594    pub left: f64,
595}
596
597impl From<[f64; 4]> for LayoutEdges {
598    fn from([top, right, bottom, left]: [f64; 4]) -> Self {
599        Self {
600            top,
601            right,
602            bottom,
603            left,
604        }
605    }
606}
607
608impl From<LayoutEdges> for [f64; 4] {
609    fn from(edges: LayoutEdges) -> Self {
610        [edges.top, edges.right, edges.bottom, edges.left]
611    }
612}
613
614/// One node's renderer-computed geometry.
615#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
616#[serde(rename_all = "camelCase")]
617pub struct LayoutDiagnosticRow {
618    pub node_id: u64,
619    pub bounds: LayoutBounds,
620    pub scroll_offset: LayoutOffset,
621    pub client_size: LayoutSize,
622    pub scroll_size: LayoutSize,
623    pub scroll_range: LayoutSize,
624    pub border: LayoutEdges,
625    pub padding: LayoutEdges,
626    pub content_size: LayoutSize,
627}
628
629#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
630#[serde(
631    tag = "action",
632    content = "params",
633    rename_all = "camelCase",
634    rename_all_fields = "camelCase"
635)]
636#[non_exhaustive]
637pub enum AgentAction {
638    /// Give one semantic node keyboard focus without activating it.
639    ///
640    /// Keyboard setup must not be implemented as a click: focusing a submit,
641    /// delete or fork button by clicking it performs the action before the key
642    /// under test is ever delivered.
643    Focus {
644        #[serde(alias = "node_id")]
645        node_id: u64,
646    },
647    /// Activate one semantic node without resolving it back through screen
648    /// coordinates. The runtime dispatches pointer, mouse and click events in
649    /// browser order directly to this target.
650    Click {
651        #[serde(alias = "node_id")]
652        node_id: u64,
653    },
654    /// Two activations in one runtime call, inside the platform's double-click
655    /// interval. Used for rows whose single click only selects or folds them.
656    DoubleClick {
657        #[serde(alias = "node_id")]
658        node_id: u64,
659    },
660    /// Present one semantic node as hovered. The target is still named by id;
661    /// the runtime owns any renderer-specific positioning needed to update CSS
662    /// hover state.
663    Hover {
664        #[serde(alias = "node_id")]
665        node_id: u64,
666    },
667    SetValue {
668        #[serde(alias = "node_id")]
669        node_id: u64,
670        value: String,
671    },
672    ScrollIntoView {
673        #[serde(alias = "node_id")]
674        node_id: u64,
675    },
676    /// Scroll a specific node's nearest scroll container by a delta.
677    ///
678    /// Wheel events carry no coordinates and are delivered to whatever the
679    /// document last saw hovered, which an injected pointer move does not
680    /// reliably set. That made every scrollable panel in the application
681    /// undrivable from outside, so a bug that only appears further down a long
682    /// page could not be reproduced without a human at the keyboard.
683    ScrollBy {
684        #[serde(alias = "node_id")]
685        node_id: u64,
686        #[serde(alias = "delta_x")]
687        delta_x: f64,
688        #[serde(alias = "delta_y")]
689        delta_y: f64,
690    },
691    Input(InputCommand),
692}
693
694#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
695#[serde(
696    tag = "input",
697    rename_all = "camelCase",
698    rename_all_fields = "camelCase"
699)]
700#[non_exhaustive]
701pub enum InputCommand {
702    Key {
703        phase: KeyPhase,
704        key: String,
705        code: String,
706        modifiers: Modifiers,
707    },
708    Pointer {
709        phase: PointerPhase,
710        x: f64,
711        y: f64,
712        button: u16,
713        modifiers: Modifiers,
714    },
715    Wheel {
716        #[serde(alias = "delta_x")]
717        delta_x: f64,
718        #[serde(alias = "delta_y")]
719        delta_y: f64,
720        phase: WheelPhase,
721        modifiers: Modifiers,
722    },
723}
724
725#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
726#[serde(rename_all = "camelCase")]
727pub struct Modifiers {
728    pub shift: bool,
729    pub control: bool,
730    pub alt: bool,
731    pub meta: bool,
732}
733
734#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
735#[serde(rename_all = "camelCase")]
736pub enum KeyPhase {
737    Down,
738    Up,
739}
740
741#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
742#[serde(rename_all = "camelCase")]
743pub enum PointerPhase {
744    Move,
745    Down,
746    Up,
747    Cancel,
748}
749
750#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
751#[serde(rename_all = "camelCase")]
752pub enum WheelPhase {
753    Started,
754    Moved,
755    Ended,
756}
757
758#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
759#[serde(rename_all = "camelCase")]
760pub struct RevisionSet {
761    pub document: u64,
762    /// Per-stage counters. A host fills one only when it can read that stage
763    /// from the runtime (blitz-dom counts Stylo traversals and layout passes);
764    /// a host that cannot leaves it at zero rather than copying `document`.
765    pub style: u64,
766    pub layout: u64,
767    pub paint: u64,
768}
769
770#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
771#[serde(rename_all = "camelCase")]
772pub struct DebugSnapshot {
773    pub revisions: RevisionSet,
774    pub active_window: Option<String>,
775    pub active_element: Option<u64>,
776    pub dom: Option<serde_json::Value>,
777    pub layout: Option<Vec<LayoutDiagnosticRow>>,
778    /// Resolved colours per node, when `include_computed_style` was set.
779    ///
780    /// Only the properties that decide legibility. A full longhand dump for
781    /// every node is megabytes of JSON nobody reads, and these are what a
782    /// question about invisible text actually needs.
783    #[serde(default, skip_serializing_if = "Option::is_none")]
784    pub computed_style: Option<serde_json::Value>,
785    pub metrics: RendererMetrics,
786}
787
788#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
789#[serde(rename_all = "camelCase")]
790pub struct AgentSnapshot {
791    pub revision: u64,
792    pub active_window: Option<String>,
793    pub focused_node: Option<u64>,
794    /// The client-space viewport in CSS pixels.
795    ///
796    /// The root and `main` boxes may be as tall as the whole document, so
797    /// their semantic bounds cannot tell an external pointer driver where the
798    /// physical window ends.
799    #[serde(default, skip_serializing_if = "Option::is_none")]
800    pub viewport: Option<[f64; 4]>,
801    pub nodes: Vec<SemanticNode>,
802}
803
804#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
805#[serde(rename_all = "camelCase")]
806pub struct SemanticNode {
807    /// The stable DOM identity supplied by the application, when present.
808    ///
809    /// This is deliberately separate from `id`: `id` is Blitz's ephemeral
810    /// node handle and may change whenever the element remounts. QA selectors
811    /// need the authored HTML `id` so a test keeps targeting the same control.
812    #[serde(default, skip_serializing_if = "Option::is_none")]
813    pub dom_id: Option<String>,
814    pub id: u64,
815    pub parent: Option<u64>,
816    pub role: String,
817    pub name: String,
818    pub value: Option<String>,
819    pub enabled: bool,
820    /// Whether the element participates in keyboard focus or native activation.
821    ///
822    /// Role alone cannot answer this for elements such as sortable column
823    /// headers: a plain `<th>` and `<th tabindex="0">` share a role, while only
824    /// the latter is an operable control.
825    #[serde(default)]
826    pub focusable: bool,
827    /// Whether this box is anchored to the window viewport.
828    ///
829    /// Fixed descendants keep their DOM parent even though layout hoists them
830    /// to the viewport. An external driver needs this bit so it does not clip
831    /// a visible fixed control against a scrolled ancestor's content box.
832    #[serde(default)]
833    pub viewport_fixed: bool,
834    pub visible: bool,
835    pub selected: bool,
836    pub bounds: Option<[f64; 4]>,
837    /// The library slot this element is, when it is part of a component.
838    ///
839    /// Read from `data-slot`, which a component library emits to name its own
840    /// parts. Addressing a control by the slot it *is* rather than by the text
841    /// it happens to carry is what lets a harness tell a trigger from the thing
842    /// it opens: those two routinely share an accessible name, so a check
843    /// written against the name passes whether or not anything happened.
844    #[serde(default, skip_serializing_if = "Option::is_none")]
845    pub slot: Option<String>,
846    /// ARIA and data attributes that target predicates may compare exactly.
847    /// Other DOM attributes stay out of semantic snapshots.
848    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
849    pub attributes: BTreeMap<String, String>,
850}
851
852#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
853#[serde(rename_all = "camelCase")]
854pub struct RendererMetrics {
855    pub revisions: RevisionSet,
856    /// Depth of a pending-work queue in front of the renderer.
857    ///
858    /// Blitz has no such queue: `View::redraw` resolves, paints and presents
859    /// inline on the event-loop thread. The one queue that exists, `ScriptQueue`,
860    /// lives inside the Tauri webview dispatcher and is not reachable from the
861    /// runtime, so this stays `None` rather than reporting a constant zero that
862    /// reads like a measured "nothing is backed up".
863    pub queue_depth: Option<u64>,
864    pub invalidations_coalesced: u64,
865    /// The most recently presented frame, as measured by blitz-shell.
866    ///
867    /// `None` until the window has drawn at least once.
868    pub frame: Option<FrameMetrics>,
869    /// Mean, p95 and worst case across the last few hundred presented frames.
870    pub frame_window: Option<FrameWindowMetrics>,
871    /// Cost of collecting this diagnostic snapshot. This measures the observer,
872    /// not the application, and is reported separately so the two are never
873    /// confused again.
874    pub snapshot: Option<SnapshotCost>,
875    /// What script execution cost, per backend poll.
876    ///
877    /// The frame numbers above cover resolve, paint and present, which is the
878    /// engine. Reactivity, event handlers, timers and microtasks are none of
879    /// those, so an application could present a 4ms frame and still feel slow
880    /// with nothing here to explain it. `None` until script has actually run.
881    pub script: Option<ScriptMetrics>,
882    pub resident_bytes: Option<u64>,
883}
884
885/// Script execution cost, in milliseconds, over the retained poll window.
886#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
887#[serde(rename_all = "camelCase")]
888pub struct ScriptMetrics {
889    pub mean_ms: f64,
890    pub p95_ms: f64,
891    pub max_ms: f64,
892    /// Polls that ran script, within the retained window.
893    pub window_polls: u64,
894    /// Every poll since launch, including the ones that found nothing to do.
895    pub total_polls: u64,
896    /// Polls that ran script since launch.
897    pub productive_polls: u64,
898    /// Total time spent in the script runtime since launch.
899    pub spent_ms: f64,
900    /// Where that time went, worst total first: event name or timer source,
901    /// call count, total milliseconds, worst single call.
902    pub breakdown: Vec<ScriptSource>,
903}
904
905/// One attributed source of script time.
906#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
907#[serde(rename_all = "camelCase")]
908pub struct ScriptSource {
909    pub label: String,
910    pub calls: u64,
911    pub total_ms: f64,
912    pub worst_ms: f64,
913}
914
915/// Timings of one real presented frame, in milliseconds.
916///
917/// Every `Option` here is a value blitz does not measure. They are left empty on
918/// purpose: a plausible-looking zero is worse than an admitted gap, because it
919/// makes a missing measurement look like a fast one.
920#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
921#[serde(rename_all = "camelCase")]
922pub struct FrameMetrics {
923    /// Wall time from the input event that caused the frame to the frame reaching
924    /// the screen. Blitz does not stamp input events with an arrival time and the
925    /// renderer reports no present timestamp, so there are no two clocks to
926    /// subtract.
927    pub input_to_present_ms: Option<f64>,
928    /// Style recalculation alone. Blitz runs style and layout inside a single
929    /// `resolve` pass and times only the pass, so the combined cost is in
930    /// `resolve_ms` instead.
931    pub style_ms: Option<f64>,
932    /// Layout alone. See `style_ms`.
933    pub layout_ms: Option<f64>,
934    /// Style plus layout, i.e. the `resolve` pass.
935    pub resolve_ms: f64,
936    /// Scene building: the `paint_scene` call that turns the resolved document
937    /// into renderer commands.
938    pub scene_ms: f64,
939    /// GPU submit alone. The renderer reports encode, submit and present as one
940    /// figure, which is in `renderer_ms`.
941    pub submit_ms: Option<f64>,
942    /// Present alone. See `submit_ms`.
943    pub present_ms: Option<f64>,
944    /// Everything the renderer did outside scene building: encode, submit and
945    /// present.
946    pub renderer_ms: f64,
947    /// `resolve_ms + scene_ms + renderer_ms`. CPU time inside `redraw`, not
948    /// input-to-photon latency.
949    pub total_ms: f64,
950    /// How long ago the frame started, measured when this response was built. A
951    /// large value means the app has been idle and these numbers are stale.
952    pub age_ms: f64,
953}
954
955/// Mean, 95th percentile and worst case for one timing series, in milliseconds.
956///
957/// The percentile and maximum matter more than the mean: a one-second average
958/// hides the single slow frame that is the only one a user notices.
959#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
960#[serde(rename_all = "camelCase")]
961pub struct TimingStats {
962    pub mean_ms: f64,
963    pub p95_ms: f64,
964    pub max_ms: f64,
965}
966
967/// Aggregate statistics over the recently presented frames.
968#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
969#[serde(rename_all = "camelCase")]
970pub struct FrameWindowMetrics {
971    /// Frames presented since process start.
972    pub frames_total: u64,
973    /// Frames the statistics below were computed over.
974    pub window_frames: u64,
975    /// Style plus layout.
976    pub resolve: TimingStats,
977    /// Scene building.
978    pub scene: TimingStats,
979    /// Encode, submit and present.
980    pub renderer: TimingStats,
981    /// Per-frame `resolve + scene + renderer`.
982    pub total: TimingStats,
983    /// Gap between the starts of consecutive frames, idle gaps excluded.
984    pub interval: TimingStats,
985    /// Frames per second across active intervals only. Blitz idles at zero FPS by
986    /// design, so counting idle time would make every measurement meaningless.
987    pub active_fps: f64,
988    /// Active intervals longer than 1.5 display refresh periods. Always zero when
989    /// `display_refresh_hz` is unknown.
990    pub missed_refreshes: u64,
991    pub display_refresh_hz: Option<f64>,
992}
993
994/// What it cost to answer this diagnostics request.
995#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
996#[serde(rename_all = "camelCase")]
997pub struct SnapshotCost {
998    /// Time spent draining the script event loop before reading the document.
999    pub poll_ms: f64,
1000    /// Time spent forcing a `resolve` so the reported layout is up to date.
1001    pub resolve_ms: f64,
1002    /// Total time spent building the response.
1003    pub total_ms: f64,
1004}
1005
1006#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1007#[serde(rename_all = "camelCase")]
1008pub struct ConsoleEntry {
1009    pub sequence: u64,
1010    pub level: String,
1011    pub message: String,
1012}
1013
1014#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1015#[serde(rename_all = "camelCase")]
1016pub struct RuntimeErrorEntry {
1017    pub sequence: u64,
1018    pub message: String,
1019    pub stack: String,
1020    pub revisions: RevisionSet,
1021}
1022
1023#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1024#[serde(tag = "state", rename_all = "camelCase")]
1025#[non_exhaustive]
1026pub enum LifecycleEvent {
1027    Relaunching { replacement_instance_id: String },
1028    Ready { instance_id: String },
1029    Quitting,
1030}
1031
1032#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1033#[serde(rename_all = "camelCase")]
1034pub struct DebugError {
1035    pub code: String,
1036    pub message: String,
1037}
1038
1039#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1040#[serde(rename_all = "camelCase")]
1041struct ToolCallParams {
1042    name: String,
1043    arguments: serde_json::Value,
1044}
1045
1046#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
1047#[serde(rename_all = "camelCase")]
1048struct ToolCallResult {
1049    content: Vec<TextContent>,
1050    structured_content: serde_json::Value,
1051    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1052    is_error: bool,
1053}
1054
1055#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1056struct TextContent {
1057    #[serde(rename = "type")]
1058    content_type: String,
1059    text: String,
1060}
1061
1062#[derive(Debug)]
1063#[non_exhaustive]
1064pub enum DebugProtocolError {
1065    Json(serde_json::Error),
1066    Rpc(JsonRpcError),
1067    NonTextFrame,
1068    RequestIdRequired,
1069    UnexpectedMessage,
1070    UnexpectedMethod(String),
1071    UnexpectedTool(String),
1072    PayloadTooLarge(usize),
1073}
1074
1075impl std::fmt::Display for DebugProtocolError {
1076    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1077        match self {
1078            Self::Json(error) => write!(formatter, "invalid debug frame: {error}"),
1079            Self::Rpc(error) => write!(
1080                formatter,
1081                "JSON-RPC error {}: {}",
1082                error.code, error.message
1083            ),
1084            Self::NonTextFrame => formatter.write_str("debug protocol requires a text frame"),
1085            Self::RequestIdRequired => formatter.write_str("tools/call requires a request id"),
1086            Self::UnexpectedMessage => formatter.write_str("unexpected JSON-RPC message"),
1087            Self::UnexpectedMethod(method) => write!(formatter, "unexpected method {method}"),
1088            Self::UnexpectedTool(tool) => write!(formatter, "unexpected tool {tool}"),
1089            Self::PayloadTooLarge(bytes) => write!(
1090                formatter,
1091                "debug response is {bytes} bytes, exceeding the {MAX_DEBUG_FRAME_BYTES}-byte frame limit"
1092            ),
1093        }
1094    }
1095}
1096
1097impl std::error::Error for DebugProtocolError {
1098    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1099        match self {
1100            Self::Json(error) => Some(error),
1101            _ => None,
1102        }
1103    }
1104}
1105
1106impl From<serde_json::Error> for DebugProtocolError {
1107    fn from(error: serde_json::Error) -> Self {
1108        Self::Json(error)
1109    }
1110}
1111
1112pub fn encode_agent_request(
1113    id: JsonRpcId,
1114    request: &AgentControlRequest,
1115) -> Result<WireMessage, DebugProtocolError> {
1116    encode_tool_request(id, AGENT_CONTROL_TOOL, request)
1117}
1118
1119pub fn decode_incoming(message: WireMessage) -> Result<IncomingRequest, DebugProtocolError> {
1120    decode_incoming_value(decode_wire_value(message)?)
1121}
1122
1123/// Decode an incoming request from a JSON value that the transport already parsed.
1124///
1125/// Server loops need the request id even when the typed payload is malformed. Keeping
1126/// the parsed value lets them recover that id and then consume the same allocation for
1127/// typed decoding instead of parsing the complete frame twice.
1128pub fn decode_incoming_value(
1129    value: serde_json::Value,
1130) -> Result<IncomingRequest, DebugProtocolError> {
1131    let JsonRpcMessage::Request(request) = decode_rpc_value(value)? else {
1132        return Err(DebugProtocolError::UnexpectedMessage);
1133    };
1134    match request.method.as_str() {
1135        MCP_INITIALIZE => Ok(IncomingRequest::Initialize {
1136            id: request.id.ok_or(DebugProtocolError::RequestIdRequired)?,
1137        }),
1138        MCP_INITIALIZED_NOTIFICATION if request.is_notification() => {
1139            Ok(IncomingRequest::Initialized)
1140        }
1141        MCP_TOOLS_LIST => Ok(IncomingRequest::ToolsList {
1142            id: request.id.ok_or(DebugProtocolError::RequestIdRequired)?,
1143        }),
1144        MCP_TOOLS_CALL => decode_incoming_tool_call(request),
1145        _ => Err(DebugProtocolError::UnexpectedMethod(request.method)),
1146    }
1147}
1148
1149/// The MCP handshake, answered on behalf of whichever host is serving.
1150///
1151/// `server_name` used to be the literal `tauri-runtime-blitz` (now izumo), because that is
1152/// where this code lived. There are three hosts now, and none of them is this
1153/// crate: a window runtime, a headless browser, and an embedder driving a
1154/// browser in-process. Each says its own name.
1155pub fn encode_initialize_response(
1156    id: JsonRpcId,
1157    server_name: &str,
1158    server_version: &str,
1159) -> Result<WireMessage, DebugProtocolError> {
1160    encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::result(
1161        Some(id),
1162        serde_json::json!({
1163            "protocolVersion": MCP_PROTOCOL_VERSION,
1164            "capabilities": {"tools": {"listChanged": false}},
1165            "serverInfo": {"name": server_name, "version": server_version}
1166        }),
1167    )))
1168}
1169
1170/// The tool list, which is the one place a build's *capability* shows.
1171///
1172/// `include_diagnostics` is the server's `diagnostics` feature. The protocol
1173/// types for diagnostics exist unconditionally, so a build that cannot collect
1174/// them has to say so here rather than by failing to define them. Advertising
1175/// a tool that answers every call with an error would be worse than omitting
1176/// it: a client would report the app as broken instead of as a plain build.
1177pub fn encode_tools_list_response(
1178    id: JsonRpcId,
1179    include_diagnostics: bool,
1180) -> Result<WireMessage, DebugProtocolError> {
1181    let mut tools = vec![serde_json::json!({
1182        "name": AGENT_CONTROL_TOOL,
1183        "description": "Inspect and operate the native Blitz semantic UI tree",
1184        "inputSchema": schema_for::<TargetEnvelope<AgentControlRequest>>()?
1185    })];
1186    if include_diagnostics {
1187        tools.push(serde_json::json!({
1188            "name": DIAGNOSTICS_TOOL,
1189            "description": "Observe Blitz DOM, layout, errors, and renderer metrics",
1190            "inputSchema": schema_for::<TargetEnvelope<DiagnosticsRequest>>()?
1191        }));
1192    }
1193    encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::result(
1194        Some(id),
1195        serde_json::json!({"tools": tools}),
1196    )))
1197}
1198
1199fn schema_for<T: JsonSchema>() -> Result<serde_json::Value, DebugProtocolError> {
1200    serde_json::to_value(schemars::schema_for!(T)).map_err(DebugProtocolError::from)
1201}
1202
1203pub fn encode_rpc_error(
1204    id: Option<JsonRpcId>,
1205    error: JsonRpcError,
1206) -> Result<WireMessage, DebugProtocolError> {
1207    encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::error(id, error)))
1208}
1209
1210pub fn decode_agent_request(
1211    message: WireMessage,
1212) -> Result<(JsonRpcId, AgentControlRequest), DebugProtocolError> {
1213    decode_tool_request(message, AGENT_CONTROL_TOOL)
1214}
1215
1216pub fn encode_diagnostics_request(
1217    id: JsonRpcId,
1218    request: &DiagnosticsRequest,
1219) -> Result<WireMessage, DebugProtocolError> {
1220    encode_tool_request(id, DIAGNOSTICS_TOOL, request)
1221}
1222
1223pub fn decode_diagnostics_request(
1224    message: WireMessage,
1225) -> Result<(JsonRpcId, DiagnosticsRequest), DebugProtocolError> {
1226    decode_tool_request(message, DIAGNOSTICS_TOOL)
1227}
1228
1229pub fn encode_response(
1230    id: JsonRpcId,
1231    response: &DebugResponse,
1232) -> Result<WireMessage, DebugProtocolError> {
1233    #[derive(Serialize)]
1234    #[serde(untagged)]
1235    enum Payload<'a> {
1236        Targeted(&'a TargetReply),
1237        Plain(&'a DebugResponse),
1238    }
1239    #[derive(Serialize)]
1240    #[serde(rename_all = "camelCase")]
1241    struct BorrowedToolCallResult<'a> {
1242        content: [TextContent; 1],
1243        structured_content: Payload<'a>,
1244        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1245        is_error: bool,
1246    }
1247
1248    #[derive(Serialize)]
1249    struct RpcResponse<'a> {
1250        jsonrpc: &'static str,
1251        id: JsonRpcId,
1252        result: BorrowedToolCallResult<'a>,
1253    }
1254
1255    let message = WireMessage::text(serde_json::to_string(&RpcResponse {
1256        jsonrpc: "2.0",
1257        id,
1258        result: BorrowedToolCallResult {
1259            content: [TextContent {
1260                content_type: "text".into(),
1261                // structuredContent is the typed payload consumed by the local
1262                // client. Repeating a full DOM snapshot as text doubled the frame
1263                // and could cross endpoint-libs' 16 MiB safety limit, which closed
1264                // an otherwise healthy socket. Keep the required human-readable
1265                // MCP content concise and send the snapshot exactly once.
1266                text: response_summary(response),
1267            }],
1268            structured_content: match response {
1269                DebugResponse::Targeted(reply) => Payload::Targeted(reply),
1270                other => Payload::Plain(other),
1271            },
1272            is_error: matches!(response.unscoped(), DebugResponse::Error(_)),
1273        },
1274    })?);
1275    if matches!(&message, WireMessage::Text(text) if text.len() > MAX_DEBUG_FRAME_BYTES) {
1276        let WireMessage::Text(text) = &message else {
1277            unreachable!("text encoding checked above")
1278        };
1279        return Err(DebugProtocolError::PayloadTooLarge(text.len()));
1280    }
1281    Ok(message)
1282}
1283
1284fn response_summary(response: &DebugResponse) -> String {
1285    match response {
1286        DebugResponse::Ack => "ok".into(),
1287        DebugResponse::Targets(targets) => format!("{} inspection targets", targets.len()),
1288        DebugResponse::Targeted(reply) => response_summary(&reply.response),
1289        DebugResponse::AgentSnapshot(snapshot) => {
1290            format!("semantic snapshot with {} nodes", snapshot.nodes.len())
1291        }
1292        DebugResponse::Snapshot(_) => "diagnostic snapshot".into(),
1293        DebugResponse::Metrics(_) => "renderer metrics".into(),
1294        DebugResponse::Idle(_) => "renderer idle".into(),
1295        DebugResponse::WindowComposition(_) => "native window composition".into(),
1296        DebugResponse::Captured(image) => {
1297            format!("captured {}x{} image", image.width, image.height)
1298        }
1299        DebugResponse::Condensation(condensation) => {
1300            format!("condensed page, {} level", condensation.level_name())
1301        }
1302        DebugResponse::WebGpu(_) => "WebGPU report".into(),
1303        DebugResponse::WebGpuBuffer(snapshot) => {
1304            format!(
1305                "WebGPU buffer {:?} at submit {}",
1306                snapshot.label, snapshot.submit
1307            )
1308        }
1309        DebugResponse::Evaluated(_) => "evaluated script".into(),
1310        DebugResponse::Error(error) => error.message.clone(),
1311    }
1312}
1313
1314pub fn decode_response(
1315    message: WireMessage,
1316) -> Result<(JsonRpcId, DebugResponse), DebugProtocolError> {
1317    decode_response_value(decode_wire_value(message)?)
1318}
1319
1320pub fn decode_response_value(
1321    value: serde_json::Value,
1322) -> Result<(JsonRpcId, DebugResponse), DebugProtocolError> {
1323    let JsonRpcMessage::Response(response) = decode_rpc_value(value)? else {
1324        return Err(DebugProtocolError::UnexpectedMessage);
1325    };
1326    let id = response.id.ok_or(DebugProtocolError::RequestIdRequired)?;
1327    if let Some(error) = response.error {
1328        return Err(DebugProtocolError::Rpc(error));
1329    }
1330    let result: ToolCallResult = serde_json::from_value(
1331        response
1332            .result
1333            .ok_or(DebugProtocolError::UnexpectedMessage)?,
1334    )?;
1335    let response = if result.structured_content.get("context").is_some() {
1336        DebugResponse::Targeted(serde_json::from_value(result.structured_content)?)
1337    } else {
1338        serde_json::from_value(result.structured_content)?
1339    };
1340    Ok((id, response))
1341}
1342
1343pub fn encode_agent_event(event: &AgentControlEvent) -> Result<WireMessage, DebugProtocolError> {
1344    encode_notification(AGENT_EVENT_NOTIFICATION, event)
1345}
1346
1347pub fn decode_agent_event(message: WireMessage) -> Result<AgentControlEvent, DebugProtocolError> {
1348    decode_notification(message, AGENT_EVENT_NOTIFICATION)
1349}
1350
1351pub fn encode_diagnostics_event(event: &DebugEvent) -> Result<WireMessage, DebugProtocolError> {
1352    encode_notification(DIAGNOSTICS_EVENT_NOTIFICATION, event)
1353}
1354
1355pub fn encode_target_event(event: &DiagnosticRecord) -> Result<WireMessage, DebugProtocolError> {
1356    let frame = encode_notification(DIAGNOSTICS_EVENT_NOTIFICATION, event)?;
1357    match &frame {
1358        WireMessage::Text(text) if text.len() > MAX_DEBUG_FRAME_BYTES => {
1359            Err(DebugProtocolError::PayloadTooLarge(text.len()))
1360        }
1361        _ => Ok(frame),
1362    }
1363}
1364
1365pub fn encode_diagnostic_overflow(
1366    first: u64,
1367    last: u64,
1368) -> Result<WireMessage, DebugProtocolError> {
1369    encode_notification(
1370        DIAGNOSTICS_EVENT_NOTIFICATION,
1371        &serde_json::json!({
1372            "event": "diagnosticOverflow",
1373            "value": {"code": "diagnosticOverflow", "firstSequence": first, "lastSequence": last}
1374        }),
1375    )
1376}
1377
1378pub fn decode_diagnostics_event(message: WireMessage) -> Result<DebugEvent, DebugProtocolError> {
1379    decode_notification(message, DIAGNOSTICS_EVENT_NOTIFICATION)
1380}
1381
1382pub fn decode_diagnostics_event_value(
1383    value: serde_json::Value,
1384) -> Result<DebugEvent, DebugProtocolError> {
1385    decode_notification_value(value, DIAGNOSTICS_EVENT_NOTIFICATION)
1386}
1387
1388fn encode_tool_request<T: Serialize>(
1389    id: JsonRpcId,
1390    tool: &str,
1391    request: &T,
1392) -> Result<WireMessage, DebugProtocolError> {
1393    let params = ToolCallParams {
1394        name: tool.into(),
1395        arguments: serde_json::to_value(request)?,
1396    };
1397    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
1398        id,
1399        MCP_TOOLS_CALL,
1400        serde_json::to_value(params)?,
1401    )))
1402}
1403
1404fn decode_tool_request<T: DeserializeOwned>(
1405    message: WireMessage,
1406    expected_tool: &str,
1407) -> Result<(JsonRpcId, T), DebugProtocolError> {
1408    let JsonRpcMessage::Request(request) = decode_rpc(message)? else {
1409        return Err(DebugProtocolError::UnexpectedMessage);
1410    };
1411    if request.method != MCP_TOOLS_CALL {
1412        return Err(DebugProtocolError::UnexpectedMethod(request.method));
1413    }
1414    let id = request.id.ok_or(DebugProtocolError::RequestIdRequired)?;
1415    let params: ToolCallParams = serde_json::from_value(request.params.ok_or_else(|| {
1416        DebugProtocolError::Rpc(JsonRpcError::new(
1417            INVALID_PARAMS,
1418            "missing tools/call params",
1419        ))
1420    })?)?;
1421    if params.name != expected_tool {
1422        return Err(DebugProtocolError::UnexpectedTool(params.name));
1423    }
1424    Ok((id, serde_json::from_value(params.arguments)?))
1425}
1426
1427fn decode_incoming_tool_call(
1428    request: JsonRpcRequest,
1429) -> Result<IncomingRequest, DebugProtocolError> {
1430    let id = request.id.ok_or(DebugProtocolError::RequestIdRequired)?;
1431    let params: ToolCallParams = serde_json::from_value(request.params.ok_or_else(|| {
1432        DebugProtocolError::Rpc(JsonRpcError::new(
1433            INVALID_PARAMS,
1434            "missing tools/call params",
1435        ))
1436    })?)?;
1437    let targeted = [
1438        "target",
1439        "expectedGeneration",
1440        "expectedDocumentId",
1441        "allTargets",
1442        "afterSequence",
1443    ]
1444    .iter()
1445    .any(|key| params.arguments.get(*key).is_some());
1446    match params.name.as_str() {
1447        AGENT_CONTROL_TOOL => {
1448            let envelope: TargetEnvelope<AgentControlRequest> =
1449                serde_json::from_value(params.arguments)?;
1450            if targeted || matches!(envelope.request, AgentControlRequest::ListTargets) {
1451                Ok(IncomingRequest::Targeted {
1452                    id,
1453                    request: TargetRequest {
1454                        options: envelope.options,
1455                        command: TargetCommand::Agent(envelope.request),
1456                    },
1457                })
1458            } else {
1459                Ok(IncomingRequest::Agent {
1460                    id,
1461                    request: envelope.request,
1462                })
1463            }
1464        }
1465        DIAGNOSTICS_TOOL => {
1466            let envelope: TargetEnvelope<DiagnosticsRequest> =
1467                serde_json::from_value(params.arguments)?;
1468            if targeted {
1469                Ok(IncomingRequest::Targeted {
1470                    id,
1471                    request: TargetRequest {
1472                        options: envelope.options,
1473                        command: TargetCommand::Diagnostics(envelope.request),
1474                    },
1475                })
1476            } else {
1477                Ok(IncomingRequest::Diagnostics {
1478                    id,
1479                    request: envelope.request,
1480                })
1481            }
1482        }
1483        _ => Err(DebugProtocolError::UnexpectedTool(params.name)),
1484    }
1485}
1486
1487fn encode_notification<T: Serialize>(
1488    method: &str,
1489    value: &T,
1490) -> Result<WireMessage, DebugProtocolError> {
1491    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::notification(
1492        method,
1493        serde_json::to_value(value)?,
1494    )))
1495}
1496
1497fn decode_notification<T: DeserializeOwned>(
1498    message: WireMessage,
1499    expected_method: &str,
1500) -> Result<T, DebugProtocolError> {
1501    decode_notification_value(decode_wire_value(message)?, expected_method)
1502}
1503
1504fn decode_notification_value<T: DeserializeOwned>(
1505    value: serde_json::Value,
1506    expected_method: &str,
1507) -> Result<T, DebugProtocolError> {
1508    let JsonRpcMessage::Request(request) = decode_rpc_value(value)? else {
1509        return Err(DebugProtocolError::UnexpectedMessage);
1510    };
1511    if !request.is_notification() {
1512        return Err(DebugProtocolError::Rpc(JsonRpcError::new(
1513            INVALID_REQUEST,
1514            "notification must not contain an id",
1515        )));
1516    }
1517    if request.method != expected_method {
1518        return Err(DebugProtocolError::UnexpectedMethod(request.method));
1519    }
1520    serde_json::from_value(request.params.ok_or_else(|| {
1521        DebugProtocolError::Rpc(JsonRpcError::new(
1522            INVALID_PARAMS,
1523            "missing notification params",
1524        ))
1525    })?)
1526    .map_err(Into::into)
1527}
1528
1529pub fn encode_rpc(message: JsonRpcMessage) -> Result<WireMessage, DebugProtocolError> {
1530    Ok(WireMessage::text(serde_json::to_string(&message)?))
1531}
1532
1533/// The request id of an incoming frame, recovered without consuming it.
1534///
1535/// A decode failure still has to be answered, and answered *to the caller*. A
1536/// JSON-RPC client matches responses by id, so an error carrying `id: null` is
1537/// delivered and then discarded, and the caller waits until it times out. That
1538/// turns "you named a field wrong" into "the app is hung", which is a much
1539/// worse and much slower thing to debug.
1540pub fn peek_request_id(message: &WireMessage) -> Option<JsonRpcId> {
1541    let WireMessage::Text(text) = message else {
1542        return None;
1543    };
1544    match parse(text) {
1545        Ok(JsonRpcMessage::Request(request)) => request.id,
1546        _ => None,
1547    }
1548}
1549
1550/// Recover a request id from an already parsed JSON value.
1551pub fn peek_value_request_id(value: &serde_json::Value) -> Option<JsonRpcId> {
1552    serde_json::from_value(value.get("id")?.clone()).ok()
1553}
1554
1555pub fn decode_wire_value(message: WireMessage) -> Result<serde_json::Value, DebugProtocolError> {
1556    let WireMessage::Text(text) = message else {
1557        return Err(DebugProtocolError::NonTextFrame);
1558    };
1559    serde_json::from_str(&text).map_err(Into::into)
1560}
1561
1562pub fn decode_rpc_value(value: serde_json::Value) -> Result<JsonRpcMessage, DebugProtocolError> {
1563    serde_json::from_value(value).map_err(Into::into)
1564}
1565
1566pub fn decode_rpc(message: WireMessage) -> Result<JsonRpcMessage, DebugProtocolError> {
1567    let WireMessage::Text(text) = message else {
1568        return Err(DebugProtocolError::NonTextFrame);
1569    };
1570    parse(&text).map_err(DebugProtocolError::Rpc)
1571}
1572
1573/// The framing the control socket speaks, and the socket type it speaks over.
1574///
1575/// Re-exported so a consumer that serves or fakes this protocol does not have to
1576/// depend on endpoint-libs and nagoya directly to name the two halves of a
1577/// connection. There is no tokio bridge here any more: the transport is nagoya
1578/// end to end.
1579#[cfg(any(feature = "server", feature = "client"))]
1580pub use endpoint_libs::libs::ws::transport::nagoya::NagoyaStream;
1581
1582#[cfg(all(test, feature = "engine"))]
1583mod test_document;
1584
1585#[cfg(test)]
1586mod tests {
1587    use super::*;
1588
1589    fn key_request() -> AgentControlRequest {
1590        AgentControlRequest::Act(AgentAction::Input(InputCommand::Key {
1591            phase: KeyPhase::Down,
1592            key: "2".into(),
1593            code: "Digit2".into(),
1594            modifiers: Modifiers {
1595                meta: true,
1596                ..Default::default()
1597            },
1598        }))
1599    }
1600
1601    #[test]
1602    fn typed_modifier_input_round_trips_mcp_tools_call() {
1603        let request = key_request();
1604        let id = JsonRpcId::Number(7);
1605        assert_eq!(
1606            decode_agent_request(encode_agent_request(id.clone(), &request).unwrap()).unwrap(),
1607            (id, request)
1608        );
1609    }
1610
1611    #[test]
1612    fn node_addressed_actions_round_trip() {
1613        for action in [
1614            AgentAction::Focus { node_id: 8 },
1615            AgentAction::Click { node_id: 9 },
1616            AgentAction::DoubleClick { node_id: 10 },
1617            AgentAction::Hover { node_id: 11 },
1618            AgentAction::SetValue {
1619                node_id: 12,
1620                value: "fixture".into(),
1621            },
1622            AgentAction::ScrollIntoView { node_id: 13 },
1623            AgentAction::ScrollBy {
1624                node_id: 14,
1625                delta_x: 1.0,
1626                delta_y: -2.0,
1627            },
1628            AgentAction::Input(InputCommand::Pointer {
1629                phase: PointerPhase::Move,
1630                x: 3.0,
1631                y: 4.0,
1632                button: 0,
1633                modifiers: Modifiers::default(),
1634            }),
1635            AgentAction::Input(InputCommand::Wheel {
1636                delta_x: 0.0,
1637                delta_y: 5.0,
1638                phase: WheelPhase::Moved,
1639                modifiers: Modifiers::default(),
1640            }),
1641        ] {
1642            let request = AgentControlRequest::Act(action);
1643            let id = JsonRpcId::Number(8);
1644            assert_eq!(
1645                decode_agent_request(encode_agent_request(id.clone(), &request).unwrap()).unwrap(),
1646                (id, request)
1647            );
1648        }
1649
1650        for request in [
1651            AgentControlRequest::Navigate {
1652                url: "/second.html".into(),
1653            },
1654            AgentControlRequest::Relaunch,
1655            AgentControlRequest::Quit,
1656        ] {
1657            let id = JsonRpcId::Number(9);
1658            assert_eq!(
1659                decode_agent_request(encode_agent_request(id.clone(), &request).unwrap()).unwrap(),
1660                (id, request)
1661            );
1662        }
1663    }
1664
1665    #[test]
1666    fn capture_scale_is_bounded_before_a_renderer_allocates() {
1667        for scale in [f32::NAN, f32::INFINITY, -1.0, 0.0, 0.24, 8.01] {
1668            assert!(
1669                CaptureRequest {
1670                    node_id: None,
1671                    scale
1672                }
1673                .validate()
1674                .is_err()
1675            );
1676        }
1677        for scale in [0.25, 1.0, 4.0, 8.0] {
1678            assert!(
1679                CaptureRequest {
1680                    node_id: None,
1681                    scale
1682                }
1683                .validate()
1684                .is_ok()
1685            );
1686        }
1687    }
1688
1689    #[test]
1690    fn oversized_capture_response_is_rejected_before_framing() {
1691        let response = DebugResponse::Captured(CapturedImage {
1692            width: 1,
1693            height: 1,
1694            rgba_base64: "A".repeat(MAX_DEBUG_FRAME_BYTES),
1695            node_id: None,
1696        });
1697        assert!(matches!(
1698            encode_response(JsonRpcId::Number(1), &response),
1699            Err(DebugProtocolError::PayloadTooLarge(_))
1700        ));
1701    }
1702
1703    #[test]
1704    fn click_wire_shape_is_literal_and_foreign_client_readable() {
1705        let message = encode_agent_request(
1706            JsonRpcId::Number(3),
1707            &AgentControlRequest::Act(AgentAction::Click { node_id: 9 }),
1708        )
1709        .unwrap();
1710        let WireMessage::Text(text) = message else {
1711            panic!("debug requests must be text frames")
1712        };
1713        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
1714        assert_eq!(value["method"], MCP_TOOLS_CALL);
1715        assert_eq!(value["params"]["name"], AGENT_CONTROL_TOOL);
1716        assert_eq!(value["params"]["arguments"]["command"], "act");
1717        assert_eq!(value["params"]["arguments"]["params"]["action"], "click");
1718        assert_eq!(
1719            value["params"]["arguments"]["params"]["params"]["nodeId"],
1720            9
1721        );
1722    }
1723
1724    #[test]
1725    fn unrelated_mcp_tool_is_rejected_explicitly() {
1726        let message = JsonRpcMessage::Request(JsonRpcRequest::call(
1727            JsonRpcId::Number(1),
1728            MCP_TOOLS_CALL,
1729            serde_json::json!({"name": "other.tool", "arguments": {}}),
1730        ));
1731        assert!(matches!(
1732            decode_agent_request(encode_rpc(message).unwrap()),
1733            Err(DebugProtocolError::UnexpectedTool(tool)) if tool == "other.tool"
1734        ));
1735    }
1736
1737    #[test]
1738    fn responses_and_notifications_round_trip() {
1739        let id = JsonRpcId::Number(19);
1740        let response = DebugResponse::Ack;
1741        assert_eq!(
1742            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap(),
1743            (id, response)
1744        );
1745
1746        let event = AgentControlEvent::TreeChanged { revision: 12 };
1747        assert_eq!(
1748            decode_agent_event(encode_agent_event(&event).unwrap()).unwrap(),
1749            event
1750        );
1751
1752        let event = DebugEvent::PaintCommitted { revision: 13 };
1753        assert_eq!(
1754            decode_diagnostics_event(encode_diagnostics_event(&event).unwrap()).unwrap(),
1755            event
1756        );
1757    }
1758
1759    #[test]
1760    fn diagnostics_metrics_request_and_response_round_trip() {
1761        let id = JsonRpcId::Number(23);
1762        assert_eq!(
1763            decode_diagnostics_request(
1764                encode_diagnostics_request(id.clone(), &DiagnosticsRequest::Metrics).unwrap()
1765            )
1766            .unwrap(),
1767            (id.clone(), DiagnosticsRequest::Metrics)
1768        );
1769
1770        let response = DebugResponse::Metrics(RendererMetrics {
1771            resident_bytes: Some(4096),
1772            ..Default::default()
1773        });
1774        assert_eq!(
1775            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap(),
1776            (id, response)
1777        );
1778    }
1779
1780    #[test]
1781    fn native_window_composition_round_trips_without_pixel_inference() {
1782        let id = JsonRpcId::Number(24);
1783        assert_eq!(
1784            decode_diagnostics_request(
1785                encode_diagnostics_request(id.clone(), &DiagnosticsRequest::WindowComposition)
1786                    .unwrap()
1787            )
1788            .unwrap(),
1789            (id.clone(), DiagnosticsRequest::WindowComposition)
1790        );
1791
1792        let response = DebugResponse::WindowComposition(WindowComposition {
1793            supported: true,
1794            surface_transparent: true,
1795            glass_enabled: true,
1796            glass_backend: Some("nativeGlass".into()),
1797            tint_rgba: Some([174, 50, 112, 0]),
1798            radius: Some(12.0),
1799        });
1800        assert_eq!(
1801            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap(),
1802            (id, response)
1803        );
1804    }
1805
1806    #[test]
1807    fn tools_list_describes_the_typed_requests() {
1808        let message = encode_tools_list_response(JsonRpcId::Number(31), true).unwrap();
1809        let JsonRpcMessage::Response(response) = decode_rpc(message).unwrap() else {
1810            panic!("tools/list should be a response")
1811        };
1812        let tools = response.result.unwrap()["tools"]
1813            .as_array()
1814            .unwrap()
1815            .to_vec();
1816
1817        let agent = &tools[0]["inputSchema"];
1818        let diagnostics = &tools[1]["inputSchema"];
1819        assert!(
1820            agent.get("oneOf").is_some() || agent.get("$defs").is_some(),
1821            "agent schema must describe its tagged command variants: {agent}"
1822        );
1823        assert!(
1824            diagnostics.get("oneOf").is_some() || diagnostics.get("$defs").is_some(),
1825            "diagnostics schema must describe its tagged command variants: {diagnostics}"
1826        );
1827        assert_ne!(agent, &serde_json::json!({"type": "object"}));
1828        assert_ne!(diagnostics, &serde_json::json!({"type": "object"}));
1829        let agent_text = agent.to_string();
1830        let diagnostics_text = diagnostics.to_string();
1831        assert!(agent_text.contains("command") && agent_text.contains("inspect"));
1832        assert!(diagnostics_text.contains("command") && diagnostics_text.contains("metrics"));
1833    }
1834
1835    #[test]
1836    fn typed_layout_row_preserves_the_existing_wire_shape() {
1837        let row = LayoutDiagnosticRow {
1838            node_id: 7,
1839            bounds: LayoutBounds {
1840                x: 1.0,
1841                y: 2.0,
1842                width: 30.0,
1843                height: 40.0,
1844            },
1845            scroll_offset: LayoutOffset { x: 3.0, y: 4.0 },
1846            client_size: LayoutSize {
1847                width: 30.0,
1848                height: 40.0,
1849            },
1850            scroll_size: LayoutSize {
1851                width: 50.0,
1852                height: 60.0,
1853            },
1854            scroll_range: LayoutSize {
1855                width: 20.0,
1856                height: 20.0,
1857            },
1858            border: LayoutEdges {
1859                top: 1.0,
1860                right: 2.0,
1861                bottom: 3.0,
1862                left: 4.0,
1863            },
1864            padding: LayoutEdges {
1865                top: 5.0,
1866                right: 6.0,
1867                bottom: 7.0,
1868                left: 8.0,
1869            },
1870            content_size: LayoutSize {
1871                width: 10.0,
1872                height: 11.0,
1873            },
1874        };
1875        let old_wire_shape = serde_json::json!({
1876            "nodeId": 7,
1877            "bounds": [1.0, 2.0, 30.0, 40.0],
1878            "scrollOffset": [3.0, 4.0],
1879            "clientSize": [30.0, 40.0],
1880            "scrollSize": [50.0, 60.0],
1881            "scrollRange": [20.0, 20.0],
1882            "border": [1.0, 2.0, 3.0, 4.0],
1883            "padding": [5.0, 6.0, 7.0, 8.0],
1884            "contentSize": [10.0, 11.0]
1885        });
1886
1887        assert_eq!(serde_json::to_value(&row).unwrap(), old_wire_shape);
1888        assert_eq!(
1889            serde_json::from_value::<LayoutDiagnosticRow>(old_wire_shape).unwrap(),
1890            row
1891        );
1892    }
1893
1894    #[test]
1895    fn semantic_node_keeps_authored_dom_identity_separate_from_node_handle() {
1896        let node = SemanticNode {
1897            dom_id: Some("settings-save".into()),
1898            id: 42,
1899            parent: None,
1900            role: "button".into(),
1901            name: "Save settings".into(),
1902            value: None,
1903            enabled: true,
1904            focusable: true,
1905            viewport_fixed: false,
1906            visible: true,
1907            selected: false,
1908            bounds: Some([1.0, 2.0, 30.0, 20.0]),
1909            slot: Some("button".into()),
1910            attributes: [("aria-sort".into(), "ascending".into())]
1911                .into_iter()
1912                .collect(),
1913        };
1914
1915        let encoded = serde_json::to_value(&node).unwrap();
1916        assert_eq!(encoded["domId"], "settings-save");
1917        assert_eq!(encoded["id"], 42);
1918        assert_eq!(encoded["attributes"]["aria-sort"], "ascending");
1919        assert_eq!(
1920            serde_json::from_value::<SemanticNode>(encoded).unwrap(),
1921            node
1922        );
1923    }
1924
1925    #[test]
1926    fn frame_metrics_round_trip_and_keep_unmeasured_fields_empty() {
1927        let id = JsonRpcId::Number(24);
1928        let response = DebugResponse::Metrics(RendererMetrics {
1929            frame: Some(FrameMetrics {
1930                resolve_ms: 1.5,
1931                scene_ms: 2.25,
1932                renderer_ms: 3.0,
1933                total_ms: 6.75,
1934                age_ms: 12.0,
1935                ..Default::default()
1936            }),
1937            frame_window: Some(FrameWindowMetrics {
1938                frames_total: 900,
1939                window_frames: 256,
1940                total: TimingStats {
1941                    mean_ms: 6.0,
1942                    p95_ms: 11.0,
1943                    max_ms: 40.0,
1944                },
1945                active_fps: 59.4,
1946                missed_refreshes: 2,
1947                display_refresh_hz: Some(60.0),
1948                ..Default::default()
1949            }),
1950            snapshot: Some(SnapshotCost {
1951                poll_ms: 0.5,
1952                resolve_ms: 1.0,
1953                total_ms: 4.0,
1954            }),
1955            ..Default::default()
1956        });
1957
1958        let (decoded_id, decoded) =
1959            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap();
1960        assert_eq!(decoded_id, id);
1961        assert_eq!(decoded, response);
1962
1963        let DebugResponse::Metrics(metrics) = decoded else {
1964            panic!("expected renderer metrics")
1965        };
1966        let frame = metrics.frame.unwrap();
1967        // Fields blitz does not measure must stay empty on the wire. Sending 0.0
1968        // is the defect this guards: a zero reads as "measured, and fast".
1969        assert_eq!(frame.input_to_present_ms, None);
1970        assert_eq!(frame.style_ms, None);
1971        assert_eq!(frame.layout_ms, None);
1972        assert_eq!(frame.submit_ms, None);
1973        assert_eq!(frame.present_ms, None);
1974        assert_eq!(metrics.queue_depth, None);
1975    }
1976}