Skip to main content

mgui_runtime/
startup.rs

1//! 启动顺序埋点与冒烟校验。
2//!
3//! `AppRunner` 在关键节点记录 [`StartupStep`](启动/窗口/AccessKit/后端/首帧/可见/
4//! 初始语义树),`--startup-smoke` 模式跑一遍隐藏(屏幕外)窗口后校验:
5//! **首帧 present 必须先于 `set_visible`**,**初始 a11y 树必须在可见后的第一帧推送**。
6//! 纯结构校验可单测,CI 无 GPU 时也能跑(配合软件回退)。
7
8/// 启动阶段(按期望发生顺序排列)
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum StartupStep {
11    Resumed,
12    WindowCreated,
13    AccessKitReady,
14    /// GPU Renderer 或软件回退后端就绪
15    BackendReady,
16    /// 首帧已成功 present(窗口仍不可见)
17    FirstFramePresented,
18    /// 调用 `set_visible(true)`(冒烟模式窗口位于屏幕外)
19    WindowVisible,
20    /// 可见后推送第一棵 AccessKit 语义树
21    A11yInitialPushed,
22}
23
24impl StartupStep {
25    pub fn as_str(self) -> &'static str {
26        match self {
27            StartupStep::Resumed => "resumed",
28            StartupStep::WindowCreated => "window_created",
29            StartupStep::AccessKitReady => "accesskit_ready",
30            StartupStep::BackendReady => "backend_ready",
31            StartupStep::FirstFramePresented => "first_frame_presented",
32            StartupStep::WindowVisible => "window_visible",
33            StartupStep::A11yInitialPushed => "a11y_initial_pushed",
34        }
35    }
36}
37
38/// 启动顺序记录(步骤 + 自启动起的毫秒数)
39#[derive(Clone, Debug, Default)]
40pub struct StartupTrace {
41    steps: Vec<(StartupStep, u64)>,
42}
43
44impl StartupTrace {
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// 记录一个阶段;同一步骤只记第一次(阶段是单向的)
50    pub fn record(&mut self, step: StartupStep, elapsed_ms: u64) {
51        if !self.has(step) {
52            self.steps.push((step, elapsed_ms));
53        }
54    }
55
56    pub fn has(&self, step: StartupStep) -> bool {
57        self.steps.iter().any(|(s, _)| *s == step)
58    }
59
60    pub fn steps(&self) -> &[(StartupStep, u64)] {
61        &self.steps
62    }
63
64    /// 校验关键顺序:
65    /// 1. 六个阶段齐全;
66    /// 2. `FirstFramePresented` 早于 `WindowVisible`(禁止白屏);
67    /// 3. `A11yInitialPushed` 晚于 `WindowVisible`(可见后首帧才推树)。
68    pub fn validate(&self) -> Result<(), String> {
69        let pos = |step: StartupStep| self.steps.iter().position(|(s, _)| *s == step);
70        let mut missing = Vec::new();
71        for step in [
72            StartupStep::Resumed,
73            StartupStep::WindowCreated,
74            StartupStep::AccessKitReady,
75            StartupStep::BackendReady,
76            StartupStep::FirstFramePresented,
77            StartupStep::WindowVisible,
78            StartupStep::A11yInitialPushed,
79        ] {
80            if pos(step).is_none() {
81                missing.push(step.as_str());
82            }
83        }
84        if !missing.is_empty() {
85            return Err(format!("缺少启动阶段: {}", missing.join(", ")));
86        }
87
88        let present = pos(StartupStep::FirstFramePresented).unwrap();
89        let visible = pos(StartupStep::WindowVisible).unwrap();
90        let a11y = pos(StartupStep::A11yInitialPushed).unwrap();
91        if present > visible {
92            return Err("首帧 present 晚于窗口显示(会白屏)".into());
93        }
94        if a11y < visible {
95            return Err("初始 a11y 树早于窗口显示(adapter 可能未激活)".into());
96        }
97        Ok(())
98    }
99
100    /// 冒烟报告:`first_frame=84ms window_visible=...;...`
101    pub fn report(&self) -> String {
102        self.steps.iter().map(|(s, ms)| format!("{}={}ms", s.as_str(), ms)).collect::<Vec<_>>().join(" ")
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    fn valid_trace() -> StartupTrace {
111        let mut t = StartupTrace::new();
112        for (i, step) in [
113            StartupStep::Resumed,
114            StartupStep::WindowCreated,
115            StartupStep::AccessKitReady,
116            StartupStep::BackendReady,
117            StartupStep::FirstFramePresented,
118            StartupStep::WindowVisible,
119            StartupStep::A11yInitialPushed,
120        ]
121        .into_iter()
122        .enumerate()
123        {
124            t.record(step, i as u64 * 10);
125        }
126        t
127    }
128
129    #[test]
130    fn valid_order_passes() {
131        assert!(valid_trace().validate().is_ok());
132    }
133
134    #[test]
135    fn visible_before_first_frame_is_rejected() {
136        let mut t = StartupTrace::new();
137        for step in [
138            StartupStep::Resumed,
139            StartupStep::WindowCreated,
140            StartupStep::AccessKitReady,
141            StartupStep::BackendReady,
142            StartupStep::WindowVisible, // 抢在首帧前显示 → 白屏
143            StartupStep::FirstFramePresented,
144            StartupStep::A11yInitialPushed,
145        ] {
146            t.record(step, 0);
147        }
148        let err = t.validate().unwrap_err();
149        assert!(err.contains("白屏"), "错误信息应指出白屏: {err}");
150    }
151
152    #[test]
153    fn a11y_before_visible_is_rejected() {
154        let mut t2 = StartupTrace::new();
155        for step in [
156            StartupStep::Resumed,
157            StartupStep::WindowCreated,
158            StartupStep::AccessKitReady,
159            StartupStep::BackendReady,
160            StartupStep::FirstFramePresented,
161            StartupStep::A11yInitialPushed,
162            StartupStep::WindowVisible,
163        ] {
164            t2.record(step, 0);
165        }
166        let err = t2.validate().unwrap_err();
167        assert!(err.contains("a11y"), "错误信息应指出 a11y 顺序: {err}");
168    }
169
170    #[test]
171    fn missing_steps_are_reported() {
172        let mut t = StartupTrace::new();
173        t.record(StartupStep::Resumed, 0);
174        t.record(StartupStep::WindowCreated, 1);
175        let err = t.validate().unwrap_err();
176        assert!(err.contains("缺少启动阶段"), "{err}");
177        assert!(err.contains("first_frame_presented"), "{err}");
178    }
179
180    #[test]
181    fn duplicate_step_keeps_first_timestamp() {
182        let mut t = StartupTrace::new();
183        t.record(StartupStep::Resumed, 5);
184        t.record(StartupStep::Resumed, 99);
185        assert_eq!(t.steps(), &[(StartupStep::Resumed, 5)]);
186    }
187}