import { ForceStopDialog } from "./ForceStopDialog"; import { serverLifecycle } from "@/lib/serverLifecycle"; import { serverUpdateBlocksRestart } from "@/lib/serverUpdate"; import { dismissClientJob, startClientUpdate, stopClientJob, syncClient, useClientJob } from "@/lib/clientJob"; import { useCallback, useEffect, useRef, useState } from "react"; import { AlertTriangle, Loader2, X } from "lucide-react"; import { api, asUiError, type ClientInfo, type Human, type Performance, type Population, type ServerSummary, type ServiceStatus, type StatusView } from "@/lib/api"; import { cn, formatBytes, formatUptime } from "@/lib/utils"; import { useHuman, useT } from "@/i18n"; import { applyServerUpdate, useServerUpdate } from "@/lib/serverUpdate"; import { checkClient, useClientStatus } from "@/lib/clientUpdate"; import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog"; import { RealmlistMenu } from "@/screens/RealmlistMenu"; import { RealmPicker } from "@/screens/RealmPicker"; import { CrashHistoryModal } from "@/screens/CrashHistoryModal"; import { ListingChip } from "@/screens/PublishCard"; import { PublishRealmDialog } from "@/screens/PublishDialog"; import { useRegistryStatus } from "@/lib/registry"; import { usePublishRealms, type PublishRealm } from "@/lib/publishRealms"; import { useAutoRestart } from "@/lib/autoRestartPrefs"; import { SplitButton } from "@/components/ui/split-button"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; type Action = "starting" | "stopping" | "restarting" | null; type Failure = { human: Human; technical: string }; /** World loop speed from the server's own timing report, with a simple smooth / busy / lagging verdict. */ function TickRate({ perf }: { perf: Performance }) { const t = useT(); const level = perf.mean_ms <= 50 ? "good" : perf.mean_ms <= 100 ? "busy" : "lag"; const tone = { good: "text-ok bg-ok/15", busy: "text-warn bg-warn/15", lag: "text-bad bg-bad/15" }[level]; const bar = { good: "bg-ok", busy: "bg-warn", lag: "bg-bad" }[level]; const fill = Math.max(4, Math.min(100, Math.round(100 - perf.mean_ms))); return (
{t("overview.tick")} {t(level === "good" ? "overview.tickGood" : level === "busy" ? "overview.tickBusy" : "overview.tickLag")}
{Math.round(perf.ticks_per_sec)} {t("overview.tickUnit")}

