Skip to main content

tilo_actions/
draft.rs

1//! Every invocation as a draft a person can read, change and confirm.
2//!
3//! Where a delegate's action asks first, the person is shown exactly what
4//! will happen before it does. [`Draft::render`] derives that from the
5//! action's inert descriptor and the arguments it would run with, so every
6//! application's actions are draftable without code of their own: a field
7//! per parameter (an object parameter's fields one level down), resource
8//! references and attachments by label, secrets withheld. An action that
9//! wants a richer preview names its layout with a contract tag
10//! ([`MESSAGE_PREVIEW_TAG`]); a parameter shaped like a message (recipients
11//! and a body) is previewed as one without it.
12//!
13//! What the person confirms is bound to the exact arguments
14//! ([`arguments_digest`]): changing a field ([`Draft::apply_edits`]) makes
15//! new arguments, and those are what run.
16
17use serde::{Deserialize, Serialize};
18use serde_json::{Map, Value};
19
20use crate::{ActionDescriptor, ParamType};
21
22/// The error code an invocation is answered with while the person it is
23/// made for has not yet confirmed it. The caller waits and asks again with
24/// the same arguments; nothing has run.
25pub const AWAITING_CONFIRMATION: &str = "action_awaiting_confirmation";
26
27/// The error code an invocation an agent makes inside a turn is answered with
28/// while the message that caused it has not reached this device: the caller
29/// waits and asks again once it has; nothing has run.
30pub const AWAITING_CAUSE: &str = "action_awaiting_cause";
31
32/// The error code an invocation is answered with when the person declined
33/// it. What follows the code is the reason they gave, if any.
34pub const DECLINED: &str = "action_declined";
35
36/// Contract tag of an action whose draft is previewed as a message: who it
37/// goes to, its subject, its body and what it carries.
38pub const MESSAGE_PREVIEW_TAG: &str = "draft:message";
39
40/// Longest text a draft keeps for one field; a longer value is shown cut
41/// and cannot be edited in place.
42pub const MAX_FIELD_CHARS: usize = 64 * 1024;
43
44/// Longest value a [`Draft::summary`] line shows before it is cut.
45pub const SUMMARY_CHARS: usize = 48;
46
47/// Most entries a list field names before saying how many more there are.
48const MAX_LISTED: usize = 12;
49
50/// How a draft is laid out.
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum DraftLayout {
54    /// One labelled field per parameter.
55    #[default]
56    Fields,
57    /// A message: recipients, subject, body and attachments.
58    Message,
59}
60
61/// The role a field plays in a [`DraftLayout::Message`].
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum MessageRole {
65    To,
66    Cc,
67    Bcc,
68    Subject,
69    Body,
70    Attachments,
71}
72
73impl MessageRole {
74    fn of(name: &str) -> Option<Self> {
75        Some(match name {
76            "to" | "recipients" => Self::To,
77            "cc" => Self::Cc,
78            "bcc" => Self::Bcc,
79            "subject" | "title" => Self::Subject,
80            "body" | "text" | "message" => Self::Body,
81            "attachments" | "files" => Self::Attachments,
82            _ => return None,
83        })
84    }
85}
86
87/// What one field holds.
88#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(remote = "Self", rename_all = "snake_case")]
90pub enum DraftValue {
91    Text {
92        text: String,
93    },
94    Number {
95        text: String,
96    },
97    Flag {
98        on: bool,
99    },
100    /// Several entries, each by its label: `3 attachments: a.pdf, b.md, c.png`.
101    List {
102        count: usize,
103        labels: Vec<String>,
104    },
105    /// Another resource, by its label.
106    Resource {
107        label: String,
108    },
109    /// A secret: shown as withheld, never copied into the draft.
110    Withheld,
111}
112
113crate::tagged_through_json_value!(DraftValue, "type");
114
115impl DraftValue {
116    /// The value in one line, as a person reads it (a list's labels joined,
117    /// a flag as `yes`/`no`). Interfaces with their own wording for counts
118    /// and flags build the line themselves.
119    #[must_use]
120    pub fn line(&self) -> String {
121        match self {
122            Self::Text { text } | Self::Number { text } => text.clone(),
123            Self::Flag { on } => if *on { "yes" } else { "no" }.to_owned(),
124            Self::List { count, labels } => {
125                let line = labels.join(", ");
126                match count.checked_sub(labels.len()) {
127                    Some(more) if more > 0 => format!("{line} +{more}"),
128                    _ => line,
129                }
130            }
131            Self::Resource { label } => label.clone(),
132            Self::Withheld => "•••".to_owned(),
133        }
134    }
135}
136
137#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
138pub struct DraftField {
139    /// Where the value sits in the arguments: the parameter, then the
140    /// field of an object parameter.
141    pub path: Vec<String>,
142    pub label: String,
143    pub value: DraftValue,
144    /// Whether a person may change it before confirming.
145    #[serde(default)]
146    pub editable: bool,
147    /// Whether it is prose that wants several lines.
148    #[serde(default)]
149    pub multiline: bool,
150    /// What the row reads instead of the raw value, where the value names one
151    /// of its parameter's choices: a field id reads as the field's name
152    /// ("Body"), a pick as the thing it picks. What runs is still `value`.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub shows: Option<String>,
155    /// Its part in a message preview.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub role: Option<MessageRole>,
158}
159
160/// An invocation as a person reviews it.
161#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
162pub struct Draft {
163    pub action_label: String,
164    pub resource_label: String,
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub description: Option<String>,
167    #[serde(default)]
168    pub layout: DraftLayout,
169    pub fields: Vec<DraftField>,
170    /// Whether the action, once taken, can be undone
171    /// ([`ActionContract::can_be_undone`](crate::ActionContract::can_be_undone)):
172    /// a reviewer is told whether it sends something away or changes their
173    /// own work.
174    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
175    pub undoable: bool,
176}
177
178/// One change a person made to a draft's field.
179#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
180pub struct DraftEdit {
181    pub path: Vec<String>,
182    pub text: String,
183}
184
185impl Draft {
186    #[must_use]
187    pub fn render(descriptor: &ActionDescriptor, arguments: &Map<String, Value>) -> Self {
188        let mut fields = Vec::new();
189        for param in &descriptor.params {
190            let Some(value) = arguments.get(param.name.as_ref()) else {
191                continue;
192            };
193            let path = vec![param.name.to_string()];
194            match (param.ty, value) {
195                (ParamType::Secret, _) => {
196                    fields.push(field(path, &param.name, DraftValue::Withheld));
197                }
198                // A secret named by reference reads as a secret does: the
199                // address of a vault item tells a reviewer nothing.
200                (ParamType::Resource, _) if crate::remote::takes_item(param) => {
201                    fields.push(field(path, &param.name, DraftValue::Withheld));
202                }
203                (ParamType::Object, Value::Object(object)) => {
204                    let properties = param
205                        .schema
206                        .as_deref()
207                        .and_then(|schema| schema.get("properties"))
208                        .and_then(Value::as_object);
209                    for (name, inner) in object {
210                        let schema = properties.and_then(|properties| properties.get(name));
211                        let mut path = path.clone();
212                        path.push(name.clone());
213                        if let Some(field) = value_field(path, name, inner, schema) {
214                            fields.push(field);
215                        }
216                    }
217                }
218                (ty, value) => {
219                    let schema = param.schema.as_deref();
220                    let mut made = value_field(path, &param.name, value, schema);
221                    if let Some(made) = made.as_mut()
222                        && ty == ParamType::Resource
223                    {
224                        made.value = DraftValue::Resource {
225                            label: made.value.line(),
226                        };
227                        made.editable = false;
228                    }
229                    // A value that names one of the parameter's choices reads by
230                    // the label the surface publishes for it: a field id reads as
231                    // the field's name, a pick as the thing it picks. `value`
232                    // stays the value the action binds, so what runs is
233                    // unchanged; only what the person reads changes.
234                    if let (Some(made), Some(raw)) = (made.as_mut(), value.as_str())
235                        && !raw.is_empty()
236                        && let Some(label) = param.choice_label(raw)
237                        && !label.trim().is_empty()
238                    {
239                        made.shows = Some(label.to_owned());
240                    }
241                    fields.extend(made);
242                }
243            }
244        }
245        let message = descriptor
246            .contract
247            .tags
248            .iter()
249            .any(|tag| tag == MESSAGE_PREVIEW_TAG)
250            || (fields
251                .iter()
252                .any(|field| field.role == Some(MessageRole::To))
253                && fields
254                    .iter()
255                    .any(|field| field.role == Some(MessageRole::Body)));
256        if !message {
257            for field in &mut fields {
258                field.role = None;
259            }
260        }
261        Self {
262            action_label: descriptor.action_label.clone(),
263            resource_label: descriptor.resource_label.clone(),
264            description: descriptor.description.clone(),
265            layout: if message {
266                DraftLayout::Message
267            } else {
268                DraftLayout::Fields
269            },
270            fields,
271            undoable: descriptor.contract.can_be_undone(),
272        }
273    }
274
275    #[must_use]
276    pub fn role(&self, role: MessageRole) -> Option<&DraftField> {
277        self.fields.iter().find(|field| field.role == Some(role))
278    }
279
280    /// What a person reads in `field`'s one line: the label it shows where
281    /// the value names a choice, its value otherwise.
282    #[must_use]
283    pub fn shown_line(field: &DraftField) -> String {
284        field.shows.clone().unwrap_or_else(|| field.value.line())
285    }
286
287    /// What the draft is about, in one line of its own values: a message's
288    /// recipients and subject, otherwise its first short values. `None` for a
289    /// draft with nothing to show.
290    #[must_use]
291    pub fn gist(&self) -> Option<String> {
292        if self.layout == DraftLayout::Message {
293            let parts: Vec<String> = [MessageRole::To, MessageRole::Subject]
294                .into_iter()
295                .filter_map(|role| self.role(role))
296                .map(Draft::shown_line)
297                .filter(|line| !line.is_empty())
298                .collect();
299            if !parts.is_empty() {
300                return Some(parts.join(" · "));
301            }
302        }
303        let parts: Vec<String> = self
304            .fields
305            .iter()
306            .filter(|field| !field.multiline && field.value != DraftValue::Withheld)
307            .map(Draft::shown_line)
308            .filter(|line| !line.is_empty())
309            .take(2)
310            .collect();
311        (!parts.is_empty()).then(|| parts.join(" · "))
312    }
313
314    /// Each field as one line a reviewer reads at a glance, by its label:
315    /// a long value cut at [`SUMMARY_CHARS`] with an ellipsis, a secret
316    /// withheld.
317    #[must_use]
318    pub fn summary(&self) -> Vec<(String, String)> {
319        self.fields
320            .iter()
321            .map(|field| {
322                let line = field
323                    .value
324                    .line()
325                    .split_whitespace()
326                    .collect::<Vec<_>>()
327                    .join(" ");
328                let cut = if line.chars().count() > SUMMARY_CHARS {
329                    let kept: String = line.chars().take(SUMMARY_CHARS).collect();
330                    format!("{}…", kept.trim_end())
331                } else {
332                    line
333                };
334                (field.label.clone(), cut)
335            })
336            .collect()
337    }
338
339    /// `arguments` with the person's `edits` applied. Only fields this draft
340    /// offers for editing change, each keeping its JSON type.
341    pub fn apply_edits(
342        &self,
343        arguments: &Map<String, Value>,
344        edits: &[DraftEdit],
345    ) -> Result<Map<String, Value>, String> {
346        let mut edited = arguments.clone();
347        for edit in edits {
348            set_path(&mut edited, &edit.path, self.edit_value(edit)?)?;
349        }
350        Ok(edited)
351    }
352
353    /// Whether every one of `edits` changes a field this draft offers for
354    /// editing to a value of its type.
355    pub fn check_edits(&self, edits: &[DraftEdit]) -> Result<(), String> {
356        edits
357            .iter()
358            .try_for_each(|edit| self.edit_value(edit).map(drop))
359    }
360
361    fn edit_value(&self, edit: &DraftEdit) -> Result<Value, String> {
362        let field = self
363            .fields
364            .iter()
365            .find(|field| field.path == edit.path && field.editable)
366            .ok_or_else(|| format!("{} cannot be changed here", edit.path.join(".")))?;
367        if edit.text.chars().count() > MAX_FIELD_CHARS {
368            return Err(format!("{} is too long", field.label));
369        }
370        Ok(match &field.value {
371            DraftValue::Text { .. } => Value::String(edit.text.clone()),
372            DraftValue::Number { .. } => {
373                let number: serde_json::Number = edit
374                    .text
375                    .trim()
376                    .parse()
377                    .map_err(|_| format!("{} needs a number", field.label))?;
378                Value::Number(number)
379            }
380            DraftValue::Flag { .. } => match edit.text.trim() {
381                "true" | "yes" => Value::Bool(true),
382                "false" | "no" => Value::Bool(false),
383                _ => return Err(format!("{} needs yes or no", field.label)),
384            },
385            _ => return Err(format!("{} cannot be changed here", field.label)),
386        })
387    }
388
389    /// The arguments this draft shows: each text, number and flag field set
390    /// at its path. `None` when a field shows its value only in part (a
391    /// secret, a list, a resource, a text cut short). A draft also leaves
392    /// out nulls and empty texts, so what this returns is only a candidate:
393    /// act on it only when it digests ([`arguments_digest`]) to the digest
394    /// the draft was confirmed for.
395    #[must_use]
396    pub fn arguments(&self) -> Option<Map<String, Value>> {
397        let mut arguments = Map::new();
398        for field in &self.fields {
399            let value = match &field.value {
400                DraftValue::Text { text } => Value::String(text.clone()),
401                DraftValue::Number { text } => Value::Number(text.parse().ok()?),
402                DraftValue::Flag { on } => Value::Bool(*on),
403                DraftValue::List { .. } | DraftValue::Resource { .. } | DraftValue::Withheld => {
404                    return None;
405                }
406            };
407            let (last, parents) = field.path.split_last()?;
408            let mut object = &mut arguments;
409            for parent in parents {
410                object = object
411                    .entry(parent.clone())
412                    .or_insert_with(|| Value::Object(Map::new()))
413                    .as_object_mut()?;
414            }
415            object.insert(last.clone(), value);
416        }
417        Some(arguments)
418    }
419
420    /// The draft as `edits` change it: what the person confirmed, shown
421    /// back to them. Edits this draft does not offer are left out.
422    #[must_use]
423    pub fn edited(&self, edits: &[DraftEdit]) -> Self {
424        let mut draft = self.clone();
425        for edit in edits {
426            let Ok(value) = self.edit_value(edit) else {
427                continue;
428            };
429            if let Some(field) = draft
430                .fields
431                .iter_mut()
432                .find(|field| field.path == edit.path)
433            {
434                field.value = match value {
435                    Value::Bool(on) => DraftValue::Flag { on },
436                    Value::Number(number) => DraftValue::Number {
437                        text: number.to_string(),
438                    },
439                    _ => DraftValue::Text {
440                        text: edit.text.clone(),
441                    },
442                };
443                // The person typed a new value: no label of a choice stands
444                // over what they wrote.
445                field.shows = None;
446            }
447        }
448        draft
449    }
450}
451
452/// The digest binding a confirmation to the exact arguments it was given
453/// for. Keys are ordered, so the same arguments always digest the same.
454#[must_use]
455pub fn arguments_digest(arguments: &Map<String, Value>) -> [u8; 32] {
456    let mut hasher = blake3::Hasher::new_derive_key("Tilo draft arguments v1");
457    tilo_canonical_json::write_object_bytes(arguments, |chunk| {
458        hasher.update(chunk);
459    });
460    *hasher.finalize().as_bytes()
461}
462
463fn set_path(
464    arguments: &mut Map<String, Value>,
465    path: &[String],
466    value: Value,
467) -> Result<(), String> {
468    let Some((last, parents)) = path.split_last() else {
469        return Err("an edit names no field".into());
470    };
471    let mut object = arguments;
472    for parent in parents {
473        object = object
474            .get_mut(parent)
475            .and_then(Value::as_object_mut)
476            .ok_or_else(|| format!("{} is not in the draft", path.join(".")))?;
477    }
478    object.insert(last.clone(), value);
479    Ok(())
480}
481
482fn field(path: Vec<String>, name: &str, value: DraftValue) -> DraftField {
483    let role = path.last().and_then(|last| MessageRole::of(last));
484    DraftField {
485        path,
486        label: humanize(name),
487        value,
488        editable: false,
489        multiline: false,
490        shows: None,
491        role,
492    }
493}
494
495/// The field for one value; `None` for nothing worth showing (null, an
496/// empty text or list).
497fn value_field(
498    path: Vec<String>,
499    name: &str,
500    value: &Value,
501    schema: Option<&Value>,
502) -> Option<DraftField> {
503    let label = schema
504        .and_then(|schema| schema.get("title"))
505        .and_then(Value::as_str)
506        .map_or_else(|| humanize(name), str::to_owned);
507    let mut made = field(path, name, DraftValue::Withheld);
508    made.label = label;
509    if schema
510        .and_then(|schema| schema.get("format"))
511        .is_some_and(|format| format == "password")
512    {
513        return Some(made);
514    }
515    match value {
516        Value::Null => return None,
517        Value::String(text) if text.trim().is_empty() => return None,
518        Value::String(text) => {
519            let long = text.chars().count() > MAX_FIELD_CHARS;
520            let shown: String = text.chars().take(MAX_FIELD_CHARS).collect();
521            made.multiline = text.contains('\n')
522                || text.chars().count() > 120
523                || made.role == Some(MessageRole::Body);
524            made.editable = !long;
525            made.value = DraftValue::Text { text: shown };
526        }
527        Value::Number(number) => {
528            made.editable = true;
529            made.value = DraftValue::Number {
530                text: number.to_string(),
531            };
532        }
533        Value::Bool(on) => {
534            made.editable = true;
535            made.value = DraftValue::Flag { on: *on };
536        }
537        Value::Array(items) if items.is_empty() => return None,
538        Value::Array(items) => {
539            made.value = DraftValue::List {
540                count: items.len(),
541                labels: items.iter().take(MAX_LISTED).map(entry_label).collect(),
542            };
543        }
544        Value::Object(object) => {
545            made.value = DraftValue::Resource {
546                label: object_label(object).unwrap_or_else(|| humanize(name)),
547            };
548        }
549    }
550    Some(made)
551}
552
553/// The keys an entry or referenced resource is named by, best first.
554const LABEL_KEYS: [&str; 8] = [
555    "label",
556    "name",
557    "title",
558    "filename",
559    "file_name",
560    "path",
561    "address",
562    "id",
563];
564
565fn object_label(object: &Map<String, Value>) -> Option<String> {
566    LABEL_KEYS.iter().find_map(|key| {
567        let text = object.get(*key)?.as_str()?;
568        let text = if *key == "path" {
569            text.rsplit('/').next().unwrap_or(text)
570        } else {
571            text
572        };
573        (!text.is_empty()).then(|| text.to_owned())
574    })
575}
576
577fn entry_label(value: &Value) -> String {
578    match value {
579        Value::String(text) => text.rsplit('/').next().unwrap_or(text).to_owned(),
580        Value::Object(object) => object_label(object).unwrap_or_else(|| "…".to_owned()),
581        other => other.to_string(),
582    }
583}
584
585/// `in_reply_to` as `In reply to`.
586fn humanize(name: &str) -> String {
587    let spaced = name.replace(['_', '-'], " ");
588    let mut chars = spaced.trim().chars();
589    chars.next().map_or_else(String::new, |first| {
590        first.to_uppercase().chain(chars).collect()
591    })
592}
593
594#[cfg(test)]
595#[path = "draft_tests.rs"]
596mod tests;