1use std::collections::BTreeMap;
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use serde::{Deserialize, Serialize};
8
9use crate::model::DiffModel;
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#[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)]
41 pub line_text: Option<String>,
42}
43
44impl Anchor {
45 pub fn is_outdated(&self, model: &DiffModel) -> bool {
50 match self.line_end.or(self.line) {
51 Some(line) => match model.find_line(&self.file, line, self.on_old_side) {
52 Some(found) => self
53 .line_text
54 .as_deref()
55 .is_some_and(|snap| snap != found.text),
56 None => true,
57 },
58 None => !model.files.iter().any(|f| f.path == self.file),
59 }
60 }
61}
62
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct Comment {
65 pub id: String,
66 pub author: String,
67 pub anchor: Anchor,
68 pub body: String,
69 pub status: CommentStatus,
70 #[serde(default)]
71 pub replies: Vec<Reply>,
72 pub at: u64,
73}
74
75#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
76pub struct Session {
77 #[serde(default)]
78 pub comments: Vec<Comment>,
79 #[serde(default)]
82 pub viewed: BTreeMap<String, String>,
83}
84
85pub fn now_unix() -> u64 {
86 SystemTime::now()
87 .duration_since(UNIX_EPOCH)
88 .map_or(0, |d| d.as_secs())
89}
90
91impl Session {
92 pub fn add_comment(&mut self, author: &str, anchor: Anchor, body: &str) -> &Comment {
93 self.comments.push(Comment {
94 id: uuid::Uuid::new_v4().to_string(),
95 author: author.to_owned(),
96 anchor,
97 body: body.to_owned(),
98 status: CommentStatus::Open,
99 replies: Vec::new(),
100 at: now_unix(),
101 });
102 #[allow(clippy::expect_used)]
104 self.comments.last().expect("just pushed")
105 }
106
107 fn comment_mut(&mut self, comment_id: &str) -> Option<&mut Comment> {
108 self.comments.iter_mut().find(|c| c.id == comment_id)
109 }
110
111 pub fn reply(&mut self, comment_id: &str, author: &str, body: &str) -> bool {
112 let Some(comment) = self.comment_mut(comment_id) else {
113 return false;
114 };
115 comment.replies.push(Reply {
116 author: author.to_owned(),
117 body: body.to_owned(),
118 at: now_unix(),
119 });
120 if comment.status == CommentStatus::Open {
121 comment.status = CommentStatus::Replied;
122 }
123 true
124 }
125
126 pub fn resolve(&mut self, comment_id: &str) -> bool {
127 let Some(comment) = self.comment_mut(comment_id) else {
128 return false;
129 };
130 comment.status = CommentStatus::Resolved;
131 true
132 }
133
134 pub fn edit_comment(&mut self, comment_id: &str, body: &str) -> bool {
136 let Some(comment) = self.comment_mut(comment_id) else {
137 return false;
138 };
139 body.clone_into(&mut comment.body);
140 true
141 }
142
143 pub fn mark_viewed(&mut self, path: &str, hash: &str) {
144 self.viewed.insert(path.to_owned(), hash.to_owned());
145 }
146
147 pub fn unmark_viewed(&mut self, path: &str) {
148 self.viewed.remove(path);
149 }
150
151 pub fn is_viewed(&self, path: &str, current_hash: &str) -> bool {
154 self.viewed.get(path).is_some_and(|h| h == current_hash)
155 }
156
157 pub fn reconcile(&mut self, model: &DiffModel) {
161 let live: BTreeMap<&str, String> = model
162 .files
163 .iter()
164 .map(|f| (f.path.as_str(), f.content_hash()))
165 .collect();
166 self.viewed
167 .retain(|path, hash| live.get(path.as_str()).is_some_and(|h| h == hash));
168 }
169}
170
171#[cfg(test)]
172mod tests {
173 use crate::model::{DiffLine, FileDiff, FileStatus, Hunk, HunkId, LineKind};
174
175 use super::*;
176
177 fn anchor(file: &str) -> Anchor {
178 Anchor {
179 file: file.to_owned(),
180 line: Some(3),
181 line_end: None,
182 on_old_side: false,
183 line_text: None,
184 }
185 }
186
187 fn file_diff(path: &str, new_text: &str) -> FileDiff {
188 FileDiff {
189 path: path.to_owned(),
190 old_path: None,
191 status: FileStatus::Modified,
192 binary: false,
193 old_text: None,
194 new_text: Some(new_text.to_owned()),
195 hunks: vec![],
196 }
197 }
198
199 fn model(files: Vec<FileDiff>) -> DiffModel {
200 DiffModel { files }
201 }
202
203 #[test]
204 fn comment_lifecycle_open_replied_resolved() {
205 let mut s = Session::default();
206 let id = s.add_comment("mattf", anchor("a.txt"), "why?").id.clone();
207 assert_eq!(s.comments[0].status, CommentStatus::Open);
208 assert!(s.reply(&id, "agent", "because"));
209 assert_eq!(s.comments[0].status, CommentStatus::Replied);
210 assert!(s.resolve(&id));
211 assert_eq!(s.comments[0].status, CommentStatus::Resolved);
212 assert!(
213 s.comments
214 .iter()
215 .all(|c| c.status == CommentStatus::Resolved)
216 );
217 }
218
219 #[test]
220 fn reply_to_missing_comment_returns_false() {
221 let mut s = Session::default();
222 assert!(!s.reply("nope", "agent", "hi"));
223 }
224
225 #[test]
226 fn resolve_missing_comment_returns_false() {
227 let mut s = Session::default();
228 assert!(!s.resolve("nope"));
229 }
230
231 #[test]
232 fn edit_comment_replaces_body_and_keeps_status() {
233 let mut s = Session::default();
234 let id = s
235 .add_comment("mattf", anchor("a.txt"), "old body")
236 .id
237 .clone();
238 assert!(s.reply(&id, "agent", "ack"));
239 assert!(s.edit_comment(&id, "new body"));
240 let c = s.comments.iter().find(|c| c.id == id).expect("comment");
241 assert_eq!(c.body, "new body");
242 assert_eq!(c.status, CommentStatus::Replied, "status is untouched");
243 assert_eq!(c.replies.len(), 1, "replies are untouched");
244 assert!(!s.edit_comment("nope", "x"));
245 }
246
247 #[test]
248 fn unresolved_comments_filters_resolved_only() {
249 let mut s = Session::default();
250 let keep = s.add_comment("mattf", anchor("a.txt"), "open").id.clone();
251 let done = s.add_comment("mattf", anchor("a.txt"), "done").id.clone();
252 assert!(s.resolve(&done));
253 let unresolved: Vec<_> = s
254 .comments
255 .iter()
256 .filter(|c| c.status != CommentStatus::Resolved)
257 .map(|c| c.id.clone())
258 .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 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 line_text: None,
328 }
329 }
330
331 #[test]
332 fn anchor_with_matching_line_text_is_current() {
333 let mut a = line_anchor("src/auth.py", Some(2));
334 a.line_text = Some("TWO".to_owned());
335 assert!(!a.is_outdated(&hunked_model()));
336 a.line_text = None;
338 assert!(!a.is_outdated(&hunked_model()));
339 }
340
341 #[test]
342 fn anchor_with_drifted_line_text_is_outdated() {
343 let mut a = line_anchor("src/auth.py", Some(2));
344 a.line_text = Some("old text".to_owned());
345 assert!(a.is_outdated(&hunked_model()));
346 }
347
348 #[test]
349 fn anchor_to_a_departed_line_is_outdated() {
350 let a = line_anchor("src/auth.py", Some(99));
351 assert!(a.is_outdated(&hunked_model()));
352 }
353
354 #[test]
355 fn old_side_anchor_checks_the_old_line() {
356 let mut a = line_anchor("src/auth.py", Some(2));
357 a.on_old_side = true;
358 a.line_text = Some("two".to_owned());
359 assert!(!a.is_outdated(&hunked_model()));
360 a.line_text = Some("TWO".to_owned());
361 assert!(a.is_outdated(&hunked_model()), "old side carries 'two'");
362 }
363
364 #[test]
365 fn range_anchor_judges_drift_on_its_end_line() {
366 let mut a = line_anchor("src/auth.py", Some(1));
367 a.line_end = Some(3);
368 a.line_text = Some("three".to_owned());
369 assert!(!a.is_outdated(&hunked_model()), "end line still matches");
370 a.line_text = Some("changed".to_owned());
371 assert!(a.is_outdated(&hunked_model()), "end line drifted");
372 }
373
374 #[test]
375 fn file_level_anchor_is_outdated_only_when_the_file_departs() {
376 assert!(!line_anchor("src/auth.py", None).is_outdated(&hunked_model()));
377 assert!(line_anchor("gone.py", None).is_outdated(&hunked_model()));
378 }
379
380 #[test]
381 fn reconcile_drops_departed_and_changed_keeps_matching() {
382 let kept = file_diff("kept.txt", "stable content\n");
383 let changed = file_diff("changed.txt", "rewritten content\n");
384
385 let mut s = Session::default();
386 s.mark_viewed("kept.txt", &kept.content_hash());
387 s.mark_viewed("changed.txt", "hash-of-old-content");
388 s.mark_viewed("departed.txt", "whatever");
389 s.add_comment("mattf", anchor("departed.txt"), "still relevant");
390
391 s.reconcile(&model(vec![kept, changed]));
392
393 assert!(s.viewed.contains_key("kept.txt"));
394 assert!(!s.viewed.contains_key("changed.txt"));
395 assert!(!s.viewed.contains_key("departed.txt"));
396 assert_eq!(s.comments.len(), 1);
398 }
399}