From 391db439492be86900eeff5184418c183ba16992 Mon Sep 17 00:00:00 2001 From: Richard Zink Date: Fri, 20 Nov 2026 13:23:52 +0100 Subject: [PATCH] Factory: merge and close buttons on the issue card, enforced order Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 6 ++++ README.md | 3 +- server/src/api.rs | 22 ++++++++++++- server/src/factory_version.rs | 2 ++ server/src/store.rs | 7 +++-- web/src/components/Factory.tsx | 57 +++++++++++++++++++++++++++------- web/src/i18n/de.ts | 2 ++ web/src/i18n/en.ts | 2 ++ web/src/styles.css | 32 +++++++++++++++++++ web/src/whatsnew.ts | 4 +++ 10 files changed, 121 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3872941..1e38418 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/); until 1.0, minor versions may contain breaking changes. +## [Unreleased] + +### Changed + +- **Factory: merge and close on the issue card.** A finished issue shows a *Merge* button on its card once the acceptance has passed (the pull request is open); after the merge the card shows *Close*. Before that neither button is shown. The server enforces the order: a pull request is merged only when the acceptance passed, an issue is closed only when its pull request is merged (a merge done on the forge itself counts). The issue also gets its version and tag right after a merge instead of at the next poll. + ## [v202611-00073] – 2026-11-20 ### Added diff --git a/README.md b/README.md index e8575cc..fb3e93d 100644 --- a/README.md +++ b/README.md @@ -292,7 +292,8 @@ the server. On *pass* the factory opens the pull request (if none is open) and comments a result table in the issue. On *fail* the issue goes back to the build with the findings (*rework*). 4. **Done, merge, version.** You review the pull request in the factory (diff, description) and - merge it there. The factory then pulls the merge, gives the issue its version, commits + merge it there – on the page or with the *Merge* button of the issue card, which appears once + the acceptance has passed (closing an issue by hand is possible only after its merge). The factory then pulls the merge, gives the issue its version, commits `VERSION`, pushes an annotated tag, comments on the issue and closes it. Issue text is treated as data, never as instructions for the factory itself. diff --git a/server/src/api.rs b/server/src/api.rs index c432fae..9199261 100644 --- a/server/src/api.rs +++ b/server/src/api.rs @@ -3011,6 +3011,15 @@ async fn factory_close_issue(Extension(user): Extension, State(app): State return Err(ApiError(StatusCode::BAD_REQUEST, "only finished issues can be closed here".into())); } let bad = |e: anyhow::Error| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")); + // Closing comes after the merge. A merge done on the forge itself counts too: ask the forge when we do not know yet. + if row["merged"].as_bool() != Some(true) { + let pr_n: u64 = row["pr_url"].as_str().unwrap_or("").trim_end_matches('/').rsplit('/').next().and_then(|n| n.parse().ok()).unwrap_or(0); + let merged = pr_n > 0 && g.pr(pr_n).await.map(|p| p["state"].as_str() == Some("merged")).unwrap_or(false); + if !merged { + return Err(ApiError(StatusCode::BAD_REQUEST, "merge the pull request first".into())); + } + app.store.factory_issue_set(&b.repo, b.number, &[("merged", json!(1))])?; + } let text = if b.comment.trim().is_empty() { "Closed.".to_string() } else { b.comment.trim().to_string() }; g.comment(b.number as u64, &format!("{}\n**Closed** by {}: {text}", crate::factory::BOT, user.username)).await.map_err(bad)?; g.close_issue(b.number as u64).await.map_err(bad)?; @@ -3072,6 +3081,10 @@ struct MergePr { /// Merge the pull request of an issue – only on the user's own click in the factory page. async fn factory_pr_merge(Extension(user): Extension, State(app): State, headers: axum::http::HeaderMap, Json(b): Json) -> ApiResult { let (g, row) = factory_issue_forge(&app, &user, &b.repo, b.number)?; + // Merging comes after a positive acceptance (the issue is "done"). + if row["state"].as_str() != Some("done") { + return Err(ApiError(StatusCode::BAD_REQUEST, "the pull request can be merged once the acceptance has passed".into())); + } let method = if b.method.is_empty() { "merge" } else { b.method.as_str() }; if !["merge", "squash", "rebase"].contains(&method) { return Err(ApiError(StatusCode::BAD_REQUEST, "unknown merge method".into())); @@ -3082,8 +3095,15 @@ async fn factory_pr_merge(Extension(user): Extension, State(app): State, user: &User, cfg: &RepoCfg) -> Result< if pr["state"].as_str() != Some("merged") { continue; } + // Remember it at once: if the version step below fails, the issue can still be closed by hand. + let _ = app.store.factory_issue_set(&cfg.url, n, &[("merged", json!(1))]); let title = r["title"].as_str().unwrap_or("").to_string(); let others: Vec = g.open_issue_titles().await?.into_iter().filter(|(num, _)| *num != n).map(|(_, t)| t).collect(); let dir = checkout(app, user, cfg).await?; diff --git a/server/src/store.rs b/server/src/store.rs index 57e2a75..3b40771 100644 --- a/server/src/store.rs +++ b/server/src/store.rs @@ -262,6 +262,7 @@ impl Store { ("images", "blob", "ALTER TABLE images ADD COLUMN blob TEXT"), ("usage", "allowance", "ALTER TABLE usage ADD COLUMN allowance REAL"), ("factory_issues", "version", "ALTER TABLE factory_issues ADD COLUMN version TEXT NOT NULL DEFAULT ''"), + ("factory_issues", "merged", "ALTER TABLE factory_issues ADD COLUMN merged INTEGER NOT NULL DEFAULT 0"), ] { let exists: bool = conn .prepare(&format!("SELECT 1 FROM pragma_table_info('{table}') WHERE name = ?1"))? @@ -1489,8 +1490,8 @@ impl Store { pub fn factory_issue(&self, repo: &str, number: i64) -> Result> { let conn = self.conn.lock().unwrap(); Ok(conn - .query_row("SELECT title, author, state, attempts, rounds, last_comment, scenarios, branch, pr_url, note, created_at, updated_at, owner_id, version FROM factory_issues WHERE repo_url = ?1 AND number = ?2", params![repo, number], |r| { - Ok(json!({"repo": repo, "number": number, "title": r.get::<_, String>(0)?, "author": r.get::<_, String>(1)?, "state": r.get::<_, String>(2)?, "attempts": r.get::<_, i64>(3)?, "rounds": r.get::<_, i64>(4)?, "last_comment": r.get::<_, i64>(5)?, "scenarios": r.get::<_, String>(6)?, "branch": r.get::<_, String>(7)?, "pr_url": r.get::<_, String>(8)?, "note": r.get::<_, String>(9)?, "created_at": r.get::<_, i64>(10)?, "updated_at": r.get::<_, i64>(11)?, "owner_id": r.get::<_, String>(12)?, "version": r.get::<_, String>(13)?})) + .query_row("SELECT title, author, state, attempts, rounds, last_comment, scenarios, branch, pr_url, note, created_at, updated_at, owner_id, version, merged FROM factory_issues WHERE repo_url = ?1 AND number = ?2", params![repo, number], |r| { + Ok(json!({"repo": repo, "number": number, "title": r.get::<_, String>(0)?, "author": r.get::<_, String>(1)?, "state": r.get::<_, String>(2)?, "attempts": r.get::<_, i64>(3)?, "rounds": r.get::<_, i64>(4)?, "last_comment": r.get::<_, i64>(5)?, "scenarios": r.get::<_, String>(6)?, "branch": r.get::<_, String>(7)?, "pr_url": r.get::<_, String>(8)?, "note": r.get::<_, String>(9)?, "created_at": r.get::<_, i64>(10)?, "updated_at": r.get::<_, i64>(11)?, "owner_id": r.get::<_, String>(12)?, "version": r.get::<_, String>(13)?, "merged": r.get::<_, i64>(14)? != 0})) }) .optional()?) } @@ -1512,7 +1513,7 @@ impl Store { /// Update the given columns (whitelisted) of an issue. pub fn factory_issue_set(&self, repo: &str, number: i64, fields: &[(&str, Value)]) -> Result<()> { - const COLS: [&str; 11] = ["title", "state", "attempts", "rounds", "last_comment", "scenarios", "branch", "pr_url", "note", "author", "version"]; + const COLS: [&str; 12] = ["title", "state", "attempts", "rounds", "last_comment", "scenarios", "branch", "pr_url", "note", "author", "version", "merged"]; let conn = self.conn.lock().unwrap(); for (k, v) in fields { if !COLS.contains(k) { diff --git a/web/src/components/Factory.tsx b/web/src/components/Factory.tsx index 282ba6f..b1ba928 100644 --- a/web/src/components/Factory.tsx +++ b/web/src/components/Factory.tsx @@ -78,6 +78,8 @@ interface Issue { branch: string; rounds: number; /** Newest phase chat that still exists. */ + /** The pull request is merged (merging comes after a positive acceptance, closing after the merge). */ + merged?: boolean; chat_session?: string; chat_phase?: Phase; created_at: number; @@ -188,6 +190,20 @@ export function Factory({ onMenu, overlayId }: { onMenu: () => void; overlayId?: ); } +/** A button inside an issue card (the card itself is a button, so this is a span with the button role). */ +function CardAction({ children, onClick, title, primary, disabled }: { children: React.ReactNode; onClick: () => void; title?: string; primary?: boolean; disabled?: boolean }) { + const run = (e: React.SyntheticEvent) => { + e.stopPropagation(); + e.preventDefault(); + if (!disabled) onClick(); + }; + return ( + (e.key === "Enter" || e.key === " ") && run(e)}> + {children} + + ); +} + /** The factory's main switch, coloured by state: green = running, yellow = stopping, red = stopped. */ function PowerSwitch({ power, onToggle }: { power: Power; onToggle: (on: boolean) => void }) { const t = useT(); @@ -402,20 +418,24 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) { setBusy(false); } }; - const mergePr = async () => { - if (!selected || !pr) return; - if (!(await confirmDialog({ message: t("factory.mergeConfirm", { n: pr.number, method: t(`factory.merge.${prMethod}` as any) }) }))) return; + const prNo = (i: Issue) => Number(i.pr_url.replace(/\/$/, "").split("/").pop()) || 0; + /** Merge the pull request of an issue; only offered once the acceptance has passed. */ + const mergeIssue = async (i: Issue, n = prNo(i)) => { + if (!n || i.state !== "done") return; + if (!(await confirmDialog({ message: t("factory.mergeConfirm", { n, method: t(`factory.merge.${prMethod}` as any) }) }))) return; setBusy(true); try { - await post("/factory/issues/pr/merge", { repo: selected.repo, number: selected.number, pr: pr.number, method: prMethod }); + await post("/factory/issues/pr/merge", { repo: i.repo, number: i.number, pr: n, method: prMethod }); toast(t("factory.merged")); await loadPr(); + await reload(); } catch (e: any) { toast(e.message); } finally { setBusy(false); } }; + const mergePr = () => (selected && pr ? mergeIssue(selected, pr.number) : Promise.resolve()); const removeIssue = async () => { if (!selected) return; if (!(await confirmDialog({ message: t("factory.removeConfirm", { n: selected.number }), confirmLabel: t("factory.remove"), danger: true }))) return; @@ -430,15 +450,16 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) { setBusy(false); } }; - const closeIssue = async () => { - if (!selected) return; - const comment = await promptDialog({ title: t("factory.closeTitle"), message: t("factory.closeMsg", { n: selected.number }), defaultValue: t("factory.closeDefault"), confirmLabel: t("factory.close") }); + /** Close an issue; only offered once its pull request is merged. */ + const closeIssueOf = async (i: Issue) => { + if (i.state !== "done" || !i.merged) return; + const comment = await promptDialog({ title: t("factory.closeTitle"), message: t("factory.closeMsg", { n: i.number }), defaultValue: t("factory.closeDefault"), confirmLabel: t("factory.close") }); if (comment === null) return; setBusy(true); try { - await post("/factory/issues/close", { repo: selected.repo, number: selected.number, comment }); + await post("/factory/issues/close", { repo: i.repo, number: i.number, comment }); toast(t("factory.closed"), "success"); - setSel(""); + if (selected && selected.number === i.number && selected.repo === i.repo) setSel(""); await reload(); } catch (e: any) { toast(e.message); @@ -446,6 +467,7 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) { setBusy(false); } }; + const closeIssue = () => (selected ? closeIssueOf(selected) : Promise.resolve()); const phaseRunning = !!selected && ["review", "building", "testing"].includes(selected.state); /** Master switch: a soft stop – no new agent starts, running ones finish their phase. */ const setPower = async (on: boolean) => { @@ -623,6 +645,19 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) { )} {tokens > 0 && {fmtCompact(tokens)} {t("factory.tokens")}} + {i.state === "done" && (i.merged || prNo(i) > 0) && ( + + {!i.merged ? ( + void mergeIssue(i)}> + {t("factory.mergeBtn")} + + ) : ( + void closeIssueOf(i)}> + {t("factory.close")} + + )} + + )} ); })} @@ -658,7 +693,7 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) { {t("factory.remove")} )} - {selected && selected.state === "done" && ( + {selected && selected.state === "done" && selected.merged && ( @@ -691,7 +726,7 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) { )} - {pr.state === "open" && ( + {pr.state === "open" && selected?.state === "done" && ( <>