Compare commits

...
Author SHA1 Message Date
Corfirean 316ef078e8 Merge pull request #233 from Corfirean/release/manager-0.9.16
Manager 0.9.16
2026-11-20 22:08:03 +05:00
ДмитрийandClaude Sonnet 5.5 1974ff54e3 Prepare Manager 0.9.16 with reviewed notes in six languages
Version 0.9.16 (Manager only; no server release). Reviewed notes: the client download now comes from
the community launcher, HD graphics hint and translated Custom Races patch card, companions startup
limit creates the missing ones, weekly world restart, server log auto-cleanup. Translations in ru,
de, fr, es and zh for these five notes and for the 0.9.15 note, which the history test requires.
Bundled server history stays at 0.261115.110; notes of later server releases show in English until
a Manager refreshes and translates them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:57:49 +05:00
Corfirean de3af82e5d Merge pull request #231 from Corfirean/feat/weekly-restart-log-cleanup-on-master
Settings: weekly world restart and server log auto-cleanup
2026-11-20 21:43:38 +05:00
Corfirean 802bde220c Merge pull request #230 from Corfirean/feat/startup-fleet-top-up
Companions: the startup limit creates the missing ones
2026-11-20 21:43:30 +05:00
Corfirean dfe7ac656b Merge pull request #229 from Corfirean/fix/client-download-launcher-on-master
Remove the dead built-in client download; point players to the launcher
2026-11-20 21:43:21 +05:00
Corfirean cee5139879 Merge pull request #232 from Corfirean/fix/changelog-fragment-length
Changelog: shorten the Custom Races 2.0.2 fragment to the 300-character limit
2026-11-20 21:43:12 +05:00
ДмитрийandClaude Sonnet 5.5 1ea2c8318b docs(changelog): shorten the Custom Races 2.0.2 fragment to the 300-character limit
Its body was 375 characters, so `changelog.py check` over the whole directory failed. The title is
unchanged, so the published 0.9.15 note is the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:43:02 +05:00
ДмитрийandClaude Sonnet 5.5 2b7dbf8e1e feat(settings): translations and changelog for weekly restart and log auto-cleanup
The weekly restart schedule and the server log auto-cleanup (previous commit) had strings only in
en and ru and no changelog fragments. Adds de/es/fr/zh for the weekday names, the weekly toggle
and the log settings, and one fragment per change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:37:01 +05:00
Дмитрий 4ff190f6d1 feat(settings): add weekly restart schedule and server log auto-cleanup 2026-11-20 21:34:23 +05:00
ДмитрийandClaude Sonnet 5.5 bff5248591 feat(companions): the startup limit is a fleet size, so missing companions are created
CoaBots.AutoLogin.MaxCount only makes the server log in companions that already exist: with 50
companions and a limit of 300, 50 came online. The Manager now creates the difference.

- coa-core: fleet_shortfall / queue_fleet_top_up queue one durable pending job per realm for
  limit - existing (at most 2000 per job, the most one server command takes). Nothing is queued
  when the fleet is complete or an unfinished job exists for the realm.
- start_server: after the world is up, each realm whose auto-login is on is topped up before its
  pending job runs (shared reconcile_realm_companions helper). If the existing count cannot be
  read, nothing is created.
- Saving the startup settings of a running server tops up right away (new top_up_startup_fleet
  command); a shortfall above 200 asks for confirmation.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:31:32 +05:00
27 changed files with 1067 additions and 103 deletions

No files matched your search

