tilo-actions 0.5.0

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store, search index entries included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
//! What a call that waits for a person's yes says about itself, and how the
//! questions that wait for a person are listed.
//!
//! A call the caller's grants leave to a person is refused by its provider
//! with [`super::ActionCallError::ConfirmationRequired`], carrying
//! [`AskedFacts`]: what the person is shown. The dispatch keeps the call as
//! its own `tilo.invocations` record in status asked, readable by the caller
//! and the person asked, and that record is the question: there is no store
//! of asks beside it. The person answers it with the record's `resolve`
//! action; on approve the dispatch admits the same call again, bound to that
//! record, and a provider reads that it was approved
//! ([`super::InvokeRequest::approval`]).
//!
//! The reading of a workspace's invocations carries each asked record a person may answer as
//! an [`Asked`] row.
//!
//! The person answers with `<record>#`[`RESOLVE`] ([`Resolve`]), which [`AskedStore`] admits:
//! only the person the record asks, only while it is asked, and at most once. An approve hands
//! the call back to the dispatch that keeps it ([`AskedDispatch`]), which admits it again under
//! its id for its original caller, checking that caller's grants as they stand then.

use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;

use super::RemoteActionTarget;

mod store;
pub use store::{
    ANSWERED, ANSWERED_THERE, AskedStore, MOST_WAITING, NOT_YOURS, NOTHING_ASKED, ON_YOUR_DEVICE,
    SECRET_GONE, TOO_MANY_WAIT, Waiting, asked_grant,
};

/// What a frame carrying an approve no resolve handed back is refused with
/// ([`AskedStore::admits_approval`]).
pub const FORGED: &str = "This call carries an approve its person did not give";

/// Admit `request`, a caller's frame, as its approve stands: refused where it carries an
/// approve `store` did not hand back ([`AskedStore::admits_approval`]), or any approve where no
/// store keeps asked records here.
///
/// # Errors
/// [`FORGED`], refused.
pub fn admit_frame(
    store: Option<&AskedStore>,
    request: &super::InvokeRequest,
) -> Result<(), super::ActionCallError> {
    if request.approval().is_none() || store.is_some_and(|store| store.admits_approval(request)) {
        Ok(())
    } else {
        Err(super::ActionCallError::Refused {
            reason: FORGED.to_owned(),
        })
    }
}

/// What a resolve from anything but the system's own confirmation is refused with: the
/// person's shell asks them, and the CLI asks them at its own prompt.
pub const CONFIRMED_BY_THE_SYSTEM: &str =
    "Only you answer this, where Tilo asks you: on your screen, or at tilo's own prompt";

/// Answer an asked record: `<record>#resolve` with a [`Resolve`], on the
/// [`super::workspace_invocations::PROVIDER`] provider.
pub const RESOLVE: &str = "resolve";
/// What an asked invocation the person declined ends with: cancelled, its message this.
pub const DECLINED: &str = "declined";
/// The phase of an invocation's progress while it waits in its asked record: its message
/// names the record (`<workspace>/<record>`).
pub const ASKED_PHASE: &str = "asked";

/// One fact the person reads before answering: a label and its value, as a
/// reviewer reads it, long values cut and secrets withheld.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Fact {
    pub label: String,
    pub value: String,
}

impl Fact {
    #[must_use]
    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            value: value.into(),
        }
    }
}

/// One record an action writes besides its own, as its declaration says it: the app by the
/// name a person reads, and what the step does there in their words, with the step's own
/// app, kind and verb for a caller that decides on them rather than reads them
/// ([`crate::ActionDescriptor::effects`]).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeclaredEffect {
    /// The app that keeps the record, by the name it shows.
    pub app: String,
    /// What the action's step does there, in the person's words.
    pub what: String,
    /// The app's id, as the declaration names it.
    #[serde(default)]
    pub app_id: String,
    /// The record's kind (`passwords.workspace-vault`).
    #[serde(default)]
    pub kind: String,
    /// The verb the step runs there.
    #[serde(default)]
    pub verb: String,
}

