mahbot 0.10.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! Plain Win32 window facts for the Windows backend: which top-level windows an application
//! owns, every target's frame in physical pixels, the virtual-desktop rect, process names, and the
//! two refusals actuation owes the caller (an elevated window, the secure desktop).
//!
//! Runs on the apartment thread, like every other platform call: a target is resolved to an
//! `HWND` here, used, and dropped — nothing stores a platform handle across jobs.
//!
//! A window's identity is its own OS handle plus the pid that owned it when enumerated
//! ([`window_key`]): a `TargetSpec::Window` either lands on that very window or fails with
//! [`core::ERR_SURFACE_GONE`] — never on another window of the application. `TargetSpec::App`
//! names an application and is resolved per call: its own active window, else its frontmost.

use super::super::core::{
    self, AppInfo, AppListing, SurfaceGeometry, TargetSpec, UnreadWindows, WindowInfo, WindowKey,
    WindowListing,
};
use std::sync::{Once, OnceLock};
use windows::Win32::Foundation::{
    CloseHandle, ERROR_INVALID_PARAMETER, HANDLE, HWND, LPARAM, POINT, RECT, STILL_ACTIVE,
    WIN32_ERROR,
};
use windows::Win32::Graphics::Dwm::{
    DWMWA_CLOAKED, DWMWA_EXTENDED_FRAME_BOUNDS, DwmGetWindowAttribute,
};
use windows::Win32::Security::{GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation};
use windows::Win32::System::StationsAndDesktops::{
    CloseDesktop, DESKTOP_CONTROL_FLAGS, DESKTOP_READOBJECTS, GetUserObjectInformationW,
    OpenInputDesktop, UOI_NAME,
};
use windows::Win32::System::Threading::{
    GetCurrentProcessId, GetExitCodeProcess, OpenProcess, OpenProcessToken, PROCESS_NAME_WIN32,
    PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
};
use windows::Win32::UI::HiDpi::{
    DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext,
};
use windows::Win32::UI::WindowsAndMessaging::{
    EnumWindows, GA_ROOT, GUITHREADINFO, GWL_EXSTYLE, GetAncestor, GetForegroundWindow,
    GetGUIThreadInfo, GetSystemMetrics, GetWindowLongW, GetWindowRect, GetWindowTextLengthW,
    GetWindowTextW, GetWindowThreadProcessId, IsIconic, IsWindow, IsWindowVisible,
    SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN,
    SetForegroundWindow, WS_EX_TOOLWINDOW, WindowFromPoint,
};
use windows::core::BOOL;

/// How long a foreground change is given to land, and how often it is re-checked.
const FOREGROUND_RETRIES: usize = 5;
const FOREGROUND_PAUSE: std::time::Duration = std::time::Duration::from_millis(20);

/// A resolved window target: everything the other modules need about one window.
pub(super) struct TargetWindow {
    pub hwnd: HWND,
    pub pid: u32,
    pub app_name: String,
    pub title: String,
    pub surface: SurfaceGeometry,
}

/// Ask for per-monitor-v2 DPI awareness once, eagerly, before any coordinate is computed.
pub(super) fn ensure_dpi_aware() {
    static ONCE: Once = Once::new();
    // SAFETY: no pointer or handle crosses this boundary, and the only failure (an
    // awareness already set by the GUI's event loop) is deliberately ignored.
    ONCE.call_once(|| unsafe {
        let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
    });
}

/// Whether an interactive desktop is attached at all: the channel question.
pub(super) fn interactive_desktop_available() -> bool {
    ensure_input_desktop().is_ok()
}

/// Resolve a target to its window. `Focused` follows the foreground window; `App` its active or
/// frontmost window.
pub(super) fn resolve(target: &TargetSpec) -> anyhow::Result<TargetWindow> {
    match target {
        TargetSpec::Screen => Err(core::screen_act_error()),
        TargetSpec::Focused => {
            // SAFETY: no arguments and no out-pointer; a null handle means no
            // foreground window and is refused below.
            let hwnd = unsafe { GetForegroundWindow() };
            if hwnd.0.is_null() {
                return Err(core::taxonomy_error(
                    core::ERR_DEGRADED,
                    "no foreground window — the session is locked, the UAC secure desktop is up, \
                     or no window has focus; ask the owner to return to their desktop",
                ));
            }
            describe(hwnd)
        }
        TargetSpec::App { app_pid, app_name } => {
            let windows = app_windows(*app_pid, app_name);
            let Some(hwnd) = app_window(&windows) else {
                return Err(absent_app(*app_pid, app_name));
            };
            describe(hwnd)
        }
        TargetSpec::Window { app_name, key, .. } => resolve_key(app_name, key),
    }
}

