1use crate::ActionContract;
20use crate::ActionParam;
21use crate::action::{EncodedAction, ExecutionLocus, OperationKind};
22use crate::context::ActionContext;
23use crate::entry::Described;
24use crate::executor::{ActionTransport, Dispatched, dispatch_by_with_context};
25use crate::registry::ActionRegistry;
26use crate::resource::{
27 ActionInput, ActionSpec, Collects, ResourceSpec, ResourceViewMountSpec, ResourceViewRangeSpec,
28};
29use serde::{Deserialize, Serialize};
30
31pub const NOT_READY: &str = "not_ready";
35
36pub const NOT_READY_REASON: &str = "what this changes has not arrived from the workspace yet; ask \
41 again";
42
43pub use tilo_action_types::ActionAddress;
44
45#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
49pub enum InputSpec {
50 None,
52 Text {
56 prompt: String,
57 placeholder: String,
58 collects: Collects,
59 },
60}
61
62impl ActionDescriptor {
63 #[must_use]
66 pub fn writes(&self) -> Option<String> {
67 if self.contract.effects.is_empty() {
68 return None;
69 }
70 let steps: Vec<String> = self
71 .contract
72 .effects
73 .iter()
74 .map(ToString::to_string)
75 .collect();
76 Some(format!("Writes: {}.", steps.join(", ")))
77 }
78
79 #[must_use]
84 pub fn changes_only_a_document(&self) -> bool {
85 self.kind == OperationKind::Document
86 || self
87 .contract
88 .tags
89 .iter()
90 .any(|tag| tag == crate::ROUTED_CHANGE_TAG)
91 }
92
93 #[must_use]
97 pub fn prompt_param(&self) -> Option<&str> {
98 match self.input {
99 InputSpec::Text { .. } => self
100 .params
101 .iter()
102 .find(|param| param.entry)
103 .or_else(|| self.params.iter().find(|param| param.required))
104 .or_else(|| self.params.first())
105 .map(|param| param.name.as_ref()),
106 InputSpec::None => None,
107 }
108 }
109
110 #[must_use]
114 pub fn domain_resource(&self) -> &str {
115 match &self.semantic_identity {
116 Some(identity) if identity.is_valid() => identity.key.as_str(),
117 _ => self.address.resource.as_str(),
118 }
119 }
120
121 #[must_use]
126 pub fn entry_param(&self) -> Option<&str> {
127 self.params
128 .iter()
129 .find(|param| param.entry)
130 .map(|param| param.name.as_ref())
131 }
132
133 #[must_use]
138 pub fn bind_prompt_text(
139 &self,
140 mut arguments: serde_json::Map<String, serde_json::Value>,
141 ) -> serde_json::Map<String, serde_json::Value> {
142 if arguments.len() == 1
143 && let Some(name) = self.prompt_param()
144 && name != crate::PROMPTED_PARAM
145 && let Some(text) = arguments.remove(crate::PROMPTED_PARAM)
146 {
147 arguments.insert(name.to_owned(), text);
148 }
149 arguments
150 }
151}
152
153impl InputSpec {
154 fn of(input: ActionInput<'_>) -> Self {
155 match input {
156 ActionInput::Immediate(_) | ActionInput::Deferred { .. } => InputSpec::None,
157 ActionInput::Prompted {
158 prompt,
159 placeholder,
160 collects,
161 } => InputSpec::Text {
162 prompt: prompt.to_owned(),
163 placeholder: placeholder.to_owned(),
164 collects,
165 },
166 }
167 }
168
169 pub fn wants_text(&self) -> bool {
171 matches!(self, InputSpec::Text { .. })
172 }
173
174 pub fn wants_content(&self) -> bool {
177 matches!(
178 self,
179 InputSpec::Text {
180 collects: Collects::Content,
181 ..
182 }
183 )
184 }
185}
186
187#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
192pub struct ActionDescriptor {
193 pub address: ActionAddress,
194 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub semantic_identity: Option<crate::ResourceSemanticIdentity>,
196 pub resource_kind: String,
200 pub resource_label: String,
202 pub action_label: String,
203 #[serde(default, skip_serializing_if = "Vec::is_empty")]
207 pub keywords: Vec<String>,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
211 pub did: Option<String>,
212 #[serde(default, skip_serializing_if = "Option::is_none")]
214 pub icon: Option<String>,
215 pub description: Option<String>,
216 #[serde(default, skip_serializing_if = "crate::ActionState::is_empty")]
219 pub state: crate::ActionState,
220 pub locus: ExecutionLocus,
221 pub kind: OperationKind,
222 pub contract: ActionContract,
223 pub input: InputSpec,
224 pub params: Vec<ActionParam>,
227 #[serde(default, skip_serializing_if = "Option::is_none")]
230 pub view: Option<ResourceViewDescriptor>,
231}
232
233#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
238pub struct ActionEffect {
239 pub app: String,
240 pub kind: String,
241 pub verb: String,
242}
243
244impl ActionEffect {
245 pub const UNDO: &'static str = "undo";
247
248 #[must_use]
251 pub fn undo(app: impl Into<String>) -> Self {
252 Self::new(app, "", Self::UNDO)
253 }
254
255 #[must_use]
257 pub fn undoes_in(&self, app: &str) -> bool {
258 self.app == app && self.kind.is_empty() && self.verb == Self::UNDO
259 }
260
261 #[must_use]
263 pub fn new(app: impl Into<String>, kind: impl Into<String>, verb: impl Into<String>) -> Self {
264 Self {
265 app: app.into(),
266 kind: kind.into(),
267 verb: verb.into(),
268 }
269 }
270}
271
272impl std::fmt::Display for ActionEffect {
273 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274 if self.kind.is_empty() {
276 return write!(formatter, "{}#{}", self.app, self.verb);
277 }
278 write!(formatter, "{} {}#{}", self.app, self.kind, self.verb)
279 }
280}
281
282#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
287#[serde(deny_unknown_fields)]
288pub struct ResourceViewDescriptor {
289 pub id: String,
290 pub label: String,
291 pub description: Option<String>,
292 pub open_action: String,
293 pub primary: bool,
294 pub mount: Option<ResourceViewMountSpec>,
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub range: Option<ResourceViewRangeSpec>,
297 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
299 pub desktop: bool,
300}
301
302impl ResourceViewDescriptor {
303 #[must_use]
306 pub fn declared_for(resource: &ResourceSpec, action_id: &str) -> Option<Self> {
307 resource
308 .views
309 .iter()
310 .find(|view| view.open_action == action_id)
311 .map(|view| Self {
312 id: view.id.clone(),
313 label: view.label.clone(),
314 description: view.description.clone(),
315 open_action: view.open_action.clone(),
316 primary: view.primary,
317 mount: view.mount.clone(),
318 range: view.range.clone(),
319 desktop: view.desktop,
320 })
321 }
322}
323
324pub const NOT_THE_ASKED_PERSON: &str = "question-not-yours";
328
329#[derive(Clone, Debug, PartialEq, Eq)]
333pub enum ApiError {
334 Unknown(ActionAddress),
336 MissingArgument(ActionAddress),
338 UnexpectedArgument(ActionAddress),
342 InvalidArguments(String),
344 ArgumentOutOfRange {
348 param: String,
349 violation: crate::params::ArgViolation,
350 },
351 Unavailable { code: String, reason: String },
354 ConfirmationRequired,
357 UnregisteredType(String),
361 Refused { code: String, reason: String },
365 Failed(String),
367}
368
369impl ApiError {
370 pub fn decoding(error: crate::action::ActionError) -> Self {
376 match error {
377 crate::action::ActionError::UnknownType(type_id) => ApiError::UnregisteredType(type_id),
378 other => ApiError::refused(other),
379 }
380 }
381
382 pub fn refused(error: crate::action::ActionError) -> Self {
385 match error {
386 crate::action::ActionError::Unavailable { code, message } => ApiError::Refused {
387 code,
388 reason: message,
389 },
390 other => ApiError::Failed(other.to_string()),
391 }
392 }
393
394 pub fn code(&self) -> &str {
397 match self {
398 ApiError::Unknown(_) | ApiError::UnregisteredType(_) => "unknown_action",
399 ApiError::MissingArgument(_)
400 | ApiError::UnexpectedArgument(_)
401 | ApiError::InvalidArguments(_)
402 | ApiError::ArgumentOutOfRange { .. } => "invalid_arguments",
403 ApiError::Unavailable { .. } => "action_unavailable",
404 ApiError::Refused { code, .. } => code,
406 ApiError::ConfirmationRequired => "action_confirmation_required",
407 ApiError::Failed(_) => "action_failed",
408 }
409 }
410
411 #[must_use]
417 pub fn failure_details(&self) -> Option<serde_json::Value> {
418 match self {
419 ApiError::ArgumentOutOfRange { param, violation } => {
420 Some(serde_json::json!({ "param": param, "violation": violation }))
421 }
422 ApiError::Unavailable { code, reason } => {
423 Some(serde_json::json!({ "code": code, "reason": reason }))
424 }
425 _ => None,
426 }
427 }
428}
429
430impl From<crate::params::ArgError> for ApiError {
433 fn from(error: crate::params::ArgError) -> Self {
434 match error {
435 crate::params::ArgError::OutOfRange { name, violation } => {
436 ApiError::ArgumentOutOfRange {
437 param: name,
438 violation,
439 }
440 }
441 error => ApiError::InvalidArguments(error.to_string()),
442 }
443 }
444}
445
446impl std::fmt::Display for ApiError {
447 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
448 match self {
449 ApiError::Unknown(a) => {
450 write!(f, "no action addressed by ({}, {})", a.resource, a.action)
451 }
452 ApiError::MissingArgument(a) => write!(
453 f,
454 "action ({}, {}) needs a text argument and none was given",
455 a.resource, a.action
456 ),
457 ApiError::UnexpectedArgument(a) => {
458 write!(f, "action ({}, {}) takes no argument", a.resource, a.action)
459 }
460 ApiError::InvalidArguments(why) | ApiError::Failed(why) => write!(f, "{why}"),
461 ApiError::Refused { reason, .. } => f.write_str(reason),
462 ApiError::ArgumentOutOfRange { param, violation } => {
463 write!(f, "argument `{param}` {violation}")
464 }
465 ApiError::Unavailable { code, reason } => write!(f, "{code}: {reason}"),
466 ApiError::ConfirmationRequired => {
467 f.write_str("this action requires explicit confirmation")
468 }
469 ApiError::UnregisteredType(t) => {
470 write!(f, "no decoder registered for action type `{t}`")
471 }
472 }
473 }
474}
475
476impl std::error::Error for ApiError {}
477
478pub fn survey(resources: &[ResourceSpec]) -> Vec<ActionDescriptor> {
483 survey_placed(resources)
484 .into_iter()
485 .map(|row| row.action)
486 .collect()
487}
488
489#[must_use]
493pub fn publishes_same(a: &[ResourceSpec], b: &[ResourceSpec]) -> bool {
494 a.len() == b.len()
495 && a.iter().zip(b).all(|(a, b)| {
496 a.id == b.id
497 && a.kind == b.kind
498 && a.label == b.label
499 && a.presentation == b.presentation
500 && a.semantic_identity == b.semantic_identity
501 && a.app_id == b.app_id
502 && a.views == b.views
503 && a.personal == b.personal
504 && a.workspace == b.workspace
505 && a.resource_type == b.resource_type
506 && a.actions.len() == b.actions.len()
507 && a.actions
508 .iter()
509 .zip(&b.actions)
510 .all(|(x, y)| x.bound() == y.bound() && describe(a, x) == describe(b, y))
511 && publishes_same(&a.children, &b.children)
512 })
513}
514
515#[derive(Clone, Debug, PartialEq, Eq)]
519pub struct PlacedAction {
520 pub parent: String,
522 pub has_children: bool,
524 pub action: ActionDescriptor,
525}
526
527#[must_use]
532pub fn survey_placed(resources: &[ResourceSpec]) -> Vec<PlacedAction> {
533 let mut out = Vec::new();
534 let _ = survey_placed_each(resources, &mut |placed| {
535 out.push(placed);
536 true
537 });
538 out
539}
540
541pub fn survey_placed_each(
546 resources: &[ResourceSpec],
547 visit: &mut dyn FnMut(PlacedAction) -> bool,
548) -> bool {
549 resources
550 .iter()
551 .all(|resource| placed_each(resource, "", visit))
552}
553
554pub fn survey_placed_level(
559 children: &[ResourceSpec],
560 parent: &str,
561 visit: &mut dyn FnMut(PlacedAction) -> bool,
562) -> bool {
563 survey_placed_level_items(children, parent, &mut |_, placed| visit(placed))
564}
565
566pub fn survey_placed_level_items(
571 children: &[ResourceSpec],
572 parent: &str,
573 visit: &mut dyn FnMut(usize, PlacedAction) -> bool,
574) -> bool {
575 children.iter().enumerate().all(|(at, child)| {
576 let has_children = !child.children.is_empty();
577 child.actions.iter().all(|action| {
578 visit(
579 at,
580 PlacedAction {
581 parent: parent.to_owned(),
582 has_children,
583 action: describe(child, action),
584 },
585 )
586 })
587 })
588}
589
590pub fn survey_placed_under(
594 resource: &ResourceSpec,
595 parent: &str,
596 visit: &mut dyn FnMut(PlacedAction) -> bool,
597) -> bool {
598 placed_each(resource, parent, visit)
599}
600
601fn placed_each(
602 resource: &ResourceSpec,
603 parent: &str,
604 visit: &mut dyn FnMut(PlacedAction) -> bool,
605) -> bool {
606 let has_children = !resource.children.is_empty();
607 for action in &resource.actions {
608 let go_on = visit(PlacedAction {
609 parent: parent.to_owned(),
610 has_children,
611 action: describe(resource, action),
612 });
613 if !go_on {
614 return false;
615 }
616 }
617 for child in &resource.children {
618 if !placed_each(child, resource.id.as_str(), visit) {
619 return false;
620 }
621 }
622 true
623}
624
625#[must_use]
628pub fn described(resources: &[ResourceSpec], address: &ActionAddress) -> Option<ActionDescriptor> {
629 locate(resources, address).map(|(resource, action)| describe(resource, action))
630}
631
632fn describe(resource: &ResourceSpec, action: &ActionSpec) -> ActionDescriptor {
633 let view = ResourceViewDescriptor::declared_for(resource, &action.id);
634 ActionDescriptor {
635 address: ActionAddress::new(resource.id.as_str(), &action.id),
636 semantic_identity: resource.semantic_identity.clone(),
637 resource_kind: resource.kind.clone(),
638 resource_label: resource.label.clone(),
639 action_label: action.label.clone(),
640 keywords: action.keywords.clone(),
641 did: action.did.clone(),
642 icon: action.icon.clone(),
643 description: action.description.clone(),
644 state: action.state.clone(),
645 locus: action.locus,
646 kind: action.kind,
647 contract: action.contract.clone(),
648 input: InputSpec::of(action.input()),
649 params: action.params().to_vec(),
650 view,
651 }
652}
653
654pub fn resolve<'a>(
657 resources: &'a [ResourceSpec],
658 address: &ActionAddress,
659) -> Option<&'a ActionSpec> {
660 locate(resources, address).map(|(_, spec)| spec)
661}
662
663pub fn locate<'a>(
666 resources: &'a [ResourceSpec],
667 address: &ActionAddress,
668) -> Option<(&'a ResourceSpec, &'a ActionSpec)> {
669 fn walk<'a>(
670 r: &'a ResourceSpec,
671 address: &ActionAddress,
672 ) -> Option<(&'a ResourceSpec, &'a ActionSpec)> {
673 if r.id.as_str() == address.resource
674 && let Some(spec) = r.actions.iter().find(|a| a.id == address.action)
675 {
676 return Some((r, spec));
677 }
678 r.children.iter().find_map(|c| walk(c, address))
679 }
680 resources.iter().find_map(|r| walk(r, address))
681}
682
683pub fn published(
688 resources: &[ResourceSpec],
689 resource: &str,
690 action: &str,
691) -> Option<ActionAddress> {
692 fn walk(r: &ResourceSpec, resource: &str, action: &str) -> Option<ActionAddress> {
693 if r.id.as_str() == resource
694 && let Some(address) = r.action_address(action)
695 {
696 return Some(address);
697 }
698 r.children.iter().find_map(|c| walk(c, resource, action))
699 }
700 resources.iter().find_map(|r| walk(r, resource, action))
701}
702
703pub fn spec_of<'a>(
707 resources: &'a [ResourceSpec],
708 resource: &str,
709 action: &str,
710) -> Option<&'a ActionSpec> {
711 published(resources, resource, action).and_then(|address| resolve(resources, &address))
712}
713
714pub fn encode(
728 resources: &[ResourceSpec],
729 address: &ActionAddress,
730 argument: Option<&str>,
731) -> Result<EncodedAction, ApiError> {
732 let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
733 ensure_available(spec)?;
734 spec.validate_deferred_shape()
735 .map_err(|error| ApiError::InvalidArguments(error.to_string()))?;
736 match (spec.input(), argument) {
737 (ActionInput::Deferred { type_id }, None) => {
738 let Some(encoded) = spec.build_deferred() else {
739 return Err(ApiError::Unknown(address.clone()));
740 };
741 if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
742 return Err(ApiError::InvalidArguments(
743 String::from_utf8_lossy(&encoded.payload).into_owned(),
744 ));
745 }
746 if encoded.type_id != *type_id {
747 return Err(ApiError::InvalidArguments(format!(
748 "builder returned `{}` but declared `{type_id}`",
749 encoded.type_id
750 )));
751 }
752 Ok(encoded)
753 }
754 (ActionInput::Deferred { .. }, Some(_)) => {
755 Err(ApiError::UnexpectedArgument(address.clone()))
756 }
757 (ActionInput::Immediate(_), None) => spec
758 .encode_immediate()
759 .map(std::sync::Arc::unwrap_or_clone)
760 .ok_or_else(|| ApiError::Unknown(address.clone())),
761 (ActionInput::Immediate(_), Some(_)) => Err(ApiError::UnexpectedArgument(address.clone())),
762 (ActionInput::Prompted { .. }, Some(text)) => {
763 let Some(encoded) = spec.build_text(text) else {
764 return Err(ApiError::Unknown(address.clone()));
765 };
766 if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
767 return Err(ApiError::InvalidArguments(
768 String::from_utf8_lossy(&encoded.payload).into_owned(),
769 ));
770 }
771 Ok(encoded)
772 }
773 (ActionInput::Prompted { .. }, None)
777 if !spec.params().is_empty() && spec.params().iter().all(|param| !param.required) =>
778 {
779 let encoded = spec
780 .build_json(&serde_json::Map::new())
781 .map_err(ApiError::from)?;
782 if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
783 return Err(ApiError::InvalidArguments(
784 String::from_utf8_lossy(&encoded.payload).into_owned(),
785 ));
786 }
787 Ok(encoded)
788 }
789 (ActionInput::Prompted { .. }, None) => Err(ApiError::MissingArgument(address.clone())),
790 }
791}
792
793pub fn encode_json(
804 resources: &[ResourceSpec],
805 address: &ActionAddress,
806 arguments: &serde_json::Map<String, serde_json::Value>,
807) -> Result<EncodedAction, ApiError> {
808 let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
809 ensure_available(spec)?;
810 let encoded = spec.build_json(arguments).map_err(ApiError::from)?;
811 if encoded.type_id == crate::resource::INVALID_ARGUMENTS_TYPE {
812 return Err(ApiError::InvalidArguments(
813 String::from_utf8_lossy(&encoded.payload).into_owned(),
814 ));
815 }
816 Ok(encoded)
817}
818
819pub fn admit(
832 resources: &[ResourceSpec],
833 address: &ActionAddress,
834 arguments: &serde_json::Map<String, serde_json::Value>,
835 confirmation: Option<&crate::remote::Confirmation>,
836) -> Result<EncodedAction, ApiError> {
837 let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
838 ensure_available(spec)?;
839 if !spec.confirmation_for_json(arguments).met_by(confirmation) {
840 return Err(ApiError::ConfirmationRequired);
841 }
842 encode_json(resources, address, arguments)
843}
844
845fn ensure_available(spec: &ActionSpec) -> Result<(), ApiError> {
846 match &spec.contract.availability {
847 crate::Availability::Available => Ok(()),
848 crate::Availability::Unavailable { code, reason } => Err(ApiError::Unavailable {
849 code: code.clone(),
850 reason: reason.clone(),
851 }),
852 }
853}
854
855#[derive(Clone, Copy, Debug)]
861pub struct InvocationProvenance<'a> {
862 pub actor: &'a [u8],
864 pub ambient: Option<&'a ActionContext>,
866}
867
868impl<'a> InvocationProvenance<'a> {
869 #[must_use]
872 pub const fn caller(actor: &'a [u8]) -> Self {
873 Self {
874 actor,
875 ambient: None,
876 }
877 }
878
879 #[must_use]
882 pub const fn within(self, ambient: &'a ActionContext) -> Self {
883 Self {
884 actor: self.actor,
885 ambient: Some(ambient),
886 }
887 }
888}
889
890pub fn invoke(
917 doc: &mut crate::action::Doc,
918 resources: &[ResourceSpec],
919 address: &ActionAddress,
920 argument: Option<&str>,
921 (provenance, confirmed): (InvocationProvenance<'_>, bool),
922 registry: &ActionRegistry,
923 transport: &mut dyn ActionTransport,
924) -> Result<Dispatched, ApiError> {
925 ensure_confirmation(resources, address, confirmed, |spec| {
926 spec.confirmation_for_argument(argument)
927 })?;
928 ensure_deferred_local_owner(resources, address, registry)?;
929 let encoded = encode(resources, address, argument)?;
930 dispatch_encoded_with_context(
931 doc, resources, address, encoded, provenance, registry, transport,
932 )
933}
934
935pub fn invoke_json(
941 doc: &mut crate::action::Doc,
942 resources: &[ResourceSpec],
943 address: &ActionAddress,
944 arguments: &serde_json::Map<String, serde_json::Value>,
945 (provenance, confirmed): (InvocationProvenance<'_>, bool),
946 registry: &ActionRegistry,
947 transport: &mut dyn ActionTransport,
948) -> Result<Dispatched, ApiError> {
949 ensure_confirmation(resources, address, confirmed, |spec| {
950 spec.confirmation_for_json(arguments)
951 })?;
952 ensure_deferred_local_owner(resources, address, registry)?;
953 let encoded = encode_json(resources, address, arguments)?;
954 dispatch_encoded_with_context(
955 doc, resources, address, encoded, provenance, registry, transport,
956 )
957}
958
959fn ensure_confirmation(
962 resources: &[ResourceSpec],
963 address: &ActionAddress,
964 confirmed: bool,
965 policy: impl FnOnce(&ActionSpec) -> crate::ConfirmationPolicy,
966) -> Result<(), ApiError> {
967 let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
968 if !matches!(policy(spec), crate::ConfirmationPolicy::None) && !confirmed {
969 return Err(ApiError::ConfirmationRequired);
970 }
971 Ok(())
972}
973
974fn ensure_deferred_local_owner(
977 resources: &[ResourceSpec],
978 address: &ActionAddress,
979 registry: &ActionRegistry,
980) -> Result<(), ApiError> {
981 let spec = resolve(resources, address).ok_or_else(|| ApiError::Unknown(address.clone()))?;
982 if spec.deferred_invocation_type().is_some()
983 || matches!(spec.input(), ActionInput::Deferred { .. })
984 {
985 spec.validate_deferred_shape()
986 .map_err(|error| ApiError::InvalidArguments(error.to_string()))?;
987 if spec.kind != OperationKind::Document || spec.locus != ExecutionLocus::ClientLocal {
988 return Err(ApiError::Unavailable {
989 code: "deferred_owner_required".into(),
990 reason: "This creation must use the owning application's address-based action API"
991 .into(),
992 });
993 }
994 if let Some(type_id) = spec.deferred_invocation_type()
995 && !registry.contains(type_id)
996 {
997 return Err(ApiError::UnregisteredType(type_id.into()));
998 }
999 }
1000 Ok(())
1001}
1002
1003fn dispatch_encoded_with_context(
1004 doc: &mut crate::action::Doc,
1005 resources: &[ResourceSpec],
1006 address: &ActionAddress,
1007 encoded: EncodedAction,
1008 provenance: InvocationProvenance<'_>,
1009 registry: &ActionRegistry,
1010 transport: &mut dyn ActionTransport,
1011) -> Result<Dispatched, ApiError> {
1012 let resource = find_resource(resources, &address.resource)
1013 .ok_or_else(|| ApiError::Unknown(address.clone()))?;
1014 let spec = resource
1015 .actions
1016 .iter()
1017 .find(|candidate| candidate.id == address.action)
1018 .ok_or_else(|| ApiError::Unknown(address.clone()))?;
1019 if spec.kind != OperationKind::Document {
1020 return Err(ApiError::Failed(format!(
1021 "{} operation must be handled by the owning application",
1022 spec.kind.as_str()
1023 )));
1024 }
1025 let mut context = spec.history_context(resource.id.as_str(), &resource.kind, &resource.label);
1026 if let Some(ambient) = provenance.ambient {
1027 context = context.enriched_by(ambient);
1028 }
1029 if !spec.carries_actions()
1032 && let Some(described) = Described::of_published(
1033 &encoded,
1034 crate::ActionKey::new("", &resource.kind, &spec.id),
1035 )
1036 {
1037 context = context.with_described(described);
1038 }
1039 let action = registry.decode(&encoded).map_err(ApiError::decoding)?;
1040 if spec.deferred_invocation_type().is_some() && action.locus() != spec.locus {
1041 return Err(ApiError::Failed(
1042 "Deferred action locus differs from its declaration".into(),
1043 ));
1044 }
1045 dispatch_by_with_context(
1046 doc,
1047 action.as_ref(),
1048 encoded,
1049 transport,
1050 Some(provenance.actor),
1051 context,
1052 )
1053 .map_err(ApiError::refused)
1054}
1055
1056#[must_use]
1058pub fn find_resource<'a>(resources: &'a [ResourceSpec], id: &str) -> Option<&'a ResourceSpec> {
1059 fn walk<'a>(resource: &'a ResourceSpec, id: &str) -> Option<&'a ResourceSpec> {
1060 if resource.id.as_str() == id {
1061 return Some(resource);
1062 }
1063 resource.children.iter().find_map(|child| walk(child, id))
1064 }
1065 resources.iter().find_map(|resource| walk(resource, id))
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070 use super::*;
1071 use crate::action::{Action, ActionError, Doc};
1072 use crate::executor::{LocalTransport, replay};
1073 use automerge::transaction::Transactable;
1074 use automerge::{AutoCommit, ROOT, ReadDoc, ScalarValue};
1075 use serde::{Deserialize, Serialize};
1076
1077 const NOTE_TYPE: &str = "test.note";
1078
1079 #[derive(Debug, Clone, Serialize, Deserialize)]
1080 enum Note {
1081 Star,
1082 Retitle(String),
1083 }
1084
1085 impl Action for Note {
1086 fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
1087 match self {
1088 Note::Star => {
1089 doc.put(&ROOT, "starred", ScalarValue::Boolean(true))?;
1090 }
1091 Note::Retitle(title) => {
1092 doc.put(&ROOT, "title", ScalarValue::Str(title.as_str().into()))?;
1093 }
1094 }
1095 Ok(())
1096 }
1097 }
1098
1099 fn registry() -> ActionRegistry {
1100 let mut r = ActionRegistry::new();
1101 r.register::<Note>(NOTE_TYPE);
1102 r
1103 }
1104
1105 fn encoded(action: &Note) -> EncodedAction {
1106 EncodedAction::encode(NOTE_TYPE, action).unwrap()
1107 }
1108
1109 fn note(star_does: &Note, retitle_does: fn(&str) -> Note) -> Vec<ResourceSpec> {
1113 vec![
1114 ResourceSpec::new("notes.note:1", "notes.note", "Harbour")
1115 .with_action(ActionSpec::immediate("star", "Star", NOTE_TYPE, star_does).unwrap())
1116 .with_action(ActionSpec::prompted_param(
1117 "retitle",
1118 "Rename",
1119 ActionParam::required("title", crate::ParamType::Text, "New title"),
1120 "title",
1121 ExecutionLocus::ClientLocal,
1122 move |text| encoded(&retitle_does(text)),
1123 )),
1124 ]
1125 }
1126
1127 fn open() -> Vec<ResourceSpec> {
1128 note(&Note::Star, |text| Note::Retitle(text.to_string()))
1129 }
1130
1131 fn star() -> ActionAddress {
1132 ActionAddress::new("notes.note:1", "star")
1133 }
1134
1135 fn retitle() -> ActionAddress {
1136 ActionAddress::new("notes.note:1", "retitle")
1137 }
1138
1139 fn perform(
1140 doc: &mut Doc,
1141 tree: &[ResourceSpec],
1142 address: &ActionAddress,
1143 argument: Option<&str>,
1144 ) -> Result<Dispatched, ApiError> {
1145 invoke(
1146 doc,
1147 tree,
1148 address,
1149 argument,
1150 (InvocationProvenance::caller(b"caller-key"), false),
1151 ®istry(),
1152 &mut LocalTransport::new(),
1153 )
1154 }
1155
1156 fn a_descriptor_carries_nothing_that_could_act() {
1160 let honest = open();
1161 let hijacked = note(&Note::Retitle("hijacked".into()), |_| Note::Star);
1162 assert_eq!(
1163 survey(&honest),
1164 survey(&hijacked),
1165 "descriptors that differ only in what they would run must not differ"
1166 );
1167
1168 let mut a = AutoCommit::new();
1169 perform(&mut a, &honest, &star(), None).unwrap();
1170 let mut b = AutoCommit::new();
1171 perform(&mut b, &hijacked, &star(), None).unwrap();
1172
1173 assert_eq!(
1174 a.get(&ROOT, "starred").unwrap().unwrap().0.as_bool(),
1175 Some(true)
1176 );
1177 assert!(b.get(&ROOT, "starred").unwrap().is_none());
1178 assert_eq!(
1179 b.get(&ROOT, "title")
1180 .unwrap()
1181 .unwrap()
1182 .0
1183 .into_string()
1184 .unwrap(),
1185 "hijacked",
1186 "the same descriptor performed a different operation — so it holds none of it"
1187 );
1188
1189 let described = survey(&honest);
1191 drop(honest);
1192 assert_eq!(described.len(), 2);
1193 }
1194
1195 tilo_test_env::scenario! {
1196 fn a_survey_describes_without_acting;
1197
1198 phase surveying_through_the_api_describes_without_acting;
1199 {
1203 a_descriptor_carries_nothing_that_could_act();
1204 survey_annotates_only_the_declared_view_open_action();
1205 enumeration_leaves_the_document_untouched();
1206 }
1207
1208 phase a_survey_names_the_row_each_action_stands_in;
1209 {
1213 let leaf = ResourceSpec::new("notes.note:1", "notes.note", "Harbour")
1214 .with_action(ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star).unwrap());
1215 let folder = ResourceSpec::new("notes.folder:a", "notes.folder", "Trips")
1216 .with_action(
1217 ActionSpec::immediate("archive", "Archive", NOTE_TYPE, &Note::Star).unwrap(),
1218 )
1219 .with_child(leaf);
1220 let placed = survey_placed(std::slice::from_ref(&folder));
1221 let at = |action: &str| {
1222 placed
1223 .iter()
1224 .find(|placed| placed.action.address.action == action)
1225 .expect("the action was surveyed")
1226 };
1227 let archived = at("archive");
1228 assert_eq!(archived.parent, "", "the folder stands at the top level");
1229 assert!(archived.has_children, "the folder holds the note below it");
1230 let starred = at("star");
1231 assert_eq!(starred.parent, "notes.folder:a", "the note is under it");
1232 assert!(
1233 !starred.has_children,
1234 "nothing stands below the note: the listing ends here"
1235 );
1236 assert_eq!(
1238 survey(std::slice::from_ref(&folder))
1239 .iter()
1240 .map(|descriptor| descriptor.address.action.clone())
1241 .collect::<Vec<_>>(),
1242 placed
1243 .iter()
1244 .map(|placed| placed.action.address.action.clone())
1245 .collect::<Vec<_>>(),
1246 );
1247 }
1248 }
1249
1250 fn survey_annotates_only_the_declared_view_open_action() {
1251 let open =
1252 ActionSpec::operation("open", "Open", OperationKind::View, "notes.open", &()).unwrap();
1253 let select =
1254 ActionSpec::operation("select", "Select", OperationKind::View, "notes.select", &())
1255 .unwrap();
1256 let resource = ResourceSpec::new("note:1", "notes.note", "Harbour")
1257 .with_action(open)
1258 .with_action(select)
1259 .with_view(
1260 crate::ResourceViewSpec::new("editor", "Editor", "open")
1261 .with_description("Edit the note")
1262 .with_primary(true),
1263 );
1264
1265 let descriptors = survey(&[resource]);
1266 let open = descriptors
1267 .iter()
1268 .find(|descriptor| descriptor.address.action == "open")
1269 .unwrap();
1270 assert_eq!(
1271 open.view,
1272 Some(ResourceViewDescriptor {
1273 id: "editor".into(),
1274 label: "Editor".into(),
1275 description: Some("Edit the note".into()),
1276 open_action: "open".into(),
1277 primary: true,
1278 range: None,
1279 mount: None,
1280 desktop: false,
1281 })
1282 );
1283 assert!(
1284 descriptors
1285 .iter()
1286 .find(|descriptor| descriptor.address.action == "select")
1287 .unwrap()
1288 .view
1289 .is_none()
1290 );
1291 }
1292
1293 fn an_address_that_no_longer_resolves_is_refused_not_redirected() {
1297 let address = survey(&open())[0].address.clone();
1298 assert_eq!(address, star());
1299
1300 let now = vec![
1302 ResourceSpec::new("notes.note:2", "notes.note", "Log").with_action(
1303 ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star).unwrap(),
1304 ),
1305 ];
1306 assert!(resolve(&now, &address).is_none());
1307
1308 let mut doc = AutoCommit::new();
1309 let before = doc.get_heads();
1310 let err = perform(&mut doc, &now, &address, None).unwrap_err();
1311
1312 assert_eq!(err, ApiError::Unknown(address));
1313 assert_eq!(err.code(), "unknown_action");
1314 assert_eq!(doc.get_heads(), before, "a refused address left no change");
1315 assert!(doc.get(&ROOT, "starred").unwrap().is_none());
1316 }
1317
1318 fn an_argument_that_does_not_match_the_declaration_is_refused() {
1322 let tree = open();
1323 let described = survey(&tree);
1324 let spec = described.iter().find(|d| d.address == retitle()).unwrap();
1325 assert!(spec.input.wants_text());
1326 assert!(!spec.input.wants_content());
1327
1328 let mut doc = AutoCommit::new();
1329 let before = doc.get_heads();
1330
1331 let err = perform(&mut doc, &tree, &retitle(), None).unwrap_err();
1332 assert_eq!(err, ApiError::MissingArgument(retitle()));
1333 assert_eq!(err.code(), "invalid_arguments");
1334
1335 let err = perform(&mut doc, &tree, &star(), Some("Log")).unwrap_err();
1336 assert_eq!(err, ApiError::UnexpectedArgument(star()));
1337 assert_eq!(err.code(), "invalid_arguments");
1338
1339 assert_eq!(doc.get_heads(), before, "a refused call left no change");
1340 assert!(doc.get(&ROOT, "title").unwrap().is_none());
1341 assert!(doc.get(&ROOT, "starred").unwrap().is_none());
1342 }
1343
1344 fn an_unregistered_action_type_is_refused_rather_than_applied() {
1348 let tree = open();
1349 let mut doc = AutoCommit::new();
1350 let before = doc.get_heads();
1351
1352 let err = invoke(
1353 &mut doc,
1354 &tree,
1355 &star(),
1356 None,
1357 (InvocationProvenance::caller(b"caller-key"), false),
1358 &ActionRegistry::new(),
1359 &mut LocalTransport::new(),
1360 )
1361 .unwrap_err();
1362
1363 assert_eq!(err, ApiError::UnregisteredType(NOTE_TYPE.into()));
1364 assert_eq!(doc.get_heads(), before);
1365 assert!(doc.get(&ROOT, "starred").unwrap().is_none());
1366 }
1367
1368 fn a_payload_its_decoder_cannot_read_is_not_called_unregistered() {
1372 #[derive(Debug, Serialize, Deserialize)]
1373 struct OtherShape {
1374 #[serde(rename = "pinned")]
1376 _pinned: bool,
1377 }
1378 impl Action for OtherShape {
1379 fn apply(&self, _doc: &mut Doc) -> Result<(), ActionError> {
1380 Ok(())
1381 }
1382 }
1383 let tree = open();
1384 let mut doc = AutoCommit::new();
1385 let before = doc.get_heads();
1386 let mut other = ActionRegistry::new();
1387 other.register::<OtherShape>(NOTE_TYPE);
1388
1389 let err = invoke(
1390 &mut doc,
1391 &tree,
1392 &star(),
1393 None,
1394 (InvocationProvenance::caller(b"caller-key"), false),
1395 &other,
1396 &mut LocalTransport::new(),
1397 )
1398 .unwrap_err();
1399
1400 let ApiError::Failed(why) = &err else {
1401 panic!("a payload the decoder cannot read is its own failure: {err:?}");
1402 };
1403 assert!(why.contains(NOTE_TYPE), "{why}");
1404 assert_eq!(doc.get_heads(), before);
1405 }
1406
1407 fn notes(doc: &AutoCommit) -> Vec<ResourceSpec> {
1410 let label = doc
1411 .get(&ROOT, "title")
1412 .ok()
1413 .flatten()
1414 .and_then(|(v, _)| v.into_string().ok())
1415 .unwrap_or_else(|| "Untitled".into());
1416 vec![
1417 ResourceSpec::new("notes.note:1", "notes.note", label).with_action(
1418 ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star).unwrap(),
1419 ),
1420 ]
1421 }
1422
1423 fn enumeration_leaves_the_document_untouched() {
1427 let mut doc = AutoCommit::new();
1428 doc.put(&ROOT, "title", ScalarValue::Str("Harbour".into()))
1429 .unwrap();
1430 doc.commit();
1431 let heads = doc.get_heads();
1432 let saved = doc.save();
1433
1434 let first = survey(¬es(&doc));
1435 let second = survey(¬es(&doc));
1436
1437 assert_eq!(first, second);
1438 assert_eq!(
1439 first.len(),
1440 1,
1441 "the survey found something to be side-effect free about"
1442 );
1443 assert_eq!(
1444 first[0].resource_label, "Harbour",
1445 "it really read the document"
1446 );
1447 assert_eq!(doc.get_heads(), heads);
1448 assert_eq!(doc.save(), saved, "surveying rewrote the document");
1449 }
1450
1451 fn a_change_through_the_api_is_attributed_to_the_caller() {
1455 let mut doc = AutoCommit::new();
1456 doc.put(&ROOT, "seed", ScalarValue::Str("s".into()))
1457 .unwrap();
1458 doc.commit();
1459 let app_actor = doc.get_actor().clone();
1460 let mut peer = AutoCommit::load(&doc.save()).unwrap();
1461
1462 let caller: &[u8] = b"maren-device-key";
1463 let notes = ActionContext::default().with_app("org.tilo.Notes", "Notes");
1465 let mut transport = LocalTransport::new();
1466 let dispatched = invoke(
1467 &mut doc,
1468 &open(),
1469 &star(),
1470 None,
1471 (InvocationProvenance::caller(caller).within(¬es), false),
1472 ®istry(),
1473 &mut transport,
1474 )
1475 .unwrap();
1476
1477 assert!(dispatched.mutated_local());
1478 let env = dispatched.envelope().clone();
1479 assert_eq!(env.actor.as_deref(), Some(caller));
1480 let context = env.context.as_ref().expect("the API supplies provenance");
1481 assert_eq!(published_verb(context), "star");
1482 assert_eq!(
1483 context
1484 .resource
1485 .as_ref()
1486 .map(|resource| resource.id.as_str()),
1487 Some("notes.note:1")
1488 );
1489
1490 let heads = doc.get_heads();
1491 let change = doc.get_change_by_hash(&heads[0]).unwrap();
1492 assert_eq!(change.actor_id().to_bytes(), caller);
1493 assert_eq!(
1494 change
1495 .message()
1496 .and_then(ActionContext::from_change_message),
1497 env.context,
1498 "semantic provenance survives as part of the durable change"
1499 );
1500 assert_ne!(change.actor_id(), &app_actor, "not the app's own actor");
1501 assert_ne!(
1502 change.actor_id().to_bytes(),
1503 &env.id.actor_bytes()[..],
1504 "not the action id's derived actor"
1505 );
1506
1507 replay(&mut peer, &env, ®istry()).unwrap();
1508 assert_eq!(
1509 peer.get_heads(),
1510 heads,
1511 "attribution must not cost the identical replay"
1512 );
1513 assert_eq!(transport.replicated.len(), 1);
1514 }
1515
1516 fn ambient_task_context_reaches_api_actions_without_overwriting_resource() {
1517 let mut doc = AutoCommit::new();
1518 let mut transport = LocalTransport::new();
1519 let ambient = ActionContext::default()
1520 .with_app("org.tilo.Notes", "Notes")
1521 .with_purpose("Prepare launch")
1522 .with_group("issue:42", "Launch", "issue");
1523 let dispatched = invoke(
1524 &mut doc,
1525 &open(),
1526 &star(),
1527 None,
1528 (
1529 InvocationProvenance {
1530 actor: b"agent:ada",
1531 ambient: Some(&ambient),
1532 },
1533 false,
1534 ),
1535 ®istry(),
1536 &mut transport,
1537 )
1538 .expect("the API answered");
1539
1540 let context = dispatched.envelope().context.as_ref().expect("context");
1541 assert_eq!(published_verb(context), "star");
1542 assert_eq!(context.purpose.as_deref(), Some("Prepare launch"));
1543 assert_eq!(
1544 context.group.as_ref().map(|group| group.id.as_str()),
1545 Some("issue:42")
1546 );
1547 assert_eq!(
1548 context
1549 .resource
1550 .as_ref()
1551 .map(|resource| resource.id.as_str()),
1552 Some("notes.note:1")
1553 );
1554 }
1555
1556 fn consequential_actions_cannot_cross_the_api_without_consent() {
1557 let resources = vec![
1558 ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
1559 ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star)
1560 .unwrap()
1561 .with_contract(ActionContract {
1562 confirmation: crate::ConfirmationPolicy::Confirm,
1563 ..ActionContract::default()
1564 }),
1565 ),
1566 ];
1567 let mut doc = AutoCommit::new();
1568 let mut transport = LocalTransport::new();
1569
1570 let refusal = invoke(
1571 &mut doc,
1572 &resources,
1573 &star(),
1574 None,
1575 (InvocationProvenance::caller(b"caller-key"), false),
1576 ®istry(),
1577 &mut transport,
1578 )
1579 .unwrap_err();
1580 assert_eq!(refusal, ApiError::ConfirmationRequired);
1581 assert!(doc.get(&ROOT, "starred").unwrap().is_none());
1582
1583 invoke(
1584 &mut doc,
1585 &resources,
1586 &star(),
1587 None,
1588 (InvocationProvenance::caller(b"caller-key"), true),
1589 ®istry(),
1590 &mut transport,
1591 )
1592 .expect("a policy check may explicitly attest confirmation");
1593 assert_eq!(
1594 doc.get(&ROOT, "starred").unwrap().unwrap().0.as_bool(),
1595 Some(true)
1596 );
1597 }
1598
1599 fn edit_by_value() -> Vec<ResourceSpec> {
1602 vec![
1603 ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
1604 ActionSpec::typed(
1605 "edit",
1606 "Edit",
1607 "title",
1608 ExecutionLocus::ClientLocal,
1609 vec![ActionParam::required(
1610 "title",
1611 crate::ParamType::Text,
1612 "Title",
1613 )],
1614 |args| encoded(&Note::Retitle(args.text("title").unwrap_or("").to_owned())),
1615 )
1616 .for_audience(crate::Audience::Agents)
1617 .with_risk(|args| {
1618 if args.text("title").is_some_and(str::is_empty) {
1619 crate::RiskLevel::Destructive
1620 } else {
1621 crate::RiskLevel::Low
1622 }
1623 }),
1624 ),
1625 ]
1626 }
1627
1628 fn edit() -> ActionAddress {
1629 ActionAddress::new("notes.note:1", "edit")
1630 }
1631
1632 fn title(value: &str) -> serde_json::Map<String, serde_json::Value> {
1633 serde_json::Map::from_iter([("title".to_owned(), serde_json::json!(value))])
1634 }
1635
1636 fn stored_title(doc: &AutoCommit) -> Option<String> {
1637 doc.get(&ROOT, "title")
1638 .unwrap()
1639 .and_then(|(value, _)| value.into_string().ok())
1640 }
1641
1642 fn a_value_classified_as_destructive_needs_the_same_consent() {
1643 let resources = edit_by_value();
1644 let mut doc = AutoCommit::new();
1645 let mut transport = LocalTransport::new();
1646 let registry = registry();
1647 let mut run = |doc: &mut AutoCommit, value: &str, confirmed: bool| {
1648 invoke_json(
1649 doc,
1650 &resources,
1651 &edit(),
1652 &title(value),
1653 (InvocationProvenance::caller(b"caller-key"), confirmed),
1654 ®istry,
1655 &mut transport,
1656 )
1657 .map(|_| ())
1658 };
1659
1660 run(&mut doc, "Harbour", false).expect("an ordinary value runs");
1661 assert_eq!(
1662 run(&mut doc, "", false).unwrap_err(),
1663 ApiError::ConfirmationRequired
1664 );
1665 assert_eq!(
1666 stored_title(&doc).as_deref(),
1667 Some("Harbour"),
1668 "the refused value changed nothing"
1669 );
1670 run(&mut doc, "", true).expect("a confirmed destructive value runs");
1671 assert_eq!(stored_title(&doc).as_deref(), Some(""));
1672
1673 let mut transport = LocalTransport::new();
1674 assert_eq!(
1675 invoke(
1676 &mut doc,
1677 &resources,
1678 &edit(),
1679 Some(""),
1680 (InvocationProvenance::caller(b"caller-key"), false),
1681 ®istry,
1682 &mut transport,
1683 )
1684 .unwrap_err(),
1685 ApiError::ConfirmationRequired
1686 );
1687 }
1688
1689 fn agent_session() -> ActionContext {
1691 ActionContext::default()
1692 .with_app("org.tilo.Agent", "Agent")
1693 .with_purpose("Remove the draft marks")
1694 .with_group("agent-session:7", "Remove the draft marks", "agent-session")
1695 }
1696
1697 fn published_verb(context: &ActionContext) -> &str {
1702 let Some(crate::Did::Verb(verb)) = &context.what else {
1703 panic!("a verb: {context:?}");
1704 };
1705 assert_eq!(verb.action.kind, "notes.note");
1706 assert!(!verb.action.app.is_empty(), "the app is filled in");
1707 &verb.action.action
1708 }
1709
1710 fn assert_recorded_within_run(doc: &mut AutoCommit, action: &str) {
1711 let heads = doc.get_heads();
1712 let change = doc
1713 .get_change_by_hash(&heads[0])
1714 .expect("the API committed");
1715 assert_eq!(change.actor_id().to_bytes(), b"agent:ada");
1716 let context = change
1717 .message()
1718 .and_then(ActionContext::from_change_message)
1719 .expect("the change carries its semantic provenance");
1720 assert_eq!(published_verb(&context), action);
1721 assert_eq!(
1722 context
1723 .resource
1724 .as_ref()
1725 .map(|resource| resource.id.as_str()),
1726 Some("notes.note:1"),
1727 "the resource stays authoritative"
1728 );
1729 let group = context.group.as_ref().expect("the run's group is recorded");
1730 assert_eq!(group.id, "agent-session:7");
1731 assert_eq!(group.kind, "agent-session");
1732 assert_eq!(context.purpose.as_deref(), Some("Remove the draft marks"));
1733 }
1734
1735 tilo_test_env::scenario! {
1736 fn an_invocation_through_the_api_is_checked_and_recorded;
1737
1738 phase invoking_through_the_api_refuses_mismatches_and_attributes_the_caller;
1739 {
1744 an_address_that_no_longer_resolves_is_refused_not_redirected();
1745 an_argument_that_does_not_match_the_declaration_is_refused();
1746 an_unregistered_action_type_is_refused_rather_than_applied();
1747 a_payload_its_decoder_cannot_read_is_not_called_unregistered();
1748 a_change_through_the_api_is_attributed_to_the_caller();
1749 ambient_task_context_reaches_api_actions_without_overwriting_resource();
1750 }
1751
1752 phase an_optional_only_prompt_runs_without_its_argument;
1753 {
1757 let tree = vec![
1758 ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
1759 ActionSpec::prompted_param(
1760 "retitle",
1761 "Rename",
1762 ActionParam::optional("title", crate::ParamType::Text, "New title"),
1763 "title",
1764 ExecutionLocus::ClientLocal,
1765 |text| encoded(&Note::Retitle(format!("[{text}]"))),
1766 ),
1767 ),
1768 ];
1769 let mut doc = AutoCommit::new();
1770 perform(&mut doc, &tree, &retitle(), None).unwrap();
1771 assert_eq!(
1772 doc.get(&ROOT, "title")
1773 .unwrap()
1774 .unwrap()
1775 .0
1776 .into_string()
1777 .unwrap(),
1778 "[]",
1779 "the omitted optional text binds as nothing typed"
1780 );
1781
1782 let mut doc = AutoCommit::new();
1783 let err = perform(&mut doc, &open(), &retitle(), None).unwrap_err();
1784 assert_eq!(err, ApiError::MissingArgument(retitle()));
1785 }
1786
1787 phase a_wire_text_argument_goes_under_the_actions_own_prompt_parameter;
1788 {
1791 let tree = open();
1792 let described = survey(&tree);
1793 let retitle_spec = described.iter().find(|d| d.address == retitle()).unwrap();
1794 assert_eq!(retitle_spec.prompt_param(), Some("title"));
1795 let lone = serde_json::json!({ crate::PROMPTED_PARAM: "Log" })
1796 .as_object()
1797 .unwrap()
1798 .clone();
1799 assert_eq!(
1800 retitle_spec.bind_prompt_text(lone.clone()),
1801 serde_json::json!({"title": "Log"})
1802 .as_object()
1803 .unwrap()
1804 .clone()
1805 );
1806 let named = serde_json::json!({"title": "Log"})
1808 .as_object()
1809 .unwrap()
1810 .clone();
1811 assert_eq!(retitle_spec.bind_prompt_text(named.clone()), named);
1812 let star_spec = described.iter().find(|d| d.address == star()).unwrap();
1814 assert_eq!(star_spec.prompt_param(), None);
1815 assert_eq!(star_spec.bind_prompt_text(lone.clone()), lone);
1816 }
1817
1818 phase consequential_api_actions_need_consent_whatever_form_the_argument_takes;
1819 {
1823 consequential_actions_cannot_cross_the_api_without_consent();
1824 a_value_classified_as_destructive_needs_the_same_consent();
1825 effective_confirmation_reads_every_argument_form();
1826 }
1827
1828 phase a_confirmed_invocation_inside_a_run_is_recorded_with_its_group;
1829 {
1833 let resources = vec![
1834 ResourceSpec::new("notes.note:1", "notes.note", "Harbour").with_action(
1835 ActionSpec::immediate("star", "Star", NOTE_TYPE, &Note::Star)
1836 .unwrap()
1837 .destructive(),
1838 ),
1839 ];
1840 let run = agent_session();
1841 let provenance = InvocationProvenance::caller(b"agent:ada").within(&run);
1842 let mut doc = AutoCommit::new();
1843 let mut transport = LocalTransport::new();
1844
1845 assert_eq!(
1846 invoke(
1847 &mut doc,
1848 &resources,
1849 &star(),
1850 None,
1851 (provenance, false),
1852 ®istry(),
1853 &mut transport,
1854 )
1855 .unwrap_err(),
1856 ApiError::ConfirmationRequired
1857 );
1858 let dispatched = invoke(
1859 &mut doc,
1860 &resources,
1861 &star(),
1862 None,
1863 (provenance, true),
1864 ®istry(),
1865 &mut transport,
1866 )
1867 .expect("a confirmed destructive action runs");
1868
1869 assert_eq!(
1870 dispatched
1871 .envelope()
1872 .context
1873 .as_ref()
1874 .and_then(|context| context.group.as_ref())
1875 .map(|group| group.id.as_str()),
1876 Some("agent-session:7"),
1877 "the replicated envelope carries the run too"
1878 );
1879 assert_recorded_within_run(&mut doc, "star");
1880 }
1881
1882 phase typed_invocations_inside_a_run_are_recorded_with_its_group;
1883 {
1887 let resources = edit_by_value();
1888 let run = agent_session();
1889 let provenance = InvocationProvenance::caller(b"agent:ada").within(&run);
1890 let mut doc = AutoCommit::new();
1891 let mut transport = LocalTransport::new();
1892
1893 invoke_json(
1894 &mut doc,
1895 &resources,
1896 &edit(),
1897 &title("Harbour"),
1898 (provenance, false),
1899 ®istry(),
1900 &mut transport,
1901 )
1902 .expect("an ordinary value runs");
1903 assert_recorded_within_run(&mut doc, "edit");
1904
1905 invoke_json(
1906 &mut doc,
1907 &resources,
1908 &edit(),
1909 &title(""),
1910 (provenance, true),
1911 ®istry(),
1912 &mut transport,
1913 )
1914 .expect("a confirmed destructive value runs");
1915 assert_eq!(stored_title(&doc).as_deref(), Some(""));
1916 assert_recorded_within_run(&mut doc, "edit");
1917 }
1918 }
1919
1920 fn effective_confirmation_reads_every_argument_form() {
1921 let resources = edit_by_value();
1922 let spec = resolve(&resources, &edit()).unwrap();
1923 let none = crate::ConfirmationPolicy::None;
1924 let confirm = crate::ConfirmationPolicy::Confirm;
1925 assert_eq!(spec.confirmation_for_json(&title("x")), none);
1926 assert_eq!(spec.confirmation_for_json(&title("")), confirm);
1927 assert_eq!(spec.confirmation_for_argument(Some("x")), none);
1928 assert_eq!(spec.confirmation_for_argument(Some("")), confirm);
1929 let typed = format!("{}{{\"title\":\"\"}}", crate::ARGUMENTS_JSON_PREFIX);
1930 assert_eq!(spec.confirmation_for_argument(Some(&typed)), confirm);
1931 assert_eq!(spec.confirmation_for_json(&serde_json::Map::new()), none);
1933
1934 assert!(!spec.reaches_people() && !spec.contract.reaches_people());
1935 assert!(spec.contract.confirmation_depends_on_arguments());
1936 assert_eq!(spec.contract.confirmation, none);
1937 assert_eq!(spec.contract.advertised_confirmation(), confirm);
1938 assert!(spec.contract.validate_declaration().is_empty());
1939
1940 let declared = spec.clone().destructive();
1942 assert_eq!(declared.confirmation_for_json(&title("x")), confirm);
1943 }
1944
1945 const OP: &str = "test.operation";
1946
1947 fn published_tree() -> Vec<ResourceSpec> {
1950 use crate::{ActionContract, ConfirmationPolicy, ParamType, RiskLevel};
1951 let encode =
1952 |value: serde_json::Value| EncodedAction::encode_operation(OP, &value).unwrap();
1953 vec![
1954 ResourceSpec::new("session", "test.session", "Session")
1955 .with_action(ActionSpec::typed_operation(
1956 "rename",
1957 "Rename",
1958 "name",
1959 OperationKind::Effect,
1960 OP,
1961 vec![crate::ActionParam::required(
1962 "name",
1963 ParamType::Text,
1964 "New name",
1965 )],
1966 move |args| encode(serde_json::json!({"rename": args.text("name")})),
1967 ))
1968 .with_action(
1969 ActionSpec::operation("reset", "Reset", OperationKind::Effect, OP, &"reset")
1970 .unwrap()
1971 .unavailable("not_now", "Finish the current step first"),
1972 )
1973 .with_child(
1974 ResourceSpec::new("disk:/dev/vdb", "test.disk", "vdb").with_action(
1975 ActionSpec::operation(
1976 "erase",
1977 "Erase",
1978 OperationKind::Effect,
1979 OP,
1980 &"erase",
1981 )
1982 .unwrap()
1983 .destructive()
1984 .with_contract(ActionContract {
1985 risk: RiskLevel::Destructive,
1986 confirmation: ConfirmationPolicy::Phrase {
1987 phrase: "/dev/vdb".into(),
1988 },
1989 ..ActionContract::default()
1990 }),
1991 ),
1992 )
1993 .with_child(
1994 ResourceSpec::new("power", "test.power", "Power").with_action(
1995 ActionSpec::operation(
1996 "off",
1997 "Power off",
1998 OperationKind::Effect,
1999 OP,
2000 &"off",
2001 )
2002 .unwrap()
2003 .privileged(),
2004 ),
2005 ),
2006 ]
2007 }
2008
2009 #[test]
2010 fn a_published_tree_is_listed_and_admits_only_exact_confirmed_bindings() {
2011 use crate::remote::{CataloguePage, CatalogueQuery, Confirmation};
2012 let tree = published_tree();
2013 let page = CataloguePage::published("test", &tree, &CatalogueQuery::default());
2014 assert_eq!(page.rows.len(), 2);
2016 assert!(page.rows.iter().all(|row| row.provider == "test"));
2017 let held = CatalogueQuery {
2018 parent_resource: Some("session".into()),
2019 ..CatalogueQuery::default()
2020 };
2021 let held = CataloguePage::published("test", &tree, &held);
2022 assert_eq!(held.rows.len(), 2);
2023 let erase = held
2024 .rows
2025 .iter()
2026 .find_map(|row| row.action.as_ref().filter(|a| a.address.action == "erase"))
2027 .unwrap();
2028 assert_eq!(erase.address.resource, "disk:/dev/vdb");
2029 let narrowed = CatalogueQuery {
2030 needle: "power".into(),
2031 parent_resource: Some("session".into()),
2032 ..CatalogueQuery::default()
2033 };
2034 assert_eq!(
2035 CataloguePage::published("test", &tree, &narrowed)
2036 .rows
2037 .len(),
2038 1
2039 );
2040
2041 let args = |value: serde_json::Value| value.as_object().unwrap().clone();
2042 let admitted = |resource: &str, action: &str, value, confirmation: Option<Confirmation>| {
2043 admit(
2044 &tree,
2045 &ActionAddress::new(resource, action),
2046 &args(value),
2047 confirmation.as_ref(),
2048 )
2049 };
2050 assert_eq!(
2051 admitted("session", "rename", serde_json::json!({"name": "x"}), None)
2052 .unwrap()
2053 .type_id,
2054 OP
2055 );
2056 for (resource, action, value, refusal) in [
2057 ("session", "nope", serde_json::json!({}), "unknown"),
2058 ("session", "rename", serde_json::json!({}), "argument"),
2059 (
2060 "session",
2061 "rename",
2062 serde_json::json!({"name": 3}),
2063 "argument",
2064 ),
2065 (
2066 "session",
2067 "rename",
2068 serde_json::json!({"name": "x", "extra": 1}),
2069 "argument",
2070 ),
2071 ("session", "reset", serde_json::json!({}), "unavailable"),
2072 ] {
2073 let error = admitted(resource, action, value, None).unwrap_err();
2074 let kind = match error {
2075 ApiError::Unknown(_) => "unknown",
2076 ApiError::Unavailable { .. } => "unavailable",
2077 ApiError::MissingArgument(_)
2078 | ApiError::UnexpectedArgument(_)
2079 | ApiError::InvalidArguments(_) => "argument",
2080 other => panic!("{other:?}"),
2081 };
2082 assert_eq!(kind, refusal, "{action}");
2083 }
2084 let erase = |confirmation| {
2085 admitted(
2086 "disk:/dev/vdb",
2087 "erase",
2088 serde_json::json!({}),
2089 confirmation,
2090 )
2091 };
2092 for wrong in [
2093 None,
2094 Some(Confirmation::Phrase("/dev/vda".into())),
2095 Some(Confirmation::Operated),
2096 ] {
2097 assert!(matches!(erase(wrong), Err(ApiError::ConfirmationRequired)));
2098 }
2099 assert!(erase(Some(Confirmation::Phrase("/dev/vdb".into()))).is_ok());
2100 let off = |confirmation| admitted("power", "off", serde_json::json!({}), confirmation);
2102 for claimed in [
2103 None,
2104 Some(Confirmation::Operated),
2105 Some(Confirmation::Phrase("off".into())),
2106 ] {
2107 assert!(matches!(off(claimed), Err(ApiError::ConfirmationRequired)));
2108 }
2109 }
2110}