mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 03:25:56 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6723a7eda1 | ||
|
|
b65b632c63 |
No files matched your search
@@ -69,6 +69,8 @@ jobs:
|
||||
with:
|
||||
node-version: 22
|
||||
- run: npm ci
|
||||
# tauri::generate_context! needs ../dist; without a warm target cache the tests do not compile without it.
|
||||
- run: npm run build
|
||||
- name: Tests
|
||||
run: cargo test --workspace --locked -- --test-threads=1
|
||||
- run: node --experimental-strip-types --test tools/*.test.mjs
|
||||
|
||||
Generated
-1
@@ -787,7 +787,6 @@ dependencies = [
|
||||
"tauri-plugin-single-instance",
|
||||
"tauri-plugin-updater",
|
||||
"tracing",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -1332,7 +1332,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_detect_toolchain() {
|
||||
let tc = detect_toolchain_for(Some(Path::new("C:/games/coa-work/plugin-spike/server-v03")));
|
||||
let realm = Path::new("C:/games/coa-work/plugin-spike/server-v03");
|
||||
if !realm.join("worldserver.exe").is_file() {
|
||||
return; // needs the local spike realm and its SDK (not on CI runners)
|
||||
}
|
||||
let tc = detect_toolchain_for(Some(realm));
|
||||
assert!(tc.msvc_available, "MSVC vcvars64.bat should be detected");
|
||||
assert!(tc.cmake_available, "CMake should be detected");
|
||||
assert!(tc.ninja_available, "Ninja should be detected");
|
||||
|
||||
@@ -3,13 +3,10 @@
|
||||
//! small set (one per CoA class); older or imported servers can have it added on request.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
|
||||
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.
|
||||
@@ -22,46 +19,37 @@ 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.
|
||||
/// Number of characters the bot module could use as templates (level 80, a CoA class, not account 1).
|
||||
pub fn template_count(db: &Db) -> Result<u32> {
|
||||
template_count_for_schema(db, "acore_characters")
|
||||
}
|
||||
|
||||
pub fn template_count_for_schema(db: &Db, chars_db: &str) -> Result<u32> {
|
||||
let n = db.query(&format!("SELECT COUNT(*) FROM {chars_db}.characters WHERE account<>1 AND level>=80;"))?;
|
||||
let n = db.query("SELECT COUNT(*) FROM acore_characters.characters WHERE account<>1 AND level>=80 AND class BETWEEN 12 AND 32;")?;
|
||||
Ok(n.trim().parse().unwrap_or(0))
|
||||
}
|
||||
|
||||
fn run_seed(db: &Db, chars_db: &str, base_guid: &str) -> Result<()> {
|
||||
fn run_seed(db: &Db, 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(chars_db, &file);
|
||||
let r = db.run_sql_file("acore_characters", &file);
|
||||
let _ = fs::remove_file(&file);
|
||||
r
|
||||
}
|
||||
|
||||
/// Fresh databases (release tooling): the original guids.
|
||||
pub fn seed_fresh(db: &Db) -> Result<()> {
|
||||
run_seed(db, "acore_characters", "0")
|
||||
run_seed(db, "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<bool> {
|
||||
ensure_templates_for_schema(db, "acore_characters")
|
||||
}
|
||||
|
||||
pub fn ensure_templates_for_schema(db: &Db, chars_db: &str) -> Result<bool> {
|
||||
if template_count_for_schema(db, chars_db)? > 0 {
|
||||
if template_count(db)? > 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
run_seed(
|
||||
db,
|
||||
chars_db,
|
||||
&format!("(SELECT IFNULL(MAX(guid),0) FROM {chars_db}.characters) + 100000"),
|
||||
"(SELECT IFNULL(MAX(guid),0) FROM acore_characters.characters) + 100000",
|
||||
)?;
|
||||
Ok(true)
|
||||
}
|
||||
@@ -137,168 +125,6 @@ pub fn offline_create(root: &Path, log: &Path, count: u32) -> Result<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<Vec<WildcardArchetypeDto>> {
|
||||
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<u8>,
|
||||
pub class_id: Option<u8>,
|
||||
pub spec_id: Option<u32>,
|
||||
pub build_id: Option<String>,
|
||||
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<String>,
|
||||
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<Option<CompanionsPendingJob>> {
|
||||
let p = pending_job_path(meta_dir, realm);
|
||||
if !p.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
match fsx::read_json::<CompanionsPendingJob>(&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::*;
|
||||
@@ -317,63 +143,4 @@ 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);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -49,19 +49,17 @@ fn parse_counts(out: &str) -> Result<Population> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Read-only query with the game's own database account. Routes automatically to the active realm's characters database.
|
||||
/// Read-only query with the game's own database account. Requires the database to be running.
|
||||
pub fn query(root: &Path) -> Result<Population> {
|
||||
let mode = crate::realms::state(root)
|
||||
.map(|s| s.active)
|
||||
.unwrap_or(crate::realms::Mode::Coa);
|
||||
query_for_realm(root, mode)
|
||||
let db = Db::from_repack(root, Account::App)?;
|
||||
query_with(
|
||||
&db,
|
||||
&bot_account_prefix(root),
|
||||
&crate::accounts::squid_bot_prefix(root),
|
||||
)
|
||||
}
|
||||
|
||||
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()))
|
||||
@@ -76,9 +74,9 @@ pub fn counts_sql_for_db(chars_db: &str, prefix: &str, squid_prefix: &str) -> Re
|
||||
let bots =
|
||||
format!("(UPPER(a.username) LIKE '{prefix}%' OR UPPER(a.username) LIKE '{squid_prefix}%')");
|
||||
Ok(format!(
|
||||
"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});"
|
||||
"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});"
|
||||
))
|
||||
}
|
||||
|
||||
@@ -87,21 +85,6 @@ 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,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -185,20 +185,8 @@ pub fn view(root: &Path) -> Result<View> {
|
||||
}
|
||||
|
||||
pub fn guard_module(root: &Path, id: &str) -> Result<()> {
|
||||
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(),
|
||||
));
|
||||
}
|
||||
}
|
||||
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()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -308,14 +296,20 @@ fn wildcard_configs(mut files: Files) -> Result<Files> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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")?;
|
||||
}
|
||||
}
|
||||
for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] {
|
||||
set(
|
||||
&mut files,
|
||||
"Core/configs/modules/mod_coa_playerbots.conf",
|
||||
key,
|
||||
value,
|
||||
)?;
|
||||
}
|
||||
set(
|
||||
&mut files,
|
||||
"Core/configs/modules/playerbots.conf",
|
||||
"AiPlayerbot.Enabled",
|
||||
"0",
|
||||
)?;
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
@@ -343,14 +337,20 @@ fn reborn_configs(mut files: Files) -> Result<Files> {
|
||||
set(&mut files, path, "RealmID", "3")?;
|
||||
}
|
||||
}
|
||||
// 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")?;
|
||||
}
|
||||
}
|
||||
for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] {
|
||||
set(
|
||||
&mut files,
|
||||
"Core/configs/modules/mod_coa_playerbots.conf",
|
||||
key,
|
||||
value,
|
||||
)?;
|
||||
}
|
||||
set(
|
||||
&mut files,
|
||||
"Core/configs/modules/playerbots.conf",
|
||||
"AiPlayerbot.Enabled",
|
||||
"0",
|
||||
)?;
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
@@ -805,7 +805,19 @@ pub fn before_start(root: &Path) -> Result<()> {
|
||||
"The installed server build does not support Wildcard.".into(),
|
||||
));
|
||||
}
|
||||
// Multi-realm Playerbots 1.0: bots are supported and enabled on all realms
|
||||
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())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -925,12 +937,11 @@ 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("1")
|
||||
Some("0")
|
||||
);
|
||||
write_configs(t.path(), &reborn).unwrap();
|
||||
write_configs(t.path(), &coa).unwrap();
|
||||
@@ -944,8 +955,8 @@ mod tests {
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(guard_module(t.path(), "companions").is_ok());
|
||||
assert!(guard_module(t.path(), "playerbots").is_ok());
|
||||
assert!(guard_module(t.path(), "companions").is_err());
|
||||
assert!(guard_module(t.path(), "playerbots").is_err());
|
||||
assert!(guard_module(t.path(), "content-scaling").is_ok());
|
||||
}
|
||||
|
||||
@@ -1167,10 +1178,6 @@ 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(),
|
||||
@@ -1181,7 +1188,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("1"));
|
||||
assert_eq!(c.get("CoaBots.Enable"), Some("0"));
|
||||
assert_eq!(
|
||||
ConfFile::parse_bytes(&w["Settings/worldserver.conf.template"])
|
||||
.unwrap()
|
||||
@@ -1253,8 +1260,14 @@ CoA.GameModeMask = 0
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(guard_module(t.path(), "companions").is_ok());
|
||||
assert!(guard_module(t.path(), "playerbots").is_ok());
|
||||
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(), "content-scaling").is_ok());
|
||||
}
|
||||
|
||||
|
||||
@@ -24,4 +24,3 @@ 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"] }
|
||||
+71
-199
@@ -630,34 +630,7 @@ async fn start_server(
|
||||
if coa_core::realms::guard_module(&r, "companions").is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
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");
|
||||
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;
|
||||
@@ -1776,7 +1749,6 @@ 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 || {
|
||||
@@ -1784,48 +1756,12 @@ async fn get_population(
|
||||
if o.mysql.state != coa_core::process::ServiceState::Running {
|
||||
return None;
|
||||
}
|
||||
if let Some(mode) = realm {
|
||||
coa_core::population::query_for_realm(&root, mode).ok()
|
||||
} else {
|
||||
coa_core::population::query(&root).ok()
|
||||
}
|
||||
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).
|
||||
@@ -1836,12 +1772,11 @@ 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_target(&root, realm)?.cancel_spawning()?,
|
||||
count: Ra::connect(&root)?.cancel_spawning()?,
|
||||
})
|
||||
})
|
||||
.await
|
||||
@@ -1851,12 +1786,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_target(&root, realm)?;
|
||||
let mut ra = Ra::connect(&root)?;
|
||||
// Anything still waiting to be created must not come back right after.
|
||||
let _ = ra.cancel_spawning();
|
||||
Ok(CompanionAction {
|
||||
count: ra.despawn_all()?,
|
||||
@@ -1865,12 +1800,13 @@ 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)?;
|
||||
@@ -1878,18 +1814,13 @@ 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 {}.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
|
||||
"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};"
|
||||
))?;
|
||||
let guids: Vec<u64> = rows.lines().filter_map(|l| l.trim().parse().ok()).collect();
|
||||
let mut ra = Ra::connect_target(&root, Some(mode))?;
|
||||
let mut ra = Ra::connect(&root)?;
|
||||
let mut done = 0;
|
||||
for g in guids {
|
||||
if ra.despawn_bot(g).unwrap_or(false) {
|
||||
@@ -1901,35 +1832,31 @@ 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(format!("before deleting all {} companions", target.realm.label())),
|
||||
Some("before deleting all companions".into()),
|
||||
&|step| {
|
||||
let _ = app.emit("backup-progress", step);
|
||||
},
|
||||
)?;
|
||||
let before = coa_core::population::query_for_realm(&root, mode)
|
||||
let before = coa_core::population::query(&root)
|
||||
.map(|p| p.bots_total)
|
||||
.unwrap_or(0);
|
||||
let mut ra = Ra::connect_target(&root, Some(mode))?;
|
||||
let mut ra = Ra::connect(&root)?;
|
||||
let _ = ra.cancel_spawning();
|
||||
ra.purge_all()?;
|
||||
Ok(CompanionAction { count: before })
|
||||
@@ -1985,11 +1912,6 @@ 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)?;
|
||||
@@ -1999,15 +1921,11 @@ async fn add_companions(
|
||||
"Choose between 1 and 2000 companions.".into(),
|
||||
));
|
||||
}
|
||||
let mode = realm.unwrap_or_else(|| {
|
||||
coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default()
|
||||
});
|
||||
let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?;
|
||||
let meta = meta_dir(&root)?;
|
||||
let mut changes = BTreeMap::new();
|
||||
changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true));
|
||||
let existing_max = config::load(&target.world_root, Scope::Bots)
|
||||
.or_else(|_| config::load(&root, Scope::Bots))
|
||||
// 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
|
||||
@@ -2016,58 +1934,68 @@ async fn add_companions(
|
||||
.and_then(|s| s.value.as_u64())
|
||||
})
|
||||
.unwrap_or(0) as u32;
|
||||
let already = coa_core::population::query_for_realm(&root, mode)
|
||||
let already = coa_core::population::query(&root)
|
||||
.map(|p| p.bots_total)
|
||||
.unwrap_or(0);
|
||||
changes.insert(
|
||||
"CoaBots.AutoLogin.MaxCount".to_string(),
|
||||
Value::from(existing_max.max(already + count).min(5000)),
|
||||
);
|
||||
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 {
|
||||
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);
|
||||
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()));
|
||||
}
|
||||
}
|
||||
baseline = coa_core::population::query_for_realm(&root, mode)
|
||||
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,
|
||||
});
|
||||
}
|
||||
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)
|
||||
.ok()
|
||||
.map(|p| p.bots_total);
|
||||
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)?)
|
||||
}
|
||||
Some(Ra::connect(&root)?.spawn_bots(count)?)
|
||||
} else {
|
||||
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 }),
|
||||
);
|
||||
}
|
||||
// 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 }),
|
||||
)?;
|
||||
None
|
||||
};
|
||||
tracing::info!(count, spawned = spawned.is_some(), "companions requested");
|
||||
@@ -2080,27 +2008,6 @@ 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 {
|
||||
@@ -3074,27 +2981,6 @@ async fn preview_install_msvc(
|
||||
blocking(move || coa_core::msvc_setup::install_build_tools(realm_root.as_deref())).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn preview_register_test_realm(
|
||||
state: State<'_, AppState>,
|
||||
path: Option<String>,
|
||||
) -> std::result::Result<ServerSummary, UiError> {
|
||||
let target = path
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(r"C:\games\coa-work\plugin-spike\server-v03"));
|
||||
|
||||
if !target.join("worldserver.exe").is_file() && !target.join("Core/worldserver.exe").is_file() {
|
||||
return Err(UiError::from(coa_core::Error::Invalid(format!(
|
||||
"Target path '{}' does not contain a valid worldserver.exe",
|
||||
target.display()
|
||||
))));
|
||||
}
|
||||
|
||||
let id = "test-realm-v03".to_string();
|
||||
state.registry.register(&id, &target)?;
|
||||
Ok(summary(id, target))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn preview_build_module(
|
||||
app: AppHandle,
|
||||
@@ -3494,7 +3380,6 @@ pub fn run() {
|
||||
release_history,
|
||||
preview_toolchain_status,
|
||||
preview_install_msvc,
|
||||
preview_register_test_realm,
|
||||
preview_build_module,
|
||||
preview_install_module,
|
||||
preview_toggle_module,
|
||||
@@ -3577,13 +3462,10 @@ 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,
|
||||
@@ -3675,22 +3557,12 @@ pub fn run() {
|
||||
let portable = start_portable(&dir);
|
||||
let (control, host_control) = control_cmds::start(&dir, portable.clone());
|
||||
let registry = Registry::at(dir.join("installs.json"));
|
||||
// Development only: an explicitly named test realm is registered into an empty list.
|
||||
if registry.list().map(|l| l.is_empty()).unwrap_or(true) {
|
||||
let test_realm_path = std::env::var("COA_TEST_REALM_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|_| PathBuf::from(r"C:\games\CoA Server Preview"));
|
||||
let target_realm = if test_realm_path.join("worldserver.exe").is_file() {
|
||||
Some(("preview-realm", test_realm_path))
|
||||
} else {
|
||||
let spike_path = PathBuf::from(r"C:\games\coa-work\plugin-spike\server-v03");
|
||||
if spike_path.join("worldserver.exe").is_file() {
|
||||
Some(("test-realm-v03", spike_path))
|
||||
} else {
|
||||
None
|
||||
if let Ok(path) = std::env::var("COA_TEST_REALM_DIR").map(PathBuf::from) {
|
||||
if path.join("worldserver.exe").is_file() {
|
||||
let _ = registry.register("preview-realm", &path);
|
||||
}
|
||||
};
|
||||
if let Some((name, path)) = target_realm {
|
||||
let _ = registry.register(name, &path);
|
||||
}
|
||||
}
|
||||
app.manage(AppState {
|
||||
|
||||
+6
-37
@@ -528,16 +528,6 @@ 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;
|
||||
@@ -822,35 +812,15 @@ export const api = {
|
||||
invoke<{ txn: UpdateTxn; preexisting_character_count?: number; modules?: ModuleRebuild[] }>("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, 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 }),
|
||||
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 }),
|
||||
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,
|
||||
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 }),
|
||||
addCompanions: (id: string, count: number) => invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count }),
|
||||
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 }),
|
||||
@@ -889,7 +859,6 @@ export const api = {
|
||||
invoke<{ ready: boolean; restart_required: boolean; message: string; toolchain: ToolchainStatus }>("preview_install_msvc", { realmId: realmId ?? null }),
|
||||
previewToolchainStatus: (realmId?: string) =>
|
||||
invoke<ToolchainStatus>("preview_toolchain_status", { realmId: realmId ?? null }),
|
||||
previewRegisterTestRealm: (path?: string) => invoke<ServerSummary>("preview_register_test_realm", { path: path ?? null }),
|
||||
previewBuildModule: (realmId: string, sourceUrlOrPath: string) =>
|
||||
invoke<BuildResult>("preview_build_module", { realmId, sourceUrlOrPath }),
|
||||
previewInstallModule: (realmId: string, moduleId: string, version: string, applySql: boolean) =>
|
||||
|
||||
+159
-712
@@ -1,125 +1,30 @@
|
||||
import { useEffect, useState } from "react";
|
||||
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 { Loader2 } from "lucide-react";
|
||||
import { api, asUiError, type CompanionSizes, type Population, type UiError } 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";
|
||||
}
|
||||
}
|
||||
import { hasKey, useHuman, useT, type Key } from "@/i18n";
|
||||
|
||||
export function CompanionsCard({ serverId }: { serverId: string }) {
|
||||
const t = useT();
|
||||
const human = useHuman();
|
||||
|
||||
// Realm & Environment state
|
||||
const [profiles, setProfiles] = useState<RealmProfiles | null>(null);
|
||||
const [selectedRealm, setSelectedRealm] = useState<RealmMode>("coa");
|
||||
const [sizes, setSizes] = useState<CompanionSizes | null>(null);
|
||||
const [pop, setPop] = useState<Population | null>(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
|
||||
// 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 [choice, setChoice] = useState<string>("small");
|
||||
const [custom, setCustom] = useState("100");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<UiError | null>(null);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const [job, setJob] = useState<{ baseline: number; target: number; since: number } | null>(null);
|
||||
|
||||
// Startup Auto-Login settings
|
||||
// Start-up login: how many existing bots the server brings online by itself every time it starts.
|
||||
const [autoOn, setAutoOn] = useState(true);
|
||||
const [autoMax, setAutoMax] = useState("");
|
||||
// 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")
|
||||
@@ -135,46 +40,6 @@ 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);
|
||||
@@ -187,128 +52,45 @@ 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, selectedRealm);
|
||||
const r = await api.stopSpawning(serverId);
|
||||
setJob(null);
|
||||
await fetchPopulation();
|
||||
return t("comp.stopped", { n: r.count });
|
||||
});
|
||||
|
||||
// Take online bots offline
|
||||
const takeOffline = () => {
|
||||
if (!window.confirm(t("comp.offlineConfirm"))) return;
|
||||
void act(async () => {
|
||||
const r = await api.takeOffline(serverId, selectedRealm);
|
||||
const r = await api.takeOffline(serverId);
|
||||
setJob(null);
|
||||
await fetchPopulation();
|
||||
return t("comp.offlineDone2", { n: r.count });
|
||||
});
|
||||
};
|
||||
|
||||
// Despawn batch
|
||||
const dn = Number(despawnN);
|
||||
const dnValid = Number.isInteger(dn) && dn >= 1 && dn <= 5000;
|
||||
const despawnSome = () =>
|
||||
act(async () => {
|
||||
const r = await api.despawnSome(serverId, dn, selectedRealm);
|
||||
await fetchPopulation();
|
||||
const r = await api.despawnSome(serverId, dn);
|
||||
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, selectedRealm);
|
||||
await api.deleteAllCompanions(serverId);
|
||||
setJob(null);
|
||||
await fetchPopulation();
|
||||
return t("comp.deleteDone");
|
||||
});
|
||||
};
|
||||
|
||||
// Switch server realm
|
||||
const switchServerRealm = async (mode: RealmMode) => {
|
||||
if (!window.confirm(`Switch server active realm to ${mode.toUpperCase()} and restart?`)) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.realmSelect(serverId, mode, true);
|
||||
await loadProfiles();
|
||||
setSelectedRealm(mode);
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Save auto startup settings
|
||||
async function saveStart() {
|
||||
setStartBusy(true);
|
||||
setError(null);
|
||||
setStartNote(null);
|
||||
try {
|
||||
await api.save(serverId, "bots", {
|
||||
"CoaBots.AutoLoginOnStartup": autoOn,
|
||||
"CoaBots.AutoLogin.MaxCount": maxNum,
|
||||
});
|
||||
await api.save(serverId, "bots", { "CoaBots.AutoLoginOnStartup": autoOn, "CoaBots.AutoLogin.MaxCount": maxNum });
|
||||
setStartNote(t("comp.startSaved"));
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
@@ -317,516 +99,181 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
|
||||
}
|
||||
}
|
||||
|
||||
// Database schema name for selected realm
|
||||
const dbSchema =
|
||||
selectedRealm === "coa"
|
||||
? "acore_characters"
|
||||
: selectedRealm === "wildcard"
|
||||
? "acore_characters_wildcard"
|
||||
: "acore_characters_reborn";
|
||||
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
|
||||
|
||||
// Binary compatibility check
|
||||
const isBinaryCompatible =
|
||||
selectedRealm === "coa" ||
|
||||
(selectedRealm === "wildcard" && (profiles?.supported ?? true)) ||
|
||||
(selectedRealm === "reborn" && (profiles?.reborn_supported ?? true));
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<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>
|
||||
<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>
|
||||
|
||||
{/* 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>
|
||||
);
|
||||
})}
|
||||
<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" />
|
||||
)}
|
||||
</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>}
|
||||
</div>
|
||||
|
||||
{/* 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>
|
||||
{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" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 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()}
|
||||
{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")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{note && !job && <p className="mt-3 text-sm text-ok" role="status">{note}</p>}
|
||||
|
||||
{/* 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>
|
||||
{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>
|
||||
<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-2.5 py-1 text-right text-sm outline-none focus:border-gold"
|
||||
className="w-20 rounded-md border border-line bg-bg px-3 py-1.5 text-right outline-none focus:border-gold"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
disabled={busy || !dnValid}
|
||||
onClick={() => void despawnSome()}
|
||||
>
|
||||
Despawn {dnValid ? dn : "…"} Bots
|
||||
<Button size="sm" variant="secondary" disabled={busy || !dnValid} onClick={() => void despawnSome()}>
|
||||
{t("comp.despawnSome", { n: dnValid ? dn : "…" })}
|
||||
</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}>
|
||||
Take All Offline
|
||||
{t("comp.offline")}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-bad hover:text-bad ml-auto"
|
||||
disabled={busy}
|
||||
onClick={deleteAll}
|
||||
>
|
||||
Purge Entire Fleet ({pop.bots_total})
|
||||
<Button size="sm" variant="ghost" className="text-bad hover:text-bad" disabled={busy} onClick={deleteAll}>
|
||||
{t("comp.delete")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 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 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>
|
||||
</div>
|
||||
{startNote && <p className="text-xs text-ok">{startNote}</p>}
|
||||
{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>}
|
||||
</div>
|
||||
|
||||
{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>
|
||||
)}
|
||||
{error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
Download,
|
||||
ExternalLink,
|
||||
Flame,
|
||||
FolderPlus,
|
||||
Gavel,
|
||||
GitFork,
|
||||
Hammer,
|
||||
@@ -791,25 +790,6 @@ export function ModulesPage({
|
||||
}
|
||||
}
|
||||
|
||||
async function registerTestRealm() {
|
||||
setActionInProgress("register-realm");
|
||||
setError(null);
|
||||
try {
|
||||
await api.previewRegisterTestRealm();
|
||||
setNotification(
|
||||
locale === "ru"
|
||||
? "Экспериментальный тестовый реалм server-v03 успешно зарегистрирован!"
|
||||
: "Experimental server-v03 test realm registered successfully!"
|
||||
);
|
||||
onChanged?.();
|
||||
await load();
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
} finally {
|
||||
setActionInProgress(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function exportDiagnostics() {
|
||||
setActionInProgress("export-diag");
|
||||
try {
|
||||
@@ -1201,17 +1181,6 @@ export function ModulesPage({
|
||||
<Download className="mr-1.5 h-3.5 w-3.5" />
|
||||
{locale === "ru" ? "Экспорт отчёта" : "Export Diagnostics"}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={registerTestRealm}
|
||||
disabled={actionInProgress === "register-realm"}
|
||||
className="text-xs text-gold hover:text-gold"
|
||||
>
|
||||
<FolderPlus className="mr-1.5 h-3.5 w-3.5" />
|
||||
{locale === "ru" ? "Подключить test-realm-v03" : "Register test-realm-v03"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
Reference in new issue
Block a user