Compare commits

..
Author SHA1 Message Date
Дмитрий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
19 changed files with 829 additions and 262 deletions

No files matched your search

@@ -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.
@@ -1,7 +0,0 @@
---
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,45 +583,6 @@ 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(
@@ -1669,65 +1630,3 @@ 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);
}
}
+68 -89
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::{Path, PathBuf};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
mod browse_preferences;
@@ -597,91 +597,6 @@ 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>,
@@ -728,8 +643,37 @@ async fn start_server(
coa_core::realms::Mode::Wildcard,
coa_core::realms::Mode::Reborn,
] {
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());
let target = match coa_core::multiworld::resolve_bot_operation_target(&r, mode) {
Ok(t) => t,
Err(e) => {
tracing::warn!("cannot resolve target for realm {}: {e}", mode.name());
continue;
}
};
let r_snap = r.clone();
let chars_db = target.chars_db;
let r_ra = r.clone();
let res = coa_core::companions::process_pending_job_with(
&meta,
mode,
&instance_id,
target.running,
|since_guid| {
let admin_db = coa_core::db::Db::from_repack(&r_snap, coa_core::db::Account::Admin)?;
let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, chars_db);
coa_core::companions::query_bot_db_snapshot(&r_snap, &admin_db, chars_db, since_guid)
},
|delta, job| {
let mut ra = Ra::connect_target(&r_ra, Some(mode))?;
if let Some(lvl) = job.level {
ra.spawn_custom(delta, lvl, job.class_id, job.spec_id, job.build_id.as_deref())
} else {
ra.spawn_bots(delta)
}
},
);
if let Err(e) = res {
tracing::warn!("pending companions for realm {} failed during reconciliation: {e}", mode.name());
}
}
Ok(())
@@ -814,6 +758,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>,
@@ -828,6 +781,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>,
@@ -3303,7 +3280,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,
@@ -3393,7 +3373,6 @@ pub fn run() {
report_targets,
companion_sizes,
add_companions,
top_up_startup_fleet,
get_wildcard_archetypes,
remote_connection,
remote_connect,
+2 -2
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,7 +70,6 @@ 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};}
+16 -2
View File
@@ -597,8 +597,6 @@ 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.",
@@ -782,6 +780,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.",
@@ -1129,6 +1136,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.",
};
+16 -2
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,8 +705,6 @@ 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.",
@@ -1339,6 +1346,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;
+16 -2
View File
@@ -597,8 +597,6 @@ 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.",
@@ -782,6 +780,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.",
@@ -1129,6 +1136,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.",
};
+16 -2
View File
@@ -597,8 +597,6 @@ 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.",
@@ -782,6 +780,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.",
@@ -1129,6 +1136,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.",
};
+16 -2
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,8 +688,6 @@ 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.",
@@ -1322,6 +1329,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.",
};
+16 -2
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,8 +659,6 @@ const zh = {
"comp.startCount": "自动登录随从数量",
"comp.startSave": "保存",
"comp.startSaved": "已保存。将在下次服务器启动时生效。",
"comp.startTopUp": "已保存。正在再创建 {n} 个同伴,使总数达到 {max};其余已存在。",
"comp.startTopUpConfirm": "再创建 {n} 个同伴,使总数达到 {max}?已存在的不会重复创建。",
"comp.startHint": "未登录的随从仍保留在数据库中,随时可在需要时手动调出上线。",
"comp.startInvalid": "请输入 0 到 5000 之间的整数。",
@@ -1131,6 +1138,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;
+16 -3
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 }
@@ -530,7 +542,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 }),
@@ -584,8 +599,6 @@ 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 }),
+2 -9
View File
@@ -305,18 +305,11 @@ 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,
});
const queued = autoOn && running ? await api.topUpStartupFleet(serverId, activeServerRealm) : 0;
setStartNote(queued > 0 ? t("comp.startTopUp", { n: queued, max: maxNum }) : t("comp.startSaved"));
setStartNote(t("comp.startSaved"));
} catch (e) {
setError(asUiError(e));
} finally {
@@ -788,7 +781,7 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
Persistent Startup Fleet
</h3>
<p className="text-xs text-muted">
The server keeps this many companions. At every start the ones that exist log in, and only the missing ones are created.
Configure how many bots automatically log into the world whenever the server launches.
</p>
<div className="flex flex-wrap items-center gap-4 text-sm">
+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>;
}