diff --git a/docs/integrations/forge.md b/docs/integrations/forge.md index f39dbaea4..1eda15079 100644 --- a/docs/integrations/forge.md +++ b/docs/integrations/forge.md @@ -298,6 +298,28 @@ A review submitted with **no body** renders `reviewed by: ` in place of the `: ` line — deliberately worded to not collide with the meta-suffix `reviewer:` line (requested reviewers, below). +### Inline review comments + +A review's line comments belong to neither the review body nor the +`latest_comment_url`. A review with only inline comments has no such url +and would otherwise land as a bare `activity on PR`. Every PR wake therefore +fetches the PR's reviews (`/pulls/N/reviews`, up to four pages of 50) and, +for the reviews new to the agent, appends an +`inline review comments (read them with `hive-forge pr reviews N`):` block +saying where they sit: one `author: path:line, path, ...` line per review +author (bare `path` when Forgejo dropped the position because the line left +the diff; control characters in a path become spaces). The comment text stays +out of the wake, and the agent reads the full review with the CLI. + +A review counts as new when it landed strictly after the thread's previously +delivered `updated_at`. Without a baseline every review counts, and so does +one with no submit time, so nothing disappears. It doesn't count when the +agent wrote it, when it's a `PENDING` draft, or when `comments_count` is 0. +The notifier fetches the newest 5 such reviews and lists at most 10 locations +(`(+N more)` for the rest). Best effort: a failed fetch yields less text and +never drops the wake. Cost: one reviews fetch per PR wake, plus one per new +commented review. + ### Merge/close vs a later comment A notification carrying a `latest_comment_url` normally takes the comment diff --git a/hive-forge-notify/src/notify.rs b/hive-forge-notify/src/notify.rs index 35e62857a..d6f829b01 100644 --- a/hive-forge-notify/src/notify.rs +++ b/hive-forge-notify/src/notify.rs @@ -361,7 +361,7 @@ async fn format_notification( // comment stays on the comment path (see `state_change_is_current`). let is_fresh_state_change = state_change_is_current(¬if.state, notif.thread.updated_at, meta.subject.as_ref()); - if has_comment && !is_fresh_state_change { + let formatted = if has_comment && !is_fresh_state_change { let enrichment = CommentEnrichment { subject_api_url, prev_updated_at, @@ -377,38 +377,16 @@ async fn format_notification( ) .await } else { - // State-change path (merge/close/new/activity). A just-merged or - // closed subject keeps its pre-merge last comment on - // `latest_comment_url`, so `has_comment` is often true here. When - // that comment was genuinely posted AFTER the close — a comment - // racing the merge inside the state-change tolerance window — append - // it so it isn't lost (best of both worlds; see - // `docs/integrations/forge.md::Merge racing a comment`). The ordinary pre-merge - // last comment (created before `closed_at`) is left off. - let comment_tail = if has_comment { - fresh_post_close_comment_tail( - client, - source, - comment_api_url, - meta.subject.as_ref(), - own_login, - ) - .await - } else { - None - }; - // Same widened marker as the comment path (see that branch's - // comment), pre-fetched here because `format_state_change_notification` - // stays sync — mirrors how `comment_tail` above is already fetched - // before the sync formatter is called, same reason. - let earlier_updates = if let (Some(since), Some(current)) = - (prev_updated_at, notif.thread.updated_at) - { - fetch_unseen_earlier_events(client, source, subject_api_url, since, current, own_login) - .await - } else { - None - }; + let (comment_tail, earlier_updates) = state_change_extras( + client, + source, + has_comment.then_some(comment_api_url), + &meta, + subject_api_url, + prev_updated_at.zip(notif.thread.updated_at), + own_login, + ) + .await; format_state_change_notification( notif.thread.updated_at, ¬if.state, @@ -417,7 +395,57 @@ async fn format_notification( comment_tail, earlier_updates, ) + }; + // A review's inline comments ride neither the review body nor the + // comment url (a bodiless review has no `latest_comment_url` at all), + // so every PR wake gets the unseen ones appended. + let mut out = formatted?; + if is_pr { + out.push_str( + &fetch_inline_review_tail(client, source, subject_api_url, prev_updated_at, own_login) + .await, + ); } + Some(out) +} + +/// The two pre-fetches the sync state-change formatter needs. +/// +/// State-change path (merge/close/new/activity). A just-merged or +/// closed subject keeps its pre-merge last comment on +/// `latest_comment_url`, so a comment url is often present here. When +/// that comment was genuinely posted AFTER the close - a comment +/// racing the merge inside the state-change tolerance window - it is +/// appended so it isn't lost (best of both worlds; see +/// `docs/integrations/forge.md::Merge racing a comment`). The ordinary +/// pre-merge last comment (created before `closed_at`) is left off. +/// The earlier-updates count is the same widened marker as the comment +/// path; both are fetched here because `format_state_change_notification` +/// stays sync. +async fn state_change_extras( + client: &reqwest::Client, + source: &S, + comment_api_url: Option<&str>, + meta: &NotifMeta<'_>, + subject_api_url: &str, + since_and_current: Option<(&str, OffsetDateTime)>, + own_login: &str, +) -> (Option, Option) { + let comment_tail = match comment_api_url { + Some(url) => { + fresh_post_close_comment_tail(client, source, url, meta.subject.as_ref(), own_login) + .await + } + None => None, + }; + let earlier_updates = match since_and_current { + Some((since, current)) => { + fetch_unseen_earlier_events(client, source, subject_api_url, since, current, own_login) + .await + } + None => None, + }; + (comment_tail, earlier_updates) } /// Shared notification metadata extracted from the polled notification. @@ -872,6 +900,140 @@ async fn fresh_post_close_comment_tail( Some(format!("\n\ncomment by {author}: {excerpt}{mentions}")) } +/// Inline review comment locations listed in one wake; the rest become a count. +const INLINE_COMMENTS_MAX: usize = 10; +/// Reviews whose inline comments are fetched for one wake (the newest). +const INLINE_REVIEWS_MAX: usize = 5; +/// Page size and page cap for the reviews list, so a long-lived PR's +/// newest reviews are not stranded behind the first page. +const REVIEWS_PAGE_SIZE: usize = 50; +const REVIEWS_PAGES_MAX: usize = 4; + +/// The PR's reviews endpoint and number from the notification subject URL. +/// Forgejo hands out the *issues* URL for a PR (`.../issues/N`); its reviews +/// live under `.../pulls/N/reviews`. `None` for any other shape. +fn reviews_api_url(subject_api_url: &str) -> Option<(String, &str)> { + let (head, number) = subject_api_url.rsplit_once("/issues/")?; + Some((format!("{head}/pulls/{number}/reviews"), number)) +} + +/// `(review id, author)` of the reviews in `reviews` (the raw reviews +/// list, oldest first) that carry inline comments the agent has not been +/// woken for: submitted strictly after `since` (all of them without a +/// baseline, and any whose time is missing, so nothing is hidden), not +/// the agent's own, and not an unsubmitted `PENDING` draft. Newest +/// [`INLINE_REVIEWS_MAX`] only. +fn unseen_inline_reviews( + reviews: &[serde_json::Value], + since: Option, + own_login: &str, +) -> Vec<(i64, String)> { + let mut unseen: Vec<(i64, String)> = reviews + .iter() + .filter(|r| r["comments_count"].as_i64().unwrap_or(0) > 0) + .filter(|r| r["state"].as_str() != Some("PENDING")) + .filter(|r| { + let author = r["user"]["login"].as_str().unwrap_or(""); + own_login.is_empty() || author != own_login + }) + .filter( + |r| match (since, r["submitted_at"].as_str().and_then(parse_rfc3339)) { + (Some(since), Some(at)) => at > since, + _ => true, + }, + ) + .filter_map(|r| { + let id = r["id"].as_i64()?; + Some((id, r["user"]["login"].as_str().unwrap_or("?").to_owned())) + }) + .collect(); + let skip = unseen.len().saturating_sub(INLINE_REVIEWS_MAX); + unseen.drain(..skip); + unseen +} + +/// One comment's location for the wake: `path:line`, or just `path` when +/// Forgejo dropped the position because the line left the diff. Control +/// characters in the path (git allows a newline in one) become spaces so a +/// PR author cannot shape the lines the agent reads. +fn comment_location(c: &serde_json::Value) -> String { + let path: String = c["path"] + .as_str() + .unwrap_or("?") + .chars() + .map(|ch| if ch.is_control() { ' ' } else { ch }) + .collect(); + match c["position"].as_u64().filter(|&line| line > 0) { + Some(line) => format!("{path}:{line}"), + None => path, + } +} + +/// The `inline review comments` block for the wake: only where the unseen +/// comments are, one line per review author (`author: path:line, ...`), +/// capped at [`INLINE_COMMENTS_MAX`] locations in total with a count for the +/// rest. The text stays out of the wake: the pointer names the CLI call that +/// prints the full review. Empty when there is nothing to show. +fn render_inline_comments(pr_number: &str, groups: &[(String, Vec)]) -> String { + let total: usize = groups.iter().map(|(_, c)| c.len()).sum(); + if total == 0 { + return String::new(); + } + let mut out = + format!("\n\ninline review comments (read them with `hive-forge pr reviews {pr_number}`):"); + let mut budget = INLINE_COMMENTS_MAX; + for (author, comments) in groups { + let shown: Vec = comments.iter().take(budget).map(comment_location).collect(); + if shown.is_empty() { + continue; + } + budget -= shown.len(); + write!(out, "\n {author}: {}", shown.join(", ")).ok(); + } + if total > INLINE_COMMENTS_MAX { + write!(out, "\n (+{} more)", total - INLINE_COMMENTS_MAX).ok(); + } + out +} + +/// Fetch + render the unseen inline review comments of a PR (see +/// [`unseen_inline_reviews`]). Best effort like every other enrichment: +/// any failed fetch just yields less (or no) text, never a dropped wake. +async fn fetch_inline_review_tail( + client: &reqwest::Client, + source: &S, + subject_api_url: &str, + prev_updated_at: Option<&str>, + own_login: &str, +) -> String { + let Some((reviews_url, pr_number)) = reviews_api_url(subject_api_url) else { + return String::new(); + }; + let mut reviews: Vec = Vec::new(); + for page in 1..=REVIEWS_PAGES_MAX { + let url = format!("{reviews_url}?page={page}&limit={REVIEWS_PAGE_SIZE}"); + let Some(batch) = fetch_json(client, &url, source).await else { + break; + }; + let Some(batch) = batch.as_array() else { + break; + }; + reviews.extend(batch.iter().cloned()); + if batch.len() < REVIEWS_PAGE_SIZE { + break; + } + } + let since = prev_updated_at.and_then(parse_rfc3339); + let mut groups = Vec::new(); + for (id, author) in unseen_inline_reviews(&reviews, since, own_login) { + let comments = fetch_json(client, &format!("{reviews_url}/{id}/comments"), source).await; + if let Some(comments) = comments.as_ref().and_then(serde_json::Value::as_array) { + groups.push((author, comments.clone())); + } + } + render_inline_comments(pr_number, &groups) +} + /// Parse an RFC 3339 timestamp as Forgejo emits them /// (`2026-06-13T11:18:42+02:00` or `...Z`, optionally with fractional /// seconds). Returns `None` on any shape `time` doesn't recognise so @@ -1824,4 +1986,127 @@ mod tests { 2 ); } + + fn review(id: i64, user: &str, state: &str, n: i64, at: &str) -> serde_json::Value { + serde_json::json!({ + "id": id, + "user": {"login": user}, + "state": state, + "comments_count": n, + "submitted_at": at, + }) + } + + #[test] + fn reviews_api_url_swaps_issues_for_pulls() { + let subject = "/api/v1/repos/o/r/issues/42"; // lint:allow test input, not a tracker reference + assert_eq!( + reviews_api_url(subject), + Some(("/api/v1/repos/o/r/pulls/42/reviews".to_owned(), "42")), + ); + assert_eq!(reviews_api_url("/api/v1/repos/o/r"), None); + } + + #[test] + fn unseen_inline_reviews_keeps_only_new_foreign_submitted_commented() { + let since = parse_rfc3339("2026-10-30T10:00:00Z"); + let reviews = vec![ + review(1, "argus", "COMMENT", 2, "2026-10-30T09:00:00Z"), // seen + review(2, "argus", "COMMENT", 0, "2026-10-30T11:00:00Z"), // no inline + review(3, "me", "COMMENT", 3, "2026-10-30T11:00:00Z"), // own + review(4, "argus", "PENDING", 1, "2026-10-30T11:00:00Z"), // draft + review(5, "argus", "REQUEST_CHANGES", 1, "2026-10-30T12:00:00Z"), + ]; + assert_eq!( + unseen_inline_reviews(&reviews, since, "me"), + vec![(5, "argus".to_owned())] + ); + } + + #[test] + fn unseen_inline_reviews_without_baseline_or_time_hides_nothing() { + let reviews = vec![ + review(1, "argus", "COMMENT", 1, "2026-10-30T09:00:00Z"), + serde_json::json!({"id": 2, "user": {"login": "argus"}, "state": "COMMENT", "comments_count": 1}), + ]; + let ids: Vec = unseen_inline_reviews(&reviews, None, "me") + .into_iter() + .map(|(id, _)| id) + .collect(); + assert_eq!(ids, vec![1, 2]); + // A missing submit time is shown even against a baseline. + let since = parse_rfc3339("2026-10-30T10:00:00Z"); + let ids: Vec = unseen_inline_reviews(&reviews, since, "me") + .into_iter() + .map(|(id, _)| id) + .collect(); + assert_eq!(ids, vec![2]); + } + + #[test] + fn unseen_inline_reviews_keeps_the_newest_few() { + let reviews: Vec<_> = (1..=8) + .map(|i| review(i, "argus", "COMMENT", 1, "2026-10-30T11:00:00Z")) + .collect(); + let ids: Vec = unseen_inline_reviews(&reviews, None, "me") + .into_iter() + .map(|(id, _)| id) + .collect(); + assert_eq!(ids, vec![4, 5, 6, 7, 8]); + } + + #[test] + fn render_inline_comments_lists_locations_not_text() { + let groups = vec![ + ( + "argus".to_owned(), + vec![ + serde_json::json!({"path": "src/a.rs", "position": 42, "body": "off by one"}), + serde_json::json!({"path": "src/b.rs", "position": 0, "body": "left the diff"}), + ], + ), + ( + "mara".to_owned(), + vec![serde_json::json!({"path": "src/c.rs", "position": 7, "body": "why"})], + ), + ]; + assert_eq!( + render_inline_comments("12", &groups), + "\n\ninline review comments (read them with `hive-forge pr reviews 12`):\ + \n argus: src/a.rs:42, src/b.rs\ + \n mara: src/c.rs:7" + ); + } + + #[test] + fn render_inline_comments_empty_is_empty() { + assert_eq!(render_inline_comments("12", &[]), ""); + assert_eq!( + render_inline_comments("12", &[("argus".to_owned(), vec![])]), + "" + ); + } + + #[test] + fn render_inline_comments_caps_locations_across_authors() { + let many = |n: u64| -> Vec { + (1..=n) + .map(|i| serde_json::json!({"path": "f.rs", "position": i})) + .collect() + }; + let out = render_inline_comments( + "12", + &[("argus".to_owned(), many(8)), ("mara".to_owned(), many(5))], + ); + // 8 from argus, the 2 left of the budget from mara, 3 counted. + assert_eq!(out.matches("f.rs:").count(), INLINE_COMMENTS_MAX); + assert!(out.contains("\n mara: f.rs:1, f.rs:2\n")); + assert!(out.ends_with("\n (+3 more)")); + } + + #[test] + fn comment_location_neutralises_control_characters_in_the_path() { + let c = serde_json::json!({"path": "a\nb\tc.rs", "position": 3}); + assert_eq!(comment_location(&c), "a b c.rs:3"); + } }