/// The refusal for an `a` id that names no window right now: the application quit or closed.
fn absent_app(app_pid: Option<u32>, app_name: &str) -> anyhow::Error {
    match app_pid.and_then(process_alive) {
        Some(true) => core::app_absent(app_name, core::AppAbsence::Windowless),
        Some(false) => core::app_absent(app_name, core::AppAbsence::Quit),
        None => core::app_absent(app_name, core::AppAbsence::Unreachable),
    }
}

/// Whether the process `pid` still exists: `Some(false)` only when the system says so.
pub(super) fn process_alive(pid: u32) -> Option<bool> {
    if pid == 0 {
        return Some(false);
    }
    let mut exit_code = 0u32;
    // SAFETY: no pointer crosses this call except the exit-code out-parameter, which
    // points at live local storage; the handle is closed before returning.
    unsafe {
        match OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) {
            Ok(process) => {
                let alive = GetExitCodeProcess(process, &raw mut exit_code).is_ok()
                    && exit_code == STILL_ACTIVE.0.cast_unsigned();
                let _ = CloseHandle(process);
                Some(alive)
            }
            Err(error) if WIN32_ERROR::from_error(&error) == Some(ERROR_INVALID_PARAMETER) => {
                Some(false)
            }
            Err(_) => None,
        }
    }
}

/// Resolve a stored window key to exactly the window it names, or refuse.
///
/// The key carries the window's own handle and the pid that owned it, so a moved, resized or
/// renamed window keeps resolving while a closed or replaced one does not. There is no fallback: a
/// title match or another window of the application would be a different surface.
fn resolve_key(app_name: &str, key: &WindowKey) -> anyhow::Result<TargetWindow> {
    let Some((pid, hwnd)) = parse_key(key) else {
        return Err(core::surface_gone(app_name));
    };
    let alive =
        // SAFETY: `hwnd` is a plain handle value from the key; the call only tests it.
        unsafe { IsWindow(Some(hwnd)) }.as_bool() && pid_of(hwnd) == pid;
    if !alive {
        return Err(core::surface_gone(app_name));
    }
    describe(hwnd)
}

/// The identity a [`WindowKey`] carries (`hwnd:<pid>:<handle>`), and the one place it is spelled.
/// Windows may recycle a handle after its window closes, so the pid is the guard.
fn window_key(hwnd: HWND, pid: u32) -> WindowKey {
    WindowKey::new(format!("hwnd:{pid}:{}", hwnd.0 as usize))
}

/// Split a [`WindowKey`] back into its owning pid and handle. `None` when the text is not one.
fn parse_key(key: &WindowKey) -> Option<(u32, HWND)> {
    let (pid, hwnd) = key.as_str().strip_prefix("hwnd:")?.split_once(':')?;
    let hwnd = hwnd.parse::<usize>().ok()?;
    Some((pid.parse().ok()?, HWND(hwnd as *mut std::ffi::c_void)))
}

/// Window geometry for a target: the window's own frame, or the virtual-desktop rect.
pub(super) fn surface_geometry(target: &TargetSpec) -> anyhow::Result<SurfaceGeometry> {
    match target {
        TargetSpec::Screen => screen_geometry(),
        other => Ok(resolve(other)?.surface),
    }
}

/// The virtual desktop across every display, origin at its min corner.
pub(super) fn screen_geometry() -> anyhow::Result<SurfaceGeometry> {
    // SAFETY: four index-only calls with no out-pointers; a non-positive metric is
    // refused below rather than trusted.
    unsafe {
        let (x, y) = (
            GetSystemMetrics(SM_XVIRTUALSCREEN),
            GetSystemMetrics(SM_YVIRTUALSCREEN),
        );
        let (width, height) = (
            GetSystemMetrics(SM_CXVIRTUALSCREEN),
            GetSystemMetrics(SM_CYVIRTUALSCREEN),
        );
        if width <= 0 || height <= 0 {
            return Err(core::taxonomy_error(
                core::ERR_DESKTOP_UNAVAILABLE,
                format!("{SECURE_DESKTOP_REASON} — there is no screen to describe"),
            ));
        }
        Ok(SurfaceGeometry {
            x: f64::from(x),
            y: f64::from(y),
            width: f64::from(width),
            height: f64::from(height),
        })
    }
}