impl DeclaredEffect {
    /// The step `step` of a declaration on the app `app_id`, whose display name is `app` and
    /// whose verb `what` does there, in the person's words.
    #[must_use]
    pub fn new(
        app: impl Into<String>,
        what: impl Into<String>,
        step: &crate::ActionEffect,
    ) -> Self {
        Self {
            app: app.into(),
            what: what.into(),
            app_id: step.app.clone(),
            kind: step.kind.clone(),
            verb: step.verb.clone(),
        }
    }
}

/// One argument an action shows the person before they answer its ask, as
/// its declaration names it: the parameter, optionally one field of it, and
/// how its value reads. Admission fills the ask's [`Fact`]s from the call's
/// arguments with these, so the card shows what the call would do without
/// asking the app.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Shown {
    /// The parameter, by its declared name; it is also the fact's label.
    pub param: String,
    /// One field of the parameter's value, when only that field is shown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,
    #[serde(default)]
    pub render: ShownAs,
}

/// How a shown value reads on the card.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ShownAs {
    /// Plain text, cut when long.
    #[default]
    Text,
    /// A list of addresses (mail recipients, members), each its own line.
    Addresses,
    /// A long value (a message body) shown folded, opened on request.
    Long,
    /// A value the person must not read on the card: shown withheld.
    Secret,
}

/// Who a member is, by id and by the name the person knows them under.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Named {
    pub id: String,
    pub name: String,
}

/// Who asks.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AskedBy {
    /// An agent, working in a turn or on its own.
    Agent(Named),
    /// An app's code, by the app and its title, and who wrote it.
    App {
        app: String,
        title: String,
        #[serde(default)]
        author: Option<Named>,
    },
    /// A device of the person's, or the server that keeps their workspaces.
    Device(Named),
    /// A program outside Tilo on the device (a Linux program reaching the session through the
    /// desktop portal, polkit or `NetworkManager`), by its name and the app id it gives, if any.
    Program {
        name: String,
        #[serde(default)]
        app_id: Option<String>,
    },
}

impl Default for AskedBy {
    fn default() -> Self {
        Self::Device(Named::default())
    }
}

/// What a call that waits for a person's yes shows them: what the asked
/// record keeps beside the call itself, and what a [`Asked`] row lists.
/// Every part is written, empty or not: a refusal travels by position.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AskedFacts {
    /// Who asks.
    pub by: AskedBy,
    /// What is asked, in the asker's words where it says something of its
    /// own (a turn's question); empty where the action's name says it.
    #[serde(default)]
    pub words: String,
    /// The record the call acts on, by its name, where it names one.
    #[serde(default)]
    pub on: Option<String>,
    /// What the person reads before answering, in order.
    #[serde(default)]
    pub facts: Vec<Fact>,
    /// The records the called action writes besides its own, as it declares them
    /// ([`crate::ActionDescriptor::effects`]): each app by the name a person reads, and what the
    /// step does there in their words. Empty for an action that writes only its own resource,
    /// which says nothing at all of what it writes.
    #[serde(default)]
    pub effects: Vec<DeclaredEffect>,
    /// Whether the call takes away what Undo does not bring back.
    #[serde(default)]
    pub destructive: bool,
    /// A question's choices, where the person answers with one of them
    /// rather than yes or no.
    #[serde(default)]
    pub choices: Vec<String>,
    /// The action's verb alone (`set`), or the phrase it declares for always:
    /// "Always let {asker} {verb} {plural}".
    #[serde(default)]
    pub verb: String,
    /// The plural of the resource type the action is on (`alarms`), which
    /// "always" is offered for; `None` where it is not offered.
    #[serde(default)]
    pub plural: Option<String>,
    /// The conversation a turn's question belongs to, by its address.
    #[serde(default)]
    pub conversation: Option<String>,
    /// What the person types or records with their answer, in order: the approve carries one
    /// entry per take ([`Resolve::typed`]). A take is a value the call needs that is none of its
    /// arguments; changing an argument is a field of [`Self::form`].
    #[serde(default)]
    pub takes: Vec<Take>,
    /// The action whose own call by the person answers this, `<provider>/<resource>#<action>`,
    /// where what they type is kept by that action (a password the vault keeps): the asking
    /// view opens its form, filled from [`Self::facts`], and nothing they type passes through
    /// the record.
    #[serde(default)]
    pub answered_by: Option<String>,
    /// Why the answer before this one did not do (a password that did not open it), shown at
    /// the takes. Each attempt is a record of its own.
    #[serde(default)]
    pub retry: Option<String>,
    /// The files or folder the person picks with their answer, where the asker wants some.
    #[serde(default)]
    pub files: Option<FilesAsked>,
    /// Whether the person picks any number of [`Self::choices`] ([`Resolve::chosen`]) rather
    /// than one ([`Resolve::choice`]).
    #[serde(default)]
    pub many: bool,
    /// The resource type the action is on, by its id (`clocks.alarm`): what a grant given
    /// with the answer is scoped to. Empty where the call is on no resource type.
    #[serde(default)]
    pub kind: String,
    /// What the action is able to do, as its contract declares it: the kind of action a grant
    /// given with the answer allows. `None` where nothing declares it, and then no grant is
    /// offered.
    #[serde(default)]
    pub effect: Option<crate::ActionKind>,
    /// What the person may change in the call's arguments before they approve it, as the
    /// action's contract draws them ([`crate::Draft::render`]): each field they may change, by
    /// its path in the arguments, with its value as asked. Empty where nothing may change.
    /// A field here changes one of the call's arguments; a take ([`Self::takes`]) is a value
    /// the call needs that is none of its arguments.
    #[serde(default)]
    pub form: Vec<crate::DraftField>,
}

