chrome-agent 0.15.0

Browser automation for AI agents. Single binary, zero deps, CDP direct to Chrome.
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
use clap::ValueEnum;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use crate::cdp::client::{CdpClient, CdpClientError};
use crate::cdp::types::EvaluateResult;
use crate::session::{PageSession, SessionStore};

// CDP's upper bound for the `screenWidth` and `screenHeight` fields in `override_params()`.
const MAX_CDP_SCREEN_DIMENSION: u32 = 10_000_000;

/// Explicit metrics persisted for one named page.
///
/// There is deliberately no preset identifier here: CDP accepts concrete metrics, while the
/// familiar device catalog belongs to the `DevTools` frontend rather than the protocol.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceEmulation {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    pub width: u32,
    pub height: u32,
    #[serde(rename = "dpr", alias = "deviceScaleFactor")]
    pub device_scale_factor: f64,
    pub mobile: bool,
    pub touch: bool,
    pub orientation: DeviceOrientation,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum DeviceOrientation {
    Portrait,
    Landscape,
}

impl DeviceOrientation {
    pub fn parse(value: &str) -> Result<Self, String> {
        match value {
            "portrait" => Ok(Self::Portrait),
            "landscape" => Ok(Self::Landscape),
            _ => Err(format!(
                "unknown orientation {value:?}; use \"portrait\" or \"landscape\""
            )),
        }
    }

    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Portrait => "portrait",
            Self::Landscape => "landscape",
        }
    }
}

impl DeviceEmulation {
    pub fn new(
        label: Option<String>,
        width: u32,
        height: u32,
        device_scale_factor: f64,
        mobile: bool,
        touch: bool,
        orientation: Option<DeviceOrientation>,
    ) -> Result<Self, String> {
        if width == 0 || width > MAX_CDP_SCREEN_DIMENSION {
            return Err(format!(
                "width must be between 1 and {MAX_CDP_SCREEN_DIMENSION}"
            ));
        }
        if height == 0 || height > MAX_CDP_SCREEN_DIMENSION {
            return Err(format!(
                "height must be between 1 and {MAX_CDP_SCREEN_DIMENSION}"
            ));
        }
        if !device_scale_factor.is_finite() || device_scale_factor <= 0.0 {
            return Err("dpr must be a finite number greater than 0".into());
        }
        let label = label
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty());
        let orientation = orientation.unwrap_or(if width <= height {
            DeviceOrientation::Portrait
        } else {
            DeviceOrientation::Landscape
        });
        if matches!(orientation, DeviceOrientation::Portrait) && width > height {
            return Err("portrait orientation requires width no greater than height".into());
        }
        if matches!(orientation, DeviceOrientation::Landscape) && height >= width {
            return Err("landscape orientation requires width greater than height".into());
        }
        Ok(Self {
            label,
            width,
            height,
            device_scale_factor,
            mobile,
            touch,
            orientation,
        })
    }

    #[must_use]
    pub fn text_line(&self) -> String {
        let label = self
            .label
            .as_deref()
            .map_or_else(String::new, |label| format!(" label={label:?}"));
        format!(
            "Device emulation:{label} viewport={}x{} dpr={} mobile={} touch={} orientation={}",
            self.width,
            self.height,
            self.device_scale_factor,
            self.mobile,
            self.touch,
            self.orientation.as_str()
        )
    }

    fn override_params(&self) -> Value {
        let (orientation_type, angle) = match self.orientation {
            DeviceOrientation::Portrait => ("portraitPrimary", 0),
            DeviceOrientation::Landscape => ("landscapePrimary", 90),
        };
        // `screenWidth`, `screenHeight`, and `screenOrientation` are experimental CDP fields.
        // The basic viewport override does not update `window.screen` or the Screen Orientation
        // API, so omitting them would expose contradictory dimensions to the page.
        json!({
            "width": self.width,
            "height": self.height,
            "deviceScaleFactor": self.device_scale_factor,
            "mobile": self.mobile,
            "screenWidth": self.width,
            "screenHeight": self.height,
            "screenOrientation": {
                "type": orientation_type,
                "angle": angle,
            },
        })
    }
}

