tauri-plugin-hasgard 0.2.1

Native automation and testing bridge for Tauri 2 applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! JSON-RPC handler for `screenshot_native`.
//!
//! The contract (path-only, `window_id`-targeted, atomic write, TCC-fallback
//! surfaced as metadata) is implemented in [`handle_screenshot`]. The handler
//! validates the request shape on every platform, then dispatches to the
//! macOS-only native capture pipeline; non-macOS callers always receive
//! `PERMISSION_DENIED` so the contract surface is identical on every host.

#[cfg(target_os = "macos")]
use std::path::Path;
#[cfg(target_os = "macos")]
use std::sync::atomic::{AtomicU64, Ordering};

use serde_json::Value;
#[cfg(target_os = "macos")]
use serde_json::json;

use crate::protocol::{RPC_INTERNAL_ERROR, RPC_INVALID_PARAMS, RpcError};

/// Domain error codes carried in the JSON-RPC `error.data.error` field.
///
/// Kept centralized so tests, the implementation, and the docs cannot drift.
pub(crate) mod codes {
    pub(crate) const INVALID_PARAMS: &str = "INVALID_PARAMS";
    pub(crate) const INVALID_OUTPUT_PATH: &str = "INVALID_OUTPUT_PATH";
    pub(crate) const UNSUPPORTED_FORMAT: &str = "UNSUPPORTED_FORMAT";
    #[cfg_attr(not(target_os = "macos"), allow(dead_code, reason = "only referenced by the macOS capture path"))]
    pub(crate) const WINDOW_NOT_FOUND: &str = "WINDOW_NOT_FOUND";
    #[cfg_attr(not(target_os = "macos"), allow(dead_code, reason = "only referenced by the macOS capture path"))]
    pub(crate) const CAPTURE_FAILED: &str = "CAPTURE_FAILED";
    pub(crate) const PERMISSION_DENIED: &str = "PERMISSION_DENIED";
}

/// Build a JSON-RPC error response with the given numeric code, message, and
/// domain error code carried in `data.error`. Extra structured detail can be
/// merged in via `extras`.
fn rpc_error(rpc_code: i32, domain: &str, message: impl Into<String>, extras: Value) -> RpcError {
    let message = message.into();
    let mut data = serde_json::Map::new();
    data.insert("error".to_owned(), Value::String(domain.to_owned()));
    data.insert("message".to_owned(), Value::String(message.clone()));
    if let Value::Object(obj) = extras {
        for (k, v) in obj {
            data.insert(k, v);
        }
    }
    RpcError { code: rpc_code, message, data: Some(Value::Object(data)) }
}

/// Parsed view of the `screenshot_native` request params with all field-level
/// validation already enforced by the validators below.
#[cfg_attr(not(target_os = "macos"), allow(dead_code, reason = "fields are read by the macOS-only capture pipeline"))]
struct ScreenshotRequest {
    window_id: u32,
    output_path: std::path::PathBuf,
}

/// Validate the request envelope. Order of checks is fixed by the contract:
///   1. `format` must be `"png"` if present (`UNSUPPORTED_FORMAT`)
///   2. `window_id` must be a u32 (`INVALID_PARAMS`)
///   3. `output_path` must be a string, absolute, with an existing parent
///      directory (`INVALID_OUTPUT_PATH`)
fn parse_request(params: Option<&Value>) -> Result<ScreenshotRequest, RpcError> {
    let obj = params.and_then(Value::as_object).ok_or_else(|| {
        rpc_error(
            RPC_INVALID_PARAMS,
            codes::INVALID_PARAMS,
            "screenshot requires an object params payload",
            Value::Null,
        )
    })?;

    // `format` is validated before `window_id` so callers using an unsupported
    // codec see the specific error rather than a generic missing-field one
    // when they also forgot `window_id`.
    let format = obj.get("format").and_then(Value::as_str).unwrap_or("png");
    if format != "png" {
        return Err(rpc_error(
            RPC_INVALID_PARAMS,
            codes::UNSUPPORTED_FORMAT,
            format!("format \"{format}\" is not supported in v1 (only \"png\")"),
            Value::Null,
        ));
    }

    let window_id_value = obj.get("window_id").ok_or_else(|| {
        rpc_error(RPC_INVALID_PARAMS, codes::INVALID_PARAMS, "screenshot requires a numeric \"window_id\"", Value::Null)
    })?;
    let window_id_u64 = window_id_value.as_u64().ok_or_else(|| {
        rpc_error(
            RPC_INVALID_PARAMS,
            codes::INVALID_PARAMS,
            "\"window_id\" must be a non-negative integer",
            Value::Null,
        )
    })?;
    let window_id = u32::try_from(window_id_u64).map_err(|_| {
        rpc_error(RPC_INVALID_PARAMS, codes::INVALID_PARAMS, "\"window_id\" overflows u32", Value::Null)
    })?;

    let output_path = parse_output_path(obj)?;

    Ok(ScreenshotRequest { window_id, output_path })
}

