Skip to main content

velox_engine/
automation.rs

1//! AI-Native UI 语义自动化控制协议(MCP JSON-RPC 2.0)与确定性时间旅行事件录像回放(`.vlxrec`)。
2//!
3//! 零外部 `serde` 依赖,直接复用 [`crate::a11y`] 与 [`crate::platform::a11y_bridge`]:
4//! - **结构化 UI 语义快照(`snapshot_json`)**:任何 Velox 应用零代码即可向 AI Agent / E2E 测试框架暴露
5//!   完整语义节点树(id / role / bounds / label / value / focusable / checked / children);
6//! - **原生 MCP 协议处理(`handle_mcp_request`)**:内置 `initialize`、`tools/list`、`tools/call`
7//!   (`velox_snapshot_tree`、`velox_click`、`velox_click_label`、`velox_fill`、`velox_scroll`、`velox_wait_idle`);
8//! - **确定性事件录像与回放(`EventRecorder` / `EventReplayer` / `.vlxrec`)**:记录 `InputEvent` + 虚拟时钟 `dt_ms`
9//!   + 帧状态校验和,实现线上 Bug 几十 KB 录像文件一帧不差复现。
10
11use std::fmt::Write as _;
12use std::format;
13use std::string::String;
14use std::vec::Vec;
15
16use crate::a11y::A11yRole;
17use crate::engine::VeloxEngine;
18use crate::platform::a11y_bridge::{AccessKitActionRequest, AccessKitBridge, AccessKitNodeData};
19use crate::pod::{InputEvent, KeyCode};
20
21/// 语义节点查询条件。
22#[derive(Clone, Debug, Default)]
23pub struct SemanticQuery {
24    pub id: Option<u32>,
25    pub role: Option<A11yRole>,
26    pub label_contains: Option<String>,
27    pub only_focusable: bool,
28}
29
30/// AI Agent 或自动化测试可下发的结构化 UI 语义动作。
31#[derive(Clone, Debug)]
32pub enum SemanticAction {
33    SnapshotTree,
34    QueryNodes(SemanticQuery),
35    ClickNode(u32),
36    ClickByLabel(String),
37    FillNode { target_id: u32, text: String },
38    ScrollNode { target_id: u32, delta_y: i16 },
39    PressKey(KeyCode),
40    WaitIdle { max_frames: u16, dt_ms: u16 },
41}
42
43/// 语义动作执行回执。
44#[derive(Clone, Debug)]
45pub struct AutomationResult {
46    pub ok: bool,
47    pub message: String,
48    pub payload_json: String,
49    pub frames_stepped: u16,
50}
51
52fn role_str(role: A11yRole) -> &'static str {
53    match role {
54        A11yRole::Window => "window",
55        A11yRole::Container => "container",
56        A11yRole::Button => "button",
57        A11yRole::TextInput => "text_input",
58        A11yRole::Slider => "slider",
59        A11yRole::ScrollRegion => "scroll_region",
60        A11yRole::Text => "text",
61        A11yRole::Image => "image",
62    }
63}
64
65fn push_json_escaped(out: &mut String, s: &str) {
66    out.push('"');
67    for ch in s.chars() {
68        match ch {
69            '"' => out.push_str("\\\""),
70            '\\' => out.push_str("\\\\"),
71            '\n' => out.push_str("\\n"),
72            '\r' => out.push_str("\\r"),
73            '\t' => out.push_str("\\t"),
74            c if (c as u32) < 0x20 => {
75                let _ = write!(out, "\\u{:04x}", c as u32);
76            }
77            c => out.push(c),
78        }
79    }
80    out.push('"');
81}
82
83fn encode_node_json(out: &mut String, n: &AccessKitNodeData) {
84    let _ = write!(
85        out,
86        "{{\"id\":{},\"role\":\"{}\",\"bounds\":[{},{},{},{}],\"focusable\":{},\"focused\":{},\"disabled\":{}",
87        n.id,
88        role_str(n.role),
89        n.bounds.x,
90        n.bounds.y,
91        n.bounds.w,
92        n.bounds.h,
93        n.focusable,
94        n.focused,
95        n.disabled
96    );
97    if let Some(lbl) = &n.label {
98        out.push_str(",\"label\":");
99        push_json_escaped(out, lbl);
100    }
101    if let Some(val) = &n.value {
102        out.push_str(",\"value\":");
103        push_json_escaped(out, val);
104    }
105    if let Some(chk) = n.checked {
106        let _ = write!(out, ",\"checked\":{chk}");
107    }
108    out.push_str(",\"children\":[");
109    for (i, cid) in n.children.iter().enumerate() {
110        if i > 0 {
111            out.push(',');
112        }
113        let _ = write!(out, "{cid}");
114    }
115    out.push_str("]}");
116}
117
118/// 面向 AI Agent 与 Playwright 级 E2E 自动化测试的统一会话控制器。
119#[derive(Default)]
120pub struct AutomationSession {
121    bridge: AccessKitBridge,
122}
123
124impl AutomationSession {
125    pub fn new() -> Self {
126        Self {
127            bridge: AccessKitBridge::new(),
128        }
129    }
130
131    /// 采集当前 [`VeloxEngine`] 的全部无障碍语义节点列表。
132    pub fn collect_nodes(&mut self, engine: &VeloxEngine) -> Vec<AccessKitNodeData> {
133        let mut fresh = AccessKitBridge::new();
134        let _ = self.bridge.sync_engine(engine);
135        fresh
136            .sync_engine(engine)
137            .map(|u| u.updated_nodes)
138            .unwrap_or_default()
139    }
140
141    /// 按查询条件检索匹配的语义节点。
142    pub fn query_nodes(&mut self, engine: &VeloxEngine, q: &SemanticQuery) -> Vec<AccessKitNodeData> {
143        let needle = q.label_contains.as_deref().map(|s| s.to_ascii_lowercase());
144        self.collect_nodes(engine)
145            .into_iter()
146            .filter(|n| {
147                if let Some(id) = q.id {
148                    if n.id != id {
149                        return false;
150                    }
151                }
152                if let Some(role) = q.role {
153                    if n.role != role {
154                        return false;
155                    }
156                }
157                if q.only_focusable && !n.focusable {
158                    return false;
159                }
160                if let Some(ref sub) = needle {
161                    let matched = n
162                        .label
163                        .as_deref()
164                        .is_some_and(|l| l.to_ascii_lowercase().contains(sub.as_str()))
165                        || n.value
166                            .as_deref()
167                            .is_some_and(|v| v.to_ascii_lowercase().contains(sub.as_str()));
168                    if !matched {
169                        return false;
170                    }
171                }
172                true
173            })
174            .collect()
175    }
176
177    /// 导出结构化 JSON 语义树快照(可直接喂给 LLM / MCP Client)。
178    pub fn snapshot_json(&mut self, engine: &VeloxEngine) -> String {
179        let nodes = self.collect_nodes(engine);
180        let vp = engine.viewport_region();
181        let focus_id = nodes.iter().find(|n| n.focused).map(|n| n.id).unwrap_or(0);
182        let mut out = String::with_capacity(nodes.len() * 96 + 64);
183        let _ = write!(
184            out,
185            "{{\"viewport\":[{},{},{},{}],\"focus_id\":{},\"node_count\":{},\"nodes\":[",
186            vp.x,
187            vp.y,
188            vp.w,
189            vp.h,
190            focus_id,
191            nodes.len()
192        );
193        for (i, n) in nodes.iter().enumerate() {
194            if i > 0 {
195                out.push(',');
196            }
197            encode_node_json(&mut out, n);
198        }
199        out.push_str("]}");
200        out
201    }
202
203    /// 执行结构化语义动作并自动步进引擎帧循环。
204    pub fn execute(&mut self, engine: &mut VeloxEngine, action: SemanticAction) -> AutomationResult {
205        match action {
206            SemanticAction::SnapshotTree => AutomationResult {
207                ok: true,
208                message: String::from("snapshot captured"),
209                payload_json: self.snapshot_json(engine),
210                frames_stepped: 0,
211            },
212            SemanticAction::QueryNodes(q) => {
213                let matched = self.query_nodes(engine, &q);
214                let mut out = String::from("[");
215                for (i, n) in matched.iter().enumerate() {
216                    if i > 0 {
217                        out.push(',');
218                    }
219                    encode_node_json(&mut out, n);
220                }
221                out.push(']');
222                AutomationResult {
223                    ok: true,
224                    message: format!("matched {} node(s)", matched.len()),
225                    payload_json: out,
226                    frames_stepped: 0,
227                }
228            }
229            SemanticAction::ClickNode(target_id) => {
230                let ok = self
231                    .bridge
232                    .apply_action_request(engine, AccessKitActionRequest::Click { target_id });
233                let _ = engine.step_frame_dt(16);
234                AutomationResult {
235                    ok,
236                    message: if ok {
237                        format!("clicked node {target_id}")
238                    } else {
239                        format!("node {target_id} not clickable or not found")
240                    },
241                    payload_json: format!("{{\"clicked\":{ok},\"target_id\":{target_id}}}"),
242                    frames_stepped: 1,
243                }
244            }
245            SemanticAction::ClickByLabel(label) => {
246                let hits = self.query_nodes(
247                    engine,
248                    &SemanticQuery {
249                        label_contains: Some(label.clone()),
250                        ..Default::default()
251                    },
252                );
253                if let Some(target) = hits.iter().find(|n| n.focusable).or_else(|| hits.first()) {
254                    let cx = target.bounds.x + target.bounds.w / 2;
255                    let cy = target.bounds.y + target.bounds.h / 2;
256                    let ok = engine.dispatch_click(cx, cy);
257                    let _ = engine.step_frame_dt(16);
258                    AutomationResult {
259                        ok,
260                        message: format!("clicked label '{}' (node #{})", label, target.id),
261                        payload_json: format!("{{\"clicked\":{ok},\"target_id\":{}}}", target.id),
262                        frames_stepped: 1,
263                    }
264                } else {
265                    AutomationResult {
266                        ok: false,
267                        message: format!("no node matched label '{label}'"),
268                        payload_json: String::from("{\"clicked\":false}"),
269                        frames_stepped: 0,
270                    }
271                }
272            }
273            SemanticAction::FillNode { target_id, text } => {
274                let ok = self.bridge.apply_action_request(
275                    engine,
276                    AccessKitActionRequest::SetValue {
277                        target_id,
278                        text: text.clone(),
279                    },
280                );
281                let _ = engine.step_frame_dt(16);
282                AutomationResult {
283                    ok,
284                    message: format!("filled node {target_id}"),
285                    payload_json: format!("{{\"filled\":{ok},\"target_id\":{target_id}}}"),
286                    frames_stepped: 1,
287                }
288            }
289            SemanticAction::ScrollNode { target_id, delta_y } => {
290                let ok = self.bridge.apply_action_request(
291                    engine,
292                    AccessKitActionRequest::Scroll { target_id, delta_y },
293                );
294                let _ = engine.step_frame_dt(16);
295                AutomationResult {
296                    ok,
297                    message: format!("scrolled node {target_id} by {delta_y}"),
298                    payload_json: format!("{{\"scrolled\":{ok},\"target_id\":{target_id}}}"),
299                    frames_stepped: 1,
300                }
301            }
302            SemanticAction::PressKey(key) => {
303                let ok = engine.dispatch_event(InputEvent::KeyDown(key));
304                let _ = engine.step_frame_dt(16);
305                AutomationResult {
306                    ok,
307                    message: String::from("dispatched key"),
308                    payload_json: format!("{{\"handled\":{ok}}}"),
309                    frames_stepped: 1,
310                }
311            }
312            SemanticAction::WaitIdle { max_frames, dt_ms } => {
313                let mut stepped = 0u16;
314                let step_dt = dt_ms.max(1);
315                for _ in 0..max_frames.max(1) {
316                    stepped += 1;
317                    let dirty = engine.step_frame_dt(step_dt);
318                    if dirty.is_empty() && !engine.needs_redraw() {
319                        break;
320                    }
321                }
322                let idle = !engine.needs_redraw();
323                AutomationResult {
324                    ok: idle,
325                    message: format!("stepped {stepped} frame(s), idle={idle}"),
326                    payload_json: format!("{{\"idle\":{idle},\"frames\":{stepped}}}"),
327                    frames_stepped: stepped,
328                }
329            }
330        }
331    }
332
333    /// 处理标准 **MCP (Model Context Protocol) JSON-RPC 2.0** 请求并返回 JSON 响应字符串。
334    ///
335    /// 内置支持方法:
336    /// - `initialize`
337    /// - `tools/list`
338    /// - `tools/call`(`velox_snapshot_tree`、`velox_click`、`velox_click_label`、`velox_fill`、`velox_scroll`、`velox_wait_idle`)
339    pub fn handle_mcp_request(&mut self, engine: &mut VeloxEngine, req_json: &str) -> String {
340        let req_id = extract_json_raw_field(req_json, "id").unwrap_or_else(|| String::from("1"));
341        let method = extract_json_string_field(req_json, "method").unwrap_or_default();
342
343        match method.as_str() {
344            "initialize" => format!(
345                "{{\"jsonrpc\":\"2.0\",\"id\":{req_id},\"result\":{{\"protocolVersion\":\"2025-03-26\",\"capabilities\":{{\"tools\":{{}}}},\"serverInfo\":{{\"name\":\"velox-automation-mcp\",\"version\":\"{version}\"}}}}}}",
346                version = env!("CARGO_PKG_VERSION"),
347            ),
348            "tools/list" => format!(
349                "{{\"jsonrpc\":\"2.0\",\"id\":{req_id},\"result\":{{\"tools\":[{{\"name\":\"velox_snapshot_tree\",\"description\":\"Capture structured Velox UI accessibility/semantic tree as JSON\"}},{{\"name\":\"velox_click\",\"description\":\"Click a UI node by numeric id\"}},{{\"name\":\"velox_click_label\",\"description\":\"Find and click a UI node by label substring\"}},{{\"name\":\"velox_fill\",\"description\":\"Focus and type text into an input node by id\"}},{{\"name\":\"velox_scroll\",\"description\":\"Scroll a container node by delta_y\"}},{{\"name\":\"velox_wait_idle\",\"description\":\"Advance frames until all animations settle to 0% CPU idle\"}}]}}}}"
350            ),
351            "tools/call" => {
352                let tool = extract_json_string_field(req_json, "name").unwrap_or_default();
353                let res = match tool.as_str() {
354                    "velox_snapshot_tree" => self.execute(engine, SemanticAction::SnapshotTree),
355                    "velox_click" => {
356                        let tid = extract_json_i64_field(req_json, "target_id").unwrap_or(0) as u32;
357                        self.execute(engine, SemanticAction::ClickNode(tid))
358                    }
359                    "velox_click_label" => {
360                        let lbl = extract_json_string_field(req_json, "label").unwrap_or_default();
361                        self.execute(engine, SemanticAction::ClickByLabel(lbl))
362                    }
363                    "velox_fill" => {
364                        let tid = extract_json_i64_field(req_json, "target_id").unwrap_or(0) as u32;
365                        let txt = extract_json_string_field(req_json, "text").unwrap_or_default();
366                        self.execute(
367                            engine,
368                            SemanticAction::FillNode {
369                                target_id: tid,
370                                text: txt,
371                            },
372                        )
373                    }
374                    "velox_scroll" => {
375                        let tid = extract_json_i64_field(req_json, "target_id").unwrap_or(0) as u32;
376                        let dy = extract_json_i64_field(req_json, "delta_y").unwrap_or(0) as i16;
377                        self.execute(
378                            engine,
379                            SemanticAction::ScrollNode {
380                                target_id: tid,
381                                delta_y: dy,
382                            },
383                        )
384                    }
385                    "velox_wait_idle" => {
386                        let max_f = extract_json_i64_field(req_json, "max_frames").unwrap_or(120) as u16;
387                        self.execute(
388                            engine,
389                            SemanticAction::WaitIdle {
390                                max_frames: max_f,
391                                dt_ms: 16,
392                            },
393                        )
394                    }
395                    _ => AutomationResult {
396                        ok: false,
397                        message: format!("unknown tool '{tool}'"),
398                        payload_json: String::from("{}"),
399                        frames_stepped: 0,
400                    },
401                };
402                let mut text_escaped = String::new();
403                push_json_escaped(&mut text_escaped, &res.payload_json);
404                format!(
405                    "{{\"jsonrpc\":\"2.0\",\"id\":{req_id},\"result\":{{\"isError\":{},\"content\":[{{\"type\":\"text\",\"text\":{text_escaped}}}]}}}}",
406                    !res.ok
407                )
408            }
409            _ => format!(
410                "{{\"jsonrpc\":\"2.0\",\"id\":{req_id},\"error\":{{\"code\":-32601,\"message\":\"Method not found\"}}}}"
411            ),
412        }
413    }
414}
415
416fn find_json_field_value<'a>(json: &'a str, key: &str) -> Option<&'a str> {
417    let needle = format!("\"{key}\"");
418    let pos = json.find(&needle)?;
419    let rest = &json[pos + needle.len()..];
420    let colon = rest.find(':')?;
421    Some(rest[colon + 1..].trim_start())
422}
423
424fn extract_json_string_field(json: &str, key: &str) -> Option<String> {
425    let val = find_json_field_value(json, key)?;
426    if !val.starts_with('"') {
427        return None;
428    }
429    let mut out = String::new();
430    let mut chars = val[1..].chars();
431    while let Some(c) = chars.next() {
432        match c {
433            '"' => return Some(out),
434            '\\' => {
435                if let Some(esc) = chars.next() {
436                    match esc {
437                        'n' => out.push('\n'),
438                        'r' => out.push('\r'),
439                        't' => out.push('\t'),
440                        '"' => out.push('"'),
441                        '\\' => out.push('\\'),
442                        other => out.push(other),
443                    }
444                }
445            }
446            other => out.push(other),
447        }
448    }
449    None
450}
451
452fn extract_json_i64_field(json: &str, key: &str) -> Option<i64> {
453    let val = find_json_field_value(json, key)?;
454    let end = val
455        .find(|c: char| !c.is_ascii_digit() && c != '-')
456        .unwrap_or(val.len());
457    val[..end].parse::<i64>().ok()
458}
459
460fn extract_json_raw_field(json: &str, key: &str) -> Option<String> {
461    let val = find_json_field_value(json, key)?;
462    if val.starts_with('"') {
463        let s = extract_json_string_field(json, key)?;
464        let mut out = String::new();
465        push_json_escaped(&mut out, &s);
466        Some(out)
467    } else {
468        let end = val
469            .find(|c: char| matches!(c, ',' | '}' | ']' | ' ' | '\n' | '\r' | '\t'))
470            .unwrap_or(val.len());
471        Some(String::from(&val[..end]))
472    }
473}
474
475// ============================================================================
476// 确定性时间旅行事件录像与回放(`.vlxrec` 紧凑文本格式)
477// ============================================================================
478
479/// 可序列化录像的输入事件子集(涵盖鼠标、滚轮、缩放、文本、按键与时钟推进)。
480#[derive(Copy, Clone, PartialEq, Eq, Debug)]
481pub enum RecordedEvent {
482    Tick,
483    PointerDown { x: i16, y: i16 },
484    PointerMove { x: i16, y: i16 },
485    PointerUp { x: i16, y: i16 },
486    Scroll { x: i16, y: i16, delta_y: i16 },
487    Pinch { x: i16, y: i16, delta_scale_x1000: i16 },
488    TextChar(char),
489    KeyCodeTag(u8),
490}
491
492impl RecordedEvent {
493    pub fn from_input_event(ev: &InputEvent) -> Option<Self> {
494        match *ev {
495            InputEvent::PointerDown { x, y } => Some(Self::PointerDown { x, y }),
496            InputEvent::PointerMove { x, y } => Some(Self::PointerMove { x, y }),
497            InputEvent::PointerUp { x, y } => Some(Self::PointerUp { x, y }),
498            InputEvent::Scroll { x, y, delta_y } => Some(Self::Scroll { x, y, delta_y }),
499            InputEvent::Pinch {
500                x,
501                y,
502                delta_scale_x1000,
503            } => Some(Self::Pinch {
504                x,
505                y,
506                delta_scale_x1000,
507            }),
508            InputEvent::TextCommit(ch) => Some(Self::TextChar(ch)),
509            InputEvent::KeyDown(KeyCode::Char(ch)) => Some(Self::TextChar(ch)),
510            InputEvent::KeyDown(k) => key_to_tag(k).map(Self::KeyCodeTag),
511            _ => None,
512        }
513    }
514
515    pub fn to_input_event(self) -> Option<InputEvent> {
516        match self {
517            Self::Tick => None,
518            Self::PointerDown { x, y } => Some(InputEvent::PointerDown { x, y }),
519            Self::PointerMove { x, y } => Some(InputEvent::PointerMove { x, y }),
520            Self::PointerUp { x, y } => Some(InputEvent::PointerUp { x, y }),
521            Self::Scroll { x, y, delta_y } => Some(InputEvent::Scroll { x, y, delta_y }),
522            Self::Pinch {
523                x,
524                y,
525                delta_scale_x1000,
526            } => Some(InputEvent::Pinch {
527                x,
528                y,
529                delta_scale_x1000,
530            }),
531            Self::TextChar(ch) => Some(InputEvent::KeyDown(KeyCode::Char(ch))),
532            Self::KeyCodeTag(t) => tag_to_key(t).map(InputEvent::KeyDown),
533        }
534    }
535}
536
537fn key_to_tag(k: KeyCode) -> Option<u8> {
538    match k {
539        KeyCode::Enter => Some(1),
540        KeyCode::Escape => Some(2),
541        KeyCode::Backspace => Some(3),
542        KeyCode::Delete => Some(4),
543        KeyCode::Tab => Some(5),
544        KeyCode::Up => Some(6),
545        KeyCode::Down => Some(7),
546        KeyCode::Left => Some(8),
547        KeyCode::Right => Some(9),
548        KeyCode::Space => Some(10),
549        KeyCode::Home => Some(11),
550        KeyCode::End => Some(12),
551        _ => None,
552    }
553}
554
555fn tag_to_key(t: u8) -> Option<KeyCode> {
556    match t {
557        1 => Some(KeyCode::Enter),
558        2 => Some(KeyCode::Escape),
559        3 => Some(KeyCode::Backspace),
560        4 => Some(KeyCode::Delete),
561        5 => Some(KeyCode::Tab),
562        6 => Some(KeyCode::Up),
563        7 => Some(KeyCode::Down),
564        8 => Some(KeyCode::Left),
565        9 => Some(KeyCode::Right),
566        10 => Some(KeyCode::Space),
567        11 => Some(KeyCode::Home),
568        12 => Some(KeyCode::End),
569        _ => None,
570    }
571}
572
573/// 单帧录像记录条(含虚拟时间差与帧确定性哈希)。
574#[derive(Copy, Clone, PartialEq, Eq, Debug)]
575pub struct RecordedStep {
576    pub dt_ms: u16,
577    pub event: RecordedEvent,
578    pub state_checksum: u64,
579}
580
581/// 计算 [`VeloxEngine`] 当前帧的结构化确定性校验和(DrawOp 数量 + HitRegion 数量 + 焦点索引 + 布局边界摘要)。
582pub fn compute_engine_frame_checksum(engine: &VeloxEngine) -> u64 {
583    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
584    let mut mix = |v: u64| {
585        h ^= v;
586        h = h.wrapping_mul(0x0100_0000_01b3);
587    };
588    let ops = engine.cached_draw_ops();
589    let hits = engine.cached_hit_regions();
590    mix(ops.len() as u64);
591    mix(hits.len() as u64);
592    mix(engine.focused_index().unwrap_or(u16::MAX) as u64);
593    for op in ops.iter().take(64) {
594        mix(op.bounds.x as u16 as u64);
595        mix(op.bounds.y as u16 as u64);
596        mix(op.bounds.w as u16 as u64);
597        mix(op.bounds.h as u16 as u64);
598    }
599    h
600}
601
602/// 确定性事件录像机(支持导出 `.vlxrec` 紧凑文本格式供线上 Bug 复现)。
603#[derive(Clone, Debug, Default)]
604pub struct EventRecorder {
605    pub steps: Vec<RecordedStep>,
606}
607
608impl EventRecorder {
609    pub fn new() -> Self {
610        Self { steps: Vec::new() }
611    }
612
613    pub fn clear(&mut self) {
614        self.steps.clear();
615    }
616
617    /// 录制一次事件派发 + 步进帧的完整确定性快照。
618    pub fn record_dispatch(
619        &mut self,
620        engine: &mut VeloxEngine,
621        dt_ms: u16,
622        event: InputEvent,
623    ) -> bool {
624        let rec = RecordedEvent::from_input_event(&event).unwrap_or(RecordedEvent::Tick);
625        let handled = engine.dispatch_event(event);
626        let _ = engine.step_frame_dt(dt_ms);
627        let checksum = compute_engine_frame_checksum(engine);
628        self.steps.push(RecordedStep {
629            dt_ms,
630            event: rec,
631            state_checksum: checksum,
632        });
633        handled
634    }
635
636    /// 仅录制一次虚拟时钟步进帧。
637    pub fn record_tick(&mut self, engine: &mut VeloxEngine, dt_ms: u16) {
638        let _ = engine.step_frame_dt(dt_ms);
639        self.steps.push(RecordedStep {
640            dt_ms,
641            event: RecordedEvent::Tick,
642            state_checksum: compute_engine_frame_checksum(engine),
643        });
644    }
645
646    /// 序列化为人类可读且极紧凑的 `.vlxrec` 录像文本。
647    pub fn to_vlxrec_text(&self) -> String {
648        let mut out = String::from("VLXREC v1\n");
649        for s in &self.steps {
650            let _ = write!(out, "{} ", s.dt_ms);
651            match s.event {
652                RecordedEvent::Tick => out.push_str("TICK"),
653                RecordedEvent::PointerDown { x, y } => {
654                    let _ = write!(out, "PD {x} {y}");
655                }
656                RecordedEvent::PointerMove { x, y } => {
657                    let _ = write!(out, "PM {x} {y}");
658                }
659                RecordedEvent::PointerUp { x, y } => {
660                    let _ = write!(out, "PU {x} {y}");
661                }
662                RecordedEvent::Scroll { x, y, delta_y } => {
663                    let _ = write!(out, "SC {x} {y} {delta_y}");
664                }
665                RecordedEvent::Pinch {
666                    x,
667                    y,
668                    delta_scale_x1000,
669                } => {
670                    let _ = write!(out, "PN {x} {y} {delta_scale_x1000}");
671                }
672                RecordedEvent::TextChar(ch) => {
673                    let _ = write!(out, "CH {}", ch as u32);
674                }
675                RecordedEvent::KeyCodeTag(tag) => {
676                    let _ = write!(out, "KY {tag}");
677                }
678            }
679            let _ = writeln!(out, " #{:016x}", s.state_checksum);
680        }
681        out
682    }
683}
684
685/// 回放验证报告。
686#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
687pub struct ReplayReport {
688    pub total_steps: usize,
689    pub checksum_matches: usize,
690    pub checksum_mismatches: usize,
691}
692
693impl ReplayReport {
694    #[inline]
695    pub const fn is_deterministic(&self) -> bool {
696        self.total_steps > 0 && self.checksum_mismatches == 0
697    }
698}
699
700/// 确定性时间旅行事件回放器。
701#[derive(Clone, Debug)]
702pub struct EventReplayer {
703    steps: Vec<RecordedStep>,
704    cursor: usize,
705}
706
707impl EventReplayer {
708    pub fn from_vlxrec_text(text: &str) -> Result<Self, &'static str> {
709        let mut lines = text.lines();
710        let header = lines.next().ok_or("empty vlxrec")?;
711        if !header.trim().starts_with("VLXREC") {
712            return Err("invalid vlxrec header");
713        }
714        let mut steps = Vec::new();
715        for line in lines {
716            let line = line.trim();
717            if line.is_empty() {
718                continue;
719            }
720            let parts: Vec<&str> = line.split_whitespace().collect();
721            if parts.len() < 3 {
722                return Err("malformed vlxrec line");
723            }
724            let dt_ms: u16 = parts[0].parse().map_err(|_| "bad dt_ms")?;
725            let checksum_hex = parts
726                .last()
727                .and_then(|s| s.strip_prefix('#'))
728                .ok_or("missing checksum")?;
729            let state_checksum = u64::from_str_radix(checksum_hex, 16).map_err(|_| "bad checksum")?;
730            let event = match parts[1] {
731                "TICK" => RecordedEvent::Tick,
732                "PD" if parts.len() >= 5 => RecordedEvent::PointerDown {
733                    x: parts[2].parse().map_err(|_| "bad x")?,
734                    y: parts[3].parse().map_err(|_| "bad y")?,
735                },
736                "PM" if parts.len() >= 5 => RecordedEvent::PointerMove {
737                    x: parts[2].parse().map_err(|_| "bad x")?,
738                    y: parts[3].parse().map_err(|_| "bad y")?,
739                },
740                "PU" if parts.len() >= 5 => RecordedEvent::PointerUp {
741                    x: parts[2].parse().map_err(|_| "bad x")?,
742                    y: parts[3].parse().map_err(|_| "bad y")?,
743                },
744                "SC" if parts.len() >= 6 => RecordedEvent::Scroll {
745                    x: parts[2].parse().map_err(|_| "bad x")?,
746                    y: parts[3].parse().map_err(|_| "bad y")?,
747                    delta_y: parts[4].parse().map_err(|_| "bad dy")?,
748                },
749                "PN" if parts.len() >= 6 => RecordedEvent::Pinch {
750                    x: parts[2].parse().map_err(|_| "bad x")?,
751                    y: parts[3].parse().map_err(|_| "bad y")?,
752                    delta_scale_x1000: parts[4].parse().map_err(|_| "bad scale")?,
753                },
754                "CH" if parts.len() >= 4 => {
755                    let cp: u32 = parts[2].parse().map_err(|_| "bad char")?;
756                    RecordedEvent::TextChar(char::from_u32(cp).ok_or("invalid unicode")?)
757                }
758                "KY" if parts.len() >= 4 => {
759                    let tag: u8 = parts[2].parse().map_err(|_| "bad key tag")?;
760                    RecordedEvent::KeyCodeTag(tag)
761                }
762                _ => return Err("unknown vlxrec opcode"),
763            };
764            steps.push(RecordedStep {
765                dt_ms,
766                event,
767                state_checksum,
768            });
769        }
770        Ok(Self { steps, cursor: 0 })
771    }
772
773    #[inline]
774    pub fn len(&self) -> usize {
775        self.steps.len()
776    }
777
778    #[inline]
779    pub fn is_empty(&self) -> bool {
780        self.steps.is_empty()
781    }
782
783    #[inline]
784    pub fn cursor(&self) -> usize {
785        self.cursor
786    }
787
788    /// 逐帧推进回放 1 步,返回 `Some(checksum_matched)`;结束时返回 `None`。
789    pub fn step_next(&mut self, engine: &mut VeloxEngine) -> Option<bool> {
790        let step = *self.steps.get(self.cursor)?;
791        self.cursor += 1;
792        if let Some(ev) = step.event.to_input_event() {
793            let _ = engine.dispatch_event(ev);
794        }
795        let _ = engine.step_frame_dt(step.dt_ms);
796        let actual = compute_engine_frame_checksum(engine);
797        Some(actual == step.state_checksum)
798    }
799
800    /// 一次性回放全部剩余步骤并返回确定性验证报告。
801    pub fn replay_all(&mut self, engine: &mut VeloxEngine) -> ReplayReport {
802        let mut report = ReplayReport::default();
803        while let Some(matched) = self.step_next(engine) {
804            report.total_steps += 1;
805            if matched {
806                report.checksum_matches += 1;
807            } else {
808                report.checksum_mismatches += 1;
809            }
810        }
811        report
812    }
813}