Skip to main content

blitz_control_protocol/
lib.rs

1//! Typed local debugging protocol carried by endpoint-libs framing.
2//!
3//! This is deliberately not WebDriver. It models the native renderer and app
4//! lifecycle directly, supports observation by more than one client, and has
5//! no authentication handshake. Agent control binds only to a local transport;
6//! expensive diagnostics collection remains an explicit compile-time feature
7//! *of the server*, `tauri-runtime-blitz/diagnostics`.
8//!
9//! # Why this is its own crate
10//!
11//! These are the server's own definitions, and a client that hand-rolls the
12//! JSON gets them wrong in ways that do not look like encoding mistakes.
13//! `AgentAction` is adjacently tagged, so `{"action":"click","node_id":9}` is
14//! malformed where `{"action":"click","params":{"node_id":9}}` is correct, and
15//! the difference used to present as a hung application. Sharing the types
16//! makes that a compile error.
17//!
18//! Speaking the protocol must not cost a renderer. `tauri-runtime-blitz` pulls
19//! in tauri, winit, wgpu and blitz, so a measurement tool that depended on it
20//! for these types would build a browser engine to send a wheel event. Nothing
21//! here needs any of that: it is serde plus endpoint-libs' framing.
22//!
23//! # No `diagnostics` feature, on purpose
24//!
25//! The types are inert data definitions and cost nothing to compile, whereas
26//! gating them creates feature skew: cargo unifies features across a build, so
27//! one workspace member asking for diagnostics types while the server crate is
28//! built without them turned `DebugResponse` into a non-exhaustive match in
29//! code nobody had touched. What stays gated in the server is *collection*,
30//! which is where the expense actually is. A build that cannot serve
31//! diagnostics says so by omitting the tool from `tools/list`; see
32//! [`encode_tools_list_response`].
33
34use endpoint_libs::libs::ws::{
35    WireMessage,
36    mcp_wire::{
37        INVALID_PARAMS, INVALID_REQUEST, JsonRpcError, JsonRpcId, JsonRpcMessage, JsonRpcRequest,
38        JsonRpcResponse, MCP_PROTOCOL_VERSION, parse,
39    },
40};
41use serde::{Deserialize, Serialize, de::DeserializeOwned};
42
43pub const DEBUG_PROTOCOL_VERSION: u32 = 1;
44pub const MCP_INITIALIZE: &str = "initialize";
45pub const MCP_INITIALIZED_NOTIFICATION: &str = "notifications/initialized";
46pub const MCP_TOOLS_LIST: &str = "tools/list";
47pub const MCP_TOOLS_CALL: &str = "tools/call";
48pub const AGENT_CONTROL_TOOL: &str = "blitz.agent.control";
49pub const AGENT_EVENT_NOTIFICATION: &str = "notifications/blitz/agent";
50pub const DIAGNOSTICS_TOOL: &str = "blitz.diagnostics";
51pub const DIAGNOSTICS_EVENT_NOTIFICATION: &str = "notifications/blitz/diagnostics";
52
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54#[serde(rename_all = "camelCase")]
55pub struct DebugDescriptor {
56    pub protocol_version: u32,
57    pub pid: u32,
58    pub instance_id: String,
59    pub address: String,
60    pub renderer: String,
61    pub renderer_revision: String,
62}
63
64#[derive(Debug, Clone, PartialEq)]
65pub enum IncomingRequest {
66    Initialize {
67        id: JsonRpcId,
68    },
69    Initialized,
70    ToolsList {
71        id: JsonRpcId,
72    },
73    Agent {
74        id: JsonRpcId,
75        request: AgentControlRequest,
76    },
77    Diagnostics {
78        id: JsonRpcId,
79        request: DiagnosticsRequest,
80    },
81}
82
83#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
84#[serde(tag = "command", content = "params", rename_all = "camelCase")]
85pub enum AgentControlRequest {
86    Inspect { root: Option<u64>, max_depth: u32 },
87    Act(AgentAction),
88    Relaunch,
89    Quit,
90}
91
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93#[serde(tag = "command", content = "params", rename_all = "camelCase")]
94pub enum DiagnosticsRequest {
95    Observe {
96        streams: Vec<DebugStream>,
97    },
98    Snapshot(SnapshotRequest),
99    Metrics,
100    WaitForIdle,
101    /// Render the current document to an RGBA8 image and return the pixels.
102    ///
103    /// The one question the rest of this protocol cannot answer. A snapshot
104    /// reports the boxes and colours the engine *resolved*, which is not the
105    /// same as what it drew: an element can hold a correct box, a correct
106    /// computed colour and an accessible role while painting nothing at all.
107    /// That gap is not hypothetical. An entire icon set rendered blank in a
108    /// shipping application while every snapshot, every layout box and every
109    /// accessibility node read exactly right, and no tool in this protocol
110    /// could see it.
111    ///
112    /// Rendered offscreen rather than read back from the window surface, which
113    /// is deliberate and is what makes this portable: there is no swapchain to
114    /// capture, no compositor to ask, and no display server to require. The
115    /// same call works over SSH, in CI, on a headless Linux box and on Android.
116    Capture(CaptureRequest),
117}
118
119/// What to draw, and how large.
120#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
121#[serde(rename_all = "camelCase")]
122pub struct CaptureRequest {
123    /// The subtree to draw, or the whole document when absent.
124    ///
125    /// Capturing one node is the difference between a test that says "the
126    /// window is not blank" and one that says "this button's icon is drawn",
127    /// and the second is the one worth writing.
128    pub node_id: Option<u64>,
129    /// Pixel scale, so a small control can be inspected at a useful size.
130    ///
131    /// A 16px icon is a handful of pixels at 1x, and antialiasing dominates
132    /// them; asking for it at 4x makes "is anything there" answerable without
133    /// making the threshold a guess.
134    pub scale: f32,
135}
136
137impl Default for CaptureRequest {
138    fn default() -> Self {
139        Self {
140            node_id: None,
141            scale: 1.0,
142        }
143    }
144}
145
146/// An RGBA8 image, as the renderer actually drew it.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
148#[serde(rename_all = "camelCase")]
149pub struct CapturedImage {
150    pub width: u32,
151    pub height: u32,
152    /// Row-major RGBA8, four bytes per pixel, base64 over the wire.
153    ///
154    /// Base64 rather than raw bytes because the transport is line-delimited
155    /// JSON, and a full window at 2x is a few megabytes: large enough to be
156    /// worth encoding compactly, not large enough to justify a second channel.
157    pub rgba_base64: String,
158    /// The node this shows, when the request named one.
159    pub node_id: Option<u64>,
160}
161
162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163#[serde(tag = "result", content = "value", rename_all = "camelCase")]
164pub enum DebugResponse {
165    Ack,
166    AgentSnapshot(AgentSnapshot),
167    Snapshot(DebugSnapshot),
168    Metrics(RendererMetrics),
169    Idle(RevisionSet),
170    Captured(CapturedImage),
171    Error(DebugError),
172}
173
174#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
175#[serde(tag = "event", content = "value", rename_all = "camelCase")]
176pub enum DebugEvent {
177    Snapshot(DebugSnapshot),
178    Metrics(RendererMetrics),
179    Console(ConsoleEntry),
180    RuntimeError(RuntimeErrorEntry),
181}
182
183#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
184#[serde(tag = "event", content = "value", rename_all = "camelCase")]
185pub enum AgentControlEvent {
186    Ready(DebugDescriptor),
187    TreeChanged { revision: u64 },
188    Lifecycle(LifecycleEvent),
189}
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
192#[serde(rename_all = "camelCase")]
193pub enum DebugStream {
194    Snapshots,
195    Metrics,
196    Console,
197    RuntimeErrors,
198}
199
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
201#[serde(rename_all = "camelCase")]
202pub struct SnapshotRequest {
203    pub include_dom: bool,
204    pub include_layout: bool,
205    pub include_computed_style: bool,
206}
207
208/// A node's live border box, encoded on the wire as `[x, y, width, height]`.
209///
210/// Named fields keep consumers out of positional indexing while the custom
211/// array conversion preserves compatibility with existing inspectors.
212#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
213#[serde(from = "[f64; 4]", into = "[f64; 4]")]
214pub struct LayoutBounds {
215    pub x: f64,
216    pub y: f64,
217    pub width: f64,
218    pub height: f64,
219}
220
221impl From<[f64; 4]> for LayoutBounds {
222    fn from([x, y, width, height]: [f64; 4]) -> Self {
223        Self {
224            x,
225            y,
226            width,
227            height,
228        }
229    }
230}
231
232impl From<LayoutBounds> for [f64; 4] {
233    fn from(bounds: LayoutBounds) -> Self {
234        [bounds.x, bounds.y, bounds.width, bounds.height]
235    }
236}
237
238/// A two-dimensional layout size, encoded as `[width, height]`.
239#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
240#[serde(from = "[f64; 2]", into = "[f64; 2]")]
241pub struct LayoutSize {
242    pub width: f64,
243    pub height: f64,
244}
245
246impl From<[f64; 2]> for LayoutSize {
247    fn from([width, height]: [f64; 2]) -> Self {
248        Self { width, height }
249    }
250}
251
252impl From<LayoutSize> for [f64; 2] {
253    fn from(size: LayoutSize) -> Self {
254        [size.width, size.height]
255    }
256}
257
258/// A live scroll offset, encoded as `[x, y]`.
259#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
260#[serde(from = "[f64; 2]", into = "[f64; 2]")]
261pub struct LayoutOffset {
262    pub x: f64,
263    pub y: f64,
264}
265
266impl From<[f64; 2]> for LayoutOffset {
267    fn from([x, y]: [f64; 2]) -> Self {
268        Self { x, y }
269    }
270}
271
272impl From<LayoutOffset> for [f64; 2] {
273    fn from(offset: LayoutOffset) -> Self {
274        [offset.x, offset.y]
275    }
276}
277
278/// Computed CSS edges, encoded in shorthand order `[top, right, bottom, left]`.
279#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
280#[serde(from = "[f64; 4]", into = "[f64; 4]")]
281pub struct LayoutEdges {
282    pub top: f64,
283    pub right: f64,
284    pub bottom: f64,
285    pub left: f64,
286}
287
288impl From<[f64; 4]> for LayoutEdges {
289    fn from([top, right, bottom, left]: [f64; 4]) -> Self {
290        Self {
291            top,
292            right,
293            bottom,
294            left,
295        }
296    }
297}
298
299impl From<LayoutEdges> for [f64; 4] {
300    fn from(edges: LayoutEdges) -> Self {
301        [edges.top, edges.right, edges.bottom, edges.left]
302    }
303}
304
305/// One node's renderer-computed geometry.
306#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
307#[serde(rename_all = "camelCase")]
308pub struct LayoutDiagnosticRow {
309    pub node_id: u64,
310    pub bounds: LayoutBounds,
311    pub scroll_offset: LayoutOffset,
312    pub client_size: LayoutSize,
313    pub scroll_size: LayoutSize,
314    pub scroll_range: LayoutSize,
315    pub border: LayoutEdges,
316    pub padding: LayoutEdges,
317    pub content_size: LayoutSize,
318}
319
320#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
321#[serde(tag = "action", content = "params", rename_all = "camelCase")]
322pub enum AgentAction {
323    /// Activate one semantic node without resolving it back through screen
324    /// coordinates. The runtime dispatches pointer, mouse and click events in
325    /// browser order directly to this target.
326    Click {
327        node_id: u64,
328    },
329    /// Two activations in one runtime call, inside the platform's double-click
330    /// interval. Used for rows whose single click only selects or folds them.
331    DoubleClick {
332        node_id: u64,
333    },
334    /// Present one semantic node as hovered. The target is still named by id;
335    /// the runtime owns any renderer-specific positioning needed to update CSS
336    /// hover state.
337    Hover {
338        node_id: u64,
339    },
340    SetValue {
341        node_id: u64,
342        value: String,
343    },
344    ScrollIntoView {
345        node_id: u64,
346    },
347    /// Scroll a specific node's nearest scroll container by a delta.
348    ///
349    /// Wheel events carry no coordinates and are delivered to whatever the
350    /// document last saw hovered, which an injected pointer move does not
351    /// reliably set. That made every scrollable panel in the application
352    /// undrivable from outside, so a bug that only appears further down a long
353    /// page could not be reproduced without a human at the keyboard.
354    ScrollBy {
355        node_id: u64,
356        delta_x: f64,
357        delta_y: f64,
358    },
359    Input(InputCommand),
360}
361
362#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
363#[serde(tag = "input", rename_all = "camelCase")]
364pub enum InputCommand {
365    Key {
366        phase: KeyPhase,
367        key: String,
368        code: String,
369        modifiers: Modifiers,
370    },
371    Pointer {
372        phase: PointerPhase,
373        x: f64,
374        y: f64,
375        button: u16,
376        modifiers: Modifiers,
377    },
378    Wheel {
379        delta_x: f64,
380        delta_y: f64,
381        phase: WheelPhase,
382        modifiers: Modifiers,
383    },
384}
385
386#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
387#[serde(rename_all = "camelCase")]
388pub struct Modifiers {
389    pub shift: bool,
390    pub control: bool,
391    pub alt: bool,
392    pub meta: bool,
393}
394
395#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
396#[serde(rename_all = "camelCase")]
397pub enum KeyPhase {
398    Down,
399    Up,
400}
401
402#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
403#[serde(rename_all = "camelCase")]
404pub enum PointerPhase {
405    Move,
406    Down,
407    Up,
408    Cancel,
409}
410
411#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
412#[serde(rename_all = "camelCase")]
413pub enum WheelPhase {
414    Started,
415    Moved,
416    Ended,
417}
418
419#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
420#[serde(rename_all = "camelCase")]
421pub struct RevisionSet {
422    pub document: u64,
423    /// Blitz does not version style, layout and paint separately from the
424    /// document, so these stay zero. Filling them with a copy of `document` would
425    /// suggest a per-stage change signal the runtime cannot actually provide.
426    pub style: u64,
427    pub layout: u64,
428    pub paint: u64,
429}
430
431#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
432#[serde(rename_all = "camelCase")]
433pub struct DebugSnapshot {
434    pub revisions: RevisionSet,
435    pub active_window: Option<String>,
436    pub active_element: Option<u64>,
437    pub dom: Option<serde_json::Value>,
438    pub layout: Option<Vec<LayoutDiagnosticRow>>,
439    /// Resolved colours per node, when `include_computed_style` was set.
440    ///
441    /// Only the properties that decide legibility. A full longhand dump for
442    /// every node is megabytes of JSON nobody reads, and these are what a
443    /// question about invisible text actually needs.
444    #[serde(default, skip_serializing_if = "Option::is_none")]
445    pub computed_style: Option<serde_json::Value>,
446    pub metrics: RendererMetrics,
447}
448
449#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
450#[serde(rename_all = "camelCase")]
451pub struct AgentSnapshot {
452    pub revision: u64,
453    pub active_window: Option<String>,
454    pub focused_node: Option<u64>,
455    pub nodes: Vec<SemanticNode>,
456}
457
458#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
459#[serde(rename_all = "camelCase")]
460pub struct SemanticNode {
461    pub id: u64,
462    pub parent: Option<u64>,
463    pub role: String,
464    pub name: String,
465    pub value: Option<String>,
466    pub enabled: bool,
467    pub visible: bool,
468    pub selected: bool,
469    pub bounds: Option<[f64; 4]>,
470    /// The library slot this element is, when it is part of a component.
471    ///
472    /// Read from `data-slot`, which a component library emits to name its own
473    /// parts. Addressing a control by the slot it *is* rather than by the text
474    /// it happens to carry is what lets a harness tell a trigger from the thing
475    /// it opens: those two routinely share an accessible name, so a check
476    /// written against the name passes whether or not anything happened.
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub slot: Option<String>,
479}
480
481#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
482#[serde(rename_all = "camelCase")]
483pub struct RendererMetrics {
484    pub revisions: RevisionSet,
485    /// Depth of a pending-work queue in front of the renderer.
486    ///
487    /// Blitz has no such queue: `View::redraw` resolves, paints and presents
488    /// inline on the event-loop thread. The one queue that exists, `ScriptQueue`,
489    /// lives inside the Tauri webview dispatcher and is not reachable from the
490    /// runtime, so this stays `None` rather than reporting a constant zero that
491    /// reads like a measured "nothing is backed up".
492    pub queue_depth: Option<u64>,
493    pub invalidations_coalesced: u64,
494    /// The most recently presented frame, as measured by blitz-shell.
495    ///
496    /// `None` until the window has drawn at least once.
497    pub frame: Option<FrameMetrics>,
498    /// Mean, p95 and worst case across the last few hundred presented frames.
499    pub frame_window: Option<FrameWindowMetrics>,
500    /// Cost of collecting this diagnostic snapshot. This measures the observer,
501    /// not the application, and is reported separately so the two are never
502    /// confused again.
503    pub snapshot: Option<SnapshotCost>,
504    /// What JavaScript cost, per `ScriptDocument::poll`.
505    ///
506    /// The frame numbers above cover resolve, paint and present, which is the
507    /// engine. Reactivity, event handlers, timers and microtasks are none of
508    /// those, so an application could present a 4ms frame and still feel slow
509    /// with nothing here to explain it. `None` until script has actually run.
510    pub script: Option<ScriptMetrics>,
511    pub resident_bytes: Option<u64>,
512}
513
514/// Script execution cost, in milliseconds, over the retained poll window.
515#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
516#[serde(rename_all = "camelCase")]
517pub struct ScriptMetrics {
518    pub mean_ms: f64,
519    pub p95_ms: f64,
520    pub max_ms: f64,
521    /// Polls that ran script, within the retained window.
522    pub window_polls: u64,
523    /// Every poll since launch, including the ones that found nothing to do.
524    pub total_polls: u64,
525    /// Polls that ran script since launch.
526    pub productive_polls: u64,
527    /// Total time spent in the script runtime since launch.
528    pub spent_ms: f64,
529    /// Where that time went, worst total first: event name or timer source,
530    /// call count, total milliseconds, worst single call.
531    pub breakdown: Vec<ScriptSource>,
532}
533
534/// One attributed source of script time.
535#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
536#[serde(rename_all = "camelCase")]
537pub struct ScriptSource {
538    pub label: String,
539    pub calls: u64,
540    pub total_ms: f64,
541    pub worst_ms: f64,
542}
543
544/// Timings of one real presented frame, in milliseconds.
545///
546/// Every `Option` here is a value blitz does not measure. They are left empty on
547/// purpose: a plausible-looking zero is worse than an admitted gap, because it
548/// makes a missing measurement look like a fast one.
549#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
550#[serde(rename_all = "camelCase")]
551pub struct FrameMetrics {
552    /// Wall time from the input event that caused the frame to the frame reaching
553    /// the screen. Blitz does not stamp input events with an arrival time and the
554    /// renderer reports no present timestamp, so there are no two clocks to
555    /// subtract.
556    pub input_to_present_ms: Option<f64>,
557    /// Style recalculation alone. Blitz runs style and layout inside a single
558    /// `resolve` pass and times only the pass, so the combined cost is in
559    /// `resolve_ms` instead.
560    pub style_ms: Option<f64>,
561    /// Layout alone. See `style_ms`.
562    pub layout_ms: Option<f64>,
563    /// Style plus layout, i.e. the `resolve` pass.
564    pub resolve_ms: f64,
565    /// Scene building: the `paint_scene` call that turns the resolved document
566    /// into renderer commands.
567    pub scene_ms: f64,
568    /// GPU submit alone. The renderer reports encode, submit and present as one
569    /// figure, which is in `renderer_ms`.
570    pub submit_ms: Option<f64>,
571    /// Present alone. See `submit_ms`.
572    pub present_ms: Option<f64>,
573    /// Everything the renderer did outside scene building: encode, submit and
574    /// present.
575    pub renderer_ms: f64,
576    /// `resolve_ms + scene_ms + renderer_ms`. CPU time inside `redraw`, not
577    /// input-to-photon latency.
578    pub total_ms: f64,
579    /// How long ago the frame started, measured when this response was built. A
580    /// large value means the app has been idle and these numbers are stale.
581    pub age_ms: f64,
582}
583
584/// Mean, 95th percentile and worst case for one timing series, in milliseconds.
585///
586/// The percentile and maximum matter more than the mean: a one-second average
587/// hides the single slow frame that is the only one a user notices.
588#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
589#[serde(rename_all = "camelCase")]
590pub struct TimingStats {
591    pub mean_ms: f64,
592    pub p95_ms: f64,
593    pub max_ms: f64,
594}
595
596/// Aggregate statistics over the recently presented frames.
597#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
598#[serde(rename_all = "camelCase")]
599pub struct FrameWindowMetrics {
600    /// Frames presented since process start.
601    pub frames_total: u64,
602    /// Frames the statistics below were computed over.
603    pub window_frames: u64,
604    /// Style plus layout.
605    pub resolve: TimingStats,
606    /// Scene building.
607    pub scene: TimingStats,
608    /// Encode, submit and present.
609    pub renderer: TimingStats,
610    /// Per-frame `resolve + scene + renderer`.
611    pub total: TimingStats,
612    /// Gap between the starts of consecutive frames, idle gaps excluded.
613    pub interval: TimingStats,
614    /// Frames per second across active intervals only. Blitz idles at zero FPS by
615    /// design, so counting idle time would make every measurement meaningless.
616    pub active_fps: f64,
617    /// Active intervals longer than 1.5 display refresh periods. Always zero when
618    /// `display_refresh_hz` is unknown.
619    pub missed_refreshes: u64,
620    pub display_refresh_hz: Option<f64>,
621}
622
623/// What it cost to answer this diagnostics request.
624#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
625#[serde(rename_all = "camelCase")]
626pub struct SnapshotCost {
627    /// Time spent draining the script event loop before reading the document.
628    pub poll_ms: f64,
629    /// Time spent forcing a `resolve` so the reported layout is up to date.
630    pub resolve_ms: f64,
631    /// Total time spent building the response.
632    pub total_ms: f64,
633}
634
635#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
636#[serde(rename_all = "camelCase")]
637pub struct ConsoleEntry {
638    pub sequence: u64,
639    pub level: String,
640    pub message: String,
641}
642
643#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
644#[serde(rename_all = "camelCase")]
645pub struct RuntimeErrorEntry {
646    pub sequence: u64,
647    pub message: String,
648    pub stack: String,
649    pub revisions: RevisionSet,
650}
651
652#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
653#[serde(tag = "state", rename_all = "camelCase")]
654pub enum LifecycleEvent {
655    Relaunching { replacement_instance_id: String },
656    Ready { instance_id: String },
657    Quitting,
658}
659
660#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
661#[serde(rename_all = "camelCase")]
662pub struct DebugError {
663    pub code: String,
664    pub message: String,
665}
666
667#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
668#[serde(rename_all = "camelCase")]
669struct ToolCallParams {
670    name: String,
671    arguments: serde_json::Value,
672}
673
674#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
675#[serde(rename_all = "camelCase")]
676struct ToolCallResult {
677    content: Vec<TextContent>,
678    structured_content: serde_json::Value,
679    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
680    is_error: bool,
681}
682
683#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
684struct TextContent {
685    #[serde(rename = "type")]
686    content_type: String,
687    text: String,
688}
689
690#[derive(Debug)]
691pub enum DebugProtocolError {
692    Json(serde_json::Error),
693    Rpc(JsonRpcError),
694    NonTextFrame,
695    RequestIdRequired,
696    UnexpectedMessage,
697    UnexpectedMethod(String),
698    UnexpectedTool(String),
699}
700
701impl std::fmt::Display for DebugProtocolError {
702    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
703        match self {
704            Self::Json(error) => write!(formatter, "invalid debug frame: {error}"),
705            Self::Rpc(error) => write!(
706                formatter,
707                "JSON-RPC error {}: {}",
708                error.code, error.message
709            ),
710            Self::NonTextFrame => formatter.write_str("debug protocol requires a text frame"),
711            Self::RequestIdRequired => formatter.write_str("tools/call requires a request id"),
712            Self::UnexpectedMessage => formatter.write_str("unexpected JSON-RPC message"),
713            Self::UnexpectedMethod(method) => write!(formatter, "unexpected method {method}"),
714            Self::UnexpectedTool(tool) => write!(formatter, "unexpected tool {tool}"),
715        }
716    }
717}
718
719impl std::error::Error for DebugProtocolError {
720    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
721        match self {
722            Self::Json(error) => Some(error),
723            _ => None,
724        }
725    }
726}
727
728impl From<serde_json::Error> for DebugProtocolError {
729    fn from(error: serde_json::Error) -> Self {
730        Self::Json(error)
731    }
732}
733
734pub fn encode_agent_request(
735    id: JsonRpcId,
736    request: &AgentControlRequest,
737) -> Result<WireMessage, DebugProtocolError> {
738    encode_tool_request(id, AGENT_CONTROL_TOOL, request)
739}
740
741pub fn decode_incoming(message: WireMessage) -> Result<IncomingRequest, DebugProtocolError> {
742    let JsonRpcMessage::Request(request) = decode_rpc(message)? else {
743        return Err(DebugProtocolError::UnexpectedMessage);
744    };
745    match request.method.as_str() {
746        MCP_INITIALIZE => Ok(IncomingRequest::Initialize {
747            id: request.id.ok_or(DebugProtocolError::RequestIdRequired)?,
748        }),
749        MCP_INITIALIZED_NOTIFICATION if request.is_notification() => {
750            Ok(IncomingRequest::Initialized)
751        }
752        MCP_TOOLS_LIST => Ok(IncomingRequest::ToolsList {
753            id: request.id.ok_or(DebugProtocolError::RequestIdRequired)?,
754        }),
755        MCP_TOOLS_CALL => decode_incoming_tool_call(request),
756        _ => Err(DebugProtocolError::UnexpectedMethod(request.method)),
757    }
758}
759
760pub fn encode_initialize_response(
761    id: JsonRpcId,
762    server_version: &str,
763) -> Result<WireMessage, DebugProtocolError> {
764    encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::result(
765        Some(id),
766        serde_json::json!({
767            "protocolVersion": MCP_PROTOCOL_VERSION,
768            "capabilities": {"tools": {"listChanged": false}},
769            "serverInfo": {"name": "tauri-runtime-blitz", "version": server_version}
770        }),
771    )))
772}
773
774/// The tool list, which is the one place a build's *capability* shows.
775///
776/// `include_diagnostics` is the server's `diagnostics` feature. The protocol
777/// types for diagnostics exist unconditionally, so a build that cannot collect
778/// them has to say so here rather than by failing to define them. Advertising
779/// a tool that answers every call with an error would be worse than omitting
780/// it: a client would report the app as broken instead of as a plain build.
781pub fn encode_tools_list_response(
782    id: JsonRpcId,
783    include_diagnostics: bool,
784) -> Result<WireMessage, DebugProtocolError> {
785    let mut tools = vec![serde_json::json!({
786        "name": AGENT_CONTROL_TOOL,
787        "description": "Inspect and operate the native Blitz semantic UI tree",
788        "inputSchema": {"type": "object"}
789    })];
790    if include_diagnostics {
791        tools.push(serde_json::json!({
792            "name": DIAGNOSTICS_TOOL,
793            "description": "Observe Blitz DOM, layout, errors, and renderer metrics",
794            "inputSchema": {"type": "object"}
795        }));
796    }
797    encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::result(
798        Some(id),
799        serde_json::json!({"tools": tools}),
800    )))
801}
802
803pub fn encode_rpc_error(
804    id: Option<JsonRpcId>,
805    error: JsonRpcError,
806) -> Result<WireMessage, DebugProtocolError> {
807    encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::error(id, error)))
808}
809
810pub fn decode_agent_request(
811    message: WireMessage,
812) -> Result<(JsonRpcId, AgentControlRequest), DebugProtocolError> {
813    decode_tool_request(message, AGENT_CONTROL_TOOL)
814}
815
816pub fn encode_diagnostics_request(
817    id: JsonRpcId,
818    request: &DiagnosticsRequest,
819) -> Result<WireMessage, DebugProtocolError> {
820    encode_tool_request(id, DIAGNOSTICS_TOOL, request)
821}
822
823pub fn decode_diagnostics_request(
824    message: WireMessage,
825) -> Result<(JsonRpcId, DiagnosticsRequest), DebugProtocolError> {
826    decode_tool_request(message, DIAGNOSTICS_TOOL)
827}
828
829pub fn encode_response(
830    id: JsonRpcId,
831    response: &DebugResponse,
832) -> Result<WireMessage, DebugProtocolError> {
833    let structured_content = serde_json::to_value(response)?;
834    let result = ToolCallResult {
835        content: vec![TextContent {
836            content_type: "text".into(),
837            // structuredContent is the typed payload consumed by the local
838            // client. Repeating a full DOM snapshot as text doubled the frame
839            // and could cross endpoint-libs' 16 MiB safety limit, which closed
840            // an otherwise healthy socket. Keep the required human-readable
841            // MCP content concise and send the snapshot exactly once.
842            text: response_summary(response),
843        }],
844        structured_content,
845        is_error: matches!(response, DebugResponse::Error(_)),
846    };
847    encode_rpc(JsonRpcMessage::Response(JsonRpcResponse::result(
848        Some(id),
849        serde_json::to_value(result)?,
850    )))
851}
852
853fn response_summary(response: &DebugResponse) -> String {
854    match response {
855        DebugResponse::Ack => "ok".into(),
856        DebugResponse::AgentSnapshot(snapshot) => {
857            format!("semantic snapshot with {} nodes", snapshot.nodes.len())
858        }
859        DebugResponse::Snapshot(_) => "diagnostic snapshot".into(),
860        DebugResponse::Metrics(_) => "renderer metrics".into(),
861        DebugResponse::Idle(_) => "renderer idle".into(),
862        DebugResponse::Captured(image) => {
863            format!("captured {}x{} image", image.width, image.height)
864        }
865        DebugResponse::Error(error) => error.message.clone(),
866    }
867}
868
869pub fn decode_response(
870    message: WireMessage,
871) -> Result<(JsonRpcId, DebugResponse), DebugProtocolError> {
872    let JsonRpcMessage::Response(response) = decode_rpc(message)? else {
873        return Err(DebugProtocolError::UnexpectedMessage);
874    };
875    let id = response.id.ok_or(DebugProtocolError::RequestIdRequired)?;
876    if let Some(error) = response.error {
877        return Err(DebugProtocolError::Rpc(error));
878    }
879    let result: ToolCallResult = serde_json::from_value(
880        response
881            .result
882            .ok_or(DebugProtocolError::UnexpectedMessage)?,
883    )?;
884    Ok((id, serde_json::from_value(result.structured_content)?))
885}
886
887pub fn encode_agent_event(event: &AgentControlEvent) -> Result<WireMessage, DebugProtocolError> {
888    encode_notification(AGENT_EVENT_NOTIFICATION, event)
889}
890
891pub fn decode_agent_event(message: WireMessage) -> Result<AgentControlEvent, DebugProtocolError> {
892    decode_notification(message, AGENT_EVENT_NOTIFICATION)
893}
894
895pub fn encode_diagnostics_event(event: &DebugEvent) -> Result<WireMessage, DebugProtocolError> {
896    encode_notification(DIAGNOSTICS_EVENT_NOTIFICATION, event)
897}
898
899pub fn decode_diagnostics_event(message: WireMessage) -> Result<DebugEvent, DebugProtocolError> {
900    decode_notification(message, DIAGNOSTICS_EVENT_NOTIFICATION)
901}
902
903fn encode_tool_request<T: Serialize>(
904    id: JsonRpcId,
905    tool: &str,
906    request: &T,
907) -> Result<WireMessage, DebugProtocolError> {
908    let params = ToolCallParams {
909        name: tool.into(),
910        arguments: serde_json::to_value(request)?,
911    };
912    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::call(
913        id,
914        MCP_TOOLS_CALL,
915        serde_json::to_value(params)?,
916    )))
917}
918
919fn decode_tool_request<T: DeserializeOwned>(
920    message: WireMessage,
921    expected_tool: &str,
922) -> Result<(JsonRpcId, T), DebugProtocolError> {
923    let JsonRpcMessage::Request(request) = decode_rpc(message)? else {
924        return Err(DebugProtocolError::UnexpectedMessage);
925    };
926    if request.method != MCP_TOOLS_CALL {
927        return Err(DebugProtocolError::UnexpectedMethod(request.method));
928    }
929    let id = request.id.ok_or(DebugProtocolError::RequestIdRequired)?;
930    let params: ToolCallParams = serde_json::from_value(request.params.ok_or_else(|| {
931        DebugProtocolError::Rpc(JsonRpcError::new(
932            INVALID_PARAMS,
933            "missing tools/call params",
934        ))
935    })?)?;
936    if params.name != expected_tool {
937        return Err(DebugProtocolError::UnexpectedTool(params.name));
938    }
939    Ok((id, serde_json::from_value(params.arguments)?))
940}
941
942fn decode_incoming_tool_call(
943    request: JsonRpcRequest,
944) -> Result<IncomingRequest, DebugProtocolError> {
945    let id = request.id.ok_or(DebugProtocolError::RequestIdRequired)?;
946    let params: ToolCallParams = serde_json::from_value(request.params.ok_or_else(|| {
947        DebugProtocolError::Rpc(JsonRpcError::new(
948            INVALID_PARAMS,
949            "missing tools/call params",
950        ))
951    })?)?;
952    match params.name.as_str() {
953        AGENT_CONTROL_TOOL => Ok(IncomingRequest::Agent {
954            id,
955            request: serde_json::from_value(params.arguments)?,
956        }),
957        DIAGNOSTICS_TOOL => Ok(IncomingRequest::Diagnostics {
958            id,
959            request: serde_json::from_value(params.arguments)?,
960        }),
961        _ => Err(DebugProtocolError::UnexpectedTool(params.name)),
962    }
963}
964
965fn encode_notification<T: Serialize>(
966    method: &str,
967    value: &T,
968) -> Result<WireMessage, DebugProtocolError> {
969    encode_rpc(JsonRpcMessage::Request(JsonRpcRequest::notification(
970        method,
971        serde_json::to_value(value)?,
972    )))
973}
974
975fn decode_notification<T: DeserializeOwned>(
976    message: WireMessage,
977    expected_method: &str,
978) -> Result<T, DebugProtocolError> {
979    let JsonRpcMessage::Request(request) = decode_rpc(message)? else {
980        return Err(DebugProtocolError::UnexpectedMessage);
981    };
982    if !request.is_notification() {
983        return Err(DebugProtocolError::Rpc(JsonRpcError::new(
984            INVALID_REQUEST,
985            "notification must not contain an id",
986        )));
987    }
988    if request.method != expected_method {
989        return Err(DebugProtocolError::UnexpectedMethod(request.method));
990    }
991    serde_json::from_value(request.params.ok_or_else(|| {
992        DebugProtocolError::Rpc(JsonRpcError::new(
993            INVALID_PARAMS,
994            "missing notification params",
995        ))
996    })?)
997    .map_err(Into::into)
998}
999
1000pub fn encode_rpc(message: JsonRpcMessage) -> Result<WireMessage, DebugProtocolError> {
1001    Ok(WireMessage::Text(serde_json::to_string(&message)?))
1002}
1003
1004/// The request id of an incoming frame, recovered without consuming it.
1005///
1006/// A decode failure still has to be answered, and answered *to the caller*. A
1007/// JSON-RPC client matches responses by id, so an error carrying `id: null` is
1008/// delivered and then discarded, and the caller waits until it times out. That
1009/// turns "you named a field wrong" into "the app is hung", which is a much
1010/// worse and much slower thing to debug.
1011pub fn peek_request_id(message: &WireMessage) -> Option<JsonRpcId> {
1012    let WireMessage::Text(text) = message else {
1013        return None;
1014    };
1015    match parse(text) {
1016        Ok(JsonRpcMessage::Request(request)) => request.id,
1017        _ => None,
1018    }
1019}
1020
1021pub fn decode_rpc(message: WireMessage) -> Result<JsonRpcMessage, DebugProtocolError> {
1022    let WireMessage::Text(text) = message else {
1023        return Err(DebugProtocolError::NonTextFrame);
1024    };
1025    parse(&text).map_err(DebugProtocolError::Rpc)
1026}
1027
1028#[cfg(test)]
1029mod tests {
1030    use endpoint_libs::libs::ws::MessageStream;
1031    use endpoint_libs::libs::ws::transport::{TransportStream, framed_json};
1032
1033    use super::*;
1034
1035    fn key_request() -> AgentControlRequest {
1036        AgentControlRequest::Act(AgentAction::Input(InputCommand::Key {
1037            phase: KeyPhase::Down,
1038            key: "2".into(),
1039            code: "Digit2".into(),
1040            modifiers: Modifiers {
1041                meta: true,
1042                ..Default::default()
1043            },
1044        }))
1045    }
1046
1047    #[test]
1048    fn typed_modifier_input_round_trips_mcp_tools_call() {
1049        let request = key_request();
1050        let id = JsonRpcId::Number(7);
1051        assert_eq!(
1052            decode_agent_request(encode_agent_request(id.clone(), &request).unwrap()).unwrap(),
1053            (id, request)
1054        );
1055    }
1056
1057    #[test]
1058    fn node_addressed_actions_round_trip() {
1059        for action in [
1060            AgentAction::Click { node_id: 9 },
1061            AgentAction::DoubleClick { node_id: 10 },
1062            AgentAction::Hover { node_id: 11 },
1063        ] {
1064            let request = AgentControlRequest::Act(action);
1065            let id = JsonRpcId::Number(8);
1066            assert_eq!(
1067                decode_agent_request(encode_agent_request(id.clone(), &request).unwrap()).unwrap(),
1068                (id, request)
1069            );
1070        }
1071    }
1072
1073    #[tokio::test(flavor = "current_thread")]
1074    async fn endpoint_framing_carries_debug_frames_without_a_session_or_token() {
1075        let (server_io, client_io) = tokio::io::duplex(64 * 1024);
1076        let mut server = TransportStream::new(framed_json(server_io));
1077        let mut client = TransportStream::new(framed_json(client_io));
1078        let request = key_request();
1079        let id = JsonRpcId::String("input-7".into());
1080
1081        client
1082            .send(encode_agent_request(id.clone(), &request).unwrap())
1083            .await
1084            .unwrap();
1085        let received = server.recv().await.unwrap().unwrap();
1086
1087        assert_eq!(decode_agent_request(received).unwrap(), (id, request));
1088    }
1089
1090    #[test]
1091    fn unrelated_mcp_tool_is_rejected_explicitly() {
1092        let message = JsonRpcMessage::Request(JsonRpcRequest::call(
1093            JsonRpcId::Number(1),
1094            MCP_TOOLS_CALL,
1095            serde_json::json!({"name": "other.tool", "arguments": {}}),
1096        ));
1097        assert!(matches!(
1098            decode_agent_request(encode_rpc(message).unwrap()),
1099            Err(DebugProtocolError::UnexpectedTool(tool)) if tool == "other.tool"
1100        ));
1101    }
1102
1103    #[test]
1104    fn responses_and_notifications_round_trip() {
1105        let id = JsonRpcId::Number(19);
1106        let response = DebugResponse::Ack;
1107        assert_eq!(
1108            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap(),
1109            (id, response)
1110        );
1111
1112        let event = AgentControlEvent::TreeChanged { revision: 12 };
1113        assert_eq!(
1114            decode_agent_event(encode_agent_event(&event).unwrap()).unwrap(),
1115            event
1116        );
1117    }
1118
1119    #[test]
1120    fn diagnostics_metrics_request_and_response_round_trip() {
1121        let id = JsonRpcId::Number(23);
1122        assert_eq!(
1123            decode_diagnostics_request(
1124                encode_diagnostics_request(id.clone(), &DiagnosticsRequest::Metrics).unwrap()
1125            )
1126            .unwrap(),
1127            (id.clone(), DiagnosticsRequest::Metrics)
1128        );
1129
1130        let response = DebugResponse::Metrics(RendererMetrics {
1131            resident_bytes: Some(4096),
1132            ..Default::default()
1133        });
1134        assert_eq!(
1135            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap(),
1136            (id, response)
1137        );
1138    }
1139
1140    #[test]
1141    fn typed_layout_row_preserves_the_existing_wire_shape() {
1142        let row = LayoutDiagnosticRow {
1143            node_id: 7,
1144            bounds: LayoutBounds {
1145                x: 1.0,
1146                y: 2.0,
1147                width: 30.0,
1148                height: 40.0,
1149            },
1150            scroll_offset: LayoutOffset { x: 3.0, y: 4.0 },
1151            client_size: LayoutSize {
1152                width: 30.0,
1153                height: 40.0,
1154            },
1155            scroll_size: LayoutSize {
1156                width: 50.0,
1157                height: 60.0,
1158            },
1159            scroll_range: LayoutSize {
1160                width: 20.0,
1161                height: 20.0,
1162            },
1163            border: LayoutEdges {
1164                top: 1.0,
1165                right: 2.0,
1166                bottom: 3.0,
1167                left: 4.0,
1168            },
1169            padding: LayoutEdges {
1170                top: 5.0,
1171                right: 6.0,
1172                bottom: 7.0,
1173                left: 8.0,
1174            },
1175            content_size: LayoutSize {
1176                width: 10.0,
1177                height: 11.0,
1178            },
1179        };
1180        let old_wire_shape = serde_json::json!({
1181            "nodeId": 7,
1182            "bounds": [1.0, 2.0, 30.0, 40.0],
1183            "scrollOffset": [3.0, 4.0],
1184            "clientSize": [30.0, 40.0],
1185            "scrollSize": [50.0, 60.0],
1186            "scrollRange": [20.0, 20.0],
1187            "border": [1.0, 2.0, 3.0, 4.0],
1188            "padding": [5.0, 6.0, 7.0, 8.0],
1189            "contentSize": [10.0, 11.0]
1190        });
1191
1192        assert_eq!(serde_json::to_value(&row).unwrap(), old_wire_shape);
1193        assert_eq!(
1194            serde_json::from_value::<LayoutDiagnosticRow>(old_wire_shape).unwrap(),
1195            row
1196        );
1197    }
1198
1199    #[test]
1200    fn frame_metrics_round_trip_and_keep_unmeasured_fields_empty() {
1201        let id = JsonRpcId::Number(24);
1202        let response = DebugResponse::Metrics(RendererMetrics {
1203            frame: Some(FrameMetrics {
1204                resolve_ms: 1.5,
1205                scene_ms: 2.25,
1206                renderer_ms: 3.0,
1207                total_ms: 6.75,
1208                age_ms: 12.0,
1209                ..Default::default()
1210            }),
1211            frame_window: Some(FrameWindowMetrics {
1212                frames_total: 900,
1213                window_frames: 256,
1214                total: TimingStats {
1215                    mean_ms: 6.0,
1216                    p95_ms: 11.0,
1217                    max_ms: 40.0,
1218                },
1219                active_fps: 59.4,
1220                missed_refreshes: 2,
1221                display_refresh_hz: Some(60.0),
1222                ..Default::default()
1223            }),
1224            snapshot: Some(SnapshotCost {
1225                poll_ms: 0.5,
1226                resolve_ms: 1.0,
1227                total_ms: 4.0,
1228            }),
1229            ..Default::default()
1230        });
1231
1232        let (decoded_id, decoded) =
1233            decode_response(encode_response(id.clone(), &response).unwrap()).unwrap();
1234        assert_eq!(decoded_id, id);
1235        assert_eq!(decoded, response);
1236
1237        let DebugResponse::Metrics(metrics) = decoded else {
1238            panic!("expected renderer metrics")
1239        };
1240        let frame = metrics.frame.unwrap();
1241        // Fields blitz does not measure must stay empty on the wire. Sending 0.0
1242        // is the defect this guards: a zero reads as "measured, and fast".
1243        assert_eq!(frame.input_to_present_ms, None);
1244        assert_eq!(frame.style_ms, None);
1245        assert_eq!(frame.layout_ms, None);
1246        assert_eq!(frame.submit_ms, None);
1247        assert_eq!(frame.present_ms, None);
1248        assert_eq!(metrics.queue_depth, None);
1249    }
1250}