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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
//! A workspace's activity as the session serves it: what changed since this
//! device last looked, the full history, and the replay of its layout.
//!
//! The session keeps the history index of every workspace on this device and
//! serves it under [`PROVIDER`] as resource [`RESOURCE`]. Its reads are live
//! views ([`crate::ExecutionMode::Live`]): an app follows [`FEED`],
//! [`SUMMARY`], [`REPLAY`] and [`DETAIL`] and gets a new result whenever the
//! workspace's history moves. Its writes are ordinary actions on the same
//! resource: naming, splitting and merging work groups, undoing and
//! restoring, opening what a change touched, and marking what was seen.
//!
//! What this device has seen stays with the session: [`MARK_VIEWED`] moves
//! its own frontier, never a shared record.
//!
//! Changes are addressed by their history id ([`Entry::id`]), 32 lowercase
//! hex digits, and a range of changes by its first and last ([`Range`]) in
//! the order [`Feed::entries`] lists them.

use serde::{Deserialize, Serialize};

use super::{InvokeArgument, RemoteActionTarget};
use crate::api::ActionAddress;

/// The provider the session serves workspace activity under.
pub const PROVIDER: &str = "tilo.activity";
/// The application whose window shows it, and whose grants reach it.
pub use tilo_app_id::apps::ACTIVITY as APP_ID;
/// The resource every action is an action of.
pub const RESOURCE: &str = "workspace.activity";

/// Live: the workspace's history, filtered by a [`FeedQuery`]; answers [`Feed`].
pub const FEED: &str = "feed";
/// Live: what changed since this device last looked; answers [`Summary`].
pub const SUMMARY: &str = "summary";
/// Live: the workspace's layout at each recent change; answers [`Replay`].
pub const REPLAY: &str = "replay";
/// Live: what a range of changes did and what can be done with it, given a
/// [`DetailQuery`]; answers [`Detail`].
pub const DETAIL: &str = "detail";
/// Live: what the person last asked to be shown from outside the app, until
/// an app shows it; answers an optional [`Focus`].
pub const FOCUS: &str = "focus";
/// Live: every agent session the history holds, each as the timeline of the
/// actions it took, given a [`SessionsQuery`]; answers [`Sessions`].
pub const SESSIONS: &str = "sessions";
/// Every line a command an agent ran printed, given the [`CommandExecution`] its
/// [`ActionView::Command`] names; answers [`SessionOutput`].
pub const SESSION_OUTPUT: &str = "session-output";

/// Mark the changes [`Viewed`] names as seen on this device.
pub const MARK_VIEWED: &str = "mark-viewed";
/// Say the [`Focus`] with the serial [`Focused`] names was shown.
pub const FOCUSED: &str = "focused";
/// Name, rename or un-name a range of changes ([`Name`]).
pub const NAME: &str = "name";
/// Split the named work group a [`Range`] sits in at its start.
pub const SPLIT: &str = "split";
/// Merge the named work groups a [`Range`] spans.
pub const MERGE: &str = "merge";
/// Move the boundary between two work sessions ([`Boundary`]).
pub const MOVE_BOUNDARY: &str = "move-boundary";
/// Undo a [`Range`] of changes.
pub const UNDO: &str = "undo";
/// Restore the workspace to before a [`Range`] of changes.
pub const RESTORE: &str = "restore";
/// Undo the agent session a [`Range`] belongs to.
pub const UNDO_SESSION: &str = "undo-session";
/// Undo one record's share of that session ([`ResourceQuery`]).
pub const UNDO_RECORD: &str = "undo-record";
/// Open a [`Target`] in its app.
pub const OPEN: &str = "open";
/// Choose, or stop choosing, the resource a [`Range`] changed as a morning
/// source of this device.
pub const CHOOSE_SOURCE: &str = "choose-source";
/// Run a [`SourceCommand`] on a chosen morning source.
pub const SOURCE: &str = "source";

/// The target of action `action` of [`RESOURCE`].
#[must_use]
pub fn target(action: &str) -> RemoteActionTarget {
    RemoteActionTarget {
        provider: PROVIDER.to_owned(),
        address: ActionAddress::new(RESOURCE, action),
    }
}

