mgui-agent 1.1.0

mgui 0.4 Headless/Agent 工具链:命名 scene + 软件快照 PNG + 语义树 JSON + 脚本回放与 motion trace
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//! mgui 0.4 Headless / Agent 工具链 —— **P0a 切片**。
//!
//! 目标形态(逐步落地,本切片覆盖前一半):
//! `my-app --scene <name> --snap out.png --tree tree.json --size WxH --time-ms N`
//!
//! 设计约束(来自 ROADMAP §9.3):
//! - 不引入第二棵 Scene 树。`Scene::build` 仍返回现有 `WidgetNode`,输出走现有
//!   `ElementTree` / `FramePaint`,与真实窗口、GPU、software、hit test、语义树同源。
//! - 真实窗口与 Headless 共用同一套 `Runtime` / `Renderer` / `Clock` 语义;
//!   本切片用软件后端 + `ManualClock`,确定性可重放。
//! - 语义树不暴露裸 `ElementId`(跨进程不稳定),改用扁平顺序 index 作为稳定 id。

pub mod scenes;
pub mod script;

pub use scenes::{builtin_scenes, A11yJourneyScene, ButtonScene, CommandRouteScene, EmptyScene, FlagshipScene};
pub use script::{
    detect_revision, detect_toolchain, parse_command_source, parse_trace, read_trace_meta, read_trace_meta_optional,
    trace_diff, trace_diff_scoped, trace_json, trace_meta_compatibility, trace_meta_hint, trace_meta_path, write_trace,
    write_trace_meta, Script, ScriptEvent, TraceDiff, TraceFrame, TraceLayer, TraceMeta, TraceSemantics,
    TRACE_SCHEMA_VERSION,
};

use mgui_core::ElementTree;
use mgui_core::WidgetNode;
use mgui_runtime::app::{CommandId, CommandRouter, CommandScope, CommandSource, CommandStats};
use mgui_shell_headless::HeadlessShell;
use mgui_software::RgbaImage;
use std::cell::RefCell;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

/// 命名场景:稳定名字 + 构建函数。注册进 [`SceneRegistry`] 后由 CLI 按名选取。
pub trait Scene {
    /// 稳定场景名(CLI `--scene <name>` 用)。
    fn name(&self) -> &'static str;
    /// 构建根 widget 树(仍是现有 `WidgetNode`,不引入第二棵树)。
    fn build(&self) -> WidgetNode;

    /// 场景若真的接入了统一命令路由,返回该 router 供 replay 注入与统计。
    /// 没接入就返回 `None`,trace 里保持「未量到」,不伪造统计。
    fn command_router(&self) -> Option<&RefCell<CommandRouter>> {
        None
    }

    /// 场景若持有共享状态,返回每帧稳定摘要(如 `revision=7`)。
    fn shared_state_summary(&self) -> Option<String> {
        None
    }

    /// 场景若持有 QueryCache 作用域,返回每帧稳定摘要;未接入则保持「未量到」。
    fn cache_scope_summary(&self) -> Option<String> {
        None
    }

    /// 场景若持有文本运行时,返回 generation / DPR / 宽度签名摘要;未接入则保持「未量到」。
    fn text_runtime_summary(&self) -> Option<String> {
        None
    }

    /// 场景若持有 locale / plural 状态,返回稳定摘要;未接入则保持「未量到」。
    fn locale_summary(&self) -> Option<String> {
        None
    }

    /// 场景若持有 AppServices 状态,返回 schema / owner / recovery 摘要;未接入则保持「未量到」。
    fn persistence_summary(&self) -> Option<String> {
        None
    }

    /// DPR / 屏幕归属变化回调;默认 no-op,真实桌面由 `App::on_scale_factor_changed` 承担。
    fn on_scale_factor_changed(&self, _dpr: f32) {}
}

/// 场景注册表:按名查找。
pub struct SceneRegistry {
    scenes: Vec<Box<dyn Scene>>,
}

