jmap-tasks-server 0.4.1

JMAP Tasks method handlers — backend-agnostic, plugs into jmap-server Dispatcher
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
//! JMAP Tasks extension method handlers (draft-ietf-jmap-tasks-06).
//!
//! # Usage
//!
//! Implement [`TasksBackend`] for your storage layer, then call
//! [`register_tasks_handlers`] to wire all method names into a
//! [`jmap_server::Dispatcher`]:
//!
//! ```rust,no_run
//! # use std::sync::Arc;
//! # use jmap_tasks_server::{TasksBackend, register_tasks_handlers};
//! # use jmap_server::{Dispatcher, JmapBackend};
//! # fn example<B: TasksBackend<CallerCtx = ()> + 'static>(backend: B) {
//! let mut dispatcher: Dispatcher<()> = Dispatcher::new();
//! register_tasks_handlers(&mut dispatcher, Arc::new(backend));
//! # }
//! ```
//!
//! # `memory` feature (reference implementation)
//!
//! Enable the `memory` feature to expose the `memory::MemoryBackend`
//! reference implementation of [`TasksBackend`]. This is the same backend
//! used by this crate's own integration tests, intended for downstream
//! contributors to study and for smoke tests / examples that do not want
//! to stand up a real database. **Not production.** API stability is
//! opt-in via this feature and may break across minor versions while the
//! crate is pre-1.0.

#![forbid(unsafe_code)]
// bd:JMAP-uqhn.4 — narrowing and sign-changing `as` casts are banned;
// use `try_from`. Widening `usize as u64` stays legal (these lints do
// not fire on it): it is lossless on every target Rust supports.
#![warn(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss
)]

use std::sync::Arc;

use jmap_server::{CallContext, ClosureHandler, Dispatcher, HandlerFuture, JmapHandler};

mod backend;
mod helpers;
/// In-memory reference implementation of [`TasksBackend`].
///
/// Gated behind `feature = "memory"`. Not production. See [`memory`] for
/// the full module documentation.
#[cfg(feature = "memory")]
pub mod memory;
mod task;
mod task_list;
mod task_notification;

pub use backend::TasksBackend;
pub use jmap_tasks_types::{TaskListProperty, TaskNotificationProperty, TaskProperty};
pub use task::{
    handle_task_changes, handle_task_copy, handle_task_get, handle_task_query,
    handle_task_query_changes, handle_task_set,
};
pub use task_list::{handle_task_list_changes, handle_task_list_get, handle_task_list_set};
pub use task_notification::{
    handle_task_notification_changes, handle_task_notification_get, handle_task_notification_query,
    handle_task_notification_query_changes, handle_task_notification_set,
};

/// Capability URI for `urn:ietf:params:jmap:tasks`.
pub use jmap_tasks_types::JMAP_TASKS_URI;

// ---------------------------------------------------------------------------
// register_tasks_handlers — the main entry point for consumers
// ---------------------------------------------------------------------------

