Skip to main content

diffler_core/
session.rs

1//! Review session: comments and per-file viewed marks, reconciled against
2//! fresh diff models. Persistence lives in `store`.
3
4use std::collections::BTreeMap;
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use serde::{Deserialize, Serialize};
8
9use crate::model::{DiffModel, HunkId};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum CommentStatus {
14    Open,
15    Replied,
16    Resolved,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Reply {
21    pub author: String,
22    pub body: String,
23    pub at: u64,
24}
25
26/// Where a comment is anchored. `line` (and `line_end` for visual ranges)
27/// is the new-side line number unless the line is a deletion, then it is
28/// the old-side number with `on_old_side`.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30pub struct Anchor {
31    pub file: String,
32    #[serde(default)]
33    pub line: Option<u32>,
34    #[serde(default)]
35    pub line_end: Option<u32>,
36    #[serde(default)]
37    pub on_old_side: bool,
38    #[serde(default)]
39    pub hunk: Option<HunkId>,
40    /// Snapshot of the anchored line's text, so the UI can mark the
41    /// comment outdated when the agent rewrites the line.
42    #[serde(default)]
43    pub line_text: Option<String>,
44}
45
46impl Anchor {
47    /// Whether the anchor no longer matches the model. Range comments
48    /// anchor to their end line: that is the line whose disappearance or
49    /// `line_text` drift marks them outdated. A line-less anchor is
50    /// outdated only once the whole file leaves the diff.
51    pub fn is_outdated(&self, model: &DiffModel) -> bool {
52        match self.line_end.or(self.line) {
53            Some(line) => match model.find_line(&self.file, line, self.on_old_side) {
54                Some(found) => self
55                    .line_text
56                    .as_deref()
57                    .is_some_and(|snap| snap != found.text),
58                None => true,
59            },
60            None => !model.files.iter().any(|f| f.path == self.file),
61        }
62    }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66pub struct Comment {
67    pub id: String,
68    pub author: String,
69    pub anchor: Anchor,
70    pub body: String,
71    pub status: CommentStatus,
72    #[serde(default)]
73    pub replies: Vec<Reply>,
74    pub at: u64,
75}
76
77#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
78pub struct Session {
79    #[serde(default)]
80    pub comments: Vec<Comment>,
81    /// Per-file viewed marks: path -> content hash of the new side at the
82    /// time of marking. A changed hash means the file needs re-review.
83    #[serde(default)]
84    pub viewed: BTreeMap<String, String>,
85}
86
87pub fn now_unix() -> u64 {
88    SystemTime::now()
89        .duration_since(UNIX_EPOCH)
90        .map_or(0, |d| d.as_secs())
91}
92
93impl Session {
94    pub fn add_comment(&mut self, author: &str, anchor: Anchor, body: &str) -> &Comment {
95        self.comments.push(Comment {
96            id: uuid::Uuid::new_v4().to_string(),
97            author: author.to_owned(),
98            anchor,
99            body: body.to_owned(),
100            status: CommentStatus::Open,
101            replies: Vec::new(),
102            at: now_unix(),
103        });
104        // just pushed, so the vec is non-empty
105        #[allow(clippy::expect_used)]
106        self.comments.last().expect("just pushed")
107    }
108
109    fn comment_mut(&mut self, comment_id: &str) -> Option<&mut Comment> {
110        self.comments.iter_mut().find(|c| c.id == comment_id)
111    }
112
113    pub fn reply(&mut self, comment_id: &str, author: &str, body: &str) -> bool {
114        let Some(comment) = self.comment_mut(comment_id) else {
115            return false;
116        };
117        comment.replies.push(Reply {
118            author: author.to_owned(),
119            body: body.to_owned(),
120            at: now_unix(),
121        });
122        if comment.status == CommentStatus::Open {
123            comment.status = CommentStatus::Replied;
124        }
125        true
126    }
127
128    pub fn resolve(&mut self, comment_id: &str) -> bool {
129        let Some(comment) = self.comment_mut(comment_id) else {
130            return false;
131        };
132        comment.status = CommentStatus::Resolved;
133        true
134    }
135
136    /// Replace a comment's body in place (status, replies, and anchor are kept).
137    pub fn edit_comment(&mut self, comment_id: &str, body: &str) -> bool {
138        let Some(comment) = self.comment_mut(comment_id) else {
139            return false;
140        };
141        body.clone_into(&mut comment.body);
142        true
143    }
144
145    pub fn unresolved_comments(&self) -> impl Iterator<Item = &Comment> {
146        self.comments
147            .iter()
148            .filter(|c| c.status != CommentStatus::Resolved)
149    }
150
151    pub fn mark_viewed(&mut self, path: &str, hash: &str) {
152        self.viewed.insert(path.to_owned(), hash.to_owned());
153    }
154
155    pub fn unmark_viewed(&mut self, path: &str) {
156        self.viewed.remove(path);
157    }
158
159    /// A stale hash means the file changed since it was marked: not viewed
160    /// anymore (auto-reset semantics).
161    pub fn is_viewed(&self, path: &str, current_hash: &str) -> bool {
162        self.viewed.get(path).is_some_and(|h| h == current_hash)
163    }
164
165    /// Drop viewed marks for files that left the diff or whose content
166    /// changed since marking. Comments are kept: they stay useful (possibly
167    /// flagged outdated) even when their file moves on.
168    pub fn reconcile(&mut self, model: &DiffModel) {
169        let live: BTreeMap<&str, String> = model
170            .files
171            .iter()
172            .map(|f| (f.path.as_str(), f.content_hash()))
173            .collect();
174        self.viewed
175            .retain(|path, hash| live.get(path.as_str()).is_some_and(|h| h == hash));
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use crate::model::{DiffLine, FileDiff, FileStatus, Hunk, HunkId, LineKind};
182
183    use super::*;
184
185    fn anchor(file: &str) -> Anchor {
186        Anchor {
187            file: file.to_owned(),
188            line: Some(3),
189            line_end: None,
190            on_old_side: false,
191            hunk: None,
192            line_text: None,
193        }
194    }
195
196    fn file_diff(path: &str, new_text: &str) -> FileDiff {
197        FileDiff {
198            path: path.to_owned(),
199            old_path: None,
200            status: FileStatus::Modified,
201            binary: false,
202            old_text: None,
203            new_text: Some(new_text.to_owned()),
204            hunks: vec![],
205        }
206    }
207
208    fn model(files: Vec<FileDiff>) -> DiffModel {
209        DiffModel { files }
210    }
211
212    #[test]
213    fn comment_lifecycle_open_replied_resolved() {
214        let mut s = Session::default();
215        let id = s.add_comment("mattf", anchor("a.txt"), "why?").id.clone();
216        assert_eq!(s.comments[0].status, CommentStatus::Open);
217        assert!(s.reply(&id, "agent", "because"));
218        assert_eq!(s.comments[0].status, CommentStatus::Replied);
219        assert!(s.resolve(&id));
220        assert_eq!(s.comments[0].status, CommentStatus::Resolved);
221        assert_eq!(s.unresolved_comments().count(), 0);
222    }
223
224    #[test]
225    fn reply_to_missing_comment_returns_false() {
226        let mut s = Session::default();
227        assert!(!s.reply("nope", "agent", "hi"));
228    }
229
230    #[test]
231    fn resolve_missing_comment_returns_false() {
232        let mut s = Session::default();
233        assert!(!s.resolve("nope"));
234    }
235
236    #[test]
237    fn edit_comment_replaces_body_and_keeps_status() {
238        let mut s = Session::default();
239        let id = s
240            .add_comment("mattf", anchor("a.txt"), "old body")
241            .id
242            .clone();
243        assert!(s.reply(&id, "agent", "ack"));
244        assert!(s.edit_comment(&id, "new body"));
245        let c = s.comments.iter().find(|c| c.id == id).expect("comment");
246        assert_eq!(c.body, "new body");
247        assert_eq!(c.status, CommentStatus::Replied, "status is untouched");
248        assert_eq!(c.replies.len(), 1, "replies are untouched");
249        assert!(!s.edit_comment("nope", "x"));
250    }
251
252    #[test]
253    fn unresolved_comments_filters_resolved_only() {
254        let mut s = Session::default();
255        let keep = s.add_comment("mattf", anchor("a.txt"), "open").id.clone();
256        let done = s.add_comment("mattf", anchor("a.txt"), "done").id.clone();
257        assert!(s.resolve(&done));
258        let unresolved: Vec<_> = s.unresolved_comments().map(|c| c.id.clone()).collect();
259        assert_eq!(unresolved, vec![keep]);
260    }
261
262    #[test]
263    fn session_serializes_round_trip_with_range_anchor() {
264        let mut s = Session::default();
265        let mut range = anchor("a.txt");
266        range.line = Some(3);
267        range.line_end = Some(7);
268        s.add_comment("mattf", range, "this whole block");
269        s.mark_viewed("b.txt", "hash-b");
270        let json = serde_json::to_string(&s).expect("serialize");
271        let back: Session = serde_json::from_str(&json).expect("deserialize");
272        assert_eq!(s, back);
273        assert_eq!(back.comments[0].anchor.line_end, Some(7));
274    }
275
276    #[test]
277    fn is_viewed_true_for_same_hash_false_after_change() {
278        let mut s = Session::default();
279        s.mark_viewed("a.txt", "hash-1");
280        assert!(s.is_viewed("a.txt", "hash-1"));
281        assert!(!s.is_viewed("a.txt", "hash-2"));
282        assert!(!s.is_viewed("other.txt", "hash-1"));
283    }
284
285    #[test]
286    fn unmark_viewed_removes_entry() {
287        let mut s = Session::default();
288        s.mark_viewed("a.txt", "hash-1");
289        s.unmark_viewed("a.txt");
290        assert!(!s.is_viewed("a.txt", "hash-1"));
291    }
292
293    /// One file, one hunk: context(1/1), deleted(2), added(2), context(3/3).
294    fn hunked_model() -> DiffModel {
295        DiffModel {
296            files: vec![FileDiff {
297                path: "src/auth.py".into(),
298                old_path: None,
299                status: FileStatus::Modified,
300                binary: false,
301                old_text: None,
302                new_text: None,
303                hunks: vec![Hunk {
304                    id: HunkId("h1".into()),
305                    old_start: 1,
306                    old_lines: 3,
307                    new_start: 1,
308                    new_lines: 3,
309                    context: String::new(),
310                    lines: vec![
311                        DiffLine::new(LineKind::Context, Some(1), Some(1), "one".into()),
312                        DiffLine::new(LineKind::Deleted, Some(2), None, "two".into()),
313                        DiffLine::new(LineKind::Added, None, Some(2), "TWO".into()),
314                        DiffLine::new(LineKind::Context, Some(3), Some(3), "three".into()),
315                    ],
316                }],
317            }],
318        }
319    }
320
321    fn line_anchor(file: &str, line: Option<u32>) -> Anchor {
322        Anchor {
323            file: file.to_owned(),
324            line,
325            line_end: None,
326            on_old_side: false,
327            hunk: None,
328            line_text: None,
329        }
330    }
331
332    #[test]
333    fn anchor_with_matching_line_text_is_current() {
334        let mut a = line_anchor("src/auth.py", Some(2));
335        a.line_text = Some("TWO".to_owned());
336        assert!(!a.is_outdated(&hunked_model()));
337        // without a snapshot, a present line counts as current
338        a.line_text = None;
339        assert!(!a.is_outdated(&hunked_model()));
340    }
341
342    #[test]
343    fn anchor_with_drifted_line_text_is_outdated() {
344        let mut a = line_anchor("src/auth.py", Some(2));
345        a.line_text = Some("old text".to_owned());
346        assert!(a.is_outdated(&hunked_model()));
347    }
348
349    #[test]
350    fn anchor_to_a_departed_line_is_outdated() {
351        let a = line_anchor("src/auth.py", Some(99));
352        assert!(a.is_outdated(&hunked_model()));
353    }
354
355    #[test]
356    fn old_side_anchor_checks_the_old_line() {
357        let mut a = line_anchor("src/auth.py", Some(2));
358        a.on_old_side = true;
359        a.line_text = Some("two".to_owned());
360        assert!(!a.is_outdated(&hunked_model()));
361        a.line_text = Some("TWO".to_owned());
362        assert!(a.is_outdated(&hunked_model()), "old side carries 'two'");
363    }
364
365    #[test]
366    fn range_anchor_judges_drift_on_its_end_line() {
367        let mut a = line_anchor("src/auth.py", Some(1));
368        a.line_end = Some(3);
369        a.line_text = Some("three".to_owned());
370        assert!(!a.is_outdated(&hunked_model()), "end line still matches");
371        a.line_text = Some("changed".to_owned());
372        assert!(a.is_outdated(&hunked_model()), "end line drifted");
373    }
374
375    #[test]
376    fn file_level_anchor_is_outdated_only_when_the_file_departs() {
377        assert!(!line_anchor("src/auth.py", None).is_outdated(&hunked_model()));
378        assert!(line_anchor("gone.py", None).is_outdated(&hunked_model()));
379    }
380
381    #[test]
382    fn reconcile_drops_departed_and_changed_keeps_matching() {
383        let kept = file_diff("kept.txt", "stable content\n");
384        let changed = file_diff("changed.txt", "rewritten content\n");
385
386        let mut s = Session::default();
387        s.mark_viewed("kept.txt", &kept.content_hash());
388        s.mark_viewed("changed.txt", "hash-of-old-content");
389        s.mark_viewed("departed.txt", "whatever");
390        s.add_comment("mattf", anchor("departed.txt"), "still relevant");
391
392        s.reconcile(&model(vec![kept, changed]));
393
394        assert!(s.viewed.contains_key("kept.txt"));
395        assert!(!s.viewed.contains_key("changed.txt"));
396        assert!(!s.viewed.contains_key("departed.txt"));
397        // comments survive reconciliation untouched
398        assert_eq!(s.comments.len(), 1);
399    }
400}