From c2161c44f687d7259f72c12cfbd4f072b8c6101d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 22 Oct 2026 02:14:33 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20feat:=20pull=20requests=20update=20?= =?UTF-8?q?live?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-core/src/store/pulls.rs | 28 +++ crates/forge-web/assets/nav.js | 48 +++- crates/forge-web/src/automerge.rs | 3 + crates/forge-web/src/boot.rs | 1 + crates/forge-web/src/live.rs | 6 + crates/forge-web/src/pages/mod.rs | 1 + crates/forge-web/src/pages/pull_live.rs | 289 +++++++++++++++++++++++ crates/forge-web/src/pages/pull_view.rs | 5 +- crates/forge-web/src/pages/pulls_list.rs | 3 +- crates/forge-web/src/post_update.rs | 5 +- crates/forge-web/src/pulls_sync.rs | 1 + crates/forge-web/src/test_support.rs | 1 + crates/forge-web/src/views/diff.rs | 2 +- crates/forge-web/tests/pulls_e2e.rs | 165 ++++++++++++- docs/architecture.md | 1 + 15 files changed, 550 insertions(+), 9 deletions(-) create mode 100644 crates/forge-web/src/pages/pull_live.rs diff --git a/crates/forge-core/src/store/pulls.rs b/crates/forge-core/src/store/pulls.rs index 260a2a9..a3ab25a 100644 --- a/crates/forge-core/src/store/pulls.rs +++ b/crates/forge-core/src/store/pulls.rs @@ -270,6 +270,34 @@ impl Store { .await } + /// Every pull request of a repo, open or closed, as `(issue id, number)`. A live page follows + /// these when something in the repo changes. + pub async fn pull_refs(&self, repo_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT i.id, i.number FROM issues i \ + WHERE i.repo_id = ?1 AND i.kind = 'pull' ORDER BY i.number", + (repo_id.to_string(),), + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), + ) + .await + } + + /// The pull requests of a repo whose head is `sha`, open or closed, as `(issue id, number)`. + pub async fn pulls_for_head_oid(&self, repo_id: &str, sha: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT i.id, i.number FROM pull_requests p \ + JOIN issues i ON i.id = p.issue_id \ + WHERE i.repo_id = ?1 AND p.head_oid = ?2 AND i.kind = 'pull' ORDER BY i.number", + (repo_id.to_string(), sha.to_string()), + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), + ) + .await + } + /// Records a new head commit after the head branch moved. Mergeability goes back to /// `unknown` and the conflict list is cleared until it is recomputed. pub async fn update_pull_head(&self, issue_id: &str, head_oid: &str) -> Result<()> { diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 373ed16..bc0427e 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -59,10 +59,23 @@ return el.type !== 'hidden' && el.type !== 'password' && el.type !== 'file'; } + // A page can hold several fields with one key (each inline comment form posts to one action with + // one name), so a key carries its occurrence: the first such field is #0, the next #1, and so on. + function fieldsKeyed() { + var seen = Object.create(null); + return Array.prototype.map.call(document.querySelectorAll('input, textarea, select'), function (el) { + var key = fieldKey(el); + var n = seen[key] || 0; + seen[key] = n + 1; + return { el: el, k: key + '#' + n }; + }); + } + function captureFields() { var active = document.activeElement; var out = []; - document.querySelectorAll('input, textarea, select').forEach(function (el) { + fieldsKeyed().forEach(function (item) { + var el = item.el; if (!savable(el)) { return; } var moved; if (el.type === 'checkbox' || el.type === 'radio') { @@ -83,18 +96,18 @@ try { if (el.selectionStart != null) { start = el.selectionStart; end = el.selectionEnd; } } catch (err) { } - out.push({ k: fieldKey(el), v: el.value, c: el.checked, i: el.selectedIndex, f: focused, s: start, e: end }); + out.push({ k: item.k, v: el.value, c: el.checked, i: el.selectedIndex, f: focused, s: start, e: end }); }); return out; } function restoreFields(saved) { if (!saved || !saved.length) { return; } - var fields = document.querySelectorAll('input, textarea, select'); + var fields = fieldsKeyed(); saved.forEach(function (was) { var el = null; for (var i = 0; i < fields.length; i++) { - if (fieldKey(fields[i]) === was.k) { el = fields[i]; break; } + if (fields[i].k === was.k) { el = fields[i].el; break; } } if (!el) { return; } if (el.type === 'checkbox' || el.type === 'radio') { el.checked = was.c; } @@ -267,6 +280,7 @@ var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 24 } : null; // A live change must not shut a menu the reader has open (a run's branch picker, say). var dd = how === 'live' ? captureDropdowns() : null; + var at = how === 'live' ? captureAnchor() : null; if (how !== 'live') { closeDropdowns(null); } var oldList = document.querySelector('.ci-run-list'); var listTop = how === 'live' && oldList ? oldList.scrollTop : null; @@ -281,11 +295,37 @@ shown = dest.pathname + dest.search; if (how === 'nav' || how === 'pop') { focusMain(); } if (how !== 'live' && placeHash(dest.hash)) { return; } + if (how === 'live' && placeAnchor(at)) { return; } if (how === 'post' || how === 'query' || how === 'live') { window.scrollTo(x, y); } else if (how === 'pop') { window.scrollTo(0, saved && typeof saved.y === 'number' ? saved.y : 0); } else { window.scrollTo(0, 0); } } + // A live change keeps the reader's place in a diff. Before the swap: the first element marked + // data-keep-anchor (a diff file, keyed by its path) that is still at least partly in view, and + // its offset from the top of the view. After the swap: the same key, moved so it sits at that + // offset again. The key is the path, since a push can move a file's position in the diff. + function captureAnchor() { + var els = document.querySelectorAll('[data-keep-anchor]'); + for (var i = 0; i < els.length; i++) { + var r = els[i].getBoundingClientRect(); + if (r.bottom > 0) { return { key: els[i].getAttribute('data-keep-anchor'), dy: r.top }; } + } + return null; + } + + function placeAnchor(at) { + if (!at) { return false; } + var els = document.querySelectorAll('[data-keep-anchor]'); + for (var i = 0; i < els.length; i++) { + if (els[i].getAttribute('data-keep-anchor') === at.key) { + window.scrollTo(window.scrollX, window.scrollY + els[i].getBoundingClientRect().top - at.dy); + return true; + } + } + return false; + } + // The runs list scrolls inside its card: bring the selected row into view there. scrollIntoView // would also scroll the page, so the list's own scrollTop is set instead. function placeRun(keepTop) { diff --git a/crates/forge-web/src/automerge.rs b/crates/forge-web/src/automerge.rs index 424458d..2690e3d 100644 --- a/crates/forge-web/src/automerge.rs +++ b/crates/forge-web/src/automerge.rs @@ -15,6 +15,7 @@ use crate::state::AppState; /// `sha`. Called after a commit status for `sha` was written. Failures are logged: the status /// that triggered this has already been stored. pub async fn on_status(state: &AppState, repo_id: &str, sha: &str) { + crate::pages::pull_live::bump_head(state, repo_id, sha).await; let pulls = match state.store.auto_merge_pulls_for_head(repo_id, sha).await { Ok(pulls) => pulls, Err(e) => { @@ -53,6 +54,8 @@ async fn evaluate_logged(state: &AppState, repo: &Repo, pr: &PullRequest) { if let Err(e) = Box::pin(evaluate(state, repo, pr)).await { tracing::error!(error = %e, repo_id = %repo.id, number = pr.issue.number, "auto-merge: evaluation failed"); } + // The evaluation may have merged the pull or left it as it was; either way its page re-reads. + crate::pages::pull_live::bump_pull(state, &repo.id, &pr.issue.id); } /// Merges `pr` when auto-merge is on and nothing blocks it any more. Returns whether it merged. diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 8634c69..759eec5 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -166,6 +166,7 @@ pub async fn serve( .cookies() .layer(crate::pages::settings_profile::avatar_body_limit()) .layer(crate::pages::repo_ctx::RepoMovedLayer) + .layer(crate::pages::pull_live::PullWriteLayer) .layer(crate::pages::not_found_page::NotFoundLayer) .layer(TowerLayer::new(crate::compression::ResponseCompression)) .compression(Compression::off()) diff --git a/crates/forge-web/src/live.rs b/crates/forge-web/src/live.rs index be336e7..0531004 100644 --- a/crates/forge-web/src/live.rs +++ b/crates/forge-web/src/live.rs @@ -44,6 +44,12 @@ pub enum Topic { RepoIssues(String), /// One issue: its body, comments, events, state, labels, reactions. Keyed by issue id. Issue(String), + /// The pull request list of a repo: a pull opened, or any pull in the repo changed. Keyed by + /// repo id. Bumped by [`crate::pages::pull_live`]. + PullList(String), + /// One pull request, its conversation, commits and files. Keyed by the pull's issue id. + /// Bumped by [`crate::pages::pull_live`]. + Pull(String), } /// The open topics, each with the counter its subscribers wait on. diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 92d5163..8efc4ae 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -78,6 +78,7 @@ pub mod profile_pins; pub mod pull_branch; pub mod pull_files; pub mod pull_flow; +pub mod pull_live; pub mod pull_reviews; pub mod pull_view; pub mod pulls_list; diff --git a/crates/forge-web/src/pages/pull_live.rs b/crates/forge-web/src/pages/pull_live.rs new file mode 100644 index 0000000..2de68f1 --- /dev/null +++ b/crates/forge-web/src/pages/pull_live.rs @@ -0,0 +1,289 @@ +//! Live pull requests. The pull list (`/{o}/{r}/pulls`) follows [`Topic::PullList`]; a pull page +//! and its tabs (conversation, commits, files) follow [`Topic::Pull`]. The pages render `data-live` +//! with the URL of their stream, and a `changed` event re-renders them in place (see `nav.js`). +//! +//! Every write reaches a topic through one of these paths: +//! - A POST under `/{o}/{r}/pulls/...` (comment, review, label, merge, draft, branch, ...): the +//! [`PullWriteLayer`] bumps after the handler ran, so no route calls a bump itself. +//! - A commit status (CI or the status API): [`bump_head`], from `automerge::on_status`. +//! - A push, a mergeability refresh or an auto-merge: [`bump_repo_pulls`], from the call site. +//! +//! The bump helpers are the one place each topic is bumped from. A new write path calls one of +//! them; it does not bump a topic directly. +//! +//! What a stream compares is a fingerprint of what the page shows ([`pull_fingerprint`], +//! [`list_fingerprint`]). A bump that changes none of it sends nothing, so over-bumping is cheap. + +use forge_core::PullRequest; +use forge_core::store::Store; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::{method, uri}; +use topcoat::router::response::Response; +use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path, path_param, route}; + +use crate::live::{Topic, stream_changes}; +use crate::pages::issue_parts::parse_number; +use crate::pages::repo_ctx::load_repo; +use crate::state::AppState; + +path_param!(owner); +path_param!(repo); +path_param!(number); + +// Bumps. Each one wakes the streams of the topics it names; none of them reads more than the +// ids it needs. A failed lookup is logged and leaves the streams as they were. + +/// A write changed one pull request: its page and the list both follow it. +pub fn bump_pull(state: &AppState, repo_id: &str, issue_id: &str) { + state.live.bump(&Topic::Pull(issue_id.to_owned())); + bump_list(state, repo_id); +} + +/// A pull request was opened, or the list changed for another reason. Only the list follows. +pub fn bump_list(state: &AppState, repo_id: &str) { + state.live.bump(&Topic::PullList(repo_id.to_owned())); +} + +/// A change that may touch any pull of the repo (a push, a label or milestone edit, a merge run +/// by auto-merge): the list and every pull page of the repo. +pub async fn bump_repo_pulls(state: &AppState, repo_id: &str) { + bump_list(state, repo_id); + match state.store.pull_refs(repo_id).await { + Ok(refs) => { + for (issue_id, _) in refs { + state.live.bump(&Topic::Pull(issue_id)); + } + } + Err(e) => tracing::error!(error = %e, repo_id, "live: listing pulls to bump failed"), + } +} + +/// A commit status was written for `sha`: the pulls whose head is that commit, and the list. +pub async fn bump_head(state: &AppState, repo_id: &str, sha: &str) { + bump_list(state, repo_id); + match state.store.pulls_for_head_oid(repo_id, sha).await { + Ok(refs) => { + for (issue_id, _) in refs { + state.live.bump(&Topic::Pull(issue_id)); + } + } + Err(e) => { + tracing::error!(error = %e, repo_id, "live: listing pulls for a head to bump failed") + } + } +} + +// Fingerprints. Each reads what the page shows; any change to it changes the string. + +/// What one pull request page shows, as one string. `viewer` is the reader: a pending review is +/// the viewer's own and shows only to them. +pub(crate) async fn pull_fingerprint( + store: &Store, + repo_id: &str, + pr: &PullRequest, + viewer: Option<&str>, +) -> Result { + let id = pr.issue.id.as_str(); + let labels = store.issue_labels(id).await?; + let assignees = store.issue_assignees(id).await?; + let reviewers = store.requested_reviewers(id).await?; + let comments = store.list_comments(id).await?; + let reviews = store.list_reviews(id).await?; + let threads = store.review_threads(id, viewer).await?; + let statuses = store.statuses_for(repo_id, &pr.head_oid).await?; + + let mut lines = vec![ + format!( + "{:?} {:?} {} {} {}", + pr.issue.state, + pr.issue.state_reason, + pr.issue.title, + pr.issue.updated_at, + pr.issue.comment_count + ), + format!("body {}", pr.issue.body), + format!( + "draft {} head {} base {} {:?} {:?} {:?} {:?}", + pr.draft, + pr.head_oid, + pr.base_oid, + pr.mergeable, + pr.merged_at, + pr.merge_commit, + pr.conflict_files + ), + format!( + "branch {:?} {} auto {:?}", + pr.head_repo_id, pr.head_branch, pr.auto_merge + ), + format!("labels {labels:?}"), + format!("assignees {assignees:?}"), + format!("reviewers {reviewers:?}"), + ]; + lines.extend(comments.iter().map(|c| format!("comment {c:?}"))); + lines.extend(reviews.iter().map(|r| format!("review {r:?}"))); + lines.extend(threads.iter().map(|t| format!("thread {t:?}"))); + lines.extend(statuses.iter().map(|s| format!("status {s:?}"))); + Ok(lines.join("\n")) +} + +/// What the pull request list shows: the fingerprint of every pull of the repo, in number order. +pub(crate) async fn list_fingerprint( + store: &Store, + repo_id: &str, + viewer: Option<&str>, +) -> Result { + let mut parts = Vec::new(); + for (_, number) in store.pull_refs(repo_id).await? { + let Some(pr) = store.pull_by_number(repo_id, number).await? else { + continue; + }; + parts.push(pull_fingerprint(store, repo_id, &pr, viewer).await?); + } + Ok(parts.join("\n#\n")) +} + +/// The fingerprint of one pull request by number. `gone` once it no longer exists. +async fn pull_read( + store: &Store, + repo_id: &str, + number: i64, + viewer: Option<&str>, +) -> Result { + match store.pull_by_number(repo_id, number).await? { + Some(pr) => pull_fingerprint(store, repo_id, &pr, viewer).await, + None => Ok("gone".to_owned()), + } +} + +// Streams + +/// The pull list's change stream. Auth is the repo read check of the list page. +#[route(GET "/{owner}/{repo}/pulls/events")] +async fn pulls_events(cx: &Cx) -> Result { + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let state = app_context::(cx); + let topic = Topic::PullList(ctx.repo.id.clone()); + let store = state.store.clone(); + let repo_id = ctx.repo.id.clone(); + let viewer = ctx.viewer.as_ref().map(|(user, _)| user.id.clone()); + stream_changes(cx, &state.live, &topic, move || { + let store = store.clone(); + let repo_id = repo_id.clone(); + let viewer = viewer.clone(); + async move { list_fingerprint(&store, &repo_id, viewer.as_deref()).await } + }) + .await +} + +/// One pull request's change stream. Auth is the page's: the repo read check, then the pull. +#[route(GET "/{owner}/{repo}/pulls/{number}/events")] +async fn pull_events(cx: &Cx) -> Result { + let number = parse_number(path_param::(cx))?; + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let state = app_context::(cx); + let Some(pr) = state.store.pull_by_number(&ctx.repo.id, number).await? else { + return Err(topcoat::router::error::not_found().into()); + }; + let topic = Topic::Pull(pr.issue.id.clone()); + let store = state.store.clone(); + let repo_id = ctx.repo.id.clone(); + let viewer = ctx.viewer.as_ref().map(|(user, _)| user.id.clone()); + stream_changes(cx, &state.live, &topic, move || { + let store = store.clone(); + let repo_id = repo_id.clone(); + let viewer = viewer.clone(); + async move { pull_read(&store, &repo_id, number, viewer.as_deref()).await } + }) + .await +} + +// The write layer + +/// Which topic a POST under the pulls paths writes to. +enum Written { + /// A write to one pull request (`/{o}/{r}/pulls/{n}/...`). + Pull { + owner: String, + repo: String, + number: i64, + }, + /// A new pull request (`/{o}/{r}/pulls`). + New { owner: String, repo: String }, + /// A repo-wide change the pulls show: a label or milestone edit. + Repo { owner: String, repo: String }, +} + +/// The write a request makes to the pull side, when it is a POST that can change one. +fn written(cx: &Cx) -> Option { + if *method(cx) != Method::POST { + return None; + } + let path = uri(cx).path().to_owned(); + let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); + let [owner, repo, kind, rest @ ..] = parts.as_slice() else { + return None; + }; + let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned()); + match (*kind, rest) { + ("pulls", []) => Some(Written::New { owner, repo }), + ("pulls", [number, ..]) => number.parse().ok().map(|number| Written::Pull { + owner, + repo, + number, + }), + ("labels" | "milestones", _) => Some(Written::Repo { owner, repo }), + _ => None, + } +} + +/// Bumps the topics a write named, once the handler has run. The handler's result passes through +/// unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and agrees. +async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { + let target = written(cx); + let result = next.run(cx, body).await; + if let Some(target) = target { + bump_written(app_context::(cx), target).await; + } + result +} + +async fn bump_written(state: &AppState, target: Written) { + let (owner, name) = match &target { + Written::Pull { owner, repo, .. } + | Written::New { owner, repo } + | Written::Repo { owner, repo } => (owner.as_str(), repo.as_str()), + }; + let repo = match state.store.repo_by_owner_and_name(owner, name).await { + Ok(Some(repo)) => repo, + Ok(None) => return, + Err(e) => { + tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); + return; + } + }; + match target { + Written::Pull { number, .. } => match state.store.pull_by_number(&repo.id, number).await { + Ok(Some(pr)) => bump_pull(state, &repo.id, &pr.issue.id), + Ok(None) => {} + Err(e) => tracing::error!(error = %e, number, "live: loading the pull to bump failed"), + }, + Written::New { .. } => bump_list(state, &repo.id), + Written::Repo { .. } => bump_repo_pulls(state, &repo.id).await, + } +} + +/// Wraps every request. Only a POST under the pulls paths, or to a label or milestone route, does +/// anything. Registered on the public router in `boot.rs`, next to the other request layers. +pub struct PullWriteLayer; + +impl Layer for PullWriteLayer { + fn path(&self) -> Option<&Path> { + None + } + + fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { + Box::pin(bump_after_write(cx, body, next)) + } +} diff --git a/crates/forge-web/src/pages/pull_view.rs b/crates/forge-web/src/pages/pull_view.rs index 09d7e4e..d21dae8 100644 --- a/crates/forge-web/src/pages/pull_view.rs +++ b/crates/forge-web/src/pages/pull_view.rs @@ -188,6 +188,7 @@ pub(crate) async fn pull_header(frame: Frame) -> Result { let Frame { title, number, + href, state_class, state_text, author, @@ -200,6 +201,8 @@ pub(crate) async fn pull_header(frame: Frame) -> Result { .. } = frame; let number_label = format!("#{number}"); + // The header is on every pull tab, so each tab follows the pull's stream. + let live_url = format!("{href}/events"); let commits_text = g::commit_count_line(lang, commit_count); let wants = g::t(lang, K::ByWantsToMerge); let into = g::t(lang, K::ByInto); @@ -208,7 +211,7 @@ pub(crate) async fn pull_header(frame: Frame) -> Result { // Turkish puts the source branch first and the commit count before the verb. let turkish = matches!(lang, Lang::Tr); Ok(view! { -
+

(title.as_str()) " " (number_label.as_str())

+