/// Register all JMAP Tasks method handlers with `dispatcher`.
///
/// `backend` is wrapped in [`Arc`] so it is cloned cheaply into each handler.
/// You may pass any `Arc<B>` — the function clones it internally into each
/// registered handler closure. Sharing the same `Arc<B>` across this call
/// and other application-level uses of the backend is a memory
/// optimization, not a correctness requirement; separate `Arc<B>` instances
/// pointing at the same underlying backend would also work.
///
/// After this call, the dispatcher handles:
/// `TaskList/get`, `TaskList/changes`, `TaskList/set`,
/// `Task/get`, `Task/changes`, `Task/set`, `Task/copy`,
/// `Task/query`, `Task/queryChanges`,
/// `TaskNotification/get`, `TaskNotification/changes`,
/// `TaskNotification/set`, `TaskNotification/query`,
/// `TaskNotification/queryChanges`.
///
/// # Re-registration semantics
///
/// This function calls [`Dispatcher::register`] once per
/// draft-ietf-jmap-tasks-06 method name. `Dispatcher::register`
/// **silently overwrites** any pre-existing handler under the same
/// method name (the underlying primitive is `HashMap::insert`). Three
/// consequences callers MUST be aware of:
///
/// - **Double-call**: invoking this function twice on the same
///   dispatcher loses the first set's handlers. The second call wins.
/// - **Custom overrides go LAST**: to replace a single handler (e.g.
///   provide a custom `Task/get`), call this function FIRST, then
///   `dispatcher.register("Task/get", my_override)`. The inverse
///   order silently undoes the custom handler.
/// - **No collision diagnostic**: there is no error or log when a
///   handler is overwritten. The contract is "last register wins" and
///   the caller is responsible for ordering.
///
/// [`Dispatcher::register`]: jmap_server::Dispatcher::register
pub fn register_tasks_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
where
    B: TasksBackend + 'static,
{
    // Helper: register one method with a closure taking
    // (Arc<B>, call_id, args, ctx). `$ctx` is the per-request caller context
    // (`B::CallerCtx`) forwarded by the dispatcher; closures pass `&ctx` to the
    // inner `handle_*` fn. `$ci` is the call_id string — most handlers ignore
    // it (`_ci`); only `Task/copy` uses it.
    // Each optional trailing ident binds the `CallContext` field of that name:
    // `created_ids`, the request-wide creation id map (RFC 8620 §5.3) that
    // `/set` handlers use to resolve `#creationId` references, or `using`,
    // the request's capability list (draft-ietf-jmap-metadata-04 §3).
    macro_rules! reg {
        ($method:expr, $backend:expr, |$b:ident, $ci:ident, $a:ident, $ctx:ident $(, $field:ident)*| $body:expr) => {{
            let backend_arc: Arc<B> = Arc::clone(&$backend);
            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
                backend_arc,
                move |$b: Arc<B>, cx: CallContext<B::CallerCtx>| {
                    let CallContext {
                        call_id: $ci,
                        args: $a,
                        caller: $ctx,
                        $($field,)*
                        ..
                    } = cx;
                    Box::pin(async move { $body }) as HandlerFuture
                },
            ));
            dispatcher.register($method, h);
        }};
    }

    // TaskList
    reg!("TaskList/get", backend, |b, _ci, a, ctx, using| {
        handle_task_list_get(&*b, &ctx, a, &using).await
    });
    reg!("TaskList/changes", backend, |b, _ci, a, ctx, using| {
        handle_task_list_changes(&*b, &ctx, a, &using).await
    });
    reg!("TaskList/set", backend, |b, _ci, a, ctx, using| {
        handle_task_list_set(&*b, &ctx, a, &using).await
    });

    // Task
    reg!("Task/get", backend, |b, _ci, a, ctx, using| {
        handle_task_get(&*b, &ctx, a, &using).await
    });
    reg!("Task/changes", backend, |b, _ci, a, ctx, using| {
        handle_task_changes(&*b, &ctx, a, &using).await
    });
    reg!("Task/set", backend, |b, _ci, a, ctx, created_ids, using| {
        handle_task_set(&*b, &ctx, &created_ids, a, &using).await
    });
    reg!("Task/copy", backend, |b, ci, a, ctx, using| {
        handle_task_copy(&*b, &ctx, a, &ci, &using).await
    });
    reg!("Task/query", backend, |b, _ci, a, ctx, using| {
        handle_task_query(&*b, &ctx, a, &using).await
    });
    reg!("Task/queryChanges", backend, |b, _ci, a, ctx, using| {
        handle_task_query_changes(&*b, &ctx, a, &using).await
    });

    // TaskNotification
    reg!("TaskNotification/get", backend, |b, _ci, a, ctx| {
        handle_task_notification_get(&*b, &ctx, a).await
    });
    reg!("TaskNotification/changes", backend, |b, _ci, a, ctx| {
        handle_task_notification_changes(&*b, &ctx, a).await
    });
    reg!("TaskNotification/set", backend, |b, _ci, a, ctx| {
        handle_task_notification_set(&*b, &ctx, a).await
    });
    reg!("TaskNotification/query", backend, |b, _ci, a, ctx| {
        handle_task_notification_query(&*b, &ctx, a).await
    });
    reg!(
        "TaskNotification/queryChanges",
        backend,
        |b, _ci, a, ctx| handle_task_notification_query_changes(&*b, &ctx, a).await
    );
}

// ---------------------------------------------------------------------------
// test_support — in-memory mock backend used by inline tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[deny(clippy::await_holding_lock)]
pub(crate) mod test_support {
    //! In-memory mock backend for unit tests.

    use std::collections::HashMap;
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::sync::{Arc, Mutex};

    use jmap_server::{
        BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
        JmapBackend, JmapObject, QueryChangesParams, QueryChangesResult, QueryObject, QueryParams,
        QueryResult, SetError, SetErrorType, SetObject,
    };
    use jmap_tasks_types::{Task, TaskList, TaskNotification};
    use jmap_types::{Id, State};

    use crate::TasksBackend;