{t("overview.tickDetail", { mean: perf.mean_ms, p95: perf.p95_ms, max: perf.max_ms })}

); } function Row({ label, s }: { label: string; s: ServiceStatus }) { const t = useT(); const running = s.state === "running"; const starting = s.state === "starting"; const crashed = s.state === "crashed"; return (
{label} {running ? t("status.running") : starting ? t("status.starting") : crashed ? t("status.crashed") : t("status.stopped")}
); } export function Overview({ server, companions = true, onForget, onOpenUpdates, onRealmChanged, onReport }: { server: ServerSummary; /** the companions module is on */ companions?: boolean; onForget: () => Promise; onOpenUpdates: () => void; onRealmChanged: () => void; /** open the problem report, which collects the diagnostics */ onReport: () => void }) { const t = useT(); const human = useHuman(); const [status, setStatus] = useState(null); // With both worlds started together, each realm gets its own card; the first realm owns the database and auth. const [realms, setRealms] = useState<{ first: string; second: string; reborn: string } | null>(null); const bothWorlds = !!status?.observed.secondary_world || !!status?.observed.reborn_world; useEffect(() => { if (!bothWorlds) { setRealms(null); return; } let alive = true; void api.realmProfiles(server.id).then((r) => { if (!alive) return; const name = (m: "coa" | "wildcard" | "reborn") => (m === "coa" ? "Conquest of Azeroth" : m === "reborn" ? "Warcraft Reborn" : "Wildcard"); setRealms({ first: name(r.active), second: name(r.active === "coa" ? "wildcard" : "coa"), reborn: name("reborn") }); }).catch(() => { if (alive) setRealms(null); }); return () => { alive = false; }; }, [bothWorlds, server.id]); const [action, setAction] = useState(null); const [realmBusy, setRealmBusy] = useState(false); const [stopFailed, setStopFailed] = useState(false); const [confirmForce, setConfirmForce] = useState(false); const [failure, setFailure] = useState(null); const [showDetails, setShowDetails] = useState(false); const [pop, setPop] = useState(null); const [client, setClient] = useState(undefined); const [dialog, setDialog] = useState(null); const clientStatus = useClientStatus(server.id).status; const [playing, setPlaying] = useState(false); const job = useClientJob(server.id); const jobBusy = job.phase === "scanning" || job.phase === "working"; const jobPct = job.step && job.step.total > 0 ? Math.min(100, Math.floor((job.step.done / job.step.total) * 100)) : 0; const [keepMine, setKeepMine] = useState(true); const [perf, setPerf] = useState(null); const upd = useServerUpdate(server.id); const visibleFailure = failure ?? upd.stateError ?? upd.uiError; const needsDecision = (upd.preview?.conflicts.length ?? 0) > 0; const runServerUpdate = async () => { setFailure(null); setShowDetails(false); await applyServerUpdate(server.id); }; const [startBots, setStartBots] = useState(undefined); const [autoRestart, setAutoRestart] = useAutoRestart(server.id); const autoRestartRef = useRef(autoRestart); autoRestartRef.current = autoRestart; const [crashCount, setCrashCount] = useState(0); const crashCountRef = useRef(0); const [showCrashModal, setShowCrashModal] = useState(false); const publishRealms = usePublishRealms(server.id, server.name); const { status: registry } = useRegistryStatus(5000); const [publishing, setPublishing] = useState(null); // The realm a card shows: the first card is the main realm, then the realm that starts next to it, then Warcraft Reborn. const chipOf = (realm: PublishRealm | undefined) => realm && r.local_id === realm.localId)} hasUrl={!!registry?.url} onOpen={() => setPublishing(realm)} />; const mainRealm = publishRealms?.[0]; const secondRealm = publishRealms?.find((r) => r !== mainRealm && r.mode !== "reborn"); const rebornRealm = publishRealms?.find((r) => r !== mainRealm && r.mode === "reborn"); const [hasCrashHistory, setHasCrashHistory] = useState(false); const [crashLoopPaused, setCrashLoopPaused] = useState(false); const [crashRestartNotice, setCrashRestartNotice] = useState(null); const lifecycle = serverLifecycle(server.id); const actionRef = useRef(null); const crashTimestampsRef = useRef([]); const pollRef = useRef<() => Promise>(undefined); useEffect(() => { let active = true; void api .listCrashes(server.id, 1) .then((items) => { if (active && items.length > 0) setHasCrashHistory(true); }) .catch(() => {}); return () => { active = false; }; }, [server.id]); useEffect(() => { void api .settings(server.id, "bots") .then((v) => { const on = v.settings.find((s) => s.key === "CoaBots.AutoLoginOnStartup"); const max = v.settings.find((s) => s.key === "CoaBots.AutoLogin.MaxCount"); setStartBots(on?.value === true && typeof max?.value === "number" ? max.value : null); }) .catch(() => setStartBots(undefined)); }, [server.id]); const alive = useRef(true); useEffect(() => { if (job.phase === "done" || job.phase === "current") void api.clientInfo(server.id).then(setClient).catch(() => undefined); }, [job.phase, server.id]); const run = useCallback( async (kind: Exclude) => { setStopFailed(false); lifecycle.request(kind); if (kind !== "stopping") { setCrashLoopPaused(false); setCrashRestartNotice(null); } setFailure(null); setShowDetails(false); setAction(kind); actionRef.current = kind; try { if (kind !== "starting") { const out = await api.stop(server.id).catch(e => { setStopFailed(true); throw e; }); if (!out.ok) { setStopFailed(true); throw { human: out.human, technical: out.output }; } } if (kind !== "stopping") { setAction("starting"); actionRef.current = "starting"; const out = await api.start(server.id); if (!out.ok) throw { human: out.human, technical: out.output }; } } catch (e) { const ui = asUiError(e); setFailure({ human: ui.human ?? asUiError(String(e)).human, technical: ui.technical }); } finally { lifecycle.complete(kind); setAction(null); actionRef.current = null; void pollRef.current?.(); } }, [server.id], ); async function forceStop() { setConfirmForce(false); setFailure(null); setShowDetails(false); setStopFailed(false); lifecycle.request("stopping"); setAction("stopping"); actionRef.current = "stopping"; try { const out = await api.forceStop(server.id); if (!out.ok) throw { human: out.human, technical: out.output }; } catch (e) { setStopFailed(true); setFailure(asUiError(e)); } finally { lifecycle.complete("stopping"); setAction(null); actionRef.current = null; void pollRef.current?.(); } } const poll = useCallback(async () => { try { const s = await api.status(server.id); if (alive.current) setStatus(s); const isWorldRunning = s.observed.world.state === "running"; if (isWorldRunning) { lifecycle.observe(true, actionRef.current !== null, serverUpdateBlocksRestart(server.id)); const p = await api.population(server.id).catch(() => null); if (alive.current) setPop(p); } else { if (alive.current) setPop(null); if ( lifecycle.observe(false, actionRef.current !== null, serverUpdateBlocksRestart(server.id)) ) { setHasCrashHistory(true); const now = Date.now(); const recent = crashTimestampsRef.current.filter((ts) => now - ts < 180000); recent.push(now); crashTimestampsRef.current = recent; crashCountRef.current += 1; const currentCrashCount = crashCountRef.current; setCrashCount(currentCrashCount); if (recent.length >= 3) { setCrashLoopPaused(true); setCrashRestartNotice(null); } else if (autoRestartRef.current) { setCrashRestartNotice(t("crash.restartNotice", { n: currentCrashCount })); void run("starting"); } } } } catch { /* transient; next poll retries */ } }, [server.id, t, run]); useEffect(() => { pollRef.current = poll; }, [poll]); // The tick rate comes from the server console (one short connection per reading), so it is read less often. const worldUp = status?.observed.world.state === "running"; useEffect(() => { if (!worldUp) { setPerf(null); return; } let live = true; const read = () => void api.performance(server.id).then((p) => live && setPerf(p)).catch(() => {}); read(); const iv = setInterval(read, 10000); return () => { live = false; clearInterval(iv); }; }, [worldUp, server.id]); useEffect(() => { alive.current = true; void api.clientInfo(server.id).then(setClient).catch(() => setClient(null)); void poll(); const t = setInterval(poll, 2000); return () => { alive.current = false; clearInterval(t); }; }, [poll]); async function play() { setFailure(null); setShowDetails(false); setPlaying(true); try { const out = await api.play(server.id); if (!out.ok) throw { human: out.human, technical: out.output }; } catch (e) { const ui = asUiError(e); setFailure({ human: ui.human ?? asUiError(String(e)).human, technical: ui.technical }); } finally { setPlaying(false); void poll(); } } if (!status) return

{t("overview.checking")}

; if (!status.path_exists) { return (

{t("overview.missingTitle")}

{t("overview.missingText", { path: server.path })}

); } const { mysql, auth, world, secondary_world, reborn_world } = status.observed; const all = [mysql, auth, world, ...(secondary_world ? [secondary_world] : []), ...(reborn_world ? [reborn_world] : [])]; const running = all.every((s) => s.state === "running"); const anyUp = all.some((s) => s.state !== "stopped"); const transitioning = action !== null || status.busy || realmBusy; const conflict = all.find((s) => s.conflict)?.conflict ?? null; const headline = realmBusy ? t("realm.switching") : transitioning ? action === "stopping" ? t("status.stopping") : t("status.starting") : running ? t("status.online") : anyUp ? t("status.attention") : t("status.offline"); const tone = transitioning ? "text-warn" : running ? "text-ok" : anyUp ? "text-warn" : "text-muted"; return (

{server.name}

{server.path}

{ onRealmChanged(); void poll(); }} />
{realms ? `${realms.first} · ${t("overview.server")}` : t("overview.server")}{chipOf(mainRealm)}
{headline}
{(crashCount > 0 || hasCrashHistory) && ( )}
{crashRestartNotice && !crashLoopPaused && (
{crashRestartNotice}
)} {crashLoopPaused && (
{t("crash.loopPaused")}
)} {!transitioning && !running && anyUp && (

{t("overview.reportHint")}{" "}

)}
{t("overview.uptime")}
{world.state === "running" ? formatUptime(world.uptime_secs) : "—"}
{t("overview.players")}
{pop ? `${pop.players_online}` : "—"}{pop && pop.bots_online > 0 ? {t("overview.bots", { n: pop.bots_online })} : null}
{companions && startBots !== undefined && (

{startBots === null ? t("overview.startBotsOff") : t("overview.startBots", { n: startBots })}

)} {perf && }
{running ? ( ) : upd.available ? ( (needsDecision ? onOpenUpdates() : void runServerUpdate()), children: <>{upd.applying && }{upd.applying ? t("btn.updating") : needsDecision ? t("overview.openUpdates") : t("btn.update")} }} secondary={{ disabled: transitioning || upd.applying, onClick: () => run("starting"), children: t("btn.startWithoutUpdate") }} /> ) : ( )} {running && ( )} {running && upd.available && ( )} {anyUp && !running && ( )}
{client && } {client && jobBusy ? (
{job.phase === "scanning" ? t("client.job.checking") : t("client.job.updating")} {jobPct}% {job.step && job.step.phase === "download" && job.step.bytes_per_sec > 0 ? ` · ${t("client.dl.speed", { speed: formatBytes(job.step.bytes_per_sec) })}` : ""}
) : client && (clientStatus?.update_available || job.phase === "choose") ? ( void startClientUpdate(server.id), children: t("btn.updateClient") }} secondary={{ disabled: realmBusy || playing || upd.applying, onClick: () => void play(), children: <>{playing && }{t("btn.playWithoutUpdate")} }} /> ) : client ? ( ) : client === null ? ( ) : null}
{(crashCount > 0 || hasCrashHistory) && ( )}
{anyUp && !running && !transitioning && (

{t("overview.partial")}

)} {job.phase === "choose" && job.plan && (

{t("client.upd.modifiedTitle", { n: job.plan.items.filter((i) => i.kind === "modified").length })}

{t("client.upd.modifiedText")}

)} {job.phase === "done" &&

{t("client.upd.done")}

} {job.phase === "current" &&

{t("client.upd.upToDate", { v: job.plan?.version ?? "" })}

} {job.phase === "stopped" && (

{t("client.dl.cancelled")}

)} {job.phase === "failed" && job.error && (

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

)} {upd.result && "committed" in upd.result && !!upd.result.preexistingCharacters &&

{t("upd.preexistingCharacters", { n: upd.result.preexistingCharacters })}

} {upd.available && upd.preview && (

{t("overview.updateAvail", { to: upd.preview.to_version, from: upd.preview.from_version ?? "?" })}

{upd.preview.latest_version &&

{t("upd.intermediate", { to: upd.preview.to_version, latest: upd.preview.latest_version })}

} {needsDecision &&

{t("overview.updateConflicts")}

} {upd.applying && (

{t("overview.updatingNote")}

{upd.step ?? ""} {upd.percent}%
)}
)} {secondary_world && (
{realms ? `${realms.second} · ${t("overview.server")}` : t("realm.secondWorld")}{chipOf(secondRealm)}
{secondary_world.state === "running" ? t("status.online") : secondary_world.state === "starting" ? t("status.starting") : t("status.offline")}
{t("overview.uptime")}
{secondary_world.state === "running" ? formatUptime(secondary_world.uptime_secs) : "—"}

{t("realm.bothRunning")}

)} {reborn_world && (
{realms ? `${realms.reborn} · ${t("overview.server")}` : t("realm.rebornWorld")}{chipOf(rebornRealm)}
{reborn_world.state === "running" ? t("status.online") : reborn_world.state === "starting" ? t("status.starting") : t("status.offline")}
{t("overview.uptime")}
{reborn_world.state === "running" ? formatUptime(reborn_world.uptime_secs) : "—"}

{t("realm.bothRunning")}

)} {conflict && !anyUp && (

{t("overview.portTitle")}

{t("overview.portText", { port: conflict.port, exe: conflict.exe ? ` (${conflict.exe})` : "" })}

)} {visibleFailure && (

{human(visibleFailure.human).title}

{human(visibleFailure.human).message}

{anyUp && (stopFailed || /still stopping|could not be stopped|Stop the server before updating/i.test(visibleFailure.technical)) && }
{showDetails && (
              {visibleFailure.technical || t("common.noOutput")}
            
)}
)} {dialog && ( setDialog(null)} onChanged={() => { void api.clientInfo(server.id).then(setClient).catch(() => setClient(null)); void checkClient(server.id); }} onPlayAnyway={() => void play()} /> )} {publishing && setPublishing(null)} />} {confirmForce && setConfirmForce(false)} onConfirm={() => void forceStop()} />} {showCrashModal && ( setShowCrashModal(false)} /> )}
); }