/// The argument an invocation carrying `value` sends.
#[must_use]
pub fn argument(value: &impl Serialize) -> InvokeArgument {
    match serde_json::to_value(value) {
        Ok(serde_json::Value::Object(map)) => InvokeArgument::Json(map),
        _ => InvokeArgument::None,
    }
}

/// Which workspaces' changes are shown.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Scope {
    /// The workspace's own changes, and ones belonging to no single workspace.
    #[default]
    ThisWorkspace,
    /// Every workspace on this device, each change labelled with its own.
    AllWorkspaces,
}

/// How far back the feed reaches.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Period {
    #[default]
    AllTime,
    Today,
    Week,
    Month,
}

/// What a [`FEED`] reads.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct FeedQuery {
    pub scope: Scope,
    pub period: Period,
    /// Only this person's changes, by the name [`Feed::people`] lists.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    /// Only the changes of this lens, by [`Lens::key`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lens: Option<String>,
    /// Only the changes to the resources one window of an app keeps: what the
    /// app's own History lists.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resources: Option<WindowResources>,
    /// The newest this many changes; `0` for the first page.
    pub limit: usize,
}

/// The resources one window of an app keeps: its own, and the chains of parts
/// it keeps beside it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct WindowResources {
    /// The app whose resources they are, by id.
    pub app: String,
    /// The window's own resource and each chain it keeps, by document id. A
    /// part of one of these chains, or a chunk of one of these resources, is
    /// the window's too.
    pub resources: Vec<String>,
    /// Only the changes to this item of them (a note, a task), by the id its
    /// actions name it by.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub item: Option<String>,
}

/// How many changes a feed answers when its query asks for no number.
pub const FEED_PAGE: usize = 200;

impl FeedQuery {
    /// Whether this query reads only resources of `app` in the workspace its
    /// caller works in: what an app may read as the person using it.
    #[must_use]
    pub fn reads_only_resources_of(&self, app: &str) -> bool {
        self.scope == Scope::ThisWorkspace
            && self
                .resources
                .as_ref()
                .is_some_and(|resources| resources.app == app)
    }

    /// How many changes the feed answers.
    #[must_use]
    pub const fn page(&self) -> usize {
        if self.limit == 0 {
            FEED_PAGE
        } else {
            self.limit
        }
    }
}

/// Who an author is to the person reading.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Relation {
    /// The reader themselves.
    Reader,
    /// Another person.
    #[default]
    Person,
    /// Software acting for someone: an agent, a Shortcut, an app.
    Software,
}

/// Who made a change.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Author {
    /// The name it goes by: a person's, an agent's own — the reader's account
    /// name too, since the line that names the author words the reader as
    /// "You" from [`Relation`]. A name, never a sentence: a row that says whom
    /// software acted for words that line once, from the facts beside it.
    pub name: String,
    /// The colour presence paints them in, `[r, g, b]`.
    pub rgb: [u8; 3],
    /// A short fragment of their key, telling apart two of the same name.
    pub identity: String,
    pub relation: Relation,
    /// For software: who it acted for, as a sentence names them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub on_behalf_of: Option<String>,
    /// For software: the member it is, an agent by its id and its person.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub member: Option<crate::MemberId>,
    /// The person it acted for is the reader.
    pub for_reader: bool,
    /// The task that named it, as it was called then.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task: Option<String>,
}

/// What kind of change an entry is.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Kind {
    #[default]
    Text,
    Move,
    Details,
    Comment,
    Delete,
    Restore,
    Access,
    Compaction,
    Redaction,
}

/// A resource a change touched, and where it opens.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Target {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app_label: Option<String>,
    pub id: String,
    pub kind: String,
    pub label: String,
}

/// A device that refused one of a change's writes, and why.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Refusal {
    /// The change it refused, by its history id.
    pub change: String,
    /// The refusing device, by its key.
    pub device: String,
    /// What the person calls that device.
    pub label: String,
    /// Why the write is not there, as the refusing device put it.
    pub reason: String,
    /// Whether waiting will change nothing: the device will not take the
    /// write, whatever the person does short of what the reason names.
    pub permanent: bool,
}

