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