From 69c9938aba2479e60bbae1ad547e2f01840d131c 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: Fri, 6 Nov 2026 19:33:41 +0500 Subject: [PATCH 1/6] feat(manager): enable multi-realm playerbots support across CoA, Wildcard, and Reborn --- crates/coa-core/src/multiworld.rs | 6 +++ crates/coa-core/src/realms.rs | 63 ++++++++++--------------------- src/screens/CompanionsCard.tsx | 14 ++++++- 3 files changed, 39 insertions(+), 44 deletions(-) diff --git a/crates/coa-core/src/multiworld.rs b/crates/coa-core/src/multiworld.rs index 96df9bb..f7bb17c 100644 --- a/crates/coa-core/src/multiworld.rs +++ b/crates/coa-core/src/multiworld.rs @@ -261,6 +261,12 @@ fn prepare(main: &Path, tree: Tree) -> Result { &fsx::ensure_within(&second, &second.join("Core/reference"))?, )?; } + if main.join("Core/plugins").is_dir() { + copy_tree( + &main.join("Core/plugins"), + &fsx::ensure_within(&second, &second.join("Core/plugins"))?, + )?; + } for entry in fs::read_dir(main.join("Core"))? { let entry = entry?; if entry.file_type()?.is_file() diff --git a/crates/coa-core/src/realms.rs b/crates/coa-core/src/realms.rs index 96532d3..ab4c156 100644 --- a/crates/coa-core/src/realms.rs +++ b/crates/coa-core/src/realms.rs @@ -185,9 +185,8 @@ pub fn view(root: &Path) -> Result { } pub fn guard_module(root: &Path, id: &str) -> Result<()> { - if state(root)?.active != Mode::Coa && matches!(id, "companions" | "playerbots") { - return Err(Error::Invalid("Bot class mechanics have not been validated for this realm. This module is unavailable on this realm.".into())); - } + // Multi-realm Playerbots 1.0 supports all realms (CoA, Wildcard, Reborn). + let _ = (root, id); Ok(()) } @@ -296,14 +295,12 @@ fn wildcard_configs(mut files: Files) -> Result { } } } - for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] { - set( - &mut files, - "Core/configs/modules/mod_coa_playerbots.conf", - key, - value, - )?; - } + set( + &mut files, + "Core/configs/modules/mod_coa_playerbots.conf", + "CoaBots.Enable", + "1", + )?; set( &mut files, "Core/configs/modules/playerbots.conf", @@ -337,14 +334,12 @@ fn reborn_configs(mut files: Files) -> Result { set(&mut files, path, "RealmID", "3")?; } } - for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] { - set( - &mut files, - "Core/configs/modules/mod_coa_playerbots.conf", - key, - value, - )?; - } + set( + &mut files, + "Core/configs/modules/mod_coa_playerbots.conf", + "CoaBots.Enable", + "1", + )?; set( &mut files, "Core/configs/modules/playerbots.conf", @@ -681,19 +676,7 @@ pub fn before_start(root: &Path) -> Result<()> { "The installed server build does not support Wildcard.".into(), )); } - let path = root.join("Core/configs/modules/mod_coa_playerbots.conf"); - let mut conf = ConfFile::parse_bytes(&fs::read(&path)?)?; - conf.set("CoaBots.Enable", "0", &[]); - fsx::atomic_write(&path, conf.to_text().as_bytes())?; - let path = root.join("Core/configs/modules/playerbots.conf"); - let bytes = if path.exists() { - fs::read(&path)? - } else { - b"[worldserver]\n".to_vec() - }; - let mut conf = ConfFile::parse_bytes(&bytes)?; - conf.set("AiPlayerbot.Enabled", "0", &[]); - fsx::atomic_write(&path, conf.to_text().as_bytes())?; + // Multi-realm Playerbots 1.0: bots are supported and enabled on all realms } Ok(()) } @@ -831,8 +814,8 @@ mod tests { }, ) .unwrap(); - assert!(guard_module(t.path(), "companions").is_err()); - assert!(guard_module(t.path(), "playerbots").is_err()); + assert!(guard_module(t.path(), "companions").is_ok()); + assert!(guard_module(t.path(), "playerbots").is_ok()); assert!(guard_module(t.path(), "content-scaling").is_ok()); } @@ -1030,7 +1013,7 @@ CoA.GameModeMask = 0 f["Core/configs/modules/mod-coa-content-scaling.conf"] ); let c = ConfFile::parse_bytes(&w["Core/configs/modules/mod_coa_playerbots.conf"]).unwrap(); - assert_eq!(c.get("CoaBots.Enable"), Some("0")); + assert_eq!(c.get("CoaBots.Enable"), Some("1")); assert_eq!( ConfFile::parse_bytes(&w["Settings/worldserver.conf.template"]) .unwrap() @@ -1102,14 +1085,8 @@ CoA.GameModeMask = 0 }, ) .unwrap(); - assert!(crate::modules::set_enabled(t.path(), t.path(), "companions", true).is_err()); - assert!(crate::config::save( - t.path(), - t.path(), - crate::config::Scope::Bots, - &BTreeMap::new() - ) - .is_err()); + assert!(guard_module(t.path(), "companions").is_ok()); + assert!(guard_module(t.path(), "playerbots").is_ok()); assert!(guard_module(t.path(), "content-scaling").is_ok()); } } diff --git a/src/screens/CompanionsCard.tsx b/src/screens/CompanionsCard.tsx index 09870c9..a3f9307 100644 --- a/src/screens/CompanionsCard.tsx +++ b/src/screens/CompanionsCard.tsx @@ -9,6 +9,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const t = useT(); const human = useHuman(); const [sizes, setSizes] = useState(null); + const [realmMode, setRealmMode] = useState(null); const [pop, setPop] = useState(null); const [running, setRunning] = useState(false); const [choice, setChoice] = useState("small"); @@ -25,6 +26,10 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const [startBusy, setStartBusy] = useState(false); const [despawnN, setDespawnN] = useState("10"); + useEffect(() => { + void api.realmProfiles(serverId).then((r) => setRealmMode(r.active)).catch(() => {}); + }, [serverId]); + useEffect(() => { void api .settings(serverId, "bots") @@ -156,7 +161,14 @@ export function CompanionsCard({ serverId }: { serverId: string }) { return ( -

{t("comp.title")}

+
+

{t("comp.title")}

+ {realmMode && ( + + {realmMode === "coa" ? "Conquest of Azeroth" : realmMode === "wildcard" ? "Wildcard" : "Warcraft Reborn"} + + )} +

{pop ? t("comp.population", { online: pop.bots_online, total: pop.bots_total }) From ca2514c790d972894f83def9ae58f500f7483f7c 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: Fri, 6 Nov 2026 22:20:54 +0500 Subject: [PATCH 2/6] feat(manager): expand multi-realm bot fleet controls, DB routing, and compatibility guards --- crates/coa-core/src/companions.rs | 23 +- crates/coa-core/src/population.rs | 37 +- crates/coa-core/src/ra.rs | 12 + crates/coa-core/src/realms.rs | 64 ++- src-tauri/src/lib.rs | 70 ++- src/lib/api.ts | 7 +- src/screens/CompanionsCard.tsx | 808 ++++++++++++++++++++++++------ 7 files changed, 799 insertions(+), 222 deletions(-) diff --git a/crates/coa-core/src/companions.rs b/crates/coa-core/src/companions.rs index 3dab4e0..63d2721 100644 --- a/crates/coa-core/src/companions.rs +++ b/crates/coa-core/src/companions.rs @@ -19,37 +19,46 @@ pub fn seed_sql(base_guid: &str) -> String { format!("SET @G = {base_guid}; SET @ACC = {TEMPLATE_ACCOUNT};\n{SQL}") } -/// Number of characters the bot module could use as templates (level 80, a CoA class, not account 1). +/// Number of characters the bot module could use as templates. pub fn template_count(db: &Db) -> Result { - let n = db.query("SELECT COUNT(*) FROM acore_characters.characters WHERE account<>1 AND level>=80 AND class BETWEEN 12 AND 32;")?; + template_count_for_schema(db, "acore_characters") +} + +pub fn template_count_for_schema(db: &Db, chars_db: &str) -> Result { + let n = db.query(&format!("SELECT COUNT(*) FROM {chars_db}.characters WHERE account<>1 AND level>=80;"))?; Ok(n.trim().parse().unwrap_or(0)) } -fn run_seed(db: &Db, base_guid: &str) -> Result<()> { +fn run_seed(db: &Db, chars_db: &str, base_guid: &str) -> Result<()> { let file = std::env::temp_dir().join(format!( "coa-companion-templates-{}.sql", std::process::id() )); fs::write(&file, seed_sql(base_guid))?; - let r = db.run_sql_file("acore_characters", &file); + let r = db.run_sql_file(chars_db, &file); let _ = fs::remove_file(&file); r } /// Fresh databases (release tooling): the original guids. pub fn seed_fresh(db: &Db) -> Result<()> { - run_seed(db, "0") + run_seed(db, "acore_characters", "0") } /// An existing server without templates: add them far above the highest guid in use, so a running world can never /// hand a new character one of their guids. Returns whether anything was added. pub fn ensure_templates(db: &Db) -> Result { - if template_count(db)? > 0 { + ensure_templates_for_schema(db, "acore_characters") +} + +pub fn ensure_templates_for_schema(db: &Db, chars_db: &str) -> Result { + if template_count_for_schema(db, chars_db)? > 0 { return Ok(false); } run_seed( db, - "(SELECT IFNULL(MAX(guid),0) FROM acore_characters.characters) + 100000", + chars_db, + &format!("(SELECT IFNULL(MAX(guid),0) FROM {chars_db}.characters) + 100000"), )?; Ok(true) } diff --git a/crates/coa-core/src/population.rs b/crates/coa-core/src/population.rs index f228e4b..133f447 100644 --- a/crates/coa-core/src/population.rs +++ b/crates/coa-core/src/population.rs @@ -49,17 +49,19 @@ fn parse_counts(out: &str) -> Result { }) } -/// Read-only query with the game's own database account. Requires the database to be running. +/// Read-only query with the game's own database account. Routes automatically to the active realm's characters database. pub fn query(root: &Path) -> Result { - let db = Db::from_repack(root, Account::App)?; - query_with( - &db, - &bot_account_prefix(root), - &crate::accounts::squid_bot_prefix(root), - ) + let mode = crate::realms::state(root) + .map(|s| s.active) + .unwrap_or(crate::realms::Mode::Coa); + query_for_realm(root, mode) } fn counts_sql(prefix: &str, squid_prefix: &str) -> Result { + counts_sql_for_db("acore_characters", prefix, squid_prefix) +} + +pub fn counts_sql_for_db(chars_db: &str, prefix: &str, squid_prefix: &str) -> Result { if [prefix, squid_prefix] .iter() .any(|prefix| prefix.is_empty() || !prefix.chars().all(|c| c.is_ascii_alphanumeric())) @@ -74,9 +76,9 @@ fn counts_sql(prefix: &str, squid_prefix: &str) -> Result { let bots = format!("(UPPER(a.username) LIKE '{prefix}%' OR UPPER(a.username) LIKE '{squid_prefix}%')"); Ok(format!( - "SELECT (SELECT COUNT(*) FROM acore_characters.characters WHERE online=1), \ - (SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND {bots}), \ - (SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE {bots});" + "SELECT (SELECT COUNT(*) FROM {chars_db}.characters WHERE online=1), \ + (SELECT COUNT(*) FROM {chars_db}.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND {bots}), \ + (SELECT COUNT(*) FROM {chars_db}.characters c JOIN acore_auth.account a ON a.id=c.account WHERE {bots});" )) } @@ -85,6 +87,21 @@ pub fn query_with(db: &Db, prefix: &str, squid_prefix: &str) -> Result Result { + parse_counts(&db.query(&counts_sql_for_db(chars_db, prefix, squid_prefix)?)?) +} + +pub fn query_for_realm(root: &Path, mode: crate::realms::Mode) -> Result { + let db = Db::from_repack(root, Account::App)?; + let schema = mode.schema("characters")?; + query_for_schema( + &db, + schema, + &bot_account_prefix(root), + &crate::accounts::squid_bot_prefix(root), + ) +} + #[derive(Debug, Clone, Serialize)] pub struct Hardware { pub cores: u32, diff --git a/crates/coa-core/src/ra.rs b/crates/coa-core/src/ra.rs index cad0bcd..c63a52e 100644 --- a/crates/coa-core/src/ra.rs +++ b/crates/coa-core/src/ra.rs @@ -272,6 +272,18 @@ impl Ra { Ok(out.lines().last().unwrap_or("").to_string()) } + /// Ask the bot module to spawn a fleet of bots of specific race and level (.botcmd spawnfleet ). + pub fn spawn_fleet(&mut self, race: u8, level: u8) -> Result { + let out = self.bot_command(&format!("botcmd spawnfleet {race} {level}"))?; + Ok(out.lines().last().unwrap_or("").to_string()) + } + + /// Bring all offline bots online gradually (.botcmd loginall). + pub fn login_all(&mut self) -> Result { + let out = self.bot_command("botcmd loginall")?; + Ok(out.lines().last().unwrap_or("").to_string()) + } + /// Set a new password for an existing account. pub fn set_account_password(&mut self, name: &str, password: &str) -> Result<()> { validate_account(name, password)?; diff --git a/crates/coa-core/src/realms.rs b/crates/coa-core/src/realms.rs index ab4c156..ec2deb9 100644 --- a/crates/coa-core/src/realms.rs +++ b/crates/coa-core/src/realms.rs @@ -185,8 +185,21 @@ pub fn view(root: &Path) -> Result { } pub fn guard_module(root: &Path, id: &str) -> Result<()> { - // Multi-realm Playerbots 1.0 supports all realms (CoA, Wildcard, Reborn). - let _ = (root, id); + let s = state(root)?; + if matches!(id, "companions" | "playerbots") { + if let Ok(v) = view(root) { + if s.active == Mode::Wildcard && !v.supported { + return Err(Error::Invalid( + "The installed server binary does not support Wildcard mode.".into(), + )); + } + if s.active == Mode::Reborn && !v.reborn_supported { + return Err(Error::Invalid( + "The installed server binary does not support Warcraft Reborn mode.".into(), + )); + } + } + } Ok(()) } @@ -295,18 +308,14 @@ fn wildcard_configs(mut files: Files) -> Result { } } } - set( - &mut files, - "Core/configs/modules/mod_coa_playerbots.conf", - "CoaBots.Enable", - "1", - )?; - set( - &mut files, - "Core/configs/modules/playerbots.conf", - "AiPlayerbot.Enabled", - "0", - )?; + // Preserve existing CoaBots.Enable if present; do not force enable or alter alternative bot systems + if let Some(bytes) = files.get("Core/configs/modules/mod_coa_playerbots.conf") { + if let Ok(conf) = ConfFile::parse_bytes(bytes) { + if conf.get("CoaBots.Enable") == Some("1") { + set(&mut files, "Core/configs/modules/mod_coa_playerbots.conf", "CoaBots.Enable", "1")?; + } + } + } Ok(files) } @@ -334,18 +343,14 @@ fn reborn_configs(mut files: Files) -> Result { set(&mut files, path, "RealmID", "3")?; } } - set( - &mut files, - "Core/configs/modules/mod_coa_playerbots.conf", - "CoaBots.Enable", - "1", - )?; - set( - &mut files, - "Core/configs/modules/playerbots.conf", - "AiPlayerbot.Enabled", - "0", - )?; + // Preserve existing CoaBots.Enable if present; do not force enable or alter alternative bot systems + if let Some(bytes) = files.get("Core/configs/modules/mod_coa_playerbots.conf") { + if let Ok(conf) = ConfFile::parse_bytes(bytes) { + if conf.get("CoaBots.Enable") == Some("1") { + set(&mut files, "Core/configs/modules/mod_coa_playerbots.conf", "CoaBots.Enable", "1")?; + } + } + } Ok(files) } @@ -796,11 +801,12 @@ mod tests { .get("RealmID"), Some("3") ); + // Requirement 6: Never alter alternative bot system settings (AiPlayerbot.Enabled) without explicit user choice assert_eq!( ConfFile::parse_bytes(&reborn["Core/configs/modules/playerbots.conf"]) .unwrap() .get("AiPlayerbot.Enabled"), - Some("0") + Some("1") ); write_configs(t.path(), &reborn).unwrap(); write_configs(t.path(), &coa).unwrap(); @@ -1003,6 +1009,10 @@ CoA.GameModeMask = 0 "Core/configs/modules/mod-coa-content-scaling.conf".into(), b"[worldserver]\nCoAContentScaling.Enable = 1\n".to_vec(), ); + f.insert( + "Core/configs/modules/mod_coa_playerbots.conf".into(), + b"[worldserver]\nCoaBots.Enable = 1\n".to_vec(), + ); f.insert( "Settings/worldserver.conf.template".into(), b"[worldserver]\nRealmID = 1\n".to_vec(), diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 8552c36..fb6f2f0 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1827,6 +1827,7 @@ async fn retry_update_validation( async fn get_population( state: State<'_, AppState>, id: String, + realm: Option, ) -> std::result::Result, UiError> { let root = path_of(&state, &id)?; Ok(tauri::async_runtime::spawn_blocking(move || { @@ -1834,12 +1835,46 @@ async fn get_population( if o.mysql.state != coa_core::process::ServiceState::Running { return None; } - coa_core::population::query(&root).ok() + if let Some(mode) = realm { + coa_core::population::query_for_realm(&root, mode).ok() + } else { + coa_core::population::query(&root).ok() + } }) .await .unwrap_or(None)) } +#[tauri::command] +async fn companions_login_all( + state: State<'_, AppState>, + id: String, +) -> std::result::Result { + let root = path_of(&state, &id)?; + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || { + let mut ra = Ra::connect(&root)?; + ra.login_all() + }) + .await +} + +#[tauri::command] +async fn companions_spawn_fleet( + state: State<'_, AppState>, + id: String, + race: u8, + level: u8, +) -> std::result::Result { + let root = path_of(&state, &id)?; + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || { + let mut ra = Ra::connect(&root)?; + ra.spawn_fleet(race, level) + }) + .await +} + #[derive(Serialize)] struct CompanionAction { /// Bots affected (cancelled from the queue, or logged out). @@ -1990,6 +2025,7 @@ async fn add_companions( state: State<'_, AppState>, id: String, count: u32, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; @@ -1999,6 +2035,14 @@ async fn add_companions( "Choose between 1 and 2000 companions.".into(), )); } + let mode = realm.unwrap_or_else(|| { + coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default() + }); + let chars_db = match mode { + coa_core::realms::Mode::Coa => "acore_characters", + coa_core::realms::Mode::Wildcard => "acore_characters_wildcard", + coa_core::realms::Mode::Reborn => "acore_characters_reborn", + }; let meta = meta_dir(&root)?; let mut changes = BTreeMap::new(); changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true)); @@ -2012,7 +2056,7 @@ async fn add_companions( .and_then(|s| s.value.as_u64()) }) .unwrap_or(0) as u32; - let already = coa_core::population::query(&root) + let already = coa_core::population::query_for_realm(&root, mode) .map(|p| p.bots_total) .unwrap_or(0); changes.insert( @@ -2021,10 +2065,11 @@ async fn add_companions( ); 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. + // Large batches while the server is stopped: create them in the database right now, fully equipped (CoA schema only). if o.world.state == coa_core::process::ServiceState::Stopped && o.auth.state == coa_core::process::ServiceState::Stopped && count >= coa_core::companions::OFFLINE_MIN + && mode == coa_core::realms::Mode::Coa && coa_core::companions::offline_factory(&root).is_some() { let started_db = o.mysql.state != coa_core::process::ServiceState::Running; @@ -2035,10 +2080,10 @@ async fn add_companions( } } let made = (|| -> Result<()> { - coa_core::companions::ensure_templates(&coa_core::db::Db::from_repack( - &root, - coa_core::db::Account::Admin, - )?)?; + coa_core::companions::ensure_templates_for_schema( + &coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin)?, + chars_db, + )?; coa_core::companions::offline_create( &root, &meta.join("logs").join("companions-offline.log"), @@ -2060,11 +2105,10 @@ async fn add_companions( let mut baseline = None; 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, - )?)?; - baseline = coa_core::population::query(&root) + if let Ok(admin_db) = coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin) { + let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, chars_db); + } + baseline = coa_core::population::query_for_realm(&root, mode) .ok() .map(|p| p.bots_total); Some(Ra::connect(&root)?.spawn_bots(count)?) @@ -3180,6 +3224,8 @@ pub fn run() { companions_take_offline, companions_delete_all, companions_despawn_some, + companions_login_all, + companions_spawn_fleet, open_link, report_targets, companion_sizes, diff --git a/src/lib/api.ts b/src/lib/api.ts index 29d87f5..4ac05c1 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -571,15 +571,18 @@ export const api = { invoke<{ txn: UpdateTxn; preexisting_character_count?: number }>("apply_update", { id, source: source ?? null, resolutions }), rollbackUpdate: (id: string, txn: string) => invoke("rollback_update", { id, txn }), retryUpdateValidation: (id: string, txn: string) => invoke("retry_update_validation", { id, txn }), - population: (id: string) => invoke("get_population", { id }), + population: (id: string, realm?: RealmMode) => invoke("get_population", { id, realm: realm ?? null }), stopSpawning: (id: string) => invoke<{ count: number }>("companions_stop_spawning", { id }), takeOffline: (id: string) => invoke<{ count: number }>("companions_take_offline", { id }), despawnSome: (id: string, count: number) => invoke<{ count: number }>("companions_despawn_some", { id, count }), deleteAllCompanions: (id: string) => invoke<{ count: number }>("companions_delete_all", { id }), + loginAllCompanions: (id: string) => invoke("companions_login_all", { id }), + spawnBotFleet: (id: string, race: number, level: number) => invoke("companions_spawn_fleet", { id, race, level }), 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; created: number | null; baseline: number | null }>("add_companions", { id, count }), + addCompanions: (id: string, count: number, realm?: RealmMode) => + invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count, realm: realm ?? null }), clientGraphics: (id: string) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_graphics", { id }), clientSetGraphics: (id: string, name: string, disabled: boolean) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_set_graphics", { id, name, disabled }), clientInfo: (id: string) => invoke("client_info", { id }), diff --git a/src/screens/CompanionsCard.tsx b/src/screens/CompanionsCard.tsx index a3f9307..3ca88ac 100644 --- a/src/screens/CompanionsCard.tsx +++ b/src/screens/CompanionsCard.tsx @@ -1,35 +1,88 @@ import { useEffect, useState } from "react"; -import { Loader2 } from "lucide-react"; -import { api, asUiError, type CompanionSizes, type Population, type UiError } from "@/lib/api"; +import { + Loader2, + Bot, + CheckCircle2, + AlertCircle, + RefreshCw, + Power, + Users, + Database, +} from "lucide-react"; +import { + api, + asUiError, + type Population, + type RealmMode, + type RealmProfiles, + 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"; +import { useHuman, useT } from "@/i18n"; export function CompanionsCard({ serverId }: { serverId: string }) { const t = useT(); const human = useHuman(); - const [sizes, setSizes] = useState(null); - const [realmMode, setRealmMode] = useState(null); + + // Realm & Environment state + const [profiles, setProfiles] = useState(null); + const [selectedRealm, setSelectedRealm] = useState("coa"); const [pop, setPop] = useState(null); const [running, setRunning] = useState(false); - const [choice, setChoice] = useState("small"); - const [custom, setCustom] = useState("100"); + + // Fleet Configuration state + const [spawnMode, setSpawnMode] = useState<"population" | "fleet">("population"); + const [countChoice, setCountChoice] = useState("50"); + const [customCount, setCustomCount] = useState("50"); + const [targetLevel, setTargetLevel] = useState(80); + const [selectedClass, setSelectedClass] = useState("all"); + const [selectedRole, setSelectedRole] = useState("all"); + const [selectedArchetype, setSelectedArchetype] = useState("all"); + + // Operational state 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 [job, setJob] = useState<{ baseline: number; target: number; since: number } | null>(null); + + // Startup Auto-Login settings 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"); + const activeServerRealm = profiles?.active ?? "coa"; + const isViewingActiveRealm = selectedRealm === activeServerRealm; + + const maxLevelForRealm = selectedRealm === "reborn" ? 60 : 80; + + // Load realm profiles + const loadProfiles = async () => { + try { + const r = await api.realmProfiles(serverId); + setProfiles(r); + if (!selectedRealm) { + setSelectedRealm(r.active); + } + } catch { + // ignore + } + }; + useEffect(() => { - void api.realmProfiles(serverId).then((r) => setRealmMode(r.active)).catch(() => {}); + void loadProfiles(); }, [serverId]); + // Adjust target level if realm changed + useEffect(() => { + if (targetLevel > maxLevelForRealm) { + setTargetLevel(maxLevelForRealm); + } + }, [selectedRealm, maxLevelForRealm, targetLevel]); + + // Load startup settings useEffect(() => { void api .settings(serverId, "bots") @@ -45,6 +98,46 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const maxNum = Number(autoMax); const maxValid = autoMax.trim() !== "" && Number.isInteger(maxNum) && maxNum >= 0 && maxNum <= 5000; + // Polling population + const fetchPopulation = async () => { + const s = await api.status(serverId).catch(() => null); + if (!s) return; + const up = s.observed.world.state === "running"; + setRunning(up); + if (up) { + const p = await api.population(serverId, selectedRealm).catch(() => null); + setPop(p); + } else { + setPop(null); + } + }; + + useEffect(() => { + let alive = true; + const poll = async () => { + if (!alive) return; + await fetchPopulation(); + }; + void poll(); + const interval = setInterval(poll, job ? 1500 : 4000); + return () => { + alive = false; + clearInterval(interval); + }; + }, [serverId, selectedRealm, 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; + 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 + + const count = countChoice === "custom" ? Number(customCount) : Number(countChoice); + const valid = Number.isInteger(count) && count >= 1 && count <= 2000; + async function act(fn: () => Promise) { setBusy(true); setError(null); @@ -57,45 +150,113 @@ export function CompanionsCard({ serverId }: { serverId: string }) { } } + // Primary action: Spawn bots / fleet + const handleSpawn = async () => { + if (!valid) return; + setBusy(true); + setError(null); + setNote(null); + try { + if (spawnMode === "fleet") { + // Fleet spawn: race 1 (Human) or 2 (Orc) + const race = 1; + const out = await api.spawnBotFleet(serverId, race, targetLevel); + setNote(out || `Spawned level ${targetLevel} fleet`); + } else { + const r = await api.addCompanions(serverId, count, selectedRealm); + 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 }) + ); + } + await fetchPopulation(); + } catch (e) { + setError(asUiError(e)); + } finally { + setBusy(false); + } + }; + + // Bring offline bots online + const handleLoginAll = () => + act(async () => { + const out = await api.loginAllCompanions(serverId); + await fetchPopulation(); + return out || "All available offline bots queued for login."; + }); + + // Stop queued creations const stopCreating = () => act(async () => { const r = await api.stopSpawning(serverId); setJob(null); + await fetchPopulation(); return t("comp.stopped", { n: r.count }); }); + // Take online bots offline const takeOffline = () => { if (!window.confirm(t("comp.offlineConfirm"))) return; void act(async () => { const r = await api.takeOffline(serverId); setJob(null); + await fetchPopulation(); return t("comp.offlineDone2", { n: r.count }); }); }; + // Despawn batch const dn = Number(despawnN); const dnValid = Number.isInteger(dn) && dn >= 1 && dn <= 5000; const despawnSome = () => act(async () => { const r = await api.despawnSome(serverId, dn); + await fetchPopulation(); return t("comp.despawnSomeDone", { n: r.count }); }); + // Delete all bots in realm const deleteAll = () => { if (!window.confirm(t("comp.deleteConfirm", { n: pop?.bots_total ?? 0 }))) return; void act(async () => { await api.deleteAllCompanions(serverId); setJob(null); + await fetchPopulation(); return t("comp.deleteDone"); }); }; + // Switch server realm + const switchServerRealm = async (mode: RealmMode) => { + if (!window.confirm(`Switch server active realm to ${mode.toUpperCase()} and restart?`)) return; + setBusy(true); + try { + await api.realmSelect(serverId, mode, true); + await loadProfiles(); + setSelectedRealm(mode); + } catch (e) { + setError(asUiError(e)); + } finally { + setBusy(false); + } + }; + + // Save auto startup settings async function saveStart() { setStartBusy(true); setError(null); setStartNote(null); try { - await api.save(serverId, "bots", { "CoaBots.AutoLoginOnStartup": autoOn, "CoaBots.AutoLogin.MaxCount": maxNum }); + await api.save(serverId, "bots", { + "CoaBots.AutoLoginOnStartup": autoOn, + "CoaBots.AutoLogin.MaxCount": maxNum, + }); setStartNote(t("comp.startSaved")); } catch (e) { setError(asUiError(e)); @@ -104,188 +265,507 @@ export function CompanionsCard({ serverId }: { serverId: string }) { } } - 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 + // Database schema name for selected realm + const dbSchema = + selectedRealm === "coa" + ? "acore_characters" + : selectedRealm === "wildcard" + ? "acore_characters_wildcard" + : "acore_characters_reborn"; - 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); - } - } + // Binary compatibility check + const isBinaryCompatible = + selectedRealm === "coa" || + (selectedRealm === "wildcard" && (profiles?.supported ?? true)) || + (selectedRealm === "reborn" && (profiles?.reborn_supported ?? true)); return ( - -

-

{t("comp.title")}

- {realmMode && ( - - {realmMode === "coa" ? "Conquest of Azeroth" : realmMode === "wildcard" ? "Wildcard" : "Warcraft Reborn"} - - )} -
-

- {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" /> - )} + + {/* Header & Realm Switcher */} +
+
+
+ +

{t("comp.title")}

+
+
+ + + DB: {dbSchema} + +
-
- {warning &&

{warning}

} - {sizes &&

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

} - -
- - {!running && {t("comp.stoppedHint")}} + {/* Realm Navigation Tabs */} +
+ {(["coa", "wildcard", "reborn"] as RealmMode[]).map((mode) => { + const isSelected = selectedRealm === mode; + const isActive = activeServerRealm === mode; + const label = + mode === "coa" + ? "Conquest of Azeroth" + : mode === "wildcard" + ? "Wildcard (Hero)" + : "Warcraft Reborn"; + return ( + + ); + })} +
- {busy && !running && count >= 100 && ( -
-

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

-
-
+ + {/* Binary Compatibility & Realm Mode Warning */} + {!isBinaryCompatible && ( +
+ +
+
Binary Compatibility Warning
+

+ The currently running server core binary does not have full multi-realm support enabled + for {selectedRealm.toUpperCase()}. Automated bot features may be restricted. +

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

-
- + {/* Realm Population Dashboard */} +
+
+
+ + Bots Online +
+
+ {running && pop ? pop.bots_online : "—"} +
+
+
+
+ + Total Fleet +
+
+ {pop ? pop.bots_total : "—"} +
+
+
+
+ + Players Online +
+
+ {running && pop ? pop.players_online : "—"} +
+
+
+
+ Status + +
+
+ {running ? ( + + Running + + ) : ( + Offline + )} +
+
+
+ + {/* Fleet Configuration & Spawning Section */} +
+
+

+ Fleet Deployment Controls +

+
+ + +
+
+ + {/* Count Selector */} + {spawnMode === "population" && ( +
+ +
+ {["10", "25", "50", "100", "250", "500"].map((n) => ( + + ))} + + {countChoice === "custom" && ( + setCustomCount(e.target.value)} + className="w-24 rounded-md border border-line bg-bg px-3 py-1.5 text-right text-sm outline-none focus:border-gold" + /> + )} +
+
+ )} + + {/* Fleet Specific Settings: Level, Class, Role, Archetype */} +
+ {/* Target Level */} +
+ + setTargetLevel(Math.max(1, Math.min(maxLevelForRealm, Number(e.target.value))))} + className="mt-1.5 w-full rounded-md border border-line bg-bg px-3 py-1.5 text-sm outline-none focus:border-gold" + /> +
+ + {/* Class Filter */} +
+ + +
+ + {/* Role Filter */} +
+ + +
+ + {/* Archetype Filter */} +
+ + +
+
+ + {/* Deployment Actions */} +
+ + + {running && pop && pop.bots_total > pop.bots_online && ( + + )} + + {!running && ( + + Server stopped: bots will be created directly in DB or queued for startup. + + )} +
+ + {/* Progress Bar during active spawn */} + {job && ( +
+
+ + Creating bots: {done} / {job.target} + + + {Math.round((done / job.target) * 100)}% + +
+
+
+
+
+ + Paced creation prevents server stalls and guarantees full talent/gear setup. + + +
+
+ )} + + {note && !job && ( +

+ + {note} +

+ )} +
+ + {/* Online Fleet Management (Despawn, Purge) */} + {running && pop && pop.bots_total > 0 && isViewingActiveRealm && ( +
+

+ Online Fleet Management +

+ +
+ 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" + className="w-20 rounded-md border border-line bg-bg px-2.5 py-1 text-right text-sm 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" - /> - + {/* Startup Auto-Login Configuration */} +
+

+ Persistent Startup Fleet +

+

+ Configure how many bots automatically log into the world whenever the server launches. +

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

{t("comp.startInvalid")}

} -

{t("comp.startHint")}

- {startNote &&

{startNote}

} + {startNote &&

{startNote}

}
- {error &&

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

} + + {error && ( +
+ + {error.human.code === "unknown" ? error.technical : human(error.human).message} +
+ )} ); } From e4edb7cbdd0ca2f783bc0fb1121a76b816c5b857 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: Sat, 7 Nov 2026 10:19:13 +0500 Subject: [PATCH 3/6] feat(manager): multi-realm character database routing, RA dispatch & extended bot manager UI --- crates/coa-core/src/multiworld.rs | 52 ++++++++++++++++ crates/coa-core/src/ra.rs | 41 ++++++++++++ src-tauri/src/lib.rs | 100 ++++++++++++------------------ src/lib/api.ts | 32 +++++++--- src/screens/CompanionsCard.tsx | 70 ++++++++++++++------- 5 files changed, 203 insertions(+), 92 deletions(-) diff --git a/crates/coa-core/src/multiworld.rs b/crates/coa-core/src/multiworld.rs index f7bb17c..7e42d2c 100644 --- a/crates/coa-core/src/multiworld.rs +++ b/crates/coa-core/src/multiworld.rs @@ -97,6 +97,58 @@ pub fn world_root(main: &Path, mode: Mode) -> PathBuf { .map_or_else(|| main.to_path_buf(), |t| tree_root(main, t)) } +#[derive(Debug, Clone)] +pub struct BotOperationTarget { + pub world_root: PathBuf, + pub chars_db: &'static str, + pub ra_port: u16, + pub running: bool, + pub realm: Mode, +} + +pub fn resolve_bot_operation_target(main: &Path, realm: Mode) -> Result { + let state = realms::state(main)?; + let chars_db = realm.schema("characters")?; + + if realm == state.active { + let ports = crate::layout::read_ports(main); + let ra_port = ports.ra; + let status = process::observe(main, &ports); + let running = status.world.state != ServiceState::Stopped; + return Ok(BotOperationTarget { + world_root: main.to_path_buf(), + chars_db, + ra_port, + running, + realm, + }); + } + + let tree = Tree::ALL + .into_iter() + .find(|t| t.enabled(&state) && t.mode(state.active) == realm) + .ok_or_else(|| Error::Invalid(format!("Realm {} is not enabled in multiworld configuration.", realm.label())))?; + + let root = tree_root(main, tree); + if !root.exists() { + return Err(Error::Invalid(format!("Multiworld directory for {} does not exist: {}", realm.label(), root.display()))); + } + + let ports = crate::layout::read_ports(&root); + let (_, default_ra) = tree.ports(&state); + let ra_port = if ports.ra != 0 { ports.ra } else { default_ra.unwrap_or(3444) }; + let status = process::observe(&root, &ports); + let running = status.world.state != ServiceState::Stopped; + + Ok(BotOperationTarget { + world_root: root, + chars_db, + ra_port, + running, + realm, + }) +} + /// Any of the extra worlds is running or still stopping. pub fn is_running(main: &Path) -> bool { Tree::ALL.into_iter().any(|t| tree_running(main, t)) diff --git a/crates/coa-core/src/ra.rs b/crates/coa-core/src/ra.rs index c63a52e..37dcb5e 100644 --- a/crates/coa-core/src/ra.rs +++ b/crates/coa-core/src/ra.rs @@ -58,6 +58,23 @@ impl Ra { Self::connect_to(read_ports(root).ra, &cfg.ra_username, &cfg.ra_password) } + /// Connect to the loopback RA port of the target realm world server. + pub fn connect_target(main: &Path, realm: Option) -> Result { + let mode = realm.unwrap_or_else(|| { + crate::realms::view(main).map(|v| v.active).unwrap_or_default() + }); + let target = crate::multiworld::resolve_bot_operation_target(main, mode)?; + if !target.running { + return Err(Error::Invalid(format!( + "Realm {} worldserver is stopped; cannot execute online bot operation.", + target.realm.label() + ))); + } + let cfg: RaSettings = fsx::read_json(&main.join("Settings/repack.json")) + .map_err(|_| Error::Invalid("The server console settings could not be read.".into()))?; + Self::connect_to(target.ra_port, &cfg.ra_username, &cfg.ra_password) + } + pub fn connect_to(port: u16, user: &str, password: &str) -> Result { let addr: SocketAddr = ([127, 0, 0, 1], port).into(); let mut stream = @@ -278,6 +295,30 @@ impl Ra { Ok(out.lines().last().unwrap_or("").to_string()) } + pub fn spawn_custom( + &mut self, + count: u32, + level: u8, + class_id: Option, + spec_id: Option, + archetype: Option<&str>, + ) -> Result { + let mut cmd = format!("botcmd spawncustom {count} {level}"); + if let Some(c) = class_id { + cmd.push_str(&format!(" {c}")); + if let Some(s) = spec_id { + cmd.push_str(&format!(" {s}")); + if let Some(a) = archetype { + if !a.is_empty() { + cmd.push_str(&format!(" {a}")); + } + } + } + } + let out = self.bot_command(&cmd)?; + Ok(out.lines().last().unwrap_or("").to_string()) + } + /// Bring all offline bots online gradually (.botcmd loginall). pub fn login_all(&mut self) -> Result { let out = self.bot_command("botcmd loginall")?; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fb6f2f0..dfcf788 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1849,11 +1849,12 @@ async fn get_population( async fn companions_login_all( state: State<'_, AppState>, id: String, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; blocking(move || { - let mut ra = Ra::connect(&root)?; + let mut ra = Ra::connect_target(&root, realm)?; ra.login_all() }) .await @@ -1865,11 +1866,12 @@ async fn companions_spawn_fleet( id: String, race: u8, level: u8, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; blocking(move || { - let mut ra = Ra::connect(&root)?; + let mut ra = Ra::connect_target(&root, realm)?; ra.spawn_fleet(race, level) }) .await @@ -1885,11 +1887,12 @@ struct CompanionAction { async fn companions_stop_spawning( state: State<'_, AppState>, id: String, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; blocking(move || { Ok(CompanionAction { - count: Ra::connect(&root)?.cancel_spawning()?, + count: Ra::connect_target(&root, realm)?.cancel_spawning()?, }) }) .await @@ -1899,12 +1902,12 @@ async fn companions_stop_spawning( async fn companions_take_offline( state: State<'_, AppState>, id: String, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; blocking(move || { - let mut ra = Ra::connect(&root)?; - // Anything still waiting to be created must not come back right after. + let mut ra = Ra::connect_target(&root, realm)?; let _ = ra.cancel_spawning(); Ok(CompanionAction { count: ra.despawn_all()?, @@ -1913,13 +1916,12 @@ async fn companions_take_offline( .await } -/// Log `count` randomly chosen online companions out to lower the load. Uses the per-bot command that every server -/// build has, so it works on older builds too. #[tauri::command] async fn companions_despawn_some( state: State<'_, AppState>, id: String, count: u32, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; @@ -1927,13 +1929,18 @@ async fn companions_despawn_some( if !(1..=5000).contains(&count) { return Err(Error::Invalid("Choose a number between 1 and 5000.".into())); } + let mode = realm.unwrap_or_else(|| { + coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default() + }); + let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?; let prefix = coa_core::population::bot_account_prefix(&root).to_uppercase(); let db = coa_core::db::Db::from_repack(&root, coa_core::db::Account::App)?; let rows = db.query(&format!( - "SELECT c.guid FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND UPPER(a.username) LIKE '{prefix}%' ORDER BY RAND() LIMIT {count};" + "SELECT c.guid FROM {}.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND UPPER(a.username) LIKE '{prefix}%' ORDER BY RAND() LIMIT {count};", + target.chars_db ))?; let guids: Vec = rows.lines().filter_map(|l| l.trim().parse().ok()).collect(); - let mut ra = Ra::connect(&root)?; + let mut ra = Ra::connect_target(&root, Some(mode))?; let mut done = 0; for g in guids { if ra.despawn_bot(g).unwrap_or(false) { @@ -1945,31 +1952,35 @@ async fn companions_despawn_some( .await } -/// Delete every companion for good. A recovery point of the characters and accounts is saved first. #[tauri::command] async fn companions_delete_all( app: AppHandle, state: State<'_, AppState>, id: String, + realm: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; blocking(move || { + let mode = realm.unwrap_or_else(|| { + coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default() + }); + let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?; let meta = meta_dir(&root)?; backup::create( &root, &meta, Kind::Quick, Trigger::BeforeDangerousChange, - Some("before deleting all companions".into()), + Some(format!("before deleting all {} companions", target.realm.label())), &|step| { let _ = app.emit("backup-progress", step); }, )?; - let before = coa_core::population::query(&root) + let before = coa_core::population::query_for_realm(&root, mode) .map(|p| p.bots_total) .unwrap_or(0); - let mut ra = Ra::connect(&root)?; + let mut ra = Ra::connect_target(&root, Some(mode))?; let _ = ra.cancel_spawning(); ra.purge_all()?; Ok(CompanionAction { count: before }) @@ -2026,6 +2037,10 @@ async fn add_companions( id: String, count: u32, realm: Option, + level: Option, + class_id: Option, + spec_id: Option, + archetype: Option, ) -> std::result::Result { let root = path_of(&state, &id)?; let _guard = BusyGuard::acquire(&state, &id)?; @@ -2038,15 +2053,10 @@ async fn add_companions( let mode = realm.unwrap_or_else(|| { coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default() }); - let chars_db = match mode { - coa_core::realms::Mode::Coa => "acore_characters", - coa_core::realms::Mode::Wildcard => "acore_characters_wildcard", - coa_core::realms::Mode::Reborn => "acore_characters_reborn", - }; + let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?; let meta = meta_dir(&root)?; let mut changes = BTreeMap::new(); changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true)); - // 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| { @@ -2064,56 +2074,22 @@ async fn add_companions( 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 (CoA schema only). - if o.world.state == coa_core::process::ServiceState::Stopped - && o.auth.state == coa_core::process::ServiceState::Stopped - && count >= coa_core::companions::OFFLINE_MIN - && mode == coa_core::realms::Mode::Coa - && 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_for_schema( - &coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin)?, - chars_db, - )?; - 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), - baseline: None, - }); - } + let mut baseline = None; - let spawned = if o.world.state == coa_core::process::ServiceState::Running { - // Older servers have no template characters to copy bots from: add them first. + let spawned = if target.running { if let Ok(admin_db) = coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin) { - let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, chars_db); + let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, target.chars_db); } baseline = coa_core::population::query_for_realm(&root, mode) .ok() .map(|p| p.bots_total); - Some(Ra::connect(&root)?.spawn_bots(count)?) + let mut ra = Ra::connect_target(&root, Some(mode))?; + if let Some(lvl) = level { + Some(ra.spawn_custom(count, lvl, class_id, spec_id, archetype.as_deref())?) + } else { + Some(ra.spawn_bots(count)?) + } } else { - // The server is stopped: creating bots needs it running, so remember the request and do it after the next start. coa_core::fsx::atomic_write_json( &meta.join("companions.pending.json"), &serde_json::json!({ "count": count }), diff --git a/src/lib/api.ts b/src/lib/api.ts index 4ac05c1..8af8dac 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -572,17 +572,33 @@ export const api = { rollbackUpdate: (id: string, txn: string) => invoke("rollback_update", { id, txn }), retryUpdateValidation: (id: string, txn: string) => invoke("retry_update_validation", { id, txn }), population: (id: string, realm?: RealmMode) => invoke("get_population", { id, realm: realm ?? null }), - stopSpawning: (id: string) => invoke<{ count: number }>("companions_stop_spawning", { id }), - takeOffline: (id: string) => invoke<{ count: number }>("companions_take_offline", { id }), - despawnSome: (id: string, count: number) => invoke<{ count: number }>("companions_despawn_some", { id, count }), - deleteAllCompanions: (id: string) => invoke<{ count: number }>("companions_delete_all", { id }), - loginAllCompanions: (id: string) => invoke("companions_login_all", { id }), - spawnBotFleet: (id: string, race: number, level: number) => invoke("companions_spawn_fleet", { id, race, level }), + stopSpawning: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_stop_spawning", { id, realm: realm ?? null }), + takeOffline: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_take_offline", { id, realm: realm ?? null }), + despawnSome: (id: string, count: number, realm?: RealmMode) => invoke<{ count: number }>("companions_despawn_some", { id, count, realm: realm ?? null }), + deleteAllCompanions: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_delete_all", { id, realm: realm ?? null }), + loginAllCompanions: (id: string, realm?: RealmMode) => invoke("companions_login_all", { id, realm: realm ?? null }), + spawnBotFleet: (id: string, race: number, level: number, realm?: RealmMode) => invoke("companions_spawn_fleet", { id, race, level, realm: realm ?? null }), openLink: (url: string) => invoke("open_link", { url }), performance: (id: string) => invoke("get_performance", { id }), companionSizes: () => invoke("companion_sizes"), - addCompanions: (id: string, count: number, realm?: RealmMode) => - invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count, realm: realm ?? null }), + addCompanions: ( + id: string, + count: number, + realm?: RealmMode, + level?: number, + classId?: number, + specId?: number, + archetype?: string + ) => + invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { + id, + count, + realm: realm ?? null, + level: level ?? null, + class_id: classId ?? null, + spec_id: specId ?? null, + archetype: archetype ?? null, + }), clientGraphics: (id: string) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_graphics", { id }), clientSetGraphics: (id: string, name: string, disabled: boolean) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_set_graphics", { id, name, disabled }), clientInfo: (id: string) => invoke("client_info", { id }), diff --git a/src/screens/CompanionsCard.tsx b/src/screens/CompanionsCard.tsx index 3ca88ac..c4dd45a 100644 --- a/src/screens/CompanionsCard.tsx +++ b/src/screens/CompanionsCard.tsx @@ -55,8 +55,9 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const activeServerRealm = profiles?.active ?? "coa"; const isViewingActiveRealm = selectedRealm === activeServerRealm; + const isRealmOperational = isViewingActiveRealm || running; - const maxLevelForRealm = selectedRealm === "reborn" ? 60 : 80; + const maxLevelForRealm = 60; // Load realm profiles const loadProfiles = async () => { @@ -158,12 +159,27 @@ export function CompanionsCard({ serverId }: { serverId: string }) { setNote(null); try { if (spawnMode === "fleet") { - // Fleet spawn: race 1 (Human) or 2 (Orc) const race = 1; - const out = await api.spawnBotFleet(serverId, race, targetLevel); + const out = await api.spawnBotFleet(serverId, race, targetLevel, selectedRealm); setNote(out || `Spawned level ${targetLevel} fleet`); } else { - const r = await api.addCompanions(serverId, count, selectedRealm); + const classNum = selectedClass !== "all" ? parseInt(selectedClass, 10) : undefined; + let specNum: number | undefined = undefined; + if (selectedRole === "tank") { + if (selectedRealm === "reborn") { + specNum = (classNum === 7 || classNum === 9 || classNum === 11) ? 4 : (classNum === 2 ? 2 : classNum === 1 ? 3 : 1); + } else if (selectedRealm === "wildcard") { + specNum = 1; + } + } else if (selectedRole === "healer") { + if (selectedRealm === "reborn") { + specNum = (classNum === 2 || classNum === 5) ? 1 : (classNum === 7 || classNum === 11 ? 3 : 1); + } else if (selectedRealm === "wildcard") { + specNum = 2; + } + } + const archStr = selectedArchetype !== "all" ? selectedArchetype : undefined; + const r = await api.addCompanions(serverId, count, selectedRealm, targetLevel, classNum, specNum, archStr); if (r.spawned && r.baseline !== null) { setJob({ baseline: r.baseline, target: count, since: Date.now() }); } @@ -186,7 +202,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { // Bring offline bots online const handleLoginAll = () => act(async () => { - const out = await api.loginAllCompanions(serverId); + const out = await api.loginAllCompanions(serverId, selectedRealm); await fetchPopulation(); return out || "All available offline bots queued for login."; }); @@ -194,7 +210,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { // Stop queued creations const stopCreating = () => act(async () => { - const r = await api.stopSpawning(serverId); + const r = await api.stopSpawning(serverId, selectedRealm); setJob(null); await fetchPopulation(); return t("comp.stopped", { n: r.count }); @@ -204,7 +220,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const takeOffline = () => { if (!window.confirm(t("comp.offlineConfirm"))) return; void act(async () => { - const r = await api.takeOffline(serverId); + const r = await api.takeOffline(serverId, selectedRealm); setJob(null); await fetchPopulation(); return t("comp.offlineDone2", { n: r.count }); @@ -216,7 +232,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const dnValid = Number.isInteger(dn) && dn >= 1 && dn <= 5000; const despawnSome = () => act(async () => { - const r = await api.despawnSome(serverId, dn); + const r = await api.despawnSome(serverId, dn, selectedRealm); await fetchPopulation(); return t("comp.despawnSomeDone", { n: r.count }); }); @@ -225,7 +241,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const deleteAll = () => { if (!window.confirm(t("comp.deleteConfirm", { n: pop?.bots_total ?? 0 }))) return; void act(async () => { - await api.deleteAllCompanions(serverId); + await api.deleteAllCompanions(serverId, selectedRealm); setJob(null); await fetchPopulation(); return t("comp.deleteDone"); @@ -514,17 +530,27 @@ export function CompanionsCard({ serverId }: { serverId: string }) { {selectedRealm === "coa" && ( <> - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + )} {selectedRealm === "wildcard" && ( @@ -605,7 +631,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) {