ferridriver 0.4.0

Browser automation in Rust with a Playwright-compatible API. Four pluggable backends: CDP pipe, CDP WebSocket, Playwright WebKit, Firefox BiDi.
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
//! `BrowserContext` -- isolated browser environment with pages, cookies, and logs.
//!
//! Mirrors Playwright's `BrowserContext` exactly:
//! - Owns pages (`Vec<AnyPage>`)
//! - Owns cookies (via any page in the context)
//! - Owns console/network/dialog logs
//! - Created by `Browser.new_context()`
//! - Pages are created by `context.new_page()`

use crate::backend::{AnyPage, CookieData};
use crate::error::Result;
use crate::network::Request;
use crate::page::Page;
use crate::state::SessionKey;
use arc_swap::ArcSwap;
use rustc_hash::FxHashMap as HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

/// A dismissed dialog event (alert, confirm, prompt).
#[derive(Debug, Clone, serde::Serialize)]
pub struct DialogEvent {
  pub dialog_type: String,
  pub message: String,
  pub action: String,
}

/// Isolated browser context. Directly holds pages, cookies, and event logs.
/// This IS the state -- not a wrapper around some other struct.
/// Stored in `BrowserState`'s context map.
pub struct BrowserContext {
  /// Pages in this context.
  pub pages: Vec<AnyPage>,
  /// Active page index.
  pub active_page_idx: usize,
  /// Element ref map for accessibility snapshots (wait-free reads via `ArcSwap`).
  pub ref_map: Arc<ArcSwap<HashMap<String, i64>>>,
  /// Console messages collected from page events.
  pub console_log: Arc<RwLock<Vec<crate::console_message::ConsoleMessage>>>,
  /// Network requests collected from page events. Live `Request`
  /// references — listeners may inspect the stored object's response /
  /// failure via the `Request` async accessors.
  pub network_log: Arc<RwLock<Vec<Request>>>,
  /// Dialog events.
  pub dialog_log: Arc<RwLock<Vec<DialogEvent>>>,
  /// Context name (unique identifier).
  name: String,
  /// CDP browser context ID (for `Target.disposeBrowserContext` on close).
  /// None for the default context.
  pub cdp_context_id: Option<String>,
}

impl BrowserContext {
  /// Create a new empty context.
  pub(crate) fn new(name: String) -> Self {
    Self {
      pages: Vec::new(),
      active_page_idx: 0,
      ref_map: Arc::new(ArcSwap::from_pointee(HashMap::default())),
      console_log: Arc::new(RwLock::new(Vec::new())),
      network_log: Arc::new(RwLock::new(Vec::new())),
      dialog_log: Arc::new(RwLock::new(Vec::new())),
      name,
      cdp_context_id: None,
    }
  }

  /// Context name.
  #[must_use]
  pub fn name(&self) -> &str {
    &self.name
  }

  /// Get the active page in this context.
  #[must_use]
  pub fn active_page(&self) -> Option<&AnyPage> {
    self.pages.get(self.active_page_idx)
  }

  // -- Cookies (operate on active page) ------------------------------------

  /// Get all cookies in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if cookies cannot be retrieved from the active page.
  pub async fn cookies(&self) -> Result<Vec<CookieData>> {
    if let Some(page) = self.active_page() {
      page.get_cookies().await
    } else {
      Ok(Vec::new())
    }
  }

  /// Add cookies to this context.
  ///
  /// # Errors
  ///
  /// Returns an error if no page exists or if setting a cookie fails.
  pub async fn add_cookies(&self, cookies: Vec<CookieData>) -> Result<()> {
    let page = self.active_page().ok_or(crate::error::FerriError::NotConnected)?;
    for cookie in cookies {
      page.set_cookie(cookie).await?;
    }
    Ok(())
  }

  /// Clear all cookies in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if clearing cookies fails on the active page.
  pub async fn clear_cookies(&self) -> Result<()> {
    if let Some(page) = self.active_page() {
      page.clear_cookies().await?;
    }
    Ok(())
  }

  /// Delete specific cookies by name and optional domain.
  ///
  /// # Errors
  ///
  /// Returns an error if reading or re-setting cookies fails.
  pub async fn delete_cookie(&self, name: &str, domain: Option<&str>) -> Result<()> {
    let cookies = self.cookies().await?;
    if let Some(page) = self.active_page() {
      page.clear_cookies().await?;
      for cookie in cookies {
        let name_matches = cookie.name == name;
        let domain_matches = domain.is_none_or(|d| cookie.domain == d);
        if !(name_matches && domain_matches) {
          page.set_cookie(cookie).await?;
        }
      }
    }
    Ok(())
  }

  // -- Console/network/dialog log access -----------------------------------

  /// Get console messages, optionally filtered by level.
  pub async fn console_messages(
    &self,
    level: Option<&str>,
    limit: usize,
  ) -> Vec<crate::console_message::ConsoleMessage> {
    let msgs = self.console_log.read().await;
    msgs
      .iter()
      .filter(|m| level.is_none_or(|l| l == "all" || m.type_str() == l))
      .rev()
      .take(limit)
      .cloned()
      .collect::<Vec<_>>()
      .into_iter()
      .rev()
      .collect()
  }

  /// Get network requests (most recent `limit` in chronological order).
  pub async fn network_requests(&self, limit: usize) -> Vec<Request> {
    let reqs = self.network_log.read().await;
    reqs
      .iter()
      .rev()
      .take(limit)
      .cloned()
      .collect::<Vec<_>>()
      .into_iter()
      .rev()
      .collect()
  }

  /// Get dialog events.
  pub async fn dialog_messages(&self, limit: usize) -> Vec<DialogEvent> {
    let msgs = self.dialog_log.read().await;
    let start = msgs.len().saturating_sub(limit);
    msgs[start..].to_vec()
  }
}

// -- ContextRef: handle for the high-level Browser API -----------------------

use crate::state::BrowserState;