/// The dispatch a call only the person's root signs is kept under, made on a device that keeps
/// none: its record waits in the workspace for one of their devices that keeps it, which asks
/// them once, takes it ([`KeptAsk::taken`]), runs it under the root and writes how it went into
/// the record ([`KeptAsk::outcome`]).
pub const AT_ROOT: &str = "at-root";

/// What answering a call kept for a device that keeps the person's root is refused with on a
/// device that keeps none.
pub const ANSWERED_AT_ROOT: &str = "This is answered on a device of yours that keeps your identity";

/// One thing the person types, or records, with their answer.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Take {
    pub label: String,
    /// Whether what is typed is a secret (a password, a passphrase): never written to the
    /// record, its history or a log, handed only to the asker on the device that asked, and
    /// never filled in beforehand. It may be answered empty.
    #[serde(default)]
    pub secret: bool,
    /// Whether a secret is shown while it is typed.
    #[serde(default)]
    pub shown: bool,
    /// What the field holds before the person types; never for a secret.
    #[serde(default)]
    pub initial: Option<String>,
    /// Whether the person presses a key chord rather than typing (a shortcut).
    #[serde(default)]
    pub chord: bool,
}

/// The files or folder an ask has the person pick, in the system's file picker.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FilesAsked {
    pub mode: FilesMode,
    /// Whether more than one may be picked.
    #[serde(default)]
    pub many: bool,
    /// The types offered to pick among, each by its label and file name patterns.
    #[serde(default)]
    pub types: Vec<FileType>,
    /// The name a file being saved is suggested under.
    #[serde(default)]
    pub name: Option<String>,
    /// The folder the picker opens in.
    #[serde(default)]
    pub folder: Option<String>,
}

/// Whether the person picks files to open, a place to save one, or a folder.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FilesMode {
    Open,
    Save,
    Folder,
}

/// A type of file offered in the picker.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FileType {
    pub label: String,
    pub patterns: Vec<String>,
}

impl AskedFacts {
    /// Whether this ask is answered only on the device that asked it: it takes a secret, or
    /// files, which only that device's own picker and its asker may see.
    #[must_use]
    pub fn answered_where_asked(&self) -> bool {
        self.files.is_some() || self.takes.iter().any(|take| take.secret)
    }

    /// Facts about a call by `by` that show nothing beyond its action.
    #[must_use]
    pub fn by(by: AskedBy) -> Self {
        Self {
            by,
            ..Self::default()
        }
    }

    /// With `fact` added after the others.
    #[must_use]
    pub fn with_fact(mut self, label: impl Into<String>, value: impl Into<String>) -> Self {
        self.facts.push(Fact::new(label, value));
        self
    }