    /// Minimal error type for the mock backend.
    ///
    /// `#[non_exhaustive]` with a named field, mirroring the canonical
    /// `jmap-mail-server` `MemoryError`: reads go through
    /// [`MockError::description`], so structured context can be added later
    /// without a breaking change. No mock path fails yet, so it has no
    /// constructor.
    #[non_exhaustive]
    #[derive(Debug)]
    pub struct MockError {
        description: String,
    }

    impl MockError {
        /// Human-readable description of the underlying failure.
        pub fn description(&self) -> &str {
            &self.description
        }
    }

    impl std::fmt::Display for MockError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "mock error: {}", self.description())
        }
    }

    impl std::error::Error for MockError {}

    /// In-memory state for one account.
    #[derive(Default, Clone)]
    struct AccountState {
        task_lists: HashMap<Id, TaskList>,
        tasks: HashMap<Id, Task>,
        notifications: HashMap<Id, TaskNotification>,
        task_list_state: u64,
        task_state: u64,
        notification_state: u64,
    }

    /// In-memory mock backend for testing.
    #[derive(Clone)]
    pub struct MockBackend {
        state: Arc<Mutex<HashMap<String, AccountState>>>,
        /// Counts how many times `update_task_per_user` was called.
        /// Used by integration tests to verify per-user routing.
        pub per_user_calls: Arc<AtomicU32>,
    }

    impl MockBackend {
        /// Create a backend with no accounts registered.
        pub fn new() -> Self {
            Self {
                state: Arc::new(Mutex::new(HashMap::new())),
                per_user_calls: Arc::new(AtomicU32::new(0)),
            }
        }

        /// Create a backend with the given account already registered.
        pub fn new_with_account(account_id: &str) -> Self {
            let b = Self::new();
            b.state
                .lock()
                .unwrap()
                .insert(account_id.to_owned(), AccountState::default());
            b
        }

        /// Register an additional account on an existing backend. Used by
        /// Task/copy tests that need two valid accounts (`fromAccountId`
        /// and `accountId` must differ per RFC 8620 §5.4).
        pub fn add_account(&mut self, account_id: &str) {
            self.state
                .lock()
                .unwrap()
                .entry(account_id.to_owned())
                .or_default();
        }

        /// Pre-populate a TaskNotification in the given account.
        pub fn add_notification(&mut self, account_id: &str, notif_id: &str) {
            let notif: TaskNotification = serde_json::from_value(serde_json::json!({
                "id": notif_id,
                "created": "2024-01-01T00:00:00Z",
                "changedBy": { "@type": "Person", "name": "Test" },
                "type": "created",
                "taskId": "task1"
            }))
            .expect("test fixture must deserialize");
            let mut guard = self.state.lock().unwrap();
            let acct = guard.entry(account_id.to_owned()).or_default();
            acct.notifications.insert(Id::from(notif_id), notif);
        }

        /// Pre-populate a Task with a specific `isDraft` value in the given account.
        ///
        /// Used by tests for the isDraft immutability enforcement path.
        pub fn seed_task(&mut self, account_id: &str, task_id: &str, is_draft: bool) {
            let task: Task = serde_json::from_value(serde_json::json!({
                "id": task_id,
                "isDraft": is_draft
            }))
            .expect("task seed fixture must deserialize");
            let mut guard = self.state.lock().unwrap();
            let acct = guard.entry(account_id.to_owned()).or_default();
            acct.tasks.insert(Id::from(task_id), task);
        }

        /// Pre-populate a TaskList with a task in the given account.
        pub fn add_task_list_with_task(&mut self, account_id: &str, list_id: &str) {
            let task_list: TaskList = serde_json::from_value(serde_json::json!({
                "id": list_id,
                "name": "Test List",
                "sortOrder": 0,
                "isSubscribed": true,
                "myRights": {
                    "mayReadItems": true,
                    "mayWriteAll": true,
                    "mayWriteOwn": true,
                    "mayUpdatePrivate": true,
                    "mayRSVP": true,
                    "mayAdmin": true,
                    "mayDelete": true
                }
            }))
            .expect("task list fixture must deserialize");
            let mut guard = self.state.lock().unwrap();
            let acct = guard.entry(account_id.to_owned()).or_default();
            acct.task_lists.insert(Id::from(list_id), task_list);
            // Add a task referencing the list
            let task: Task = serde_json::from_value(serde_json::json!({
                "id": "task1",
                "taskListId": list_id
            }))
            .expect("task fixture must deserialize");
            acct.tasks.insert(Id::from("task1"), task);
        }
    }

    impl JmapBackend for MockBackend {
        type Error = MockError;
        type CallerCtx = ();

        async fn account_exists(&self, _caller: &(), account_id: &Id) -> Result<bool, Self::Error> {
            Ok(self.state.lock().unwrap().contains_key(account_id.as_ref()))
        }

        async fn get_objects<O: GetObject + Send + Sync>(
            &self,
            _caller: &(),
            account_id: &Id,
            ids: Option<&[Id]>,
            _properties: Option<&[String]>,
        ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
            // Attempt to serve from the tasks store via a serde round-trip.
            // When O = Task this is identity; for other types the deserialize
            // step will fail (no data in the store matches) and we fall back
            // to empty — preserving the prior behaviour for TaskList/get etc.
            let guard = self.state.lock().unwrap();
            let Some(acct) = guard.get(account_id.as_ref()) else {
                return Ok((vec![], vec![]));
            };

            let mut found: Vec<O> = Vec::new();
            let mut not_found: Vec<Id> = Vec::new();

            if let Some(id_slice) = ids {
                for id in id_slice {
                    if let Some(task) = acct.tasks.get(id) {
                        match serde_json::to_value(task)
                            .ok()
                            .and_then(|v| serde_json::from_value::<O>(v).ok())
                        {
                            Some(obj) => found.push(obj),
                            None => not_found.push(id.clone()),
                        }
                    } else {
                        not_found.push(id.clone());
                    }
                }
            }
            // If no specific ids were requested, serve nothing (empty list) —
            // the isDraft check always passes specific ids.
            Ok((found, not_found))
        }

        async fn get_state<O: JmapObject + Send + Sync>(
            &self,
            _caller: &(),
            _account_id: &Id,
        ) -> Result<State, Self::Error> {
            Ok(State::from("0"))
        }

        async fn get_changes<O: JmapObject + Send + Sync>(
            &self,
            _caller: &(),
            _account_id: &Id,
            _params: jmap_server::ChangesParams<'_>,
        ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
            Ok(ChangesResult::new(
                vec![],
                vec![],
                vec![],
                false,
                State::from("0"),
            ))
        }

        async fn query_objects<O: QueryObject + Send + Sync>(
            &self,
            _caller: &(),
            _account_id: &Id,
            _params: QueryParams<'_, O>,
        ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
            Ok(QueryResult::new(
                vec![],
                0,
                Some(0),
                State::from("0"),
                false,
            ))
        }

        async fn query_changes<O: QueryObject + Send + Sync>(
            &self,
            _caller: &(),
            _account_id: &Id,
            params: QueryChangesParams<'_, O>,
        ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
            let QueryChangesParams {
                since_query_state, ..
            } = params;
            Ok(QueryChangesResult::new(
                since_query_state.clone(),
                State::from("0"),
                Some(0),
                vec![],
                vec![],
            ))
        }
    }

    impl TasksBackend for MockBackend {
        async fn create_object<O, F>(
            &self,
            _caller: &(),
            _account_id: &Id,
            _create_id: &str,
            build: F,
        ) -> Result<(Id, O), BackendSetError<Self::Error>>
        where
            O: SetObject + Send + Sync,
            F: FnOnce(&Id) -> O + Send,
        {
            {
                let id = Id::from("mock-id-1");
                let obj = build(&id);
                Ok((id, obj))
            }
        }

        async fn copy_object<O: SetObject + Send + Sync>(
            &self,
            _caller: &(),
            _from_account_id: &Id,
            _to_account_id: &Id,
            obj: O,
            _create: &serde_json::Value,
        ) -> Result<(Id, O), BackendSetError<Self::Error>> {
            Ok((Id::from("mock-id-1"), obj))
        }

        /// Rejects every update with `forbidden`, except that a Task patch
        /// setting `isDraft: true` on a stored Task that is not a draft is
        /// `invalidProperties` naming `isDraft`: the backend half of
        /// draft-tasks-06 §4 "This may only be set to true upon creation",
        /// which `TasksBackend::update_object` requires of every backend.
        async fn update_object<O: SetObject + Send + Sync>(
            &self,
            _caller: &(),
            account_id: &Id,
            id: &Id,
            patch: O::Patch,
        ) -> Result<Option<O>, BackendSetError<Self::Error>> {
            let sets_draft = serde_json::to_value(&patch)
                .ok()
                .and_then(|p| p.get("isDraft").and_then(|v| v.as_bool()))
                == Some(true);
            let stored_not_draft = self
                .state
                .lock()
                .unwrap()
                .get(account_id.as_ref())
                .and_then(|a| a.tasks.get(id))
                .is_some_and(|t| t.is_draft != Some(true));
            if O::TYPE_NAME == "Task" && sets_draft && stored_not_draft {
                return Err(BackendSetError::SetError(Box::new(
                    SetError::new(SetErrorType::InvalidProperties)
                        .with_properties(vec!["isDraft".to_owned()]),
                )));
            }
            Err(BackendSetError::SetError(Box::new(SetError::new(
                SetErrorType::Forbidden,
            ))))
        }

        async fn destroy_object<O: SetObject + Send + Sync>(
            &self,
            _caller: &(),
            account_id: &Id,
            id: &Id,
        ) -> Result<(), BackendSetError<Self::Error>> {
            let mut guard = self.state.lock().unwrap();
            if let Some(acct) = guard.get_mut(account_id.as_ref()) {
                if acct.notifications.remove(id).is_some() {
                    acct.notification_state += 1;
                    return Ok(());
                }
                if acct.tasks.remove(id).is_some() {
                    acct.task_state += 1;
                    return Ok(());
                }
                if acct.task_lists.remove(id).is_some() {
                    acct.task_list_state += 1;
                    return Ok(());
                }
            }
            Err(BackendSetError::SetError(Box::new(SetError::new(
                SetErrorType::NotFound,
            ))))
        }

        fn supports_type<O: JmapObject>(
            &self,
            _caller: &Self::CallerCtx,
            _account_id: &jmap_types::Id,
        ) -> bool {
            true
        }

        async fn update_task_per_user(
            &self,
            caller: &(),
            account_id: &Id,
            id: &Id,
            patch: jmap_types::PatchObject,
        ) -> Result<Option<Task>, BackendSetError<Self::Error>> {
            // Track that this per-user path was called.
            self.per_user_calls.fetch_add(1, Ordering::Relaxed);
            // Delegate to update_object (same outcome as default impl).
            self.update_object::<Task>(caller, account_id, id, patch)
                .await
        }

        async fn task_list_has_tasks(
            &self,
            _caller: &(),
            account_id: &Id,
            task_list_id: &Id,
        ) -> Result<bool, MockError> {
            let guard = self.state.lock().unwrap();
            if let Some(acct) = guard.get(account_id.as_ref()) {
                return Ok(acct.tasks.values().any(|t| {
                    t.task_list_id
                        .as_ref()
                        .is_some_and(|lid| lid == task_list_id)
                }));
            }
            Ok(false)
        }
    }
}

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