/// One change.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Entry {
    pub id: String,
    /// Its id in the history of the resource it changed, where that is not [`Self::id`]: what the
    /// app keeping the resource names the change by.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub change: Option<String>,
    pub author: Author,
    pub kind: Kind,
    /// When, in milliseconds since the Unix epoch.
    pub at_ms: i64,
    pub summary: String,
    /// What it did, as its action recorded it (the app, the resource, the item and the step):
    /// a reader that has the app's own words says it in them rather than in [`Self::summary`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step: Option<crate::ActionContext>,
    /// The workspace it belongs to, under [`Scope::AllWorkspaces`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace: Option<String>,
    /// The app it was made in, as a person names it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app: Option<String>,
    /// The resource it changed, as its own title names it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource: Option<String>,
    /// The named work group it sits in, by [`Group::id`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
    /// Whether its content was redacted.
    pub redacted: bool,
    /// The devices that refused it, so its author reads where it is not.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub refused: Vec<Refusal>,
}

/// A named range of changes.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Group {
    /// The naming record; a rename addresses it.
    pub id: String,
    pub label: String,
    /// Its oldest change.
    pub start: String,
    /// Its newest change; `None` while it is still open.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end: Option<String>,
    /// Who named it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub named_by: Option<String>,
}

/// A way to narrow the feed: an app, a resource, a work group.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Lens {
    /// What [`FeedQuery::lens`] names it by.
    pub key: String,
    pub label: String,
}

/// The workspace's history, as a [`FeedQuery`] narrows it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Feed {
    /// The workspace's name.
    pub workspace: String,
    pub scope: Scope,
    /// Changes the query matches, of which [`Self::entries`] holds the
    /// newest.
    pub total: usize,
    /// Newest first.
    pub entries: Vec<Entry>,
    pub groups: Vec<Group>,
    /// Everyone who changed something, in the order they first did.
    pub people: Vec<String>,
    pub lenses: Vec<Lens>,
    /// The history is still being read.
    pub pending: bool,
    /// Whether this device can change the history here: name, undo,
    /// restore.
    pub mutations: bool,
}

/// Where in the app a [`Focus`] opens.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum View {
    /// What changed since this device last looked.
    #[default]
    WhatsNew,
    /// Every change, filtered and selected as the focus says.
    History,
    /// The workspace played back change by change.
    Replay,
}

/// What to show, asked for outside the app: the glance in the top bar, a
/// file's own history, a command naming a view. Each ask has its own `serial`; the app that shows it
/// says so ([`FOCUSED`]), and it is not offered again.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Focus {
    pub serial: u64,
    pub view: View,
    /// Only this person's changes, as [`FeedQuery::author`] names them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    /// Only this lens's changes, as [`FeedQuery::lens`] names it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lens: Option<String>,
    /// This change, selected.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entry: Option<String>,
}

/// One action of a work session's evidence.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct BriefAction {
    pub author: Author,
    pub summary: String,
    pub at_ms: i64,
}

/// A work session: related changes told as an outcome.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Brief {
    pub title: String,
    /// Who and how much, in the history's own words.
    pub detail: String,
    pub authors: Vec<Author>,
    pub apps: Vec<String>,
    pub resources: Vec<String>,
    pub changes: usize,
    /// Oldest first.
    pub actions: Vec<BriefAction>,
    pub first_ms: i64,
    pub last_ms: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
    /// The record of a person-corrected session; only such a session's
    /// boundary moves.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub work_session: Option<String>,
    /// The changes it tells of.
    pub entries: Vec<String>,
}

/// Where the reader left off.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Resume {
    pub target: Target,
    pub author: Author,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app: Option<String>,
    pub at_ms: i64,
}

/// A resource this device chose to hear about each morning.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Source {
    /// What [`SourceRequest::key`] names it by.
    pub key: String,
    pub label: String,
    /// What its app says about it now; empty when it says nothing.
    pub text: String,
    /// Whether its app refreshes it on request.
    pub refreshable: bool,
    /// How the last command on it went.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
}

/// What changed since this device last looked.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Summary {
    pub workspace: String,
    /// Newest first.
    pub briefs: Vec<Brief>,
    /// The briefs told in a sentence by a model on this device.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub narrative: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resume: Option<Resume>,
    /// Whether these are the changes made while the reader was away.
    pub away: bool,
    /// Whether morning sources can be chosen here.
    pub sources_available: bool,
    pub sources: Vec<Source>,
    /// The history is still being read.
    pub pending: bool,
}