    /// What a run's failure for want of the person's answer states in its
    /// `details`: these facts, as JSON.
    #[must_use]
    pub fn to_details(&self) -> serde_json::Value {
        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
    }

    /// The facts a run's failure states in its `details`; none where it
    /// states none.
    #[must_use]
    pub fn from_details(details: Option<&serde_json::Value>) -> Self {
        details
            .cloned()
            .and_then(|details| serde_json::from_value(details).ok())
            .unwrap_or_default()
    }

    /// The value of the fact labelled `label`.
    #[must_use]
    pub fn fact(&self, label: &str) -> Option<&str> {
        self.facts
            .iter()
            .find(|fact| fact.label == label)
            .map(|fact| fact.value.as_str())
    }
}

/// A `tilo.invocations` record, by the workspace it is in and its address there.
///
/// Which record it is is its workspace and address alone; [`Self::device`] says where it was
/// asked, and plays no part in naming it.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RecordRef {
    pub workspace: String,
    pub record: String,
    /// The device that asked, by its id, for an ask answered only there
    /// ([`AskedFacts::answered_where_asked`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub device: Option<String>,
}

impl PartialEq for RecordRef {
    fn eq(&self, other: &Self) -> bool {
        self.workspace == other.workspace && self.record == other.record
    }
}

impl Eq for RecordRef {}

impl PartialOrd for RecordRef {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Ordered as it is named: by its workspace, then its address there.
impl Ord for RecordRef {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        (&self.workspace, &self.record).cmp(&(&other.workspace, &other.record))
    }
}

impl std::hash::Hash for RecordRef {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.workspace.hash(state);
        self.record.hash(state);
    }
}

impl RecordRef {
    /// How `invocation` stands while its person is asked about it in this record: under way,
    /// with nothing of it done, its phase saying so ([`ASKED_PHASE`]) and its message naming
    /// the record.
    #[must_use]
    pub fn waiting(&self, invocation: crate::InvocationId) -> crate::InvocationUpdate {
        crate::InvocationUpdate::Progress {
            invocation,
            sequence: 1,
            phase: ASKED_PHASE.to_owned(),
            completed: None,
            total: None,
            message: Some(format!("{}/{}", self.workspace, self.record)),
        }
    }
}

/// What writes a call that waits for a person's yes as its own invocation
/// record in status asked: the workspace's store, which the host hands
/// whoever answers callers.
pub trait AskedRecords: Send + Sync {
    /// Write the call `request` that `caller` made, which needs the yes of
    /// `facts.by`'s person, as its `tilo.invocations` record in status asked
    /// in `workspace`, read by the caller and the person asked: its address.
    ///
    /// # Errors
    /// Why it could not be written, in words its caller reads.
    fn write_asked(
        &self,
        workspace: &str,
        caller: &super::Caller,
        request: &super::InvokeRequest,
        facts: &AskedFacts,
    ) -> Result<RecordRef, String>;

    /// Every asked record `person` (their root key) may answer, across the
    /// workspaces here, oldest first.
    fn asked_of(&self, person: &[u8; 32]) -> Vec<Asked>;

    /// Answered once an asked record here changes: what a live listing of
    /// [`Self::asked_of`] waits on before it reads again.
    fn changed(&self) -> super::Pending<()>;
}

/// A person's approve of an asked record, as the call kept in it reads it
/// when the dispatch admits it again ([`super::InvokeRequest::approval`]).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Approval {
    /// The asked record.
    pub record: RecordRef,
    /// The choice they picked, by its place among [`AskedFacts::choices`],
    /// for a question that offers choices.
    pub choice: Option<usize>,
    /// The choices they picked, for a question that offers many ([`AskedFacts::many`]).
    #[serde(default)]
    pub chosen: Vec<usize>,
    /// What they typed, one entry per take ([`AskedFacts::takes`]). Kept in memory only and
    /// wiped when dropped: it never travels in a frame, so it reaches the asker only on the
    /// device that asked.
    #[serde(skip)]
    pub typed: Vec<Zeroizing<String>>,
    /// The files they picked, as URIs ([`AskedFacts::files`]).
    #[serde(default)]
    pub files: Vec<String>,
    /// The arguments as the person changed them before approving ([`Resolve::edits`]): the
    /// call carries exactly these, and is the same call as the one kept with them in place of
    /// its own ([`same_call`]). `None` where they changed nothing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub arguments: Option<Box<serde_json::Map<String, serde_json::Value>>>,
}

