Factory: open missing pull requests, scroll the board sideways again

An accepted issue whose pull request could not be opened (forge unreachable or
overloaded) offered neither merge nor close; the poll now opens it later.

The factory columns contained overscroll on both axes, so swipes and arrow keys
over a column never reached the board. Contain it vertically only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Richard ZinkandClaude Sonnet 5.5 committed 2026-11-27 14:56:49 +01:00
1 parent 96059d28eb
commit 955130fbc3
4 files changed
+110 -14

No files matched your search

+97 -13
View File
@@ -5,7 +5,7 @@
//! machine and the phase runs build on top of it.
use crate::app::App;
use crate::store::User;
use crate::store::{Store, User};
use anyhow::{Context, Result, bail};
use std::sync::Arc;
use serde::{Deserialize, Serialize};
@@ -751,6 +751,22 @@ impl Forge {
}
}
/// URL of the open pull request from `head`; opens one when there is none.
/// An earlier pull request may be merged or closed already (later commits would be lost):
/// only an open one counts.
pub async fn ensure_pr(&self, title: &str, body: &str, head: &str, base: &str) -> Result<String> {
if let Some(url) = self.open_pr(head).await.ok().flatten() {
return Ok(url);
}
let pr = self.create_pr(title, body, head, base).await?;
pr["html_url"].as_str().filter(|u| !u.is_empty()).map(String::from).context("the new pull request has no URL")
}
pub async fn default_branch(&self) -> Result<String> {
let repo = self.call(reqwest::Method::GET, self.rp(""), None).await?;
repo["default_branch"].as_str().filter(|b| !b.is_empty()).map(String::from).context("the repository has no default branch")
}
/// Organisations (GitLab: groups) the token's user can create repositories in.
pub async fn orgs(&self) -> Result<Vec<String>> {
let (url, keys): (String, [&str; 3]) = match self.kind {
@@ -1413,20 +1429,16 @@ async fn qa(app: Arc<App>, user: User, cfg: RepoCfg, issue: Value) {
return;
}
// Accepted: now the pull request is opened (unless one exists from an earlier run).
// An earlier pull request may be merged or closed already (later rework commits would be lost):
// only an open one counts.
let mut pr_url = g.open_pr(&branch).await.ok().flatten().unwrap_or_default();
if pr_url.is_empty() {
let built = row["note"].as_str().unwrap_or("").trim();
let body = format!("Built and accepted by the software factory for #{n}.\n\n**Build**\n{}\n\n**Acceptance** – {summary}\n\n{table}", if built.is_empty() { "–" } else { built });
match g.create_pr(&format!("#{n} {}", issue["title"].as_str().unwrap_or("")), &body, &branch, &base).await {
Ok(pr) => pr_url = pr["html_url"].as_str().unwrap_or("").to_string(),
Err(e) => tracing::warn!("factory {repo}#{n}: pull request: {e:#}"),
}
}
let built = row["note"].as_str().unwrap_or("").trim();
let body = format!("Built and accepted by the software factory for #{n}.\n\n**Build**\n{}\n\n**Acceptance** – {summary}\n\n{table}", if built.is_empty() { "–" } else { built });
// If this fails (forge unreachable), the poll opens the pull request later (open_missing_prs).
let pr_url = g.ensure_pr(&format!("#{n} {}", issue["title"].as_str().unwrap_or("")), &body, &branch, &base).await.unwrap_or_else(|e| {
tracing::warn!("factory {repo}#{n}: pull request: {e:#}");
String::new()
});
set(&[("state", json!("done")), ("attempts", json!(0)), ("note", json!(summary.clone())), ("pr_url", json!(pr_url.clone()))]);
let _ = g.set_labels(n as u64, &status_labels(&cfg, "done")).await;
let pr = if pr_url.is_empty() { format!(" Open a pull request from branch `{branch}` – the factory never merges.") } else { format!(" Review and merge the [pull request]({pr_url}) – the factory never merges.") };
let pr = if pr_url.is_empty() { format!(" The pull request for branch `{branch}` could not be opened yet; the factory tries again.") } else { format!(" Review and merge the [pull request]({pr_url}) – the factory never merges.") };
let caveat = if unv > 0 { format!(" **{unv} scenario(s) could not be verified** – check those yourself.") } else { String::new() };
bot_comment(&g, n as u64, &format!("**Acceptance: passed** ({pass} passed, {unv} unverified, {skipped} out of scope).{caveat} {summary}\n\n{table}{pr}")).await;
notify(&app, &user, &format!("Factory #{n}"), &format!("accepted ({pass} passed, {unv} unverified)"), n).await;
@@ -1467,6 +1479,30 @@ pub(crate) async fn alert(app: &App, repo: &str, n: i64, what: &str, detail: &st
crate::telegram::notify_user(app, owner, &text).await;
}
/// Accepted issues without a pull request (the forge was unreachable right after the acceptance):
/// the board offers neither merge nor close for them, so open it now.
async fn open_missing_prs(store: &Store, g: &Forge, cfg: &RepoCfg, owner: &str) -> Result<()> {
let missing = |r: &Value| {
r["repo"].as_str() == Some(cfg.url.as_str()) && r["state"].as_str() == Some("done") && r["merged"].as_bool() != Some(true) && r["pr_url"].as_str() == Some("") && r["branch"].as_str().is_some_and(|b| !b.is_empty())
};
for row in store.factory_issues(owner)?.into_iter().filter(|r| missing(r)) {
let n = issue_no(&row);
let branch = row["branch"].as_str().unwrap_or("");
let title = format!("#{n} {}", row["title"].as_str().unwrap_or(""));
let body = format!("Built and accepted by the software factory for #{n}.\n\n**Acceptance** – {}", row["note"].as_str().unwrap_or("").trim());
let opened = async { g.ensure_pr(&title, &body, branch, &g.default_branch().await?).await }.await;
match opened {
Ok(url) => {
store.factory_issue_set(&cfg.url, n, &[("pr_url", json!(url))])?;
let _ = g.set_labels(n as u64, &status_labels(cfg, "done")).await;
bot_comment(g, n as u64, &format!("**Acceptance: passed.** Review and merge the [pull request]({url}) – the factory never merges.")).await;
}
Err(e) => tracing::warn!("factory {}#{n}: pull request: {e:#}", cfg.url),
}
}
Ok(())
}
/// One pass over a repository: take up new issues, restart reviews after answers.
/// Who may file issues for the factory: the configured users, by default the token's owner.
pub async fn allowed_authors(g: &Forge, cfg: &RepoCfg) -> Result<Vec<String>> {
@@ -1566,6 +1602,9 @@ pub async fn poll_repo(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<()>
app.store.factory_issue_delete(&cfg.url, n)?;
}
}
if let Err(e) = open_missing_prs(&app.store, &g, cfg, &user.id).await {
tracing::warn!("factory {}: pull requests: {e:#}", cfg.url);
}
// Merged issues get their version and tag.
if let Err(e) = crate::factory_version::version_pass(app, user, cfg).await {
tracing::warn!("factory {}: versions: {e:#}", cfg.url);
@@ -1958,6 +1997,51 @@ mod tests {
serde_json::from_value(json!({"url": url, "token": "tok"})).unwrap()
}
#[tokio::test]
async fn opens_the_missing_pull_request_of_an_accepted_issue() {
use axum::{Json, Router, routing::get};
use std::sync::atomic::{AtomicUsize, Ordering};
// A forge that fails the first attempt to create the pull request.
let created = Arc::new(AtomicUsize::new(0));
let count = created.clone();
let app = Router::new()
.route("/api/v1/repos/o/r", get(|| async { Json(json!({"default_branch": "main"})) }))
.route(
"/api/v1/repos/o/r/pulls",
get(|| async { Json(json!([])) }).post(move |Json(b): Json<Value>| {
let count = count.clone();
async move {
assert_eq!((b["head"].as_str(), b["base"].as_str()), (Some("factory/issue-7"), Some("main")));
match count.fetch_add(1, Ordering::SeqCst) {
0 => Err(axum::http::StatusCode::INTERNAL_SERVER_ERROR),
_ => Ok(Json(json!({"number": 9, "html_url": "http://forge/o/r/pulls/9"}))),
}
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let cfg = repo(&format!("http://{}/o/r", listener.local_addr().unwrap()));
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let dir = std::env::temp_dir().join(format!("cc-factory-pr-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let store = Store::open(&dir.join("t.db")).unwrap();
store.factory_issue_add(&cfg.url, 7, "u", "Title", "me").unwrap();
store.factory_issue_set(&cfg.url, 7, &[("state", json!("done")), ("branch", json!("factory/issue-7"))]).unwrap();
let g = Forge::new(&cfg).unwrap();
let pr_url = || store.factory_issue(&cfg.url, 7).unwrap().unwrap()["pr_url"].as_str().unwrap().to_string();
open_missing_prs(&store, &g, &cfg, "u").await.unwrap();
assert_eq!(pr_url(), "");
open_missing_prs(&store, &g, &cfg, "u").await.unwrap();
assert_eq!(pr_url(), "http://forge/o/r/pulls/9");
// Done once: later polls leave it alone.
open_missing_prs(&store, &g, &cfg, "u").await.unwrap();
assert_eq!(created.load(Ordering::SeqCst), 2);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn parses_repo_urls() {
let t = |a: &str, b: &str, c: &str| (a.to_string(), b.to_string(), c.to_string());