/// One group of tabs in a replayed workspace.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ReplayGroup {
    pub tabs: Vec<String>,
    /// The tab it showed, by index into [`Self::tabs`].
    pub active: usize,
    /// Its share of the strip, in thousandths.
    pub width_permille: u32,
}

/// A workspace as it was.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ReplayWorkspace {
    pub name: String,
    pub groups: Vec<ReplayGroup>,
}

/// Someone's pointer as it was.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ReplayPointer {
    pub name: String,
    pub rgb: [u8; 3],
}

/// The layout after one change.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Frame {
    pub entry: String,
    pub author: Author,
    pub summary: String,
    pub at_ms: i64,
    pub workspaces: Vec<ReplayWorkspace>,
    pub pointers: Vec<ReplayPointer>,
}

/// The workspace's layout at each recent change.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Replay {
    /// Oldest first.
    pub frames: Vec<Frame>,
    /// Changes whose layout could not be read back.
    pub unavailable: usize,
    /// What the replay cannot show, said once.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// The history is still being read.
    pub pending: bool,
}

/// A range of changes, by its first and last in feed order.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Range {
    pub from: String,
    pub to: String,
}

impl Range {
    /// The range of the one change `id`.
    #[must_use]
    pub fn one(id: &str) -> Self {
        Self {
            from: id.to_owned(),
            to: id.to_owned(),
        }
    }
}

/// What a [`DETAIL`] reads.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct DetailQuery {
    pub range: Range,
    /// Also compare the workspace before and after the session.
    pub compare: bool,
}

/// What can be done with a range of changes, and which action does it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DetailAction {
    Open,
    Compare,
    Restore,
    Undo,
    Split,
    Merge,
    ChooseSource,
    UndoEntry,
    /// Undo the whole agent session.
    UndoSession,
}

impl DetailAction {
    /// The action of [`RESOURCE`] that does it; [`DetailAction::Compare`]
    /// is a [`DetailQuery`] of its own.
    #[must_use]
    pub const fn action(self) -> &'static str {
        match self {
            Self::Open => OPEN,
            Self::Compare => DETAIL,
            Self::Restore => RESTORE,
            Self::Undo => UNDO,
            Self::UndoSession => UNDO_SESSION,
            Self::UndoEntry => UNDO_RECORD,
            Self::Split => SPLIT,
            Self::Merge => MERGE,
            Self::ChooseSource => CHOOSE_SOURCE,
        }
    }
}

/// An offered action, worded for the session it acts on.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Offer {
    pub action: DetailAction,
    pub label: String,
}

/// The agent session a change belongs to.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Session {
    /// The instruction, as the person phrased it.
    pub instruction: String,
    /// Who ran it and who asked, as a sentence.
    pub byline: String,
    /// Why the agent did what it did.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decision: Option<String>,
    /// The records it changed, each with what it did there.
    pub records: Vec<SessionRecord>,
    /// Why it cannot be undone from here, when it cannot.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub undo_blocked: Option<String>,
    /// How its undo went, while one runs or once it ended.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub undo_status: Option<String>,
    /// The records its undo did not reach, one sentence each: reported,
    /// never left out of what the person is told happened.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub unreverted: Vec<String>,
}

/// A record an agent session changed.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SessionRecord {
    /// The record, as its title names it.
    pub record: String,
    /// The app it belongs to.
    pub app: String,
    /// The record's own id, which [`ResourceQuery`] names to undo just it.
    pub id: String,
    /// The app's id, which [`ResourceQuery`] names to undo just it.
    pub app_id: String,
    /// What the session did to it, as a sentence.
    pub change: String,
    /// The action that undoes this record's share of the session, when the
    /// document is open here; absent when it cannot be undone on its own.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub undo: Option<Offer>,
}

/// One record of an agent session, as [`UNDO_RECORD`] names it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ResourceQuery {
    /// The session, by its range in the history.
    pub range: Range,
    /// The session, by the task it worked (`task:<id>`, or a Tasks issue's address), in place
    /// of [`Self::range`]: what a view that follows the task rather than the history (the agent
    /// composer) names it by.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task: Option<String>,
    /// The record inside that session.
    pub app_id: String,
    pub id: String,
    /// The one change inside that record to take back, as its own history names it; absent to
    /// take back the session's whole share of the record.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub step: Option<String>,
}