impl Approval {
    /// The approve of `record`, picking `choice` where it offers choices, and nothing more.
    #[must_use]
    pub fn new(record: RecordRef, choice: Option<usize>) -> Self {
        Self {
            record,
            choice,
            chosen: Vec::new(),
            typed: Vec::new(),
            files: Vec::new(),
            arguments: None,
        }
    }
}

/// An answer a person may give an asked record.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Offer {
    #[default]
    Approve,
    Decline,
    /// Approve, and grant the asker the action on every resource of its type.
    ApproveAndGrant,
}

impl Offer {
    /// What a question showing `facts` offers, in the order they are shown: approve, approve
    /// and grant where there is a resource type to name and an agent or an app to grant it
    /// to, and decline.
    #[must_use]
    pub fn of(facts: &AskedFacts) -> Vec<Self> {
        let mut offers = vec![Self::Approve];
        if facts.plural.is_some()
            && facts.choices.is_empty()
            && !matches!(facts.by, AskedBy::Device(_) | AskedBy::Program { .. })
        {
            offers.push(Self::ApproveAndGrant);
        }
        offers.push(Self::Decline);
        offers
    }
}

/// The arguments of [`RESOLVE`]: the person's answer, and for a question that offers choices
/// the one they picked, by its place among [`AskedFacts::choices`].
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Resolve {
    pub resolution: Offer,
    #[serde(default)]
    pub choice: Option<usize>,
    /// The choices picked, for a question that offers many ([`AskedFacts::many`]).
    #[serde(default, deserialize_with = "none_is_empty")]
    pub chosen: Vec<usize>,
    /// What the person typed, one entry per take, in order ([`AskedFacts::takes`]). A secret
    /// one is never written anywhere: the record and its history keep the answer without it.
    #[serde(default, deserialize_with = "none_is_empty")]
    pub typed: Vec<String>,
    /// The files picked, as URIs ([`AskedFacts::files`]).
    #[serde(default, deserialize_with = "none_is_empty")]
    pub files: Vec<String>,
    /// What the person changed in the call before approving, each a field of
    /// [`AskedFacts::form`] set to what they wrote: the call runs with its arguments so changed,
    /// admitted again as a fresh call with them would be, so the action's own contract checks
    /// them. Only with an approve.
    #[serde(
        default,
        deserialize_with = "none_is_empty",
        skip_serializing_if = "Vec::is_empty"
    )]
    pub edits: Vec<crate::DraftEdit>,
}

/// A list a caller left out as nothing (`null`, as a view passes an option it did not give)
/// read as an empty one.
fn none_is_empty<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: Deserialize<'de>,
{
    Ok(Option::<Vec<T>>::deserialize(deserializer)?.unwrap_or_default())
}

impl Resolve {
    /// This answer as the record and its history may keep it: what was typed for a secret
    /// take of `facts` left out.
    #[must_use]
    pub fn kept(&self, facts: &AskedFacts) -> Self {
        let typed = self
            .typed
            .iter()
            .enumerate()
            .filter(|(at, _)| facts.takes.get(*at).is_none_or(|take| !take.secret))
            .map(|(_, typed)| typed.clone())
            .collect();
        Self {
            typed,
            ..self.clone()
        }
    }
}

/// Go on where the person approved `request`; else refuse it until they do, showing them
/// `facts`: what a provider whose action needs their yes does, and all it does. The dispatch
/// that carried the call keeps it as its asked record, and an approve brings it back once,
/// the same call, carrying [`super::InvokeRequest::approval`].
///
/// # Errors
/// [`super::ActionCallError::ConfirmationRequired`] with `facts`, for a call nobody approved.
pub fn approved_or_asks(
    request: &super::InvokeRequest,
    facts: impl FnOnce() -> AskedFacts,
) -> Result<(), super::ActionCallError> {
    if request.approval().is_some() {
        Ok(())
    } else {
        Err(super::ActionCallError::asks(facts()))
    }
}

