Skip to main content

jmap_tasks_server/
task.rs

1//! Task/* method handlers (draft-tasks-06 §4).
2//!
3//! The `isDraft` immutability constraint (once false, never true again) is
4//! enforced by [`crate::TasksBackend::update_object`], not by Task/set.
5//!
6//! # Wire-shape contract
7//!
8//! Every `handle_*` function in this module conforms to the canonical JMAP
9//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
10//! Object whose fields match the corresponding RFC 8620 §5 method shape
11//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3, `/copy` → §5.4,
12//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
13//! arguments defined by draft-tasks-06 §4. The returned `Value` is the
14//! corresponding method-response object per the same section refs.
15//!
16//! The returned `HandlerOutput::extra_invocations` carries any invocations
17//! that this handler injected into the request stream (RFC 8620 §6.3).
18//! For the standard `/get`, `/changes`, `/set`, `/query`, and
19//! `/queryChanges` handlers in this module the vector is **always
20//! empty**. `handle_task_copy` is the one exception: it MAY emit
21//! `Task/set` follow-up invocations when `onSuccessDestroyOriginal` is
22//! true (RFC 8620 §5.4).
23//!
24//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
25//! §3.6.2 and §5):
26//!
27//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
28//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
29//!   `maxObjectsInSet`;
30//! - `/set`, `/copy`: `stateMismatch`;
31//! - `/copy`: `fromAccountNotFound`;
32//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
33//! - `/queryChanges`: `tooManyChanges`;
34//! - `/query`, `/queryChanges`: `unsupportedFilter`;
35//! - `/query`: `unsupportedSort`, `anchorNotFound`.
36//!
37//! Per-target failures inside a `/set` or `/copy` call surface in the
38//! `notCreated` / `notUpdated` / `notDestroyed` maps within `Ok((Value, ...))`,
39//! not as `Err`.
40
41use std::collections::BTreeMap;
42
43use jmap_tasks_types::{Task, TaskComparator};
44use jmap_types::{Id, Invocation, JmapError, PatchObject};
45use serde::Deserialize;
46use serde_json::{Value, json};
47
48use crate::TasksBackend;
49use crate::helpers::{
50    SetAccumulators, check_metadata_entry, enforce_max_objects_in_set, extract_account_id,
51    finalize_set_response, reject_unsupported_sort, resolve_refs,
52};
53use jmap_server::{
54    HandlerOutput, backend_set_error_value, bool_arg, reject_read_only_patch, reject_server_set,
55    server_fail_from_backend, server_fail_value_from_backend,
56};
57
58// ---------------------------------------------------------------------------
59// Task/get
60// ---------------------------------------------------------------------------
61
62/// Handle a `Task/get` method call (draft-tasks-06 §4.5).
63///
64/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
65/// `ids`, optional `properties`); the returned `Value` is the §5.1
66/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
67///
68/// If `"utcStart"` or `"utcDue"` appear in the requested `properties` (or if
69/// `properties` is `null` — meaning all fields), [`TasksBackend::compute_utc_times`]
70/// is called for each returned task and the computed values are merged in
71/// (draft-tasks-06 §4, utcStart/utcDue paragraphs).
72///
73/// `using` is the request's capability list (pass
74/// [`jmap_server::CallContext::using`]). When the backend lists Task for
75/// draft-ietf-jmap-metadata-04 ([`JmapBackend::metadata_info`](jmap_server::JmapBackend::metadata_info)),
76/// `metadata` is returned as an object, by default only with
77/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
78/// `properties` may hold `metadata/<namespace>` subselectors (-04 §2,
79/// §3.1); see [`jmap_server::handle_get_with_metadata`].
80///
81/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
82pub async fn handle_task_get<B: TasksBackend>(
83    backend: &B,
84    caller: &B::CallerCtx,
85    args: Value,
86    using: &[String],
87) -> Result<HandlerOutput, JmapError> {
88    // Determine whether utcStart / utcDue are requested.
89    let want_utc = match args.get("properties") {
90        None | Some(Value::Null) => true, // all properties requested
91        Some(Value::Array(props)) => props
92            .iter()
93            .any(|p| p.as_str().is_some_and(|s| s == "utcStart" || s == "utcDue")),
94        _ => false,
95    };
96
97    // Peek accountId to thread through compute_utc_times (bd:JMAP-ops7.25).
98    // handle_get re-extracts and re-validates idempotently below; a malformed
99    // or missing accountId surfaces here as invalidArguments before the
100    // delegate call.
101    let account_id: Id = args
102        .get("accountId")
103        .and_then(|v| v.as_str())
104        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))
105        .and_then(|s| {
106            Id::new_validated(s).map_err(|e| {
107                JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}"))
108            })
109        })?;
110
111    // Delegate to the generic get handler.
112    let HandlerOutput {
113        primary: mut response,
114        extra_invocations: tail,
115        ..
116    } = jmap_server::handle_get_with_metadata::<Task, B>(backend, caller, args, using).await?;
117
118    // If utcStart or utcDue were requested, augment each returned task.
119    if want_utc && let Some(Value::Array(list)) = response.get_mut("list") {
120        for item in list.iter_mut() {
121            if let Ok(task) = Task::deserialize(&*item) {
122                let (utc_start, utc_due) = backend
123                    .compute_utc_times(caller, &account_id, &task, None)
124                    .await;
125                if let Some(s) = utc_start {
126                    item["utcStart"] = Value::String(s.into_inner());
127                }
128                if let Some(d) = utc_due {
129                    item["utcDue"] = Value::String(d.into_inner());
130                }
131            }
132        }
133    }
134
135    Ok(HandlerOutput::new(response).with_extra(tail))
136}
137
138// ---------------------------------------------------------------------------
139// Task/changes
140// ---------------------------------------------------------------------------
141
142/// Handle a `Task/changes` method call (draft-tasks-06 §4.6).
143///
144/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
145/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
146/// `/changes` response shape (`accountId`, `oldState`, `newState`,
147/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
148///
149/// `using` is the request's capability list (pass
150/// [`jmap_server::CallContext::using`]); with
151/// `urn:ietf:params:jmap:metadata` the request may set
152/// draft-ietf-jmap-metadata-04 §3.3 `ignoreMetadataOnlyChanges`, and
153/// without it metadata-only changes are left out (-04 §3).
154///
155/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
156pub async fn handle_task_changes<B: TasksBackend>(
157    backend: &B,
158    caller: &B::CallerCtx,
159    args: Value,
160    using: &[String],
161) -> Result<HandlerOutput, JmapError> {
162    jmap_server::handle_changes::<Task, B>(backend, caller, args, using).await
163}
164
165// ---------------------------------------------------------------------------
166// Task/set
167// ---------------------------------------------------------------------------
168
169/// The Task properties that hold the id of another record, which a client
170/// may set to a `#creationId` reference (RFC 8620 §5.3).
171const TASK_ID_PROPERTIES: &[&str] = &["taskListId"];
172
173/// Handle a `Task/set` method call (draft-tasks-06 §4.7).
174///
175/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
176/// `ifInState`, optional `create` / `update` / `destroy` maps); the
177/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
178/// `oldState`, `newState`, plus the per-operation result maps).
179///
180/// **isDraft immutability**: this handler does not check `isDraft`. The
181/// backend's [`crate::TasksBackend::update_object`] MUST reject a patch that
182/// sets `isDraft: true` on a Task whose stored value is not `true` with
183/// `invalidProperties`, atomically with the write; the rejection is reported
184/// in `notUpdated`.
185///
186/// **`taskListId` references**: a `#creationId` value on create or update
187/// names a TaskList created earlier in the request and resolves against
188/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]; RFC 8620
189/// §5.3). An unknown reference is `invalidProperties` naming `taskListId`.
190///
191/// `using` is the request's capability list (pass
192/// [`jmap_server::CallContext::using`]): a write to `metadata` or
193/// `privateMetadata` without `urn:ietf:params:jmap:metadata` is
194/// `invalidProperties` (draft-ietf-jmap-metadata-04 §3), as is `null` for
195/// either in a create (-04 §3.2). The backend validates the rest.
196///
197/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
198pub async fn handle_task_set<B: TasksBackend>(
199    backend: &B,
200    caller: &B::CallerCtx,
201    created_ids: &BTreeMap<Id, Id>,
202    args: Value,
203    using: &[String],
204) -> Result<HandlerOutput, JmapError> {
205    let (account_id, mut args) = extract_account_id(args)?;
206
207    // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
208    // error). Without this, a /set against an unknown accountId would silently
209    // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
210    if !backend
211        .account_exists(caller, &account_id)
212        .await
213        .map_err(|e| server_fail_from_backend(&e))?
214    {
215        return Err(JmapError::account_not_found());
216    }
217
218    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
219    // unbounded /set batches before touching the storage layer.
220    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
221
222    let old_state = backend
223        .get_state::<Task>(caller, &account_id)
224        .await
225        .map_err(|e| server_fail_from_backend(&e))?;
226
227    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
228        && if_in_state != old_state.as_ref()
229    {
230        return Err(JmapError::state_mismatch());
231    }
232
233    let mut created = serde_json::Map::new();
234    let mut not_created = serde_json::Map::new();
235    let mut updated = serde_json::Map::new();
236    let mut not_updated = serde_json::Map::new();
237    let mut destroyed_list: Vec<Value> = Vec::new();
238    let mut not_destroyed = serde_json::Map::new();
239    let mut mutated = false;
240
241    // -----------------------------------------------------------------------
242    // create
243    // -----------------------------------------------------------------------
244    if let Some(Value::Object(create_map)) = args.remove("create") {
245        for (create_id, mut obj_val) in create_map {
246            if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Task>) {
247                not_created.insert(create_id, serde_json::Value::from(&err));
248                continue;
249            }
250            if let Some(Err(err)) = obj_val
251                .as_object()
252                .map(|o| check_metadata_entry(o, true, using))
253            {
254                not_created.insert(create_id, serde_json::Value::from(&*err));
255                continue;
256            }
257            if let Err(err) = resolve_refs(&mut obj_val, TASK_ID_PROPERTIES, created_ids) {
258                not_created.insert(create_id, serde_json::Value::from(&*err));
259                continue;
260            }
261            // `Task.id` is optional, so the create parses without one and
262            // `build` sets the id the backend mints.
263            let mut task: Task = match serde_json::from_value(obj_val) {
264                Ok(t) => t,
265                Err(e) => {
266                    not_created.insert(
267                        create_id,
268                        json!({ "type": "invalidProperties", "description": e.to_string() }),
269                    );
270                    continue;
271                }
272            };
273
274            let build = move |id: &Id| {
275                task.id = Some(id.clone());
276                task
277            };
278            match backend
279                .create_object::<Task, _>(caller, &account_id, &create_id, build)
280                .await
281            {
282                Ok((_new_id, created_obj)) => {
283                    mutated = true;
284                    created.insert(create_id, jmap_server::serialize_value(&created_obj)?);
285                }
286                Err(e) => {
287                    not_created.insert(create_id, backend_set_error_value(e));
288                }
289            }
290        }
291    }
292
293    // -----------------------------------------------------------------------
294    // update
295    // -----------------------------------------------------------------------
296    if let Some(Value::Object(update_map)) = args.remove("update") {
297        for (id_str, mut patch_val) in update_map {
298            // isDraft immutability (draft-tasks-06 §4 isDraft paragraph) is
299            // enforced by the backend in update_object, atomically with the
300            // write (TasksBackend::update_object, bd:JMAP-h47t.29).
301            let id = match jmap_server::parse_wire_id(&id_str, "id") {
302                Ok(id) => id,
303                Err(err) => {
304                    not_updated.insert(id_str, serde_json::Value::from(&*err));
305                    continue;
306                }
307            };
308
309            // Route to the per-user update path when every patch key targets
310            // a per-user Task property (draft-tasks-06 §4.5.1).
311            //
312            // PatchObject keys are RFC 6901 JSON Pointers (RFC 8620 §5.3), so a
313            // per-user keyword toggle is sent as `keywords/done`, not bare
314            // `keywords`. Classify on the FIRST pointer segment (the substring
315            // before the first '/'), not the whole key.
316            //
317            // The null short-circuit that was here previously (`v.is_null() ||
318            // ...`) misclassified a delete-shared-property patch like
319            // `{"title": null}` as per-user-only, and an empty patch object as
320            // per-user-only via vacuous-truth on `iter().all`. Both go to
321            // `update_object` now: deletions are shared mutations, and an
322            // empty patch is a no-op that should not bump per-user state.
323            //
324            // Per-user property names (`keywords`, `color`, `freeBusyStatus`,
325            // `useDefaultAlerts`, `alerts`) contain no `/` or `~`, so a plain
326            // `split('/').next()` is correct without RFC 6901 unescaping.
327            let is_per_user_only = patch_val.as_object().is_some_and(|m| {
328                !m.is_empty()
329                    && m.keys().all(|k| {
330                        let head = k.split('/').next().unwrap_or(k);
331                        jmap_tasks_types::is_per_user_task_property(head)
332                    })
333            });
334
335            if let Err(err) = resolve_refs(&mut patch_val, TASK_ID_PROPERTIES, created_ids) {
336                not_updated.insert(id_str, serde_json::Value::from(&*err));
337                continue;
338            }
339
340            // Convert wire-format Value into a typed PatchObject. RFC 8620
341            // §5.3 mandates a PatchObject is a JSON Object; non-object
342            // values produce an `invalidPatch` SetError. Conversion runs
343            // after the isDraft and per-user-routing introspection above so
344            // those checks operate on the raw wire shape.
345            let patch = match serde_json::from_value::<PatchObject>(patch_val) {
346                Ok(p) => p,
347                Err(e) => {
348                    not_updated.insert(
349                        id_str,
350                        json!({ "type": "invalidPatch", "description": e.to_string() }),
351                    );
352                    continue;
353                }
354            };
355            if let Some(err) = reject_read_only_patch::<Task>(patch.as_map(), None) {
356                not_updated.insert(id_str, serde_json::Value::from(&err));
357                continue;
358            }
359            if let Err(err) = check_metadata_entry(patch.as_map(), false, using) {
360                not_updated.insert(id_str, serde_json::Value::from(&*err));
361                continue;
362            }
363
364            let update_result = if is_per_user_only {
365                backend
366                    .update_task_per_user(caller, &account_id, &id, patch)
367                    .await
368            } else {
369                backend
370                    .update_object::<Task>(caller, &account_id, &id, patch)
371                    .await
372            };
373
374            match update_result {
375                Ok(Some(obj)) => {
376                    mutated = true;
377                    updated.insert(id_str, jmap_server::serialize_value(&obj)?);
378                }
379                Ok(None) => {
380                    mutated = true;
381                    updated.insert(id_str, Value::Null);
382                }
383                Err(e) => {
384                    not_updated.insert(id_str, backend_set_error_value(e));
385                }
386            }
387        }
388    }
389
390    // -----------------------------------------------------------------------
391    // destroy
392    // -----------------------------------------------------------------------
393    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
394        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
395        // Two-pass validation is intentional: this up-front loop fails the whole
396        // request loudly; the `None => continue` arm in the inner match below
397        // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
398        // delete this pre-check on the reasoning that the inner match handles
399        // non-string elements — silent-skip is the wrong behaviour per the
400        // workspace "silent-drop is a data-integrity bug class" rule
401        // (JMAP-wlip.1).
402        let id_strs: Vec<&str> = destroy_arr
403            .iter()
404            .map(|v| {
405                v.as_str().ok_or_else(|| {
406                    JmapError::invalid_arguments(format!(
407                        "destroy: every element must be a string Id; got {}",
408                        jmap_server::json_type_name(v)
409                    ))
410                })
411            })
412            .collect::<Result<_, _>>()?;
413        for id_str in id_strs {
414            let id_str = id_str.to_owned();
415            let id = match jmap_server::parse_wire_id(&id_str, "id") {
416                Ok(id) => id,
417                Err(err) => {
418                    not_destroyed.insert(id_str, serde_json::Value::from(&*err));
419                    continue;
420                }
421            };
422
423            match backend
424                .destroy_object::<Task>(caller, &account_id, &id)
425                .await
426            {
427                Ok(()) => {
428                    mutated = true;
429                    destroyed_list.push(Value::String(id_str));
430                }
431                Err(e) => {
432                    not_destroyed.insert(id_str, backend_set_error_value(e));
433                }
434            }
435        }
436    }
437
438    finalize_set_response::<B, Task>(
439        backend,
440        caller,
441        &account_id,
442        old_state,
443        mutated,
444        SetAccumulators {
445            created,
446            updated,
447            destroyed: destroyed_list,
448            not_created,
449            not_updated,
450            not_destroyed,
451        },
452    )
453    .await
454}
455
456// ---------------------------------------------------------------------------
457// Task/copy
458// ---------------------------------------------------------------------------
459
460/// Handle a `Task/copy` method call (draft-tasks-06 §4.8).
461///
462/// `args` is the RFC 8620 §5.4 `/copy` request shape (`fromAccountId`,
463/// optional `ifFromInState`, `accountId`, optional `ifInState`, `create`
464/// map, optional `onSuccessDestroyOriginal`, optional
465/// `destroyFromIfInState`); the returned `Value` is the §5.4 `/copy`
466/// response shape (`fromAccountId`, `accountId`, optional `oldState`,
467/// `newState`, optional `created`, optional `notCreated`).
468///
469/// `call_id` is the request's method-call id, used to construct any
470/// follow-up `Task/set` invocations injected when
471/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4 + §6.3).
472///
473/// Copies tasks from `fromAccountId` into the current account. The `create`
474/// map keys are client-side creation ids; the backend assigns new server-side
475/// ids.
476///
477/// `using` is the request's capability list (pass
478/// [`jmap_server::CallContext::using`]). draft-ietf-jmap-metadata-04 §3.4:
479/// the copy keeps the source's `metadata`, and its `privateMetadata` only
480/// with `urn:ietf:params:jmap:metadata` in `using` and when the
481/// destination supports it; neither is copied when the destination does
482/// not list Task ([`JmapBackend::metadata_info`](jmap_server::JmapBackend::metadata_info)).
483/// The create object "MAY include metadata and privateMetadata to override
484/// the copied values, with the same rules as a create in Foo/set": the
485/// handler rejects them without the capability and rejects `null`, and
486/// [`TasksBackend::copy_object`] validates the rest against the create
487/// object only: "Copied values are not revalidated against the
488/// destination account".
489///
490/// Returns `(response_args, extra_invocations)`. The extra invocation list
491/// is populated with a follow-up `Task/set` invocation when
492/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4); otherwise it is
493/// empty.
494pub async fn handle_task_copy<B: TasksBackend>(
495    backend: &B,
496    caller: &B::CallerCtx,
497    args: Value,
498    call_id: &str,
499    using: &[String],
500) -> Result<HandlerOutput, JmapError> {
501    let (to_account_id, mut args) = extract_account_id(args)?;
502
503    if !backend
504        .account_exists(caller, &to_account_id)
505        .await
506        .map_err(|e| server_fail_from_backend(&e))?
507    {
508        return Err(JmapError::account_not_found());
509    }
510
511    let from_account_id_str = args
512        .remove("fromAccountId")
513        .and_then(|v| v.as_str().map(|s| s.to_owned()))
514        .ok_or_else(|| JmapError::invalid_arguments("fromAccountId is required"))?;
515    let from_account_id = Id::new_validated(from_account_id_str)
516        .map_err(|e| JmapError::invalid_arguments(format!("fromAccountId: {e}")))?;
517
518    // RFC 8620 §5.4: fromAccountId MUST differ from accountId. The canonical
519    // sibling jmap-mail-server enforces this in handle_email_copy; without it
520    // a same-account "copy" silently produces a duplicate within the source
521    // account, contradicting the meaning of /copy.
522    if from_account_id == to_account_id {
523        return Err(JmapError::invalid_arguments(
524            "fromAccountId must be different from accountId",
525        ));
526    }
527
528    // RFC 8620 §5.4: validate fromAccountId resolves to a real account;
529    // emit the spec-canonical `fromAccountNotFound` (not the generic
530    // `accountNotFound`) when it does not.
531    if !backend
532        .account_exists(caller, &from_account_id)
533        .await
534        .map_err(|e| server_fail_from_backend(&e))?
535    {
536        return Err(JmapError::from_account_not_found());
537    }
538
539    // RFC 8620 §5.4 `ifFromInState`: if supplied, the source-account Task
540    // state MUST match; otherwise abort with stateMismatch. Probed before
541    // the destination state so a stale source guard fails fast.
542    if let Some(if_from_in_state) = args.get("ifFromInState").and_then(|v| v.as_str()) {
543        let from_state = backend
544            .get_state::<Task>(caller, &from_account_id)
545            .await
546            .map_err(|e| server_fail_from_backend(&e))?;
547        if if_from_in_state != from_state.as_ref() {
548            return Err(JmapError::state_mismatch());
549        }
550    }
551
552    let old_state = backend
553        .get_state::<Task>(caller, &to_account_id)
554        .await
555        .map_err(|e| server_fail_from_backend(&e))?;
556
557    // RFC 8620 §5.4 `ifInState`: if supplied, the destination-account Task
558    // state MUST match; otherwise abort with stateMismatch.
559    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
560        && if_in_state != old_state.as_ref()
561    {
562        return Err(JmapError::state_mismatch());
563    }
564
565    // RFC 8620 §5.4 `onSuccessDestroyOriginal` / `destroyFromIfInState`:
566    // parsed here so the request payload is consumed in handler-local order
567    // and so a clearly-shaped per-feature value is available below.
568    let on_success_destroy_original: bool = bool_arg(&args, "onSuccessDestroyOriginal", false);
569    let destroy_from_if_in_state: Option<String> = args
570        .get("destroyFromIfInState")
571        .and_then(|v| v.as_str())
572        .map(|s| s.to_owned());
573
574    let mut created = serde_json::Map::new();
575    let mut not_created = serde_json::Map::new();
576    let mut mutated = false;
577    // (create_id, source_id) pairs for entries that succeeded — fed to the
578    // implicit Task/set destroy below when onSuccessDestroyOriginal is true.
579    let mut copied_source_ids: Vec<(String, Id)> = Vec::new();
580
581    if let Some(Value::Object(create_map)) = args.remove("create") {
582        for (create_id, client_val) in create_map {
583            // RFC 8620 §5.4: the Foo object MUST contain an `id` property,
584            // which is the id (in the fromAccount) of the record to be copied.
585            // The earlier handler silently invented a "placeholder" id when
586            // the client omitted one, masking the missing-id case the spec
587            // treats as a hard requirement.
588            let Some(source_id_str) = client_val.get("id").and_then(|v| v.as_str()) else {
589                not_created.insert(
590                    create_id,
591                    json!({"type": "invalidProperties", "properties": ["id"]}),
592                );
593                continue;
594            };
595            let source_id: Id = match jmap_server::parse_wire_id(source_id_str, "id") {
596                Ok(id) => id,
597                Err(err) => {
598                    not_created.insert(create_id, serde_json::Value::from(&*err));
599                    continue;
600                }
601            };
602
603            // Fetch the source Task from `fromAccountId`. RFC 8620 §5.4 frames
604            // /copy as a read-from-source-then-create-in-destination operation;
605            // unknown source ids surface as `notFound` per-entry SetErrors.
606            let mut source_tasks: Vec<Task> = match backend
607                .get_objects::<Task>(
608                    caller,
609                    &from_account_id,
610                    Some(std::slice::from_ref(&source_id)),
611                    None,
612                )
613                .await
614            {
615                Ok((objs, not_found)) => {
616                    if !not_found.is_empty() || objs.is_empty() {
617                        not_created.insert(create_id, json!({"type": "notFound"}));
618                        continue;
619                    }
620                    objs
621                }
622                Err(e) => {
623                    not_created.insert(create_id, server_fail_value_from_backend(&e));
624                    continue;
625                }
626            };
627
628            // RFC 8620 §5.4: "any other properties included [in the create
629            // entry] are used instead of the current value for that property
630            // on the original." Serialize the source, overlay client-supplied
631            // properties, strip the source id so the backend assigns a fresh
632            // server id. Pattern mirrors jmap-calendars-server event.rs:610-642.
633            // draft-ietf-jmap-metadata-04 §3.4: metadata overrides follow the
634            // Foo/set create rules (§3, §3.2).
635            if let Some(Err(err)) = client_val
636                .as_object()
637                .map(|o| check_metadata_entry(o, true, using))
638            {
639                not_created.insert(create_id, Value::from(&*err));
640                continue;
641            }
642            // -04 §3.4: "When the request does not use this capability, only
643            // metadata is copied", "privateMetadata is not copied when the
644            // destination does not support it, and neither property is
645            // copied when the data type is not listed in the destination
646            // account". The overrides are merged in below.
647            let info = backend.metadata_info::<Task>(caller, &to_account_id);
648            if !jmap_server::uses_metadata(using)
649                || !info.as_ref().is_some_and(|i| i.supports_private)
650            {
651                source_tasks[0].private_metadata = None;
652            }
653            if info.is_none() {
654                source_tasks[0].metadata = None;
655            }
656            let Ok(Value::Object(mut merged)) = serde_json::to_value(&source_tasks[0]) else {
657                not_created.insert(
658                    create_id,
659                    json!({
660                        "type": "serverFail",
661                        "description": "failed to serialize source Task",
662                    }),
663                );
664                continue;
665            };
666            if let Value::Object(client_props) = &client_val {
667                for (k, v) in client_props {
668                    if k != "id" {
669                        merged.insert(k.clone(), v.clone());
670                    }
671                }
672            }
673            merged.remove("id");
674
675            let task: Task = match serde_json::from_value(Value::Object(merged)) {
676                Ok(t) => t,
677                Err(e) => {
678                    not_created.insert(
679                        create_id,
680                        json!({ "type": "invalidProperties", "description": e.to_string() }),
681                    );
682                    continue;
683                }
684            };
685
686            // -04 §3.4: the backend validates only the metadata supplied in
687            // the create object; the copied values are not revalidated.
688            match backend
689                .copy_object(caller, &from_account_id, &to_account_id, task, &client_val)
690                .await
691            {
692                Ok((_new_id, created_task)) => {
693                    mutated = true;
694                    created.insert(
695                        create_id.clone(),
696                        jmap_server::serialize_value(&created_task)?,
697                    );
698                    copied_source_ids.push((create_id, source_id));
699                }
700                Err(e) => {
701                    not_created.insert(create_id, backend_set_error_value(e));
702                }
703            }
704        }
705    }
706
707    let new_state = if mutated {
708        backend
709            .get_state::<Task>(caller, &to_account_id)
710            .await
711            .map_err(|e| server_fail_from_backend(&e))?
712    } else {
713        old_state.clone()
714    };
715
716    let resp = json!({
717        "fromAccountId": from_account_id.as_ref(),
718        "accountId": to_account_id.as_ref(),
719        "oldState": old_state.as_ref(),
720        "newState": new_state.as_ref(),
721        "created":    if created.is_empty()     { Value::Null } else { Value::Object(created) },
722        "notCreated": if not_created.is_empty() { Value::Null } else { Value::Object(not_created) },
723    });
724
725    // RFC 8620 §5.4 `onSuccessDestroyOriginal`: after emitting the Task/copy
726    // response, the server MUST make a single implicit Task/set call against
727    // fromAccountId destroying each successfully copied source record.
728    // `destroyFromIfInState`, if supplied, is passed through as the ifInState
729    // argument on that implicit call. The dispatcher returns the extra
730    // Invocation vec to the caller (RFC 8620 §6.3 chained responses).
731    // Pattern mirrors jmap-mail-server email.rs:2432-2575.
732    let mut extra: Vec<Invocation> = Vec::new();
733    if on_success_destroy_original && !copied_source_ids.is_empty() {
734        let from_old_state = backend
735            .get_state::<Task>(caller, &from_account_id)
736            .await
737            .map_err(|e| server_fail_from_backend(&e))?;
738
739        // Honour destroyFromIfInState on the implicit Task/set call. A
740        // mismatch yields a stateMismatch top-level error on the synthesized
741        // response (§5.4 inheriting §5.3 semantics on the chained call).
742        let mut destroy_state_mismatch = false;
743        if let Some(if_state) = destroy_from_if_in_state.as_deref()
744            && if_state != from_old_state.as_ref()
745        {
746            destroy_state_mismatch = true;
747        }
748
749        let mut destroyed_arr: Vec<Value> = Vec::new();
750        let mut not_destroyed = serde_json::Map::new();
751
752        if !destroy_state_mismatch {
753            for (_, source_id) in &copied_source_ids {
754                match backend
755                    .destroy_object::<Task>(caller, &from_account_id, source_id)
756                    .await
757                {
758                    Ok(()) => {
759                        destroyed_arr.push(Value::String(source_id.as_ref().to_owned()));
760                    }
761                    Err(e) => {
762                        not_destroyed
763                            .insert(source_id.as_ref().to_owned(), backend_set_error_value(e));
764                    }
765                }
766            }
767        }
768
769        let from_new_state = backend
770            .get_state::<Task>(caller, &from_account_id)
771            .await
772            .map_err(|e| server_fail_from_backend(&e))?;
773
774        let set_resp = if destroy_state_mismatch {
775            json!({
776                "type": "stateMismatch",
777            })
778        } else {
779            json!({
780                "accountId": from_account_id.as_ref(),
781                "oldState": from_old_state.as_ref(),
782                "newState": from_new_state.as_ref(),
783                "created": Value::Null,
784                "updated": Value::Null,
785                "destroyed": if destroyed_arr.is_empty() { Value::Null } else { Value::Array(destroyed_arr) },
786                "notCreated": Value::Null,
787                "notUpdated": Value::Null,
788                "notDestroyed": if not_destroyed.is_empty() { Value::Null } else { Value::Object(not_destroyed) },
789            })
790        };
791
792        let method_name = if destroy_state_mismatch {
793            "error".to_owned()
794        } else {
795            "Task/set".to_owned()
796        };
797        extra.push(Invocation::new(method_name, set_resp, call_id.to_owned()));
798    }
799
800    Ok(HandlerOutput::new(resp).with_extra(extra))
801}
802
803// ---------------------------------------------------------------------------
804// Task/query
805// ---------------------------------------------------------------------------
806
807/// Handle a `Task/query` method call (draft-tasks-06 §4.13).
808///
809/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`,
810/// optional `filter`, optional `sort`, optional `position`, optional
811/// `anchor`, optional `anchorOffset`, optional `limit`, optional
812/// `calculateTotal`); the returned `Value` is the §5.5 `/query`
813/// response shape (`accountId`, `queryState`, `canCalculateChanges`,
814/// `position`, `ids`, optional `total`).
815///
816/// `using` is the request's capability list (pass
817/// [`jmap_server::CallContext::using`]); without
818/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-04 §3.6
819/// filter condition is `unsupportedFilter` (-04 §3).
820///
821/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
822pub async fn handle_task_query<B: TasksBackend>(
823    backend: &B,
824    caller: &B::CallerCtx,
825    args: Value,
826    using: &[String],
827) -> Result<HandlerOutput, JmapError> {
828    jmap_server::reject_metadata_filter_arg(
829        &args,
830        jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
831        using,
832    )?;
833    reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
834    jmap_server::handle_query::<Task, B>(backend, caller, args).await
835}
836
837// ---------------------------------------------------------------------------
838// Task/queryChanges
839// ---------------------------------------------------------------------------
840
841/// Handle a `Task/queryChanges` method call (draft-tasks-06 §4.14).
842///
843/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
844/// optional `filter`, optional `sort`, `sinceQueryState`, optional
845/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
846/// returned `Value` is the §5.6 `/queryChanges` response shape
847/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
848/// `removed`, `added`).
849///
850/// `using` is the request's capability list (pass
851/// [`jmap_server::CallContext::using`]); without
852/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-04 §3.6
853/// filter condition is `unsupportedFilter` (-04 §3).
854///
855/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
856pub async fn handle_task_query_changes<B: TasksBackend>(
857    backend: &B,
858    caller: &B::CallerCtx,
859    args: Value,
860    using: &[String],
861) -> Result<HandlerOutput, JmapError> {
862    jmap_server::reject_metadata_filter_arg(
863        &args,
864        jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
865        using,
866    )?;
867    reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
868    jmap_server::handle_query_changes::<Task, B>(backend, caller, args).await
869}
870
871// ---------------------------------------------------------------------------
872// Tests
873// ---------------------------------------------------------------------------
874
875#[cfg(test)]
876mod tests {
877    use super::*;
878    use serde_json::json;
879
880    use crate::test_support::MockBackend;
881
882    /// Oracle: RFC 8620 §5.5 `unsupportedSort`: "The sort is syntactically
883    /// valid, but includes a property the server does not support sorting
884    /// on". draft-ietf-jmap-tasks-06 §4.13 defers to CalendarEvent/query, whose sort
885    /// properties are start, uid, recurrenceId, created and updated; `title` is not among them.
886    #[tokio::test]
887    async fn query_unlisted_sort_property_returns_unsupported_sort() {
888        let backend = MockBackend::new_with_account("acc1");
889        let args = json!({ "accountId": "acc1", "sort": [{ "property": "title" }] });
890        let err = handle_task_query(&backend, &(), args, &[])
891            .await
892            .expect_err("unlisted sort property must be rejected");
893        assert_eq!(err.error_type.to_string(), "unsupportedSort");
894    }
895
896    /// Oracle: as above; `Task/queryChanges` carries the same `sort`
897    /// (RFC 8620 §5.6).
898    #[tokio::test]
899    async fn query_changes_unlisted_sort_property_returns_unsupported_sort() {
900        let backend = MockBackend::new_with_account("acc1");
901        let args = json!({
902            "accountId": "acc1",
903            "sinceQueryState": "0",
904            "sort": [{ "property": "start" }, { "property": "title" }]
905        });
906        let err = handle_task_query_changes(&backend, &(), args, &[])
907            .await
908            .expect_err("unlisted sort property must be rejected");
909        assert_eq!(err.error_type.to_string(), "unsupportedSort");
910    }
911
912    /// Oracle: draft-ietf-jmap-tasks-06 §4.13 defers to CalendarEvent/query, whose sort
913    /// properties are start, uid, recurrenceId, created and updated, so a `start` sort is accepted.
914    #[tokio::test]
915    async fn query_listed_sort_property_is_accepted() {
916        let backend = MockBackend::new_with_account("acc1");
917        let args = json!({ "accountId": "acc1", "sort": [{ "property": "start" }] });
918        handle_task_query(&backend, &(), args, &[])
919            .await
920            .expect("listed sort property must not be rejected");
921    }
922
923    /// Oracle: Task/get with unknown accountId returns accountNotFound.
924    #[tokio::test]
925    async fn get_unknown_account_returns_account_not_found() {
926        let backend = MockBackend::new();
927        let args = json!({ "accountId": "unknown", "ids": null });
928        let result = handle_task_get(&backend, &(), args, &[]).await;
929        let err = result.expect_err("must return error for unknown account");
930        assert_eq!(err.error_type.to_string(), "accountNotFound");
931    }
932
933    /// Oracle: Task/copy missing fromAccountId returns invalidArguments.
934    #[tokio::test]
935    async fn copy_missing_from_account_id_returns_invalid_arguments() {
936        let backend = MockBackend::new_with_account("acc1");
937        let args = json!({
938            "accountId": "acc1",
939            "create": {}
940        });
941        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
942        let err = result.expect_err("must return error when fromAccountId missing");
943        assert_eq!(err.error_type.to_string(), "invalidArguments");
944    }
945
946    /// Oracle: RFC 8620 §5.4 — fromAccountId MUST be different from accountId.
947    /// A same-account request must be rejected with invalidArguments before
948    /// any per-create work. Matches the canonical sibling jmap-mail-server
949    /// at email.rs:2263-2268.
950    #[tokio::test]
951    async fn copy_same_account_returns_invalid_arguments() {
952        let backend = MockBackend::new_with_account("acc1");
953        let args = json!({
954            "accountId": "acc1",
955            "fromAccountId": "acc1",
956            "create": {}
957        });
958        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
959        let err = result.expect_err("must reject same-account Task/copy per RFC 8620 §5.4");
960        assert_eq!(err.error_type.to_string(), "invalidArguments");
961    }
962
963    /// Oracle: RFC 8620 §5.4 — `fromAccountId` that does not resolve to a
964    /// real account returns the spec-canonical `fromAccountNotFound` error,
965    /// not the generic `accountNotFound`.
966    #[tokio::test]
967    async fn copy_unknown_from_account_returns_from_account_not_found() {
968        let backend = MockBackend::new_with_account("acc1");
969        let args = json!({
970            "accountId": "acc1",
971            "fromAccountId": "no-such-account",
972            "create": {}
973        });
974        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
975        let err = result.expect_err("must reject unknown fromAccountId");
976        assert_eq!(err.error_type.to_string(), "fromAccountNotFound");
977    }
978
979    /// Oracle: RFC 8620 §5.4 — `ifFromInState` mismatch on the source
980    /// account returns `stateMismatch`.
981    #[tokio::test]
982    async fn copy_if_from_in_state_mismatch_returns_state_mismatch() {
983        let mut backend = MockBackend::new_with_account("acc1");
984        backend.add_account("acc2");
985        let args = json!({
986            "accountId": "acc1",
987            "fromAccountId": "acc2",
988            "ifFromInState": "stale-source-state",
989            "create": {}
990        });
991        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
992        let err = result.expect_err("must reject stale ifFromInState");
993        assert_eq!(err.error_type.to_string(), "stateMismatch");
994    }
995
996    /// Oracle: RFC 8620 §5.4 — `ifInState` mismatch on the destination
997    /// account returns `stateMismatch`.
998    #[tokio::test]
999    async fn copy_if_in_state_mismatch_returns_state_mismatch() {
1000        let mut backend = MockBackend::new_with_account("acc1");
1001        backend.add_account("acc2");
1002        let args = json!({
1003            "accountId": "acc1",
1004            "fromAccountId": "acc2",
1005            "ifInState": "stale-destination-state",
1006            "create": {}
1007        });
1008        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1009        let err = result.expect_err("must reject stale ifInState");
1010        assert_eq!(err.error_type.to_string(), "stateMismatch");
1011    }
1012
1013    /// Oracle: RFC 8620 §5.4 — a create entry without an `id` property must
1014    /// produce a per-entry `invalidProperties` SetError naming `id`. The
1015    /// previous handler silently substituted a "placeholder" id, masking
1016    /// this hard requirement.
1017    #[tokio::test]
1018    async fn copy_create_entry_without_id_returns_invalid_properties() {
1019        let mut backend = MockBackend::new_with_account("acc1");
1020        backend.add_account("acc2");
1021        let args = json!({
1022            "accountId": "acc1",
1023            "fromAccountId": "acc2",
1024            "create": { "c1": {} }
1025        });
1026        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1027            .await
1028            .expect("top-level call must succeed");
1029        let nc = resp["notCreated"].as_object().expect("notCreated present");
1030        let err = nc.get("c1").expect("c1 in notCreated");
1031        assert_eq!(err["type"], "invalidProperties");
1032        assert_eq!(err["properties"][0], "id");
1033    }
1034
1035    /// Oracle: RFC 8620 §5.4 — when the source id does not resolve to a
1036    /// Task in `fromAccountId`, the per-entry result is `notFound`.
1037    #[tokio::test]
1038    async fn copy_unknown_source_id_returns_not_found() {
1039        let mut backend = MockBackend::new_with_account("acc1");
1040        backend.add_account("acc2");
1041        let args = json!({
1042            "accountId": "acc1",
1043            "fromAccountId": "acc2",
1044            "create": { "c1": { "id": "no-such-task" } }
1045        });
1046        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1047            .await
1048            .expect("top-level call must succeed");
1049        let nc = resp["notCreated"].as_object().expect("notCreated present");
1050        assert_eq!(nc["c1"]["type"], "notFound");
1051    }
1052
1053    /// Oracle: RFC 8620 §5.4 — the create entry's `id` selects WHAT to copy;
1054    /// client-supplied properties OTHER than `id` overlay the source values.
1055    /// Verify the handler actually round-trips through the source: seed a
1056    /// Task into `from_account`, request a copy that overrides `title`, and
1057    /// confirm the response carries the override.
1058    #[tokio::test]
1059    async fn copy_fetches_source_and_overlays_client_overrides() {
1060        let mut backend = MockBackend::new_with_account("acc1");
1061        backend.add_account("acc2");
1062        backend.seed_task("acc2", "src1", true); // source task in acc2
1063
1064        let args = json!({
1065            "accountId": "acc1",
1066            "fromAccountId": "acc2",
1067            "create": {
1068                "c1": { "id": "src1", "title": "Overridden title" }
1069            }
1070        });
1071        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1072            .await
1073            .expect("top-level call must succeed");
1074
1075        // Source was fetched and the override applied: the created entry
1076        // carries the new title, not the source value (which had none).
1077        let created = resp["created"].as_object().expect("created present");
1078        let c1 = created.get("c1").expect("c1 in created");
1079        assert_eq!(
1080            c1["title"], "Overridden title",
1081            "client-supplied title must override source value: {resp}"
1082        );
1083    }
1084
1085    /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is true, the
1086    /// server emits a single implicit Task/set call against fromAccountId
1087    /// destroying each successfully copied source. The synthesized response
1088    /// appears in the extra Vec<Invocation> with the same callId as the
1089    /// triggering Task/copy. Mirrors canonical jmap-mail-server
1090    /// email.rs:2432-2575.
1091    #[tokio::test]
1092    async fn copy_on_success_destroy_original_emits_implicit_task_set() {
1093        let mut backend = MockBackend::new_with_account("acc1");
1094        backend.add_account("acc2");
1095        backend.seed_task("acc2", "src1", true);
1096
1097        let args = json!({
1098            "accountId": "acc1",
1099            "fromAccountId": "acc2",
1100            "onSuccessDestroyOriginal": true,
1101            "create": {
1102                "c1": { "id": "src1" }
1103            }
1104        });
1105        let HandlerOutput {
1106            extra_invocations: extra,
1107            ..
1108        } = handle_task_copy(&backend, &(), args, "c0", &[])
1109            .await
1110            .expect("top-level call must succeed");
1111
1112        // Exactly one synthesized invocation: ("Task/set", response, "c0").
1113        assert_eq!(extra.len(), 1, "must emit one implicit Task/set: {extra:?}");
1114        let Invocation {
1115            name: method,
1116            arguments: val,
1117            call_id: ci,
1118        } = &extra[0];
1119        assert_eq!(method, "Task/set");
1120        assert_eq!(ci, "c0");
1121        assert_eq!(val["accountId"], "acc2", "implicit set targets fromAccount");
1122        let destroyed = val["destroyed"]
1123            .as_array()
1124            .expect("destroyed must be array");
1125        assert_eq!(destroyed.len(), 1);
1126        assert_eq!(destroyed[0], "src1");
1127        // Both state fields are present on the synthesized response. Their
1128        // bump semantics depend on the underlying backend's get_state — the
1129        // MockBackend here always returns "0" so we only assert presence;
1130        // state-advance semantics are covered by stateful integration tests.
1131        assert!(val.get("oldState").is_some(), "oldState must be present");
1132        assert!(val.get("newState").is_some(), "newState must be present");
1133    }
1134
1135    /// Oracle: RFC 8620 §5.4 — `destroyFromIfInState` mismatch on the implicit
1136    /// Task/set call yields a `stateMismatch` error response in place of the
1137    /// normal Task/set body. The destroy MUST NOT proceed.
1138    #[tokio::test]
1139    async fn copy_destroy_from_if_in_state_mismatch_aborts_destroy() {
1140        let mut backend = MockBackend::new_with_account("acc1");
1141        backend.add_account("acc2");
1142        backend.seed_task("acc2", "src1", true);
1143
1144        let args = json!({
1145            "accountId": "acc1",
1146            "fromAccountId": "acc2",
1147            "onSuccessDestroyOriginal": true,
1148            "destroyFromIfInState": "stale-source-state",
1149            "create": {
1150                "c1": { "id": "src1" }
1151            }
1152        });
1153        let HandlerOutput {
1154            extra_invocations: extra,
1155            ..
1156        } = handle_task_copy(&backend, &(), args, "c0", &[])
1157            .await
1158            .expect("top-level call must succeed");
1159
1160        assert_eq!(extra.len(), 1);
1161        let Invocation { arguments: val, .. } = &extra[0];
1162        assert_eq!(val["type"], "stateMismatch");
1163    }
1164
1165    /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is false (or
1166    /// absent), no implicit Task/set call is synthesized.
1167    #[tokio::test]
1168    async fn copy_without_on_success_emits_no_extra_invocations() {
1169        let mut backend = MockBackend::new_with_account("acc1");
1170        backend.add_account("acc2");
1171        backend.seed_task("acc2", "src1", true);
1172
1173        let args = json!({
1174            "accountId": "acc1",
1175            "fromAccountId": "acc2",
1176            "create": {
1177                "c1": { "id": "src1" }
1178            }
1179        });
1180        let HandlerOutput {
1181            extra_invocations: extra,
1182            ..
1183        } = handle_task_copy(&backend, &(), args, "c0", &[])
1184            .await
1185            .expect("top-level call must succeed");
1186        assert!(
1187            extra.is_empty(),
1188            "no extra invocations without onSuccessDestroyOriginal: {extra:?}"
1189        );
1190    }
1191
1192    /// Oracle: Task/set empty destroy returns valid response.
1193    #[tokio::test]
1194    async fn set_empty_destroy_returns_valid_response() {
1195        let backend = MockBackend::new_with_account("acc1");
1196        let args = json!({ "accountId": "acc1", "destroy": [] });
1197        let HandlerOutput { primary: resp, .. } =
1198            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1199                .await
1200                .expect("must not return top-level error");
1201        assert_eq!(resp["accountId"], "acc1");
1202    }
1203
1204    // ── isDraft immutability enforcement (draft-tasks-06 §4 (isDraft paragraph)) ─
1205
1206    /// Oracle: draft-tasks-06 §4 — "Once set to false, the value [isDraft]
1207    /// cannot be updated to true."
1208    /// A patch of {"isDraft": true} on a task that already has isDraft=false
1209    /// MUST be rejected with invalidProperties. The handler does no isDraft
1210    /// check, so this exercises the backend rejection reaching `notUpdated`.
1211    #[tokio::test]
1212    async fn set_is_draft_revert_rejected_when_current_is_false() {
1213        let mut backend = MockBackend::new_with_account("acc1");
1214        // Pre-seed a published (isDraft=false) task.
1215        backend.seed_task("acc1", "t1", false);
1216
1217        let args = json!({
1218            "accountId": "acc1",
1219            "update": {
1220                "t1": { "isDraft": true }
1221            }
1222        });
1223        let HandlerOutput { primary: resp, .. } =
1224            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1225                .await
1226                .expect("must not return a top-level error");
1227
1228        let not_updated = resp["notUpdated"]
1229            .as_object()
1230            .expect("notUpdated must be an object");
1231        assert!(
1232            not_updated.contains_key("t1"),
1233            "t1 must appear in notUpdated: {resp}"
1234        );
1235        assert_eq!(
1236            not_updated["t1"]["type"].as_str(),
1237            Some("invalidProperties"),
1238            "error type must be invalidProperties"
1239        );
1240        assert_eq!(
1241            not_updated["t1"]["properties"][0].as_str(),
1242            Some("isDraft"),
1243            "properties must list isDraft"
1244        );
1245    }
1246
1247    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": true} on a task that
1248    /// is already a draft (isDraft=true) is allowed (no state transition).
1249    #[tokio::test]
1250    async fn set_is_draft_true_on_draft_task_passes_to_backend() {
1251        let mut backend = MockBackend::new_with_account("acc1");
1252        // Pre-seed a draft task (isDraft=true).
1253        backend.seed_task("acc1", "t2", true);
1254
1255        let args = json!({
1256            "accountId": "acc1",
1257            "update": {
1258                "t2": { "isDraft": true }
1259            }
1260        });
1261        let HandlerOutput { primary: resp, .. } =
1262            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1263                .await
1264                .expect("must not return a top-level error");
1265
1266        // The handler passes the patch to the backend (which returns Forbidden
1267        // in the mock). The important thing is it is NOT pre-rejected here —
1268        // it must NOT appear in notUpdated with type=="invalidProperties".
1269        if let Some(not_updated) = resp["notUpdated"].as_object()
1270            && let Some(err) = not_updated.get("t2")
1271        {
1272            assert_ne!(
1273                err["type"].as_str(),
1274                Some("invalidProperties"),
1275                "isDraft:true on an existing draft must not produce invalidProperties"
1276            );
1277        }
1278    }
1279
1280    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": false} is always allowed
1281    /// (moving from draft to published is a one-way door going the right way).
1282    #[tokio::test]
1283    async fn set_is_draft_false_passes_to_backend() {
1284        let mut backend = MockBackend::new_with_account("acc1");
1285        backend.seed_task("acc1", "t3", true);
1286
1287        let args = json!({
1288            "accountId": "acc1",
1289            "update": {
1290                "t3": { "isDraft": false }
1291            }
1292        });
1293        let HandlerOutput { primary: resp, .. } =
1294            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1295                .await
1296                .expect("must not return a top-level error");
1297
1298        // Like above: the patch must NOT be pre-rejected with invalidProperties.
1299        if let Some(not_updated) = resp["notUpdated"].as_object()
1300            && let Some(err) = not_updated.get("t3")
1301        {
1302            assert_ne!(
1303                err["type"].as_str(),
1304                Some("invalidProperties"),
1305                "isDraft:false must never produce invalidProperties"
1306            );
1307        }
1308    }
1309
1310    // ── compute_utc_times / utcStart wiring (draft-tasks-06 §4 (utcStart/utcDue paragraphs)) ─
1311
1312    /// Oracle: draft-tasks-06 §4 — utcStart is not returned unless explicitly
1313    /// requested in `properties`.  The default impl returns None so it must be
1314    /// absent from the response when not requested.
1315    #[tokio::test]
1316    async fn get_without_utc_properties_omits_utc_fields() {
1317        let backend = MockBackend::new_with_account("acc1");
1318        let args = json!({
1319            "accountId": "acc1",
1320            "ids": null,
1321            "properties": ["id", "title"]  // utcStart and utcDue NOT listed
1322        });
1323        let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
1324            .await
1325            .expect("must succeed");
1326        // The list is empty (no tasks seeded), but the response itself must be valid.
1327        assert_eq!(resp["accountId"], "acc1");
1328        // No utcStart or utcDue should appear in response items (list is empty so
1329        // this is vacuously satisfied, but the path is exercised without error).
1330        let list = resp["list"].as_array().expect("list must be an array");
1331        for item in list {
1332            assert!(
1333                item.get("utcStart").is_none(),
1334                "utcStart must not appear when not in properties"
1335            );
1336        }
1337    }
1338
1339    /// Oracle: draft-tasks-06 §4 — when utcStart is in properties, the handler
1340    /// calls compute_utc_times. The default impl returns (None, None) so
1341    /// no utcStart key is injected, but no error is raised either.
1342    #[tokio::test]
1343    async fn get_with_utc_start_in_properties_does_not_error() {
1344        let backend = MockBackend::new_with_account("acc1");
1345        let args = json!({
1346            "accountId": "acc1",
1347            "ids": null,
1348            "properties": ["id", "utcStart", "utcDue"]
1349        });
1350        let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
1351            .await
1352            .expect("must succeed with utcStart in properties");
1353        assert_eq!(resp["accountId"], "acc1");
1354    }
1355
1356    // ── per-user property routing (draft-tasks-06 §4.5.1) ──────────────────
1357    //
1358    // Routing is observable via MockBackend::per_user_calls — a counter that
1359    // increments inside `update_task_per_user` and stays at 0 for paths that
1360    // go to `update_object`. The earlier shape of these tests only asserted
1361    // that no `invalidProperties` error came back, which would pass even if
1362    // routing were inverted; tightened here to inspect the counter directly.
1363
1364    /// Oracle: draft-tasks-06 §4.5.1 — a patch with only per-user properties
1365    /// (bare keys, no JSON Pointer sub-paths) must route to update_task_per_user.
1366    #[tokio::test]
1367    async fn set_per_user_only_patch_routes_to_per_user_update() {
1368        use std::sync::atomic::Ordering;
1369        let backend = MockBackend::new_with_account("acc1");
1370        // color is a per-user property (§4.5.1).
1371        let args = json!({
1372            "accountId": "acc1",
1373            "update": { "t1": { "color": "#ff0000" } }
1374        });
1375        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1376            .await
1377            .expect("must not return top-level error");
1378        assert_eq!(
1379            backend.per_user_calls.load(Ordering::Relaxed),
1380            1,
1381            "per-user-only patch must route to update_task_per_user"
1382        );
1383    }
1384
1385    /// Oracle: draft-tasks-06 §4.5.1 + RFC 8620 §5.3 — JSON-pointer patches on
1386    /// per-user properties (e.g. `keywords/done: true` to toggle a single
1387    /// keyword, `alerts/0/offset: null` to clear an alert sub-field) must still
1388    /// route to update_task_per_user. The first pointer segment is the
1389    /// property name; the implementation MUST classify on that segment, not
1390    /// on the whole key.
1391    #[tokio::test]
1392    async fn set_per_user_json_pointer_patch_routes_to_per_user_update() {
1393        use std::sync::atomic::Ordering;
1394        let backend = MockBackend::new_with_account("acc1");
1395        let args = json!({
1396            "accountId": "acc1",
1397            "update": {
1398                "t1": {
1399                    "keywords/done": true,
1400                    "alerts/0/offset": null
1401                }
1402            }
1403        });
1404        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1405            .await
1406            .expect("must not return top-level error");
1407        assert_eq!(
1408            backend.per_user_calls.load(Ordering::Relaxed),
1409            1,
1410            "JSON-pointer patch on per-user properties must route to update_task_per_user"
1411        );
1412    }
1413
1414    /// Oracle: draft-tasks-06 §4.5.1 — a patch on a shared property (title)
1415    /// must route to update_object.
1416    #[tokio::test]
1417    async fn set_shared_property_patch_routes_to_update_object() {
1418        use std::sync::atomic::Ordering;
1419        let backend = MockBackend::new_with_account("acc1");
1420        let args = json!({
1421            "accountId": "acc1",
1422            "update": { "t1": { "title": "New title" } }
1423        });
1424        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1425            .await
1426            .expect("must not return top-level error");
1427        assert_eq!(
1428            backend.per_user_calls.load(Ordering::Relaxed),
1429            0,
1430            "shared-property patch must NOT route to update_task_per_user"
1431        );
1432    }
1433
1434    /// Oracle: RFC 7396 / RFC 8620 §5.3 — `{"title": null}` is a delete-shared-
1435    /// property mutation, NOT a per-user mutation. The previous routing
1436    /// short-circuited on null values, misclassifying this as per-user-only.
1437    #[tokio::test]
1438    async fn set_shared_property_null_patch_routes_to_update_object() {
1439        use std::sync::atomic::Ordering;
1440        let backend = MockBackend::new_with_account("acc1");
1441        let args = json!({
1442            "accountId": "acc1",
1443            "update": { "t1": { "title": null } }
1444        });
1445        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1446            .await
1447            .expect("must not return top-level error");
1448        assert_eq!(
1449            backend.per_user_calls.load(Ordering::Relaxed),
1450            0,
1451            "delete-shared-property patch must NOT route to update_task_per_user"
1452        );
1453    }
1454
1455    /// Oracle: draft-tasks-06 §4.5.1 — a mixed patch (per-user + shared)
1456    /// routes to update_object, never update_task_per_user.
1457    #[tokio::test]
1458    async fn set_mixed_patch_routes_to_update_object() {
1459        use std::sync::atomic::Ordering;
1460        let backend = MockBackend::new_with_account("acc1");
1461        let args = json!({
1462            "accountId": "acc1",
1463            "update": { "t1": { "color": "#ff0000", "title": "New" } }
1464        });
1465        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1466            .await
1467            .expect("must not return top-level error");
1468        assert_eq!(
1469            backend.per_user_calls.load(Ordering::Relaxed),
1470            0,
1471            "mixed patch must route to update_object"
1472        );
1473    }
1474
1475    /// Oracle: RFC 8620 §5.3 — an empty PatchObject is a no-op, not a per-user
1476    /// mutation. The previous routing classified it as per-user-only via
1477    /// vacuous-truth on `iter().all`.
1478    #[tokio::test]
1479    async fn set_empty_patch_routes_to_update_object() {
1480        use std::sync::atomic::Ordering;
1481        let backend = MockBackend::new_with_account("acc1");
1482        let args = json!({
1483            "accountId": "acc1",
1484            "update": { "t1": {} }
1485        });
1486        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1487            .await
1488            .expect("must not return top-level error");
1489        assert_eq!(
1490            backend.per_user_calls.load(Ordering::Relaxed),
1491            0,
1492            "empty patch must NOT route to update_task_per_user"
1493        );
1494    }
1495
1496    /// RFC 8620 §5.3 types `destroy` as "Id[]|null", so an object element
1497    /// is "invalidArguments: One of the arguments is of the wrong type"
1498    /// (§3.6.2). The description names only the JSON type: §3.6.1 reserves
1499    /// it for "unstructured English text suitable for displaying to a
1500    /// developer", so the client-supplied value is never echoed
1501    /// (bd JMAP-zegc).
1502    #[tokio::test]
1503    async fn set_non_string_destroy_element_does_not_echo_value() {
1504        let backend = MockBackend::new_with_account("acc");
1505        let args = json!({ "accountId": "acc", "destroy": [{ "note": "CANARY-zegc" }] });
1506        let err = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1507            .await
1508            .expect_err("non-string destroy element must be a method error");
1509        assert_eq!(err.error_type.to_string(), "invalidArguments");
1510        let desc = err.description.as_deref().unwrap_or_default();
1511        assert!(desc.contains("got object"), "{desc}");
1512        assert!(!desc.contains("CANARY"), "{desc}");
1513    }
1514}