/// Handle to a browser context. Created by `Browser::new_context()` / `default_context()`.
/// Provides the Playwright-compatible context API by delegating to `BrowserState`.
#[derive(Clone)]
pub struct ContextRef {
  pub(crate) state: Arc<RwLock<BrowserState>>,
  pub(crate) name: Arc<str>,
  /// Pre-parsed session key (avoids re-parsing on every operation).
  pub(crate) key: SessionKey,
  /// Default timeout for actions in this context (ms). 0 = no override.
  /// `Arc<AtomicU64>` so the Playwright `setDefaultTimeout` setter can
  /// mutate through a shared `&self` handle (the `QuickJS` binding holds
  /// the context behind an `Arc` and cannot offer `&mut self`).
  default_timeout_ms: Arc<std::sync::atomic::AtomicU64>,
  /// Default navigation timeout in this context (ms). 0 = no override.
  /// Shared via `Arc<AtomicU64>` for the same reason as
  /// [`Self::default_timeout_ms`].
  default_navigation_timeout_ms: Arc<std::sync::atomic::AtomicU64>,
  /// Context-scoped event emitter. Shared across every `ContextRef`
  /// clone with the same composite session key via the per-state
  /// [`BrowserState::get_or_create_context_events`] registry — without
  /// this, `browser.defaultContext()` called twice would hand out two
  /// separate emitters and `context.on('weberror', cb)` would silently
  /// miss events dispatched via the per-page bridge installed on a
  /// page created through a different `ContextRef` instance.
  events: crate::events::ContextEventEmitter,
  /// Parent browser handle. `Some` when the context was created from a
  /// [`crate::Browser`] (`browser.newContext()` / `browser.defaultContext()`);
  /// surfaced by [`Self::browser`] to mirror Playwright's
  /// `browserContext.browser(): Browser | null`. `Browser` is a cheap
  /// `Arc`-handle clone, so this carries no protocol cost.
  browser: Option<crate::Browser>,
  /// Shared closed-flag for this context's composite key (see
  /// [`BrowserState::context_closed`]). `false` from handle creation
  /// until [`Self::close`] flips it `true`; backs [`Self::is_closed`].
  closed: Arc<std::sync::atomic::AtomicBool>,
}

impl ContextRef {
  pub fn new(state: Arc<RwLock<BrowserState>>, name: String) -> Self {
    let key = SessionKey::parse(&name);
    // Look up (or initialise) the shared emitter for this composite
    // key. Uses `try_read` because `ContextRef::new` must be callable
    // from sync contexts (e.g. `Browser::default_context`). In the
    // common case the state lock is uncontended at construction time;
    // if `try_read` fails (concurrent writer) we fall back to a
    // transient per-instance emitter so the handle is still usable —
    // event delivery would then be scoped to this `ContextRef` clone
    // only, matching the old behaviour. `get_or_create_context_events`
    // itself uses a `std::sync::Mutex` so it doesn't need the tokio
    // read guard to stay alive beyond the call.
    let (events, closed) = match state.try_read() {
      Ok(s) => (
        s.get_or_create_context_events(&key.to_composite()),
        s.get_or_create_context_closed(&key.to_composite()),
      ),
      Err(_) => (
        crate::events::ContextEventEmitter::new(),
        Arc::new(std::sync::atomic::AtomicBool::new(false)),
      ),
    };
    Self {
      state,
      name: Arc::from(name),
      key,
      default_timeout_ms: Arc::new(std::sync::atomic::AtomicU64::new(0)),
      default_navigation_timeout_ms: Arc::new(std::sync::atomic::AtomicU64::new(0)),
      events,
      browser: None,
      closed,
    }
  }

  /// Attach the parent [`crate::Browser`] handle so [`Self::browser`]
  /// returns it. Called by [`crate::Browser::new_context`] and
  /// [`crate::Browser::default_context`] right after construction.
  #[must_use]
  pub(crate) fn with_browser(mut self, browser: crate::Browser) -> Self {
    self.browser = Some(browser);
    self
  }

  /// Parent browser handle, or `None` for a context not created from a
  /// [`crate::Browser`]. Mirrors Playwright's
  /// `browserContext.browser(): Browser | null`
  /// (`/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:290`).
  #[must_use]
  pub fn browser(&self) -> Option<&crate::Browser> {
    self.browser.as_ref()
  }

  /// Whether this context has been closed. Mirrors Playwright's
  /// `browserContext.isClosed(): boolean`
  /// (`/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:298`).
  /// `false` from handle creation until [`Self::close`] is called (or the
  /// underlying browser instance is shut down / disconnected), matching
  /// Playwright's `_closingStatus !== 'none'`. Uses the shared
  /// [`BrowserState::context_closed`] flag so a `close()` on one handle is
  /// seen by every clone with the same composite key.
  #[must_use]
  pub fn is_closed(&self) -> bool {
    if self.closed.load(std::sync::atomic::Ordering::SeqCst) {
      return true;
    }
    // A disconnected browser implicitly closes every context.
    self.browser.as_ref().is_some_and(|b| !b.is_connected())
  }

  /// Context-scoped event emitter. Cheap to clone.
  #[must_use]
  pub fn events(&self) -> &crate::events::ContextEventEmitter {
    &self.events
  }

  /// Context name.
  #[must_use]
  pub fn name(&self) -> &str {
    &self.name
  }