/// What comparing the workspace before and after a session found.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "kebab-case")]
pub enum Comparison {
    /// What changed, one line each.
    Changes { lines: Vec<String> },
    /// The workspace's state either side could not be read.
    Unavailable,
}

/// One field a range of changes changed, with what it held either side of it.
///
/// [`Comparison::Changes`] says a field changed; this says what it changed
/// from and to, which is the question "compare before and after" is asked
/// for.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct FieldChange {
    /// The field's name as the person reads it ("Title").
    pub field: String,
    /// What it held before; empty when it was not there.
    pub before: String,
    /// What it holds after; empty when it was removed.
    pub after: String,
}

/// What a range of changes did.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Detail {
    pub title: String,
    /// Who, where and why, in the history's own words.
    pub provenance: String,
    pub authors: Vec<String>,
    pub resources: Vec<Target>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group_label: Option<String>,
    pub offers: Vec<Offer>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<Session>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub comparison: Option<Comparison>,
    /// The fields the session changed, with what they held either side: empty
    /// when the provider could not read both states.
    pub changes: Vec<FieldChange>,
    /// The session is no longer in the history (an undo or a filter moved it).
    pub gone: bool,
}

/// What a [`SESSIONS`] reads.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SessionsQuery {
    pub scope: Scope,
    /// The newest this many sessions; `0` for the first page.
    pub limit: usize,
    /// The newest this many of each session's changes still in effect; `0` for the first page.
    pub changes: usize,
}

/// How many sessions a [`SESSIONS`] read answers when its query asks for no number.
pub const SESSIONS_PAGE: usize = 50;

/// How many of a session's changes still in effect a [`SESSIONS`] read answers when its query
/// asks for no number.
pub const SESSION_CHANGES_PAGE: usize = 20;

impl SessionsQuery {
    /// How many sessions the read answers.
    #[must_use]
    pub const fn page(&self) -> usize {
        if self.limit == 0 {
            SESSIONS_PAGE
        } else {
            self.limit
        }
    }

    /// How many of each session's changes still in effect the read answers.
    #[must_use]
    pub const fn changes_page(&self) -> usize {
        if self.changes == 0 {
            SESSION_CHANGES_PAGE
        } else {
            self.changes
        }
    }
}

/// What one action of a session shows when it is opened: every action an agent
/// takes has a view of its own, so none of them is opaque.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ActionView {
    /// A file it changed: its path, and the lines either side when the provider
    /// read them. Without lines the view reads them with a [`DETAIL`]
    /// comparison of the action's range.
    File {
        target: Target,
        path: String,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        lines: Vec<DiffLine>,
    },
    /// A command line it ran in a shell, with what came of it: the shell
    /// session's own record of the execution ([`CommandExecution`]), never a copy.
    Command {
        target: Target,
        /// The command line, as the shell ran it.
        command: String,
        /// The directory it ran in.
        #[serde(default, skip_serializing_if = "String::is_empty")]
        cwd: String,
        /// The last lines it printed, without terminal escapes.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        output: Vec<String>,
        /// It printed more than `output` holds; the rest is
        /// read with [`SESSION_OUTPUT`].
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        more: bool,
        /// How the program ended; `None` while it runs or when unknown.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        exit: Option<i32>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        started_ms: Option<i64>,
        /// When it ended; `None` while it runs.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        ended_ms: Option<i64>,
        /// The execution record, once the shell ran it.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        execution: Option<CommandExecution>,
    },
    /// A web page it opened or acted on.
    Page {
        target: Target,
        url: String,
        /// The page's title, when it had one.
        #[serde(default, skip_serializing_if = "String::is_empty")]
        title: String,
    },
    /// A record of an app it changed.
    Record { target: Target },
}

impl ActionView {
    /// Whether it is a command its shell has not finished running.
    #[must_use]
    pub const fn is_running(&self) -> bool {
        matches!(
            self,
            Self::Command {
                ended_ms: None,
                execution: Some(_),
                ..
            }
        )
    }