/// Whether `target` answers an asked record ([`RESOLVE`]).
#[must_use]
pub fn is_resolve(target: &RemoteActionTarget) -> bool {
    target.provider == super::workspace_invocations::PROVIDER && target.address.action == RESOLVE
}

/// The person a call by `caller` asks when it waits for a yes: the person it acts for, else
/// the person calling. Never the person of the device that carried the connection.
#[must_use]
pub fn asked_person(caller: &super::Caller) -> Option<String> {
    caller
        .acting_for_person()
        .or_else(|| caller.acting().person_id())
        .filter(|person| !person.is_empty())
        .map(str::to_owned)
}

/// The person `caller` answers as: a person acting themselves, or a view acting for the
/// person it was opened for. An agent, a bot, an automation or an app answers for nobody,
/// whoever it acts for: the confirmation is always the system's.
#[must_use]
pub fn answering_person(caller: &super::Caller) -> Option<&str> {
    let acting = caller.acting();
    if acting.is_agent() || acting.is_bot() || acting.is_automation() || acting.app.is_some() {
        return None;
    }
    acting.person_id().filter(|person| !person.is_empty())
}

/// Whether `call` is the call `kept`: the same target and the same arguments, as they travel.
/// Where `call` carries a person's approve that changed the arguments ([`Approval::arguments`]),
/// it is the kept call with those in place of its own, and with the arguments its record kept
/// none of ([`KeptAsk::sealed`]), which the approve never shows, as `kept` carries them.
#[must_use]
pub fn same_call(kept: &super::InvokeRequest, call: &super::InvokeRequest) -> bool {
    let value = |target: &super::RemoteActionTarget, argument: &super::InvokeArgument| {
        serde_json::to_value((target, argument)).ok()
    };
    let edited = call
        .approval()
        .and_then(|approval| approval.arguments.as_deref().cloned())
        .map(|mut edited| {
            if let (super::InvokeArgument::Json(kept), super::InvokeArgument::Json(sent)) =
                (&kept.argument, &call.argument)
            {
                for name in sent.keys() {
                    if !edited.contains_key(name)
                        && let Some(value) = kept.get(name)
                    {
                        edited.insert(name.clone(), value.clone());
                    }
                }
            }
            super::InvokeArgument::Json(edited)
        });
    let kept = value(&kept.target, edited.as_ref().unwrap_or(&kept.argument));
    matches!((kept, value(&call.target, &call.argument)), (Some(a), Some(b)) if a == b)
}

/// The dispatch that keeps a call waiting in its asked record, as the person's answer reaches
/// it: the only place a call carrying their approve is admitted again.
pub trait AskedDispatch: Send + Sync {
    /// What this dispatch needs, beside the call and its caller, to admit `invocation` again
    /// once it no longer remembers it (the host restarted): kept with its record.
    fn context(&self, invocation: super::InvocationId) -> serde_json::Value;

    /// The window a person's press asked `invocation` in, where it did: kept with its record, so
    /// the question stands over that window. `None` for a call no press asked (an agent's).
    fn pressed(&self, invocation: super::InvocationId) -> Option<Pressed> {
        let _ = invocation;
        None
    }

    /// Admit `request` again under its id for `caller`, who asked for it, carrying the person's
    /// approve ([`super::InvokeRequest::approval`]): only where it still waits in its asked
    /// record for the same call, or, where this dispatch no longer remembers it, as a new call
    /// under that id, with `context` ([`Self::context`]). It runs under `caller`'s grants as
    /// they stand now, and how it goes reaches `caller` as every invocation of theirs does.
    ///
    /// # Errors
    /// Why it was not admitted again.
    fn readmit(
        &self,
        caller: &super::Caller,
        request: super::InvokeRequest,
        context: &serde_json::Value,
    ) -> Result<(), super::ActionCallError>;

    /// End `invocation`, which `caller` asked for, declined by the person: `caller` is told so.
    /// One this dispatch no longer remembers ended already.
    ///
    /// # Errors
    /// Why it could not be ended.
    fn declined(
        &self,
        caller: &super::Caller,
        invocation: super::InvocationId,
    ) -> Result<(), super::ActionCallError>;

