Skip to main content

jmap_tasks_server/
lib.rs

1//! JMAP Tasks extension method handlers (draft-ietf-jmap-tasks-06).
2//!
3//! # Usage
4//!
5//! Implement [`TasksBackend`] for your storage layer, then call
6//! [`register_tasks_handlers`] to wire all method names into a
7//! [`jmap_server::Dispatcher`]:
8//!
9//! ```rust,no_run
10//! # use std::sync::Arc;
11//! # use jmap_tasks_server::{TasksBackend, register_tasks_handlers};
12//! # use jmap_server::{Dispatcher, JmapBackend};
13//! # fn example<B: TasksBackend<CallerCtx = ()> + 'static>(backend: B) {
14//! let mut dispatcher: Dispatcher<()> = Dispatcher::new();
15//! register_tasks_handlers(&mut dispatcher, Arc::new(backend));
16//! # }
17//! ```
18//!
19//! # `memory` feature (reference implementation)
20//!
21//! Enable the `memory` feature to expose the `memory::MemoryBackend`
22//! reference implementation of [`TasksBackend`]. This is the same backend
23//! used by this crate's own integration tests, intended for downstream
24//! contributors to study and for smoke tests / examples that do not want
25//! to stand up a real database. **Not production.** API stability is
26//! opt-in via this feature and may break across minor versions while the
27//! crate is pre-1.0.
28
29#![forbid(unsafe_code)]
30
31use std::sync::Arc;
32
33use jmap_server::{Dispatcher, HandlerFuture, JmapHandler};
34
35pub mod backend;
36mod helpers;
37/// In-memory reference implementation of [`TasksBackend`].
38///
39/// Gated behind `feature = "memory"`. Not production. See [`memory`] for
40/// the full module documentation.
41#[cfg(feature = "memory")]
42pub mod memory;
43pub mod task;
44pub mod task_list;
45pub mod task_notification;
46
47pub use backend::{
48    AddedItem, BackendChangesError, BackendSetError, ChangesResult, GetObject, JmapBackend,
49    JmapObject, QueryChangesResult, QueryObject, QueryResult, SetError, SetErrorType, SetObject,
50    TasksBackend,
51};
52pub use task::{
53    handle_task_changes, handle_task_copy, handle_task_get, handle_task_query,
54    handle_task_query_changes, handle_task_set,
55};
56pub use task_list::{handle_task_list_changes, handle_task_list_get, handle_task_list_set};
57pub use task_notification::{
58    handle_task_notification_changes, handle_task_notification_get, handle_task_notification_query,
59    handle_task_notification_query_changes, handle_task_notification_set,
60};
61
62/// Capability URI for `urn:ietf:params:jmap:tasks`.
63pub use jmap_tasks_types::JMAP_TASKS_URI;
64
65// ---------------------------------------------------------------------------
66// register_tasks_handlers — the main entry point for consumers
67// ---------------------------------------------------------------------------
68
69/// Register all JMAP Tasks method handlers with `dispatcher`.
70///
71/// `backend` is wrapped in [`Arc`] so it is cloned cheaply into each handler.
72///
73/// After this call, the dispatcher handles:
74/// `TaskList/get`, `TaskList/changes`, `TaskList/set`,
75/// `Task/get`, `Task/changes`, `Task/set`, `Task/copy`,
76/// `Task/query`, `Task/queryChanges`,
77/// `TaskNotification/get`, `TaskNotification/changes`,
78/// `TaskNotification/set`, `TaskNotification/query`,
79/// `TaskNotification/queryChanges`.
80pub fn register_tasks_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
81where
82    B: TasksBackend + 'static,
83{
84    // Helper: register one method with a closure taking
85    // (Arc<B>, call_id, args, ctx). `$ctx` is the per-request caller context
86    // (`B::CallerCtx`) forwarded by the dispatcher; closures pass `&ctx` to the
87    // inner `handle_*` fn. `$ci` is the call_id string — most handlers ignore
88    // it (`_ci`); only `Task/copy` uses it.
89    macro_rules! reg {
90        ($method:expr, $backend:expr, |$b:ident, $ci:ident, $a:ident, $ctx:ident| $body:expr) => {{
91            let backend_arc: Arc<B> = Arc::clone(&$backend);
92            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler {
93                backend: backend_arc,
94                call_fn: Box::new(
95                    move |$b: Arc<B>, $ci: String, $a: serde_json::Value, $ctx: B::CallerCtx| {
96                        Box::pin(async move { $body }) as HandlerFuture
97                    },
98                ),
99            });
100            dispatcher.register($method, h);
101        }};
102    }
103
104    // TaskList
105    reg!("TaskList/get", backend, |b, _ci, a, ctx| {
106        handle_task_list_get(&*b, &ctx, a).await
107    });
108    reg!("TaskList/changes", backend, |b, _ci, a, ctx| {
109        handle_task_list_changes(&*b, &ctx, a).await
110    });
111    reg!("TaskList/set", backend, |b, _ci, a, ctx| {
112        handle_task_list_set(&*b, &ctx, a).await
113    });
114
115    // Task
116    reg!("Task/get", backend, |b, _ci, a, ctx| {
117        handle_task_get(&*b, &ctx, a).await
118    });
119    reg!("Task/changes", backend, |b, _ci, a, ctx| {
120        handle_task_changes(&*b, &ctx, a).await
121    });
122    reg!("Task/set", backend, |b, _ci, a, ctx| {
123        handle_task_set(&*b, &ctx, a).await
124    });
125    reg!("Task/copy", backend, |b, _ci, a, ctx| {
126        handle_task_copy(&*b, &ctx, a).await
127    });
128    reg!("Task/query", backend, |b, _ci, a, ctx| {
129        handle_task_query(&*b, &ctx, a).await
130    });
131    reg!("Task/queryChanges", backend, |b, _ci, a, ctx| {
132        handle_task_query_changes(&*b, &ctx, a).await
133    });
134
135    // TaskNotification
136    reg!("TaskNotification/get", backend, |b, _ci, a, ctx| {
137        handle_task_notification_get(&*b, &ctx, a).await
138    });
139    reg!("TaskNotification/changes", backend, |b, _ci, a, ctx| {
140        handle_task_notification_changes(&*b, &ctx, a).await
141    });
142    reg!("TaskNotification/set", backend, |b, _ci, a, ctx| {
143        handle_task_notification_set(&*b, &ctx, a).await
144    });
145    reg!("TaskNotification/query", backend, |b, _ci, a, ctx| {
146        handle_task_notification_query(&*b, &ctx, a).await
147    });
148    reg!(
149        "TaskNotification/queryChanges",
150        backend,
151        |b, _ci, a, ctx| handle_task_notification_query_changes(&*b, &ctx, a).await
152    );
153}
154
155pub use jmap_server::ClosureHandler;
156
157// ---------------------------------------------------------------------------
158// test_support — in-memory mock backend used by inline tests
159// ---------------------------------------------------------------------------
160
161#[cfg(test)]
162#[deny(clippy::await_holding_lock)]
163pub(crate) mod test_support {
164    //! In-memory mock backend for unit tests.
165
166    use std::collections::HashMap;
167    use std::sync::atomic::{AtomicU32, Ordering};
168    use std::sync::{Arc, Mutex};
169
170    use jmap_server::{
171        BackendChangesError, BackendSetError, ChangesResult, GetObject, JmapBackend, JmapObject,
172        QueryChangesResult, QueryObject, QueryResult, SetError, SetErrorType, SetObject,
173    };
174    use jmap_tasks_types::{Task, TaskList, TaskNotification};
175    use jmap_types::{Id, State};
176
177    use crate::backend::TasksBackend;
178
179    /// Minimal error type for the mock backend.
180    #[derive(Debug)]
181    pub struct MockError(pub String);
182
183    impl std::fmt::Display for MockError {
184        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185            write!(f, "mock error: {}", self.0)
186        }
187    }
188
189    impl std::error::Error for MockError {}
190
191    /// In-memory state for one account.
192    #[derive(Default, Clone)]
193    struct AccountState {
194        task_lists: HashMap<Id, TaskList>,
195        tasks: HashMap<Id, Task>,
196        notifications: HashMap<Id, TaskNotification>,
197        task_list_state: u64,
198        task_state: u64,
199        notification_state: u64,
200    }
201
202    /// In-memory mock backend for testing.
203    #[derive(Clone)]
204    pub struct MockBackend {
205        state: Arc<Mutex<HashMap<String, AccountState>>>,
206        /// Counts how many times `update_task_per_user` was called.
207        /// Used by integration tests to verify per-user routing.
208        pub per_user_calls: Arc<AtomicU32>,
209    }
210
211    impl MockBackend {
212        /// Create a backend with no accounts registered.
213        pub fn new() -> Self {
214            Self {
215                state: Arc::new(Mutex::new(HashMap::new())),
216                per_user_calls: Arc::new(AtomicU32::new(0)),
217            }
218        }
219
220        /// Create a backend with the given account already registered.
221        pub fn new_with_account(account_id: &str) -> Self {
222            let b = Self::new();
223            b.state
224                .lock()
225                .unwrap()
226                .insert(account_id.to_owned(), AccountState::default());
227            b
228        }
229
230        /// Pre-populate a TaskNotification in the given account.
231        pub fn add_notification(&mut self, account_id: &str, notif_id: &str) {
232            let notif: TaskNotification = serde_json::from_value(serde_json::json!({
233                "id": notif_id,
234                "created": "2024-01-01T00:00:00Z",
235                "changedBy": { "@type": "Person", "name": "Test" },
236                "type": "created",
237                "taskId": "task1"
238            }))
239            .expect("test fixture must deserialize");
240            let mut guard = self.state.lock().unwrap();
241            let acct = guard.entry(account_id.to_owned()).or_default();
242            acct.notifications.insert(Id::from(notif_id), notif);
243        }
244
245        /// Pre-populate a Task with a specific `isDraft` value in the given account.
246        ///
247        /// Used by tests for the isDraft immutability enforcement path.
248        pub fn seed_task(&mut self, account_id: &str, task_id: &str, is_draft: bool) {
249            let task: Task = serde_json::from_value(serde_json::json!({
250                "id": task_id,
251                "isDraft": is_draft
252            }))
253            .expect("task seed fixture must deserialize");
254            let mut guard = self.state.lock().unwrap();
255            let acct = guard.entry(account_id.to_owned()).or_default();
256            acct.tasks.insert(Id::from(task_id), task);
257        }
258
259        /// Pre-populate a TaskList with a task in the given account.
260        pub fn add_task_list_with_task(&mut self, account_id: &str, list_id: &str) {
261            let task_list: TaskList = serde_json::from_value(serde_json::json!({
262                "id": list_id,
263                "name": "Test List",
264                "sortOrder": 0,
265                "isSubscribed": true,
266                "myRights": {
267                    "mayReadItems": true,
268                    "mayWriteAll": true,
269                    "mayWriteOwn": true,
270                    "mayUpdatePrivate": true,
271                    "mayRSVP": true,
272                    "mayAdmin": true,
273                    "mayDelete": true
274                }
275            }))
276            .expect("task list fixture must deserialize");
277            let mut guard = self.state.lock().unwrap();
278            let acct = guard.entry(account_id.to_owned()).or_default();
279            acct.task_lists.insert(Id::from(list_id), task_list);
280            // Add a task referencing the list
281            let task: Task = serde_json::from_value(serde_json::json!({
282                "id": "task1",
283                "taskListId": list_id
284            }))
285            .expect("task fixture must deserialize");
286            acct.tasks.insert(Id::from("task1"), task);
287        }
288    }
289
290    impl JmapBackend for MockBackend {
291        type Error = MockError;
292        type CallerCtx = ();
293
294        async fn account_exists(&self, _caller: &(), account_id: &Id) -> Result<bool, Self::Error> {
295            Ok(self.state.lock().unwrap().contains_key(account_id.as_ref()))
296        }
297
298        async fn get_objects<O: GetObject + Send + Sync>(
299            &self,
300            _caller: &(),
301            account_id: &Id,
302            ids: Option<&[Id]>,
303            _properties: Option<&[String]>,
304        ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
305            // Attempt to serve from the tasks store via a serde round-trip.
306            // When O = Task this is identity; for other types the deserialize
307            // step will fail (no data in the store matches) and we fall back
308            // to empty — preserving the prior behaviour for TaskList/get etc.
309            let guard = self.state.lock().unwrap();
310            let Some(acct) = guard.get(account_id.as_ref()) else {
311                return Ok((vec![], vec![]));
312            };
313
314            let mut found: Vec<O> = Vec::new();
315            let mut not_found: Vec<Id> = Vec::new();
316
317            if let Some(id_slice) = ids {
318                for id in id_slice {
319                    if let Some(task) = acct.tasks.get(id) {
320                        match serde_json::to_value(task)
321                            .ok()
322                            .and_then(|v| serde_json::from_value::<O>(v).ok())
323                        {
324                            Some(obj) => found.push(obj),
325                            None => not_found.push(id.clone()),
326                        }
327                    } else {
328                        not_found.push(id.clone());
329                    }
330                }
331            }
332            // If no specific ids were requested, serve nothing (empty list) —
333            // the isDraft check always passes specific ids.
334            Ok((found, not_found))
335        }
336
337        async fn get_state<O: JmapObject + Send + Sync>(
338            &self,
339            _caller: &(),
340            _account_id: &Id,
341        ) -> Result<State, Self::Error> {
342            Ok(State::from("0"))
343        }
344
345        async fn get_changes<O: JmapObject + Send + Sync>(
346            &self,
347            _caller: &(),
348            _account_id: &Id,
349            _since_state: &State,
350            _max_changes: Option<u64>,
351        ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
352            Ok(ChangesResult::new(
353                vec![],
354                vec![],
355                vec![],
356                false,
357                State::from("0"),
358            ))
359        }
360
361        async fn query_objects<O: QueryObject + Send + Sync>(
362            &self,
363            _caller: &(),
364            _account_id: &Id,
365            _filter: Option<&O::Filter>,
366            _sort: Option<&[O::Comparator]>,
367            _limit: Option<u64>,
368            _position: i64,
369        ) -> Result<QueryResult, Self::Error> {
370            Ok(QueryResult::new(
371                vec![],
372                0,
373                Some(0),
374                State::from("0"),
375                false,
376            ))
377        }
378
379        async fn query_changes<O: QueryObject + Send + Sync>(
380            &self,
381            _caller: &(),
382            _account_id: &Id,
383            since_query_state: &State,
384            _filter: Option<&O::Filter>,
385            _sort: Option<&[O::Comparator]>,
386            _max_changes: Option<u64>,
387            _up_to_id: Option<&Id>,
388            _collapse_threads: bool,
389        ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
390            Ok(QueryChangesResult::new(
391                since_query_state.clone(),
392                State::from("0"),
393                Some(0),
394                vec![],
395                vec![],
396            ))
397        }
398    }
399
400    impl TasksBackend for MockBackend {
401        async fn create_object<O: SetObject + Send + Sync>(
402            &self,
403            _caller: &(),
404            _account_id: &Id,
405            _create_id: &str,
406            obj: O,
407        ) -> Result<(Id, O), BackendSetError<Self::Error>> {
408            Ok((Id::from("mock-id-1"), obj))
409        }
410
411        async fn update_object<O: SetObject + Send + Sync>(
412            &self,
413            _caller: &(),
414            _account_id: &Id,
415            _id: &Id,
416            _patch: O::Patch,
417        ) -> Result<Option<O>, BackendSetError<Self::Error>> {
418            Err(BackendSetError::SetError(SetError::new(
419                SetErrorType::Forbidden,
420            )))
421        }
422
423        async fn destroy_object<O: SetObject + Send + Sync>(
424            &self,
425            _caller: &(),
426            account_id: &Id,
427            id: &Id,
428        ) -> Result<(), BackendSetError<Self::Error>> {
429            let mut guard = self.state.lock().unwrap();
430            if let Some(acct) = guard.get_mut(account_id.as_ref()) {
431                if acct.notifications.remove(id).is_some() {
432                    acct.notification_state += 1;
433                    return Ok(());
434                }
435                if acct.tasks.remove(id).is_some() {
436                    acct.task_state += 1;
437                    return Ok(());
438                }
439                if acct.task_lists.remove(id).is_some() {
440                    acct.task_list_state += 1;
441                    return Ok(());
442                }
443            }
444            Err(BackendSetError::SetError(SetError::new(
445                SetErrorType::NotFound,
446            )))
447        }
448
449        fn supports_type<O: JmapObject>(&self) -> bool {
450            true
451        }
452
453        async fn copy_task(
454            &self,
455            _caller: &(),
456            _from_account_id: &Id,
457            _to_account_id: &Id,
458            task: Task,
459        ) -> Result<(Id, Task), BackendSetError<Self::Error>> {
460            Ok((Id::from("copied-task-1"), task))
461        }
462
463        async fn update_task_per_user(
464            &self,
465            caller: &(),
466            account_id: &Id,
467            id: &Id,
468            patch: jmap_types::PatchObject,
469        ) -> Result<Option<Task>, BackendSetError<Self::Error>> {
470            // Track that this per-user path was called.
471            self.per_user_calls.fetch_add(1, Ordering::Relaxed);
472            // Delegate to update_object (same outcome as default impl).
473            self.update_object::<Task>(caller, account_id, id, patch)
474                .await
475        }
476
477        async fn task_list_has_tasks(
478            &self,
479            _caller: &(),
480            account_id: &Id,
481            task_list_id: &Id,
482        ) -> bool {
483            let guard = self.state.lock().unwrap();
484            if let Some(acct) = guard.get(account_id.as_ref()) {
485                return acct.tasks.values().any(|t| {
486                    t.task_list_id
487                        .as_ref()
488                        .map(|lid| lid == task_list_id)
489                        .unwrap_or(false)
490                });
491            }
492            false
493        }
494    }
495}
496
497// ---------------------------------------------------------------------------
498// Tests
499// ---------------------------------------------------------------------------
500
501#[cfg(test)]
502mod tests {
503    use std::sync::atomic::Ordering;
504    use std::sync::Arc;
505
506    use jmap_server::{Dispatcher, JmapRequest, State};
507    use serde_json::json;
508
509    use super::*;
510    use crate::test_support::MockBackend;
511
512    // Helper: build a minimal JmapRequest with one method call.
513    fn single_call(method: &str, args: serde_json::Value, call_id: &str) -> JmapRequest {
514        JmapRequest::new(
515            vec!["urn:ietf:params:jmap:tasks".into()],
516            vec![(method.into(), args, call_id.into())],
517            None,
518        )
519    }
520
521    /// Oracle: register_tasks_handlers registers all 14 JMAP Tasks methods.
522    ///
523    /// Verification: each method name returns a non-error response when
524    /// dispatched with a valid account (not `unknownMethod`).
525    #[tokio::test]
526    async fn registers_all_14_methods() {
527        let backend = Arc::new(MockBackend::new_with_account("acc1"));
528        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
529        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
530
531        let methods = [
532            ("TaskList/get", json!({"accountId": "acc1", "ids": null})),
533            (
534                "TaskList/changes",
535                json!({"accountId": "acc1", "sinceState": "0"}),
536            ),
537            ("TaskList/set", json!({"accountId": "acc1", "destroy": []})),
538            ("Task/get", json!({"accountId": "acc1", "ids": null})),
539            (
540                "Task/changes",
541                json!({"accountId": "acc1", "sinceState": "0"}),
542            ),
543            ("Task/set", json!({"accountId": "acc1", "destroy": []})),
544            (
545                "Task/copy",
546                json!({"fromAccountId": "acc1", "accountId": "acc1", "create": {}}),
547            ),
548            (
549                "Task/query",
550                json!({"accountId": "acc1", "filter": null, "sort": null}),
551            ),
552            (
553                "Task/queryChanges",
554                json!({"accountId": "acc1", "sinceQueryState": "0"}),
555            ),
556            (
557                "TaskNotification/get",
558                json!({"accountId": "acc1", "ids": null}),
559            ),
560            (
561                "TaskNotification/changes",
562                json!({"accountId": "acc1", "sinceState": "0"}),
563            ),
564            (
565                "TaskNotification/set",
566                json!({"accountId": "acc1", "destroy": []}),
567            ),
568            (
569                "TaskNotification/query",
570                json!({"accountId": "acc1", "filter": null, "sort": null}),
571            ),
572            (
573                "TaskNotification/queryChanges",
574                json!({"accountId": "acc1", "sinceQueryState": "0"}),
575            ),
576        ];
577
578        for (method, args) in methods {
579            let req = single_call(method, args, "c0");
580            let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
581            assert_eq!(
582                resp.method_responses.len(),
583                1,
584                "{method}: expected 1 response"
585            );
586            let (_, resp_args, _) = &resp.method_responses[0];
587            assert_ne!(
588                resp_args["type"], "unknownMethod",
589                "{method}: must not be unknownMethod — is it registered?"
590            );
591        }
592    }
593
594    /// Oracle: TaskNotification/set with create entries → notCreated contains
595    /// `forbidden` for every create entry; no top-level error.
596    #[tokio::test]
597    async fn task_notification_set_create_returns_forbidden() {
598        let backend = Arc::new(MockBackend::new_with_account("acc1"));
599        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
600        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
601
602        let req = single_call(
603            "TaskNotification/set",
604            json!({
605                "accountId": "acc1",
606                "create": {
607                    "c1": {
608                        "id": "x",
609                        "created": "2024-01-01T00:00:00Z",
610                        "changedBy": { "@type": "Person", "name": "A" },
611                        "type": "created",
612                        "taskId": "t1"
613                    }
614                }
615            }),
616            "c0",
617        );
618        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
619        let (_, args, _) = &resp.method_responses[0];
620        assert!(
621            args.get("type").is_none(),
622            "must not be a top-level error: {args}"
623        );
624        assert_eq!(
625            args["notCreated"]["c1"]["type"], "forbidden",
626            "create must be forbidden: {args}"
627        );
628    }
629
630    /// Oracle: TaskList/set destroy with tasks returns taskListHasTasks error.
631    ///
632    /// When `onDestroyRemoveTasks` is false (default) and the task list has tasks,
633    /// the destroy should fail with a custom `taskListHasTasks` error.
634    #[tokio::test]
635    async fn task_list_set_destroy_with_tasks_returns_task_list_has_tasks() {
636        let mut backend = MockBackend::new_with_account("acc1");
637        backend.add_task_list_with_task("acc1", "list1");
638        let backend = Arc::new(backend);
639
640        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
641        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
642
643        let req = single_call(
644            "TaskList/set",
645            json!({
646                "accountId": "acc1",
647                "destroy": ["list1"],
648                "onDestroyRemoveTasks": false
649            }),
650            "c0",
651        );
652        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
653        let (_, args, _) = &resp.method_responses[0];
654        assert!(
655            args.get("type").is_none(),
656            "must not be a top-level error: {args}"
657        );
658        assert_eq!(
659            args["notDestroyed"]["list1"]["type"], "taskListHasTasks",
660            "must return taskListHasTasks when list has tasks: {args}"
661        );
662    }
663
664    // ── Integration tests: isDraft, utcStart, per-user routing ──────────────
665
666    /// Oracle: draft-tasks-06 §4 — isDraft false→true revert is rejected via
667    /// dispatcher (end-to-end path through register_tasks_handlers).
668    #[tokio::test]
669    async fn isdraft_revert_via_dispatcher() {
670        let mut backend = MockBackend::new_with_account("acc1");
671        backend.seed_task("acc1", "t1", false);
672        let backend = Arc::new(backend);
673
674        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
675        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
676
677        let req = single_call(
678            "Task/set",
679            json!({
680                "accountId": "acc1",
681                "update": { "t1": { "isDraft": true } }
682            }),
683            "c0",
684        );
685        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
686        let (_, args, _) = &resp.method_responses[0];
687        assert!(
688            args.get("type").is_none(),
689            "must not be a top-level error: {args}"
690        );
691        assert_eq!(
692            args["notUpdated"]["t1"]["type"], "invalidProperties",
693            "isDraft revert must be invalidProperties: {args}"
694        );
695        assert_eq!(
696            args["notUpdated"]["t1"]["properties"][0], "isDraft",
697            "isDraft must be listed in properties: {args}"
698        );
699    }
700
701    /// Oracle: draft-tasks-06 §4 — isDraft false (draft → published) is always
702    /// allowed; the handler must not pre-reject it.
703    #[tokio::test]
704    async fn isdraft_draft_to_publish_allowed() {
705        let mut backend = MockBackend::new_with_account("acc1");
706        backend.seed_task("acc1", "t1", true);
707        let backend = Arc::new(backend);
708
709        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
710        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
711
712        let req = single_call(
713            "Task/set",
714            json!({
715                "accountId": "acc1",
716                "update": { "t1": { "isDraft": false } }
717            }),
718            "c0",
719        );
720        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
721        let (_, args, _) = &resp.method_responses[0];
722        // The patch must NOT be pre-rejected with invalidProperties.
723        if let Some(not_updated) = args["notUpdated"].as_object() {
724            if let Some(err) = not_updated.get("t1") {
725                assert_ne!(
726                    err["type"].as_str(),
727                    Some("invalidProperties"),
728                    "isDraft:false must not produce invalidProperties: {args}"
729                );
730            }
731        }
732    }
733
734    /// Oracle: draft-tasks-06 §4 (lines 739-772) — utcStart is NOT returned
735    /// when not in the properties list.
736    #[tokio::test]
737    async fn utcstart_not_in_default_properties() {
738        let backend = Arc::new(MockBackend::new_with_account("acc1"));
739        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
740        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
741
742        let req = single_call(
743            "Task/get",
744            json!({ "accountId": "acc1", "ids": null, "properties": ["id"] }),
745            "c0",
746        );
747        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
748        let (_, args, _) = &resp.method_responses[0];
749        assert!(args.get("type").is_none(), "must not be error: {args}");
750        for item in args["list"].as_array().unwrap_or(&vec![]) {
751            assert!(
752                item.get("utcStart").is_none(),
753                "utcStart must not appear when not requested: {item}"
754            );
755        }
756    }
757
758    /// Oracle: draft-tasks-06 §4 — when utcStart is explicitly requested,
759    /// the handler invokes compute_task_utc_times (default: returns None, so
760    /// no value injected), but no error is raised.
761    #[tokio::test]
762    async fn utcstart_returned_when_requested() {
763        let backend = Arc::new(MockBackend::new_with_account("acc1"));
764        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
765        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
766
767        let req = single_call(
768            "Task/get",
769            json!({
770                "accountId": "acc1",
771                "ids": null,
772                "properties": ["id", "utcStart"]
773            }),
774            "c0",
775        );
776        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
777        let (_, args, _) = &resp.method_responses[0];
778        assert!(
779            args.get("type").is_none(),
780            "Task/get with utcStart must not error: {args}"
781        );
782    }
783
784    /// Oracle: draft-tasks-06 §4.5.1 — a per-user-only patch is routed to
785    /// `update_task_per_user`. MockBackend tracks the call count.
786    #[tokio::test]
787    async fn per_user_patch_split() {
788        let backend = Arc::new(MockBackend::new_with_account("acc1"));
789        let mut dispatcher: Dispatcher<()> = Dispatcher::new();
790        register_tasks_handlers(&mut dispatcher, Arc::clone(&backend));
791
792        let before = backend.per_user_calls.load(Ordering::Relaxed);
793
794        let req = single_call(
795            "Task/set",
796            json!({
797                "accountId": "acc1",
798                "update": { "t1": { "color": "#ff0000" } }
799            }),
800            "c0",
801        );
802        let resp = dispatcher.dispatch(req, (), State::from("s0")).await;
803        let (_, args, _) = &resp.method_responses[0];
804        assert!(
805            args.get("type").is_none(),
806            "must not be top-level error: {args}"
807        );
808
809        let after = backend.per_user_calls.load(Ordering::Relaxed);
810        assert_eq!(
811            after - before,
812            1,
813            "per_user update must have been called exactly once for a color-only patch"
814        );
815    }
816}