    /// The resource the action touched, where it opens.
    #[must_use]
    pub const fn target(&self) -> &Target {
        match self {
            Self::File { target, .. }
            | Self::Command { target, .. }
            | Self::Page { target, .. }
            | Self::Record { target } => target,
        }
    }
}

/// One line of a file's change.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiffLine {
    pub side: DiffSide,
    pub text: String,
}

/// Which side of a change a [`DiffLine`] is on.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DiffSide {
    /// Unchanged, shown for its context.
    Both,
    Removed,
    Added,
}

/// One action of an agent session: what it did in one record, and the view
/// that shows it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionAction {
    /// Its changes, which [`UNDO`] takes back on their own.
    pub range: Range,
    /// How many changes `range` is: an action that wrote four paragraphs in one note is one
    /// action of four changes.
    pub changes: usize,
    pub at_ms: i64,
    /// What it did, as a sentence.
    pub summary: String,
    pub view: ActionView,
    /// The app and record it changed, as [`ResourceQuery`] names them to undo
    /// just this action.
    pub app_id: String,
    pub record: String,
    /// The action that undoes this record's share of the session alone, when
    /// it can be undone on its own here.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub undo: Option<Offer>,
}

/// One of a session's changes still in effect: what it changed, where, and how to open it and
/// take it back.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SessionChange {
    /// The change, as a range of one in the history.
    pub range: Range,
    /// The change in its record's own history, which its undo names as the step.
    pub step: String,
    pub at_ms: i64,
    /// What it changed, as a sentence.
    pub summary: String,
    /// The app and record it changed.
    pub app_id: String,
    pub record: String,
    /// The resource it touched, where it opens.
    pub target: Target,
    /// The action that undoes this change alone, when it can be undone on its own here.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub undo: Option<Offer>,
}

/// One agent session: an instruction it worked, and the actions it took for
/// it, oldest first.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentSession {
    /// The session's record, as the history keeps it.
    pub id: String,
    /// The agent, and who it acted for.
    pub agent: Author,
    /// The workspace it worked in, under [`Scope::AllWorkspaces`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace: Option<String>,
    /// What it was asked, as the person phrased it.
    pub instruction: String,
    /// Why it did what it did, when it said.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decision: Option<String>,
    pub started_ms: i64,
    /// When it last acted.
    pub last_ms: i64,
    /// Every change it made, which [`UNDO_SESSION`] takes back.
    pub range: Range,
    pub actions: Vec<SessionAction>,
    /// Its changes still in effect, newest first: what the session still leaves in place, each
    /// undone on its own. A page of [`Self::changes_total`].
    pub in_effect: Vec<SessionChange>,
    /// How many of its changes are still in effect.
    pub changes_total: usize,
    /// Why it cannot be undone from here, when it cannot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub undo_blocked: Option<String>,
    /// What it is doing now, or did last: a command still running, else its
    /// newest action. A reader shows it only for a session that is working.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub now: Option<Now>,
}

impl AgentSession {
    /// How many changes the session made to records and files, as a person counts what it changed:
    /// each of its edits, not the commands it ran or the pages it read. What its card and the
    /// notice that it finished both say.
    #[must_use]
    pub fn changes(&self) -> usize {
        self.actions
            .iter()
            .filter(|action| {
                matches!(
                    action.view,
                    ActionView::File { .. } | ActionView::Record { .. }
                )
            })
            .map(|action| action.changes.max(1))
            .sum()
    }
}

/// What a session is doing at the moment it is read.
///
/// Written as derived; read through one `serde_json::Value` ([`Now::read`]),
/// which takes the same JSON. A derived reader of an internally tagged enum
/// buffers the value and is compiled again for every reader it meets: a
/// large share of the code a page loads first, for a handful of fields.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Now {
    /// A command line it asked a shell to run, which has not ended.
    Running { command: String, since_ms: i64 },
    /// A file it changed last.
    Editing { path: String, at_ms: i64 },
    /// A web page it opened or acted on last.
    Browsing {
        url: String,
        #[serde(default, skip_serializing_if = "String::is_empty")]
        title: String,
        at_ms: i64,
    },
    /// A record of an app it changed last, as its action says it.
    Changing { summary: String, at_ms: i64 },
    /// A command it ran last, which ended.
    Ran { command: String, at_ms: i64 },
}

