actl-uia 0.1.6

Windows UIA backend: the ONLY crate allowed to touch COM/unsafe
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! locate —— 定位链(L1 精确 → L2 名称模糊 → L3 序数/锚点 → L4 虚拟化容器),
//! 以及基于定位的元素等待(wait/wait --gone)。候选 ref 编号与 snapshot 同源。

use actl_core::target::Target;
use actl_core::{CtlError, ErrorCode};

use uiautomation::{UIAutomation, UIElement, UITreeWalker};

use crate::window::{ensure_window_responsive, find_window, top_level_of_focused};
use crate::{internal, timing};

/// 定位结果:命中元素 + 所在窗口。
pub struct Located {
    pub window_title: String,
    pub role: String,
    pub name: Option<String>,
    pub automation_id: Option<String>,
    /// 定位链实际命中级别:"primary" | "fuzzy-name" | "role-ordinal" |
    /// "anchor" | "ref-replay" | "item-container"——agent 据此判断置信度并决定是否加验证
    pub resolved_by: &'static str,
    pub(crate) element: UIElement,
}

/// 在目标窗口内按 Target 定位元素;遍历须完整,不能用截断结果证明唯一性。
/// `Ref(n)` 数不到 = 树已变化 → STALE_REF;语义选择器无命中 → NOT_FOUND(06 §4)。
pub fn locate(app: Option<&str>, target: &Target, near: Option<&str>) -> Result<Located, CtlError> {
    if matches!(target, Target::Uia(_)) && near.is_some() {
        return Err(CtlError::protocol(
            "uia selectors do not support --near; use within and unique conditions",
        ));
    }
    // xy: 坐标目标无元素可解析——物理专用通道(pointer_at_physical),
    // 误入元素定位路径 = 协议错误(所有元素类命令对 xy 的统一拒绝)
    if let Target::Coord(..) = target {
        return Err(CtlError::protocol(format!(
            "{} cannot be resolved to an element; coordinate targets are physical-only (click xy:x,y --app <win> --physical)",
            target.describe()
        )));
    }
    let auto = UIAutomation::new().map_err(internal)?;
    if let Target::Uia(selector) = target {
        let root = crate::scoped_locate::window(&auto, app)?;
        return crate::scoped_locate::locate(&auto, &root, selector);
    }
    let walker = auto.create_tree_walker().map_err(internal)?;
    let root = {
        let _t = actl_core::trace::scope("locate.window");
        match app {
            Some(pattern) => find_window(&auto, &walker, pattern)?,
            None => {
                // fail-closed:@eN 的编号只对快照来源窗口的遍历顺序有意义;对着
                // "当前恰好聚焦的窗口"重放,前台一变就会静默点进别的应用(已实际发生)。
                if matches!(target, Target::Ref(_)) {
                    return Err(CtlError::protocol(format!(
                        "{} requires --app: refs are scoped to the window the snapshot came from; \
                         pass --app <title-substr> or re-snapshot",
                        target.describe()
                    )));
                }
                top_level_of_focused(&auto, &walker)?
            }
        }
    };
    let window_title = root
        .get_name()
        .map_err(|e| crate::read_channel::failure("window.name", e))?;
    // 激活感知:挂起目标先唤醒(有界),避免 DFS 里逐调用 stall
    let _wake_ms = {
        let _t = actl_core::trace::scope("locate.wake");
        ensure_window_responsive(&root)
    };

    // @eN:计数重放,不参与 fallback(ref 漂移 = STALE_REF,模糊化反而危险)
    if let Target::Ref(n) = target {
        let mut counter = 0u32;
        let _t = actl_core::trace::scope("locate.ref-replay");
        return match collect_until_ref(&walker, &root, 0, *n, &mut counter)? {
            Some(hit) => {
                crate::identity::check_ref(&root, &hit, *n)?;
                located_from(hit, window_title, "ref-replay")
            }
            None => Err(CtlError::new(
                ErrorCode::StaleRef,
                format!(
                    "{} does not resolve — the tree changed since the snapshot",
                    target.describe()
                ),
            )),
        };
    }

    // L1 精确:全量收集(ref 编号与 snapshot 同源,候选可直接重放)
    // id: 快路径:provider 侧条件匹配(TreeScope::Subtree,单次 COM 往返替代
    // 逐元素三连读)——AutomationId 语义 = 精确匹配,与属性条件语义一致;
    // name: 的子串语义 provider 做不了,不走快路径。
    let mut counter = 0u32;
    let mut matches = Vec::new();
    if let Target::Id(_) = target {
        let hits = {
            let _t = actl_core::trace::scope("locate.fastpath");
            fast_exact_ids(&auto, &root, target)?
        };
        match hits {
            Some(hits) if hits.len() == 1 => {
                return located_from(hits[0].clone(), window_title, "primary");
            }
            Some(hits) if hits.is_empty() => {
                // L1 确定空手(id: 无 fuzzy 层),直落 L4 虚拟化容器
                let _t = actl_core::trace::scope("locate.l4");
                if let Some(hit) = locate_virtualized(&walker, &root, target)? {
                    return located_from(hit, window_title, "item-container");
                }
                return Err(CtlError::new(
                    ErrorCode::NotFound,
                    format!(
                        "no element matches {} (exact and virtualized-container levels)",
                        target.describe()
                    ),
                ));
            }
            _ => {} // 多命中(候选需 ref 编号)或快路径不可用 → 全遍历
        }
    }
    {
        let _t = actl_core::trace::scope("locate.dfs");
        collect_matches(&walker, &root, 0, target, false, &mut counter, &mut matches)?;
    }

    // L2 名称模糊(仅 name: 目标且 L1 空手时):大小写/空白不敏感
    if matches.is_empty() {
        if let Target::Name(_) = target {
            let mut fuzzy = Vec::new();
            collect_matches(&walker, &root, 0, target, true, &mut counter, &mut fuzzy)?;
            if !fuzzy.is_empty() {
                fuzzy.sort_by_key(|c: &Candidate| c.ref_no);
                return select(
                    fuzzy,
                    target,
                    near,
                    &walker,
                    &root,
                    window_title,
                    "fuzzy-name",
                );
            }
        }
        // L4 虚拟化容器(spike 2026-09-26 证真:Explorer 文件列表的 ListItem 不物化,
        // walker 遍历恒 0 命中;ItemContainerPattern::FindItemByProperty 精确命中)
        let l4 = {
            let _t = actl_core::trace::scope("locate.l4");
            locate_virtualized(&walker, &root, target)?
        };
        if let Some(hit) = l4 {
            return located_from(hit, window_title, "item-container");
        }
        return Err(CtlError::new(
            ErrorCode::NotFound,
            format!(
                "no element matches {} (exact, fuzzy and virtualized-container levels)",
                target.describe()
            ),
        ));
    }
    matches.sort_by_key(|c: &Candidate| c.ref_no);
    select(
        matches,
        target,
        near,
        &walker,
        &root,
        window_title,
        "primary",
    )
}

