diff --git a/CHANGELOG.md b/CHANGELOG.md index b756d78..3f067f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,24 @@ All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/); until 1.0, minor versions may contain breaking changes. +## [Unreleased] + +### Added + +- **Factory: show and approve pull requests.** Selecting an issue shows its open pull request (state, + conflicts, files, +/− lines, link) with "Approve and merge" (merge commit, squash or rebase). Merging only + happens on your click after a confirmation; the factory itself still never merges. +- **Factory: plan with a model and file the issues.** "Plan a feature" starts a chat that works out a new + feature with you; "Cut a milestone" lets a model cut a milestone of the spec into numbered deliverables + ("M2.1 – …"). The chat reads the repository and ends with an issue list; a dialog lets you tick and edit + the issues, which are then created on the forge with `Spec:` and `Scope:` lines and the prerequisites. + They get the factory label only if you ask for it, so you can start them one after the other. + +### Fixed + +- An accepted rework build now gets a new pull request when the earlier one was merged or closed already; + before, the commits of the rework rounds stayed on the branch without any pull request. + ## [v202611-00046] – 2026-11-16 ### Changed diff --git a/server/src/api.rs b/server/src/api.rs index 107964c..98644a8 100644 --- a/server/src/api.rs +++ b/server/src/api.rs @@ -164,6 +164,11 @@ pub fn router(app: AppState) -> Router { .route("/factory/overview", get(factory_overview)) .route("/factory/poll", post(factory_poll)) .route("/factory/issues/restart", post(factory_restart)) + .route("/factory/issue-chats", post(factory_new_issue_chat)) + .route("/factory/issue-chats/{id}", get(factory_issue_chat)) + .route("/factory/issue-chats/{id}/create", post(factory_create_issues)) + .route("/factory/issues/pr", get(factory_pr)) + .route("/factory/issues/pr/merge", post(factory_pr_merge)) .route("/account/factory/connection/test", post(test_factory_connection)) .route("/factory/drafts", post(factory_new_draft)) .route("/factory/drafts/{id}", get(factory_draft)) @@ -2653,6 +2658,128 @@ async fn factory_poll(Extension(user): Extension, State(app): State, +} + +fn factory_repo_cfg(app: &AppState, user: &User, repo: &str) -> Result { + let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?; + s.repos.iter().find(|r| r.url == repo).map(|r| s.resolve(r)).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "the repository is not configured".into())) +} + +/// Start a chat that works out a feature or cuts a milestone into issues. +async fn factory_new_issue_chat(Extension(user): Extension, State(app): State, Json(b): Json) -> ApiResult { + if !["feature", "slice"].contains(&b.mode.as_str()) { + return Err(ApiError(StatusCode::BAD_REQUEST, "unknown mode".into())); + } + let cfg = factory_repo_cfg(&app, &user, &b.repo)?; + let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?; + let model = b.model.filter(|m| !m.is_empty()).unwrap_or(s.defaults.spec_model.clone()); + let session = crate::factory::start_issue_chat(&app, &user, &cfg, &model, &b.mode, &b.topic).await.map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?; + Ok(Json(json!(session))) +} + +fn issue_chat_session(app: &AppState, user: &User, id: &str) -> Result<(String, std::path::PathBuf), ApiError> { + let session = app.session(id).map_err(|_| ApiError(StatusCode::NOT_FOUND, "unknown chat".into()))?; + let dir = crate::factory::issue_chat_of(app, user, &session).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "not an issue chat".into()))?; + let repo = std::fs::read_to_string(dir.join("repo.txt")).unwrap_or_default().trim().to_string(); + Ok((repo, dir)) +} + +/// The issue list the model proposed in its last message. +async fn factory_issue_chat(Extension(user): Extension, State(app): State, Path(id): Path) -> ApiResult { + let (repo, _) = issue_chat_session(&app, &user, &id)?; + Ok(Json(json!({"repo": repo, "proposal": crate::factory::issue_proposal(&app, &id)}))) +} + +#[derive(Deserialize)] +struct CreateIssues { + spec: String, + issues: Vec, + /// Give the issues the factory label so the workflow starts right away. + #[serde(default)] + start: bool, +} + +/// Create the (possibly edited) issues of a proposal on the forge. +async fn factory_create_issues(Extension(user): Extension, State(app): State, headers: axum::http::HeaderMap, Path(id): Path, Json(b): Json) -> ApiResult { + let (repo, _) = issue_chat_session(&app, &user, &id)?; + let cfg = factory_repo_cfg(&app, &user, &repo)?; + if b.issues.is_empty() || b.issues.len() > 100 { + return Err(ApiError(StatusCode::BAD_REQUEST, "choose between 1 and 100 issues".into())); + } + let created = crate::factory::create_issues(&cfg, &b.spec, &b.issues, b.start).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?; + app.audit(Some(&user), "factory.issues.create", &format!("{repo} ({} issues)", created.len()), &crate::auth::client_ip(&headers)); + if b.start { + let _ = crate::factory::poll_repo(&app, &user, &cfg).await; + } + Ok(Json(json!({"created": created}))) +} + +#[derive(Deserialize)] +struct PrQuery { + repo: String, + number: i64, +} + +/// The issue's forge client and row; the issue must belong to the user. +fn factory_issue_forge(app: &AppState, user: &User, repo: &str, number: i64) -> Result<(crate::factory::Forge, Value), ApiError> { + let row = app.store.factory_issue(repo, number)?.filter(|r| r["owner_id"].as_str() == Some(user.id.as_str())).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "unknown issue".into()))?; + let s: crate::factory::FactorySettings = app.store.user_setting(&user.id, "factory")?; + let cfg = s.repos.iter().find(|r| r.url == repo).map(|r| s.resolve(r)).ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "the repository is not configured".into()))?; + let g = crate::factory::Forge::new(&cfg).map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("{e:#}")))?; + Ok((g, row)) +} + +/// The pull request of an issue: the open one from its branch, else the one on record. +async fn factory_pr(Extension(user): Extension, State(app): State, Query(q): Query) -> ApiResult { + let (g, row) = factory_issue_forge(&app, &user, &q.repo, q.number)?; + let bad = |e: anyhow::Error| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")); + let branch = row["branch"].as_str().unwrap_or(""); + let mut pr = if branch.is_empty() { None } else { g.find_pr(branch).await.map_err(bad)? }; + if pr.is_none() { + let n: u64 = row["pr_url"].as_str().unwrap_or("").trim_end_matches('/').rsplit('/').next().and_then(|n| n.parse().ok()).unwrap_or(0); + if n > 0 { + pr = g.pr(n).await.ok(); + } + } + Ok(Json(json!({"pr": pr}))) +} + +#[derive(Deserialize)] +struct MergePr { + repo: String, + number: i64, + pr: u64, + #[serde(default)] + method: String, +} + +/// 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)?; + 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())); + } + let pr = g.pr(b.pr).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?; + // Only the pull request of this issue's own branch may be merged from here. + if pr["head"].as_str() != row["branch"].as_str() || pr["state"].as_str() != Some("open") { + return Err(ApiError(StatusCode::BAD_REQUEST, "this is not the open pull request of the issue".into())); + } + g.merge_pr(b.pr, method).await.map_err(|e| ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}")))?; + app.store.factory_issue_set(&b.repo, b.number, &[("pr_url", json!(pr["html_url"].as_str().unwrap_or("")))])?; + app.audit(Some(&user), "factory.pr.merge", &format!("{}#{}", b.repo, b.number), &crate::auth::client_ip(&headers)); + Ok(Json(json!({"ok": true}))) +} + #[derive(Deserialize)] struct RestartIssue { repo: String, diff --git a/server/src/factory.rs b/server/src/factory.rs index 4b1074a..b1a5037 100644 --- a/server/src/factory.rs +++ b/server/src/factory.rs @@ -504,6 +504,64 @@ impl Forge { } /// Open a pull request (GitLab: merge request); returns {number, html_url}. + /// A pull/merge request in one shape: number, html_url, title, state (open|merged|closed), + /// mergeable, changed_files, additions, deletions, head. + fn norm_pr(&self, v: &Value) -> Value { + match self.kind { + Kind::Gitlab => json!({ + "number": v["iid"], "html_url": v["web_url"], "title": v["title"], + "state": match v["state"].as_str() { Some("opened") => "open", Some("merged") => "merged", _ => "closed" }, + "mergeable": v["merge_status"].as_str() == Some("can_be_merged"), + "changed_files": v["changes_count"], "additions": Value::Null, "deletions": Value::Null, "head": v["source_branch"], + }), + _ => json!({ + "number": v["number"], "html_url": v["html_url"], "title": v["title"], + "state": if v["merged"].as_bool() == Some(true) || v["merged_at"].is_string() { json!("merged") } else if v["state"].as_str() == Some("open") { json!("open") } else { json!("closed") }, + "mergeable": v["mergeable"], "changed_files": v["changed_files"], "additions": v["additions"], "deletions": v["deletions"], "head": v["head"]["ref"], + }), + } + } + + pub async fn pr(&self, number: u64) -> Result { + let path = if self.kind == Kind::Gitlab { format!("/merge_requests/{number}") } else { format!("/pulls/{number}") }; + let v = self.call(reqwest::Method::GET, self.rp(&path), None).await?; + Ok(self.norm_pr(&v)) + } + + /// The open pull request from a branch with its details, if there is one. + pub async fn find_pr(&self, head: &str) -> Result> { + let url = self.open_pr(head).await?; + let Some(url) = url else { return Ok(None) }; + let n: u64 = url.trim_end_matches('/').rsplit('/').next().and_then(|n| n.parse().ok()).unwrap_or(0); + if n == 0 { + return Ok(None); + } + Ok(Some(self.pr(n).await?)) + } + + /// Merge a pull request (method: merge, squash or rebase). Only ever called on the user's click. + pub async fn merge_pr(&self, number: u64, method: &str) -> Result<()> { + match self.kind { + Kind::Gitea => self.call(reqwest::Method::POST, self.rp(&format!("/pulls/{number}/merge")), Some(json!({"Do": method}))).await.map(|_| ()), + Kind::Github => self.call(reqwest::Method::PUT, self.rp(&format!("/pulls/{number}/merge")), Some(json!({"merge_method": method}))).await.map(|_| ()), + Kind::Gitlab => self.call(reqwest::Method::PUT, self.rp(&format!("/merge_requests/{number}/merge")), Some(json!({"squash": method == "squash"}))).await.map(|_| ()), + } + } + + /// URL of the open pull/merge request from this branch, if there is one. + pub async fn open_pr(&self, head: &str) -> Result> { + match self.kind { + Kind::Gitlab => { + let v = self.call(reqwest::Method::GET, self.rp(&format!("/merge_requests?state=opened&source_branch={}", urlenc(head))), None).await?; + Ok(v.as_array().and_then(|a| a.first()).and_then(|m| m["web_url"].as_str()).map(String::from)) + } + _ => { + let v = self.call(reqwest::Method::GET, self.rp("/pulls?state=open&per_page=100&limit=100"), None).await?; + Ok(v.as_array().and_then(|a| a.iter().find(|p| p["head"]["ref"].as_str() == Some(head))).and_then(|p| p["html_url"].as_str()).map(String::from)) + } + } + } + pub async fn create_pr(&self, title: &str, body: &str, head: &str, base: &str) -> Result { match self.kind { Kind::Gitlab => { @@ -1082,7 +1140,9 @@ async fn qa(app: Arc, user: User, cfg: RepoCfg, issue: Value) { return; } // Accepted: now the pull request is opened (unless one exists from an earlier run). - let mut pr_url = row["pr_url"].as_str().unwrap_or("").to_string(); + // 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 }); @@ -1201,6 +1261,135 @@ pub fn spawn(app: Arc) { } +// --- issue chats: work out features / cut milestones with a model and file the issues --------- + +/// Instructions of an issue chat. `{repo_dir}` is the checkout (read-only for the chat), `{mode}` the task. +pub const ISSUE_INSTRUCTIONS: &str = r#"You are the planning stage of a software factory. Autonomous agents will later review, build and accept every issue you help to write – without being able to ask questions. Answer in the user's language. + +Your working directory is a scratch folder. The project is checked out at {repo_dir} (read it, never change anything in it; do not create issues or touch the forge yourself). Its specification lives under docs/specs/ in that checkout. + +{mode} + +Rules for every issue you propose: +- One issue is one deliverable that one agent can build and check in about an hour: a single function or a few closely related ones, never a whole milestone. +- Give it a short title WITHOUT numbering prefix unless you are cutting a numbered milestone (then "M2.3 – Title"), a description of what must exist afterwards, and checkable facts (what someone sees in the running app). Do not repeat the spec; name the spec sections instead. +- `scope` is one line naming exactly what is in scope (e.g. "M2.3 – Quotas (spec section 12)"); everything else in the spec is out of scope for that issue. +- `depends` names the deliverables that must be merged first, or "none". +- Order the issues so that each builds on the earlier ones. Point out gaps and contradictions in the spec instead of guessing. + +When the user says the plan is done, end your message with exactly one fenced json block and nothing after it: +```json +{"decision": "issues", "spec": "docs/specs/.md", "issues": [{"title": "…", "description": "…", "scope": "…", "depends": "…"}]} +``` +The user reviews the list in a dialog and the issues are created from it."#; + +/// The two tasks of an issue chat. +fn issue_mode(mode: &str, topic: &str) -> String { + if mode == "slice" { + format!("Task: cut the milestone \"{topic}\" of the specification into single numbered deliverables (titles like \"{topic}.1 – …\", \"{topic}.2 – …\"). Read the milestone and every feature it names, check what the code already has, and propose the smallest sensible slices in build order. Show the user the list first and adjust it together before you finish.") + } else { + format!("Task: work out a new feature together with the user{}. Interview step by step (a few questions at a time): goal, users, behaviour and edge cases, how it fits the existing code, what is out of scope, how someone checks that it works. Then propose one or more issues; split a larger feature into deliverables that can be built one after the other.", if topic.trim().is_empty() { String::new() } else { format!(" – starting point: {topic}") }) + } +} + +/// Folder of an issue chat: //_issues/ (holds repo.txt with the repository URL). +pub fn issue_chat_dir(app: &App, user: &User, id: &str) -> Result { + let home = app.factory_home(user).context("the factory area is not mounted (FACTORY_DIR → /factory)")?; + Ok(home.join("_issues").join(id)) +} + +/// Is this chat an issue chat of the user? Returns its folder. +pub fn issue_chat_of(app: &App, user: &User, session: &crate::types::Session) -> Option { + let home = app.factory_home(user)?.join("_issues"); + let cwd = std::path::PathBuf::from(&session.cwd); + (session.owner_id.as_deref() == Some(&user.id) && cwd.starts_with(&home) && cwd != home).then_some(cwd) +} + +/// Start an issue chat for a repository. mode: "feature" or "slice" (topic = the milestone). +pub async fn start_issue_chat(app: &Arc, user: &User, cfg: &RepoCfg, model: &str, mode: &str, topic: &str) -> Result { + if mode == "slice" && topic.trim().is_empty() { + bail!("name the milestone to cut (e.g. M2)"); + } + let repo = checkout(app, user, cfg).await?; + let id = crate::types::new_id(); + let dir = issue_chat_dir(app, user, &id)?; + std::fs::create_dir_all(&dir)?; + std::fs::write(dir.join("repo.txt"), &cfg.url)?; + let model = Some(model.to_string()).filter(|m| !m.is_empty()).or_else(|| Some(app.config().server.default_model.clone()).filter(|m| !m.is_empty())).or_else(|| app.registry().first_model()).context("no model configured")?; + let (_, _, name) = cfg.parts()?; + let now = crate::types::now_ms(); + let session = crate::types::Session { + id, + title: format!("Factory – issues – {name}"), + cwd: dir.display().to_string(), + model, + agent: "build".into(), + permission_mode: "default".into(), + parent_id: None, + owner_id: Some(user.id.clone()), + created_at: now, + updated_at: now, + todos: Value::Null, + last_usage: None, + clean_room: None, + phase: None, + worktree: None, + pinned: false, + archived: false, + folder: Some(FACTORY_FOLDER.to_string()), + instructions: ISSUE_INSTRUCTIONS.replace("{repo_dir}", &repo.display().to_string()).replace("{mode}", &issue_mode(mode, topic.trim())), + telegram_quiet: true, + summary: String::new(), + color: None, + icon: None, + }; + app.save_session(session) +} + +/// The issue list the model ended its last message with. +pub fn issue_proposal(app: &App, session_id: &str) -> Option { + parse_result(&last_text(app, session_id)).filter(|v| v["decision"] == "issues" && v["issues"].is_array()) +} + +/// Body of an issue made from a proposal: the description plus the lines the factory reads. +pub fn issue_body(description: &str, spec: &str, scope: &str, depends: &str) -> String { + let mut body = description.trim().to_string(); + body.push_str(&format!("\n\nSpec: {spec}")); + if !scope.trim().is_empty() { + body.push_str(&format!("\nScope: {}", scope.trim().replace('\n', " "))); + } + let d = depends.trim(); + if !d.is_empty() && !d.eq_ignore_ascii_case("none") && !d.eq_ignore_ascii_case("keine") { + body.push_str(&format!("\n\nPrerequisite: {d} – merge it first, then start this issue.")); + } + body.push('\n'); + body +} + +/// Create the issues on the forge; with `start` they get the factory label (the workflow starts). +pub async fn create_issues(cfg: &RepoCfg, spec: &str, issues: &[Value], start: bool) -> Result> { + let spec = spec.trim(); + if spec.is_empty() || spec.starts_with('/') || spec.contains("..") { + bail!("the spec path is missing or invalid"); + } + let g = Forge::new(cfg)?; + if start { + g.ensure_labels().await?; + } + let mut out = Vec::new(); + for i in issues { + let title = i["title"].as_str().unwrap_or("").trim(); + if title.is_empty() { + bail!("an issue has no title"); + } + let body = issue_body(i["description"].as_str().unwrap_or(""), spec, i["scope"].as_str().unwrap_or(""), i["depends"].as_str().unwrap_or("")); + let labels = if start { vec![cfg.label.clone()] } else { Vec::new() }; + let r = g.create_issue(title, &body, &labels).await?; + out.push(json!({"number": issue_no(&r), "title": title, "url": r["html_url"]})); + } + Ok(out) +} + // --- spec chat and project creation --------------------------------------------------- /// Instructions of the chat in which the user writes a spec together with a model. @@ -1495,6 +1684,19 @@ mod tests { assert!(SPEC_INSTRUCTIONS.contains("setup.json")); } + #[test] + fn issue_body_carries_the_factory_lines() { + let b = issue_body("Do X.", "docs/specs/a.md", "M2.1 – X (section 3)", "M1.4"); + assert!(b.contains("Spec: docs/specs/a.md") && b.contains("Scope: M2.1 – X (section 3)") && b.contains("Prerequisite: M1.4")); + assert!(!issue_body("Do X.", "a.md", "", "none").contains("Prerequisite")); + assert_eq!(spec_path(&json!({"body": b})).as_deref(), Some("docs/specs/a.md")); + assert!(issue_mode("slice", "M2").contains("\"M2.1 – …\"")); + let p = ISSUE_INSTRUCTIONS.replace("{repo_dir}", "/f/r"); + assert!(p.contains("/f/r") && p.contains("\"decision\": \"issues\"")); + let t = "Fertig.\n```json\n{\"decision\": \"issues\", \"spec\": \"a.md\", \"issues\": []}\n```"; + assert!(parse_result(t).is_some_and(|v| v["decision"] == "issues")); + } + #[test] fn encodes_labels() { assert_eq!(urlenc("factory:qa"), "factory%3Aqa"); diff --git a/web/src/components/ChatView.tsx b/web/src/components/ChatView.tsx index b7ec711..b63adc7 100644 --- a/web/src/components/ChatView.tsx +++ b/web/src/components/ChatView.tsx @@ -1,4 +1,4 @@ -import { DraftBar, isDraftChat } from "./FactoryDraft"; +import { DraftBar, IssueBar, isDraftChat, isIssueChat } from "./FactoryDraft"; import { takePrefill } from "../share"; import { Icon } from "./Icon"; import { FileChip, FileFigure, fileType, imageSize, imageSrc } from "./FileFigure"; @@ -1091,6 +1091,7 @@ export function ChatView({ sessionId, onMenu, onClosePane }: { sessionId: string {sharing && setSharing(false)} />} {rewinding && setRewinding(undefined)} />} {!readOnly && isDraftChat(session.cwd) && } + {!readOnly && isIssueChat(session.cwd) && } {!readOnly && } {!readOnly && } {readOnly ? ( diff --git a/web/src/components/Factory.tsx b/web/src/components/Factory.tsx index bdf47eb..12074cd 100644 --- a/web/src/components/Factory.tsx +++ b/web/src/components/Factory.tsx @@ -2,11 +2,23 @@ import { useEffect, useMemo, useState } from "react"; import { get, post, put } from "../api"; import { fmtCompact, fmtCost, fmtRelative, useT } from "../i18n"; import { navigate } from "../router"; -import { confirmDialog, toast } from "../dialogs"; +import { choiceDialog, confirmDialog, promptDialog, toast } from "../dialogs"; import { Icon } from "./Icon"; import { Spinner } from "./Activity"; import { ModelSelect } from "./ModelSelect"; +interface PrInfo { + number: number; + html_url: string; + title: string; + state: "open" | "merged" | "closed"; + mergeable: boolean | null; + changed_files: number | null; + additions: number | null; + deletions: number | null; + head: string; +} + type Phase = "review" | "build" | "qa"; const PHASES: Phase[] = ["review", "build", "qa"]; @@ -180,6 +192,35 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) { } }; + /** Start a chat that works out a feature or cuts a milestone into issues. */ + const issueChat = async (mode: "feature" | "slice") => { + if (!data) return; + let target = repo; + if (!target) { + const repos = data.repos.filter((r) => r.enabled); + if (repos.length === 1) target = repos[0].url; + else { + const pick = await choiceDialog({ message: t("issues.pickRepo"), choices: repos.map((r) => ({ value: r.url, label: repoName(r.url) })) }); + if (!pick) return; + target = pick; + } + } + let topic = ""; + if (mode === "slice") { + const name = await promptDialog({ message: t("issues.sliceWhich"), placeholder: "M2", confirmLabel: t("issues.sliceGo") }); + if (!name?.trim()) return; + topic = name.trim(); + } + setBusy(true); + try { + const s = await post<{ id: string }>("/factory/issue-chats", { repo: target, mode, topic }); + navigate(`/s/${s.id}`); + } catch (e: any) { + toast(e.message); + setBusy(false); + } + }; + const issues = useMemo(() => (data?.issues ?? []).filter((i) => !repo || i.repo === repo), [data, repo]); const runs = useMemo(() => (data?.runs ?? []).filter((r) => !repo || r.repo === repo), [data, repo]); if (!data) return
; @@ -231,6 +272,37 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) { setBusy(false); } }; + const [pr, setPr] = useState(null); + const [prMethod, setPrMethod] = useState("merge"); + const selKey = selected ? `${selected.repo}#${selected.number}` : ""; + const loadPr = async () => { + if (!selected || (!selected.branch && !selected.pr_url)) return setPr(null); + try { + const r = await get<{ pr: PrInfo | null }>(`/factory/issues/pr?repo=${encodeURIComponent(selected.repo)}&number=${selected.number}`); + setPr(r.pr); + } catch { + setPr(null); + } + }; + useEffect(() => { + setPr(null); + void loadPr(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [selKey, selected?.state]); + 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; + setBusy(true); + try { + await post("/factory/issues/pr/merge", { repo: selected.repo, number: selected.number, pr: pr.number, method: prMethod }); + toast(t("factory.merged")); + await loadPr(); + } catch (e: any) { + toast(e.message); + } finally { + setBusy(false); + } + }; const phaseRunning = !!selected && ["review", "building", "testing"].includes(selected.state); return ( @@ -289,6 +361,12 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) { + + @@ -360,6 +438,36 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) { )} {selected?.note &&
{selected.note}
} + {pr && ( +
+ + #{pr.number} {pr.title} + + {t(`factory.pr.${pr.state}` as any)} + {pr.state === "open" && pr.mergeable === false && {t("factory.pr.conflict")}} + {pr.changed_files != null && ( + + {t("factory.pr.files", { n: pr.changed_files })} + {pr.additions != null && ` · +${pr.additions} −${pr.deletions ?? 0}`} + + )} + + {pr.state === "open" && ( + <> + + + + )} +
+ )} {shown.length === 0 &&
{t("factory.noRuns")}
} {shown.length > 0 && (
diff --git a/web/src/components/FactoryDraft.tsx b/web/src/components/FactoryDraft.tsx index eb8b992..df67c73 100644 --- a/web/src/components/FactoryDraft.tsx +++ b/web/src/components/FactoryDraft.tsx @@ -183,3 +183,132 @@ function CreateProjectDialog({ sessionId, onClose }: { sessionId: string; onClos
); } + +export const isIssueChat = (cwd: string) => /\/_issues\/[^/]+$/.test(cwd); + +interface ProposedIssue { + title: string; + description: string; + scope: string; + depends: string; +} +interface IssueProposal { + repo: string; + proposal: { spec?: string; issues: ProposedIssue[] } | null; +} + +/** Bar above the composer of an issue chat: file the proposed issues on the forge. */ +export function IssueBar({ sessionId }: { sessionId: string }) { + const t = useT(); + const [open, setOpen] = useState(false); + return ( + <> +
+ + {t("issues.hint")} + + +
+ {open && setOpen(false)} />} + + ); +} + +function CreateIssuesDialog({ sessionId, onClose }: { sessionId: string; onClose: () => void }) { + const t = useT(); + const [data, setData] = useState(); + const [items, setItems] = useState<(ProposedIssue & { on: boolean })[]>([]); + const [spec, setSpec] = useState(""); + const [start, setStart] = useState(false); + const [busy, setBusy] = useState(false); + + useEffect(() => { + get(`/factory/issue-chats/${sessionId}`) + .then((d) => { + setData(d); + setSpec(d.proposal?.spec ?? ""); + setItems((d.proposal?.issues ?? []).map((i) => ({ title: i.title ?? "", description: i.description ?? "", scope: i.scope ?? "", depends: i.depends ?? "", on: true }))); + }) + .catch((e) => { + toast(e.message); + onClose(); + }); + }, [sessionId]); + + if (!data) + return ( +
+
+ +
+
+ ); + + const chosen = items.filter((i) => i.on && i.title.trim()); + const set = (k: number, patch: Partial) => setItems(items.map((x, j) => (j === k ? { ...x, ...patch } : x))); + const create = async () => { + setBusy(true); + try { + const r = await post<{ created: { number: number }[] }>(`/factory/issue-chats/${sessionId}/create`, { + spec, + start, + issues: chosen.map(({ on, ...i }) => i), + }); + toast(t("issues.created", { n: r.created.length }), "success"); + onClose(); + navigate("/factory"); + } catch (e: any) { + toast(e.message); + setBusy(false); + } + }; + + return ( +
+
e.stopPropagation()}> +

{t("issues.create")}

+ {!data.proposal ? ( +
{t("issues.noProposal")}
+ ) : ( + <> + +
+ {items.map((i, k) => ( +
+ +
{i.scope}
+ {i.depends && i.depends.toLowerCase() !== "none" &&
{t("issues.depends", { d: i.depends })}
} +
+ {t("issues.description")} +