  /// Create a new page in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if page creation fails.
  pub async fn new_page(&self) -> Result<Arc<Page>> {
    {
      let mut state = self.state.write().await;
      Box::pin(state.ensure_instance(&self.key.instance)).await?;
    }

    // Read the (optional) `BrowserContextOptions` bag before the open —
    // a custom `viewport` (or `null` viewport) has to be known up-front
    // so the backend opens the page at the right size rather than
    // resizing afterwards.
    let ctx_opts = {
      let state = self.state.read().await;
      state.get_context_options(&self.key.to_composite())
    };
    let resolved_viewport = match &ctx_opts {
      Some(opts) => match opts.viewport {
        crate::options::ViewportOption::Null => None,
        crate::options::ViewportOption::Default | crate::options::ViewportOption::Size { .. } => {
          opts.resolved_viewport()
        },
      },
      None => None,
    };

    let plan = {
      let state = self.state.read().await;
      state.page_open_plan(&self.key)?
    };
    // Override the state's default viewport with the options bag's
    // resolved viewport when the caller supplied one. `ViewportOption::Null`
    // drops the default entirely (matches Playwright's `viewport: null`
    // opt-out).
    let effective_viewport = if ctx_opts
      .as_ref()
      .is_some_and(|o| o.viewport != crate::options::ViewportOption::Default)
    {
      resolved_viewport
    } else {
      plan.viewport.clone()
    };

    let (any_page, browser_context_id) = if &*self.key.context == "default" {
      (
        Box::pin(plan.browser.new_page(
          "about:blank",
          plan.browser_context_id.as_deref(),
          effective_viewport.as_ref(),
        ))
        .await?,
        None,
      )
    } else if let Some(existing_ctx_id) = plan.browser_context_id.clone() {
      (
        Box::pin(
          plan
            .browser
            .new_page("about:blank", Some(&existing_ctx_id), effective_viewport.as_ref()),
        )
        .await?,
        Some(existing_ctx_id),
      )
    } else {
      // Per-context options flow through:
      //   * CDP: `Target.createBrowserContext({ proxyServer, proxyBypassList })`
      //     (`crBrowser.ts::doCreateNewContext`)
      //   * BiDi: `browser.createUserContext({ proxy })`
      //     (`bidiBrowser.ts::doCreateNewContext`)
      //   * webkit: `Playwright.createContext` + `Playwright.setLanguages`
      //     (`wkBrowser.ts::WKBrowserContext.initialize`), then per-page
      //     overrides applied in `attach()` before the about:blank document
      //     becomes scriptable.
      let ctx_id = plan.browser.new_context(ctx_opts.as_ref()).await?;
      let page = Box::pin(
        plan
          .browser
          .new_page("about:blank", Some(&ctx_id), effective_viewport.as_ref()),
      )
      .await?;
      (page, Some(ctx_id))
    };

    {
      let mut state = self.state.write().await;
      state.register_opened_page(&self.key, any_page.clone(), browser_context_id)?;
    }

    // `Page::with_context` spawns the FrameAttached/Detached/Navigated
    // listener so sync accessors (`main_frame`, `frames`, `parent_frame`,
    // `child_frames`, `is_detached`, `name`, `url`) see live state via
    // the listener. Sync after the eager `Page.getFrameTree` RTT was
    // dropped (`PERF_AUDIT` §M.4).
    let page = Page::with_context(any_page, self.clone());

    // Apply the BrowserContextOptions bag to the fresh page. Fields
    // without a backend implementation are silently skipped;
    // backend-specific failures funnel up as `FerriError` and fail
    // `new_page`, matching Playwright's "option applies or
    // context.newPage rejects" contract.
    if let Some(opts) = ctx_opts.as_ref() {
      apply_context_options(&page, opts).await?;
      // Hydrate `storageState` once per context — cookies + localStorage
      // applied to the first page; subsequent pages in the same
      // context inherit. Mirrors Playwright's
      // `/tmp/playwright/packages/playwright-core/src/server/browserContext.ts::setStorageState`.
      if let Some(ref storage) = opts.storage_state {
        let should_hydrate = {
          let state = self.state.read().await;
          state.claim_storage_state_hydration(&self.key.to_composite())
        };
        if should_hydrate {
          let state_value = match storage {
            crate::options::StorageStateInput::Inline(v) => v.clone(),
            crate::options::StorageStateInput::Path(p) => {
              let text = std::fs::read_to_string(p)
                .map_err(|e| crate::error::FerriError::Backend(format!("storageState: read {}: {e}", p.display())))?;
              serde_json::from_str(&text).map_err(|e| {
                crate::error::FerriError::Backend(format!("storageState: parse JSON from {}: {e}", p.display()))
              })?
            },
          };
          page.set_storage_state(&state_value).await?;
        }
      }
    }

    // If the context was configured with `recordVideo`, spawn the
    // recording runtime now that we have the strong `Arc<Page>`.
    // `start_video_recording` attaches a `Video` handle on the Page
    // that resolves when the encoder finishes; the recording runs in
    // the background via `tokio::spawn` and is stopped when the page
    // closes.
    let record_opts = {
      let state = self.state.read().await;
      state.get_record_video(&self.key.to_composite())
    };
    if let Some(opts) = record_opts {
      start_video_recording(&page, &opts);
    }

    // Re-apply every context-level binding (exposeBinding /
    // exposeFunction) to the fresh page so it sees `window[name]`
    // just like pages opened before the binding was registered.
    self.apply_context_bindings(page.inner()).await?;

    Ok(page)
  }

