solari-browser 0.6.5

Rust binding for the Solari Browser platform control plane (sessions, profiles, replays, managed proxy).
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
//! # solari-browser
//!
//! Rust binding for the **Solari Browser** platform — the control plane:
//! acquire and release pooled stealth Chromium sessions, manage stored browser
//! profiles, pull session replays, and inspect managed-proxy egress. It speaks
//! the same wire contract as the reference `@solarisdk/browser` TypeScript
//! package (`sdk/src/index.ts`).
//!
//! ```no_run
//! use solari_browser::{Client, ClientOptions, CreateSessionOptions, ProxySpec};
//!
//! # async fn ex() -> Result<(), solari_browser::SolariError> {
//! let client = Client::new(ClientOptions::default_region("slr_live_…"))?;
//!
//! let session = client
//!     .sessions()
//!     .create(
//!         CreateSessionOptions::new()
//!             .stealth(true)
//!             .proxy(ProxySpec::country("us")),
//!     )
//!     .await?;
//!
//! println!("ws  {}", session.ws_endpoint);   // Playwright wire protocol
//! println!("cdp {}", session.cdp_endpoint);  // raw CDP — use this from Rust
//!
//! client.sessions().release(&session.id).await?;
//! # Ok(()) }
//! ```
//!
//! ## Scope
//!
//! This crate is the **control plane plus browser attachment**. Playwright has
//! no Rust binding, so there is no port of the TypeScript `BrowserSession`
//! Playwright object model; instead, with the `connect` feature enabled you get
//! two levels of attachment, both driving the session over raw CDP via
//! [`chromiumoxide`](https://docs.rs/chromiumoxide):
//! - [`connect`] — attach to a session you already created; and
//! - [`Client::launch`] — a thin one-call convenience (create, connect, seed an
//!   attached profile's cookies, health-probe, retry, and release on close)
//!   that hands back the same [`chromiumoxide::Browser`] to drive.
//!
//! Enable it with:
//!
//! ```toml
//! solari-browser = { version = "0.6", features = ["connect"] }
//! ```
//!
//! ## Endpoints vs. the TypeScript SDK
//!
//! The TS SDK routes `wsEndpoint` / `cdpEndpoint` through a Node-side loopback
//! `LocalProxy`. This crate has no such indirection: [`Session::ws_endpoint`]
//! and [`Session::cdp_endpoint`] are the **upstream** gateway endpoints.

mod client;
mod error;
mod profile_editor;
mod http;
mod types;

#[cfg(feature = "connect")]
mod connect;

#[cfg(feature = "connect")]
mod session;

pub use client::{
    Client, ClientOptions, CreateSessionOptions, ListSessionsOptions, Profiles, Proxy, Sessions,
};
pub use profile_editor::{EditorState, EditorStatus, ProfileEditor};
pub use error::{ApiErrorBody, SolariError, SolariErrorCode};
pub use types::{
    Cookie, LocalStorageEntry, Profile, ProfileSaveResult, ProxyCountries, ProxyRequest, ProxySpec,
    ProxyTier, ReplayUrl, ResolvedProxyConfig, SameSite, Session, SessionList, SessionSummary,
    SessionView, SolariRegion,
    StorageOrigin, StorageState,
};

#[cfg(feature = "connect")]
pub use connect::{connect, connect_endpoint, ConnectedBrowser};

#[cfg(feature = "connect")]
pub use session::{LaunchOptions, LaunchedSession};

#[cfg(test)]
mod tests {
    use super::client::{derive_cdp_from_ws, iso8601_utc};
    use super::*;
    use std::sync::{Arc, Mutex};
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    // -----------------------------------------------------------------------
    // Mock HTTP server: serves a scripted list of responses, one per accepted
    // connection, and captures every raw request it saw.
    // -----------------------------------------------------------------------

    async fn bind_mock() -> (TcpListener, u16) {
        let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = l.local_addr().unwrap().port();
        (l, port)
    }

    /// Serve `responses` in order — one per connection — capturing raw requests.
    fn serve(listener: TcpListener, responses: Vec<(u16, String)>) -> Arc<Mutex<Vec<String>>> {
        let captured: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
        let cap = captured.clone();
        tokio::spawn(async move {
            for (status, body) in responses {
                let Ok((mut sock, _)) = listener.accept().await else {
                    return;
                };
                // Read headers, then the Content-Length body.
                let mut buf = Vec::new();
                let mut tmp = [0u8; 1024];
                while let Ok(n) = sock.read(&mut tmp).await {
                    if n == 0 {
                        break; // peer closed before we saw a full request
                    }
                    buf.extend_from_slice(&tmp[..n]);
                    let Some(pos) = find_subslice(&buf, b"\r\n\r\n") else {
                        continue; // headers still incomplete
                    };
                    let head = String::from_utf8_lossy(&buf[..pos]).to_string();
                    let clen = content_length(&head).unwrap_or(0);
                    let body_start = pos + 4;
                    while buf.len() < body_start + clen {
                        match sock.read(&mut tmp).await {
                            Ok(0) | Err(_) => break,
                            Ok(n) => buf.extend_from_slice(&tmp[..n]),
                        }
                    }
                    break;
                }
                cap.lock()
                    .unwrap()
                    .push(String::from_utf8_lossy(&buf).to_string());

                let reason = match status {
                    200 => "OK",
                    201 => "Created",
                    204 => "No Content",
                    400 => "Bad Request",
                    402 => "Payment Required",
                    404 => "Not Found",
                    429 => "Too Many Requests",
                    503 => "Service Unavailable",
                    _ => "Status",
                };
                let resp = format!(
                    "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                    body.len(),
                    body
                );
                let _ = sock.write_all(resp.as_bytes()).await;
                let _ = sock.flush().await;
            }
        });
        captured
    }

    fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
        haystack.windows(needle.len()).position(|w| w == needle)
    }

    fn content_length(head: &str) -> Option<usize> {
        for line in head.lines() {
            if let Some(v) = line.to_lowercase().strip_prefix("content-length:") {
                return v.trim().parse().ok();
            }
        }
        None
    }

    fn split_req(raw: &str) -> (String, String) {
        match raw.split_once("\r\n\r\n") {
            Some((h, b)) => (h.to_string(), b.to_string()),
            None => (raw.to_string(), String::new()),
        }
    }

    fn client_for(port: u16) -> Client {
        Client::new(
            ClientOptions::new("slr_live_id_secret", format!("http://127.0.0.1:{port}"))
                .backoff_ms(0),
        )
        .unwrap()
    }

    // -----------------------------------------------------------------------
    // Tests
    // -----------------------------------------------------------------------

    // A BARE 404 on release means "already gone" and is success. A 404 the
    // gateway marked InvalidSessionId means it REFUSED the id and released
    // nothing — the pool slot is still held until orphan-grace, so reporting
    // success is what made these releases leak slots silently.

    #[tokio::test]
    async fn release_tolerates_a_bare_404() {
        let (l, port) = bind_mock().await;
        let _ = serve(l, vec![(404, r#"{"error":"Not Found"}"#.to_string())]);
        let client = client_for(port);
        assert!(client.sessions().release("s_1").await.is_ok());
    }

    #[tokio::test]
    async fn release_tolerates_a_404_with_an_unrelated_code() {
        let (l, port) = bind_mock().await;
        let _ = serve(
            l,
            vec![(404, r#"{"error":"Not Found","code":"SomethingElse"}"#.to_string())],
        );
        let client = client_for(port);
        assert!(client.sessions().release("s_1").await.is_ok());
    }

    #[tokio::test]
    async fn release_fails_on_404_invalid_session_id() {
        let (l, port) = bind_mock().await;
        let _ = serve(
            l,
            vec![(
                404,
                r#"{"error":"Not Found","code":"InvalidSessionId"}"#.to_string(),
            )],
        );
        let client = client_for(port);
        let err = client
            .sessions()
            .release("s_1")
            .await
            .expect_err("a refused session id released nothing and must not look like success");
        assert_eq!(err.status(), Some(404));
        assert_eq!(err.code(), Some(&SolariErrorCode::InvalidSessionId));
    }

    #[tokio::test]
    async fn invalid_session_id_round_trips_through_the_wire_string() {
        assert_eq!(
            SolariErrorCode::from("InvalidSessionId"),
            SolariErrorCode::InvalidSessionId
        );
        assert_eq!(SolariErrorCode::InvalidSessionId.as_str(), "InvalidSessionId");
    }

    /// POST /sessions request shape: method/path, auth + content-type headers,
    /// only the truthy options serialized, everything else omitted.
    #[tokio::test]
    async fn create_session_request_shape() {
        let (l, port) = bind_mock().await;
        let body = r#"{"sessionId":"s_1","wsEndpoint":"wss://gw.example.com/ws/s_1","cdpEndpoint":"wss://gw.example.com/cdp/s_1","expiresAt":"2026-01-01T00:00:00Z"}"#;
        let captured = serve(l, vec![(201, body.to_string())]);

        let client = client_for(port);
        let session = client
            .sessions()
            .create(
                CreateSessionOptions::new()
                    .stealth(true)
                    .proxy(ProxySpec::country("us")),
            )
            .await
            .unwrap();

        assert_eq!(session.id, "s_1");
        assert_eq!(session.ws_endpoint, "wss://gw.example.com/ws/s_1");
        assert_eq!(session.cdp_endpoint, "wss://gw.example.com/cdp/s_1");
        assert_eq!(session.expires_at, "2026-01-01T00:00:00Z");
        // No profile requested → storage state stays absent (not "empty").
        assert!(session.storage_state.is_none());
        assert!(session.proxy.is_none());

        let raw = captured.lock().unwrap()[0].clone();
        let (head, body) = split_req(&raw);
        assert!(head.starts_with("POST /sessions "), "head: {head}");
        let lower = head.to_lowercase();
        assert!(
            lower.contains("authorization: bearer slr_live_id_secret"),
            "head: {head}"
        );
        assert!(lower.contains("content-type: application/json"), "head: {head}");

        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
        assert_eq!(json.get("stealth").unwrap(), true);
        assert_eq!(json.get("proxy").unwrap(), "us");
        // Falsy / unset options are omitted entirely.
        assert!(json.get("recording").is_none(), "body: {body}");
        assert!(json.get("captcha").is_none(), "body: {body}");
        assert!(json.get("profileId").is_none(), "body: {body}");
    }

    /// timeoutSeconds, keepAlive and userMetadata go out on create; the metadata comes back on the Session.
    #[tokio::test]
    async fn create_session_sends_timeout_keep_alive_and_user_metadata() {
        let (l, port) = bind_mock().await;
        let body = r#"{"sessionId":"s_9","wsEndpoint":"wss://gw.example.com/ws/s_9","userMetadata":{"job":"j-7"}}"#;
        let captured = serve(l, vec![(201, body.to_string())]);

        let mut meta = serde_json::Map::new();
        meta.insert("job".into(), serde_json::json!("j-7"));
        let session = client_for(port)
            .sessions()
            .create(
                CreateSessionOptions::new()
                    .session_timeout_ms(120_000)
                    .keep_alive(true)
                    .user_metadata(meta),
            )
            .await
            .unwrap();

        let raw = captured.lock().unwrap()[0].clone();
        let (_, body) = split_req(&raw);
        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
        assert_eq!(json["timeoutSeconds"], 120);
        assert_eq!(json["keepAlive"], true);
        assert_eq!(json["userMetadata"]["job"], "j-7");
        assert_eq!(session.user_metadata.unwrap()["job"], "j-7");
    }

    /// Session lifetime goes out as whole seconds, rounded up; the deprecated seconds option still works
    /// and the millisecond one wins when both are set.
    #[test]
    fn session_timeout_ms_converts_to_wire_seconds() {
        use crate::client::session_timeout_seconds as conv;
        assert_eq!(conv(None, None).unwrap(), None);
        assert_eq!(conv(Some(0), None).unwrap(), None);
        assert_eq!(conv(Some(1000), None).unwrap(), Some(1));
        assert_eq!(conv(Some(1001), None).unwrap(), Some(2));
        assert_eq!(conv(Some(59_999), None).unwrap(), Some(60));
        assert_eq!(conv(Some(60_000), None).unwrap(), Some(60));
        assert_eq!(conv(None, Some(90)).unwrap(), Some(90));
        assert_eq!(conv(None, Some(0)).unwrap(), None);
        assert_eq!(conv(Some(120_000), Some(90)).unwrap(), Some(120), "the new name wins");
        assert!(conv(Some(u64::MAX), None).is_err(), "too large for the wire field");
        // The wire field is int32 (the Go SDK enforces it too): the largest seconds that fit still go out,
        // one more is refused, even though it fits a u32.
        let max = i32::MAX as u64;
        assert_eq!(conv(Some(max * 1000), None).unwrap(), Some(i32::MAX as u32));
        assert!(conv(Some(max * 1000 + 1), None).is_err(), "int32 seconds + 1 is refused");
        assert!(conv(Some((u32::MAX as u64) * 1000), None).is_err(), "fits u32, not int32");
        assert_eq!(conv(None, Some(i32::MAX as u32)).unwrap(), Some(i32::MAX as u32));
        assert!(conv(None, Some(i32::MAX as u32 + 1)).is_err(), "legacy seconds above int32 are refused too");
    }

    /// The wire field stays timeoutSeconds, and the new option's name is never sent.
    #[tokio::test]
    async fn session_timeout_ms_is_sent_as_timeout_seconds() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![(201, r#"{"sessionId":"s_1","wsEndpoint":"wss://gw.example.com/ws/s_1"}"#.to_string())],
        );
        client_for(port)
            .sessions()
            .create(CreateSessionOptions::new().session_timeout_ms(61_001))
            .await
            .unwrap();
        let raw = captured.lock().unwrap()[0].clone();
        let (_, body) = split_req(&raw);
        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
        assert_eq!(json["timeoutSeconds"], 62);
        assert!(json.get("sessionTimeoutMs").is_none() && json.get("session_timeout_ms").is_none());
    }

    /// The deprecated builder method still sends its seconds.
    #[allow(deprecated)]
    #[tokio::test]
    async fn deprecated_timeout_seconds_still_works() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![(201, r#"{"sessionId":"s_1","wsEndpoint":"wss://gw.example.com/ws/s_1"}"#.to_string())],
        );
        client_for(port)
            .sessions()
            .create(CreateSessionOptions::new().timeout_seconds(90))
            .await
            .unwrap();
        let raw = captured.lock().unwrap()[0].clone();
        let (_, body) = split_req(&raw);
        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
        assert_eq!(json["timeoutSeconds"], 90);
    }

    /// The new options add nothing to the body when unset: still no body at all.
    #[tokio::test]
    async fn new_create_options_are_omitted_when_unset() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![(201, r#"{"sessionId":"s_2","wsEndpoint":"wss://gw.example.com/ws/s_2"}"#.to_string())],
        );
        client_for(port)
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap();
        let raw = captured.lock().unwrap()[0].clone();
        let (_, body) = split_req(&raw);
        assert!(body.trim().is_empty(), "body: {body}");
    }

    /// get lifts the gateway's fields out of the response.
    #[tokio::test]
    async fn get_returns_the_gateway_view() {
        let (l, port) = bind_mock().await;
        let body = r#"{"id":"s_1","status":"active","kind":"stealth","org":"o1","createdAt":"c","expiresAt":"e","userMetadata":{"a":"b"},"wsEndpoint":"wss://gw/ws/s_1","cdpEndpoint":"wss://gw/cdp/s_1"}"#;
        let _ = serve(l, vec![(200, body.to_string())]);
        let v = client_for(port).sessions().get("s_1").await.unwrap();
        assert_eq!(v.id.as_deref(), Some("s_1"));
        assert_eq!(v.kind.as_deref(), Some("stealth"));
        assert_eq!(v.org.as_deref(), Some("o1"));
        assert_eq!(v.user_metadata.unwrap()["a"], "b");
        assert!(v.cdp_endpoint.is_some() && v.ws_endpoint.is_some());
    }

    #[tokio::test]
    async fn list_sends_paging_and_the_metadata_filter_and_parses_the_page() {
        let (l, port) = bind_mock().await;
        let body = r#"{"sessions":[{"id":"s1","status":"active","kind":"fast","createdAt":"c","expiresAt":"e","userMetadata":{"team":"x"}},{"id":"s2","status":"released"}],"nextCursor":"cur2"}"#;
        let captured = serve(l, vec![(200, body.to_string())]);

        let mut opts = ListSessionsOptions::default();
        opts.limit = Some(2);
        opts.cursor = Some("cur1".into());
        opts.metadata.insert("team".into(), "x".into());
        opts.metadata.insert("env".into(), "prod".into());
        let page = client_for(port).sessions().list(opts).await.unwrap();

        let raw = captured.lock().unwrap()[0].clone();
        let (head, _) = split_req(&raw);
        assert!(head.starts_with("GET /sessions?"), "head: {head}");
        assert!(head.contains("limit=2"), "head: {head}");
        assert!(head.contains("cursor=cur1"), "head: {head}");
        // Pairs are sorted by key and joined by AND.
        assert!(
            head.contains("q=user_metadata%5B%27env%27%5D%3A%27prod%27%20AND%20user_metadata%5B%27team%27%5D%3A%27x%27"),
            "head: {head}"
        );
        assert_eq!(page.sessions.len(), 2);
        assert_eq!(page.sessions[0].id, "s1");
        assert_eq!(page.sessions[0].user_metadata.as_ref().unwrap()["team"], "x");
        assert_eq!(page.sessions[1].status, "released");
        assert_eq!(page.next_cursor.as_deref(), Some("cur2"));
    }

    #[tokio::test]
    async fn list_with_default_options_requests_a_bare_path_and_handles_an_empty_page() {
        let (l, port) = bind_mock().await;
        let captured = serve(l, vec![(200, r#"{"sessions":[]}"#.to_string())]);
        let page = client_for(port)
            .sessions()
            .list(ListSessionsOptions::default())
            .await
            .unwrap();
        let raw = captured.lock().unwrap()[0].clone();
        let (head, _) = split_req(&raw);
        assert!(head.starts_with("GET /sessions HTTP/1.1"), "head: {head}");
        assert!(page.sessions.is_empty());
        assert!(page.next_cursor.is_none());
    }

    /// A filter the gateway grammar cannot express is refused before any request is sent.
    #[tokio::test]
    async fn list_refuses_an_unexpressible_filter_without_a_request() {
        let (l, port) = bind_mock().await;
        let captured = serve(l, vec![(200, r#"{"sessions":[]}"#.to_string())]);
        let client = client_for(port);

        for (k, v) in [("k", "it's"), ("k'", "v"), ("", "v")] {
            let mut opts = ListSessionsOptions::default();
            opts.metadata.insert(k.into(), v.into());
            assert!(client.sessions().list(opts).await.is_err(), "{k:?}={v:?}");
        }
        let mut many = ListSessionsOptions::default();
        for i in 0..11 {
            many.metadata.insert(format!("k{i}"), "v".into());
        }
        assert!(client.sessions().list(many).await.is_err());
        assert!(captured.lock().unwrap().is_empty(), "no request may be sent");
    }

    /// A gateway 400 on the filter surfaces its code.
    #[tokio::test]
    async fn list_surfaces_a_gateway_validation_error() {
        let (l, port) = bind_mock().await;
        let _ = serve(
            l,
            vec![(400, r#"{"error":"Invalid q","code":"ValidationError","field":"q"}"#.to_string())],
        );
        let err = client_for(port)
            .sessions()
            .list(ListSessionsOptions::default())
            .await
            .unwrap_err();
        assert_eq!(err.status(), Some(400));
    }

    /// With no options at all, the body is omitted entirely (not `{}`).
    #[tokio::test]
    async fn create_session_omits_empty_body() {
        let (l, port) = bind_mock().await;
        let body = r#"{"sessionId":"s_2","wsEndpoint":"wss://gw.example.com/ws/s_2"}"#;
        let captured = serve(l, vec![(201, body.to_string())]);

        let client = client_for(port);
        client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap();

        let raw = captured.lock().unwrap()[0].clone();
        let (head, body) = split_req(&raw);
        assert!(body.trim().is_empty(), "expected no body, got: {body}");
        assert!(
            !head.to_lowercase().contains("content-length: 2"),
            "head: {head}"
        );
    }

    /// A full ProxyRequest serializes camelCase, with unset fields omitted.
    #[tokio::test]
    async fn create_session_proxy_request_shape() {
        let (l, port) = bind_mock().await;
        let body = r#"{"sessionId":"s_3","wsEndpoint":"wss://gw.example.com/ws/s_3","proxy":{"server":"http://p:1","username":"u","password":"p","timezoneId":"America/Los_Angeles","country":"us","tier":"mobile"}}"#;
        let captured = serve(l, vec![(201, body.to_string())]);

        let client = client_for(port);
        let session = client
            .sessions()
            .create(CreateSessionOptions::new().stealth(true).proxy(
                ProxyRequest::country("us")
                    .tier(ProxyTier::Mobile)
                    .session("warm-1")
                    .session_duration(15),
            ))
            .await
            .unwrap();

        let proxy = session.proxy.expect("resolved proxy");
        assert_eq!(proxy.country, "us");
        assert_eq!(proxy.tier, Some(ProxyTier::Mobile));
        assert_eq!(proxy.timezone_id, "America/Los_Angeles");

        let raw = captured.lock().unwrap()[0].clone();
        let (_, body) = split_req(&raw);
        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
        let p = json.get("proxy").unwrap();
        assert_eq!(p.get("country").unwrap(), "us");
        assert_eq!(p.get("tier").unwrap(), "mobile");
        assert_eq!(p.get("session").unwrap(), "warm-1");
        assert_eq!(p.get("sessionDuration").unwrap(), 15);
        assert!(p.get("asn").is_none());
        assert!(p.get("city").is_none());
    }

    /// The gateway marks `404 ReplayPending` retryable: the recording upload is
    /// still in flight. An idempotent GET must honour that hint even though 404
    /// is nowhere near the 5xx allowlist.
    #[tokio::test]
    async fn retryable_hint_retries_idempotent_get() {
        let (l, port) = bind_mock().await;
        let pending =
            r#"{"error":"replay still uploading","code":"ReplayPending","retryable":true}"#;
        let ok = r#"{"url":"https://s3/replay.ndjson.gz"}"#;
        let captured = serve(
            l,
            vec![(404, pending.to_string()), (200, ok.to_string())],
        );

        let client = client_for(port);
        let link = client.sessions().replay_url("sess-1").await.unwrap();

        assert_eq!(link.url, "https://s3/replay.ndjson.gz");
        // Two attempts: the hint is what produced the second.
        assert_eq!(captured.lock().unwrap().len(), 2);
    }

    /// A 404 WITHOUT the hint is terminal -- the FLAG changes the outcome, not
    /// the status.
    #[tokio::test]
    async fn no_hint_means_no_retry() {
        let (l, port) = bind_mock().await;
        let terminal = r#"{"error":"no replay","code":"ReplayUnavailable"}"#;
        let captured = serve(
            l,
            vec![
                (404, terminal.to_string()),
                (200, r#"{"url":"never reached"}"#.to_string()),
            ],
        );

        let client = client_for(port);
        assert!(client.sessions().replay_url("sess-1").await.is_err());
        assert_eq!(captured.lock().unwrap().len(), 1);
    }

    /// RETRACTED REASON, kept deliberately. This asserted the opposite, because
    /// "the browser API issues no Idempotency-Key, so a re-sent create could
    /// leave a second live session behind". Creates now mint a key, so the
    /// gateway answers the retry from the first result instead of creating
    /// twice -- the condition was removed, not worked around.
    ///
    /// This is the case the gateway-side guard produces: a duplicate arriving
    /// while the first create is still running is answered 409 + retryable.
    #[tokio::test]
    async fn retryable_hint_honoured_on_keyed_create() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![
                (409, r#"{"error":"in progress","retryable":true}"#.to_string()),
                (201, r#"{"sessionId":"s_ok","wsEndpoint":"wss://x/ws/s_ok"}"#.to_string()),
            ],
        );

        let client = client_for(port);
        assert!(client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .is_ok());
        let reqs = captured.lock().unwrap();
        assert_eq!(reqs.len(), 2, "the hint must be honoured on a keyed create");

        // The key identifies the CALL, not the attempt: a fresh key per retry
        // would silently defeat the mechanism (the gateway would see two
        // distinct keys and create twice) while every assertion above still
        // passes. Only comparing the two captured headers catches that.
        fn idempotency_key(head: &str) -> Option<String> {
            for line in head.lines() {
                if let Some(v) = line.to_lowercase().strip_prefix("idempotency-key:") {
                    return Some(v.trim().to_string());
                }
            }
            None
        }
        let (head1, _) = split_req(&reqs[0]);
        let (head2, _) = split_req(&reqs[1]);
        let key1 = idempotency_key(&head1).expect("first attempt must carry a key");
        let key2 = idempotency_key(&head2).expect("second attempt must carry a key");
        assert_eq!(key1, key2, "retries must reuse the SAME key, not mint a fresh one");
    }

    /// A key identifies the CALL: two separate creates must not share one.
    #[tokio::test]
    async fn idempotency_keys_differ_between_calls() {
        assert_ne!(
            crate::http::new_idempotency_key(),
            crate::http::new_idempotency_key()
        );
    }

    /// 503 is retried up to max_attempts and can succeed on the second try.
    #[tokio::test]
    async fn retries_on_503() {
        let (l, port) = bind_mock().await;
        let ok = r#"{"sessionId":"s_ok","wsEndpoint":"wss://gw.example.com/ws/s_ok"}"#;
        let captured = serve(
            l,
            vec![
                (503, r#"{"error":"no capacity"}"#.to_string()),
                (201, ok.to_string()),
            ],
        );

        let client = client_for(port);
        let session = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap();

        assert_eq!(session.id, "s_ok");
        // Two attempts were actually made.
        assert_eq!(captured.lock().unwrap().len(), 2);
    }

    /// A 502 PoolResponseUnparseable carries retryable:false (the pool may already have created the
    /// session): one attempt, and the code reaches the caller.
    #[tokio::test]
    async fn pool_response_unparseable_502_is_not_retried() {
        let (l, port) = bind_mock().await;
        let ok = r#"{"sessionId":"s_ok","wsEndpoint":"wss://gw.example.com/ws/s_ok"}"#;
        let captured = serve(
            l,
            vec![
                (
                    502,
                    r#"{"error":"Pool returned an invalid response","code":"PoolResponseUnparseable","retryable":false}"#.to_string(),
                ),
                (201, ok.to_string()),
            ],
        );

        let client = client_for(port);
        let err = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap_err();

        assert_eq!(err.status(), Some(502));
        assert_eq!(captured.lock().unwrap().len(), 1, "retryable:false must not be retried");
    }

    /// Retries are exhausted after max_attempts → the last response, with its status and code.
    #[tokio::test]
    async fn retries_exhausted_on_persistent_503() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![
                (503, "{}".to_string()),
                (503, "{}".to_string()),
                (201, "{}".to_string()), // never reached: max_attempts is 2
            ],
        );

        let client = client_for(port);
        let err = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap_err();

        assert!(matches!(err, SolariError::Api { .. }), "{err:?}");
        assert_eq!(err.status(), Some(503));
        assert_eq!(captured.lock().unwrap().len(), 2);
    }

    /// A 503 with a code that outlasts the retries keeps that code.
    #[tokio::test]
    async fn final_5xx_keeps_its_code() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![
                (503, r#"{"error":"unhealthy","code":"BrowserUnhealthy"}"#.to_string()),
                (503, r#"{"error":"unhealthy","code":"BrowserUnhealthy"}"#.to_string()),
            ],
        );

        let client = client_for(port);
        let err = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap_err();

        assert_eq!(err.status(), Some(503));
        assert_eq!(err.code(), Some(&SolariErrorCode::BrowserUnhealthy));
        assert_eq!(captured.lock().unwrap().len(), 2);
    }

    /// A transport failure that outlasts the retries is still the exhausted Transport error.
    #[tokio::test]
    async fn transport_failure_exhausts_as_transport_error() {
        let (l, port) = bind_mock().await;
        drop(l); // nothing listens on this port any more
        let client = client_for(port);
        let err = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap_err();

        assert!(matches!(err, SolariError::Transport { .. }), "{err:?}");
        assert!(err.to_string().contains("exhausted 2 attempts"), "{err}");
    }

    /// 400 is NOT retried — it comes straight back on the first attempt.
    #[tokio::test]
    async fn does_not_retry_on_400() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![
                (400, r#"{"error":"bad proxy country"}"#.to_string()),
                (201, "{}".to_string()), // must NOT be consumed
            ],
        );

        let client = client_for(port);
        let err = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap_err();

        assert_eq!(err.status(), Some(400));
        assert!(err.to_string().contains("bad proxy country"), "{err}");
        // Exactly one request was made.
        assert_eq!(captured.lock().unwrap().len(), 1);
    }

    /// `{code}` is parsed out of error bodies into the typed enum; unknown codes
    /// survive as `Other`.
    #[tokio::test]
    async fn parses_error_codes() {
        let (l, port) = bind_mock().await;
        serve(
            l,
            vec![
                (
                    402,
                    r#"{"code":"FeatureRequiresPlan","error":"captcha requires a paid plan"}"#
                        .to_string(),
                ),
                (
                    429,
                    r#"{"code":"ConcurrencyLimitExceeded"}"#.to_string(),
                ),
                (400, r#"{"code":"SomethingNew"}"#.to_string()),
                (400, "not json at all".to_string()),
            ],
        );

        let client = client_for(port);

        let err = client
            .sessions()
            .create(CreateSessionOptions::new().captcha(true))
            .await
            .unwrap_err();
        assert_eq!(err.status(), Some(402));
        assert_eq!(err.code(), Some(&SolariErrorCode::FeatureRequiresPlan));
        assert!(err.to_string().contains("captcha requires a paid plan"));

        let err = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap_err();
        assert_eq!(err.status(), Some(429));
        assert_eq!(err.code(), Some(&SolariErrorCode::ConcurrencyLimitExceeded));

        // Unknown code → preserved verbatim, not dropped.
        let err = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap_err();
        assert_eq!(
            err.code(),
            Some(&SolariErrorCode::Other("SomethingNew".to_string()))
        );

        // Non-JSON body → no code, but still a typed API error with the status.
        let err = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap_err();
        assert_eq!(err.status(), Some(400));
        assert_eq!(err.code(), None);
    }

    /// GET /profiles parses the list, including unknown keys via `extra`.
    #[tokio::test]
    async fn profiles_list_parses() {
        let (l, port) = bind_mock().await;
        let body = r#"[{"id":"p_1","name":"amazon","createdAt":"2026-01-01T00:00:00Z"},{"id":"p_2","name":"gmail"}]"#;
        let captured = serve(l, vec![(200, body.to_string())]);

        let client = client_for(port);
        let profiles = client.profiles().list().await.unwrap();

        assert_eq!(profiles.len(), 2);
        assert_eq!(profiles[0].id, "p_1");
        assert_eq!(profiles[0].name, "amazon");
        // Index-signature keys survive.
        assert_eq!(
            profiles[0].extra.get("createdAt").unwrap(),
            "2026-01-01T00:00:00Z"
        );
        assert_eq!(profiles[1].id, "p_2");
        assert!(profiles[1].extra.is_empty());

        let (head, _) = split_req(&captured.lock().unwrap()[0]);
        assert!(head.starts_with("GET /profiles "), "head: {head}");
    }

    /// POST /profiles sends `{name}` and parses the created profile.
    #[tokio::test]
    async fn profiles_create_and_save() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![
                (201, r#"{"id":"p_9","name":"shopify"}"#.to_string()),
                (200, r#"{"version":3,"sizeBytes":2048}"#.to_string()),
                (200, "{}".to_string()), // save with defaults
            ],
        );

        let client = client_for(port);
        let profile = client.profiles().create("shopify").await.unwrap();
        assert_eq!(profile.id, "p_9");
        assert_eq!(profile.name, "shopify");

        let state = StorageState {
            cookies: Some(vec![Cookie {
                name: "sid".into(),
                value: "abc".into(),
                domain: Some(".shopify.com".into()),
                same_site: Some(SameSite::Lax),
                ..Default::default()
            }]),
            ..Default::default()
        };
        let saved = client.profiles().save("p_9", &state).await.unwrap();
        assert_eq!(saved.version, 3);
        assert_eq!(saved.size_bytes, 2048);

        // Missing fields default to 0.
        let saved = client.profiles().save("p_9", &state).await.unwrap();
        assert_eq!(saved.version, 0);
        assert_eq!(saved.size_bytes, 0);

        let reqs = captured.lock().unwrap().clone();
        let (head, body) = split_req(&reqs[0]);
        assert!(head.starts_with("POST /profiles "), "head: {head}");
        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
        assert_eq!(json.get("name").unwrap(), "shopify");

        // save wraps the state under `storageState` and keeps camelCase inside.
        let (head, body) = split_req(&reqs[1]);
        assert!(head.starts_with("POST /profiles/p_9/save "), "head: {head}");
        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
        let cookie = &json["storageState"]["cookies"][0];
        assert_eq!(cookie.get("name").unwrap(), "sid");
        assert_eq!(cookie.get("domain").unwrap(), ".shopify.com");
        assert_eq!(cookie.get("sameSite").unwrap(), "Lax");
        // Unset cookie fields are omitted, not sent as null.
        assert!(cookie.get("httpOnly").is_none(), "cookie: {cookie}");
    }

    /// DELETE tolerates 404 on both sessions and profiles.
    #[tokio::test]
    async fn delete_tolerates_404() {
        let (l, port) = bind_mock().await;
        serve(
            l,
            vec![
                (404, r#"{"error":"Not Found"}"#.to_string()),
                (404, r#"{"error":"Not Found"}"#.to_string()),
                (500, r#"{"error":"boom"}"#.to_string()),
            ],
        );

        let client = client_for(port);
        client.sessions().release("s_gone").await.unwrap();
        client.profiles().delete("p_gone").await.unwrap();
        // But a real failure still propagates.
        let err = client.sessions().release("s_bad").await.unwrap_err();
        assert_eq!(err.status(), Some(500));
    }

    /// replay-url defaults: expiresInSeconds → 0, contentEncoding → "gzip".
    #[tokio::test]
    async fn replay_url_defaults() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![
                (200, r#"{"url":"https://s3.example.com/r1"}"#.to_string()),
                (
                    200,
                    r#"{"url":"https://s3.example.com/r2","expiresInSeconds":600,"contentEncoding":"identity"}"#
                        .to_string(),
                ),
                (200, r#"{"expiresInSeconds":600}"#.to_string()),
            ],
        );

        let client = client_for(port);

        let replay = client.sessions().replay_url("s_1").await.unwrap();
        assert_eq!(replay.url, "https://s3.example.com/r1");
        assert_eq!(replay.expires_in_seconds, 0);
        assert_eq!(replay.content_encoding, "gzip");

        let replay = client.sessions().replay_url("s_2").await.unwrap();
        assert_eq!(replay.expires_in_seconds, 600);
        assert_eq!(replay.content_encoding, "identity");

        // A body with no url is a protocol error, not a silent empty string.
        let err = client.sessions().replay_url("s_3").await.unwrap_err();
        assert!(matches!(err, SolariError::Protocol { .. }), "{err:?}");

        let (head, _) = split_req(&captured.lock().unwrap()[0]);
        assert!(head.starts_with("GET /sessions/s_1/replay-url "), "head: {head}");
    }

    /// GET /proxy/countries.
    #[tokio::test]
    async fn proxy_countries() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![(
                200,
                r#"{"enabled":true,"countries":["br","de","gb","us"]}"#.to_string(),
            )],
        );

        let client = client_for(port);
        let res = client.proxy().countries().await.unwrap();
        assert!(res.enabled);
        assert_eq!(res.countries, vec!["br", "de", "gb", "us"]);

        let (head, _) = split_req(&captured.lock().unwrap()[0]);
        assert!(head.starts_with("GET /proxy/countries "), "head: {head}");
    }

    /// GET /sessions/:id.
    #[tokio::test]
    async fn session_get_parses() {
        let (l, port) = bind_mock().await;
        serve(
            l,
            vec![(
                200,
                r#"{"sessionId":"s_1","status":"busy","expiresAt":"2026-01-01T00:00:00Z","slot":3}"#
                    .to_string(),
            )],
        );

        let client = client_for(port);
        let view = client.sessions().get("s_1").await.unwrap();
        assert_eq!(view.session_id.as_deref(), Some("s_1"));
        assert_eq!(view.status.as_deref(), Some("busy"));
        assert_eq!(view.expires_at.as_deref(), Some("2026-01-01T00:00:00Z"));
        assert_eq!(view.extra.get("slot").unwrap(), 3);
    }

    /// cdpEndpoint is derived from wsEndpoint when the API omits it.
    #[test]
    fn cdp_derivation() {
        assert_eq!(
            derive_cdp_from_ws("wss://api.getsolari.com/ws/abc.def"),
            "wss://api.getsolari.com/cdp/abc.def"
        );
        assert_eq!(
            derive_cdp_from_ws("ws://127.0.0.1:3000/ws/s_1?token=x"),
            "ws://127.0.0.1:3000/cdp/s_1?token=x"
        );
        // Non-/ws/ paths pass through untouched.
        assert_eq!(
            derive_cdp_from_ws("wss://api.getsolari.com/other/abc"),
            "wss://api.getsolari.com/other/abc"
        );
        // Unparseable input passes through untouched.
        assert_eq!(derive_cdp_from_ws("not a url"), "not a url");
    }

    /// A create response without cdpEndpoint derives one from wsEndpoint.
    #[tokio::test]
    async fn create_session_derives_cdp() {
        let (l, port) = bind_mock().await;
        let body = r#"{"sessionId":"s_1","wsEndpoint":"wss://gw.example.com/ws/s_1"}"#;
        serve(l, vec![(201, body.to_string())]);

        let client = client_for(port);
        let session = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap();

        assert_eq!(session.ws_endpoint, "wss://gw.example.com/ws/s_1");
        assert_eq!(session.cdp_endpoint, "wss://gw.example.com/cdp/s_1");
        // expiresAt was omitted → a ~1h ISO-8601 UTC fallback was synthesized.
        assert!(session.expires_at.ends_with('Z'), "{}", session.expires_at);
        assert_eq!(session.expires_at.len(), 24, "{}", session.expires_at);
    }

    /// A malformed create response (no sessionId) is a protocol error.
    #[tokio::test]
    async fn create_session_rejects_bad_response() {
        let (l, port) = bind_mock().await;
        serve(l, vec![(201, r#"{"wsEndpoint":"wss://x/ws/1"}"#.to_string())]);

        let client = client_for(port);
        let err = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap_err();
        assert!(matches!(err, SolariError::Protocol { .. }), "{err:?}");
    }

    /// With a profileId, `storageStateUrl` is followed to the presigned object.
    #[tokio::test]
    async fn storage_state_fetched_from_presigned_url() {
        let (l, port) = bind_mock().await;
        let create = format!(
            r#"{{"sessionId":"s_1","wsEndpoint":"wss://gw.example.com/ws/s_1","storageStateUrl":{{"url":"http://127.0.0.1:{port}/presigned","expiresInSeconds":60}}}}"#
        );
        let state = r#"{"cookies":[{"name":"sid","value":"abc","domain":".example.com","sameSite":"Lax"}],"origins":[{"origin":"https://example.com","localStorage":[{"name":"k","value":"v"}]}]}"#;
        serve(l, vec![(201, create), (200, state.to_string())]);

        let client = client_for(port);
        let session = client
            .sessions()
            .create(CreateSessionOptions::new().profile_id("p_1"))
            .await
            .unwrap();

        let state = session
            .storage_state
            .expect("profile attached → Some")
            .expect("presigned state → Some");
        let cookies = state.cookies.unwrap();
        assert_eq!(cookies[0].name, "sid");
        assert_eq!(cookies[0].same_site, Some(SameSite::Lax));
        let origins = state.origins.unwrap();
        assert_eq!(origins[0].origin, "https://example.com");
        assert_eq!(origins[0].local_storage.as_ref().unwrap()[0].value, "v");
    }

    /// The three storage-state states are distinguished: absent vs empty vs set.
    #[tokio::test]
    async fn storage_state_absent_vs_empty() {
        let (l, port) = bind_mock().await;
        serve(
            l,
            vec![
                // profileId requested, storageStateUrl.url is null → empty profile.
                (
                    201,
                    r#"{"sessionId":"s_1","wsEndpoint":"wss://x/ws/s_1","storageStateUrl":{"url":null}}"#
                        .to_string(),
                ),
                // profileId requested, no storageStateUrl at all → empty profile.
                (
                    201,
                    r#"{"sessionId":"s_2","wsEndpoint":"wss://x/ws/s_2"}"#.to_string(),
                ),
                // profileId requested, legacy inline storageState → populated.
                (
                    201,
                    r#"{"sessionId":"s_3","wsEndpoint":"wss://x/ws/s_3","storageState":{"cookies":[]}}"#
                        .to_string(),
                ),
                // No profileId → absent entirely.
                (
                    201,
                    r#"{"sessionId":"s_4","wsEndpoint":"wss://x/ws/s_4"}"#.to_string(),
                ),
            ],
        );

        let client = client_for(port);

        let s = client
            .sessions()
            .create(CreateSessionOptions::new().profile_id("p_1"))
            .await
            .unwrap();
        assert!(matches!(s.storage_state, Some(None)), "null url → Some(None)");

        let s = client
            .sessions()
            .create(CreateSessionOptions::new().profile_id("p_1"))
            .await
            .unwrap();
        assert!(matches!(s.storage_state, Some(None)), "no url → Some(None)");

        let s = client
            .sessions()
            .create(CreateSessionOptions::new().profile_id("p_1"))
            .await
            .unwrap();
        let inline = s.storage_state.expect("Some").expect("Some");
        assert_eq!(inline.cookies.unwrap().len(), 0);

        let s = client
            .sessions()
            .create(CreateSessionOptions::default())
            .await
            .unwrap();
        assert!(s.storage_state.is_none(), "no profile → None");
    }

    /// Client construction: defaults, validation, region resolution.
    #[test]
    fn client_options_and_defaults() {
        let opts = ClientOptions::default_region("k");
        assert_eq!(opts.base_url, "https://api.getsolari.com");
        assert_eq!(opts.max_attempts, 2);
        assert_eq!(opts.backoff_ms, 500);
        assert_eq!(opts.timeout_ms, 90_000);

        assert_eq!(
            ClientOptions::for_region("k", SolariRegion::UsWest).base_url,
            "https://api.getsolari.com"
        );

        // Trailing slashes are stripped.
        let c = Client::new(ClientOptions::new("k", "https://gw.example.com/")).unwrap();
        assert_eq!(c.base_url(), "https://gw.example.com");

        // An empty api key is rejected.
        let err = Client::new(ClientOptions::new("", "https://gw.example.com")).unwrap_err();
        assert!(matches!(err, SolariError::Config { .. }), "{err:?}");
    }

    /// The ISO-8601 fallback formatter. Expectations cross-checked against
    /// `date -u -d @<ts>`.
    #[test]
    fn iso8601_formatting() {
        assert_eq!(iso8601_utc(0), "1970-01-01T00:00:00.000Z");
        assert_eq!(iso8601_utc(1_768_000_000), "2026-01-09T23:06:40.000Z");
        assert_eq!(iso8601_utc(1_000_000_000), "2001-09-09T01:46:40.000Z");
        // 2024-02-29 (leap day) 12:00:00Z.
        assert_eq!(iso8601_utc(1_709_208_000), "2024-02-29T12:00:00.000Z");
        // 2000 is a leap year (divisible by 400) — the century special case.
        assert_eq!(iso8601_utc(951_782_400), "2000-02-29T00:00:00.000Z");
        // 2100 is NOT a leap year (divisible by 100, not 400).
        assert_eq!(iso8601_utc(4_102_444_800), "2100-01-01T00:00:00.000Z");
        // Pre-epoch must floor, not truncate toward zero.
        assert_eq!(iso8601_utc(-1), "1969-12-31T23:59:59.000Z");
    }

    /// Error codes round-trip through their wire strings.
    #[test]
    fn error_code_round_trip() {
        for code in [
            SolariErrorCode::FeatureRequiresPlan,
            SolariErrorCode::ConcurrencyLimitExceeded,
            SolariErrorCode::PlanLimitExceeded,
            SolariErrorCode::BrowserUnhealthy,
        ] {
            assert_eq!(SolariErrorCode::from(code.as_str()), code);
        }
        assert_eq!(
            SolariErrorCode::from("BrowserUnhealthy"),
            SolariErrorCode::BrowserUnhealthy
        );
        assert_eq!(
            SolariErrorCode::Other("Nope".into()).to_string(),
            "Nope".to_string()
        );
    }

    // Regression: launch()'s retry loop must retry create() itself on a
    // transient failure, not only the connect+probe step after it. A bare
    // `?` on create() short-circuits launch() before opts.retries/is_transient
    // are ever consulted -- found in review (Feature 3), proved with this
    // harness before the fix landed.
    #[cfg(feature = "connect")]
    #[tokio::test]
    async fn launch_retries_create_itself_on_transient_exhaustion() {
        let (l, port) = bind_mock().await;
        let captured = serve(
            l,
            vec![
                // First create(): exhausts max_attempts(2) on 503 -> Transport
                // error, which is_transient says yes to.
                (503, "{}".to_string()),
                (503, "{}".to_string()),
                // Second create() (the retry launch() must make): a single
                // non-transient 400 ends the loop deterministically, so the
                // request count alone proves the retry fired.
                (400, r#"{"error":"bad request"}"#.to_string()),
            ],
        );

        let client = client_for(port);
        let result = client
            .launch(LaunchOptions::new(CreateSessionOptions::default()).retries(1))
            .await;
        let Err(err) = result else {
            panic!("expected second create()'s 400 to end the loop, got Ok");
        };

        assert_eq!(err.status(), Some(400));
        // 2 (exhausted first create) + 1 (second create) == 3. If the bare
        // `?` regression were present, launch() would return on the first
        // create()'s Transport error and this would be 2.
        assert_eq!(captured.lock().unwrap().len(), 3);
    }
}