forge
Explore
Log in

Don't you dare go Hollow

Pull requests update live

Browse files at this commit

c2161c44f687d7259f72c12cfbd4f072b8c6101dAhmet Kaan GümüşParent: fac9525
  • feat
    • pull requests update live
Show full message
⚡ feat: pull requests update live
crates/forge-core/src/store/pulls.rsmodified+28 -0
@@ -270,6 +270,34 @@ impl Store {
270 .await270 .await
271 }271 }
272 272
273+ /// Every pull request of a repo, open or closed, as `(issue id, number)`. A live page follows
274+ /// these when something in the repo changes.
275+ pub async fn pull_refs(&self, repo_id: &str) -> Result<Vec<(Id, i64)>> {
276+ let conn = self.read_conn().await;
277+ fetch_all(
278+ &conn,
279+ "SELECT i.id, i.number FROM issues i \
280+ WHERE i.repo_id = ?1 AND i.kind = 'pull' ORDER BY i.number",
281+ (repo_id.to_string(),),
282+ |row| Ok((col_text(row, 0)?, col_int(row, 1)?)),
283+ )
284+ .await
285+ }
286+
287+ /// The pull requests of a repo whose head is `sha`, open or closed, as `(issue id, number)`.
288+ pub async fn pulls_for_head_oid(&self, repo_id: &str, sha: &str) -> Result<Vec<(Id, i64)>> {
289+ let conn = self.read_conn().await;
290+ fetch_all(
291+ &conn,
292+ "SELECT i.id, i.number FROM pull_requests p \
293+ JOIN issues i ON i.id = p.issue_id \
294+ WHERE i.repo_id = ?1 AND p.head_oid = ?2 AND i.kind = 'pull' ORDER BY i.number",
295+ (repo_id.to_string(), sha.to_string()),
296+ |row| Ok((col_text(row, 0)?, col_int(row, 1)?)),
297+ )
298+ .await
299+ }
300+
273 /// Records a new head commit after the head branch moved. Mergeability goes back to301 /// Records a new head commit after the head branch moved. Mergeability goes back to
274 /// `unknown` and the conflict list is cleared until it is recomputed.302 /// `unknown` and the conflict list is cleared until it is recomputed.
275 pub async fn update_pull_head(&self, issue_id: &str, head_oid: &str) -> Result<()> {303 pub async fn update_pull_head(&self, issue_id: &str, head_oid: &str) -> Result<()> {
crates/forge-web/assets/nav.jsmodified+44 -4
@@ -59,10 +59,23 @@
59 return el.type !== 'hidden' && el.type !== 'password' && el.type !== 'file';59 return el.type !== 'hidden' && el.type !== 'password' && el.type !== 'file';
60 }60 }
61 61
62+ // A page can hold several fields with one key (each inline comment form posts to one action with
63+ // one name), so a key carries its occurrence: the first such field is #0, the next #1, and so on.
64+ function fieldsKeyed() {
65+ var seen = Object.create(null);
66+ return Array.prototype.map.call(document.querySelectorAll('input, textarea, select'), function (el) {
67+ var key = fieldKey(el);
68+ var n = seen[key] || 0;
69+ seen[key] = n + 1;
70+ return { el: el, k: key + '#' + n };
71+ });
72+ }
73+
62 function captureFields() {74 function captureFields() {
63 var active = document.activeElement;75 var active = document.activeElement;
64 var out = [];76 var out = [];
65- document.querySelectorAll('input, textarea, select').forEach(function (el) {77+ fieldsKeyed().forEach(function (item) {
78+ var el = item.el;
66 if (!savable(el)) { return; }79 if (!savable(el)) { return; }
67 var moved;80 var moved;
68 if (el.type === 'checkbox' || el.type === 'radio') {81 if (el.type === 'checkbox' || el.type === 'radio') {
@@ -83,18 +96,18 @@
83 try {96 try {
84 if (el.selectionStart != null) { start = el.selectionStart; end = el.selectionEnd; }97 if (el.selectionStart != null) { start = el.selectionStart; end = el.selectionEnd; }
85 } catch (err) { }98 } catch (err) { }
86- out.push({ k: fieldKey(el), v: el.value, c: el.checked, i: el.selectedIndex, f: focused, s: start, e: end });99+ out.push({ k: item.k, v: el.value, c: el.checked, i: el.selectedIndex, f: focused, s: start, e: end });
87 });100 });
88 return out;101 return out;
89 }102 }
90 103
91 function restoreFields(saved) {104 function restoreFields(saved) {
92 if (!saved || !saved.length) { return; }105 if (!saved || !saved.length) { return; }
93- var fields = document.querySelectorAll('input, textarea, select');106+ var fields = fieldsKeyed();
94 saved.forEach(function (was) {107 saved.forEach(function (was) {
95 var el = null;108 var el = null;
96 for (var i = 0; i < fields.length; i++) {109 for (var i = 0; i < fields.length; i++) {
97- if (fieldKey(fields[i]) === was.k) { el = fields[i]; break; }110+ if (fields[i].k === was.k) { el = fields[i].el; break; }
98 }111 }
99 if (!el) { return; }112 if (!el) { return; }
100 if (el.type === 'checkbox' || el.type === 'radio') { el.checked = was.c; }113 if (el.type === 'checkbox' || el.type === 'radio') { el.checked = was.c; }
@@ -267,6 +280,7 @@
267 var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 24 } : null;280 var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 24 } : null;
268 // A live change must not shut a menu the reader has open (a run's branch picker, say).281 // A live change must not shut a menu the reader has open (a run's branch picker, say).
269 var dd = how === 'live' ? captureDropdowns() : null;282 var dd = how === 'live' ? captureDropdowns() : null;
283+ var at = how === 'live' ? captureAnchor() : null;
270 if (how !== 'live') { closeDropdowns(null); }284 if (how !== 'live') { closeDropdowns(null); }
271 var oldList = document.querySelector('.ci-run-list');285 var oldList = document.querySelector('.ci-run-list');
272 var listTop = how === 'live' && oldList ? oldList.scrollTop : null;286 var listTop = how === 'live' && oldList ? oldList.scrollTop : null;
@@ -281,11 +295,37 @@
281 shown = dest.pathname + dest.search;295 shown = dest.pathname + dest.search;
282 if (how === 'nav' || how === 'pop') { focusMain(); }296 if (how === 'nav' || how === 'pop') { focusMain(); }
283 if (how !== 'live' && placeHash(dest.hash)) { return; }297 if (how !== 'live' && placeHash(dest.hash)) { return; }
298+ if (how === 'live' && placeAnchor(at)) { return; }
284 if (how === 'post' || how === 'query' || how === 'live') { window.scrollTo(x, y); }299 if (how === 'post' || how === 'query' || how === 'live') { window.scrollTo(x, y); }
285 else if (how === 'pop') { window.scrollTo(0, saved && typeof saved.y === 'number' ? saved.y : 0); }300 else if (how === 'pop') { window.scrollTo(0, saved && typeof saved.y === 'number' ? saved.y : 0); }
286 else { window.scrollTo(0, 0); }301 else { window.scrollTo(0, 0); }
287 }302 }
288 303
304+ // A live change keeps the reader's place in a diff. Before the swap: the first element marked
305+ // data-keep-anchor (a diff file, keyed by its path) that is still at least partly in view, and
306+ // its offset from the top of the view. After the swap: the same key, moved so it sits at that
307+ // offset again. The key is the path, since a push can move a file's position in the diff.
308+ function captureAnchor() {
309+ var els = document.querySelectorAll('[data-keep-anchor]');
310+ for (var i = 0; i < els.length; i++) {
311+ var r = els[i].getBoundingClientRect();
312+ if (r.bottom > 0) { return { key: els[i].getAttribute('data-keep-anchor'), dy: r.top }; }
313+ }
314+ return null;
315+ }
316+
317+ function placeAnchor(at) {
318+ if (!at) { return false; }
319+ var els = document.querySelectorAll('[data-keep-anchor]');
320+ for (var i = 0; i < els.length; i++) {
321+ if (els[i].getAttribute('data-keep-anchor') === at.key) {
322+ window.scrollTo(window.scrollX, window.scrollY + els[i].getBoundingClientRect().top - at.dy);
323+ return true;
324+ }
325+ }
326+ return false;
327+ }
328+
289 // The runs list scrolls inside its card: bring the selected row into view there. scrollIntoView329 // The runs list scrolls inside its card: bring the selected row into view there. scrollIntoView
290 // would also scroll the page, so the list's own scrollTop is set instead.330 // would also scroll the page, so the list's own scrollTop is set instead.
291 function placeRun(keepTop) {331 function placeRun(keepTop) {
crates/forge-web/src/automerge.rsmodified+3 -0
@@ -15,6 +15,7 @@ use crate::state::AppState;
15 /// `sha`. Called after a commit status for `sha` was written. Failures are logged: the status15 /// `sha`. Called after a commit status for `sha` was written. Failures are logged: the status
16 /// that triggered this has already been stored.16 /// that triggered this has already been stored.
17 pub async fn on_status(state: &AppState, repo_id: &str, sha: &str) {17 pub async fn on_status(state: &AppState, repo_id: &str, sha: &str) {
18+ crate::pages::pull_live::bump_head(state, repo_id, sha).await;
18 let pulls = match state.store.auto_merge_pulls_for_head(repo_id, sha).await {19 let pulls = match state.store.auto_merge_pulls_for_head(repo_id, sha).await {
19 Ok(pulls) => pulls,20 Ok(pulls) => pulls,
20 Err(e) => {21 Err(e) => {
@@ -53,6 +54,8 @@ async fn evaluate_logged(state: &AppState, repo: &Repo, pr: &PullRequest) {
53 if let Err(e) = Box::pin(evaluate(state, repo, pr)).await {54 if let Err(e) = Box::pin(evaluate(state, repo, pr)).await {
54 tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "auto-merge: evaluation failed");55 tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "auto-merge: evaluation failed");
55 }56 }
57+ // The evaluation may have merged the pull or left it as it was; either way its page re-reads.
58+ crate::pages::pull_live::bump_pull(state, &repo.id, &pr.issue.id);
56 }59 }
57 60
58 /// Merges `pr` when auto-merge is on and nothing blocks it any more. Returns whether it merged.61 /// Merges `pr` when auto-merge is on and nothing blocks it any more. Returns whether it merged.
crates/forge-web/src/boot.rsmodified+1 -0
@@ -166,6 +166,7 @@ pub async fn serve(
166 .cookies()166 .cookies()
167 .layer(crate::pages::settings_profile::avatar_body_limit())167 .layer(crate::pages::settings_profile::avatar_body_limit())
168 .layer(crate::pages::repo_ctx::RepoMovedLayer)168 .layer(crate::pages::repo_ctx::RepoMovedLayer)
169+ .layer(crate::pages::pull_live::PullWriteLayer)
169 .layer(crate::pages::not_found_page::NotFoundLayer)170 .layer(crate::pages::not_found_page::NotFoundLayer)
170 .layer(TowerLayer::new(crate::compression::ResponseCompression))171 .layer(TowerLayer::new(crate::compression::ResponseCompression))
171 .compression(Compression::off())172 .compression(Compression::off())
crates/forge-web/src/live.rsmodified+6 -0
@@ -44,6 +44,12 @@ pub enum Topic {
44 RepoIssues(String),44 RepoIssues(String),
45 /// One issue: its body, comments, events, state, labels, reactions. Keyed by issue id.45 /// One issue: its body, comments, events, state, labels, reactions. Keyed by issue id.
46 Issue(String),46 Issue(String),
47+ /// The pull request list of a repo: a pull opened, or any pull in the repo changed. Keyed by
48+ /// repo id. Bumped by [`crate::pages::pull_live`].
49+ PullList(String),
50+ /// One pull request, its conversation, commits and files. Keyed by the pull's issue id.
51+ /// Bumped by [`crate::pages::pull_live`].
52+ Pull(String),
47 }53 }
48 54
49 /// The open topics, each with the counter its subscribers wait on.55 /// The open topics, each with the counter its subscribers wait on.
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -78,6 +78,7 @@ pub mod profile_pins;
78 pub mod pull_branch;78 pub mod pull_branch;
79 pub mod pull_files;79 pub mod pull_files;
80 pub mod pull_flow;80 pub mod pull_flow;
81+pub mod pull_live;
81 pub mod pull_reviews;82 pub mod pull_reviews;
82 pub mod pull_view;83 pub mod pull_view;
83 pub mod pulls_list;84 pub mod pulls_list;
crates/forge-web/src/pages/pull_live.rsadded+289 -0
@@ -0,0 +1,289 @@
1+//! Live pull requests. The pull list (`/{o}/{r}/pulls`) follows [`Topic::PullList`]; a pull page
2+//! and its tabs (conversation, commits, files) follow [`Topic::Pull`]. The pages render `data-live`
3+//! with the URL of their stream, and a `changed` event re-renders them in place (see `nav.js`).
4+//!
5+//! Every write reaches a topic through one of these paths:
6+//! - A POST under `/{o}/{r}/pulls/...` (comment, review, label, merge, draft, branch, ...): the
7+//! [`PullWriteLayer`] bumps after the handler ran, so no route calls a bump itself.
8+//! - A commit status (CI or the status API): [`bump_head`], from `automerge::on_status`.
9+//! - A push, a mergeability refresh or an auto-merge: [`bump_repo_pulls`], from the call site.
10+//!
11+//! The bump helpers are the one place each topic is bumped from. A new write path calls one of
12+//! them; it does not bump a topic directly.
13+//!
14+//! What a stream compares is a fingerprint of what the page shows ([`pull_fingerprint`],
15+//! [`list_fingerprint`]). A bump that changes none of it sends nothing, so over-bumping is cheap.
16+
17+use forge_core::PullRequest;
18+use forge_core::store::Store;
19+use topcoat::Result;
20+use topcoat::context::{Cx, app_context};
21+use topcoat::router::request::{method, uri};
22+use topcoat::router::response::Response;
23+use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route};
24+
25+use crate::live::{Topic, stream_changes};
26+use crate::pages::issue_parts::parse_number;
27+use crate::pages::repo_ctx::load_repo;
28+use crate::state::AppState;
29+
30+path_param!(owner);
31+path_param!(repo);
32+path_param!(number);
33+
34+// Bumps. Each one wakes the streams of the topics it names; none of them reads more than the
35+// ids it needs. A failed lookup is logged and leaves the streams as they were.
36+
37+/// A write changed one pull request: its page and the list both follow it.
38+pub fn bump_pull(state: &AppState, repo_id: &str, issue_id: &str) {
39+ state.live.bump(&Topic::Pull(issue_id.to_owned()));
40+ bump_list(state, repo_id);
41+}
42+
43+/// A pull request was opened, or the list changed for another reason. Only the list follows.
44+pub fn bump_list(state: &AppState, repo_id: &str) {
45+ state.live.bump(&Topic::PullList(repo_id.to_owned()));
46+}
47+
48+/// A change that may touch any pull of the repo (a push, a label or milestone edit, a merge run
49+/// by auto-merge): the list and every pull page of the repo.
50+pub async fn bump_repo_pulls(state: &AppState, repo_id: &str) {
51+ bump_list(state, repo_id);
52+ match state.store.pull_refs(repo_id).await {
53+ Ok(refs) => {
54+ for (issue_id, _) in refs {
55+ state.live.bump(&Topic::Pull(issue_id));
56+ }
57+ }
58+ Err(e) => tracing::error!(error = %e, repo_id, "live: listing pulls to bump failed"),
59+ }
60+}
61+
62+/// A commit status was written for `sha`: the pulls whose head is that commit, and the list.
63+pub async fn bump_head(state: &AppState, repo_id: &str, sha: &str) {
64+ bump_list(state, repo_id);
65+ match state.store.pulls_for_head_oid(repo_id, sha).await {
66+ Ok(refs) => {
67+ for (issue_id, _) in refs {
68+ state.live.bump(&Topic::Pull(issue_id));
69+ }
70+ }
71+ Err(e) => {
72+ tracing::error!(error = %e, repo_id, "live: listing pulls for a head to bump failed")
73+ }
74+ }
75+}
76+
77+// Fingerprints. Each reads what the page shows; any change to it changes the string.
78+
79+/// What one pull request page shows, as one string. `viewer` is the reader: a pending review is
80+/// the viewer's own and shows only to them.
81+pub(crate) async fn pull_fingerprint(
82+ store: &Store,
83+ repo_id: &str,
84+ pr: &PullRequest,
85+ viewer: Option<&str>,
86+) -> Result<String> {
87+ let id = pr.issue.id.as_str();
88+ let labels = store.issue_labels(id).await?;
89+ let assignees = store.issue_assignees(id).await?;
90+ let reviewers = store.requested_reviewers(id).await?;
91+ let comments = store.list_comments(id).await?;
92+ let reviews = store.list_reviews(id).await?;
93+ let threads = store.review_threads(id, viewer).await?;
94+ let statuses = store.statuses_for(repo_id, &pr.head_oid).await?;
95+
96+ let mut lines = vec![
97+ format!(
98+ "{:?} {:?} {} {} {}",
99+ pr.issue.state,
100+ pr.issue.state_reason,
101+ pr.issue.title,
102+ pr.issue.updated_at,
103+ pr.issue.comment_count
104+ ),
105+ format!("body {}", pr.issue.body),
106+ format!(
107+ "draft {} head {} base {} {:?} {:?} {:?} {:?}",
108+ pr.draft,
109+ pr.head_oid,
110+ pr.base_oid,
111+ pr.mergeable,
112+ pr.merged_at,
113+ pr.merge_commit,
114+ pr.conflict_files
115+ ),
116+ format!(
117+ "branch {:?} {} auto {:?}",
118+ pr.head_repo_id, pr.head_branch, pr.auto_merge
119+ ),
120+ format!("labels {labels:?}"),
121+ format!("assignees {assignees:?}"),
122+ format!("reviewers {reviewers:?}"),
123+ ];
124+ lines.extend(comments.iter().map(|c| format!("comment {c:?}")));
125+ lines.extend(reviews.iter().map(|r| format!("review {r:?}")));
126+ lines.extend(threads.iter().map(|t| format!("thread {t:?}")));
127+ lines.extend(statuses.iter().map(|s| format!("status {s:?}")));
128+ Ok(lines.join("\n"))
129+}
130+
131+/// What the pull request list shows: the fingerprint of every pull of the repo, in number order.
132+pub(crate) async fn list_fingerprint(
133+ store: &Store,
134+ repo_id: &str,
135+ viewer: Option<&str>,
136+) -> Result<String> {
137+ let mut parts = Vec::new();
138+ for (_, number) in store.pull_refs(repo_id).await? {
139+ let Some(pr) = store.pull_by_number(repo_id, number).await? else {
140+ continue;
141+ };
142+ parts.push(pull_fingerprint(store, repo_id, &pr, viewer).await?);
143+ }
144+ Ok(parts.join("\n#\n"))
145+}
146+
147+/// The fingerprint of one pull request by number. `gone` once it no longer exists.
148+async fn pull_read(
149+ store: &Store,
150+ repo_id: &str,
151+ number: i64,
152+ viewer: Option<&str>,
153+) -> Result<String> {
154+ match store.pull_by_number(repo_id, number).await? {
155+ Some(pr) => pull_fingerprint(store, repo_id, &pr, viewer).await,
156+ None => Ok("gone".to_owned()),
157+ }
158+}
159+
160+// Streams
161+
162+/// The pull list's change stream. Auth is the repo read check of the list page.
163+#[route(GET "/{owner}/{repo}/pulls/events")]
164+async fn pulls_events(cx: &Cx) -> Result<Response> {
165+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
166+ let state = app_context::<AppState>(cx);
167+ let topic = Topic::PullList(ctx.repo.id.clone());
168+ let store = state.store.clone();
169+ let repo_id = ctx.repo.id.clone();
170+ let viewer = ctx.viewer.as_ref().map(|(user, _)| user.id.clone());
171+ stream_changes(cx, &state.live, &topic, move || {
172+ let store = store.clone();
173+ let repo_id = repo_id.clone();
174+ let viewer = viewer.clone();
175+ async move { list_fingerprint(&store, &repo_id, viewer.as_deref()).await }
176+ })
177+ .await
178+}
179+
180+/// One pull request's change stream. Auth is the page's: the repo read check, then the pull.
181+#[route(GET "/{owner}/{repo}/pulls/{number}/events")]
182+async fn pull_events(cx: &Cx) -> Result<Response> {
183+ let number = parse_number(path_param::<Number>(cx))?;
184+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
185+ let state = app_context::<AppState>(cx);
186+ let Some(pr) = state.store.pull_by_number(&ctx.repo.id, number).await? else {
187+ return Err(topcoat::router::error::not_found().into());
188+ };
189+ let topic = Topic::Pull(pr.issue.id.clone());
190+ let store = state.store.clone();
191+ let repo_id = ctx.repo.id.clone();
192+ let viewer = ctx.viewer.as_ref().map(|(user, _)| user.id.clone());
193+ stream_changes(cx, &state.live, &topic, move || {
194+ let store = store.clone();
195+ let repo_id = repo_id.clone();
196+ let viewer = viewer.clone();
197+ async move { pull_read(&store, &repo_id, number, viewer.as_deref()).await }
198+ })
199+ .await
200+}
201+
202+// The write layer
203+
204+/// Which topic a POST under the pulls paths writes to.
205+enum Written {
206+ /// A write to one pull request (`/{o}/{r}/pulls/{n}/...`).
207+ Pull {
208+ owner: String,
209+ repo: String,
210+ number: i64,
211+ },
212+ /// A new pull request (`/{o}/{r}/pulls`).
213+ New { owner: String, repo: String },
214+ /// A repo-wide change the pulls show: a label or milestone edit.
215+ Repo { owner: String, repo: String },
216+}
217+
218+/// The write a request makes to the pull side, when it is a POST that can change one.
219+fn written(cx: &Cx) -> Option<Written> {
220+ if *method(cx) != Method::POST {
221+ return None;
222+ }
223+ let path = uri(cx).path().to_owned();
224+ let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
225+ let [owner, repo, kind, rest @ ..] = parts.as_slice() else {
226+ return None;
227+ };
228+ let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned());
229+ match (*kind, rest) {
230+ ("pulls", []) => Some(Written::New { owner, repo }),
231+ ("pulls", [number, ..]) => number.parse().ok().map(|number| Written::Pull {
232+ owner,
233+ repo,
234+ number,
235+ }),
236+ ("labels" | "milestones", _) => Some(Written::Repo { owner, repo }),
237+ _ => None,
238+ }
239+}
240+
241+/// Bumps the topics a write named, once the handler has run. The handler's result passes through
242+/// unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and agrees.
243+async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> {
244+ let target = written(cx);
245+ let result = next.run(cx, body).await;
246+ if let Some(target) = target {
247+ bump_written(app_context::<AppState>(cx), target).await;
248+ }
249+ result
250+}
251+
252+async fn bump_written(state: &AppState, target: Written) {
253+ let (owner, name) = match &target {
254+ Written::Pull { owner, repo, .. }
255+ | Written::New { owner, repo }
256+ | Written::Repo { owner, repo } => (owner.as_str(), repo.as_str()),
257+ };
258+ let repo = match state.store.repo_by_owner_and_name(owner, name).await {
259+ Ok(Some(repo)) => repo,
260+ Ok(None) => return,
261+ Err(e) => {
262+ tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed");
263+ return;
264+ }
265+ };
266+ match target {
267+ Written::Pull { number, .. } => match state.store.pull_by_number(&repo.id, number).await {
268+ Ok(Some(pr)) => bump_pull(state, &repo.id, &pr.issue.id),
269+ Ok(None) => {}
270+ Err(e) => tracing::error!(error = %e, number, "live: loading the pull to bump failed"),
271+ },
272+ Written::New { .. } => bump_list(state, &repo.id),
273+ Written::Repo { .. } => bump_repo_pulls(state, &repo.id).await,
274+ }
275+}
276+
277+/// Wraps every request. Only a POST under the pulls paths, or to a label or milestone route, does
278+/// anything. Registered on the public router in `boot.rs`, next to the other request layers.
279+pub struct PullWriteLayer;
280+
281+impl Layer for PullWriteLayer {
282+ fn path(&self) -> Option<&Path> {
283+ None
284+ }
285+
286+ fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> {
287+ Box::pin(bump_after_write(cx, body, next))
288+ }
289+}
crates/forge-web/src/pages/pull_view.rsmodified+4 -1
@@ -188,6 +188,7 @@ pub(crate) async fn pull_header(frame: Frame) -> Result<impl View> {
188 let Frame {188 let Frame {
189 title,189 title,
190 number,190 number,
191+ href,
191 state_class,192 state_class,
192 state_text,193 state_text,
193 author,194 author,
@@ -200,6 +201,8 @@ pub(crate) async fn pull_header(frame: Frame) -> Result<impl View> {
200 ..201 ..
201 } = frame;202 } = frame;
202 let number_label = format!("#{number}");203 let number_label = format!("#{number}");
204+ // The header is on every pull tab, so each tab follows the pull's stream.
205+ let live_url = format!("{href}/events");
203 let commits_text = g::commit_count_line(lang, commit_count);206 let commits_text = g::commit_count_line(lang, commit_count);
204 let wants = g::t(lang, K::ByWantsToMerge);207 let wants = g::t(lang, K::ByWantsToMerge);
205 let into = g::t(lang, K::ByInto);208 let into = g::t(lang, K::ByInto);
@@ -208,7 +211,7 @@ pub(crate) async fn pull_header(frame: Frame) -> Result<impl View> {
208 // Turkish puts the source branch first and the commit count before the verb.211 // Turkish puts the source branch first and the commit count before the verb.
209 let turkish = matches!(lang, Lang::Tr);212 let turkish = matches!(lang, Lang::Tr);
210 Ok(view! {213 Ok(view! {
211- <section class="issue-head">214+ <section class="issue-head" data-live=(live_url.as_str())>
212 <h1 class="issue-heading">(title.as_str()) " " <span class="issue-number">(number_label.as_str())</span></h1>215 <h1 class="issue-heading">(title.as_str()) " " <span class="issue-number">(number_label.as_str())</span></h1>
213 <p class="issue-byline">216 <p class="issue-byline">
214 <span class=(state_class)>(state_text)</span>217 <span class=(state_class)>(state_text)</span>
crates/forge-web/src/pages/pulls_list.rsmodified+2 -1
@@ -258,10 +258,11 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
258 let draft_sel = sel.draft;258 let draft_sel = sel.draft;
259 259
260 let header = ctx.head(state, "pulls").await?;260 let header = ctx.head(state, "pulls").await?;
261+ let live_url = format!("/{owner}/{name}/pulls/events");
261 Ok(view! {262 Ok(view! {
262 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()),263 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), extra_stylesheet: Some(labels_href.as_str()),
263 repo_head(head: header)264 repo_head(head: header)
264- <div class="issue-toolbar">265+ <div class="issue-toolbar" data-live=(live_url.as_str())>
265 <nav class="issue-tabs" aria-label=(g::t(lang, K::ListStateNavLabel))>266 <nav class="issue-tabs" aria-label=(g::t(lang, K::ListStateNavLabel))>
266 <a class=(state_tab_class(state_word == "open")) href=(open_href.as_str())>(open_text.as_str())</a>267 <a class=(state_tab_class(state_word == "open")) href=(open_href.as_str())>(open_text.as_str())</a>
267 <a class=(state_tab_class(state_word == "closed")) href=(closed_href.as_str())>(closed_text.as_str())</a>268 <a class=(state_tab_class(state_word == "closed")) href=(closed_href.as_str())>(closed_text.as_str())</a>
crates/forge-web/src/post_update.rsmodified+4 -1
@@ -73,7 +73,10 @@ pub async fn after_ref_update(
73 }73 }
74 }74 }
75 }75 }
76- pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await76+ let synced = pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await;
77+ // A push can move, merge or open any pull of the repo, so every pull page is woken.
78+ crate::pages::pull_live::bump_repo_pulls(state, &repo.id).await;
79+ synced
77 }80 }
78 81
79 /// Processes the commits added to the default branch by one ref update, oldest first.82 /// Processes the commits added to the default branch by one ref update, oldest first.
crates/forge-web/src/pulls_sync.rsmodified+1 -0
@@ -344,6 +344,7 @@ pub async fn refresh_mergeability(
344 &files,344 &files,
345 )345 )
346 .await?;346 .await?;
347+ crate::pages::pull_live::bump_pull(state, &base_repo.id, &pr.issue.id);
347 Ok(())348 Ok(())
348 }349 }
349 350
crates/forge-web/src/test_support.rsmodified+1 -0
@@ -98,6 +98,7 @@ pub fn app_router(state: AppState) -> Router {
98 .cookies()98 .cookies()
99 .layer(avatar_body_limit())99 .layer(avatar_body_limit())
100 .layer(RepoMovedLayer)100 .layer(RepoMovedLayer)
101+ .layer(crate::pages::pull_live::PullWriteLayer)
101 .layer(TowerLayer::new(crate::compression::ResponseCompression))102 .layer(TowerLayer::new(crate::compression::ResponseCompression))
102 .compression(Compression::off())103 .compression(Compression::off())
103 .build()104 .build()
crates/forge-web/src/views/diff.rsmodified+1 -1
@@ -601,7 +601,7 @@ async fn diff_file(file: FileView, lang: Lang, split: bool, anchored: bool) -> R
601 _ => "diff-table",601 _ => "diff-table",
602 };602 };
603 Ok(view! {603 Ok(view! {
604- <section class="diff-file" id=(file.anchor.as_str())>604+ <section class="diff-file" id=(file.anchor.as_str()) data-keep-anchor=(file.label.as_str())>
605 <header class="diff-file-header">605 <header class="diff-file-header">
606 <code class="diff-path">(file.label.as_str())</code>606 <code class="diff-path">(file.label.as_str())</code>
607 <span class="diff-file-meta">607 <span class="diff-file-meta">
crates/forge-web/tests/pulls_e2e.rsmodified+164 -1
@@ -12,7 +12,7 @@ use std::path::{Path, PathBuf};
12 use std::process::{Command, Output};12 use std::process::{Command, Output};
13 use std::time::{Duration, Instant};13 use std::time::{Duration, Instant};
14 14
15-use reqwest::header::{LOCATION, SET_COOKIE};15+use reqwest::header::{AUTHORIZATION, CONTENT_TYPE, COOKIE, LOCATION, SET_COOKIE};
16 16
17 const TAHINLI_PW: &str = "tahinli-password-123";17 const TAHINLI_PW: &str = "tahinli-password-123";
18 const BOB_PW: &str = "bob-password-4567";18 const BOB_PW: &str = "bob-password-4567";
@@ -558,6 +558,169 @@ async fn push_to_head_branch_updates_open_pull() {
558 assert!(commits.body.contains(&second[..7]), "new commit sha shown");558 assert!(commits.body.contains(&second[..7]), "new commit sha shown");
559 }559 }
560 560
561+/// Opens a live stream, as `session` or anonymously.
562+async fn open_stream(http: &Http, path: &str, session: Option<&str>) -> reqwest::Response {
563+ let mut req = http.client.get(format!("{}{path}", http.base));
564+ if let Some(session) = session {
565+ req = req.header(COOKIE, session);
566+ }
567+ req.send().await.expect("stream request")
568+}
569+
570+/// Waits for the next event of a stream, which must be `changed`.
571+async fn next_changed(res: &mut reqwest::Response, what: &str) {
572+ let chunk = tokio::time::timeout(Duration::from_secs(5), res.chunk())
573+ .await
574+ .unwrap_or_else(|_| panic!("no event after {what}"))
575+ .expect("stream chunk")
576+ .expect("stream still open");
577+ let text = String::from_utf8_lossy(&chunk);
578+ assert!(text.contains("event: changed"), "{what}: {text}");
579+}
580+
581+/// Asserts that nothing arrives on a stream for two seconds.
582+async fn assert_quiet(res: &mut reqwest::Response, what: &str) {
583+ let got = tokio::time::timeout(Duration::from_secs(2), res.chunk()).await;
584+ assert!(got.is_err(), "{what}: the stream sent an event");
585+}
586+
587+#[tokio::test]
588+async fn pull_pages_follow_writes_live() {
589+ let b = boot().await;
590+ let (tahinli, token, work) = tahinli_repo_with_main(&b).await;
591+
592+ git(&work, &["checkout", "-q", "-b", "live"]);
593+ let first = commit(
594+ &work,
595+ "live.txt",
596+ "live\n",
597+ "first on live",
598+ "tahinli",
599+ "tahinli@example.test",
600+ );
601+ git(&work, &["push", "-q", "origin", "HEAD:refs/heads/live"]);
602+ let number = open_pull(&b.http, &tahinli, "main", "live", "Live pull").await;
603+ let pull = format!("{REPO_PATH}/pulls/{number}");
604+ let list = format!("{REPO_PATH}/pulls");
605+
606+ // The pull page and the list render the streams they follow.
607+ let page = b.http.get_cookie(&pull, &tahinli).await;
608+ assert_eq!(page.status, 200, "GET pull");
609+ assert!(
610+ page.body.contains(&format!("data-live=\"{pull}/events\"")),
611+ "pull page follows its stream"
612+ );
613+ let listing = b.http.get_cookie(&list, &tahinli).await;
614+ assert!(
615+ listing
616+ .body
617+ .contains(&format!("data-live=\"{list}/events\"")),
618+ "pull list follows its stream"
619+ );
620+
621+ let mut pull_events = open_stream(&b.http, &format!("{pull}/events"), Some(&tahinli)).await;
622+ assert_eq!(pull_events.status().as_u16(), 200, "pull stream");
623+ let mut list_events = open_stream(&b.http, &format!("{list}/events"), Some(&tahinli)).await;
624+ assert_eq!(list_events.status().as_u16(), 200, "list stream");
625+ assert_quiet(&mut pull_events, "connecting to the pull stream").await;
626+
627+ // A comment on the conversation wakes both the pull and the list.
628+ let csrf = csrf_token(&b.http, &tahinli).await;
629+ let res = b
630+ .http
631+ .post_form(
632+ &format!("{pull}/comments"),
633+ &[
634+ ("csrf", &csrf),
635+ ("body", "a comment"),
636+ ("action", "comment"),
637+ ],
638+ Some(&tahinli),
639+ )
640+ .await;
641+ assert_eq!(res.status, 303, "comment: {}", res.body);
642+ next_changed(&mut pull_events, "a comment").await;
643+ next_changed(&mut list_events, "a comment").await;
644+
645+ // A review submitted on the head.
646+ let csrf = csrf_token(&b.http, &tahinli).await;
647+ let res = b
648+ .http
649+ .post_form(
650+ &format!("{pull}/reviews"),
651+ &[
652+ ("csrf", &csrf),
653+ ("state", "comment"),
654+ ("body", "a review"),
655+ ("head_oid", &first),
656+ ],
657+ Some(&tahinli),
658+ )
659+ .await;
660+ assert_eq!(res.status, 303, "review: {}", res.body);
661+ next_changed(&mut pull_events, "a review").await;
662+
663+ // A push to the head branch updates the pull and the list.
664+ let second = commit(
665+ &work,
666+ "second.txt",
667+ "2\n",
668+ "second on live",
669+ "tahinli",
670+ "tahinli@example.test",
671+ );
672+ git(&work, &["push", "-q", "origin", "HEAD:refs/heads/live"]);
673+ next_changed(&mut pull_events, "a push to the head").await;
674+ next_changed(&mut list_events, "a push to the head").await;
675+
676+ // A commit status for the head commit (what CI reports) changes the pull.
677+ let status = b
678+ .http
679+ .client
680+ .post(format!(
681+ "{}/api/v1/repos/tahinli/r/statuses/{second}",
682+ b.http.base
683+ ))
684+ .header(AUTHORIZATION, format!("Bearer {token}"))
685+ .header(CONTENT_TYPE, "application/json")
686+ .body(r#"{"state":"success","context":"ci/test"}"#)
687+ .send()
688+ .await
689+ .expect("status request");
690+ assert_eq!(status.status().as_u16(), 201, "status posted");
691+ next_changed(&mut pull_events, "a commit status on the head").await;
692+
693+ // Merging the pull changes it, and the list.
694+ let res = merge(&b.http, &tahinli, number, "merge").await;
695+ assert_eq!(res.status, 303, "merge: {}", res.body);
696+ next_changed(&mut pull_events, "the merge").await;
697+ next_changed(&mut list_events, "the merge").await;
698+
699+ // A private repo streams only to a viewer who can read it.
700+ let csrf = csrf_token(&b.http, &tahinli).await;
701+ let res = b
702+ .http
703+ .post_form(
704+ "/new",
705+ &[
706+ ("csrf", &csrf),
707+ ("name", "priv"),
708+ ("description", ""),
709+ ("visibility", "private"),
710+ ("default_branch", "main"),
711+ ],
712+ Some(&tahinli),
713+ )
714+ .await;
715+ assert_eq!(res.status, 303, "create private repo: {}", res.body);
716+ let anonymous = open_stream(&b.http, "/tahinli/priv/pulls/events", None).await;
717+ assert_eq!(anonymous.status().as_u16(), 404, "private list, anonymous");
718+ let anonymous = open_stream(&b.http, "/tahinli/priv/pulls/1/events", None).await;
719+ assert_eq!(anonymous.status().as_u16(), 404, "private pull, anonymous");
720+ let member = open_stream(&b.http, "/tahinli/priv/pulls/events", Some(&tahinli)).await;
721+ assert_eq!(member.status().as_u16(), 200, "private list, owner");
722+}
723+
561 #[tokio::test]724 #[tokio::test]
562 async fn fork_pull_squash_merge_credits_contributor() {725 async fn fork_pull_squash_merge_credits_contributor() {
563 let b = boot().await;726 let b = boot().await;
docs/architecture.mdmodified+1 -0
@@ -490,6 +490,7 @@ Known gaps:
490 - Reviews (approve, request changes, comment) and review comments anchored to commit, path, line, side, and hunk. Comments are marked outdated, not deleted.490 - Reviews (approve, request changes, comment) and review comments anchored to commit, path, line, side, and hunk. Comments are marked outdated, not deleted.
491 - Merge strategies: merge commit (`commit-tree` from merge-tree output), squash, rebase, fast-forward only.491 - Merge strategies: merge commit (`commit-tree` from merge-tree output), squash, rebase, fast-forward only.
492 - `range-diff` for "what changed since the last review." AGit (`refs/for/<branch>`) is considered later.492 - `range-diff` for "what changed since the last review." AGit (`refs/for/<branch>`) is considered later.
493+- 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`.
493 494
494 ### Webhooks, push mirrors, replication, backups, export495 ### Webhooks, push mirrors, replication, backups, export
495 496