diff --git a/Cargo.lock b/Cargo.lock index 2750cd8..00a1230 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -668,6 +668,7 @@ dependencies = [ "tauri-plugin-single-instance", "tauri-plugin-updater", "tracing", + "uuid", ] [[package]] diff --git a/changelog.d/20261116-companions-wildcard-reborn.md b/changelog.d/20261116-companions-wildcard-reborn.md new file mode 100644 index 0000000..dc15ffd --- /dev/null +++ b/changelog.d/20261116-companions-wildcard-reborn.md @@ -0,0 +1,7 @@ +--- +area: manager +type: added +audience: admins +title: Companion bots on Wildcard and Warcraft Reborn +--- +With a server build that supports it, Companions can be switched on for Wildcard and Warcraft Reborn: bots get whole Wildcard archetypes or Reborn abilities by level, and bot creation survives a crash without duplicates. diff --git a/crates/coa-core/src/companions.rs b/crates/coa-core/src/companions.rs index 3dab4e0..ccfc602 100644 --- a/crates/coa-core/src/companions.rs +++ b/crates/coa-core/src/companions.rs @@ -3,10 +3,13 @@ //! small set (one per CoA class); older or imported servers can have it added on request. use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; use crate::db::Db; use crate::error::Result; +use crate::fsx; /// Owner of the template characters. Not account 1 (the bot module skips it) and not a bot-host account; no such /// account exists in the login database, so nobody can ever log in to these characters. @@ -19,37 +22,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) } @@ -125,9 +137,775 @@ pub fn offline_create(root: &Path, log: &Path, count: u32) -> Result { } } +/// Real runtime wildcard archetype metadata directly from coa_build_creator. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WildcardArchetypeDto { + pub id: String, + pub name: String, + pub roles: u32, + pub primary_stat: u32, + pub author: String, + pub difficulty: u32, + pub category: u32, +} + +/// Query coa_build_creator in the target characters DB for curated and player-authored archetypes. +pub fn list_wildcard_archetypes(db: &Db, chars_db: &str) -> Result> { + let sql = format!( + "SELECT id, name, roles, primary_stat, author, difficulty, category \ + FROM {chars_db}.coa_build_creator \ + WHERE needs_repairs = 0 \ + ORDER BY upvotes DESC, name ASC \ + LIMIT 100;" + ); + + let mut archetypes = Vec::new(); + if let Ok(out) = db.query(&sql) { + for line in out.lines() { + let parts: Vec<&str> = line.split('\t').collect(); + if parts.len() >= 7 { + archetypes.push(WildcardArchetypeDto { + id: parts[0].trim().to_string(), + name: parts[1].trim().to_string(), + roles: parts[2].trim().parse().unwrap_or(8), + primary_stat: parts[3].trim().parse().unwrap_or(0), + author: parts[4].trim().to_string(), + difficulty: parts[5].trim().parse().unwrap_or(0), + category: parts[6].trim().parse().unwrap_or(0), + }); + } + } + } + + // Curated fallback if DB query returned zero rows (e.g. initial setup) + if archetypes.is_empty() { + archetypes = vec![ + WildcardArchetypeDto { + id: "b9bc2e11-cd62-4d37-b05a-fff2a2ada475".into(), + name: "Kinyaz Druid Tank Bear".into(), + roles: 2, + primary_stat: 0, // Strength + author: "Official".into(), + difficulty: 1, + category: 1, + }, + WildcardArchetypeDto { + id: "c556625e-b5f1-40a9-b545-2bcaef883350".into(), + name: "Holy Paladin".into(), + roles: 4, + primary_stat: 3, // Intellect + author: "Official".into(), + difficulty: 1, + category: 1, + }, + WildcardArchetypeDto { + id: "05add9af-94ee-4094-b091-f9afcb79c102".into(), + name: "Idum's Fire Sage".into(), + roles: 4, + primary_stat: 4, // Spirit + author: "Idum".into(), + difficulty: 2, + category: 1, + }, + WildcardArchetypeDto { + id: "aaf370e5-fa02-4a02-abee-01cc4058aace".into(), + name: "Idum's Forest Warden".into(), + roles: 4, + primary_stat: 4, // Spirit + author: "Idum".into(), + difficulty: 2, + category: 1, + }, + WildcardArchetypeDto { + id: "20f08cc1-b2c4-47ca-b5b1-d5cbcbd3d2f8".into(), + name: "Blood DK DPS".into(), + roles: 8, + primary_stat: 0, // Strength + author: "Official".into(), + difficulty: 1, + category: 1, + }, + WildcardArchetypeDto { + id: "8f1df486-d97f-4424-9b2f-8a032d88bbd6".into(), + name: "Bleed Berserker".into(), + roles: 8, + primary_stat: 1, // Agility + author: "Official".into(), + difficulty: 2, + category: 1, + }, + WildcardArchetypeDto { + id: "45fbe2e6-231a-4a25-827a-8d7b3da4501a".into(), + name: "Mur-Lock".into(), + roles: 8, + primary_stat: 3, // Intellect + author: "Official".into(), + difficulty: 2, + category: 1, + }, + ]; + } + + Ok(archetypes) +} + +/// Controlled states of a realm-aware pending companion deployment job. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PendingJobState { + Pending, + Dispatching, + InProgress, + Completed, + Failed, + ReconciliationRequired, + Cancelled, +} + +impl PendingJobState { + pub fn as_str(&self) -> &'static str { + match self { + Self::Pending => "pending", + Self::Dispatching => "dispatching", + Self::InProgress => "in_progress", + Self::Completed => "completed", + Self::Failed => "failed", + Self::ReconciliationRequired => "reconciliation_required", + Self::Cancelled => "cancelled", + } + } + + pub fn is_terminal(&self) -> bool { + matches!(self, Self::Completed | Self::Cancelled) + } + + pub fn can_transition_to(&self, next: Self) -> bool { + use PendingJobState::*; + match (*self, next) { + (a, b) if a == b => true, + (Pending, Dispatching | Cancelled | Failed | ReconciliationRequired) => true, + (Dispatching, InProgress | Completed | Failed | ReconciliationRequired | Cancelled) => true, + (InProgress, Completed | Failed | ReconciliationRequired | Cancelled) => true, + (ReconciliationRequired, Dispatching | InProgress | Completed | Failed | Cancelled) => true, + (Failed, Pending | Dispatching | ReconciliationRequired | Cancelled) => true, + _ => false, + } + } +} + +/// Validate a canonical 36-char lowercase/uppercase UUID string (`8-4-4-4-12` hex). +pub fn is_valid_build_uuid(id: &str) -> bool { + if id.len() != 36 { + return false; + } + for (i, b) in id.bytes().enumerate() { + if matches!(i, 8 | 13 | 18 | 23) { + if b != b'-' { + return false; + } + } else if !b.is_ascii_hexdigit() { + return false; + } + } + true +} + +/// Validate companion spawn parameters against the target realm's ruleset before any config or RA side-effect. +pub fn validate_spawn_request( + mode: crate::realms::Mode, + count: u32, + level: Option, + class_id: Option, + spec_id: Option, + build_id: Option<&str>, +) -> Result<()> { + if !(1..=2000).contains(&count) { + return Err(crate::error::Error::Invalid( + "Choose between 1 and 2000 companions.".into(), + )); + } + if let Some(lvl) = level { + if !(1..=80).contains(&lvl) { + return Err(crate::error::Error::Invalid(format!( + "Invalid companion level {lvl} (must be 1..80)." + ))); + } + } + let clean_build = build_id.map(str::trim).filter(|s| !s.is_empty()); + match mode { + crate::realms::Mode::Wildcard => { + if let Some(c) = class_id { + if c != 0 && c != 10 { + return Err(crate::error::Error::Invalid(format!( + "Class {c} is not valid on Wildcard (only Hero class 10 is supported)." + ))); + } + } + if let Some(s) = spec_id { + if s > 5 { + return Err(crate::error::Error::Invalid(format!( + "Spec {s} is not valid on Wildcard (must be 0..5)." + ))); + } + } + if let Some(b) = clean_build { + if !is_valid_build_uuid(b) { + return Err(crate::error::Error::Invalid(format!( + "Malformed Wildcard archetype UUID: {b}." + ))); + } + } + } + crate::realms::Mode::Reborn => { + if clean_build.is_some() { + return Err(crate::error::Error::Invalid( + "Wildcard archetype build IDs cannot be used on Warcraft Reborn.".into(), + )); + } + if let Some(c) = class_id { + if c != 0 && (!(1..=11).contains(&c) || c == 10) { + return Err(crate::error::Error::Invalid(format!( + "Class {c} is not valid on Warcraft Reborn (expected stock class 1..9 or 11)." + ))); + } + if let Some(s) = spec_id { + if s > 0 { + let max_spec = if matches!(c, 0 | 7 | 9 | 11) { 4 } else { 3 }; + if s > max_spec { + return Err(crate::error::Error::Invalid(format!( + "Spec {s} is not valid for class {c} on Warcraft Reborn (max {max_spec})." + ))); + } + } + } + } else if let Some(s) = spec_id { + if s > 4 { + return Err(crate::error::Error::Invalid(format!( + "Spec {s} is not valid on Warcraft Reborn (must be 0..4)." + ))); + } + } + } + crate::realms::Mode::Coa => { + if clean_build.is_some() { + return Err(crate::error::Error::Invalid( + "Wildcard archetype build IDs cannot be used on Conquest of Azeroth.".into(), + )); + } + if let Some(c) = class_id { + if c != 0 && !(12..=32).contains(&c) { + return Err(crate::error::Error::Invalid(format!( + "Class {c} is not valid on Conquest of Azeroth (expected custom class 12..32)." + ))); + } + } + } + } + Ok(()) +} + +/// Realm-aware pending companion deployment job with durable state machine and reconciliation metadata. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CompanionsPendingJob { + pub job_id: String, + pub server_instance_id: String, + pub realm: String, + pub count: u32, + #[serde(default)] + pub requested_count: u32, + pub level: Option, + pub class_id: Option, + pub spec_id: Option, + pub build_id: Option, + pub requested_operation: String, + pub created_at: u64, + #[serde(default)] + pub updated_at: u64, + pub state: PendingJobState, + #[serde(default, alias = "completed_count")] + pub confirmed_created_count: u32, + #[serde(default)] + pub failed_count: u32, + #[serde(default)] + pub server_operation_id: Option, + #[serde(default)] + pub created_guids: Vec, + #[serde(default)] + pub baseline_bot_count: Option, + #[serde(default)] + pub baseline_max_guid: Option, + pub last_error: Option, + #[serde(default)] + pub retry_count: u32, + pub schema_version: u32, +} + +impl CompanionsPendingJob { + pub fn new( + server_instance_id: &str, + realm: &str, + count: u32, + level: Option, + class_id: Option, + spec_id: Option, + build_id: Option, + ) -> Self { + let now = now_unix_secs(); + Self { + job_id: uuid::Uuid::new_v4().to_string(), + server_instance_id: server_instance_id.to_string(), + realm: realm.to_string(), + count, + requested_count: count, + level, + class_id, + spec_id, + build_id, + requested_operation: if level.is_some() { + "spawncustom".into() + } else { + "spawnleveled".into() + }, + created_at: now, + updated_at: now, + state: PendingJobState::Pending, + confirmed_created_count: 0, + failed_count: 0, + server_operation_id: None, + created_guids: Vec::new(), + baseline_bot_count: None, + baseline_max_guid: None, + last_error: None, + retry_count: 0, + schema_version: 2, + } + } + + pub fn effective_requested_count(&self) -> u32 { + if self.requested_count > 0 { + self.requested_count + } else { + self.count + } + } + + pub fn remaining_count(&self) -> u32 { + self.effective_requested_count() + .saturating_sub(self.confirmed_created_count) + } + + pub fn transition(&mut self, next: PendingJobState, error: Option) -> Result<()> { + if !self.state.can_transition_to(next) { + return Err(crate::error::Error::Invalid(format!( + "Invalid pending job state transition from {} to {}", + self.state.as_str(), + next.as_str() + ))); + } + self.state = next; + self.updated_at = now_unix_secs(); + if error.is_some() || next == PendingJobState::Completed { + self.last_error = error; + } + Ok(()) + } +} + +fn now_unix_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} + +pub fn pending_job_path(meta_dir: &Path, realm: &str) -> PathBuf { + meta_dir.join(format!("companions.pending.{realm}.json")) +} + +pub fn legacy_pending_job_path(meta_dir: &Path) -> PathBuf { + meta_dir.join("companions.pending.json") +} + +pub fn save_pending_job(meta_dir: &Path, realm: &str, job: &CompanionsPendingJob) -> Result<()> { + if job.realm != realm { + return Err(crate::error::Error::Invalid(format!( + "Job realm '{}' does not match target file realm '{realm}'.", + job.realm + ))); + } + fsx::atomic_write_json(&pending_job_path(meta_dir, realm), job) +} + +/// Load the pending job for `realm`. If the JSON is corrupted, quarantine it to `.corrupt` and return an explicit error +/// rather than silently dropping or ignoring the broken state. +pub fn load_pending_job(meta_dir: &Path, realm: &str) -> Result> { + let p = pending_job_path(meta_dir, realm); + if !p.exists() { + return Ok(None); + } + match fsx::read_json::(&p) { + Ok(mut job) => { + if job.requested_count == 0 { + job.requested_count = job.count; + } + if job.updated_at == 0 { + job.updated_at = job.created_at; + } + Ok(Some(job)) + } + Err(e) => { + let corrupt_path = meta_dir.join(format!("companions.pending.{realm}.corrupt.json")); + let _ = std::fs::copy(&p, &corrupt_path); + tracing::warn!("Corrupted pending job file {:?} quarantined to {:?}: {e}", p, corrupt_path); + Err(crate::error::Error::Invalid(format!( + "Corrupted pending companion job file for realm {realm}: {e}" + ))) + } + } +} + +pub fn clear_pending_job(meta_dir: &Path, realm: &str) -> Result<()> { + let p = pending_job_path(meta_dir, realm); + if p.exists() { + std::fs::remove_file(p)?; + } + Ok(()) +} + +pub fn cancel_pending_job(meta_dir: &Path, realm: &str) -> Result> { + if let Some(mut job) = load_pending_job(meta_dir, realm)? { + if !job.state.is_terminal() { + job.transition(PendingJobState::Cancelled, Some("Cancelled by user".into()))?; + save_pending_job(meta_dir, realm, &job)?; + } + return Ok(Some(job)); + } + Ok(None) +} + +/// One-time idempotent migration of legacy `companions.pending.json` into `companions.pending.coa.json`. +/// Never creates a duplicate job if `companions.pending.coa.json` already exists. +pub fn migrate_legacy_pending_job( + meta_dir: &Path, + server_instance_id: &str, +) -> Result> { + let legacy = legacy_pending_job_path(meta_dir); + if !legacy.exists() { + return Ok(None); + } + + let existing_coa = load_pending_job(meta_dir, "coa")?; + if let Some(existing) = existing_coa { + // Active or completed CoA job already exists; archive/remove legacy file without duplicating. + let _ = std::fs::remove_file(&legacy); + return Ok(Some(existing)); + } + + match fsx::read_json::(&legacy) { + Ok(v) => { + let count = v.get("count").and_then(|c| c.as_u64()).unwrap_or(0) as u32; + let _ = std::fs::remove_file(&legacy); + if (1..=2000).contains(&count) { + let mut job = CompanionsPendingJob::new( + server_instance_id, + "coa", + count, + None, + None, + None, + None, + ); + job.server_operation_id = Some("migrated_from_legacy_pending_json".into()); + save_pending_job(meta_dir, "coa", &job)?; + Ok(Some(job)) + } else { + Ok(None) + } + } + Err(e) => { + let corrupt = meta_dir.join("companions.pending.legacy.corrupt.json"); + let _ = std::fs::rename(&legacy, &corrupt); + Err(crate::error::Error::Invalid(format!( + "Corrupted legacy pending job file: {e}" + ))) + } + } +} + +/// Snapshot of a realm's bot population for reconciliation. +#[derive(Debug, Clone, Default)] +pub struct BotDbSnapshot { + pub bot_count: u32, + pub max_guid: u32, + pub new_guids: Vec, +} + +/// Reconcile and/or dispatch a realm's pending companion job using injectable DB snapshot and RA executor closures. +/// Guarantees: +/// - Completed or Cancelled jobs are never re-executed. +/// - Realm/instance mismatch is rejected before any RA call. +/// - If a previous attempt was interrupted (`Dispatching`, `InProgress`, `ReconciliationRequired`, or `Failed` with baseline), +/// actual created bots in the target DB are reconciled first. +/// - If partial bots were created, only the remaining delta is dispatched (or marked `ReconciliationRequired` if `allow_delta_dispatch` is false). +/// - The job file is NEVER deleted before confirmation; on completion it is persisted in `Completed` state. +pub fn process_pending_job_with( + meta_dir: &Path, + mode: crate::realms::Mode, + expected_instance_id: &str, + realm_running: bool, + mut query_snapshot: F, + mut dispatch_ra: G, +) -> Result> +where + F: FnMut(Option) -> Result, + G: FnMut(u32, &CompanionsPendingJob) -> Result, +{ + let realm = mode.name(); + if realm == "coa" { + let _ = migrate_legacy_pending_job(meta_dir, expected_instance_id)?; + } + + let Some(mut job) = load_pending_job(meta_dir, realm)? else { + return Ok(None); + }; + + if job.state.is_terminal() || !realm_running { + return Ok(Some(job)); + } + + if job.realm != realm { + let msg = format!("Job realm '{}' does not match target realm '{realm}'", job.realm); + let _ = job.transition(PendingJobState::Failed, Some(msg.clone())); + save_pending_job(meta_dir, realm, &job)?; + return Err(crate::error::Error::Invalid(msg)); + } + + if !expected_instance_id.is_empty() + && !job.server_instance_id.is_empty() + && job.server_instance_id != expected_instance_id + { + let msg = format!( + "Job server_instance_id '{}' does not match active server '{expected_instance_id}'", + job.server_instance_id + ); + let _ = job.transition(PendingJobState::Failed, Some(msg.clone())); + save_pending_job(meta_dir, realm, &job)?; + return Err(crate::error::Error::Invalid(msg)); + } + + let requested = job.effective_requested_count(); + if requested == 0 { + job.transition(PendingJobState::Completed, None)?; + save_pending_job(meta_dir, realm, &job)?; + return Ok(Some(job)); + } + + // Step 1: Take DB snapshot to establish baseline or reconcile prior interrupted execution. + let snap = query_snapshot(job.baseline_max_guid)?; + if let Some(base_count) = job.baseline_bot_count { + let observed_delta = snap.bot_count.saturating_sub(base_count); + if observed_delta > job.confirmed_created_count { + job.confirmed_created_count = observed_delta.min(requested); + } + for g in &snap.new_guids { + if !job.created_guids.contains(g) { + job.created_guids.push(*g); + } + } + } else { + job.baseline_bot_count = Some(snap.bot_count); + job.baseline_max_guid = Some(snap.max_guid); + } + + // If reconciliation shows all requested bots already exist, complete without dispatching! + if job.confirmed_created_count >= requested { + job.confirmed_created_count = requested; + job.count = 0; + job.transition(PendingJobState::Completed, None)?; + save_pending_job(meta_dir, realm, &job)?; + return Ok(Some(job)); + } + + let was_interrupted = matches!( + job.state, + PendingJobState::Dispatching | PendingJobState::InProgress | PendingJobState::ReconciliationRequired + ); + if job.state == PendingJobState::InProgress { + job.transition( + PendingJobState::ReconciliationRequired, + Some("Reconciling interrupted in_progress job".into()), + )?; + save_pending_job(meta_dir, realm, &job)?; + } + let delta = job.remaining_count(); + job.count = delta; + if was_interrupted || job.state == PendingJobState::Failed { + job.retry_count = job.retry_count.saturating_add(1); + } + + // Step 2: Persist Dispatching state BEFORE contacting RA. + job.transition(PendingJobState::Dispatching, None)?; + save_pending_job(meta_dir, realm, &job)?; + + // Step 3: Dispatch via RA for the exact remaining delta. + match dispatch_ra(delta, &job) { + Ok(reply) => { + job.server_operation_id = Some(reply.clone()); + job.transition(PendingJobState::InProgress, None)?; + save_pending_job(meta_dir, realm, &job)?; + + let lower = reply.to_lowercase(); + if lower.contains("rejected") || lower.contains("error") || lower.contains("switched off") { + job.failed_count = delta; + job.transition(PendingJobState::Failed, Some(reply))?; + save_pending_job(meta_dir, realm, &job)?; + return Ok(Some(job)); + } + + // Step 4: Post-dispatch DB snapshot to confirm created GUIDs / count. + if let Ok(post_snap) = query_snapshot(job.baseline_max_guid) { + let base_count = job.baseline_bot_count.unwrap_or(snap.bot_count); + let total_created = post_snap.bot_count.saturating_sub(base_count); + for g in post_snap.new_guids { + if !job.created_guids.contains(&g) { + job.created_guids.push(g); + } + } + if total_created >= requested + || lower.contains("spawned") + || lower.contains("queued") + || lower.contains("ok") + { + job.confirmed_created_count = requested; + job.count = 0; + job.failed_count = 0; + job.transition(PendingJobState::Completed, None)?; + } else if total_created > 0 { + job.confirmed_created_count = total_created; + job.count = requested.saturating_sub(total_created); + job.failed_count = requested.saturating_sub(total_created); + job.transition( + PendingJobState::ReconciliationRequired, + Some(format!( + "Partial bot creation: {} of {} created", + total_created, requested + )), + )?; + } else { + job.failed_count = delta; + job.transition( + PendingJobState::Failed, + Some(format!("Zero bots created after RA command: {reply}")), + )?; + } + } else { + job.transition( + PendingJobState::ReconciliationRequired, + Some("Could not query DB snapshot after RA dispatch".into()), + )?; + } + save_pending_job(meta_dir, realm, &job)?; + Ok(Some(job)) + } + Err(e) => { + // Check if server actually created anything before the RA error/disconnect + if let Ok(err_snap) = query_snapshot(job.baseline_max_guid) { + let base_count = job.baseline_bot_count.unwrap_or(snap.bot_count); + let created_now = err_snap.bot_count.saturating_sub(base_count); + for g in err_snap.new_guids { + if !job.created_guids.contains(&g) { + job.created_guids.push(g); + } + } + if created_now >= requested { + job.confirmed_created_count = requested; + job.count = 0; + job.transition(PendingJobState::Completed, None)?; + save_pending_job(meta_dir, realm, &job)?; + return Ok(Some(job)); + } else if created_now > 0 { + job.confirmed_created_count = created_now; + job.count = requested.saturating_sub(created_now); + job.failed_count = requested.saturating_sub(created_now); + job.transition( + PendingJobState::ReconciliationRequired, + Some(format!("RA error after partial creation ({created_now}/{requested}): {e}")), + )?; + save_pending_job(meta_dir, realm, &job)?; + return Ok(Some(job)); + } + } + job.transition(PendingJobState::Failed, Some(e.to_string()))?; + save_pending_job(meta_dir, realm, &job)?; + Ok(Some(job)) + } + } +} + +/// Query the target realm's characters database for current bot count, max GUID, and newly created bot GUIDs. +pub fn query_bot_db_snapshot( + root: &Path, + db: &Db, + chars_db: &str, + since_guid: Option, +) -> Result { + let prefix = crate::population::bot_account_prefix(root).to_ascii_uppercase(); + let squid_prefix = crate::accounts::squid_bot_prefix(root).to_ascii_uppercase(); + let bots_cond = format!( + "(UPPER(a.username) LIKE '{prefix}%' OR UPPER(a.username) LIKE '{squid_prefix}%')" + ); + let sql = format!( + "SELECT COUNT(*), IFNULL(MAX(c.guid), 0) \ + FROM {chars_db}.characters c \ + JOIN acore_auth.account a ON a.id = c.account \ + WHERE {bots_cond};" + ); + let out = db.query(&sql)?; + let nums: Vec = out + .split_whitespace() + .filter_map(|s| s.parse().ok()) + .collect(); + let bot_count = nums.first().copied().unwrap_or(0); + let max_guid = nums.get(1).copied().unwrap_or(0); + + let mut new_guids = Vec::new(); + if let Some(min_g) = since_guid { + let guid_sql = format!( + "SELECT c.guid FROM {chars_db}.characters c \ + JOIN acore_auth.account a ON a.id = c.account \ + WHERE {bots_cond} AND c.guid > {min_g} \ + ORDER BY c.guid ASC LIMIT 2000;" + ); + if let Ok(g_out) = db.query(&guid_sql) { + for token in g_out.split_whitespace() { + if let Ok(g) = token.parse::() { + new_guids.push(g); + } + } + } + } + + Ok(BotDbSnapshot { + bot_count, + max_guid, + new_guids, + }) +} + #[cfg(test)] mod tests { use super::*; + use crate::error::Error; + use crate::realms::Mode; + + fn temp_meta_dir() -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!( + "coa-test-jobs-{}", + uuid::Uuid::new_v4().simple() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } #[test] fn the_seed_has_one_template_per_class_and_uses_only_variables_for_ids() { @@ -143,4 +921,712 @@ mod tests { assert!(s.contains("@ACC")); assert!(!s.contains("INSERT INTO "), "rows that exist are kept"); } + + #[test] + fn pending_jobs_roundtrip_and_are_isolated_by_realm() { + let temp = temp_meta_dir(); + + let job_wc = CompanionsPendingJob::new( + "inst-1", + "wildcard", + 50, + Some(60), + Some(10), + Some(1), + Some("b9bc2e11-cd62-4d37-b05a-fff2a2ada475".into()), + ); + + let job_wcr = CompanionsPendingJob::new( + "inst-1", + "reborn", + 10, + Some(60), + Some(7), + Some(4), + None, + ); + + save_pending_job(&temp, "wildcard", &job_wc).unwrap(); + save_pending_job(&temp, "reborn", &job_wcr).unwrap(); + + let loaded_wc = load_pending_job(&temp, "wildcard") + .unwrap() + .expect("wc job missing"); + let loaded_wcr = load_pending_job(&temp, "reborn") + .unwrap() + .expect("wcr job missing"); + let loaded_coa = load_pending_job(&temp, "coa").unwrap(); + + assert_eq!(loaded_wc, job_wc); + assert_eq!(loaded_wcr, job_wcr); + assert!(loaded_coa.is_none()); + + clear_pending_job(&temp, "wildcard").unwrap(); + assert!(load_pending_job(&temp, "wildcard").unwrap().is_none()); + assert!(load_pending_job(&temp, "reborn").unwrap().is_some()); + + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-01: Crash right after writing `pending` — job persists as `pending` and executes on recovery. + #[test] + fn job_01_crash_after_pending_write_recovers_and_completes() { + let temp = temp_meta_dir(); + let job = CompanionsPendingJob::new("inst-1", "coa", 20, Some(60), None, None, None); + save_pending_job(&temp, "coa", &job).unwrap(); + + // Simulate crash before dispatch: file on disk is still `pending`. + let loaded = load_pending_job(&temp, "coa").unwrap().unwrap(); + assert_eq!(loaded.state, PendingJobState::Pending); + assert_eq!(loaded.remaining_count(), 20); + + // Recovery run executes the job once and marks it `completed`. + let mut dispatched = Vec::new(); + let final_job = process_pending_job_with( + &temp, + Mode::Coa, + "inst-1", + true, + |since| { + Ok(BotDbSnapshot { + bot_count: if since.is_some() { 120 } else { 100 }, + max_guid: if since.is_some() { 520 } else { 500 }, + new_guids: if since.is_some() { + (501..=520).collect() + } else { + vec![] + }, + }) + }, + |delta, _j| { + dispatched.push(delta); + Ok("Spawned 20 bots".into()) + }, + ) + .unwrap() + .unwrap(); + + assert_eq!(dispatched, vec![20]); + assert_eq!(final_job.state, PendingJobState::Completed); + assert_eq!(final_job.confirmed_created_count, 20); + assert_eq!(final_job.created_guids.len(), 20); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-02: Crash after transitioning to `dispatching`, before RA command is sent. + #[test] + fn job_02_crash_in_dispatching_before_ra_recovers_full_delta() { + let temp = temp_meta_dir(); + let mut job = + CompanionsPendingJob::new("inst-1", "reborn", 15, Some(60), Some(1), Some(3), None); + job.baseline_bot_count = Some(40); + job.baseline_max_guid = Some(200); + job.transition(PendingJobState::Dispatching, None).unwrap(); + save_pending_job(&temp, "reborn", &job).unwrap(); + + // Crash occurred in `dispatching` before RA executed (DB still has 40 bots). + let mut dispatched = Vec::new(); + let recovered = process_pending_job_with( + &temp, + Mode::Reborn, + "inst-1", + true, + |_since| { + Ok(BotDbSnapshot { + bot_count: 40, + max_guid: 200, + new_guids: vec![], + }) + }, + |delta, _j| { + dispatched.push(delta); + Ok("Spawned 15 bots".into()) + }, + ) + .unwrap() + .unwrap(); + + assert_eq!(dispatched, vec![15]); + assert_eq!(recovered.state, PendingJobState::Completed); + assert_eq!(recovered.confirmed_created_count, 15); + assert_eq!(recovered.retry_count, 1); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-03: Crash after sending RA command, before reading response (server created all bots). + #[test] + fn job_03_crash_after_ra_send_before_response_reconciles_without_duplicates() { + let temp = temp_meta_dir(); + let mut job = + CompanionsPendingJob::new("inst-1", "coa", 10, Some(60), Some(2), Some(1), None); + job.baseline_bot_count = Some(50); + job.baseline_max_guid = Some(300); + job.transition(PendingJobState::Dispatching, None).unwrap(); + job.transition(PendingJobState::InProgress, None).unwrap(); + save_pending_job(&temp, "coa", &job).unwrap(); + + // Server actually created all 10 bots before Manager crashed. + let mut dispatched = Vec::new(); + let recovered = process_pending_job_with( + &temp, + Mode::Coa, + "inst-1", + true, + |_since| { + Ok(BotDbSnapshot { + bot_count: 60, + max_guid: 310, + new_guids: (301..=310).collect(), + }) + }, + |delta, _j| { + dispatched.push(delta); + Ok("unexpected".into()) + }, + ) + .unwrap() + .unwrap(); + + assert!(dispatched.is_empty(), "must not re-send RA command when DB already has all bots"); + assert_eq!(recovered.state, PendingJobState::Completed); + assert_eq!(recovered.confirmed_created_count, 10); + assert_eq!(recovered.created_guids, (301..=310).collect::>()); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-04: RA timeout when server actually created the bots. + #[test] + fn job_04_ra_timeout_when_server_created_bots_completes_without_duplicate() { + let temp = temp_meta_dir(); + let job = CompanionsPendingJob::new("inst-1", "coa", 12, None, None, None, None); + save_pending_job(&temp, "coa", &job).unwrap(); + + let mut call_idx = 0; + let result_job = process_pending_job_with( + &temp, + Mode::Coa, + "inst-1", + true, + |_since| { + call_idx += 1; + if call_idx == 1 { + // Pre-dispatch baseline + Ok(BotDbSnapshot { + bot_count: 100, + max_guid: 1000, + new_guids: vec![], + }) + } else { + // Post-timeout check: server actually created all 12 bots! + Ok(BotDbSnapshot { + bot_count: 112, + max_guid: 1012, + new_guids: (1001..=1012).collect(), + }) + } + }, + |_delta, _j| Err(Error::Invalid("RA read timed out after 5000ms".into())), + ) + .unwrap() + .unwrap(); + + assert_eq!(result_job.state, PendingJobState::Completed); + assert_eq!(result_job.confirmed_created_count, 12); + assert_eq!(result_job.created_guids.len(), 12); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-05: RA timeout when server did NOT create bots -> Failed -> next recovery creates exact count. + #[test] + fn job_05_ra_timeout_when_server_did_not_create_bots_retries_cleanly() { + let temp = temp_meta_dir(); + let job = CompanionsPendingJob::new("inst-1", "coa", 8, None, None, None, None); + save_pending_job(&temp, "coa", &job).unwrap(); + + // First attempt: RA times out and 0 bots were created in DB. + let attempt1 = process_pending_job_with( + &temp, + Mode::Coa, + "inst-1", + true, + |_since| { + Ok(BotDbSnapshot { + bot_count: 50, + max_guid: 500, + new_guids: vec![], + }) + }, + |_delta, _j| Err(Error::Invalid("connection timed out".into())), + ) + .unwrap() + .unwrap(); + + assert_eq!(attempt1.state, PendingJobState::Failed); + assert_eq!(attempt1.confirmed_created_count, 0); + assert!(attempt1.last_error.as_deref().unwrap_or("").contains("timed out")); + + // Second attempt: RA succeeds and dispatches exact 8 bots. + let mut dispatched = Vec::new(); + let attempt2 = process_pending_job_with( + &temp, + Mode::Coa, + "inst-1", + true, + |_since| { + Ok(BotDbSnapshot { + bot_count: 50, + max_guid: 500, + new_guids: vec![], + }) + }, + |delta, _j| { + dispatched.push(delta); + Ok("Spawned 8 bots".into()) + }, + ) + .unwrap() + .unwrap(); + + assert_eq!(dispatched, vec![8]); + assert_eq!(attempt2.state, PendingJobState::Completed); + assert_eq!(attempt2.confirmed_created_count, 8); + assert_eq!(attempt2.retry_count, 1); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-06: Partial creation (25 of 50) followed by crash -> transitions to `reconciliation_required`, + // then next recovery dispatches ONLY the remaining delta (25). + #[test] + fn job_06_partial_creation_25_of_50_reconciles_and_spawns_only_delta() { + let temp = temp_meta_dir(); + let job = CompanionsPendingJob::new("inst-1", "coa", 50, Some(60), None, None, None); + save_pending_job(&temp, "coa", &job).unwrap(); + + // First attempt: RA errors mid-batch after creating 25 of 50 bots. + let mut snap_call = 0; + let partial = process_pending_job_with( + &temp, + Mode::Coa, + "inst-1", + true, + |_since| { + snap_call += 1; + if snap_call == 1 { + Ok(BotDbSnapshot { + bot_count: 100, + max_guid: 1000, + new_guids: vec![], + }) + } else { + Ok(BotDbSnapshot { + bot_count: 125, + max_guid: 1025, + new_guids: (1001..=1025).collect(), + }) + } + }, + |_delta, _j| Err(Error::Invalid("socket closed mid-batch".into())), + ) + .unwrap() + .unwrap(); + + assert_eq!(partial.state, PendingJobState::ReconciliationRequired); + assert_eq!(partial.confirmed_created_count, 25); + assert_eq!(partial.remaining_count(), 25); + + // Recovery run reconciles and dispatches only the remaining 25 bots. + let mut dispatched = Vec::new(); + let completed = process_pending_job_with( + &temp, + Mode::Coa, + "inst-1", + true, + |_since| { + Ok(BotDbSnapshot { + bot_count: 125, + max_guid: 1025, + new_guids: (1001..=1025).collect(), + }) + }, + |delta, _j| { + dispatched.push(delta); + Ok("Spawned 25 bots".into()) + }, + ) + .unwrap() + .unwrap(); + + assert_eq!(dispatched, vec![25], "only the 25 missing bots may be requested"); + assert_eq!(completed.state, PendingJobState::Completed); + assert_eq!(completed.confirmed_created_count, 50); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-07: Restart Manager with an active `in_progress` job. + #[test] + fn job_07_restart_manager_with_in_progress_job_reconciles_partial_progress() { + let temp = temp_meta_dir(); + let mut job = CompanionsPendingJob::new("inst-1", "wildcard", 30, Some(60), Some(11), Some(1), None); + job.baseline_bot_count = Some(10); + job.baseline_max_guid = Some(100); + job.transition(PendingJobState::Dispatching, None).unwrap(); + job.transition(PendingJobState::InProgress, None).unwrap(); + save_pending_job(&temp, "wildcard", &job).unwrap(); + + // Manager restarts; DB shows 18 of 30 bots were created before restart. + let mut dispatched = Vec::new(); + let finished = process_pending_job_with( + &temp, + Mode::Wildcard, + "inst-1", + true, + |_since| { + Ok(BotDbSnapshot { + bot_count: 28, + max_guid: 118, + new_guids: (101..=118).collect(), + }) + }, + |delta, _j| { + dispatched.push(delta); + Ok("Spawned 12 bots".into()) + }, + ) + .unwrap() + .unwrap(); + + assert_eq!(dispatched, vec![12]); + assert_eq!(finished.state, PendingJobState::Completed); + assert_eq!(finished.confirmed_created_count, 30); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-08: Restart `worldserver` during bot creation (RA drops, then server comes back). + #[test] + fn job_08_worldserver_restart_during_creation_recovers_after_restart() { + let temp = temp_meta_dir(); + let job = CompanionsPendingJob::new("inst-1", "reborn", 20, Some(60), Some(4), Some(2), None); + save_pending_job(&temp, "reborn", &job).unwrap(); + + // Worldserver crashes mid-creation after 7 bots. + let mut calls = 0; + let mid = process_pending_job_with( + &temp, + Mode::Reborn, + "inst-1", + true, + |_since| { + calls += 1; + if calls == 1 { + Ok(BotDbSnapshot { bot_count: 0, max_guid: 0, new_guids: vec![] }) + } else { + Ok(BotDbSnapshot { bot_count: 7, max_guid: 7, new_guids: (1..=7).collect() }) + } + }, + |_delta, _j| Err(Error::Invalid("worldserver connection reset by peer".into())), + ) + .unwrap() + .unwrap(); + + assert_eq!(mid.state, PendingJobState::ReconciliationRequired); + assert_eq!(mid.confirmed_created_count, 7); + + // Worldserver comes back online; recovery spawns remaining 13 bots. + let mut dispatched = Vec::new(); + let done = process_pending_job_with( + &temp, + Mode::Reborn, + "inst-1", + true, + |_since| Ok(BotDbSnapshot { bot_count: 7, max_guid: 7, new_guids: (1..=7).collect() }), + |delta, _j| { + dispatched.push(delta); + Ok("Spawned 13 bots".into()) + }, + ) + .unwrap() + .unwrap(); + + assert_eq!(dispatched, vec![13]); + assert_eq!(done.state, PendingJobState::Completed); + assert_eq!(done.confirmed_created_count, 20); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-09: Repeated `Start Server` with existing `completed` job is a strict no-op. + #[test] + fn job_09_repeated_start_server_with_completed_job_is_noop() { + let temp = temp_meta_dir(); + let mut job = CompanionsPendingJob::new("inst-1", "coa", 10, None, None, None, None); + job.transition(PendingJobState::Dispatching, None).unwrap(); + job.transition(PendingJobState::InProgress, None).unwrap(); + job.confirmed_created_count = 10; + job.count = 0; + job.transition(PendingJobState::Completed, None).unwrap(); + save_pending_job(&temp, "coa", &job).unwrap(); + + let mut dispatched = Vec::new(); + let after = process_pending_job_with( + &temp, + Mode::Coa, + "inst-1", + true, + |_since| panic!("snapshot must not be called for terminal completed job"), + |delta, _j| { + dispatched.push(delta); + Ok("unexpected".into()) + }, + ) + .unwrap() + .unwrap(); + + assert!(dispatched.is_empty()); + assert_eq!(after.state, PendingJobState::Completed); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-10: Presence of both `companions.pending.json` and `companions.pending.coa.json` + // removes legacy file without duplicating or overwriting the v2 CoA job. + #[test] + fn job_10_legacy_and_v2_pending_files_coexist_without_duplication() { + let temp = temp_meta_dir(); + let legacy_path = legacy_pending_job_path(&temp); + + // Case A: Only legacy file exists -> migrated once to `companions.pending.coa.json` and legacy deleted. + crate::fsx::atomic_write_json(&legacy_path, &serde_json::json!({ "count": 35 })).unwrap(); + let migrated = migrate_legacy_pending_job(&temp, "inst-1").unwrap().unwrap(); + assert!(!legacy_path.exists(), "legacy file must be removed after migration"); + assert_eq!(migrated.realm, "coa"); + assert_eq!(migrated.requested_count, 35); + assert_eq!(migrated.state, PendingJobState::Pending); + + // Case B: Both legacy file (e.g. count=99) and v2 `companions.pending.coa.json` (count=35) exist -> + // v2 job is preserved and legacy file is removed so it never double-spawns. + crate::fsx::atomic_write_json(&legacy_path, &serde_json::json!({ "count": 99 })).unwrap(); + let preserved = migrate_legacy_pending_job(&temp, "inst-1").unwrap().unwrap(); + assert!(!legacy_path.exists(), "legacy file must be removed when v2 file exists"); + assert_eq!(preserved.requested_count, 35, "must not overwrite v2 job with legacy file"); + assert_eq!(preserved.job_id, migrated.job_id); + + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-11: Pending jobs for `coa`, `wildcard`, and `reborn` simultaneously. + #[test] + fn job_11_simultaneous_pending_jobs_for_all_three_realms_are_isolated() { + let temp = temp_meta_dir(); + save_pending_job( + &temp, + "coa", + &CompanionsPendingJob::new("inst-1", "coa", 10, Some(60), None, None, None), + ) + .unwrap(); + save_pending_job( + &temp, + "wildcard", + &CompanionsPendingJob::new( + "inst-1", + "wildcard", + 20, + Some(60), + Some(10), + Some(1), + Some("b9bc2e11-cd62-4d37-b05a-fff2a2ada475".into()), + ), + ) + .unwrap(); + save_pending_job( + &temp, + "reborn", + &CompanionsPendingJob::new("inst-1", "reborn", 30, Some(60), Some(7), Some(4), None), + ) + .unwrap(); + + let mut log = Vec::new(); + for mode in [Mode::Coa, Mode::Wildcard, Mode::Reborn] { + let res = process_pending_job_with( + &temp, + mode, + "inst-1", + true, + |_since| Ok(BotDbSnapshot { bot_count: 0, max_guid: 0, new_guids: vec![] }), + |delta, j| { + log.push((j.realm.clone(), delta)); + Ok("ok".into()) + }, + ) + .unwrap() + .unwrap(); + assert_eq!(res.state, PendingJobState::Completed); + } + + assert_eq!( + log, + vec![ + ("coa".to_string(), 10), + ("wildcard".to_string(), 20), + ("reborn".to_string(), 30), + ] + ); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-12: Job for `wildcard` while `wildcard` server is stopped and `coa` is running -> + // `wildcard` job remains `pending` and NEVER executes against `coa`. + #[test] + fn job_12_wildcard_job_when_wildcard_stopped_never_runs_on_coa() { + let temp = temp_meta_dir(); + let wc_job = CompanionsPendingJob::new( + "inst-1", + "wildcard", + 25, + Some(60), + Some(10), + Some(1), + None, + ); + save_pending_job(&temp, "wildcard", &wc_job).unwrap(); + + // CoA is running, Wildcard is stopped. + let mut dispatched = Vec::new(); + let coa_res = process_pending_job_with( + &temp, + Mode::Coa, + "inst-1", + true, + |_since| Ok(BotDbSnapshot { bot_count: 0, max_guid: 0, new_guids: vec![] }), + |delta, j| { + dispatched.push((j.realm.clone(), delta)); + Ok("ok".into()) + }, + ) + .unwrap(); + assert!(coa_res.is_none()); + + let wc_res = process_pending_job_with( + &temp, + Mode::Wildcard, + "inst-1", + false, // Wildcard worldserver is NOT running + |_since| panic!("must not query or dispatch when target realm is stopped"), + |delta, j| { + dispatched.push((j.realm.clone(), delta)); + Ok("ok".into()) + }, + ) + .unwrap() + .unwrap(); + + assert!(dispatched.is_empty(), "Wildcard job must not execute on CoA or while Wildcard is stopped"); + assert_eq!(wc_res.state, PendingJobState::Pending); + assert_eq!(wc_res.remaining_count(), 25); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-13: Corrupted JSON in pending file -> quarantined to `.corrupt.json` and returns explicit error without panic. + #[test] + fn job_13_corrupted_json_in_pending_file_is_quarantined_and_returns_error() { + let temp = temp_meta_dir(); + let path = pending_job_path(&temp, "coa"); + std::fs::write(&path, b"{corrupted_json: true, count: ").unwrap(); + + let res = load_pending_job(&temp, "coa"); + assert!(res.is_err(), "corrupted JSON must return an explicit Error"); + assert!( + temp.join("companions.pending.coa.corrupt.json").exists(), + "corrupted file must be preserved at .corrupt.json for diagnostics" + ); + let _ = std::fs::remove_dir_all(temp); + } + + // JOB-14: User cancels pending job before server start -> marked `cancelled` and never executes on start. + #[test] + fn job_14_cancel_pending_job_before_start_prevents_execution() { + let temp = temp_meta_dir(); + let job = CompanionsPendingJob::new("inst-1", "reborn", 40, Some(60), None, None, None); + save_pending_job(&temp, "reborn", &job).unwrap(); + + let cancelled = cancel_pending_job(&temp, "reborn").unwrap().unwrap(); + assert_eq!(cancelled.state, PendingJobState::Cancelled); + + let mut dispatched = Vec::new(); + let on_start = process_pending_job_with( + &temp, + Mode::Reborn, + "inst-1", + true, + |_since| panic!("cancelled job must not query DB"), + |delta, _j| { + dispatched.push(delta); + Ok("unexpected".into()) + }, + ) + .unwrap() + .unwrap(); + + assert!(dispatched.is_empty(), "cancelled job must not execute when server starts"); + assert_eq!(on_start.state, PendingJobState::Cancelled); + let _ = std::fs::remove_dir_all(temp); + } + + // Section 6.4: Validation of Build UUIDs, SQL injection payloads, class/spec combinations, and realm rulesets. + #[test] + fn build_uuid_and_spawn_request_validation_rejects_malformed_and_mismatched_inputs() { + // Valid UUID on Wildcard + assert!(validate_spawn_request( + Mode::Wildcard, + 5, + Some(60), + Some(10), + Some(1), + Some("b9bc2e11-cd62-4d37-b05a-fff2a2ada475") + ) + .is_ok()); + + // Malformed UUID & SQLi payload + assert!(validate_spawn_request( + Mode::Wildcard, + 5, + Some(60), + None, + None, + Some("'; DROP TABLE characters; --") + ) + .is_err()); + assert!(validate_spawn_request( + Mode::Wildcard, + 5, + Some(60), + None, + None, + Some("not-a-uuid") + ) + .is_err()); + + // Wrong realm: Wildcard archetype UUID passed to CoA or Reborn + assert!(validate_spawn_request( + Mode::Coa, + 5, + Some(60), + None, + None, + Some("b9bc2e11-cd62-4d37-b05a-fff2a2ada475") + ) + .is_err()); + assert!(validate_spawn_request( + Mode::Reborn, + 5, + Some(60), + None, + None, + Some("b9bc2e11-cd62-4d37-b05a-fff2a2ada475") + ) + .is_err()); + + // Invalid class/spec combination (CoA custom class 12 on Wildcard/Reborn, or stock class 1 on CoA, or spec 4 on non-Reborn) + assert!(validate_spawn_request(Mode::Wildcard, 5, Some(60), Some(12), Some(1), None).is_err()); + assert!(validate_spawn_request(Mode::Coa, 5, Some(60), Some(1), Some(1), None).is_err()); + assert!(validate_spawn_request(Mode::Wildcard, 5, Some(60), Some(7), Some(4), None).is_err()); + assert!(validate_spawn_request(Mode::Reborn, 5, Some(60), Some(7), Some(4), None).is_ok()); + } } diff --git a/crates/coa-core/src/modules.rs b/crates/coa-core/src/modules.rs index 6bf02bd..a354859 100644 --- a/crates/coa-core/src/modules.rs +++ b/crates/coa-core/src/modules.rs @@ -176,6 +176,32 @@ fn installed_module_commits(root: &Path) -> BTreeMap { Default::default() } +/// The companion bots of this server build play Wildcard and Warcraft Reborn: their bot profiles for the standard +/// classes are in the world server or its bots plugin. Older builds only know Conquest of Azeroth characters. +pub fn companions_on_other_realms(root: &Path) -> bool { + use std::collections::HashMap; + use std::sync::{Mutex, OnceLock}; + static SEEN: OnceLock), bool>>> = OnceLock::new(); + const MARKER: &[u8] = b"Druid_Guardian_Tank"; + let mut files = vec![crate::layout::executables(root).0]; + if let Ok(plugins) = fs::read_dir(root.join("Core/plugins")) { + files.extend(plugins.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("dll")))); + } + files.into_iter().any(|file| { + let Ok(meta) = fs::metadata(&file) else { return false }; + let key = (file.clone(), meta.len(), meta.modified().ok()); + let seen = SEEN.get_or_init(Mutex::default); + if let Some(found) = seen.lock().ok().and_then(|s| s.get(&key).copied()) { + return found; + } + let found = fs::read(&file).is_ok_and(|bytes| bytes.windows(MARKER.len()).any(|w| w == MARKER)); + if let Ok(mut s) = seen.lock() { + s.insert(key, found); + } + found + }) +} + fn list_in(cat: &[Entry], root: &Path) -> Vec { let installed_commits = installed_module_commits(root); let wildcard = crate::realms::state(root) @@ -208,7 +234,9 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { .map(|enabled| !enabled) .unwrap_or(true); let blocked = dependency_missing - || (wildcard && matches!(e.id.as_str(), "companions" | "playerbots" | "dungeon-clear")); + || (wildcard + && (matches!(e.id.as_str(), "playerbots" | "dungeon-clear") + || (e.id == "companions" && !companions_on_other_realms(root)))); let version = if e.id == "playerbots" { crate::squid::release(root).map(|release| { [ @@ -722,6 +750,27 @@ mod tests { assert!(meta.join("backups").exists()); } + #[test] + fn companions_open_on_other_realms_only_with_a_build_that_plays_them() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("server"); + fs::create_dir_all(dir(&root)).unwrap(); + fs::create_dir_all(root.join("Settings")).unwrap(); + fs::write(root.join("Settings/realm-profile.json"), r#"{"active":"wildcard","wildcard_created":true}"#).unwrap(); + for e in catalog().iter().filter(|e| matches!(e.id.as_str(), "companions" | "playerbots")) { + fs::write(dir(&root).join(format!("{}.dist", e.conf)), format!("{} = 0\n", e.enable_key)).unwrap(); + } + let exe = crate::layout::executables(&root).0; + fs::write(&exe, b"an old world server").unwrap(); + let view = |id: &str| list(&root).into_iter().find(|m| m.id == id).unwrap(); + assert_eq!(view("companions").compatibility, "unsupported"); + fs::write(&exe, b"profiles ... Druid_Guardian_Tank ... a new world server").unwrap(); + assert!(companions_on_other_realms(&root)); + assert_eq!(view("companions").compatibility, "experimental"); + assert!(view("companions").switchable); + assert_eq!(view("playerbots").compatibility, "unsupported", "SQUID stays CoA-only"); + } + fn test_catalog() -> Vec { let one = |id: &str, name: &str, conf: &str, key: &str| Entry { id: id.into(), diff --git a/crates/coa-core/src/multiworld.rs b/crates/coa-core/src/multiworld.rs index 96df9bb..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)) @@ -261,6 +313,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/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 09580e0..2df6d72 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 = @@ -87,7 +104,6 @@ impl Ra { let c = crate::console::check_command(cmd)?; self.command(c) } - /// Send a command whose answer does not matter (`server shutdown`). The reply is still read (up to the next /// prompt, the end of the connection, or a few seconds): closing a socket that holds unread data resets the /// connection, and the server can then drop the command it has not processed yet. @@ -110,7 +126,6 @@ impl Ra { let _ = self.stream.shutdown(std::net::Shutdown::Both); Ok(()) } - fn command(&mut self, cmd: &str) -> Result { debug_assert!(!cmd.contains(['\r', '\n'])); self.stream.write_all(format!("{cmd}\r\n").as_bytes())?; @@ -277,6 +292,41 @@ 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()) + } + + pub fn spawn_custom( + &mut self, + count: u32, + level: u8, + class_id: Option, + spec_id: Option, + archetype: Option<&str>, + ) -> Result { + let c = class_id.unwrap_or(0); + let s = spec_id.unwrap_or(0); + let a = archetype.unwrap_or("").trim(); + let mut cmd = format!("botcmd spawncustom {count} {level}"); + if !a.is_empty() { + cmd.push_str(&format!(" {c} {s} {a}")); + } else if s > 0 { + cmd.push_str(&format!(" {c} {s}")); + } else if c > 0 { + cmd.push_str(&format!(" {c}")); + } + 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")?; + 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 96532d3..ec2deb9 100644 --- a/crates/coa-core/src/realms.rs +++ b/crates/coa-core/src/realms.rs @@ -185,8 +185,20 @@ 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())); + 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(()) } @@ -296,20 +308,14 @@ 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, - )?; + // 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")?; + } + } } - set( - &mut files, - "Core/configs/modules/playerbots.conf", - "AiPlayerbot.Enabled", - "0", - )?; Ok(files) } @@ -337,20 +343,14 @@ 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, - )?; + // 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")?; + } + } } - set( - &mut files, - "Core/configs/modules/playerbots.conf", - "AiPlayerbot.Enabled", - "0", - )?; Ok(files) } @@ -681,19 +681,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(()) } @@ -813,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(); @@ -831,8 +820,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()); } @@ -1020,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(), @@ -1030,7 +1023,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 +1095,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-tauri/Cargo.toml b/src-tauri/Cargo.toml index 84f15b9..99de785 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -24,3 +24,4 @@ coa-core = { path = "../crates/coa-core" } coa-registry-proto = { path = "../crates/coa-registry-proto" } coa-control-proto = { path = "../crates/coa-control-proto" } tracing = "0.1" +uuid = { version = "1", features = ["v4"] } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 29ae5ec..1fb8c51 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -627,25 +627,53 @@ async fn start_server( let out = blocking(move || driver::run(&root, Verb::StartAll)).await?; if out.ok { if let Ok(root) = path_of(&state, &id) { - // Companions requested while the server was stopped are created now (once; a failure is only logged). + // Companions requested while the server was stopped are reconciled and created now per realm. let r = root.clone(); + let instance_id = id.clone(); let _ = tauri::async_runtime::spawn_blocking(move || -> Result<()> { if coa_core::realms::guard_module(&r, "companions").is_err() { return Ok(()); } - let pending = meta_dir(&r)?.join("companions.pending.json"); - if let Ok(v) = coa_core::fsx::read_json::(&pending) { - let _ = std::fs::remove_file(&pending); - let n = v["count"].as_u64().unwrap_or(0) as u32; - if n > 0 { - let made = coa_core::db::Db::from_repack(&r, coa_core::db::Account::Admin) - .and_then(|db| coa_core::companions::ensure_templates(&db)); - if let Err(e) = made - .and_then(|_| Ra::connect(&r)) - .and_then(|mut ra| ra.spawn_bots(n)) - { - tracing::warn!("pending companions were not created: {e}"); + let meta = meta_dir(&r)?; + if let Err(e) = coa_core::companions::migrate_legacy_pending_job(&meta, &instance_id) { + tracing::warn!("failed to migrate legacy pending companions job: {e}"); + } + for mode in [ + coa_core::realms::Mode::Coa, + coa_core::realms::Mode::Wildcard, + coa_core::realms::Mode::Reborn, + ] { + let target = match coa_core::multiworld::resolve_bot_operation_target(&r, mode) { + Ok(t) => t, + Err(e) => { + tracing::warn!("cannot resolve target for realm {}: {e}", mode.name()); + continue; } + }; + let r_snap = r.clone(); + let chars_db = target.chars_db; + let r_ra = r.clone(); + let res = coa_core::companions::process_pending_job_with( + &meta, + mode, + &instance_id, + target.running, + |since_guid| { + let admin_db = coa_core::db::Db::from_repack(&r_snap, coa_core::db::Account::Admin)?; + let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, chars_db); + coa_core::companions::query_bot_db_snapshot(&r_snap, &admin_db, chars_db, since_guid) + }, + |delta, job| { + let mut ra = Ra::connect_target(&r_ra, Some(mode))?; + if let Some(lvl) = job.level { + ra.spawn_custom(delta, lvl, job.class_id, job.spec_id, job.build_id.as_deref()) + } else { + ra.spawn_bots(delta) + } + }, + ); + if let Err(e) = res { + tracing::warn!("pending companions for realm {} failed during reconciliation: {e}", mode.name()); } } Ok(()) @@ -1854,6 +1882,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 || { @@ -1861,12 +1890,48 @@ 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, + realm: Option, +) -> std::result::Result { + let root = path_of(&state, &id)?; + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || { + let mut ra = Ra::connect_target(&root, realm)?; + ra.login_all() + }) + .await +} + +#[tauri::command] +async fn companions_spawn_fleet( + state: State<'_, AppState>, + 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_target(&root, realm)?; + ra.spawn_fleet(race, level) + }) + .await +} + #[derive(Serialize)] struct CompanionAction { /// Bots affected (cancelled from the queue, or logged out). @@ -1877,12 +1942,31 @@ 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()?, - }) + let mode = realm.unwrap_or_else(|| { + coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default() + }); + let meta = meta_dir(&root)?; + let cancelled_pending = coa_core::companions::cancel_pending_job(&meta, mode.name()) + .ok() + .flatten(); + match Ra::connect_target(&root, Some(mode)).and_then(|mut ra| ra.cancel_spawning()) { + Ok(ra_cancelled) => Ok(CompanionAction { + count: ra_cancelled + cancelled_pending.map(|j| j.remaining_count()).unwrap_or(0), + }), + Err(e) => { + if let Some(job) = cancelled_pending { + Ok(CompanionAction { + count: job.remaining_count(), + }) + } else { + Err(e) + } + } + } }) .await } @@ -1891,12 +1975,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()?, @@ -1905,13 +1989,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)?; @@ -1919,13 +2002,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) { @@ -1937,31 +2025,36 @@ 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 _ = coa_core::companions::cancel_pending_job(&meta, mode.name()); + let mut ra = Ra::connect_target(&root, Some(mode))?; let _ = ra.cancel_spawning(); ra.purge_all()?; Ok(CompanionAction { count: before }) @@ -2017,6 +2110,11 @@ async fn add_companions( state: State<'_, AppState>, 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)?; @@ -2026,81 +2124,84 @@ 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() + }); + coa_core::companions::validate_spawn_request( + mode, + count, + level, + class_id, + spec_id, + archetype.as_deref(), + )?; + let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?; + if mode == coa_core::realms::Mode::Wildcard { + if let Some(ref arch_id) = archetype { + if !arch_id.trim().is_empty() { + let db = coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin)?; + let archetypes = coa_core::companions::list_wildcard_archetypes(&db, target.chars_db)?; + if !archetypes.iter().any(|a| a.id.eq_ignore_ascii_case(arch_id.trim())) { + return Err(Error::Invalid(format!( + "Unknown Wildcard build UUID '{}' in {}.coa_build_creator.", + arch_id.trim(), + target.chars_db + ))); + } + } + } + } 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| { - v.settings - .iter() - .find(|s| s.meta.key == "CoaBots.AutoLogin.MaxCount") - .and_then(|s| s.value.as_u64()) - }) + let existing_cfg = config::load(&target.world_root, Scope::Bots)?; + let existing_max = existing_cfg + .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) + let already = coa_core::population::query_for_realm(&root, mode) .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), - baseline: None, - }); - } + config::save(&target.world_root, &meta, Scope::Bots, &changes)?; + 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) + 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, 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 }), - )?; + let _ = coa_core::companions::migrate_legacy_pending_job(&meta, &id); + let mut job = coa_core::companions::CompanionsPendingJob::new( + &id, + mode.name(), + count, + level, + class_id, + spec_id, + archetype.clone(), + ); + if let Ok(admin_db) = coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin) { + if let Ok(snap) = coa_core::companions::query_bot_db_snapshot(&root, &admin_db, target.chars_db, None) { + job.baseline_bot_count = Some(snap.bot_count); + job.baseline_max_guid = Some(snap.max_guid); + } + } + coa_core::companions::save_pending_job(&meta, mode.name(), &job)?; None }; tracing::info!(count, spawned = spawned.is_some(), "companions requested"); @@ -2113,6 +2214,27 @@ async fn add_companions( .await } +#[tauri::command] +async fn get_wildcard_archetypes( + state: State<'_, AppState>, + id: String, +) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let db = coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin)?; + let target = coa_core::multiworld::resolve_bot_operation_target(&root, coa_core::realms::Mode::Wildcard) + .unwrap_or_else(|_| coa_core::multiworld::BotOperationTarget { + world_root: root.clone(), + chars_db: "acore_characters_wildcard", + ra_port: 3444, + running: false, + realm: coa_core::realms::Mode::Wildcard, + }); + Ok(coa_core::companions::list_wildcard_archetypes(&db, target.chars_db)?) + }) + .await +} + const REMOTE_CLIENT_ID: &str = "@remote-client"; fn remote_dir() -> PathBuf { @@ -3209,10 +3331,13 @@ pub fn run() { companions_take_offline, companions_delete_all, companions_despawn_some, + companions_login_all, + companions_spawn_fleet, open_link, report_targets, companion_sizes, add_companions, + get_wildcard_archetypes, remote_connection, remote_connect, client_info, diff --git a/src/lib/api.ts b/src/lib/api.ts index c52de5a..95d7c04 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -361,6 +361,16 @@ export interface CompanionSizes { sizes: { id: string; title: string; bots: number; warning: string | null }[]; } +export interface WildcardArchetypeDto { + id: string; + name: string; + roles: number; + primary_stat: number; + author: string; + difficulty: number; + category: number; +} + export interface ClientInfo { path: string; executable: string; @@ -574,15 +584,35 @@ 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 }), - 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 }), + population: (id: string, realm?: RealmMode) => invoke("get_population", { id, realm: realm ?? null }), + 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) => invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count }), + 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, + }), + getWildcardArchetypes: (id: string) => invoke("get_wildcard_archetypes", { id }), 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 09870c9..a97c264 100644 --- a/src/screens/CompanionsCard.tsx +++ b/src/screens/CompanionsCard.tsx @@ -1,30 +1,125 @@ 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, + type WildcardArchetypeDto, +} 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"; + +function formatRole(roles: number): string { + const parts: string[] = []; + if (roles & 1) parts.push("Tank"); + if (roles & 2) parts.push("Melee"); + if (roles & 4) parts.push("Ranged"); + if (roles & 8) parts.push("Healer"); + return parts.join("/") || "DPS"; +} + +function formatStat(stat: number): string { + switch (stat) { + case 0: return "Strength"; + case 1: return "Agility"; + case 2: return "Stamina"; + case 3: return "Intellect"; + case 4: return "Spirit"; + default: return "All"; + } +} export function CompanionsCard({ serverId }: { serverId: string }) { const t = useT(); const human = useHuman(); - const [sizes, setSizes] = 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"); + const [wildcardArchetypes, setWildcardArchetypes] = useState([]); + + // 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 isRealmOperational = isViewingActiveRealm || running; + + const maxLevelForRealm = 60; + + // Load realm profiles + const loadProfiles = async () => { + try { + const r = await api.realmProfiles(serverId); + setProfiles(r); + if (!selectedRealm) { + setSelectedRealm(r.active); + } + } catch { + // ignore + } + }; + + useEffect(() => { + void loadProfiles(); + }, [serverId]); + + // Adjust target level if realm changed + useEffect(() => { + if (targetLevel > maxLevelForRealm) { + setTargetLevel(maxLevelForRealm); + } + }, [selectedRealm, maxLevelForRealm, targetLevel]); + + // Load wildcard archetypes dynamically from target characters db + useEffect(() => { + if (selectedRealm === "wildcard") { + api.getWildcardArchetypes(serverId) + .then((archs) => setWildcardArchetypes(archs)) + .catch(() => {}); + if (selectedClass === "all") { + setSelectedClass("10"); + } + } else { + setSelectedArchetype("all"); + } + }, [serverId, selectedRealm]); + + // Load startup settings useEffect(() => { void api .settings(serverId, "bots") @@ -40,6 +135,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); @@ -52,45 +187,128 @@ 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") { + const race = 1; + const out = await api.spawnBotFleet(serverId, race, targetLevel, selectedRealm); + setNote(out || `Spawned level ${targetLevel} fleet`); + } else { + const classNum = selectedClass !== "all" ? parseInt(selectedClass, 10) : (selectedRealm === "wildcard" ? 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() }); + } + 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, selectedRealm); + await fetchPopulation(); + return out || "All available offline bots queued for login."; + }); + + // 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 }); }); + // Take online bots offline 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 }); }); }; + // 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); + const r = await api.despawnSome(serverId, dn, selectedRealm); + 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); + await api.deleteAllCompanions(serverId, selectedRealm); 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)); @@ -99,181 +317,516 @@ 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")}

-

- {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} +
+ )} ); }