/// Apply the complete override set to one CDP target.
///
/// The three commands form one logical operation. If any command fails, [`clear_overrides`]
/// attempts every cleanup command before the original error is returned.
async fn apply_overrides(
    client: &CdpClient,
    config: &DeviceEmulation,
) -> Result<(), CdpClientError> {
    if let Err(error) = client
        .send(
            "Emulation.setDeviceMetricsOverride",
            config.override_params(),
        )
        .await
    {
        let _ = clear_overrides(client).await;
        return Err(error);
    }

    // The public option promises touch capability, not a hardware finger count, so enabled uses
    // CDP's default of one. Disabled omits `maxTouchPoints`; Chromium rejects an explicit zero.
    let touch_params = if config.touch {
        json!({"enabled": true, "maxTouchPoints": 1})
    } else {
        json!({"enabled": false})
    };
    if let Err(error) = client
        .send("Emulation.setTouchEmulationEnabled", touch_params)
        .await
    {
        let _ = clear_overrides(client).await;
        return Err(error);
    }

    // Chrome can leave `Input.dispatchMouseEvent` unanswered when this experimental switch is
    // enabled. Keep the browser-side conversion off and let chrome-agent's input dispatcher emit
    // explicit touch events instead; capability detection above remains target-scoped in CDP.
    if let Err(error) = client
        .send(
            "Emulation.setEmitTouchEventsForMouse",
            json!({"enabled": false, "configuration": "desktop"}),
        )
        .await
    {
        let _ = clear_overrides(client).await;
        return Err(error);
    }

    client.set_touch_emulation(config.touch);
    Ok(())
}

/// Clear every override set by [`apply_overrides`].
///
/// Each command is attempted even if an earlier one fails. The first error is returned only after
/// metrics, touch capability, and mouse-to-touch translation have all had a chance to reset.
pub async fn clear_overrides(client: &CdpClient) -> Result<(), CdpClientError> {
    client.set_touch_emulation(false);
    let emit = client
        .send(
            "Emulation.setEmitTouchEventsForMouse",
            json!({"enabled": false, "configuration": "desktop"}),
        )
        .await;
    let touch = client
        .send(
            "Emulation.setTouchEmulationEnabled",
            json!({"enabled": false}),
        )
        .await;
    let metrics = client
        .send("Emulation.clearDeviceMetricsOverride", json!({}))
        .await;

    emit.and(touch).and(metrics)
}

/// Make the emulated page Chrome's active target before touching its overrides.
///
/// Not cosmetic: the Screen Orientation API of a background target silently reports the ACTIVE
/// target's orientation, so without this an `emulate status` on the mobile page right after a
/// sibling page was created reads "landscape" off the sibling (the e2e suite pins this).
/// The cost is stated rather than hidden: one target per browser is foreground, so every command
/// on an emulated page backgrounds its siblings — their `visibilityState` flips and their rAF and
/// timers throttle until they are acted on in turn. That is what a browser does when a user
/// switches tabs, and side-by-side pages in one Chrome cannot both be foreground.
async fn activate_target(client: &CdpClient, target_id: &str) -> Result<(), CdpClientError> {
    client
        .send("Target.activateTarget", json!({"targetId": target_id}))
        .await
}

/// Apply and persist a configuration for one named page.
///
/// The session update is the commit point: it changes only after CDP accepts the complete override
/// set and the page reports its effective values. Callers persist that update before reporting
/// success. Before the commit, failure attempts to restore the configuration active at entry.
pub async fn apply_and_store(
    client: &CdpClient,
    store: &mut SessionStore,
    browser_name: &str,
    page_name: &str,
    config: DeviceEmulation,
) -> Result<Value, crate::BoxError> {
    let (previous, target_id) = match page_session(store, browser_name, page_name) {
        Ok(page) => (page.device_emulation.clone(), page.target_id.clone()),
        Err(error) => return Err(error),
    };
    activate_target(client, &target_id).await?;
    if let Err(error) = apply_overrides(client, &config).await {
        let message = error.to_string();
        restore_previous(client, previous.as_ref(), &message).await?;
        return Err(message.into());
    }
    let observed = match read_effective_metrics(client)
        .await
        .map_err(|error| error.to_string())
    {
        Ok(observed) => observed,
        Err(message) => {
            let _ = clear_overrides(client).await;
            restore_previous(client, previous.as_ref(), &message).await?;
            return Err(message.into());
        }
    };
    page_session_mut(store, browser_name, page_name)?.device_emulation = Some(config.clone());
    Ok(json!({"ok": true, "emulation": config, "effective": observed}))
}

