Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
815 lines
33 KiB
TypeScript
815 lines
33 KiB
TypeScript
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<Phase, string>;
|
||
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<string, string> = { 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 (
|
||
<>
|
||
<div className="topbar">
|
||
<button className="ghost menu-btn" onClick={onMenu} aria-label={t("nav.menu")}>
|
||
<Icon name="menu" />
|
||
</button>
|
||
<div className="grow">
|
||
<h1>{t("factory.title")}</h1>
|
||
</div>
|
||
<div className="segmented">
|
||
{(["overview", "settings"] as const).map((x) => (
|
||
<button key={x} className={tab === x ? "active" : ""} onClick={() => setTab(x)}>
|
||
{t(`factory.tab.${x}` as any)}
|
||
</button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
<div className="page">
|
||
<div className="page-inner" style={{ maxWidth: 1280 }}>
|
||
{tab === "overview" ? <FactoryOverview onSettings={() => setTab("settings")} /> : <FactorySettings />}
|
||
</div>
|
||
</div>
|
||
</>
|
||
);
|
||
}
|
||
|
||
function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
||
const t = useT();
|
||
const [data, setData] = useState<Overview>();
|
||
const [repo, setRepo] = useState<string>("");
|
||
const [sel, setSel] = useState<string>("");
|
||
const [now, setNow] = useState(Date.now());
|
||
const [busy, setBusy] = useState(false);
|
||
|
||
const reload = () =>
|
||
get<Overview>("/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<PrInfo | null>(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 <div className="empty"><Spinner /></div>;
|
||
if (data.repos.length === 0)
|
||
return (
|
||
<div className="empty">
|
||
<p>{t("factory.empty")}</p>
|
||
<div className="row" style={{ gap: 8, justifyContent: "center" }}>
|
||
<button className="primary" onClick={newProject} disabled={busy}>
|
||
<Icon name="plus" /> {t("factory.newProject")}
|
||
</button>
|
||
<button onClick={onSettings}>{t("factory.tab.settings")}</button>
|
||
</div>
|
||
</div>
|
||
);
|
||
|
||
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 && <div className="notice err">{t("factory.noArea")}</div>}
|
||
<div className="kpis">
|
||
<div className="kpi">
|
||
<div className="k-label">{t("factory.kpi.running")}</div>
|
||
<div className="k-value">{running.length}</div>
|
||
<div className="k-sub">{t("factory.kpi.issues", { n: issues.length })}</div>
|
||
</div>
|
||
<div className="kpi">
|
||
<div className="k-label">{t("factory.kpi.done")}</div>
|
||
<div className="k-value">{done}</div>
|
||
<div className="k-sub">{t("factory.kpi.failed", { n: failed })}</div>
|
||
</div>
|
||
<div className="kpi">
|
||
<div className="k-label">{t("factory.kpi.tokens")}</div>
|
||
<div className="k-value">{fmtCompact(sum((r) => r.input_tokens + r.output_tokens))}</div>
|
||
<div className="k-sub">
|
||
{fmtCompact(sum((r) => r.input_tokens))} {t("factory.in")} · {fmtCompact(sum((r) => r.output_tokens))} {t("factory.out")}
|
||
</div>
|
||
</div>
|
||
<div className="kpi">
|
||
<div className="k-label">{t("factory.kpi.cost")}</div>
|
||
<div className="k-value">{fmtCost(sum((r) => r.cost), "USD")}</div>
|
||
<div className="k-sub">{t("factory.kpi.runs", { n: runs.length })}</div>
|
||
</div>
|
||
<div className="kpi">
|
||
<div className="k-label">{t("factory.kpi.time")}</div>
|
||
<div className="k-value">{finished.length ? fmtDuration(sum((r) => runMs(r, now)) / finished.length) : "–"}</div>
|
||
<div className="k-sub">{t("factory.kpi.perRun")}</div>
|
||
</div>
|
||
</div>
|
||
|
||
<div className="factory-repos">
|
||
<button className={`factory-repo ${repo === "" ? "active" : ""}`} onClick={() => setRepo("")}>
|
||
<b>{t("factory.allRepos")}</b>
|
||
<span className="hint">{t("factory.kpi.issues", { n: data.issues.length })}</span>
|
||
</button>
|
||
{data.repos.map((r) => {
|
||
const mine = data.issues.filter((i) => i.repo === r.url);
|
||
return (
|
||
<button key={r.url} className={`factory-repo ${repo === r.url ? "active" : ""} ${r.enabled ? "" : "off"}`} onClick={() => setRepo(r.url)}>
|
||
<b>{repoName(r.url)}</b>
|
||
<span className="chip">{KIND_NAME[r.kind] ?? r.kind}</span>
|
||
<span className="hint">
|
||
{r.running > 0 && <span className="factory-pulse" />}
|
||
{t("factory.repoLine", { n: mine.length, run: r.running })}
|
||
</span>
|
||
<span className="hint mono">{PHASES.map((p) => r.models[p] || "·").map((m) => m.split("/").pop()).join(" → ")}</span>
|
||
{!r.has_token && <span className="chip warn">{t("factory.noToken")}</span>}
|
||
</button>
|
||
);
|
||
})}
|
||
<button className="small primary" onClick={newProject} disabled={busy}>
|
||
<Icon name="plus" /> {t("factory.newProject")}
|
||
</button>
|
||
<button className="small" onClick={() => issueChat("feature")} disabled={busy} title={t("issues.featureHint")}>
|
||
<Icon name="sparkle" /> {t("issues.feature")}
|
||
</button>
|
||
<button className="small" onClick={() => issueChat("slice")} disabled={busy} title={t("issues.sliceHint")}>
|
||
<Icon name="sparkle" /> {t("issues.slice")}
|
||
</button>
|
||
<button className="small" onClick={poll} disabled={busy} title={t("factory.pollNow")}>
|
||
<Icon name="refresh" /> {t("factory.pollNow")}
|
||
</button>
|
||
</div>
|
||
|
||
<div className="factory-board">
|
||
{COLUMNS.map((c) => {
|
||
const cards = issues.filter((i) => c.states.includes(i.state));
|
||
return (
|
||
<div key={c.id} className="factory-col">
|
||
<h4>
|
||
{t(`factory.col.${c.id}` as any)} <span className="chip">{cards.length}</span>
|
||
</h4>
|
||
{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 (
|
||
<button key={`${i.repo}#${i.number}`} className={`factory-card ${sel === `${i.repo}#${i.number}` ? "active" : ""} ${active ? "running" : ""}`} onClick={() => setSel(sel === `${i.repo}#${i.number}` ? "" : `${i.repo}#${i.number}`)}>
|
||
<span className="hint">
|
||
{repoName(i.repo)} #{i.number}
|
||
</span>
|
||
<b>{i.title || `#${i.number}`}</b>
|
||
{latest && (
|
||
<span className="hint">
|
||
{active && <span className="factory-pulse" />}
|
||
{t(`factory.phase.${latest.phase}` as any)} · {(latest.model || "").split("/").pop()} · {fmtDuration(runMs(latest, now))}
|
||
</span>
|
||
)}
|
||
{tokens > 0 && <span className="hint">{fmtCompact(tokens)} {t("factory.tokens")}</span>}
|
||
</button>
|
||
);
|
||
})}
|
||
</div>
|
||
);
|
||
})}
|
||
</div>
|
||
|
||
<div className="panel" style={{ marginTop: 16 }}>
|
||
<div className="row">
|
||
<h3 style={{ margin: 0 }}>{selected ? `${repoName(selected.repo)} #${selected.number} – ${selected.title}` : t("factory.latestRuns")}</h3>
|
||
<span className="spacer" />
|
||
{selected && !phaseRunning && (
|
||
<>
|
||
<span className="hint">{t("factory.restartAt")}</span>
|
||
<button className="small" onClick={() => restart("new")} disabled={busy}>
|
||
{t("factory.col.review")}
|
||
</button>
|
||
<button className="small" onClick={() => restart("approved")} disabled={busy}>
|
||
{t("factory.col.build")}
|
||
</button>
|
||
<button className="small" onClick={() => restart("qa")} disabled={busy || !selected.branch}>
|
||
{t("factory.col.qa")}
|
||
</button>
|
||
</>
|
||
)}
|
||
{selected && (
|
||
<>
|
||
<a className="small ghost button-link" href={issueUrl(selected.repo, selected.number)} target="_blank" rel="noreferrer">
|
||
<Icon name="external" /> Gitea
|
||
</a>
|
||
{selected.pr_url && (
|
||
<a className="small ghost button-link" href={selected.pr_url} target="_blank" rel="noreferrer">
|
||
<Icon name="external" /> {t("factory.pr")}
|
||
</a>
|
||
)}
|
||
</>
|
||
)}
|
||
</div>
|
||
{selected?.note && <div className="hint" style={{ margin: "6px 0" }}>{selected.note}</div>}
|
||
{pr && (
|
||
<div className="factory-pr">
|
||
<a href={pr.html_url} target="_blank" rel="noreferrer">
|
||
<Icon name="external" /> #{pr.number} {pr.title}
|
||
</a>
|
||
<span className={`chip ${pr.state === "merged" ? "ok" : pr.state === "open" ? "" : "warn"}`}>{t(`factory.pr.${pr.state}` as any)}</span>
|
||
{pr.state === "open" && pr.mergeable === false && <span className="chip warn">{t("factory.pr.conflict")}</span>}
|
||
{pr.changed_files != null && (
|
||
<span className="hint">
|
||
{t("factory.pr.files", { n: pr.changed_files })}
|
||
{pr.additions != null && ` · +${pr.additions} −${pr.deletions ?? 0}`}
|
||
</span>
|
||
)}
|
||
<span className="spacer" />
|
||
{pr.state === "open" && (
|
||
<>
|
||
<select value={prMethod} onChange={(e) => setPrMethod(e.target.value)} disabled={busy}>
|
||
{["merge", "squash", "rebase"].map((m) => (
|
||
<option key={m} value={m}>
|
||
{t(`factory.merge.${m}` as any)}
|
||
</option>
|
||
))}
|
||
</select>
|
||
<button className="small primary" onClick={mergePr} disabled={busy || pr.mergeable === false}>
|
||
{t("factory.mergeBtn")}
|
||
</button>
|
||
</>
|
||
)}
|
||
</div>
|
||
)}
|
||
{shown.length === 0 && <div className="hint">{t("factory.noRuns")}</div>}
|
||
{shown.length > 0 && (
|
||
<div className="table-wrap">
|
||
<table className="grid factory-runs">
|
||
<thead>
|
||
<tr>
|
||
{!selected && <th>{t("factory.issue")}</th>}
|
||
<th>{t("factory.phase")}</th>
|
||
<th>{t("factory.model")}</th>
|
||
<th>{t("factory.status")}</th>
|
||
<th>{t("factory.started")}</th>
|
||
<th>{t("factory.duration")}</th>
|
||
<th>{t("factory.tokens")}</th>
|
||
<th>{t("factory.cost")}</th>
|
||
<th />
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{shown.map((r) => (
|
||
<tr key={r.id}>
|
||
{!selected && (
|
||
<td>
|
||
{repoName(r.repo)} #{r.issue}
|
||
</td>
|
||
)}
|
||
<td>
|
||
{t(`factory.phase.${r.phase}` as any)}
|
||
{r.round > 0 && <span className="hint"> · {t("factory.round", { n: r.round })}</span>}
|
||
</td>
|
||
<td className="mono">{r.model}</td>
|
||
<td>
|
||
<span className={`chip ${r.status === "done" ? "ok" : r.status === "running" ? "" : "warn"}`}>
|
||
{r.status === "running" && <span className="factory-pulse" />}
|
||
{t(`factory.runStatus.${r.status}` as any) || r.status}
|
||
</span>
|
||
</td>
|
||
<td>{fmtRelative(r.started_at)}</td>
|
||
<td>{fmtDuration(runMs(r, now))}</td>
|
||
<td title={`${r.input_tokens} / ${r.output_tokens}`}>
|
||
{fmtCompact(r.input_tokens)} / {fmtCompact(r.output_tokens)}
|
||
</td>
|
||
<td>{fmtCost(r.cost, "USD")}</td>
|
||
<td>
|
||
<button className="small" onClick={() => navigate(`/s/${r.session_id}`)}>
|
||
<Icon name="eye" /> {t("factory.openChat")}
|
||
</button>
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
)}
|
||
</div>
|
||
</>
|
||
);
|
||
}
|
||
|
||
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<PhaseCfg>) => void }) {
|
||
const t = useT();
|
||
return (
|
||
<div className="factory-phase">
|
||
<h4>{t(`factory.phase.${phase}` as any)}</h4>
|
||
<label>
|
||
<span>{t("factory.model")}</span>
|
||
<ModelSelect value={value.model} onChange={(model) => onChange({ model })} emptyLabel={t("jobEditor.defaultModel")} />
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.agent")}</span>
|
||
<select value={value.agent} onChange={(e) => onChange({ agent: e.target.value })}>
|
||
<option value="codecraft">CodeCraft</option>
|
||
<option value="claude-code">Claude Code</option>
|
||
</select>
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.mode")}</span>
|
||
<select value={value.permission_mode} onChange={(e) => onChange({ permission_mode: e.target.value })}>
|
||
{MODES.map((m) => (
|
||
<option key={m} value={m}>
|
||
{t(`permissionMode.${m}` as any)}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.timeout")}</span>
|
||
<input type="number" min={1} value={value.timeout_minutes} onChange={(e) => onChange({ timeout_minutes: Number(e.target.value) || 60 })} />
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.extraPrompt")}</span>
|
||
<textarea rows={3} value={value.extra_prompt} onChange={(e) => onChange({ extra_prompt: e.target.value })} />
|
||
</label>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const URL_PLACEHOLDER: Record<string, string> = { gitea: "https://git.example.org", github: "https://github.com", gitlab: "https://gitlab.com" };
|
||
|
||
function FactorySettings() {
|
||
const t = useT();
|
||
const [st, setSt] = useState<Settings>();
|
||
const [busy, setBusy] = useState<string>();
|
||
const [orgs, setOrgs] = useState<Record<string, string[]>>({});
|
||
|
||
useEffect(() => {
|
||
get<Settings>("/account/factory")
|
||
.then(setSt)
|
||
.catch((e) => toast(e.message));
|
||
}, []);
|
||
if (!st) return <div className="empty"><Spinner /></div>;
|
||
const { connections: conns, repos } = st;
|
||
|
||
const setConns = (connections: Connection[]) => setSt({ ...st, connections });
|
||
const setRepos = (r: RepoCfg[]) => setSt({ ...st, repos: r });
|
||
const upConn = (i: number, patch: Partial<Connection>) => setConns(conns.map((c, k) => (k === i ? { ...c, ...patch } : c)));
|
||
const up = (i: number, patch: Partial<RepoCfg>) => setRepos(repos.map((r, k) => (k === i ? { ...r, ...patch } : r)));
|
||
const upPhase = (i: number, p: Phase, patch: Partial<PhaseCfg>) => up(i, { [p]: { ...repos[i][p], ...patch } } as any);
|
||
const upDefault = (p: Phase, patch: Partial<PhaseCfg>) => setSt({ ...st, defaults: { ...st.defaults, [p]: { ...st.defaults[p], ...patch } } });
|
||
|
||
const save = async () => {
|
||
const s = await put<Settings>("/account/factory", st);
|
||
setSt(s);
|
||
return s;
|
||
};
|
||
const act = async (key: string, f: () => Promise<void>) => {
|
||
setBusy(key);
|
||
try {
|
||
await f();
|
||
} catch (e: any) {
|
||
toast(e.message);
|
||
} finally {
|
||
setBusy(undefined);
|
||
}
|
||
};
|
||
|
||
return (
|
||
<>
|
||
<div className="notice">{t("factory.settingsHint")}</div>
|
||
|
||
<h3 className="factory-h">{t("factory.connections")}</h3>
|
||
<div className="hint" style={{ marginBottom: 8 }}>{t("factory.connectionsHint")}</div>
|
||
{conns.map((c, i) => (
|
||
<div key={i} className="panel">
|
||
<div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
|
||
<h3 style={{ margin: 0 }}>{c.name || KIND_NAME[c.kind]}</h3>
|
||
<span className="spacer" />
|
||
<button
|
||
className="small"
|
||
disabled={busy !== undefined}
|
||
onClick={() =>
|
||
act(`c${i}`, async () => {
|
||
const saved = await save();
|
||
const id = saved.connections[i]?.id;
|
||
const r = await post<{ login: string; orgs: string[] }>("/account/factory/connection/test", { id });
|
||
setOrgs({ ...orgs, [id]: r.orgs });
|
||
toast(t("factory.connOk", { login: r.login, n: r.orgs.length }), "success");
|
||
})
|
||
}
|
||
>
|
||
{busy === `c${i}` ? <Spinner small /> : <Icon name="plug" />} {t("factory.testConn")}
|
||
</button>
|
||
<button
|
||
className="small"
|
||
title={t("common.delete")}
|
||
aria-label={t("common.delete")}
|
||
onClick={async () => {
|
||
if (await confirmDialog({ message: t("factory.connDeleteConfirm", { name: c.name || KIND_NAME[c.kind] }), danger: true })) setConns(conns.filter((_, k) => k !== i));
|
||
}}
|
||
>
|
||
<Icon name="trash" />
|
||
</button>
|
||
</div>
|
||
<div className="factory-form">
|
||
<label>
|
||
<span>{t("factory.connName")}</span>
|
||
<input value={c.name} onChange={(e) => upConn(i, { name: e.target.value })} />
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.kind")}</span>
|
||
<select value={c.kind} onChange={(e) => upConn(i, { kind: e.target.value as Connection["kind"] })}>
|
||
{Object.entries(KIND_NAME).map(([k, n]) => (
|
||
<option key={k} value={k}>
|
||
{n}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.serviceUrl")}</span>
|
||
<input value={c.url} placeholder={URL_PLACEHOLDER[c.kind]} onChange={(e) => upConn(i, { url: e.target.value })} />
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.token")}</span>
|
||
<input type="password" autoComplete="new-password" value={c.token} placeholder={t("factory.tokenPlaceholder")} onChange={(e) => upConn(i, { token: e.target.value })} onFocus={(e) => c.token.startsWith("•") && e.currentTarget.select()} />
|
||
<span className="hint">{c.token.startsWith("•") ? t("factory.tokenSet") : t(`factory.tokenHint.${c.kind}` as any)}</span>
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.defaultOwner")}</span>
|
||
<input list={`orgs-${c.id}`} value={c.owner} placeholder={t("draft.ownerPlaceholder")} onChange={(e) => upConn(i, { owner: e.target.value })} />
|
||
<datalist id={`orgs-${c.id}`}>
|
||
{(orgs[c.id] ?? []).map((o) => (
|
||
<option key={o} value={o} />
|
||
))}
|
||
</datalist>
|
||
</label>
|
||
</div>
|
||
</div>
|
||
))}
|
||
<button onClick={() => setConns([...conns, blankConn()])}>
|
||
<Icon name="plus" /> {t("factory.addConn")}
|
||
</button>
|
||
|
||
<h3 className="factory-h">{t("factory.defaults")}</h3>
|
||
<div className="hint" style={{ marginBottom: 8 }}>{t("factory.defaultsHint")}</div>
|
||
<div className="panel">
|
||
<label className="factory-form" style={{ margin: 0 }}>
|
||
<span style={{ fontSize: 12 }}>{t("factory.specModel")}</span>
|
||
<ModelSelect value={st.defaults.spec_model} onChange={(spec_model) => setSt({ ...st, defaults: { ...st.defaults, spec_model } })} emptyLabel={t("jobEditor.defaultModel")} />
|
||
</label>
|
||
<div className="factory-phases" style={{ marginTop: 10 }}>
|
||
{PHASES.map((p) => (
|
||
<PhaseForm key={p} phase={p} value={st.defaults[p]} onChange={(patch) => upDefault(p, patch)} />
|
||
))}
|
||
</div>
|
||
</div>
|
||
|
||
<h3 className="factory-h">{t("factory.repos")}</h3>
|
||
{repos.map((r, i) => (
|
||
<div key={i} className="panel">
|
||
<div className="row" style={{ flexWrap: "wrap", gap: 8 }}>
|
||
<h3 style={{ margin: 0 }}>{r.url ? repoName(r.url) : t("factory.newRepo")}</h3>
|
||
<span className="chip">{KIND_NAME[conns.find((c) => c.id === r.connection)?.kind ?? r.kind] ?? r.kind}</span>
|
||
<span className="spacer" />
|
||
<label className="switch">
|
||
<input type="checkbox" checked={r.enabled} onChange={(e) => up(i, { enabled: e.target.checked })} />
|
||
<span>{t(r.enabled ? "jobs.on" : "jobs.off")}</span>
|
||
</label>
|
||
<button
|
||
className="small"
|
||
disabled={busy !== undefined}
|
||
onClick={() =>
|
||
act(`t${i}`, async () => {
|
||
await save();
|
||
const res = await post<{ info: { login: string; repo: string; can_push: boolean }; labels_created: string[]; folder: string }>("/account/factory/test", { url: r.url });
|
||
toast(t("factory.testOk", { login: res.info.login, repo: res.info.repo, n: res.labels_created.length }), "success");
|
||
})
|
||
}
|
||
>
|
||
{busy === `t${i}` ? <Spinner small /> : <Icon name="plug" />} {t("factory.test")}
|
||
</button>
|
||
<button
|
||
className="small"
|
||
title={t("common.delete")}
|
||
aria-label={t("common.delete")}
|
||
onClick={async () => {
|
||
if (await confirmDialog({ message: t("factory.deleteConfirm", { name: repoName(r.url) || "?" }), danger: true })) setRepos(repos.filter((_, k) => k !== i));
|
||
}}
|
||
>
|
||
<Icon name="trash" />
|
||
</button>
|
||
</div>
|
||
<div className="factory-form">
|
||
<label>
|
||
<span>{t("factory.connection")}</span>
|
||
<select
|
||
value={r.connection}
|
||
onChange={(e) => up(i, { connection: e.target.value, kind: conns.find((c) => c.id === e.target.value)?.kind ?? r.kind })}
|
||
>
|
||
<option value="">{t("factory.noConnection")}</option>
|
||
{conns
|
||
.filter((c) => c.id)
|
||
.map((c) => (
|
||
<option key={c.id} value={c.id}>
|
||
{c.name || KIND_NAME[c.kind]}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
{!r.connection && (
|
||
<label>
|
||
<span>{t("factory.kind")}</span>
|
||
<select value={r.kind} onChange={(e) => up(i, { kind: e.target.value })}>
|
||
{Object.entries(KIND_NAME).map(([k, n]) => (
|
||
<option key={k} value={k}>
|
||
{n}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
)}
|
||
<label>
|
||
<span>{t("factory.url")}</span>
|
||
<input value={r.url} placeholder="https://host/owner/repo.git" onChange={(e) => up(i, { url: e.target.value })} />
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.repoToken")}</span>
|
||
<input type="password" autoComplete="new-password" value={r.token} placeholder={t("factory.repoTokenPlaceholder")} onChange={(e) => up(i, { token: e.target.value })} onFocus={(e) => r.token.startsWith("•") && e.currentTarget.select()} />
|
||
<span className="hint">{r.token.startsWith("•") ? t("factory.tokenSet") : t("factory.repoTokenHint")}</span>
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.label")}</span>
|
||
<input value={r.label} onChange={(e) => up(i, { label: e.target.value })} />
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.parallel")}</span>
|
||
<input type="number" min={1} max={4} value={r.max_parallel} onChange={(e) => up(i, { max_parallel: Number(e.target.value) || 1 })} />
|
||
</label>
|
||
<label>
|
||
<span>{t("factory.allowed")}</span>
|
||
<input value={r.allowed_users.join(", ")} placeholder={t("factory.allowedPlaceholder")} onChange={(e) => up(i, { allowed_users: e.target.value.split(",").map((u) => u.trim()).filter(Boolean) })} />
|
||
</label>
|
||
</div>
|
||
<div className="factory-phases">
|
||
{PHASES.map((p) => (
|
||
<PhaseForm key={p} phase={p} value={r[p]} onChange={(patch) => upPhase(i, p, patch)} />
|
||
))}
|
||
</div>
|
||
</div>
|
||
))}
|
||
<div className="row" style={{ gap: 8, marginTop: 12 }}>
|
||
<button onClick={() => setRepos([...repos, blankRepo(conns.find((c) => c.id)?.id ?? "", conns.find((c) => c.id)?.kind ?? "gitea")])}>
|
||
<Icon name="plus" /> {t("factory.addRepo")}
|
||
</button>
|
||
<button
|
||
className="primary"
|
||
disabled={busy !== undefined}
|
||
onClick={() =>
|
||
act("save", async () => {
|
||
await save();
|
||
toast(t("factory.saved"), "success");
|
||
})
|
||
}
|
||
>
|
||
{busy === "save" ? <Spinner small /> : <Icon name="check" />} {t("common.save")}
|
||
</button>
|
||
</div>
|
||
</>
|
||
);
|
||
}
|