/// Pull `output_path` out of the request payload and apply the security
/// contract: must be a string, absolute, not a symlink, and live under an
/// existing parent directory.
fn parse_output_path(obj: &serde_json::Map<String, Value>) -> Result<std::path::PathBuf, RpcError> {
    let output_path_str = obj.get("output_path").and_then(Value::as_str).ok_or_else(|| {
        rpc_error(
            RPC_INVALID_PARAMS,
            codes::INVALID_OUTPUT_PATH,
            "screenshot requires a string \"output_path\"",
            Value::Null,
        )
    })?;
    let output_path = std::path::PathBuf::from(output_path_str);
    if !output_path.is_absolute() {
        return Err(rpc_error(
            RPC_INVALID_PARAMS,
            codes::INVALID_OUTPUT_PATH,
            format!("output_path must be absolute, got \"{}\"", output_path.display()),
            Value::Null,
        ));
    }
    // A pre-existing symlink at `output_path` is a footgun: the atomic rename
    // would replace the symlink itself (so the link's target is unchanged), but
    // a future read-back through the same path follows the link to wherever the
    // attacker last pointed it. Refusing symlinks here makes the contract
    // ("output_path is the file on disk") hold for the caller.
    if output_path.is_symlink() {
        return Err(rpc_error(
            RPC_INVALID_PARAMS,
            codes::INVALID_OUTPUT_PATH,
            format!("output_path must not be a symlink: {}", output_path.display()),
            Value::Null,
        ));
    }
    if output_path.is_dir() {
        return Err(rpc_error(
            RPC_INVALID_PARAMS,
            codes::INVALID_OUTPUT_PATH,
            format!("output_path must be a file path, got directory: {}", output_path.display()),
            Value::Null,
        ));
    }
    let parent = output_path.parent().ok_or_else(|| {
        rpc_error(
            RPC_INVALID_PARAMS,
            codes::INVALID_OUTPUT_PATH,
            format!("output_path \"{}\" has no parent directory", output_path.display()),
            Value::Null,
        )
    })?;
    // Refuse to create parent directories: an absolute path beneath a
    // non-existent directory could be an attacker-controlled prefix on a
    // shared host. Caller must pre-create the destination directory.
    if !parent.as_os_str().is_empty() && !parent.is_dir() {
        return Err(rpc_error(
            RPC_INVALID_PARAMS,
            codes::INVALID_OUTPUT_PATH,
            format!("output_path parent directory does not exist: {}", parent.display()),
            Value::Null,
        ));
    }
    Ok(output_path)
}

/// Top-level entry point used by the JSON-RPC dispatcher.
///
/// Returns the contract-shaped success result or a structured `RpcError`. The
/// success result fills the response with `output_path`, `window_id`, pixel
/// dimensions, `scale_factor`, `byte_size`, the chosen `backend`, and the
/// `tcc_denied` flag.
pub(crate) async fn handle_screenshot(params: Option<&Value>) -> Result<Value, RpcError> {
    let req = parse_request(params)?;

    #[cfg(target_os = "macos")]
    {
        tokio::task::spawn_blocking(move || run_macos(req)).await.map_err(|join_err| {
            rpc_error(
                RPC_INTERNAL_ERROR,
                codes::CAPTURE_FAILED,
                format!("screenshot capture task did not complete: {join_err}"),
                Value::Null,
            )
        })?
    }

    #[cfg(not(target_os = "macos"))]
    {
        // The validators above always run so non-macOS callers see contract
        // violations (bad format, relative path) ahead of the platform error.
        let _ = req;
        Err(rpc_error(
            RPC_INTERNAL_ERROR,
            codes::PERMISSION_DENIED,
            "screenshot is only available on macOS in this release",
            Value::Null,
        ))
    }
}