/// 分级裁决:唯一命中 → 命中;多命中且有锚点 → 最近者;多命中 → AMBIGUOUS
/// 附结构化候选(ref/role/name,docs/12 §4 协议评审项);RoleAt 越界 → NOT_FOUND。
fn select(
    matches: Vec<Candidate>,
    target: &Target,
    near: Option<&str>,
    walker: &UITreeWalker,
    root: &UIElement,
    window_title: String,
    level: &'static str,
) -> Result<Located, CtlError> {
    // L3 序数直选
    if let Target::RoleAt(_, n) | Target::IdAt(_, n) = target {
        return match matches.get((*n as usize).saturating_sub(1)) {
            Some(c) => located_from(
                c.element.clone(),
                window_title,
                if matches!(target, Target::IdAt(..)) {
                    "id-ordinal"
                } else {
                    "role-ordinal"
                },
            ),
            None => Err(CtlError::new(
                ErrorCode::NotFound,
                format!(
                    "{}: only {} match(es) in the window",
                    target.describe(),
                    matches.len()
                ),
            )),
        };
    }
    if matches.len() == 1 {
        return located_from(matches[0].element.clone(), window_title, level);
    }
    // 多命中 + 锚点:取与锚点矩形中心距最近者
    if let Some(anchor_pat) = near {
        let mut counter = 0u32;
        let mut anchors = Vec::new();
        // 锚点接受完整选择器语法;裸串按 name: 子串兜底
        let anchor_target =
            actl_core::parse_target(anchor_pat).unwrap_or(Target::Name(anchor_pat.to_string()));
        collect_matches(
            walker,
            root,
            0,
            &anchor_target,
            false,
            &mut counter,
            &mut anchors,
        )?;
        if anchors.len() != 1 {
            return Err(CtlError::new(
                ErrorCode::NotFound,
                format!(
                    "--near anchor {anchor_pat:?} must match exactly one element, got {}",
                    anchors.len()
                ),
            ));
        }
        {
            let ar = anchors[0]
                .element
                .get_bounding_rectangle()
                .map_err(|e| crate::read_channel::failure("anchor.bounds", e))?;
            let (ax, ay) = center(&ar);
            let mut best: Option<(f64, usize)> = None;
            for (i, c) in matches.iter().enumerate() {
                {
                    let r = c
                        .element
                        .get_bounding_rectangle()
                        .map_err(|e| crate::read_channel::failure("candidate.bounds", e))?;
                    let (cx, cy) = center(&r);
                    let dx = (cx - ax) as f64;
                    let dy = (cy - ay) as f64;
                    let d = dx * dx + dy * dy;
                    if best.map(|(bd, _)| d < bd).unwrap_or(true) {
                        best = Some((d, i));
                    }
                }
            }
            if let Some((_, i)) = best {
                return located_from(matches[i].element.clone(), window_title, "anchor");
            }
        }
    }
    // AMBIGUOUS + 结构化候选(每个含可重放的 ref)
    let evidence: Vec<serde_json::Value> = matches
        .iter()
        .take(8)
        .map(|c| {
            serde_json::json!({
                "ref": format!("@e{}", c.ref_no),
                "role": c.role,
                "name": c.name,
                "automation_id": c.automation_id,
            })
        })
        .collect();
    Err(CtlError::with_evidence(
        ErrorCode::Ambiguous,
        format!(
            "{} matches {} elements in the window; pick one by @eN or role ordinal              (--near anchor also applies)",
            target.describe(),
            matches.len()
        ),
        serde_json::json!({ "candidates": evidence }),
    ))
}