impl<'de> Deserialize<'de> for Now {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = <serde_json::Value as Deserialize>::deserialize(deserializer)?;
        Self::read(&value).map_err(serde::de::Error::custom)
    }
}

impl Now {
    /// The moment `value` writes: `{"kind": .., ..fields}`.
    #[inline(never)]
    fn read(value: &serde_json::Value) -> Result<Self, String> {
        let field = |name: &str| value.get(name);
        let text = |name: &str| {
            field(name)
                .and_then(serde_json::Value::as_str)
                .map(str::to_owned)
                .ok_or_else(|| format!("missing field `{name}`"))
        };
        let millis = |name: &str| {
            field(name)
                .and_then(serde_json::Value::as_i64)
                .ok_or_else(|| format!("missing field `{name}`"))
        };
        let kind = field("kind")
            .and_then(serde_json::Value::as_str)
            .ok_or("missing field `kind`")?;
        Ok(match kind {
            "running" => Self::Running {
                command: text("command")?,
                since_ms: millis("since_ms")?,
            },
            "editing" => Self::Editing {
                path: text("path")?,
                at_ms: millis("at_ms")?,
            },
            "browsing" => Self::Browsing {
                url: text("url")?,
                title: if field("title").is_some() {
                    text("title")?
                } else {
                    String::new()
                },
                at_ms: millis("at_ms")?,
            },
            "changing" => Self::Changing {
                summary: text("summary")?,
                at_ms: millis("at_ms")?,
            },
            "ran" => Self::Ran {
                command: text("command")?,
                at_ms: millis("at_ms")?,
            },
            other => return Err(format!("unknown variant `{other}`")),
        })
    }
}

/// Where a command's execution is recorded: the shell session's record and
/// the execution in it. Terminal keeps every execution a session ran there,
/// with its command, directory, exit status, times and output.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CommandExecution {
    /// The workspace the session's record is in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace: Option<String>,
    /// The app that keeps the session's record.
    pub app_id: String,
    /// The session's record.
    pub record: String,
    /// The execution, an item of the session's executions.
    pub execution: String,
}

/// Everything an execution printed, as [`SESSION_OUTPUT`] reads it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SessionOutput {
    /// Its lines, without terminal escapes, at most [`SESSION_OUTPUT_LINES`].
    pub lines: Vec<String>,
    /// It printed more than the lines hold, or more than its shell kept.
    pub truncated: bool,
    /// The execution is not known here, or its output has not reached this device.
    pub unavailable: bool,
    /// The execution has not ended.
    pub running: bool,
}

/// The most lines a [`SESSION_OUTPUT`] read answers: its newest.
pub const SESSION_OUTPUT_LINES: usize = 10_000;
/// The most lines an [`ActionView::Command`] carries.
pub const COMMAND_TAIL_LINES: usize = 12;

/// Every agent session a [`SessionsQuery`] reads, newest first.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Sessions {
    pub sessions: Vec<AgentSession>,
    /// Sessions the query matches, of which [`Self::sessions`] holds the newest.
    pub total: usize,
    /// The history is still being read.
    pub pending: bool,
    /// Whether this device can undo here.
    pub mutations: bool,
}

/// Which [`Focus`] [`FOCUSED`] says was shown.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Focused {
    pub serial: u64,
}

/// What [`MARK_VIEWED`] marks: the changes the reader was shown.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Viewed {
    pub entries: Vec<String>,
    /// Count them seen once the reader stops following [`SUMMARY`], rather
    /// than now: the summary they are reading stays as it is until then.
    pub later: bool,
}

/// What [`NAME`] writes. An empty label removes the name.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Name {
    pub range: Range,
    /// The naming record a rename replaces.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub record: Option<String>,
    pub label: String,
}

/// Which way a [`Boundary`] moves.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Toward {
    /// The older session's newest change joins the newer session.
    #[default]
    Newer,
    /// The newer session's oldest change joins the older session.
    Older,
}

/// What [`MOVE_BOUNDARY`] moves: the boundary between the two adjacent
/// work sessions holding `older` and `newer`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Boundary {
    /// A change of the older session.
    pub older: String,
    /// A change of the newer session.
    pub newer: String,
    pub toward: Toward,
}