  /// Inject every registered context-level binding onto `page`.
  /// Called from `new_page` so a freshly-opened page sees the same
  /// `window[name]` proxies as pages opened before the binding existed.
  async fn apply_context_bindings(&self, page: &AnyPage) -> Result<()> {
    let composite = self.key.to_composite();
    let bindings = {
      let bindings_handle = self.state.read().await.context_bindings_handle();
      let guard = bindings_handle.read().await;
      guard
        .get(&composite)
        .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect::<Vec<_>>())
        .unwrap_or_default()
    };
    for (name, binding) in bindings {
      let fn_for_page = bind_source(binding, composite.clone(), page);
      page.expose_function(&name, fn_for_page).await?;
    }
    Ok(())
  }

  /// Get all pages in this context as Page handles.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist.
  pub async fn pages(&self) -> Result<Vec<Arc<Page>>> {
    let inner_pages = {
      let state = self.state.read().await;
      let ctx = state.context(&self.name)?;
      ctx.pages.clone()
    };
    let mut pages = Vec::with_capacity(inner_pages.len());
    for inner in inner_pages {
      pages.push(Page::with_context(inner, self.clone()));
    }
    Ok(pages)
  }

  /// Get all cookies in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or cookie retrieval fails.
  pub async fn cookies(&self) -> Result<Vec<CookieData>> {
    let page = {
      let state = self.state.read().await;
      state.context(&self.name)?.active_page().cloned()
    };
    if let Some(page) = page {
      page.get_cookies().await
    } else {
      Ok(Vec::new())
    }
  }

  /// Export the current storage state of this context — cookies plus a
  /// per-origin `localStorage` snapshot.
  ///
  /// Playwright: `storageState(options?: { path?: string, indexedDB?: boolean })
  ///   : Promise<{ cookies, origins }>`
  /// (`/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:460`;
  /// server collection at `.../server/browserContext.ts:609`).
  ///
  /// Cookies are read via the existing [`Self::cookies`] surface. For each
  /// live page in the context we evaluate `Object.entries(localStorage)` to
  /// snapshot its origin's storage, grouping by `location.origin` and skipping
  /// origins with no entries (mirrors Playwright's `if (storage.localStorage
  /// .length)` filter). `opts.path`, when set, writes the JSON-serialized
  /// state (pretty-printed) to disk; `opts.indexed_db` is accepted for
  /// signature parity but does not yet collect `IndexedDB` databases.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist, cookie retrieval fails,
  /// or (when `path` is set) the file cannot be written.
  pub async fn storage_state(
    &self,
    opts: Option<crate::options::StorageStateOptions>,
  ) -> Result<crate::options::StorageState> {
    // Page-side wrapper JSON-stringifies the result so the backend ships flat
    // strings rather than re-serializing via its own RemoteValue path (see
    // CLAUDE.md "utility-script JSON.stringify wrapper trick").
    const COLLECT_JS: &str = r"JSON.stringify({
      origin: location.origin,
      localStorage: Object.entries(localStorage).map(([name, value]) => ({ name, value }))
    })";

    let cookies = self.cookies().await?;

    let pages = self.pages().await?;
    let mut origins: Vec<crate::options::OriginState> = Vec::new();
    let mut seen: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();

    for page in &pages {
      // `Ok(None)` (no value) and `Err` (opaque origin / mid-navigation, where
      // localStorage access throws) are both skipped, matching Playwright's
      // per-page try/catch.
      let Ok(Some(raw)) = page.inner.evaluate(COLLECT_JS).await else {
        continue;
      };
      let parsed: Option<crate::options::OriginState> = raw
        .as_str()
        .and_then(|s| serde_json::from_str::<crate::options::OriginState>(s).ok());
      let Some(state) = parsed else { continue };
      if state.origin.is_empty() || state.origin == "null" || state.local_storage.is_empty() {
        continue;
      }
      if seen.insert(state.origin.clone()) {
        origins.push(state);
      }
    }

    let state = crate::options::StorageState { cookies, origins };

    if let Some(opts) = opts {
      if let Some(path) = opts.path {
        let json = serde_json::to_string_pretty(&state)
          .map_err(|e| crate::error::FerriError::Backend(format!("storageState: serialize JSON: {e}")))?;
        if let Some(parent) = path.parent() {
          if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent).map_err(|e| {
              crate::error::FerriError::Backend(format!("storageState: mkdir {}: {e}", parent.display()))
            })?;
          }
        }
        std::fs::write(&path, json)
          .map_err(|e| crate::error::FerriError::Backend(format!("storageState: write {}: {e}", path.display())))?;
      }
    }

    Ok(state)
  }

  /// Add cookies to this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or setting cookies fails.
  pub async fn add_cookies(&self, cookies: Vec<CookieData>) -> Result<()> {
    let page = {
      let state = self.state.read().await;
      state.context(&self.name)?.active_page().cloned()
    }
    .ok_or(crate::error::FerriError::NotConnected)?;

    for cookie in cookies {
      page.set_cookie(cookie).await?;
    }
    Ok(())
  }

  /// Clear all cookies in this context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or clearing cookies fails.
  pub async fn clear_cookies(&self) -> Result<()> {
    let page = {
      let state = self.state.read().await;
      state.context(&self.name)?.active_page().cloned()
    };
    if let Some(page) = page {
      page.clear_cookies().await?;
    }
    Ok(())
  }

  /// Clear cookies matching the given filters (matches Playwright's `context.clearCookies(options?)`).
  /// If no filters are specified, all cookies are cleared.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or clearing cookies fails.
  pub async fn clear_cookies_filtered(&self, options: &crate::backend::ClearCookieOptions) -> Result<()> {
    if options.name.is_none() && options.domain.is_none() && options.path.is_none() {
      return self.clear_cookies().await;
    }
    let page = {
      let state = self.state.read().await;
      state.context(&self.name)?.active_page().cloned()
    };
    if let Some(page) = page {
      let cookies = page.get_cookies().await?;
      page.clear_cookies().await?;
      for c in cookies {
        let name_match = options.name.as_ref().is_none_or(|n| &c.name == n);
        let domain_match = options.domain.as_ref().is_none_or(|d| &c.domain == d);
        let path_match = options.path.as_ref().is_none_or(|p| &c.path == p);
        if !(name_match && domain_match && path_match) {
          page.set_cookie(c).await?;
        }
      }
    }
    Ok(())
  }

  /// Delete a specific cookie by name and optional domain
  /// (matches Playwright's `context.clearCookies({ name })`).
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or deleting fails.
  pub async fn delete_cookie(&self, name: &str, domain: Option<&str>) -> Result<()> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    ctx.delete_cookie(name, domain).await
  }

  /// Set the default timeout for actions in this context (ms). Mirrors
  /// Playwright's `browserContext.setDefaultTimeout(timeout)`. Takes
  /// `&self` (interior mutability via `Arc<AtomicU64>`) so it works
  /// behind a shared handle.
  pub fn set_default_timeout(&self, ms: u64) {
    self.default_timeout_ms.store(ms, std::sync::atomic::Ordering::Relaxed);
  }

  /// Set the default navigation timeout for this context (ms). Mirrors
  /// Playwright's `browserContext.setDefaultNavigationTimeout(timeout)`.
  pub fn set_default_navigation_timeout(&self, ms: u64) {
    self
      .default_navigation_timeout_ms
      .store(ms, std::sync::atomic::Ordering::Relaxed);
  }

  /// Current default action timeout (ms). 0 = no override.
  #[must_use]
  pub fn default_timeout(&self) -> u64 {
    self.default_timeout_ms.load(std::sync::atomic::Ordering::Relaxed)
  }

  /// Current default navigation timeout (ms). 0 = no override.
  #[must_use]
  pub fn default_navigation_timeout(&self) -> u64 {
    self
      .default_navigation_timeout_ms
      .load(std::sync::atomic::Ordering::Relaxed)
  }

  /// Mutate the stored [`crate::options::BrowserContextOptions`] bag
  /// via `f`, then re-apply the bag to every already-open page in
  /// this context. The single idiomatic entry point behind every
  /// Playwright public context setter (`setGeolocation`,
  /// `setOffline`, `setExtraHTTPHeaders`, `grantPermissions`, etc.)
  /// and the backbone for future per-field mutators.
  ///
  /// Future pages opened in this context see the updated bag because
  /// `ContextRef::new_page` reads from the same registry.
  ///
  /// # Errors
  ///
  /// Returns an error when `page.apply_context_options` rejects on
  /// any open page (aggregated per-field).
  async fn mutate_options<F>(&self, f: F) -> Result<()>
  where
    F: FnOnce(&mut crate::options::BrowserContextOptions),
  {
    let composite = self.key.to_composite();
    let updated = {
      let state = self.state.read().await;
      let mut opts = state.get_context_options(&composite).unwrap_or_default();
      f(&mut opts);
      state.set_context_options(&composite, opts.clone());
      opts
    };
    let pages = Box::pin(self.pages()).await?;
    for page in pages {
      Box::pin(page.apply_context_options(&updated)).await?;
    }
    Ok(())
  }

  /// Grant permissions in this context. Stores the list on the
  /// options bag and re-applies to every open page — matches
  /// Playwright's `browserContext.grantPermissions` semantics where
  /// the grant persists for future pages too.
  ///
  /// The `origin` parameter is currently ignored at the backend
  /// level (CDP `Browser.grantPermissions` accepts an `origin` but
  /// we don't thread it through the options bag yet — the
  /// bag-stored list grants for every origin).
  ///
  /// # Errors
  ///
  /// Returns an error if the re-application fails on any page.
  pub async fn grant_permissions(&self, permissions: &[String], _origin: Option<&str>) -> Result<()> {
    let perms = permissions.to_vec();
    self.mutate_options(|o| o.permissions = Some(perms)).await
  }

  /// Clear all granted permissions.
  ///
  /// # Errors
  ///
  /// Returns an error if resetting permissions fails.
  pub async fn clear_permissions(&self) -> Result<()> {
    // Reset via the backend's `Browser.resetPermissions` on every
    // page, then drop the list from the options bag.
    let pages = self.pages().await?;
    for page in &pages {
      page.inner().reset_permissions().await?;
    }
    self.mutate_options(|o| o.permissions = None).await
  }

  /// Close this context (remove from `BrowserState`).
  ///
  /// # Errors
  ///
  /// Returns an error if state lock acquisition fails.
  pub async fn close(&self) -> Result<()> {
    self.closed.store(true, std::sync::atomic::Ordering::SeqCst);
    let mut state = self.state.write().await;
    let persistent = state.persistent_context;
    state.remove_context(&self.name).await;
    if persistent {
      // Persistent-context launch contract: closing the context closes
      // the underlying browser too. Playwright:
      // `/tmp/playwright/packages/playwright-core/types/types.d.ts:15199`.
      state.shutdown().await;
    }
    Ok(())
  }

  /// Access the internal state (for MCP server integration).
  #[must_use]
  pub fn state(&self) -> &Arc<RwLock<BrowserState>> {
    &self.state
  }

  /// Enable `recordVideo` for pages opened in this context AFTER
  /// the call. Pages already open do not retroactively start
  /// recording — matches Playwright's context-creation-time binding
  /// semantics (`browser.newContext({ recordVideo: { dir, size? } })`).
  ///
  /// Transitional shim — prefer passing `recordVideo` to
  /// `browser.newContext(options)` directly.
  ///
  /// # Errors
  ///
  /// Returns an error if the state write fails. Does NOT re-apply
  /// to already-open pages (the recording runtime attaches at page
  /// open via `start_video_recording`).
  pub async fn set_record_video(&self, opts: crate::options::RecordVideoOptions) -> Result<()> {
    let composite = self.key.to_composite();
    let state = self.state.read().await;
    state.set_record_video(&composite, opts.clone());
    // Also fold into the options bag so future `browser.newContext`
    // re-reads see it, and so a later `context.setOffline`-style
    // mutator doesn't clobber the record_video field.
    let mut bag = state.get_context_options(&composite).unwrap_or_default();
    bag.record_video = Some(opts);
    state.set_context_options(&composite, bag);
    Ok(())
  }

  // ── Context-level events ────────────────────────────────────────────────

  /// Register a context-level event listener. Supported events:
  /// `'weberror'` (unhandled errors / rejections on any page in this
  /// context — mirrors Playwright's
  /// `browserContext.on('weberror', (webError: WebError) => ...)`).
  pub fn on(&self, event_name: &str, callback: crate::events::ContextEventCallback) -> crate::events::ListenerId {
    self.events.on(event_name, callback)
  }

  /// One-shot context-level listener — see [`Self::on`].
  pub fn once(&self, event_name: &str, callback: crate::events::ContextEventCallback) -> crate::events::ListenerId {
    self.events.once(event_name, callback)
  }

  /// Remove a previously registered context-level listener.
  pub fn off(&self, id: crate::events::ListenerId) {
    self.events.off(id);
  }

  /// Wait for the next context-level event matching `event_name`, with
  /// `timeout_ms`. Mirrors Playwright's
  /// `browserContext.waitForEvent(event, options?)`.
  ///
  /// # Errors
  ///
  /// Returns an error if the timeout elapses or the event channel is closed.
  pub async fn wait_for_event(&self, event_name: &str, timeout_ms: u64) -> Result<crate::events::ContextEvent> {
    self.events.wait_for_event(event_name, timeout_ms).await
  }

  // ── Context-level APIs (apply to all pages) ────────────────────────────

  /// Add an init script to all pages in this context (current + future).
  /// Mirrors Playwright's `browserContext.addInitScript(script, arg)` from
  /// `/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:356`.
  /// See [`crate::page::Page::add_init_script`] for argument semantics.
  ///
  /// Returns a [`crate::disposable::Disposable`] whose `dispose()` removes the
  /// injected script from every page it was added to. Mirrors Playwright
  /// `browserContext.addInitScript(...)` which returns a `DisposableObject`
  /// (`client/browserContext.ts:361`).
  ///
  /// # Errors
  ///
  /// Returns an error if `evaluation_script` lowering fails, the context
  /// does not exist, or script injection fails on any page.
  pub async fn add_init_script(
    &self,
    script: crate::options::InitScriptSource,
    arg: Option<serde_json::Value>,
  ) -> Result<crate::disposable::Disposable> {
    let source = crate::options::evaluation_script(script, arg.as_ref())?;
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    let mut undo = Vec::with_capacity(ctx.pages.len());
    for page in &ctx.pages {
      let id = page.add_init_script(&source).await?;
      undo.push((page.clone(), id));
    }
    drop(state);
    Ok(crate::disposable::Disposable::new(move || async move {
      for (page, id) in undo {
        page.remove_init_script(&id).await?;
      }
      Ok(())
    }))
  }

  /// Playwright: `browserContext.setGeolocation(geo)` — mutates the
  /// options bag and re-applies to every open page.
  ///
  /// # Errors
  ///
  /// Returns an error if re-application fails on any page.
  pub async fn set_geolocation(&self, lat: f64, lng: f64, accuracy: f64) -> Result<()> {
    self
      .mutate_options(|o| {
        o.geolocation = Some(crate::options::Geolocation {
          latitude: lat,
          longitude: lng,
          accuracy,
        });
      })
      .await
  }

  /// Playwright: `browserContext.setExtraHTTPHeaders(headers)`.
  ///
  /// # Errors
  ///
  /// Returns an error if re-application fails on any page.
  pub async fn set_extra_http_headers(&self, headers: &rustc_hash::FxHashMap<String, String>) -> Result<()> {
    let headers = headers.clone();
    self.mutate_options(|o| o.extra_http_headers = Some(headers)).await
  }

  /// Playwright: `browserContext.setOffline(offline)`.
  ///
  /// # Errors
  ///
  /// Returns an error if re-application fails on any page.
  pub async fn set_offline(&self, offline: bool) -> Result<()> {
    self.mutate_options(|o| o.offline = Some(offline)).await
  }

  /// Playwright: `browserContext.setHTTPCredentials(httpCredentials |
  /// null)` (`/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:355`).
  /// Stores the credentials on the context options bag so pages opened
  /// later inherit them, and applies them to every already-open page.
  /// Passing `None` clears stored credentials — future 401 challenges
  /// then surface as the browser's native auth dialog rather than being
  /// answered automatically.
  ///
  /// The bag mutation alone cannot express "clear" (the per-field
  /// `apply_context_options` future is keyed on `Some`), so this drives
  /// the dedicated [`crate::Page::set_http_credentials`] backend path on
  /// each open page directly.
  ///
  /// # Errors
  ///
  /// Returns an error if any open page's backend rejects the change
  /// (e.g. a backend that does not support auth-challenge interception).
  pub async fn set_http_credentials(&self, credentials: Option<crate::options::HttpCredentials>) -> Result<()> {
    let composite = self.key.to_composite();
    {
      let state = self.state.read().await;
      let mut opts = state.get_context_options(&composite).unwrap_or_default();
      opts.http_credentials.clone_from(&credentials);
      state.set_context_options(&composite, opts);
    }
    let pages = self.pages().await?;
    for page in pages {
      page.set_http_credentials(credentials.clone()).await?;
    }
    Ok(())
  }

  /// Register a route handler for all pages in this context.
  ///
  /// Returns a [`crate::disposable::Disposable`] whose `dispose()` removes the
  /// handler from every page (equivalent to [`Self::unroute`]).
  /// Mirrors Playwright `browserContext.route(...)` which returns a
  /// `DisposableStub` (`client/browserContext.ts:377`).
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or route registration fails.
  pub async fn route(
    &self,
    matcher: crate::url_matcher::UrlMatcher,
    handler: crate::route::RouteHandler,
    times: Option<u32>,
  ) -> Result<crate::disposable::Disposable> {
    // NOTE: `times` is applied per-page here (each page tracks its own
    // remaining count) rather than shared across the whole context. For the
    // common single-page / times:1 case this matches Playwright; a strict
    // context-shared counter across multiple pages is not yet implemented.
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    let mut undo = Vec::with_capacity(ctx.pages.len());
    for page in &ctx.pages {
      page.route(matcher.clone(), handler.clone(), times).await?;
      undo.push(page.clone());
    }
    drop(state);
    Ok(crate::disposable::Disposable::new(move || async move {
      for page in undo {
        page.unroute(&matcher).await?;
      }
      Ok(())
    }))
  }

  /// Playwright: `browserContext.routeFromHAR(har, options?)`. Replays a HAR
  /// file across every page in this context. Replay-only; recording
  /// (`update: true`) is unsupported.
  ///
  /// # Errors
  ///
  /// Returns an error if the HAR file cannot be read/parsed or routes fail
  /// to install.
  pub async fn route_from_har(&self, path: &std::path::Path, options: crate::har::RouteFromHarOptions) -> Result<()> {
    let handler = crate::har::route_handler_from_file(path, options.not_found)?;
    let matcher = options.url.unwrap_or_else(crate::url_matcher::UrlMatcher::any);
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    for page in &ctx.pages {
      page.route(matcher.clone(), handler.clone(), None).await?;
    }
    Ok(())
  }

  /// Remove route handlers matching the given matcher from all pages.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or route removal fails.
  pub async fn unroute(&self, matcher: &crate::url_matcher::UrlMatcher) -> Result<()> {
    let state = self.state.read().await;
    let ctx = state.context(&self.name)?;
    for page in &ctx.pages {
      page.unroute(matcher).await?;
    }
    Ok(())
  }

  // ── Exposed bindings / functions (apply to all pages) ───────────────────

  /// Playwright: `browserContext.exposeBinding(name, callback)` from
  /// `/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:364`.
  ///
  /// Registers `window[name]` on every page in this context (current +
  /// future). The page-side call routes back into `callback`, which
  /// receives a [`crate::events::BindingSource`] as its first argument
  /// followed by the page-side call args. The callback's return value
  /// (after awaiting any returned promise in the binding layers) is
  /// delivered to the page-side caller.
  ///
  /// Returns a [`crate::disposable::Disposable`] whose `dispose()` removes the binding
  /// from the registry and from every page in the context.
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or injection fails
  /// on any page.
  pub async fn expose_binding(
    &self,
    name: &str,
    callback: crate::events::ExposedBinding,
  ) -> Result<crate::disposable::Disposable> {
    {
      let bindings = self.state.read().await.context_bindings_handle();
      let mut guard = bindings.write().await;
      guard
        .entry(self.key.to_composite())
        .or_default()
        .insert(name.to_string(), callback.clone());
    }
    // Apply to every page already open in this context.
    let pages = {
      let state = self.state.read().await;
      state.context(&self.name).map(|c| c.pages.clone()).unwrap_or_default()
    };
    let composite = self.key.to_composite();
    for page in &pages {
      let fn_for_page = bind_source(callback.clone(), composite.clone(), page);
      page.expose_function(name, fn_for_page).await?;
    }
    Ok(crate::disposable::Disposable::new({
      let this = self.clone();
      let name = name.to_string();
      move || async move {
        let _ = this.remove_exposed_binding(&name).await;
        Ok(())
      }
    }))
  }

  /// Playwright: `browserContext.exposeFunction(name, callback)` from
  /// `/tmp/playwright/packages/playwright-core/src/client/browserContext.ts:370`.
  ///
  /// `exposeFunction` is `exposeBinding` minus the source argument:
  /// the supplied source-less [`crate::events::ExposedFn`] is wrapped
  /// into an [`crate::events::ExposedBinding`] that discards the
  /// [`crate::events::BindingSource`].
  ///
  /// # Errors
  ///
  /// Returns an error if the context does not exist or injection fails
  /// on any page.
  pub async fn expose_function(
    &self,
    name: &str,
    callback: crate::events::ExposedFn,
  ) -> Result<crate::disposable::Disposable> {
    let binding: crate::events::ExposedBinding = Arc::new(move |_source, args| callback(args));
    self.expose_binding(name, binding).await
  }

  /// Remove a previously exposed binding/function from the registry and
  /// from every page in this context. Mirrors Playwright's
  /// `BrowserContext.removeExposedBinding` (driven by `Disposable`).
  ///
  /// # Errors
  ///
  /// Returns an error if removal fails on any open page.
  pub async fn remove_exposed_binding(&self, name: &str) -> Result<()> {
    {
      let bindings = self.state.read().await.context_bindings_handle();
      let mut guard = bindings.write().await;
      if let Some(map) = guard.get_mut(&self.key.to_composite()) {
        map.remove(name);
      }
    }
    let pages = {
      let state = self.state.read().await;
      state.context(&self.name).map(|c| c.pages.clone()).unwrap_or_default()
    };
    for page in &pages {
      page.remove_exposed_function(name).await?;
    }
    Ok(())
  }
}

