Merge feat/companions-realms: companion bots on Wildcard and Warcraft Reborn

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	crates/coa-core/src/ra.rs
This commit is contained in:
Дмитрий committed 2026-11-16 00:52:15 +05:00
commit 326a4fe3d3
12 files changed
+2691 -327

No files matched your search

Generated
+1
View File
@@ -668,6 +668,7 @@ dependencies = [
"tauri-plugin-single-instance",
"tauri-plugin-updater",
"tracing",
"uuid",
]
[[package]]
@@ -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.
File diff suppressed because it is too large. Load diff
+50 -1
View File
@@ -176,6 +176,32 @@ fn installed_module_commits(root: &Path) -> BTreeMap<String, String> {
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<Mutex<HashMap<(PathBuf, u64, Option<std::time::SystemTime>), 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<ModuleView> {
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<ModuleView> {
.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<Entry> {
let one = |id: &str, name: &str, conf: &str, key: &str| Entry {
id: id.into(),
+58
View File
@@ -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<BotOperationTarget> {
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<PathBuf> {
&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()
+27 -10
View File
@@ -49,17 +49,19 @@ fn parse_counts(out: &str) -> Result<Population> {
})
}
/// 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<Population> {
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<String> {
counts_sql_for_db("acore_characters", prefix, squid_prefix)
}
pub fn counts_sql_for_db(chars_db: &str, prefix: &str, squid_prefix: &str) -> Result<String> {
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<String> {
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<Populatio
parse_counts(&db.query(&counts_sql(prefix, squid_prefix)?)?)
}
pub fn query_for_schema(db: &Db, chars_db: &str, prefix: &str, squid_prefix: &str) -> Result<Population> {
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<Population> {
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,
+52 -2
View File
@@ -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<crate::realms::Mode>) -> Result<Ra> {
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<Ra> {
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<String> {
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 <race> <level>).
pub fn spawn_fleet(&mut self, race: u8, level: u8) -> Result<String> {
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<u8>,
spec_id: Option<u32>,
archetype: Option<&str>,
) -> Result<String> {
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<String> {
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)?;
+40 -53
View File
@@ -185,8 +185,20 @@ pub fn view(root: &Path) -> Result<View> {
}
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<Files> {
}
}
}
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<Files> {
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());
}
}
+1
View File
@@ -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"] }
+213 -88
View File
@@ -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::<serde_json::Value>(&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<coa_core::realms::Mode>,
) -> std::result::Result<Option<coa_core::population::Population>, 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<coa_core::realms::Mode>,
) -> std::result::Result<String, UiError> {
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<coa_core::realms::Mode>,
) -> std::result::Result<String, UiError> {
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<coa_core::realms::Mode>,
) -> std::result::Result<CompanionAction, UiError> {
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<coa_core::realms::Mode>,
) -> std::result::Result<CompanionAction, UiError> {
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<coa_core::realms::Mode>,
) -> std::result::Result<CompanionAction, UiError> {
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<u64> = 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<coa_core::realms::Mode>,
) -> std::result::Result<CompanionAction, UiError> {
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<coa_core::realms::Mode>,
level: Option<u8>,
class_id: Option<u8>,
spec_id: Option<u32>,
archetype: Option<String>,
) -> std::result::Result<CompanionsResult, UiError> {
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<Vec<coa_core::companions::WildcardArchetypeDto>, 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,
+36 -6
View File
@@ -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<UpdateTxn>("rollback_update", { id, txn }),
retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }),
population: (id: string) => invoke<Population | null>("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<Population | null>("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<string>("companions_login_all", { id, realm: realm ?? null }),
spawnBotFleet: (id: string, race: number, level: number, realm?: RealmMode) => invoke<string>("companions_spawn_fleet", { id, race, level, realm: realm ?? null }),
openLink: (url: string) => invoke<void>("open_link", { url }),
performance: (id: string) => invoke<Performance | null>("get_performance", { id }),
companionSizes: () => invoke<CompanionSizes>("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<WildcardArchetypeDto[]>("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<ClientInfo | null>("client_info", { id }),
+712 -159
View File
@@ -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<CompanionSizes | null>(null);
// Realm & Environment state
const [profiles, setProfiles] = useState<RealmProfiles | null>(null);
const [selectedRealm, setSelectedRealm] = useState<RealmMode>("coa");
const [pop, setPop] = useState<Population | null>(null);
const [running, setRunning] = useState(false);
const [choice, setChoice] = useState<string>("small");
const [custom, setCustom] = useState("100");
// Fleet Configuration state
const [spawnMode, setSpawnMode] = useState<"population" | "fleet">("population");
const [countChoice, setCountChoice] = useState<string>("50");
const [customCount, setCustomCount] = useState<string>("50");
const [targetLevel, setTargetLevel] = useState<number>(80);
const [selectedClass, setSelectedClass] = useState<string>("all");
const [selectedRole, setSelectedRole] = useState<string>("all");
const [selectedArchetype, setSelectedArchetype] = useState<string>("all");
const [wildcardArchetypes, setWildcardArchetypes] = useState<WildcardArchetypeDto[]>([]);
// Operational state
const [busy, setBusy] = useState(false);
const [error, setError] = useState<UiError | null>(null);
const [note, setNote] = useState<string | null>(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<string | null>(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<string>) {
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 (
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("comp.title")}</h2>
<p className="mt-1 text-sm text-muted">
{pop
? t("comp.population", { online: pop.bots_online, total: pop.bots_total })
: running
? t("comp.reading")
: t("comp.startToSee")}
</p>
<fieldset className="mt-4">
<legend className="text-sm text-muted">{t("comp.wantMore")}</legend>
<div className="mt-2 flex flex-wrap gap-2">
{sizes?.sizes.map((s) => (
<label key={s.id} className={`cursor-pointer rounded-md border px-3 py-2 text-sm ${choice === s.id ? "border-gold bg-gold/10" : "border-line hover:bg-white/5"}`}>
<input type="radio" name="size" className="sr-only" checked={choice === s.id} onChange={() => setChoice(s.id)} />
{hasKey(`comp.size.${s.id}`) ? t(`comp.size.${s.id}` as Key) : s.title} <span className="text-muted">· {s.bots}</span>
</label>
))}
<label className={`cursor-pointer rounded-md border px-3 py-2 text-sm ${choice === "custom" ? "border-gold bg-gold/10" : "border-line hover:bg-white/5"}`}>
<input type="radio" name="size" className="sr-only" checked={choice === "custom"} onChange={() => setChoice("custom")} />
{t("comp.custom")}
</label>
{choice === "custom" && (
<input aria-label={t("comp.numberLabel")} value={custom} onChange={(e) => 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" />
)}
<Card className="mt-6 p-6 space-y-6">
{/* Header & Realm Switcher */}
<div>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2">
<Bot className="h-6 w-6 text-gold" />
<h2 className="text-xl font-bold tracking-tight">{t("comp.title")}</h2>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-muted flex items-center gap-1">
<Database className="h-3.5 w-3.5" />
DB: <code className="text-gold">{dbSchema}</code>
</span>
</div>
</div>
</fieldset>
{warning && <p className="mt-3 text-sm text-warn" role="status">{warning}</p>}
{sizes && <p className="mt-2 text-xs text-muted">{t("comp.hardware", { cores: sizes.hardware.cores, ram: sizes.hardware.ram_gb.toFixed(0) })}</p>}
<div className="mt-4 flex items-center gap-3">
<Button variant="primary" disabled={busy || !valid || job !== null} onClick={() => void add()}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{valid ? t("comp.add", { n: count }) : t("comp.addPlain")}
</Button>
{!running && <span className="text-xs text-muted">{t("comp.stoppedHint")}</span>}
{/* Realm Navigation Tabs */}
<div className="mt-4 flex flex-wrap gap-2 border-b border-line pb-3">
{(["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 (
<button
key={mode}
type="button"
onClick={() => setSelectedRealm(mode)}
className={`flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors ${
isSelected
? "bg-gold/20 text-gold border border-gold/40 shadow-sm"
: "border border-line hover:bg-white/5 text-muted hover:text-white"
}`}
>
<span>{label}</span>
{isActive && (
<span className="rounded bg-ok/20 px-1.5 py-0.5 text-[10px] font-semibold text-ok uppercase">
Active Server
</span>
)}
</button>
);
})}
</div>
</div>
{busy && !running && count >= 100 && (
<div className="mt-3">
<p className="text-sm text-muted" role="status">{t("comp.progressOffline", { n: count })}</p>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-busy="true">
<div className="h-full w-full animate-pulse rounded-full bg-gold/70" />
{/* Binary Compatibility & Realm Mode Warning */}
{!isBinaryCompatible && (
<div className="rounded-lg border border-bad/40 bg-bad/10 p-4 text-sm text-bad flex items-start gap-3">
<AlertCircle className="h-5 w-5 shrink-0 mt-0.5" />
<div>
<div className="font-semibold">Binary Compatibility Warning</div>
<p className="mt-1 text-xs text-bad/90">
The currently running server core binary does not have full multi-realm support enabled
for <strong>{selectedRealm.toUpperCase()}</strong>. Automated bot features may be restricted.
</p>
</div>
</div>
)}
{job && (
<div className="mt-3">
<div className="flex justify-between text-sm">
<span role="status">{t("comp.progress", { done, target: job.target })}</span>
<span className="text-muted">{Math.round((done / job.target) * 100)}%</span>
</div>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={done} aria-valuemin={0} aria-valuemax={job.target}>
<div className="h-full rounded-full bg-gold transition-[width] duration-500" style={{ width: `${(done / job.target) * 100}%` }} />
</div>
{done === 0 && Date.now() - job.since > 20000 && <p className="mt-1 text-xs text-muted">{t("comp.progressStalled")}</p>}
<Button className="mt-2" size="sm" variant="ghost" disabled={busy} onClick={() => void stopCreating()}>
{t("comp.stop")}
{/* Active Realm Switch Helper */}
{!isViewingActiveRealm && (
<div className="rounded-lg border border-warn/40 bg-warn/10 p-3 text-sm flex items-center justify-between gap-3">
<span className="text-warn text-xs">
Viewing <strong>{selectedRealm.toUpperCase()}</strong> bots, but the worldserver is currently running in{" "}
<strong>{activeServerRealm.toUpperCase()}</strong> mode.
</span>
<Button
size="sm"
variant="secondary"
disabled={busy}
onClick={() => void switchServerRealm(selectedRealm)}
>
Switch Server to {selectedRealm.toUpperCase()}
</Button>
</div>
)}
{note && !job && <p className="mt-3 text-sm text-ok" role="status">{note}</p>}
{running && pop && pop.bots_total > 0 && (
<div className="mt-5 border-t border-line pt-4">
<h3 className="text-sm font-semibold">{t("comp.manageTitle")}</h3>
<div className="mt-2 flex flex-wrap items-center gap-2 text-sm">
<label htmlFor="despawn-n" className="text-muted">{t("comp.despawnCount")}</label>
{/* Realm Population Dashboard */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
<div className="rounded-lg border border-line bg-bg/50 p-3">
<div className="text-xs text-muted flex items-center gap-1.5">
<Bot className="h-3.5 w-3.5 text-gold" />
Bots Online
</div>
<div className="mt-1 text-2xl font-bold text-white">
{running && pop ? pop.bots_online : "—"}
</div>
</div>
<div className="rounded-lg border border-line bg-bg/50 p-3">
<div className="text-xs text-muted flex items-center gap-1.5">
<Users className="h-3.5 w-3.5 text-gold" />
Total Fleet
</div>
<div className="mt-1 text-2xl font-bold text-white">
{pop ? pop.bots_total : "—"}
</div>
</div>
<div className="rounded-lg border border-line bg-bg/50 p-3">
<div className="text-xs text-muted flex items-center gap-1.5">
<CheckCircle2 className="h-3.5 w-3.5 text-ok" />
Players Online
</div>
<div className="mt-1 text-2xl font-bold text-white">
{running && pop ? pop.players_online : "—"}
</div>
</div>
<div className="rounded-lg border border-line bg-bg/50 p-3 flex flex-col justify-between">
<div className="text-xs text-muted flex items-center justify-between">
<span>Status</span>
<button
onClick={() => void fetchPopulation()}
title="Refresh"
className="text-muted hover:text-white"
>
<RefreshCw className="h-3 w-3" />
</button>
</div>
<div className="text-sm font-medium">
{running ? (
<span className="text-ok flex items-center gap-1">
<span className="h-2 w-2 rounded-full bg-ok animate-pulse" /> Running
</span>
) : (
<span className="text-muted">Offline</span>
)}
</div>
</div>
</div>
{/* Fleet Configuration & Spawning Section */}
<div className="border-t border-line pt-5 space-y-4">
<div className="flex items-center justify-between">
<h3 className="font-semibold text-sm tracking-wide uppercase text-muted">
Fleet Deployment Controls
</h3>
<div className="flex rounded-md border border-line p-0.5 text-xs">
<button
type="button"
onClick={() => setSpawnMode("population")}
className={`px-2.5 py-1 rounded transition-colors ${
spawnMode === "population" ? "bg-gold/20 text-gold font-medium" : "text-muted hover:text-white"
}`}
>
Batch Population
</button>
<button
type="button"
onClick={() => setSpawnMode("fleet")}
className={`px-2.5 py-1 rounded transition-colors ${
spawnMode === "fleet" ? "bg-gold/20 text-gold font-medium" : "text-muted hover:text-white"
}`}
>
Synchronous Fleet
</button>
</div>
</div>
{/* Count Selector */}
{spawnMode === "population" && (
<div>
<label className="text-xs text-muted">Fleet Size (Number of Bots)</label>
<div className="mt-2 flex flex-wrap gap-2">
{["10", "25", "50", "100", "250", "500"].map((n) => (
<button
key={n}
type="button"
onClick={() => setCountChoice(n)}
className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
countChoice === n
? "border-gold bg-gold/15 text-gold font-medium"
: "border-line hover:bg-white/5 text-muted"
}`}
>
{n}
</button>
))}
<button
type="button"
onClick={() => setCountChoice("custom")}
className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
countChoice === "custom"
? "border-gold bg-gold/15 text-gold font-medium"
: "border-line hover:bg-white/5 text-muted"
}`}
>
Custom
</button>
{countChoice === "custom" && (
<input
type="number"
min="1"
max="2000"
value={customCount}
onChange={(e) => 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"
/>
)}
</div>
</div>
)}
{/* Fleet Specific Settings: Level, Class, Role, Archetype */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
{/* Target Level */}
<div>
<label className="text-xs text-muted">
{spawnMode === "fleet" ? "Fleet Level" : "Max Level Cap"} (1 - {maxLevelForRealm})
</label>
<input
type="number"
min="1"
max={maxLevelForRealm}
value={targetLevel}
onChange={(e) => 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"
/>
</div>
{/* Class Filter */}
<div>
<label className="text-xs text-muted">Class Focus</label>
<select
value={selectedClass}
onChange={(e) => setSelectedClass(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"
>
<option value="all">All Realm Classes</option>
{selectedRealm === "coa" && (
<>
<option value="12">Barbarian</option>
<option value="13">Witch Doctor</option>
<option value="14">Felsworn</option>
<option value="15">Witch Hunter</option>
<option value="16">Stormbringer</option>
<option value="17">Knight of Xoroth</option>
<option value="18">Guardian</option>
<option value="19">Templar</option>
<option value="20">Bloodmage</option>
<option value="21">Ranger</option>
<option value="22">Chronomancer</option>
<option value="23">Necromancer</option>
<option value="24">Pyromancer</option>
<option value="25">Cultist</option>
<option value="26">Starcaller</option>
<option value="27">Tinker</option>
<option value="28">Venomancer</option>
<option value="29">Reaper</option>
<option value="30">Sun Cleric</option>
<option value="31">Runemaster</option>
<option value="32">Primalist</option>
</>
)}
{selectedRealm === "wildcard" && (
<option value="10">Hero (Freepick)</option>
)}
{selectedRealm === "reborn" && (
<>
<option value="1">Warrior</option>
<option value="2">Paladin</option>
<option value="3">Hunter</option>
<option value="4">Rogue</option>
<option value="5">Priest</option>
<option value="6">Death Knight</option>
<option value="7">Shaman</option>
<option value="8">Mage</option>
<option value="9">Warlock</option>
<option value="11">Druid</option>
</>
)}
</select>
</div>
{/* Role Filter */}
<div>
<label className="text-xs text-muted">Combat Role</label>
<select
value={selectedRole}
onChange={(e) => setSelectedRole(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"
>
<option value="all">All Roles</option>
<option value="tank">Tank</option>
<option value="healer">Healer</option>
<option value="melee">Melee DPS</option>
<option value="ranged">Ranged Physical DPS</option>
<option value="caster">Caster DPS</option>
</select>
</div>
{/* Archetype Filter */}
<div>
<label className="text-xs text-muted">Archetype / Build</label>
<select
value={selectedArchetype}
onChange={(e) => setSelectedArchetype(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"
>
<option value="all">Auto / Integral Archetype</option>
{selectedRealm === "wildcard" && (
<>
{wildcardArchetypes.map((b) => (
<option key={b.id} value={b.id}>
{b.name} ({formatRole(b.roles)}) [{formatStat(b.primary_stat)}]
</option>
))}
</>
)}
{selectedRealm === "reborn" && (
<>
<option value="spiritguard">Spirit Guard Shaman (Tank)</option>
<option value="darkapoth">Dark Apotheosis Warlock (Tank)</option>
<option value="guardianbear">Guardian Bear Druid (Tank)</option>
<option value="protpal">Protection Paladin (Tank)</option>
<option value="protwar">Protection Warrior (Tank)</option>
<option value="holypriest">Holy Priest (Healer)</option>
<option value="restodruid">Restoration Druid / Shaman</option>
</>
)}
{selectedRealm === "coa" && (
<option value="class_spec">Class Mastery Specialization</option>
)}
</select>
</div>
</div>
{/* Deployment Actions */}
<div className="flex flex-wrap items-center gap-3 pt-2">
<Button
variant="primary"
disabled={busy || !valid || job !== null || !isRealmOperational}
onClick={() => void handleSpawn()}
>
{busy && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
{spawnMode === "fleet"
? `Spawn Level ${targetLevel} Fleet`
: `Deploy ${valid ? count : ""} Bots`}
</Button>
{running && pop && pop.bots_total > pop.bots_online && (
<Button
variant="secondary"
disabled={busy || job !== null || !isRealmOperational}
onClick={() => void handleLoginAll()}
title="Bring all created bots online"
>
<Power className="h-4 w-4 mr-1.5 text-ok" />
Bring All Online ({pop.bots_total - pop.bots_online} idle)
</Button>
)}
{!running && (
<span className="text-xs text-muted">
Server stopped: bots will be created directly in DB or queued for startup.
</span>
)}
</div>
{/* Progress Bar during active spawn */}
{job && (
<div className="rounded-lg border border-line bg-bg/40 p-4 space-y-2">
<div className="flex justify-between text-sm">
<span className="font-medium">
Creating bots: {done} / {job.target}
</span>
<span className="text-gold font-bold">
{Math.round((done / job.target) * 100)}%
</span>
</div>
<div className="h-2 overflow-hidden rounded-full bg-white/10">
<div
className="h-full rounded-full bg-gold transition-[width] duration-300"
style={{ width: `${(done / job.target) * 100}%` }}
/>
</div>
<div className="flex justify-between items-center pt-1">
<span className="text-xs text-muted">
Paced creation prevents server stalls and guarantees full talent/gear setup.
</span>
<Button size="sm" variant="ghost" disabled={busy} onClick={() => void stopCreating()}>
Cancel Queue
</Button>
</div>
</div>
)}
{note && !job && (
<p className="text-sm text-ok flex items-center gap-1.5">
<CheckCircle2 className="h-4 w-4 shrink-0" />
{note}
</p>
)}
</div>
{/* Online Fleet Management (Despawn, Purge) */}
{running && pop && pop.bots_total > 0 && isViewingActiveRealm && (
<div className="border-t border-line pt-5 space-y-3">
<h3 className="font-semibold text-sm tracking-wide uppercase text-muted">
Online Fleet Management
</h3>
<div className="flex flex-wrap items-center gap-3 text-sm">
<label htmlFor="despawn-n" className="text-muted text-xs">
Despawn Batch:
</label>
<input
id="despawn-n"
value={despawnN}
onChange={(e) => 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"
/>
<Button size="sm" variant="secondary" disabled={busy || !dnValid} onClick={() => void despawnSome()}>
{t("comp.despawnSome", { n: dnValid ? dn : "…" })}
<Button
size="sm"
variant="secondary"
disabled={busy || !dnValid}
onClick={() => void despawnSome()}
>
Despawn {dnValid ? dn : "…"} Bots
</Button>
</div>
<p className="mt-1 text-xs text-muted">{t("comp.despawnHint")}</p>
<div className="mt-3 flex flex-wrap gap-2">
<Button size="sm" variant="secondary" disabled={busy} onClick={takeOffline}>
{t("comp.offline")}
Take All Offline
</Button>
<Button size="sm" variant="ghost" className="text-bad hover:text-bad" disabled={busy} onClick={deleteAll}>
{t("comp.delete")}
<Button
size="sm"
variant="ghost"
className="text-bad hover:text-bad ml-auto"
disabled={busy}
onClick={deleteAll}
>
Purge Entire Fleet ({pop.bots_total})
</Button>
</div>
</div>
)}
<div className="mt-5 border-t border-line pt-4">
<h3 className="text-sm font-semibold">{t("comp.startTitle")}</h3>
<label className="mt-2 flex cursor-pointer items-center gap-2 text-sm">
<input type="checkbox" checked={autoOn} onChange={(e) => setAutoOn(e.target.checked)} />
{t("comp.startAuto")}
</label>
<div className="mt-2 flex flex-wrap items-center gap-2 text-sm">
<label htmlFor="start-max" className="text-muted">{t("comp.startCount")}</label>
<input
id="start-max"
value={autoMax}
onChange={(e) => 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"
/>
<Button size="sm" variant="secondary" disabled={startBusy || (autoOn && !maxValid)} onClick={() => void saveStart()}>
{t("comp.startSave")}
</Button>
{/* Startup Auto-Login Configuration */}
<div className="border-t border-line pt-5 space-y-3">
<h3 className="font-semibold text-sm tracking-wide uppercase text-muted">
Persistent Startup Fleet
</h3>
<p className="text-xs text-muted">
Configure how many bots automatically log into the world whenever the server launches.
</p>
<div className="flex flex-wrap items-center gap-4 text-sm">
<label className="flex cursor-pointer items-center gap-2">
<input
type="checkbox"
checked={autoOn}
onChange={(e) => setAutoOn(e.target.checked)}
className="rounded border-line text-gold focus:ring-gold"
/>
<span>Enable Auto-Login on Server Startup</span>
</label>
<div className="flex items-center gap-2">
<label htmlFor="start-max" className="text-xs text-muted">
Startup Limit:
</label>
<input
id="start-max"
value={autoMax}
onChange={(e) => 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"
/>
<Button
size="sm"
variant="secondary"
disabled={startBusy || (autoOn && !maxValid)}
onClick={() => void saveStart()}
>
Save Setting
</Button>
</div>
</div>
{autoOn && !maxValid && autoMax !== "" && <p className="mt-1 text-xs text-warn">{t("comp.startInvalid")}</p>}
<p className="mt-1 text-xs text-muted">{t("comp.startHint")}</p>
{startNote && <p className="mt-2 text-sm text-ok" role="status">{startNote}</p>}
{startNote && <p className="text-xs text-ok">{startNote}</p>}
</div>
{error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
{error && (
<div className="rounded-md border border-bad/40 bg-bad/10 p-3 text-sm text-bad flex items-center gap-2">
<AlertCircle className="h-4 w-4 shrink-0" />
<span>{error.human.code === "unknown" ? error.technical : human(error.human).message}</span>
</div>
)}
</Card>
);
}