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 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub remote_id: Option<String>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct Anchor {
34 pub file: String,
35 #[serde(default)]
36 pub line: Option<u32>,
37 #[serde(default)]
38 pub line_end: Option<u32>,
39 #[serde(default)]
40 pub on_old_side: bool,
41 #[serde(default)]
44 pub line_text: Option<String>,
45}
46
47impl Anchor {
48 pub fn is_outdated(&self, model: &DiffModel) -> bool {
53 match self.line_end.or(self.line) {
54 Some(line) => match model.find_line(&self.file, line, self.on_old_side) {
55 Some(found) => self
56 .line_text
57 .as_deref()
58 .is_some_and(|snap| snap != found.text),
59 None => true,
60 },
61 None => !model.files.iter().any(|f| f.path == self.file),
62 }
63 }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub struct Comment {
68 pub id: String,
69 pub author: String,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub remote_id: Option<String>,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub thread_id: Option<String>,
77 pub anchor: Anchor,
78 pub body: String,
79 pub status: CommentStatus,
80 #[serde(default)]
81 pub replies: Vec<Reply>,
82 pub at: u64,
83}
84
85#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
86pub struct Session {
87 #[serde(default)]
88 pub comments: Vec<Comment>,
89 #[serde(default)]
92 pub viewed: BTreeMap<String, String>,
93}
94
95pub fn now_unix() -> u64 {
96 SystemTime::now()
97 .duration_since(UNIX_EPOCH)
98 .map_or(0, |d| d.as_secs())
99}
100
101impl Session {
102 pub fn add_comment(&mut self, anchor: Anchor, author: &str, body: &str) -> &Comment {
103 self.comments.push(Comment {
104 remote_id: None,
105 thread_id: None,
106 id: uuid::Uuid::new_v4().to_string(),
107 author: author.to_owned(),
108 anchor,
109 body: body.to_owned(),
110 status: CommentStatus::Open,
111 replies: Vec::new(),
112 at: now_unix(),
113 });
114 #[allow(clippy::expect_used)]
116 self.comments.last().expect("just pushed")
117 }
118
119 fn comment_mut(&mut self, comment_id: &str) -> Option<&mut Comment> {
120 self.comments.iter_mut().find(|c| c.id == comment_id)
121 }
122
123 pub fn delete_comment(&mut self, id: &str) -> bool {
125 let before = self.comments.len();
126 self.comments.retain(|c| c.id != id);
127 self.comments.len() != before
128 }
129
130 pub fn reply(&mut self, comment_id: &str, author: &str, body: &str) -> bool {
131 let Some(comment) = self.comment_mut(comment_id) else {
132 return false;
133 };
134 comment.replies.push(Reply {
135 remote_id: None,
136 author: author.to_owned(),
137 body: body.to_owned(),
138 at: now_unix(),
139 });
140 if comment.status == CommentStatus::Open {
141 comment.status = CommentStatus::Replied;
142 }
143 true
144 }
145
146 pub fn resolve(&mut self, comment_id: &str) -> bool {
147 let Some(comment) = self.comment_mut(comment_id) else {
148 return false;
149 };
150 comment.status = CommentStatus::Resolved;
151 true
152 }
153
154 pub fn edit_comment(&mut self, comment_id: &str, body: &str) -> bool {
158 let Some(comment) = self.comment_mut(comment_id) else {
159 return false;
160 };
161 body.clone_into(&mut comment.body);
162 true
163 }
164
165 pub fn mark_viewed(&mut self, path: &str, hash: &str) {
166 self.viewed.insert(path.to_owned(), hash.to_owned());
167 }
168
169 pub fn unmark_viewed(&mut self, path: &str) {
170 self.viewed.remove(path);
171 }
172
173 pub fn is_viewed(&self, path: &str, current_hash: &str) -> bool {
176 self.viewed.get(path).is_some_and(|h| h == current_hash)
177 }
178
179 pub fn reconcile(&mut self, model: &DiffModel) {
183 let live: BTreeMap<&str, String> = model
184 .files
185 .iter()
186 .map(|f| (f.path.as_str(), f.content_hash()))
187 .collect();
188 self.viewed
189 .retain(|path, hash| live.get(path.as_str()).is_some_and(|h| h == hash));
190 }
191}
192
193#[cfg(test)]
194mod tests {
195 use crate::model::{DiffLine, FileDiff, FileStatus, Hunk, HunkId, LineKind};
196 use crate::test_support::{anchor, file_diff};
197
198 use super::*;
199
200 fn model(files: Vec<FileDiff>) -> DiffModel {
201 DiffModel { files }
202 }
203
204 #[test]
205 fn comment_lifecycle_open_replied_resolved() {
206 let mut s = Session::default();
207 let id = s
208 .add_comment(anchor("a.txt", Some(3)), "reviewer", "why?")
209 .id
210 .clone();
211 assert_eq!(s.comments[0].status, CommentStatus::Open);
212 assert!(s.reply(&id, "agent", "because"));
213 assert_eq!(s.comments[0].status, CommentStatus::Replied);
214 assert!(s.resolve(&id));
215 assert_eq!(s.comments[0].status, CommentStatus::Resolved);
216 assert!(
217 s.comments
218 .iter()
219 .all(|c| c.status == CommentStatus::Resolved)
220 );
221 }
222
223 #[test]
224 fn reply_to_missing_comment_returns_false() {
225 let mut s = Session::default();
226 assert!(!s.reply("nope", "agent", "hi"));
227 }
228
229 #[test]
230 fn resolve_missing_comment_returns_false() {
231 let mut s = Session::default();
232 assert!(!s.resolve("nope"));
233 }
234
235 #[test]
236 fn edit_comment_replaces_body_and_keeps_status() {
237 let mut s = Session::default();
238 let id = s
239 .add_comment(anchor("a.txt", Some(3)), "reviewer", "old body")
240 .id
241 .clone();
242 assert!(s.reply(&id, "agent", "ack"));
243 assert!(s.edit_comment(&id, "new body"));
244 let c = s.comments.iter().find(|c| c.id == id).expect("comment");
245 assert_eq!(c.body, "new body");
246 assert_eq!(c.status, CommentStatus::Replied, "status is untouched");
247 assert_eq!(c.replies.len(), 1, "replies are untouched");
248 assert!(!s.edit_comment("nope", "x"));
249 }
250
251 #[test]
252 fn unresolved_comments_filters_resolved_only() {
253 let mut s = Session::default();
254 let keep = s
255 .add_comment(anchor("a.txt", Some(3)), "reviewer", "open")
256 .id
257 .clone();
258 let done = s
259 .add_comment(anchor("a.txt", Some(3)), "reviewer", "done")
260 .id
261 .clone();
262 assert!(s.resolve(&done));
263 let unresolved: Vec<_> = s
264 .comments
265 .iter()
266 .filter(|c| c.status != CommentStatus::Resolved)
267 .map(|c| c.id.clone())
268 .collect();
269 assert_eq!(unresolved, vec![keep]);
270 }
271
272 #[test]
273 fn session_serializes_round_trip_with_range_anchor() {
274 let mut s = Session::default();
275 let mut range = anchor("a.txt", Some(3));
276 range.line_end = Some(7);
277 s.add_comment(range, "reviewer", "this whole block");
278 s.mark_viewed("b.txt", "hash-b");
279 let json = serde_json::to_string(&s).expect("serialize");
280 let back: Session = serde_json::from_str(&json).expect("deserialize");
281 assert_eq!(s, back);
282 assert_eq!(back.comments[0].anchor.line_end, Some(7));
283 }
284
285 #[test]
286 fn is_viewed_true_for_same_hash_false_after_change() {
287 let mut s = Session::default();
288 s.mark_viewed("a.txt", "hash-1");
289 assert!(s.is_viewed("a.txt", "hash-1"));
290 assert!(!s.is_viewed("a.txt", "hash-2"));
291 assert!(!s.is_viewed("other.txt", "hash-1"));
292 }
293
294 #[test]
295 fn unmark_viewed_removes_entry() {
296 let mut s = Session::default();
297 s.mark_viewed("a.txt", "hash-1");
298 s.unmark_viewed("a.txt");
299 assert!(!s.is_viewed("a.txt", "hash-1"));
300 }
301
302 fn hunked_model() -> DiffModel {
304 DiffModel {
305 files: vec![FileDiff {
306 path: "src/auth.py".into(),
307 old_path: None,
308 status: FileStatus::Modified,
309 binary: false,
310 old_text: None,
311 new_text: None,
312 hunks: vec![Hunk {
313 id: HunkId("h1".into()),
314 old_start: 1,
315 old_lines: 3,
316 new_start: 1,
317 new_lines: 3,
318 context: String::new(),
319 lines: vec![
320 DiffLine::new(LineKind::Context, Some(1), Some(1), "one".into()),
321 DiffLine::new(LineKind::Deleted, Some(2), None, "two".into()),
322 DiffLine::new(LineKind::Added, None, Some(2), "TWO".into()),
323 DiffLine::new(LineKind::Context, Some(3), Some(3), "three".into()),
324 ],
325 }],
326 hashes: crate::model::HashCache::default(),
327 }],
328 }
329 }
330
331 #[test]
332 fn anchor_with_matching_line_text_is_current() {
333 let mut a = 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 = 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 = 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 = 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 = 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!(!anchor("src/auth.py", None).is_outdated(&hunked_model()));
377 assert!(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(
390 anchor("departed.txt", Some(3)),
391 "reviewer",
392 "still relevant",
393 );
394
395 s.reconcile(&model(vec![kept, changed]));
396
397 assert!(s.viewed.contains_key("kept.txt"));
398 assert!(!s.viewed.contains_key("changed.txt"));
399 assert!(!s.viewed.contains_key("departed.txt"));
400 assert_eq!(s.comments.len(), 1);
402 }
403}