opencode-sdk 0.1.7

Rust SDK for OpenCode (HTTP-first hybrid with SSE streaming)
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
//! Sessions API for OpenCode.
//!
//! This module provides methods for session endpoints (18 total).

use crate::error::Result;
use crate::http::HttpClient;
use crate::types::session::{
    CreateSessionRequest, RevertRequest, Session, SessionCreateOptions, SessionDiff, SessionStatus,
    ShareInfo, SummarizeRequest, TodoItem, UpdateSessionRequest,
};
use reqwest::Method;

/// Sessions API client.
#[derive(Clone)]
pub struct SessionsApi {
    http: HttpClient,
}

impl SessionsApi {
    /// Create a new Sessions API client.
    pub fn new(http: HttpClient) -> Self {
        Self { http }
    }

    /// Create a new session.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn create(&self, req: &CreateSessionRequest) -> Result<Session> {
        let body = serde_json::to_value(req)?;

        let path = if let Some(directory) = &req.directory {
            format!("/session?directory={}", urlencoding::encode(directory))
        } else {
            "/session".to_string()
        };

        self.http
            .request_json(Method::POST, &path, Some(body))
            .await
    }

    /// Create a new session using convenience options.
    ///
    /// This maps to the same wire format/query semantics as [`Self::create`].
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn create_with(&self, options: SessionCreateOptions) -> Result<Session> {
        let req: CreateSessionRequest = options.into();
        self.create(&req).await
    }

    /// Get session by ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or session not found.
    pub async fn get(&self, id: &str) -> Result<Session> {
        self.http
            .request_json(Method::GET, &format!("/session/{}", id), None)
            .await
    }

    /// List all sessions.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn list(&self) -> Result<Vec<Session>> {
        self.http.request_json(Method::GET, "/session", None).await
    }

    /// Delete session by ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn delete(&self, id: &str) -> Result<()> {
        self.http
            .request_empty(Method::DELETE, &format!("/session/{}", id), None)
            .await
    }

    /// Fork a session from a specific point.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn fork(&self, id: &str) -> Result<Session> {
        self.http
            .request_json(
                Method::POST,
                &format!("/session/{}/fork", id),
                Some(serde_json::json!({})),
            )
            .await
    }

    /// Abort an active session.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn abort(&self, id: &str) -> Result<()> {
        self.http
            .request_empty(
                Method::POST,
                &format!("/session/{}/abort", id),
                Some(serde_json::json!({})),
            )
            .await
    }

    /// Get session status.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn status(&self) -> Result<SessionStatus> {
        self.http
            .request_json(Method::GET, "/session/status", None)
            .await
    }

    /// Get children of a session (forked sessions).
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn children(&self, id: &str) -> Result<Vec<Session>> {
        self.http
            .request_json(Method::GET, &format!("/session/{}/children", id), None)
            .await
    }

    /// Get todos for a session.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn todo(&self, id: &str) -> Result<Vec<TodoItem>> {
        self.http
            .request_json(Method::GET, &format!("/session/{}/todo", id), None)
            .await
    }

    /// Update a session.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn update(&self, id: &str, req: &UpdateSessionRequest) -> Result<Session> {
        let body = serde_json::to_value(req)?;
        self.http
            .request_json(Method::PATCH, &format!("/session/{}", id), Some(body))
            .await
    }

    /// Initialize a session.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn init(&self, id: &str) -> Result<Session> {
        self.http
            .request_json(
                Method::POST,
                &format!("/session/{}/init", id),
                Some(serde_json::json!({})),
            )
            .await
    }

    /// Share a session.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn share(&self, id: &str) -> Result<ShareInfo> {
        self.http
            .request_json(
                Method::POST,
                &format!("/session/{}/share", id),
                Some(serde_json::json!({})),
            )
            .await
    }

    /// Unshare a session.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn unshare(&self, id: &str) -> Result<()> {
        self.http
            .request_empty(Method::DELETE, &format!("/session/{}/share", id), None)
            .await
    }

    /// Get session diff.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn diff(&self, id: &str) -> Result<SessionDiff> {
        self.http
            .request_json(Method::GET, &format!("/session/{}/diff", id), None)
            .await
    }

    /// Get session diff since a specific message.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn diff_since_message(&self, id: &str, message_id: &str) -> Result<SessionDiff> {
        let encoded = urlencoding::encode(message_id);
        self.http
            .request_json(
                Method::GET,
                &format!("/session/{}/diff?messageID={}", id, encoded),
                None,
            )
            .await
    }

    /// Summarize a session.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn summarize(&self, id: &str, req: &SummarizeRequest) -> Result<Session> {
        let body = serde_json::to_value(req)?;
        self.http
            .request_json(
                Method::POST,
                &format!("/session/{}/summarize", id),
                Some(body),
            )
            .await
    }

    /// Revert a session to a previous state.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn revert(&self, id: &str, req: &RevertRequest) -> Result<Session> {
        let body = serde_json::to_value(req)?;
        self.http
            .request_json(Method::POST, &format!("/session/{}/revert", id), Some(body))
            .await
    }

    /// Unrevert a session (undo a revert).
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn unrevert(&self, id: &str) -> Result<Session> {
        self.http
            .request_json(
                Method::POST,
                &format!("/session/{}/unrevert", id),
                Some(serde_json::json!({})),
            )
            .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::HttpConfig;
    use std::time::Duration;
    use wiremock::matchers::{body_json, method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn test_create_session() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session"))
            .and(body_json(serde_json::json!({})))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "session123",
                "projectId": "proj1",
                "directory": "/path",
                "title": "New Session",
                "version": "1.0",
                "time": {"created": 1234567890, "updated": 1234567890}
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let session = sessions
            .create(&CreateSessionRequest::default())
            .await
            .unwrap();
        assert_eq!(session.id, "session123");
    }

    #[tokio::test]
    async fn test_create_session_with_options() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session"))
            .and(query_param("directory", "/tmp/project"))
            .and(body_json(serde_json::json!({
                "title": "Quick Win",
                "parentID": "parent-123"
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "session123",
                "projectId": "proj1",
                "directory": "/tmp/project",
                "title": "Quick Win",
                "version": "1.0",
                "time": {"created": 1234567890, "updated": 1234567890}
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let session = sessions
            .create_with(
                SessionCreateOptions::new()
                    .with_title("Quick Win")
                    .with_parent_id("parent-123")
                    .with_directory("/tmp/project"),
            )
            .await
            .unwrap();

        assert_eq!(session.id, "session123");
        assert_eq!(session.title, "Quick Win");
    }

    #[tokio::test]
    async fn test_get_session() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/session/abc123"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "abc123",
                "projectId": "p1",
                "directory": "/path",
                "title": "Test Session",
                "version": "1.0",
                "time": {"created": 1234567890, "updated": 1234567890}
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let session = sessions.get("abc123").await.unwrap();
        assert_eq!(session.id, "abc123");
        assert_eq!(session.title, "Test Session");
    }

    #[tokio::test]
    async fn test_list_sessions() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/session"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
                {"id": "s1", "projectId": "p1", "directory": "/path", "title": "S1", "version": "1.0", "time": {"created": 1234567890, "updated": 1234567890}},
                {"id": "s2", "projectId": "p1", "directory": "/path", "title": "S2", "version": "1.0", "time": {"created": 1234567890, "updated": 1234567890}}
            ])))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let list = sessions.list().await.unwrap();
        assert_eq!(list.len(), 2);
    }

    #[tokio::test]
    async fn test_delete_session() {
        let mock_server = MockServer::start().await;

        Mock::given(method("DELETE"))
            .and(path("/session/del123"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        sessions.delete("del123").await.unwrap();
    }

    #[tokio::test]
    async fn test_children() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/session/parent123/children"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
                {"id": "child1", "projectId": "p1", "directory": "/path", "title": "Child 1", "version": "1.0", "time": {"created": 1234567890, "updated": 1234567890}}
            ])))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let children = sessions.children("parent123").await.unwrap();
        assert_eq!(children.len(), 1);
        assert_eq!(children[0].id, "child1");
    }

    #[tokio::test]
    async fn test_todo() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/session/s1/todo"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
                {"id": "t1", "content": "Task 1", "completed": false},
                {"id": "t2", "content": "Task 2", "completed": true}
            ])))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let todos = sessions.todo("s1").await.unwrap();
        assert_eq!(todos.len(), 2);
        assert!(!todos[0].completed);
        assert!(todos[1].completed);
    }

    #[tokio::test]
    async fn test_update_session() {
        let mock_server = MockServer::start().await;

        Mock::given(method("PATCH"))
            .and(path("/session/s1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "s1",
                "projectId": "p1",
                "directory": "/path",
                "title": "Updated Title",
                "version": "1.0",
                "time": {"created": 1234567890, "updated": 1234567891}
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let session = sessions
            .update(
                "s1",
                &UpdateSessionRequest {
                    title: Some("Updated Title".into()),
                },
            )
            .await
            .unwrap();
        assert_eq!(session.title, "Updated Title");
    }

    #[tokio::test]
    async fn test_share() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session/s1/share"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "url": "https://share.example.com/s1"
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let share = sessions.share("s1").await.unwrap();
        assert_eq!(share.url, "https://share.example.com/s1");
    }

    #[tokio::test]
    async fn test_unshare() {
        let mock_server = MockServer::start().await;

        Mock::given(method("DELETE"))
            .and(path("/session/s1/share"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        sessions.unshare("s1").await.unwrap();
    }

    #[tokio::test]
    async fn test_diff() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/session/s1/diff"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "diff": "--- a/file.rs\n+++ b/file.rs\n@@ -1 +1 @@\n-old\n+new",
                "files": ["file.rs"]
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let diff = sessions.diff("s1").await.unwrap();
        assert!(diff.diff.contains("file.rs"));
        assert_eq!(diff.files.len(), 1);
    }

    #[tokio::test]
    async fn test_summarize() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session/s1/summarize"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "s1",
                "projectId": "p1",
                "directory": "/path",
                "title": "Summarized Session",
                "version": "1.0",
                "time": {"created": 1234567890, "updated": 1234567891}
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let session = sessions
            .summarize(
                "s1",
                &SummarizeRequest {
                    provider_id: "anthropic".into(),
                    model_id: "claude-3-5-sonnet".into(),
                    auto: None,
                },
            )
            .await
            .unwrap();
        assert_eq!(session.id, "s1");
    }

    #[tokio::test]
    async fn test_revert() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session/s1/revert"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "s1",
                "projectId": "p1",
                "directory": "/path",
                "title": "Reverted Session",
                "version": "1.0",
                "time": {"created": 1234567890, "updated": 1234567891}
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let session = sessions
            .revert(
                "s1",
                &crate::types::session::RevertRequest {
                    message_id: "m5".into(),
                    part_id: None,
                },
            )
            .await
            .unwrap();
        assert_eq!(session.id, "s1");
    }

    #[tokio::test]
    async fn test_unrevert() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session/s1/unrevert"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "s1",
                "projectId": "p1",
                "directory": "/path",
                "title": "Unreverted Session",
                "version": "1.0",
                "time": {"created": 1234567890, "updated": 1234567891}
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let session = sessions.unrevert("s1").await.unwrap();
        assert_eq!(session.id, "s1");
    }

    // ==================== Error Case Tests ====================

    #[tokio::test]
    async fn test_get_session_not_found() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/session/nonexistent"))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "name": "NotFound",
                "message": "Session not found",
                "data": {"id": "nonexistent"}
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let result = sessions.get("nonexistent").await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.is_not_found());
        assert_eq!(err.error_name(), Some("NotFound"));
    }

    #[tokio::test]
    async fn test_create_session_validation_error() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session"))
            .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({
                "name": "ValidationError",
                "message": "Invalid session configuration"
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let result = sessions.create(&CreateSessionRequest::default()).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.is_validation_error());
    }

    #[tokio::test]
    async fn test_children_not_found() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/session/missing/children"))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "name": "NotFound",
                "message": "Session not found"
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let result = sessions.children("missing").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().is_not_found());
    }

    #[tokio::test]
    async fn test_update_session_not_found() {
        let mock_server = MockServer::start().await;

        Mock::given(method("PATCH"))
            .and(path("/session/missing"))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "name": "NotFound",
                "message": "Session not found"
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let result = sessions
            .update("missing", &UpdateSessionRequest { title: None })
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().is_not_found());
    }

    #[tokio::test]
    async fn test_share_server_error() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session/s1/share"))
            .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({
                "name": "InternalError",
                "message": "Failed to generate share link"
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let result = sessions.share("s1").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().is_server_error());
    }

    #[tokio::test]
    async fn test_diff_not_found() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/session/missing/diff"))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "name": "NotFound",
                "message": "Session not found"
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let result = sessions.diff("missing").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().is_not_found());
    }

    #[tokio::test]
    async fn test_summarize_validation_error() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session/s1/summarize"))
            .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({
                "name": "ValidationError",
                "message": "Invalid provider or model"
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let result = sessions
            .summarize(
                "s1",
                &SummarizeRequest {
                    provider_id: "invalid".into(),
                    model_id: "invalid".into(),
                    auto: None,
                },
            )
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().is_validation_error());
    }

    #[tokio::test]
    async fn test_revert_not_found() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session/missing/revert"))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "name": "NotFound",
                "message": "Session not found"
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let result = sessions
            .revert(
                "missing",
                &crate::types::session::RevertRequest {
                    message_id: "m1".into(),
                    part_id: None,
                },
            )
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().is_not_found());
    }

    #[tokio::test]
    async fn test_abort_server_error() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/session/s1/abort"))
            .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({
                "name": "InternalError",
                "message": "Failed to abort session"
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let result = sessions.abort("s1").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().is_server_error());
    }

    #[tokio::test]
    async fn test_todo_not_found() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/session/missing/todo"))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "name": "NotFound",
                "message": "Session not found"
            })))
            .mount(&mock_server)
            .await;

        let http = HttpClient::new(HttpConfig {
            base_url: mock_server.uri(),
            directory: None,
            timeout: Duration::from_secs(30),
        })
        .unwrap();

        let sessions = SessionsApi::new(http);
        let result = sessions.todo("missing").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().is_not_found());
    }
}