use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContextReference {
pub kind: ContextReferenceKind,
pub source: ContextReferenceSource,
pub badge: String,
pub label: String,
pub target: String,
pub included: bool,
pub expanded: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextReferenceKind {
File,
Directory,
Missing,
Unsupported,
MediaMention,
MediaAttachment,
GitContext,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextReferenceSource {
AtMention,
Attachment,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MediaAttachmentReference {
pub kind: String,
pub path: String,
pub start_byte: usize,
pub end_byte: usize,
}
#[must_use]
pub fn media_attachment_references(input: &str) -> Vec<MediaAttachmentReference> {
let mut out = Vec::new();
let mut offset = 0usize;
for line in input.split_inclusive('\n') {
let start_byte = offset;
let end_byte = offset + line.len();
offset = end_byte;
let trimmed = line.trim();
let Some(body) = trimmed
.strip_prefix("[Attached ")
.and_then(|value| value.strip_suffix(']'))
else {
continue;
};
let Some((kind, rest)) = body.split_once(": ") else {
continue;
};
let path = rest
.rsplit_once(" at ")
.map_or(rest, |(_, path)| path)
.trim();
if !path.is_empty() {
out.push(MediaAttachmentReference {
kind: kind.trim().to_string(),
path: path.to_string(),
start_byte,
end_byte,
});
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialization_roundtrip() {
let reference = ContextReference {
kind: ContextReferenceKind::File,
source: ContextReferenceSource::AtMention,
badge: "file".to_string(),
label: "test.rs".to_string(),
target: "/path/to/test.rs".to_string(),
included: true,
expanded: false,
detail: Some("included".to_string()),
};
let json = serde_json::to_string(&reference).unwrap();
let deserialized: ContextReference = serde_json::from_str(&json).unwrap();
assert_eq!(reference, deserialized);
}
#[test]
fn parses_media_attachments() {
let input = "Here is the screenshot:\n[Attached image: 100x100 at /tmp/shot.png]\nPlease analyze it.";
let refs = media_attachment_references(input);
assert_eq!(refs.len(), 1);
assert_eq!(refs[0].kind, "image");
assert_eq!(refs[0].path, "/tmp/shot.png");
}
}