    /// Whether this dispatch runs nothing on its person's answer: the asker makes the call again
    /// itself (an app's own process), so the answer is the grant that call is decided by. Its
    /// person's approve then writes a grant for one use, and their decline a refusal, both where
    /// their app permissions show and change them.
    fn runs_nothing(&self) -> bool {
        false
    }

    /// End `invocation`, which `caller` asked for, withdrawn by whoever asked it before its
    /// person answered ([`AskedStore::withdraw`]): it ends cancelled, saying `message`.
    fn withdrawn(&self, caller: &super::Caller, invocation: super::InvocationId, message: &str) {
        let _ = (caller, invocation, message);
    }
}

/// The action of a record's read the person is asked about: an app's join of another app's
/// record, waiting as `<record>#read` in its asked record ([`AskedReads`]).
pub const READ: &str = "read";

/// Where a read the person is asked about waits for them: as its asked record, an invocation of
/// the record's [`READ`] that they answer as every asked call.
pub trait AskedReads: Send + Sync {
    /// Keep `caller`'s read of `address`, which the app `app` reads for them, as its asked record
    /// showing `facts`: allowed once the person approves it, refused when they decline it or
    /// it is withdrawn.
    fn ask_read(
        &self,
        caller: &super::Caller,
        app: &str,
        address: &super::ResourceAddress,
        facts: AskedFacts,
    ) -> super::Pending<super::Decided>;
}

/// An asked record as the host keeps it in its own state: the call that waits, who asked it,
/// what its person is shown, and what its dispatch needs to admit it again, so the call waits
/// across the host's restarts.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
// A kept record grows: a build reads what a later one wrote, so unknown fields are let through.
#[serde(rename_all = "camelCase")]
pub struct KeptAsk {
    pub at: RecordRef,
    /// The person asked, their root key in hex.
    pub person: String,
    pub caller: super::KeptCaller,
    pub request: super::InvokeRequest,
    pub facts: AskedFacts,
    pub asked_at_ms: u64,
    /// The dispatch that keeps the call, by the name it gave the store.
    pub dispatch: String,
    /// What that dispatch needs to admit it again ([`AskedDispatch::context`]).
    pub context: serde_json::Value,
    /// The device that took the call to run it, its key in hex, once the person answered it
    /// there ([`AT_ROOT`]): written before it runs, so that device resumes it after a restart.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub taken: Option<String>,
    /// How the call ended where it ran ([`AT_ROOT`]): what the device that asked shows, after
    /// which it forgets the record.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outcome: Option<crate::InvocationUpdate>,
    /// The call's arguments as its person changed them when they approved it
    /// ([`Resolve::edits`]), beside the call as it was asked ([`Self::request`]): what runs, and
    /// what a device that takes it again after a restart runs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edited: Option<serde_json::Map<String, serde_json::Value>>,
    /// The window a person's press asked it in ([`AskedDispatch::pressed`]), so its question
    /// stands over that window also after a restart.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pressed: Option<Pressed>,
    /// The arguments [`Self::request`] carried that the record keeps none of, those its action
    /// declares secret ([`super::secret_arguments`]), by name: their values are held in the memory
    /// of the device that asked alone, and a call kept from before it started again cannot run.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sealed: Vec<String>,
}

/// Where a host keeps the asked records that wait, across its restarts: each kept once it is
/// written, and forgotten once it is answered, in that order. The host reads what it kept back
/// when it starts ([`AskedStore::keep_through`]).
pub trait AskedKeeping: Send + Sync {
    /// Keep `ask`, in place of the one kept under its record.
    fn keep(&self, ask: &KeptAsk);

    /// Forget the record `at`: it waits no more.
    fn forget(&self, at: &RecordRef);
}

/// What writes the grant a person gives with an approve
/// ([`Offer::ApproveAndGrant`]): an ordinary grant of the workspace's policy, shown and taken
/// back as every grant is.
pub trait AskedGrants: Send + Sync {
    /// Write `grant` in `workspace`, given by `person` (their root key, hex).
    ///
    /// # Errors
    /// Why it was not written: refused where it reaches beyond what `person` may grant.
    fn grant(
        &self,
        workspace: &str,
        person: &str,
        grant: tilo_action_policy::Grant,
    ) -> super::Pending<Result<(), String>>;
}

