import { useEffect, useMemo, useState } from "react"; import { get, post, put } from "../api"; import { fmtCompact, fmtCost, fmtRelative, useT } from "../i18n"; import { navigate } from "../router"; 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"]; interface PhaseCfg { model: string; agent: string; permission_mode: string; timeout_minutes: number; extra_prompt: string; } interface RepoCfg { url: string; kind: string; connection: string; token: string; label: string; max_parallel: number; allowed_users: string[]; enabled: boolean; review: PhaseCfg; build: PhaseCfg; qa: PhaseCfg; } interface Connection { id: string; name: string; kind: "gitea" | "github" | "gitlab"; url: string; token: string; owner: string; } interface Defaults { spec_model: string; review: PhaseCfg; build: PhaseCfg; qa: PhaseCfg; } interface Settings { connections: Connection[]; defaults: Defaults; repos: RepoCfg[]; } interface Issue { repo: string; number: number; title: string; author: string; state: string; note: string; pr_url: string; branch: string; rounds: number; created_at: number; updated_at: number; } interface Run { id: string; repo: string; issue: number; phase: Phase; round: number; session_id: string; model: string; started_at: number; ended_at: number | null; status: string; input_tokens: number; output_tokens: number; cost: number; } interface RepoInfo { url: string; kind: string; enabled: boolean; label: string; max_parallel: number; has_token: boolean; models: Record; running: number; } interface Overview { area: boolean; repos: RepoInfo[]; issues: Issue[]; runs: Run[]; } /** Board columns: a column collects one or more issue states. */ const COLUMNS: { id: string; states: string[] }[] = [ { id: "review", states: ["new", "review"] }, { id: "question", states: ["question"] }, { id: "approved", states: ["approved"] }, { id: "build", states: ["building", "rework"] }, { id: "qa", states: ["qa", "testing"] }, { id: "done", states: ["done"] }, { id: "failed", states: ["failed", "rejected"] }, ]; const KIND_NAME: Record = { gitea: "Gitea", github: "GitHub", gitlab: "GitLab" }; const repoName = (url: string) => url.replace(/\.git$/, "").split("/").slice(-2).join("/"); const issueUrl = (repo: string, n: number) => `${repo.replace(/\.git$/, "")}/issues/${n}`; function fmtDuration(ms: number) { const s = Math.max(0, Math.round(ms / 1000)); if (s < 60) return `${s} s`; const m = Math.floor(s / 60); return m < 60 ? `${m} min ${s % 60} s` : `${Math.floor(m / 60)} h ${m % 60} min`; } const runMs = (r: Run, now: number) => (r.ended_at ?? now) - r.started_at; /** Software factory: spec issues in Gitea are reviewed, built and accepted by agents with a model per phase. */ export function Factory({ onMenu }: { onMenu: () => void }) { const t = useT(); const [tab, setTab] = useState<"overview" | "settings">("overview"); return ( <>

{t("factory.title")}

