Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0940e9cf28 | ||
|
|
ab0bdbe3e9 | ||
|
|
313d3e1c08 | ||
|
|
8686990a30 | ||
|
|
dd066f2094 | ||
|
|
5bbe5adff1 | ||
|
|
79846186ea |
No files matched your search
@@ -347,7 +347,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-core"
|
name = "coa-core"
|
||||||
version = "0.1.6"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"chrono",
|
"chrono",
|
||||||
@@ -375,7 +375,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-release"
|
name = "coa-release"
|
||||||
version = "0.1.6"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chrono",
|
"chrono",
|
||||||
"coa-core",
|
"coa-core",
|
||||||
@@ -384,7 +384,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-server-manager"
|
name = "coa-server-manager"
|
||||||
version = "0.1.6"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"coa-core",
|
"coa-core",
|
||||||
"serde",
|
"serde",
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ resolver = "2"
|
|||||||
members = ["crates/coa-core", "crates/coa-release", "src-tauri"]
|
members = ["crates/coa-core", "crates/coa-release", "src-tauri"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.6"
|
version = "0.2.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "AGPL-3.0-only"
|
license = "AGPL-3.0-only"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
//! Adds the template characters to a scratch install and creates companions offline. usage: companions_e2e <install folder> <count>
|
||||||
|
//! The folder name must contain "installtest" and its database must already be running (Scripts/manage.py start-mysql).
|
||||||
|
use coa_core::db::{Account, Db};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let root = std::path::PathBuf::from(&a[0]);
|
||||||
|
assert!(a[0].to_lowercase().contains("installtest"), "refusing to touch a server that is not a disposable test install");
|
||||||
|
let count: u32 = a[1].parse().unwrap();
|
||||||
|
let db = Db::from_repack(&root, Account::Admin).expect("db");
|
||||||
|
println!("templates before: {}", coa_core::companions::template_count(&db).unwrap());
|
||||||
|
println!("added: {}", coa_core::companions::ensure_templates(&db).unwrap());
|
||||||
|
println!("templates after: {}", coa_core::companions::template_count(&db).unwrap());
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
match coa_core::companions::offline_create(&root, &root.join("companions-e2e.log"), count) {
|
||||||
|
Ok(tail) => println!("offline create ok in {:?}:\n{tail}", t.elapsed()),
|
||||||
|
Err(e) => println!("offline create FAILED: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
//! Check and apply a real published update on a DISPOSABLE install. usage: update_url <install folder> <update url>
|
||||||
|
//! The folder name must contain "installtest"; ports must already point away from any running server.
|
||||||
|
use coa_core::download::Cancel;
|
||||||
|
use coa_core::pkgsource::Source;
|
||||||
|
use coa_core::registry::{metadata_dir_for, MetaDir};
|
||||||
|
use coa_core::update::{apply, preview, Params, RepackEnv};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let root = std::path::PathBuf::from(&a[0]);
|
||||||
|
assert!(a[0].to_lowercase().contains("installtest"), "refusing: not a disposable test install");
|
||||||
|
let dir = metadata_dir_for(&root).unwrap();
|
||||||
|
let (_, meta) = MetaDir::open(&dir).unwrap();
|
||||||
|
let src = Source::Url(a[1].clone());
|
||||||
|
let p = preview(&root, &meta, &src, coa_core::signing::EMBEDDED_PUBLIC_KEY, &Default::default()).unwrap_or_else(|e| panic!("preview failed: {e:?}"));
|
||||||
|
println!("preview: {} -> {} | download {} bytes | {} files change | {} migrations | conflicts {:?}", p.from_version.clone().unwrap_or_default(), p.to_version, p.download_bytes, p.items.iter().filter(|i| format!("{:?}", i.action) != "Skip").count(), p.migrations, p.conflicts);
|
||||||
|
let env = RepackEnv { root: &root, meta_dir: &dir };
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let out = apply(
|
||||||
|
&Params { root: &root, meta_dir: &dir, source: src, trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY, cancel: Cancel::default(), resolutions: Default::default(), env: &env, fail_after_ops: None },
|
||||||
|
&|s, pct| eprintln!(" {pct:>3}% {s}"),
|
||||||
|
)
|
||||||
|
.unwrap_or_else(|e| panic!("apply failed: {e:?}"));
|
||||||
|
println!("apply finished in {:?}: state {:?}, to {:?}", t.elapsed(), out.txn.state, out.txn.to_version);
|
||||||
|
}
|
||||||
@@ -86,9 +86,41 @@ pub fn restore_quiet_logging(settings: &Path) -> Result<()> {
|
|||||||
fs::remove_file(&original)?;
|
fs::remove_file(&original)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let world = settings.join("worldserver.conf.template");
|
||||||
|
if world.is_file() {
|
||||||
|
let bytes = fs::read(&world)?;
|
||||||
|
let patched = quiet_world_logging(&String::from_utf8_lossy(&bytes));
|
||||||
|
if patched.as_bytes() != bytes.as_slice() {
|
||||||
|
fs::write(&world, patched)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The network logger at debug level writes a line for every packet the world sends (hundreds of thousands per hour
|
||||||
|
/// with creatures fighting); keep it to errors. CoA's own logger defaults to errors only unless `Logger.coa` exists.
|
||||||
|
pub fn quiet_world_logging(text: &str) -> String {
|
||||||
|
let nl = if text.contains("\r\n") { "\r\n" } else { "\n" };
|
||||||
|
let mut out: Vec<String> = Vec::new();
|
||||||
|
let has_coa = text.lines().any(|l| l.trim_start().starts_with("Logger.coa="));
|
||||||
|
for line in text.lines() {
|
||||||
|
let l = line.trim();
|
||||||
|
if l.starts_with("Logger.network=") {
|
||||||
|
out.push("Logger.network=2,Server".to_string());
|
||||||
|
} else {
|
||||||
|
out.push(line.to_string());
|
||||||
|
}
|
||||||
|
if l.starts_with("Logger.root=") && !has_coa {
|
||||||
|
out.push("Logger.coa=4,Console Server".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut s = out.join(nl);
|
||||||
|
if text.ends_with('\n') {
|
||||||
|
s.push_str(nl);
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
pub fn build(p: &Params, say: &dyn Fn(&str)) -> Result<()> {
|
pub fn build(p: &Params, say: &dyn Fn(&str)) -> Result<()> {
|
||||||
if p.out.exists() {
|
if p.out.exists() {
|
||||||
return Err(Error::Invalid(format!("{} already exists; choose a new folder.", p.out.display())));
|
return Err(Error::Invalid(format!("{} already exists; choose a new folder.", p.out.display())));
|
||||||
@@ -268,11 +300,20 @@ mod tests {
|
|||||||
fs::write(d.path().join("worldserver.conf.template.original"), "Logger.root=2,Console Server").unwrap();
|
fs::write(d.path().join("worldserver.conf.template.original"), "Logger.root=2,Console Server").unwrap();
|
||||||
fs::write(d.path().join("authserver.conf.template"), "unchanged").unwrap();
|
fs::write(d.path().join("authserver.conf.template"), "unchanged").unwrap();
|
||||||
restore_quiet_logging(d.path()).unwrap();
|
restore_quiet_logging(d.path()).unwrap();
|
||||||
assert_eq!(fs::read_to_string(d.path().join("worldserver.conf.template")).unwrap(), "Logger.root=2,Console Server");
|
let restored = fs::read_to_string(d.path().join("worldserver.conf.template")).unwrap();
|
||||||
|
assert!(restored.starts_with("Logger.root=2,Console Server") && !restored.contains("Logger.root=6"), "{restored}");
|
||||||
assert!(!d.path().join("worldserver.conf.template.original").exists());
|
assert!(!d.path().join("worldserver.conf.template.original").exists());
|
||||||
assert_eq!(fs::read_to_string(d.path().join("authserver.conf.template")).unwrap(), "unchanged");
|
assert_eq!(fs::read_to_string(d.path().join("authserver.conf.template")).unwrap(), "unchanged");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_world_template_gets_a_quiet_network_logger_and_a_coa_logger() {
|
||||||
|
let input = "Logger.root=2,Console Server\r\nLogger.network=5,Server\r\nOther = 1\r\n";
|
||||||
|
let out = quiet_world_logging(input);
|
||||||
|
assert_eq!(out, "Logger.root=2,Console Server\r\nLogger.coa=4,Console Server\r\nLogger.network=2,Server\r\nOther = 1\r\n");
|
||||||
|
assert_eq!(quiet_world_logging(&out), out, "idempotent");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn refuses_to_overwrite_an_existing_output_folder() {
|
fn refuses_to_overwrite_an_existing_output_folder() {
|
||||||
let d = tempfile::tempdir().unwrap();
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -48,8 +48,57 @@ pub fn ensure_templates(db: &Db) -> Result<bool> {
|
|||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn has_seed_file(_root: &Path) -> bool {
|
/// The bot module's offline factory ships with the server package; it creates fully equipped bots straight in the
|
||||||
!SQL.is_empty()
|
/// database while the world server is stopped (fast and safe for large batches).
|
||||||
|
pub const OFFLINE_FACTORY: &str = "Extras/CoABotTools/offline_bot_factory.py";
|
||||||
|
|
||||||
|
/// Batches at least this large are created offline when the server happens to be stopped.
|
||||||
|
pub const OFFLINE_MIN: u32 = 100;
|
||||||
|
|
||||||
|
pub fn offline_factory(root: &Path) -> Option<std::path::PathBuf> {
|
||||||
|
let p = root.join(OFFLINE_FACTORY);
|
||||||
|
(p.is_file() && root.join("Runtime/python/python.exe").is_file() && root.join("mysql/bin/mysql.exe").is_file() && root.join("mysql/admin-client.ini").is_file()).then_some(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the offline factory for `count` leveled bots. The database must be running and the world/auth servers stopped.
|
||||||
|
/// Returns the tail of its report. Credentials are passed as a file path only, never on the command line.
|
||||||
|
pub fn offline_create(root: &Path, log: &Path, count: u32) -> Result<String> {
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
let script = offline_factory(root).ok_or_else(|| crate::error::Error::Invalid("The offline bot factory is not part of this server.".into()))?;
|
||||||
|
if let Some(dir) = log.parent() {
|
||||||
|
fs::create_dir_all(dir)?;
|
||||||
|
}
|
||||||
|
let out = fs::File::create(log)?;
|
||||||
|
let err = out.try_clone()?;
|
||||||
|
let mut child = Command::new(root.join("Runtime/python/python.exe"))
|
||||||
|
.arg(&script)
|
||||||
|
.args(["--count", &count.to_string(), "--leveled", "--mysql-exe"])
|
||||||
|
.arg(root.join("mysql/bin/mysql.exe"))
|
||||||
|
.arg("--defaults-file")
|
||||||
|
.arg(root.join("mysql/admin-client.ini"))
|
||||||
|
.current_dir(root)
|
||||||
|
.stdin(Stdio::null())
|
||||||
|
.stdout(Stdio::from(out))
|
||||||
|
.stderr(Stdio::from(err))
|
||||||
|
.spawn()?;
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let status = loop {
|
||||||
|
if let Some(s) = child.try_wait()? {
|
||||||
|
break s;
|
||||||
|
}
|
||||||
|
if started.elapsed() > std::time::Duration::from_secs(45 * 60) {
|
||||||
|
let _ = child.kill();
|
||||||
|
return Err(crate::error::Error::Invalid("Creating the companions took too long and was stopped.".into()));
|
||||||
|
}
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(500));
|
||||||
|
};
|
||||||
|
let text = fs::read_to_string(log).unwrap_or_default();
|
||||||
|
let tail: Vec<&str> = text.lines().rev().take(6).collect::<Vec<_>>().into_iter().rev().collect();
|
||||||
|
if status.success() {
|
||||||
|
Ok(tail.join("\n"))
|
||||||
|
} else {
|
||||||
|
Err(crate::error::Error::Invalid(format!("The bot factory reported an error: {}", tail.join(" | "))))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ pub enum Error {
|
|||||||
NetworkUnreachable(String),
|
NetworkUnreachable(String),
|
||||||
#[error("the bot module found no level 80 template characters")]
|
#[error("the bot module found no level 80 template characters")]
|
||||||
CompanionTemplatesMissing,
|
CompanionTemplatesMissing,
|
||||||
|
#[error("this server's bot module does not have that command yet")]
|
||||||
|
CompanionCommandUnsupported,
|
||||||
#[error("invalid values: {}", .0.iter().map(|f| format!("{}: {}", f.key, f.message)).collect::<Vec<_>>().join("; "))]
|
#[error("invalid values: {}", .0.iter().map(|f| format!("{}: {}", f.key, f.message)).collect::<Vec<_>>().join("; "))]
|
||||||
Validation(Vec<FieldError>),
|
Validation(Vec<FieldError>),
|
||||||
}
|
}
|
||||||
@@ -55,6 +57,7 @@ pub enum ErrorCode {
|
|||||||
PackageNotPublished,
|
PackageNotPublished,
|
||||||
NetworkUnreachable,
|
NetworkUnreachable,
|
||||||
CompanionTemplatesMissing,
|
CompanionTemplatesMissing,
|
||||||
|
CompanionCommandUnsupported,
|
||||||
Unknown,
|
Unknown,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,6 +153,11 @@ impl ErrorCode {
|
|||||||
"New companions are copied from level 80 characters of each class. Create one level 80 character per class on any account except the console account, then try again.",
|
"New companions are copied from level 80 characters of each class. Create one level 80 character per class on any account except the console account, then try again.",
|
||||||
&[ShowDetails],
|
&[ShowDetails],
|
||||||
),
|
),
|
||||||
|
ErrorCode::CompanionCommandUnsupported => (
|
||||||
|
"This server version can not do that yet",
|
||||||
|
"The bot module of this server build has no such command. Update the server, or restart it to stop what is running.",
|
||||||
|
&[ShowDetails],
|
||||||
|
),
|
||||||
ErrorCode::Unknown => ("Something went wrong", "See the technical details.", &[ShowDetails]),
|
ErrorCode::Unknown => ("Something went wrong", "See the technical details.", &[ShowDetails]),
|
||||||
};
|
};
|
||||||
Human { code: self, title, message, actions }
|
Human { code: self, title, message, actions }
|
||||||
@@ -166,6 +174,7 @@ impl Error {
|
|||||||
Error::PackageNotPublished(_) => ErrorCode::PackageNotPublished,
|
Error::PackageNotPublished(_) => ErrorCode::PackageNotPublished,
|
||||||
Error::NetworkUnreachable(_) => ErrorCode::NetworkUnreachable,
|
Error::NetworkUnreachable(_) => ErrorCode::NetworkUnreachable,
|
||||||
Error::CompanionTemplatesMissing => ErrorCode::CompanionTemplatesMissing,
|
Error::CompanionTemplatesMissing => ErrorCode::CompanionTemplatesMissing,
|
||||||
|
Error::CompanionCommandUnsupported => ErrorCode::CompanionCommandUnsupported,
|
||||||
_ => ErrorCode::Unknown,
|
_ => ErrorCode::Unknown,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -97,6 +97,35 @@ impl Ra {
|
|||||||
Ok(parse_server_info(&out))
|
Ok(parse_server_info(&out))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn bot_command(&mut self, cmd: &str) -> Result<String> {
|
||||||
|
let out = self.command(cmd)?;
|
||||||
|
if is_unsupported_command(&out) {
|
||||||
|
return Err(Error::CompanionCommandUnsupported);
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop every bot still waiting to be created. Returns how many were waiting.
|
||||||
|
pub fn cancel_spawning(&mut self) -> Result<u32> {
|
||||||
|
Ok(first_number(&self.bot_command("botcmd spawncancel")?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Log every bot out without deleting anything. Returns how many were online.
|
||||||
|
pub fn despawn_all(&mut self) -> Result<u32> {
|
||||||
|
Ok(first_number(&self.bot_command("botcmd despawnall")?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Log one bot out (the character stays saved). False when that bot was not online.
|
||||||
|
pub fn despawn_bot(&mut self, guid: u64) -> Result<bool> {
|
||||||
|
Ok(self.bot_command(&format!("botcmd despawn {guid}"))?.to_lowercase().contains("despawned"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Log every bot out and delete every bot character for good (the caller saves a recovery point first).
|
||||||
|
pub fn purge_all(&mut self) -> Result<String> {
|
||||||
|
let out = self.bot_command("botcmd purgeall")?;
|
||||||
|
Ok(out.lines().last().unwrap_or("").to_string())
|
||||||
|
}
|
||||||
|
|
||||||
/// Ask the bot module to create `count` leveling bots (throttled by the module itself). Only a number is sent.
|
/// Ask the bot module to create `count` leveling bots (throttled by the module itself). Only a number is sent.
|
||||||
pub fn spawn_bots(&mut self, count: u32) -> Result<String> {
|
pub fn spawn_bots(&mut self, count: u32) -> Result<String> {
|
||||||
if !(1..=2000).contains(&count) {
|
if !(1..=2000).contains(&count) {
|
||||||
@@ -121,6 +150,16 @@ impl Ra {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The console answers an unknown sub-command with the list of the ones it knows.
|
||||||
|
fn is_unsupported_command(out: &str) -> bool {
|
||||||
|
let l = out.to_lowercase();
|
||||||
|
l.contains("possible subcommands") || l.contains("### usage") || l.contains("no such command") || l.contains("unknown command")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn first_number(text: &str) -> u32 {
|
||||||
|
text.split(|c: char| !c.is_ascii_digit()).find(|t| !t.is_empty()).and_then(|t| t.parse().ok()).unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
/// How fast the world loop is running, read from `server info`.
|
/// How fast the world loop is running, read from `server info`.
|
||||||
#[derive(Debug, Clone, Serialize, PartialEq)]
|
#[derive(Debug, Clone, Serialize, PartialEq)]
|
||||||
pub struct Performance {
|
pub struct Performance {
|
||||||
@@ -213,6 +252,16 @@ mod tests {
|
|||||||
(port, h)
|
(port, h)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unknown_bot_subcommand_is_recognised_and_numbers_are_read_from_replies() {
|
||||||
|
assert!(is_unsupported_command("### USAGE: .botcmd ...
|
||||||
|
Possible subcommands:
|
||||||
|
|- botcmd despawn"));
|
||||||
|
assert!(!is_unsupported_command("BotMgr: cancelled 35 queued bot spawn(s)."));
|
||||||
|
assert_eq!(first_number("BotMgr: cancelled 35 queued bot spawn(s)."), 35);
|
||||||
|
assert_eq!(first_number("nothing"), 0);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn server_info_timing_is_parsed_and_unrelated_text_is_ignored() {
|
fn server_info_timing_is_parsed_and_unrelated_text_is_ignored() {
|
||||||
let text = "AzerothCore rev. x
|
let text = "AzerothCore rev. x
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>CoA Server Manager</title>
|
<title>CoA Server Manager</title>
|
||||||
|
<link rel="icon" type="image/png" href="/src/assets/logo.png" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "coa-server-manager",
|
"name": "coa-server-manager",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.1.6",
|
"version": "0.2.0",
|
||||||
"license": "AGPL-3.0-only",
|
"license": "AGPL-3.0-only",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 6.3 KiB After Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 141 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 5.3 KiB After Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 7.1 KiB After Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 54 KiB |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 171 KiB |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 2.9 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 200 KiB |
|
Before Width: | Height: | Size: 2.1 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 3.6 KiB After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 4.5 KiB After Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 7.3 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 167 KiB |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 499 KiB |
|
Before Width: | Height: | Size: 3.6 KiB After Width: | Height: | Size: 1.7 MiB |
@@ -514,6 +514,78 @@ async fn get_population(state: State<'_, AppState>, id: String) -> std::result::
|
|||||||
.unwrap_or(None))
|
.unwrap_or(None))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct CompanionAction {
|
||||||
|
/// Bots affected (cancelled from the queue, or logged out).
|
||||||
|
count: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn companions_stop_spawning(state: State<'_, AppState>, id: String) -> std::result::Result<CompanionAction, UiError> {
|
||||||
|
let root = path_of(&state, &id)?;
|
||||||
|
blocking(move || Ok(CompanionAction { count: Ra::connect(&root)?.cancel_spawning()? })).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn companions_take_offline(state: State<'_, AppState>, id: String) -> 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 _ = ra.cancel_spawning();
|
||||||
|
Ok(CompanionAction { count: ra.despawn_all()? })
|
||||||
|
})
|
||||||
|
.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) -> std::result::Result<CompanionAction, UiError> {
|
||||||
|
let root = path_of(&state, &id)?;
|
||||||
|
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||||
|
blocking(move || {
|
||||||
|
if !(1..=5000).contains(&count) {
|
||||||
|
return Err(Error::Invalid("Choose a number between 1 and 5000.".into()));
|
||||||
|
}
|
||||||
|
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};"
|
||||||
|
))?;
|
||||||
|
let guids: Vec<u64> = rows.lines().filter_map(|l| l.trim().parse().ok()).collect();
|
||||||
|
let mut ra = Ra::connect(&root)?;
|
||||||
|
let mut done = 0;
|
||||||
|
for g in guids {
|
||||||
|
if ra.despawn_bot(g).unwrap_or(false) {
|
||||||
|
done += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(CompanionAction { count: done })
|
||||||
|
})
|
||||||
|
.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) -> std::result::Result<CompanionAction, UiError> {
|
||||||
|
let root = path_of(&state, &id)?;
|
||||||
|
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||||
|
blocking(move || {
|
||||||
|
let meta = meta_dir(&root)?;
|
||||||
|
backup::create(&root, &meta, Kind::Quick, Trigger::BeforeDangerousChange, Some("before deleting all companions".into()), &|step| {
|
||||||
|
let _ = app.emit("backup-progress", step);
|
||||||
|
})?;
|
||||||
|
let before = coa_core::population::query(&root).map(|p| p.bots_total).unwrap_or(0);
|
||||||
|
let mut ra = Ra::connect(&root)?;
|
||||||
|
let _ = ra.cancel_spawning();
|
||||||
|
ra.purge_all()?;
|
||||||
|
Ok(CompanionAction { count: before })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn get_performance(state: State<'_, AppState>, id: String) -> std::result::Result<Option<coa_core::ra::Performance>, UiError> {
|
async fn get_performance(state: State<'_, AppState>, id: String) -> std::result::Result<Option<coa_core::ra::Performance>, UiError> {
|
||||||
let root = path_of(&state, &id)?;
|
let root = path_of(&state, &id)?;
|
||||||
@@ -544,6 +616,10 @@ fn companion_sizes() -> CompanionSizes {
|
|||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
struct CompanionsResult {
|
struct CompanionsResult {
|
||||||
spawned: Option<String>,
|
spawned: Option<String>,
|
||||||
|
/// Created offline with their equipment (server was stopped and the batch was large).
|
||||||
|
created: Option<u32>,
|
||||||
|
/// Companions that existed before this request (for a progress bar while the server creates the new ones).
|
||||||
|
baseline: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Turn on automatic bot login for `count` bots and, if the server is running, ask it to create them.
|
/// Turn on automatic bot login for `count` bots and, if the server is running, ask it to create them.
|
||||||
@@ -558,12 +634,45 @@ async fn add_companions(state: State<'_, AppState>, id: String, count: u32) -> s
|
|||||||
let meta = meta_dir(&root)?;
|
let meta = meta_dir(&root)?;
|
||||||
let mut changes = BTreeMap::new();
|
let mut changes = BTreeMap::new();
|
||||||
changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true));
|
changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true));
|
||||||
changes.insert("CoaBots.AutoLogin.MaxCount".to_string(), Value::from(count));
|
// 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()))
|
||||||
|
.unwrap_or(0) as u32;
|
||||||
|
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)));
|
||||||
config::save(&root, &meta, Scope::Bots, &changes)?;
|
config::save(&root, &meta, Scope::Bots, &changes)?;
|
||||||
let o = coa_core::process::observe(&root, &layout::read_ports(&root));
|
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 });
|
||||||
|
}
|
||||||
|
let mut baseline = None;
|
||||||
let spawned = if o.world.state == coa_core::process::ServiceState::Running {
|
let spawned = if o.world.state == coa_core::process::ServiceState::Running {
|
||||||
// Older servers have no template characters to copy bots from: add them first.
|
// 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)?)?;
|
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);
|
||||||
Some(Ra::connect(&root)?.spawn_bots(count)?)
|
Some(Ra::connect(&root)?.spawn_bots(count)?)
|
||||||
} else {
|
} else {
|
||||||
// The server is stopped: creating bots needs it running, so remember the request and do it after the next start.
|
// The server is stopped: creating bots needs it running, so remember the request and do it after the next start.
|
||||||
@@ -571,7 +680,7 @@ async fn add_companions(state: State<'_, AppState>, id: String, count: u32) -> s
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
tracing::info!(count, spawned = spawned.is_some(), "companions requested");
|
tracing::info!(count, spawned = spawned.is_some(), "companions requested");
|
||||||
Ok(CompanionsResult { spawned })
|
Ok(CompanionsResult { spawned, created: None, baseline })
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@@ -892,6 +1001,10 @@ pub fn run() {
|
|||||||
rollback_update,
|
rollback_update,
|
||||||
get_population,
|
get_population,
|
||||||
get_performance,
|
get_performance,
|
||||||
|
companions_stop_spawning,
|
||||||
|
companions_take_offline,
|
||||||
|
companions_delete_all,
|
||||||
|
companions_despawn_some,
|
||||||
open_link,
|
open_link,
|
||||||
companion_sizes,
|
companion_sizes,
|
||||||
add_companions,
|
add_companions,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "CoA Server Manager",
|
"productName": "CoA Server Manager",
|
||||||
"version": "0.1.6",
|
"version": "0.2.0",
|
||||||
"identifier": "com.coa.servermanager",
|
"identifier": "com.coa.servermanager",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "npm run dev",
|
"beforeDevCommand": "npm run dev",
|
||||||
|
|||||||
|
After Width: | Height: | Size: 143 KiB |
@@ -30,7 +30,8 @@ export {};
|
|||||||
if(cmd==="list_presets"){const pr=args?.scope==="server"?serverPresets:botsPresets;return (pr.presets as any[]).map(p=>({id:p.id,title:p.title,description:p.description}));}
|
if(cmd==="list_presets"){const pr=args?.scope==="server"?serverPresets:botsPresets;return (pr.presets as any[]).map(p=>({id:p.id,title:p.title,description:p.description}));}
|
||||||
if(cmd==="preview_preset"){const a=args;const sc=a.scope==="server"?serverSchema:botsSchema;const pr=(a.scope==="server"?serverPresets:botsPresets).presets as any[];const p=pr.find(x=>x.id===a.preset)??{id:a.preset??"defaults",title:"Recommended defaults",description:"Every setting returns to its default value."};const st=(sc.settings as any[]).filter(x=>x.type==="int"||x.type==="float"||x.type==="enum").slice(0,3);return {id:p.id,title:p.title,description:p.description,changes:st.map(x=>({key:x.key,title:x.title,from:x.default,to:x.type==="enum"?(x.options?.[1]?.value??x.default):(Number(x.default)||1)*2,dangerous:false}))};}
|
if(cmd==="preview_preset"){const a=args;const sc=a.scope==="server"?serverSchema:botsSchema;const pr=(a.scope==="server"?serverPresets:botsPresets).presets as any[];const p=pr.find(x=>x.id===a.preset)??{id:a.preset??"defaults",title:"Recommended defaults",description:"Every setting returns to its default value."};const st=(sc.settings as any[]).filter(x=>x.type==="int"||x.type==="float"||x.type==="enum").slice(0,3);return {id:p.id,title:p.title,description:p.description,changes:st.map(x=>({key:x.key,title:x.title,from:x.default,to:x.type==="enum"?(x.options?.[1]?.value??x.default):(Number(x.default)||1)*2,dangerous:false}))};}
|
||||||
if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]};
|
if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]};
|
||||||
if(cmd==="get_population") return null;
|
if(cmd==="add_companions"){const base=(window as any).__bots??85;(window as any).__target=base+args.count;return {spawned:"queued",created:null,baseline:base};}
|
||||||
|
if(cmd==="get_population"){if(!running) return null;let b=(window as any).__bots??85;const t=(window as any).__target??0;if(t>b){b=Math.min(t,b+25);(window as any).__bots=b;}return {online_total:b,bots_online:Math.max(0,b-7),players_online:0,bots_total:b};}
|
||||||
if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null;
|
if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null;
|
||||||
if(cmd==="run_diagnostics") return {problems:2,checks:[{id:"files",title:"Server files",level:"ok",detail:"All expected server parts were found."},{id:"world",title:"World server",level:"warn",detail:"Not running."},{id:"disk",title:"Free disk space",level:"warn",detail:"Only 3 GB free; backups and updates need room."},{id:"exposure",title:"Private services",level:"ok",detail:"Database and server console are not reachable from the network."}]};
|
if(cmd==="run_diagnostics") return {problems:2,checks:[{id:"files",title:"Server files",level:"ok",detail:"All expected server parts were found."},{id:"world",title:"World server",level:"warn",detail:"Not running."},{id:"disk",title:"Free disk space",level:"warn",detail:"Only 3 GB free; backups and updates need room."},{id:"exposure",title:"Private services",level:"ok",detail:"Database and server console are not reachable from the network."}]};
|
||||||
if(cmd==="plugin:event|listen") return 1;
|
if(cmd==="plugin:event|listen") return 1;
|
||||||
|
|||||||
@@ -527,6 +527,47 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
|||||||
"fr.g.ts.4": "Tailscale muss bei euch beiden laufen, solange ihr spielt.",
|
"fr.g.ts.4": "Tailscale muss bei euch beiden laufen, solange ihr spielt.",
|
||||||
"fr.g.ts.admin": "Tailscale-Verwaltungsseite öffnen",
|
"fr.g.ts.admin": "Tailscale-Verwaltungsseite öffnen",
|
||||||
"fr.g.ts.share": "So funktioniert das Teilen (tailscale.com)",
|
"fr.g.ts.share": "So funktioniert das Teilen (tailscale.com)",
|
||||||
|
|
||||||
|
// Bots at start
|
||||||
|
"comp.startTitle": "Bots beim Serverstart",
|
||||||
|
"comp.startAuto": "Bots melden sich beim Serverstart automatisch an",
|
||||||
|
"comp.startCount": "Wie viele sich anmelden",
|
||||||
|
"comp.startSave": "Speichern",
|
||||||
|
"comp.startSaved": "Gespeichert. Gilt ab dem nächsten Serverstart.",
|
||||||
|
"comp.startHint": "Bots, die sich nicht anmelden, bleiben gespeichert und können später online gebracht werden.",
|
||||||
|
"comp.startInvalid": "Gib eine ganze Zahl von 0 bis 5000 ein.",
|
||||||
|
|
||||||
|
// Overview start bots
|
||||||
|
"overview.startBots": "Bots melden sich beim Start an: {n}",
|
||||||
|
"overview.startBotsOff": "Bots melden sich beim Start nicht an",
|
||||||
|
|
||||||
|
// Offline bots
|
||||||
|
"comp.offlineDone": "{n} Begleiter samt Ausrüstung erstellt. Sie melden sich beim Serverstart an.",
|
||||||
|
|
||||||
|
// Companions progress
|
||||||
|
"comp.progress": "{done} von {target} hinzugefügt",
|
||||||
|
"comp.progressDone": "Alle {n} Begleiter sind erstellt. Sie melden sich jetzt an.",
|
||||||
|
"comp.progressOffline": "{n} Begleiter werden samt Ausrüstung erstellt … das dauert einige Minuten.",
|
||||||
|
"comp.progressStalled": "Warte darauf, dass der Server weitere erstellt …",
|
||||||
|
|
||||||
|
// Companions control
|
||||||
|
"comp.stop": "Erstellung stoppen",
|
||||||
|
"comp.stopped": "Gestoppt. {n} noch wartende Begleiter wurden abgebrochen; bereits erstellte bleiben erhalten.",
|
||||||
|
"comp.manageTitle": "Vorhandene Begleiter verwalten",
|
||||||
|
"comp.offline": "Alle offline nehmen",
|
||||||
|
"comp.offlineConfirm": "Alle Begleiter aus dem Spiel abmelden? Sie bleiben gespeichert und kommen beim nächsten Serverstart oder beim erneuten Hinzufügen zurück.",
|
||||||
|
"comp.offlineDone2": "{n} Begleiter offline genommen. Sie bleiben gespeichert.",
|
||||||
|
"comp.delete": "Alle Begleiter löschen …",
|
||||||
|
"comp.deleteConfirm": "Alle {n} Begleiter endgültig löschen? Zuvor wird ein Wiederherstellungspunkt gespeichert. Deine eigenen Charaktere bleiben unberührt.",
|
||||||
|
"comp.deleteDone": "Alle Begleiter wurden gelöscht. Zuvor wurde ein Wiederherstellungspunkt gespeichert.",
|
||||||
|
"err.companion_command_unsupported.title": "Diese Serverversion kann das noch nicht",
|
||||||
|
"err.companion_command_unsupported.message": "Das Bot-Modul dieses Server-Builds kennt diesen Befehl nicht. Aktualisiere den Server oder starte ihn neu, um Laufendes zu stoppen.",
|
||||||
|
|
||||||
|
// Despawn some
|
||||||
|
"comp.despawnSome": "{n} Bots entfernen",
|
||||||
|
"comp.despawnCount": "Wie viele abmelden",
|
||||||
|
"comp.despawnHint": "Entlastet sofort: Jeder Bot online kostet Serverzeit. Sie bleiben gespeichert und kommen beim nächsten Start zurück, wenn die automatische Anmeldung an ist.",
|
||||||
|
"comp.despawnSomeDone": "{n} Begleiter abgemeldet. Sie bleiben gespeichert.",
|
||||||
};
|
};
|
||||||
|
|
||||||
export default de;
|
export default de;
|
||||||
@@ -527,6 +527,47 @@ const en = {
|
|||||||
"fr.g.ts.4": "Both of you must keep Tailscale running while you play.",
|
"fr.g.ts.4": "Both of you must keep Tailscale running while you play.",
|
||||||
"fr.g.ts.admin": "Open the Tailscale admin page",
|
"fr.g.ts.admin": "Open the Tailscale admin page",
|
||||||
"fr.g.ts.share": "How sharing works (tailscale.com)",
|
"fr.g.ts.share": "How sharing works (tailscale.com)",
|
||||||
|
|
||||||
|
// Bots at start
|
||||||
|
"comp.startTitle": "Bots at server start",
|
||||||
|
"comp.startAuto": "Bots log in automatically when the server starts",
|
||||||
|
"comp.startCount": "How many log in",
|
||||||
|
"comp.startSave": "Save",
|
||||||
|
"comp.startSaved": "Saved. It applies the next time the server starts.",
|
||||||
|
"comp.startHint": "Bots that do not log in stay saved and can be brought online later.",
|
||||||
|
"comp.startInvalid": "Enter a whole number from 0 to 5000.",
|
||||||
|
|
||||||
|
// Overview start bots
|
||||||
|
"overview.startBots": "Bots log in at start: {n}",
|
||||||
|
"overview.startBotsOff": "Bots log in at start: off",
|
||||||
|
|
||||||
|
// Offline bots
|
||||||
|
"comp.offlineDone": "Created {n} companions with their equipment. They log in when the server starts.",
|
||||||
|
|
||||||
|
// Companions progress
|
||||||
|
"comp.progress": "{done} of {target} added",
|
||||||
|
"comp.progressDone": "All {n} companions are created. They are logging in now.",
|
||||||
|
"comp.progressOffline": "Creating {n} companions with their equipment… this takes a few minutes.",
|
||||||
|
"comp.progressStalled": "Waiting for the server to create more…",
|
||||||
|
|
||||||
|
// Companions control
|
||||||
|
"comp.stop": "Stop creating",
|
||||||
|
"comp.stopped": "Stopped. {n} companions that were still waiting are cancelled; the ones already created stay.",
|
||||||
|
"comp.manageTitle": "Manage existing companions",
|
||||||
|
"comp.offline": "Take all offline",
|
||||||
|
"comp.offlineConfirm": "Log all companions out of the game? They stay saved and come back at the next server start or when you add them again.",
|
||||||
|
"comp.offlineDone2": "{n} companions taken offline. They stay saved.",
|
||||||
|
"comp.delete": "Delete all companions…",
|
||||||
|
"comp.deleteConfirm": "Delete all {n} companions for good? A recovery point is saved first. Your own characters are not touched.",
|
||||||
|
"comp.deleteDone": "All companions were deleted. A recovery point was saved first.",
|
||||||
|
"err.companion_command_unsupported.title": "This server version can not do that yet",
|
||||||
|
"err.companion_command_unsupported.message": "The bot module of this server build has no such command. Update the server, or restart it to stop what is running.",
|
||||||
|
|
||||||
|
// Despawn some
|
||||||
|
"comp.despawnSome": "Despawn {n} bots",
|
||||||
|
"comp.despawnCount": "How many to log out",
|
||||||
|
"comp.despawnHint": "Eases the load right away: every online bot costs server time. They stay saved and return at the next start if automatic login is on.",
|
||||||
|
"comp.despawnSomeDone": "{n} companions logged out. They stay saved.",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export default en;
|
export default en;
|
||||||
@@ -527,6 +527,47 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
|||||||
"fr.g.ts.4": "Tailscale debe seguir en marcha en ambos equipos mientras jugáis.",
|
"fr.g.ts.4": "Tailscale debe seguir en marcha en ambos equipos mientras jugáis.",
|
||||||
"fr.g.ts.admin": "Abrir la página de administración de Tailscale",
|
"fr.g.ts.admin": "Abrir la página de administración de Tailscale",
|
||||||
"fr.g.ts.share": "Cómo funciona compartir (tailscale.com)",
|
"fr.g.ts.share": "Cómo funciona compartir (tailscale.com)",
|
||||||
|
|
||||||
|
// Bots at start
|
||||||
|
"comp.startTitle": "Bots al iniciar el servidor",
|
||||||
|
"comp.startAuto": "Los bots inician sesión automáticamente al arrancar el servidor",
|
||||||
|
"comp.startCount": "Cuántos inician sesión",
|
||||||
|
"comp.startSave": "Guardar",
|
||||||
|
"comp.startSaved": "Guardado. Se aplica la próxima vez que se inicie el servidor.",
|
||||||
|
"comp.startHint": "Los bots que no inician sesión quedan guardados y se pueden conectar más tarde.",
|
||||||
|
"comp.startInvalid": "Introduce un número entero de 0 a 5000.",
|
||||||
|
|
||||||
|
// Overview start bots
|
||||||
|
"overview.startBots": "Bots que inician sesión al arrancar: {n}",
|
||||||
|
"overview.startBotsOff": "Bots al arrancar: desactivado",
|
||||||
|
|
||||||
|
// Offline bots
|
||||||
|
"comp.offlineDone": "Se crearon {n} compañeros con su equipo. Iniciarán sesión cuando arranque el servidor.",
|
||||||
|
|
||||||
|
// Companions progress
|
||||||
|
"comp.progress": "{done} de {target} añadidos",
|
||||||
|
"comp.progressDone": "Se crearon los {n} compañeros. Están iniciando sesión.",
|
||||||
|
"comp.progressOffline": "Creando {n} compañeros con su equipo… esto tarda unos minutos.",
|
||||||
|
"comp.progressStalled": "Esperando a que el servidor cree más…",
|
||||||
|
|
||||||
|
// Companions control
|
||||||
|
"comp.stop": "Detener la creación",
|
||||||
|
"comp.stopped": "Detenido. Se cancelaron {n} compañeros que seguían en espera; los ya creados se quedan.",
|
||||||
|
"comp.manageTitle": "Gestionar los compañeros existentes",
|
||||||
|
"comp.offline": "Desconectar a todos",
|
||||||
|
"comp.offlineConfirm": "¿Desconectar a todos los compañeros del juego? Quedan guardados y vuelven en el próximo inicio del servidor o cuando los añadas de nuevo.",
|
||||||
|
"comp.offlineDone2": "{n} compañeros desconectados. Quedan guardados.",
|
||||||
|
"comp.delete": "Eliminar a todos los compañeros…",
|
||||||
|
"comp.deleteConfirm": "¿Eliminar definitivamente los {n} compañeros? Antes se guarda un punto de recuperación. Tus propios personajes no se tocan.",
|
||||||
|
"comp.deleteDone": "Se eliminaron todos los compañeros. Antes se guardó un punto de recuperación.",
|
||||||
|
"err.companion_command_unsupported.title": "Esta versión del servidor aún no puede hacerlo",
|
||||||
|
"err.companion_command_unsupported.message": "El módulo de bots de esta versión del servidor no tiene ese comando. Actualiza el servidor o reinícialo para detener lo que esté en marcha.",
|
||||||
|
|
||||||
|
// Despawn some
|
||||||
|
"comp.despawnSome": "Retirar {n} bots",
|
||||||
|
"comp.despawnCount": "Cuántos desconectar",
|
||||||
|
"comp.despawnHint": "Alivia la carga al instante: cada bot conectado cuesta tiempo de servidor. Quedan guardados y vuelven en el próximo inicio si el inicio de sesión automático está activado.",
|
||||||
|
"comp.despawnSomeDone": "{n} compañeros desconectados. Quedan guardados.",
|
||||||
};
|
};
|
||||||
|
|
||||||
export default es;
|
export default es;
|
||||||
@@ -527,6 +527,47 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
|||||||
"fr.g.ts.4": "Tailscale doit rester lancé chez vous deux pendant que vous jouez.",
|
"fr.g.ts.4": "Tailscale doit rester lancé chez vous deux pendant que vous jouez.",
|
||||||
"fr.g.ts.admin": "Ouvrir la page d’administration de Tailscale",
|
"fr.g.ts.admin": "Ouvrir la page d’administration de Tailscale",
|
||||||
"fr.g.ts.share": "Comment fonctionne le partage (tailscale.com)",
|
"fr.g.ts.share": "Comment fonctionne le partage (tailscale.com)",
|
||||||
|
|
||||||
|
// Bots at start
|
||||||
|
"comp.startTitle": "Bots au démarrage du serveur",
|
||||||
|
"comp.startAuto": "Les bots se connectent automatiquement au démarrage du serveur",
|
||||||
|
"comp.startCount": "Combien se connectent",
|
||||||
|
"comp.startSave": "Enregistrer",
|
||||||
|
"comp.startSaved": "Enregistré. S’applique au prochain démarrage du serveur.",
|
||||||
|
"comp.startHint": "Les bots qui ne se connectent pas restent enregistrés et peuvent être mis en ligne plus tard.",
|
||||||
|
"comp.startInvalid": "Saisissez un nombre entier de 0 à 5000.",
|
||||||
|
|
||||||
|
// Overview start bots
|
||||||
|
"overview.startBots": "Bots connectés au démarrage : {n}",
|
||||||
|
"overview.startBotsOff": "Bots connectés au démarrage : aucun",
|
||||||
|
|
||||||
|
// Offline bots
|
||||||
|
"comp.offlineDone": "{n} compagnons créés avec leur équipement. Ils se connecteront au démarrage du serveur.",
|
||||||
|
|
||||||
|
// Companions progress
|
||||||
|
"comp.progress": "{done} sur {target} ajoutés",
|
||||||
|
"comp.progressDone": "Les {n} compagnons sont créés. Ils se connectent maintenant.",
|
||||||
|
"comp.progressOffline": "Création de {n} compagnons avec leur équipement… cela prend quelques minutes.",
|
||||||
|
"comp.progressStalled": "En attente de la création des suivants par le serveur…",
|
||||||
|
|
||||||
|
// Companions control
|
||||||
|
"comp.stop": "Arrêter la création",
|
||||||
|
"comp.stopped": "Arrêté. {n} compagnons encore en attente sont annulés ; ceux déjà créés restent.",
|
||||||
|
"comp.manageTitle": "Gérer les compagnons existants",
|
||||||
|
"comp.offline": "Tout mettre hors ligne",
|
||||||
|
"comp.offlineConfirm": "Déconnecter tous les compagnons du jeu ? Ils restent enregistrés et reviennent au prochain démarrage du serveur ou quand vous les ajoutez de nouveau.",
|
||||||
|
"comp.offlineDone2": "{n} compagnons mis hors ligne. Ils restent enregistrés.",
|
||||||
|
"comp.delete": "Supprimer tous les compagnons…",
|
||||||
|
"comp.deleteConfirm": "Supprimer définitivement les {n} compagnons ? Un point de restauration est d’abord enregistré. Vos propres personnages ne sont pas touchés.",
|
||||||
|
"comp.deleteDone": "Tous les compagnons ont été supprimés. Un point de restauration a été enregistré d’abord.",
|
||||||
|
"err.companion_command_unsupported.title": "Cette version du serveur ne sait pas encore le faire",
|
||||||
|
"err.companion_command_unsupported.message": "Le module de bots de cette version du serveur n’a pas cette commande. Mettez le serveur à jour ou redémarrez-le pour arrêter ce qui est en cours.",
|
||||||
|
|
||||||
|
// Despawn some
|
||||||
|
"comp.despawnSome": "Retirer {n} bots",
|
||||||
|
"comp.despawnCount": "Combien déconnecter",
|
||||||
|
"comp.despawnHint": "Allège aussitôt la charge : chaque bot en ligne coûte du temps serveur. Ils restent enregistrés et reviennent au prochain démarrage si la connexion automatique est activée.",
|
||||||
|
"comp.despawnSomeDone": "{n} compagnons déconnectés. Ils restent enregistrés.",
|
||||||
};
|
};
|
||||||
|
|
||||||
export default fr;
|
export default fr;
|
||||||
@@ -527,6 +527,47 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
|||||||
"fr.g.ts.4": "Пока вы играете, Tailscale должен быть запущен у обоих.",
|
"fr.g.ts.4": "Пока вы играете, Tailscale должен быть запущен у обоих.",
|
||||||
"fr.g.ts.admin": "Открыть страницу администрирования Tailscale",
|
"fr.g.ts.admin": "Открыть страницу администрирования Tailscale",
|
||||||
"fr.g.ts.share": "Как работает предоставление доступа (tailscale.com)",
|
"fr.g.ts.share": "Как работает предоставление доступа (tailscale.com)",
|
||||||
|
|
||||||
|
// Bots at start
|
||||||
|
"comp.startTitle": "Боты при запуске сервера",
|
||||||
|
"comp.startAuto": "Боты входят в игру автоматически при запуске сервера",
|
||||||
|
"comp.startCount": "Сколько входит",
|
||||||
|
"comp.startSave": "Сохранить",
|
||||||
|
"comp.startSaved": "Сохранено. Вступит в силу при следующем запуске сервера.",
|
||||||
|
"comp.startHint": "Боты, которые не входят, остаются сохранёнными, их можно вывести в сеть позже.",
|
||||||
|
"comp.startInvalid": "Введите целое число от 0 до 5000.",
|
||||||
|
|
||||||
|
// Overview start bots
|
||||||
|
"overview.startBots": "Боты входят при запуске: {n}",
|
||||||
|
"overview.startBotsOff": "Боты при запуске не входят",
|
||||||
|
|
||||||
|
// Offline bots
|
||||||
|
"comp.offlineDone": "Создано компаньонов: {n}, сразу со снаряжением. Они войдут в игру при запуске сервера.",
|
||||||
|
|
||||||
|
// Companions progress
|
||||||
|
"comp.progress": "Добавлено {done} из {target}",
|
||||||
|
"comp.progressDone": "Все компаньоны ({n}) созданы. Они входят в игру.",
|
||||||
|
"comp.progressOffline": "Создаю компаньонов ({n}) со снаряжением… это займёт несколько минут.",
|
||||||
|
"comp.progressStalled": "Жду, пока сервер создаст остальных…",
|
||||||
|
|
||||||
|
// Companions control
|
||||||
|
"comp.stop": "Остановить создание",
|
||||||
|
"comp.stopped": "Остановлено. Ожидавшие очереди компаньоны ({n}) отменены; уже созданные остаются.",
|
||||||
|
"comp.manageTitle": "Управление существующими компаньонами",
|
||||||
|
"comp.offline": "Вывести всех из игры",
|
||||||
|
"comp.offlineConfirm": "Вывести всех компаньонов из игры? Они остаются сохранёнными и вернутся при следующем запуске сервера или когда вы их снова добавите.",
|
||||||
|
"comp.offlineDone2": "Из игры выведено компаньонов: {n}. Они остаются сохранёнными.",
|
||||||
|
"comp.delete": "Удалить всех компаньонов…",
|
||||||
|
"comp.deleteConfirm": "Удалить всех компаньонов ({n}) навсегда? Сначала сохраняется точка восстановления. Ваши собственные персонажи не затрагиваются.",
|
||||||
|
"comp.deleteDone": "Все компаньоны удалены. Сначала была сохранена точка восстановления.",
|
||||||
|
"err.companion_command_unsupported.title": "Эта версия сервера пока этого не умеет",
|
||||||
|
"err.companion_command_unsupported.message": "В модуле ботов этой сборки сервера нет такой команды. Обновите сервер или перезапустите его, чтобы остановить текущую работу.",
|
||||||
|
|
||||||
|
// Despawn some
|
||||||
|
"comp.despawnSome": "Убрать ботов: {n}",
|
||||||
|
"comp.despawnCount": "Сколько убрать",
|
||||||
|
"comp.despawnHint": "Сразу снижает нагрузку: каждый бот в сети отнимает время сервера. Они остаются сохранёнными и вернутся при следующем запуске, если включён автоматический вход.",
|
||||||
|
"comp.despawnSomeDone": "Убрано из игры компаньонов: {n}. Они остаются сохранёнными.",
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ru;
|
export default ru;
|
||||||
@@ -37,6 +37,46 @@ body {
|
|||||||
user-select: none;
|
user-select: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Dark, slim scroll bars that match the interface (the default light ones stand out too much). */
|
||||||
|
html {
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: rgb(255 255 255 / 0.16) transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
*::-webkit-scrollbar {
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
*::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
*::-webkit-scrollbar-thumb {
|
||||||
|
background: rgb(255 255 255 / 0.14);
|
||||||
|
border-radius: 999px;
|
||||||
|
border: 2px solid transparent;
|
||||||
|
background-clip: content-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
*::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: rgb(201 162 74 / 0.55);
|
||||||
|
background-clip: content-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
*::-webkit-scrollbar-thumb:active {
|
||||||
|
background: rgb(201 162 74 / 0.8);
|
||||||
|
background-clip: content-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
*::-webkit-scrollbar-corner {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
::selection {
|
::selection {
|
||||||
background: rgb(201 162 74 / 0.35);
|
background: rgb(201 162 74 / 0.35);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -289,10 +289,14 @@ export const api = {
|
|||||||
invoke<{ txn: UpdateTxn }>("apply_update", { id, source: source ?? null, resolutions }),
|
invoke<{ txn: UpdateTxn }>("apply_update", { id, source: source ?? null, resolutions }),
|
||||||
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
|
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
|
||||||
population: (id: string) => invoke<Population | null>("get_population", { id }),
|
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 }),
|
openLink: (url: string) => invoke<void>("open_link", { url }),
|
||||||
performance: (id: string) => invoke<Performance | null>("get_performance", { id }),
|
performance: (id: string) => invoke<Performance | null>("get_performance", { id }),
|
||||||
companionSizes: () => invoke<CompanionSizes>("companion_sizes"),
|
companionSizes: () => invoke<CompanionSizes>("companion_sizes"),
|
||||||
addCompanions: (id: string, count: number) => invoke<{ spawned: string | null }>("add_companions", { id, count }),
|
addCompanions: (id: string, count: number) => invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count }),
|
||||||
clientInfo: (id: string) => invoke<ClientInfo | null>("client_info", { id }),
|
clientInfo: (id: string) => invoke<ClientInfo | null>("client_info", { id }),
|
||||||
setClient: (id: string, path: string) => invoke<ClientInfo>("set_client", { id, path }),
|
setClient: (id: string, path: string) => invoke<ClientInfo>("set_client", { id, path }),
|
||||||
setRealmlist: (id: string, host: string) => invoke<string[]>("client_realmlist", { id, host }),
|
setRealmlist: (id: string, host: string) => invoke<string[]>("client_realmlist", { id, host }),
|
||||||
|
|||||||
@@ -16,6 +16,88 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
|
|||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState<UiError | null>(null);
|
const [error, setError] = useState<UiError | null>(null);
|
||||||
const [note, setNote] = useState<string | 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 [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");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void api
|
||||||
|
.settings(serverId, "bots")
|
||||||
|
.then((v) => {
|
||||||
|
const on = v.settings.find((s) => s.key === "CoaBots.AutoLoginOnStartup");
|
||||||
|
const max = v.settings.find((s) => s.key === "CoaBots.AutoLogin.MaxCount");
|
||||||
|
if (on) setAutoOn(on.value === true);
|
||||||
|
if (max) setAutoMax(String(max.value));
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}, [serverId]);
|
||||||
|
|
||||||
|
const maxNum = Number(autoMax);
|
||||||
|
const maxValid = autoMax.trim() !== "" && Number.isInteger(maxNum) && maxNum >= 0 && maxNum <= 5000;
|
||||||
|
|
||||||
|
async function act(fn: () => Promise<string>) {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
setNote(await fn());
|
||||||
|
} catch (e) {
|
||||||
|
setError(asUiError(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const stopCreating = () =>
|
||||||
|
act(async () => {
|
||||||
|
const r = await api.stopSpawning(serverId);
|
||||||
|
setJob(null);
|
||||||
|
return t("comp.stopped", { n: r.count });
|
||||||
|
});
|
||||||
|
|
||||||
|
const takeOffline = () => {
|
||||||
|
if (!window.confirm(t("comp.offlineConfirm"))) return;
|
||||||
|
void act(async () => {
|
||||||
|
const r = await api.takeOffline(serverId);
|
||||||
|
setJob(null);
|
||||||
|
return t("comp.offlineDone2", { n: r.count });
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const dn = Number(despawnN);
|
||||||
|
const dnValid = Number.isInteger(dn) && dn >= 1 && dn <= 5000;
|
||||||
|
const despawnSome = () =>
|
||||||
|
act(async () => {
|
||||||
|
const r = await api.despawnSome(serverId, dn);
|
||||||
|
return t("comp.despawnSomeDone", { n: r.count });
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteAll = () => {
|
||||||
|
if (!window.confirm(t("comp.deleteConfirm", { n: pop?.bots_total ?? 0 }))) return;
|
||||||
|
void act(async () => {
|
||||||
|
await api.deleteAllCompanions(serverId);
|
||||||
|
setJob(null);
|
||||||
|
return t("comp.deleteDone");
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
async function saveStart() {
|
||||||
|
setStartBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setStartNote(null);
|
||||||
|
try {
|
||||||
|
await api.save(serverId, "bots", { "CoaBots.AutoLoginOnStartup": autoOn, "CoaBots.AutoLogin.MaxCount": maxNum });
|
||||||
|
setStartNote(t("comp.startSaved"));
|
||||||
|
} catch (e) {
|
||||||
|
setError(asUiError(e));
|
||||||
|
} finally {
|
||||||
|
setStartBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void api.companionSizes().then(setSizes);
|
void api.companionSizes().then(setSizes);
|
||||||
@@ -28,12 +110,23 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
|
|||||||
setPop(up ? await api.population(serverId).catch(() => null) : null);
|
setPop(up ? await api.population(serverId).catch(() => null) : null);
|
||||||
};
|
};
|
||||||
void poll();
|
void poll();
|
||||||
const t = setInterval(poll, 4000);
|
// Faster while companions are being created, so the progress bar moves.
|
||||||
|
const t = setInterval(poll, job ? 1500 : 4000);
|
||||||
return () => {
|
return () => {
|
||||||
alive = false;
|
alive = false;
|
||||||
clearInterval(t);
|
clearInterval(t);
|
||||||
};
|
};
|
||||||
}, [serverId]);
|
}, [serverId, 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;
|
||||||
|
// 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.
|
// 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 }) => {
|
const warningFor = (size?: { bots: number; warning: string | null }) => {
|
||||||
@@ -52,7 +145,8 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
|
|||||||
setNote(null);
|
setNote(null);
|
||||||
try {
|
try {
|
||||||
const r = await api.addCompanions(serverId, count);
|
const r = await api.addCompanions(serverId, count);
|
||||||
setNote(r.spawned ? t("comp.spawned", { n: count }) : t("comp.saved", { n: 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) {
|
} catch (e) {
|
||||||
setError(asUiError(e));
|
setError(asUiError(e));
|
||||||
} finally {
|
} finally {
|
||||||
@@ -94,13 +188,91 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
|
|||||||
{sizes && <p className="mt-2 text-xs text-muted">{t("comp.hardware", { cores: sizes.hardware.cores, ram: sizes.hardware.ram_gb.toFixed(0) })}</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">
|
<div className="mt-4 flex items-center gap-3">
|
||||||
<Button variant="primary" disabled={busy || !valid} onClick={() => void add()}>
|
<Button variant="primary" disabled={busy || !valid || job !== null} onClick={() => void add()}>
|
||||||
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||||
{valid ? t("comp.add", { n: count }) : t("comp.addPlain")}
|
{valid ? t("comp.add", { n: count }) : t("comp.addPlain")}
|
||||||
</Button>
|
</Button>
|
||||||
{!running && <span className="text-xs text-muted">{t("comp.stoppedHint")}</span>}
|
{!running && <span className="text-xs text-muted">{t("comp.stoppedHint")}</span>}
|
||||||
</div>
|
</div>
|
||||||
{note && <p className="mt-3 text-sm text-ok" role="status">{note}</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>
|
||||||
|
)}
|
||||||
|
{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>}
|
||||||
|
|
||||||
|
{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-3 py-1.5 text-right outline-none focus:border-gold"
|
||||||
|
/>
|
||||||
|
<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}>
|
||||||
|
{t("comp.offline")}
|
||||||
|
</Button>
|
||||||
|
<Button size="sm" variant="ghost" className="text-bad hover:text-bad" disabled={busy} onClick={deleteAll}>
|
||||||
|
{t("comp.delete")}
|
||||||
|
</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>
|
||||||
|
</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>}
|
||||||
|
</div>
|
||||||
{error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
|
{error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -69,6 +69,18 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
|
|||||||
const [client, setClient] = useState<ClientInfo | null>(null);
|
const [client, setClient] = useState<ClientInfo | null>(null);
|
||||||
const [playing, setPlaying] = useState(false);
|
const [playing, setPlaying] = useState(false);
|
||||||
const [perf, setPerf] = useState<Performance | null>(null);
|
const [perf, setPerf] = useState<Performance | null>(null);
|
||||||
|
const [startBots, setStartBots] = useState<number | null | undefined>(undefined);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void api
|
||||||
|
.settings(server.id, "bots")
|
||||||
|
.then((v) => {
|
||||||
|
const on = v.settings.find((s) => s.key === "CoaBots.AutoLoginOnStartup");
|
||||||
|
const max = v.settings.find((s) => s.key === "CoaBots.AutoLogin.MaxCount");
|
||||||
|
setStartBots(on?.value === true && typeof max?.value === "number" ? max.value : null);
|
||||||
|
})
|
||||||
|
.catch(() => setStartBots(undefined));
|
||||||
|
}, [server.id]);
|
||||||
const alive = useRef(true);
|
const alive = useRef(true);
|
||||||
|
|
||||||
const poll = useCallback(async () => {
|
const poll = useCallback(async () => {
|
||||||
@@ -213,6 +225,9 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
|
|||||||
<dd className="mt-0.5 text-lg">{pop ? `${pop.players_online}` : "—"}{pop && pop.bots_online > 0 ? <span className="ml-2 text-sm text-muted">{t("overview.companions", { n: pop.bots_online })}</span> : null}</dd>
|
<dd className="mt-0.5 text-lg">{pop ? `${pop.players_online}` : "—"}{pop && pop.bots_online > 0 ? <span className="ml-2 text-sm text-muted">{t("overview.companions", { n: pop.bots_online })}</span> : null}</dd>
|
||||||
</div>
|
</div>
|
||||||
</dl>
|
</dl>
|
||||||
|
{startBots !== undefined && (
|
||||||
|
<p className="mt-3 text-xs text-muted">{startBots === null ? t("overview.startBotsOff") : t("overview.startBots", { n: startBots })}</p>
|
||||||
|
)}
|
||||||
{perf && <TickRate perf={perf} />}
|
{perf && <TickRate perf={perf} />}
|
||||||
|
|
||||||
<div className="mt-7 flex items-center gap-4">
|
<div className="mt-7 flex items-center gap-4">
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useState } from "react";
|
|||||||
import { Archive, Bot, Gauge, Globe, Server, Settings, Terminal, Users, type LucideIcon } from "lucide-react";
|
import { Archive, Bot, Gauge, Globe, Server, Settings, Terminal, Users, type LucideIcon } from "lucide-react";
|
||||||
import { type ServerSummary } from "@/lib/api";
|
import { type ServerSummary } from "@/lib/api";
|
||||||
import { useT, type Key } from "@/i18n";
|
import { useT, type Key } from "@/i18n";
|
||||||
|
import logo from "@/assets/logo.png";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { Overview } from "@/screens/Overview";
|
import { Overview } from "@/screens/Overview";
|
||||||
import { Placeholder } from "@/screens/Placeholder";
|
import { Placeholder } from "@/screens/Placeholder";
|
||||||
@@ -41,7 +42,10 @@ export function Shell(props: {
|
|||||||
return (
|
return (
|
||||||
<div className="flex h-full">
|
<div className="flex h-full">
|
||||||
<nav className="flex w-60 shrink-0 flex-col border-r border-line bg-[#0b0c0e] p-3" aria-label={t("nav.main")}>
|
<nav className="flex w-60 shrink-0 flex-col border-r border-line bg-[#0b0c0e] p-3" aria-label={t("nav.main")}>
|
||||||
<div className="px-3 pb-4 pt-2 text-sm font-semibold tracking-wide text-gold">{t("app.name")}</div>
|
<div className="flex items-center gap-2 px-3 pb-4 pt-2 text-sm font-semibold tracking-wide text-gold">
|
||||||
|
<img src={logo} alt="" aria-hidden className="h-7 w-7" />
|
||||||
|
{t("app.name")}
|
||||||
|
</div>
|
||||||
<ul className="flex flex-col gap-0.5">
|
<ul className="flex flex-col gap-0.5">
|
||||||
{NAV.map(({ id, label, icon: Icon }) => (
|
{NAV.map(({ id, label, icon: Icon }) => (
|
||||||
<li key={id}>
|
<li key={id}>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { FolderSearch, Download } from "lucide-react";
|
import { FolderSearch, Download } from "lucide-react";
|
||||||
import { useT } from "@/i18n";
|
import { useT } from "@/i18n";
|
||||||
|
import logo from "@/assets/logo.png";
|
||||||
import { LanguagePicker } from "@/components/LanguagePicker";
|
import { LanguagePicker } from "@/components/LanguagePicker";
|
||||||
|
|
||||||
export function Welcome({ onImport, onInstall, onBack }: { onImport: () => void; onInstall: () => void; onBack?: () => void }) {
|
export function Welcome({ onImport, onInstall, onBack }: { onImport: () => void; onInstall: () => void; onBack?: () => void }) {
|
||||||
@@ -8,7 +9,7 @@ export function Welcome({ onImport, onInstall, onBack }: { onImport: () => void;
|
|||||||
<main className="relative flex h-full flex-col items-center justify-center px-8">
|
<main className="relative flex h-full flex-col items-center justify-center px-8">
|
||||||
<LanguagePicker className="absolute right-6 top-5" />
|
<LanguagePicker className="absolute right-6 top-5" />
|
||||||
<div className="mb-10 text-center">
|
<div className="mb-10 text-center">
|
||||||
<div className="mx-auto mb-5 h-12 w-12 rounded-full border-2 border-gold/80 bg-card-2" aria-hidden />
|
<img src={logo} alt="" aria-hidden className="mx-auto mb-5 h-24 w-24 drop-shadow-[0_6px_24px_rgb(201_162_74/0.35)]" />
|
||||||
<h1 className="text-3xl font-semibold tracking-tight">{t("welcome.title")}</h1>
|
<h1 className="text-3xl font-semibold tracking-tight">{t("welcome.title")}</h1>
|
||||||
<p className="mt-2 text-muted">{t("welcome.subtitle")}</p>
|
<p className="mt-2 text-muted">{t("welcome.subtitle")}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||