Skip to main content

tilo_actions/remote/
asked.rs

1//! What a call that waits for a person's yes says about itself, and how the
2//! questions that wait for a person are listed.
3//!
4//! A call the caller's grants leave to a person is refused by its provider
5//! with [`super::ActionCallError::ConfirmationRequired`], carrying
6//! [`AskedFacts`]: what the person is shown. The dispatch keeps the call as
7//! its own `tilo.invocations` record in status asked, readable by the caller
8//! and the person asked, and that record is the question: there is no store
9//! of asks beside it. The person answers it with the record's `resolve`
10//! action; on approve the dispatch admits the same call again, bound to that
11//! record, and a provider reads that it was approved
12//! ([`super::InvokeRequest::approval`]).
13//!
14//! The reading of a workspace's invocations carries each asked record a person may answer as
15//! an [`Asked`] row.
16//!
17//! The person answers with `<record>#`[`RESOLVE`] ([`Resolve`]), which tilo-remote-actions'
18//! `AskedStore` admits: only the person the record asks, only while it is asked, and at most once. An approve hands
19//! the call back to the dispatch that keeps it ([`AskedDispatch`]), which admits it again under
20//! its id for its original caller, checking that caller's grants as they stand then.
21
22use serde::{Deserialize, Serialize};
23use zeroize::Zeroizing;
24
25use super::RemoteActionTarget;
26
27/// What a frame carrying an approve no resolve handed back is refused with
28/// ([`ApprovalsHanded::admits_approval`]).
29pub const FORGED: &str = "This call carries an approve its person did not give";
30
31/// Where the approves a person gave are kept: the asked records a host keeps
32/// (tilo-remote-actions' `AskedStore`), which hand an approved call back to its dispatch.
33pub trait ApprovalsHanded: Send + Sync {
34    /// Whether `request`, arriving as a frame from outside a dispatch, may carry the person's
35    /// approve it carries: only the call a resolve of its record approved and handed back,
36    /// byte for byte the same, under the same id, and once. A frame that carries an approve
37    /// this does not admit is refused whole, never run without it: a caller cannot approve
38    /// its own call. A frame that carries none is admitted as it is.
39    fn admits_approval(&self, request: &super::InvokeRequest) -> bool;
40}
41
42/// Admit `request`, a caller's frame, as its approve stands: refused where it carries an
43/// approve `store` did not hand back ([`ApprovalsHanded::admits_approval`]), or any approve
44/// where no store keeps asked records here.
45///
46/// # Errors
47/// [`FORGED`], refused.
48pub fn admit_frame(
49    store: Option<&dyn ApprovalsHanded>,
50    request: &super::InvokeRequest,
51) -> Result<(), super::ActionCallError> {
52    if request.approval().is_none() || store.is_some_and(|store| store.admits_approval(request)) {
53        Ok(())
54    } else {
55        Err(super::ActionCallError::Refused {
56            reason: FORGED.to_owned(),
57        })
58    }
59}
60
61/// What a resolve from anything but the system's own confirmation is refused with: the
62/// person's shell asks them, and the CLI asks them at its own prompt.
63pub const CONFIRMED_BY_THE_SYSTEM: &str =
64    "Only you answer this, where Tilo asks you: on your screen, or at tilo's own prompt";
65
66/// Answer an asked record: `<record>#resolve` with a [`Resolve`], on the
67/// [`super::WORKSPACE_INVOCATIONS_PROVIDER`] provider.
68pub const RESOLVE: &str = "resolve";
69/// What an asked invocation the person declined ends with: cancelled, its message this.
70pub const DECLINED: &str = "declined";
71/// The phase of an invocation's progress while it waits in its asked record: its message
72/// names the record (`<workspace>/<record>`).
73pub const ASKED_PHASE: &str = "asked";
74
75/// One fact the person reads before answering: a label and its value, as a
76/// reviewer reads it, long values cut and secrets withheld.
77#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "camelCase")]
79pub struct Fact {
80    pub label: String,
81    pub value: String,
82}
83
84impl Fact {
85    #[must_use]
86    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
87        Self {
88            label: label.into(),
89            value: value.into(),
90        }
91    }
92}
93
94/// One record an action writes besides its own, as its declaration says it: the app by the
95/// name a person reads, and what the step does there in their words, with the step's own
96/// app, kind and verb for a caller that decides on them rather than reads them
97/// ([`crate::ActionDescriptor::effects`]).
98#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub struct DeclaredEffect {
101    /// The app that keeps the record, by the name it shows.
102    pub app: String,
103    /// What the action's step does there, in the person's words.
104    pub what: String,
105    /// The app's id, as the declaration names it.
106    #[serde(default)]
107    pub app_id: String,
108    /// The record's kind (`passwords.workspace-vault`).
109    #[serde(default)]
110    pub kind: String,
111    /// The verb the step runs there.
112    #[serde(default)]
113    pub verb: String,
114}
115
116impl DeclaredEffect {
117    /// The step `step` of a declaration on the app `app_id`, whose display name is `app` and
118    /// whose verb `what` does there, in the person's words.
119    #[must_use]
120    pub fn new(
121        app: impl Into<String>,
122        what: impl Into<String>,
123        step: &crate::ActionEffect,
124    ) -> Self {
125        Self {
126            app: app.into(),
127            what: what.into(),
128            app_id: step.app.clone(),
129            kind: step.kind.clone(),
130            verb: step.verb.clone(),
131        }
132    }
133}
134
135/// One argument an action shows the person before they answer its ask, as
136/// its declaration names it: the parameter, optionally one field of it, and
137/// how its value reads. Admission fills the ask's [`Fact`]s from the call's
138/// arguments with these, so the card shows what the call would do without
139/// asking the app.
140#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(rename_all = "camelCase")]
142pub struct Shown {
143    /// The parameter, by its declared name; it is also the fact's label.
144    pub param: String,
145    /// One field of the parameter's value, when only that field is shown.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub field: Option<String>,
148    #[serde(default)]
149    pub render: ShownAs,
150}
151
152/// How a shown value reads on the card.
153#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
154#[serde(rename_all = "camelCase")]
155pub enum ShownAs {
156    /// Plain text, cut when long.
157    #[default]
158    Text,
159    /// A list of addresses (mail recipients, members), each its own line.
160    Addresses,
161    /// A long value (a message body) shown folded, opened on request.
162    Long,
163    /// A value the person must not read on the card: shown withheld.
164    Secret,
165}
166
167/// Who a member is, by id and by the name the person knows them under.
168#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
169#[serde(rename_all = "camelCase")]
170pub struct Named {
171    pub id: String,
172    pub name: String,
173}
174
175/// Who asks.
176#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
177#[serde(rename_all = "camelCase")]
178pub enum AskedBy {
179    /// An agent, working in a turn or on its own, or a key a person's calls came in on: the
180    /// member the workspace names each of them by.
181    Agent(Named),
182    /// An app's code, by the app and its title, and who wrote it.
183    App {
184        app: String,
185        title: String,
186        #[serde(default)]
187        author: Option<Named>,
188    },
189    /// A device of the person's, or the server that keeps their workspaces.
190    Device(Named),
191    /// A program outside Tilo on the device (a Linux program reaching the session through the
192    /// desktop portal, polkit or `NetworkManager`), by its name and the app id it gives, if any.
193    Program {
194        name: String,
195        #[serde(default)]
196        app_id: Option<String>,
197    },
198}
199
200impl Default for AskedBy {
201    fn default() -> Self {
202        Self::Device(Named::default())
203    }
204}
205
206/// What a call that waits for a person's yes shows them: what the asked
207/// record keeps beside the call itself, and what a [`Asked`] row lists.
208/// Every part is written, empty or not: a refusal travels by position.
209#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(rename_all = "camelCase")]
211pub struct AskedFacts {
212    /// Who asks.
213    pub by: AskedBy,
214    /// What is asked, in the asker's words where it says something of its
215    /// own (a turn's question); empty where the action's name says it.
216    #[serde(default)]
217    pub words: String,
218    /// The record the call acts on, by its name, where it names one.
219    #[serde(default)]
220    pub on: Option<String>,
221    /// What the person reads before answering, in order.
222    #[serde(default)]
223    pub facts: Vec<Fact>,
224    /// The records the called action writes besides its own, as it declares them
225    /// ([`crate::ActionDescriptor::effects`]): each app by the name a person reads, and what the
226    /// step does there in their words. Empty for an action that writes only its own resource,
227    /// which says nothing at all of what it writes.
228    #[serde(default)]
229    pub effects: Vec<DeclaredEffect>,
230    /// Whether the call takes away what Undo does not bring back.
231    #[serde(default)]
232    pub destructive: bool,
233    /// A question's choices, where the person answers with one of them
234    /// rather than yes or no.
235    #[serde(default)]
236    pub choices: Vec<String>,
237    /// The action's verb alone (`set`), or the phrase it declares for always:
238    /// "Always let {asker} {verb} {plural}".
239    #[serde(default)]
240    pub verb: String,
241    /// The plural of the resource type the action is on (`alarms`), which
242    /// "always" is offered for; `None` where it is not offered.
243    #[serde(default)]
244    pub plural: Option<String>,
245    /// The conversation a turn's question belongs to, by its address.
246    #[serde(default)]
247    pub conversation: Option<String>,
248    /// What the person types or records with their answer, in order: the approve carries one
249    /// entry per take ([`Resolve::typed`]). A take is a value the call needs that is none of its
250    /// arguments; changing an argument is a field of [`Self::form`].
251    #[serde(default)]
252    pub takes: Vec<Take>,
253    /// The action whose own call by the person answers this, `<provider>/<resource>#<action>`,
254    /// where what they type is kept by that action (a password the vault keeps): the asking
255    /// view opens its form, filled from [`Self::facts`], and nothing they type passes through
256    /// the record.
257    #[serde(default)]
258    pub answered_by: Option<String>,
259    /// Why the answer before this one did not do (a password that did not open it), shown at
260    /// the takes. Each attempt is a record of its own.
261    #[serde(default)]
262    pub retry: Option<String>,
263    /// The files or folder the person picks with their answer, where the asker wants some.
264    #[serde(default)]
265    pub files: Option<FilesAsked>,
266    /// Whether the person picks any number of [`Self::choices`] ([`Resolve::chosen`]) rather
267    /// than one ([`Resolve::choice`]).
268    #[serde(default)]
269    pub many: bool,
270    /// The resource type the action is on, by its id (`clocks.alarm`): what a grant given
271    /// with the answer is scoped to. Empty where the call is on no resource type.
272    #[serde(default)]
273    pub kind: String,
274    /// What the action is able to do, as its contract declares it: the kind of action a grant
275    /// given with the answer allows. `None` where nothing declares it, and then no grant is
276    /// offered.
277    #[serde(default)]
278    pub effect: Option<crate::ActionKind>,
279    /// What the person may change in the call's arguments before they approve it, as the
280    /// action's contract draws them ([`crate::Draft::render`]): each field they may change, by
281    /// its path in the arguments, with its value as asked. Empty where nothing may change.
282    /// A field here changes one of the call's arguments; a take ([`Self::takes`]) is a value
283    /// the call needs that is none of its arguments.
284    #[serde(default)]
285    pub form: Vec<crate::DraftField>,
286    /// What declining is called where it does something of its own (`Keep` the workspace, `Don't
287    /// add` the program): the asking view words its way out with it. `None` where declining only
288    /// says no.
289    #[serde(default)]
290    pub decline: Option<String>,
291    /// A picture of what is asked about, as a `data:` URL the asking view shows beside who asks:
292    /// a downloaded program's own artwork. `None` for none.
293    #[serde(default)]
294    pub picture: Option<String>,
295}
296
297/// The dispatch a call only the person's root signs is kept under, made on a device that keeps
298/// none: its record waits in the workspace for one of their devices that keeps it, which asks
299/// them once, takes it ([`KeptAsk::taken`]), runs it under the root and writes how it went into
300/// the record ([`KeptAsk::outcome`]).
301pub const AT_ROOT: &str = "at-root";
302
303/// What answering a call kept for a device that keeps the person's root is refused with on a
304/// device that keeps none.
305pub const ANSWERED_AT_ROOT: &str = "This is answered on a device of yours that keeps your identity";
306
307/// One thing the person types, or records, with their answer.
308#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
309#[serde(rename_all = "camelCase")]
310pub struct Take {
311    pub label: String,
312    /// Whether what is typed is a secret (a password, a passphrase): never written to the
313    /// record, its history or a log, handed only to the asker on the device that asked, and
314    /// never filled in beforehand. It may be answered empty.
315    #[serde(default)]
316    pub secret: bool,
317    /// Whether a secret is shown while it is typed.
318    #[serde(default)]
319    pub shown: bool,
320    /// What the field holds before the person types; never for a secret.
321    #[serde(default)]
322    pub initial: Option<String>,
323    /// Whether the person presses a key chord rather than typing (a shortcut).
324    #[serde(default)]
325    pub chord: bool,
326}
327
328/// The files or folder an ask has the person pick, in the system's file picker.
329#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
330#[serde(rename_all = "camelCase")]
331pub struct FilesAsked {
332    pub mode: FilesMode,
333    /// Whether more than one may be picked.
334    #[serde(default)]
335    pub many: bool,
336    /// The types offered to pick among, each by its label and file name patterns.
337    #[serde(default)]
338    pub types: Vec<FileType>,
339    /// The name a file being saved is suggested under.
340    #[serde(default)]
341    pub name: Option<String>,
342    /// The folder the picker opens in.
343    #[serde(default)]
344    pub folder: Option<String>,
345}
346
347/// Whether the person picks files to open, a place to save one, or a folder.
348#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
349#[serde(rename_all = "snake_case")]
350pub enum FilesMode {
351    Open,
352    Save,
353    Folder,
354}
355
356/// A type of file offered in the picker.
357#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
358#[serde(rename_all = "camelCase")]
359pub struct FileType {
360    pub label: String,
361    pub patterns: Vec<String>,
362}
363
364impl AskedFacts {
365    /// Whether this ask is answered only on the device that asked it: it takes a secret, or
366    /// files, which only that device's own picker and its asker may see.
367    #[must_use]
368    pub fn answered_where_asked(&self) -> bool {
369        self.files.is_some() || self.takes.iter().any(|take| take.secret)
370    }
371
372    /// Facts about a call by `by` that show nothing beyond its action.
373    #[must_use]
374    pub fn by(by: AskedBy) -> Self {
375        Self {
376            by,
377            ..Self::default()
378        }
379    }
380
381    /// With `fact` added after the others.
382    #[must_use]
383    pub fn with_fact(mut self, label: impl Into<String>, value: impl Into<String>) -> Self {
384        self.facts.push(Fact::new(label, value));
385        self
386    }
387
388    /// What a run's failure for want of the person's answer states in its
389    /// `details`: these facts, as JSON.
390    #[must_use]
391    pub fn to_details(&self) -> serde_json::Value {
392        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
393    }
394
395    /// The facts a run's failure states in its `details`; none where it
396    /// states none.
397    #[must_use]
398    pub fn from_details(details: Option<&serde_json::Value>) -> Self {
399        details
400            .cloned()
401            .and_then(|details| serde_json::from_value(details).ok())
402            .unwrap_or_default()
403    }
404
405    /// The value of the fact labelled `label`.
406    #[must_use]
407    pub fn fact(&self, label: &str) -> Option<&str> {
408        self.facts
409            .iter()
410            .find(|fact| fact.label == label)
411            .map(|fact| fact.value.as_str())
412    }
413}
414
415/// A `tilo.invocations` record, by the workspace it is in and its address there.
416///
417/// Which record it is is its workspace and address alone; [`Self::device`] says where it was
418/// asked, and plays no part in naming it.
419#[derive(Clone, Debug, Serialize, Deserialize)]
420pub struct RecordRef {
421    pub workspace: String,
422    pub record: String,
423    /// The device that asked, by its id, for an ask answered only there
424    /// ([`AskedFacts::answered_where_asked`]).
425    #[serde(default, skip_serializing_if = "Option::is_none")]
426    pub device: Option<String>,
427}
428
429impl PartialEq for RecordRef {
430    fn eq(&self, other: &Self) -> bool {
431        self.workspace == other.workspace && self.record == other.record
432    }
433}
434
435impl Eq for RecordRef {}
436
437impl PartialOrd for RecordRef {
438    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
439        Some(self.cmp(other))
440    }
441}
442
443/// Ordered as it is named: by its workspace, then its address there.
444impl Ord for RecordRef {
445    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
446        (&self.workspace, &self.record).cmp(&(&other.workspace, &other.record))
447    }
448}
449
450impl std::hash::Hash for RecordRef {
451    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
452        self.workspace.hash(state);
453        self.record.hash(state);
454    }
455}
456
457impl RecordRef {
458    /// How `invocation` stands while its person is asked about it in this record: under way,
459    /// with nothing of it done, its phase saying so ([`ASKED_PHASE`]) and its message naming
460    /// the record.
461    #[must_use]
462    pub fn waiting(&self, invocation: crate::InvocationId) -> crate::InvocationUpdate {
463        crate::InvocationUpdate::Progress {
464            invocation,
465            sequence: 1,
466            phase: ASKED_PHASE.to_owned(),
467            completed: None,
468            total: None,
469            message: Some(format!("{}/{}", self.workspace, self.record)),
470        }
471    }
472
473    /// The record `update` says its invocation waits in for its person ([`Self::waiting`]):
474    /// `None` for an update that says anything else.
475    #[must_use]
476    pub fn waited_in(update: &crate::InvocationUpdate) -> Option<Self> {
477        let crate::InvocationUpdate::Progress {
478            phase,
479            message: Some(message),
480            ..
481        } = update
482        else {
483            return None;
484        };
485        if phase != ASKED_PHASE {
486            return None;
487        }
488        let (workspace, record) = message.split_once('/')?;
489        Some(Self {
490            workspace: workspace.to_owned(),
491            record: record.to_owned(),
492            device: None,
493        })
494    }
495}
496
497/// What writes a call that waits for a person's yes as its own invocation
498/// record in status asked: the workspace's store, which the host hands
499/// whoever answers callers.
500pub trait AskedRecords: Send + Sync {
501    /// Write the call `request` that `caller` made, which needs the yes of
502    /// `facts.by`'s person, as its `tilo.invocations` record in status asked
503    /// in `workspace`, read by the caller and the person asked: its address.
504    ///
505    /// # Errors
506    /// Why it could not be written, in words its caller reads.
507    fn write_asked(
508        &self,
509        workspace: &str,
510        caller: &super::Caller,
511        request: &super::InvokeRequest,
512        facts: &AskedFacts,
513    ) -> Result<RecordRef, String>;
514
515    /// Every asked record `person` (their root key) may answer, across the
516    /// workspaces here, oldest first.
517    fn asked_of(&self, person: &[u8; 32]) -> Vec<Asked>;
518
519    /// Answered once an asked record here changes: what a live listing of
520    /// [`Self::asked_of`] waits on before it reads again.
521    fn changed(&self) -> super::Pending<()>;
522}
523
524/// A person's approve of an asked record, as the call kept in it reads it
525/// when the dispatch admits it again ([`super::InvokeRequest::approval`]).
526#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
527pub struct Approval {
528    /// The asked record.
529    pub record: RecordRef,
530    /// The choice they picked, by its place among [`AskedFacts::choices`],
531    /// for a question that offers choices.
532    pub choice: Option<usize>,
533    /// The choices they picked, for a question that offers many ([`AskedFacts::many`]).
534    #[serde(default)]
535    pub chosen: Vec<usize>,
536    /// What they typed, one entry per take ([`AskedFacts::takes`]). Kept in memory only and
537    /// wiped when dropped: it never travels in a frame, so it reaches the asker only on the
538    /// device that asked.
539    #[serde(skip)]
540    pub typed: Vec<Zeroizing<String>>,
541    /// The files they picked, as URIs ([`AskedFacts::files`]).
542    #[serde(default)]
543    pub files: Vec<String>,
544    /// The arguments as the person changed them before approving ([`Resolve::edits`]): the
545    /// call carries exactly these, and is the same call as the one kept with them in place of
546    /// its own ([`same_call`]). `None` where they changed nothing.
547    #[serde(default, skip_serializing_if = "Option::is_none")]
548    pub arguments: Option<Box<serde_json::Map<String, serde_json::Value>>>,
549}
550
551impl Approval {
552    /// The approve of `record`, picking `choice` where it offers choices, and nothing more.
553    #[must_use]
554    pub fn new(record: RecordRef, choice: Option<usize>) -> Self {
555        Self {
556            record,
557            choice,
558            chosen: Vec::new(),
559            typed: Vec::new(),
560            files: Vec::new(),
561            arguments: None,
562        }
563    }
564}
565
566/// An answer a person may give an asked record.
567#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
568#[serde(rename_all = "snake_case")]
569pub enum Offer {
570    #[default]
571    Approve,
572    Decline,
573    /// Approve, and grant the asker the action on every resource of its type.
574    ApproveAndGrant,
575}
576
577impl Offer {
578    /// What a question showing `facts` offers, in the order they are shown: approve, approve
579    /// and grant where there is a resource type to name and an agent or an app to grant it
580    /// to, and decline.
581    #[must_use]
582    pub fn of(facts: &AskedFacts) -> Vec<Self> {
583        let mut offers = vec![Self::Approve];
584        if facts.plural.is_some()
585            && facts.choices.is_empty()
586            && !matches!(facts.by, AskedBy::Device(_) | AskedBy::Program { .. })
587        {
588            offers.push(Self::ApproveAndGrant);
589        }
590        offers.push(Self::Decline);
591        offers
592    }
593}
594
595/// The arguments of [`RESOLVE`]: the person's answer, and for a question that offers choices
596/// the one they picked, by its place among [`AskedFacts::choices`].
597#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
598#[serde(rename_all = "camelCase", deny_unknown_fields)]
599pub struct Resolve {
600    pub resolution: Offer,
601    #[serde(default)]
602    pub choice: Option<usize>,
603    /// The choices picked, for a question that offers many ([`AskedFacts::many`]).
604    #[serde(default, deserialize_with = "none_is_empty")]
605    pub chosen: Vec<usize>,
606    /// What the person typed, one entry per take, in order ([`AskedFacts::takes`]). A secret
607    /// one is never written anywhere: the record and its history keep the answer without it.
608    #[serde(default, deserialize_with = "none_is_empty")]
609    pub typed: Vec<String>,
610    /// The files picked, as URIs ([`AskedFacts::files`]).
611    #[serde(default, deserialize_with = "none_is_empty")]
612    pub files: Vec<String>,
613    /// What the person changed in the call before approving, each a field of
614    /// [`AskedFacts::form`] set to what they wrote: the call runs with its arguments so changed,
615    /// admitted again as a fresh call with them would be, so the action's own contract checks
616    /// them. Only with an approve.
617    #[serde(
618        default,
619        deserialize_with = "none_is_empty",
620        skip_serializing_if = "Vec::is_empty"
621    )]
622    pub edits: Vec<crate::DraftEdit>,
623}
624
625/// A list a caller left out as nothing (`null`, as a view passes an option it did not give)
626/// read as an empty one.
627fn none_is_empty<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
628where
629    D: serde::Deserializer<'de>,
630    T: Deserialize<'de>,
631{
632    Ok(Option::<Vec<T>>::deserialize(deserializer)?.unwrap_or_default())
633}
634
635impl Resolve {
636    /// This answer as the record and its history may keep it: what was typed for a secret
637    /// take of `facts` left out.
638    #[must_use]
639    pub fn kept(&self, facts: &AskedFacts) -> Self {
640        let typed = self
641            .typed
642            .iter()
643            .enumerate()
644            .filter(|(at, _)| facts.takes.get(*at).is_none_or(|take| !take.secret))
645            .map(|(_, typed)| typed.clone())
646            .collect();
647        Self {
648            typed,
649            ..self.clone()
650        }
651    }
652}
653
654/// Go on where the person approved `request`; else refuse it until they do, showing them
655/// `facts`: what a provider whose action needs their yes does, and all it does. The dispatch
656/// that carried the call keeps it as its asked record, and an approve brings it back once,
657/// the same call, carrying [`super::InvokeRequest::approval`].
658///
659/// # Errors
660/// [`super::ActionCallError::ConfirmationRequired`] with `facts`, for a call nobody approved.
661pub fn approved_or_asks(
662    request: &super::InvokeRequest,
663    facts: impl FnOnce() -> AskedFacts,
664) -> Result<(), super::ActionCallError> {
665    if request.approval().is_some() {
666        Ok(())
667    } else {
668        Err(super::ActionCallError::asks(facts()))
669    }
670}
671
672/// Whether `target` answers an asked record ([`RESOLVE`]).
673#[must_use]
674pub fn is_resolve(target: &RemoteActionTarget) -> bool {
675    target.provider == super::WORKSPACE_INVOCATIONS_PROVIDER && target.address.action == RESOLVE
676}
677
678/// The person a call by `caller` asks when it waits for a yes: the person it acts for, else
679/// the person calling. Never the person of the device that carried the connection.
680#[must_use]
681pub fn asked_person(caller: &super::Caller) -> Option<String> {
682    caller
683        .acting_for_person()
684        .or_else(|| caller.acting().person_id())
685        // A device a host placed acts for nobody, and the host that placed it acts for its
686        // person: what it holds for that person is put to them.
687        .map(str::to_owned)
688        .or_else(|| {
689            caller
690                .placed_records()
691                .map(|placed| hex::encode(placed.person()))
692        })
693        .filter(|person| !person.is_empty())
694}
695
696/// The person `caller` answers as: a person acting themselves, or a view acting for the
697/// person it was opened for. An agent, a bot, an automation or an app answers for nobody,
698/// whoever it acts for: the confirmation is always the system's.
699#[must_use]
700pub fn answering_person(caller: &super::Caller) -> Option<&str> {
701    let acting = caller.acting();
702    if acting.is_agent() || acting.is_bot() || acting.is_automation() || acting.app.is_some() {
703        return None;
704    }
705    acting.person_id().filter(|person| !person.is_empty())
706}
707
708/// Whether `call` is the call `kept`: the same target and the same arguments, as they travel.
709/// Where `call` carries a person's approve that changed the arguments ([`Approval::arguments`]),
710/// it is the kept call with those in place of its own, and with the arguments its record kept
711/// none of ([`KeptAsk::sealed`]), which the approve never shows, as `kept` carries them.
712#[must_use]
713pub fn same_call(kept: &super::InvokeRequest, call: &super::InvokeRequest) -> bool {
714    let value = |target: &super::RemoteActionTarget, argument: &super::InvokeArgument| {
715        serde_json::to_value((target, argument)).ok()
716    };
717    let edited = call
718        .approval()
719        .and_then(|approval| approval.arguments.as_deref().cloned())
720        .map(|mut edited| {
721            if let (super::InvokeArgument::Json(kept), super::InvokeArgument::Json(sent)) =
722                (&kept.argument, &call.argument)
723            {
724                for name in sent.keys() {
725                    if !edited.contains_key(name)
726                        && let Some(value) = kept.get(name)
727                    {
728                        edited.insert(name.clone(), value.clone());
729                    }
730                }
731            }
732            super::InvokeArgument::Json(edited)
733        });
734    let kept = value(&kept.target, edited.as_ref().unwrap_or(&kept.argument));
735    matches!((kept, value(&call.target, &call.argument)), (Some(a), Some(b)) if a == b)
736}
737
738/// The dispatch that keeps a call waiting in its asked record, as the person's answer reaches
739/// it: the only place a call carrying their approve is admitted again.
740pub trait AskedDispatch: Send + Sync {
741    /// What this dispatch needs, beside the call and its caller, to admit `invocation` again
742    /// once it no longer remembers it (the host restarted): kept with its record.
743    fn context(&self, invocation: super::InvocationId) -> serde_json::Value;
744
745    /// The window a person's press asked `invocation` in, where it did: kept with its record, so
746    /// the question stands over that window. `None` for a call no press asked (an agent's).
747    fn pressed(&self, invocation: super::InvocationId) -> Option<Pressed> {
748        let _ = invocation;
749        None
750    }
751
752    /// Admit `request` again under its id for `caller`, who asked for it, carrying the person's
753    /// approve ([`super::InvokeRequest::approval`]): only where it still waits in its asked
754    /// record for the same call, or, where this dispatch no longer remembers it, as a new call
755    /// under that id, with `context` ([`Self::context`]). It runs under `caller`'s grants as
756    /// they stand now, and how it goes reaches `caller` as every invocation of theirs does.
757    ///
758    /// # Errors
759    /// Why it was not admitted again.
760    fn readmit(
761        &self,
762        caller: &super::Caller,
763        request: super::InvokeRequest,
764        context: &serde_json::Value,
765    ) -> Result<(), super::ActionCallError>;
766
767    /// End `invocation`, which `caller` asked for, declined by the person: `caller` is told so.
768    /// One this dispatch no longer remembers ended already.
769    ///
770    /// # Errors
771    /// Why it could not be ended.
772    fn declined(
773        &self,
774        caller: &super::Caller,
775        invocation: super::InvocationId,
776    ) -> Result<(), super::ActionCallError>;
777
778    /// Whether this dispatch runs nothing on its person's answer: the asker makes the call again
779    /// itself (an app's own process), so the answer is the grant that call is decided by. Its
780    /// person's approve then writes a grant for one use, and their decline a refusal, both where
781    /// their app permissions show and change them.
782    fn runs_nothing(&self) -> bool {
783        false
784    }
785
786    /// End `invocation`, which `caller` asked for, withdrawn by whoever asked it before its
787    /// person answered (tilo-remote-actions' `AskedStore::withdraw`): it ends cancelled, saying `message`.
788    fn withdrawn(&self, caller: &super::Caller, invocation: super::InvocationId, message: &str) {
789        let _ = (caller, invocation, message);
790    }
791}
792
793/// The action of a record's read the person is asked about: an app's join of another app's
794/// record, waiting as `<record>#read` in its asked record ([`AskedReads`]).
795pub const READ: &str = "read";
796
797/// Where a read the person is asked about waits for them: as its asked record, an invocation of
798/// the record's [`READ`] that they answer as every asked call.
799pub trait AskedReads: Send + Sync {
800    /// Keep `caller`'s read of `address`, which the app `app` reads for them, as its asked record
801    /// showing `facts`: allowed once the person approves it, refused when they decline it or
802    /// it is withdrawn.
803    fn ask_read(
804        &self,
805        caller: &super::Caller,
806        app: &str,
807        address: &super::ResourceAddress,
808        facts: AskedFacts,
809    ) -> super::Pending<super::Decided>;
810}
811
812/// An asked record as the host keeps it in its own state: the call that waits, who asked it,
813/// what its person is shown, and what its dispatch needs to admit it again, so the call waits
814/// across the host's restarts.
815#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
816// A kept record grows: a build reads what a later one wrote, so unknown fields are let through.
817#[serde(rename_all = "camelCase")]
818pub struct KeptAsk {
819    pub at: RecordRef,
820    /// The person asked, their root key in hex.
821    pub person: String,
822    pub caller: super::KeptCaller,
823    pub request: super::InvokeRequest,
824    pub facts: AskedFacts,
825    pub asked_at_ms: u64,
826    /// The dispatch that keeps the call, by the name it gave the store.
827    pub dispatch: String,
828    /// What that dispatch needs to admit it again ([`AskedDispatch::context`]).
829    pub context: serde_json::Value,
830    /// The device that took the call to run it, its key in hex, once the person answered it
831    /// there ([`AT_ROOT`]): written before it runs, so that device resumes it after a restart.
832    #[serde(default, skip_serializing_if = "Option::is_none")]
833    pub taken: Option<String>,
834    /// How the call ended where it ran ([`AT_ROOT`]): what the device that asked shows, after
835    /// which it forgets the record.
836    #[serde(default, skip_serializing_if = "Option::is_none")]
837    pub outcome: Option<crate::InvocationUpdate>,
838    /// The call's arguments as its person changed them when they approved it
839    /// ([`Resolve::edits`]), beside the call as it was asked ([`Self::request`]): what runs, and
840    /// what a device that takes it again after a restart runs.
841    #[serde(default, skip_serializing_if = "Option::is_none")]
842    pub edited: Option<serde_json::Map<String, serde_json::Value>>,
843    /// The window a person's press asked it in ([`AskedDispatch::pressed`]), so its question
844    /// stands over that window also after a restart.
845    #[serde(default, skip_serializing_if = "Option::is_none")]
846    pub pressed: Option<Pressed>,
847    /// The arguments [`Self::request`] carried that the record keeps none of, those its action
848    /// declares secret ([`super::secret_arguments`]), by name: their values are held in the memory
849    /// of the device that asked alone, and a call kept from before it started again cannot run.
850    #[serde(default, skip_serializing_if = "Vec::is_empty")]
851    pub sealed: Vec<String>,
852}
853
854/// Where a host keeps the asked records that wait, across its restarts: each kept once it is
855/// written, and forgotten once it is answered, in that order. The host reads what it kept back
856/// when it starts (tilo-remote-actions' `AskedStore::keep_through`).
857pub trait AskedKeeping: Send + Sync {
858    /// Keep `ask`, in place of the one kept under its record.
859    fn keep(&self, ask: &KeptAsk);
860
861    /// Forget the record `at`: it waits no more.
862    fn forget(&self, at: &RecordRef);
863}
864
865/// What writes the grant a person gives with an approve
866/// ([`Offer::ApproveAndGrant`]): an ordinary grant of the workspace's policy, shown and taken
867/// back as every grant is.
868pub trait AskedGrants: Send + Sync {
869    /// Write `grant` in `workspace`, given by `person` (their root key, hex).
870    ///
871    /// # Errors
872    /// Why it was not written: refused where it reaches beyond what `person` may grant.
873    fn grant(
874        &self,
875        workspace: &str,
876        person: &str,
877        grant: tilo_action_policy::Grant,
878    ) -> super::Pending<Result<(), String>>;
879}
880
881/// Where the call was pressed, when a person's press asked it.
882#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
883#[serde(rename_all = "camelCase")]
884pub struct Pressed {
885    /// The device the press was on, by its id.
886    pub device: String,
887    pub app: String,
888    /// The window's tab key, as the session publishes it (`device.Window.key`).
889    pub instance: String,
890    pub resource: String,
891    /// Where in that window the press was, as the compositor that delivered it saw it: the
892    /// question stands there, its answer under the press. `None` for a press it gave no point
893    /// for (a key).
894    #[serde(default)]
895    pub at: Option<PressPoint>,
896}
897
898/// A point in a window, in its logical pixels from its top-left corner.
899#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
900pub struct PressPoint {
901    pub x: i32,
902    pub y: i32,
903}
904
905/// One question that waits for the person, as the reading of its workspace's invocations
906/// carries it: an asked invocation record they may answer with `<record>#resolve`.
907#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
908#[serde(rename_all = "camelCase")]
909pub struct Asked {
910    /// The record: what `resolve` is called on.
911    pub record: RecordRef,
912    /// The workspace the asked call acts in.
913    pub workspace: String,
914    /// That workspace by its name.
915    pub workspace_name: String,
916    /// The app whose action is asked.
917    pub app: String,
918    /// The action, `<app>#<action>`.
919    pub action: String,
920    /// The action by its published label.
921    pub name: String,
922    /// Since when it waits, in milliseconds since the Unix epoch.
923    pub asked_at_ms: u64,
924    #[serde(default)]
925    pub pressed: Option<Pressed>,
926    pub offers: Vec<Offer>,
927    #[serde(flatten)]
928    pub facts: AskedFacts,
929}
930
931#[cfg(test)]
932mod tests {
933    #![allow(clippy::unwrap_used, reason = "in a test this is the assertion")]
934
935    use super::*;
936
937    /// A row reads as a client binds it: camel case, its facts beside the
938    /// record's own names.
939    #[test]
940    fn a_row_reads_as_a_client_binds_it() {
941        let row = Asked {
942            record: RecordRef {
943                workspace: "acme".into(),
944                record: "invocations/7".into(),
945                device: None,
946            },
947            workspace: "acme".into(),
948            workspace_name: "Acme".into(),
949            app: "clocks".into(),
950            action: "clocks#set-alarm".into(),
951            name: "Set alarm".into(),
952            asked_at_ms: 9,
953            pressed: None,
954            offers: Vec::new(),
955            facts: AskedFacts {
956                verb: "set".into(),
957                plural: Some("alarms".into()),
958                ..AskedFacts::by(AskedBy::Agent(Named {
959                    id: "scout".into(),
960                    name: "Scout".into(),
961                }))
962            }
963            .with_fact("At", "07:00"),
964        };
965        let row = Asked {
966            offers: Offer::of(&row.facts),
967            ..row
968        };
969        let json = serde_json::to_value(&row).unwrap();
970        assert_eq!(
971            json,
972            serde_json::json!({
973                "record": {"workspace": "acme", "record": "invocations/7"},
974                "workspace": "acme",
975                "workspaceName": "Acme",
976                "app": "clocks",
977                "action": "clocks#set-alarm",
978                "name": "Set alarm",
979                "askedAtMs": 9,
980                "pressed": null,
981                "offers": ["approve", "approve_and_grant", "decline"],
982                "by": {"agent": {"id": "scout", "name": "Scout"}},
983                "words": "",
984                "on": null,
985                "facts": [{"label": "At", "value": "07:00"}],
986                "effects": [],
987                "destructive": false,
988                "choices": [],
989                "verb": "set",
990                "plural": "alarms",
991                "conversation": null,
992                "takes": [],
993                "answeredBy": null,
994                "retry": null,
995                "files": null,
996                "many": false,
997                "kind": "",
998                "effect": null,
999                "form": [],
1000                "decline": null,
1001                "picture": null,
1002            })
1003        );
1004        assert_eq!(serde_json::from_value::<Asked>(json).unwrap(), row);
1005    }
1006
1007    /// The facts travel by position as a refusal does: every part is written
1008    /// whether or not it holds anything.
1009    #[test]
1010    fn facts_travel_by_position() {
1011        let facts = AskedFacts::by(AskedBy::Device(Named {
1012            id: "d".into(),
1013            name: "Laptop".into(),
1014        }))
1015        .with_fact("To", "https://visa.example");
1016        let wire = postcard::to_allocvec(&facts).unwrap();
1017        assert_eq!(postcard::from_bytes::<AskedFacts>(&wire).unwrap(), facts);
1018    }
1019}