agentmux_common/test_offscreen.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A test build that never shows a window on a real display.
5//!
6//! A tester starts an isolated build with `AGENTMUX_TEST_OFFSCREEN=1`. Every window the host
7//! creates then goes to [`ORIGIN`], far above every display, and nothing saves that place as the
8//! person's window position. Before this, the window opened on screen and a separate script
9//! raced to move it, and three times (2026-11-15) a tester's window showed on a shared screen.
10//!
11//! Only a dev or local build honours it ([`build_kind`](crate::build_kind)): a published release
12//! ignores the variable, so one inherited from a test instance's shell cannot hide a person's
13//! windows. The decision is the binary's, never the variable's alone.
14//!
15//! Windows and Linux/X11 place a window anywhere. Wayland cannot place a window at all, so there
16//! the flag does nothing and a tester must use X11 (or XWayland) for a test build.
17//!
18//! macOS cannot park a window: AppKit puts a shown window onto a display. There no window is ever
19//! shown at all (`test_offscreen_macos`): the process blocks every way to order one in, refuses to
20//! start if it cannot, and stops itself if one is on the on-screen list anyway.
21
22use crate::build_kind::{build_kind, BuildKind};
23
24/// The environment variable a launch sets.
25pub const ENV: &str = "AGENTMUX_TEST_OFFSCREEN";
26
27/// Where a window goes: far above every display, with its left edge at 0. Not the pool's corner
28/// (-32000, -32000): the host reads a window whose left edge is under -20000 as a spare pool window
29/// (`OFFSCREEN_POOL_THRESHOLD_X`), counts it as closed, and ends the app when it is the only one.
30pub const ORIGIN: (i32, i32) = (0, -32000);
31
32/// Whether a build of this `kind` started with `value` in [`ENV`] runs off-screen.
33pub fn requested_by(kind: BuildKind, value: Option<&str>) -> bool {
34 kind != BuildKind::Release && matches!(value.map(str::trim), Some("1" | "true" | "yes" | "on"))
35}
36
37/// True when this process creates every window off-screen. Read once.
38pub fn active() -> bool {
39 static ACTIVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
40 *ACTIVE.get_or_init(|| requested_by(build_kind(), std::env::var(ENV).ok().as_deref()))
41}
42
43/// The Chromium switches that keep a test build silent. A test run is driven on a machine a person
44/// works at, and an agent sound (turn done, waiting) through that person's speakers is as much an
45/// intrusion as a window on their screen. `mute-audio` zeroes every sample and `disable-audio-output`
46/// swaps the audio service's output for a fake one, so no device is opened; Chromium forwards both
47/// to the audio service process. Neither depends on the app's sound setting, so a build that has
48/// sounds on (the default) is silent anyway, in the app's own sounds and in any page a pane loads.
49pub const SILENT_SWITCHES: [&str; 2] = ["mute-audio", "disable-audio-output"];
50
51/// The phrase [`start_line`] carries when audio is off, which `scripts/offscreen-check.sh` looks for
52/// in a binary: a build from before this one honours the off-screen flag but plays sound.
53pub const AUDIO_OFF_MARK: &str = "audio stays off";
54
55fn silent_switches_for(off_screen: bool) -> &'static [&'static str] {
56 if off_screen {
57 &SILENT_SWITCHES
58 } else {
59 &[]
60 }
61}
62
63/// The switches the host adds to its command line: [`SILENT_SWITCHES`] in test window mode, none otherwise.
64pub fn silent_switches() -> &'static [&'static str] {
65 silent_switches_for(active())
66}
67
68/// A spare pool window waits parked with its left edge under this (the host's
69/// `OFFSCREEN_POOL_THRESHOLD_X`): it is already off-screen and stays there until it is promoted.
70pub const PARKED_BELOW_X: i32 = -20000;
71
72/// Where a window goes: `pos` unless `off_screen`; and then [`ORIGIN`], except a parked pool window.
73fn placed(off_screen: bool, pos: (i32, i32)) -> (i32, i32) {
74 if off_screen && pos.0 >= PARKED_BELOW_X {
75 ORIGIN
76 } else {
77 pos
78 }
79}
80
81/// `(x, y)` for a window that is off-screen, or `pos` when this process is not.
82pub fn place(pos: (i32, i32)) -> (i32, i32) {
83 placed(active(), pos)
84}
85
86/// A window rect `(x, y, width, height)` with its origin moved off-screen when this process is.
87pub fn place_rect((x, y, w, h): (i32, i32, i32, i32)) -> (i32, i32, i32, i32) {
88 let (x, y) = place((x, y));
89 (x, y, w, h)
90}
91
92/// The rect a window is created at when this process is off-screen, `None` when it is not: CEF
93/// places a window whose initial bounds are empty at (0, 0), so the window must say where it starts.
94/// `bounds` are the ones the window was asked for, if any (a spare pool window keeps its parking place).
95pub fn initial_rect(bounds: Option<(i32, i32, i32, i32)>) -> Option<(i32, i32, i32, i32)> {
96 active().then(|| place_rect(bounds.unwrap_or((0, 0, 1200, 800))))
97}
98
99/// Why a process must not start: it was asked to stay off-screen and cannot. On macOS AppKit moves a
100/// window onto a display when it is first shown and clamps every later move, so the only way is that
101/// no window is ever ordered in; `test_offscreen_macos` makes that so,
102/// and a process where it could not be made so refuses to start rather than show a window.
103#[cfg(target_os = "macos")]
104fn engage(process: &str) -> Result<(), String> {
105 crate::test_offscreen_macos::engage(process).map_err(|why| {
106 format!("{ENV}=1 needs every window kept from being shown on macOS, and that could not be set up ({why}). Nothing was started.")
107 })
108}
109
110#[cfg(not(target_os = "macos"))]
111fn engage(_process: &str) -> Result<(), String> {
112 Ok(())
113}
114
115/// `NSApplicationActivationPolicy` raw values.
116const ACTIVATION_REGULAR: isize = 0;
117const ACTIVATION_ACCESSORY: isize = 1;
118
119fn activation_policy(off_screen: bool) -> isize {
120 if off_screen {
121 ACTIVATION_ACCESSORY
122 } else {
123 ACTIVATION_REGULAR
124 }
125}
126
127/// The macOS activation policy the host sets: a normal Dock app, or an accessory app in test window
128/// mode (no Dock tile, no menu bar, never activated by itself), so a test run leaves no icon in the
129/// person's Dock and cannot take the keyboard from their frontmost app.
130pub fn macos_activation_policy() -> isize {
131 activation_policy(active())
132}
133
134/// The start of a process: when it runs off-screen it first makes sure it can (on macOS, that no
135/// window will ever be ordered in), and refuses (one line on stderr, exit status 2, nothing started)
136/// when it cannot. It then logs [`start_line`] if there is one.
137pub fn begin(process: &str) {
138 if active() {
139 if let Err(why) = engage(process) {
140 eprintln!("{process}: {why}");
141 std::process::exit(2);
142 }
143 }
144 if let Some(line) = start_line(process) {
145 tracing::info!("{line}");
146 }
147}
148
149/// One log line for the start of a process that says what the variable did, so a tester can
150/// tell a build that ignored it from one that honoured it. `None` when it was not set.
151pub fn start_line(process: &str) -> Option<String> {
152 let value = std::env::var(ENV).ok().filter(|v| !v.trim().is_empty())?;
153 Some(describe(process, &value, active(), cfg!(target_os = "macos")))
154}
155
156/// [`start_line`]'s text for a process that `active`ly runs in test window mode or ignored `value`.
157fn describe(process: &str, value: &str, active: bool, macos: bool) -> String {
158 if active && macos {
159 format!("{process}: test window mode: no window is ever shown (every way to order one in is blocked, a watchdog stops the process if one is on the screen) and its place is not saved; {AUDIO_OFF_MARK}: no sound is played and no audio output is opened")
160 } else if active {
161 format!("{process}: test window mode: every window is created off-screen at ({}, {}) and its place is not saved; {AUDIO_OFF_MARK}: no sound is played and no audio output is opened", ORIGIN.0, ORIGIN.1)
162 } else {
163 format!("{process}: {ENV}={value} ignored: only a dev or local build runs off-screen")
164 }
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170
171 #[test]
172 fn a_dev_or_local_build_honours_it() {
173 for kind in [BuildKind::Dev, BuildKind::Local] {
174 for v in ["1", "true", "yes", "on", " 1 "] {
175 assert!(requested_by(kind, Some(v)), "{kind:?} {v:?}");
176 }
177 }
178 }
179
180 #[test]
181 fn a_published_release_never_does() {
182 for v in ["1", "true", "yes", "on"] {
183 assert!(!requested_by(BuildKind::Release, Some(v)), "{v:?}");
184 }
185 }
186
187 #[test]
188 fn unset_empty_or_other_values_do_not() {
189 for v in [None, Some(""), Some("0"), Some("false"), Some("no"), Some("off"), Some("2")] {
190 assert!(!requested_by(BuildKind::Dev, v), "{v:?}");
191 }
192 }
193
194 #[test]
195 fn a_process_that_is_not_off_screen_gives_no_initial_rect() {
196 // The tests run without the variable set.
197 assert_eq!(initial_rect(None), None);
198 assert_eq!(initial_rect(Some((5, 6, 7, 8))), None);
199 assert_eq!(place_rect((10, 20, 30, 40)), (10, 20, 30, 40));
200 }
201
202 #[test]
203 fn a_test_build_is_an_accessory_app_and_a_normal_one_is_not() {
204 assert_eq!(activation_policy(true), 1);
205 assert_eq!(activation_policy(false), 0);
206 // The tests run without the variable set.
207 assert_eq!(macos_activation_policy(), 0);
208 }
209
210 #[test]
211 fn a_test_build_is_silent_and_a_normal_one_is_not_touched() {
212 assert_eq!(silent_switches_for(true), ["mute-audio", "disable-audio-output"]);
213 assert!(silent_switches_for(false).is_empty());
214 // The tests run without the variable set.
215 assert!(silent_switches().is_empty());
216 }
217
218 #[test]
219 fn the_start_line_says_audio_stays_off_only_when_the_build_runs_in_test_mode() {
220 for macos in [true, false] {
221 let on = describe("host", "1", true, macos);
222 assert!(on.contains(AUDIO_OFF_MARK), "{on}");
223 assert!(on.contains("test window mode"), "{on}");
224 let ignored = describe("host", "1", false, macos);
225 assert!(!ignored.contains(AUDIO_OFF_MARK), "{ignored}");
226 assert!(ignored.contains("ignored"), "{ignored}");
227 }
228 }
229
230 #[test]
231 fn a_spare_pool_window_keeps_its_parking_place() {
232 // The pool parks at (-32000, -32000), or that scaled by the display (-25600 at 80%).
233 for pos in [(-32000, -32000), (-25600, -25600), (-20001, 0)] {
234 assert_eq!(placed(true, pos), pos);
235 }
236 // Everything else goes to the origin, including a window at 0,0 and on a display left of the primary.
237 for pos in [(0, 0), (500, 300), (-1920, 0), (-20000, 0), (-19999, 0)] {
238 assert_eq!(placed(true, pos), ORIGIN, "{pos:?}");
239 }
240 assert_eq!(placed(false, (500, 300)), (500, 300));
241 }
242
243 #[test]
244 fn the_corner_is_far_outside_any_display() {
245 // Higher than any arrangement of displays reaches.
246 assert!(ORIGIN.1 <= -16000);
247 // And not under the host's pool threshold, which reads such a window as a spare one.
248 assert!(ORIGIN.0 > -20000);
249 }
250}