Skip to main content

agentmux_launcher/wrr/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Phase B.9.1 — Window Reality Reconciliation (WRR) reducer arm.
5//
6// Catches the class of bug surfaced during the B.6.1 smoke test:
7// a CEF browser opens, gets a Win32 HWND, and is then "lost" to
8// the user (off-screen, behind another window, never foregrounded).
9// The pre-B.9 reducer tracked identity (`label`, `kind`, `parent`)
10// but not observability (visible? on-monitor? has the user seen
11// it?), so its drift detector compared `host.browsers.len() ==
12// launcher.windows.len()` — both can be in lockstep wrong about
13// Win32 reality.
14//
15// Design lives at `docs/retro/wrr-design-2026-04-28.md`. This
16// module implements the launcher-side reducer arm:
17//
18//   * `apply_*` functions: one per `Command::ReportHwnd*` /
19//     `ReportMonitorTopologyChanged`. Each mutates `State` and
20//     emits `Event::HwndDriftDetected` for every classification
21//     it can determine at this transition.
22//   * `severity_for(kind)`: the per-kind severity floor classifier.
23//
24// No I/O here: these run under the launcher's state lock. Arms that
25// want a log line push it onto the `diagnostics` sink they're given;
26// `ipc/server.rs` writes those lines after the lock is released.
27//
28// Pure event-driven. There is no clock task, no heartbeat — drift
29// is emitted at the moment the OS-driven Command is dispatched
30// through the reducer. See the design doc for the trade-off ("we
31// don't catch steady-state staleness without an event").
32
33use agentmux_common::ipc::{Event, HwndDriftKind, Rect, Severity};
34
35use crate::state::{PendingHwnd, State};
36
37pub mod rect;
38
39/// Internal — the four branches of `apply_hwnd_opened` against a
40/// known `label_hint`. Lifted into its own enum so the function
41/// can drop the `&mut WindowMirror` borrow before calling
42/// `state.bump_version()` on the drift-emitting path (rustc E0499).
43enum HwndOpenedOutcome {
44    /// Existing mirror was waiting for an HWND; linked successfully.
45    Linked,
46    /// Existing mirror was already linked to a DIFFERENT HWND. The
47    /// explicit `on_after_created` path is authoritative — REPAIR by
48    /// overwriting the stale link, and emit `HwndWithoutBrowser`
49    /// drift to surface the prior incorrect link for diagnostics.
50    /// Carry the prior HWND for the drift message.
51    /// (PR #664: replaces the no-repair behavior that caused the
52    /// `panel grows but no window appears` user symptom under
53    /// burst creates.)
54    Repaired(u64),
55    /// No mirror exists for that label — fall through to pending
56    /// stash (caller responsibility).
57    NoMatchingLabel,
58}
59
60/// Phase B.9.1 — handle `Command::ReportHwndOpened`. Either:
61///   1. The hwnd's `label_hint` matches an existing
62///      `state.windows[label]` whose `hwnd` is `None` → link them.
63///   2. No matching label → stash in `state.pending_hwnds` for a
64///      later reconciliation. If the class name doesn't look like
65///      an AgentMux window (filtered at the host hook, but
66///      defense-in-depth here too), don't even stash.
67pub fn apply_hwnd_opened(
68    state: &mut State,
69    hwnd: u64,
70    class_name: String,
71    title: String,
72    label_hint: Option<String>,
73    now_ms: u64,
74    diagnostics: &mut Vec<String>,
75) -> Vec<Event> {
76    // Case 1: label_hint maps to an existing WindowMirror that's
77    // waiting for an HWND. Happy path — link them, no drift.
78    if let Some(label) = label_hint.as_deref() {
79        // Read mirror state via a scoped borrow so we can release
80        // it before calling `state.bump_version()` (which needs &mut
81        // self on State). Result tells us which branch to take
82        // outside the borrow.
83        //
84        // `drain_pending` is set when the link succeeds so we can
85        // remove a matching stale `pending_hwnds` entry AFTER
86        // releasing the mirror borrow. The dual-source design
87        // (WinEvent CREATE + on_after_created) can leave a stale
88        // pending entry; without draining it,
89        // `apply_hwnd_destroyed` would early-return on the
90        // stale entry and skip the orphan-destroy chain.
91        // (reagent #600 P1.)
92        // PR #664 codex P1 round 5 — STEAL HWND from any other mirror
93        // that currently claims it. The drain-on-WindowOpened may have
94        // wrong-linked the same HWND to a different label earlier; if
95        // we don't clear that other mirror's link, we end up with TWO
96        // mirrors pointing to the same HWND. `apply_hwnd_destroyed`
97        // uses `iter().find(...)` which returns the FIRST match — the
98        // other mirror would persist as a ghost row forever.
99        //
100        // Scan FIRST (immutable borrow), then mutate via `get_mut(label)`.
101        let stolen_from: Option<String> = state
102            .windows
103            .iter()
104            .find(|(other_label, m)| {
105                other_label.as_str() != label && m.hwnd == Some(hwnd)
106            })
107            .map(|(other_label, _)| other_label.clone());
108
109        let mut drain_pending = false;
110        let outcome: HwndOpenedOutcome = match state.windows.get_mut(label) {
111            Some(mirror) if mirror.hwnd.is_none() => {
112                mirror.hwnd = Some(hwnd);
113                drain_pending = true;
114                HwndOpenedOutcome::Linked
115            }
116            Some(mirror) if mirror.hwnd == Some(hwnd) => {
117                // Same HWND already linked. This is a benign
118                // duplicate from the dual-source design: WinEvent
119                // CREATE hook reports first (label_hint=None,
120                // pending), then `on_after_created` reports
121                // explicitly (label_hint=Some, this path). Or
122                // vice versa under timing variation. No-op,
123                // no drift. (codex #600 P2.)
124                //
125                // Drain any matching stale pending entry. Without
126                // this, `apply_hwnd_destroyed` would early-return
127                // on the stale pending entry instead of running
128                // the orphan-destroy chain. (reagent #600 P1.)
129                drain_pending = true;
130                HwndOpenedOutcome::Linked
131            }
132            Some(mirror) => {
133                // PR #664 — REPAIR instead of just emitting drift.
134                // The explicit `on_after_created` path is the
135                // AUTHORITATIVE source for label↔HWND linking. The
136                // launcher's drain-on-WindowOpened (in
137                // `handle_report_window_opened`) provides best-effort
138                // linking but can wrong-pick under burst creates;
139                // when the explicit path arrives later it REPAIRS
140                // any stale link by overwriting.
141                //
142                // The `prior` HWND that was wrongly linked here will
143                // be re-attributed when ITS OWN on_after_created
144                // fires (same flow, recursive REPAIR if needed).
145                //
146                // We still emit `HwndWithoutBrowser` drift so the
147                // existence of a stale link is visible in the log
148                // for diagnostic purposes. Without the drift event,
149                // the silent repair would mask real bugs.
150                let prior = mirror.hwnd.unwrap_or(0);
151                mirror.hwnd = Some(hwnd);
152                drain_pending = true;
153                HwndOpenedOutcome::Repaired(prior)
154            }
155            None => HwndOpenedOutcome::NoMatchingLabel,
156        };
157        // Apply the steal AFTER the get_mut borrow is released.
158        // (codex P1 round 5) Maintains the 1:1 HWND↔label invariant
159        // that `apply_hwnd_destroyed`'s find()-by-hwnd relies on.
160        // Steal is meaningful only when we actually claimed the HWND
161        // (Linked or Repaired); NoMatchingLabel falls through to
162        // pending stash without claiming.
163        let stole = matches!(outcome, HwndOpenedOutcome::Linked | HwndOpenedOutcome::Repaired(_))
164            && stolen_from.is_some();
165        if stole {
166            if let Some(other_label) = stolen_from.as_deref() {
167                if let Some(other) = state.windows.get_mut(other_label) {
168                    other.hwnd = None;
169                }
170            }
171        }
172        if drain_pending {
173            state.pending_hwnds.remove(&hwnd);
174        }
175        match outcome {
176            HwndOpenedOutcome::Linked if !stole => return vec![],
177            HwndOpenedOutcome::Linked => {
178                // Linked + stole: we cleanly linked our mirror, but
179                // had to take the HWND from another label that was
180                // wrongly holding it (drain wrong-pick that wasn't
181                // yet repaired). Emit drift so the steal is visible.
182                let v = state.bump_version();
183                let other = stolen_from.as_deref().unwrap_or("?");
184                return vec![Event::HwndDriftDetected {
185                    kind: HwndDriftKind::HwndWithoutBrowser,
186                    label: Some(label.to_string()),
187                    hwnd: Some(hwnd),
188                    detail: format!(
189                        "ReportHwndOpened label_hint={} linked hwnd={} (stole from label={})",
190                        label, hwnd, other
191                    ),
192                    severity: severity_for(HwndDriftKind::HwndWithoutBrowser),
193                    version: v,
194                }];
195            }
196            HwndOpenedOutcome::Repaired(existing) => {
197                // Repair is a normal self-healing path: the launcher's
198                // best-effort drain in `handle_report_window_opened`
199                // wrong-picked an HWND under burst-create concurrency,
200                // and the explicit `apply_hwnd_opened` from
201                // `client.rs::on_after_created` is now correcting it.
202                // Logging this at Error severity as a `HwndDriftDetected`
203                // event flooded the renderer with one drift per fresh
204                // top-level (6 in a clean v0.33.696 session) and made
205                // genuine drifts harder to spot.
206                //
207                // Now: a diagnostic line only, no event. The pure-state
208                // mutation (mirror.hwnd overwrite + drain_pending +
209                // optional steal-clear on the prior holder) still
210                // happens above. Linked + stole still emits drift —
211                // that's a different shape (clean link that had to
212                // claim a wrongly-held HWND, which the prior holder's
213                // own `apply_hwnd_opened` may not yet have repaired).
214                let stolen_suffix = stolen_from
215                    .as_deref()
216                    .map(|s| format!(" (stole from label={})", s))
217                    .unwrap_or_default();
218                diagnostics.push(format!(
219                    "[wrr] hwnd_repaired label={} prior_hwnd={} new_hwnd={}{}",
220                    label, existing, hwnd, stolen_suffix
221                ));
222                return vec![];
223            }
224            HwndOpenedOutcome::NoMatchingLabel => { /* fall through to pending */ }
225        }
226    }
227
228    // Case 2: stash as pending. Filtered class names get dropped
229    // here too as belt-and-suspenders — host hook is the primary
230    // filter (see `wrr/classify.rs::is_app_class` in agentmux-cef).
231    state.pending_hwnds.insert(
232        hwnd,
233        PendingHwnd {
234            class_name,
235            title,
236            label_hint,
237            arrived_at_ms: now_ms,
238        },
239    );
240    vec![]
241}
242
243/// Phase B.9.1 — handle `Command::ReportHwndDestroyed`. Three
244/// outcomes:
245///   1. HWND links to a `WindowMirror` AND we already received a
246///      `ReportWindowClosed` for that label (mirror is gone) →
247///      no drift, expected ordering.
248///   2. HWND links to a `WindowMirror` that's STILL in
249///      `state.windows` → CEF didn't report close yet. Renderer
250///      probably crashed → `OrphanDestroy` drift.
251///   3. HWND was pending (never linked) → drop the pending entry,
252///      no drift (it never claimed to be a real window).
253pub fn apply_hwnd_destroyed(state: &mut State, hwnd: u64, host_running: bool) -> Vec<Event> {
254    // Drain any pending entry first. Don't early-return: the
255    // dual-source design (WinEvent CREATE + explicit
256    // on_after_created link) can leave a stale pending entry
257    // co-existing with a linked mirror — we still need to run
258    // the mirror check below to fire the orphan-destroy chain
259    // on a renderer crash. (reagent #600 P1.)
260    let _ = state.pending_hwnds.remove(&hwnd);
261
262    // Find the label whose mirror is linked to this HWND, if any.
263    let orphan_label: Option<String> = state
264        .windows
265        .iter()
266        .find(|(_, m)| m.hwnd == Some(hwnd))
267        .map(|(label, _)| label.clone());
268
269    if let Some(label) = orphan_label {
270        // Case 2: orphan destroy. Clear the link AND the mirror
271        // entry — the window is gone from Win32, regardless of
272        // what CEF thinks. Future `ReportWindowClosed` for the
273        // label will be a no-op (closed-on-missing is silently
274        // tolerated upstream).
275        //
276        // Emit the SAME shutdown events the normal close path
277        // (`handle_report_window_closed`) would emit:
278        // `WindowClosed` (so subscribers prune mirrors / atoms)
279        // and `WindowInstanceReleased` (so the InstancePanel
280        // count drops). Without these the frontend would show a
281        // stale window after a renderer crash. Order: drift first
282        // (so logs lead with "this is bad"), then the shutdown
283        // events. (reagent #600 P1.)
284        let _ = state.windows.remove(&label);
285        let released_num = state.instance_registry.remove(&label);
286        let _ = state.backend_window_ids.remove(&label);
287        let v_drift = state.bump_version();
288        let drift = Event::HwndDriftDetected {
289            kind: HwndDriftKind::OrphanDestroy,
290            label: Some(label.clone()),
291            hwnd: Some(hwnd),
292            detail: format!(
293                "HWND destroyed without preceding ReportWindowClosed for label={}",
294                label
295            ),
296            severity: severity_for(HwndDriftKind::OrphanDestroy),
297            version: v_drift,
298        };
299        let v_closed = state.bump_version();
300        let closed = Event::WindowClosed {
301            label: label.clone(),
302            version: v_closed,
303            // crash-detected close: host's on_before_close didn't
304            // run, so the F.6 cleanup saga must skip this trigger
305            // (it would never receive the panes-reaped / pool-drain
306            // terminal reports).
307            crash_detected: true,
308        };
309        let mut out = vec![drift, closed];
310        if let Some(num) = released_num {
311            let v_released = state.bump_version();
312            out.push(Event::WindowInstanceReleased {
313                label,
314                num,
315                version: v_released,
316            });
317        }
318
319        // Mirror the OrphanInstance + HostShouldQuit pair the normal
320        // close path emits at `reducer/window.rs::handle_report_window_closed`.
321        // Without this, a crash-detected last-window close empties
322        // `state.windows` but never wakes the host's orphan reconciler
323        // (which only listens to `HostShouldQuit`), so the warm pool
324        // browsers stay alive and the host doesn't quit. Caller passes
325        // `host_running` so wrr stays out of the connection module's
326        // private API.
327        //
328        // Workstream 0 Phase 1 — same background-service exclusion as the
329        // normal close path (see its comment): don't arm the orphan/
330        // teardown-backstop machinery for an intentionally-resting host.
331        if state.windows.is_empty() && !state.background_service_enabled && host_running {
332            let v_drift = state.bump_version();
333            out.push(Event::HwndDriftDetected {
334                kind: HwndDriftKind::OrphanInstance,
335                label: None,
336                hwnd: None,
337                detail:
338                    "Last user-visible window destroyed (crash-detected); host still alive (likely holding warm pool)"
339                        .to_string(),
340                severity: Severity::Warn,
341                version: v_drift,
342            });
343            let v_quit = state.bump_version();
344            out.push(Event::HostShouldQuit { version: v_quit });
345        }
346
347        return out;
348    }
349
350    // Case 1 (or: HWND was already removed from a mirror by a
351    // prior `WindowClosed`, then this destroy is the natural
352    // follow-up). No drift.
353    vec![]
354}
355
356/// Placement grace window. CEF creates top-level windows hidden,
357/// runs `SetWindowPos` to place them, then shows them. The
358/// intermediate `WM_HIDE` events arrive before `WM_FOREGROUND`,
359/// which would otherwise look like `HiddenSinceOpen` drift on
360/// every fresh window. Hides occurring within this window of the
361/// host's `ReportWindowOpened` are part of normal placement and
362/// don't count.
363const HIDDEN_SINCE_OPEN_GRACE_MS: u64 = 500;
364
365/// Phase B.9.1 — handle `Command::ReportHwndVisibilityChanged`.
366/// Drift fires only on `visible=false` for a known label that has
367/// not been foregrounded since open AND is past the post-open
368/// placement grace window.
369pub fn apply_hwnd_visibility_changed(
370    state: &mut State,
371    hwnd: u64,
372    visible: bool,
373    now_ms: u64,
374) -> Vec<Event> {
375    let mut drift: Option<Event> = None;
376    let mut version_to_bump = false;
377    let label_for_drift: Option<String> = state
378        .windows
379        .iter_mut()
380        .find(|(_, m)| m.hwnd == Some(hwnd))
381        .and_then(|(label, mirror)| {
382            mirror.visible = visible;
383            // Visibility=true at any time clears any deferred hide
384            // — the placement transition completed, no drift needed.
385            if visible {
386                mirror.hidden_since_open_deferred = false;
387                return None;
388            }
389            // Drift-storm cap: HiddenSinceOpen fires AT MOST ONCE per
390            // window per session. The cap flag is monotonic for the
391            // window's lifetime. The placement grace check below is
392            // additive: hides during placement set `hidden_since_open_deferred`
393            // (without arming the cap) so the next reducer call past
394            // the grace via `drain_deferred_hidden_since_open` can
395            // fire the drift. Hides past the grace fire immediately.
396            let past_grace =
397                now_ms.saturating_sub(mirror.opened_at_ms) > HIDDEN_SINCE_OPEN_GRACE_MS;
398            if past_grace
399                && !mirror.foregrounded_since_open
400                && !mirror.hidden_since_open_emitted
401            {
402                mirror.hidden_since_open_emitted = true;
403                mirror.hidden_since_open_deferred = false;
404                version_to_bump = true;
405                Some(label.clone())
406            } else if !past_grace
407                && !mirror.foregrounded_since_open
408                && !mirror.hidden_since_open_emitted
409            {
410                // Suppressed during placement grace. Mark as deferred
411                // so a later reducer call past the grace window can
412                // promote this to a drift if the window is still
413                // hidden (codex P2 PR #725 round 1 — without this,
414                // a stuck-hidden window that gets no further
415                // visibility events permanently loses the signal).
416                mirror.hidden_since_open_deferred = true;
417                None
418            } else {
419                None
420            }
421        });
422    if version_to_bump {
423        let v = state.bump_version();
424        drift = Some(Event::HwndDriftDetected {
425            kind: HwndDriftKind::HiddenSinceOpen,
426            label: label_for_drift,
427            hwnd: Some(hwnd),
428            detail: "Window hidden without ever being foregrounded since open".to_string(),
429            severity: severity_for(HwndDriftKind::HiddenSinceOpen),
430            version: v,
431        });
432    }
433    drift.into_iter().collect()
434}
435
436/// Sweep `hidden_since_open_deferred` mirrors and emit drift for any
437/// that have crossed the placement grace boundary while still hidden
438/// and never foregrounded. Called from `reducer::update` AFTER every
439/// command processes so any recovery event the command itself
440/// dispatched (visible=true / foreground change / window closed) has
441/// a chance to clear the deferred state first. Without the AFTER
442/// ordering, a slow placement whose first post-grace event is the
443/// recovery itself would fire a spurious drift before the recovery
444/// runs (codex P2 PR #725 round 2).
445///
446/// Even with the AFTER ordering, this pass is the heartbeat that
447/// catches stuck-hidden windows whose own `ReportHwndVisibilityChanged`
448/// was suppressed during grace: any subsequent unrelated command
449/// past the grace promotes the deferred state to a fired drift.
450///
451/// (codex P2 PR #725 round 1 — addresses the "no recheck after grace"
452/// concern. Stuck-hidden windows that produce ZERO further commands
453/// are still a hole — we'd need a periodic timer for that — but
454/// realistic launcher traffic generates events constantly, so this
455/// catches the practical cases.)
456pub fn drain_deferred_hidden_since_open(state: &mut State, now_ms: u64) -> Vec<Event> {
457    let stuck: Vec<(String, Option<u64>)> = state
458        .windows
459        .iter()
460        .filter(|(_, m)| m.hidden_since_open_deferred)
461        .filter(|(_, m)| !m.visible)
462        .filter(|(_, m)| !m.foregrounded_since_open)
463        .filter(|(_, m)| !m.hidden_since_open_emitted)
464        .filter(|(_, m)| now_ms.saturating_sub(m.opened_at_ms) > HIDDEN_SINCE_OPEN_GRACE_MS)
465        .map(|(label, m)| (label.clone(), m.hwnd))
466        .collect();
467    let mut events = Vec::with_capacity(stuck.len());
468    for (label, hwnd) in stuck {
469        if let Some(mirror) = state.windows.get_mut(&label) {
470            mirror.hidden_since_open_emitted = true;
471            mirror.hidden_since_open_deferred = false;
472        }
473        let v = state.bump_version();
474        events.push(Event::HwndDriftDetected {
475            kind: HwndDriftKind::HiddenSinceOpen,
476            label: Some(label),
477            hwnd,
478            detail: "Window hidden without ever being foregrounded since open (deferred from placement grace)".to_string(),
479            severity: severity_for(HwndDriftKind::HiddenSinceOpen),
480            version: v,
481        });
482    }
483    events
484}
485
486/// Phase B.9.1 — handle `Command::ReportHwndForegroundChanged`.
487/// Updates the "has been seen" flag. Never emits drift directly
488/// — its role is to suppress future `HiddenSinceOpen` emissions.
489pub fn apply_hwnd_foreground_changed(state: &mut State, hwnd: u64, now_ms: u64) -> Vec<Event> {
490    if let Some((_, mirror)) = state.windows.iter_mut().find(|(_, m)| m.hwnd == Some(hwnd)) {
491        mirror.foregrounded_since_open = true;
492        mirror.last_foreground_at_ms = Some(now_ms);
493        // Foreground = window made it to the user. Clear any deferred
494        // hide so the drain pass doesn't fire spurious drift past the
495        // grace for a window the user actually saw.
496        mirror.hidden_since_open_deferred = false;
497    }
498    vec![]
499}
500
501/// Phase B.9.1 — handle `Command::ReportHwndIconicChanged`. Updates
502/// state. No drift directly — operator can read steady state via
503/// `--diag wrr` (B.9.2) if they want to see who's minimized.
504pub fn apply_hwnd_iconic_changed(state: &mut State, hwnd: u64, iconic: bool) -> Vec<Event> {
505    if let Some((_, mirror)) = state.windows.iter_mut().find(|(_, m)| m.hwnd == Some(hwnd)) {
506        mirror.iconic = iconic;
507    }
508    vec![]
509}
510
511/// Phase B.9.1 — handle `Command::ReportHwndPositionChanged`.
512/// Compares the new rect against `state.monitors`; emits
513/// `OffMonitor` drift if it doesn't intersect any monitor.
514/// Suppressed when `state.monitors` is empty (we don't yet know
515/// the topology — first `ReportMonitorTopologyChanged` will
516/// reconcile every label's `last_rect` against fresh monitors).
517pub fn apply_hwnd_position_changed(
518    state: &mut State,
519    hwnd: u64,
520    new_rect: Rect,
521    diagnostics: &mut Vec<String>,
522) -> Vec<Event> {
523    let mut events: Vec<Event> = Vec::new();
524    let monitors = state.monitors.clone();
525
526    // Phase B.9.1 diagnostic — single line per position event so
527    // operators can correlate with host-side hook activity. Returned
528    // to the caller, which writes it after releasing the state lock.
529    let linked_label_diag: Option<String> = state
530        .windows
531        .iter()
532        .find(|(_, m)| m.hwnd == Some(hwnd))
533        .map(|(label, _)| label.clone());
534    diagnostics.push(format!(
535        "[ipc] WRR-POS hwnd={:#x} rect=({},{})-({},{}) linked={:?} monitors={} pending={}",
536        hwnd, new_rect.left, new_rect.top, new_rect.right, new_rect.bottom,
537        linked_label_diag, monitors.len(), state.pending_hwnds.len()
538    ));
539
540    // Sentinel-aware drift suppression: CEF Views creates Win32
541    // top-level windows at the (-32000,-32000) / (-31970,-31970)
542    // hidden-sentinel positions for a brief moment between
543    // CreateWindow and the first SetWindowPos that places them.
544    // Firing OffMonitor on every window's open transient produces
545    // log noise without surfacing a real bug. Suppress drift for
546    // these positions; if the window stays at the sentinel
547    // (genuine bug), the *follow-up* event that lands at a
548    // non-sentinel off-monitor position WILL fire — and if it
549    // never moves, the corrective branch below acts on the FIRST
550    // sentinel report (since the foregrounded_since_open guard
551    // catches it).
552    let is_sentinel = is_win32_hidden_sentinel(&new_rect);
553
554    // Resolve the mirror: collect everything we need from a scoped
555    // borrow, then release it before calling `state.bump_version()`
556    // (rustc E0499 — same trick as `apply_hwnd_opened`).
557    //
558    // Storm-cap snapshot: capture the prior emit-flags so the gate
559    // logic below knows whether each side-effect has fired before.
560    // `apply_hwnd_position_changed` fires per WM_MOVE during a
561    // drag — without the caps, a window dragged across an off-
562    // monitor region storms the renderer with drift + corrective
563    // events.
564    struct Resolved {
565        label: String,
566        off_monitor: bool,
567        foregrounded_since_open: bool,
568        off_monitor_drift_emitted: bool,
569        corrective_window_move_emitted: bool,
570    }
571    let resolved: Option<Resolved> = state
572        .windows
573        .iter_mut()
574        .find(|(_, m)| m.hwnd == Some(hwnd))
575        .map(|(label, mirror)| {
576            mirror.last_rect = Some(new_rect);
577            let off_monitor =
578                !monitors.is_empty() && !rect::intersects_any(&new_rect, &monitors);
579            Resolved {
580                label: label.clone(),
581                off_monitor,
582                foregrounded_since_open: mirror.foregrounded_since_open,
583                off_monitor_drift_emitted: mirror.off_monitor_drift_emitted,
584                corrective_window_move_emitted: mirror.corrective_window_move_emitted,
585            }
586        });
587
588    let Some(r) = resolved else {
589        return events;
590    };
591
592    if !r.off_monitor {
593        return events;
594    }
595
596    // Window is off all monitors. Fire drift unless we're in the
597    // open-transient sentinel state (per above) OR the cap has
598    // already fired for this window.
599    let mut fire_drift = false;
600    let mut fire_corrective = false;
601    if !is_sentinel && !r.off_monitor_drift_emitted {
602        fire_drift = true;
603    }
604
605    // Phase B.9.2 — pure-reducer self-heal. If the window has
606    // never been foregrounded, this off-monitor state is from the
607    // open transition (NOT user action), so we emit a corrective
608    // move. The host's WRR subscriber applies it via SetWindowPos
609    // on the UI thread. The Win32 hidden sentinel is INCLUDED in
610    // the corrective trigger (we always want to move a window off
611    // the sentinel before the user notices), even though it's
612    // suppressed for drift to avoid log noise.
613    //
614    // Compute the corrective target ONCE (reagent P2 PR #722 round 2)
615    // — used both as the gate for `fire_corrective` and as the
616    // event payload below.
617    let corrective_target = if !r.foregrounded_since_open && !r.corrective_window_move_emitted && !agentmux_common::test_offscreen::active() {
618        pick_primary_centered(&monitors)
619    } else {
620        None
621    };
622    if corrective_target.is_some() {
623        fire_corrective = true;
624    }
625
626    if fire_drift {
627        // Mark the cap before bumping the version so re-entrant
628        // event handlers see consistent state.
629        if let Some((_, mirror)) = state
630            .windows
631            .iter_mut()
632            .find(|(_, m)| m.hwnd == Some(hwnd))
633        {
634            mirror.off_monitor_drift_emitted = true;
635        }
636        let v = state.bump_version();
637        events.push(Event::HwndDriftDetected {
638            kind: HwndDriftKind::OffMonitor,
639            label: Some(r.label.clone()),
640            hwnd: Some(hwnd),
641            detail: format!(
642                "Window rect ({},{})-({},{}) does not intersect any of {} monitors",
643                new_rect.left, new_rect.top, new_rect.right, new_rect.bottom,
644                monitors.len()
645            ),
646            severity: severity_for(HwndDriftKind::OffMonitor),
647            version: v,
648        });
649    }
650
651    if let Some(target) = corrective_target.filter(|_| fire_corrective) {
652        if let Some((_, mirror)) = state
653            .windows
654            .iter_mut()
655            .find(|(_, m)| m.hwnd == Some(hwnd))
656        {
657            mirror.corrective_window_move_emitted = true;
658        }
659        let v = state.bump_version();
660        events.push(Event::CorrectiveWindowMove {
661            hwnd,
662            target_rect: target,
663            reason: HwndDriftKind::OffMonitor,
664            version: v,
665        });
666    }
667
668    events
669}
670
671/// Phase B.9.1 — Win32 sentinel positions for "this window is
672/// hidden." CEF parks new windows here briefly between create
673/// and first paint; same value family (`SW_HIDE` analog used by
674/// `ITaskbarList::DeleteTab` removed windows). We suppress drift
675/// emission for these but DO trigger corrective move (the user
676/// shouldn't see the sentinel).
677fn is_win32_hidden_sentinel(r: &Rect) -> bool {
678    // Both classic ((-32000,-32000)) and the (-31970, -31970)
679    // CEF-Views variant. Plus a generous epsilon for either
680    // axis since the bottom-right corner is offset by a default
681    // window size (e.g. (-31840,-31972)).
682    (r.left <= -31000 && r.top <= -31000) || (r.right <= -31000 && r.bottom <= -31000)
683}
684
685/// Phase B.9.2 — pick a corrective target rect: centered on the
686/// first monitor at a sensible default size (1280x800 or 70% of
687/// monitor, whichever is smaller). `None` if the monitor list is
688/// empty (caller suppresses corrective in that case).
689fn pick_primary_centered(monitors: &[Rect]) -> Option<Rect> {
690    let primary = monitors.first()?;
691    let mw = primary.right - primary.left;
692    let mh = primary.bottom - primary.top;
693    if mw <= 0 || mh <= 0 {
694        return None;
695    }
696    let w = std::cmp::min(1280, (mw as f32 * 0.7) as i32);
697    let h = std::cmp::min(800, (mh as f32 * 0.7) as i32);
698    let cx = primary.left + (mw - w) / 2;
699    let cy = primary.top + (mh - h) / 2;
700    Some(Rect {
701        left: cx,
702        top: cy,
703        right: cx + w,
704        bottom: cy + h,
705    })
706}
707
708/// Phase B.9.1 — handle `Command::ReportMonitorTopologyChanged`.
709/// Replaces `state.monitors` wholesale, then re-evaluates every
710/// known mirror's `last_rect` against the new set. Emits
711/// `OffMonitor` for any window that newly falls off (e.g. user
712/// unplugged the external display where the window lived).
713pub fn apply_monitor_topology_changed(state: &mut State, rects: Vec<Rect>) -> Vec<Event> {
714    state.monitors = rects;
715    let monitors = state.monitors.clone();
716    if monitors.is_empty() {
717        // Headless / fully-disconnected — suppress drift; nothing
718        // is "off" if there's no "on".
719        return vec![];
720    }
721    let mut events: Vec<Event> = Vec::new();
722    // Gate emission on `off_monitor_drift_emitted` (codex P2 PR
723    // #722 round 3): without this, repeated topology changes
724    // (display hot-plug or rapid resolution change) re-emit drift
725    // for the same stranded window every event.
726    let stranded: Vec<(String, u64, Rect)> = state
727        .windows
728        .iter()
729        .filter_map(|(label, mirror)| {
730            if mirror.off_monitor_drift_emitted {
731                return None;
732            }
733            let r = mirror.last_rect?;
734            let h = mirror.hwnd?;
735            if rect::intersects_any(&r, &monitors) {
736                None
737            } else {
738                Some((label.clone(), h, r))
739            }
740        })
741        .collect();
742    for (label, hwnd, rect) in stranded {
743        if let Some((_, mirror)) = state
744            .windows
745            .iter_mut()
746            .find(|(l, _)| **l == label)
747        {
748            mirror.off_monitor_drift_emitted = true;
749        }
750        let v = state.bump_version();
751        events.push(Event::HwndDriftDetected {
752            kind: HwndDriftKind::OffMonitor,
753            label: Some(label),
754            hwnd: Some(hwnd),
755            detail: format!(
756                "Monitor topology change stranded window at ({},{})-({},{})",
757                rect.left, rect.top, rect.right, rect.bottom
758            ),
759            severity: severity_for(HwndDriftKind::OffMonitor),
760            version: v,
761        });
762    }
763    events
764}
765
766/// Phase B.9.1 — per-kind severity classifier. The split is
767/// deliberate: `OrphanDestroy` and `HwndWithoutBrowser` indicate a
768/// real divergence between CEF identity and Win32 reality (a CEF
769/// bug or a missed report path) — ERROR. `OffMonitor`,
770/// `HiddenSinceOpen`, `LingeringHwnd` are operationally
771/// significant (user can't see / use the window) but don't
772/// indicate a state-machine bug — WARN. `BrowserWithoutHwnd` is
773/// commonly transient (race window between OS create and host
774/// link) — INFO; only meaningful if it doesn't reconcile.
775pub fn severity_for(kind: HwndDriftKind) -> Severity {
776    match kind {
777        HwndDriftKind::OrphanDestroy => Severity::Error,
778        HwndDriftKind::HwndWithoutBrowser => Severity::Error,
779        HwndDriftKind::OffMonitor => Severity::Warn,
780        HwndDriftKind::HiddenSinceOpen => Severity::Warn,
781        HwndDriftKind::LingeringHwnd => Severity::Warn,
782        HwndDriftKind::BrowserWithoutHwnd => Severity::Info,
783        // Phase B.9.3 — OrphanInstance is operationally significant
784        // (process tree won't quit) but isn't a state-machine bug
785        // per se; it's an observation about cross-process lifecycle.
786        // WARN matches the other "user can't see / use this" kinds.
787        HwndDriftKind::OrphanInstance => Severity::Warn,
788    }
789}