1use serde::{Deserialize, Serialize};
12
13use crate::InvocationId;
14use crate::entry::{ActionItem, Described, Did, PathStep};
15use crate::key::ActionKind;
16use tilo_action_policy::{Acting, Actor};
17
18pub const CHANGE_MESSAGE_PREFIX: &str = "tilo.entry/3 ";
22
23pub const CONTINUATION_PREFIX: &str = "tilo.cont/3 ";
32
33#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(remote = "Self", default)]
35pub struct ActionContext {
36 #[serde(skip_serializing_if = "Option::is_none")]
38 pub app: Option<ActionApp>,
39 #[serde(skip_serializing_if = "Option::is_none")]
40 pub resource: Option<ActionResource>,
41 #[serde(skip_serializing_if = "Option::is_none")]
44 pub item: Option<ActionItem>,
45 #[serde(skip_serializing_if = "Option::is_none")]
47 pub what: Option<Did>,
48 #[serde(skip_serializing_if = "Option::is_none")]
51 pub kind: Option<ActionKind>,
52 #[serde(skip_serializing_if = "Option::is_none")]
54 pub purpose: Option<String>,
55 #[serde(skip_serializing_if = "Option::is_none")]
57 pub group: Option<WorkGroup>,
58 #[serde(skip_serializing_if = "Vec::is_empty")]
60 pub facets: Vec<ActionFacet>,
61 #[serde(skip_serializing_if = "Option::is_none")]
64 pub invoker: Option<ActionInvoker>,
65 #[serde(skip_serializing_if = "Option::is_none")]
69 pub source_invocation: Option<InvocationId>,
70 #[serde(skip_serializing_if = "Option::is_none")]
76 pub signed: Option<Box<crate::remote::SignedCall>>,
77 #[serde(skip_serializing_if = "Option::is_none")]
79 pub caused_by: Option<Cause>,
80 #[serde(skip_serializing_if = "Option::is_none")]
89 pub action: Option<crate::EncodedAction>,
90 #[serde(skip_serializing_if = "Option::is_none")]
95 pub compensation: Option<crate::EncodedAction>,
96 #[serde(skip_serializing_if = "Option::is_none")]
101 pub gesture: Option<crate::ActionId>,
102 #[serde(skip_serializing_if = "ChangeKind::is_content")]
107 pub change: ChangeKind,
108 #[serde(default, skip_serializing_if = "Vec::is_empty")]
113 pub shows: Vec<crate::remote::asked::Fact>,
114 #[serde(skip_serializing_if = "Option::is_none")]
119 pub approval: Option<crate::remote::asked::Approval>,
120 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
126 pub pressed: bool,
127}
128
129read_through_json_value!(ActionContext);
130
131fn ambient_gesture(gesture: crate::ActionId, group: Option<&WorkGroup>) -> crate::ActionId {
135 recorded_gesture(
136 gesture,
137 group.map(|group| (group.kind.as_str(), group.id.as_str())),
138 )
139}
140
141#[must_use]
146pub fn recorded_gesture(gesture: crate::ActionId, run: Option<(&str, &str)>) -> crate::ActionId {
147 let mut hasher = blake3::Hasher::new_derive_key("tilo ambient gesture v1");
148 hasher.update(gesture.0.as_bytes());
149 if let Some((kind, id)) = run {
150 for part in [kind, id] {
151 hasher.update(&u64::try_from(part.len()).unwrap_or(u64::MAX).to_le_bytes());
152 hasher.update(part.as_bytes());
153 }
154 }
155 let id = *hasher
156 .finalize()
157 .as_bytes()
158 .first_chunk::<16>()
159 .unwrap_or(&[0; 16]);
160 crate::ActionId(uuid::Builder::from_custom_bytes(id).into_uuid())
161}
162
163impl Clone for ActionContext {
166 fn clone(&self) -> Self {
167 Self {
168 app: self.app.clone(),
169 resource: self.resource.clone(),
170 item: self.item.clone(),
171 what: self.what.clone(),
172 kind: self.kind,
173 purpose: self.purpose.clone(),
174 group: self.group.clone(),
175 facets: self.facets.clone(),
176 invoker: self.invoker.clone(),
177 source_invocation: self.source_invocation,
178 signed: self.signed.clone(),
179 caused_by: self.caused_by.clone(),
180 action: self.action.clone(),
181 compensation: self.compensation.clone(),
182 gesture: self.gesture,
183 change: self.change,
184 shows: self.shows.clone(),
185 approval: self.approval.clone(),
186 pressed: self.pressed,
187 }
188 }
189}
190
191pub const COMPENSATION_BUDGET: usize = 128 * 1024;
194
195pub const WHOLE_ACTION_BUDGET: usize = 256 * 1024;
201
202pub const HISTORY_BUDGET: usize = 1024 * 1024;
205
206#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
211pub enum ChangeKind {
212 #[default]
215 Content,
216 Housekeeping,
219 External,
225}
226
227impl ChangeKind {
228 pub const fn is_content(&self) -> bool {
229 matches!(self, Self::Content)
230 }
231
232 pub const fn is_step(&self) -> bool {
235 self.is_content()
236 }
237}
238
239impl ActionContext {
240 #[must_use]
243 pub fn enriched_by(mut self, ambient: &Self) -> Self {
244 if self.app.is_none() {
245 self.app.clone_from(&ambient.app);
246 }
247 if self.resource.is_none() {
248 self.resource.clone_from(&ambient.resource);
249 }
250 if self.item.is_none() {
251 self.item.clone_from(&ambient.item);
252 }
253 if self.purpose.is_none() {
254 self.purpose.clone_from(&ambient.purpose);
255 }
256 if self.group.is_none() {
257 self.group.clone_from(&ambient.group);
258 }
259 if self.invoker.is_none() {
260 self.invoker.clone_from(&ambient.invoker);
261 }
262 if self.source_invocation.is_none() {
263 self.source_invocation = ambient.source_invocation;
264 }
265 if self.signed.is_none() {
266 self.signed.clone_from(&ambient.signed);
267 }
268 if self.caused_by.is_none() {
269 self.caused_by.clone_from(&ambient.caused_by);
270 }
271 if self.gesture.is_none() {
277 self.gesture = ambient
278 .gesture
279 .map(|gesture| ambient_gesture(gesture, ambient.group.as_ref()));
280 }
281 for facet in &ambient.facets {
282 if !self.facets.contains(facet) {
283 self.facets.push(facet.clone());
284 }
285 }
286 self
287 }
288
289 #[must_use]
294 pub fn with_source_invocation(mut self, invocation: Option<InvocationId>) -> Self {
295 self.source_invocation = invocation;
296 self
297 }
298
299 #[must_use]
301 pub fn with_caused_by(mut self, cause: Option<Cause>) -> Self {
302 self.caused_by = cause;
303 self
304 }
305
306 pub fn for_resource(
307 id: impl Into<String>,
308 kind: impl Into<String>,
309 label: impl Into<String>,
310 ) -> Self {
311 Self::of_resource(ActionResource {
312 id: id.into(),
313 kind: kind.into(),
314 label: label.into(),
315 })
316 }
317
318 #[inline(never)]
322 fn of_resource(resource: ActionResource) -> Self {
323 Self {
324 resource: Some(resource),
325 ..Self::default()
326 }
327 }
328
329 pub fn for_app(id: impl Into<String>, label: impl Into<String>) -> Self {
331 Self::default().with_app(id, label)
332 }
333
334 #[must_use]
335 pub fn with_app(mut self, id: impl Into<String>, label: impl Into<String>) -> Self {
336 self.app = Some(ActionApp {
337 id: id.into(),
338 label: label.into(),
339 });
340 self
341 }
342
343 #[must_use]
344 pub fn with_purpose(mut self, purpose: impl Into<String>) -> Self {
345 let purpose = purpose.into();
346 self.purpose = nonempty(&purpose);
347 self
348 }
349
350 #[must_use]
351 pub fn with_group(
352 mut self,
353 id: impl Into<String>,
354 label: impl Into<String>,
355 kind: impl Into<String>,
356 ) -> Self {
357 self.group = Some(WorkGroup {
358 id: id.into(),
359 label: Some(label.into()),
360 kind: kind.into(),
361 declared_id: None,
362 session: None,
363 });
364 self
365 }
366
367 #[must_use]
368 pub fn with_invoker(mut self, invoker: ActionInvoker) -> Self {
369 self.invoker = Some(invoker);
370 self
371 }
372
373 #[must_use]
377 pub fn with_host_actor(mut self, actor: &Acting, presence: Option<PresenceId>) -> Self {
378 let mut invoker = ActionInvoker::admitted(actor);
379 invoker.presence = presence;
380 self.invoker = Some(invoker);
381 self
382 }
383
384 #[must_use]
385 pub fn with_facet(mut self, facet: ActionFacet) -> Self {
386 self.facets.push(facet);
387 self
388 }
389
390 #[must_use]
393 pub fn in_step(mut self) -> Self {
394 if self.gesture.is_none() {
395 self.gesture = crate::executor::current_step();
396 }
397 self
398 }
399
400 #[must_use]
402 pub fn in_gesture(mut self, gesture: Option<crate::ActionId>) -> Self {
403 self.gesture = gesture;
404 self
405 }
406
407 #[must_use]
408 pub fn with_change(mut self, change: ChangeKind) -> Self {
409 self.change = change;
410 self
411 }
412
413 #[must_use]
415 pub fn with_described(mut self, described: Described) -> Self {
416 self.what = Some(described.what);
417 if described.item.is_some() {
418 self.item = described.item;
419 }
420 self
421 }
422
423 pub fn described(&self) -> Option<Described> {
425 Some(Described {
426 what: self.what.clone()?,
427 item: self.item.clone(),
428 })
429 }
430
431 pub fn is_housekeeping(&self) -> bool {
433 self.change == ChangeKind::Housekeeping
434 }
435
436 pub fn is_activity(&self) -> bool {
439 self.change.is_content()
440 }
441
442 pub fn acting(&self) -> Option<&Acting> {
444 self.invoker.as_ref().map(|invoker| &invoker.acting)
445 }
446
447 #[must_use]
452 pub fn whole_edit_by(acting: &Acting) -> String {
453 Self::default()
454 .with_invoker(ActionInvoker::admitted(acting))
455 .change_message()
456 .unwrap_or_default()
457 }
458
459 pub fn change_message(&self) -> Option<String> {
462 if self == &Self::default() {
463 return None;
464 }
465 serde_json::to_value(wire::Entry::of(self))
466 .ok()
467 .map(|entry| format!("{CHANGE_MESSAGE_PREFIX}{}", crate::compact::encode(&entry)))
468 }
469
470 pub fn from_change_message(message: &str) -> Option<Self> {
477 Self::of_label(crate::stamp::Stamp::read(message)?)
478 }
479
480 pub fn head_of_change_message(message: &str) -> Option<Self> {
487 Self::of_label(crate::stamp::Stamp::read_head(message)?)
488 }
489
490 fn of_label((label, stamp): (crate::stamp::Label, crate::stamp::Stamp)) -> Option<Self> {
493 matches!(
494 label,
495 crate::stamp::Label::Entry | crate::stamp::Label::Stamp
496 )
497 .then(|| stamp.action_context())
498 }
499
500 #[must_use]
505 pub fn continuation_of(&self, first: &Self) -> Option<String> {
506 let gesture = self.gesture?;
507 let action = self.action.as_ref()?;
508 let earlier = first.action.as_ref()?;
509 let bare = |entry: &Self| Self {
510 action: None,
511 gesture: None,
512 ..entry.clone()
513 };
514 if self.compensation.is_some()
515 || first.compensation.is_some()
516 || action.type_id != earlier.type_id
517 || bare(self) != bare(first)
518 {
519 return None;
520 }
521 let claim = ContinuedAction::token(self)?;
522 let now = std::str::from_utf8(&action.payload).ok()?;
523 let then = std::str::from_utf8(&earlier.payload).ok()?;
524 let kept = now
525 .char_indices()
526 .zip(then.chars())
527 .find(|((_, now), then)| now != then)
528 .map_or_else(|| now.len().min(then.len()), |((at, _), _)| at);
529 let (now_rest, then_rest) = (now.get(kept..)?, then.get(kept..)?);
530 let tail: usize = now_rest
531 .chars()
532 .rev()
533 .zip(then_rest.chars().rev())
534 .take_while(|(now, then)| now == then)
535 .map(|(now, _)| now.len_utf8())
536 .sum();
537 let middle = now_rest.get(..now_rest.len().checked_sub(tail)?)?;
538 Some(format!(
539 "{CONTINUATION_PREFIX}{} {claim} {kept} {tail} {middle}",
540 gesture_token(gesture)
541 ))
542 }
543
544 #[must_use]
546 pub fn continued_gesture(message: &str) -> Option<crate::ActionId> {
547 let rest = message.strip_prefix(CONTINUATION_PREFIX)?;
548 gesture_of(rest.split(' ').next()?)
549 }
550
551 #[must_use]
554 pub fn continued(message: &str, first: &Self) -> Option<Self> {
555 let rest = message.strip_prefix(CONTINUATION_PREFIX)?;
556 let mut parts = rest.splitn(3, ' ');
557 let gesture = gesture_of(parts.next()?)?;
558 let _claim = parts.next()?;
559 let mut diff = parts.next()?.splitn(3, ' ');
560 let kept = diff.next()?.parse::<usize>().ok()?;
561 let tail = diff.next()?.parse::<usize>().ok()?;
562 let earlier = first.action.as_ref()?;
563 let then = std::str::from_utf8(&earlier.payload).ok()?;
564 let payload = [
565 then.get(..kept)?,
566 diff.next()?,
567 then.get(then.len().checked_sub(tail)?..)?,
568 ]
569 .concat();
570 Some(Self {
571 action: Some(crate::EncodedAction {
572 type_id: earlier.type_id.clone(),
573 payload: payload.into_bytes(),
574 }),
575 gesture: Some(gesture),
576 ..first.clone()
577 })
578 }
579}
580
581#[derive(Clone, Debug, PartialEq, Eq)]
588pub enum ContinuedAction {
589 Edit {
590 kind: String,
591 path: Vec<PathStep>,
592 },
593 Verb {
594 action: crate::ActionKey,
595 item: Option<String>,
596 },
597}
598
599impl ContinuedAction {
600 fn token(entry: &ActionContext) -> Option<String> {
603 let edit = |path: &[PathStep]| Self::Edit {
604 kind: entry
605 .resource
606 .as_ref()
607 .map_or_else(String::new, |resource| resource.kind.clone()),
608 path: path.to_vec(),
609 };
610 let action = match &entry.what {
611 Some(Did::Verb(verb)) => Self::Verb {
612 action: verb.action.clone(),
613 item: entry.item.as_ref().map(|item| item.id.clone()),
614 },
615 Some(Did::Edit(changed)) => edit(&changed.path),
616 None => edit(&[]),
617 Some(_) => return None,
618 };
619 let mut token = action.write()?;
620 if let Some(invoker) = &entry.invoker {
624 let tree = serde_json::to_value(&invoker.acting).ok()?;
625 token.push(INVOKER_MARK);
626 token.push_str(&hex::encode(crate::compact::encode(&tree)));
627 }
628 Some(token)
629 }
630
631 #[must_use]
635 pub fn invoker_of_message(message: &str) -> Option<crate::Acting> {
636 let rest = message.strip_prefix(CONTINUATION_PREFIX)?;
637 let (_, invoker) = rest.split(' ').nth(1)?.split_once(INVOKER_MARK)?;
638 let text = crate::compact::decode(std::str::from_utf8(&hex::decode(invoker).ok()?).ok()?)?;
639 serde_json::from_str(&text).ok()
640 }
641
642 #[must_use]
644 pub fn of_message(message: &str) -> Option<Self> {
645 let rest = message.strip_prefix(CONTINUATION_PREFIX)?;
646 let token = rest.split(' ').nth(1)?;
647 Self::parse(
648 token
649 .split_once(INVOKER_MARK)
650 .map_or(token, |(claim, _)| claim),
651 )
652 }
653
654 fn write(&self) -> Option<String> {
656 fn name(text: &str) -> Option<&str> {
658 (!text.contains([' ', ':', '/', INVOKER_MARK])).then_some(text)
659 }
660 fn write_step(token: &mut String, at: usize, step: &PathStep) -> Option<()> {
661 if at > 0 {
662 token.push('/');
663 }
664 let (tag, text) = match step {
665 PathStep::Field(field) => ('f', name(field)?),
666 PathStep::Item(id) => ('i', name(id)?),
667 PathStep::Key(key) => ('k', name(key)?),
668 PathStep::Cell(row, column) => {
669 token.push('c');
670 token.push_str(name(row)?);
671 token.push(':');
672 token.push_str(name(column)?);
673 return Some(());
674 }
675 };
676 token.push(tag);
677 token.push_str(text);
678 Some(())
679 }
680 let mut token = String::new();
681 match self {
682 Self::Edit { kind, path } => {
683 token.push_str("e:");
684 token.push_str(name(kind)?);
685 token.push(':');
686 for (at, step) in path.iter().enumerate() {
687 write_step(&mut token, at, step)?;
688 }
689 }
690 Self::Verb { action, item } => {
691 token.push_str("v:");
692 for part in [&action.app, &action.kind, &action.action] {
693 token.push_str(name(part)?);
694 token.push('/');
695 }
696 token.pop();
697 if let Some(item) = item {
698 token.push(':');
699 token.push_str(name(item)?);
700 }
701 }
702 }
703 Some(token)
704 }
705
706 fn parse(token: &str) -> Option<Self> {
708 fn read_step(step: &str) -> Option<PathStep> {
709 let (tag, rest) = step.split_at_checked(1)?;
710 Some(match tag {
711 "f" => PathStep::Field(rest.to_owned()),
712 "i" => PathStep::Item(rest.to_owned()),
713 "k" => PathStep::Key(rest.to_owned()),
714 "c" => {
715 let (row, column) = rest.split_once(':')?;
716 PathStep::Cell(row.to_owned(), column.to_owned())
717 }
718 _ => return None,
719 })
720 }
721 let (tag, rest) = token.split_once(':')?;
722 Some(match tag {
723 "e" => {
724 let (kind, path) = rest.split_once(':')?;
725 let path = if path.is_empty() {
726 Vec::new()
727 } else {
728 path.split('/').map(read_step).collect::<Option<Vec<_>>>()?
729 };
730 Self::Edit {
731 kind: kind.to_owned(),
732 path,
733 }
734 }
735 "v" => {
736 let (app, rest) = rest.split_once('/')?;
737 let (kind, rest) = rest.split_once('/')?;
738 let (action, item) = match rest.split_once(':') {
739 Some((action, item)) => (action, Some(item.to_owned())),
740 None => (rest, None),
741 };
742 Self::Verb {
743 action: crate::ActionKey::new(app, kind, action),
744 item,
745 }
746 }
747 _ => return None,
748 })
749 }
750}
751
752const INVOKER_MARK: char = '~';
755
756fn gesture_token(gesture: crate::ActionId) -> String {
759 crate::compact::encode(&serde_json::Value::String(
760 gesture.0.hyphenated().to_string(),
761 ))
762}
763
764fn gesture_of(token: &str) -> Option<crate::ActionId> {
766 let text = crate::compact::decode(token)?;
767 let text = serde_json::from_str::<String>(&text).ok()?;
768 uuid::Uuid::try_parse(&text).ok().map(crate::ActionId)
769}
770
771pub(crate) fn entry_of_message(message: &str) -> Option<ActionContext> {
775 let entry = crate::compact::json_of(message.strip_prefix(CHANGE_MESSAGE_PREFIX)?)?;
776 let entry: serde_json::Value = serde_json::from_slice(&entry).ok()?;
777 serde_json::from_value::<wire::Entry>(entry)
778 .ok()
779 .map(wire::Entry::into_context)
780}
781
782pub(crate) fn entry_head_of_message(message: &str) -> Option<ActionContext> {
785 let entry = crate::compact::json_of(message.strip_prefix(CHANGE_MESSAGE_PREFIX)?)?;
786 serde_json::from_slice::<wire::Head>(&entry)
787 .ok()
788 .map(wire::Head::into_context)
789}
790
791mod wire {
798 use serde::{Deserialize, Serialize};
799
800 use super::{
801 ActionApp, ActionContext, ActionFacet, ActionInvoker, ActionItem, ActionResource, Cause,
802 ChangeKind, WorkGroup,
803 };
804 use crate::entry::{Did, PathStep};
805 use crate::key::ActionKind;
806
807 #[derive(Default, Serialize, Deserialize)]
808 #[serde(default)]
809 pub(super) struct Entry {
810 #[serde(rename = "p", skip_serializing_if = "Option::is_none")]
811 app: Option<ActionApp>,
812 #[serde(rename = "r", skip_serializing_if = "Option::is_none")]
813 resource: Option<Resource>,
814 #[serde(rename = "i", skip_serializing_if = "Option::is_none")]
815 item: Option<Item>,
816 #[serde(rename = "w", skip_serializing_if = "Option::is_none")]
817 what: Option<Did>,
818 #[serde(rename = "wp", skip_serializing_if = "Option::is_none")]
820 shared_path: Option<Vec<PathStep>>,
821 #[serde(rename = "k", skip_serializing_if = "Option::is_none")]
822 kind: Option<ActionKind>,
823 #[serde(rename = "pu", skip_serializing_if = "Option::is_none")]
824 purpose: Option<String>,
825 #[serde(rename = "gr", skip_serializing_if = "Option::is_none")]
826 group: Option<WorkGroup>,
827 #[serde(rename = "f", skip_serializing_if = "Vec::is_empty")]
828 facets: Vec<ActionFacet>,
829 #[serde(
830 rename = "by",
831 skip_serializing_if = "Option::is_none",
832 deserialize_with = "readable"
833 )]
834 invoker: Option<ActionInvoker>,
835 #[serde(rename = "s", skip_serializing_if = "Option::is_none")]
836 source_invocation: Option<crate::InvocationId>,
837 #[serde(rename = "sc", skip_serializing_if = "Option::is_none")]
838 signed: Option<Box<crate::remote::SignedCall>>,
839 #[serde(rename = "cb", skip_serializing_if = "Option::is_none")]
840 caused_by: Option<Cause>,
841 #[serde(rename = "a", skip_serializing_if = "Option::is_none")]
842 action: Option<Action>,
843 #[serde(rename = "u", skip_serializing_if = "Option::is_none")]
844 compensation: Option<Action>,
845 #[serde(rename = "g", skip_serializing_if = "Option::is_none")]
846 gesture: Option<String>,
847 #[serde(rename = "c", skip_serializing_if = "ChangeKind::is_content")]
848 change: ChangeKind,
849 #[serde(rename = "sh", default, skip_serializing_if = "Vec::is_empty")]
850 shows: Vec<crate::remote::asked::Fact>,
851 }
852
853 #[derive(Default, Deserialize)]
856 #[serde(default)]
857 pub(super) struct Head<'a> {
858 #[serde(rename = "k", borrow)]
859 kind: Option<&'a serde_json::value::RawValue>,
860 #[serde(rename = "gr", borrow)]
861 group: Option<&'a serde_json::value::RawValue>,
862 #[serde(rename = "by", borrow)]
863 invoker: Option<&'a serde_json::value::RawValue>,
864 #[serde(rename = "s", borrow)]
865 invocation: Option<&'a serde_json::value::RawValue>,
866 #[serde(rename = "a", borrow)]
869 action: Option<&'a serde_json::value::RawValue>,
870 #[serde(rename = "g", borrow)]
871 gesture: Option<&'a serde_json::value::RawValue>,
872 #[serde(rename = "c", borrow)]
873 change: Option<&'a serde_json::value::RawValue>,
874 }
875
876 fn field<T: serde::de::DeserializeOwned>(
879 raw: Option<&serde_json::value::RawValue>,
880 ) -> Option<T> {
881 let value = serde_json::from_slice::<serde_json::Value>(raw?.get().as_bytes()).ok()?;
882 serde_json::from_value(value).ok()
883 }
884
885 impl Head<'_> {
886 pub(super) fn into_context(self) -> ActionContext {
887 ActionContext {
888 kind: field(self.kind).or_else(|| self.action.map(|_| ActionKind::Undoable)),
889 group: field(self.group),
890 invoker: field(self.invoker),
891 source_invocation: field(self.invocation),
892 gesture: field::<String>(self.gesture)
893 .and_then(|gesture| uuid::Uuid::try_parse(&gesture).ok())
894 .map(crate::ActionId),
895 change: field(self.change).unwrap_or_default(),
896 ..ActionContext::default()
897 }
898 }
899 }
900
901 #[derive(Serialize, Deserialize)]
904 #[serde(untagged)]
905 enum Action {
906 Json(String, serde_json::Value),
907 Bytes { t: String, b: Vec<u8> },
908 }
909
910 impl Action {
911 fn of(action: &crate::EncodedAction) -> Self {
912 serde_json::from_slice::<serde_json::Value>(&action.payload)
913 .ok()
914 .filter(|value| {
915 serde_json::to_vec(value).is_ok_and(|bytes| bytes == action.payload)
916 })
917 .map_or_else(
918 || Self::Bytes {
919 t: action.type_id.clone(),
920 b: action.payload.clone(),
921 },
922 |value| Self::Json(action.type_id.clone(), value),
923 )
924 }
925
926 fn into_encoded(self) -> Option<crate::EncodedAction> {
927 Some(match self {
928 Self::Json(type_id, value) => crate::EncodedAction {
929 type_id,
930 payload: serde_json::to_vec(&value).ok()?,
931 },
932 Self::Bytes { t, b } => crate::EncodedAction {
933 type_id: t,
934 payload: b,
935 },
936 })
937 }
938 }
939
940 #[derive(Serialize, Deserialize)]
943 #[serde(untagged)]
944 enum Resource {
945 Full(String, String, String),
946 Root(String, String),
947 }
948
949 impl Resource {
950 fn of(resource: &ActionResource) -> Self {
951 if resource.id == resource.kind {
952 Self::Root(resource.kind.clone(), resource.label.clone())
953 } else {
954 Self::Full(
955 resource.id.clone(),
956 resource.kind.clone(),
957 resource.label.clone(),
958 )
959 }
960 }
961
962 fn into_resource(self) -> ActionResource {
963 match self {
964 Self::Full(id, kind, label) => ActionResource { id, kind, label },
965 Self::Root(kind, label) => ActionResource {
966 id: kind.clone(),
967 kind,
968 label,
969 },
970 }
971 }
972 }
973
974 #[derive(Serialize, Deserialize)]
977 #[serde(untagged)]
978 enum Item {
979 Full(String, String),
980 Named((String,)),
981 }
982
983 impl Item {
984 fn of(item: &ActionItem, resource: Option<&ActionResource>) -> Self {
985 let named = resource.is_some_and(|resource| {
986 !item.id.is_empty()
987 && !item.id.contains('/')
988 && resource
989 .id
990 .strip_suffix(item.id.as_str())
991 .is_some_and(|rest| rest.ends_with('/'))
992 });
993 if named {
994 Self::Named((item.label.clone(),))
995 } else {
996 Self::Full(item.id.clone(), item.label.clone())
997 }
998 }
999
1000 fn into_item(self, resource: Option<&ActionResource>) -> ActionItem {
1001 match self {
1002 Self::Full(id, label) => ActionItem { id, label },
1003 Self::Named((label,)) => ActionItem {
1004 id: resource
1005 .and_then(|resource| resource.id.rsplit('/').next())
1006 .unwrap_or_default()
1007 .to_owned(),
1008 label,
1009 },
1010 }
1011 }
1012 }
1013
1014 fn readable<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
1018 where
1019 D: serde::Deserializer<'de>,
1020 T: serde::de::DeserializeOwned,
1021 {
1022 let value = serde_json::Value::deserialize(deserializer)?;
1023 Ok(serde_json::from_value(value).ok())
1024 }
1025
1026 fn trimmed(what: &Did) -> Did {
1030 let mut what = what.clone();
1031 trim(&mut what);
1032 what
1033 }
1034
1035 fn trim(what: &mut Did) {
1036 match what {
1037 Did::Edit(edit) if matches!(edit.path.as_slice(), [PathStep::Field(field)] if *field == edit.field) =>
1038 {
1039 edit.path.clear();
1040 }
1041 Did::Group(group) => {
1042 if group.count as usize == group.members.len()
1043 && distinct_of(&group.members) == group.distinct
1044 {
1045 group.distinct.clear();
1046 }
1047 group.members.iter_mut().for_each(trim);
1048 }
1049 _ => {}
1050 }
1051 }
1052
1053 fn filled(mut what: Did) -> Did {
1054 fill(&mut what);
1055 what
1056 }
1057
1058 fn fill(what: &mut Did) {
1059 match what {
1060 Did::Edit(edit) if edit.path.is_empty() => {
1061 edit.path.push(PathStep::Field(edit.field.clone()));
1062 }
1063 Did::Group(group) => {
1064 group.members.iter_mut().for_each(fill);
1065 if group.distinct.is_empty() && group.count as usize == group.members.len() {
1066 group.distinct = distinct_of(&group.members);
1067 }
1068 }
1069 _ => {}
1070 }
1071 }
1072
1073 fn action_paths(
1077 action: Option<&crate::EncodedAction>,
1078 what: &Did,
1079 ) -> Option<Vec<Option<Vec<PathStep>>>> {
1080 fn path_of(stamped: &serde_json::Value) -> Option<Vec<PathStep>> {
1081 serde_json::from_value(stamped.get("op")?.get("args")?.get("path")?.clone()).ok()
1082 }
1083 let action = action?;
1084 let value: serde_json::Value = serde_json::from_slice(&action.payload).ok()?;
1085 let paths: Vec<Option<Vec<PathStep>>> = if crate::group_form::is_group(&action.type_id) {
1086 crate::group_form::members(value)?
1087 .iter()
1088 .map(path_of)
1089 .collect()
1090 } else {
1091 vec![path_of(&value)]
1092 };
1093 let fits = match what {
1094 Did::Edit(_) => paths.len() == 1,
1095 Did::Group(group) => paths.len() == group.members.len(),
1096 _ => false,
1097 };
1098 (fits && paths.iter().any(Option::is_some)).then_some(paths)
1099 }
1100
1101 fn paths_from_action(what: &Did, paths: &[Option<Vec<PathStep>>]) -> Did {
1106 let mut what = what.clone();
1107 let mut members: Vec<&mut Did> = match &mut what {
1108 Did::Group(group) => {
1109 if group.count as usize == group.members.len()
1110 && distinct_of(&group.members) == group.distinct
1111 {
1112 group.distinct.clear();
1113 }
1114 group.members.iter_mut().collect()
1115 }
1116 single => vec![single],
1117 };
1118 for (member, path) in members.iter_mut().zip(paths) {
1119 if let Did::Edit(edit) = member
1120 && path.as_ref() == Some(&edit.path)
1121 {
1122 edit.path.clear();
1123 }
1124 }
1125 what
1126 }
1127
1128 fn paths_given_back(mut what: Did, paths: &[Option<Vec<PathStep>>]) -> Did {
1130 let members: Vec<&mut Did> = match &mut what {
1131 Did::Group(group) => group.members.iter_mut().collect(),
1132 single => vec![single],
1133 };
1134 for (member, path) in members.into_iter().zip(paths) {
1135 if let (Did::Edit(edit), Some(path)) = (member, path)
1136 && edit.path.is_empty()
1137 {
1138 edit.path.clone_from(path);
1139 }
1140 }
1141 what
1142 }
1143
1144 fn shared_path(what: &Did) -> Option<Vec<PathStep>> {
1147 let Did::Group(group) = what else {
1148 return None;
1149 };
1150 let mut edits = group.members.iter().filter_map(|member| match member {
1151 Did::Edit(edit) => Some(edit),
1152 _ => None,
1153 });
1154 let first = edits.next()?;
1155 let mut more = false;
1156 for edit in edits {
1157 if edit.path != first.path {
1158 return None;
1159 }
1160 more = true;
1161 }
1162 let trivial =
1163 matches!(first.path.as_slice(), [PathStep::Field(field)] if *field == first.field);
1164 (more && !first.path.is_empty() && !trivial).then(|| first.path.clone())
1165 }
1166
1167 fn without_shared_path(mut what: Did) -> Did {
1169 if shared_path(&what).is_some()
1170 && let Did::Group(group) = &mut what
1171 {
1172 for member in &mut group.members {
1173 if let Did::Edit(edit) = member {
1174 edit.path.clear();
1175 }
1176 }
1177 }
1178 what
1179 }
1180
1181 fn with_shared_path(mut what: Did, shared: Option<&[PathStep]>) -> Did {
1183 if let (Some(shared), Did::Group(group)) = (shared, &mut what) {
1184 for member in &mut group.members {
1185 if let Did::Edit(edit) = member {
1186 edit.path = shared.to_vec();
1187 }
1188 }
1189 }
1190 what
1191 }
1192
1193 fn distinct_of(members: &[Did]) -> Vec<Did> {
1195 match Did::group(members.iter().cloned()) {
1196 Did::Group(group) => group.distinct,
1197 _ => Vec::new(),
1198 }
1199 }
1200
1201 impl Entry {
1202 pub(super) fn of(context: &ActionContext) -> Self {
1203 let undoable = context.action.is_some() && context.kind == Some(ActionKind::Undoable);
1204 let paths = context
1205 .what
1206 .as_ref()
1207 .and_then(|what| action_paths(context.action.as_ref(), what));
1208 Self {
1209 app: context.app.clone(),
1210 resource: context.resource.as_ref().map(Resource::of),
1211 item: context
1212 .item
1213 .as_ref()
1214 .map(|item| Item::of(item, context.resource.as_ref())),
1215 shared_path: context
1216 .what
1217 .as_ref()
1218 .filter(|_| paths.is_none())
1219 .and_then(shared_path),
1220 what: context.what.as_ref().map(|what| match &paths {
1221 Some(paths) => paths_from_action(what, paths),
1222 None => without_shared_path(trimmed(what)),
1223 }),
1224 kind: context.kind.filter(|_| !undoable),
1225 purpose: context.purpose.clone(),
1226 group: context.group.clone(),
1227 facets: context.facets.clone(),
1228 invoker: context.invoker.clone(),
1229 source_invocation: context.source_invocation,
1230 signed: context.signed.clone(),
1231 caused_by: context.caused_by.clone(),
1232 action: context.action.as_ref().map(Action::of),
1233 compensation: context.compensation.as_ref().map(Action::of),
1234 gesture: context
1235 .gesture
1236 .map(|gesture| gesture.0.simple().to_string()),
1237 change: context.change,
1238 shows: context.shows.clone(),
1239 }
1240 }
1241
1242 pub(super) fn into_context(self) -> ActionContext {
1243 let action = self.action.and_then(Action::into_encoded);
1244 let resource = self.resource.map(Resource::into_resource);
1245 ActionContext {
1246 app: self.app,
1247 resource: resource.clone(),
1248 item: self.item.map(|item| item.into_item(resource.as_ref())),
1249 what: self.what.map(|what| {
1250 let paths = self
1252 .shared_path
1253 .is_none()
1254 .then(|| action_paths(action.as_ref(), &what))
1255 .flatten();
1256 match paths {
1257 Some(paths) => filled(paths_given_back(what, &paths)),
1258 None => filled(with_shared_path(what, self.shared_path.as_deref())),
1259 }
1260 }),
1261 kind: self
1262 .kind
1263 .or_else(|| action.as_ref().map(|_| ActionKind::Undoable)),
1264 purpose: self.purpose,
1265 group: self.group,
1266 facets: self.facets,
1267 invoker: self.invoker,
1268 source_invocation: self.source_invocation,
1269 signed: self.signed,
1270 caused_by: self.caused_by,
1271 compensation: self.compensation.and_then(Action::into_encoded),
1272 gesture: self
1273 .gesture
1274 .and_then(|gesture| uuid::Uuid::try_parse(&gesture).ok())
1275 .map(crate::ActionId),
1276 change: self.change,
1277 shows: self.shows,
1278 action,
1279 approval: None,
1280 pressed: false,
1281 }
1282 }
1283 }
1284}
1285
1286pub const MAX_LABEL_CHARS: usize = 96;
1288
1289#[must_use]
1293pub fn one_line(text: &str, max: usize) -> Option<String> {
1294 let line: String = text
1295 .lines()
1296 .map(str::trim)
1297 .find(|line| !line.is_empty())?
1298 .chars()
1299 .filter(|character| !character.is_control())
1300 .take(max)
1301 .collect();
1302 nonempty(&line)
1303}
1304
1305fn nonempty(value: &str) -> Option<String> {
1306 let trimmed = value.trim();
1307 (!trimmed.is_empty()).then(|| trimmed.to_string())
1308}
1309
1310pub use tilo_action_types::{MAX_PRESENCE_ID_BYTES, PresenceId};
1311
1312const MAX_DEVICE_NAME_CHARS: usize = 64;
1314
1315#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1322pub struct InvokerDevice {
1323 pub id: String,
1325 #[serde(default, skip_serializing_if = "String::is_empty")]
1328 pub name: String,
1329}
1330
1331impl InvokerDevice {
1332 #[must_use]
1335 pub fn certified(key: [u8; 32], label: &str) -> Self {
1336 Self {
1337 id: hex::encode(key),
1338 name: label
1339 .trim()
1340 .chars()
1341 .filter(|character| !character.is_control())
1342 .take(MAX_DEVICE_NAME_CHARS)
1343 .collect(),
1344 }
1345 }
1346
1347 #[must_use]
1350 pub fn short_id(&self) -> &str {
1351 self.id.get(..8).unwrap_or(&self.id)
1352 }
1353
1354 #[must_use]
1357 pub fn label(&self) -> &str {
1358 if self.name.is_empty() {
1359 self.short_id()
1360 } else {
1361 &self.name
1362 }
1363 }
1364}
1365
1366#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1372pub struct ActionInvoker {
1373 pub acting: Acting,
1374 #[serde(default, skip_serializing_if = "Option::is_none")]
1375 pub presence: Option<PresenceId>,
1376 #[serde(default, skip_serializing_if = "Option::is_none")]
1379 pub appearance: Option<crate::Appearance>,
1380 #[serde(default, skip_serializing_if = "Option::is_none")]
1385 pub name: Option<String>,
1386 #[serde(default, skip_serializing_if = "Option::is_none")]
1392 pub device: Option<InvokerDevice>,
1393}
1394
1395impl ActionInvoker {
1396 #[must_use]
1398 pub fn admitted(acting: &Acting) -> Self {
1399 Self {
1400 acting: acting.clone(),
1401 presence: None,
1402 appearance: None,
1403 name: None,
1404 device: None,
1405 }
1406 }
1407
1408 #[must_use]
1410 pub fn member(member: tilo_action_policy::MemberId) -> Self {
1411 Self::admitted(&Acting::member(member))
1412 }
1413
1414 #[track_caller]
1416 #[must_use]
1417 pub fn person(id: impl Into<tilo_action_policy::PersonId>) -> Self {
1418 Self::admitted(&Acting::person(id))
1419 }
1420
1421 #[track_caller]
1423 #[must_use]
1424 pub fn agent(id: impl Into<String>, person: impl Into<tilo_action_policy::PersonId>) -> Self {
1425 Self::admitted(&Acting::agent(id, person))
1426 }
1427
1428 #[must_use]
1429 pub fn bot(id: impl Into<String>) -> Self {
1430 Self::admitted(&Acting::bot(id))
1431 }
1432
1433 #[must_use]
1434 pub fn automation(id: impl Into<String>) -> Self {
1435 Self::admitted(&Acting::automation(id))
1436 }
1437
1438 #[must_use]
1441 pub fn view(&self) -> Option<PresenceId> {
1442 if let Some(presence) = &self.presence {
1443 return Some(presence.clone());
1444 }
1445 let member = self.acting.by.member_id()?.actor_bytes();
1446 PresenceId::new(String::from_utf8(member).ok()?).ok()
1447 }
1448
1449 #[must_use]
1450 pub fn with_presence(mut self, presence: PresenceId) -> Self {
1451 self.presence = Some(presence);
1452 self
1453 }
1454
1455 #[must_use]
1457 pub fn named(mut self, name: Option<String>) -> Self {
1458 self.name = name;
1459 self
1460 }
1461
1462 #[must_use]
1467 pub fn from_device(mut self, device: Option<InvokerDevice>) -> Self {
1468 self.device = device;
1469 self
1470 }
1471
1472 #[must_use]
1475 pub fn acting_for(mut self, person: impl Into<tilo_action_policy::PersonId>) -> Self {
1476 let person = person.into();
1477 if person.trim().is_empty() || self.acting.person_id() == Some(person.as_str()) {
1478 self.acting.acted_for.clear();
1479 } else {
1480 self.acting.acted_for = vec![Acting::person(person)];
1481 }
1482 self
1483 }
1484
1485 #[must_use]
1489 pub fn with_appearance(mut self, appearance: Option<crate::Appearance>) -> Self {
1490 self.appearance = appearance;
1491 self
1492 }
1493
1494 pub fn delivered(actor: &Actor, context: Option<&ActionContext>) -> Self {
1502 let invoker = context.and_then(|context| context.invoker.as_ref());
1503 if let Some(automation) = invoker.filter(|invoker| {
1506 invoker.acting.is_automation()
1507 && invoker.acting.acted_for.first().map(|node| &node.by) == Some(actor)
1508 }) {
1509 return automation.clone();
1510 }
1511 match invoker.filter(|invoker| invoker.acting.by == *actor) {
1512 Some(named) => named.clone(),
1513 None => Self::admitted(&Acting::from(actor.clone())),
1514 }
1515 }
1516}
1517
1518#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1519pub struct ActionApp {
1520 pub id: String,
1522 pub label: String,
1523}
1524
1525#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1526pub struct ActionResource {
1527 pub id: String,
1528 pub kind: String,
1529 pub label: String,
1530}
1531
1532#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1537pub struct Cause {
1538 pub installation: String,
1539 pub event: String,
1541 pub depth: u8,
1542}
1543
1544pub const AGENT_SESSION_GROUP: &str = "agent-session";
1548
1549pub const COMMAND_GROUP: &str = "command";
1552
1553pub const HISTORY_GROUP: &str = "history";
1557
1558#[must_use]
1560pub fn history_group(op: &crate::HistoryOp) -> String {
1561 let op = match op {
1562 crate::HistoryOp::Redo => "redo",
1563 crate::HistoryOp::Restore => "restore",
1564 crate::HistoryOp::Undo
1565 | crate::HistoryOp::Checkpoint { .. }
1566 | crate::HistoryOp::Migrate { .. } => "undo",
1567 };
1568 format!("{HISTORY_GROUP}:{op}")
1569}
1570
1571#[must_use]
1573pub fn history_move(kind: &str) -> Option<crate::HistoryOp> {
1574 match kind.strip_prefix(HISTORY_GROUP)?.strip_prefix(':')? {
1575 "redo" => Some(crate::HistoryOp::Redo),
1576 "restore" => Some(crate::HistoryOp::Restore),
1577 "undo" => Some(crate::HistoryOp::Undo),
1578 _ => None,
1579 }
1580}
1581
1582#[must_use]
1585pub fn names_a_session(kind: &str) -> bool {
1586 kind == AGENT_SESSION_GROUP || kind == COMMAND_GROUP
1587}
1588
1589#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1592pub struct WorkGroup {
1593 pub id: String,
1595 #[serde(default, skip_serializing_if = "Option::is_none")]
1600 pub label: Option<String>,
1601 pub kind: String,
1603 #[serde(default, skip_serializing_if = "Option::is_none")]
1608 pub declared_id: Option<String>,
1609 #[serde(default, skip_serializing_if = "Option::is_none")]
1614 pub session: Option<String>,
1615}
1616
1617pub const RISK_FACET: &str = "risk";
1620
1621pub const PLACE_FACET: &str = "place";
1626
1627#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1630pub struct ActionFacet {
1631 pub key: String,
1633 pub value: String,
1634}
1635
1636impl ActionFacet {
1637 pub fn new(key: impl Into<String>, value: impl Into<String>) -> Self {
1638 Self {
1639 key: key.into(),
1640 value: value.into(),
1641 }
1642 }
1643}
1644
1645#[cfg(test)]
1646mod tests {
1647 use super::*;
1648 use crate::entry::{EditOp, FieldEdit, PathStep, Scalar};
1649 use crate::key::ActionKey;
1650 use tilo_action_policy::MemberId;
1651
1652 fn laptop() -> InvokerDevice {
1653 InvokerDevice::certified([0x5c; 32], " Studio\u{7} laptop ")
1654 }
1655
1656 fn starred() -> Described {
1657 Described::new(Did::Edit(FieldEdit {
1658 ty: "snippet".into(),
1659 field: "favorite".into(),
1660 path: vec![
1661 PathStep::Field("snippets".into()),
1662 PathStep::Item("s1".into()),
1663 PathStep::Field("favorite".into()),
1664 ],
1665 op: EditOp::Set,
1666 old: Some(false.into()),
1667 new: Some(true.into()),
1668 args: std::collections::BTreeMap::new(),
1669 }))
1670 .on("s1", "Deploy script")
1671 }
1672
1673 fn written(message: &str) -> String {
1675 let entry = message.strip_prefix(CHANGE_MESSAGE_PREFIX).unwrap();
1676 crate::compact::decode(entry).unwrap()
1677 }
1678
1679 tilo_test_env::scenario! {
1680 fn the_host_states_the_invoker;
1681
1682 phase the_host_rewriting_the_invoker_drops_an_appearance_the_caller_put_there;
1683 {
1684 let smuggled = ActionContext::default().with_invoker(
1685 ActionInvoker::person("mallory")
1686 .with_appearance(Some(crate::Appearance::new("Ada", None, None).unwrap())),
1687 );
1688 let hosted = smuggled.with_host_actor(&crate::Acting::person("mallory"), None);
1689 assert_eq!(hosted.invoker.unwrap().appearance, None);
1690 }
1691
1692 phase a_delivered_invoker_keeps_the_appearance_only_for_the_named_actor;
1693 {
1694 let appearance = crate::Appearance::new("alice", None, None).unwrap();
1695 let context = ActionContext::default().with_invoker(
1696 ActionInvoker::bot("7f1c").with_appearance(Some(appearance.clone())),
1697 );
1698 assert_eq!(
1699 ActionInvoker::delivered(&MemberId::bot("7f1c").into(), Some(&context)).appearance,
1700 Some(appearance)
1701 );
1702 assert_eq!(
1703 ActionInvoker::delivered(&MemberId::person("b").into(), Some(&context)).appearance,
1704 None
1705 );
1706 }
1707
1708 phase a_device_is_named_by_its_certificate_or_the_start_of_its_key;
1709 {
1710 let laptop = laptop();
1711 assert_eq!(laptop.id, "5c".repeat(32));
1712 assert_eq!(
1713 laptop.name, "Studio laptop",
1714 "trimmed, no control characters"
1715 );
1716 assert_eq!(laptop.short_id(), "5c5c5c5c");
1717 assert_eq!(laptop.label(), "Studio laptop");
1718 let unnamed = InvokerDevice::certified([0x40; 32], " ");
1719 assert_eq!(unnamed.label(), "40404040");
1720 let long = InvokerDevice::certified([1; 32], &"x".repeat(200));
1721 assert_eq!(long.name.chars().count(), MAX_DEVICE_NAME_CHARS);
1722 }
1723
1724 phase the_host_rewriting_the_invoker_drops_a_device_the_caller_put_there;
1725 {
1726 let smuggled = ActionContext::default().with_invoker(
1727 ActionInvoker::agent("mallory", "ada").from_device(Some(laptop())),
1728 );
1729 let hosted = smuggled.with_host_actor(&crate::Acting::agent("mallory", "ada"), None);
1730 assert_eq!(hosted.invoker.unwrap().device, None);
1731 }
1732
1733 phase a_delivered_invoker_keeps_the_device_only_for_the_named_actor;
1734 {
1735 let context = ActionContext::default().with_invoker(
1736 ActionInvoker::agent("task-7", "ada").from_device(Some(laptop())),
1737 );
1738 assert_eq!(
1739 ActionInvoker::delivered(&MemberId::agent("task-7", "ada").into(), Some(&context)).device,
1740 Some(laptop())
1741 );
1742 assert_eq!(
1743 ActionInvoker::delivered(&MemberId::agent("task-8", "ada").into(), Some(&context)).device,
1744 None,
1745 "another actor is not on that device because a context names it"
1746 );
1747 assert_eq!(ActionInvoker::delivered(&MemberId::agent("task-7", "ada").into(), None).device, None);
1748 }
1749
1750 phase invoker_round_trips_and_is_enriched_from_ambient;
1751 {
1752 let invoker = ActionInvoker::agent("alpha", "ada")
1753 .with_presence(PresenceId::new("task-7").unwrap());
1754 let context = ActionContext::for_resource("r", "k", "l").with_invoker(invoker.clone());
1755 let message = context.change_message().unwrap();
1756 assert_eq!(
1757 ActionContext::from_change_message(&message),
1758 Some(context.clone())
1759 );
1760 let enriched = ActionContext::default().enriched_by(&context);
1761 assert_eq!(enriched.invoker, Some(invoker));
1762 }
1763
1764 phase a_person_acting_for_themselves_records_nobody;
1765 {
1766 assert_eq!(
1767 ActionInvoker::person("ada").acting_for("ada").acting.acted_for_person(),
1768 None
1769 );
1770 let agent = ActionInvoker::agent("claude", "ada").acting_for("ada");
1771 assert!(agent.acting.is_agent());
1772 assert_eq!(agent.acting.acted_for_person(), Some("ada"));
1773 }
1774
1775 phase host_invoker_overwrites_a_forged_envelope_invoker;
1776 {
1777 let forged = ActionContext::for_resource("r", "k", "l").with_invoker(
1778 ActionInvoker::person("owner")
1779 .acting_for("other")
1780 .with_presence(PresenceId::new("owner-window").unwrap()),
1781 );
1782 let task = PresenceId::new("agent-alpha-view").unwrap();
1783 let rewritten = forged
1784 .clone()
1785 .with_host_actor(&crate::Acting::agent("alpha", "owner"), Some(task.clone()));
1786 assert_eq!(
1787 rewritten.invoker,
1788 Some(ActionInvoker::agent("alpha", "owner").with_presence(task))
1789 );
1790 let delegated = forged.with_host_actor(
1791 &crate::Acting::agent("alpha", "owner").acting_for(crate::Acting::person("owner")),
1792 None,
1793 );
1794 let invoker = delegated.invoker.unwrap();
1795 assert!(invoker.acting.is_agent());
1796 assert_eq!(
1797 invoker.acting.acted_for_person(),
1798 Some("owner"),
1799 "the host records whom the admitted actor acts for"
1800 );
1801 }
1802
1803 phase delivered_invoker_keeps_the_presence_only_for_the_delivered_actor;
1804 {
1805 let presence = PresenceId::new("agent-a-view").unwrap();
1806 let context =
1807 ActionContext::default()
1808 .with_host_actor(&crate::Acting::agent("a", "ada"), Some(presence.clone()));
1809 assert_eq!(
1810 ActionInvoker::delivered(&MemberId::agent("a", "ada").into(), Some(&context)),
1811 ActionInvoker::agent("a", "ada").with_presence(presence)
1812 );
1813 assert_eq!(
1816 ActionInvoker::delivered(&MemberId::person("b").into(), Some(&context)),
1817 ActionInvoker::person("b")
1818 );
1819 assert_eq!(
1820 ActionInvoker::delivered(&MemberId::person("b").into(), None),
1821 ActionInvoker::person("b")
1822 );
1823 let shortcut = ActionInvoker::automation("morning").acting_for("b");
1826 let run = ActionContext::default().with_invoker(shortcut.clone());
1827 assert_eq!(ActionInvoker::delivered(&MemberId::person("b").into(), Some(&run)), shortcut);
1828 assert_eq!(
1829 ActionInvoker::delivered(&MemberId::person("c").into(), Some(&run)),
1830 ActionInvoker::person("c")
1831 );
1832 }
1833
1834 phase presence_ids_are_bounded;
1835 {
1836 assert!(PresenceId::new("").is_err());
1837 assert!(PresenceId::new("has space").is_err());
1838 assert!(PresenceId::new("x".repeat(MAX_PRESENCE_ID_BYTES + 1)).is_err());
1839 assert!(PresenceId::new("x".repeat(MAX_PRESENCE_ID_BYTES)).is_ok());
1840 assert!(serde_json::from_str::<PresenceId>("\"\"").is_err());
1841 }
1842 }
1843
1844 tilo_test_env::scenario! {
1845 fn a_context_reads_back_from_its_change_message;
1846
1847 phase an_appearance_round_trips_through_the_change_message;
1848 {
1849 let appearance = crate::Appearance::new(
1850 "alice",
1851 None,
1852 Some(crate::Persona {
1853 service: "discord".into(),
1854 account: "80351110224678912".into(),
1855 linked: None,
1856 }),
1857 )
1858 .unwrap();
1859 let entry = ActionContext::default().with_invoker(
1860 ActionInvoker::bot("7f1c")
1861 .acting_for("ada")
1862 .with_appearance(Some(appearance.clone())),
1863 );
1864 let read = ActionContext::from_change_message(&entry.change_message().unwrap()).unwrap();
1865 assert_eq!(read, entry);
1866 assert_eq!(read.invoker.unwrap().appearance, Some(appearance));
1867 let plain = ActionContext::default().with_invoker(ActionInvoker::person("ada"));
1868 let json = serde_json::to_string(&plain.invoker).unwrap();
1869 assert!(!json.contains("appearance"), "{json}");
1870 }
1871
1872 phase the_device_an_agent_works_from_round_trips_through_the_change_message;
1873 {
1874 let entry = ActionContext::default().with_invoker(
1875 ActionInvoker::agent("task-7", "ada")
1876 .acting_for("ada")
1877 .from_device(Some(laptop())),
1878 );
1879 let read = ActionContext::from_change_message(&entry.change_message().unwrap()).unwrap();
1880 assert_eq!(read, entry);
1881 assert_eq!(read.invoker.unwrap().device, Some(laptop()));
1882 let local = ActionContext::default().with_invoker(ActionInvoker::agent("task-8", "ada"));
1884 let json = serde_json::to_string(&local.invoker).unwrap();
1885 assert!(!json.contains("\"device\""), "{json}");
1886 }
1887
1888 phase a_cause_survives_the_change_message;
1889 {
1890 let context = ActionContext::for_app("so.tilo.chat", "Chat").with_caused_by(Some(Cause {
1891 installation: "4a6c0c49-8a0d-4c3e-9d55-0a1b2c3d4e5f".into(),
1892 event: "ab".repeat(32),
1893 depth: 3,
1894 }));
1895 let message = context.change_message().unwrap();
1896 let read = ActionContext::from_change_message(&message).unwrap();
1897 assert_eq!(read.caused_by, context.caused_by);
1898 let plain = ActionContext::for_app("so.tilo.chat", "Chat")
1900 .change_message()
1901 .unwrap();
1902 assert!(
1903 ActionContext::from_change_message(&plain)
1904 .unwrap()
1905 .caused_by
1906 .is_none()
1907 );
1908 }
1909
1910 phase entries_round_trip_through_the_change_message;
1911 {
1912 let entry = ActionContext::for_resource("lib", "snippets.library", "Snippets")
1913 .with_app("org.tilo.Snippets", "Snippets")
1914 .with_described(starred())
1915 .with_group("run:7", "Tidy snippets", "agent-session")
1916 .with_invoker(
1917 ActionInvoker::agent("claude", "ada").acting_for("ada"),
1918 )
1919 .with_source_invocation(Some(InvocationId(uuid::Uuid::from_u128(42))));
1920 let message = entry.change_message().unwrap();
1921 let read = ActionContext::from_change_message(&message).unwrap();
1922 assert_eq!(read, entry);
1923 assert!(read.acting().unwrap().is_agent());
1924 assert_eq!(
1925 read.acting().unwrap().acted_for_person(),
1926 Some("ada")
1927 );
1928 assert_eq!(read.described(), Some(starred()));
1929
1930 let verb = ActionContext::default().with_described(Described::new(Did::verb(
1931 ActionKey::new("snippets", "snippets.library", "new-snippet"),
1932 [("title".to_string(), Scalar::from("Deploy"))],
1933 )));
1934 let read = ActionContext::from_change_message(&verb.change_message().unwrap()).unwrap();
1935 assert_eq!(read, verb);
1936 }
1937
1938 phase an_entry_leaves_out_what_its_reader_derives_and_reads_back_the_same;
1939 {
1940 let action = crate::EncodedAction {
1941 type_id: "word-processor.edit".into(),
1942 payload: br#"{"op":"type","text":"a"}"#.to_vec(),
1943 };
1944 let entry = ActionContext {
1945 what: Some(Did::Edit(crate::FieldEdit {
1946 ty: "document".into(),
1947 field: "body".into(),
1948 path: vec![PathStep::Field("body".into())],
1949 op: crate::EditOp::Splice,
1950 old: None,
1951 new: None,
1952 args: std::collections::BTreeMap::new(),
1953 })),
1954 kind: Some(ActionKind::Undoable),
1955 action: Some(action),
1956 gesture: Some(crate::ActionId::new()),
1957 ..ActionContext::for_resource("doc:1", "word-processor.document", "Plan")
1958 .with_app("org.tilo.WordProcessor", "Word Processor")
1959 };
1960 let message = entry.change_message().unwrap();
1961 for derived in ["undoable", "path", "[123,"] {
1964 assert!(!message.contains(derived), "{derived} in {message}");
1965 }
1966 assert!(message.len() < 230, "{} B: {message}", message.len());
1967 let read = ActionContext::from_change_message(&message).unwrap();
1968 assert_eq!(read, entry);
1969 assert_eq!(
1970 read.change_message().unwrap(),
1971 message,
1972 "written again the same"
1973 );
1974 let bare = ActionContext { app: None, ..entry };
1976 let read = ActionContext::from_change_message(&bare.change_message().unwrap()).unwrap();
1977 assert_eq!(read, bare);
1978 }
1979
1980 phase a_group_writes_what_its_members_share_once;
1981 {
1982 let path = vec![
1983 PathStep::Field("sheets".into()),
1984 PathStep::Item("s1".into()),
1985 PathStep::Field("cells".into()),
1986 ];
1987 let edit = |op| {
1988 Did::Edit(FieldEdit {
1989 ty: "sheet".into(),
1990 field: "cells".into(),
1991 path: path.clone(),
1992 op,
1993 old: None,
1994 new: None,
1995 args: std::collections::BTreeMap::new(),
1996 })
1997 };
1998 let mut entry =
1999 ActionContext::for_resource("sheets.workbook", "sheets.workbook", "Workbook");
2000 entry.what = Some(Did::group([edit(EditOp::InsertRow), edit(EditOp::SetCell)]));
2001 let message = entry.change_message().unwrap();
2002 assert!(!message.contains("distinct"), "{message}");
2003 assert_eq!(
2004 written(&message).matches("\"cells\"").count(),
2005 3,
2006 "the path once: {message}"
2007 );
2008 let read = ActionContext::from_change_message(&message).unwrap();
2009 assert_eq!(read, entry);
2010 assert_eq!(
2011 read.change_message().unwrap(),
2012 message,
2013 "written again the same"
2014 );
2015 }
2016
2017 phase an_edit_takes_its_path_from_the_action_it_carries;
2018 {
2019 let path = vec![
2020 PathStep::Field("pages".into()),
2021 PathStep::Item("p1".into()),
2022 PathStep::Field("body".into()),
2023 ];
2024 let mut entry = ActionContext::for_resource("notes.notebook", "notes.notebook", "Notebook");
2025 entry.what = Some(Did::Edit(FieldEdit {
2026 ty: "page".into(),
2027 field: "body".into(),
2028 path,
2029 op: EditOp::Splice,
2030 old: None,
2031 new: None,
2032 args: std::collections::BTreeMap::new(),
2033 }));
2034 entry.action = Some(crate::EncodedAction {
2035 type_id: "notes.notebook".into(),
2036 payload: br#"{"op":{"action":"field-edit","args":{"op":"rich","path":[{"field":"pages"},{"item":"p1"},{"field":"body"}]}},"at":0}"#.to_vec(),
2037 });
2038 entry.kind = Some(ActionKind::Undoable);
2039 let message = entry.change_message().unwrap();
2040 assert_eq!(
2041 written(&message).matches("\"pages\"").count(),
2042 1,
2043 "the path once: {message}"
2044 );
2045 assert!(
2046 message.len() * 10 < written(&message).len() * 7,
2047 "the compact form is well under the JSON one: {message}"
2048 );
2049 let read = ActionContext::from_change_message(&message).unwrap();
2050 assert_eq!(read, entry);
2051 assert_eq!(
2052 read.change_message().unwrap(),
2053 message,
2054 "written again the same"
2055 );
2056 }
2057
2058 phase an_item_named_by_its_resource_writes_its_id_once;
2059 {
2060 let mut entry =
2061 ActionContext::for_resource("notes.notebook/pages/p1", "tilo.rich-text", "Document");
2062 entry.item = Some(ActionItem {
2063 id: "p1".into(),
2064 label: "Plans".into(),
2065 });
2066 let message = entry.change_message().unwrap();
2067 assert_eq!(message.matches("p1").count(), 1, "the id once: {message}");
2068 let read = ActionContext::from_change_message(&message).unwrap();
2069 assert_eq!(read, entry);
2070 assert_eq!(
2071 read.change_message().unwrap(),
2072 message,
2073 "written again the same"
2074 );
2075 entry.item = Some(ActionItem {
2077 id: "p2".into(),
2078 label: "Other".into(),
2079 });
2080 let read = ActionContext::from_change_message(&entry.change_message().unwrap()).unwrap();
2081 assert_eq!(read, entry);
2082 }
2083
2084 phase an_invoker_written_in_an_older_form_keeps_the_rest_of_its_entry;
2085 {
2086 let context = ActionContext::for_resource("r", "k", "l");
2087 let mut json: serde_json::Value =
2088 serde_json::from_str(&written(&context.change_message().unwrap())).unwrap();
2089 json["by"] = serde_json::json!({ "actor": "ada" });
2090 let message = format!("{CHANGE_MESSAGE_PREFIX}{}", crate::compact::encode(&json));
2091 assert_eq!(ActionContext::from_change_message(&message), Some(context));
2092 }
2093
2094 phase defaults_are_not_written;
2095 {
2096 let context = ActionContext::for_resource("r", "k", "l");
2097 let message = context.change_message().unwrap();
2098 let json: serde_json::Value = serde_json::from_str(&written(&message)).unwrap();
2099 let written: Vec<&str> = json
2100 .as_object()
2101 .unwrap()
2102 .keys()
2103 .map(String::as_str)
2104 .collect();
2105 assert_eq!(written, ["r"], "{message}");
2106 assert_eq!(ActionContext::from_change_message(&message), Some(context));
2107 let outside = ActionContext::default().with_change(ChangeKind::External);
2108 let mut outside = outside;
2109 outside.kind = Some(ActionKind::Outside);
2110 let read = ActionContext::from_change_message(&outside.change_message().unwrap()).unwrap();
2111 assert_eq!(read.kind, Some(ActionKind::Outside));
2112 assert!(
2113 !read.is_activity(),
2114 "what came from outside is not activity"
2115 );
2116 }
2117
2118 phase housekeeping_is_carried;
2119 {
2120 let content = ActionContext::for_resource("r", "k", "l");
2121 let marker = content.clone().with_change(ChangeKind::Housekeeping);
2122 let message = marker.change_message().unwrap();
2123 let read = ActionContext::from_change_message(&message).unwrap();
2124 assert!(read.is_housekeeping());
2125 assert_eq!(read, marker);
2126 let bare = ActionContext::default().with_change(ChangeKind::Housekeeping);
2127 assert!(
2128 bare.change_message().is_some(),
2129 "housekeeping alone is still written"
2130 );
2131 assert!(
2132 !ActionContext::from_change_message(&content.change_message().unwrap())
2133 .unwrap()
2134 .is_housekeeping()
2135 );
2136 }
2137
2138 phase unrelated_or_malformed_messages_are_not_entries;
2139 {
2140 assert!(ActionContext::from_change_message("saved draft").is_none());
2141 assert!(ActionContext::from_change_message("tilo.entry/1 {").is_none());
2142 assert!(ActionContext::default().change_message().is_none());
2143 }
2144 }
2145
2146 tilo_test_env::scenario! {
2147 fn ambient_context_fills_what_the_action_leaves_open;
2148
2149 phase ambient_context_fills_intent_without_overwriting_the_action;
2150 {
2151 let action = ActionContext::for_resource("file:1", "file", "brief.md")
2152 .with_app("org.tilo.Code", "Code");
2153 let ambient = ActionContext::default()
2154 .with_purpose("Prepare launch")
2155 .with_group("issue:42", "Launch", "issue")
2156 .with_app("wrong", "Wrong");
2157 let merged = action.enriched_by(&ambient);
2158 assert_eq!(
2159 merged.app.as_ref().map(|app| app.id.as_str()),
2160 Some("org.tilo.Code")
2161 );
2162 assert_eq!(merged.purpose.as_deref(), Some("Prepare launch"));
2163 assert_eq!(
2164 merged.group.as_ref().map(|group| group.id.as_str()),
2165 Some("issue:42")
2166 );
2167 }
2168 }
2169
2170 #[test]
2171 fn a_keystroke_continues_its_writers_last_entry_with_its_gesture_bytes_and_claim() {
2172 let typed = |letter: &str, gesture: u128| ActionContext {
2173 action: Some(crate::EncodedAction {
2174 type_id: "notes.notebook".into(),
2175 payload: format!(
2176 r#"{{"SpliceText":{{"at":12,"ins":{letter}}},"path":[{{"item":"8dc4"}}]}}"#
2177 )
2178 .into_bytes(),
2179 }),
2180 ..ActionContext::default()
2181 .with_described(starred())
2182 .in_gesture(Some(crate::ActionId(uuid::Uuid::from_u128(gesture))))
2183 };
2184 let (first, next) = (typed(r#""n""#, 7), typed(r#""é \"q\"""#, 8));
2186 let message = next.continuation_of(&first).unwrap();
2187 assert_eq!(
2188 message,
2189 r#"tilo.cont/3 U8000000000000000000000 e::fsnippets/is1/ffavorite 30 28 é \"q\""#
2190 );
2191 assert_eq!(
2192 ContinuedAction::of_message(&message),
2193 Some(ContinuedAction::Edit {
2194 kind: String::new(),
2195 path: vec![
2196 PathStep::Field("snippets".into()),
2197 PathStep::Item("s1".into()),
2198 PathStep::Field("favorite".into()),
2199 ],
2200 })
2201 );
2202 assert_eq!(
2203 ActionContext::continued(&message, &first),
2204 Some(next),
2205 "read back byte for byte"
2206 );
2207 }
2208}