{(["overview", "settings"] as const).map((x) => ( ))}
{tab === "overview" ? setTab("settings")} /> : }
); } function FactoryOverview({ onSettings }: { onSettings: () => void }) { const t = useT(); const [data, setData] = useState(); const [repo, setRepo] = useState(""); const [sel, setSel] = useState(""); const [now, setNow] = useState(Date.now()); const [busy, setBusy] = useState(false); const reload = () => get("/factory/overview") .then(setData) .catch((e) => toast(e.message)); useEffect(() => { void reload(); const h = setInterval(() => { void reload(); setNow(Date.now()); }, 5000); return () => clearInterval(h); }, []); const newProject = async () => { setBusy(true); try { const s = await post<{ id: string }>("/factory/drafts", {}); navigate(`/s/${s.id}`); } catch (e: any) { toast(e.message); setBusy(false); } }; /** 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]); const selected = issues.find((i) => `${i.repo}#${i.number}` === sel); 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]); if (!data) return
; if (data.repos.length === 0) return (

{t("factory.empty")}

); const sum = (f: (r: Run) => number) => runs.reduce((a, r) => a + f(r), 0); const finished = runs.filter((r) => r.ended_at); const running = runs.filter((r) => !r.ended_at); const done = issues.filter((i) => i.state === "done").length; const failed = issues.filter((i) => ["failed", "rejected"].includes(i.state)).length; const runsOf = (i: Issue) => data.runs.filter((r) => r.repo === i.repo && r.issue === i.number); const shown = selected ? runsOf(selected) : runs.slice(0, 12); const poll = async () => { setBusy(true); try { const r = await post<{ errors: string[] }>("/factory/poll", {}); if (r.errors.length) toast(r.errors.join("\n")); await reload(); } catch (e: any) { toast(e.message); } finally { setBusy(false); } }; const restart = async (to: "new" | "approved" | "qa") => { if (!selected) return; setBusy(true); try { await post("/factory/issues/restart", { repo: selected.repo, number: selected.number, to }); toast(t("factory.restarted")); await reload(); } catch (e: any) { toast(e.message); } finally { 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; 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 ( <> {!data.area &&
{t("factory.noArea")}
}
{t("factory.kpi.running")}
{running.length}
{t("factory.kpi.issues", { n: issues.length })}
{t("factory.kpi.done")}
{done}
{t("factory.kpi.failed", { n: failed })}
{t("factory.kpi.tokens")}
{fmtCompact(sum((r) => r.input_tokens + r.output_tokens))}
{fmtCompact(sum((r) => r.input_tokens))} {t("factory.in")} · {fmtCompact(sum((r) => r.output_tokens))} {t("factory.out")}
{t("factory.kpi.cost")}
{fmtCost(sum((r) => r.cost), "USD")}
{t("factory.kpi.runs", { n: runs.length })}
{t("factory.kpi.time")}
{finished.length ? fmtDuration(sum((r) => runMs(r, now)) / finished.length) : "–"}
{t("factory.kpi.perRun")}
{data.repos.map((r) => { const mine = data.issues.filter((i) => i.repo === r.url); return ( ); })}
{COLUMNS.map((c) => { const cards = issues.filter((i) => c.states.includes(i.state)); return (

{t(`factory.col.${c.id}` as any)} {cards.length}

{cards.map((i) => { const rs = runsOf(i); const active = rs.find((r) => !r.ended_at); const latest = active ?? rs[0]; const tokens = rs.reduce((a, r) => a + r.input_tokens + r.output_tokens, 0); return ( ); })}
); })}

{selected ? `${repoName(selected.repo)} #${selected.number} – ${selected.title}` : t("factory.latestRuns")}

{selected && !phaseRunning && ( <> {t("factory.restartAt")} )} {selected && ( <> Gitea {selected.pr_url && ( {t("factory.pr")} )} )}
{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 && (
{!selected && } {shown.map((r) => ( {!selected && ( )} ))}
{t("factory.issue")}{t("factory.phase")} {t("factory.model")} {t("factory.status")} {t("factory.started")} {t("factory.duration")} {t("factory.tokens")} {t("factory.cost")}
{repoName(r.repo)} #{r.issue} {t(`factory.phase.${r.phase}` as any)} {r.round > 0 && · {t("factory.round", { n: r.round })}} {r.model} {r.status === "running" && } {t(`factory.runStatus.${r.status}` as any) || r.status} {fmtRelative(r.started_at)} {fmtDuration(runMs(r, now))} {fmtCompact(r.input_tokens)} / {fmtCompact(r.output_tokens)} {fmtCost(r.cost, "USD")}
)}
); } const blankPhase = (): PhaseCfg => ({ model: "", agent: "codecraft", permission_mode: "auto", timeout_minutes: 60, extra_prompt: "" }); const blankRepo = (connection = "", kind = "gitea"): RepoCfg => ({ url: "", kind, connection, token: "", label: "factory", max_parallel: 1, allowed_users: [], enabled: true, review: blankPhase(), build: blankPhase(), qa: blankPhase() }); const blankConn = (): Connection => ({ id: "", name: "", kind: "gitea", url: "", token: "", owner: "" }); const MODES = ["default", "auto", "accept_edits", "bypass"]; function PhaseForm({ phase, value, onChange }: { phase: Phase; value: PhaseCfg; onChange: (patch: Partial) => void }) { const t = useT(); return (

{t(`factory.phase.${phase}` as any)}