#[cfg(target_os = "macos")]
fn run_macos(req: ScreenshotRequest) -> Result<Value, RpcError> {
    use super::{
        EnumeratedLayerZeroWindows, ScreenshotBackend, ScreenshotError, WindowBounds, enumerate_layer_zero_windows,
        selected_backend,
    };

    let ScreenshotRequest { window_id, output_path } = req;

    // Single pass over the on-screen window list collects both the
    // `available_windows` payload for WINDOW_NOT_FOUND and the target's
    // bounds — one CGWindowListCopyWindowInfo snapshot instead of two,
    // which also closes the TOCTOU between the two former calls.
    let EnumeratedLayerZeroWindows { available: discovered, target_bounds } = enumerate_layer_zero_windows(window_id)
        .map_err(|err| match err {
        ScreenshotError::PlatformUnsupported => rpc_error(
            RPC_INTERNAL_ERROR,
            codes::PERMISSION_DENIED,
            "screenshot is only available on macOS in this release",
            Value::Null,
        ),
        ScreenshotError::CaptureFailed { message } => rpc_error(
            RPC_INTERNAL_ERROR,
            codes::CAPTURE_FAILED,
            format!("failed to enumerate windows: {message}"),
            Value::Null,
        ),
    })?;

    if target_bounds.is_none() {
        return Err(rpc_error(
            RPC_INVALID_PARAMS,
            codes::WINDOW_NOT_FOUND,
            format!("window_id {window_id} not found"),
            json!({
                "available_windows": render_available_windows(&discovered),
            }),
        ));
    }

    let tmp_path = tmp_path_for(&output_path);

    let primary = selected_backend();
    let (backend, tcc_denied) = capture_with_fallback(primary, window_id, &tmp_path)?;

    let metadata = match read_png_metadata(&tmp_path) {
        Ok(m) => m,
        Err(err) => {
            cleanup_tmp(&tmp_path);
            return Err(err);
        }
    };

    let logical_bounds = target_bounds.unwrap_or(WindowBounds { width: 0.0, height: 0.0 });
    let scale_factor = compute_scale_factor(metadata.width, logical_bounds);

    if let Err(err) = std::fs::rename(&tmp_path, &output_path) {
        cleanup_tmp(&tmp_path);
        return Err(rpc_error(
            RPC_INTERNAL_ERROR,
            codes::CAPTURE_FAILED,
            format!("failed to rename {} to {}: {err}", tmp_path.display(), output_path.display()),
            Value::Null,
        ));
    }

    // The other `ScreenshotBackend` variants never reach this point because
    // the dispatcher in `capture_with_fallback` already maps them to error
    // responses. The match is exhaustive so a future backend variant forces
    // an explicit decision here instead of silently flowing into a fallback.
    let backend_label = match backend {
        ScreenshotBackend::ScreencaptureProbe => "screencapture",
        ScreenshotBackend::CgWindowList => "cgwindow",
        ScreenshotBackend::WkWebViewSnapshot | ScreenshotBackend::PlatformUnsupported => {
            unreachable!("capture_with_fallback returns Err for these variants")
        }
    };
    Ok(json!({
        "output_path": output_path.display().to_string(),
        "window_id": window_id,
        "width": metadata.width,
        "height": metadata.height,
        "scale_factor": scale_factor,
        "byte_size": metadata.byte_size,
        "backend": backend_label,
        "tcc_denied": tcc_denied,
    }))
}

#[cfg(target_os = "macos")]
fn render_available_windows(discovered: &[super::DiscoveredWindow]) -> Vec<Value> {
    discovered
        .iter()
        .map(|w| {
            json!({
                "window_id": w.window_id,
                "owner": w.owner,
                "title": w.title,
                "layer": w.layer,
            })
        })
        .collect()
}

#[cfg(target_os = "macos")]
struct PngMetadata {
    width: u32,
    height: u32,
    byte_size: u64,
}

/// Monotonic counter appended to the tmp filename so two concurrent captures
/// from the same process targeting the same final path never collide on disk.
#[cfg(target_os = "macos")]
static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Compute the temp-write target alongside the final output path. Combining
/// the pid (cross-process disambiguator) with a process-local atomic counter
/// (intra-process disambiguator) guarantees a fresh tmp filename even when
/// multiple captures race on the same final path.
#[cfg(target_os = "macos")]
fn tmp_path_for(final_path: &Path) -> std::path::PathBuf {
    let mut name = final_path.file_name().map(std::ffi::OsString::from).unwrap_or_default();
    let counter = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
    name.push(format!(".tmp.{}.{counter}.png", std::process::id()));
    final_path.with_file_name(name)
}