fn center(r: &uiautomation::types::Rect) -> (i32, i32) {
    (
        (r.get_left() + r.get_right()) / 2,
        (r.get_top() + r.get_bottom()) / 2,
    )
}

fn located_from(
    elem: UIElement,
    window_title: String,
    resolved_by: &'static str,
) -> Result<Located, CtlError> {
    Ok(Located {
        window_title,
        role: strict_role(&elem)?,
        name: Some(
            elem.get_name()
                .map_err(|e| crate::read_channel::failure("name", e))?,
        ),
        automation_id: Some(
            elem.get_automation_id()
                .map_err(|e| crate::read_channel::failure("automation_id", e))?,
        ),
        resolved_by,
        element: elem,
    })
}
/// 定位链候选(ref 与 snapshot 同源编号,可直接重放)
struct Candidate {
    element: UIElement,
    ref_no: u32,
    role: String,
    name: Option<String>,
    automation_id: Option<String>,
}

/// @eN 在完整观察的树中重放;观察失败与 ref 消失分开。
fn collect_until_ref(
    _walker: &UITreeWalker,
    elem: &UIElement,
    _depth: u32,
    want: u32,
    counter: &mut u32,
) -> Result<Option<UIElement>, CtlError> {
    for entry in crate::observation::tree(elem)?.require_complete()? {
        let role = strict_role(&entry.element)?;
        if actl_core::is_interactive_role(&role) {
            *counter += 1;
            if *counter == want {
                return Ok(Some(entry.element));
            }
        }
    }
    Ok(None)
}