impl Default for SceneRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl SceneRegistry {
    pub fn new() -> Self {
        Self { scenes: Vec::new() }
    }

    pub fn register(&mut self, scene: Box<dyn Scene>) {
        self.scenes.push(scene);
    }

    pub fn get(&self, name: &str) -> Option<&dyn Scene> {
        self.scenes.iter().find(|s| s.name() == name).map(|b| b.as_ref())
    }

    pub fn contains(&self, name: &str) -> bool {
        self.get(name).is_some()
    }

    /// 按名构建根 widget;未知场景返回带可用列表的错误,避免调用方 `unwrap()`。
    pub fn build(&self, name: &str) -> Result<WidgetNode, String> {
        self.get(name)
            .map(|scene| scene.build())
            .ok_or_else(|| format!("unknown scene: {name} (available: {:?})", self.names()))
    }

    pub fn names(&self) -> Vec<&'static str> {
        self.scenes.iter().map(|s| s.name()).collect()
    }
}

/// 无窗口应用宿主:命名 scene + 确定性时钟 + 软件光栅化。
///
/// 复用已 mount 的树(重复 render 不再 remount),便于未来 P0b 的逐帧回放。
pub struct HeadlessApp {
    shell: HeadlessShell,
    registry: SceneRegistry,
    mounted_scene: Option<String>,
}

impl HeadlessApp {
    pub fn new(width: f32, height: f32, registry: SceneRegistry) -> Self {
        Self { shell: HeadlessShell::new(width, height), registry, mounted_scene: None }
    }

    /// 渲染指定场景到给定逻辑时间(ms)。同一 scene 重复调用复用已 mount 的树。
    pub fn render(&mut self, name: &str, time_ms: u64) -> Result<(), String> {
        self.mount_scene(name)?;
        self.shell.set_time(time_ms);
        self.shell.frame();
        Ok(())
    }

    /// 挂载场景(若尚未挂载或切换了 scene)。P0a 单帧与 P0b 回放共用。
    fn mount_scene(&mut self, name: &str) -> Result<(), String> {
        if self.mounted_scene.as_deref() != Some(name) {
            let scene = self
                .registry
                .get(name)
                .ok_or_else(|| format!("unknown scene: {name} (available: {:?})", self.registry.names()))?;
            self.shell.mount(scene.build());
            self.mounted_scene = Some(name.to_string());
        }
        Ok(())
    }

