forge
Explore
Log in

Don't you dare go Hollow

Suggested changes in pull request reviews

Browse files at this commit

ca21cba4f3f4489469a5aa2a9786dae3d979e782Ahmet Kaan GümüşParent: 5bed83d
  • feat
    • suggested changes in pull request reviews
Show full message
✨ feat: suggested changes in pull request reviews
crates/forge-core/src/lib.rsmodified+1 -0
@@ -28,6 +28,7 @@ pub mod secret;
28 pub mod server_settings;28 pub mod server_settings;
29 pub mod session;29 pub mod session;
30 pub mod store;30 pub mod store;
31+pub mod suggestions;
31 pub mod time;32 pub mod time;
32 pub mod token;33 pub mod token;
33 pub mod totp;34 pub mod totp;
crates/forge-core/src/suggestions.rsadded+209 -0
@@ -0,0 +1,209 @@
1+//! Suggested changes in review comments. A comment whose body holds a fenced block opened with
2+//! ```suggestion proposes replacing the commented line with the lines of that block. This module
3+//! splits a body into text and suggestion parts, and computes the replacement of one line of a
4+//! file. The web layer checks the replacement against the head and the git layer commits it.
5+
6+/// One part of a comment body: markdown text, or the lines of a suggestion block.
7+#[derive(Debug, Clone, PartialEq, Eq)]
8+pub enum Part {
9+ Text(String),
10+ Suggestion(Vec<String>),
11+}
12+
13+/// Why a suggestion cannot replace a line.
14+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15+pub enum ApplyError {
16+ /// The file has no such line.
17+ OutOfRange,
18+ /// The line no longer reads what the comment was written against.
19+ Changed,
20+}
21+
22+/// Splits a comment body into text and suggestion parts, in order. A suggestion opens with three
23+/// or more backticks and the word `suggestion`, and closes with a line of at least as many
24+/// backticks. A fence that never closes is text, as is any other code fence.
25+pub fn split_body(body: &str) -> Vec<Part> {
26+ let lines: Vec<&str> = body.split('\n').collect();
27+ let mut parts = Vec::new();
28+ let mut text: Vec<&str> = Vec::new();
29+ let mut i = 0;
30+ while i < lines.len() {
31+ if let Some(ticks) = open_fence(lines[i]) {
32+ let close = (i + 1..lines.len()).find(|&j| closes_fence(lines[j], ticks));
33+ if let Some(close) = close {
34+ if !text.is_empty() {
35+ parts.push(Part::Text(text.join("\n")));
36+ text.clear();
37+ }
38+ let block = lines[i + 1..close]
39+ .iter()
40+ .map(|line| line.trim_end_matches('\r').to_owned())
41+ .collect();
42+ parts.push(Part::Suggestion(block));
43+ i = close + 1;
44+ continue;
45+ }
46+ }
47+ text.push(lines[i]);
48+ i += 1;
49+ }
50+ if !text.is_empty() {
51+ parts.push(Part::Text(text.join("\n")));
52+ }
53+ parts
54+}
55+
56+/// The number of backticks of a line that opens a suggestion block, if it does.
57+fn open_fence(line: &str) -> Option<usize> {
58+ let ticks = line.bytes().take_while(|&b| b == b'`').count();
59+ (ticks >= 3 && line[ticks..].trim() == "suggestion").then_some(ticks)
60+}
61+
62+/// Whether `line` closes a fence opened with `ticks` backticks.
63+fn closes_fence(line: &str, ticks: usize) -> bool {
64+ let trimmed = line.trim();
65+ trimmed.len() >= ticks && trimmed.bytes().all(|b| b == b'`')
66+}
67+
68+/// The text of the commented line, read from the last line of a stored diff hunk. The hunk ends
69+/// at the commented line, and that line is an added or a context line. `None` for a deleted line.
70+pub fn hunk_line(diff_hunk: &str) -> Option<&str> {
71+ let last = diff_hunk.lines().last()?;
72+ match last.as_bytes().first()? {
73+ b'+' | b' ' => Some(&last[1..]),
74+ _ => None,
75+ }
76+}
77+
78+/// `text` with line `line` (1-based) replaced by `replacement`, when that line still reads
79+/// `expected`. An empty replacement deletes the line. The trailing newline of `text` is kept.
80+pub fn replace_line(
81+ text: &str,
82+ line: u32,
83+ expected: &str,
84+ replacement: &[String],
85+) -> Result<String, ApplyError> {
86+ if text.is_empty() {
87+ return Err(ApplyError::OutOfRange);
88+ }
89+ let index = (line as usize)
90+ .checked_sub(1)
91+ .ok_or(ApplyError::OutOfRange)?;
92+ let ends_with_newline = text.ends_with('\n');
93+ let body = text.strip_suffix('\n').unwrap_or(text);
94+ let mut lines: Vec<&str> = body.split('\n').collect();
95+ let current = lines.get(index).ok_or(ApplyError::OutOfRange)?;
96+ if current.trim_end_matches('\r') != expected.trim_end_matches('\r') {
97+ return Err(ApplyError::Changed);
98+ }
99+ let replacement: Vec<&str> = replacement.iter().map(String::as_str).collect();
100+ lines.splice(index..=index, replacement);
101+ let mut out = lines.join("\n");
102+ if ends_with_newline {
103+ out.push('\n');
104+ }
105+ Ok(out)
106+}
107+
108+#[cfg(test)]
109+mod tests {
110+ use super::*;
111+
112+ fn lines(items: &[&str]) -> Vec<String> {
113+ items.iter().map(|s| s.to_string()).collect()
114+ }
115+
116+ #[test]
117+ fn body_without_a_suggestion_is_one_text_part() {
118+ assert_eq!(
119+ split_body("looks fine\n\n```rust\nlet x = 1;\n```"),
120+ vec![Part::Text("looks fine\n\n```rust\nlet x = 1;\n```".into())]
121+ );
122+ }
123+
124+ #[test]
125+ fn suggestion_block_is_split_out_with_its_surrounding_text() {
126+ let body = "Try this:\n```suggestion\nlet y = 2;\n```\nThanks";
127+ assert_eq!(
128+ split_body(body),
129+ vec![
130+ Part::Text("Try this:".into()),
131+ Part::Suggestion(lines(&["let y = 2;"])),
132+ Part::Text("Thanks".into()),
133+ ]
134+ );
135+ }
136+
137+ #[test]
138+ fn empty_suggestion_and_several_blocks_are_parsed_in_order() {
139+ let body = "```suggestion\n```\n\n````suggestion\na\n```\nb\n````";
140+ assert_eq!(
141+ split_body(body),
142+ vec![
143+ Part::Suggestion(vec![]),
144+ Part::Text("".into()),
145+ Part::Suggestion(lines(&["a", "```", "b"])),
146+ ]
147+ );
148+ }
149+
150+ #[test]
151+ fn unclosed_suggestion_fence_stays_text() {
152+ let body = "```suggestion\nlet y = 2;";
153+ assert_eq!(split_body(body), vec![Part::Text(body.into())]);
154+ }
155+
156+ #[test]
157+ fn hunk_last_line_gives_the_commented_text() {
158+ assert_eq!(hunk_line("-old\n+let x = 1;"), Some("let x = 1;"));
159+ assert_eq!(hunk_line(" ctx\n more"), Some("more"));
160+ assert_eq!(hunk_line("+a\n-gone"), None);
161+ assert_eq!(hunk_line(""), None);
162+ }
163+
164+ #[test]
165+ fn replace_line_swaps_one_line_and_keeps_the_rest() {
166+ let text = "a\nb\nc\n";
167+ assert_eq!(
168+ replace_line(text, 2, "b", &lines(&["B"])),
169+ Ok("a\nB\nc\n".into())
170+ );
171+ }
172+
173+ #[test]
174+ fn replace_line_can_expand_delete_and_keep_a_missing_newline() {
175+ assert_eq!(
176+ replace_line("a\nb", 2, "b", &lines(&["b1", "b2"])),
177+ Ok("a\nb1\nb2".into())
178+ );
179+ assert_eq!(replace_line("a\nb\nc\n", 2, "b", &[]), Ok("a\nc\n".into()));
180+ }
181+
182+ #[test]
183+ fn replace_line_refuses_a_changed_or_missing_line() {
184+ assert_eq!(
185+ replace_line("a\nb\n", 2, "old", &lines(&["x"])),
186+ Err(ApplyError::Changed)
187+ );
188+ assert_eq!(
189+ replace_line("a\nb\n", 3, "b", &lines(&["x"])),
190+ Err(ApplyError::OutOfRange)
191+ );
192+ assert_eq!(
193+ replace_line("a\n", 0, "a", &lines(&["x"])),
194+ Err(ApplyError::OutOfRange)
195+ );
196+ assert_eq!(
197+ replace_line("", 1, "", &lines(&["x"])),
198+ Err(ApplyError::OutOfRange)
199+ );
200+ }
201+
202+ #[test]
203+ fn replace_line_ignores_carriage_returns_on_the_expected_line() {
204+ assert_eq!(
205+ replace_line("a\r\nb\r\n", 1, "a", &lines(&["A"])),
206+ Ok("A\nb\r\n".into())
207+ );
208+ }
209+}
crates/forge-git/src/pulls.rsmodified+116 -0
@@ -632,6 +632,122 @@ pub async fn rebase_commits(
632 Ok(RebaseResult::Clean { tip, count })632 Ok(RebaseResult::Clean { tip, count })
633 }633 }
634 634
635+/// One file of a commit made by [`commit_file_edit`].
636+#[derive(Debug, Clone, Copy)]
637+pub struct FileEdit<'a> {
638+ /// Repo path of the file. It must be a regular file in the base commit.
639+ pub path: &'a str,
640+ /// The new content of the file.
641+ pub content: &'a [u8],
642+}
643+
644+static EDIT_INDEX_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
645+
646+/// Commits `edit` on top of `base` and moves `refname` from `base` to the new commit, only if the
647+/// ref still holds `base`. A moved ref gives `Error::RefMoved` and nothing changes. The new tree is
648+/// `base`'s tree with the one file replaced and its mode kept. It is built in a temporary index in
649+/// the repo, so no working tree is needed. The commit's only parent is `base`. Returns its id.
650+#[allow(clippy::too_many_arguments)]
651+pub async fn commit_file_edit(
652+ env: &GitEnv,
653+ repo: &Path,
654+ refname: &str,
655+ base: &str,
656+ edit: &FileEdit<'_>,
657+ message: &str,
658+ author: &Signature,
659+ committer: &Signature,
660+) -> Result<String> {
661+ validate_ref(refname)?;
662+ validate_oid(base)?;
663+ validate_blob_path(edit.path)?;
664+ let seq = EDIT_INDEX_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
665+ let index = repo.join(format!("forge-edit-index-{}-{seq}", std::process::id()));
666+ let result = edit_and_commit(
667+ env, repo, &index, refname, base, edit, message, author, committer,
668+ )
669+ .await;
670+ // The index is scratch space. A leftover file is harmless, but do not keep it.
671+ let _ = tokio::fs::remove_file(&index).await;
672+ result
673+}
674+
675+#[allow(clippy::too_many_arguments)]
676+async fn edit_and_commit(
677+ env: &GitEnv,
678+ repo: &Path,
679+ index: &Path,
680+ refname: &str,
681+ base: &str,
682+ edit: &FileEdit<'_>,
683+ message: &str,
684+ author: &Signature,
685+ committer: &Signature,
686+) -> Result<String> {
687+ let blob = GitCommand::new(env, "hash-object")
688+ .git_dir(repo)
689+ .arg("-w")
690+ .arg("--stdin")
691+ .output_stdin(edit.content)
692+ .await?;
693+ let blob = String::from_utf8_lossy(&blob).trim().to_owned();
694+ validate_oid(&blob)?;
695+
696+ GitCommand::new(env, "read-tree")
697+ .git_dir(repo)
698+ .env("GIT_INDEX_FILE", index)
699+ .user_arg(base)?
700+ .status()
701+ .await?;
702+
703+ // `ls-files -s` gives `<mode> <oid> <stage>\t<path>`. The path must be the file itself, and a
704+ // regular file: a symlink or a submodule is not something a suggestion can rewrite.
705+ let listing = GitCommand::new(env, "ls-files")
706+ .git_dir(repo)
707+ .env("GIT_INDEX_FILE", index)
708+ .arg("-s")
709+ .arg("-z")
710+ .arg("--")
711+ .user_arg(edit.path)?
712+ .output()
713+ .await?;
714+ let entry =
715+ String::from_utf8_lossy(listing.split(|b| *b == 0).next().unwrap_or_default()).into_owned();
716+ let mode = match entry.split_once('\t') {
717+ Some((meta, path)) if path == edit.path => meta.split_whitespace().next().unwrap_or(""),
718+ _ => "",
719+ };
720+ if mode != "100644" && mode != "100755" {
721+ return Err(Error::InvalidInput(format!(
722+ "{} is not a regular file at this commit",
723+ edit.path
724+ )));
725+ }
726+ let mode = mode.to_owned();
727+
728+ GitCommand::new(env, "update-index")
729+ .git_dir(repo)
730+ .env("GIT_INDEX_FILE", index)
731+ .arg("--add")
732+ .arg("--cacheinfo")
733+ .user_arg(&mode)?
734+ .user_arg(&blob)?
735+ .user_arg(edit.path)?
736+ .status()
737+ .await?;
738+
739+ let tree = GitCommand::new(env, "write-tree")
740+ .git_dir(repo)
741+ .env("GIT_INDEX_FILE", index)
742+ .output()
743+ .await?;
744+ let tree = String::from_utf8_lossy(&tree).trim().to_owned();
745+
746+ let commit = commit_tree(env, repo, &tree, &[base], message, author, committer).await?;
747+ update_ref_cas(env, repo, refname, &commit, base).await?;
748+ Ok(commit)
749+}
750+
635 #[cfg(test)]751 #[cfg(test)]
636 mod tests {752 mod tests {
637 use super::*;753 use super::*;
crates/forge-web/assets/nav.jsmodified+17 -0
@@ -996,6 +996,23 @@
996 if (/^#L\d+$/.test(location.hash)) { logSelect(location.hash.slice(1), true); }996 if (/^#L\d+$/.test(location.hash)) { logSelect(location.hash.slice(1), true); }
997 });997 });
998 998
999+ // "Suggest change" (a button with data-suggest in a comment form) puts a ```suggestion block that
1000+ // holds the commented line into the form's comment box, at the caret. No request is made.
1001+ document.addEventListener('click', function (e) {
1002+ var btn = e.target && e.target.closest ? e.target.closest('[data-suggest]') : null;
1003+ if (!btn) { return; }
1004+ e.preventDefault();
1005+ var form = btn.closest('form');
1006+ var area = form ? form.querySelector('textarea[name="body"]') : null;
1007+ if (!area) { return; }
1008+ var block = '```suggestion\n' + btn.getAttribute('data-suggest') + '\n```\n';
1009+ var start = area.selectionStart != null ? area.selectionStart : area.value.length;
1010+ var end = area.selectionEnd != null ? area.selectionEnd : start;
1011+ area.value = area.value.slice(0, start) + block + area.value.slice(end);
1012+ area.focus();
1013+ area.setSelectionRange(start + block.length, start + block.length);
1014+ });
1015+
999 // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of1016 // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of
1000 // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in1017 // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in
1001 // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose1018 // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose
crates/forge-web/src/ci/live.rsmodified+3 -3
@@ -80,7 +80,7 @@ impl CiLive {
80 80
81 /// One keyed set of counters. A key has an entry only while it has a receiver or a bump is due.81 /// One keyed set of counters. A key has an entry only while it has a receiver or a bump is due.
82 #[derive(Default)]82 #[derive(Default)]
83-struct Signals {83+pub(crate) struct Signals {
84 counters: Mutex<HashMap<String, watch::Sender<u64>>>,84 counters: Mutex<HashMap<String, watch::Sender<u64>>>,
85 }85 }
86 86
@@ -89,7 +89,7 @@ impl Signals {
89 self.counters.lock().unwrap_or_else(PoisonError::into_inner)89 self.counters.lock().unwrap_or_else(PoisonError::into_inner)
90 }90 }
91 91
92- fn subscribe(&self, key: &str) -> watch::Receiver<u64> {92+ pub(crate) fn subscribe(&self, key: &str) -> watch::Receiver<u64> {
93 self.counters()93 self.counters()
94 .entry(key.to_owned())94 .entry(key.to_owned())
95 .or_insert_with(|| watch::channel(0).0)95 .or_insert_with(|| watch::channel(0).0)
@@ -98,7 +98,7 @@ impl Signals {
98 98
99 /// Counts one change. Without a subscriber there is no entry, so the bump is a no-op. An entry99 /// Counts one change. Without a subscriber there is no entry, so the bump is a no-op. An entry
100 /// whose last receiver is gone is removed here.100 /// whose last receiver is gone is removed here.
101- fn bump(&self, key: &str) {101+ pub(crate) fn bump(&self, key: &str) {
102 let mut counters = self.counters();102 let mut counters = self.counters();
103 let Some(tx) = counters.get(key) else {103 let Some(tx) = counters.get(key) else {
104 return;104 return;
crates/forge-web/src/i18n/pulls_review.rsmodified+30 -0
@@ -75,6 +75,12 @@ pub enum K {
75 ReviewErrInvalid,75 ReviewErrInvalid,
76 ReviewErrBadLine,76 ReviewErrBadLine,
77 ReviewErrClosed,77 ReviewErrClosed,
78+ ReviewErrOutdated,
79+ ReviewErrNoPush,
80+ SuggestedChange,
81+ SuggestChange,
82+ ApplySuggestion,
83+ SuggestionOutdated,
78 EditReviewComment,84 EditReviewComment,
79 CommentLabel,85 CommentLabel,
80 SaveComment,86 SaveComment,
@@ -290,6 +296,24 @@ pub fn t(lang: Lang, key: K) -> &'static str {
290 (ReviewErrClosed, Tr) => {296 (ReviewErrClosed, Tr) => {
291 "Bu çekme isteği kapalı olduğu için yeni incelemeler gönderilemez."297 "Bu çekme isteği kapalı olduğu için yeni incelemeler gönderilemez."
292 }298 }
299+ (ReviewErrOutdated, En) => {
300+ "This suggestion no longer applies to the current head. Reload the page to see the latest code."
301+ }
302+ (ReviewErrOutdated, Tr) => {
303+ "Bu öneri artık güncel başın üzerinde uygulanamıyor. En son kodu görmek için sayfayı yenileyin."
304+ }
305+ (ReviewErrNoPush, En) => {
306+ "You cannot push to this branch, so the suggestion cannot be applied."
307+ }
308+ (ReviewErrNoPush, Tr) => "Bu dala push yapamadığınız için öneri uygulanamaz.",
309+ (SuggestChange, En) => "Suggest change",
310+ (SuggestChange, Tr) => "Değişiklik öner",
311+ (SuggestedChange, En) => "Suggested change",
312+ (SuggestedChange, Tr) => "Önerilen değişiklik",
313+ (ApplySuggestion, En) => "Apply suggestion",
314+ (ApplySuggestion, Tr) => "Öneriyi uygula",
315+ (SuggestionOutdated, En) => "This suggestion is outdated",
316+ (SuggestionOutdated, Tr) => "Bu öneri güncel değil",
293 (EditReviewComment, En) => "Edit review comment",317 (EditReviewComment, En) => "Edit review comment",
294 (EditReviewComment, Tr) => "İnceleme yorumunu düzenle",318 (EditReviewComment, Tr) => "İnceleme yorumunu düzenle",
295 (CommentLabel, En) => "Comment",319 (CommentLabel, En) => "Comment",
@@ -479,6 +503,12 @@ pub const ALL: &[K] = &[
479 K::ReviewErrInvalid,503 K::ReviewErrInvalid,
480 K::ReviewErrBadLine,504 K::ReviewErrBadLine,
481 K::ReviewErrClosed,505 K::ReviewErrClosed,
506+ K::ReviewErrOutdated,
507+ K::ReviewErrNoPush,
508+ K::SuggestedChange,
509+ K::SuggestChange,
510+ K::ApplySuggestion,
511+ K::SuggestionOutdated,
482 K::EditReviewComment,512 K::EditReviewComment,
483 K::CommentLabel,513 K::CommentLabel,
484 K::SaveComment,514 K::SaveComment,
crates/forge-web/src/pages/issue_parts.rsmodified+6 -0
@@ -20,6 +20,7 @@ use crate::i18n::issues::{self as g, K};
20 use crate::notify::{self, Activity};20 use crate::notify::{self, Activity};
21 use crate::pages::edit_history::{edit_counts, history_href, thread_edit_counts};21 use crate::pages::edit_history::{edit_counts, history_href, thread_edit_counts};
22 use crate::pages::notifications::{NotifyBox, notify_box};22 use crate::pages::notifications::{NotifyBox, notify_box};
23+use crate::pages::pull_reviews::suggest_states;
23 use crate::pages::repo_ctx::RepoCtx;24 use crate::pages::repo_ctx::RepoCtx;
24 use crate::pages::tree::link_context;25 use crate::pages::tree::link_context;
25 use crate::render::markdown::{LinkContext, render_markdown};26 use crate::render::markdown::{LinkContext, render_markdown};
@@ -899,6 +900,10 @@ async fn review_entries(
899 )900 )
900 .is_ok();901 .is_ok();
901 let edits = thread_edit_counts(state, &threads).await?;902 let edits = thread_edit_counts(state, &threads).await?;
903+ let suggest = match store.pull_by_number(&ctx.repo.id, item.number).await? {
904+ Some(pr) => suggest_states(state, ctx, &pr, viewer(ctx), &threads).await?,
905+ None => Default::default(),
906+ };
902 let thread_ctx = ThreadCtx {907 let thread_ctx = ThreadCtx {
903 pr_href: repo_href(908 pr_href: repo_href(
904 &ctx.repo.owner_name,909 &ctx.repo.owner_name,
@@ -915,6 +920,7 @@ async fn review_entries(
915 tz: tz.to_owned(),920 tz: tz.to_owned(),
916 link: Some(link.clone()),921 link: Some(link.clone()),
917 edits,922 edits,
923+ suggest: std::sync::Arc::new(suggest),
918 };924 };
919 925
920 let mut keyed = Vec::new();926 let mut keyed = Vec::new();
crates/forge-web/src/pages/pull_files.rsmodified+14 -7
@@ -5,6 +5,7 @@
5 //! are in `pull_reviews`.5 //! are in `pull_reviews`.
6 6
7 use std::collections::HashMap;7 use std::collections::HashMap;
8+use std::sync::Arc;
8 9
9 use forge_core::{Action, IssueState, Side, Thread, authorize};10 use forge_core::{Action, IssueState, Side, Thread, authorize};
10 use forge_git::command::ObjectSource;11 use forge_git::command::ObjectSource;
@@ -21,7 +22,7 @@ use crate::i18n::pulls::{self as g, K};
21 use crate::i18n::{self, Lang};22 use crate::i18n::{self, Lang};
22 use crate::pages::edit_history::thread_edit_counts;23 use crate::pages::edit_history::thread_edit_counts;
23 use crate::pages::issue_parts::{csrf_of, may_converse, parse_number, triage, viewer};24 use crate::pages::issue_parts::{csrf_of, may_converse, parse_number, triage, viewer};
24-use crate::pages::pull_reviews::{error_text_in, pull_diff};25+use crate::pages::pull_reviews::{error_text_in, pull_diff, suggest_states};
25 use crate::pages::pull_view::{commits_of, frame_in, is_merged, pull_header, pull_subnav_in};26 use crate::pages::pull_view::{commits_of, frame_in, is_merged, pull_header, pull_subnav_in};
26 use crate::pages::repo::repo_head;27 use crate::pages::repo::repo_head;
27 use crate::pages::repo_ctx::load_repo;28 use crate::pages::repo_ctx::load_repo;
@@ -175,6 +176,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
175 .await?;176 .await?;
176 let pending = threads.iter().filter(|t| t.root.pending).count();177 let pending = threads.iter().filter(|t| t.root.pending).count();
177 let edits = thread_edit_counts(state, &threads).await?;178 let edits = thread_edit_counts(state, &threads).await?;
179+ let suggest = suggest_states(state, &ctx, &pr, viewer(&ctx), &threads).await?;
178 let mut by_line: HashMap<(usize, Side, u32), Vec<Thread>> = HashMap::new();180 let mut by_line: HashMap<(usize, Side, u32), Vec<Thread>> = HashMap::new();
179 for thread in threads.into_iter().filter(|t| !t.root.outdated) {181 for thread in threads.into_iter().filter(|t| !t.root.outdated) {
180 if let Some(index) = file_index(&diff, &thread.root.path) {182 if let Some(index) = file_index(&diff, &thread.root.path) {
@@ -197,6 +199,7 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
197 tz: ctx.viewer_tz().to_owned(),199 tz: ctx.viewer_tz().to_owned(),
198 link: Some(link),200 link: Some(link),
199 edits,201 edits,
202+ suggest: Arc::new(suggest),
200 };203 };
201 let comments = LineComments {204 let comments = LineComments {
202 anchors: can_comment && !opts.ignore_ws,205 anchors: can_comment && !opts.ignore_ws,
@@ -208,6 +211,8 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
208 };211 };
209 212
210 let error = review_error_from(lang, cx);213 let error = review_error_from(lang, cx);
214+ // The page follows the pull request's event stream: a change re-renders it.
215+ let live = format!("{href}/events");
211 let owner = ctx.repo.owner_name.clone();216 let owner = ctx.repo.owner_name.clone();
212 let name = ctx.repo.name.clone();217 let name = ctx.repo.name.clone();
213 let parent = pr.merge_base.clone();218 let parent = pr.merge_base.clone();
@@ -222,12 +227,14 @@ async fn pull_files(cx: &Cx) -> Result<impl View> {
222 if let Some(message) = error {227 if let Some(message) = error {
223 alert(message: message.as_str())228 alert(message: message.as_str())
224 }229 }
225- if can_review {230+ <div data-live=(live.as_str())>
226- review_bar(lang: lang, pr_href: href.clone(), csrf: csrf.clone(), pending: pending, is_author: is_author)231+ if can_review {
227- }232+ review_bar(lang: lang, pr_href: href.clone(), csrf: csrf.clone(), pending: pending, is_author: is_author)
228- diff_section(diff: &diff, owner: owner.as_str(), repo: name.as_str(),233+ }
229- oid: pr.head_oid.as_str(), parent: parent.as_deref(),234+ diff_section(diff: &diff, owner: owner.as_str(), repo: name.as_str(),
230- subject: g::t(lang, K::ThisPullRequest), lang: DiffLang(lang), comments: comments, opts: opts)235+ oid: pr.head_oid.as_str(), parent: parent.as_deref(),
236+ subject: g::t(lang, K::ThisPullRequest), lang: DiffLang(lang), comments: comments, opts: opts)
237+ </div>
231 )238 )
232 })239 })
233 }240 }
crates/forge-web/src/pages/pull_reviews.rsmodified+368 -14
@@ -9,10 +9,15 @@
9 //! dismisses. Archived repos refuse every write. Closed or merged pull requests accept comments9 //! dismisses. Archived repos refuse every write. Closed or merged pull requests accept comments
10 //! and replies but no new reviews.10 //! and replies but no new reviews.
11 11
12+use std::collections::HashMap;
13+
14+use forge_core::protection::effective;
12 use forge_core::reviews::{ReviewComment, ReviewState, Side};15 use forge_core::reviews::{ReviewComment, ReviewState, Side};
13-use forge_core::{Action, IssueState, PullRequest, User, authorize};16+use forge_core::suggestions::{Part, hunk_line, replace_line, split_body};
17+use forge_core::{Action, IssueState, PullRequest, Thread, User, authorize};
18+use forge_git::browse::read_text_blob;
14 use forge_git::history::{CommitDiff, DiffStatus, FileDiff, LineKind};19 use forge_git::history::{CommitDiff, DiffStatus, FileDiff, LineKind};
15-use forge_git::pulls::range_diff_files;20+use forge_git::pulls::{FileEdit, Signature, commit_file_edit, range_diff_files};
16 use serde::Deserialize;21 use serde::Deserialize;
17 use topcoat::Result;22 use topcoat::Result;
18 use topcoat::context::{Cx, app_context};23 use topcoat::context::{Cx, app_context};
@@ -25,15 +30,22 @@ use topcoat::view::{View, view};
25 use crate::auth::require_user;30 use crate::auth::require_user;
26 use crate::i18n::pulls_review::{self as g, K};31 use crate::i18n::pulls_review::{self as g, K};
27 use crate::i18n::{self, Lang};32 use crate::i18n::{self, Lang};
33+use crate::internal::{may_push_directly, trigger_maintenance};
28 use crate::notify::{self, Activity};34 use crate::notify::{self, Activity};
29 use crate::pages::issue_parts::{check_write, csrf_of, may_change, may_converse, parse_number};35 use crate::pages::issue_parts::{check_write, csrf_of, may_change, may_converse, parse_number};
36+use crate::pages::pulls_merge::contact_email;
30 use crate::pages::repo::repo_head;37 use crate::pages::repo::repo_head;
31 use crate::pages::repo_ctx::{RepoCtx, load_repo};38 use crate::pages::repo_ctx::{RepoCtx, load_repo};
39+use crate::post_update::after_ref_update;
32 use crate::state::AppState;40 use crate::state::AppState;
33 use crate::views::diff::LIMITS;41 use crate::views::diff::LIMITS;
34-use crate::views::{alert, repo_href, shell};42+use crate::views::review_thread::SuggestState;
43+use crate::views::{alert, now_unix, repo_href, shell};
35 use crate::webhooks::emit::{Sender, emit_review};44 use crate::webhooks::emit::{Sender, emit_review};
36 45
46+/// The largest file a suggestion is applied to, in bytes.
47+const MAX_SUGGESTED_FILE: usize = 4 << 20;
48+
37 path_param!(owner);49 path_param!(owner);
38 path_param!(repo);50 path_param!(repo);
39 path_param!(number);51 path_param!(number);
@@ -47,6 +59,10 @@ pub(crate) const ERR_EMPTY: &str = "empty";
47 pub(crate) const ERR_INVALID: &str = "invalid";59 pub(crate) const ERR_INVALID: &str = "invalid";
48 pub(crate) const ERR_BAD_LINE: &str = "bad_line";60 pub(crate) const ERR_BAD_LINE: &str = "bad_line";
49 pub(crate) const ERR_CLOSED: &str = "closed";61 pub(crate) const ERR_CLOSED: &str = "closed";
62+/// A suggestion no longer applies to the head, so it is not applied.
63+pub(crate) const ERR_OUTDATED: &str = "outdated";
64+/// The viewer may not push to the pull request's head branch, so cannot apply a suggestion.
65+pub(crate) const ERR_NO_PUSH: &str = "no_push";
50 66
51 /// The message for a `review_error` code in `lang`, or `None` for an unknown code.67 /// The message for a `review_error` code in `lang`, or `None` for an unknown code.
52 pub(crate) fn error_text_in(lang: Lang, code: &str) -> Option<&'static str> {68 pub(crate) fn error_text_in(lang: Lang, code: &str) -> Option<&'static str> {
@@ -57,6 +73,8 @@ pub(crate) fn error_text_in(lang: Lang, code: &str) -> Option<&'static str> {
57 ERR_INVALID => Some(g::t(lang, K::ReviewErrInvalid)),73 ERR_INVALID => Some(g::t(lang, K::ReviewErrInvalid)),
58 ERR_BAD_LINE => Some(g::t(lang, K::ReviewErrBadLine)),74 ERR_BAD_LINE => Some(g::t(lang, K::ReviewErrBadLine)),
59 ERR_CLOSED => Some(g::t(lang, K::ReviewErrClosed)),75 ERR_CLOSED => Some(g::t(lang, K::ReviewErrClosed)),
76+ ERR_OUTDATED => Some(g::t(lang, K::ReviewErrOutdated)),
77+ ERR_NO_PUSH => Some(g::t(lang, K::ReviewErrNoPush)),
60 _ => None,78 _ => None,
61 }79 }
62 }80 }
@@ -88,6 +106,8 @@ struct ReviewForm {
88 reason: String,106 reason: String,
89 /// `1` to resolve a thread, `0` to unresolve it.107 /// `1` to resolve a thread, `0` to unresolve it.
90 resolved: String,108 resolved: String,
109+ /// The index of the suggestion block to apply, among the comment's suggestion blocks.
110+ block: String,
91 /// The tab the form was posted from: `files` or anything else for the conversation.111 /// The tab the form was posted from: `files` or anything else for the conversation.
92 #[serde(rename = "return")]112 #[serde(rename = "return")]
93 ret: String,113 ret: String,
@@ -222,6 +242,99 @@ fn refusal(tab: &str, code: &str, anchor: &str) -> SeeOther {
222 see_other(format!("{tab}?review_error={code}{anchor}"))242 see_other(format!("{tab}?review_error={code}{anchor}"))
223 }243 }
224 244
245+// Suggested changes
246+
247+/// Whether the viewer may apply a suggestion to the head of `pr`: signed in with Write, the head
248+/// branch lives in this repo, the repo is not archived, and a restricted branch rule does not
249+/// bar them from pushing.
250+async fn may_apply(
251+ state: &AppState,
252+ ctx: &RepoCtx,
253+ pr: &PullRequest,
254+ viewer: Option<&User>,
255+) -> Result<bool> {
256+ let Some(user) = viewer else {
257+ return Ok(false);
258+ };
259+ if pr.head_repo_id.as_ref() != Some(&ctx.repo.id) || ctx.repo.archived {
260+ return Ok(false);
261+ }
262+ if authorize(Some(user), &ctx.repo, ctx.role, ctx.org_role, Action::Write).is_err() {
263+ return Ok(false);
264+ }
265+ let rules = state.store.list_branch_rules(&ctx.repo.id).await?;
266+ let rule = effective(&rules, &ctx.repo.default_branch, &pr.head_branch);
267+ if rule.restrict_push {
268+ return Ok(may_push_directly(&state.store, &ctx.repo, &user.id).await?);
269+ }
270+ Ok(true)
271+}
272+
273+/// The lines of suggestion block `index` (counted from 0) of `body`, if it has one.
274+fn suggestion_at(body: &str, index: usize) -> Option<Vec<String>> {
275+ split_body(body)
276+ .into_iter()
277+ .filter_map(|part| match part {
278+ Part::Suggestion(lines) => Some(lines),
279+ Part::Text(_) => None,
280+ })
281+ .nth(index)
282+}
283+
284+/// Whether the first suggestion of `root` still applies to `current`, the head's text of its file.
285+fn suggestion_applies(current: &str, root: &ReviewComment) -> bool {
286+ let (Some(expected), Some(lines)) = (hunk_line(&root.diff_hunk), suggestion_at(&root.body, 0))
287+ else {
288+ return false;
289+ };
290+ replace_line(current, root.line, expected, &lines).is_ok()
291+}
292+
293+/// The suggestion state of each thread of the pull request whose root proposes a change, keyed by
294+/// root id. A suggestion is `Ready` when it applies to the head and the viewer may apply it, and
295+/// `Outdated` when it no longer applies. A closed pull request shows none.
296+pub(crate) async fn suggest_states(
297+ state: &AppState,
298+ ctx: &RepoCtx,
299+ pr: &PullRequest,
300+ viewer: Option<&User>,
301+ threads: &[Thread],
302+) -> Result<HashMap<String, SuggestState>> {
303+ let mut states = HashMap::new();
304+ if is_closed(pr) {
305+ return Ok(states);
306+ }
307+ let pushable = may_apply(state, ctx, pr, viewer).await?;
308+ for thread in threads {
309+ let root = &thread.root;
310+ if root.pending || root.side != Side::New || suggestion_at(&root.body, 0).is_none() {
311+ continue;
312+ }
313+ let current = read_text_blob(&ctx.path, &pr.head_oid, &root.path, MAX_SUGGESTED_FILE)
314+ .ok()
315+ .flatten();
316+ let applies = !root.outdated
317+ && current
318+ .as_deref()
319+ .is_some_and(|text| suggestion_applies(text, root));
320+ if !applies {
321+ states.insert(root.id.clone(), SuggestState::Outdated);
322+ } else if pushable {
323+ states.insert(root.id.clone(), SuggestState::Ready);
324+ }
325+ }
326+ Ok(states)
327+}
328+
329+/// The signature of `user` as an author or committer of a suggestion commit.
330+fn signature_of(state: &AppState, user: &User) -> Signature {
331+ Signature {
332+ name: user.username.clone(),
333+ email: contact_email(&state.config.base_url, user),
334+ time_unix: now_unix(),
335+ }
336+}
337+
225 // Line comments338 // Line comments
226 339
227 /// Adds a line comment (single, or into the author's pending review) on the Files tab. The340 /// Adds a line comment (single, or into the author's pending review) on the Files tab. The
@@ -284,10 +397,12 @@ async fn review_comment_post(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<Se
284 )397 )
285 .await398 .await
286 {399 {
287- Ok(_) => Ok(see_other(format!(400+ Ok(_) => {
288- "{files}#L-{file_index}-{}-{line}",401+ Ok(see_other(format!(
289- side.as_str()402+ "{files}#L-{file_index}-{}-{line}",
290- ))),403+ side.as_str()
404+ )))
405+ }
291 Err(forge_core::Error::Invalid(_)) => {406 Err(forge_core::Error::Invalid(_)) => {
292 Ok(see_other(format!("{back}&review_error={ERR_INVALID}")))407 Ok(see_other(format!("{back}&review_error={ERR_INVALID}")))
293 }408 }
@@ -319,7 +434,9 @@ async fn review_comment_reply(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<S
319 .reply_review_comment(&pr.issue.id, &user.id, &root, &form.body)434 .reply_review_comment(&pr.issue.id, &user.id, &root, &form.body)
320 .await435 .await
321 {436 {
322- Ok(_) => Ok(see_other(format!("{tab}{anchor}"))),437+ Ok(_) => {
438+ Ok(see_other(format!("{tab}{anchor}")))
439+ }
323 Err(forge_core::Error::Invalid(_)) => Ok(refusal(&tab, ERR_INVALID, &anchor)),440 Err(forge_core::Error::Invalid(_)) => Ok(refusal(&tab, ERR_INVALID, &anchor)),
324 Err(e) => Err(e.into()),441 Err(e) => Err(e.into()),
325 }442 }
@@ -418,11 +535,13 @@ async fn review_comment_edit_save(cx: &Cx, Form(form): Form<ReviewForm>) -> Resu
418 .edit_review_comment(&comment.id, &form.body)535 .edit_review_comment(&comment.id, &form.body)
419 .await536 .await
420 {537 {
421- Ok(()) => Ok(see_other(format!(538+ Ok(()) => {
422- "{}#rc-{}",539+ Ok(see_other(format!(
423- tab_url(&ctx, number, &form.ret),540+ "{}#rc-{}",
424- root_of(&comment)541+ tab_url(&ctx, number, &form.ret),
425- ))),542+ root_of(&comment)
543+ )))
544+ }
426 Err(forge_core::Error::Invalid(_)) => Ok(refusal(&edit_url, ERR_INVALID, "")),545 Err(forge_core::Error::Invalid(_)) => Ok(refusal(&edit_url, ERR_INVALID, "")),
427 Err(e) => Err(e.into()),546 Err(e) => Err(e.into()),
428 }547 }
@@ -488,6 +607,97 @@ async fn review_comment_resolve(cx: &Cx, Form(form): Form<ReviewForm>) -> Result
488 Ok(see_other(format!("{tab}{anchor}")))607 Ok(see_other(format!("{tab}{anchor}")))
489 }608 }
490 609
610+/// Applies suggestion block `block` of a root comment to the pull request's head. The commit is
611+/// made by the viewer, with the commenter as co-author, and replaces the commented line. The
612+/// thread is then resolved and the push flow runs, as for any ref update. Refused when the pull
613+/// request is closed, the viewer may not push to the head, or the line no longer reads what the
614+/// suggestion was written against.
615+#[route(POST "/{owner}/{repo}/pulls/{number}/review_comments/{comment_id}/apply")]
616+async fn review_comment_apply(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<SeeOther> {
617+ let number = parse_number(path_param::<Number>(cx))?;
618+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
619+ let (user, session) = require_user(cx).await?;
620+ check_write(&ctx, &session, &form.csrf)?;
621+ let state = app_context::<AppState>(cx);
622+ let pr = pull_for(state, &ctx, number).await?;
623+ let comment = comment_on_pull(state, &pr, &user, path_param::<CommentId>(cx)).await?;
624+ let files = tab_url(&ctx, number, &form.ret);
625+ let anchor = format!("#rc-{}", comment.id);
626+ if comment.reply_to.is_some() || comment.pending || comment.side != Side::New {
627+ return Ok(refusal(&files, ERR_INVALID, &anchor));
628+ }
629+ if is_closed(&pr) {
630+ return Ok(refusal(&files, ERR_CLOSED, &anchor));
631+ }
632+ if !may_apply(state, &ctx, &pr, Some(&user)).await? {
633+ return Ok(refusal(&files, ERR_NO_PUSH, &anchor));
634+ }
635+ let block = form.block.parse::<usize>().unwrap_or(0);
636+ let Some(lines) = suggestion_at(&comment.body, block) else {
637+ return Ok(refusal(&files, ERR_INVALID, &anchor));
638+ };
639+ let Some(expected) = hunk_line(&comment.diff_hunk) else {
640+ return Ok(refusal(&files, ERR_INVALID, &anchor));
641+ };
642+ let head = pr.head_oid.clone();
643+ let current = if comment.outdated {
644+ None
645+ } else {
646+ read_text_blob(&ctx.path, &head, &comment.path, MAX_SUGGESTED_FILE)
647+ .ok()
648+ .flatten()
649+ };
650+ let Some(edited) =
651+ current.and_then(|text| replace_line(&text, comment.line, expected, &lines).ok())
652+ else {
653+ return Ok(refusal(&files, ERR_OUTDATED, &anchor));
654+ };
655+
656+ let author = signature_of(state, &user);
657+ let (trailer_name, trailer_email) = match state.store.user_by_id(&comment.author_id).await? {
658+ Some(commenter) => {
659+ let email = contact_email(&state.config.base_url, &commenter);
660+ (commenter.username, email)
661+ }
662+ None => (comment.author_name.clone(), author.email.clone()),
663+ };
664+ let message =
665+ format!("Apply suggestion from review\n\nCo-authored-by: {trailer_name} <{trailer_email}>");
666+ let refname = format!("refs/heads/{}", pr.head_branch);
667+ let file = FileEdit {
668+ path: &comment.path,
669+ content: edited.as_bytes(),
670+ };
671+ let commit = match commit_file_edit(
672+ &state.git, &ctx.path, &refname, &head, &file, &message, &author, &author,
673+ )
674+ .await
675+ {
676+ Ok(commit) => commit,
677+ Err(forge_git::error::Error::RefMoved(_)) => {
678+ return Ok(refusal(&files, ERR_STALE, &anchor));
679+ }
680+ Err(forge_git::error::Error::InvalidInput(_)) => {
681+ return Ok(refusal(&files, ERR_OUTDATED, &anchor));
682+ }
683+ Err(e) => return Err(e.into()),
684+ };
685+
686+ // The commit has landed, so the steps after it log their failures and do not refuse.
687+ if let Err(e) = state
688+ .store
689+ .set_thread_resolved(&comment.id, &user.id, true)
690+ .await
691+ {
692+ tracing::error!(error = %e, repo_id = %ctx.repo.id, "suggestion: resolving the thread failed");
693+ }
694+ trigger_maintenance(&state.git, &ctx.repo.id);
695+ if let Err(e) = after_ref_update(state, &ctx.repo, &user.id, &refname, &head, &commit).await {
696+ tracing::error!(error = %e, repo_id = %ctx.repo.id, ref_name = %refname, "suggestion: post-update failed");
697+ }
698+ Ok(see_other(format!("{files}{anchor}")))
699+}
700+
491 // Reviews701 // Reviews
492 702
493 /// Submits the author's pending review as a comment, approval or change request. The PR author703 /// Submits the author's pending review as a comment, approval or change request. The PR author
@@ -619,7 +829,9 @@ async fn review_dismiss(cx: &Cx, Form(form): Form<ReviewForm>) -> Result<SeeOthe
619 .dismiss_review(&review.id, &user.id, &form.reason)829 .dismiss_review(&review.id, &user.id, &form.reason)
620 .await830 .await
621 {831 {
622- Ok(()) => Ok(see_other(format!("{tab}#review-{}", review.id))),832+ Ok(()) => {
833+ Ok(see_other(format!("{tab}#review-{}", review.id)))
834+ }
623 Err(forge_core::Error::Invalid(_)) => Ok(refusal(&tab, ERR_INVALID, "")),835 Err(forge_core::Error::Invalid(_)) => Ok(refusal(&tab, ERR_INVALID, "")),
624 Err(e) => Err(e.into()),836 Err(e) => Err(e.into()),
625 }837 }
@@ -1180,4 +1392,146 @@ mod tests {
1180 let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;1392 let (status, _, _) = send(&fx.router, "POST", &uri, Some("tahinli"), Some(form)).await;
1181 assert_eq!(status, 403);1393 assert_eq!(status, 403);
1182 }1394 }
1395+
1396+ /// The comment body that proposes replacing line 2 of `a.txt` with `text`.
1397+ fn suggestion(text: &str) -> String {
1398+ format!("Try this:\n```suggestion\n{text}\n```")
1399+ }
1400+
1401+ /// Posts the apply form for suggestion block 0 of comment `comment_id`.
1402+ async fn apply_as(
1403+ fx: &Fixture,
1404+ number: i64,
1405+ token: &str,
1406+ comment_id: &str,
1407+ ) -> (u16, Option<String>) {
1408+ let form = csrf_form(token, &[("block", "0"), ("return", "files")]);
1409+ let uri = format!("/tahinli/demo/pulls/{number}/review_comments/{comment_id}/apply");
1410+ let (status, location, _) = send(&fx.router, "POST", &uri, Some(token), Some(form)).await;
1411+ (status, location)
1412+ }
1413+
1414+ #[tokio::test]
1415+ async fn applying_a_suggestion_commits_it_to_the_head_and_resolves_the_thread() {
1416+ let fx = Fixture::new(Visibility::Public).await;
1417+ owner_session(&fx).await;
1418+ let number = open_pull(&fx).await;
1419+ let before = pull(&fx, number).await.head_oid;
1420+
1421+ let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
1422+ assert_eq!(status, 303);
1423+ let root = root_id(&fx, number).await;
1424+ let (status, location) = apply_as(&fx, number, "tahinli", &root).await;
1425+ assert_eq!(status, 303);
1426+ assert!(!location.unwrap().contains("review_error"));
1427+
1428+ let pr = pull(&fx, number).await;
1429+ assert_ne!(
1430+ pr.head_oid, before,
1431+ "the head moved to the suggestion commit"
1432+ );
1433+ assert_eq!(
1434+ git(&fx.bare, &["show", &format!("{}:a.txt", pr.head_oid)]),
1435+ "one\ntwo!\nthree"
1436+ );
1437+ assert_eq!(
1438+ git(&fx.bare, &["log", "-1", "--format=%an", &pr.head_oid]),
1439+ "tahinli"
1440+ );
1441+ let message = git(&fx.bare, &["log", "-1", "--format=%B", &pr.head_oid]);
1442+ assert!(
1443+ message.starts_with("Apply suggestion from review"),
1444+ "{message}"
1445+ );
1446+ assert!(
1447+ message.contains("Co-authored-by: tahinli <"),
1448+ "commenter trailer: {message}"
1449+ );
1450+ assert_eq!(git(&fx.bare, &["rev-parse", "feature"]), pr.head_oid);
1451+ let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
1452+ assert!(threads[0].root.resolved, "applying resolves the thread");
1453+ }
1454+
1455+ #[tokio::test]
1456+ async fn outdated_suggestion_is_shown_without_apply_and_refused() {
1457+ let fx = Fixture::new(Visibility::Public).await;
1458+ owner_session(&fx).await;
1459+ let number = open_pull(&fx).await;
1460+ let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
1461+ assert_eq!(status, 303);
1462+ let root = root_id(&fx, number).await;
1463+
1464+ // The head moves on: its line 2 no longer reads what the suggestion was written against.
1465+ let pr = pull(&fx, number).await;
1466+ git(&fx.work, &["checkout", "-q", "feature"]);
1467+ std::fs::write(fx.work.join("a.txt"), "one\nmoved\nthree\n").unwrap();
1468+ git(&fx.work, &["commit", "-q", "-am", "Move line 2"]);
1469+ let moved = git(&fx.work, &["rev-parse", "HEAD"]);
1470+ git(
1471+ &fx.work,
1472+ &[
1473+ "push",
1474+ "-q",
1475+ &fx.bare.to_string_lossy(),
1476+ "HEAD:refs/heads/feature",
1477+ ],
1478+ );
1479+ fx.store
1480+ .update_pull_head(&pr.issue.id, &moved)
1481+ .await
1482+ .unwrap();
1483+
1484+ let page = get(&fx, number, "tahinli").await;
1485+ assert!(
1486+ page.contains("This suggestion is outdated"),
1487+ "outdated note shown"
1488+ );
1489+ assert!(
1490+ !page.contains("Apply suggestion"),
1491+ "no apply button when outdated"
1492+ );
1493+
1494+ let (status, location) = apply_as(&fx, number, "tahinli", &root).await;
1495+ assert_eq!(status, 303);
1496+ assert!(location.unwrap().contains("review_error=outdated"));
1497+ assert_eq!(
1498+ git(&fx.bare, &["rev-parse", "feature"]),
1499+ moved,
1500+ "nothing was committed"
1501+ );
1502+ let threads = fx.store.review_threads(&pr.issue.id, None).await.unwrap();
1503+ assert!(
1504+ !threads[0].root.resolved,
1505+ "a refused apply leaves the thread open"
1506+ );
1507+ }
1508+
1509+ #[tokio::test]
1510+ async fn a_reader_without_push_access_cannot_apply_and_sees_no_button() {
1511+ let fx = Fixture::new(Visibility::Public).await;
1512+ owner_session(&fx).await;
1513+ let number = open_pull(&fx).await;
1514+ let (status, _) = comment_on(&fx, number, "tahinli", "2", &suggestion("two!")).await;
1515+ assert_eq!(status, 303);
1516+ let root = root_id(&fx, number).await;
1517+ sign_in(&fx, "rita", "rita").await;
1518+
1519+ let page = get(&fx, number, "rita").await;
1520+ assert!(page.contains("Suggested change"), "the diff still shows");
1521+ assert!(
1522+ !page.contains("Apply suggestion"),
1523+ "no apply button without push access"
1524+ );
1525+
1526+ let (status, location) = apply_as(&fx, number, "rita", &root).await;
1527+ assert_eq!(status, 303);
1528+ assert!(location.unwrap().contains("review_error=no_push"));
1529+ }
1530+
1531+ /// The Files tab of the pull request as `token` sees it.
1532+ async fn get(fx: &Fixture, number: i64, token: &str) -> String {
1533+ let uri = format!("/tahinli/demo/pulls/{number}/files");
1534+ let (_, _, body) = send(&fx.router, "GET", &uri, Some(token), None).await;
1535+ body
1536+ }
1183 }1537 }
crates/forge-web/src/pages/pull_view.rsmodified+3 -1
@@ -789,6 +789,8 @@ async fn pull_conversation(
789 let page_title = frame.page_title.clone();789 let page_title = frame.page_title.clone();
790 let header = ctx.head(state, "pulls").await?;790 let header = ctx.head(state, "pulls").await?;
791 let labels_href = repo_href(&owner, &name, "labels.css", "");791 let labels_href = repo_href(&owner, &name, "labels.css", "");
792+ // The conversation follows the pull request's event stream: a change re-renders it.
793+ let live = format!("{href}/events");
792 Ok(view! { cx =>794 Ok(view! { cx =>
793 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()),795 shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()),
794 repo_head(head: header)796 repo_head(head: header)
@@ -798,7 +800,7 @@ async fn pull_conversation(
798 if let Some(message) = review_error {800 if let Some(message) = review_error {
799 alert(message: message)801 alert(message: message)
800 }802 }
801- <div class="issue-layout">803+ <div class="issue-layout" data-live=(live.as_str())>
802 <div class="issue-column">804 <div class="issue-column">
803 discussion_timeline(lang: lang, discussion: discussion)805 discussion_timeline(lang: lang, discussion: discussion)
804 if review_box_shown {806 if review_box_shown {
crates/forge-web/src/pages/pulls_merge.rsmodified+1 -1
@@ -498,7 +498,7 @@ pub async fn perform_merge(
498 498
499 /// The address written into a commit for `user`: their email, or a noreply address on this499 /// The address written into a commit for `user`: their email, or a noreply address on this
500 /// instance's host when they have none.500 /// instance's host when they have none.
501-fn contact_email(base_url: &str, user: &User) -> String {501+pub(crate) fn contact_email(base_url: &str, user: &User) -> String {
502 match user502 match user
503 .email503 .email
504 .as_deref()504 .as_deref()
crates/forge-web/src/pulls_sync.rsmodified+3 -0
@@ -57,12 +57,15 @@ pub async fn sync_pulls_for_ref(
57 {57 {
58 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: head update failed");58 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: head update failed");
59 }59 }
60+ // Open pull request pages show the new head, commits and mergeability.
61+ crate::pages::pull_live::bump_pull(state, &repo.id, &issue_id);
60 }62 }
61 let bases = state.store.open_pulls_for_base(&repo.id, branch).await?;63 let bases = state.store.open_pulls_for_base(&repo.id, branch).await?;
62 for (number, issue_id) in bases {64 for (number, issue_id) in bases {
63 if let Err(e) = sync_base(state, repo, actor_id, number, &issue_id, old, new).await {65 if let Err(e) = sync_base(state, repo, actor_id, number, &issue_id, old, new).await {
64 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: base update failed");66 tracing::error!(error = %e, repo_id = %repo.id, number, "pull sync: base update failed");
65 }67 }
68+ crate::pages::pull_live::bump_pull(state, &repo.id, &issue_id);
66 }69 }
67 Ok(())70 Ok(())
68 }71 }
crates/forge-web/src/views/diff.rsmodified+9 -0
@@ -21,6 +21,7 @@ use topcoat::view::{View, component, view};
21 use crate::i18n::Lang;21 use crate::i18n::Lang;
22 use crate::i18n::browse as b;22 use crate::i18n::browse as b;
23 use crate::i18n::code::{self as g, K};23 use crate::i18n::code::{self as g, K};
24+use crate::i18n::pulls_review::{self as pr_g, K as PrK};
24 use crate::pages::commits::url_path;25 use crate::pages::commits::url_path;
25 use crate::views::review_thread::{ThreadCtx, review_thread_in};26 use crate::views::review_thread::{ThreadCtx, review_thread_in};
26 27
@@ -163,6 +164,8 @@ struct InlineForm {
163 head_oid: String,164 head_oid: String,
164 has_pending: bool,165 has_pending: bool,
165 can_review: bool,166 can_review: bool,
167+ /// The text of the commented line, when a suggestion can replace it (a line on the new side).
168+ suggest_line: Option<String>,
166 }169 }
167 170
168 /// What renders under a line: its threads and, if open, the form.171 /// What renders under a line: its threads and, if open, the form.
@@ -429,6 +432,7 @@ impl FileView {
429 head_oid: oid.to_owned(),432 head_oid: oid.to_owned(),
430 has_pending: comments.has_pending,433 has_pending: comments.has_pending,
431 can_review: comments.ctx.can_review,434 can_review: comments.ctx.can_review,
435+ suggest_line: (side == Side::New).then(|| line.text.clone()),
432 });436 });
433 let below = (!threads.is_empty() || form.is_some()).then(|| RowBelow {437 let below = (!threads.is_empty() || form.is_some()).then(|| RowBelow {
434 threads,438 threads,
@@ -770,12 +774,14 @@ async fn inline_comment_form(form: InlineForm, lang: Lang) -> Result<impl View>
770 head_oid,774 head_oid,
771 has_pending,775 has_pending,
772 can_review,776 can_review,
777+ suggest_line,
773 } = form;778 } = form;
774 let review_label = if has_pending {779 let review_label = if has_pending {
775 g::t(lang, K::AddReviewComment)780 g::t(lang, K::AddReviewComment)
776 } else {781 } else {
777 g::t(lang, K::StartReview)782 g::t(lang, K::StartReview)
778 };783 };
784+ let suggest_label = pr_g::t(lang, PrK::SuggestChange);
779 Ok(view! {785 Ok(view! {
780 <form method="post" action=(action.as_str()) class="review-inline-form stack">786 <form method="post" action=(action.as_str()) class="review-inline-form stack">
781 <input type="hidden" name="csrf" value=(csrf.as_str())>787 <input type="hidden" name="csrf" value=(csrf.as_str())>
@@ -792,6 +798,9 @@ async fn inline_comment_form(form: InlineForm, lang: Lang) -> Result<impl View>
792 if can_review {798 if can_review {
793 <button type="submit" name="action" value="review">(review_label)</button>799 <button type="submit" name="action" value="review">(review_label)</button>
794 }800 }
801+ if let Some(text) = suggest_line {
802+ <button type="button" class="link-button" data-suggest=(text.as_str())>(suggest_label)</button>
803+ }
795 <a href=(cancel_href.as_str())>(g::t(lang, K::CancelLink))</a>804 <a href=(cancel_href.as_str())>(g::t(lang, K::CancelLink))</a>
796 </div>805 </div>
797 </form>806 </form>
crates/forge-web/src/views/review_thread.rsmodified+142 -6
@@ -6,6 +6,7 @@
6 use std::collections::HashMap;6 use std::collections::HashMap;
7 use std::sync::Arc;7 use std::sync::Arc;
8 8
9+use forge_core::suggestions::{Part, hunk_line, split_body};
9 use forge_core::{ReviewComment, Thread};10 use forge_core::{ReviewComment, Thread};
10 use topcoat::Result;11 use topcoat::Result;
11 use topcoat::view::{Unescaped, View, component, view};12 use topcoat::view::{Unescaped, View, component, view};
@@ -16,6 +17,15 @@ use crate::pages::issue_parts::When;
16 use crate::render::markdown::{LinkContext, render_markdown};17 use crate::render::markdown::{LinkContext, render_markdown};
17 use crate::views::{avatar_url, display_name, now_unix, user_href, user_link};18 use crate::views::{avatar_url, display_name, now_unix, user_href, user_link};
18 19
20+/// What the Apply control of a suggestion shows. A root without a state shows the diff only.
21+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22+pub enum SuggestState {
23+ /// It applies to the head and the viewer may apply it.
24+ Ready,
25+ /// It no longer applies to the head, so it cannot be applied.
26+ Outdated,
27+}
28+
19 /// What a thread needs from its page: where the review POSTs go, the CSRF token, who is viewing29 /// What a thread needs from its page: where the review POSTs go, the CSRF token, who is viewing
20 /// and what they may do. Built once per page and cloned into each thread.30 /// and what they may do. Built once per page and cloned into each thread.
21 #[derive(Clone, Default)]31 #[derive(Clone, Default)]
@@ -39,6 +49,24 @@ pub struct ThreadCtx {
39 pub link: Option<LinkContext>,49 pub link: Option<LinkContext>,
40 /// Earlier versions per review comment id. A comment in here with a count shows "edited".50 /// Earlier versions per review comment id. A comment in here with a count shows "edited".
41 pub edits: Arc<HashMap<String, u64>>,51 pub edits: Arc<HashMap<String, u64>>,
52+ /// The suggestion state of each root comment that proposes a change, keyed by root id.
53+ pub suggest: Arc<HashMap<String, SuggestState>>,
54+}
55+
56+/// One part of a comment body: rendered markdown, or a suggested change.
57+#[derive(Clone)]
58+struct PartRow {
59+ /// The rendered markdown of a text part. Empty for a suggestion.
60+ html: String,
61+ suggestion: bool,
62+ /// The commented line as it reads now, shown as the removed line. Empty when unknown.
63+ old: String,
64+ /// The lines the suggestion puts in place of the commented line.
65+ new_lines: Vec<String>,
66+ /// The index of the suggestion among the comment's blocks, for the apply form.
67+ block: String,
68+ apply_action: Option<String>,
69+ outdated: bool,
42 }70 }
43 71
44 /// One comment of a thread, flattened for the view.72 /// One comment of a thread, flattened for the view.
@@ -48,12 +76,52 @@ struct CommentRow {
48 login: String,76 login: String,
49 avatar: String,77 avatar: String,
50 when: When,78 when: When,
51- html: String,79+ parts: Vec<PartRow>,
52 history_href: Option<String>,80 history_href: Option<String>,
53 edit_href: Option<String>,81 edit_href: Option<String>,
54 delete_href: Option<String>,82 delete_href: Option<String>,
55 }83 }
56 84
85+/// The parts of a comment body. Each suggestion block becomes a suggestion part: its removed line
86+/// comes from the stored hunk, and `state` (set only for a root) sets the apply control.
87+fn body_parts(
88+ comment: &ReviewComment,
89+ ctx: &ThreadCtx,
90+ state: Option<SuggestState>,
91+) -> Vec<PartRow> {
92+ let old = hunk_line(&comment.diff_hunk).unwrap_or_default().to_owned();
93+ let mut block = 0usize;
94+ split_body(&comment.body)
95+ .into_iter()
96+ .map(|part| match part {
97+ Part::Text(text) => PartRow {
98+ html: render_markdown(&text, ctx.link.as_ref()),
99+ suggestion: false,
100+ old: String::new(),
101+ new_lines: Vec::new(),
102+ block: String::new(),
103+ apply_action: None,
104+ outdated: false,
105+ },
106+ Part::Suggestion(lines) => {
107+ let index = block;
108+ block += 1;
109+ let apply_action = (state == Some(SuggestState::Ready))
110+ .then(|| format!("{}/review_comments/{}/apply", ctx.pr_href, comment.id));
111+ PartRow {
112+ html: String::new(),
113+ suggestion: true,
114+ old: old.clone(),
115+ new_lines: lines,
116+ block: index.to_string(),
117+ apply_action,
118+ outdated: state == Some(SuggestState::Outdated),
119+ }
120+ }
121+ })
122+ .collect()
123+}
124+
57 /// The controls and content of a thread, shared by the open and the collapsed (resolved) forms.125 /// The controls and content of a thread, shared by the open and the collapsed (resolved) forms.
58 struct ThreadParts {126 struct ThreadParts {
59 location: String,127 location: String,
@@ -70,16 +138,23 @@ struct ThreadParts {
70 lang: Lang,138 lang: Lang,
71 }139 }
72 140
73-fn comment_row(comment: ReviewComment, ctx: &ThreadCtx, now: i64, lang: Lang) -> CommentRow {141+fn comment_row(
142+ comment: ReviewComment,
143+ ctx: &ThreadCtx,
144+ now: i64,
145+ lang: Lang,
146+ state: Option<SuggestState>,
147+) -> CommentRow {
74 let mine = ctx.viewer_id.as_deref() == Some(comment.author_id.as_str());148 let mine = ctx.viewer_id.as_deref() == Some(comment.author_id.as_str());
75 let base = format!("{}/review_comments/{}", ctx.pr_href, comment.id);149 let base = format!("{}/review_comments/{}", ctx.pr_href, comment.id);
76 let edited = ctx.edits.get(&comment.id).is_some_and(|count| *count > 0);150 let edited = ctx.edits.get(&comment.id).is_some_and(|count| *count > 0);
151+ let parts = body_parts(&comment, ctx, state);
77 CommentRow {152 CommentRow {
78 avatar: avatar_url(&comment.author_name, None),153 avatar: avatar_url(&comment.author_name, None),
79 author: display_name(lang, &comment.author_name),154 author: display_name(lang, &comment.author_name),
80 login: comment.author_name.clone(),155 login: comment.author_name.clone(),
81 when: When::new(lang, &comment.created_at, &ctx.tz, now),156 when: When::new(lang, &comment.created_at, &ctx.tz, now),
82- html: render_markdown(&comment.body, ctx.link.as_ref()),157+ parts,
83 history_href: edited158 history_href: edited
84 .then(|| format!("{}/history/review_comment/{}", ctx.pr_href, comment.id)),159 .then(|| format!("{}/history/review_comment/{}", ctx.pr_href, comment.id)),
85 edit_href: (mine && ctx.can_comment).then(|| format!("{base}/edit")),160 edit_href: (mine && ctx.can_comment).then(|| format!("{base}/edit")),
@@ -116,6 +191,7 @@ pub async fn review_thread_in(
116 let now = now_unix();191 let now = now_unix();
117 let return_to = return_to.to_owned();192 let return_to = return_to.to_owned();
118 let Thread { root, replies } = thread;193 let Thread { root, replies } = thread;
194+ let suggest = ctx.suggest.get(&root.id).copied();
119 let anchor = format!("rc-{}", root.id);195 let anchor = format!("rc-{}", root.id);
120 let location = format!("{}:{}", root.path, root.line);196 let location = format!("{}:{}", root.path, root.line);
121 let hunk = (show_hunk && !root.diff_hunk.is_empty()).then(|| root.diff_hunk.clone());197 let hunk = (show_hunk && !root.diff_hunk.is_empty()).then(|| root.diff_hunk.clone());
@@ -130,9 +206,14 @@ pub async fn review_thread_in(
130 } else {206 } else {
131 ("1", g::t(lang, K::Resolve))207 ("1", g::t(lang, K::Resolve))
132 };208 };
209+ // Only the root's suggestions are applied: the commented line is the root's.
133 let comments: Vec<CommentRow> = std::iter::once(root)210 let comments: Vec<CommentRow> = std::iter::once(root)
134 .chain(replies)211 .chain(replies)
135- .map(|comment| comment_row(comment, &ctx, now, lang))212+ .enumerate()
213+ .map(|(index, comment)| {
214+ let state = if index == 0 { suggest } else { None };
215+ comment_row(comment, &ctx, now, lang, state)
216+ })
136 .collect();217 .collect();
137 218
138 let parts = ThreadParts {219 let parts = ThreadParts {
@@ -318,7 +399,7 @@ async fn thread_comment(
318 login,399 login,
319 avatar,400 avatar,
320 when,401 when,
321- html,402+ parts,
322 history_href,403 history_href,
323 edit_href,404 edit_href,
324 delete_href,405 delete_href,
@@ -349,7 +430,62 @@ async fn thread_comment(
349 }430 }
350 </span>431 </span>
351 </header>432 </header>
352- <div class="markdown-body review-comment-body">(Unescaped::new_unchecked(html))</div>433+ for part in parts.into_iter() {
434+ comment_part(part: part, csrf: csrf.clone(), return_to: return_to.clone(),
435+ lang: lang)
436+ }
353 </article>437 </article>
354 })438 })
355 }439 }
440+
441+/// One part of a comment body: its markdown, or a suggested change with its removed and added
442+/// lines, the Apply control when it applies, and a note when it is outdated.
443+#[component]
444+async fn comment_part(
445+ part: PartRow,
446+ csrf: String,
447+ return_to: String,
448+ lang: Lang,
449+) -> Result<impl View> {
450+ let PartRow {
451+ html,
452+ suggestion,
453+ old,
454+ new_lines,
455+ block,
456+ apply_action,
457+ outdated,
458+ } = part;
459+ let caption = g::t(lang, K::SuggestedChange);
460+ let apply_label = g::t(lang, K::ApplySuggestion);
461+ let outdated_text = g::t(lang, K::SuggestionOutdated);
462+ let removed_sign = "-";
463+ let added_sign = "+";
464+ Ok(view! {
465+ if !suggestion {
466+ <div class="markdown-body review-comment-body">(Unescaped::new_unchecked(html))</div>
467+ }
468+ if suggestion {
469+ <div class="review-suggestion">
470+ <div class="review-suggestion-caption">(caption)</div>
471+ if !old.is_empty() {
472+ <div class="review-suggestion-line del"><span class="review-suggestion-sign">(removed_sign)</span><code>(old.as_str())</code></div>
473+ }
474+ for line in new_lines.into_iter() {
475+ <div class="review-suggestion-line add"><span class="review-suggestion-sign">(added_sign)</span><code>(line.as_str())</code></div>
476+ }
477+ if let Some(action) = apply_action {
478+ <form method="post" action=(action.as_str()) class="review-suggestion-apply">
479+ <input type="hidden" name="csrf" value=(csrf.as_str())>
480+ <input type="hidden" name="return" value=(return_to.as_str())>
481+ <input type="hidden" name="block" value=(block.as_str())>
482+ <button type="submit">(apply_label)</button>
483+ </form>
484+ }
485+ if outdated {
486+ <p class="review-suggestion-outdated">(outdated_text)</p>
487+ }
488+ </div>
489+ }
490+ })
491+}
docs/architecture.mdmodified+2 -0
@@ -501,6 +501,8 @@ Known gaps:
501 - Mergeability checked with `git merge-tree --write-tree`, recomputed when base or head moves. Optional `refs/pull/N/merge`.501 - Mergeability checked with `git merge-tree --write-tree`, recomputed when base or head moves. Optional `refs/pull/N/merge`.
502 - Three-dot diffs from the merge base, rename detection (`-M`), binary detection, lazy-loaded large files.502 - Three-dot diffs from the merge base, rename detection (`-M`), binary detection, lazy-loaded large files.
503 - Reviews (approve, request changes, comment) and review comments anchored to commit, path, line, side, and hunk. Comments are marked outdated, not deleted.503 - Reviews (approve, request changes, comment) and review comments anchored to commit, path, line, side, and hunk. Comments are marked outdated, not deleted.
504+- Suggested changes: a comment body with a ```` ```suggestion ```` block proposes replacing the commented line. It renders as a removed and an added line. Anyone with push access to a same-repo head branch can apply it while the PR is open and the line still reads what the suggestion was written against. The apply writes one commit on the head (tree built with `hash-object`, `read-tree`, `update-index`, `write-tree`, `commit-tree`, and a compare-and-swap `update-ref`), authored by the viewer with `Co-authored-by:` the commenter, resolves the thread, and runs the normal push flow. Single line only; multi-line ranges and batched suggestions are not supported.
505+- Live updates: the Files and Conversation tabs follow `/{owner}/{repo}/pulls/{n}/events` (SSE), and re-render on any review write or head update.
504 - Merge strategies: merge commit (`commit-tree` from merge-tree output), squash, rebase, fast-forward only.506 - Merge strategies: merge commit (`commit-tree` from merge-tree output), squash, rebase, fast-forward only.
505 - `range-diff` for "what changed since the last review." AGit (`refs/for/<branch>`) is considered later.507 - `range-diff` for "what changed since the last review." AGit (`refs/for/<branch>`) is considered later.
506 - Live pages: the pull list and every pull tab (conversation, commits, files) update while open. Each has an event stream (`/{o}/{r}/pulls/events`, `/{o}/{r}/pulls/{n}/events`) that sends `changed` when a write changes what the page shows. A POST under the pulls paths, a push, a commit status for the head, and a mergeability or auto-merge run each wake it. The page re-reads in place and keeps typed text, focus and open inline forms; the Files tab keeps the file in view at the same offset. Streams are in-process, event driven, and never poll. Topics live in `live.rs`; the bump helpers are in `pages/pull_live.rs`.508 - Live pages: the pull list and every pull tab (conversation, commits, files) update while open. Each has an event stream (`/{o}/{r}/pulls/events`, `/{o}/{r}/pulls/{n}/events`) that sends `changed` when a write changes what the page shows. A POST under the pulls paths, a push, a commit status for the head, and a mergeability or auto-merge run each wake it. The page re-reads in place and keeps typed text, focus and open inline forms; the Files tab keeps the file in view at the same offset. Streams are in-process, event driven, and never poll. Topics live in `live.rs`; the bump helpers are in `pages/pull_live.rs`.
style/main.scssmodified+59 -0
@@ -3102,6 +3102,65 @@ span.reaction {
3102 margin-top: 6px;3102 margin-top: 6px;
3103 }3103 }
3104 3104
3105+// A suggested change: the commented line (removed) and the lines that replace it (added), in the
3106+// same colours as the diff's del and add rows.
3107+.review-suggestion {
3108+ margin-top: 8px;
3109+ border: 1px solid var(--border);
3110+ border-radius: var(--radius-lg);
3111+ background: var(--surface);
3112+ overflow: hidden;
3113+ font-size: 0.875rem;
3114+}
3115+
3116+.review-suggestion-caption {
3117+ padding: 6px 10px;
3118+ border-bottom: 1px solid var(--border);
3119+ color: var(--muted);
3120+}
3121+
3122+.review-suggestion-line {
3123+ display: flex;
3124+ gap: 8px;
3125+ padding: 2px 10px;
3126+ font-family: var(--mono);
3127+ font-size: 0.8125rem;
3128+ white-space: pre;
3129+ overflow-x: auto;
3130+
3131+ code {
3132+ font-family: inherit;
3133+ white-space: pre;
3134+ }
3135+
3136+ &.add {
3137+ background: var(--add-bg);
3138+ color: var(--add-text);
3139+ }
3140+
3141+ &.del {
3142+ background: var(--del-bg);
3143+ color: var(--del-text);
3144+ }
3145+}
3146+
3147+.review-suggestion-sign {
3148+ flex: 0 0 auto;
3149+ width: 1ch;
3150+}
3151+
3152+.review-suggestion-apply {
3153+ padding: 8px 10px;
3154+ border-top: 1px solid var(--border);
3155+}
3156+
3157+.review-suggestion-outdated {
3158+ margin: 0;
3159+ padding: 8px 10px;
3160+ border-top: 1px solid var(--border);
3161+ color: var(--muted);
3162+}
3163+
3105 .review-thread-actions {3164 .review-thread-actions {
3106 display: flex;3165 display: flex;
3107 gap: 12px;3166 gap: 12px;