fn strict_role(elem: &UIElement) -> Result<String, CtlError> {
    elem.get_control_type()
        .map(|v| format!("{v:?}"))
        .map_err(|e| crate::read_channel::failure("control_type", e))
}

fn collect_matches(
    _walker: &UITreeWalker,
    elem: &UIElement,
    _depth: u32,
    target: &Target,
    fuzzy: bool,
    counter: &mut u32,
    out: &mut Vec<Candidate>,
) -> Result<(), CtlError> {
    *counter = 0;
    for entry in crate::observation::tree(elem)?.require_complete()? {
        let element = entry.element;
        let role = strict_role(&element)?;
        let ref_no = if actl_core::is_interactive_role(&role) {
            *counter += 1;
            *counter
        } else {
            0
        };
        let name = element
            .get_name()
            .map_err(|e| crate::read_channel::failure("name", e))?;
        let id = element
            .get_automation_id()
            .map_err(|e| crate::read_channel::failure("automation_id", e))?;
        let hit = match target {
            Target::Name(s) if fuzzy => actl_core::target::fuzzy_contains(&name, s),
            Target::Name(s) => name.contains(s.as_str()),
            Target::Id(s) | Target::IdAt(s, _) => id == *s,
            Target::Role(s) | Target::RoleAt(s, _) => role == *s,
            _ => false,
        };
        if hit {
            out.push(Candidate {
                element,
                ref_no,
                role,
                name: Some(name),
                automation_id: Some(id),
            });
        }
    }
    Ok(())
}
/// id: 目标的 provider 侧精确匹配(UIA FindAll + AutomationId 属性条件,
/// TreeScope::Subtree 与 DFS 全遍历同覆盖含根自身)。
/// 条件创建/查询失败直接传播,不能触发静默回退。
fn fast_exact_ids(
    auto: &UIAutomation,
    root: &UIElement,
    target: &Target,
) -> Result<Option<Vec<UIElement>>, CtlError> {
    use uiautomation::types::{TreeScope, UIProperty};
    use uiautomation::variants::Variant;

    let Target::Id(s) = target else {
        return Ok(None);
    };
    let cond = auto
        .create_property_condition(UIProperty::AutomationId, Variant::from(s.clone()), None)
        .map_err(|e| crate::read_channel::failure("id.condition", e))?;
    let cache = auto.create_cache_request().map_err(internal)?;
    cache
        .set_tree_filter(auto.create_true_condition().map_err(internal)?)
        .map_err(internal)?;
    cache.set_tree_scope(TreeScope::Element).map_err(internal)?;
    root.find_all_build_cache(TreeScope::Subtree, &cond, &cache)
        .map(Some)
        .map_err(|e| crate::read_channel::failure("id.query", e))
}

// ─── L4 虚拟化容器兜底(M2 观察层强化,spike 2026-09-26 证真) ───────────────
// Explorer/任务管理器等大列表的 ListItem 不物化(US1 实测:等 6s + F5 后 walker
// 遍历仍 0 命中),ItemContainerPattern::FindItemByProperty 由 provider 侧
// 直接命中未物化条目(61 文件目录实测:树内 0 命中 → 精确查询命中末位文件)。

/// L4 支持的属性查询映射:Name → UIA Name 精确;Id → AutomationId 精确。
/// Role/Ref 无属性查询语义(Name/AutomationId 之外的属性 provider 普遍不支持),
/// 返回 None(定位链保持原 NotFound/STALE_REF 语义)。
fn container_query_for(
    target: &Target,
) -> Option<(windows::Win32::UI::Accessibility::UIA_PROPERTY_ID, String)> {
    use windows::Win32::UI::Accessibility::{UIA_AutomationIdPropertyId, UIA_NamePropertyId};
    match target {
        Target::Name(s) => Some((UIA_NamePropertyId, s.clone())),
        Target::Id(s) => Some((UIA_AutomationIdPropertyId, s.clone())),
        _ => None,
    }
}