    /// 逐帧回放输入脚本,返回每帧的确定性 motion trace。
    ///
    /// 时序契约(与真实窗口帧循环一致):
    /// 1. 虚拟时钟从第 0 帧的 0ms 起,每帧 `advance(frame_ms)`;
    /// 2. 当帧脚本事件在 paint **之前**注入,走 `ShellEvent` 同源管线;
    /// 3. trace 读 `frame_with_stats()` 的真实 `FrameStats` 与刚产出的 `FramePaint`。
    ///
    /// 不使用 `render()` 的 `set_time(绝对毫秒)`:回放必须以固定步长推进,
    /// 否则脚本帧号与逻辑时间的关系会随调用方式漂移。
    pub fn run_script(
        &mut self,
        name: &str,
        script: &Script,
        frame_ms: u64,
        frames: usize,
    ) -> Result<Vec<TraceFrame>, String> {
        self.mount_scene(name)?;
        let scene = self.registry.get(name).ok_or_else(|| format!("unknown scene: {name}"))?;
        self.shell.set_time(0);
        let mut trace = Vec::with_capacity(frames);
        for frame in 0..frames {
            if frame > 0 {
                self.shell.advance(frame_ms);
            }
            let semantics_revision_before = self.shell.tree().semantics_revision();
            let mut labels = Vec::new();
            for event in script.events_at(frame) {
                if let ScriptEvent::ScaleFactorChanged { dpr, logical_width, logical_height } = event {
                    // 与桌面 shell 的 ScaleFactorChanged 回调同语义:先更新 metrics,再通知
                    // 应用重算测量环境;不作为输入事件进入 dispatch_shell_event。
                    self.shell.resize(mgui_core::Size::new(*logical_width, *logical_height), *dpr);
                    mgui_text::text::set_text_dpr(*dpr);
                    scene.on_scale_factor_changed(*dpr);
                    labels.push(format!("ScaleFactorChanged {{ dpr: {dpr}, size: {logical_width}x{logical_height} }}"));
                    continue;
                }
                if let ScriptEvent::Command { source, id } = event {
                    let source = command_source(source).ok_or_else(|| format!("unknown command source: {source}"))?;
                    let router = scene
                        .command_router()
                        .ok_or_else(|| format!("scene[{name}] 没有 CommandRouter,无法回放 command 事件"))?;
                    // 命令处理器在 Agent 场景里只改共享状态;CommandScope 用独立空树避免
                    // 与 shell.tree_mut() 同时借用。真实宿主仍传自己的树,口径不变。
                    let mut scope_tree = ElementTree::new();
                    let mut redraw = false;
                    let mut rebuild = false;
                    let mut scope = CommandScope::new(
                        &self.shell,
                        &mut scope_tree,
                        None,
                        &[],
                        source,
                        Some(&mut redraw),
                        Some(&mut rebuild),
                    );
                    router.borrow_mut().dispatch(&mut scope, CommandId::new(*id));
                    labels.push(format!("Command {{ source: {}, id: {} }}", source.as_str(), id));
                    continue;
                }
                let shell_event = event.to_shell_event()?.ok_or_else(|| "event is not a ShellEvent".to_string())?;
                labels.push(format!("{shell_event:?}"));
                self.shell.dispatch_shell_event(&shell_event);
            }
            let (_image, stats) = self.shell.frame_with_stats();
            let paint = self.shell.frame_paint().expect("frame_with_stats 刚产出 FramePaint");
            let command = scene.command_router().map(|router| format_command_stats(router.borrow().stats()));
            let semantics = TraceSemantics {
                command,
                shared_state: scene.shared_state_summary(),
                cache_scope: scene.cache_scope_summary(),
                text_runtime: scene.text_runtime_summary(),
                locale: scene.locale_summary(),
                persistence: scene.persistence_summary(),
                a11y_digest: a11y_digest(self.shell()),
                focus: focus_label(self.shell()),
                semantics_bumps: u32::from(self.shell.tree().semantics_revision() != semantics_revision_before),
            };
            trace.push(TraceFrame::new(frame, self.shell.now_ms(), labels, stats, paint).with_semantics(semantics));
        }
        Ok(trace)
    }

    /// 写出 motion trace JSON。
    pub fn save_trace(&self, path: &str, trace: &[TraceFrame]) -> Result<(), String> {
        write_trace(path, trace)
    }

    /// 把最近一帧软件光栅化结果写出为 PNG。
    pub fn save_png(&self, path: &str) -> Result<(), String> {
        let img = self.shell.image().ok_or_else(|| "no frame rendered; call render() first".to_string())?;
        write_png(path, img)
    }

    /// 把当前语义树写出为 JSON(稳定 index id)。
    pub fn save_tree(&self, path: &str) -> Result<(), String> {
        let json = tree_json(&self.shell);
        std::fs::write(path, json).map_err(|e| e.to_string())?;
        Ok(())
    }

    pub fn shell(&self) -> &HeadlessShell {
        &self.shell
    }
}

fn write_png(path: &str, img: &RgbaImage) -> Result<(), String> {
    use std::fs::File;
    let file = File::create(path).map_err(|e| e.to_string())?;
    let mut enc = png::Encoder::new(file, img.width, img.height);
    enc.set_color(png::ColorType::Rgba);
    enc.set_depth(png::BitDepth::Eight);
    let mut w = enc.write_header().map_err(|e| e.to_string())?;
    w.write_image_data(&img.data).map_err(|e| e.to_string())?;
    Ok(())
}