/// Report both the requested configuration and the values currently observable by the page.
pub async fn status(
    client: &CdpClient,
    store: &SessionStore,
    browser_name: &str,
    page_name: &str,
) -> Result<Value, crate::BoxError> {
    let (config, target_id) = match page_session(store, browser_name, page_name) {
        Ok(page) => (page.device_emulation.clone(), page.target_id.clone()),
        Err(error) => return Err(error),
    };
    if let Some(config) = config {
        activate_target(client, &target_id).await?;
        let observed = read_effective_metrics(client).await?;
        Ok(json!({"ok": true, "emulation": config, "effective": observed}))
    } else {
        Ok(json!({"ok": true, "emulation": null}))
    }
}

/// Clear the target overrides before removing this page's persisted configuration.
pub async fn clear(
    client: &CdpClient,
    store: &mut SessionStore,
    browser_name: &str,
    page_name: &str,
) -> Result<Value, crate::BoxError> {
    let target_id = page_session(store, browser_name, page_name)?
        .target_id
        .clone();
    activate_target(client, &target_id).await?;
    clear_overrides(client).await?;
    page_session_mut(store, browser_name, page_name)?.device_emulation = None;
    Ok(json!({"ok": true, "emulation": null}))
}

/// Reapply the configuration attached to this exact browser and named-page pair.
///
/// CDP does not guarantee these overrides across session disconnects, whereas the named page
/// survives across CLI invocations. Every new connection therefore reapplies the stored values
/// before executing ordinary commands.
pub async fn reapply(
    client: &CdpClient,
    store: &SessionStore,
    browser_name: &str,
    page_name: &str,
) -> Result<(), crate::BoxError> {
    let (config, target_id) = match page_session(store, browser_name, page_name) {
        Ok(page) => (page.device_emulation.clone(), page.target_id.clone()),
        Err(error) => return Err(error),
    };
    if let Some(config) = config {
        activate_target(client, &target_id).await?;
        apply_overrides(client, &config).await?;
    }
    Ok(())
}

async fn restore_previous(
    client: &CdpClient,
    previous: Option<&DeviceEmulation>,
    original_error: &str,
) -> Result<(), crate::BoxError> {
    let Some(previous) = previous else {
        return Ok(());
    };
    apply_overrides(client, previous).await.map_err(|restore_error| {
        format!(
            "{original_error}; restoring the previous device configuration also failed: {restore_error}"
        )
        .into()
    })
}

fn page_session<'a>(
    store: &'a SessionStore,
    browser_name: &str,
    page_name: &str,
) -> Result<&'a PageSession, crate::BoxError> {
    store
        .browsers
        .get(browser_name)
        .and_then(|browser| browser.pages.get(page_name))
        .ok_or_else(|| "Current page disappeared from the session store".into())
}

fn page_session_mut<'a>(
    store: &'a mut SessionStore,
    browser_name: &str,
    page_name: &str,
) -> Result<&'a mut PageSession, crate::BoxError> {
    store
        .browsers
        .get_mut(browser_name)
        .and_then(|browser| browser.pages.get_mut(page_name))
        .ok_or_else(|| "Current page disappeared from the session store".into())
}

/// Format values returned by [`read_effective_metrics`] for human-readable status output.
#[must_use]
pub fn format_effective_metrics(value: &Value) -> String {
    format!(
        "Effective: viewport={}x{} screen={}x{} dpr={} touch_points={} coarse_pointer={} orientation={}",
        value["layoutViewport"]["width"],
        value["layoutViewport"]["height"],
        value["screen"]["width"],
        value["screen"]["height"],
        value["deviceScaleFactor"],
        value["touchPoints"],
        value["coarsePointer"],
        value["orientation"].as_str().unwrap_or("unknown"),
    )
}

