diff --git a/Cargo.lock b/Cargo.lock index 35ae8cc..0ac9215 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -787,6 +787,7 @@ dependencies = [ "tauri-plugin-single-instance", "tauri-plugin-updater", "tracing", + "uuid", ] [[package]] diff --git a/crates/coa-core/src/companions.rs b/crates/coa-core/src/companions.rs index 63d2721..b1db98e 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. @@ -134,6 +137,168 @@ 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) +} + +/// Realm-aware pending companion deployment job. +#[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, + pub level: Option, + pub class_id: Option, + pub spec_id: Option, + pub build_id: Option, + pub requested_operation: String, + pub created_at: u64, + pub state: String, // "pending", "in_progress", "completed", "failed" + pub completed_count: u32, + pub failed_count: u32, + pub last_error: Option, + pub schema_version: u32, +} + +pub fn pending_job_path(meta_dir: &Path, realm: &str) -> PathBuf { + meta_dir.join(format!("companions.pending.{realm}.json")) +} + +pub fn save_pending_job(meta_dir: &Path, realm: &str, job: &CompanionsPendingJob) -> Result<()> { + fsx::atomic_write_json(&pending_job_path(meta_dir, realm), job) +} + +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(job) => Ok(Some(job)), + Err(e) => { + tracing::warn!("Corrupted pending job file {:?}: {e}", p); + Ok(None) + } + } +} + +pub fn clear_pending_job(meta_dir: &Path, realm: &str) -> Result<()> { + let p = pending_job_path(meta_dir, realm); + if p.exists() { + let _ = std::fs::remove_file(p); + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -152,4 +317,63 @@ 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 = std::env::temp_dir().join(format!("coa-test-jobs-{}", uuid::Uuid::new_v4().simple())); + std::fs::create_dir_all(&temp).unwrap(); + + let job_wc = CompanionsPendingJob { + job_id: "test-wc-1".into(), + server_instance_id: "inst-1".into(), + realm: "wildcard".into(), + count: 50, + level: Some(60), + class_id: Some(10), + spec_id: Some(1), + build_id: Some("b9bc2e11-cd62-4d37-b05a-fff2a2ada475".into()), + requested_operation: "spawn".into(), + created_at: 1000, + state: "pending".into(), + completed_count: 0, + failed_count: 0, + last_error: None, + schema_version: 1, + }; + + let job_wcr = CompanionsPendingJob { + job_id: "test-wcr-1".into(), + server_instance_id: "inst-1".into(), + realm: "reborn".into(), + count: 10, + level: Some(60), + class_id: Some(7), + spec_id: Some(4), + build_id: None, + requested_operation: "spawn".into(), + created_at: 1001, + state: "pending".into(), + completed_count: 0, + failed_count: 0, + last_error: None, + schema_version: 1, + }; + + 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); + } } diff --git a/crates/coa-core/src/ra.rs b/crates/coa-core/src/ra.rs index c4314cc..b25d814 100644 --- a/crates/coa-core/src/ra.rs +++ b/crates/coa-core/src/ra.rs @@ -547,43 +547,23 @@ impl Ra { 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 let Some(c) = class_id { - + 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}")); - - if let Some(s) = spec_id { - - cmd.push_str(&format!(" {s}")); - - if let Some(a) = archetype { - - if !a.is_empty() { - - cmd.push_str(&format!(" {a}")); - - } - - } - - } - } let out = self.bot_command(&cmd)?; diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index bf45e14..d8710db 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 6c2b51a..b58ab68 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -630,7 +630,34 @@ async fn start_server( if coa_core::realms::guard_module(&r, "companions").is_err() { return Ok(()); } - let pending = meta_dir(&r)?.join("companions.pending.json"); + let meta = meta_dir(&r)?; + for mode in [ + coa_core::realms::Mode::Coa, + coa_core::realms::Mode::Wildcard, + coa_core::realms::Mode::Reborn, + ] { + if let Ok(Some(job)) = coa_core::companions::load_pending_job(&meta, mode.name()) { + let _ = coa_core::companions::clear_pending_job(&meta, mode.name()); + if job.count > 0 { + if let Ok(admin_db) = coa_core::db::Db::from_repack(&r, coa_core::db::Account::Admin) { + if let Ok(target) = coa_core::multiworld::resolve_bot_operation_target(&r, mode) { + let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, target.chars_db); + } + } + if let Ok(mut ra) = Ra::connect_target(&r, Some(mode)) { + let res = if let Some(lvl) = job.level { + ra.spawn_custom(job.count, lvl, job.class_id, job.spec_id, job.build_id.as_deref()) + } else { + ra.spawn_bots(job.count) + }; + if let Err(e) = res { + tracing::warn!("pending companions for realm {} were not created: {e}", mode.name()); + } + } + } + } + } + let pending = meta.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; @@ -1979,7 +2006,8 @@ async fn add_companions( let meta = meta_dir(&root)?; let mut changes = BTreeMap::new(); changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true)); - let existing_max = config::load(&root, Scope::Bots) + let existing_max = config::load(&target.world_root, Scope::Bots) + .or_else(|_| config::load(&root, Scope::Bots)) .ok() .and_then(|v| { v.settings @@ -1995,7 +2023,8 @@ async fn add_companions( "CoaBots.AutoLogin.MaxCount".to_string(), Value::from(existing_max.max(already + count).min(5000)), ); - config::save(&root, &meta, Scope::Bots, &changes)?; + let _ = config::save(&target.world_root, &meta, Scope::Bots, &changes) + .or_else(|_| config::save(&root, &meta, Scope::Bots, &changes)); let mut baseline = None; let spawned = if target.running { @@ -2012,10 +2041,33 @@ async fn add_companions( Some(ra.spawn_bots(count)?) } } else { - coa_core::fsx::atomic_write_json( - &meta.join("companions.pending.json"), - &serde_json::json!({ "count": count }), - )?; + let job = coa_core::companions::CompanionsPendingJob { + job_id: uuid::Uuid::new_v4().to_string(), + server_instance_id: id.clone(), + realm: mode.name().to_string(), + count, + level, + class_id, + spec_id, + build_id: archetype.clone(), + requested_operation: "spawn".to_string(), + created_at: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(), + state: "pending".to_string(), + completed_count: 0, + failed_count: 0, + last_error: None, + schema_version: 1, + }; + coa_core::companions::save_pending_job(&meta, mode.name(), &job)?; + if mode == coa_core::realms::Mode::Coa { + let _ = coa_core::fsx::atomic_write_json( + &meta.join("companions.pending.json"), + &serde_json::json!({ "count": count }), + ); + } None }; tracing::info!(count, spawned = spawned.is_some(), "companions requested"); @@ -2028,6 +2080,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 { @@ -3510,6 +3583,7 @@ pub fn run() { 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 92e40b7..3978776 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -528,6 +528,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; @@ -840,6 +850,7 @@ export const api = { 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 c4dd45a..a97c264 100644 --- a/src/screens/CompanionsCard.tsx +++ b/src/screens/CompanionsCard.tsx @@ -16,11 +16,32 @@ import { type RealmMode, type RealmProfiles, type UiError, + type WildcardArchetypeDto, } from "@/lib/api"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; 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(); @@ -39,6 +60,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { 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); @@ -83,6 +105,20 @@ export function CompanionsCard({ serverId }: { serverId: string }) { } }, [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 @@ -163,7 +199,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) { const out = await api.spawnBotFleet(serverId, race, targetLevel, selectedRealm); setNote(out || `Spawned level ${targetLevel} fleet`); } else { - const classNum = selectedClass !== "all" ? parseInt(selectedClass, 10) : undefined; + const classNum = selectedClass !== "all" ? parseInt(selectedClass, 10) : (selectedRealm === "wildcard" ? 10 : undefined); let specNum: number | undefined = undefined; if (selectedRole === "tank") { if (selectedRealm === "reborn") { @@ -601,12 +637,11 @@ export function CompanionsCard({ serverId }: { serverId: string }) { {selectedRealm === "wildcard" && ( <> - - - - - - + {wildcardArchetypes.map((b) => ( + + ))} )} {selectedRealm === "reborn" && (