1use serde::{Deserialize, Serialize};
10
11use crate::{ActionApp, ActionResource, InvocationId, WorkGroup};
12use tilo_action_policy::Acting;
13
14pub const INTERACTION_VERSION: u16 = 2;
16pub const MAX_INTERACTION_BYTES: usize = 32 * 1024;
18pub const MAX_ANCHOR_ITEMS: usize = 64;
19pub const MAX_ID_BYTES: usize = 512;
20pub const MAX_LABEL_BYTES: usize = 512;
21pub const MAX_DETAIL_BYTES: usize = 2 * 1024;
22
23#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
25pub struct InteractionTextRange {
26 pub block: String,
27 pub start: u64,
28 pub end: u64,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
34pub struct InteractionGridRange {
35 pub start_col: u32,
36 pub start_row: u32,
37 pub end_col: u32,
38 pub end_row: u32,
39}
40
41#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(remote = "Self", tag = "kind", rename_all = "snake_case")]
46pub enum InteractionAnchor {
47 Resource,
49 SemanticControl { id: String },
51 Text {
53 region: String,
54 ranges: Vec<InteractionTextRange>,
55 },
56 Grid {
58 sheet: String,
59 ranges: Vec<InteractionGridRange>,
60 },
61 Objects { ids: Vec<String> },
63 ListItems { ids: Vec<String> },
65 Timeline {
67 track: Option<String>,
68 start_ms: u64,
69 end_ms: u64,
70 },
71}
72
73read_through_json_value!(InteractionAnchor);
74
75#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(remote = "Self", tag = "phase", rename_all = "snake_case")]
79pub enum InteractionPhase {
80 Locating,
81 Applying,
82 Progress {
83 label: String,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 completed: Option<u64>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 total: Option<u64>,
88 },
89 Waiting {
90 #[serde(default, skip_serializing_if = "Option::is_none")]
91 reason: Option<String>,
92 },
93 Committed,
94 Failed {
95 #[serde(default, skip_serializing_if = "Option::is_none")]
96 code: Option<String>,
97 message: String,
98 },
99 Cancelled {
100 #[serde(default, skip_serializing_if = "Option::is_none")]
101 message: Option<String>,
102 },
103}
104
105read_through_json_value!(InteractionPhase);
106
107impl InteractionPhase {
108 pub fn is_terminal(&self) -> bool {
109 matches!(
110 self,
111 Self::Committed | Self::Failed { .. } | Self::Cancelled { .. }
112 )
113 }
114}
115
116#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
118pub struct InteractionAction {
119 pub id: String,
120 pub label: String,
121 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub app: Option<ActionApp>,
123 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub step: Option<crate::StepKind>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub creates: Option<String>,
136 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub did: Option<String>,
144}
145
146#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
152pub struct SemanticInteraction {
153 pub version: u16,
154 pub invocation: InvocationId,
155 pub sequence: u64,
156 pub actor: Acting,
157 pub phase: InteractionPhase,
158 pub action: InteractionAction,
159 pub resource: ActionResource,
160 pub anchor: InteractionAnchor,
161 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub group: Option<WorkGroup>,
163}
164
165pub type InteractionUpdate = SemanticInteraction;
170
171impl SemanticInteraction {
172 #[must_use]
176 pub fn written_in(
177 &self,
178 region: Option<&str>,
179 block: &str,
180 text: &str,
181 ) -> Option<(usize, usize)> {
182 let InteractionAnchor::Text {
183 region: written,
184 ranges,
185 } = &self.anchor
186 else {
187 return None;
188 };
189 if region.is_some_and(|region| region != written) {
190 return None;
191 }
192 let range = ranges.iter().find(|range| {
195 range.block == block || (!range.block.is_empty() && block.starts_with(&range.block))
196 })?;
197 let chars = text.chars().count();
198 let start = usize::try_from(range.start).ok()?.min(chars);
199 let end = usize::try_from(range.end).ok()?.min(chars).max(start);
200 let byte = |index: usize| {
201 text.char_indices()
202 .nth(index)
203 .map_or(text.len(), |(byte, _)| byte)
204 };
205 Some((byte(start), byte(end)))
206 }
207
208 #[must_use]
215 pub fn normalized_by_broker(mut self, actor: Acting, sequence: u64) -> Self {
216 self.actor = actor;
217 self.sequence = sequence;
218 self
219 }
220
221 pub fn validate(&self) -> Result<(), InteractionViolation> {
225 if self.version != INTERACTION_VERSION {
226 return Err(issue("version", "unsupported interaction version"));
227 }
228 for node in self.actor.nodes() {
229 validate_id("actor", node.by.id())?;
230 }
231 validate_id("action.id", &self.action.id)?;
232 validate_label("action.label", &self.action.label)?;
233 if let Some(did) = &self.action.did {
234 validate_label("action.did", did)?;
235 }
236 validate_resource(&self.resource)?;
237 if let Some(app) = &self.action.app {
238 validate_id("action.app.id", &app.id)?;
239 validate_label("action.app.label", &app.label)?;
240 }
241 if let Some(group) = &self.group {
242 validate_id("group.id", &group.id)?;
243 if let Some(label) = &group.label {
244 validate_label("group.label", label)?;
245 }
246 validate_id("group.kind", &group.kind)?;
247 }
248 validate_phase(&self.phase)?;
249 validate_anchor(&self.anchor)?;
250 let encoded = serde_json::to_vec(self)
251 .map_err(|_| issue("interaction", "interaction could not be encoded"))?;
252 if encoded.len() > MAX_INTERACTION_BYTES {
253 return Err(issue("interaction", "encoded interaction is too large"));
254 }
255 Ok(())
256 }
257}
258
259#[derive(Clone, Debug, PartialEq, Eq)]
260pub struct InteractionViolation {
261 pub field: &'static str,
262 pub reason: &'static str,
263}
264
265impl std::fmt::Display for InteractionViolation {
266 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267 write!(formatter, "{}: {}", self.field, self.reason)
268 }
269}
270
271impl std::error::Error for InteractionViolation {}
272
273const fn issue(field: &'static str, reason: &'static str) -> InteractionViolation {
274 InteractionViolation { field, reason }
275}
276
277fn validate_nonempty(
278 field: &'static str,
279 value: &str,
280 maximum: usize,
281) -> Result<(), InteractionViolation> {
282 if value.trim().is_empty() {
283 return Err(issue(field, "must not be empty"));
284 }
285 if value.len() > maximum {
286 return Err(issue(field, "is too long"));
287 }
288 Ok(())
289}
290
291fn validate_id(field: &'static str, value: &str) -> Result<(), InteractionViolation> {
292 validate_nonempty(field, value, MAX_ID_BYTES)
293}
294
295fn validate_label(field: &'static str, value: &str) -> Result<(), InteractionViolation> {
296 validate_nonempty(field, value, MAX_LABEL_BYTES)
297}
298
299fn validate_resource(resource: &ActionResource) -> Result<(), InteractionViolation> {
300 validate_id("resource.id", &resource.id)?;
301 validate_id("resource.kind", &resource.kind)?;
302 validate_label("resource.label", &resource.label)
303}
304
305fn validate_detail(field: &'static str, value: &str) -> Result<(), InteractionViolation> {
306 if value.len() > MAX_DETAIL_BYTES {
307 return Err(issue(field, "is too long"));
308 }
309 Ok(())
310}
311
312fn validate_phase(phase: &InteractionPhase) -> Result<(), InteractionViolation> {
313 match phase {
314 InteractionPhase::Waiting {
315 reason: Some(reason),
316 } => validate_detail("phase.reason", reason),
317 InteractionPhase::Progress {
318 label,
319 completed,
320 total,
321 } => {
322 validate_nonempty("phase.label", label, MAX_LABEL_BYTES)?;
323 if let (Some(completed), Some(total)) = (completed, total)
324 && completed > total
325 {
326 return Err(issue("phase.progress", "completed exceeds total"));
327 }
328 Ok(())
329 }
330 InteractionPhase::Failed { code, message } => {
331 if let Some(code) = code {
332 validate_id("phase.code", code)?;
333 }
334 validate_nonempty("phase.message", message, MAX_DETAIL_BYTES)
335 }
336 InteractionPhase::Cancelled {
337 message: Some(message),
338 } => validate_detail("phase.message", message),
339 InteractionPhase::Locating
340 | InteractionPhase::Applying
341 | InteractionPhase::Waiting { reason: None }
342 | InteractionPhase::Committed
343 | InteractionPhase::Cancelled { message: None } => Ok(()),
344 }
345}
346
347fn validate_anchor(anchor: &InteractionAnchor) -> Result<(), InteractionViolation> {
348 match anchor {
349 InteractionAnchor::Resource => Ok(()),
350 InteractionAnchor::SemanticControl { id } => validate_id("anchor.id", id),
351 InteractionAnchor::Text { region, ranges } => {
352 validate_id("anchor.region", region)?;
353 validate_count("anchor.ranges", ranges.len())?;
354 for range in ranges {
355 validate_id("anchor.range.block", &range.block)?;
356 if range.end < range.start {
357 return Err(issue("anchor.range", "range end precedes start"));
358 }
359 }
360 Ok(())
361 }
362 InteractionAnchor::Grid { sheet, ranges } => {
363 validate_id("anchor.sheet", sheet)?;
364 validate_count("anchor.ranges", ranges.len())?;
365 if ranges
366 .iter()
367 .any(|range| range.end_col < range.start_col || range.end_row < range.start_row)
368 {
369 return Err(issue("anchor.range", "range end precedes start"));
370 }
371 Ok(())
372 }
373 InteractionAnchor::Objects { ids } | InteractionAnchor::ListItems { ids } => {
374 validate_count("anchor.ids", ids.len())?;
375 for id in ids {
376 validate_id("anchor.id", id)?;
377 }
378 Ok(())
379 }
380 InteractionAnchor::Timeline {
381 track,
382 start_ms,
383 end_ms,
384 } => {
385 if let Some(track) = track {
386 validate_id("anchor.track", track)?;
387 }
388 if end_ms < start_ms {
389 return Err(issue("anchor.range", "range end precedes start"));
390 }
391 Ok(())
392 }
393 }
394}
395
396fn validate_count(field: &'static str, count: usize) -> Result<(), InteractionViolation> {
397 if count == 0 {
398 return Err(issue(field, "must not be empty"));
399 }
400 if count > MAX_ANCHOR_ITEMS {
401 return Err(issue(field, "has too many items"));
402 }
403 Ok(())
404}
405
406#[cfg(test)]
407mod tests {
408 use super::*;
409
410 fn example(anchor: InteractionAnchor) -> SemanticInteraction {
411 SemanticInteraction {
412 version: INTERACTION_VERSION,
413 invocation: InvocationId::new(),
414 sequence: 2,
415 actor: Acting::agent("scribe", "ada"),
416 phase: InteractionPhase::Applying,
417 action: InteractionAction {
418 id: "format-range".into(),
419 label: "Format range".into(),
420 app: Some(ActionApp {
421 id: "org.tilo.Sheets".into(),
422 label: "Sheets".into(),
423 }),
424 step: None,
425 creates: None,
426 did: None,
427 },
428 resource: ActionResource {
429 id: "sheets.sheet:budget".into(),
430 kind: "sheets.sheet".into(),
431 label: "Budget".into(),
432 },
433 anchor,
434 group: Some(WorkGroup {
435 id: "task:42".into(),
436 label: Some("Prepare budget".into()),
437 kind: "task".into(),
438 declared_id: None,
439 session: None,
440 }),
441 }
442 }
443
444 #[test]
448 fn the_interaction_wire_is_versioned_and_broker_normalised() {
449 versioned_grid_interaction_round_trips();
450 additive_fields_are_ignored_but_unknown_versions_are_refused();
451 broker_normalization_replaces_claimed_attribution_and_sequence();
452 }
453
454 fn versioned_grid_interaction_round_trips() {
455 let interaction = example(InteractionAnchor::Grid {
456 sheet: "sheet:budget".into(),
457 ranges: vec![InteractionGridRange {
458 start_col: 1,
459 start_row: 2,
460 end_col: 4,
461 end_row: 8,
462 }],
463 });
464 interaction.validate().expect("valid interaction");
465 let json = serde_json::to_string(&interaction).expect("encode");
466 let decoded: SemanticInteraction = serde_json::from_str(&json).expect("decode");
467 assert_eq!(decoded, interaction);
468 assert!(!json.contains("pixel"));
469 assert!(!json.contains("x\""));
470 }
471
472 fn additive_fields_are_ignored_but_unknown_versions_are_refused() {
473 let interaction = example(InteractionAnchor::Resource);
474 let mut value = serde_json::to_value(&interaction).expect("encode");
475 value
476 .as_object_mut()
477 .expect("object")
478 .insert("future_hint".into(), serde_json::json!(true));
479 let decoded: SemanticInteraction = serde_json::from_value(value).expect("decode");
480 assert_eq!(decoded, interaction);
481
482 let mut future = interaction;
483 future.version = INTERACTION_VERSION + 1;
484 assert_eq!(future.validate().unwrap_err().field, "version");
485 }
486
487 fn broker_normalization_replaces_claimed_attribution_and_sequence() {
488 let claimed = example(InteractionAnchor::Resource);
489 let normalized = claimed.normalized_by_broker(Acting::agent("reviewer", "ada"), 17);
490 assert_eq!(normalized.actor, Acting::agent("reviewer", "ada"));
491 assert_eq!(normalized.sequence, 17);
492 }
493
494 #[test]
498 fn interaction_fields_are_explicit_and_bounded() {
499 anchors_are_nonempty_ordered_and_bounded();
500 labels_and_terminal_details_are_bounded();
501 terminal_phases_are_explicit();
502 progress_is_labelled_and_in_range();
503 }
504
505 fn anchors_are_nonempty_ordered_and_bounded() {
506 let backwards = example(InteractionAnchor::Text {
507 region: "body".into(),
508 ranges: vec![InteractionTextRange {
509 block: "block:1".into(),
510 start: 9,
511 end: 3,
512 }],
513 });
514 assert_eq!(backwards.validate().unwrap_err().field, "anchor.range");
515
516 let too_many = example(InteractionAnchor::Objects {
517 ids: (0..=MAX_ANCHOR_ITEMS)
518 .map(|n| format!("shape:{n}"))
519 .collect(),
520 });
521 assert_eq!(too_many.validate().unwrap_err().field, "anchor.ids");
522
523 let empty = example(InteractionAnchor::ListItems { ids: Vec::new() });
524 assert_eq!(empty.validate().unwrap_err().field, "anchor.ids");
525 }
526
527 fn labels_and_terminal_details_are_bounded() {
528 let mut oversized = example(InteractionAnchor::Resource);
529 oversized.phase = InteractionPhase::Failed {
530 code: Some("action_failed".into()),
531 message: "x".repeat(MAX_DETAIL_BYTES + 1),
532 };
533 assert_eq!(oversized.validate().unwrap_err().field, "phase.message");
534
535 oversized.phase = InteractionPhase::Committed;
536 oversized.resource.label = "x".repeat(MAX_LABEL_BYTES + 1);
537 assert_eq!(oversized.validate().unwrap_err().field, "resource.label");
538
539 oversized.resource.label = "Label".into();
540 oversized.action.did = Some("x".repeat(MAX_LABEL_BYTES + 1));
541 assert_eq!(oversized.validate().unwrap_err().field, "action.did");
542 }
543
544 fn terminal_phases_are_explicit() {
545 assert!(!InteractionPhase::Locating.is_terminal());
546 assert!(!InteractionPhase::Applying.is_terminal());
547 assert!(
548 !InteractionPhase::Progress {
549 label: "Uploading".into(),
550 completed: Some(3),
551 total: Some(10),
552 }
553 .is_terminal()
554 );
555 assert!(InteractionPhase::Committed.is_terminal());
556 assert!(
557 InteractionPhase::Failed {
558 code: None,
559 message: "no".into()
560 }
561 .is_terminal()
562 );
563 assert!(InteractionPhase::Cancelled { message: None }.is_terminal());
564 }
565
566 fn progress_is_labelled_and_in_range() {
567 let mut interaction = example(InteractionAnchor::Resource);
568 interaction.phase = InteractionPhase::Progress {
569 label: String::new(),
570 completed: None,
571 total: None,
572 };
573 assert_eq!(interaction.validate().unwrap_err().field, "phase.label");
574
575 interaction.phase = InteractionPhase::Progress {
576 label: "Indexing".into(),
577 completed: Some(11),
578 total: Some(10),
579 };
580 assert_eq!(interaction.validate().unwrap_err().field, "phase.progress");
581 }
582}