1use serde::{Deserialize, Serialize};
21
22use crate::{
23 ActionContract, ActionDescriptor, ActionParam, ActionSpec, ApiError, ExecutionLocus,
24 OperationKind,
25};
26
27pub const REQUIRES_TAG_PREFIX: &str = "tilo.requires.";
29
30pub const PRESENCE_VIEW_TAG: &str = "tilo.presence-view";
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
40#[serde(rename_all = "kebab-case")]
41pub enum ContextRequirement {
42 Caret,
44 Selection,
46 FindHits,
48}
49
50impl ContextRequirement {
51 pub const ALL: [Self; 3] = [Self::Caret, Self::Selection, Self::FindHits];
52
53 pub const fn tag(self) -> &'static str {
55 match self {
56 Self::Caret => "tilo.requires.caret",
57 Self::Selection => "tilo.requires.selection",
58 Self::FindHits => "tilo.requires.find-hits",
59 }
60 }
61
62 pub const fn refusal_code(self) -> &'static str {
64 match self {
65 Self::Caret => "needs-caret",
66 Self::Selection => "needs-selection",
67 Self::FindHits => "needs-find-hits",
68 }
69 }
70
71 pub fn refusal(self) -> ApiError {
74 let reason = match self {
75 Self::Caret => "Place the caret in the document first",
76 Self::Selection => "Select some text first",
77 Self::FindHits => "Find something first",
78 };
79 ApiError::Unavailable {
80 code: self.refusal_code().into(),
81 reason: reason.into(),
82 }
83 }
84
85 fn from_tag(tag: &str) -> Option<Self> {
86 Self::ALL
87 .into_iter()
88 .find(|requirement| requirement.tag() == tag)
89 }
90}
91
92impl ActionContract {
93 pub fn requirements(&self) -> Vec<ContextRequirement> {
95 let mut requirements: Vec<_> = self
96 .tags
97 .iter()
98 .filter_map(|tag| ContextRequirement::from_tag(tag))
99 .collect();
100 requirements.sort_unstable();
101 requirements.dedup();
102 requirements
103 }
104
105 pub fn is_presence_view(&self) -> bool {
108 self.tags.iter().any(|tag| tag == PRESENCE_VIEW_TAG)
109 }
110
111 fn add_tag(&mut self, tag: &str) {
112 if !self.tags.iter().any(|existing| existing == tag) {
113 self.tags.push(tag.to_owned());
114 }
115 }
116}
117
118impl ActionSpec {
119 #[must_use]
123 pub fn requires(mut self, requirement: ContextRequirement) -> Self {
124 self.type_mut().contract.add_tag(requirement.tag());
125 self
126 }
127
128 #[must_use]
131 pub fn presence_view(mut self) -> Self {
132 self.type_mut().contract.add_tag(PRESENCE_VIEW_TAG);
133 self
134 }
135}
136
137#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
140pub struct CatalogueSchemaEntry {
141 pub resource_kind: String,
142 pub action: String,
143 pub kind: OperationKind,
144 pub locus: ExecutionLocus,
145 pub contract: ActionContract,
146 pub params: Vec<ActionParam>,
147}
148
149impl CatalogueSchemaEntry {
150 pub fn of(descriptor: &ActionDescriptor) -> Self {
151 Self {
152 resource_kind: descriptor.resource_kind.clone(),
153 action: descriptor.address.action.clone(),
154 kind: descriptor.kind,
155 locus: descriptor.locus,
156 contract: descriptor.contract.clone(),
157 params: descriptor.params.clone(),
158 }
159 }
160
161 fn sort_key(&self) -> (String, String, String) {
162 (
163 self.resource_kind.clone(),
164 self.action.clone(),
165 serde_json::to_string(self).unwrap_or_default(),
166 )
167 }
168}
169
170pub fn catalogue_schema(descriptors: &[ActionDescriptor]) -> Vec<CatalogueSchemaEntry> {
175 let mut entries: Vec<_> = descriptors
176 .iter()
177 .map(CatalogueSchemaEntry::of)
178 .map(|entry| (entry.sort_key(), entry))
179 .collect();
180 entries.sort_by(|a, b| a.0.cmp(&b.0));
181 entries.dedup_by(|a, b| a.0 == b.0);
182 entries.into_iter().map(|(_, entry)| entry).collect()
183}
184
185pub fn catalogue_schema_bytes(entries: &[CatalogueSchemaEntry]) -> Vec<u8> {
188 serde_json::to_vec(entries).unwrap_or_default()
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194 use crate::{EncodedAction, ResourceSpec, api};
195
196 fn encoded(tag: &str) -> EncodedAction {
197 EncodedAction {
198 type_id: "fixture.action".into(),
199 payload: tag.as_bytes().to_vec(),
200 }
201 }
202
203 struct TwoViews {
206 views: std::collections::HashMap<String, (String, bool)>,
207 own: (String, bool),
208 }
209
210 fn tree(caret: &str, selected: bool, schema: bool) -> Vec<ResourceSpec> {
211 let mut root = ResourceSpec::new("doc", "fixture.document", "Document").with_action(
212 ActionSpec::immediate_encoded(
213 "type-text",
214 "Type",
215 ExecutionLocus::ClientLocal,
216 encoded(&format!("type@{caret}")),
217 )
218 .requires(ContextRequirement::Caret),
219 );
220 if schema || selected {
221 root = root.with_action(
222 ActionSpec::immediate_encoded(
223 "toggle-mark",
224 "Bold",
225 ExecutionLocus::ClientLocal,
226 encoded(&format!("bold@{caret}")),
227 )
228 .requires(ContextRequirement::Selection),
229 );
230 }
231 if !schema {
232 root = root.with_child(
234 ResourceSpec::new(format!("doc.caret:{caret}"), "fixture.caret", "Caret")
235 .with_action(ActionSpec::immediate_encoded(
236 "go-to",
237 "Go to",
238 ExecutionLocus::ClientLocal,
239 encoded(caret),
240 )),
241 );
242 }
243 vec![root]
244 }
245
246 impl TwoViews {
247 fn resources_for(&self, presence: Option<&crate::PresenceId>) -> Vec<ResourceSpec> {
249 let Some(presence) = presence else {
250 return tree(&self.own.0, self.own.1, false);
251 };
252 self.views
253 .get(presence.as_str())
254 .map_or_else(Vec::new, |(caret, selected)| tree(caret, *selected, false))
255 }
256 }
257
258 fn schema_tree() -> Vec<ResourceSpec> {
260 let mut schema = tree("", false, true);
261 schema.push(
262 ResourceSpec::new("doc.caret", "fixture.caret", "Caret").with_action(
263 ActionSpec::immediate_encoded(
264 "go-to",
265 "Go to",
266 ExecutionLocus::ClientLocal,
267 encoded(""),
268 ),
269 ),
270 );
271 schema
272 }
273
274 fn provider(agent_caret: &str, agent_selected: bool) -> TwoViews {
275 TwoViews {
276 views: [(
277 "window:t".to_string(),
278 (agent_caret.to_string(), agent_selected),
279 )]
280 .into(),
281 own: ("b1".into(), false),
282 }
283 }
284
285 tilo_test_env::scenario! {
286 fn a_schema_is_stable_and_per_invoker;
287
288 phase requirement_flags_round_trip_through_contract_tags;
289 {
290 let spec =
291 ActionSpec::immediate_encoded("x", "X", ExecutionLocus::ClientLocal, encoded("x"))
292 .requires(ContextRequirement::Selection)
293 .requires(ContextRequirement::Selection)
294 .requires(ContextRequirement::Caret)
295 .presence_view();
296 assert_eq!(
297 spec.contract.requirements(),
298 vec![ContextRequirement::Caret, ContextRequirement::Selection]
299 );
300 assert!(spec.contract.is_presence_view());
301 assert_eq!(spec.contract.tags.len(), 3, "tags are not duplicated");
302 assert!(matches!(
303 ContextRequirement::Selection.refusal(),
304 ApiError::Unavailable { ref code, .. } if code == "needs-selection"
305 ));
306 let json = serde_json::to_value(&spec.contract).unwrap();
307 let back: ActionContract = serde_json::from_value(json).unwrap();
308 assert_eq!(back.requirements(), spec.contract.requirements());
309 }
310
311 phase schema_is_stable_across_caret_moves_and_selection;
312 {
313 let before = provider("b1", false);
314 let after = provider("b7", true);
315 let presence = crate::PresenceId::new("window:t").unwrap();
316 assert_ne!(
318 api::survey(&before.resources_for(Some(&presence))).len(),
319 api::survey(&after.resources_for(Some(&presence))).len()
320 );
321 let schema = catalogue_schema(&api::survey(&schema_tree()));
322 for provider in [&before, &after] {
325 for entry in
326 catalogue_schema(&api::survey(&provider.resources_for(Some(&presence))))
327 {
328 assert!(
329 schema
330 .iter()
331 .any(|schema| schema.resource_kind == entry.resource_kind
332 && schema.action == entry.action
333 && schema.contract == entry.contract),
334 "{} {} missing from schema",
335 entry.resource_kind,
336 entry.action
337 );
338 }
339 }
340 }
341
342 phase schema_ignores_volatile_ids_labels_and_order;
343 {
344 let a = api::survey(&tree("b1", false, false));
345 let mut b = api::survey(&tree("b99", false, false));
346 b.reverse();
347 for descriptor in &mut b {
348 descriptor.resource_label = "Renamed".into();
349 }
350 assert_eq!(catalogue_schema(&a), catalogue_schema(&b));
351 }
352
353 phase resolution_is_per_invoker;
354 {
355 let provider = provider("b7", true);
356 let agent = crate::PresenceId::new("window:t").unwrap();
357 let address = api::ActionAddress::new("doc", "type-text");
358 let agent_tree = provider.resources_for(Some(&agent));
359 let own_tree = provider.resources_for(None);
360 assert_eq!(
361 api::encode(&agent_tree, &address, None).unwrap().payload,
362 b"type@b7".to_vec()
363 );
364 assert_eq!(
365 api::encode(&own_tree, &address, None).unwrap().payload,
366 b"type@b1".to_vec()
367 );
368 let bold = api::ActionAddress::new("doc", "toggle-mark");
371 assert!(api::resolve(&agent_tree, &bold).is_some());
372 assert!(api::resolve(&own_tree, &bold).is_none());
373 let stranger = crate::PresenceId::new("window:other").unwrap();
375 assert!(provider.resources_for(Some(&stranger)).is_empty());
376 }
377 }
378}