/// Where the call was pressed, when a person's press asked it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Pressed {
    /// The device the press was on, by its id.
    pub device: String,
    pub app: String,
    /// The window's tab key, as the session publishes it (`device.Window.key`).
    pub instance: String,
    pub resource: String,
    /// Where in that window the press was, as the compositor that delivered it saw it: the
    /// question stands there, its answer under the press. `None` for a press it gave no point
    /// for (a key).
    #[serde(default)]
    pub at: Option<PressPoint>,
}

/// A point in a window, in its logical pixels from its top-left corner.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PressPoint {
    pub x: i32,
    pub y: i32,
}

/// One question that waits for the person, as the reading of its workspace's invocations
/// carries it: an asked invocation record they may answer with `<record>#resolve`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Asked {
    /// The record: what `resolve` is called on.
    pub record: RecordRef,
    /// The workspace the asked call acts in.
    pub workspace: String,
    /// That workspace by its name.
    pub workspace_name: String,
    /// The app whose action is asked.
    pub app: String,
    /// The action, `<app>#<action>`.
    pub action: String,
    /// The action by its published label.
    pub name: String,
    /// Since when it waits, in milliseconds since the Unix epoch.
    pub asked_at_ms: u64,
    #[serde(default)]
    pub pressed: Option<Pressed>,
    pub offers: Vec<Offer>,
    #[serde(flatten)]
    pub facts: AskedFacts,
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, reason = "in a test this is the assertion")]

    use super::*;

    /// A row reads as a client binds it: camel case, its facts beside the
    /// record's own names.
    #[test]
    fn a_row_reads_as_a_client_binds_it() {
        let row = Asked {
            record: RecordRef {
                workspace: "acme".into(),
                record: "invocations/7".into(),
                device: None,
            },
            workspace: "acme".into(),
            workspace_name: "Acme".into(),
            app: "clocks".into(),
            action: "clocks#set-alarm".into(),
            name: "Set alarm".into(),
            asked_at_ms: 9,
            pressed: None,
            offers: Vec::new(),
            facts: AskedFacts {
                verb: "set".into(),
                plural: Some("alarms".into()),
                ..AskedFacts::by(AskedBy::Agent(Named {
                    id: "scout".into(),
                    name: "Scout".into(),
                }))
            }
            .with_fact("At", "07:00"),
        };
        let row = Asked {
            offers: Offer::of(&row.facts),
            ..row
        };
        let json = serde_json::to_value(&row).unwrap();
        assert_eq!(
            json,
            serde_json::json!({
                "record": {"workspace": "acme", "record": "invocations/7"},
                "workspace": "acme",
                "workspaceName": "Acme",
                "app": "clocks",
                "action": "clocks#set-alarm",
                "name": "Set alarm",
                "askedAtMs": 9,
                "pressed": null,
                "offers": ["approve", "approve_and_grant", "decline"],
                "by": {"agent": {"id": "scout", "name": "Scout"}},
                "words": "",
                "on": null,
                "facts": [{"label": "At", "value": "07:00"}],
                "effects": [],
                "destructive": false,
                "choices": [],
                "verb": "set",
                "plural": "alarms",
                "conversation": null,
                "takes": [],
                "answeredBy": null,
                "retry": null,
                "files": null,
                "many": false,
                "kind": "",
                "effect": null,
                "form": [],
            })
        );
        assert_eq!(serde_json::from_value::<Asked>(json).unwrap(), row);
    }

    /// The facts travel by position as a refusal does: every part is written
    /// whether or not it holds anything.
    #[test]
    fn facts_travel_by_position() {
        let facts = AskedFacts::by(AskedBy::Device(Named {
            id: "d".into(),
            name: "Laptop".into(),
        }))
        .with_fact("To", "https://visa.example");
        let wire = postcard::to_allocvec(&facts).unwrap();
        assert_eq!(postcard::from_bytes::<AskedFacts>(&wire).unwrap(), facts);
    }
}