/// The application of the foreground window, or `None` when no window has the foreground.
pub(super) fn foreground_app_name() -> Option<String> {
    let hwnd = foreground()?;
    Some(app_name(pid_of(hwnd), &title_of(hwnd)))
}

/// The window a point lies over, attributed to the process that owns it — what a coordinate click
/// is checked against when it is sent. `None` when no window is there (the desktop itself) or the
/// window found cannot be attributed to an application.
pub(super) fn window_at_point(x: i32, y: i32) -> Option<core::WindowAtPoint> {
    let hwnd = top_level_at(x, y)?;
    let pid = pid_of(hwnd);
    if pid == 0 {
        return None;
    }
    let title = title_of(hwnd);
    Some(core::WindowAtPoint {
        app_pid: Some(pid),
        app_name: app_name(pid, &title),
        title,
        // The frame is how the window the caller addressed is told apart from this one.
        frame: surface_of(hwnd).ok(),
    })
}

/// The window a screen coordinate lands on, for the elevated-window check.
pub(super) fn top_level_at(x: i32, y: i32) -> Option<HWND> {
    // SAFETY: the point is passed by value; a null handle means no window there.
    let hwnd = unsafe { WindowFromPoint(POINT { x, y }) };
    if hwnd.0.is_null() {
        return None;
    }
    // SAFETY: `hwnd` is an OS handle this frame does not own, checked non-null just
    // above; `GA_ROOT` only answers an ancestor, null when the window has none.
    let root = unsafe { GetAncestor(hwnd, GA_ROOT) };
    Some(if root.0.is_null() { hwnd } else { root })
}

/// The window that has focus: where a key chord and synthetic typing go.
pub(super) fn foreground() -> Option<HWND> {
    // SAFETY: no arguments and no out-pointer; a null handle is filtered out below.
    let hwnd = unsafe { GetForegroundWindow() };
    (!hwnd.0.is_null()).then_some(hwnd)
}

/// Refuse input aimed at a window that is not in front: typing, a drag or a wheel would land
/// elsewhere.
pub(super) fn ensure_foreground(hwnd: HWND) -> anyhow::Result<()> {
    // SAFETY: no arguments; the handle is only compared, never dereferenced.
    if unsafe { GetForegroundWindow() } == hwnd {
        return Ok(());
    }
    let title = title_of(hwnd);
    Err(core::not_brought_forward(core::window_description(
        &app_name(pid_of(hwnd), &title),
        &title,
    )))
}

/// Bring a window to the foreground before input aimed at it. Best-effort: Windows may refuse
/// foreground changes for a background process. Every pinned action then verifies with
/// [`ensure_foreground`]; a coordinate click raises and is checked against the window under its
/// point.
pub(super) fn activate(hwnd: HWND) {
    // SAFETY: no arguments; the handle is only compared, never dereferenced.
    if unsafe { GetForegroundWindow() } == hwnd {
        return;
    }
    // SAFETY: `hwnd` is a handle the caller resolved from the OS and does not own;
    // a refusal is a FALSE this ignores, and `ensure_foreground` is the real check.
    unsafe {
        let _ = SetForegroundWindow(hwnd);
    }
    // Windows applies some foreground changes asynchronously; give it a moment.
    for _ in 0..FOREGROUND_RETRIES {
        // SAFETY: as above — a no-argument query whose result is only compared.
        if unsafe { GetForegroundWindow() } == hwnd {
            return;
        }
        std::thread::sleep(FOREGROUND_PAUSE);
    }
}

/// The two platform refusals actuation owes the caller, checked before any input or
/// accessibility action: the secure desktop ([`ensure_input_desktop`]) and an elevated window.
/// `hwnd` is the window the input actually lands on — `None` is the desktop itself, which no
/// process owns and which cannot be elevated.
pub(super) fn ensure_actuation_allowed(hwnd: Option<HWND>) -> anyhow::Result<()> {
    ensure_input_desktop()?;
    let Some(hwnd) = hwnd else {
        return Ok(());
    };
    if hwnd.0.is_null() || own_process_is_elevated() {
        return Ok(());
    }
    let pid = pid_of(hwnd);
    if is_own_process(pid) || !process_is_elevated(pid) {
        return Ok(());
    }
    let title = title_of(hwnd);
    let app = process_name(pid).unwrap_or_else(|| format!("pid {pid}"));
    Err(core::permission_denied(format!(
        "{} belongs to {app} (pid {pid}), which runs elevated — this non-elevated process cannot \
         send it input or drive its accessibility elements (Windows blocks both); {}ask the owner \
         to run that application without elevation",
        core::window_description("", &title),
        if super::super::capture_known_available() {
            "a capture of the window may still work — "
        } else {
            ""
        }
    )))
}

