Skip to main content

utils/
display_meta.rs

1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3
4/// Human-readable display metadata for a tool operation.
5#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
6pub struct ToolDisplayMeta {
7    pub title: String,
8    pub value: String,
9}
10
11impl ToolDisplayMeta {
12    pub fn new(title: impl Into<String>, value: impl Into<String>) -> Self {
13        Self { title: title.into(), value: value.into() }
14    }
15}
16
17/// Full file contents for a diff
18#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
19pub struct FileDiff {
20    pub path: String,
21    /// Original file content (`None` for new files).
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub old_text: Option<String>,
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub new_text: Option<String>,
26}
27
28impl FileDiff {
29    pub fn first_change(&self) -> ToolLocation {
30        let old = self.old_text.as_deref().unwrap_or_default();
31        let new = self.new_text.as_deref().unwrap_or_default();
32        let unchanged = old.lines().zip(new.lines()).take_while(|(old, new)| old == new).count();
33        let line = (unchanged + 1).min(new.lines().count().max(1));
34        ToolLocation::new(self.path.clone(), Some(u32::try_from(line).unwrap_or(u32::MAX)))
35    }
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
39pub struct ToolLocation {
40    pub path: String,
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub line: Option<u32>,
43}
44
45impl ToolLocation {
46    pub fn new(path: impl Into<String>, line: Option<u32>) -> Self {
47        Self { path: path.into(), line }
48    }
49}
50
51/// A snapshot of the agent's current task plan.
52#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
53pub struct PlanMeta {
54    pub entries: Vec<PlanMetaEntry>,
55}
56
57/// A single entry in a plan.
58#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
59pub struct PlanMetaEntry {
60    pub content: String,
61    pub status: PlanMetaStatus,
62}
63
64/// Execution status of a plan entry.
65#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, JsonSchema)]
66#[serde(rename_all = "snake_case")]
67pub enum PlanMetaStatus {
68    Pending,
69    InProgress,
70    Completed,
71    Cancelled,
72}
73
74/// Typed wrapper for the MCP `_meta` field on tool results.
75#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
76pub struct ToolResultMeta {
77    pub display: ToolDisplayMeta,
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub file_diff: Option<FileDiff>,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub plan: Option<PlanMeta>,
82    #[serde(default, skip_serializing_if = "Vec::is_empty")]
83    pub locations: Vec<ToolLocation>,
84}
85
86impl From<ToolDisplayMeta> for ToolResultMeta {
87    fn from(display: ToolDisplayMeta) -> Self {
88        Self::new(display)
89    }
90}
91
92impl ToolResultMeta {
93    pub fn new(display: ToolDisplayMeta) -> Self {
94        Self { display, file_diff: None, plan: None, locations: Vec::new() }
95    }
96
97    pub fn with_plan(display: ToolDisplayMeta, plan: PlanMeta) -> Self {
98        Self { plan: Some(plan), ..Self::new(display) }
99    }
100
101    pub fn with_file_diff(display: ToolDisplayMeta, file_diff: FileDiff) -> Self {
102        let locations = vec![file_diff.first_change()];
103        Self { file_diff: Some(file_diff), locations, ..Self::new(display) }
104    }
105
106    #[must_use]
107    pub fn located(mut self, location: ToolLocation) -> Self {
108        self.locations.push(location);
109        self
110    }
111}
112
113pub fn truncate(s: &str, max_length: usize) -> String {
114    if s.chars().count() <= max_length {
115        s.to_string()
116    } else {
117        let mut truncated = s.chars().take(max_length.saturating_sub(3)).collect::<String>();
118        truncated.push_str("...");
119        truncated
120    }
121}
122
123pub fn basename(path: &str) -> String {
124    let platform_basename = std::path::Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path);
125
126    if platform_basename.contains('\\') {
127        path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
128    } else {
129        platform_basename.to_string()
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    fn display(title: &str, value: &str) -> ToolDisplayMeta {
138        ToolDisplayMeta::new(title, value)
139    }
140
141    fn assert_serde_roundtrip<T: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug>(val: &T) {
142        let json = serde_json::to_string(val).unwrap();
143        let parsed: T = serde_json::from_str(&json).unwrap();
144        assert_eq!(&parsed, val);
145    }
146
147    fn sample_diff(old_text: Option<&str>) -> FileDiff {
148        FileDiff {
149            path: "/tmp/main.rs".to_string(),
150            old_text: old_text.map(str::to_string),
151            new_text: Some("new content".to_string()),
152        }
153    }
154
155    fn sample_plan() -> PlanMeta {
156        PlanMeta {
157            entries: vec![
158                PlanMetaEntry { content: "Research AI agents".into(), status: PlanMetaStatus::Completed },
159                PlanMetaEntry { content: "Implement tracking".into(), status: PlanMetaStatus::InProgress },
160                PlanMetaEntry { content: "Write tests".into(), status: PlanMetaStatus::Pending },
161            ],
162        }
163    }
164
165    #[test]
166    fn test_new_sets_title_and_value() {
167        let meta = display("Read file", "Cargo.toml, 156 lines");
168        assert_eq!(meta.title, "Read file");
169        assert_eq!(meta.value, "Cargo.toml, 156 lines");
170    }
171
172    #[test]
173    fn test_serde_json_shape() {
174        let json = serde_json::to_value(display("Read file", "Cargo.toml")).unwrap();
175        assert_eq!(json["title"], "Read file");
176        assert_eq!(json["value"], "Cargo.toml");
177    }
178
179    #[test]
180    fn test_serde_roundtrips() {
181        assert_serde_roundtrip(&display("Grep", "'TODO' in src (42 matches)"));
182        assert_serde_roundtrip(&sample_diff(Some("old content")));
183        assert_serde_roundtrip(&sample_plan());
184
185        let result_meta: ToolResultMeta = display("Read file", "Cargo.toml, 156 lines").into();
186        assert_serde_roundtrip(&result_meta);
187    }
188
189    #[test]
190    fn test_into_result_meta() {
191        let d = display("Write file", "main.rs");
192        let meta: ToolResultMeta = d.clone().into();
193        assert_eq!(meta, ToolResultMeta { display: d, file_diff: None, plan: None, locations: Vec::new() });
194    }
195
196    #[test]
197    fn a_file_diff_is_located_at_its_first_changed_line() {
198        let diff = |old: Option<&str>, new: &str| FileDiff {
199            path: "/tmp/main.rs".to_string(),
200            old_text: old.map(str::to_string),
201            new_text: Some(new.to_string()),
202        };
203        let line = |diff: FileDiff| ToolResultMeta::with_file_diff(display("Edit file", "main.rs"), diff).locations;
204
205        assert_eq!(line(diff(Some("a\nb\nc\n"), "a\nb\nC\n")), [ToolLocation::new("/tmp/main.rs", Some(3))]);
206        assert_eq!(line(diff(None, "new\n")), [ToolLocation::new("/tmp/main.rs", Some(1))], "a new file starts at 1");
207        assert_eq!(
208            line(diff(Some("a\nb\n"), "a\n")),
209            [ToolLocation::new("/tmp/main.rs", Some(1))],
210            "never past the end"
211        );
212    }
213
214    #[test]
215    fn test_optional_fields_omitted_when_none() {
216        let diff_json = serde_json::to_value(sample_diff(None)).unwrap();
217        assert!(diff_json.get("old_text").is_none());
218
219        let meta_json = serde_json::to_value::<ToolResultMeta>(display("Read", "f.rs").into()).unwrap();
220        assert!(meta_json.get("plan").is_none());
221        assert!(meta_json.get("file_diff").is_none());
222    }
223
224    #[test]
225    fn empty_and_deleted_file_snapshots_remain_distinct() {
226        let empty: FileDiff = serde_json::from_value(serde_json::json!({
227            "path": "/tmp/file", "old_text": "old", "new_text": ""
228        }))
229        .unwrap();
230        let deleted: FileDiff = serde_json::from_value(serde_json::json!({
231            "path": "/tmp/file", "old_text": "old"
232        }))
233        .unwrap();
234        assert_eq!(empty.new_text.as_deref(), Some(""));
235        assert_eq!(deleted.new_text, None);
236        assert_serde_roundtrip(&empty);
237        assert_serde_roundtrip(&deleted);
238        assert_serde_roundtrip(&PlanMetaStatus::Cancelled);
239    }
240
241    #[test]
242    fn test_file_diff_missing_old_text_defaults_to_none() {
243        let parsed: FileDiff = serde_json::from_str(r#"{"path":"/tmp/f.rs","new_text":"content"}"#).unwrap();
244        assert_eq!(parsed.old_text, None);
245    }
246
247    #[test]
248    fn test_truncate() {
249        assert_eq!(truncate("short", 10), "short");
250
251        let long = truncate("cargo check --message-format=json --locked", 20);
252        assert!(long.chars().count() <= 20);
253        assert!(long.ends_with("..."));
254
255        let multibyte = truncate("こんにちは世界テスト文字列", 8);
256        assert_eq!(multibyte.chars().count(), 8);
257        assert!(multibyte.ends_with("..."));
258    }
259
260    #[test]
261    fn test_basename() {
262        for (path, expected) in [
263            ("/Users/josh/code/aether/Cargo.toml", "Cargo.toml"),
264            (r"C:\Users\josh\code\aether\Cargo.toml", "Cargo.toml"),
265            ("Cargo.toml", "Cargo.toml"),
266        ] {
267            assert_eq!(basename(path), expected, "path: {path}");
268        }
269    }
270
271    #[test]
272    fn test_plan_meta_status_serde_snake_case() {
273        let json = serde_json::to_value(PlanMetaStatus::InProgress).unwrap();
274        assert_eq!(json, serde_json::Value::String("in_progress".to_string()));
275    }
276}