/// 最小 JSON 字符串转义(不引入 serde 依赖,避免侵入 `SemanticsData`)。
fn json_str(s: &str) -> String {
    let mut out = String::from("\"");
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            _ => out.push(c),
        }
    }
    out.push('"');
    out
}

fn json_opt(s: &Option<String>) -> String {
    match s {
        Some(v) => json_str(v),
        None => "null".to_string(),
    }
}

/// 基于 `a11y_snapshot()` 的扁平语义列表生成 JSON。
///
/// 用扁平顺序 index 作为稳定 id:同结构、同构建顺序两次运行 id 一致(满足可重放)。
/// 不暴露裸 `ElementId`(跨进程不稳定)。层级结构可由调用方按 `child_count` /
/// `bounds` 还原,或后续接 element 树遍历升级为 `root/0/2` 路径 id。
fn tree_json(shell: &HeadlessShell) -> String {
    let snap = shell.a11y_snapshot();
    let mut out = String::from("[\n");
    for (i, pair) in snap.iter().enumerate() {
        let d = &pair.1;
        if i > 0 {
            out.push_str(",\n");
        }
        let b = d.bounds;
        out.push_str(&format!(
            "  {{\"id\":\"{}\",\"role\":\"{:?}\",\"label\":{},\"enabled\":{},\"focusable\":{},\"bounds\":{{\"x\":{},\"y\":{},\"w\":{},\"h\":{}}},\"child_count\":{}}}",
            i,
            d.role,
            json_opt(&d.label),
            d.enabled,
            d.focusable,
            b.x,
            b.y,
            b.width,
            b.height,
            d.children.len(),
        ));
    }
    out.push_str("\n]");
    out
}

fn command_source(source: &str) -> Option<CommandSource> {
    match parse_command_source(source)? {
        "menu" => Some(CommandSource::Menu),
        "tray_menu" => Some(CommandSource::TrayMenu),
        "tray_click" => Some(CommandSource::TrayClick),
        "global_shortcut" => Some(CommandSource::GlobalShortcut),
        "second_instance" => Some(CommandSource::SecondInstance),
        _ => None,
    }
}

fn format_command_stats(stats: CommandStats) -> String {
    format!(
        "delivered={},consumed={},passthrough={},menu={},tray_menu={},tray_click={},global_shortcut={},second_instance={}",
        stats.delivered,
        stats.consumed,
        stats.passthrough,
        stats.menu,
        stats.tray_menu,
        stats.tray_click,
        stats.global_shortcut,
        stats.second_instance
    )
}

/// 当前焦点元素的稳定语义标签;没有焦点时返回 None。
/// 不暴露裸 ElementId(跨进程不稳定),优先用语义 label,其次用 role。
fn focus_label(shell: &HeadlessShell) -> Option<String> {
    let id = shell.tree().focused_element()?;
    shell
        .a11y_snapshot()
        .into_iter()
        .find(|(candidate, _)| *candidate == id)
        .map(|(_, data)| data.label.unwrap_or_else(|| format!("{:?}", data.role)))
        .or_else(|| {
            shell.tree().inspect_elements(800).into_iter().find(|e| e.id == id).map(|e| e.type_name.to_string())
        })
}