/// Remove the tmp file if it exists. Errors during cleanup do not propagate —
/// the caller is already returning the original capture failure — but they are
/// logged so a lingering tmp file does not vanish silently from operator view.
#[cfg(target_os = "macos")]
fn cleanup_tmp(path: &Path) {
    if let Err(err) = std::fs::remove_file(path)
        && err.kind() != std::io::ErrorKind::NotFound
    {
        tracing::warn!(
            tmp_path = %path.display(),
            error = %err,
            "failed to remove tauri-hasgard screenshot tmp file",
        );
    }
}

#[cfg(target_os = "macos")]
fn capture_with_fallback(
    primary: super::ScreenshotBackend, window_id: u32, tmp_path: &Path,
) -> Result<(super::ScreenshotBackend, bool), RpcError> {
    use super::{ScreenshotBackend, capture_cgwindow, capture_screencapture};

    match primary {
        ScreenshotBackend::ScreencaptureProbe => {
            match capture_screencapture(window_id, tmp_path) {
                Ok(()) => Ok((ScreenshotBackend::ScreencaptureProbe, false)),
                Err(primary_err) => {
                    // TCC was granted at probe time but the per-window capture
                    // still failed. Try the CGWindow fallback so the caller
                    // does not lose the artifact when permission was revoked
                    // between probe and call.
                    match capture_cgwindow(window_id, tmp_path) {
                        Ok(()) => Ok((ScreenshotBackend::CgWindowList, true)),
                        Err(fallback_err) => {
                            cleanup_tmp(tmp_path);
                            Err(rpc_error(
                                RPC_INTERNAL_ERROR,
                                codes::CAPTURE_FAILED,
                                format!(
                                    "screencapture failed ({primary_err}) and CGWindow fallback also failed ({fallback_err})"
                                ),
                                Value::Null,
                            ))
                        }
                    }
                }
            }
        }
        ScreenshotBackend::CgWindowList => match capture_cgwindow(window_id, tmp_path) {
            Ok(()) => Ok((ScreenshotBackend::CgWindowList, true)),
            Err(err) => {
                cleanup_tmp(tmp_path);
                Err(rpc_error(
                    RPC_INTERNAL_ERROR,
                    codes::CAPTURE_FAILED,
                    format!("CGWindow capture failed: {err}"),
                    Value::Null,
                ))
            }
        },
        ScreenshotBackend::WkWebViewSnapshot | ScreenshotBackend::PlatformUnsupported => Err(rpc_error(
            RPC_INTERNAL_ERROR,
            codes::PERMISSION_DENIED,
            "screenshot is only available on macOS in this release",
            Value::Null,
        )),
    }
}

#[cfg(target_os = "macos")]
fn read_png_metadata(path: &Path) -> Result<PngMetadata, RpcError> {
    let metadata = std::fs::metadata(path).map_err(|err| {
        rpc_error(
            RPC_INTERNAL_ERROR,
            codes::CAPTURE_FAILED,
            format!("failed to stat captured PNG {}: {err}", path.display()),
            Value::Null,
        )
    })?;
    let byte_size = metadata.len();

    // `ImageReader::into_dimensions` parses the PNG header (IHDR chunk) only —
    // a few hundred bytes — instead of decoding the entire raster. For a 4K
    // Retina capture this avoids ~33 MiB of pointless RGBA allocation just to
    // read width/height for the response payload.
    let reader = image::ImageReader::open(path).map_err(|err| {
        rpc_error(
            RPC_INTERNAL_ERROR,
            codes::CAPTURE_FAILED,
            format!("failed to open captured PNG {}: {err}", path.display()),
            Value::Null,
        )
    })?;
    let (width, height) = reader.into_dimensions().map_err(|err| {
        rpc_error(
            RPC_INTERNAL_ERROR,
            codes::CAPTURE_FAILED,
            format!("failed to read PNG dimensions from {}: {err}", path.display()),
            Value::Null,
        )
    })?;
    Ok(PngMetadata { width, height, byte_size })
}