/// L4 执行体:窗口内收集 ItemContainer 容器,逐个精确查询。
/// 仅在 L1/L2 双落空后进入(不在热路径);无命中返回 None → NotFound。
/// FindItemByProperty 为**精确匹配**(provider 侧无子串语义)——name: 的
/// 子串语义在 L1/L2 已消耗,进入 L4 的 name 值必须是完整名称(如完整文件名)。
///
/// unsafe 理由(AGENTS §5,crate 豁免点):crate 安全包装不接受 NULL 起查元素
/// (MS 文档语义 = "从头查",且零值 UIElement 的 Drop 会 Release(null) 崩溃),
/// 经 `UIElement::as_ref()` 取原生 IUIAutomationElement 直调 GetCurrentPattern
/// + FindItemByProperty(None, ...);类型与 crate 同源(均 windows 0.62)。
fn locate_virtualized(
    _walker: &UITreeWalker,
    root: &UIElement,
    target: &Target,
) -> Result<Option<UIElement>, CtlError> {
    use uiautomation::{types::UIProperty, variants::Variant};
    use windows::{
        Win32::UI::Accessibility::{
            IUIAutomationElement, IUIAutomationItemContainerPattern, UIA_ItemContainerPatternId,
        },
        core::Interface,
    };
    let Some((prop, value)) = container_query_for(target) else {
        return Ok(None);
    };
    let value = Variant::from(value);
    let entries = crate::observation::tree(root)?.require_complete()?;
    let mut hit = None;
    for entry in entries {
        let c = entry.element;
        if !crate::read_channel::available(
            &c,
            UIProperty::IsItemContainerPatternAvailable,
            "item-container",
        )? {
            continue;
        }
        // Raw ABI preserves S_OK + null (observed absence), unlike a non-null interface wrapper.
        // The returned non-null COM reference is adopted exactly once; no null UIElement is made.
        unsafe {
            let pattern: IUIAutomationItemContainerPattern = c
                .as_ref()
                .GetCurrentPattern(UIA_ItemContainerPatternId)
                .and_then(|p| p.cast())
                .map_err(|e| crate::read_channel::failure("item-container.pattern", e.into()))?;
            let mut raw = std::ptr::null_mut();
            (pattern.vtable().FindItemByProperty)(
                pattern.as_raw(),
                std::ptr::null_mut(),
                prop,
                std::mem::transmute_copy(value.as_ref()),
                &mut raw,
            )
            .ok()
            .map_err(|e| crate::read_channel::failure("item-container.query", e.into()))?;
            if !raw.is_null() {
                let element = UIElement::from(IUIAutomationElement::from_raw(raw));
                let mut second = std::ptr::null_mut();
                (pattern.vtable().FindItemByProperty)(
                    pattern.as_raw(),
                    element.as_ref().as_raw(),
                    prop,
                    std::mem::transmute_copy(value.as_ref()),
                    &mut second,
                )
                .ok()
                .map_err(|e| crate::read_channel::failure("item-container.next", e.into()))?;
                if !second.is_null() {
                    // Adopt and release the extra returned reference before rejecting ambiguity.
                    let _second = IUIAutomationElement::from_raw(second);
                    return Err(CtlError::new(
                        ErrorCode::Ambiguous,
                        "multiple virtualized items matched",
                    ));
                }
                if hit.is_some() {
                    return Err(CtlError::new(
                        ErrorCode::Ambiguous,
                        "multiple virtualized containers matched",
                    ));
                }
                hit = Some(element);
            }
        }
    }
    Ok(hit)
}
/// wait 族轮询的定位语义:仅 NOT_FOUND 表示缺席;其他观察错误立即传播。
/// **AMBIGUOUS = 确定性多命中,等待不可能收敛 → 立即失败**(候选 evidence
/// 已随错误携带,无需等满超时;2026-09-27 抖音多文档页实测:samples 冻结
/// 在 1 的误导性 TIMEOUT 根因)。
fn poll(app: Option<&str>, target: &Target) -> Result<Option<Located>, CtlError> {
    actl_core::wait_control::check()?;
    crate::scoped_locate::observed(locate(app, target, None))
}