/// 语义树稳定 digest:只用于 trace diff 定位,不暴露 ElementId。
///
/// 同一结构/标签/bounds 两次运行必须一致;任何语义节点变化都要反映到 digest。
fn a11y_digest(shell: &HeadlessShell) -> String {
    let mut hasher = DefaultHasher::new();
    for (_, data) in shell.a11y_snapshot() {
        format!("{data:?}").hash(&mut hasher);
    }
    format!("{:016x}", hasher.finish())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scenes::{AppServicesJourneyScene, MultiDprWindowsScene};
    use mgui_components::{ButtonWidget, ContainerWidget};
    use mgui_core::{Size, WidgetNode};

    struct ProbeScene;
    impl Scene for ProbeScene {
        fn name(&self) -> &'static str {
            "probe"
        }
        fn build(&self) -> WidgetNode {
            WidgetNode::new(
                ContainerWidget::new().child(ButtonWidget::new(Size::new(160.0, 48.0)).with_text("Hi", 16.0)),
            )
        }
    }

    #[test]
    fn registry_lookup_and_render_smoke() {
        let mut reg = SceneRegistry::new();
        reg.register(Box::new(ProbeScene));
        assert_eq!(reg.names(), vec!["probe"]);
        assert!(reg.get("probe").is_some());
        assert!(reg.get("missing").is_none());

        let mut app = HeadlessApp::new(200.0, 120.0, reg);
        app.render("probe", 0).expect("render probe");
        // 有语义树输出(至少一个 Button 角色节点)
        let json = tree_json(app.shell());
        assert!(json.contains("Button"), "语义树应包含 Button 节点: {json}");
    }

    fn fresh_app() -> HeadlessApp {
        let mut reg = SceneRegistry::new();
        reg.register(Box::new(ProbeScene));
        HeadlessApp::new(200.0, 120.0, reg)
    }

    #[test]
    fn semantic_digest_is_stable_for_the_same_tree() {
        let mut app = fresh_app();
        app.render("probe", 0).expect("render probe");
        let first = a11y_digest(app.shell());
        let second = a11y_digest(app.shell());
        assert_eq!(first, second);
        assert_eq!(first.len(), 16);
    }

    #[test]
    fn a11y_journey_records_focus_chain_and_semantic_bumps() {
        let mut reg = SceneRegistry::new();
        reg.register(Box::new(A11yJourneyScene::default()));
        let script = Script::parse(
            r#"[
                {"frame":0,"event":{"type":"key","key":"Tab","pressed":true}},
                {"frame":1,"event":{"type":"key","key":"Tab","pressed":true}},
                {"frame":2,"event":{"type":"key","key":"Enter","pressed":true}},
                {"frame":3,"event":{"type":"key","key":"Enter","pressed":false}},
                {"frame":4,"event":{"type":"key","key":"Escape","pressed":true}},
                {"frame":5,"event":{"type":"key","key":"Tab","pressed":true}}
            ]"#,
        )
        .expect("parse a11y script");
        let mut app = HeadlessApp::new(320.0, 220.0, reg);
        let trace = app.run_script("a11y_journey", &script, 16, 6).expect("replay");

        let focus: Vec<Option<&str>> = trace.iter().map(|f| f.semantics.focus.as_deref()).collect();
        assert_eq!(focus[0], Some("Journey A"), "首个 Tab 应进入焦点链");
        assert_eq!(focus[1], Some("Journey B"));
        assert_eq!(focus[2], focus[1], "Enter 按下不应移动焦点");
        assert_eq!(focus[3], focus[1], "Enter 抬起不应移动焦点");
        assert_eq!(focus[4], focus[1], "Escape 不应移动焦点");
        assert_eq!(focus[5], Some("Journey C"));
        assert_eq!(trace[3].semantics.shared_state.as_deref(), Some("activations=1"), "Enter 抬起才激活按钮");
        assert_eq!(trace[4].semantics.shared_state.as_deref(), Some("activations=1"));
        assert!(trace.iter().any(|f| f.semantics.semantics_bumps > 0), "焦点链变化必须在语义 revision 上留下 bump");
    }

    #[test]
    fn command_route_and_shared_state_are_injected_into_trace() {
        let mut reg = SceneRegistry::new();
        reg.register(Box::new(CommandRouteScene::default()));
        let script = Script::parse(
            r#"[
                {"frame":0,"event":{"type":"command","source":"menu","id":1}},
                {"frame":1,"event":{"type":"command","source":"global_shortcut","id":2}},
                {"frame":2,"event":{"type":"command","source":"second_instance","id":99}}
            ]"#,
        )
        .expect("parse command script");
        let mut app = HeadlessApp::new(320.0, 180.0, reg);
        let trace = app.run_script("command_route", &script, 16, 3).expect("replay");

        let command = trace[0].semantics.command.as_deref().expect("command source");
        assert!(command.contains("delivered=1,consumed=1,passthrough=0"), "{command}");
        assert!(command.contains("menu=1"), "{command}");
        assert_eq!(trace[0].semantics.shared_state.as_deref(), Some("revision=1"));

        let command = trace[1].semantics.command.as_deref().expect("command source");
        assert!(command.contains("delivered=2,consumed=1,passthrough=1"), "{command}");
        assert!(command.contains("global_shortcut=1"), "{command}");
        assert_eq!(trace[1].semantics.shared_state.as_deref(), Some("revision=1"));

        let command = trace[2].semantics.command.as_deref().expect("command source");
        assert!(command.contains("delivered=3,consumed=1,passthrough=2"), "{command}");
        assert!(command.contains("second_instance=1"), "{command}");
        assert!(trace[0].events[0].contains("source: menu"), "命令事件应留在 trace 的事件列");
    }

    #[test]
    fn app_services_journey_is_injected_into_trace() {
        let mut reg = SceneRegistry::new();
        reg.register(Box::new(AppServicesJourneyScene::default()));
        let script = Script::parse(
            r#"[
                {"frame":0,"event":{"type":"command","source":"menu","id":1}},
                {"frame":1,"event":{"type":"command","source":"menu","id":2}},
                {"frame":2,"event":{"type":"command","source":"menu","id":3}},
                {"frame":3,"event":{"type":"command","source":"menu","id":4}},
                {"frame":4,"event":{"type":"command","source":"menu","id":5}}
            ]"#,
        )
        .expect("parse app services script");
        let mut app = HeadlessApp::new(320.0, 180.0, reg);
        let trace = app.run_script("app_services_journey", &script, 16, 5).expect("replay");

        assert_eq!(
            trace[0].semantics.shared_state.as_deref(),
            Some("settings=showcase.high_contrast=1 recent=0 crashes=0")
        );
        assert_eq!(
            trace[1].semantics.shared_state.as_deref(),
            Some("settings=showcase.high_contrast=1 recent=1 crashes=0")
        );
        assert_eq!(
            trace[2].semantics.shared_state.as_deref(),
            Some("settings=showcase.high_contrast=1 recent=1 crashes=1")
        );
        assert_eq!(
            trace[4].semantics.shared_state.as_deref(),
            Some("settings=showcase.high_contrast=1 recent=0 crashes=0")
        );
        let persistence = trace[4].semantics.persistence.as_deref().expect("persistence source");
        assert!(persistence.contains("schema=1 owner=held recovery=none"), "{persistence}");
    }

    #[test]
    fn multi_dpr_windows_trace_covers_scale_chain_and_same_dpr_noop() {
        let mut reg = SceneRegistry::new();
        reg.register(Box::new(MultiDprWindowsScene::default()));
        let script = Script::parse(
            r#"[
                {"frame":0,"event":{"type":"scale_factor_changed","dpr":1.0,"logical_width":800,"logical_height":600}},
                {"frame":1,"event":{"type":"scale_factor_changed","dpr":1.25,"logical_width":800,"logical_height":600}},
                {"frame":2,"event":{"type":"scale_factor_changed","dpr":2.0,"logical_width":800,"logical_height":600}},
                {"frame":3,"event":{"type":"scale_factor_changed","dpr":1.5,"logical_width":800,"logical_height":600}},
                {"frame":4,"event":{"type":"scale_factor_changed","dpr":1.5,"logical_width":800,"logical_height":600}}
            ]"#,
        )
        .expect("parse scale script");
        let mut app = HeadlessApp::new(800.0, 600.0, reg);
        let trace = app.run_script("multi_dpr_windows", &script, 16, 5).expect("replay");

        assert!(trace[0].events[0].contains("ScaleFactorChanged"), "DPR 变化应进入 trace 事件列");
        let first = trace[0].semantics.shared_state.as_deref().expect("state");
        assert!(first.contains("window_a_dpr=1.00") && first.contains("window_b_dpr=1.00"), "{first}");
        assert!(first.contains("revision=1"), "{first}");
        let third = trace[2].semantics.shared_state.as_deref().expect("state");
        assert!(third.contains("window_b_dpr=2.00") && third.contains("revision=3"), "{third}");
        let fourth = trace[3].semantics.shared_state.as_deref().expect("state");
        assert!(fourth.contains("window_b_dpr=1.50") && fourth.contains("revision=4"), "{fourth}");
        let fifth = trace[4].semantics.shared_state.as_deref().expect("state");
        assert!(fifth.contains("window_b_dpr=1.50") && fifth.contains("revision=4"), "同 DPR 不应推进 revision");
        let text = trace[4].semantics.text_runtime.as_deref().expect("text runtime source");
        assert!(text.contains("window_a_key=") && text.contains("window_b_key="), "{text}");
    }

    #[test]
    fn script_replay_advances_virtual_clock_and_is_deterministic() {
        let script = Script::parse(
            r#"[
                {"frame":1,"event":{"type":"pointer_move","x":10,"y":20}},
                {"frame":3,"event":{"type":"key","key":"Enter","pressed":true}}
            ]"#,
        )
        .expect("parse script");

        let replay = || fresh_app().run_script("probe", &script, 16, 6).expect("replay");
        let a = replay();
        let b = replay();

        assert_eq!(a.len(), 6);
        assert_eq!(a, b, "同脚本两次回放必须逐位相等");
        for (i, frame) in a.iter().enumerate() {
            assert_eq!(frame.frame, i);
            assert_eq!(frame.time_ms, (i as u64) * 16, "逻辑时间必须由虚拟时钟逐帧推进");
        }
        // 事件只在指定帧注入,且翻译成真实 ShellEvent(走同源管线)。
        assert!(a[0].events.is_empty() && a[2].events.is_empty());
        assert_eq!(a[1].events.len(), 1);
        assert!(a[1].events[0].contains("CursorMoved"));
        assert_eq!(a[3].events.len(), 1);
        assert!(a[3].events[0].contains("Enter"));
    }

    #[test]
    fn trace_captures_real_stats_layers_and_writes_json() {
        let script = Script::parse("[]").expect("parse empty script");
        let mut app = fresh_app();
        let trace = app.run_script("probe", &script, 16, 3).expect("replay");

        assert_eq!(trace.len(), 3);
        // trace 读的是 run_frame 真实产出的 layer,ProbeScene 的按钮至少产出一层。
        assert!(!trace[0].layers.is_empty(), "trace 应记录真实 layer effect");
        // headless 稳态帧从不全树重建 —— 这是 P0b"不逐帧重建"的验收锚点。
        assert!(!trace[2].rebuilt, "稳态帧不应 rebuilt");

        let path = std::env::temp_dir().join("mgui_agent_trace_test.json");
        let p = path.to_str().expect("utf8 path");
        app.save_trace(p, &trace).expect("write trace");
        let written = std::fs::read_to_string(p).expect("read trace");
        assert!(written.contains("\"time_ms\""), "trace JSON 应含逻辑时间");
        assert!(written.contains("\"paint_commands\""), "trace JSON 应含每帧绘制量");
        let _ = std::fs::remove_file(p);
    }
}