/// Bind a [`crate::events::ExposedBinding`] to a concrete page by
/// capturing the per-call [`crate::events::BindingSource`]. The backend
/// binding dispatch (`page.expose_function`) only forwards the page-side
/// call args, so the `{ context, page, frame }` identity is captured
/// here at apply time. `page`/`frame` use the page's main-frame id
/// (the stable per-page identifier reachable without an extra RTT);
/// `context` is the composite session key.
fn bind_source(
  binding: crate::events::ExposedBinding,
  context_key: String,
  page: &AnyPage,
) -> crate::events::ExposedFn {
  let frame_id = page.peek_main_frame_id().unwrap_or_default();
  Arc::new(move |args| {
    let source = crate::events::BindingSource {
      context: context_key.clone(),
      page: frame_id.clone(),
      frame: frame_id.clone(),
    };
    binding(source, args)
  })
}

/// Apply every supported field on a [`crate::options::BrowserContextOptions`]
/// bag to a freshly-opened [`Page`]. Each field corresponds to an
/// existing Page setter; fields with no backend support on a given
/// backend bubble up the backend's `FerriError` (typically
/// `FerriError::Unsupported { reason }`) which then fails
/// `ContextRef::new_page`. Field application order mirrors Playwright's
/// `BrowserContext.doCreateNewContext` server-side sequencing
/// (`/tmp/playwright/packages/playwright-core/src/server/browserContext.ts`):
/// emulation before navigation, permissions last.
///
/// Fields deferred to a follow-up session (no-op here): `proxy`,
/// `record_har`, `storage_state`, `screen`, `base_url`, `service_workers`,
/// `accept_downloads`, `ignore_https_errors`, `strict_selectors` beyond
/// storage, `bypass_csp`. Each gets a dedicated implementation when the
/// supporting infrastructure lands. (`http_credentials` is now wired
/// through CDP both at context-creation time and via the dynamic
/// `ContextRef::set_http_credentials` setter.)
/// Apply a context-options bag to a freshly-opened page. This
/// delegates to the backend's single `apply_context_options` dispatch
/// which fires every protocol command in parallel and aggregates
/// errors (matches Playwright's `crPage._updateXxx()` set driven by
/// `Promise.all`). Keeping the helper thin here means the context
/// layer stays backend-agnostic — the only Rust-level choice is
/// "apply the whole bag or don't".
async fn apply_context_options(page: &Arc<Page>, opts: &crate::options::BrowserContextOptions) -> Result<()> {
  Box::pin(page.apply_context_options(opts)).await
}