/// wait --element:轮询定位直到目标可解析(TIMEOUT 语义;与 --expect 的
/// "立即断言"分工见 06 §3.6"耐心等待")。
pub fn wait_element(app: Option<&str>, target: &Target, timeout_ms: u64) -> Result<(), CtlError> {
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
    loop {
        if poll(app, target)?.is_some() {
            return Ok(());
        }
        if std::time::Instant::now() >= deadline {
            return Err(CtlError::new(
                ErrorCode::Timeout,
                format!(
                    "element {} did not resolve within {timeout_ms}ms",
                    target.describe()
                ),
            ));
        }
        std::thread::sleep(std::time::Duration::from_millis(timing().poll_ms));
    }
}

/// wait --gone:轮询直到目标**不再**可解析(消失;TIMEOUT 语义)。
pub fn wait_gone(app: Option<&str>, target: &Target, timeout_ms: u64) -> Result<(), CtlError> {
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
    loop {
        if poll(app, target)?.is_none() {
            return Ok(());
        }
        if std::time::Instant::now() >= deadline {
            return Err(CtlError::new(
                ErrorCode::Timeout,
                format!(
                    "{} still resolves after {timeout_ms}ms (expected it to disappear)",
                    target.describe()
                ),
            ));
        }
        std::thread::sleep(std::time::Duration::from_millis(timing().poll_ms));
    }
}

#[cfg(test)]
mod tests {
    use super::container_query_for;
    use actl_core::target::Target;
    use windows::Win32::UI::Accessibility::{UIA_AutomationIdPropertyId, UIA_NamePropertyId};

    #[test]
    fn l4_maps_name_and_id_to_exact_property_queries() {
        let (prop, v) = container_query_for(&Target::Name("report.xlsx".into())).expect("name");
        assert_eq!(prop, UIA_NamePropertyId);
        assert_eq!(v, "report.xlsx");

        let (prop, v) = container_query_for(&Target::Id("SystemListItem".into())).expect("id");
        assert_eq!(prop, UIA_AutomationIdPropertyId);
        assert_eq!(v, "SystemListItem");
    }

    #[test]
    fn l4_excludes_role_and_ref_targets() {
        assert!(container_query_for(&Target::Role("ListItem".into())).is_none());
        assert!(container_query_for(&Target::RoleAt("ListItem".into(), 2)).is_none());
        assert!(container_query_for(&Target::Ref(7)).is_none());
    }
}

/// wait --property:轮询直到元素可解析且属性满足期望(06 §3.4 完整谓词语法)。
/// 谓词:`value=<expected>`(Value/TextPattern 双通道)| `name=<substr>` | `checked=on|off`;
/// contains=true 时 value/name 用子串语义。元素尚未可解析视为"未满足"继续等
/// (与 --element 的分工:property 隐含存在性)。
pub fn wait_property(
    app: Option<&str>,
    target: &Target,
    predicate: &WaitPredicate,
    timeout_ms: u64,
) -> Result<String, CtlError> {
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
    let mut last: Option<String> = None;
    loop {
        if let Some(loc) = poll(app, target)? {
            let actual = predicate.read(&loc.element)?;
            if predicate.satisfied(actual.as_deref()) {
                return Ok(actual.unwrap_or_default());
            }
            last = actual;
        }
        if std::time::Instant::now() >= deadline {
            return Err(CtlError::with_evidence(
                ErrorCode::Timeout,
                format!(
                    "{} did not satisfy {} within {timeout_ms}ms",
                    target.describe(),
                    predicate.describe()
                ),
                serde_json::json!({ "last_actual": last, "actual":last, "target":target.describe(), "expected":predicate.expected, "property":predicate.describe().split('=').next(), "channel":match predicate.prop { WaitProp::Value => "value-or-text-pattern", WaitProp::Name => "name", WaitProp::Text => "text-pattern", WaitProp::Checked => "toggle-pattern" }, "comparison":if predicate.contains {"contains"} else {"exact"} }),
            ));
        }
        std::thread::sleep(std::time::Duration::from_millis(timing().poll_ms));
    }
}