Generated
+4 -4
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]]
name = "coa-core"
version = "0.9.15"
version = "0.9.16"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -621,7 +621,7 @@ dependencies = [
[[package]]
name = "coa-launcher"
version = "0.9.15"
version = "0.9.16"
dependencies = [
"coa-core",
"serde_json",
@@ -644,7 +644,7 @@ dependencies = [
[[package]]
name = "coa-release"
version = "0.9.15"
version = "0.9.16"
dependencies = [
"chrono",
"coa-core",
@@ -653,7 +653,7 @@ dependencies = [
[[package]]
name = "coa-server-manager"
version = "0.9.15"
version = "0.9.16"
dependencies = [
"coa-control-proto",
"coa-core",
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/coa-core", "crates/coa-launcher", "crates/coa-release", "crat
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
[workspace.package]
version = "0.9.15"
version = "0.9.16"
edition = "2021"
license = "AGPL-3.0-only"
@@ -4,4 +4,4 @@ type: changed
audience: players
title: The Custom Races client update brings version 2.0.2
---
Updating the Custom Races client now installs 2.0.2: the retail body model files, the subclass and HD patches, the current CoACustomRace.exe and the newer subclass interface with the Two-Players bar. The 2.0 archives already downloaded are reused, so about 4.4 GB of new files are fetched. Update the Manager before the server: the matching server release needs this version.
Updating the Custom Races client installs 2.0.2, including the retail body models, subclass and HD patches and the Two-Players bar. About 4.4 GB of new files are fetched. Update the Manager before the server.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Clean server logs by hand or automatically when they grow too big
---
Server logging settings show how much the logs take and clean them with one button. Optionally the Manager cleans them above a size you choose; logs the running server uses are kept.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: players
title: The startup limit for companions now creates the ones that are missing
---
With 50 companions and a startup limit of 300, the Manager now creates the missing 250 instead of logging in only 50. Companions that exist are never created again. Up to 2000 are created at a time.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Restart the world every week on a chosen day and time
---
Next to the daily restart, pick a weekday, a time and the in-game countdown in the scheduled restart settings. Existing daily schedules keep working.
+101
View File
@@ -583,6 +583,45 @@ pub fn cancel_pending_job(meta_dir: &Path, realm: &str) -> Result<Option<Compani
Ok(None)
}
/// The most companions a startup fleet can hold (the limit the settings accept).
pub const STARTUP_FLEET_MAX: u32 = 5000;
/// The most companions one creation job asks the server for (a single server command takes at most this many).
pub const FLEET_JOB_MAX: u32 = 2000;
/// Companions still missing so that `limit` of them exist. The startup limit is a fleet size, not an addition: with
/// 50 companions and a limit of 300 only 250 are missing, and with 300 or more nothing is.
pub fn fleet_shortfall(limit: u32, existing: u32) -> u32 {
limit.min(STARTUP_FLEET_MAX).saturating_sub(existing)
}
/// Queue the durable job that creates the companions a realm's startup fleet is missing (at most `FLEET_JOB_MAX`
/// at a time; the rest follows at the next start or save). Returns the new job, or `None` when the fleet is complete
/// or an unfinished job already exists for the realm: that one is carried out instead, because a second job would
/// create the same bots twice.
pub fn queue_fleet_top_up(
meta_dir: &Path,
instance_id: &str,
mode: crate::realms::Mode,
limit: u32,
existing: u32,
) -> Result<Option<CompanionsPendingJob>> {
let missing = fleet_shortfall(limit, existing).min(FLEET_JOB_MAX);
if missing == 0 {
return Ok(None);
}
let realm = mode.name();
if let Some(job) = load_pending_job(meta_dir, realm)? {
if !job.state.is_terminal() {
return Ok(None);
}
}
validate_spawn_request(mode, missing, None, None, None, None)?;
let job = CompanionsPendingJob::new(instance_id, realm, missing, None, None, None, None);
save_pending_job(meta_dir, realm, &job)?;
Ok(Some(job))
}
/// One-time idempotent migration of legacy `companions.pending.json` into `companions.pending.coa.json`.
/// Never creates a duplicate job if `companions.pending.coa.json` already exists.
pub fn migrate_legacy_pending_job(
@@ -1630,3 +1669,65 @@ mod tests {
assert!(validate_spawn_request(Mode::Reborn, 5, Some(60), Some(7), Some(4), None).is_ok());
}
}
#[cfg(test)]
mod fleet_tests {
use super::*;
use crate::realms::Mode;
#[test]
fn the_limit_is_a_fleet_size_not_an_addition() {
assert_eq!(fleet_shortfall(300, 50), 250);
assert_eq!(fleet_shortfall(300, 300), 0);
assert_eq!(fleet_shortfall(300, 450), 0);
assert_eq!(fleet_shortfall(0, 0), 0);
assert_eq!(fleet_shortfall(9000, 0), STARTUP_FLEET_MAX);
}
#[test]
fn only_the_missing_companions_are_queued() {
let dir = tempfile::tempdir().unwrap();
let job = queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 300, 50).unwrap().unwrap();
assert_eq!(job.count, 250);
assert_eq!(job.effective_requested_count(), 250);
assert_eq!(job.realm, "coa");
let saved = load_pending_job(dir.path(), "coa").unwrap().unwrap();
assert_eq!(saved.job_id, job.job_id);
}
#[test]
fn a_complete_fleet_creates_nothing() {
let dir = tempfile::tempdir().unwrap();
assert!(queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 300, 300).unwrap().is_none());
assert!(queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 300, 1000).unwrap().is_none());
assert!(load_pending_job(dir.path(), "coa").unwrap().is_none());
}
#[test]
fn an_unfinished_job_is_not_doubled_but_a_finished_one_is_replaced() {
let dir = tempfile::tempdir().unwrap();
let first = queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 300, 50).unwrap().unwrap();
assert!(queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 400, 50).unwrap().is_none());
assert_eq!(load_pending_job(dir.path(), "coa").unwrap().unwrap().job_id, first.job_id);
cancel_pending_job(dir.path(), "coa").unwrap();
let second = queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 400, 50).unwrap().unwrap();
assert_ne!(second.job_id, first.job_id);
assert_eq!(second.count, 350);
}
#[test]
fn one_job_never_asks_for_more_than_a_server_command_takes() {
let dir = tempfile::tempdir().unwrap();
let job = queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 5000, 0).unwrap().unwrap();
assert_eq!(job.count, FLEET_JOB_MAX);
}
#[test]
fn realms_keep_separate_jobs() {
let dir = tempfile::tempdir().unwrap();
queue_fleet_top_up(dir.path(), "srv", Mode::Coa, 100, 0).unwrap().unwrap();
let reborn = queue_fleet_top_up(dir.path(), "srv", Mode::Reborn, 40, 10).unwrap().unwrap();
assert_eq!(reborn.count, 30);
assert_eq!(load_pending_job(dir.path(), "coa").unwrap().unwrap().count, 100);
}
}
+169 -21
View File
@@ -5,7 +5,7 @@
use std::path::{Path, PathBuf};
use std::time::Duration;
use chrono::{Local, NaiveDateTime, NaiveTime, Timelike};
use chrono::{Datelike, Local, NaiveDateTime, NaiveTime, Timelike};
use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
@@ -20,14 +20,53 @@ const LATE: Duration = Duration::from_secs(15 * 60);
/// A world that has not come back within this time no longer counts as restarting.
const UNDER_WAY_LIMIT: Duration = Duration::from_secs(45 * 60);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Weekday {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
#[default]
Sunday,
}
impl Weekday {
fn to_chrono(self) -> chrono::Weekday {
match self {
Self::Monday => chrono::Weekday::Mon,
Self::Tuesday => chrono::Weekday::Tue,
Self::Wednesday => chrono::Weekday::Wed,
Self::Thursday => chrono::Weekday::Thu,
Self::Friday => chrono::Weekday::Fri,
Self::Saturday => chrono::Weekday::Sat,
Self::Sunday => chrono::Weekday::Sun,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DueRestart {
pub moment: NaiveDateTime,
pub warning_minutes: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(rename_all = "camelCase", default)]
pub struct RestartSchedule {
pub enabled: bool,
/// Local time, `HH:MM`.
pub time: String,
/// The in-game countdown before the restart, in minutes (1-60).
pub warning_minutes: u32,
pub weekly_enabled: bool,
pub weekly_day: Weekday,
/// Local time for weekly restart, `HH:MM`.
pub weekly_time: String,
/// The in-game countdown before the weekly restart, in minutes (1-60).
pub weekly_warning_minutes: u32,
}
impl Default for RestartSchedule {
@@ -36,35 +75,72 @@ impl Default for RestartSchedule {
enabled: false,
time: "05:00".into(),
warning_minutes: 5,
weekly_enabled: false,
weekly_day: Weekday::Sunday,
weekly_time: "05:00".into(),
weekly_warning_minutes: 5,
}
}
}
impl RestartSchedule {
fn at(&self) -> Option<NaiveTime> {
NaiveTime::parse_from_str(self.time.trim(), "%H:%M").ok()
fn parse_time(text: &str) -> Option<NaiveTime> {
NaiveTime::parse_from_str(text.trim(), "%H:%M").ok()
}
fn validate(&self) -> Result<()> {
if self.at().is_none() {
fn validate_entry(time: &str, warning_minutes: u32) -> Result<()> {
if Self::parse_time(time).is_none() {
return Err(Error::Invalid("The restart time must be HH:MM, for example 05:00.".into()));
}
if !(1..=60).contains(&self.warning_minutes) {
if !(1..=60).contains(&warning_minutes) {
return Err(Error::Invalid("The restart warning must be 1 to 60 minutes.".into()));
}
Ok(())
}
/// The scheduled moment of `now`'s day, when a restart is due at `now` for a world started at `started`:
/// the moment has passed by less than [`LATE`] and the world was already running before it.
pub fn due(&self, now: NaiveDateTime, started: NaiveDateTime) -> Option<NaiveDateTime> {
if !self.enabled {
return None;
fn validate(&self) -> Result<()> {
if self.enabled {
Self::validate_entry(&self.time, self.warning_minutes)?;
}
let moment = now.date().and_time(self.at()?);
if self.weekly_enabled {
Self::validate_entry(&self.weekly_time, self.weekly_warning_minutes)?;
}
Ok(())
}
fn due_at(time_str: &str, now: NaiveDateTime, started: NaiveDateTime) -> Option<NaiveDateTime> {
let at = Self::parse_time(time_str)?;
let moment = now.date().and_time(at);
let late = now.signed_duration_since(moment).to_std().ok()?;
(late <= LATE && started < moment).then_some(moment)
}
/// The scheduled moment of `now`'s day, when a daily or weekly restart is due at `now` for a world started at `started`:
/// the moment has passed by less than [`LATE`] and the world was already running before it.
pub fn due_restart(&self, now: NaiveDateTime, started: NaiveDateTime) -> Option<DueRestart> {
if self.weekly_enabled && now.weekday() == self.weekly_day.to_chrono() {
if let Some(moment) = Self::due_at(&self.weekly_time, now, started) {
return Some(DueRestart {
moment,
warning_minutes: self.weekly_warning_minutes,
});
}
}
if self.enabled {
if let Some(moment) = Self::due_at(&self.time, now, started) {
return Some(DueRestart {
moment,
warning_minutes: self.warning_minutes,
});
}
}
None
}
/// The scheduled moment of `now`'s day, when a restart is due at `now` for a world started at `started`.
pub fn due(&self, now: NaiveDateTime, started: NaiveDateTime) -> Option<NaiveDateTime> {
self.due_restart(now, started).map(|d| d.moment)
}
}
/// The folder whose schedule a world follows: an extra world (`<server>/.realms/<name>`) follows its server's.
@@ -84,11 +160,14 @@ pub fn load(root: &Path) -> RestartSchedule {
pub fn save(root: &Path, schedule: &RestartSchedule) -> Result<RestartSchedule> {
let mut schedule = schedule.clone();
schedule.time = schedule.time.trim().to_string();
if schedule.enabled {
schedule.validate()?;
} else if schedule.at().is_none() {
schedule.weekly_time = schedule.weekly_time.trim().to_string();
schedule.validate()?;
if !schedule.enabled && RestartSchedule::parse_time(&schedule.time).is_none() {
schedule.time = RestartSchedule::default().time;
}
if !schedule.weekly_enabled && RestartSchedule::parse_time(&schedule.weekly_time).is_none() {
schedule.weekly_time = RestartSchedule::default().weekly_time;
}
crate::fsx::atomic_write_json(&owner(root).join(FILE), &schedule)?;
Ok(schedule)
}
@@ -127,7 +206,7 @@ mod tests {
#[test]
fn a_restart_is_due_once_after_its_time_for_a_world_that_ran_before_it() {
let s = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 5 };
let s = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 5, ..RestartSchedule::default() };
let started = at("2026-11-14 20:00");
assert_eq!(s.due(at("2026-11-15 04:59"), started), None);
assert_eq!(s.due(at("2026-11-15 05:00"), started), Some(at("2026-11-15 05:00")));
@@ -140,19 +219,88 @@ mod tests {
assert_eq!(off.due(at("2026-11-15 05:00"), started), None);
}
#[test]
fn weekly_restart_triggers_only_on_configured_weekday_and_independently_of_daily() {
// 2026-11-15 is Sunday; 2026-11-16 is Monday.
let s = RestartSchedule {
enabled: false,
weekly_enabled: true,
weekly_day: Weekday::Sunday,
weekly_time: "04:00".into(),
weekly_warning_minutes: 15,
..RestartSchedule::default()
};
let started = at("2026-11-14 20:00");
assert_eq!(s.due_restart(at("2026-11-15 03:59"), started), None);
assert_eq!(
s.due_restart(at("2026-11-15 04:05"), started),
Some(DueRestart { moment: at("2026-11-15 04:00"), warning_minutes: 15 })
);
// Monday does not trigger Sunday's weekly restart.
assert_eq!(s.due_restart(at("2026-11-16 04:05"), started), None);
// Both daily and weekly enabled: each triggers on its own schedule.
let both = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 5, ..s };
assert_eq!(
both.due_restart(at("2026-11-15 04:05"), started),
Some(DueRestart { moment: at("2026-11-15 04:00"), warning_minutes: 15 })
);
assert_eq!(
both.due_restart(at("2026-11-15 05:02"), at("2026-11-15 04:16")),
Some(DueRestart { moment: at("2026-11-15 05:00"), warning_minutes: 5 })
);
}
#[test]
fn schedules_are_validated_and_extra_worlds_follow_their_server() {
let d = tempfile::tempdir().unwrap();
assert_eq!(load(d.path()), RestartSchedule::default());
let bad = RestartSchedule { enabled: true, time: "25:00".into(), warning_minutes: 5 };
let bad = RestartSchedule { enabled: true, time: "25:00".into(), warning_minutes: 5, ..RestartSchedule::default() };
assert!(save(d.path(), &bad).is_err());
let quiet = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 0 };
let quiet = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 0, ..RestartSchedule::default() };
assert!(save(d.path(), &quiet).is_err());
let good = RestartSchedule { enabled: true, time: " 04:30 ".into(), warning_minutes: 10 };
assert_eq!(save(d.path(), &good).unwrap().time, "04:30");
let bad_weekly = RestartSchedule {
weekly_enabled: true,
weekly_time: "99:00".into(),
..RestartSchedule::default()
};
assert!(save(d.path(), &bad_weekly).is_err());
let quiet_weekly = RestartSchedule {
weekly_enabled: true,
weekly_warning_minutes: 61,
..RestartSchedule::default()
};
assert!(save(d.path(), &quiet_weekly).is_err());
let good = RestartSchedule {
enabled: true,
time: " 04:30 ".into(),
warning_minutes: 10,
weekly_enabled: true,
weekly_day: Weekday::Wednesday,
weekly_time: " 03:15 ".into(),
weekly_warning_minutes: 20,
};
let saved = save(d.path(), &good).unwrap();
assert_eq!(saved.time, "04:30");
assert_eq!(saved.weekly_time, "03:15");
assert_eq!(saved.weekly_day, Weekday::Wednesday);
let extra = d.path().join(".realms/secondary");
std::fs::create_dir_all(&extra).unwrap();
assert!(load(&extra).enabled);
assert!(load(&extra).weekly_enabled);
// Legacy schedule JSON without weekly fields loads cleanly with defaults.
std::fs::write(
d.path().join(FILE),
r#"{"enabled":true,"time":"06:00","warningMinutes":10}"#,
)
.unwrap();
let legacy = load(d.path());
assert!(legacy.enabled);
assert_eq!(legacy.time, "06:00");
assert!(!legacy.weekly_enabled);
assert_eq!(legacy.weekly_day, Weekday::Sunday);
assert!(!under_way(d.path()));
mark_under_way(d.path()).unwrap();
assert!(under_way(d.path()));
+17 -3
View File
@@ -174,7 +174,13 @@ fn spawn_relay(root: &Path, launcher: Option<&Path>) -> Result<Proc> {
pub fn watch_world(root: &Path, launcher: Option<&Path>, offset: i32, log: Progress) -> Result<()> {
squid::validate_bots(root)?;
let mut relay: Option<Proc> = None;
let mut last_log_clean = Instant::now();
loop {
if let Some(report) = crate::server_logging::auto_clean_if_needed(root) {
if report.freed_bytes > 0 {
log(&format!("Auto-cleaned server logs ({} MB freed).", report.freed_bytes / (1024 * 1024)));
}
}
let world = spawn_child(root, "world", &root.join("Core/worldserver.exe"), &["-c", "configs/worldserver.conf"], &root.join("Core"), &root.join("Core/Logs/world-console.log"))?;
let started = schedule::now();
let mut requested = false;
@@ -204,8 +210,8 @@ pub fn watch_world(root: &Path, launcher: Option<&Path>, offset: i32, log: Progr
}
if !requested {
let plan = schedule::load(root);
if plan.due(schedule::now(), started).is_some() {
let seconds = plan.warning_minutes * 60;
if let Some(due) = plan.due_restart(schedule::now(), started) {
let seconds = due.warning_minutes * 60;
let asked = Settings::load(root, offset).and_then(|cfg| {
crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password)
.and_then(|mut ra| ra.run(&format!("server restart {seconds}")))
@@ -214,12 +220,20 @@ pub fn watch_world(root: &Path, launcher: Option<&Path>, offset: i32, log: Progr
Ok(_) => {
schedule::mark_under_way(root)?;
requested = true;
log(&format!("Scheduled restart: the world restarts in {} minutes.", plan.warning_minutes));
log(&format!("Scheduled restart: the world restarts in {} minutes.", due.warning_minutes));
}
Err(e) => log(&format!("Scheduled restart could not be requested ({e}); retrying.")),
}
}
}
if last_log_clean.elapsed() >= Duration::from_secs(300) {
last_log_clean = Instant::now();
if let Some(report) = crate::server_logging::auto_clean_if_needed(root) {
if report.freed_bytes > 0 {
log(&format!("Auto-cleaned server logs ({} MB freed).", report.freed_bytes / (1024 * 1024)));
}
}
}
}
std::thread::sleep(Duration::from_secs(2));
};
+265 -1
View File
@@ -1,4 +1,9 @@
use std::{fs, path::Path};
use std::{
fs,
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
use crate::{
config::{parser::ConfFile, Scope},
@@ -6,6 +11,213 @@ use crate::{
fsx,
};
const SETTINGS_FILE: &str = "Settings/log-settings.json";
const DEFAULT_MAX_SIZE_MB: u64 = 500;
const MIN_MAX_SIZE_MB: u64 = 10;
const MAX_MAX_SIZE_MB: u64 = 100_000;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct LogSettings {
pub auto_cleanup: bool,
pub max_size_mb: u64,
}
impl Default for LogSettings {
fn default() -> Self {
Self {
auto_cleanup: false,
max_size_mb: DEFAULT_MAX_SIZE_MB,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CleanLogsReport {
pub freed_bytes: u64,
pub remaining_bytes: u64,
pub deleted_files: u64,
pub skipped_files: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerLoggingView {
pub preset: Option<String>,
pub log_bytes: u64,
pub settings: LogSettings,
}
fn owner(root: &Path) -> PathBuf {
if crate::launcher::settings::is_extra_world(root) {
if let Some(main) = root.parent().and_then(Path::parent) {
return main.to_path_buf();
}
}
root.to_path_buf()
}
pub fn load_settings(root: &Path) -> LogSettings {
let mut settings: LogSettings =
fsx::read_json(&owner(root).join(SETTINGS_FILE)).unwrap_or_default();
if settings.max_size_mb < MIN_MAX_SIZE_MB || settings.max_size_mb > MAX_MAX_SIZE_MB {
settings.max_size_mb = DEFAULT_MAX_SIZE_MB;
}
settings
}
pub fn save_settings(root: &Path, settings: &LogSettings) -> Result<LogSettings> {
let mut settings = settings.clone();
if settings.auto_cleanup {
if !(MIN_MAX_SIZE_MB..=MAX_MAX_SIZE_MB).contains(&settings.max_size_mb) {
return Err(Error::Invalid(format!(
"Log auto-cleanup threshold must be between {MIN_MAX_SIZE_MB} and {MAX_MAX_SIZE_MB} MB."
)));
}
} else if !(MIN_MAX_SIZE_MB..=MAX_MAX_SIZE_MB).contains(&settings.max_size_mb) {
settings.max_size_mb = DEFAULT_MAX_SIZE_MB;
}
fsx::atomic_write_json(&owner(root).join(SETTINGS_FILE), &settings)?;
Ok(settings)
}
pub fn detect_preset(root: &Path) -> Option<String> {
let candidates = [
root.join("Core/configs/worldserver.conf"),
root.join("Settings/worldserver.conf.template"),
];
for path in candidates {
let Ok(bytes) = fs::read(&path) else {
continue;
};
let Ok(conf) = ConfFile::parse_bytes(&bytes) else {
continue;
};
let found = conf
.entries()
.find(|(k, _)| *k == "Logger.root")
.and_then(|(_, value)| {
value
.split(',')
.next()
.map(str::trim)
.and_then(|s| s.parse::<u32>().ok())
});
if let Some(level) = found {
return match level {
0 => Some("off".into()),
2 => Some("errors".into()),
4 => Some("normal".into()),
_ => None,
};
}
}
None
}
fn log_dirs(root: &Path) -> Vec<PathBuf> {
let base = owner(root);
let mut dirs = Vec::new();
for prefix in ["", ".realms/secondary/", ".realms/reborn/"] {
let candidate = base.join(format!("{prefix}Core/Logs"));
if let Ok(checked) = fsx::ensure_within(&base, &candidate) {
if checked.is_dir() {
dirs.push(checked);
}
}
}
dirs
}
fn measure_dir(dir: &Path) -> u64 {
let Ok(entries) = fs::read_dir(dir) else {
return 0;
};
let mut total = 0u64;
for entry in entries.flatten() {
let path = entry.path();
let Ok(meta) = entry.metadata() else {
continue;
};
if meta.is_dir() {
total = total.saturating_add(measure_dir(&path));
} else if meta.is_file() {
total = total.saturating_add(meta.len());
}
}
total
}
pub fn measure_logs(root: &Path) -> u64 {
log_dirs(root)
.into_iter()
.fold(0u64, |acc, dir| acc.saturating_add(measure_dir(&dir)))
}
fn clean_dir(dir: &Path, report: &mut CleanLogsReport, remove_empty_dir: bool) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(meta) = entry.metadata() else {
continue;
};
if meta.is_dir() {
clean_dir(&path, report, true);
} else if meta.is_file() {
let size = meta.len();
match fs::remove_file(&path) {
Ok(()) => {
report.freed_bytes = report.freed_bytes.saturating_add(size);
report.deleted_files = report.deleted_files.saturating_add(1);
}
Err(_) => {
report.remaining_bytes = report.remaining_bytes.saturating_add(size);
report.skipped_files = report.skipped_files.saturating_add(1);
}
}
}
}
if remove_empty_dir {
let _ = fs::remove_dir(dir);
}
}
pub fn clean_logs(root: &Path) -> Result<CleanLogsReport> {
let mut report = CleanLogsReport {
freed_bytes: 0,
remaining_bytes: 0,
deleted_files: 0,
skipped_files: 0,
};
for dir in log_dirs(root) {
clean_dir(&dir, &mut report, false);
}
Ok(report)
}
pub fn auto_clean_if_needed(root: &Path) -> Option<CleanLogsReport> {
let settings = load_settings(root);
if !settings.auto_cleanup {
return None;
}
let limit = settings.max_size_mb.saturating_mul(1024 * 1024);
if measure_logs(root) <= limit {
return None;
}
clean_logs(root).ok()
}
pub fn state(root: &Path) -> ServerLoggingView {
ServerLoggingView {
preset: detect_preset(root),
log_bytes: measure_logs(root),
settings: load_settings(root),
}
}
fn transform(bytes: &[u8], preset: &str) -> Result<String> {
let level = match preset {
"normal" => 4,
@@ -162,4 +374,56 @@ mod tests {
assert_eq!(transform(normal.as_bytes(), "normal").unwrap(), normal);
assert!(transform(original, "unsupported").is_err());
}
#[test]
fn detects_preset_measures_and_cleans_logs_across_realms() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
fs::create_dir_all(root.join("Core/configs")).unwrap();
fs::write(root.join("Core/configs/worldserver.conf"), "Logger.root=4,Console Server\n").unwrap();
assert_eq!(detect_preset(root).as_deref(), Some("normal"));
fs::write(root.join("Core/configs/worldserver.conf"), "Logger.root=0,Console Server\n").unwrap();
assert_eq!(detect_preset(root).as_deref(), Some("off"));
fs::write(root.join("Core/configs/worldserver.conf"), "Logger.root=2,Console Server\n").unwrap();
assert_eq!(detect_preset(root).as_deref(), Some("errors"));
fs::create_dir_all(root.join("Core/Logs/archive")).unwrap();
fs::create_dir_all(root.join(".realms/secondary/Core/Logs")).unwrap();
fs::write(root.join("Core/Logs/Server.log"), vec![b'a'; 1000]).unwrap();
fs::write(root.join("Core/Logs/archive/old.log"), vec![b'b'; 500]).unwrap();
fs::write(root.join(".realms/secondary/Core/Logs/Server.log"), vec![b'c'; 250]).unwrap();
assert_eq!(measure_logs(root), 1750);
let report = clean_logs(root).unwrap();
assert_eq!(report.freed_bytes, 1750);
assert_eq!(report.remaining_bytes, 0);
assert_eq!(report.deleted_files, 3);
assert_eq!(report.skipped_files, 0);
assert_eq!(measure_logs(root), 0);
assert!(!root.join("Core/Logs/archive").exists());
}
#[test]
fn log_settings_validate_and_auto_clean_only_above_threshold() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
assert_eq!(load_settings(root), LogSettings::default());
assert!(save_settings(root, &LogSettings { auto_cleanup: true, max_size_mb: 5 }).is_err());
let saved = save_settings(root, &LogSettings { auto_cleanup: true, max_size_mb: 10 }).unwrap();
assert!(saved.auto_cleanup);
assert_eq!(saved.max_size_mb, 10);
fs::create_dir_all(root.join("Core/Logs")).unwrap();
fs::write(root.join("Core/Logs/Server.log"), vec![b'x'; 1024]).unwrap();
// 1 KB < 10 MB: does not clean.
assert!(auto_clean_if_needed(root).is_none());
assert_eq!(measure_logs(root), 1024);
// Threshold check helper: writing > 10 MB triggers cleanup.
let over = vec![b'y'; 10 * 1024 * 1024 + 1];
fs::write(root.join("Core/Logs/Big.log"), over).unwrap();
let cleaned = auto_clean_if_needed(root).unwrap();
assert!(cleaned.freed_bytes > 10 * 1024 * 1024);
assert_eq!(measure_logs(root), 0);
}
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "coa-server-manager",
"version": "0.9.15",
"version": "0.9.16",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "coa-server-manager",
"version": "0.9.15",
"version": "0.9.16",
"dependencies": {
"@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-dialog": "^2.8.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "coa-server-manager",
"private": true,
"version": "0.9.15",
"version": "0.9.16",
"license": "AGPL-3.0-only",
"type": "module",
"scripts": {
+125 -32
View File
@@ -2,7 +2,7 @@
//! registry; the frontend can never ask the backend to touch an arbitrary path (scan is read-only).
use std::collections::HashSet;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
mod browse_preferences;
@@ -597,6 +597,91 @@ async fn run_verb(
.map_err(Into::into)
}
/// Creates the companions a realm's startup fleet is missing (when its auto-login is on and its world runs) and
/// carries out the realm's pending companion job. Returns how many companions were queued to top the fleet up.
fn reconcile_realm_companions(
root: &Path,
meta: &Path,
instance_id: &str,
mode: coa_core::realms::Mode,
top_up: bool,
) -> Result<u32> {
let target = coa_core::multiworld::resolve_bot_operation_target(root, mode)?;
let mut queued = 0;
if top_up && target.running {
match queue_startup_fleet(root, meta, instance_id, mode, &target.world_root) {
Ok(n) => queued = n,
Err(e) => tracing::warn!("startup fleet of realm {} was not topped up: {e}", mode.name()),
}
}
let r_snap = root.to_path_buf();
let chars_db = target.chars_db;
let r_ra = root.to_path_buf();
coa_core::companions::process_pending_job_with(
meta,
mode,
instance_id,
target.running,
|since_guid| {
let admin_db = coa_core::db::Db::from_repack(&r_snap, coa_core::db::Account::Admin)?;
let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, chars_db);
coa_core::companions::query_bot_db_snapshot(&r_snap, &admin_db, chars_db, since_guid)
},
|delta, job| {
let mut ra = Ra::connect_target(&r_ra, Some(mode))?;
if let Some(lvl) = job.level {
ra.spawn_custom(delta, lvl, job.class_id, job.spec_id, job.build_id.as_deref())
} else {
ra.spawn_bots(delta)
}
},
)?;
Ok(queued)
}
/// Queues the job that creates the companions missing from a realm's startup fleet. The realm's auto-login limit is
/// the fleet size: companions that exist already count, so only the difference is created. Nothing is created when
/// the number of existing companions cannot be read.
fn queue_startup_fleet(
root: &Path,
meta: &Path,
instance_id: &str,
mode: coa_core::realms::Mode,
world_root: &Path,
) -> Result<u32> {
let cfg = config::load(world_root, Scope::Bots)?;
let value = |key: &str| cfg.settings.iter().find(|s| s.meta.key == key).map(|s| s.value.clone());
let on = value("CoaBots.AutoLoginOnStartup").and_then(|v| v.as_bool()).unwrap_or(false);
let limit = value("CoaBots.AutoLogin.MaxCount").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
if !on || limit == 0 {
return Ok(0);
}
let existing = coa_core::population::query_for_realm(root, mode)?.bots_total;
let job = coa_core::companions::queue_fleet_top_up(meta, instance_id, mode, limit, existing)?;
Ok(job.map_or(0, |j| j.count))
}
/// After the startup fleet settings are saved: create the companions the fleet is missing right away when the realm's
/// world is running (otherwise it happens at the next start). Returns how many were queued.
#[tauri::command]
async fn top_up_startup_fleet(
state: State<'_, AppState>,
id: String,
realm: Option<coa_core::realms::Mode>,
) -> std::result::Result<u32, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || {
if coa_core::realms::guard_module(&root, "companions").is_err() {
return Ok(0);
}
let meta = meta_dir(&root)?;
let mode = realm.unwrap_or_else(|| coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default());
reconcile_realm_companions(&root, &meta, &id, mode, true)
})
.await
}
#[tauri::command]
async fn start_server(
state: State<'_, AppState>,
@@ -643,37 +728,8 @@ async fn start_server(
coa_core::realms::Mode::Wildcard,
coa_core::realms::Mode::Reborn,
] {
let target = match coa_core::multiworld::resolve_bot_operation_target(&r, mode) {
Ok(t) => t,
Err(e) => {
tracing::warn!("cannot resolve target for realm {}: {e}", mode.name());
continue;
}
};
let r_snap = r.clone();
let chars_db = target.chars_db;
let r_ra = r.clone();
let res = coa_core::companions::process_pending_job_with(
&meta,
mode,
&instance_id,
target.running,
|since_guid| {
let admin_db = coa_core::db::Db::from_repack(&r_snap, coa_core::db::Account::Admin)?;
let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, chars_db);
coa_core::companions::query_bot_db_snapshot(&r_snap, &admin_db, chars_db, since_guid)
},
|delta, job| {
let mut ra = Ra::connect_target(&r_ra, Some(mode))?;
if let Some(lvl) = job.level {
ra.spawn_custom(delta, lvl, job.class_id, job.spec_id, job.build_id.as_deref())
} else {
ra.spawn_bots(delta)
}
},
);
if let Err(e) = res {
tracing::warn!("pending companions for realm {} failed during reconciliation: {e}", mode.name());
if let Err(e) = reconcile_realm_companions(&r, &meta, &instance_id, mode, true) {
tracing::warn!("companions for realm {} failed during start-up: {e}", mode.name());
}
}
Ok(())
@@ -758,6 +814,15 @@ async fn get_settings(
blocking(move || config::load(&root, scope)).await
}
#[tauri::command]
async fn server_logging_state(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<coa_core::server_logging::ServerLoggingView, UiError> {
let root = path_of(&state, &id)?;
blocking(move || Ok(coa_core::server_logging::state(&root))).await
}
#[tauri::command]
async fn server_logging_preset(
state: State<'_, AppState>,
@@ -772,6 +837,30 @@ async fn server_logging_preset(
}).await
}
#[tauri::command]
async fn server_logging_settings_save(
state: State<'_, AppState>,
id: String,
settings: coa_core::server_logging::LogSettings,
) -> std::result::Result<coa_core::server_logging::ServerLoggingView, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || {
coa_core::server_logging::save_settings(&root, &settings)?;
Ok(coa_core::server_logging::state(&root))
}).await
}
#[tauri::command]
async fn server_logs_clean(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<coa_core::server_logging::CleanLogsReport, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || coa_core::server_logging::clean_logs(&root)).await
}
#[tauri::command]
async fn save_settings(
state: State<'_, AppState>,
@@ -3062,7 +3151,10 @@ pub fn run() {
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_process::init())
.invoke_handler(tauri::generate_handler![
server_logging_state,
server_logging_preset,
server_logging_settings_save,
server_logs_clean,
release_history,
default_install_dir,
game_data_folder,
@@ -3152,6 +3244,7 @@ pub fn run() {
report_targets,
companion_sizes,
add_companions,
top_up_startup_fleet,
get_wildcard_archetypes,
remote_connection,
remote_connect,
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "CoA Server Manager",
"version": "0.9.15",
"version": "0.9.16",
"identifier": "com.coa.servermanager",
"build": {
"beforeDevCommand": "npm run dev",
+35 -5
View File
@@ -52,7 +52,13 @@
"Restart the world every day at a chosen time": "Ежедневный перезапуск мира в выбранное время",
"Switches for the Custom Races V2 subclasses, Hero Races and the /dev menu": "Переключатели подклассов, героических рас и меню /dev из Custom Races V2",
"Companion bots on Wildcard and Warcraft Reborn": "Боты-компаньоны на Wildcard и Warcraft Reborn",
"The Custom Races card tells which characters stay out while races are off": "Карточка Custom Races показывает, какие персонажи не войдут в мир, пока расы выключены"
"The Custom Races card tells which characters stay out while races are off": "Карточка Custom Races показывает, какие персонажи не войдут в мир, пока расы выключены",
"The Custom Races client update brings version 2.0.2": "Обновление клиента Custom Races приносит версию 2.0.2",
"The game client now comes from the community launcher, not from the Manager": "Игровой клиент теперь берётся из лаунчера сообщества, а не из Менеджера",
"Client setup says where to switch HD graphics; Custom Races patch card is translated": "Установка клиента подсказывает, где переключить HD-графику; карточка патча Custom Races переведена",
"Clean server logs by hand or automatically when they grow too big": "Очищайте логи сервера вручную или автоматически, когда они становятся слишком большими",
"The startup limit for companions now creates the ones that are missing": "Лимит запуска компаньонов теперь создаёт недостающих",
"Restart the world every week on a chosen day and time": "Перезапускайте мир каждую неделю в выбранный день и время"
},
"de": {
"Choose Parallel or Global level scaling in module settings": "Parallele oder globale Levelskalierung in den Moduleinstellungen wählen",
@@ -106,7 +112,13 @@
"Restart the world every day at a chosen time": "Die Welt täglich zu einer gewählten Uhrzeit neu starten",
"Switches for the Custom Races V2 subclasses, Hero Races and the /dev menu": "Schalter für die Unterklassen, Heldenvölker und das /dev-Menü von Custom Races V2",
"Companion bots on Wildcard and Warcraft Reborn": "Begleiter-Bots auf Wildcard und Warcraft Reborn",
"The Custom Races card tells which characters stay out while races are off": "Die Custom-Races-Karte zeigt, welche Figuren draußen bleiben, solange die Völker aus sind"
"The Custom Races card tells which characters stay out while races are off": "Die Custom-Races-Karte zeigt, welche Figuren draußen bleiben, solange die Völker aus sind",
"The Custom Races client update brings version 2.0.2": "Das Update des Custom-Races-Clients bringt Version 2.0.2",
"The game client now comes from the community launcher, not from the Manager": "Der Spielclient kommt jetzt vom Community-Launcher und nicht mehr vom Manager",
"Client setup says where to switch HD graphics; Custom Races patch card is translated": "Die Client-Einrichtung sagt, wo man die HD-Grafik umschaltet; die Karte des Custom-Races-Patches ist übersetzt",
"Clean server logs by hand or automatically when they grow too big": "Serverlogs von Hand oder automatisch bereinigen, wenn sie zu groß werden",
"The startup limit for companions now creates the ones that are missing": "Das Startlimit für Begleiter erstellt jetzt die fehlenden",
"Restart the world every week on a chosen day and time": "Die Welt jede Woche an einem gewählten Tag und zu einer gewählten Zeit neu starten"
},
"fr": {
"Choose Parallel or Global level scaling in module settings": "Choisissez une progression parallèle ou globale des niveaux dans les paramètres du module",
@@ -160,7 +172,13 @@
"Restart the world every day at a chosen time": "Redémarrez le monde chaque jour à l'heure choisie",
"Switches for the Custom Races V2 subclasses, Hero Races and the /dev menu": "Interrupteurs pour les sous-classes, races héroïques et le menu /dev de Custom Races V2",
"Companion bots on Wildcard and Warcraft Reborn": "Bots compagnons sur Wildcard et Warcraft Reborn",
"The Custom Races card tells which characters stay out while races are off": "La carte Custom Races indique quels personnages restent hors du monde quand les races sont désactivées"
"The Custom Races card tells which characters stay out while races are off": "La carte Custom Races indique quels personnages restent hors du monde quand les races sont désactivées",
"The Custom Races client update brings version 2.0.2": "La mise à jour du client Custom Races apporte la version 2.0.2",
"The game client now comes from the community launcher, not from the Manager": "Le client du jeu vient désormais du lanceur de la communauté, plus du Manager",
"Client setup says where to switch HD graphics; Custom Races patch card is translated": "La configuration du client indique où changer les graphismes HD ; la carte du patch Custom Races est traduite",
"Clean server logs by hand or automatically when they grow too big": "Nettoyez les journaux du serveur à la main ou automatiquement quand ils deviennent trop gros",
"The startup limit for companions now creates the ones that are missing": "La limite de démarrage des compagnons crée maintenant ceux qui manquent",
"Restart the world every week on a chosen day and time": "Redémarrez le monde chaque semaine au jour et à l’heure choisis"
},
"es": {
"Choose Parallel or Global level scaling in module settings": "Elige escalado de nivel paralelo o global en los ajustes del módulo",
@@ -214,7 +232,13 @@
"Restart the world every day at a chosen time": "Reinicia el mundo cada día a la hora elegida",
"Switches for the Custom Races V2 subclasses, Hero Races and the /dev menu": "Interruptores para las subclases, razas heroicas y el menú /dev de Custom Races V2",
"Companion bots on Wildcard and Warcraft Reborn": "Bots acompañantes en Wildcard y Warcraft Reborn",
"The Custom Races card tells which characters stay out while races are off": "La tarjeta Custom Races indica qué personajes quedan fuera mientras las razas están desactivadas"
"The Custom Races card tells which characters stay out while races are off": "La tarjeta Custom Races indica qué personajes quedan fuera mientras las razas están desactivadas",
"The Custom Races client update brings version 2.0.2": "La actualización del cliente de Custom Races trae la versión 2.0.2",
"The game client now comes from the community launcher, not from the Manager": "El cliente del juego ahora viene del launcher de la comunidad, no del Manager",
"Client setup says where to switch HD graphics; Custom Races patch card is translated": "La configuración del cliente indica dónde cambiar los gráficos HD; la tarjeta del parche de Custom Races está traducida",
"Clean server logs by hand or automatically when they grow too big": "Limpia los registros del servidor a mano o automáticamente cuando crecen demasiado",
"The startup limit for companions now creates the ones that are missing": "El límite de inicio de los compañeros ahora crea los que faltan",
"Restart the world every week on a chosen day and time": "Reinicia el mundo cada semana en el día y la hora elegidos"
},
"zh": {
"Choose Parallel or Global level scaling in module settings": "在模块设置中选择并行或全局等级缩放",
@@ -268,7 +292,13 @@
"Restart the world every day at a chosen time": "每天在选定时间重启世界",
"Switches for the Custom Races V2 subclasses, Hero Races and the /dev menu": "Custom Races V2 副职业、英雄种族和 /dev 菜单的开关",
"Companion bots on Wildcard and Warcraft Reborn": "Wildcard 和 Warcraft Reborn 上的伙伴机器人",
"The Custom Races card tells which characters stay out while races are off": "Custom Races 卡片会显示种族关闭时哪些角色无法进入世界"
"The Custom Races card tells which characters stay out while races are off": "Custom Races 卡片会显示种族关闭时哪些角色无法进入世界",
"The Custom Races client update brings version 2.0.2": "Custom Races 客户端更新带来 2.0.2 版本",
"The game client now comes from the community launcher, not from the Manager": "游戏客户端现在来自社区启动器,而不是 Manager",
"Client setup says where to switch HD graphics; Custom Races patch card is translated": "客户端设置会说明在哪里切换 HD 画质;Custom Races 补丁卡片已翻译",
"Clean server logs by hand or automatically when they grow too big": "手动清理服务器日志,或在日志过大时自动清理",
"The startup limit for companions now creates the ones that are missing": "同伴的启动上限现在会创建缺少的同伴",
"Restart the world every week on a chosen day and time": "每周在选定的日期和时间重启世界"
}
},
"server": {
+3 -1
View File
@@ -45,7 +45,8 @@ export {};
if(cmd==="addons_list"||cmd==="addons_install"||cmd==="addons_remove"){const w=window as any;w.__addons=w.__addons??{dragonui:"old"};if(cmd==="addons_install"){await new Promise(r=>setTimeout(r,700));w.__addons[args.addon]="new";}if(cmd==="addons_remove")delete w.__addons[args.addon];return addonCatalog.addons.map((a:any)=>({id:a.id,name:a.name,description:a.description,author:a.author,license:a.license,needs:a.needs??null,repo:a.repo,size:a.files.reduce((s:number,f:any)=>s+f.size,0),installed:a.id in w.__addons,updateAvailable:w.__addons[a.id]==="old",foreignFolders:a.id==="coacombat"&&!(a.id in w.__addons)?["CoACombat"]:[],bundled:null as string|null})).concat([{id:"coa-dev-menu",name:"CoA Dev Menu",description:{en:"The in-game /dev editor for game masters.",ru:"Внутриигровой редактор /dev для гейм-мастеров. Ставится вместе с клиентским патчем Custom Races V2 и включается вместе с ним."},author:"ilusixn",license:"see repository",needs:null,repo:"https://github.com/ilusixn/ilusixn-dev-menu",size:0,installed:true,updateAvailable:false,foreignFolders:[],bundled:"custom-races"}]);}
if(cmd==="custom_race_characters") return {players:2,companionBots:14,squidBots:0};
if(cmd==="purge_custom_race_bots"){await new Promise(r=>setTimeout(r,500));return 14;}
if(cmd==="restart_schedule"||cmd==="restart_schedule_save"){const w=window as any;w.__sched=w.__sched??{enabled:false,time:"05:00",warningMinutes:5};if(cmd==="restart_schedule_save"){const s=args.schedule;if(s.enabled&&!/^([01]\d|2[0-3]):[0-5]\d$/.test(s.time))throw new Error("The restart time must be HH:MM, for example 05:00.");w.__sched={...s};}return {schedule:w.__sched,supported:true};}
if(cmd==="restart_schedule"||cmd==="restart_schedule_save"){const w=window as any;w.__sched=w.__sched??{enabled:false,time:"05:00",warningMinutes:5,weeklyEnabled:false,weeklyDay:"sunday",weeklyTime:"05:00",weeklyWarningMinutes:5};if(cmd==="restart_schedule_save"){const s=args.schedule;if(s.enabled&&!/^([01]\d|2[0-3]):[0-5]\d$/.test(s.time))throw new Error("The restart time must be HH:MM, for example 05:00.");if(s.weeklyEnabled&&!/^([01]\d|2[0-3]):[0-5]\d$/.test(s.weeklyTime))throw new Error("The restart time must be HH:MM, for example 05:00.");w.__sched={...s};}return {schedule:w.__sched,supported:true};}
if(cmd==="server_logging_state"||cmd==="server_logging_preset"||cmd==="server_logging_settings_save"||cmd==="server_logs_clean"){const w=window as any;w.__logs=w.__logs??{preset:"normal",logBytes:148*1024*1024,settings:{autoCleanup:false,maxSizeMb:500}};if(cmd==="server_logging_preset"){w.__logs.preset=args.preset;return;}if(cmd==="server_logging_settings_save"){w.__logs.settings={...args.settings};}if(cmd==="server_logs_clean"){const freed=w.__logs.logBytes;w.__logs.logBytes=0;return {freedBytes:freed,remainingBytes:0,deletedFiles:freed>0?3:0,skippedFiles:0};}return w.__logs;}
if(cmd==="mysql_custom"||cmd==="mysql_custom_save"){const w=window as any;if(cmd==="mysql_custom_save")w.__my=args.text;const text:string=w.__my??"";const applied=text.split("\n").map((l:string)=>l.trim()).filter((l:string)=>l&&!l.startsWith("#")&&!/^(port|datadir|basedir|bind[-_]address)\b/i.test(l)).map((l:string)=>l+"\n").join("");return {text,applied};}
if(cmd==="realm_names"||cmd==="realm_rename"){const w=window as any;w.__rn=w.__rn??{};const defs:[number,string][]=[[1,"Conquest of Azeroth"],[2,"Wildcard"]];if(cmd==="realm_rename"){await new Promise(r=>setTimeout(r,300));const n=(args.name??"").trim();if(n.length>32||n.includes('"'))throw new Error("The realm name can have at most 32 characters.");if(n)w.__rn[args.realmId]=n;else delete w.__rn[args.realmId];}return defs.map(([id,d])=>({id,name:w.__rn[id]??d,defaultName:d,custom:id in w.__rn}));}
if(cmd==="realm_profiles") return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:simultaneous&&running,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:withReborn&&running};
@@ -69,6 +70,7 @@ 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==="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==="top_up_startup_fleet") return 0;
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==="check_update") return {from_version:(window as any).__updated?"0.261028.83":"0.261026.81",to_version:"0.261028.83",items:[],conflicts:[],migrations:5,pending_migrations:(window as any).__updated?0:5,download_bytes:6000000};
if(cmd==="apply_update"){const w=window as any;for(let i=1;i<=8;i++){await new Promise((r: any)=>setTimeout(r,700));(w.__handlers?.["update-progress"]??[]).forEach((h: any)=>h({event:"update-progress",id:1,payload:{step:i<4?"Downloading the update":i<7?"Applying the update":"Finishing",percent:i*12}}));}(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261028.83"},migrations:null};}
+18
View File
@@ -597,6 +597,8 @@ const de: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Wie viele sich anmelden",
"comp.startSave": "Speichern",
"comp.startSaved": "Gespeichert. Gilt ab dem nächsten Serverstart.",
"comp.startTopUp": "Gespeichert. {n} weitere Begleiter werden erstellt, damit {max} existieren; die übrigen gibt es schon.",
"comp.startTopUpConfirm": "{n} weitere Begleiter erstellen, damit {max} existieren? Vorhandene werden nicht erneut erstellt.",
"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.",
@@ -755,6 +757,15 @@ const de: Partial<Record<keyof typeof en, string>> = {
"mysql.applied": "Angewandte Optionen: {count}",
"sched.title": "Geplanter Neustart",
"sched.enable": "Die Welt jeden Tag neu starten",
"sched.weeklyEnable": "Die Welt jede Woche neu starten",
"sched.day": "Tag",
"sched.days.monday": "Montag",
"sched.days.tuesday": "Dienstag",
"sched.days.wednesday": "Mittwoch",
"sched.days.thursday": "Donnerstag",
"sched.days.friday": "Freitag",
"sched.days.saturday": "Samstag",
"sched.days.sunday": "Sonntag",
"sched.time": "Uhrzeit",
"sched.warning": "Vorwarnung (Minuten)",
"sched.hint": "Die Welt startet zu dieser Uhrzeit dieses Computers neu, mit einem Countdown im Spielchat; die Datenbank läuft weiter, Spieler melden sich danach wieder an. Ein laufender Server übernimmt die neue Zeit innerhalb einer Minute.",
@@ -1099,6 +1110,13 @@ const de: Partial<Record<keyof typeof en, string>> = {
"serverLogs.errors": "Nur Fehler",
"serverLogs.off": "Aus",
"serverLogs.saved": "Gespeichert. Zum Anwenden den Server neu starten.",
"serverLogs.autoClean": "Serverlogs nach Größe automatisch bereinigen",
"serverLogs.maxSize": "Max. Größe",
"serverLogs.autoCleanHint": "Löscht alte Logdateien, wenn Core/Logs diese Größe überschreitet (geprüft beim Start der Welt und regelmäßig während des Betriebs).",
"serverLogs.currentSize": "Aktuelle Loggröße: {size}",
"serverLogs.cleanNow": "Logs bereinigen ({size})",
"serverLogs.cleaned": "{freed} an Logs bereinigt.",
"serverLogs.skippedInUse": "{remaining} werden vom laufenden Server verwendet und konnten nicht entfernt werden.",
"mod.requiresSquid": "Aktivieren Sie SQUID-Bots, um Dungeon Clear zu verwenden.",
};
+18
View File
@@ -64,6 +64,15 @@ const en = {
"mysql.applied": "Options applied: {count}",
"sched.title": "Scheduled restart",
"sched.enable": "Restart the world every day",
"sched.weeklyEnable": "Restart the world every week",
"sched.day": "Day",
"sched.days.monday": "Monday",
"sched.days.tuesday": "Tuesday",
"sched.days.wednesday": "Wednesday",
"sched.days.thursday": "Thursday",
"sched.days.friday": "Friday",
"sched.days.saturday": "Saturday",
"sched.days.sunday": "Sunday",
"sched.time": "Time",
"sched.warning": "Warning (minutes)",
"sched.hint": "The world restarts at this time of this computer with a countdown in the game chat; the database keeps running and players log in again after it. A minute after saving, the running server follows the new time.",
@@ -696,6 +705,8 @@ const en = {
"comp.startCount": "How many log in",
"comp.startSave": "Save",
"comp.startSaved": "Saved. It applies the next time the server starts.",
"comp.startTopUp": "Saved. Creating {n} more companions so that {max} exist; the others already exist.",
"comp.startTopUpConfirm": "Create {n} more companions so that {max} exist? Companions that already exist are not created again.",
"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.",
@@ -1309,6 +1320,13 @@ const en = {
"serverLogs.errors": "Errors only",
"serverLogs.off": "Off",
"serverLogs.saved": "Saved. Restart the server to apply.",
"serverLogs.autoClean": "Auto-clean server logs by size",
"serverLogs.maxSize": "Max size",
"serverLogs.autoCleanHint": "Clears old log files when Core/Logs exceeds this size (checked on world start and periodically while running).",
"serverLogs.currentSize": "Current log size: {size}",
"serverLogs.cleanNow": "Clean logs ({size})",
"serverLogs.cleaned": "Cleaned {freed} of logs.",
"serverLogs.skippedInUse": "{remaining} in use by the running server could not be removed.",
"mod.requiresSquid": "Enable SQUID bots to use Dungeon Clear.",
} as const;
+18
View File
@@ -597,6 +597,8 @@ const es: Partial<Record<keyof typeof en, string>> = {
"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.startTopUp": "Guardado. Se crean {n} compañeros más para que existan {max}; los demás ya existen.",
"comp.startTopUpConfirm": "¿Crear {n} compañeros más para que existan {max}? Los que ya existen no se crean de nuevo.",
"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.",
@@ -755,6 +757,15 @@ const es: Partial<Record<keyof typeof en, string>> = {
"mysql.applied": "Opciones aplicadas: {count}",
"sched.title": "Reinicio programado",
"sched.enable": "Reiniciar el mundo cada día",
"sched.weeklyEnable": "Reiniciar el mundo cada semana",
"sched.day": "Día",
"sched.days.monday": "Lunes",
"sched.days.tuesday": "Martes",
"sched.days.wednesday": "Miércoles",
"sched.days.thursday": "Jueves",
"sched.days.friday": "Viernes",
"sched.days.saturday": "Sábado",
"sched.days.sunday": "Domingo",
"sched.time": "Hora",
"sched.warning": "Aviso (minutos)",
"sched.hint": "El mundo se reinicia a esta hora de este ordenador con una cuenta atrás en el chat del juego; la base de datos sigue en marcha y los jugadores vuelven a entrar después. Un servidor en marcha sigue la nueva hora en menos de un minuto.",
@@ -1099,6 +1110,13 @@ const es: Partial<Record<keyof typeof en, string>> = {
"serverLogs.errors": "Solo errores",
"serverLogs.off": "Desactivados",
"serverLogs.saved": "Guardado. Reinicia el servidor para aplicar los cambios.",
"serverLogs.autoClean": "Limpiar automáticamente los registros del servidor por tamaño",
"serverLogs.maxSize": "Tamaño máx.",
"serverLogs.autoCleanHint": "Borra los archivos de registro antiguos cuando Core/Logs supera este tamaño (se comprueba al iniciar el mundo y periódicamente mientras funciona).",
"serverLogs.currentSize": "Tamaño actual de los registros: {size}",
"serverLogs.cleanNow": "Limpiar registros ({size})",
"serverLogs.cleaned": "Se limpiaron {freed} de registros.",
"serverLogs.skippedInUse": "{remaining} están en uso por el servidor en marcha y no se pudieron eliminar.",
"mod.requiresSquid": "Activa los bots SQUID para usar Dungeon Clear.",
};
+18
View File
@@ -597,6 +597,8 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Combien se connectent",
"comp.startSave": "Enregistrer",
"comp.startSaved": "Enregistré. S’applique au prochain démarrage du serveur.",
"comp.startTopUp": "Enregistré. {n} compagnons de plus sont créés pour qu’il y en ait {max} ; les autres existent déjà.",
"comp.startTopUpConfirm": "Créer {n} compagnons de plus pour qu’il y en ait {max} ? Ceux qui existent déjà ne sont pas recréés.",
"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.",
@@ -755,6 +757,15 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"mysql.applied": "Options appliquées : {count}",
"sched.title": "Redémarrage planifié",
"sched.enable": "Redémarrer le monde chaque jour",
"sched.weeklyEnable": "Redémarrer le monde chaque semaine",
"sched.day": "Jour",
"sched.days.monday": "Lundi",
"sched.days.tuesday": "Mardi",
"sched.days.wednesday": "Mercredi",
"sched.days.thursday": "Jeudi",
"sched.days.friday": "Vendredi",
"sched.days.saturday": "Samedi",
"sched.days.sunday": "Dimanche",
"sched.time": "Heure",
"sched.warning": "Avertissement (minutes)",
"sched.hint": "Le monde redémarre à cette heure de cet ordinateur avec un compte à rebours dans le chat du jeu ; la base de données continue de tourner et les joueurs se reconnectent ensuite. Un serveur en marche suit la nouvelle heure en moins d'une minute.",
@@ -1099,6 +1110,13 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"serverLogs.errors": "Erreurs uniquement",
"serverLogs.off": "Désactivés",
"serverLogs.saved": "Enregistré. Redémarrez le serveur pour appliquer.",
"serverLogs.autoClean": "Nettoyer automatiquement les journaux du serveur selon leur taille",
"serverLogs.maxSize": "Taille max.",
"serverLogs.autoCleanHint": "Supprime les anciens fichiers journaux quand Core/Logs dépasse cette taille (vérifié au démarrage du monde et périodiquement pendant son fonctionnement).",
"serverLogs.currentSize": "Taille actuelle des journaux : {size}",
"serverLogs.cleanNow": "Nettoyer les journaux ({size})",
"serverLogs.cleaned": "{freed} de journaux nettoyés.",
"serverLogs.skippedInUse": "{remaining} sont utilisés par le serveur en cours et n’ont pas pu être supprimés.",
"mod.requiresSquid": "Activez les bots SQUID pour utiliser Dungeon Clear.",
};
+18
View File
@@ -67,6 +67,15 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"mysql.applied": "Применяется параметров: {count}",
"sched.title": "Перезапуск по расписанию",
"sched.enable": "Перезапускать мир каждый день",
"sched.weeklyEnable": "Перезапускать мир каждую неделю",
"sched.day": "День",
"sched.days.monday": "Понедельник",
"sched.days.tuesday": "Вторник",
"sched.days.wednesday": "Среда",
"sched.days.thursday": "Четверг",
"sched.days.friday": "Пятница",
"sched.days.saturday": "Суббота",
"sched.days.sunday": "Воскресенье",
"sched.time": "Время",
"sched.warning": "Предупреждение (минуты)",
"sched.hint": "Мир перезапускается в это время этого компьютера, с обратным отсчётом в игровом чате; база данных продолжает работать, игроки заходят снова после перезапуска. Работающий сервер подхватывает новое время в течение минуты.",
@@ -679,6 +688,8 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Сколько входит",
"comp.startSave": "Сохранить",
"comp.startSaved": "Сохранено. Вступит в силу при следующем запуске сервера.",
"comp.startTopUp": "Сохранено. Создаётся ещё {n} компаньонов, чтобы их стало {max}; остальные уже есть.",
"comp.startTopUpConfirm": "Создать ещё {n} компаньонов, чтобы их стало {max}? Уже существующие заново не создаются.",
"comp.startHint": "Боты, которые не входят, остаются сохранёнными, их можно вывести в сеть позже.",
"comp.startInvalid": "Введите целое число от 0 до 5000.",
@@ -1292,6 +1303,13 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"serverLogs.errors": "Только ошибки",
"serverLogs.off": "Выключены",
"serverLogs.saved": "Сохранено. Перезапустите сервер для применения.",
"serverLogs.autoClean": "Автоочистка логов сервера по размеру",
"serverLogs.maxSize": "Макс. размер",
"serverLogs.autoCleanHint": "Очищает старые файлы логов при превышении порога в Core/Logs (проверяется при запуске мира и периодически во время работы).",
"serverLogs.currentSize": "Текущий размер логов: {size}",
"serverLogs.cleanNow": "Очистить логи ({size})",
"serverLogs.cleaned": "Очищено логов: {freed}.",
"serverLogs.skippedInUse": "{remaining} заняты работающим сервером и не были удалены.",
"mod.requiresSquid": "Для Dungeon Clear сначала включите SQUID bots.",
};
+18
View File
@@ -65,6 +65,15 @@ const zh = {
"mysql.applied": "生效的选项:{count}",
"sched.title": "定时重启",
"sched.enable": "每天重启世界",
"sched.weeklyEnable": "每周重启世界",
"sched.day": "星期",
"sched.days.monday": "星期一",
"sched.days.tuesday": "星期二",
"sched.days.wednesday": "星期三",
"sched.days.thursday": "星期四",
"sched.days.friday": "星期五",
"sched.days.saturday": "星期六",
"sched.days.sunday": "星期日",
"sched.time": "时间",
"sched.warning": "提前警告(分钟)",
"sched.hint": "世界会在本机的这个时间重启,并在游戏聊天中倒计时;数据库保持运行,玩家在重启后重新登录。正在运行的服务器会在一分钟内采用新时间。",
@@ -650,6 +659,8 @@ const zh = {
"comp.startCount": "自动登录随从数量",
"comp.startSave": "保存",
"comp.startSaved": "已保存。将在下次服务器启动时生效。",
"comp.startTopUp": "已保存。正在再创建 {n} 个同伴,使总数达到 {max};其余已存在。",
"comp.startTopUpConfirm": "再创建 {n} 个同伴,使总数达到 {max}?已存在的不会重复创建。",
"comp.startHint": "未登录的随从仍保留在数据库中,随时可在需要时手动调出上线。",
"comp.startInvalid": "请输入 0 到 5000 之间的整数。",
@@ -1101,6 +1112,13 @@ const zh = {
"serverLogs.errors": "仅错误",
"serverLogs.off": "关闭",
"serverLogs.saved": "已保存。重启服务器后生效。",
"serverLogs.autoClean": "按大小自动清理服务器日志",
"serverLogs.maxSize": "最大大小",
"serverLogs.autoCleanHint": "当 Core/Logs 超过此大小时清理旧日志文件(在世界启动时和运行期间定期检查)。",
"serverLogs.currentSize": "当前日志大小:{size}",
"serverLogs.cleanNow": "清理日志({size})",
"serverLogs.cleaned": "已清理 {freed} 日志。",
"serverLogs.skippedInUse": "{remaining} 正被运行中的服务器占用,无法删除。",
"mod.requiresSquid": "请先启用 SQUID 机器人,再使用 Dungeon Clear。",
} as const;
+18 -1
View File
@@ -60,8 +60,20 @@ export interface StatusView {
export type RealmMode = "coa" | "wildcard" | "reborn";
export interface CustomRaceCharacters { players: number; companionBots: number; squidBots: number }
export interface AddonView { id: string; name: string; description: Record<string, string>; author: string; license: string; needs: string | null; repo: string; size: number; installed: boolean; updateAvailable: boolean; foreignFolders: string[]; bundled?: string | null }
export interface RestartSchedule { enabled: boolean; time: string; warningMinutes: number }
export type Weekday = "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday";
export interface RestartSchedule {
enabled: boolean;
time: string;
warningMinutes: number;
weeklyEnabled: boolean;
weeklyDay: Weekday;
weeklyTime: string;
weeklyWarningMinutes: number;
}
export interface RestartScheduleView { schedule: RestartSchedule; supported: boolean }
export interface LogSettings { autoCleanup: boolean; maxSizeMb: number }
export interface CleanLogsReport { freedBytes: number; remainingBytes: number; deletedFiles: number; skippedFiles: number }
export interface ServerLoggingView { preset: "normal" | "errors" | "off" | null; logBytes: number; settings: LogSettings }
export interface CustomMysql { text: string; applied: string }
export interface RealmName { id: number; name: string; defaultName: string; custom: boolean }
export interface RealmProfiles { active: RealmMode; wildcard_created: boolean; reborn_created: boolean; reborn_supported: boolean; supported: boolean; recovery_pending: boolean; simultaneous: boolean; secondary_world_port: number | null; secondary_running: boolean; with_reborn: boolean; reborn_world_port: number | null; reborn_running: boolean }
@@ -502,7 +514,10 @@ export const api = {
forceStop: (id: string) => invoke<DriverOutcome>("force_stop_server", { id }),
stop: (id: string) => invoke<DriverOutcome>("stop_server", { id }),
settings: (id: string, scope: Scope) => invoke<SettingsView>("get_settings", { id, scope }),
serverLoggingState: (id: string) => invoke<ServerLoggingView>("server_logging_state", { id }),
serverLoggingPreset: (id: string, preset: "normal" | "errors" | "off") => invoke<void>("server_logging_preset", { id, preset }),
serverLoggingSettingsSave: (id: string, settings: LogSettings) => invoke<ServerLoggingView>("server_logging_settings_save", { id, settings }),
serverLogsClean: (id: string) => invoke<CleanLogsReport>("server_logs_clean", { id }),
save: (id: string, scope: Scope, changes: Record<string, JsonValue>) => invoke<SaveReport>("save_settings", { id, scope, changes }),
presets: (scope: Scope) => invoke<PresetInfo[]>("list_presets", { scope }),
backups: (id: string) => invoke<RecoveryPoint[]>("list_backups", { id }),
@@ -556,6 +571,8 @@ export const api = {
invoke<{ txn: UpdateTxn; preexisting_character_count?: number }>("apply_update", { id, source: source ?? null, resolutions }),
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }),
/** Creates the companions the startup fleet is missing (the limit is a fleet size). Returns how many were queued. */
topUpStartupFleet: (id: string, realm?: RealmMode) => invoke<number>("top_up_startup_fleet", { id, realm: realm ?? null }),
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 }),
+9 -2
View File
@@ -305,11 +305,18 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
setError(null);
setStartNote(null);
try {
// The limit is a fleet size: companions that exist count, only the missing ones are created.
const missing = autoOn && running && isViewingActiveRealm && pop ? Math.max(0, maxNum - pop.bots_total) : 0;
if (missing > 200 && !window.confirm(t("comp.startTopUpConfirm", { n: Math.min(missing, 2000), max: maxNum }))) {
setStartBusy(false);
return;
}
await api.save(serverId, "bots", {
"CoaBots.AutoLoginOnStartup": autoOn,
"CoaBots.AutoLogin.MaxCount": maxNum,
});
setStartNote(t("comp.startSaved"));
const queued = autoOn && running ? await api.topUpStartupFleet(serverId, activeServerRealm) : 0;
setStartNote(queued > 0 ? t("comp.startTopUp", { n: queued, max: maxNum }) : t("comp.startSaved"));
} catch (e) {
setError(asUiError(e));
} finally {
@@ -781,7 +788,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
Persistent Startup Fleet
</h3>
<p className="text-xs text-muted">
Configure how many bots automatically log into the world whenever the server launches.
The server keeps this many companions. At every start the ones that exist log in, and only the missing ones are created.
</p>
<div className="flex flex-wrap items-center gap-4 text-sm">
+42 -5
View File
@@ -1,14 +1,25 @@
import { useEffect, useState } from "react";
import { api, asUiError, type RestartSchedule } from "@/lib/api";
import { api, asUiError, type RestartSchedule, type Weekday } from "@/lib/api";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useT } from "@/i18n";
/** A daily world restart at a chosen local time, with an in-game countdown (#202). */
const WEEKDAYS: Weekday[] = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
const DEFAULT_SCHEDULE: RestartSchedule = {
enabled: false,
time: "05:00",
warningMinutes: 5,
weeklyEnabled: false,
weeklyDay: "sunday",
weeklyTime: "05:00",
weeklyWarningMinutes: 5,
};
/** Daily and weekly world restarts at chosen local times, with an in-game countdown (#202). */
export function RestartScheduleSettings({ serverId }: { serverId: string }) {
const t = useT();
const [saved, setSaved] = useState<RestartSchedule | null>(null);
const [draft, setDraft] = useState<RestartSchedule>({ enabled: false, time: "05:00", warningMinutes: 5 });
const [draft, setDraft] = useState<RestartSchedule>(DEFAULT_SCHEDULE);
const [supported, setSupported] = useState(true);
const [busy, setBusy] = useState(false);
const [done, setDone] = useState(false);
@@ -29,6 +40,8 @@ export function RestartScheduleSettings({ serverId }: { serverId: string }) {
const changed = !!saved && JSON.stringify(saved) !== JSON.stringify(draft);
const minutesOk = Number.isInteger(draft.warningMinutes) && draft.warningMinutes >= 1 && draft.warningMinutes <= 60;
const weeklyMinutesOk = Number.isInteger(draft.weeklyWarningMinutes) && draft.weeklyWarningMinutes >= 1 && draft.weeklyWarningMinutes <= 60;
const valid = (!draft.enabled || minutesOk) && (!draft.weeklyEnabled || weeklyMinutesOk);
const input = "rounded border border-line bg-bg px-2 py-1 text-sm text-ink outline-none focus:border-gold";
return <Card className="mt-6 p-6" aria-busy={busy}>
<h2 className="font-semibold">{t("sched.title")}</h2>
@@ -46,10 +59,34 @@ export function RestartScheduleSettings({ serverId }: { serverId: string }) {
<input type="number" min={1} max={60} step={1} className={`${input} w-20`} value={draft.warningMinutes} disabled={busy || !draft.enabled} onChange={e => { setDraft(d => ({ ...d, warningMinutes: Number(e.target.value) })); setDone(false); }} />
</label>
</div>
<p className="mt-2 text-sm text-muted">{t("sched.hint")}</p>
<div className="mt-4 border-t border-line pt-4">
<label className="flex cursor-pointer items-center gap-3">
<input type="checkbox" className="h-4 w-4 accent-[#c9a24a]" checked={draft.weeklyEnabled} disabled={busy || !saved} onChange={e => { setDraft(d => ({ ...d, weeklyEnabled: e.target.checked })); setDone(false); }} />
<span className="text-sm font-medium">{t("sched.weeklyEnable")}</span>
</label>
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm">
<label className="flex items-center gap-2">
<span>{t("sched.day")}</span>
<select className={input} value={draft.weeklyDay} disabled={busy || !draft.weeklyEnabled} onChange={e => { setDraft(d => ({ ...d, weeklyDay: e.target.value as Weekday })); setDone(false); }}>
{WEEKDAYS.map(day => <option key={day} value={day}>{t(`sched.days.${day}`)}</option>)}
</select>
</label>
<label className="flex items-center gap-2">
<span>{t("sched.time")}</span>
<input type="time" className={input} value={draft.weeklyTime} disabled={busy || !draft.weeklyEnabled} onChange={e => { setDraft(d => ({ ...d, weeklyTime: e.target.value })); setDone(false); }} />
</label>
<label className="flex items-center gap-2">
<span>{t("sched.warning")}</span>
<input type="number" min={1} max={60} step={1} className={`${input} w-20`} value={draft.weeklyWarningMinutes} disabled={busy || !draft.weeklyEnabled} onChange={e => { setDraft(d => ({ ...d, weeklyWarningMinutes: Number(e.target.value) })); setDone(false); }} />
</label>
</div>
</div>
<p className="mt-3 text-sm text-muted">{t("sched.hint")}</p>
{!supported && <p className="mt-2 text-sm text-warn">{t("sched.unsupported")}</p>}
<div className="mt-3 flex items-center gap-3">
<Button size="sm" disabled={busy || !changed || (draft.enabled && !minutesOk)} onClick={() => void save()}>{t("sched.save")}</Button>
<Button size="sm" disabled={busy || !changed || !valid} onClick={() => void save()}>{t("sched.save")}</Button>
{done && <span className="text-xs text-muted">{t("sched.saved")}</span>}
</div>
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
+138 -9
View File
@@ -1,26 +1,155 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import { Card } from "@/components/ui/card";
import { api, asUiError } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { api, asUiError, type CleanLogsReport, type LogSettings, type ServerLoggingView } from "@/lib/api";
import { formatBytes } from "@/lib/utils";
import { useT } from "@/i18n";
const DEFAULT_LOG_SETTINGS: LogSettings = { autoCleanup: false, maxSizeMb: 500 };
export function ServerLoggingSettings({ serverId }: { serverId: string }) {
const t = useT();
const [view, setView] = useState<ServerLoggingView | null>(null);
const [draft, setDraft] = useState<LogSettings>(DEFAULT_LOG_SETTINGS);
const [busy, setBusy] = useState(false);
const [saved, setSaved] = useState(false);
const [autoSaved, setAutoSaved] = useState(false);
const [cleanReport, setCleanReport] = useState<CleanLogsReport | null>(null);
const [error, setError] = useState("");
async function apply(preset: "normal" | "errors" | "off") {
setBusy(true); setSaved(false); setError("");
try { await api.serverLoggingPreset(serverId, preset); setSaved(true); }
catch (error) { setError(asUiError(error).technical); }
finally { setBusy(false); }
useEffect(() => {
let alive = true;
void api.serverLoggingState(serverId)
.then(v => {
if (!alive) return;
setView(v);
setDraft(v.settings);
})
.catch(err => {
if (alive) setError(asUiError(err).technical);
});
return () => { alive = false; };
}, [serverId]);
async function refreshState() {
const v = await api.serverLoggingState(serverId);
setView(v);
setDraft(v.settings);
}
return <Card className="mt-6 p-6">
async function apply(preset: "normal" | "errors" | "off") {
setBusy(true); setSaved(false); setAutoSaved(false); setCleanReport(null); setError("");
try {
await api.serverLoggingPreset(serverId, preset);
await refreshState();
setSaved(true);
} catch (err) {
setError(asUiError(err).technical);
} finally {
setBusy(false);
}
}
async function saveAutoCleanup() {
setBusy(true); setSaved(false); setAutoSaved(false); setCleanReport(null); setError("");
try {
const v = await api.serverLoggingSettingsSave(serverId, draft);
setView(v);
setDraft(v.settings);
setAutoSaved(true);
} catch (err) {
setError(asUiError(err).technical);
} finally {
setBusy(false);
}
}
async function cleanNow() {
setBusy(true); setSaved(false); setAutoSaved(false); setCleanReport(null); setError("");
try {
const report = await api.serverLogsClean(serverId);
setCleanReport(report);
await refreshState();
} catch (err) {
setError(asUiError(err).technical);
} finally {
setBusy(false);
}
}
const changed = !!view && JSON.stringify(view.settings) !== JSON.stringify(draft);
const sizeOk = Number.isInteger(draft.maxSizeMb) && draft.maxSizeMb >= 10 && draft.maxSizeMb <= 100000;
const logBytes = view?.logBytes ?? 0;
const input = "rounded border border-line bg-bg px-2 py-1 text-sm text-ink outline-none focus:border-gold";
return <Card className="mt-6 p-6" aria-busy={busy}>
<h2 className="font-semibold">{t("serverLogs.title")}</h2>
<p className="mt-2 text-sm text-muted">{t("serverLogs.description")}</p>
<div className="mt-4 flex flex-wrap gap-2">
{(["normal", "errors", "off"] as const).map(preset => <button key={preset} disabled={busy} onClick={() => apply(preset)} className="rounded-md border border-line px-3 py-2 text-sm hover:bg-white/5 disabled:opacity-50">{t(`serverLogs.${preset}`)}</button>)}
{(["normal", "errors", "off"] as const).map(preset => {
const active = view?.preset === preset;
return <button
key={preset}
disabled={busy}
aria-pressed={active}
onClick={() => void apply(preset)}
className={`rounded-md border px-3 py-2 text-sm disabled:opacity-50 ${active ? "border-gold bg-gold/10 text-gold" : "border-line hover:bg-white/5"}`}
>
{t(`serverLogs.${preset}`)}
</button>;
})}
</div>
{saved && <p role="status" className="mt-3 text-sm text-ok">{t("serverLogs.saved")}</p>}
<div className="mt-5 border-t border-line pt-4">
<label className="flex cursor-pointer items-center gap-3">
<input
type="checkbox"
className="h-4 w-4 accent-[#c9a24a]"
checked={draft.autoCleanup}
disabled={busy || !view}
onChange={e => { setDraft(d => ({ ...d, autoCleanup: e.target.checked })); setAutoSaved(false); }}
/>
<span className="text-sm font-medium">{t("serverLogs.autoClean")}</span>
</label>
<div className="mt-3 flex flex-wrap items-center gap-3 text-sm">
<label className="flex items-center gap-2">
<span>{t("serverLogs.maxSize")}</span>
<input
type="number"
min={10}
max={100000}
step={10}
className={`${input} w-24`}
value={draft.maxSizeMb}
disabled={busy || !draft.autoCleanup}
onChange={e => { setDraft(d => ({ ...d, maxSizeMb: Number(e.target.value) })); setAutoSaved(false); }}
/>
<span className="text-muted">MB</span>
</label>
<Button size="sm" disabled={busy || !changed || (draft.autoCleanup && !sizeOk)} onClick={() => void saveAutoCleanup()}>
{t("sched.save")}
</Button>
{autoSaved && <span role="status" className="text-xs text-ok">{t("sched.saved")}</span>}
</div>
<p className="mt-2 text-xs text-muted">{t("serverLogs.autoCleanHint")}</p>
</div>
<div className="mt-5 flex flex-wrap items-center justify-between gap-3 border-t border-line pt-4">
<span className="text-sm text-muted">
{t("serverLogs.currentSize", { size: formatBytes(logBytes) })}
</span>
<Button size="sm" disabled={busy || !view || logBytes === 0} onClick={() => void cleanNow()}>
{t("serverLogs.cleanNow", { size: formatBytes(logBytes) })}
</Button>
</div>
{cleanReport && (
<p role="status" className="mt-3 text-sm text-ok">
{t("serverLogs.cleaned", { freed: formatBytes(cleanReport.freedBytes) })}
{cleanReport.skippedFiles > 0 && ` ${t("serverLogs.skippedInUse", { remaining: formatBytes(cleanReport.remainingBytes) })}`}
</p>
)}
{error && <p role="alert" className="mt-3 text-sm text-bad">{error}</p>}
</Card>;
}
+6 -13
View File
@@ -1,17 +1,10 @@
{
"version": "0.9.14",
"version": "0.9.16",
"notes": [
"Install community addons from the Manager",
"Old item and creature data is cleared before every Play",
"Turning the custom races client patch on or off takes seconds again",
"The database moves to a free port when Windows reserves or another program takes 3307",
"Your own MySQL settings survive restarts and updates",
"Disabled custom races stay disabled after a server update that adds races",
"Rename your realms in the Manager",
"The account for a friend's server is in the login box at every Play",
"Restart the world every day at a chosen time",
"Switches for the Custom Races V2 subclasses, Hero Races and the /dev menu",
"Companion bots on Wildcard and Warcraft Reborn",
"The Custom Races card tells which characters stay out while races are off"
"The game client now comes from the community launcher, not from the Manager",
"Client setup says where to switch HD graphics; Custom Races patch card is translated",
"Clean server logs by hand or automatically when they grow too big",
"The startup limit for companions now creates the ones that are missing",
"Restart the world every week on a chosen day and time"
]
}