use serde::{Deserialize, Serialize};
use crate::{ActionApp, ActionResource, InvocationId, WorkGroup};
use tilo_action_policy::Acting;
pub const INTERACTION_VERSION: u16 = 2;
pub const MAX_INTERACTION_BYTES: usize = 32 * 1024;
pub const MAX_ANCHOR_ITEMS: usize = 64;
pub const MAX_ID_BYTES: usize = 512;
pub const MAX_LABEL_BYTES: usize = 512;
pub const MAX_DETAIL_BYTES: usize = 2 * 1024;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionTextRange {
pub block: String,
pub start: u64,
pub end: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionGridRange {
pub start_col: u32,
pub start_row: u32,
pub end_col: u32,
pub end_row: u32,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "kind", rename_all = "snake_case")]
pub enum InteractionAnchor {
Resource,
SemanticControl { id: String },
Text {
region: String,
ranges: Vec<InteractionTextRange>,
},
Grid {
sheet: String,
ranges: Vec<InteractionGridRange>,
},
Objects { ids: Vec<String> },
ListItems { ids: Vec<String> },
Timeline {
track: Option<String>,
start_ms: u64,
end_ms: u64,
},
}
read_through_json_value!(InteractionAnchor);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "phase", rename_all = "snake_case")]
pub enum InteractionPhase {
Locating,
Applying,
Progress {
label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
completed: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
total: Option<u64>,
},
Waiting {
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
},
Committed,
Failed {
#[serde(default, skip_serializing_if = "Option::is_none")]
code: Option<String>,
message: String,
},
Cancelled {
#[serde(default, skip_serializing_if = "Option::is_none")]
message: Option<String>,
},
}
read_through_json_value!(InteractionPhase);
impl InteractionPhase {
pub fn is_terminal(&self) -> bool {
matches!(
self,
Self::Committed | Self::Failed { .. } | Self::Cancelled { .. }
)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractionAction {
pub id: String,
pub label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app: Option<ActionApp>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub step: Option<crate::StepKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub creates: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub did: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SemanticInteraction {
pub version: u16,
pub invocation: InvocationId,
pub sequence: u64,
pub actor: Acting,
pub phase: InteractionPhase,
pub action: InteractionAction,
pub resource: ActionResource,
pub anchor: InteractionAnchor,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub group: Option<WorkGroup>,
}
pub type InteractionUpdate = SemanticInteraction;
impl SemanticInteraction {
#[must_use]
pub fn written_in(
&self,
region: Option<&str>,
block: &str,
text: &str,
) -> Option<(usize, usize)> {
let InteractionAnchor::Text {
region: written,
ranges,
} = &self.anchor
else {
return None;
};
if region.is_some_and(|region| region != written) {
return None;
}
let range = ranges.iter().find(|range| {
range.block == block || (!range.block.is_empty() && block.starts_with(&range.block))
})?;
let chars = text.chars().count();
let start = usize::try_from(range.start).ok()?.min(chars);
let end = usize::try_from(range.end).ok()?.min(chars).max(start);
let byte = |index: usize| {
text.char_indices()
.nth(index)
.map_or(text.len(), |(byte, _)| byte)
};
Some((byte(start), byte(end)))
}
#[must_use]
pub fn normalized_by_broker(mut self, actor: Acting, sequence: u64) -> Self {
self.actor = actor;
self.sequence = sequence;
self
}
pub fn validate(&self) -> Result<(), InteractionViolation> {
if self.version != INTERACTION_VERSION {
return Err(issue("version", "unsupported interaction version"));
}
for node in self.actor.nodes() {
validate_id("actor", node.by.id())?;
}
validate_id("action.id", &self.action.id)?;
validate_label("action.label", &self.action.label)?;
if let Some(did) = &self.action.did {
validate_label("action.did", did)?;
}
validate_resource(&self.resource)?;
if let Some(app) = &self.action.app {
validate_id("action.app.id", &app.id)?;
validate_label("action.app.label", &app.label)?;
}
if let Some(group) = &self.group {
validate_id("group.id", &group.id)?;
if let Some(label) = &group.label {
validate_label("group.label", label)?;
}
validate_id("group.kind", &group.kind)?;
}
validate_phase(&self.phase)?;
validate_anchor(&self.anchor)?;
let encoded = serde_json::to_vec(self)
.map_err(|_| issue("interaction", "interaction could not be encoded"))?;
if encoded.len() > MAX_INTERACTION_BYTES {
return Err(issue("interaction", "encoded interaction is too large"));
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InteractionViolation {
pub field: &'static str,
pub reason: &'static str,
}
impl std::fmt::Display for InteractionViolation {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "{}: {}", self.field, self.reason)
}
}
impl std::error::Error for InteractionViolation {}
const fn issue(field: &'static str, reason: &'static str) -> InteractionViolation {
InteractionViolation { field, reason }
}
fn validate_nonempty(
field: &'static str,
value: &str,
maximum: usize,
) -> Result<(), InteractionViolation> {
if value.trim().is_empty() {
return Err(issue(field, "must not be empty"));
}
if value.len() > maximum {
return Err(issue(field, "is too long"));
}
Ok(())
}
fn validate_id(field: &'static str, value: &str) -> Result<(), InteractionViolation> {
validate_nonempty(field, value, MAX_ID_BYTES)
}
fn validate_label(field: &'static str, value: &str) -> Result<(), InteractionViolation> {
validate_nonempty(field, value, MAX_LABEL_BYTES)
}
fn validate_resource(resource: &ActionResource) -> Result<(), InteractionViolation> {
validate_id("resource.id", &resource.id)?;
validate_id("resource.kind", &resource.kind)?;
validate_label("resource.label", &resource.label)
}
fn validate_detail(field: &'static str, value: &str) -> Result<(), InteractionViolation> {
if value.len() > MAX_DETAIL_BYTES {
return Err(issue(field, "is too long"));
}
Ok(())
}
fn validate_phase(phase: &InteractionPhase) -> Result<(), InteractionViolation> {
match phase {
InteractionPhase::Waiting {
reason: Some(reason),
} => validate_detail("phase.reason", reason),
InteractionPhase::Progress {
label,
completed,
total,
} => {
validate_nonempty("phase.label", label, MAX_LABEL_BYTES)?;
if let (Some(completed), Some(total)) = (completed, total)
&& completed > total
{
return Err(issue("phase.progress", "completed exceeds total"));
}
Ok(())
}
InteractionPhase::Failed { code, message } => {
if let Some(code) = code {
validate_id("phase.code", code)?;
}
validate_nonempty("phase.message", message, MAX_DETAIL_BYTES)
}
InteractionPhase::Cancelled {
message: Some(message),
} => validate_detail("phase.message", message),
InteractionPhase::Locating
| InteractionPhase::Applying
| InteractionPhase::Waiting { reason: None }
| InteractionPhase::Committed
| InteractionPhase::Cancelled { message: None } => Ok(()),
}
}
fn validate_anchor(anchor: &InteractionAnchor) -> Result<(), InteractionViolation> {
match anchor {
InteractionAnchor::Resource => Ok(()),
InteractionAnchor::SemanticControl { id } => validate_id("anchor.id", id),
InteractionAnchor::Text { region, ranges } => {
validate_id("anchor.region", region)?;
validate_count("anchor.ranges", ranges.len())?;
for range in ranges {
validate_id("anchor.range.block", &range.block)?;
if range.end < range.start {
return Err(issue("anchor.range", "range end precedes start"));
}
}
Ok(())
}
InteractionAnchor::Grid { sheet, ranges } => {
validate_id("anchor.sheet", sheet)?;
validate_count("anchor.ranges", ranges.len())?;
if ranges
.iter()
.any(|range| range.end_col < range.start_col || range.end_row < range.start_row)
{
return Err(issue("anchor.range", "range end precedes start"));
}
Ok(())
}
InteractionAnchor::Objects { ids } | InteractionAnchor::ListItems { ids } => {
validate_count("anchor.ids", ids.len())?;
for id in ids {
validate_id("anchor.id", id)?;
}
Ok(())
}
InteractionAnchor::Timeline {
track,
start_ms,
end_ms,
} => {
if let Some(track) = track {
validate_id("anchor.track", track)?;
}
if end_ms < start_ms {
return Err(issue("anchor.range", "range end precedes start"));
}
Ok(())
}
}
}
fn validate_count(field: &'static str, count: usize) -> Result<(), InteractionViolation> {
if count == 0 {
return Err(issue(field, "must not be empty"));
}
if count > MAX_ANCHOR_ITEMS {
return Err(issue(field, "has too many items"));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn example(anchor: InteractionAnchor) -> SemanticInteraction {
SemanticInteraction {
version: INTERACTION_VERSION,
invocation: InvocationId::new(),
sequence: 2,
actor: Acting::agent("scribe", "ada"),
phase: InteractionPhase::Applying,
action: InteractionAction {
id: "format-range".into(),
label: "Format range".into(),
app: Some(ActionApp {
id: "org.tilo.Sheets".into(),
label: "Sheets".into(),
}),
step: None,
creates: None,
did: None,
},
resource: ActionResource {
id: "sheets.sheet:budget".into(),
kind: "sheets.sheet".into(),
label: "Budget".into(),
},
anchor,
group: Some(WorkGroup {
id: "task:42".into(),
label: Some("Prepare budget".into()),
kind: "task".into(),
declared_id: None,
session: None,
}),
}
}
#[test]
fn the_interaction_wire_is_versioned_and_broker_normalised() {
versioned_grid_interaction_round_trips();
additive_fields_are_ignored_but_unknown_versions_are_refused();
broker_normalization_replaces_claimed_attribution_and_sequence();
}
fn versioned_grid_interaction_round_trips() {
let interaction = example(InteractionAnchor::Grid {
sheet: "sheet:budget".into(),
ranges: vec![InteractionGridRange {
start_col: 1,
start_row: 2,
end_col: 4,
end_row: 8,
}],
});
interaction.validate().expect("valid interaction");
let json = serde_json::to_string(&interaction).expect("encode");
let decoded: SemanticInteraction = serde_json::from_str(&json).expect("decode");
assert_eq!(decoded, interaction);
assert!(!json.contains("pixel"));
assert!(!json.contains("x\""));
}
fn additive_fields_are_ignored_but_unknown_versions_are_refused() {
let interaction = example(InteractionAnchor::Resource);
let mut value = serde_json::to_value(&interaction).expect("encode");
value
.as_object_mut()
.expect("object")
.insert("future_hint".into(), serde_json::json!(true));
let decoded: SemanticInteraction = serde_json::from_value(value).expect("decode");
assert_eq!(decoded, interaction);
let mut future = interaction;
future.version = INTERACTION_VERSION + 1;
assert_eq!(future.validate().unwrap_err().field, "version");
}
fn broker_normalization_replaces_claimed_attribution_and_sequence() {
let claimed = example(InteractionAnchor::Resource);
let normalized = claimed.normalized_by_broker(Acting::agent("reviewer", "ada"), 17);
assert_eq!(normalized.actor, Acting::agent("reviewer", "ada"));
assert_eq!(normalized.sequence, 17);
}
#[test]
fn interaction_fields_are_explicit_and_bounded() {
anchors_are_nonempty_ordered_and_bounded();
labels_and_terminal_details_are_bounded();
terminal_phases_are_explicit();
progress_is_labelled_and_in_range();
}
fn anchors_are_nonempty_ordered_and_bounded() {
let backwards = example(InteractionAnchor::Text {
region: "body".into(),
ranges: vec![InteractionTextRange {
block: "block:1".into(),
start: 9,
end: 3,
}],
});
assert_eq!(backwards.validate().unwrap_err().field, "anchor.range");
let too_many = example(InteractionAnchor::Objects {
ids: (0..=MAX_ANCHOR_ITEMS)
.map(|n| format!("shape:{n}"))
.collect(),
});
assert_eq!(too_many.validate().unwrap_err().field, "anchor.ids");
let empty = example(InteractionAnchor::ListItems { ids: Vec::new() });
assert_eq!(empty.validate().unwrap_err().field, "anchor.ids");
}
fn labels_and_terminal_details_are_bounded() {
let mut oversized = example(InteractionAnchor::Resource);
oversized.phase = InteractionPhase::Failed {
code: Some("action_failed".into()),
message: "x".repeat(MAX_DETAIL_BYTES + 1),
};
assert_eq!(oversized.validate().unwrap_err().field, "phase.message");
oversized.phase = InteractionPhase::Committed;
oversized.resource.label = "x".repeat(MAX_LABEL_BYTES + 1);
assert_eq!(oversized.validate().unwrap_err().field, "resource.label");
oversized.resource.label = "Label".into();
oversized.action.did = Some("x".repeat(MAX_LABEL_BYTES + 1));
assert_eq!(oversized.validate().unwrap_err().field, "action.did");
}
fn terminal_phases_are_explicit() {
assert!(!InteractionPhase::Locating.is_terminal());
assert!(!InteractionPhase::Applying.is_terminal());
assert!(
!InteractionPhase::Progress {
label: "Uploading".into(),
completed: Some(3),
total: Some(10),
}
.is_terminal()
);
assert!(InteractionPhase::Committed.is_terminal());
assert!(
InteractionPhase::Failed {
code: None,
message: "no".into()
}
.is_terminal()
);
assert!(InteractionPhase::Cancelled { message: None }.is_terminal());
}
fn progress_is_labelled_and_in_range() {
let mut interaction = example(InteractionAnchor::Resource);
interaction.phase = InteractionPhase::Progress {
label: String::new(),
completed: None,
total: None,
};
assert_eq!(interaction.validate().unwrap_err().field, "phase.label");
interaction.phase = InteractionPhase::Progress {
label: "Indexing".into(),
completed: Some(11),
total: Some(10),
};
assert_eq!(interaction.validate().unwrap_err().field, "phase.progress");
}
}