/// Refuse an accessibility ACTION aimed at a window of mahbot itself. UI Automation answers a call
/// addressed to our own process in-process, and this backend has no path onto the interface thread
/// the dashboard owns, so an element action issued from the accessibility thread can freeze the
/// dashboard or abort the process — and a trap cannot be caught. Listing, reading and capturing our
/// own windows, and raw input reaching them, are unaffected.
pub(super) fn ensure_not_own_window(hwnd: HWND) -> anyhow::Result<()> {
    if !is_own_process(pid_of(hwnd)) {
        return Ok(());
    }
    let title = title_of(hwnd);
    Err(core::taxonomy_error(
        core::ERR_SELF_TARGET,
        format!(
            "{} belongs to mahbot itself: this process cannot drive its own accessibility elements \
             safely, because a same-process element action is answered in-process and there is no \
             way onto the interface thread — it could freeze the dashboard or kill the service, so \
             it is refused instead. Our windows stay listed, readable and capturable, and \
             coordinate input still reaches them",
            core::window_description("", &title)
        ),
    ))
}

/// Refuse while the secure desktop or the lock screen owns the input desktop.
fn ensure_input_desktop() -> anyhow::Result<()> {
    // The default desktop is not localized; when the secure desktop is up, it is the one to name.
    let desktop =
        // SAFETY: no out-pointer; the returned desktop handle is owned by this function
        // and closed below, and a failed open carries no handle at all.
        unsafe { OpenInputDesktop(DESKTOP_CONTROL_FLAGS::default(), false, DESKTOP_READOBJECTS) };
    let Ok(desktop) = desktop else {
        return Err(secure_desktop_error());
    };
    let mut name = [0u16; 64];
    // SAFETY: the object is the live desktop handle from above, which this call
    // only queries; `name` is a live `[u16; 64]` local whose own byte length is
    // passed as the cap, so the call writes at most those 64 UTF-16 units.
    let read = unsafe {
        GetUserObjectInformationW(
            windows::Win32::Foundation::HANDLE(desktop.0),
            UOI_NAME,
            Some(name.as_mut_ptr().cast()),
            (name.len() * 2) as u32,
            None,
        )
    };
    // SAFETY: `desktop` came from `OpenInputDesktop` above, was only queried since,
    // and is released here exactly once.
    unsafe {
        let _ = CloseDesktop(desktop);
    }
    if read.is_err() {
        return Err(secure_desktop_error());
    }
    let end = name.iter().position(|c| *c == 0).unwrap_or(name.len());
    if String::from_utf16_lossy(&name[..end]).eq_ignore_ascii_case("Default") {
        return Ok(());
    }
    Err(secure_desktop_error())
}

/// What a session without an interactive desktop is, named once: the core gate
/// ([`super::core::ERR_DESKTOP_UNAVAILABLE`]) and every Windows refusal spell it the same way.
pub(super) const SECURE_DESKTOP_REASON: &str = "the UAC secure desktop, the lock screen or a \
     non-interactive session owns the desktop";

fn secure_desktop_error() -> anyhow::Error {
    core::taxonomy_error(
        core::ERR_DESKTOP_UNAVAILABLE,
        format!(
            "{SECURE_DESKTOP_REASON} — nothing can be read or actuated there; ask the owner to return to their desktop"
        ),
    )
}

fn own_process_is_elevated() -> bool {
    static OWN: OnceLock<bool> = OnceLock::new();
    // SAFETY: the only unsafe call is the argument, `GetCurrentProcessId`, which has
    // no arguments and no failure mode.
    *OWN.get_or_init(|| unsafe { process_is_elevated(GetCurrentProcessId()) })
}

