1#[cfg(feature = "client")]
69pub mod client;
70
71pub mod condense;
76#[cfg(all(unix, any(feature = "server", feature = "client")))]
77mod control_directory;
78#[cfg(feature = "engine")]
80pub mod document;
81#[allow(clippy::disallowed_methods)]
83pub mod guarded_writer;
84#[cfg(feature = "engine")]
86pub mod in_process;
87
88#[cfg(feature = "engine")]
103pub trait ControlScriptBackend: blitz_dom::Document {
104 fn dispatch_dom_event(&mut self, event: blitz_traits::events::DomEvent);
106
107 fn handle_pointer_move_to_node(
109 &mut self,
110 event: blitz_traits::events::BlitzPointerEvent,
111 node: blitz_dom::NodeId,
112 );
113
114 fn handle_ui_event_to_node(
116 &mut self,
117 event: blitz_traits::events::UiEvent,
118 node: blitz_dom::NodeId,
119 );
120
121 fn script_metrics(&self) -> Option<ScriptMetrics> {
123 None
124 }
125}
126#[cfg(any(feature = "server", feature = "client"))]
128pub mod latest;
129pub mod lifecycle;
131pub mod target;
132pub use target::*;
133#[cfg(any(feature = "server", feature = "client"))]
134pub mod journal;
135pub mod webgpu;
137pub use webgpu::*;
138#[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
162pub const DEBUG_PROTOCOL_VERSION: u32 = 2;
167pub 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 Navigate {
237 url: String,
238 },
239 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 WindowComposition,
277 Capture(CaptureRequest),
293 WebGpuInspect,
299 WebGpuCapture {
304 target: String,
305 },
306 WebGpuBuffer {
315 target: String,
316 offset: u64,
317 length: Option<u64>,
318 },
319 Evaluate {
326 script: String,
327 },
328}
329
330#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
332#[serde(rename_all = "camelCase")]
333pub struct CaptureRequest {
334 pub node_id: Option<u64>,
340 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#[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 pub rgba_base64: String,
378 pub node_id: Option<u64>,
380}
381
382#[cfg(feature = "capture")]
383impl CapturedImage {
384 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 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)] #[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 Condensation(condense::Condensation),
439 Evaluated(serde_json::Value),
441 Error(DebugError),
442}
443
444#[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)] #[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 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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
514 pub node_ids: Vec<u64>,
515}
516
517#[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#[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#[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#[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#[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 Focus {
644 #[serde(alias = "node_id")]
645 node_id: u64,
646 },
647 Click {
651 #[serde(alias = "node_id")]
652 node_id: u64,
653 },
654 DoubleClick {
657 #[serde(alias = "node_id")]
658 node_id: u64,
659 },
660 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 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 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 #[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 #[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 #[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 #[serde(default)]
826 pub focusable: bool,
827 #[serde(default)]
833 pub viewport_fixed: bool,
834 pub visible: bool,
835 pub selected: bool,
836 pub bounds: Option<[f64; 4]>,
837 #[serde(default, skip_serializing_if = "Option::is_none")]
845 pub slot: Option<String>,
846 #[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 pub queue_depth: Option<u64>,
864 pub invalidations_coalesced: u64,
865 pub frame: Option<FrameMetrics>,
869 pub frame_window: Option<FrameWindowMetrics>,
871 pub snapshot: Option<SnapshotCost>,
875 pub script: Option<ScriptMetrics>,
882 pub resident_bytes: Option<u64>,
883}
884
885#[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 pub window_polls: u64,
894 pub total_polls: u64,
896 pub productive_polls: u64,
898 pub spent_ms: f64,
900 pub breakdown: Vec<ScriptSource>,
903}
904
905#[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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
921#[serde(rename_all = "camelCase")]
922pub struct FrameMetrics {
923 pub input_to_present_ms: Option<f64>,
928 pub style_ms: Option<f64>,
932 pub layout_ms: Option<f64>,
934 pub resolve_ms: f64,
936 pub scene_ms: f64,
939 pub submit_ms: Option<f64>,
942 pub present_ms: Option<f64>,
944 pub renderer_ms: f64,
947 pub total_ms: f64,
950 pub age_ms: f64,
953}
954
955#[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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
969#[serde(rename_all = "camelCase")]
970pub struct FrameWindowMetrics {
971 pub frames_total: u64,
973 pub window_frames: u64,
975 pub resolve: TimingStats,
977 pub scene: TimingStats,
979 pub renderer: TimingStats,
981 pub total: TimingStats,
983 pub interval: TimingStats,
985 pub active_fps: f64,
988 pub missed_refreshes: u64,
991 pub display_refresh_hz: Option<f64>,
992}
993
994#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
996#[serde(rename_all = "camelCase")]
997pub struct SnapshotCost {
998 pub poll_ms: f64,
1000 pub resolve_ms: f64,
1002 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
1123pub 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
1149pub 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
1170pub 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 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
1533pub 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
1550pub 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#[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 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}