/// A command on a chosen morning source.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SourceCommand {
    #[default]
    Open,
    Remove,
    Refresh,
    DraftRefresh,
    NextSource,
}

/// What [`SOURCE`] runs.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SourceRequest {
    pub key: String,
    pub command: SourceCommand,
}

/// A change's history id from its [`Entry::id`].
#[must_use]
pub fn entry_id(hex: &str) -> Option<[u8; 16]> {
    let mut bytes = [0_u8; 16];
    hex::decode_to_slice(hex, &mut bytes).ok()?;
    Some(bytes)
}

/// The [`Entry::id`] of history id `bytes`.
#[must_use]
pub fn entry_hex(bytes: &[u8; 16]) -> String {
    hex::encode(bytes)
}

/// The history id of a change, as [`Entry::id`] spells it.
#[must_use]
pub fn change_hex(change: &[u8; 32]) -> String {
    hex::encode(&change[..16])
}

#[cfg(test)]
mod tests {
    use super::*;

    tilo_test_env::scenario! {
        fn workspace_activity_reads_back_as_written;

        phase every_moment_reads_back_as_written_and_a_bare_page_has_no_title;
        {
            let moments = [
                Now::Running {
                    command: "cargo test".into(),
                    since_ms: -3,
                },
                Now::Editing {
                    path: "src/lib.rs".into(),
                    at_ms: 4,
                },
                Now::Browsing {
                    url: "https://example.org".into(),
                    title: "Example".into(),
                    at_ms: 5,
                },
                Now::Browsing {
                    url: "https://example.org".into(),
                    title: String::new(),
                    at_ms: 6,
                },
                Now::Changing {
                    summary: "Renamed a note".into(),
                    at_ms: 7,
                },
                Now::Ran {
                    command: "ls".into(),
                    at_ms: 8,
                },
            ];
            for now in moments {
                let written = serde_json::to_string(&now).unwrap();
                assert_eq!(
                    serde_json::from_str::<Now>(&written).unwrap(),
                    now,
                    "{written}"
                );
                let value = serde_json::to_value(&now).unwrap();
                assert_eq!(serde_json::from_value::<Now>(value).unwrap(), now);
            }
            assert!(serde_json::from_str::<Now>(r#"{"kind":"sleeping","at_ms":1}"#).is_err());
            assert!(serde_json::from_str::<Now>(r#"{"kind":"ran","at_ms":1}"#).is_err());
            assert_eq!(
                serde_json::from_str::<Now>(r#"{"kind":"ran","command":"ls","at_ms":1,"more":0}"#)
                    .unwrap(),
                Now::Ran {
                    command: "ls".into(),
                    at_ms: 1
                },
                "a field a newer writer adds is passed over"
            );
        }

        phase an_entry_id_reads_back_from_its_hex_and_nothing_else_does;
        {
            let id = [7_u8; 16];
            assert_eq!(entry_id(&entry_hex(&id)), Some(id));
            assert_eq!(entry_id("07"), None);
            assert_eq!(entry_id(&"zz".repeat(16)), None);
        }

        phase a_query_reads_back_and_an_empty_one_asks_for_the_first_page;
        {
            let query = FeedQuery {
                scope: Scope::AllWorkspaces,
                period: Period::Week,
                author: Some("Ada".into()),
                lens: Some("app:so.tilo.notes".into()),
                resources: Some(WindowResources {
                    app: "so.tilo.notes".into(),
                    resources: vec!["window:0000000000000000".into()],
                    item: Some("note-1".into()),
                }),
                limit: 400,
            };
            let InvokeArgument::Json(map) = argument(&query) else {
                panic!("a query is an object");
            };
            let read: FeedQuery = serde_json::from_value(serde_json::Value::Object(map)).unwrap();
            assert_eq!(read, query);
            assert_eq!(FeedQuery::default().page(), FEED_PAGE);
            assert!(!query.reads_only_resources_of("so.tilo.notes"), "every workspace's is no app's own");
            let here = FeedQuery { scope: Scope::ThisWorkspace, ..query };
            assert!(here.reads_only_resources_of("so.tilo.notes"));
            assert!(!here.reads_only_resources_of("so.tilo.chat"), "Notes' resources are not Chat's");
            assert!(!FeedQuery::default().reads_only_resources_of("so.tilo.notes"));
        }
    }
}