Skip to main content

agentmux_mcp/
window_capture.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Window capture and discovery, plus the audit log both write.
5//!
6//! Split out of `main.rs` (audit step 17,
7//! `docs/reports/REPORT_DRY_AND_MODULARITY_AUDIT_2026_09_06.md`) — it was the
8//! largest single cluster in that file and is one concern: find AgentMux
9//! windows, decide what this agent is allowed to capture (`CaptureTier`),
10//! capture it, and record what was captured.
11//!
12//! Bodies are unchanged from `main.rs`; the only edits were `pub(crate)` on
13//! the items `call_tool` and the tests name. `main.rs` glob-imports this
14//! module, so those call sites — and `mod tests`'s `use super::*` — resolve
15//! exactly as they did before.
16
17use std::time::Duration;
18
19use anyhow::Result;
20use serde_json::{json, Value};
21
22use crate::agent_slug;
23
24/// Where `CaptureWindow` writes its PNGs: `<AgentMux root>/tmp/capture-window`,
25/// not the shared OS temp dir — reagent P2 on this tool's own PR (#2709
26/// round 1): `std::env::temp_dir()` is world-readable on a multi-user host,
27/// and CaptureWindow can capture arbitrary OS windows (not just AgentMux's own
28/// pane), so a captured image could leak to other local users.
29///
30/// The root comes from `agentmux_common::data_paths::agentmux_root()`, the one
31/// resolver srv uses too (#3372). This used to be a private copy that read only
32/// `AGENTMUX_DATA_HOME` and fell back to `/` with no home dir; it now honours
33/// `AGENTMUX_HOME_OVERRIDE` first and errors instead.
34pub(crate) fn capture_window_dir() -> Result<std::path::PathBuf, String> {
35    Ok(agentmux_common::data_paths::agentmux_root()?.join("tmp/capture-window"))
36}
37
38pub(crate) const CAPTURE_RETENTION: std::time::Duration = std::time::Duration::from_secs(60 * 60);
39
40/// Same bug class, same fix, as `agentmux-srv`'s `prune_old_screenshots`
41/// (`ui_handlers.rs`, reagent P2, PR #2662) — reapplied here per reagent's
42/// review of this tool's own PR (#2709 round 1), which found it wasn't
43/// reused. Best-effort, on the write path, PNG-only.
44pub(crate) fn prune_old_captures(dir: &std::path::Path) {
45    let Ok(entries) = std::fs::read_dir(dir) else {
46        return;
47    };
48    let now = std::time::SystemTime::now();
49    for entry in entries.flatten() {
50        let path = entry.path();
51        if path.extension().and_then(|e| e.to_str()) != Some("png") {
52            continue;
53        }
54        let Ok(metadata) = entry.metadata() else { continue };
55        let Ok(modified) = metadata.modified() else { continue };
56        let Ok(age) = now.duration_since(modified) else { continue };
57        if age > CAPTURE_RETENTION {
58            let _ = std::fs::remove_file(&path);
59        }
60    }
61}
62
63/// Max ancestor hops to walk from this MCP process before giving up —
64/// bounds the fallback search (see `own_instance_pids`'s doc comment for why
65/// this is a fallback, not the primary signal), while never walking so far
66/// up the tree (e.g. to `explorer.exe`) that "same instance" degrades into
67/// "everything on the desktop."
68pub(crate) const OWN_INSTANCE_ANCESTOR_HOPS: usize = 8;
69
70/// PIDs `CaptureWindow` must treat as "this agent's own AgentMux instance"
71/// and always exclude — reagent P0 (PR #2709 round 3).
72///
73/// **Primary signal: `AGENTMUX_APP_PATH`.** Every process belonging to this
74/// exact running instance (portable build or install) is launched from
75/// under that one directory — confirmed directly (not assumed): this
76/// agent's own host process's `Process::exe()` path
77/// (`...\agentmux-0.55.18+....-x64-portable\runtime\agentmux-0.55.18.exe`)
78/// starts with `AGENTMUX_APP_PATH`
79/// (`...\agentmux-0.55.18+....-x64-portable`) exactly. This is more precise
80/// than matching on version number alone — it correctly tells apart two
81/// separate instances that happen to share a version (e.g. two portable
82/// builds of the same release), which a version-string match would
83/// conflate.
84///
85/// **Fallback signal: bounded process-ancestor walk.** Kept as a second,
86/// additive layer (union, not replacement) for the case `AGENTMUX_APP_PATH`
87/// isn't set (confirmed present for `AGENTMUX_RUNTIME_MODE=portable`; not
88/// separately confirmed for `task dev` instances). **This alone is not
89/// reliable** — verified directly by testing: Windows recycles PIDs and a
90/// process's recorded parent-PID can point at an already-exited process, so
91/// `sys.process(stale_ppid)` returns `None` and the walk silently stops
92/// short of the real ancestor chain. Confirmed this exact failure in
93/// testing (the walk never reached this instance's own host process). Kept
94/// only as defense-in-depth alongside the path-based signal, never alone.
95///
96/// Fails safe: an unresolvable `pid()` on a *candidate* window (checked by
97/// the caller, `CaptureWindow`'s handler) is treated as "assume it's mine,
98/// exclude it" — so a window this function's own signals can't positively
99/// place is still excluded, not silently let through.
100pub(crate) fn own_instance_pids() -> std::collections::HashSet<u32> {
101    let sys = sysinfo::System::new_all();
102    let mut result = std::collections::HashSet::new();
103
104    if let Ok(app_path) = std::env::var("AGENTMUX_APP_PATH") {
105        if !app_path.is_empty() {
106            let app_path = std::path::Path::new(&app_path);
107            for (pid, proc) in sys.processes() {
108                if proc.exe().map(|e| e.starts_with(app_path)).unwrap_or(false) {
109                    result.insert(pid.as_u32());
110                }
111            }
112        }
113    }
114
115    let my_pid = sysinfo::Pid::from(std::process::id() as usize);
116    let mut ancestors = vec![my_pid];
117    let mut current = my_pid;
118    for _ in 0..OWN_INSTANCE_ANCESTOR_HOPS {
119        let Some(proc) = sys.process(current) else { break };
120        let Some(parent) = proc.parent() else { break };
121        ancestors.push(parent);
122        current = parent;
123    }
124    result.extend(ancestors.iter().map(|p| p.as_u32()));
125    for (pid, proc) in sys.processes() {
126        let Some(ppid) = proc.parent() else { continue };
127        if !ancestors.contains(&ppid) {
128            continue;
129        }
130        if proc.name().to_string_lossy().to_lowercase().starts_with("agentmux") {
131            result.insert(pid.as_u32());
132        }
133    }
134    result
135}
136
137/// Capture tier for one target window — see
138/// `docs/specs/SPEC_AGENT_UNRESTRICTED_CAPTURE_WITH_ACCOUNTABILITY_2026_08_30.md`
139/// §3. Keyed on WHAT is being captured, never on who is asking: identity is
140/// already proven upstream (`sign_ui_automation_auth`), so the open question
141/// is what a proven identity may reach.
142///
143/// This replaces the previous binary `!is_self` exclusion. That rule came from
144/// `SPEC_AGENT_UI_AUTOMATION_CLICK_SCREENSHOT_2026_08_18.md` §6, which itself
145/// says cross-agent targeting *"if it's ever wanted at all"* should be a
146/// distinct capability — i.e. it defaulted closed because no mechanism existed
147/// to be selective, not because open had been judged wrong. The repo owner has
148/// since directed that agents be able to capture anything. This enum is that
149/// mechanism.
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub(crate) enum CaptureTier {
152    /// T1 — another pane inside the caller's OWN instance. Its window hosts
153    /// every agent's pane, which is exactly what the old rule blocked.
154    SameInstance,
155    /// T2 — a different AgentMux instance owned by the same OS user.
156    OtherInstance,
157    /// T3 — a window owned by a DIFFERENT OS user. The one tier that crosses a
158    /// human rather than an agent boundary: that user never consented to this
159    /// app's agents, and no in-app notification can reach them.
160    OtherUser,
161    /// T4 — a non-AgentMux window owned by the same OS user (their browser,
162    /// their password manager). PR #2709 round 2 caught the original unscoped
163    /// tool capturing a KeePass window; allowed now, but always audited.
164    ForeignApp,
165}
166
167impl CaptureTier {
168    /// Phase 1 `allow` defaults (spec §3). Only T3 is closed, and only because
169    /// it is a human-to-human boundary — every agent-to-agent tier is open.
170    pub(crate) fn allowed(self) -> bool {
171        !matches!(self, CaptureTier::OtherUser)
172    }
173
174    pub(crate) fn label(self) -> &'static str {
175        match self {
176            CaptureTier::SameInstance => "T1-same-instance",
177            CaptureTier::OtherInstance => "T2-other-instance",
178            CaptureTier::OtherUser => "T3-other-user",
179            CaptureTier::ForeignApp => "T4-foreign-app",
180        }
181    }
182}
183
184/// The OS user id owning the calling process, used to place a target window on
185/// the near or far side of the T3 boundary.
186///
187/// Fails CLOSED, matching `own_instance_pids()`'s existing discipline: if this
188/// returns `None` every window resolves to `OtherUser` and capture is denied.
189/// An unresolvable owner is exactly the case where guessing "probably mine"
190/// would be how a cross-user capture slips through.
191pub(crate) fn current_user_id(sys: &sysinfo::System) -> Option<String> {
192    let me = sysinfo::get_current_pid().ok()?;
193    sys.process(me)
194        .and_then(|p| p.user_id())
195        .map(|u| u.to_string())
196}
197
198/// A completed capture. Richer than the bare message string it replaces so
199/// `audit_log_capture_window` can record WHAT was captured and at which tier,
200/// rather than only the caller's query and a success/failure flag.
201#[derive(Debug)]
202pub(crate) struct CaptureOutcome {
203    /// Human-facing tool result, returned to the caller verbatim.
204    pub(crate) message: String,
205    pub(crate) tier: CaptureTier,
206    /// Resolved target — `pid=N title="..."`.
207    pub(crate) target: String,
208    /// Hex SHA-256 of the saved PNG; `None` if hashing failed (best-effort).
209    pub(crate) image_sha256: Option<String>,
210    /// Whether the private and secret panes of an AgentMux window were blacked out (`window_blackout`).
211    pub(crate) redacted: bool,
212}
213
214/// One top-level window visible to this process, with the metadata both
215/// `DiscoverWindows` and `CaptureWindow` need. Shared via
216/// `enumerate_agentmux_windows()` so the two tools can't drift on what counts
217/// as "AgentMux's own window", "the calling agent's own instance", or which
218/// tier a target falls in.
219pub(crate) struct AgentMuxWindowInfo {
220    pub(crate) window: xcap::Window,
221    pub(crate) pid: u32,
222    pub(crate) title: String,
223    pub(crate) exe_path: String,
224    pub(crate) is_self: bool,
225    /// Whether the owning process is an AgentMux process at all — T4 targets
226    /// are enumerated now, so this is no longer implied by presence in the list.
227    pub(crate) is_agentmux: bool,
228    pub(crate) tier: CaptureTier,
229}
230
231/// Enumerate every top-level OS window, AgentMux-owned or not, each tagged
232/// with the `CaptureTier` that decides whether it may be captured.
233///
234/// `is_agentmux` is matched via `app_name()`, not `title()` — AgentMux's own
235/// process names are version-stamped, e.g. `agentmux-0.55.18`, not a single
236/// fixed string, but they all share the `agentmux` prefix (reagent P1, PR
237/// #2709 round 2). That flag no longer decides *inclusion* — non-AgentMux
238/// windows are T4 capture targets — but it still gates disclosure: they stay
239/// out of `DiscoverWindows`' default listing and their titles are withheld
240/// from candidate/miss lists (`candidate_label`), which is what keeps round
241/// 2's KeePass-title leak closed now that they're enumerated at all.
242///
243/// `is_self` marks windows belonging to the calling agent's OWN instance
244/// (`own_instance_pids()`).
245///
246/// **Historical note (reagent P2 on PR #2845):** this comment previously said
247/// `is_self` windows were "hard-excluded downstream by `capture_window_impl`
248/// … the actual isolation boundary, not a nicety" (reagent P0, PR #2709
249/// round 3). That is no longer true and the reasoning has been superseded, not
250/// merely relaxed: the boundary it protected —
251/// `SPEC_AGENT_UI_AUTOMATION_CLICK_SCREENSHOT_2026_08_18.md` §6's own-pane-only
252/// default — was an unratified recommendation that defaulted closed because no
253/// mechanism existed to be selective. `is_self` now resolves to
254/// `CaptureTier::SameInstance`, which is allowed. See
255/// `SPEC_AGENT_UNRESTRICTED_CAPTURE_WITH_ACCOUNTABILITY_2026_08_30.md`.
256pub(crate) fn enumerate_agentmux_windows() -> Result<Vec<AgentMuxWindowInfo>> {
257    let windows =
258        xcap::Window::all().map_err(|e| anyhow::anyhow!("failed to enumerate windows: {e}"))?;
259    let own_pids = own_instance_pids();
260    let sys = sysinfo::System::new_all();
261    let me = current_user_id(&sys);
262    let mut out = Vec::new();
263    for window in windows {
264        let is_agentmux = window
265            .app_name()
266            .map(|a| a.to_lowercase().starts_with("agentmux"))
267            .unwrap_or(false);
268        // Non-AgentMux windows are no longer skipped — they are T4 targets.
269        // They stay out of `DiscoverWindows`' default listing (see its
270        // `include_foreign` arg) so ordinary discovery doesn't disclose the
271        // titles of a user's unrelated applications as a side effect.
272        let pid = window.pid().unwrap_or(0);
273        // Fails safe: an unresolvable pid is treated as "assume it's mine"
274        // rather than silently dropped, so `DiscoverWindows` still surfaces
275        // that the window exists instead of hiding it.
276        //
277        // That promise is real again as of reagentx P2 on PR #2845. Briefly it
278        // wasn't: an unresolvable OWNER resolves the window to T3, and
279        // `DiscoverWindows` was dropping non-allowed tiers outright, so such a
280        // window vanished from the listing even with `include_self`. It is now
281        // listed with `title`/`exe_path` redacted, which keeps the disclosure
282        // closed without reintroducing the hiding this comment warns against.
283        let is_self = pid == 0 || own_pids.contains(&pid);
284        let proc = sys.process(sysinfo::Pid::from(pid as usize));
285        let title = window.title().unwrap_or_default();
286        let exe_path = proc
287            .and_then(|p| p.exe())
288            .map(|p| p.display().to_string())
289            .unwrap_or_default();
290
291        // Tier resolution. The OS-user check runs FIRST and outranks
292        // everything else: a window owned by another human is T3 no matter
293        // what process owns it, including another AgentMux instance of theirs.
294        let owner = proc.and_then(|p| p.user_id()).map(|u| u.to_string());
295        let tier = match (&me, &owner) {
296            // Both known and different — the human boundary.
297            (Some(mine), Some(theirs)) if mine != theirs => CaptureTier::OtherUser,
298            // Either side unresolvable — fail closed, same discipline as
299            // `is_self` above. Guessing "probably mine" here is precisely how
300            // a cross-user capture would slip through.
301            (None, _) | (_, None) => CaptureTier::OtherUser,
302            _ if is_self => CaptureTier::SameInstance,
303            _ if is_agentmux => CaptureTier::OtherInstance,
304            _ => CaptureTier::ForeignApp,
305        };
306
307        out.push(AgentMuxWindowInfo {
308            window,
309            pid,
310            title,
311            exe_path,
312            is_self,
313            is_agentmux,
314            tier,
315        });
316    }
317    Ok(out)
318}
319
320/// Cheap heuristic for "this capture is probably a blank/unpainted frame,
321/// not a real render" — sample ~200 evenly-spaced pixels and check they're
322/// all within a small tolerance of the first one. Not real image analysis
323/// (a legitimately solid-color themed window would also trip this) —
324/// deliberately cheap and approximate, used only to decide whether a short
325/// bounded retry is worth attempting, and to set `likely_unrendered` as a
326/// hint, never as a hard failure.
327pub(crate) fn looks_unrendered(img: &image::RgbaImage) -> bool {
328    let pixels = img.as_raw();
329    if pixels.len() < 4 {
330        return true;
331    }
332    let (r0, g0, b0) = (pixels[0], pixels[1], pixels[2]);
333    let pixel_count = pixels.len() / 4;
334    let step = (pixel_count / 200).max(1);
335    let mut sampled = 0usize;
336    for i in (0..pixel_count).step_by(step) {
337        let idx = i * 4;
338        sampled += 1;
339        if pixels[idx].abs_diff(r0) > 8 || pixels[idx + 1].abs_diff(g0) > 8 || pixels[idx + 2].abs_diff(b0) > 8 {
340            return false;
341        }
342    }
343    sampled > 0
344}
345
346/// Label for a window in the AUDIT TRAIL.
347///
348/// Fuller than `candidate_label` where it can be — reagentx P2 on PR #2845
349/// correctly spotted that reusing the caller-facing label lost a T4 window's
350/// title on a post-resolution failure, giving foreign-app failures less audit
351/// detail than AgentMux ones for no reason.
352///
353/// But NOT unconditionally full, because that finding's premise — "the audit
354/// is server-side only" — does not hold here. The trail is an NDJSON file in
355/// this instance's own data dir, and agents have shell access; it was read
356/// with `tail` during this PR's own verification. It is therefore not a
357/// confidential sink.
358///
359/// So audit detail follows the ALLOW decision, not AgentMux-ness:
360///   - allowed tier → full title. The agent could capture the window and read
361///     the title off the pixels anyway, so recording it discloses nothing new.
362///   - withheld tier → pid and tier only. Recording a T3 title would hand the
363///     agent, via a file it can read, exactly the content the tier denied it —
364///     reopening through the log the same oracle closed in the title-miss path.
365pub(crate) fn audit_target_label(w: &impl WindowFacts) -> String {
366    if w.tier().allowed() {
367        format!("pid={} title={:?}", w.pid(), w.title())
368    } else {
369        format!("pid={} {} <title withheld>", w.pid(), w.tier().label())
370    }
371}
372
373/// Label for a window in a CALLER-FACING disambiguation/candidate list.
374///
375/// Stricter than `audit_target_label` above, because the audiences differ: this
376/// one is returned to the agent, so it withholds the TITLE of every
377/// non-AgentMux window — reagent P1 on PR #2845. Foreign windows became
378/// capturable with the tier model, so any list built from the capturable set
379/// would otherwise disclose a user's unrelated app titles (their browser,
380/// their password manager) as a side effect of a miss or an ambiguous match,
381/// bypassing `DiscoverWindows`' own `include_foreign` opt-in. The pid alone
382/// disambiguates, and is what the caller needs anyway.
383pub(crate) fn candidate_label(w: &impl WindowFacts) -> String {
384    if w.is_agentmux() {
385        format!("pid={} title={:?}", w.pid(), w.title())
386    } else {
387        format!("pid={} <non-AgentMux window; pass include_foreign to UI's windows action to identify it>", w.pid())
388    }
389}
390
391/// The window `CaptureWindow` was asked for, found among every window and checked against its tier. Holds no OS
392/// window, so the caller can ask srv for the window's private rectangles before the frame is taken
393/// (`window_blackout`) without holding one across a wait.
394///
395/// `index: None` with more than one `title_contains` match is an error
396/// listing every candidate, NOT a silent pick of match 0 — see
397/// docs/reports/REPORT_AGENT_SCREENSHOT_WINDOW_CONTROL_BLOCKERS_2026_08_24.md
398/// §1 for the real incident (an ambiguous match silently captured an
399/// unrelated, sensitive window) this specifically fixes. `index: Some(i)`
400/// is still honored directly against whatever matched, unchanged from the
401/// original behavior, for callers who already disambiguate explicitly.
402pub(crate) struct ResolvedWindow {
403    /// The OS window's id, to find it again for the frame.
404    pub(crate) id: u32,
405    pub(crate) pid: u32,
406    pub(crate) title: String,
407    pub(crate) tier: CaptureTier,
408    pub(crate) is_agentmux: bool,
409    pub(crate) is_self: bool,
410    /// How many of this AgentMux's own windows have this title, the target included.
411    pub(crate) same_title: usize,
412}
413
414pub(crate) fn resolve_window(
415    title_contains: Option<&str>,
416    index: Option<usize>,
417    pid: Option<u32>,
418    // Filled the moment a target is RESOLVED, so a failure after that point —
419    // a denied T3 pid, a failed capture_image, a failed PNG write — is still
420    // audited with its tier and target instead of nulls (codex P2 on PR #2845).
421    // Without it the log cannot tell "no such window" apart from "blocked
422    // cross-user attempt", which is the entry a reviewer most wants to find.
423    resolved: &mut Option<(CaptureTier, String)>,
424) -> Result<ResolvedWindow> {
425    let all = enumerate_agentmux_windows()?;
426    let target = select_target(&all, title_contains, index, pid, resolved)?;
427    *resolved = Some((target.tier, audit_target_label(target)));
428    Ok(ResolvedWindow {
429        id: target.window.id().map_err(|e| anyhow::anyhow!("the window has no id to capture it by: {e}"))?,
430        pid: target.pid,
431        title: target.title.clone(),
432        tier: target.tier,
433        is_agentmux: target.is_agentmux,
434        is_self: target.is_self,
435        same_title: all.iter().filter(|w| w.is_agentmux && w.is_self && w.title == target.title).count(),
436    })
437}
438
439/// The frame of `target`, found again by its id; the second is whether it still looks unpainted.
440pub(crate) fn capture_frame(target: &ResolvedWindow) -> Result<(image::RgbaImage, bool)> {
441    let windows = xcap::Window::all().map_err(|e| anyhow::anyhow!("failed to enumerate windows: {e}"))?;
442    let window = windows
443        .iter()
444        .find(|w| w.id().ok() == Some(target.id))
445        .ok_or_else(|| anyhow::anyhow!("window pid={} closed before it was captured", target.pid))?;
446    capture_settled(window)
447}
448
449/// Save a captured frame and say what was captured.
450pub(crate) fn finish_capture(target: &ResolvedWindow, image: &image::RgbaImage, likely_unrendered: bool, redacted: bool) -> Result<CaptureOutcome> {
451    let dir = capture_window_dir()
452        .map_err(|e| anyhow::anyhow!("cannot resolve the AgentMux root for captures: {e}"))?;
453    let path = save_capture(image, &dir)?;
454    Ok(CaptureOutcome {
455        message: outcome_message(&target.title, &path, likely_unrendered),
456        tier: target.tier,
457        // The resolved target, not the query string — an audit reviewer needs
458        // to know WHAT was captured, which a `title_contains` substring does
459        // not tell them.
460        target: format!("pid={} title={:?}", target.pid, target.title),
461        image_sha256: sha256_file(&path),
462        redacted,
463    })
464}
465
466/// What choosing a capture target needs to know about a window, so the choice can be tested
467/// without a desktop (`AgentMuxWindowInfo` holds the OS window itself).
468pub(crate) trait WindowFacts {
469    fn pid(&self) -> u32;
470    fn title(&self) -> &str;
471    fn is_agentmux(&self) -> bool;
472    fn tier(&self) -> CaptureTier;
473}
474
475impl WindowFacts for AgentMuxWindowInfo {
476    fn pid(&self) -> u32 {
477        self.pid
478    }
479    fn title(&self) -> &str {
480        &self.title
481    }
482    fn is_agentmux(&self) -> bool {
483        self.is_agentmux
484    }
485    fn tier(&self) -> CaptureTier {
486        self.tier
487    }
488}
489
490/// The window `CaptureWindow` was asked for, by pid or by title, out of every window `all`.
491/// Fills `resolved` as soon as a withheld window is the one asked for, so the audit can tell
492/// it from an absent one; what the caller is told never differs between the two for a title.
493fn select_target<'a, W: WindowFacts>(
494    all: &'a [W],
495    title_contains: Option<&str>,
496    index: Option<usize>,
497    pid: Option<u32>,
498    resolved: &mut Option<(CaptureTier, String)>,
499) -> Result<&'a W> {
500    // Tier gate replaces the old `!w.is_self` exclusion — see `CaptureTier`.
501    // Only T3 (a different OS user's window) is withheld; every agent-to-agent
502    // tier, including this instance's own window, is reachable.
503    let foreign: Vec<&W> = all.iter().filter(|w| w.tier().allowed()).collect();
504
505    match pid {
506        Some(target_pid) => select_by_pid(all, &foreign, target_pid, index, resolved),
507        None => select_by_title(all, &foreign, title_contains, index, resolved),
508    }
509}
510
511/// [`select_target`] for a pid. `foreign` is `all` without the withheld windows.
512fn select_by_pid<'a, W: WindowFacts>(
513    all: &'a [W],
514    foreign: &[&'a W],
515    target_pid: u32,
516    index: Option<usize>,
517    resolved: &mut Option<(CaptureTier, String)>,
518) -> Result<&'a W> {
519    // A single host process can own multiple top-level windows sharing
520    // the same pid (`find_all_own_windows` in
521    // crates/cef/src/commands/window/lifecycle.rs), so a plain `.find()`
522    // would capture whichever matching window enumerated first — possibly
523    // a pool/sub-window, not the one the caller meant. Same
524    // ambiguity-rejection shape as the title_contains branch below:
525    // `index` disambiguates, an unqualified ambiguous match does not.
526    let matches: Vec<&W> = foreign
527        .iter()
528        .filter(|w| w.pid() == target_pid)
529        .copied()
530        .collect();
531    if matches.is_empty() {
532        // `foreign` is already tier-filtered, so a withheld T3 window is
533        // absent from it and would otherwise be indistinguishable from a
534        // pid that doesn't exist — reported identically to the caller AND
535        // audited as `tier: null`. Look it up in the UNFILTERED set to
536        // separate "withheld" from "absent" (codex P2 / reagentx P2).
537        if let Some(blocked) = all.iter().find(|w| w.pid() == target_pid) {
538            *resolved = Some((blocked.tier(), audit_target_label(blocked)));
539            anyhow::bail!(
540                "window pid={target_pid} is {} — capture is withheld for windows owned \
541                 by a different OS user; every other tier is available",
542                blocked.tier().label()
543            );
544        }
545        anyhow::bail!(
546            "no window found for pid {target_pid} — use UI's windows action to see \
547             current candidates"
548        );
549    }
550    Ok(match index {
551        Some(i) => *matches.get(i).ok_or_else(|| {
552            anyhow::anyhow!(
553                "index {i} out of range — only {} window(s) matched pid {target_pid}",
554                matches.len()
555            )
556        })?,
557        None if matches.len() == 1 => matches[0],
558        None => {
559            let candidates: Vec<String> = matches
560                .iter()
561                .map(|w| candidate_label(*w))
562                .collect();
563            anyhow::bail!(
564                "{} windows matched pid {target_pid} — a single process can own \
565                 multiple top-level windows; pass an explicit index (0-based) \
566                 alongside pid to disambiguate. Candidates: {}",
567                matches.len(),
568                candidates.join("; ")
569            );
570        }
571    })
572}
573
574/// The error for a title that matched no window the caller may capture.
575fn title_miss<W: WindowFacts>(
576    all: &[W],
577    foreign: &[&W],
578    title_contains: &str,
579    needle: &str,
580    resolved: &mut Option<(CaptureTier, String)>,
581) -> anyhow::Error {
582    // A title matching ONLY a withheld window is recorded for the
583    // AUDIT — and deliberately changes nothing the caller sees.
584    //
585    // reagentx P1 on PR #2845: an earlier version bailed here with a
586    // distinguishable "exists but is T3" message. Withholding the
587    // literal title wasn't enough — differing *responses* are an
588    // existence oracle. An agent can probe substrings (binary-search
589    // over characters) and reconstruct a cross-user window's title
590    // without ever being granted capture, defeating the very boundary
591    // this tier exists to hold. Introduced while fixing the audit gap
592    // below it: making withheld-vs-absent legible to the auditor made
593    // it legible to the attacker too.
594    //
595    // The split that resolves it: the AUDIT is server-side and may
596    // know; the CALLER may not. So this records `resolved` and then
597    // falls through to the identical generic-miss message below —
598    // structurally the same code path and the same bytes either way,
599    // rather than two branches a future edit could let drift apart.
600    //
601    // The pid branch above is deliberately NOT symmetric: it does name
602    // the tier. A caller must already hold the pid to ask, `Discover
603    // Windows` never hands out T3 pids, and process ownership is
604    // already enumerable by anything with shell access — so the pid's
605    // existence is not a secret this tool is keeping, while a window
606    // TITLE is exactly the content it is.
607    if let Some(blocked) = all
608        .iter()
609        .find(|w| !w.tier().allowed() && w.title().to_lowercase().contains(&needle))
610    {
611        *resolved = Some((blocked.tier(), audit_target_label(blocked)));
612    }
613    // Only lists AGENTMUX windows' titles, never every window on the
614    // desktop — reagent P2 (PR #2709 round 2): the original version
615    // dumped every visible window's title on any miss, which let a
616    // caller enumerate arbitrary window titles (confirmed in testing:
617    // it leaked a password manager's document title) with no real
618    // match required at all.
619    //
620    // The `is_agentmux` filter is load-bearing again as of the tier
621    // model — reagent P1 on PR #2845. `foreign` now includes T4
622    // non-AgentMux windows (they became capturable), so listing it
623    // wholesale would have re-opened exactly that leak, and would have
624    // bypassed `DiscoverWindows`' own `include_foreign` opt-in in the
625    // process: a caller could enumerate the user's desktop by
626    // deliberately missing.
627    let titles: Vec<&str> = foreign
628        .iter()
629        .filter(|w| w.is_agentmux())
630        .map(|w| w.title())
631        .filter(|t| !t.is_empty())
632        .collect();
633    if titles.is_empty() {
634        return anyhow::anyhow!(
635            "no AgentMux window title contains {title_contains:?} — \
636             no other AgentMux windows are currently open"
637        );
638    }
639    anyhow::anyhow!(
640        "no AgentMux window title contains {title_contains:?}. \
641         Open AgentMux window titles: {}",
642        titles.join(", ")
643    )
644}
645
646/// [`select_target`] for a title. `foreign` is `all` without the withheld windows.
647fn select_by_title<'a, W: WindowFacts>(
648    all: &'a [W],
649    foreign: &[&'a W],
650    title_contains: Option<&str>,
651    index: Option<usize>,
652    resolved: &mut Option<(CaptureTier, String)>,
653) -> Result<&'a W> {
654    let title_contains = title_contains
655        .ok_or_else(|| anyhow::anyhow!("must provide either pid or title_contains"))?;
656    let needle = title_contains.to_lowercase();
657    let matches: Vec<&W> = foreign
658        .iter()
659        .filter(|w| w.title().to_lowercase().contains(&needle))
660        .copied()
661        .collect();
662
663    if matches.is_empty() {
664        return Err(title_miss(all, foreign, title_contains, &needle, resolved));
665    }
666
667    Ok(match index {
668        Some(i) => *matches.get(i).ok_or_else(|| {
669            anyhow::anyhow!(
670                "index {i} out of range — only {} window(s) matched {title_contains:?}",
671                matches.len()
672            )
673        })?,
674        None if matches.len() == 1 => matches[0],
675        None => {
676            // The fix for blocker #1 in the report: an ambiguous
677            // match with no explicit index used to silently capture
678            // index 0 despite this tool's own docstring claiming it
679            // would list candidates instead. It now actually does.
680            let candidates: Vec<String> = matches
681                .iter()
682                .map(|w| candidate_label(*w))
683                .collect();
684            anyhow::bail!(
685                "{} windows matched {title_contains:?} — pass an explicit index (0-based), \
686                 or better, one of these pids directly (preferred: stable, unlike title). \
687                 Candidates: {}",
688                matches.len(),
689                candidates.join("; ")
690            );
691        }
692    })
693}
694
695/// The window's image, retried a little for one that has not painted yet.
696/// The second is whether it still looks unpainted.
697fn capture_settled(window: &xcap::Window) -> Result<(image::RgbaImage, bool)> {
698    // Short bounded retry for a freshly-created window that hasn't
699    // painted its first real frame yet — see looks_unrendered()'s doc
700    // comment. std::thread::sleep (not tokio::time::sleep): this fn is
701    // plain sync code called from the async dispatch path, and the
702    // bounded ~800ms worst case is a deliberate, request-scoped wait
703    // directly serving this call, not background work stealing the
704    // runtime from anything else.
705    let mut image = window
706        .capture_image()
707        .map_err(|e| anyhow::anyhow!("capture failed: {e}"))?;
708    let mut likely_unrendered = looks_unrendered(&image);
709    let mut attempts = 1;
710    while likely_unrendered && attempts < 3 {
711        std::thread::sleep(Duration::from_millis(400));
712        image = window
713            .capture_image()
714            .map_err(|e| anyhow::anyhow!("capture failed: {e}"))?;
715        likely_unrendered = looks_unrendered(&image);
716        attempts += 1;
717    }
718    Ok((image, likely_unrendered))
719}
720
721/// Saves `image` as a new PNG in `dir` (made if need be) and returns its path.
722fn save_capture(image: &image::RgbaImage, dir: &std::path::Path) -> Result<std::path::PathBuf> {
723    std::fs::create_dir_all(dir)
724        .map_err(|e| anyhow::anyhow!("failed to create capture dir {}: {e}", dir.display()))?;
725    let path = dir.join(format!("{}.png", uuid::Uuid::new_v4()));
726    image
727        .save(&path)
728        .map_err(|e| anyhow::anyhow!("failed to save capture to {}: {e}", path.display()))?;
729    // Unbounded growth over repeated/looped calls otherwise — same bug
730    // class as UIScreenshot's own screenshot dir (reagent P2, PR #2662)
731    // and reagent's own review of this PR (round 1) pointing out that
732    // fix wasn't reused here. Same fix, same shape: best-effort, on the
733    // write path.
734    prune_old_captures(dir);
735    Ok(path)
736}
737
738/// What `CaptureWindow` tells the caller about a saved capture.
739fn outcome_message(title: &str, path: &std::path::Path, likely_unrendered: bool) -> String {
740    // codex P2 on PR #2810: no process start time is collected or checked
741    // anywhere, so claiming "this window was created recently" was
742    // unsupported and misleading for a mature window that just happens to
743    // render a near-uniform frame (looks_unrendered's own doc comment
744    // already acknowledges that legitimate case). State only what was
745    // actually observed.
746    let hint = if likely_unrendered {
747        " (likely_unrendered: true — the captured frame looks solid or \
748           near-solid-color even after retrying, which can mean the window \
749           hasn't painted its first real frame yet, or that it genuinely \
750           looks like this; consider capturing it again shortly if \
751           that's unexpected)"
752    } else {
753        ""
754    };
755    format!(
756        "Captured window {title:?} to {}{hint} — use Read on that path to view it yourself, or Pane (action \"open\", view \"media\") to show it to the user.",
757        path.display()
758    )
759}
760
761/// Hex SHA-256 of a captured PNG, recorded in the audit trail so a leaked
762/// screenshot can be traced back to the call that produced it (spec §6).
763/// Best-effort — a hashing failure yields `None` and must never fail the
764/// capture, matching `audit_log_capture_window`'s own "never break the tool"
765/// discipline.
766pub(crate) fn sha256_file(path: &std::path::Path) -> Option<String> {
767    use sha2::{Digest, Sha256};
768    let bytes = std::fs::read(path).ok()?;
769    let mut hasher = Sha256::new();
770    hasher.update(&bytes);
771    Some(format!("{:x}", hasher.finalize()))
772}
773
774/// Audit trail for `CaptureWindow` — reagent P1 (PR #2709 round 4): the
775/// residual risk after rounds 2-3's scoping (a different AgentMux
776/// instance's window, which can belong to a different OS user on a shared
777/// machine) is a disclosure-across-a-human-boundary question, not a
778/// technical one a capability flag alone would fully answer — a real
779/// per-agent opt-in gate is tracked as a separate follow-up (no existing
780/// settings/enforcement mechanism to build it on today). Logging every
781/// call — who, what was requested, what happened — is the honest,
782/// shippable Phase-1 answer: best-effort (a logging failure must never
783/// break the tool itself), append-only NDJSON inside `capture_window_dir()`
784/// itself — `prune_old_captures`'s PNG-only extension filter already
785/// leaves a `.log` file in that same directory untouched, so this doesn't
786/// need (or want) its own separate directory alongside it.
787pub(crate) fn audit_log_capture_window(
788    query_desc: &str,
789    outcome: &Result<CaptureOutcome>,
790    // Resolved target/tier for the FAILURE paths — on success the outcome
791    // carries its own. See resolve_window's `resolved` param.
792    resolved: &Option<(CaptureTier, String)>,
793) {
794    let entry = serde_json::json!({
795        "timestamp": agentmux_common::time::now_secs_u64(),
796        "agent_id": agent_slug().unwrap_or_else(|_| "unknown".to_string()),
797        "tool": "CaptureWindow",
798        // "pid=N" or "title_contains=\"...\"" — whichever targeting mode
799        // the caller used (SPEC_AGENT_APP_API_WINDOW_CONTROL_ROBUSTNESS_2026_08_24.md
800        // added pid-based targeting as an alternative to title matching).
801        "query": query_desc,
802        // The RESOLVED target and its tier, not just the query string — a
803        // reviewer needs to know what was actually captured, which a
804        // `title_contains` substring doesn't say. Absent on failure, since
805        // nothing was resolved (spec §6).
806        "tier": outcome
807            .as_ref()
808            .ok()
809            .map(|c| c.tier.label())
810            .or_else(|| resolved.as_ref().map(|(t, _)| t.label())),
811        "target": outcome
812            .as_ref()
813            .ok()
814            .map(|c| c.target.clone())
815            .or_else(|| resolved.as_ref().map(|(_, t)| t.clone())),
816        // Traces a leaked screenshot back to the call that produced it.
817        "image_sha256": outcome.as_ref().ok().and_then(|c| c.image_sha256.clone()),
818        // Whether an AgentMux window's private and secret panes were blacked out (`window_blackout`).
819        "redacted": outcome.as_ref().map(|c| c.redacted).unwrap_or(false),
820        "outcome": match outcome {
821            Ok(c) => serde_json::json!({"result": "success", "detail": c.message}),
822            Err(e) => serde_json::json!({"result": "error", "detail": e.to_string()}),
823        },
824    });
825    append_window_audit_log_entry(&entry);
826}
827
828/// One `DiscoverWindows` entry.
829///
830/// A withheld (T3) window is LISTED but redacted, not omitted — reagentx P2 on
831/// PR #2845 caught two contradictions the omit-entirely approach created:
832///   - the `is_self` fail-safe promised an unresolvable-pid window would
833///     "still surface ... instead of hiding it", which an unconditional drop
834///     broke (an unresolvable owner resolves to T3)
835///   - this tool advertises `capturable` so a caller can "see why a window is
836///     out of reach before trying", unreachable if every listed entry is
837///     capturable by construction
838///
839/// Redacting satisfies both while keeping the disclosure closed: `title` and
840/// `exe_path` (which embeds the owning OS username) are exactly what must not
841/// cross the human boundary, and they are the only fields dropped. A pid and
842/// "someone else owns this" are already available to anything with shell
843/// access, so surfacing them costs nothing — and it makes a wholesale
844/// user-id-resolution failure diagnosable instead of silently returning an
845/// empty list.
846pub(crate) fn window_listing_entry(w: &AgentMuxWindowInfo) -> Value {
847    if w.tier.allowed() {
848        json!({
849            "pid": w.pid,
850            "title": w.title,
851            "exe_path": w.exe_path,
852            "is_self": w.is_self,
853            "is_agentmux": w.is_agentmux,
854            "tier": w.tier.label(),
855            "capturable": true,
856        })
857    } else {
858        json!({
859            "pid": w.pid,
860            "title": null,
861            "exe_path": null,
862            "is_self": w.is_self,
863            "is_agentmux": w.is_agentmux,
864            "tier": w.tier.label(),
865            "capturable": false,
866            "withheld_reason": "owned by a different OS user; title and exe_path withheld",
867        })
868    }
869}
870
871/// Audit trail for `DiscoverWindows` — reagent P1 on PR #2810: this tool
872/// discloses `exe_path` (a full filesystem path, typically embedding the OS
873/// username) for windows belonging to OTHER AgentMux instances/users on a
874/// shared machine — the exact same disclosure-across-a-human-boundary risk
875/// `audit_log_capture_window` above already exists to log, but this tool
876/// shipped with none. Same shape, same file (a single window-related audit
877/// trail is easier to review than two): best-effort, never blocks the
878/// tool's own result.
879pub(crate) fn audit_log_discover_windows(include_self: bool, include_foreign: bool, windows: &[Value]) {
880    let entry = serde_json::json!({
881        "timestamp": agentmux_common::time::now_secs_u64(),
882        "agent_id": agent_slug().unwrap_or_else(|_| "unknown".to_string()),
883        "tool": "DiscoverWindows",
884        // Both flags — reagentx P2 on PR #2845. `include_foreign` is the one
885        // that actually triggers this trail's reason for existing: it
886        // discloses non-AgentMux window titles and exe_paths. Recording only
887        // `include_self` left a reviewer scanning query strings unable to tell
888        // whether foreign disclosure was even requested, inferable only by
889        // picking through each entry's `is_agentmux` tag.
890        "query": format!("include_self={include_self} include_foreign={include_foreign}"),
891        "outcome": serde_json::json!({
892            "result": "success",
893            "window_count": windows.len(),
894            "windows": windows,
895        }),
896    });
897    append_window_audit_log_entry(&entry);
898}
899
900/// Shared append-only NDJSON writer for both window-tool audit trails above
901/// — best-effort (a logging failure must never break the tool itself),
902/// inside `capture_window_dir()` itself since `prune_old_captures`'s
903/// PNG-only extension filter already leaves a `.log` file in that same
904/// directory untouched, so this doesn't need (or want) its own directory.
905pub(crate) fn append_window_audit_log_entry(entry: &Value) {
906    let Ok(dir) = capture_window_dir() else {
907        return;
908    };
909    if std::fs::create_dir_all(&dir).is_err() {
910        return;
911    }
912    let line = format!("{entry}\n");
913    if let Ok(mut f) = std::fs::OpenOptions::new()
914        .create(true)
915        .append(true)
916        .open(dir.join("capture-window-audit.log"))
917    {
918        use std::io::Write;
919        let _ = f.write_all(line.as_bytes());
920    }
921}
922
923#[cfg(test)]
924#[path = "tests/window_capture_tests.rs"]
925mod tests;