/// Whether a process's token is elevated. A failed query answers "no": the refusal then does not
/// fire.
fn process_is_elevated(pid: u32) -> bool {
    // SAFETY: every handle here is the OS's own return, checked or closed in this
    // function — `token` is only read after `OpenProcessToken` succeeded — and
    // `GetTokenInformation` fills a live `TOKEN_ELEVATION` whose byte count is
    // `size_of` of that same type.
    unsafe {
        let Ok(process) = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) else {
            return false;
        };
        let mut token = HANDLE::default();
        let opened = OpenProcessToken(process, TOKEN_QUERY, &raw mut token).is_ok();
        let _ = CloseHandle(process);
        if !opened {
            return false;
        }
        let mut elevation = TOKEN_ELEVATION::default();
        let mut size = 0u32;
        let read = GetTokenInformation(
            token,
            TokenElevation,
            Some(std::ptr::from_mut(&mut elevation).cast()),
            std::mem::size_of::<TOKEN_ELEVATION>() as u32,
            &raw mut size,
        )
        .is_ok();
        let _ = CloseHandle(token);
        read && elevation.TokenIsElevated != 0
    }
}

/// One enumerated top-level window.
struct Enumerated {
    hwnd: HWND,
    pid: u32,
    app_name: String,
    title: String,
    active: bool,
    /// The frame, or why it could not be read: a window without one is left out of the listing.
    surface: anyhow::Result<SurfaceGeometry>,
}

/// The running applications, with the one in front named. That is the foreground window's — the one
/// source both listings read, so they cannot disagree. A machine with no window in front names
/// none.
pub(super) fn list_apps() -> AppListing {
    AppListing {
        apps: apps_of(&top_level_windows()),
        frontmost: foreground_app_name(),
    }
}

/// Every running application that owns at least one listed top-level window, in a stable order.
fn apps_of(windows: &[Enumerated]) -> Vec<AppInfo> {
    let mut apps: Vec<AppInfo> = Vec::new();
    for win in windows {
        // Name as well as pid: one host process (a UWP frame host) serves several apps.
        if apps
            .iter()
            .any(|a| a.pid == Some(win.pid) && a.name.eq_ignore_ascii_case(&win.app_name))
        {
            continue;
        }
        apps.push(AppInfo {
            pid: Some(win.pid),
            name: win.app_name.clone(),
        });
    }
    apps
}

/// Top-level windows, optionally narrowed to one application's. A window whose frame
/// cannot be read has no coordinates to act on, so it is not listed — a zeroed
/// surface would silently map every normalized point to the origin — but the
/// application that lost one is: [`WindowListing::unread`] carries how many of its
/// windows could not be read and the first error.
/// One application's windows that a listing could not read, accumulated to be
/// reported as one note rather than one note per lost window.
struct LostFrames {
    app_name: String,
    count: usize,
    first_error: String,
}

pub(super) fn list_windows(app: Option<&AppInfo>) -> WindowListing {
    let windows = match app {
        Some(app) => app_windows(app.pid, &app.name),
        None => top_level_windows(),
    };
    let mut listing = WindowListing::default();
    let mut lost: Vec<LostFrames> = Vec::new();
    // The application in front is the foreground window's — the same source the
    // applications listing reads, so the two cannot disagree, and the filtered list need
    // not contain that window at all.
    listing.frontmost = foreground_app_name();
    // In an all-applications listing only the foreground window is marked: a background
    // application's focused window cannot be read there. A single-application listing asks that
    // application's own thread instead, so it marks its active window even when it is not in front
    // — the two sources are exclusive, so it never marks two, and it marks none rather than
    // guessing.
    let focused_of_app = if app.is_some() {
        marked_window_of(&windows)
    } else {
        None
    };
    for win in windows {
        let surface = match win.surface {
            Ok(surface) => surface,
            Err(error) => {
                match lost
                    .iter_mut()
                    .find(|entry| entry.app_name.eq_ignore_ascii_case(&win.app_name))
                {
                    Some(entry) => entry.count += 1,
                    None => lost.push(LostFrames {
                        app_name: win.app_name.clone(),
                        count: 1,
                        first_error: format!("{error:#}"),
                    }),
                }
                continue;
            }
        };
        // The enumeration is front to back, so the place among the windows is the rank.
        let rank = Some(listing.windows.len() + 1);
        listing.windows.push(WindowInfo {
            app_pid: Some(win.pid),
            app_name: win.app_name,
            title: win.title,
            key: window_key(win.hwnd, win.pid),
            surface,
            focused: match focused_of_app {
                Some(focused) => focused == win.hwnd,
                None => win.active,
            },
            rank,
        });
    }
    listing.order = core::WindowOrder::All;
    listing.unread = lost
        .into_iter()
        .map(|entry| UnreadWindows {
            app_name: entry.app_name,
            reason: format!(
                "{} {} no readable frame (first error: {})",
                entry.count,
                if entry.count == 1 {
                    "window has"
                } else {
                    "windows have"
                },
                entry.first_error
            ),
        })
        .collect();
    listing
}