/// Kick off a background recording runtime for a freshly-opened page
/// whose context has `recordVideo` enabled. Constructs the Video
/// handle, attaches it to the page, and spawns a task that awaits the
/// page close then drives the encoder to completion.
///
/// The attach-first-then-spawn ordering matters: callers of
/// [`crate::Page::video`] can observe the handle the moment `new_page`
/// returns, even before the first frame has been captured. The handle
/// blocks on the underlying watch channel inside `path()` /
/// `save_as()` / `delete()`, so observing an in-progress recording
/// and calling `await video.path()` resolves cleanly once the page
/// closes.
///
/// Should a backend's `AnyPage::start_screencast` ever surface a typed
/// error, the video sink is populated with the error text so the
/// Playwright contract — `page.video()` returns a handle; the handle's
/// methods reject with a clear reason — is preserved. (Every current
/// backend, including Playwright `WebKit`, supports screencast.)
fn start_video_recording(page: &Arc<Page>, opts: &crate::options::RecordVideoOptions) {
  // Compose the output filename: `<dir>/<timestamp>-<page-id>.<ext>`.
  // Playwright derives its name from the page's GUID; ferridriver uses
  // millisecond-since-epoch + an atomic counter — unique across pages
  // within the same context and the same second. The extension comes
  // from `crate::video::video_extension()` so changes to the encoder
  // format propagate without a filename rewrite.
  static VIDEO_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

  let (video, sink) = crate::video::Video::new();
  page.attach_video(Arc::new(video));

  let size = opts.size.unwrap_or_default();
  let width = size.width & !1;
  let height = size.height & !1;
  let millis = std::time::SystemTime::now()
    .duration_since(std::time::UNIX_EPOCH)
    .map_or(0, |d| d.as_millis());
  let id = VIDEO_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  let filename = format!("{millis}-{id}.{}", crate::video::video_extension());
  let output_path = opts.dir.join(filename);

  // Ensure the directory exists before the encoder opens the file.
  // Errors here funnel into the sink so the user-facing `path()`
  // rejects with a clear reason instead of the test hanging.
  if let Err(e) = std::fs::create_dir_all(&opts.dir) {
    sink.finish_err(crate::FerriError::backend(format!(
      "failed to create recordVideo.dir {}: {e}",
      opts.dir.display()
    )));
    return;
  }

  let page_for_task = page.clone();
  tokio::spawn(async move {
    // Default CDP screencast quality matches Playwright's
    // `DEFAULT_SCREENCAST_OPTIONS.quality` (90).
    let handle = match crate::video::start_recording(&page_for_task, output_path.clone(), width, height, 90).await {
      Ok(h) => h,
      Err(e) => {
        sink.finish_err(crate::FerriError::backend(format!("start_recording: {e}")));
        return;
      },
    };
    // Wait for the page to close before stopping the recording.
    // Polls at 50ms — matches the cadence of the frame-cache
    // listener task and keeps the observable delay inside the
    // "page.close() has returned" barrier below ~50ms in the
    // common case.
    while !page_for_task.is_closed() {
      tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }
    match handle.stop(&page_for_task).await {
      Ok(path) => sink.finish_ok(path),
      Err(e) => sink.finish_err(crate::FerriError::backend(format!("stop recording: {e}"))),
    }
  });
}

