import { useEffect, useMemo, useState } from "react"; import { sessionCanUseGmTools } from "../app/releaseFeatures"; import { useShellStore } from "../app/shellStore"; import { fetchBalanceLabArtifact, getBalanceLabJob, getBalanceLabReport, getBalanceLabRuntime, listBalanceLabJobs, startBalanceLabJob, type BalanceLabBossCategory, type BalanceLabJob, type BalanceLabPartySource, type BalanceLabRuntimeStatus, type BalanceLabSpecSelection, type BalanceLabSuiteReport, } from "../app/balanceLabClient"; import { classById } from "../app/characterCatalog"; import { BOSS_TESTING_CATALOG } from "../game/bossTesting"; import { selectableBenchmarkBuildCatalog, type SelectableBenchmarkBuildCatalogEntry, } from "../game/benchmark/benchmarkBuilds"; import { BalanceLabResults } from "./BalanceLabResults"; import { BrandMark, FrontSurface } from "./FrontSurface"; type BossScope = BalanceLabBossCategory | "specific"; const ARTIFACT_LABELS: Readonly> = { "suite-report.html": "Open full report", "suite-report.json": "Download report JSON", "suite-report.md": "Download report Markdown", "party_configurations.csv": "Party configurations CSV", "class_specs_across_parties.csv": "Class/spec totals CSV", "class_abilities_across_parties.csv": "Class/spec ability breakdown CSV", "class_spec_by_boss.csv": "Class/spec by boss CSV", "bosses_across_parties.csv": "Boss totals CSV", "boss_by_party.csv": "Boss by party CSV", "suite_runs.csv": "Every simulation CSV", "suite-config.json": "Exact rerun configuration", }; function errorMessage(error: unknown): string { return error instanceof Error ? error.message : "The Balance Lab request failed."; } function progressPercent(job: BalanceLabJob): number { if (job.status === "complete") return 100; if (job.status === "queued" || job.progress.partiesTotal < 1) return 0; const currentFraction = job.progress.simulationsTotal > 0 ? job.progress.simulationsCompleted / job.progress.simulationsTotal : 0; return Math.max(0, Math.min(99, ((job.progress.partiesCompleted + currentFraction) / job.progress.partiesTotal) * 100)); } function describeJob(job: BalanceLabJob): string { if (job.status === "queued") return "Waiting for the current server job to finish."; if (job.status === "failed") return job.error ?? "The server job failed."; if (job.status === "complete") return job.summary ? `Completed ${job.summary.runs.toLocaleString()} simulations across ${job.summary.bosses.toLocaleString()} bosses and ${job.summary.partyConfigurations.toLocaleString()} party configurations.` : `Completed ${job.progress.partiesTotal} party configurations.`; const party = job.progress.party || job.progress.partiesCompleted + 1; const simulation = job.progress.simulationsTotal > 0 ? ` · current party ${job.progress.simulationsCompleted}/${job.progress.simulationsTotal} boss simulations` : ""; return `Party ${party}/${job.progress.partiesTotal}${simulation}`; } function coveragePartyCount(builds: readonly SelectableBenchmarkBuildCatalogEntry[]): number { const bySource = new Map(); for (const build of builds) bySource.set(build.source, [...(bySource.get(build.source) ?? []), build]); return [...bySource.values()].reduce((total, rows) => { const tanks = rows.filter((build) => build.role === "tank").length; const healers = rows.filter((build) => build.role === "healer").length; const damage = rows.filter((build) => build.role === "damage").length; return total + Math.max(1, tanks, healers, Math.ceil(damage / 3)); }, 0); } export function BalanceLabScreen({ onClose }: { readonly onClose: () => void }) { const session = useShellStore((state) => state.session); const token = session?.accessToken ?? ""; const [source, setSource] = useState("all"); const [specSelection, setSpecSelection] = useState("random"); const [specSearch, setSpecSearch] = useState(""); const [selectedBuildIds, setSelectedBuildIds] = useState([]); const [level, setLevel] = useState(60); const [partyConfigurations, setPartyConfigurations] = useState(10); const [simulationsPerParty, setSimulationsPerParty] = useState(3); const [durationSeconds, setDurationSeconds] = useState(60); const [partySeed, setPartySeed] = useState(1); const [bossScope, setBossScope] = useState("all"); const [bossSearch, setBossSearch] = useState(""); const [selectedBossKeys, setSelectedBossKeys] = useState([]); const [jobs, setJobs] = useState([]); const [selectedJobId, setSelectedJobId] = useState(null); const [jobSearch, setJobSearch] = useState(""); const [jobStatus, setJobStatus] = useState<"all" | BalanceLabJob["status"]>("all"); const [reports, setReports] = useState>>({}); const [reportLoadingId, setReportLoadingId] = useState(null); const [reportError, setReportError] = useState(""); const [runtimeStatus, setRuntimeStatus] = useState(null); const [loading, setLoading] = useState(true); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(""); const selectedJob = jobs.find((job) => job.id === selectedJobId) ?? jobs[0] ?? null; const selectedReport = selectedJob ? reports[selectedJob.id] ?? null : null; const visibleJobs = useMemo(() => { const query = jobSearch.trim().toLowerCase(); return jobs.filter((job) => ( (jobStatus === "all" || job.status === jobStatus) && (!query || `${job.requestedBy} ${job.spec.source} ${job.spec.level} ${job.spec.specSelection ?? "random"} ${job.id} ${job.status}`.toLowerCase().includes(query)) )); }, [jobSearch, jobStatus, jobs]); const availableBuilds = useMemo(() => selectableBenchmarkBuildCatalog( Number.isFinite(level) ? level : 60, ).filter((build) => source === "all" || build.source === source).sort((left, right) => ( left.source.localeCompare(right.source) || classById(left.classId).name.localeCompare(classById(right.classId).name) || left.orientation.localeCompare(right.orientation) || left.role.localeCompare(right.role) )), [level, source]); const selectedBuildSet = useMemo(() => new Set(selectedBuildIds), [selectedBuildIds]); const selectedBuilds = useMemo(() => availableBuilds.filter((build) => selectedBuildSet.has(build.id)), [ availableBuilds, selectedBuildSet, ]); const filteredBuilds = useMemo(() => { const query = specSearch.trim().toLowerCase(); return availableBuilds.filter((build) => !query || `${classById(build.classId).name} ${build.orientation} ${build.role} ${build.source} ${build.id}`.toLowerCase().includes(query)); }, [availableBuilds, specSearch]); const filteredBosses = useMemo(() => { const query = bossSearch.trim().toLowerCase(); return BOSS_TESTING_CATALOG.filter((boss) => !query || `${boss.name} ${boss.dungeonTitle} ${boss.key} ${boss.category}`.toLowerCase().includes(query)); }, [bossSearch]); const selectedBossSet = useMemo(() => new Set(selectedBossKeys), [selectedBossKeys]); const bossCount = bossScope === "specific" ? selectedBossKeys.length : BOSS_TESTING_CATALOG.filter((boss) => bossScope === "all" || boss.category === bossScope).length; const coverageBuilds = specSelection === "all" ? availableBuilds : selectedBuilds; const partyCount = specSelection === "random" ? partyConfigurations * (source === "all" ? 3 : 1) : coveragePartyCount(coverageBuilds); const coveredSpecCount = specSelection === "all" ? availableBuilds.length : selectedBuilds.length; const estimatedRuns = partyCount * bossCount * simulationsPerParty; useEffect(() => { if (!token) return; let cancelled = false; setLoading(true); void Promise.all([listBalanceLabJobs(token), getBalanceLabRuntime(token)]).then(([nextJobs, runtime]) => { if (cancelled) return; setJobs(nextJobs); setRuntimeStatus(runtime); setSelectedJobId((current) => current ?? nextJobs[0]?.id ?? null); setError(""); }).catch((reason) => { if (!cancelled) setError(errorMessage(reason)); }).finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; }, [token]); useEffect(() => { if (!token || !selectedJob || (selectedJob.status !== "queued" && selectedJob.status !== "running")) return; let cancelled = false; const timer = window.setInterval(() => { void getBalanceLabJob(selectedJob.id, token).then((updated) => { if (cancelled) return; setJobs((current) => [updated, ...current.filter((job) => job.id !== updated.id)]); }).catch((reason) => { if (!cancelled) setError(errorMessage(reason)); }); }, 1_500); return () => { cancelled = true; window.clearInterval(timer); }; }, [selectedJob, token]); useEffect(() => { if (!token || !selectedJob || selectedJob.status !== "complete" || selectedReport || !selectedJob.artifacts.includes("suite-report.json")) return; let cancelled = false; setReportLoadingId(selectedJob.id); setReportError(""); void getBalanceLabReport(selectedJob.id, token).then((report) => { if (!cancelled) setReports((current) => ({ ...current, [selectedJob.id]: report })); }).catch((reason) => { if (!cancelled) setReportError(errorMessage(reason)); }).finally(() => { if (!cancelled) setReportLoadingId((current) => current === selectedJob.id ? null : current); }); return () => { cancelled = true; }; }, [selectedJob, selectedReport, token]); if (!sessionCanUseGmTools(session)) { return (

Game Master access required

Server simulations are available only to server-authorized GM accounts.

); } const toggleBoss = (key: string) => { setSelectedBossKeys((current) => current.includes(key) ? current.filter((candidate) => candidate !== key) : [...current, key]); }; const toggleBuild = (id: string) => { setSelectedBuildIds((current) => current.includes(id) ? current.filter((candidate) => candidate !== id) : [...current, id]); }; const run = async () => { if (!runtimeStatus?.available) { setError(runtimeStatus?.error ?? "The server Balance Lab runtime is unavailable."); return; } if (bossScope === "specific" && selectedBossKeys.length === 0) { setError("Select at least one boss for a specific-boss run."); return; } if (specSelection === "specific" && selectedBuilds.length === 0) { setError("Select at least one class/spec for a specific-spec run."); return; } setSubmitting(true); setError(""); try { const job = await startBalanceLabJob({ source, specSelection, selectedBuildIds: specSelection === "specific" ? selectedBuilds.map((build) => build.id) : [], level, partyConfigurations: specSelection === "random" ? partyConfigurations : partyCount, simulationsPerParty, durationSeconds, partySeed, bossCategory: bossScope === "specific" ? "all" : bossScope, bossKeys: bossScope === "specific" ? selectedBossKeys : [], }, token); setJobs((current) => [job, ...current.filter((candidate) => candidate.id !== job.id)]); setSelectedJobId(job.id); } catch (reason) { setError(errorMessage(reason)); } finally { setSubmitting(false); } }; const openArtifact = async (job: BalanceLabJob, name: string) => { const preview = name.endsWith(".html") ? window.open("", "_blank") : null; setError(""); try { const blob = await fetchBalanceLabArtifact(job.id, name, token); const url = URL.createObjectURL(blob); if (preview) preview.location.href = url; else { const anchor = document.createElement("a"); anchor.href = url; anchor.download = name; anchor.click(); } window.setTimeout(() => URL.revokeObjectURL(url), 60_000); } catch (reason) { preview?.close(); setError(errorMessage(reason)); } }; return (
Server-authorized GM toolBalance Lab

New automatic sweep

Simulation setup

This mode runs on the game server. The browser submits the job and may be closed while the server continues.

{runtimeStatus &&
{runtimeStatus.available ? "Server runtime ready" : "Server runtime unavailable"} {runtimeStatus.available ? runtimeStatus.version : `${runtimeStatus.error} Install Python 3 in the server container, set BALANCE_LAB_PYTHON=python3, and restart the app.`}
}
{specSelection === "random" ? : }
{specSelection !== "random" &&

{specSelection === "all" ? `${coveredSpecCount} class/spec builds will be covered at least once across the minimum valid party set.` : `${coveredSpecCount} selected class/spec builds will be covered; unselected specs fill required party roles.`}

} {specSelection === "specific" && (
setSpecSearch(event.currentTarget.value)} placeholder="Search class, spec, role, or source" /> {selectedBuilds.length} selected
{filteredBuilds.map((build) => )}
)} {bossScope === "specific" && (
setBossSearch(event.currentTarget.value)} placeholder="Search boss, dungeon, or key" />{selectedBossKeys.length} selected
{filteredBosses.map((boss) => )}
)}
Party configurations {partyCount.toLocaleString()}Class/spec coverage {specSelection === "random" ? "Random" : coveredSpecCount.toLocaleString()}Bosses {bossCount.toLocaleString()}Total simulations {estimatedRuns.toLocaleString()}

To spend this device's CPU instead, run npm run balance:lab from the project checkout.

{error &&

{error}

}

Saved on server

Run history

setJobSearch(event.currentTarget.value)} />
{visibleJobs.map((job) => )} {!loading && visibleJobs.length === 0 &&

No saved runs match these filters.

}
{selectedJob?.status === "complete" &&
{reportLoadingId === selectedJob.id &&

Loading this run's complete analysis…

} {reportError && !selectedReport &&

{reportError}

} {selectedReport && }
}
); }