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\":\"0.4.0\"}}}}}}"
346            ),
347            "tools/list" => format!(
348                "{{\"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\"}}]}}}}"
349            ),
350            "tools/call" => {
351                let tool = extract_json_string_field(req_json, "name").unwrap_or_default();
352                let res = match tool.as_str() {
353                    "velox_snapshot_tree" => self.execute(engine, SemanticAction::SnapshotTree),
354                    "velox_click" => {
355                        let tid = extract_json_i64_field(req_json, "target_id").unwrap_or(0) as u32;
356                        self.execute(engine, SemanticAction::ClickNode(tid))
357                    }
358                    "velox_click_label" => {
359                        let lbl = extract_json_string_field(req_json, "label").unwrap_or_default();
360                        self.execute(engine, SemanticAction::ClickByLabel(lbl))
361                    }
362                    "velox_fill" => {
363                        let tid = extract_json_i64_field(req_json, "target_id").unwrap_or(0) as u32;
364                        let txt = extract_json_string_field(req_json, "text").unwrap_or_default();
365                        self.execute(
366                            engine,
367                            SemanticAction::FillNode {
368                                target_id: tid,
369                                text: txt,
370                            },
371                        )
372                    }
373                    "velox_scroll" => {
374                        let tid = extract_json_i64_field(req_json, "target_id").unwrap_or(0) as u32;
375                        let dy = extract_json_i64_field(req_json, "delta_y").unwrap_or(0) as i16;
376                        self.execute(
377                            engine,
378                            SemanticAction::ScrollNode {
379                                target_id: tid,
380                                delta_y: dy,
381                            },
382                        )
383                    }
384                    "velox_wait_idle" => {
385                        let max_f = extract_json_i64_field(req_json, "max_frames").unwrap_or(120) as u16;
386                        self.execute(
387                            engine,
388                            SemanticAction::WaitIdle {
389                                max_frames: max_f,
390                                dt_ms: 16,
391                            },
392                        )
393                    }
394                    _ => AutomationResult {
395                        ok: false,
396                        message: format!("unknown tool '{tool}'"),
397                        payload_json: String::from("{}"),
398                        frames_stepped: 0,
399                    },
400                };
401                let mut text_escaped = String::new();
402                push_json_escaped(&mut text_escaped, &res.payload_json);
403                format!(
404                    "{{\"jsonrpc\":\"2.0\",\"id\":{req_id},\"result\":{{\"isError\":{},\"content\":[{{\"type\":\"text\",\"text\":{text_escaped}}}]}}}}",
405                    !res.ok
406                )
407            }
408            _ => format!(
409                "{{\"jsonrpc\":\"2.0\",\"id\":{req_id},\"error\":{{\"code\":-32601,\"message\":\"Method not found\"}}}}"
410            ),
411        }
412    }
413}
414
415fn find_json_field_value<'a>(json: &'a str, key: &str) -> Option<&'a str> {
416    let needle = format!("\"{key}\"");
417    let pos = json.find(&needle)?;
418    let rest = &json[pos + needle.len()..];
419    let colon = rest.find(':')?;
420    Some(rest[colon + 1..].trim_start())
421}
422
423fn extract_json_string_field(json: &str, key: &str) -> Option<String> {
424    let val = find_json_field_value(json, key)?;
425    if !val.starts_with('"') {
426        return None;
427    }
428    let mut out = String::new();
429    let mut chars = val[1..].chars();
430    while let Some(c) = chars.next() {
431        match c {
432            '"' => return Some(out),
433            '\\' => {
434                if let Some(esc) = chars.next() {
435                    match esc {
436                        'n' => out.push('\n'),
437                        'r' => out.push('\r'),
438                        't' => out.push('\t'),
439                        '"' => out.push('"'),
440                        '\\' => out.push('\\'),
441                        other => out.push(other),
442                    }
443                }
444            }
445            other => out.push(other),
446        }
447    }
448    None
449}
450
451fn extract_json_i64_field(json: &str, key: &str) -> Option<i64> {
452    let val = find_json_field_value(json, key)?;
453    let end = val
454        .find(|c: char| !c.is_ascii_digit() && c != '-')
455        .unwrap_or(val.len());
456    val[..end].parse::<i64>().ok()
457}
458
459fn extract_json_raw_field(json: &str, key: &str) -> Option<String> {
460    let val = find_json_field_value(json, key)?;
461    if val.starts_with('"') {
462        let s = extract_json_string_field(json, key)?;
463        let mut out = String::new();
464        push_json_escaped(&mut out, &s);
465        Some(out)
466    } else {
467        let end = val
468            .find(|c: char| matches!(c, ',' | '}' | ']' | ' ' | '\n' | '\r' | '\t'))
469            .unwrap_or(val.len());
470        Some(String::from(&val[..end]))
471    }
472}
473
474// ============================================================================
475// 确定性时间旅行事件录像与回放(`.vlxrec` 紧凑文本格式)
476// ============================================================================
477
478/// 可序列化录像的输入事件子集(涵盖鼠标、滚轮、缩放、文本、按键与时钟推进)。
479#[derive(Copy, Clone, PartialEq, Eq, Debug)]
480pub enum RecordedEvent {
481    Tick,
482    PointerDown { x: i16, y: i16 },
483    PointerMove { x: i16, y: i16 },
484    PointerUp { x: i16, y: i16 },
485    Scroll { x: i16, y: i16, delta_y: i16 },
486    Pinch { x: i16, y: i16, delta_scale_x1000: i16 },
487    TextChar(char),
488    KeyCodeTag(u8),
489}
490
491impl RecordedEvent {
492    pub fn from_input_event(ev: &InputEvent) -> Option<Self> {
493        match *ev {
494            InputEvent::PointerDown { x, y } => Some(Self::PointerDown { x, y }),
495            InputEvent::PointerMove { x, y } => Some(Self::PointerMove { x, y }),
496            InputEvent::PointerUp { x, y } => Some(Self::PointerUp { x, y }),
497            InputEvent::Scroll { x, y, delta_y } => Some(Self::Scroll { x, y, delta_y }),
498            InputEvent::Pinch {
499                x,
500                y,
501                delta_scale_x1000,
502            } => Some(Self::Pinch {
503                x,
504                y,
505                delta_scale_x1000,
506            }),
507            InputEvent::TextCommit(ch) => Some(Self::TextChar(ch)),
508            InputEvent::KeyDown(KeyCode::Char(ch)) => Some(Self::TextChar(ch)),
509            InputEvent::KeyDown(k) => key_to_tag(k).map(Self::KeyCodeTag),
510            _ => None,
511        }
512    }
513
514    pub fn to_input_event(self) -> Option<InputEvent> {
515        match self {
516            Self::Tick => None,
517            Self::PointerDown { x, y } => Some(InputEvent::PointerDown { x, y }),
518            Self::PointerMove { x, y } => Some(InputEvent::PointerMove { x, y }),
519            Self::PointerUp { x, y } => Some(InputEvent::PointerUp { x, y }),
520            Self::Scroll { x, y, delta_y } => Some(InputEvent::Scroll { x, y, delta_y }),
521            Self::Pinch {
522                x,
523                y,
524                delta_scale_x1000,
525            } => Some(InputEvent::Pinch {
526                x,
527                y,
528                delta_scale_x1000,
529            }),
530            Self::TextChar(ch) => Some(InputEvent::KeyDown(KeyCode::Char(ch))),
531            Self::KeyCodeTag(t) => tag_to_key(t).map(InputEvent::KeyDown),
532        }
533    }
534}
535
536fn key_to_tag(k: KeyCode) -> Option<u8> {
537    match k {
538        KeyCode::Enter => Some(1),
539        KeyCode::Escape => Some(2),
540        KeyCode::Backspace => Some(3),
541        KeyCode::Delete => Some(4),
542        KeyCode::Tab => Some(5),
543        KeyCode::Up => Some(6),
544        KeyCode::Down => Some(7),
545        KeyCode::Left => Some(8),
546        KeyCode::Right => Some(9),
547        KeyCode::Space => Some(10),
548        KeyCode::Home => Some(11),
549        KeyCode::End => Some(12),
550        _ => None,
551    }
552}
553
554fn tag_to_key(t: u8) -> Option<KeyCode> {
555    match t {
556        1 => Some(KeyCode::Enter),
557        2 => Some(KeyCode::Escape),
558        3 => Some(KeyCode::Backspace),
559        4 => Some(KeyCode::Delete),
560        5 => Some(KeyCode::Tab),
561        6 => Some(KeyCode::Up),
562        7 => Some(KeyCode::Down),
563        8 => Some(KeyCode::Left),
564        9 => Some(KeyCode::Right),
565        10 => Some(KeyCode::Space),
566        11 => Some(KeyCode::Home),
567        12 => Some(KeyCode::End),
568        _ => None,
569    }
570}
571
572/// 单帧录像记录条(含虚拟时间差与帧确定性哈希)。
573#[derive(Copy, Clone, PartialEq, Eq, Debug)]
574pub struct RecordedStep {
575    pub dt_ms: u16,
576    pub event: RecordedEvent,
577    pub state_checksum: u64,
578}
579
580/// 计算 [`VeloxEngine`] 当前帧的结构化确定性校验和(DrawOp 数量 + HitRegion 数量 + 焦点索引 + 布局边界摘要)。
581pub fn compute_engine_frame_checksum(engine: &VeloxEngine) -> u64 {
582    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
583    let mut mix = |v: u64| {
584        h ^= v;
585        h = h.wrapping_mul(0x0100_0000_01b3);
586    };
587    let ops = engine.cached_draw_ops();
588    let hits = engine.cached_hit_regions();
589    mix(ops.len() as u64);
590    mix(hits.len() as u64);
591    mix(engine.focused_index().unwrap_or(u16::MAX) as u64);
592    for op in ops.iter().take(64) {
593        mix(op.bounds.x as u16 as u64);
594        mix(op.bounds.y as u16 as u64);
595        mix(op.bounds.w as u16 as u64);
596        mix(op.bounds.h as u16 as u64);
597    }
598    h
599}
600
601/// 确定性事件录像机(支持导出 `.vlxrec` 紧凑文本格式供线上 Bug 复现)。
602#[derive(Clone, Debug, Default)]
603pub struct EventRecorder {
604    pub steps: Vec<RecordedStep>,
605}
606
607impl EventRecorder {
608    pub fn new() -> Self {
609        Self { steps: Vec::new() }
610    }
611
612    pub fn clear(&mut self) {
613        self.steps.clear();
614    }
615
616    /// 录制一次事件派发 + 步进帧的完整确定性快照。
617    pub fn record_dispatch(
618        &mut self,
619        engine: &mut VeloxEngine,
620        dt_ms: u16,
621        event: InputEvent,
622    ) -> bool {
623        let rec = RecordedEvent::from_input_event(&event).unwrap_or(RecordedEvent::Tick);
624        let handled = engine.dispatch_event(event);
625        let _ = engine.step_frame_dt(dt_ms);
626        let checksum = compute_engine_frame_checksum(engine);
627        self.steps.push(RecordedStep {
628            dt_ms,
629            event: rec,
630            state_checksum: checksum,
631        });
632        handled
633    }
634
635    /// 仅录制一次虚拟时钟步进帧。
636    pub fn record_tick(&mut self, engine: &mut VeloxEngine, dt_ms: u16) {
637        let _ = engine.step_frame_dt(dt_ms);
638        self.steps.push(RecordedStep {
639            dt_ms,
640            event: RecordedEvent::Tick,
641            state_checksum: compute_engine_frame_checksum(engine),
642        });
643    }
644
645    /// 序列化为人类可读且极紧凑的 `.vlxrec` 录像文本。
646    pub fn to_vlxrec_text(&self) -> String {
647        let mut out = String::from("VLXREC v1\n");
648        for s in &self.steps {
649            let _ = write!(out, "{} ", s.dt_ms);
650            match s.event {
651                RecordedEvent::Tick => out.push_str("TICK"),
652                RecordedEvent::PointerDown { x, y } => {
653                    let _ = write!(out, "PD {x} {y}");
654                }
655                RecordedEvent::PointerMove { x, y } => {
656                    let _ = write!(out, "PM {x} {y}");
657                }
658                RecordedEvent::PointerUp { x, y } => {
659                    let _ = write!(out, "PU {x} {y}");
660                }
661                RecordedEvent::Scroll { x, y, delta_y } => {
662                    let _ = write!(out, "SC {x} {y} {delta_y}");
663                }
664                RecordedEvent::Pinch {
665                    x,
666                    y,
667                    delta_scale_x1000,
668                } => {
669                    let _ = write!(out, "PN {x} {y} {delta_scale_x1000}");
670                }
671                RecordedEvent::TextChar(ch) => {
672                    let _ = write!(out, "CH {}", ch as u32);
673                }
674                RecordedEvent::KeyCodeTag(tag) => {
675                    let _ = write!(out, "KY {tag}");
676                }
677            }
678            let _ = writeln!(out, " #{:016x}", s.state_checksum);
679        }
680        out
681    }
682}
683
684/// 回放验证报告。
685#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
686pub struct ReplayReport {
687    pub total_steps: usize,
688    pub checksum_matches: usize,
689    pub checksum_mismatches: usize,
690}
691
692impl ReplayReport {
693    #[inline]
694    pub const fn is_deterministic(&self) -> bool {
695        self.total_steps > 0 && self.checksum_mismatches == 0
696    }
697}
698
699/// 确定性时间旅行事件回放器。
700#[derive(Clone, Debug)]
701pub struct EventReplayer {
702    steps: Vec<RecordedStep>,
703    cursor: usize,
704}
705
706impl EventReplayer {
707    pub fn from_vlxrec_text(text: &str) -> Result<Self, &'static str> {
708        let mut lines = text.lines();
709        let header = lines.next().ok_or("empty vlxrec")?;
710        if !header.trim().starts_with("VLXREC") {
711            return Err("invalid vlxrec header");
712        }
713        let mut steps = Vec::new();
714        for line in lines {
715            let line = line.trim();
716            if line.is_empty() {
717                continue;
718            }
719            let parts: Vec<&str> = line.split_whitespace().collect();
720            if parts.len() < 3 {
721                return Err("malformed vlxrec line");
722            }
723            let dt_ms: u16 = parts[0].parse().map_err(|_| "bad dt_ms")?;
724            let checksum_hex = parts
725                .last()
726                .and_then(|s| s.strip_prefix('#'))
727                .ok_or("missing checksum")?;
728            let state_checksum = u64::from_str_radix(checksum_hex, 16).map_err(|_| "bad checksum")?;
729            let event = match parts[1] {
730                "TICK" => RecordedEvent::Tick,
731                "PD" if parts.len() >= 5 => RecordedEvent::PointerDown {
732                    x: parts[2].parse().map_err(|_| "bad x")?,
733                    y: parts[3].parse().map_err(|_| "bad y")?,
734                },
735                "PM" if parts.len() >= 5 => RecordedEvent::PointerMove {
736                    x: parts[2].parse().map_err(|_| "bad x")?,
737                    y: parts[3].parse().map_err(|_| "bad y")?,
738                },
739                "PU" if parts.len() >= 5 => RecordedEvent::PointerUp {
740                    x: parts[2].parse().map_err(|_| "bad x")?,
741                    y: parts[3].parse().map_err(|_| "bad y")?,
742                },
743                "SC" if parts.len() >= 6 => RecordedEvent::Scroll {
744                    x: parts[2].parse().map_err(|_| "bad x")?,
745                    y: parts[3].parse().map_err(|_| "bad y")?,
746                    delta_y: parts[4].parse().map_err(|_| "bad dy")?,
747                },
748                "PN" if parts.len() >= 6 => RecordedEvent::Pinch {
749                    x: parts[2].parse().map_err(|_| "bad x")?,
750                    y: parts[3].parse().map_err(|_| "bad y")?,
751                    delta_scale_x1000: parts[4].parse().map_err(|_| "bad scale")?,
752                },
753                "CH" if parts.len() >= 4 => {
754                    let cp: u32 = parts[2].parse().map_err(|_| "bad char")?;
755                    RecordedEvent::TextChar(char::from_u32(cp).ok_or("invalid unicode")?)
756                }
757                "KY" if parts.len() >= 4 => {
758                    let tag: u8 = parts[2].parse().map_err(|_| "bad key tag")?;
759                    RecordedEvent::KeyCodeTag(tag)
760                }
761                _ => return Err("unknown vlxrec opcode"),
762            };
763            steps.push(RecordedStep {
764                dt_ms,
765                event,
766                state_checksum,
767            });
768        }
769        Ok(Self { steps, cursor: 0 })
770    }
771
772    #[inline]
773    pub fn len(&self) -> usize {
774        self.steps.len()
775    }
776
777    #[inline]
778    pub fn is_empty(&self) -> bool {
779        self.steps.is_empty()
780    }
781
782    #[inline]
783    pub fn cursor(&self) -> usize {
784        self.cursor
785    }
786
787    /// 逐帧推进回放 1 步,返回 `Some(checksum_matched)`;结束时返回 `None`。
788    pub fn step_next(&mut self, engine: &mut VeloxEngine) -> Option<bool> {
789        let step = *self.steps.get(self.cursor)?;
790        self.cursor += 1;
791        if let Some(ev) = step.event.to_input_event() {
792            let _ = engine.dispatch_event(ev);
793        }
794        let _ = engine.step_frame_dt(step.dt_ms);
795        let actual = compute_engine_frame_checksum(engine);
796        Some(actual == step.state_checksum)
797    }
798
799    /// 一次性回放全部剩余步骤并返回确定性验证报告。
800    pub fn replay_all(&mut self, engine: &mut VeloxEngine) -> ReplayReport {
801        let mut report = ReplayReport::default();
802        while let Some(matched) = self.step_next(engine) {
803            report.total_steps += 1;
804            if matched {
805                report.checksum_matches += 1;
806            } else {
807                report.checksum_mismatches += 1;
808            }
809        }
810        report
811    }
812}