#[cfg(test)]
mod tests {
  use super::*;
  use std::sync::atomic::{AtomicUsize, Ordering};

  #[tokio::test]
  async fn expose_function_wrapper_discards_source() {
    // The exposeFunction adapter must drop the BindingSource and pass
    // only the page-side args to the user callback (Playwright:
    // `(source, ...args) => callback(...args)`).
    let seen = Arc::new(AtomicUsize::new(0));
    let seen_cb = seen.clone();
    let inner: crate::events::ExposedFn = Arc::new(move |args: Vec<serde_json::Value>| {
      seen_cb.store(args.len(), Ordering::SeqCst);
      Box::pin(async move { serde_json::json!(args.iter().filter_map(serde_json::Value::as_i64).sum::<i64>()) })
    });
    let binding: crate::events::ExposedBinding = Arc::new(move |_source, args| inner(args));
    let source = crate::events::BindingSource {
      context: "inst:ctx".into(),
      page: "frame-1".into(),
      frame: "frame-1".into(),
    };
    let out = binding(source, vec![serde_json::json!(20), serde_json::json!(22)]).await;
    assert_eq!(seen.load(Ordering::SeqCst), 2);
    assert_eq!(out, serde_json::json!(42));
  }

  #[tokio::test]
  async fn disposable_runs_once() {
    let count = Arc::new(AtomicUsize::new(0));
    let c = count.clone();
    let d = crate::disposable::Disposable::new(move || {
      let c = c.clone();
      async move {
        c.fetch_add(1, Ordering::SeqCst);
        Ok(())
      }
    });
    d.dispose().await.expect("dispose");
    d.dispose().await.expect("dispose");
    assert_eq!(count.load(Ordering::SeqCst), 1);
  }
}