/// The concrete window a target names right now, as the rest of the backend reports it.
pub(super) fn window_info(target: &TargetSpec) -> anyhow::Result<WindowInfo> {
    let resolved = resolve(target)?;
    Ok(WindowInfo {
        app_pid: Some(resolved.pid),
        app_name: resolved.app_name,
        title: resolved.title,
        key: window_key(resolved.hwnd, resolved.pid),
        surface: resolved.surface,
        focused: false,
        rank: None,
    })
}

/// The window a single-application listing marks `[focused]`: the application's own active
/// window (asked of its thread, which reads it even when the application is not in front), else
/// the one of its windows that is the foreground window. `None` when neither names a listed
/// window, so the application is listed without a mark rather than marked by a guess.
fn marked_window_of(windows: &[Enumerated]) -> Option<HWND> {
    let first = windows.first()?;
    active_window_of_application(first.hwnd)
        // An untitled or tool window is filtered out of the enumeration, and a mark on a filtered
        // window is dropped with it.
        .filter(|hwnd| windows.iter().any(|win| win.hwnd == *hwnd))
        .or_else(|| windows.iter().find(|win| win.active).map(|win| win.hwnd))
}

/// The window an `a` id names: what [`TargetSpec::App`] resolves to — the window the listing
/// marks whenever a mark could be placed ([`marked_window_of`]), else the application's frontmost
/// listed window. `None` only when it has no listed window at all.
fn app_window(windows: &[Enumerated]) -> Option<HWND> {
    marked_window_of(windows).or_else(|| windows.first().map(|win| win.hwnd))
}

/// The window an application holds as active in its own input queue: the one way to name a
/// background application's focused window, since the foreground window belongs to whichever
/// application is in front.
///
/// `None` when the thread does not answer — it exited, or its window is on another desktop —
/// which the listing states as a mark it cannot place rather than guessing.
fn active_window_of_application(hwnd: HWND) -> Option<HWND> {
    // SAFETY: no out-pointer beyond the structure below, which the call fills; the thread
    // id belongs to the window's own process and the call only reads its state.
    let thread = unsafe { GetWindowThreadProcessId(hwnd, None) };
    if thread == 0 {
        return None;
    }
    let mut info = GUITHREADINFO {
        cbSize: std::mem::size_of::<GUITHREADINFO>() as u32,
        ..Default::default()
    };
    // SAFETY: `info` is a live structure of the size its `cbSize` states, which is the
    // shape this call writes.
    unsafe { GetGUIThreadInfo(thread, &raw mut info) }.ok()?;
    (!info.hwndActive.0.is_null()).then_some(info.hwndActive)
}

/// One application's top-level windows (by pid when known, else by name), front to back.
fn app_windows(pid: Option<u32>, app_name: &str) -> Vec<Enumerated> {
    top_level_windows()
        .into_iter()
        .filter(|win| match pid {
            Some(pid) => {
                win.pid == pid
                    && (app_name.is_empty() || win.app_name.eq_ignore_ascii_case(app_name))
            }
            None => win.app_name.eq_ignore_ascii_case(app_name),
        })
        .collect()
}

/// All top-level application windows, front to back, plus the foreground window when the filter
/// would hide it. Visible and titled, which tells an application window from the helper windows
/// every toolkit leaves around. Owned windows are kept (a modal dialog is exactly the surface an
/// agent needs); cloaked windows — another virtual desktop, a suspended UWP app — are dropped, they
/// have no pixels.
fn top_level_windows() -> Vec<Enumerated> {
    let mut handles: Vec<HWND> = Vec::new();
    // SAFETY: `handles` is a live local that outlives this synchronous enumeration,
    // and `collect_window` receives its address through the `LPARAM`; nothing else
    // touches the vector until `EnumWindows` returns.
    unsafe {
        let _ = EnumWindows(
            Some(collect_window),
            LPARAM(std::ptr::from_mut(&mut handles).cast::<std::ffi::c_void>() as isize),
        );
    }
    // SAFETY: no arguments and no out-pointer.
    let foreground = unsafe { GetForegroundWindow() };
    let mut windows: Vec<Enumerated> = handles
        .into_iter()
        .filter(|hwnd| is_application_window(*hwnd))
        .map(|hwnd| enumerate(hwnd, foreground))
        .collect();
    // The foreground window joins the list even when the filter above hides it.
    if foreground_joins_listing(&windows, foreground) {
        windows.insert(0, enumerate(foreground, foreground));
    }
    windows
}