/// Derive `scale_factor` by dividing pixel width by logical (point) width.
/// Falls back to 1.0 when the logical bounds are unknown or zero so the
/// response never returns NaN/Inf.
#[cfg(target_os = "macos")]
fn compute_scale_factor(pixel_width: u32, logical: super::WindowBounds) -> f32 {
    if logical.width <= 0.0 {
        return 1.0;
    }
    let scale = f64::from(pixel_width) / logical.width;
    if scale.is_finite() && scale > 0.0 {
        // Round to 2 decimal places to avoid `2.00000003` artifacts when the
        // CGWindowBounds Width carries float noise. Strict-pixel-diff harnesses
        // tag artifacts by this value, so stability matters more than exact
        // bit-for-bit fidelity. Truncation to f32 is intentional: Retina scale
        // factors land in a small finite range (1.0 / 2.0 / 3.0) that f32
        // represents losslessly.
        let rounded = (scale * 100.0).round() / 100.0;
        #[allow(clippy::cast_possible_truncation, reason = "Retina scale factors fit in f32 without loss")]
        let scale_f32 = rounded as f32;
        scale_f32
    } else {
        1.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn err_data(err: &RpcError) -> &Value {
        err.data.as_ref().expect("error data present")
    }

    #[tokio::test]
    async fn rejects_missing_window_id() {
        let params = json!({"output_path": "/tmp/x.png"});
        let err = handle_screenshot(Some(&params)).await.expect_err("must reject missing window_id");
        assert_eq!(err.code, RPC_INVALID_PARAMS);
        assert!(err.message.contains("window_id"), "message must mention window_id, got: {}", err.message);
    }

    #[tokio::test]
    async fn rejects_relative_output_path() {
        let params = json!({"window_id": 42_u32, "output_path": "relative/path.png"});
        let err = handle_screenshot(Some(&params)).await.expect_err("must reject relative output_path");
        assert_eq!(err.code, RPC_INVALID_PARAMS);
        assert_eq!(err_data(&err).get("error").and_then(Value::as_str), Some(codes::INVALID_OUTPUT_PATH));
    }

    #[tokio::test]
    async fn rejects_nonexistent_parent_directory() {
        let params = json!({
            "window_id": 42_u32,
            "output_path": "/tauri-hasgard-test-no-such-dir-9f3a/x.png",
        });
        let err = handle_screenshot(Some(&params)).await.expect_err("must reject missing parent dir");
        assert_eq!(err.code, RPC_INVALID_PARAMS);
        assert_eq!(err_data(&err).get("error").and_then(Value::as_str), Some(codes::INVALID_OUTPUT_PATH));
    }

    #[tokio::test]
    async fn rejects_directory_output_path() {
        let params = json!({
            "window_id": 42_u32,
            "output_path": std::env::temp_dir().display().to_string(),
        });
        let err = handle_screenshot(Some(&params)).await.expect_err("must reject directory output_path");
        assert_eq!(err.code, RPC_INVALID_PARAMS);
        assert_eq!(err_data(&err).get("error").and_then(Value::as_str), Some(codes::INVALID_OUTPUT_PATH));
    }

    #[tokio::test]
    async fn rejects_unsupported_format() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("tauri-hasgard-test-screenshot-{}.png", std::process::id()));
        let params = json!({
            "window_id": 42_u32,
            "output_path": path.display().to_string(),
            "format": "jpeg",
        });
        let err = handle_screenshot(Some(&params)).await.expect_err("must reject jpeg format");
        assert_eq!(err.code, RPC_INVALID_PARAMS);
        assert_eq!(err_data(&err).get("error").and_then(Value::as_str), Some(codes::UNSUPPORTED_FORMAT));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn tmp_path_keeps_png_extension_for_image_reader() {
        let path = Path::new("/tmp/tauri-hasgard-shot.png");
        let tmp = tmp_path_for(path);
        assert_eq!(tmp.extension().and_then(|ext| ext.to_str()), Some("png"));
        assert!(tmp.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.contains(".tmp.")));
    }

    #[cfg(target_os = "macos")]
    #[tokio::test]
    async fn window_not_found_returns_available_list() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("tauri-hasgard-test-screenshot-not-found-{}.png", std::process::id()));
        // 0 is `kCGNullWindowID` per CoreGraphics and never identifies a real
        // window, so this is the most reliably-missing window_id we can pick
        // without touching the host's display state.
        let params = json!({
            "window_id": u32::MAX,
            "output_path": path.display().to_string(),
        });
        let err = handle_screenshot(Some(&params)).await.expect_err("must reject unknown window_id");
        assert_eq!(err.code, RPC_INVALID_PARAMS);
        assert_eq!(err_data(&err).get("error").and_then(Value::as_str), Some(codes::WINDOW_NOT_FOUND));
        let list =
            err_data(&err).get("available_windows").and_then(Value::as_array).expect("available_windows present");
        // On a headless CI runner the list may be empty; the contract only
        // requires the key, not a minimum length. Assert shape on any entry
        // that does come back so the discovery payload stays stable.
        if let Some(first) = list.first() {
            assert!(first.get("window_id").is_some());
            assert!(first.get("owner").is_some());
            assert!(first.get("title").is_some());
            assert!(first.get("layer").is_some());
        }
    }
}