/// wait --stable 的结果(settle 证据:采样数/变化数/末次样本长度)。
pub struct StableOutcome {
    pub samples: usize,
    pub changes: usize,
    pub last_len: usize,
}

/// wait --stable:settle 谓词——轮询直到元素可解析且观测样本连续两次不变
/// (采样间隔 settle_ms,默认 250ms → 稳定窗 500ms)。样本通道:text 优先、
/// value 次之、name 兜底(Chromium Document 的 Value=URL 对内容 settle 无
/// 意义,正文只能走 TextPattern,与 get 的 text/value 分工一致)。元素消失
/// 期间稳定计数清零(隐含存在性);超时 TIMEOUT 附 samples/changes evidence。
pub fn wait_stable(
    app: Option<&str>,
    target: &Target,
    timeout_ms: u64,
) -> Result<StableOutcome, CtlError> {
    const STABLE_SAMPLES: usize = 2;
    let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
    let mut last: Option<String> = None;
    let mut stable = 0usize;
    let mut samples = 0usize;
    let mut changes = 0usize;
    loop {
        if let Some(loc) = poll(app, target)? {
            let sample = stability_sample(&loc.element)?;
            samples += 1;
            stable = match &last {
                Some(prev) if prev == &sample => stable + 1,
                Some(_) => {
                    changes += 1;
                    1
                }
                None => 1,
            };
            last = Some(sample);
            if stable >= STABLE_SAMPLES {
                return Ok(StableOutcome {
                    samples,
                    changes,
                    last_len: last.as_deref().map(str::len).unwrap_or(0),
                });
            }
        } else {
            stable = 0;
        }
        if std::time::Instant::now() >= deadline {
            return Err(CtlError::with_evidence(
                ErrorCode::Timeout,
                format!(
                    "{} did not settle within {timeout_ms}ms (content still changing or element absent)",
                    target.describe()
                ),
                serde_json::json!({
                    "samples": samples,
                    "changes": changes,
                    "last_len": last.as_deref().map(str::len),
                }),
            ));
        }
        std::thread::sleep(std::time::Duration::from_millis(timing().settle_ms));
    }
}

/// 稳定性采样:text > value > name(富文本正文只有 TextPattern 可读;
/// value 通道兜底纯控件,name 最后)。
fn stability_sample(elem: &UIElement) -> Result<String, CtlError> {
    if let Some(text) = crate::read::read_text(elem)? {
        return Ok(text);
    }
    if let Some(value) = crate::read::read_value(elem)? {
        return Ok(value);
    }
    elem.get_name()
        .map_err(|e| crate::read_channel::failure("name", e))
}

/// wait/verify 共用的属性谓词(解析与判定分离,便于单测)。
pub struct WaitPredicate {
    pub prop: WaitProp,
    pub expected: String,
    pub contains: bool,
}

pub enum WaitProp {
    Text,
    Value,
    Name,
    Checked,
}