// Whether the foreground window is a surface the filter hid but the listing keeps.
fn foreground_joins_listing(windows: &[Enumerated], foreground: HWND) -> bool {
    if foreground.0.is_null() || windows.iter().any(|win| win.hwnd == foreground) {
        return false;
    }
    // SAFETY: `foreground` is an OS handle and visibility is a query with no pointer.
    unsafe { IsWindowVisible(foreground) }.as_bool() && !is_cloaked(foreground)
}

/// One window's enumerated facts.
fn enumerate(hwnd: HWND, foreground: HWND) -> Enumerated {
    let pid = pid_of(hwnd);
    let title = title_of(hwnd);
    Enumerated {
        hwnd,
        pid,
        app_name: app_name(pid, &title),
        title,
        active: hwnd == foreground,
        surface: surface_of(hwnd),
    }
}

/// An application's display name. UWP and WinUI apps are hosted by `ApplicationFrameHost.exe`,
/// one process for several apps, so the window's own title is the app there — the exe stem would
/// merge them into one. Consequence: a frame-hosted app whose title changes after enumeration
/// makes its stored `a` target stale (a `w` target keeps the handle); re-enumerating is the fix.
fn app_name(pid: u32, title: &str) -> String {
    match process_name(pid) {
        Some(stem) if stem.eq_ignore_ascii_case("ApplicationFrameHost") && !title.is_empty() => {
            title.to_string()
        }
        Some(stem) => stem,
        None => format!("pid {pid}"),
    }
}

// SAFETY: only ever installed as `EnumWindows`' callback, whose `lparam` this
// module sets to the address of its own `Vec<HWND>`; `hwnd` is an OS handle this
// frame does not own.
unsafe extern "system" fn collect_window(hwnd: HWND, lparam: LPARAM) -> BOOL {
    // Always continue: a `FALSE` here would make `EnumWindows` report an error.
    // SAFETY: `lparam` is that `&mut Vec<HWND>` from `top_level_windows`, still live and
    // exclusively reachable here, so it is aligned and pushable.
    let handles = unsafe { &mut *(lparam.0 as *mut Vec<HWND>) };
    handles.push(hwnd);
    BOOL(1)
}

fn is_application_window(hwnd: HWND) -> bool {
    // SAFETY: no out-pointers in the group; `hwnd` is a handle enumeration just
    // reported, and a window closed since then merely fails these queries.
    unsafe {
        if !IsWindowVisible(hwnd).as_bool() || GetWindowTextLengthW(hwnd) == 0 {
            return false;
        }
        // Tool windows are palettes and floating bars; they are still reachable, so they are kept.
        let ex_style = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32;
        if ex_style & WS_EX_TOOLWINDOW.0 != 0 {
            return false;
        }
        !is_cloaked(hwnd)
    }
}

fn is_cloaked(hwnd: HWND) -> bool {
    let mut cloaked = 0u32;
    // SAFETY: `cloaked` is a live `u32` local and the byte count is `size_of` of
    // that same type, which is what `DWMWA_CLOAKED` writes.
    let queried = unsafe {
        DwmGetWindowAttribute(
            hwnd,
            DWMWA_CLOAKED,
            std::ptr::from_mut(&mut cloaked).cast(),
            std::mem::size_of::<u32>() as u32,
        )
    };
    queried.is_ok() && cloaked != 0
}

/// A window's surface in physical pixels: the visible frame without the invisible resize border
/// (`DWMWA_EXTENDED_FRAME_BOUNDS`), falling back to `GetWindowRect`.
fn surface_of(hwnd: HWND) -> anyhow::Result<SurfaceGeometry> {
    let mut rect = RECT::default();
    // SAFETY: `rect` is a live `RECT` local and the byte count is `size_of` of that
    // same type, the shape `DWMWA_EXTENDED_FRAME_BOUNDS` writes.
    let frame = unsafe {
        DwmGetWindowAttribute(
            hwnd,
            DWMWA_EXTENDED_FRAME_BOUNDS,
            std::ptr::from_mut(&mut rect).cast(),
            std::mem::size_of::<RECT>() as u32,
        )
    };
    if frame.is_err() {
        return window_rect(hwnd);
    }
    Ok(geometry(rect))
}

