import { useEffect, useState } from "react"; import { Loader2 } from "lucide-react"; import { api, asUiError, type CompanionSizes, type Population, type UiError } from "@/lib/api"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { hasKey, useHuman, useT, type Key } from "@/i18n"; export function CompanionsCard({ serverId }: { serverId: string }) { const t = useT(); const human = useHuman(); const [sizes, setSizes] = useState(null); const [pop, setPop] = useState(null); const [running, setRunning] = useState(false); const [choice, setChoice] = useState("small"); const [custom, setCustom] = useState("100"); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [note, setNote] = useState(null); // Start-up login: how many existing bots the server brings online by itself every time it starts. const [autoOn, setAutoOn] = useState(true); const [autoMax, setAutoMax] = useState(""); // A creation that is still in progress on the running server: how many existed before and how many were asked for. const [job, setJob] = useState<{ baseline: number; target: number; since: number } | null>(null); const [startNote, setStartNote] = useState(null); const [startBusy, setStartBusy] = useState(false); const [despawnN, setDespawnN] = useState("10"); useEffect(() => { void api .settings(serverId, "bots") .then((v) => { const on = v.settings.find((s) => s.key === "CoaBots.AutoLoginOnStartup"); const max = v.settings.find((s) => s.key === "CoaBots.AutoLogin.MaxCount"); if (on) setAutoOn(on.value === true); if (max) setAutoMax(String(max.value)); }) .catch(() => {}); }, [serverId]); const maxNum = Number(autoMax); const maxValid = autoMax.trim() !== "" && Number.isInteger(maxNum) && maxNum >= 0 && maxNum <= 5000; async function act(fn: () => Promise) { setBusy(true); setError(null); try { setNote(await fn()); } catch (e) { setError(asUiError(e)); } finally { setBusy(false); } } const stopCreating = () => act(async () => { const r = await api.stopSpawning(serverId); setJob(null); return t("comp.stopped", { n: r.count }); }); const takeOffline = () => { if (!window.confirm(t("comp.offlineConfirm"))) return; void act(async () => { const r = await api.takeOffline(serverId); setJob(null); return t("comp.offlineDone2", { n: r.count }); }); }; const dn = Number(despawnN); const dnValid = Number.isInteger(dn) && dn >= 1 && dn <= 5000; const despawnSome = () => act(async () => { const r = await api.despawnSome(serverId, dn); return t("comp.despawnSomeDone", { n: r.count }); }); const deleteAll = () => { if (!window.confirm(t("comp.deleteConfirm", { n: pop?.bots_total ?? 0 }))) return; void act(async () => { await api.deleteAllCompanions(serverId); setJob(null); return t("comp.deleteDone"); }); }; async function saveStart() { setStartBusy(true); setError(null); setStartNote(null); try { await api.save(serverId, "bots", { "CoaBots.AutoLoginOnStartup": autoOn, "CoaBots.AutoLogin.MaxCount": maxNum }); setStartNote(t("comp.startSaved")); } catch (e) { setError(asUiError(e)); } finally { setStartBusy(false); } } useEffect(() => { void api.companionSizes().then(setSizes); let alive = true; const poll = async () => { const s = await api.status(serverId).catch(() => null); if (!alive || !s) return; const up = s.observed.world.state === "running"; setRunning(up); setPop(up ? await api.population(serverId).catch(() => null) : null); }; void poll(); // Faster while companions are being created, so the progress bar moves. const t = setInterval(poll, job ? 1500 : 4000); return () => { alive = false; clearInterval(t); }; }, [serverId, job !== null]); // eslint-disable-line react-hooks/exhaustive-deps const done = job && pop ? Math.max(0, Math.min(job.target, pop.bots_total - job.baseline)) : 0; useEffect(() => { if (!job) return; // Finished, or the server went away, or nothing new appeared for two minutes. if ((pop && done >= job.target) || !running) { if (pop && done >= job.target) setNote(t("comp.progressDone", { n: job.target })); setJob(null); } }, [done, running]); // eslint-disable-line react-hooks/exhaustive-deps // The backend describes a size's warning in English; show the translated text for the two known kinds. const warningFor = (size?: { bots: number; warning: string | null }) => { if (!size?.warning) return null; return size.warning.startsWith(`${size.bots} companions`) ? t("comp.warnHardware", { n: size.bots, cores: sizes?.hardware.cores ?? "?", ram: sizes ? sizes.hardware.ram_gb.toFixed(0) : "?" }) : t("comp.warnMemory"); }; const count = choice === "custom" ? Number(custom) : (sizes?.sizes.find((s) => s.id === choice)?.bots ?? 0); const warning = choice === "custom" ? (count > 500 ? t("comp.largeWarning") : null) : (warningFor(sizes?.sizes.find((s) => s.id === choice))); const valid = Number.isInteger(count) && count >= 1 && count <= 2000; async function add() { setBusy(true); setError(null); setNote(null); try { const r = await api.addCompanions(serverId, count); if (r.spawned && r.baseline !== null) setJob({ baseline: r.baseline, target: count, since: Date.now() }); setNote(r.created ? t("comp.offlineDone", { n: r.created }) : r.spawned ? t("comp.spawned", { n: count }) : t("comp.saved", { n: count })); } catch (e) { setError(asUiError(e)); } finally { setBusy(false); } } return (

{t("comp.title")}

{pop ? t("comp.population", { online: pop.bots_online, total: pop.bots_total }) : running ? t("comp.reading") : t("comp.startToSee")}

{t("comp.wantMore")}
{sizes?.sizes.map((s) => ( ))} {choice === "custom" && ( setCustom(e.target.value)} inputMode="numeric" className="w-24 rounded-md border border-line bg-bg px-3 py-2 text-right text-sm outline-none focus:border-gold" /> )}
{warning &&

{warning}

} {sizes &&

{t("comp.hardware", { cores: sizes.hardware.cores, ram: sizes.hardware.ram_gb.toFixed(0) })}

}
{!running && {t("comp.stoppedHint")}}
{busy && !running && count >= 100 && (

{t("comp.progressOffline", { n: count })}

)} {job && (
{t("comp.progress", { done, target: job.target })} {Math.round((done / job.target) * 100)}%
{done === 0 && Date.now() - job.since > 20000 &&

{t("comp.progressStalled")}

}
)} {note && !job &&

{note}

} {running && pop && pop.bots_total > 0 && (

{t("comp.manageTitle")}

setDespawnN(e.target.value)} inputMode="numeric" aria-invalid={!dnValid} className="w-20 rounded-md border border-line bg-bg px-3 py-1.5 text-right outline-none focus:border-gold" />

{t("comp.despawnHint")}

)}

{t("comp.startTitle")}

setAutoMax(e.target.value)} inputMode="numeric" disabled={!autoOn} aria-invalid={!maxValid} className="w-24 rounded-md border border-line bg-bg px-3 py-1.5 text-right outline-none focus:border-gold disabled:opacity-40" />
{autoOn && !maxValid && autoMax !== "" &&

{t("comp.startInvalid")}

}

{t("comp.startHint")}

{startNote &&

{startNote}

}
{error &&

{error.human.code === "unknown" ? error.technical : human(error.human).message}

} ); }