/// Read the values observable by page script after Chromium has applied the overrides.
///
/// These values are measured rather than copied from the request so status exposes Chromium's
/// effective behavior, including any normalization performed by the browser.
async fn read_effective_metrics(client: &CdpClient) -> Result<Value, crate::BoxError> {
    // Deliberately omit `contextId`: device emulation belongs to the page target, while `frame`
    // binds ordinary eval calls to an iframe. Status must continue to describe the top document
    // without clearing that caller-selected frame binding.
    let result: EvaluateResult = client
        .call(
            "Runtime.evaluate",
            json!({
                "expression": r"({
                    layoutViewport: {width: innerWidth, height: innerHeight},
                    screen: {width: screen.width, height: screen.height},
                    deviceScaleFactor: devicePixelRatio,
                    touchPoints: navigator.maxTouchPoints,
                    coarsePointer: matchMedia('(pointer: coarse)').matches,
                    orientation: screen.orientation.type.startsWith('portrait')
                        ? 'portrait'
                        : 'landscape'
                })",
                "returnByValue": true,
                "awaitPromise": true,
            }),
        )
        .await?;

    if let Some(exception) = &result.exception_details {
        return Err(format!(
            "Evaluation error: {}",
            exception
                .exception
                .as_ref()
                .and_then(|error| error.description.as_deref())
                .unwrap_or(&exception.text)
        )
        .into());
    }

    Ok(result.result.value.unwrap_or_default())
}

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

    #[test]
    fn orientation_parser_matches_cli_casing() {
        assert_eq!(
            DeviceOrientation::parse("portrait"),
            Ok(DeviceOrientation::Portrait)
        );
        assert_eq!(
            DeviceOrientation::parse("landscape"),
            Ok(DeviceOrientation::Landscape)
        );
        assert!(DeviceOrientation::parse("Portrait").is_err());
    }

    #[test]
    fn orientation_defaults_from_dimensions() {
        let portrait = DeviceEmulation::new(None, 412, 915, 2.625, true, true, None).unwrap();
        let landscape = DeviceEmulation::new(None, 915, 412, 2.625, true, true, None).unwrap();
        assert_eq!(portrait.orientation, DeviceOrientation::Portrait);
        assert_eq!(landscape.orientation, DeviceOrientation::Landscape);
    }

    #[test]
    fn invalid_metrics_are_refused_before_cdp() {
        assert!(DeviceEmulation::new(None, 0, 915, 1.0, true, true, None).is_err());
        assert!(DeviceEmulation::new(None, 412, 0, 1.0, true, true, None).is_err());
        assert!(DeviceEmulation::new(None, 412, 915, 0.0, true, true, None).is_err());
        assert!(DeviceEmulation::new(None, 412, 915, f64::NAN, true, true, None).is_err());
        assert!(DeviceEmulation::new(None, 412, 915, f64::INFINITY, true, true, None).is_err());
        assert!(DeviceEmulation::new(None, 412, 915, 11.0, true, true, None).is_ok());
        assert!(
            DeviceEmulation::new(
                None,
                500,
                500,
                1.0,
                false,
                false,
                Some(DeviceOrientation::Landscape),
            )
            .is_err()
        );
    }

    #[test]
    fn requested_json_uses_the_same_dpr_name_as_pipe_input() {
        let config = DeviceEmulation::new(None, 390, 844, 3.0, true, true, None).unwrap();
        let value = serde_json::to_value(&config).unwrap();
        assert_eq!(value["dpr"], 3.0);
        assert!(value.get("deviceScaleFactor").is_none());

        let legacy: DeviceEmulation = serde_json::from_value(json!({
            "width": 390,
            "height": 844,
            "deviceScaleFactor": 2.0,
            "mobile": true,
            "touch": true,
            "orientation": "portrait"
        }))
        .unwrap();
        assert!((legacy.device_scale_factor - 2.0).abs() < f64::EPSILON);
    }

    #[test]
    fn effective_values_have_a_compact_human_form() {
        let text = format_effective_metrics(&json!({
            "layoutViewport": {"width": 412, "height": 915},
            "screen": {"width": 412, "height": 915},
            "deviceScaleFactor": 2.625,
            "touchPoints": 1,
            "coarsePointer": true,
            "orientation": "portrait",
        }));
        assert_eq!(
            text,
            "Effective: viewport=412x915 screen=412x915 dpr=2.625 touch_points=1 coarse_pointer=true orientation=portrait"
        );
    }

    #[test]
    fn labels_are_trimmed_and_empty_labels_are_omitted() {
        let named = DeviceEmulation::new(
            Some("  checkout phone  ".into()),
            412,
            915,
            1.0,
            true,
            true,
            None,
        )
        .unwrap();
        let unnamed =
            DeviceEmulation::new(Some("  ".into()), 412, 915, 1.0, true, true, None).unwrap();
        assert_eq!(named.label.as_deref(), Some("checkout phone"));
        assert_eq!(unnamed.label, None);
    }
}