impl WaitPredicate {
    /// 解析 "prop=expected" 形态(prop ∈ value|name|text|checked;checked 期望 on/off)
    pub fn parse(raw: &str) -> Result<Self, CtlError> {
        let Some((prop, expected)) = raw.split_once('=') else {
            return Err(CtlError::protocol(format!(
                "invalid predicate {raw:?}: expected <prop>=<expected> with prop in value|name|text|checked"
            )));
        };
        let prop = match prop.trim() {
            "value" => WaitProp::Value,
            "name" => WaitProp::Name,
            "text" => WaitProp::Text,
            "checked" => WaitProp::Checked,
            other => {
                return Err(CtlError::protocol(format!(
                    "unknown predicate property {other:?}: expected value|name|text|checked"
                )));
            }
        };
        let expected = expected.trim().to_string();
        if expected.is_empty() {
            return Err(CtlError::protocol(format!(
                "predicate {raw:?} has an empty expectation"
            )));
        }
        if matches!(prop, WaitProp::Checked) && !matches!(expected.as_str(), "on" | "off") {
            return Err(CtlError::protocol(
                "checked predicate expects on|off (e.g. checked=on)",
            ));
        }
        Ok(Self {
            prop,
            expected,
            contains: false,
        })
    }

    pub fn describe(&self) -> String {
        let p = match self.prop {
            WaitProp::Value => "value",
            WaitProp::Name => "name",
            WaitProp::Text => "text",
            WaitProp::Checked => "checked",
        };
        format!("{p}={}", self.expected)
    }

    /// 读元素当前值(Checked 读 Toggle 状态,Value 走双通道,Name 读 UIA Name)
    pub fn read(&self, elem: &uiautomation::UIElement) -> Result<Option<String>, CtlError> {
        let (value, channel) = match self.prop {
            WaitProp::Value => (crate::read::read_value(elem)?, "value-or-text-pattern"),
            WaitProp::Text => (crate::read::read_text(elem)?, "text-pattern"),
            WaitProp::Name => (
                Some(
                    elem.get_name()
                        .map_err(|e| crate::read_channel::failure("name", e))?,
                ),
                "name",
            ),
            WaitProp::Checked => (
                crate::read_channel::toggle(elem)?.map(|v| v.to_lowercase()),
                "toggle-pattern",
            ),
        };
        Ok(Some(crate::read_channel::require(value, channel)?))
    }

    /// 判定(读不到值 = 未满足,fail-closed)
    pub fn satisfied(&self, actual: Option<&str>) -> bool {
        let Some(a) = actual else { return false };
        match (&self.prop, self.contains) {
            (WaitProp::Checked, _)
            | (WaitProp::Value, false)
            | (WaitProp::Name | WaitProp::Text, false) => a == self.expected,
            (WaitProp::Value, true) | (WaitProp::Name | WaitProp::Text, true) => {
                a.contains(&self.expected)
            }
        }
    }
}

#[cfg(test)]
mod wait_tests {
    use super::*;
    use actl_core::CtlError;

    #[test]
    fn predicate_parses_and_rejects() {
        let p = WaitPredicate::parse("value=OK").unwrap();
        assert!(p.satisfied(Some("OK")));
        assert!(!p.satisfied(Some("ok"))); // exact by default
        let p = WaitPredicate::parse("checked=on").unwrap();
        assert!(p.satisfied(Some("on")));
        assert!(WaitPredicate::parse("checked=maybe").is_err());
        assert!(WaitPredicate::parse("bogus=1").is_err());
        assert!(WaitPredicate::parse("noequalsign").is_err());
        assert!(WaitPredicate::parse("value=").is_err());
    }

    #[test]
    fn contains_semantics_apply_to_value_and_name_only() {
        let mut p = WaitPredicate::parse("value=56,877").unwrap();
        p.contains = true;
        assert!(p.satisfied(Some("显示为 56,877")));
        let mut p = WaitPredicate::parse("name=保存").unwrap();
        p.contains = true;
        assert!(p.satisfied(Some("另存为 - 保存")));
    }

    #[test]
    fn missing_actual_is_unsatisfied() {
        let p = WaitPredicate::parse("name=x").unwrap();
        assert!(!p.satisfied(None));
        let _ = CtlError::protocol(""); // silence unused import in tests
    }
}