From 79846186eadfaea452568b866a43a7a5c64a34f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Wed, 30 Sep 2026 23:10:22 +0500 Subject: [PATCH] Bots at start on the Bots page and the main card; adding companions raises the start limit; large batches are created offline with equipment when the server is stopped Co-Authored-By: Claude Sonnet 5.5 --- crates/coa-core/examples/companions_e2e.rs | 19 +++++++ crates/coa-core/src/companions.rs | 53 +++++++++++++++++- src-tauri/src/lib.rs | 37 ++++++++++++- src/i18n/locales/de.ts | 16 ++++++ src/i18n/locales/en.ts | 16 ++++++ src/i18n/locales/es.ts | 16 ++++++ src/i18n/locales/fr.ts | 16 ++++++ src/i18n/locales/ru.ts | 16 ++++++ src/lib/api.ts | 2 +- src/screens/CompanionsCard.tsx | 62 +++++++++++++++++++++- src/screens/Overview.tsx | 15 ++++++ 11 files changed, 262 insertions(+), 6 deletions(-) create mode 100644 crates/coa-core/examples/companions_e2e.rs diff --git a/crates/coa-core/examples/companions_e2e.rs b/crates/coa-core/examples/companions_e2e.rs new file mode 100644 index 0000000..98af3fe --- /dev/null +++ b/crates/coa-core/examples/companions_e2e.rs @@ -0,0 +1,19 @@ +//! Adds the template characters to a scratch install and creates companions offline. usage: companions_e2e +//! The folder name must contain "installtest" and its database must already be running (Scripts/manage.py start-mysql). +use coa_core::db::{Account, Db}; + +fn main() { + let a: Vec = std::env::args().skip(1).collect(); + let root = std::path::PathBuf::from(&a[0]); + assert!(a[0].to_lowercase().contains("installtest"), "refusing to touch a server that is not a disposable test install"); + let count: u32 = a[1].parse().unwrap(); + let db = Db::from_repack(&root, Account::Admin).expect("db"); + println!("templates before: {}", coa_core::companions::template_count(&db).unwrap()); + println!("added: {}", coa_core::companions::ensure_templates(&db).unwrap()); + println!("templates after: {}", coa_core::companions::template_count(&db).unwrap()); + let t = std::time::Instant::now(); + match coa_core::companions::offline_create(&root, &root.join("companions-e2e.log"), count) { + Ok(tail) => println!("offline create ok in {:?}:\n{tail}", t.elapsed()), + Err(e) => println!("offline create FAILED: {e}"), + } +} diff --git a/crates/coa-core/src/companions.rs b/crates/coa-core/src/companions.rs index ae3026d..db67c05 100644 --- a/crates/coa-core/src/companions.rs +++ b/crates/coa-core/src/companions.rs @@ -48,8 +48,57 @@ pub fn ensure_templates(db: &Db) -> Result { Ok(true) } -pub fn has_seed_file(_root: &Path) -> bool { - !SQL.is_empty() +/// The bot module's offline factory ships with the server package; it creates fully equipped bots straight in the +/// database while the world server is stopped (fast and safe for large batches). +pub const OFFLINE_FACTORY: &str = "Extras/CoABotTools/offline_bot_factory.py"; + +/// Batches at least this large are created offline when the server happens to be stopped. +pub const OFFLINE_MIN: u32 = 100; + +pub fn offline_factory(root: &Path) -> Option { + let p = root.join(OFFLINE_FACTORY); + (p.is_file() && root.join("Runtime/python/python.exe").is_file() && root.join("mysql/bin/mysql.exe").is_file() && root.join("mysql/admin-client.ini").is_file()).then_some(p) +} + +/// Run the offline factory for `count` leveled bots. The database must be running and the world/auth servers stopped. +/// Returns the tail of its report. Credentials are passed as a file path only, never on the command line. +pub fn offline_create(root: &Path, log: &Path, count: u32) -> Result { + use std::process::{Command, Stdio}; + let script = offline_factory(root).ok_or_else(|| crate::error::Error::Invalid("The offline bot factory is not part of this server.".into()))?; + if let Some(dir) = log.parent() { + fs::create_dir_all(dir)?; + } + let out = fs::File::create(log)?; + let err = out.try_clone()?; + let mut child = Command::new(root.join("Runtime/python/python.exe")) + .arg(&script) + .args(["--count", &count.to_string(), "--leveled", "--mysql-exe"]) + .arg(root.join("mysql/bin/mysql.exe")) + .arg("--defaults-file") + .arg(root.join("mysql/admin-client.ini")) + .current_dir(root) + .stdin(Stdio::null()) + .stdout(Stdio::from(out)) + .stderr(Stdio::from(err)) + .spawn()?; + let started = std::time::Instant::now(); + let status = loop { + if let Some(s) = child.try_wait()? { + break s; + } + if started.elapsed() > std::time::Duration::from_secs(45 * 60) { + let _ = child.kill(); + return Err(crate::error::Error::Invalid("Creating the companions took too long and was stopped.".into())); + } + std::thread::sleep(std::time::Duration::from_millis(500)); + }; + let text = fs::read_to_string(log).unwrap_or_default(); + let tail: Vec<&str> = text.lines().rev().take(6).collect::>().into_iter().rev().collect(); + if status.success() { + Ok(tail.join("\n")) + } else { + Err(crate::error::Error::Invalid(format!("The bot factory reported an error: {}", tail.join(" | ")))) + } } #[cfg(test)] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a054bd7..96a7965 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -544,6 +544,8 @@ fn companion_sizes() -> CompanionSizes { #[derive(Serialize)] struct CompanionsResult { spawned: Option, + /// Created offline with their equipment (server was stopped and the batch was large). + created: Option, } /// Turn on automatic bot login for `count` bots and, if the server is running, ask it to create them. @@ -558,9 +560,40 @@ async fn add_companions(state: State<'_, AppState>, id: String, count: u32) -> s let meta = meta_dir(&root)?; let mut changes = BTreeMap::new(); changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true)); - changes.insert("CoaBots.AutoLogin.MaxCount".to_string(), Value::from(count)); + // Every companion, old and new, should come back at the next start, so the start-up limit only ever grows here. + let existing_max = config::load(&root, Scope::Bots) + .ok() + .and_then(|v| v.settings.iter().find(|s| s.meta.key == "CoaBots.AutoLogin.MaxCount").and_then(|s| s.value.as_u64())) + .unwrap_or(0) as u32; + let already = coa_core::population::query(&root).map(|p| p.bots_total).unwrap_or(0); + changes.insert("CoaBots.AutoLogin.MaxCount".to_string(), Value::from(existing_max.max(already + count).min(5000))); config::save(&root, &meta, Scope::Bots, &changes)?; let o = coa_core::process::observe(&root, &layout::read_ports(&root)); + // Large batches while the server is stopped: create them in the database right now, fully equipped. + if o.world.state == coa_core::process::ServiceState::Stopped + && o.auth.state == coa_core::process::ServiceState::Stopped + && count >= coa_core::companions::OFFLINE_MIN + && coa_core::companions::offline_factory(&root).is_some() + { + let started_db = o.mysql.state != coa_core::process::ServiceState::Running; + if started_db { + let out = driver::run(&root, Verb::StartMysql)?; + if !out.ok { + return Err(Error::Invalid("The database could not be started.".into())); + } + } + let made = (|| -> Result<()> { + coa_core::companions::ensure_templates(&coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin)?)?; + coa_core::companions::offline_create(&root, &meta.join("logs").join("companions-offline.log"), count)?; + Ok(()) + })(); + if started_db { + let _ = driver::run(&root, Verb::StopAll); + } + made?; + tracing::info!(count, "companions created offline"); + return Ok(CompanionsResult { spawned: None, created: Some(count) }); + } let spawned = if o.world.state == coa_core::process::ServiceState::Running { // Older servers have no template characters to copy bots from: add them first. coa_core::companions::ensure_templates(&coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin)?)?; @@ -571,7 +604,7 @@ async fn add_companions(state: State<'_, AppState>, id: String, count: u32) -> s None }; tracing::info!(count, spawned = spawned.is_some(), "companions requested"); - Ok(CompanionsResult { spawned }) + Ok(CompanionsResult { spawned, created: None }) }) .await } diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 68bb44f..2ac468c 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -527,6 +527,22 @@ const de: Partial> = { "fr.g.ts.4": "Tailscale muss bei euch beiden laufen, solange ihr spielt.", "fr.g.ts.admin": "Tailscale-Verwaltungsseite öffnen", "fr.g.ts.share": "So funktioniert das Teilen (tailscale.com)", + + // Bots at start + "comp.startTitle": "Bots beim Serverstart", + "comp.startAuto": "Bots melden sich beim Serverstart automatisch an", + "comp.startCount": "Wie viele sich anmelden", + "comp.startSave": "Speichern", + "comp.startSaved": "Gespeichert. Gilt ab dem nächsten Serverstart.", + "comp.startHint": "Bots, die sich nicht anmelden, bleiben gespeichert und können später online gebracht werden.", + "comp.startInvalid": "Gib eine ganze Zahl von 0 bis 5000 ein.", + + // Overview start bots + "overview.startBots": "Bots melden sich beim Start an: {n}", + "overview.startBotsOff": "Bots melden sich beim Start nicht an", + + // Offline bots + "comp.offlineDone": "{n} Begleiter samt Ausrüstung erstellt. Sie melden sich beim Serverstart an.", }; export default de; diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index c775177..7dc5c08 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -527,6 +527,22 @@ const en = { "fr.g.ts.4": "Both of you must keep Tailscale running while you play.", "fr.g.ts.admin": "Open the Tailscale admin page", "fr.g.ts.share": "How sharing works (tailscale.com)", + + // Bots at start + "comp.startTitle": "Bots at server start", + "comp.startAuto": "Bots log in automatically when the server starts", + "comp.startCount": "How many log in", + "comp.startSave": "Save", + "comp.startSaved": "Saved. It applies the next time the server starts.", + "comp.startHint": "Bots that do not log in stay saved and can be brought online later.", + "comp.startInvalid": "Enter a whole number from 0 to 5000.", + + // Overview start bots + "overview.startBots": "Bots log in at start: {n}", + "overview.startBotsOff": "Bots log in at start: off", + + // Offline bots + "comp.offlineDone": "Created {n} companions with their equipment. They log in when the server starts.", } as const; export default en; diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 65f5696..be3d469 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -527,6 +527,22 @@ const es: Partial> = { "fr.g.ts.4": "Tailscale debe seguir en marcha en ambos equipos mientras jugáis.", "fr.g.ts.admin": "Abrir la página de administración de Tailscale", "fr.g.ts.share": "Cómo funciona compartir (tailscale.com)", + + // Bots at start + "comp.startTitle": "Bots al iniciar el servidor", + "comp.startAuto": "Los bots inician sesión automáticamente al arrancar el servidor", + "comp.startCount": "Cuántos inician sesión", + "comp.startSave": "Guardar", + "comp.startSaved": "Guardado. Se aplica la próxima vez que se inicie el servidor.", + "comp.startHint": "Los bots que no inician sesión quedan guardados y se pueden conectar más tarde.", + "comp.startInvalid": "Introduce un número entero de 0 a 5000.", + + // Overview start bots + "overview.startBots": "Bots que inician sesión al arrancar: {n}", + "overview.startBotsOff": "Bots al arrancar: desactivado", + + // Offline bots + "comp.offlineDone": "Se crearon {n} compañeros con su equipo. Iniciarán sesión cuando arranque el servidor.", }; export default es; diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index a4ad5b7..94512d7 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -527,6 +527,22 @@ const fr: Partial> = { "fr.g.ts.4": "Tailscale doit rester lancé chez vous deux pendant que vous jouez.", "fr.g.ts.admin": "Ouvrir la page d’administration de Tailscale", "fr.g.ts.share": "Comment fonctionne le partage (tailscale.com)", + + // Bots at start + "comp.startTitle": "Bots au démarrage du serveur", + "comp.startAuto": "Les bots se connectent automatiquement au démarrage du serveur", + "comp.startCount": "Combien se connectent", + "comp.startSave": "Enregistrer", + "comp.startSaved": "Enregistré. S’applique au prochain démarrage du serveur.", + "comp.startHint": "Les bots qui ne se connectent pas restent enregistrés et peuvent être mis en ligne plus tard.", + "comp.startInvalid": "Saisissez un nombre entier de 0 à 5000.", + + // Overview start bots + "overview.startBots": "Bots connectés au démarrage : {n}", + "overview.startBotsOff": "Bots connectés au démarrage : aucun", + + // Offline bots + "comp.offlineDone": "{n} compagnons créés avec leur équipement. Ils se connecteront au démarrage du serveur.", }; export default fr; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 0926a7a..bf79b50 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -527,6 +527,22 @@ const ru: Partial> = { "fr.g.ts.4": "Пока вы играете, Tailscale должен быть запущен у обоих.", "fr.g.ts.admin": "Открыть страницу администрирования Tailscale", "fr.g.ts.share": "Как работает предоставление доступа (tailscale.com)", + + // Bots at start + "comp.startTitle": "Боты при запуске сервера", + "comp.startAuto": "Боты входят в игру автоматически при запуске сервера", + "comp.startCount": "Сколько входит", + "comp.startSave": "Сохранить", + "comp.startSaved": "Сохранено. Вступит в силу при следующем запуске сервера.", + "comp.startHint": "Боты, которые не входят, остаются сохранёнными, их можно вывести в сеть позже.", + "comp.startInvalid": "Введите целое число от 0 до 5000.", + + // Overview start bots + "overview.startBots": "Боты входят при запуске: {n}", + "overview.startBotsOff": "Боты при запуске не входят", + + // Offline bots + "comp.offlineDone": "Создано компаньонов: {n}, сразу со снаряжением. Они войдут в игру при запуске сервера.", }; export default ru; diff --git a/src/lib/api.ts b/src/lib/api.ts index 915d224..f147472 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -292,7 +292,7 @@ export const api = { openLink: (url: string) => invoke("open_link", { url }), performance: (id: string) => invoke("get_performance", { id }), companionSizes: () => invoke("companion_sizes"), - addCompanions: (id: string, count: number) => invoke<{ spawned: string | null }>("add_companions", { id, count }), + addCompanions: (id: string, count: number) => invoke<{ spawned: string | null; created: number | null }>("add_companions", { id, count }), clientInfo: (id: string) => invoke("client_info", { id }), setClient: (id: string, path: string) => invoke("set_client", { id, path }), setRealmlist: (id: string, host: string) => invoke("client_realmlist", { id, host }), diff --git a/src/screens/CompanionsCard.tsx b/src/screens/CompanionsCard.tsx index 4e68dc7..6b188fb 100644 --- a/src/screens/CompanionsCard.tsx +++ b/src/screens/CompanionsCard.tsx @@ -16,6 +16,40 @@ export function CompanionsCard({ serverId }: { serverId: string }) { 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(""); + const [startNote, setStartNote] = useState(null); + const [startBusy, setStartBusy] = useState(false); + + 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 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); @@ -52,7 +86,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { setNote(null); try { const r = await api.addCompanions(serverId, count); - setNote(r.spawned ? t("comp.spawned", { n: count }) : t("comp.saved", { n: count })); + 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 { @@ -101,6 +135,32 @@ export function CompanionsCard({ serverId }: { serverId: string }) { {!running && {t("comp.stoppedHint")}} {note &&

{note}

} + +
+

{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}

} ); diff --git a/src/screens/Overview.tsx b/src/screens/Overview.tsx index 1cd0192..a84962b 100644 --- a/src/screens/Overview.tsx +++ b/src/screens/Overview.tsx @@ -69,6 +69,18 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget const [client, setClient] = useState(null); const [playing, setPlaying] = useState(false); const [perf, setPerf] = useState(null); + const [startBots, setStartBots] = useState(undefined); + + 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); const poll = useCallback(async () => { @@ -213,6 +225,9 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
{pop ? `${pop.players_online}` : "—"}{pop && pop.bots_online > 0 ? {t("overview.companions", { n: pop.bots_online })} : null}
+ {startBots !== undefined && ( +

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

+ )} {perf && }