/// The window rect, invisible resize border included — the other size a capture may report.
pub(super) fn window_rect(hwnd: HWND) -> anyhow::Result<SurfaceGeometry> {
    let mut rect = RECT::default();
    // SAFETY: `rect` is a live local of exactly the type the call fills.
    unsafe { GetWindowRect(hwnd, &raw mut rect) }.map_err(|e| {
        core::taxonomy_error(
            core::ERR_NOT_MATCHED,
            format!("window is gone or has no frame ({e}) — re-enumerate windows"),
        )
    })?;
    Ok(geometry(rect))
}

fn geometry(rect: RECT) -> SurfaceGeometry {
    SurfaceGeometry {
        x: f64::from(rect.left),
        y: f64::from(rect.top),
        width: f64::from(rect.right - rect.left),
        height: f64::from(rect.bottom - rect.top),
    }
}

/// Everything the caller needs about one window, refusing a minimized one: its frame sits
/// off-screen and its capture is black, so every action on it would be a lie.
fn describe(hwnd: HWND) -> anyhow::Result<TargetWindow> {
    let pid = pid_of(hwnd);
    let title = title_of(hwnd);
    // A handle that vanished since resolution answers FALSE, which reads as "not minimized".
    // SAFETY: one handle argument and no out-pointer.
    if unsafe { IsIconic(hwnd) }.as_bool() {
        return Err(core::minimized_window(&title));
    }
    Ok(TargetWindow {
        hwnd,
        pid,
        app_name: app_name(pid, &title),
        title,
        surface: surface_of(hwnd)?,
    })
}

fn pid_of(hwnd: HWND) -> u32 {
    let mut pid = 0u32;
    // SAFETY: `pid` is a live `u32` local the call fills in place; a window that
    // vanished simply leaves the zero it started with.
    unsafe {
        GetWindowThreadProcessId(hwnd, Some(&raw mut pid));
    }
    pid
}

/// Whether `pid` is this very process. A window that vanished before the query answers "no".
fn is_own_process(pid: u32) -> bool {
    // SAFETY: `GetCurrentProcessId` takes no arguments and has no failure mode.
    pid != 0 && pid == unsafe { GetCurrentProcessId() }
}

/// A window's title as a label: kept to the product's cap, the ellipsis marking the cut.
fn title_of(hwnd: HWND) -> String {
    core::cap_label(&title_text(hwnd))
}

/// A window's title as read — bounded by a product-sized buffer, never by what the window
/// reports, so a document-length title is not materialised. `observe` keeps it through
/// [`core::Truncation::keep_name`], which counts a cut title in the observation header.
pub(super) fn title_text(hwnd: HWND) -> String {
    // SAFETY: one handle argument, no out-pointer.
    let length = unsafe { GetWindowTextLengthW(hwnd) };
    if length <= 0 {
        return String::new();
    }
    // The reported length decides how much is ASKED FOR, never how much is allocated.
    let wanted = core::MAX_NAME_CHARS * 2 + 2;
    let mut buffer = vec![0u16; (length as usize).min(wanted) + 1];
    // SAFETY: `buffer` is alive here and the binding passes its own length as the cap,
    // so the call cannot write past it.
    let written = unsafe { GetWindowTextW(hwnd, &mut buffer) };
    String::from_utf16_lossy(&buffer[..written.max(0) as usize])
}

/// An application's display name: its executable's file stem ("notepad"), which is what
/// `windows { app: … }` matches and what the target lines show.
fn process_name(pid: u32) -> Option<String> {
    if pid == 0 {
        return None;
    }
    let mut path = vec![0u16; 1024];
    let mut length = u32::try_from(path.len()).ok()?;
    // SAFETY: `process` is the checked handle from `.ok()?` and is closed before the
    // block ends; `path` is a live 1024-unit buffer whose own length is passed as
    // the cap, and `length` is a local in/out count the call keeps within it.
    unsafe {
        let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?;
        let queried = QueryFullProcessImageNameW(
            process,
            PROCESS_NAME_WIN32,
            windows::core::PWSTR(path.as_mut_ptr()),
            &raw mut length,
        );
        let _ = CloseHandle(process);
        queried.ok()?;
    }
    let full = String::from_utf16_lossy(&path[..length as usize]);
    let name = std::path::Path::new(&full)
        .file_stem()
        .map(|stem| stem.to_string_lossy().into_owned())?;
    if name.is_empty() { None } else { Some(name) }
}