#[cfg(test)]
mod tests {
    use jmap_types::Invocation;
    use std::sync::Arc;
    use std::sync::atomic::Ordering;

    use jmap_server::{Dispatcher, JmapRequest, State};
    use serde_json::json;

    use super::*;
    use crate::test_support::MockBackend;

    // Helper: build a minimal JmapRequest with one method call.
    fn single_call(method: &str, args: serde_json::Value, call_id: &str) -> JmapRequest {
        JmapRequest::new(
            vec!["urn:ietf:params:jmap:tasks".into()],
            vec![Invocation::new(method, args, call_id)],
            None,
        )
    }

    /// Oracle: register_tasks_handlers registers all 14 JMAP Tasks methods.
    ///
    /// Verification: each method name returns a non-error response when
    /// dispatched with a valid account (not `unknownMethod`).
    #[tokio::test]
    async fn registers_all_14_methods() {
        let backend = Arc::new(MockBackend::new_with_account("acc1"));
        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));

        let methods = [
            ("TaskList/get", json!({"accountId": "acc1", "ids": null})),
            (
                "TaskList/changes",
                json!({"accountId": "acc1", "sinceState": "0"}),
            ),
            ("TaskList/set", json!({"accountId": "acc1", "destroy": []})),
            ("Task/get", json!({"accountId": "acc1", "ids": null})),
            (
                "Task/changes",
                json!({"accountId": "acc1", "sinceState": "0"}),
            ),
            ("Task/set", json!({"accountId": "acc1", "destroy": []})),
            (
                "Task/copy",
                json!({"fromAccountId": "acc1", "accountId": "acc1", "create": {}}),
            ),
            (
                "Task/query",
                json!({"accountId": "acc1", "filter": null, "sort": null}),
            ),
            (
                "Task/queryChanges",
                json!({"accountId": "acc1", "sinceQueryState": "0"}),
            ),
            (
                "TaskNotification/get",
                json!({"accountId": "acc1", "ids": null}),
            ),
            (
                "TaskNotification/changes",
                json!({"accountId": "acc1", "sinceState": "0"}),
            ),
            (
                "TaskNotification/set",
                json!({"accountId": "acc1", "destroy": []}),
            ),
            (
                "TaskNotification/query",
                json!({"accountId": "acc1", "filter": null, "sort": null}),
            ),
            (
                "TaskNotification/queryChanges",
                json!({"accountId": "acc1", "sinceQueryState": "0"}),
            ),
        ];

        for (method, args) in methods {
            let req = single_call(method, args, "c0");
            let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
            assert_eq!(
                resp.method_responses.len(),
                1,
                "{method}: expected 1 response"
            );
            let Invocation {
                arguments: resp_args,
                ..
            } = &resp.method_responses[0];
            assert_ne!(
                resp_args["type"], "unknownMethod",
                "{method}: must not be unknownMethod — is it registered?"
            );
        }
    }

    /// Oracle: TaskNotification/set with create entries → notCreated contains
    /// `forbidden` for every create entry; no top-level error.
    #[tokio::test]
    async fn task_notification_set_create_returns_forbidden() {
        let backend = Arc::new(MockBackend::new_with_account("acc1"));
        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));

        let req = single_call(
            "TaskNotification/set",
            json!({
                "accountId": "acc1",
                "create": {
                    "c1": {
                        "id": "x",
                        "created": "2024-01-01T00:00:00Z",
                        "changedBy": { "@type": "Person", "name": "A" },
                        "type": "created",
                        "taskId": "t1"
                    }
                }
            }),
            "c0",
        );
        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert!(
            args.get("type").is_none(),
            "must not be a top-level error: {args}"
        );
        assert_eq!(
            args["notCreated"]["c1"]["type"], "forbidden",
            "create must be forbidden: {args}"
        );
    }

    /// Oracle: TaskList/set destroy with tasks returns taskListHasTask error
    /// (draft-ietf-jmap-tasks-06 §3.4).
    ///
    /// When `onDestroyRemoveTasks` is false (default) and the task list has tasks,
    /// the destroy should fail with a custom `taskListHasTask` error.
    #[tokio::test]
    async fn task_list_set_destroy_with_tasks_returns_task_list_has_task() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_task_list_with_task("acc1", "list1");
        let backend = Arc::new(backend);

        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));

        let req = single_call(
            "TaskList/set",
            json!({
                "accountId": "acc1",
                "destroy": ["list1"],
                "onDestroyRemoveTasks": false
            }),
            "c0",
        );
        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert!(
            args.get("type").is_none(),
            "must not be a top-level error: {args}"
        );
        assert_eq!(
            args["notDestroyed"]["list1"]["type"], "taskListHasTask",
            "must return taskListHasTask when list has tasks: {args}"
        );
    }

    // ── Integration tests: isDraft, utcStart, per-user routing ──────────────

    /// Oracle: draft-tasks-06 §4 — isDraft false→true revert is rejected via
    /// dispatcher (end-to-end path through register_tasks_handlers).
    #[tokio::test]
    async fn isdraft_revert_via_dispatcher() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.seed_task("acc1", "t1", false);
        let backend = Arc::new(backend);

        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));

        let req = single_call(
            "Task/set",
            json!({
                "accountId": "acc1",
                "update": { "t1": { "isDraft": true } }
            }),
            "c0",
        );
        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert!(
            args.get("type").is_none(),
            "must not be a top-level error: {args}"
        );
        assert_eq!(
            args["notUpdated"]["t1"]["type"], "invalidProperties",
            "isDraft revert must be invalidProperties: {args}"
        );
        assert_eq!(
            args["notUpdated"]["t1"]["properties"][0], "isDraft",
            "isDraft must be listed in properties: {args}"
        );
    }

    /// Oracle: draft-tasks-06 §4 — isDraft false (draft → published) is always
    /// allowed; the handler must not pre-reject it.
    #[tokio::test]
    async fn isdraft_draft_to_publish_allowed() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.seed_task("acc1", "t1", true);
        let backend = Arc::new(backend);

        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));

        let req = single_call(
            "Task/set",
            json!({
                "accountId": "acc1",
                "update": { "t1": { "isDraft": false } }
            }),
            "c0",
        );
        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        // The patch must NOT be pre-rejected with invalidProperties.
        if let Some(not_updated) = args["notUpdated"].as_object()
            && let Some(err) = not_updated.get("t1")
        {
            assert_ne!(
                err["type"].as_str(),
                Some("invalidProperties"),
                "isDraft:false must not produce invalidProperties: {args}"
            );
        }
    }

    /// Oracle: draft-tasks-06 §4 (utcStart/utcDue paragraphs) — utcStart is NOT returned
    /// when not in the properties list.
    #[tokio::test]
    async fn utcstart_not_in_default_properties() {
        let backend = Arc::new(MockBackend::new_with_account("acc1"));
        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));

        let req = single_call(
            "Task/get",
            json!({ "accountId": "acc1", "ids": null, "properties": ["id"] }),
            "c0",
        );
        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert!(args.get("type").is_none(), "must not be error: {args}");
        for item in args["list"].as_array().into_iter().flatten() {
            assert!(
                item.get("utcStart").is_none(),
                "utcStart must not appear when not requested: {item}"
            );
        }
    }

    /// Oracle: draft-tasks-06 §4 — when utcStart is explicitly requested,
    /// the handler invokes compute_utc_times (default: returns None, so
    /// no value injected), but no error is raised.
    #[tokio::test]
    async fn utcstart_returned_when_requested() {
        let backend = Arc::new(MockBackend::new_with_account("acc1"));
        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));

        let req = single_call(
            "Task/get",
            json!({
                "accountId": "acc1",
                "ids": null,
                "properties": ["id", "utcStart"]
            }),
            "c0",
        );
        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert!(
            args.get("type").is_none(),
            "Task/get with utcStart must not error: {args}"
        );
    }

    /// Oracle: bd:JMAP-ops7.25 — the `account_id` argument plumbed into
    /// `TasksBackend::compute_utc_times` matches the request's `accountId`
    /// and is delivered as a validated [`Id`]. Locks in the args-threading
    /// contract: a backend that overrides `compute_utc_times` can rely on
    /// receiving the caller-validated account id.
    ///
    /// Also oracle: draft-tasks-06 §4 (utcStart is computed from `start` and
    /// `timeZone`) and RFC 8620 §5.1 ("only the properties listed in the
    /// array are returned"). The stub's stored task has `start` and
    /// `timeZone`, and its `compute_utc_times` returns the hand-written
    /// `2024-06-15T09:00:00Z` only when `start` reaches it, so a request
    /// for `["id", "utcStart"]` must return exactly `id` and that value.
    #[tokio::test]
    async fn compute_utc_times_receives_validated_account_id() {
        use std::sync::Mutex;

        use jmap_server::{
            BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
            JmapBackend, JmapObject, QueryChangesParams, QueryChangesResult, QueryObject,
            QueryParams, QueryResult, SetObject,
        };
        use jmap_tasks_types::Task;
        use jmap_types::{Id, UTCDate};

        use crate::TasksBackend;
        use crate::test_support::MockError;

        /// Minimal recording backend that returns exactly one Task on
        /// `get_objects::<Task>` (so the handler's augmentation loop fires
        /// once) and captures the `account_id` argument that `compute_utc_times`
        /// receives.
        struct AccountIdRecorder {
            observed: Mutex<Vec<Id>>,
        }

        impl JmapBackend for AccountIdRecorder {
            type Error = MockError;
            type CallerCtx = ();

            async fn account_exists(
                &self,
                _caller: &(),
                _account_id: &Id,
            ) -> Result<bool, Self::Error> {
                Ok(true)
            }

            async fn get_objects<O: GetObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &Id,
                _ids: Option<&[Id]>,
                _properties: Option<&[String]>,
            ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
                // Synthesize one Task via JSON round-trip. Non-Task types
                // get back an empty list (handler exercise here is
                // Task/get only).
                let item = json!({
                    "id": "t1",
                    "start": "2024-06-15T09:00:00",
                    "timeZone": "Etc/UTC"
                });
                match serde_json::from_value::<O>(item) {
                    Ok(obj) => Ok((vec![obj], vec![])),
                    Err(_) => Ok((vec![], vec![])),
                }
            }

            async fn get_state<O: JmapObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &Id,
            ) -> Result<State, Self::Error> {
                Ok(State::from("s0"))
            }

            async fn get_changes<O: JmapObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &Id,
                _params: jmap_server::ChangesParams<'_>,
            ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
                Ok(ChangesResult::new(
                    vec![],
                    vec![],
                    vec![],
                    false,
                    State::from("s0"),
                ))
            }

            async fn query_objects<O: QueryObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &Id,
                _params: QueryParams<'_, O>,
            ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
                Ok(QueryResult::new(
                    vec![],
                    0,
                    Some(0),
                    State::from("s0"),
                    false,
                ))
            }

            async fn query_changes<O: QueryObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &Id,
                params: QueryChangesParams<'_, O>,
            ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
                let QueryChangesParams {
                    since_query_state, ..
                } = params;
                Ok(QueryChangesResult::new(
                    since_query_state.clone(),
                    State::from("s0"),
                    Some(0),
                    vec![],
                    vec![],
                ))
            }
        }

        impl TasksBackend for AccountIdRecorder {
            async fn create_object<O, F>(
                &self,
                _caller: &(),
                _account_id: &Id,
                _create_id: &str,
                build: F,
            ) -> Result<(Id, O), BackendSetError<Self::Error>>
            where
                O: SetObject + Send + Sync,
                F: FnOnce(&Id) -> O + Send,
            {
                {
                    let id = Id::from("t1");
                    let obj = build(&id);
                    Ok((id, obj))
                }
            }

            async fn copy_object<O: SetObject + Send + Sync>(
                &self,
                _caller: &(),
                _from_account_id: &Id,
                _to_account_id: &Id,
                obj: O,
                _create: &serde_json::Value,
            ) -> Result<(Id, O), BackendSetError<Self::Error>> {
                Ok((Id::from("t1"), obj))
            }

            async fn update_object<O: SetObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &Id,
                _id: &Id,
                _patch: O::Patch,
            ) -> Result<Option<O>, BackendSetError<Self::Error>> {
                Ok(None)
            }

            async fn update_task_per_user(
                &self,
                caller: &(),
                account_id: &Id,
                id: &Id,
                patch: jmap_types::PatchObject,
            ) -> Result<Option<jmap_tasks_types::Task>, BackendSetError<Self::Error>> {
                self.update_object::<jmap_tasks_types::Task>(caller, account_id, id, patch)
                    .await
            }

            async fn destroy_object<O: SetObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &Id,
                _id: &Id,
            ) -> Result<(), BackendSetError<Self::Error>> {
                Ok(())
            }

            fn supports_type<O: JmapObject>(
                &self,
                _caller: &Self::CallerCtx,
                _account_id: &jmap_types::Id,
            ) -> bool {
                true
            }

            async fn task_list_has_tasks(
                &self,
                _caller: &(),
                _account_id: &Id,
                _task_list_id: &Id,
            ) -> Result<bool, MockError> {
                Ok(false)
            }

            async fn compute_utc_times(
                &self,
                _caller: &(),
                account_id: &Id,
                task: &Task,
                _tz_hint: Option<&str>,
            ) -> (Option<UTCDate>, Option<UTCDate>) {
                self.observed.lock().unwrap().push(account_id.clone());
                let fixed = task
                    .start
                    .as_ref()
                    .map(|_| UTCDate::from("2024-06-15T09:00:00Z"));
                (fixed.clone(), fixed)
            }
        }

        let backend = Arc::new(AccountIdRecorder {
            observed: Mutex::new(Vec::new()),
        });
        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));

        let req = single_call(
            "Task/get",
            json!({
                "accountId": "acc1",
                "ids": null,
                "properties": ["id", "utcStart"]
            }),
            "c0",
        );
        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert!(
            args.get("type").is_none(),
            "Task/get with utcStart must not error: {args}"
        );

        let seen = backend.observed.lock().unwrap().clone();
        assert_eq!(
            seen,
            vec![Id::from("acc1")],
            "compute_utc_times must receive the request's accountId exactly once \
             (one Task synthesized, utcStart requested)"
        );
        assert_eq!(
            args["list"],
            json!([{ "id": "t1", "utcStart": "2024-06-15T09:00:00Z" }]),
            "utcStart must be computed from the stored start, and only the \
             requested properties returned"
        );
    }

    /// Oracle: draft-tasks-06 §4.5.1 — a per-user-only patch is routed to
    /// `update_task_per_user`. MockBackend tracks the call count.
    #[tokio::test]
    async fn per_user_patch_split() {
        let backend = Arc::new(MockBackend::new_with_account("acc1"));
        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));

        let before = backend.per_user_calls.load(Ordering::Relaxed);

        let req = single_call(
            "Task/set",
            json!({
                "accountId": "acc1",
                "update": { "t1": { "color": "#ff0000" } }
            }),
            "c0",
        );
        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert!(
            args.get("type").is_none(),
            "must not be top-level error: {args}"
        );

        let after = backend.per_user_calls.load(Ordering::Relaxed);
        assert_eq!(
            after - before,
            1,
            "per_user update must have been called exactly once for a color-only patch"
        );
    }
}