mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 03:25:56 +00:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88ccce8280 | ||
|
|
17eba1c30e | ||
|
|
dbf494c2c2 | ||
|
|
086534f849 | ||
|
|
1b0adbf94c | ||
|
|
a8afe88c83 | ||
|
|
657229aafc | ||
|
|
b5abc6fc4f | ||
|
|
81c5556ffe | ||
|
|
4b51301230 | ||
|
|
6f1eaac719 | ||
|
|
206d4844c9 | ||
|
|
10cfdcf5a2 | ||
|
|
316ef078e8 | ||
|
|
1974ff54e3 | ||
|
|
de3af82e5d | ||
|
|
802bde220c | ||
|
|
dfe7ac656b | ||
|
|
cee5139879 | ||
|
|
1ea2c8318b | ||
|
|
2b7dbf8e1e | ||
|
|
4ff190f6d1 | ||
|
|
bff5248591 |
No files matched your search
@@ -8,6 +8,22 @@ Published releases and previews. Pre-release entries do not change the stable up
|
||||
|
||||
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
|
||||
|
||||
## 0.9.17 — 2026-11-23
|
||||
|
||||
- The game client link points to the new community site, conquestofazerothcore.to.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.17) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.16...v0.9.17)
|
||||
|
||||
## 0.9.16 — 2026-11-20
|
||||
|
||||
- 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.
|
||||
|
||||
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.16) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.15...v0.9.16)
|
||||
|
||||
## 0.9.15 — 2026-11-19
|
||||
|
||||
- The Custom Races client update brings version 2.0.2.
|
||||
|
||||
Generated
+4
-4
@@ -586,7 +586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-core"
|
||||
version = "0.9.15"
|
||||
version = "0.9.18"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -621,7 +621,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-launcher"
|
||||
version = "0.9.15"
|
||||
version = "0.9.18"
|
||||
dependencies = [
|
||||
"coa-core",
|
||||
"serde_json",
|
||||
@@ -644,7 +644,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-release"
|
||||
version = "0.9.15"
|
||||
version = "0.9.18"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"coa-core",
|
||||
@@ -653,7 +653,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-server-manager"
|
||||
version = "0.9.15"
|
||||
version = "0.9.18"
|
||||
dependencies = [
|
||||
"coa-control-proto",
|
||||
"coa-core",
|
||||
|
||||
+1
-1
@@ -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.18"
|
||||
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: modules
|
||||
type: added
|
||||
audience: admins
|
||||
title: Configure Playerbot Characters from the Modules page
|
||||
---
|
||||
Set up an OpenAI, Ollama, Anthropic or OpenAI-compatible connection from Modules, including its API key. Playerbot Characters gives CoA Companions or SQUID Playerbots dialogue and memories.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: modules
|
||||
type: added
|
||||
audience: admins
|
||||
title: Choose Playerbot Characters models from a live provider list
|
||||
---
|
||||
Search the models available from your configured provider and refresh the list when models change. Custom endpoints can still use a model ID entered manually.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: players
|
||||
title: The game client link points to the new community site, conquestofazerothcore.to
|
||||
---
|
||||
The old community website no longer works, so the client setup dialog now opens conquestofazerothcore.to, where you download the launcher and sign in.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Settings now shows the server version and update button after you have checked for updates
|
||||
---
|
||||
The Server card in Settings > Updates could stay empty, with only "…" and no update button, while the main screen already offered an update. It now shows the same version and update as the main screen.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: changed
|
||||
audience: admins
|
||||
title: Adding companions reuses offline bots and keeps your startup limit
|
||||
---
|
||||
Bots that already exist and are offline are logged in first and only the missing ones are created. Adding companions no longer raises the number of bots that log in when the server starts.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: players
|
||||
title: Custom Races installs the 2.0.3 client with the Snagtooth race
|
||||
---
|
||||
Updating Custom Races adds the new Alliance race and its fixes. Only the changed archives are downloaded again.
|
||||
+33
-1
@@ -191,7 +191,13 @@
|
||||
"Corfirean/coa-server-manager:20261115-v2-feature-switches.md",
|
||||
"Corfirean/coa-server-manager:20261116-companions-wildcard-reborn.md",
|
||||
"Corfirean/coa-server-manager:20261116-custom-race-characters-off.md",
|
||||
"Corfirean/coa-server-manager:20261118-custom-races-2-0-2-client.md"
|
||||
"Corfirean/coa-server-manager:20261117-client-download-needs-launcher.md",
|
||||
"Corfirean/coa-server-manager:20261118-custom-races-2-0-2-client.md",
|
||||
"Corfirean/coa-server-manager:20261120-hd-graphics-hint-and-patch-labels.md",
|
||||
"Corfirean/coa-server-manager:20261120-server-log-auto-cleanup.md",
|
||||
"Corfirean/coa-server-manager:20261120-startup-fleet-creates-missing-companions.md",
|
||||
"Corfirean/coa-server-manager:20261120-weekly-world-restart.md",
|
||||
"Corfirean/coa-server-manager:20261123-client-site-link.md"
|
||||
],
|
||||
"releases": [
|
||||
{
|
||||
@@ -982,6 +988,32 @@
|
||||
],
|
||||
"commit": "2b9021ce072e3b6c7e9c8106f8a54f59f1b37424",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.14...v0.9.15"
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.16",
|
||||
"version": "0.9.16",
|
||||
"date": "2026-11-20",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.16",
|
||||
"notes": [
|
||||
"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"
|
||||
],
|
||||
"commit": "316ef078e8047c790cb081f0991d9e0d618fcd2d",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.15...v0.9.16"
|
||||
},
|
||||
{
|
||||
"tag": "v0.9.17",
|
||||
"version": "0.9.17",
|
||||
"date": "2026-11-23",
|
||||
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.17",
|
||||
"notes": [
|
||||
"The game client link points to the new community site, conquestofazerothcore.to"
|
||||
],
|
||||
"commit": "b5abc6fc4f6ab348efd57521136a2153ec948ca0",
|
||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.16...v0.9.17"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -14,34 +14,36 @@ use crate::download::Cancel;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
pub const CLIENT_VERSION: &str = "2.0.2";
|
||||
pub const CLIENT_VERSION: &str = "2.0.3";
|
||||
pub const MANIFEST_FILENAME: &str = "custom_races_patch_manifest.txt";
|
||||
/// Files earlier releases installed that the current release no longer ships (removed on update).
|
||||
#[cfg(test)]
|
||||
const RETIRED_FILES: &[&str] = &["Ascension.exe"];
|
||||
/// The client archives of the coa-custom-2.0.2 release. Clients 1 to 9 are byte for byte the 2.0 archives and keep their
|
||||
/// 2.0 file names, so a verified copy in the cache or in Downloads is not fetched again. The server archive is read
|
||||
/// only for its client addons; the SkinCollection (Skinshifter) addon in Client 17 is not installed (see RACE_ADDONS).
|
||||
/// Order matters: a later archive replaces a file of an earlier one, and Client 17 carries the newer Ascension_Subclass.
|
||||
/// The client archives of the coa-custom-2.0.3 release. Clients 1 to 11 and 17 are byte for byte the archives of the
|
||||
/// earlier releases and keep the file names the Manager already saved them under, so a verified copy in the cache or in
|
||||
/// Downloads is not fetched again. The server archive is read only for its client addons; the SkinCollection
|
||||
/// (Skinshifter) addon in Client 17 is not installed (see RACE_ADDONS). Order matters: a later archive replaces a file of
|
||||
/// an earlier one; Client 17 carries the newer Ascension_Subclass and Client 18 comes last.
|
||||
pub const ARCHIVES: &[(&str, &str)] = &[
|
||||
("CoA-Custom-V2-Client-1.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-1.zip"),
|
||||
("CoA-Custom-V2-Client-2.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-2.zip"),
|
||||
("CoA-Custom-V2-Client-3.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-3.zip"),
|
||||
("CoA-Custom-V2-Client-4.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-4.zip"),
|
||||
("CoA-Custom-V2-Client-5.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-5.zip"),
|
||||
("CoA-Custom-V2-Client-6.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-6.zip"),
|
||||
("CoA-Custom-V2-Client-7.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-7.zip"),
|
||||
("CoA-Custom-V2-Client-8.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-8.zip"),
|
||||
("CoA-Custom-V2-Client-9.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-9.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-10.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-10.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-11.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-11.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-12.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-12.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-13.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-13.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-14.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-14.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-15.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-15.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-16.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-16.zip"),
|
||||
("CoA-Custom-V2.0.2-Server.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Server.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-17.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.2/CoA-Custom-V2.0.2-Client-17.zip"),
|
||||
("CoA-Custom-V2-Client-1.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-1.zip"),
|
||||
("CoA-Custom-V2-Client-2.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-2.zip"),
|
||||
("CoA-Custom-V2-Client-3.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-3.zip"),
|
||||
("CoA-Custom-V2-Client-4.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-4.zip"),
|
||||
("CoA-Custom-V2-Client-5.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-5.zip"),
|
||||
("CoA-Custom-V2-Client-6.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-6.zip"),
|
||||
("CoA-Custom-V2-Client-7.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-7.zip"),
|
||||
("CoA-Custom-V2-Client-8.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-8.zip"),
|
||||
("CoA-Custom-V2-Client-9.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-9.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-10.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-10.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-11.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-11.zip"),
|
||||
("CoA-Custom-V2.0.3-Client-12.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-12.zip"),
|
||||
("CoA-Custom-V2.0.3-Client-13.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-13.zip"),
|
||||
("CoA-Custom-V2.0.3-Client-14.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-14.zip"),
|
||||
("CoA-Custom-V2.0.3-Client-15.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-15.zip"),
|
||||
("CoA-Custom-V2.0.3-Client-16.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-16.zip"),
|
||||
("CoA-Custom-V2.0.3-Server.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Server.zip"),
|
||||
("CoA-Custom-V2.0.2-Client-17.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-17.zip"),
|
||||
("CoA-Custom-V2.0.3-Client-18.zip", "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0.3/CoA-Custom-V2.0.3-Client-18.zip"),
|
||||
];
|
||||
|
||||
pub const RACE_MPQS: &[&str] = &[
|
||||
@@ -134,6 +136,7 @@ pub const RACE_MPQS: &[&str] = &[
|
||||
"patch-ZZZZZZC.MPQ",
|
||||
"patch-ZZZZZZD.MPQ",
|
||||
"patch-ZZZZZZE.MPQ",
|
||||
"patch-ZZZZZZF.MPQ",
|
||||
"patch-retail-001.mpq",
|
||||
"patch-retail-002.mpq",
|
||||
"patch-retail-003.mpq",
|
||||
@@ -440,6 +443,8 @@ fn patch_files(client: &Path) -> Result<Vec<PatchFile>> {
|
||||
include_str!("custom_races_hashes_1_9_2.json")
|
||||
} else if manifest.lines().any(|line| line == "# CoA Custom 2.0") {
|
||||
include_str!("custom_races_hashes_2_0.json")
|
||||
} else if manifest.lines().any(|line| line == "# CoA Custom 2.0.2") {
|
||||
include_str!("custom_races_hashes_2_0_2.json")
|
||||
} else {
|
||||
include_str!("custom_races_hashes.json")
|
||||
};
|
||||
@@ -1143,33 +1148,37 @@ fn archive_job(filename: &str, url: &str, cache: &Path) -> Result<crate::downloa
|
||||
178_667_276,
|
||||
"9a66f782be47f66ce4ec9f4f70cb1970218fe48950a031b39aa79c091008901b",
|
||||
),
|
||||
"CoA-Custom-V2.0.2-Client-12.zip" => (
|
||||
1_053_880_101,
|
||||
"f7a90890a0248967eb4572c641f5dee1bd0cafba12d1841360821b79cd5b1c3e",
|
||||
"CoA-Custom-V2.0.3-Client-12.zip" => (
|
||||
1_053_879_059,
|
||||
"25d5711963dbae2fa9d030ee883dae6846bd8bcb099ed4cdc27f30fa31561a81",
|
||||
),
|
||||
"CoA-Custom-V2.0.2-Client-13.zip" => (
|
||||
950_360_503,
|
||||
"8ae00b9bebc4e21d6d6d32ddbf319c341f3c418349a3aeb3d840dffb0fa14d3f",
|
||||
"CoA-Custom-V2.0.3-Client-13.zip" => (
|
||||
950_359_687,
|
||||
"34efe8dfc1a7d7168298c24c530af5d3625e8a2c48b7183f5c82ad019ece3cf2",
|
||||
),
|
||||
"CoA-Custom-V2.0.2-Client-14.zip" => (
|
||||
971_472_467,
|
||||
"511ec3fd1933b9342920262f6a5eae7e451671a49679e93612632b77c31ba57f",
|
||||
"CoA-Custom-V2.0.3-Client-14.zip" => (
|
||||
970_584_608,
|
||||
"cb1c9b8e2b1fba065bd0f9a252eb20a2f1031828eddef90e3f72e8729124f18c",
|
||||
),
|
||||
"CoA-Custom-V2.0.2-Client-15.zip" => (
|
||||
1_106_537_793,
|
||||
"b65505a047508cbd15f4fec670d3953873014250efc484aa3bdb75cb3b3cbbf1",
|
||||
"CoA-Custom-V2.0.3-Client-15.zip" => (
|
||||
1_106_629_165,
|
||||
"718d45ef055aa09a48f14f74e2cb14ca3bd782d75a6e1e3f5148146f418af7b6",
|
||||
),
|
||||
"CoA-Custom-V2.0.2-Client-16.zip" => (
|
||||
11_874_081,
|
||||
"5442dc06147e60140c43eebfae14f6ad5f19e6fed974db471b65211497609a27",
|
||||
"CoA-Custom-V2.0.3-Client-16.zip" => (
|
||||
14_217_214,
|
||||
"cdd9c345d9a0fa8ab9290348f83de6a5bcf05ae543bd3c58aa0d507c7725cb15",
|
||||
),
|
||||
"CoA-Custom-V2.0.2-Client-17.zip" => (
|
||||
947_478,
|
||||
"707e09c8b95926e2d83bdc16adab763901951566caf6bf4fcebfdf4d7ba0e62a",
|
||||
),
|
||||
"CoA-Custom-V2.0.2-Server.zip" => (
|
||||
96_857_277,
|
||||
"36d0cba993623064ce01f364116f99330423cec3cef22101e50cf941dfd85afe",
|
||||
"CoA-Custom-V2.0.3-Server.zip" => (
|
||||
97_128_649,
|
||||
"876c871ff616ee2f7fad6f096d70eec9aa4f05a1ebe6f6925bee522e8e7bd16a",
|
||||
),
|
||||
"CoA-Custom-V2.0.3-Client-18.zip" => (
|
||||
57_277_519,
|
||||
"04e335984443505fea88fa07930c7ecc35eec3fe7fe19cdca8dc731a688f1896",
|
||||
),
|
||||
_ => return Err(Error::Invalid("Unknown custom races archive.".into())),
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"CoACustomRace.exe": "8c283dcd464418e6859217dd53ad522b6a61f064c6db349c77d3cb90412690d9",
|
||||
"CoACustomRace.exe": "124937935a67527f8755cf0cfbad29e7a8567896d95efda1923d3aea6b6a5629",
|
||||
"CoAVolFog-regions.ini": "a21c2616c866ea29bdf2c75af2607e8cb982fdaaef1167375b23f1490325a0a5",
|
||||
"CoAVolFog.dll": "65c9abb6d44ce41bc943b25a83ab4292dd0697d6490a60385e75610fe66801ce",
|
||||
"CoAVolFog.ini": "921d99e3dd5a85db4d815c4baf94851639e85e74a5bb5b5f610548a0fbf94483",
|
||||
@@ -41,6 +41,7 @@
|
||||
"Data/Retail/Assets/EquipmentFitting/90-0.bin": "747cb1fb166a9e167c247af47a59348a40395c2f7fa8c745a5cd8c738682782b",
|
||||
"Data/Retail/Assets/EquipmentFitting/90-1.bin": "834acb7c2e4c5b1637c8e2f2be1a7c1ab9e6587ec57eba5b2ab43d1a9138de41",
|
||||
"Data/Retail/Assets/EquipmentFitting/91-0.bin": "06128794647a6ad9158b77344512d31ef46a85f6a6d5b23364993d7275938bc1",
|
||||
"Data/Retail/Assets/EquipmentFitting/92-0.bin": "b05ad17cc3228dce19bfef18d2d25d319f3a6410a9bf4c828bea4514482f07d4",
|
||||
"Data/Retail/Cache/Retail/wow-d718abcc42604d8efbd35aecfa5bb75b/decoded/2/strict/id-1000746.bin": "ecaf3974d2d340dff24669acbfe902f93f3f0dedb7184feacc1ae792dfbab37a",
|
||||
"Data/Retail/Cache/Retail/wow-d718abcc42604d8efbd35aecfa5bb75b/decoded/2/strict/id-1000747.bin": "c35a99841af8ff6c8db60ddc771d2222447b4f969ef01fce5caf0dbd5e6537fe",
|
||||
"Data/Retail/Cache/Retail/wow-d718abcc42604d8efbd35aecfa5bb75b/decoded/2/strict/id-1000748.bin": "2cfd30380d491cb89dddec16f3bbc9344eb92087caa3419d0c8185286e26e6ae",
|
||||
@@ -4821,17 +4822,18 @@
|
||||
"Data/patch-ZZZZZY-SUBXB-HD.MPQ": "7fb6172edd64f6fc27816964d0ed13ba351afc9c07b2920564a5d41694e5ae1b",
|
||||
"Data/patch-ZZZZZY-SUBXC-HD.MPQ": "765a0158bc501c435b828e64923f06f981a1408ea27b42a38b9ea2b467dcd54f",
|
||||
"Data/patch-ZZZZZY.MPQ": "05b8cbd7a45cc9933a84ee991ff3193063cb2d040296843b947e190e8c64e741",
|
||||
"Data/patch-ZZZZZZ.MPQ": "b3f95a34f2c5d2157f54191124e864db4d2cb559156d2b7fccb119d9ae247ec8",
|
||||
"Data/patch-ZZZZZZ.MPQ": "4397a0d1f0096403a7fb1afc0245405ea88cb40e4d30096a9018e147c1da8e86",
|
||||
"Data/patch-ZZZZZZA.MPQ": "2c8f9caef8e3f3cf33b9b35bf5782123b4759a8fecb92a326be59d2f918608f7",
|
||||
"Data/patch-ZZZZZZB.MPQ": "cb3107c155b57e6b77e92d881be3f2113a5401c101be185175d06b0a7ffdf6ab",
|
||||
"Data/patch-ZZZZZZC.MPQ": "0fbd43a7208a11ee02a2ed31ed1da90bf4240074e7e508ed801f20de50e697d4",
|
||||
"Data/patch-ZZZZZZD.MPQ": "53f4dac665280030ac8764cd2b45fc8ff65c5e85981b3f3ddcff34d5bc8d3c7f",
|
||||
"Data/patch-ZZZZZZE.MPQ": "64fb42fc12367bc0b8b95489315c882d36c195c90732bd5a8ed449f7373653cf",
|
||||
"Data/patch-retail-001.mpq": "1b0fafbdc6d01b92b5f09566f05510361972879a0407a79c03d1146f3440b764",
|
||||
"Data/patch-retail-002.mpq": "6802c1c9530a9fb4107fd56bf18185484257cda69ead36a170ab557cea5b64d3",
|
||||
"Data/patch-retail-003.mpq": "ae3f030fdb0b340a420ee9a3f027c47798e2646ab73bcac62b6f6b6c8589ca9b",
|
||||
"Data/patch-retail-004.mpq": "ed857958adcf96266d25c2ab2da882359fc302d9d2f2da9032010061a0ca0a37",
|
||||
"Data/patch-retail-005.mpq": "4fb237c92ccfccb7de90ff3ef184d04edb08dfda0ed2b2f16de802dff0455a5e",
|
||||
"Data/patch-ZZZZZZF.MPQ": "94215a9ab04a184a94faffd4ea20946ad89fdbbff7304a8f54154caa4fbaa09a",
|
||||
"Data/patch-retail-001.mpq": "20d23806aa200c5f82ec0eac3f92d0790344f6c02ef01d1f96f2740925f11eae",
|
||||
"Data/patch-retail-002.mpq": "5887468bab8b3f176f544d57a79ec28db71f6771783d8739016da9d1602e777c",
|
||||
"Data/patch-retail-003.mpq": "95997a69db7b6ad02ce50ed51b6e5b91d3fa633406ae53be50f04eca81eeb4b8",
|
||||
"Data/patch-retail-004.mpq": "6c00d97911460ff40d69046baa79f8f7faa6be3334a61725a6fb92716473ec36",
|
||||
"Data/patch-retail-005.mpq": "18e559b69e1e1ba11989c74c0d0cde0141228b1b6d62985ef30a5d10d5647e57",
|
||||
"EsteriaAppearance.bin": "90d9cfaeaf6de10f014f1d1610ea10453ec9b240255759aea99513cac488a3ec",
|
||||
"EsteriaAppearance.dll": "88e268d3be9eca3b0644f543d823f4bdcc04a9700a6e8ed73fd2a1260ad191af",
|
||||
"EsteriaAppearanceGeometry.bin": "cacd2086eabf43391bca07b622e17444de91b30593827e9e1e54758fe4dcd8e7",
|
||||
@@ -4888,6 +4890,9 @@
|
||||
"EsteriaSethrakTextures.bin": "d2b2cf58087a391f00198008fe871edd400ddf28d54a3a05674df74c5198528a",
|
||||
"EsteriaSlime.bin": "491e942ceb6abda83c0249afebae7c9c43af3897b35e45fa33d6f9177ecbc177",
|
||||
"EsteriaSlimeTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaSnagtooth.bin": "eadfd9b4345140223ca0cd6db72db15b806be8c5cfa498586a65b2c7b6c6b06a",
|
||||
"EsteriaSnagtoothSkins.bin": "9c206ed7737432accad5ccf36ddbd6a61c71276c392e5d42dab38b6b8217fa1f",
|
||||
"EsteriaSnagtoothTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaSporeling.bin": "b6ae22df1f6c9329c338dfe5047a5d6dd01c42dec8d16a28bff7c58f6ace3c8f",
|
||||
"EsteriaSporelingTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
|
||||
"EsteriaStormforged.bin": "3e44bc2dc41d53b3531d15c3a55852baf5656bf2e15cde6d2a68ebc6e4575a78",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -665,6 +665,11 @@ fn game_args(
|
||||
a.extend(env("AC_UPDATES_ENABLE_DATABASES", "0"));
|
||||
if kind == GameKind::World {
|
||||
a.extend(["--volume".into(), format!("{}:{DATA}:ro", data.display())]);
|
||||
let pbc = crate::modules::pbc::ASSET_DIR;
|
||||
let assets = host.join(pbc);
|
||||
if assets.is_dir() {
|
||||
a.extend(["--volume".into(), format!("{}:/srv/{pbc}:ro", assets.display())]);
|
||||
}
|
||||
let races = host.join("Data/dbc_races");
|
||||
if races.is_dir() && races != data.join("dbc_races") {
|
||||
a.extend([
|
||||
@@ -1066,6 +1071,8 @@ mod tests {
|
||||
#[test]
|
||||
fn a_first_start_creates_the_network_the_image_and_the_containers_in_order() {
|
||||
let (_d, root) = server("t1");
|
||||
let assets = root.join(crate::modules::pbc::ASSET_DIR);
|
||||
fs::create_dir_all(&assets).unwrap();
|
||||
let sim = Sim::new();
|
||||
let o = start_all(&sim, &root);
|
||||
assert!(o.ok, "{}", o.output);
|
||||
@@ -1091,6 +1098,10 @@ mod tests {
|
||||
["coa-t1-db", "coa-t1-world", "coa-t1-auth"],
|
||||
"database, then world, then auth"
|
||||
);
|
||||
let calls = sim.calls_of("run");
|
||||
let mount = format!("{}:/srv/Extras/PlayerbotCharacters:ro", assets.display());
|
||||
assert!(calls[1].args.windows(2).any(|w| w == ["--volume", mount.as_str()]));
|
||||
assert!(!calls[0].args.contains(&mount) && !calls[2].args.contains(&mount));
|
||||
let exec = sim.calls_of("exec");
|
||||
assert_eq!(
|
||||
exec.len(),
|
||||
|
||||
@@ -154,6 +154,14 @@ pub fn safe_join(root: &Path, rel: &str) -> Result<PathBuf> {
|
||||
|
||||
/// Write `bytes` to `path` so readers see either the old or the new content, never a partial file.
|
||||
pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
atomic_write_inner(path, bytes, false)
|
||||
}
|
||||
|
||||
pub(crate) fn atomic_write_private(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
atomic_write_inner(path, bytes, true)
|
||||
}
|
||||
|
||||
fn atomic_write_inner(path: &Path, bytes: &[u8], _private: bool) -> Result<()> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| Error::PathRejected("no parent directory".into()))?;
|
||||
@@ -166,7 +174,14 @@ pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
uuid::Uuid::new_v4().simple()
|
||||
));
|
||||
let write = || -> std::io::Result<()> {
|
||||
let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
if _private {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut f = options.open(&tmp)?;
|
||||
f.write_all(bytes)?;
|
||||
f.sync_all()?;
|
||||
Ok(())
|
||||
|
||||
@@ -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()));
|
||||
|
||||
@@ -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));
|
||||
};
|
||||
|
||||
@@ -12,6 +12,8 @@ use crate::config::parser::ConfFile;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
pub mod pbc;
|
||||
|
||||
static CATALOG: &str = include_str!("../../../modules/catalog.json");
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
@@ -512,6 +514,12 @@ fn settings_in(cat: &[Entry], root: &Path, id: &str) -> Result<Vec<Setting>> {
|
||||
};
|
||||
Ok(effective
|
||||
.entries()
|
||||
.filter(|(key, _)| {
|
||||
id != "mod-pbc"
|
||||
|| !["PBC.ApiKey", "PBC.AltModelApiKey"]
|
||||
.iter()
|
||||
.any(|secret| key.eq_ignore_ascii_case(secret))
|
||||
})
|
||||
.map(|(k, v)| {
|
||||
let mut val = fields
|
||||
.get(k)
|
||||
@@ -703,6 +711,63 @@ fn save_settings_in(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn playerbot_characters_uses_the_packaged_default_and_keeps_host_settings() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path().join("server");
|
||||
let meta = temp.path().join("metadata");
|
||||
let cat = catalog();
|
||||
let id = "mod-pbc";
|
||||
let card = || list_in(&cat, &root).into_iter().find(|m| m.id == id).unwrap();
|
||||
fs::create_dir_all(dir(&root)).unwrap();
|
||||
fs::create_dir_all(&meta).unwrap();
|
||||
assert!(!card().installed);
|
||||
|
||||
let dist = dir(&root).join("playerbots_characters.conf.dist");
|
||||
let defaults = "[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = ../Extras/PlayerbotCharacters/my-connection.jsonc\n";
|
||||
fs::write(&dist, defaults).unwrap();
|
||||
let installed = card();
|
||||
assert!(installed.installed && installed.switchable && installed.has_settings);
|
||||
assert!(!installed.enabled);
|
||||
|
||||
let key = "PBC.DefaultConnection";
|
||||
let path = "C:/Test Server/Model Config/custom.jsonc";
|
||||
save_settings_in(&cat, &root, &meta, id, &BTreeMap::from([(key.into(), path.into())])).unwrap();
|
||||
set_enabled_in(&cat, &root, &meta, id, true).unwrap();
|
||||
assert!(card().enabled);
|
||||
set_enabled_in(&cat, &root, &meta, id, false).unwrap();
|
||||
assert!(!card().enabled);
|
||||
let active = read(&dir(&root).join("playerbots_characters.conf")).unwrap();
|
||||
assert_eq!(active.get(key), Some(path));
|
||||
assert_eq!(fs::read_to_string(dist).unwrap(), defaults);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playerbot_characters_preserves_legacy_connections_without_exposing_keys() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
fs::create_dir_all(dir(root)).unwrap();
|
||||
let name = "playerbots_characters.conf";
|
||||
fs::write(
|
||||
dir(root).join(name),
|
||||
"[worldserver]\nPBC.Enable = 1\nPBC.BaseUrl = https://example.test/v1\nPBC.Model = legacy\nPBC.ApiKey = fixture-key\nPBC.AltModelApiKey = fixture-alt-key\n",
|
||||
).unwrap();
|
||||
fs::write(
|
||||
dir(root).join(format!("{name}.dist")),
|
||||
"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = \"\"\n",
|
||||
).unwrap();
|
||||
|
||||
crate::config::materialize_module_configs(root).unwrap();
|
||||
let config = read(&dir(root).join(name)).unwrap();
|
||||
assert_eq!(config.get("PBC.Enable"), Some("1"));
|
||||
assert_eq!(config.get("PBC.DefaultConnection"), Some("\"\""));
|
||||
assert_eq!(config.get("PBC.ApiKey"), Some("fixture-key"));
|
||||
assert_eq!(config.get("PBC.AltModelApiKey"), Some("fixture-alt-key"));
|
||||
let visible = serde_json::to_string(&settings(root, "mod-pbc").unwrap()).unwrap();
|
||||
assert!(!visible.contains("fixture-key") && !visible.contains("fixture-alt-key"));
|
||||
assert!(!pbc::load(root).unwrap().active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_is_time_card_settings_and_backups_match_the_module() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
//! Owns the connection file created by the Manager. Handwritten connection files stay with their owners.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::config::parser::{ConfFile, unquote};
|
||||
use crate::realms::{self, Mode};
|
||||
use crate::{Error, Result, fsx};
|
||||
|
||||
pub mod models;
|
||||
|
||||
const MODULE: &str = "mod-pbc";
|
||||
const PATH_SETTING: &str = "PBC.DefaultConnection";
|
||||
pub(crate) const ASSET_DIR: &str = "Extras/PlayerbotCharacters";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ApiType {
|
||||
Openai,
|
||||
Ollama,
|
||||
Anthropic,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ConnectionUpdate {
|
||||
pub api_type: ApiType,
|
||||
pub base_url: String,
|
||||
pub model: String,
|
||||
pub api_key: Option<String>,
|
||||
pub remove_key: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Connection {
|
||||
api_type: ApiType,
|
||||
base_url: String,
|
||||
model: String,
|
||||
api_key: String,
|
||||
request_timeout_sec: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ConnectionView {
|
||||
pub api_type: ApiType,
|
||||
pub base_url: String,
|
||||
pub model: String,
|
||||
pub has_key: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Setup {
|
||||
pub active: bool,
|
||||
pub connection: Option<ConnectionView>,
|
||||
}
|
||||
|
||||
fn managed_connection(root: &Path) -> Result<(PathBuf, String)> {
|
||||
let file = match realms::state(root)?.active {
|
||||
Mode::Coa => "manager-connection.jsonc",
|
||||
Mode::Wildcard => "manager-connection-wildcard.jsonc",
|
||||
Mode::Reborn => "manager-connection-reborn.jsonc",
|
||||
};
|
||||
let relative = format!("{ASSET_DIR}/{file}");
|
||||
let path = fsx::ensure_within(root, &root.join(&relative))?;
|
||||
Ok((path, format!("../{relative}")))
|
||||
}
|
||||
|
||||
/// Secondary worlds use their own Core directory. Point their packaged paths back to the shared assets.
|
||||
pub(crate) fn rebase_packaged_paths(config: &str, root: &Path) -> Result<String> {
|
||||
let mut conf = ConfFile::parse_bytes(config.as_bytes())?;
|
||||
let assets = root.join(ASSET_DIR);
|
||||
for key in [
|
||||
PATH_SETTING, "PBC.UtilityConnection", "PBC.CondensationConnection",
|
||||
"PBC.RelationshipUpdateConnection", "PBC.PromptsPath", "PBC.CharacterCardsPath",
|
||||
"PBC.HttpServerFrontendPath",
|
||||
] {
|
||||
let Some(relative) = conf.get(key).map(unquote)
|
||||
.and_then(|path| path.strip_prefix("../Extras/PlayerbotCharacters/"))
|
||||
else { continue };
|
||||
let Ok(path) = fsx::safe_join(&assets, relative) else { continue };
|
||||
let path = path.to_string_lossy().replace('\\', "/");
|
||||
conf.set(key, &format!("\"{path}\""), &[]);
|
||||
}
|
||||
Ok(conf.to_text())
|
||||
}
|
||||
|
||||
fn read_connection(path: &Path) -> Result<Option<Vec<u8>>> {
|
||||
match fs::read(path) {
|
||||
Ok(bytes) => Ok(Some(bytes)),
|
||||
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(bytes: &[u8]) -> Result<Connection> {
|
||||
serde_json::from_slice(bytes).map_err(|_| Error::Invalid("The Manager model connection file is invalid.".into()))
|
||||
}
|
||||
|
||||
fn view(connection: Connection) -> ConnectionView {
|
||||
ConnectionView {
|
||||
api_type: connection.api_type,
|
||||
base_url: connection.base_url,
|
||||
model: connection.model,
|
||||
has_key: !connection.api_key.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
fn module_setting(root: &Path) -> Result<String> {
|
||||
super::settings(root, MODULE)?
|
||||
.into_iter()
|
||||
.find(|setting| setting.key == PATH_SETTING)
|
||||
.map(|setting| setting.value)
|
||||
.ok_or_else(|| Error::Invalid("This server package does not provide a model connection setting.".into()))
|
||||
}
|
||||
|
||||
pub fn load(root: &Path) -> Result<Setup> {
|
||||
let (path, setting) = managed_connection(root)?;
|
||||
let active = unquote(&module_setting(root)?) == setting;
|
||||
let connection = read_connection(&path)?
|
||||
.as_deref()
|
||||
.map(parse)
|
||||
.transpose()?
|
||||
.map(view);
|
||||
Ok(Setup { active, connection })
|
||||
}
|
||||
|
||||
fn connection_url(base_url: &str) -> Result<reqwest::Url> {
|
||||
let url = reqwest::Url::parse(base_url.trim().trim_end_matches('/'))
|
||||
.map_err(|_| Error::Invalid("Enter a valid model API base URL.".into()))?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host().is_none()
|
||||
|| !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some()
|
||||
{
|
||||
return Err(Error::Invalid("Use an HTTP or HTTPS base URL without credentials, a query, or a fragment.".into()));
|
||||
}
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
fn connection_key(
|
||||
api_type: ApiType,
|
||||
base_url: &str,
|
||||
submitted_key: Option<&str>,
|
||||
remove_key: bool,
|
||||
previous: Option<Connection>,
|
||||
) -> Result<String> {
|
||||
let submitted_key = submitted_key.map(str::trim).filter(|value| !value.is_empty());
|
||||
if submitted_key.is_some_and(|value| value.chars().any(char::is_control)) {
|
||||
return Err(Error::Invalid("Enter the API key on a single line.".into()));
|
||||
}
|
||||
|
||||
let key = if remove_key {
|
||||
String::new()
|
||||
} else if let Some(key) = submitted_key {
|
||||
key.to_owned()
|
||||
} else {
|
||||
previous
|
||||
.filter(|old| old.api_type == api_type && old.base_url == base_url)
|
||||
.map(|old| old.api_key)
|
||||
.unwrap_or_default()
|
||||
};
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
pub fn save(root: &Path, meta: &Path, update: ConnectionUpdate) -> Result<Setup> {
|
||||
let (path, setting) = managed_connection(root)?;
|
||||
let active = unquote(&module_setting(root)?) == setting;
|
||||
let url = connection_url(&update.base_url)?;
|
||||
let base_url = url.as_str().trim_end_matches('/');
|
||||
let model = update.model.trim();
|
||||
if model.is_empty() || model.chars().any(char::is_control) {
|
||||
return Err(Error::Invalid("Enter a model name on a single line.".into()));
|
||||
}
|
||||
let previous = read_connection(&path)?;
|
||||
let key = connection_key(
|
||||
update.api_type, base_url, update.api_key.as_deref(), update.remove_key,
|
||||
previous.as_deref().map(parse).transpose()?,
|
||||
)?;
|
||||
let connection = Connection {
|
||||
api_type: update.api_type,
|
||||
base_url: base_url.into(),
|
||||
model: model.into(),
|
||||
api_key: key,
|
||||
request_timeout_sec: if matches!(update.api_type, ApiType::Ollama) { 60 } else { 30 },
|
||||
};
|
||||
fsx::atomic_write_private(&path, &serde_json::to_vec_pretty(&connection)?)?;
|
||||
if !active {
|
||||
let changes = BTreeMap::from([(PATH_SETTING.into(), setting)]);
|
||||
if let Err(error) = super::save_settings(root, meta, MODULE, &changes) {
|
||||
if let Some(bytes) = previous {
|
||||
fsx::atomic_write_private(&path, &bytes)?;
|
||||
} else {
|
||||
fs::remove_file(&path)?;
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(Setup { active: true, connection: Some(view(connection)) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn update(api_type: ApiType, base_url: &str, api_key: Option<&str>) -> ConnectionUpdate {
|
||||
ConnectionUpdate { api_type, base_url: base_url.into(), model: "example-model".into(),
|
||||
api_key: api_key.map(str::to_owned), remove_key: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_setup_preserves_manual_files_and_only_reuses_keys_for_the_same_endpoint() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let meta = root.join("metadata");
|
||||
let configs = root.join("Core/configs/modules");
|
||||
fs::create_dir_all(&meta).unwrap();
|
||||
fs::create_dir_all(&configs).unwrap();
|
||||
fs::write(configs.join("playerbots_characters.conf.dist"),
|
||||
"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = ../my-custom.jsonc\n").unwrap();
|
||||
fs::write(root.join("my-custom.jsonc"), b"// manual connection").unwrap();
|
||||
assert!(!load(root).unwrap().active);
|
||||
|
||||
let base_url = "https://api.example.com/v1";
|
||||
let saved = save(root, &meta, update(ApiType::Openai, base_url, Some("fixture-key"))).unwrap();
|
||||
assert!(saved.active && saved.connection.as_ref().unwrap().has_key);
|
||||
assert!(!serde_json::to_string(&saved).unwrap().contains("fixture-key"));
|
||||
assert!(save(root, &meta, update(ApiType::Openai, base_url, None)).unwrap().connection.unwrap().has_key);
|
||||
let mut clear = update(ApiType::Openai, base_url, None);
|
||||
clear.remove_key = true;
|
||||
assert!(!save(root, &meta, clear).unwrap().connection.unwrap().has_key);
|
||||
save(root, &meta, update(ApiType::Openai, base_url, Some("replacement-key"))).unwrap();
|
||||
let changed = save(root, &meta, update(ApiType::Ollama, "http://127.0.0.1:11434", None)).unwrap();
|
||||
assert!(!changed.connection.unwrap().has_key);
|
||||
assert!(save(root, &meta, update(ApiType::Openai, "https://user:secret@example.com", None)).is_err());
|
||||
assert_eq!(fs::read(root.join("my-custom.jsonc")).unwrap(), b"// manual connection");
|
||||
let config = fs::read_to_string(configs.join("playerbots_characters.conf")).unwrap();
|
||||
assert!(config.contains("PBC.Enable = 0"));
|
||||
assert!(!config.contains("replacement-key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secondary_world_uses_the_shared_pbc_assets_and_keeps_custom_paths() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let config = "[worldserver]\nPBC.DefaultConnection = \"../Extras/PlayerbotCharacters/manager-connection.jsonc\"\nPBC.PromptsPath = \"../Extras/PlayerbotCharacters/prompts\"\nPBC.UtilityConnection = \"custom.jsonc\"\n";
|
||||
let result = rebase_packaged_paths(config, temp.path()).unwrap();
|
||||
let result = ConfFile::parse_bytes(result.as_bytes()).unwrap();
|
||||
let expected = temp.path().join(ASSET_DIR).to_string_lossy().replace('\\', "/");
|
||||
assert_eq!(result.get(PATH_SETTING).map(unquote), Some(format!("{expected}/manager-connection.jsonc").as_str()));
|
||||
assert_eq!(result.get("PBC.PromptsPath").map(unquote), Some(format!("{expected}/prompts").as_str()));
|
||||
assert_eq!(result.get("PBC.UtilityConnection").map(unquote), Some("custom.jsonc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_realm_saves_its_own_model_connection() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let config = root.join("Core/configs/modules/playerbots_characters.conf");
|
||||
let meta = root.join("metadata");
|
||||
fsx::atomic_write(&config, b"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = \"\"\n").unwrap();
|
||||
let (coa_path, _) = managed_connection(root).unwrap();
|
||||
let endpoint = "https://example.test/v1";
|
||||
save(root, &meta, update(ApiType::Openai, endpoint, Some("coa-key"))).unwrap();
|
||||
let coa_config = fs::read(&config).unwrap();
|
||||
let coa_connection = fs::read(&coa_path).unwrap();
|
||||
|
||||
let state = root.join("Settings/realm-profile.json");
|
||||
let mut realm_state = realms::RealmState {
|
||||
active: Mode::Wildcard,
|
||||
wildcard_created: true,
|
||||
..Default::default()
|
||||
};
|
||||
fsx::atomic_write_json(&state, &realm_state).unwrap();
|
||||
let (wildcard_path, _) = managed_connection(root).unwrap();
|
||||
assert_ne!(coa_path, wildcard_path);
|
||||
assert!(load(root).unwrap().connection.is_none());
|
||||
let mut wildcard = update(ApiType::Openai, endpoint, None);
|
||||
wildcard.model = "wildcard-model".into();
|
||||
let saved = save(root, &meta, wildcard).unwrap().connection.unwrap();
|
||||
assert!(!saved.has_key);
|
||||
assert_eq!(saved.model, "wildcard-model");
|
||||
assert_eq!(fs::read(&coa_path).unwrap(), coa_connection);
|
||||
|
||||
realm_state.active = Mode::Coa;
|
||||
fsx::atomic_write_json(&state, &realm_state).unwrap();
|
||||
fsx::atomic_write(&config, &coa_config).unwrap();
|
||||
let restored = load(root).unwrap();
|
||||
assert!(restored.active && restored.connection.unwrap().has_key);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
//! Read-only model discovery for the endpoint being edited in the Manager.
|
||||
use reqwest::blocking::Client;
|
||||
use reqwest::header::{self, HeaderMap, HeaderValue};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
use super::{connection_key, connection_url, managed_connection, module_setting, parse, read_connection, ApiType};
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_PAGE_BYTES: u64 = 4 * 1024 * 1024;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Request {
|
||||
pub api_type: ApiType,
|
||||
pub base_url: String,
|
||||
pub api_key: Option<String>,
|
||||
pub remove_key: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Model {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CatalogPage {
|
||||
data: Vec<ApiModel>,
|
||||
#[serde(default)]
|
||||
has_more: bool,
|
||||
last_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ApiModel {
|
||||
id: String,
|
||||
display_name: Option<String>,
|
||||
name: Option<String>,
|
||||
lifecycle: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OllamaList {
|
||||
models: Vec<OllamaModel>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OllamaModel {
|
||||
model: Option<String>,
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
fn request_headers(api_type: ApiType, key: &str) -> Result<HeaderMap> {
|
||||
let mut headers = HeaderMap::new();
|
||||
if api_type == ApiType::Anthropic {
|
||||
// Match the Claude API version and credential format used for dialogue in mod-pbc.
|
||||
headers.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));
|
||||
headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
}
|
||||
if !key.is_empty() {
|
||||
let (name, value) = if api_type == ApiType::Anthropic {
|
||||
(header::HeaderName::from_static("x-api-key"), key.to_owned())
|
||||
} else {
|
||||
(header::AUTHORIZATION, format!("Bearer {key}"))
|
||||
};
|
||||
let mut value = HeaderValue::from_str(&value)
|
||||
.map_err(|_| Error::Invalid("The API key contains unsupported characters.".into()))?;
|
||||
value.set_sensitive(true);
|
||||
headers.insert(name, value);
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
pub fn list(root: &Path, request: Request) -> Result<Vec<Model>> {
|
||||
module_setting(root)?;
|
||||
let mut url = connection_url(&request.base_url)?;
|
||||
let (path, _) = managed_connection(root)?;
|
||||
let previous = read_connection(&path)?;
|
||||
let key = connection_key(
|
||||
request.api_type, url.as_str().trim_end_matches('/'), request.api_key.as_deref(),
|
||||
request.remove_key, previous.as_deref().map(parse).transpose()?,
|
||||
)?;
|
||||
let mut path = url.path_segments_mut()
|
||||
.map_err(|_| Error::Invalid("Enter a valid model API base URL.".into()))?;
|
||||
path.pop_if_empty();
|
||||
if request.api_type == ApiType::Ollama {
|
||||
path.extend(["api", "tags"]);
|
||||
} else {
|
||||
path.push("models");
|
||||
}
|
||||
drop(path);
|
||||
let headers = request_headers(request.api_type, &key)?;
|
||||
let client = Client::builder()
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.map_err(|_| Error::Invalid("Could not start the model list request.".into()))?;
|
||||
|
||||
let deadline = Instant::now() + TIMEOUT;
|
||||
let mut models = BTreeMap::new();
|
||||
let mut cursor = None::<String>;
|
||||
let mut seen_cursors = HashSet::new();
|
||||
loop {
|
||||
let mut page_url = url.clone();
|
||||
if let Some(cursor) = &cursor {
|
||||
page_url.query_pairs_mut().append_pair("after_id", cursor);
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return Err(Error::Invalid("The model list request timed out.".into()));
|
||||
}
|
||||
let response = client.get(page_url).headers(headers.clone()).timeout(remaining).send()
|
||||
.map_err(|error| Error::Invalid(if error.is_timeout() {
|
||||
"The model list request timed out."
|
||||
} else {
|
||||
"Could not reach the model endpoint."
|
||||
}.into()))?;
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
return Err(Error::Invalid(format!("The provider returned HTTP {status} for its model list.")));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
response.take(MAX_PAGE_BYTES + 1).read_to_end(&mut body)
|
||||
.map_err(|_| Error::Invalid("Could not read the provider's model list.".into()))?;
|
||||
if body.len() as u64 > MAX_PAGE_BYTES {
|
||||
return Err(Error::Invalid("The provider returned an oversized model list.".into()));
|
||||
}
|
||||
let invalid_list = |_| Error::Invalid("The endpoint did not return a model list.".into());
|
||||
if request.api_type == ApiType::Ollama {
|
||||
let list: OllamaList = serde_json::from_slice(&body).map_err(invalid_list)?;
|
||||
for model in list.models {
|
||||
if let Some(id) = present(model.model).or_else(|| present(model.name)) {
|
||||
models.insert(id.clone(), id);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
let page: CatalogPage = serde_json::from_slice(&body).map_err(invalid_list)?;
|
||||
for model in page.data {
|
||||
if model.lifecycle.as_deref() == Some("retired") || model.id.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let name = present(model.display_name).or_else(|| present(model.name))
|
||||
.unwrap_or_else(|| model.id.clone());
|
||||
models.insert(model.id, name);
|
||||
}
|
||||
if !page.has_more {
|
||||
break;
|
||||
}
|
||||
cursor = page.last_id.filter(|value| !value.is_empty() && seen_cursors.insert(value.clone()));
|
||||
if cursor.is_none() {
|
||||
return Err(Error::Invalid("The provider returned an invalid model list cursor.".into()));
|
||||
}
|
||||
}
|
||||
|
||||
let mut choices: Vec<_> = models.into_iter().map(|(id, name)| Model { id, name }).collect();
|
||||
choices.sort_by_cached_key(|model| model.name.to_lowercase());
|
||||
Ok(choices)
|
||||
}
|
||||
|
||||
fn present(value: Option<String>) -> Option<String> {
|
||||
value.filter(|text| !text.trim().is_empty())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::pbc::{self, ConnectionUpdate};
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::thread::{self, JoinHandle};
|
||||
|
||||
fn server(pages: Vec<(&'static str, &'static str, &'static str)>) -> (String, JoinHandle<Vec<String>>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let worker = thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
pages.into_iter().map(|(status, headers, body)| {
|
||||
let mut socket = loop {
|
||||
match listener.accept() {
|
||||
Ok((socket, _)) => break socket,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock && Instant::now() < deadline => {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(error) => panic!("Mock model endpoint did not receive its request: {error}"),
|
||||
}
|
||||
};
|
||||
socket.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let mut request = String::new();
|
||||
let mut reader = BufReader::new(&socket);
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
request.push_str(&line.to_ascii_lowercase());
|
||||
}
|
||||
write!(socket, "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n{headers}\r\n{body}", body.len()).unwrap();
|
||||
request
|
||||
}).collect()
|
||||
});
|
||||
(format!("http://127.0.0.1:{port}"), worker)
|
||||
}
|
||||
|
||||
fn install() -> tempfile::TempDir {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let configs = root.path().join("Core/configs/modules");
|
||||
fs::create_dir_all(&configs).unwrap();
|
||||
fs::write(configs.join("playerbots_characters.conf.dist"),
|
||||
"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = ../connection.jsonc\n").unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
fn request(api_type: ApiType, base_url: &str, api_key: Option<&str>) -> Request {
|
||||
Request { api_type, base_url: base_url.into(), api_key: api_key.map(str::to_owned), remove_key: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_compatible_lists_current_models_and_reuses_the_matching_saved_key() {
|
||||
let root = install();
|
||||
let (endpoint, requests) = server(vec![
|
||||
("200 OK", "", r#"{"data":[{"id":"model-a"}]}"#),
|
||||
("200 OK", "", r#"{"data":[{"id":"model-b","name":"New Model"},{"id":"model-b","name":"New Model"}]}"#),
|
||||
]);
|
||||
let base = format!("{endpoint}/proxy/v1");
|
||||
pbc::save(root.path(), &root.path().join("metadata"), ConnectionUpdate {
|
||||
api_type: ApiType::Openai, base_url: base.clone(), model: "saved-model".into(),
|
||||
api_key: Some("fixture-secret".into()), remove_key: false,
|
||||
}).unwrap();
|
||||
let (path, _) = managed_connection(root.path()).unwrap();
|
||||
let saved = fs::read(&path).unwrap();
|
||||
|
||||
let models = list(root.path(), request(ApiType::Openai, &base, None)).unwrap();
|
||||
assert_eq!(models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["model-a"]);
|
||||
let refreshed = list(root.path(), request(ApiType::Openai, &base, Some("new-draft-key"))).unwrap();
|
||||
assert_eq!(refreshed.len(), 1);
|
||||
assert_eq!((&*refreshed[0].id, &*refreshed[0].name), ("model-b", "New Model"));
|
||||
assert_eq!(fs::read(path).unwrap(), saved);
|
||||
let requests = requests.join().unwrap();
|
||||
assert!(requests.iter().all(|r| r.starts_with("get /proxy/v1/models ")));
|
||||
assert!(requests[0].contains("authorization: bearer fixture-secret\r\n"));
|
||||
assert!(requests[1].contains("authorization: bearer new-draft-key\r\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ollama_lists_installed_models_without_reusing_a_key_for_another_endpoint() {
|
||||
let root = install();
|
||||
pbc::save(root.path(), &root.path().join("metadata"), ConnectionUpdate {
|
||||
api_type: ApiType::Ollama, base_url: "http://127.0.0.1:11434".into(), model: "saved-model".into(),
|
||||
api_key: Some("fixture-secret".into()), remove_key: false,
|
||||
}).unwrap();
|
||||
let (endpoint, requests) = server(vec![
|
||||
("200 OK", "", r#"{"models":[{"model":"qwen:7b","name":"alternate"},{"name":"gemma:4b"}]}"#),
|
||||
]);
|
||||
let models = list(root.path(), request(ApiType::Ollama, &endpoint, None)).unwrap();
|
||||
assert_eq!(models.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["gemma:4b", "qwen:7b"]);
|
||||
let requests = requests.join().unwrap();
|
||||
assert!(requests[0].starts_with("get /api/tags "));
|
||||
assert!(!requests[0].contains("authorization:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anthropic_follows_cursors_and_keeps_display_names_and_exact_ids() {
|
||||
let root = install();
|
||||
let (endpoint, requests) = server(vec![
|
||||
("200 OK", "", r#"{"data":[{"id":"claude-sonnet-test","display_name":"Claude Sonnet Test"}],"has_more":true,"last_id":"opaque/page+1"}"#),
|
||||
("200 OK", "", r#"{"data":[{"id":"claude-haiku-test","display_name":"Claude Haiku Test"},{"id":"retired-test","lifecycle":"retired"}],"has_more":false}"#),
|
||||
]);
|
||||
let models = list(root.path(), request(ApiType::Anthropic, &format!("{endpoint}/v1"), Some("fixture-key"))).unwrap();
|
||||
assert_eq!(models.iter().map(|m| (&*m.id, &*m.name)).collect::<Vec<_>>(), [
|
||||
("claude-haiku-test", "Claude Haiku Test"), ("claude-sonnet-test", "Claude Sonnet Test"),
|
||||
]);
|
||||
let requests = requests.join().unwrap();
|
||||
assert!(requests[0].starts_with("get /v1/models "));
|
||||
assert!(requests[1].starts_with("get /v1/models?after_id=opaque%2fpage%2b1 "));
|
||||
for request in requests {
|
||||
assert!(request.contains("anthropic-version: 2023-06-01\r\n"));
|
||||
assert!(request.contains("x-api-key: fixture-key\r\n"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redirects_and_http_errors_keep_the_connection_file_and_do_not_expose_the_key() {
|
||||
let root = install();
|
||||
let (endpoint, requests) = server(vec![
|
||||
("302 Found", "Location: http://127.0.0.1:1/models\r\n", ""),
|
||||
("401 Unauthorized", "", "fixture-secret"),
|
||||
]);
|
||||
pbc::save(root.path(), &root.path().join("metadata"), ConnectionUpdate {
|
||||
api_type: ApiType::Openai, base_url: endpoint.clone(), model: "saved-model".into(),
|
||||
api_key: Some("fixture-secret".into()), remove_key: false,
|
||||
}).unwrap();
|
||||
let (path, _) = managed_connection(root.path()).unwrap();
|
||||
let saved = fs::read(&path).unwrap();
|
||||
let redirect = list(root.path(), request(ApiType::Openai, &endpoint, None)).err().unwrap();
|
||||
assert!(redirect.to_string().contains("302"));
|
||||
let mut no_auth = request(ApiType::Openai, &endpoint, None);
|
||||
no_auth.remove_key = true;
|
||||
let unauthorized = list(root.path(), no_auth).err().unwrap();
|
||||
assert!(unauthorized.to_string().contains("401"));
|
||||
assert!(!unauthorized.to_string().contains("fixture-secret"));
|
||||
let requests = requests.join().unwrap();
|
||||
assert!(requests[0].contains("authorization: bearer fixture-secret"));
|
||||
assert!(!requests[1].contains("authorization:"));
|
||||
assert_eq!(fs::read(path).unwrap(), saved);
|
||||
}
|
||||
}
|
||||
@@ -376,6 +376,8 @@ fn prepare(main: &Path, tree: Tree) -> Result<PathBuf> {
|
||||
conf.set("CoA.AllowRemoteClients", "1", &[]);
|
||||
}
|
||||
conf.to_text()
|
||||
} else if path == "Core/configs/modules/playerbots_characters.conf" {
|
||||
crate::modules::pbc::rebase_packaged_paths(&text, main)?
|
||||
} else {
|
||||
text
|
||||
};
|
||||
|
||||
@@ -327,6 +327,21 @@ impl Ra {
|
||||
Ok(out.lines().last().unwrap_or("").to_string())
|
||||
}
|
||||
|
||||
/// Log in up to `count` existing offline bots without creating new characters. Returns how many the server queued.
|
||||
/// A bots module that takes no count answers with its usage text: that is reported as unsupported.
|
||||
pub fn login_offline_bots(&mut self, count: u32) -> Result<u32> {
|
||||
if !(1..=5000).contains(&count) {
|
||||
return Err(Error::Invalid(
|
||||
"Choose between 1 and 5000 companions.".into(),
|
||||
));
|
||||
}
|
||||
let out = self.bot_command(&format!("botcmd loginall {count}"))?;
|
||||
if !out.contains("queued") {
|
||||
return Err(Error::CompanionCommandUnsupported);
|
||||
}
|
||||
Ok(first_number(&out).min(count))
|
||||
}
|
||||
|
||||
/// Set a new password for an existing account.
|
||||
pub fn set_account_password(&mut self, name: &str, password: &str) -> Result<()> {
|
||||
validate_account(name, password)?;
|
||||
@@ -625,6 +640,30 @@ AC>";
|
||||
assert_eq!(h.join().unwrap()[2], "botcmd spawnleveled 50");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_offline_bots_sends_count() {
|
||||
let _lock = serial();
|
||||
let (port, h) = fake_ra("BotMgr: queued 500 offline bot(s) for login.");
|
||||
let mut ra = Ra::connect_to(port, "u", "p").unwrap();
|
||||
assert_eq!(ra.login_offline_bots(500).unwrap(), 500);
|
||||
assert!(ra.login_offline_bots(0).is_err() && ra.login_offline_bots(6000).is_err());
|
||||
drop(ra);
|
||||
assert_eq!(h.join().unwrap()[2], "botcmd loginall 500");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_offline_bots_reports_a_module_without_a_count_as_unsupported() {
|
||||
let _lock = serial();
|
||||
let (port, h) = fake_ra("### USAGE: .botcmd loginall");
|
||||
let mut ra = Ra::connect_to(port, "u", "p").unwrap();
|
||||
assert!(matches!(
|
||||
ra.login_offline_bots(5),
|
||||
Err(Error::CompanionCommandUnsupported)
|
||||
));
|
||||
drop(ra);
|
||||
h.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_account_and_input_validation() {
|
||||
let _lock = serial();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -2362,6 +2362,38 @@ mod tests {
|
||||
w
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playerbot_characters_release_files_leave_host_connections_and_cards_in_place() {
|
||||
const DIST: &str = "Core/configs/modules/playerbots_characters.conf.dist";
|
||||
const CONFIG: &str = "Core/configs/modules/playerbots_characters.conf";
|
||||
const CONNECTION: &str = "Extras/PlayerbotCharacters/manager-connection.jsonc";
|
||||
const CARD: &str = "Extras/PlayerbotCharacters/cards/Companion.card.txt";
|
||||
const PROMPT: &str = "Extras/PlayerbotCharacters/prompts/enUS/CharacterContext.custom.txt";
|
||||
let defaults = b"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = \"\"\n";
|
||||
for configured in [false, true] {
|
||||
let w = world(&[(DIST, defaults), ("Extras/PlayerbotCharacters/cards/README.txt", b"Cards")], false);
|
||||
let host_config = b"[worldserver]\nPBC.Enable = 1\nPBC.DefaultConnection = ../Extras/PlayerbotCharacters/manager-connection.jsonc\n";
|
||||
if configured {
|
||||
write(&w.root, CONFIG, host_config);
|
||||
write(&w.root, CONNECTION, b"{\"apiKey\":\"fixture-only\"}");
|
||||
write(&w.root, CARD, b"My character card");
|
||||
write(&w.root, PROMPT, b"My custom prompt");
|
||||
}
|
||||
assert_eq!(run(&w, &Fake::ok(), BTreeMap::new(), None).unwrap().txn.state, State::Committed);
|
||||
assert_eq!(fs::read(w.root.join(DIST)).unwrap(), defaults);
|
||||
let module = crate::modules::list(&w.root).into_iter().find(|m| m.id == "mod-pbc").unwrap();
|
||||
assert!(module.installed && module.enabled == configured);
|
||||
if configured {
|
||||
assert_eq!(fs::read(w.root.join(CONFIG)).unwrap(), host_config);
|
||||
assert_eq!(fs::read(w.root.join(CONNECTION)).unwrap(), b"{\"apiKey\":\"fixture-only\"}");
|
||||
assert_eq!(fs::read(w.root.join(CARD)).unwrap(), b"My character card");
|
||||
assert_eq!(fs::read(w.root.join(PROMPT)).unwrap(), b"My custom prompt");
|
||||
} else {
|
||||
assert!(!w.root.join(CONNECTION).exists());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_waits_for_an_update_check_but_not_for_active_maintenance() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,6 +1,24 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"modules": [
|
||||
{
|
||||
"id": "mod-pbc",
|
||||
"name": "Playerbot Characters",
|
||||
"description": {
|
||||
"en": "Gives CoA Companions or SQUID Playerbots dialogue, personalities and memories. Requires a model connection you configure.",
|
||||
"ru": "Добавляет диалоги, характеры и воспоминания ботам CoA Companions или SQUID Playerbots. Нужно настроить подключение к модели.",
|
||||
"de": "Gibt CoA Companions oder SQUID Playerbots Dialoge, Persönlichkeiten und Erinnerungen. Die Verbindung zu einem KI-Modell muss eingerichtet werden.",
|
||||
"fr": "Ajoute des dialogues, des personnalités et des souvenirs aux bots CoA Companions ou SQUID Playerbots. Une connexion à un modèle doit être configurée.",
|
||||
"es": "Añade diálogos, personalidades y recuerdos a los bots de CoA Companions o SQUID Playerbots. Requiere configurar una conexión con un modelo.",
|
||||
"zh": "为 CoA Companions 或 SQUID Playerbots 添加对话、个性和记忆。需要自行配置模型连接。"
|
||||
},
|
||||
"repo": "https://github.com/deseven/mod-pbc#model-connection-setup",
|
||||
"conf": "playerbots_characters.conf",
|
||||
"enable_key": "PBC.Enable",
|
||||
"default_on": false,
|
||||
"status": "early",
|
||||
"icon": "bot"
|
||||
},
|
||||
{
|
||||
"id": "dungeon-clear",
|
||||
"name": "Dungeon Clear",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "coa-server-manager",
|
||||
"version": "0.9.15",
|
||||
"version": "0.9.18",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "coa-server-manager",
|
||||
"version": "0.9.15",
|
||||
"version": "0.9.18",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.12.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.0",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "coa-server-manager",
|
||||
"private": true,
|
||||
"version": "0.9.15",
|
||||
"version": "0.9.18",
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
+193
-44
@@ -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>,
|
||||
@@ -1621,6 +1710,40 @@ async fn module_save_settings(
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn pbc_connection(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
) -> std::result::Result<coa_core::modules::pbc::Setup, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
blocking(move || coa_core::modules::pbc::load(&root)).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn pbc_list_models(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
request: coa_core::modules::pbc::models::Request,
|
||||
) -> std::result::Result<Vec<coa_core::modules::pbc::models::Model>, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
blocking(move || coa_core::modules::pbc::models::list(&root, request)).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn pbc_save_connection(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
update: coa_core::modules::pbc::ConnectionUpdate,
|
||||
) -> std::result::Result<coa_core::modules::pbc::Setup, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||
blocking(move || {
|
||||
let (dir, _) = install_meta(&root)?;
|
||||
coa_core::modules::pbc::save(&root, &dir, update)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn all_settings(
|
||||
state: State<'_, AppState>,
|
||||
@@ -2154,6 +2277,7 @@ async fn add_companions(
|
||||
let meta = meta_dir(&root)?;
|
||||
let mut changes = BTreeMap::new();
|
||||
changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true));
|
||||
// Preserve the configured startup limit (CoaBots.AutoLogin.MaxCount); only set it when there is none.
|
||||
let existing_cfg = config::load(&target.world_root, Scope::Bots)?;
|
||||
let existing_max = existing_cfg
|
||||
.settings
|
||||
@@ -2161,13 +2285,12 @@ async fn add_companions(
|
||||
.find(|s| s.meta.key == "CoaBots.AutoLogin.MaxCount")
|
||||
.and_then(|s| s.value.as_u64())
|
||||
.unwrap_or(0) as u32;
|
||||
let already = coa_core::population::query_for_realm(&root, mode)
|
||||
.map(|p| p.bots_total)
|
||||
.unwrap_or(0);
|
||||
changes.insert(
|
||||
"CoaBots.AutoLogin.MaxCount".to_string(),
|
||||
Value::from(existing_max.max(already + count).min(5000)),
|
||||
);
|
||||
if existing_max == 0 {
|
||||
changes.insert(
|
||||
"CoaBots.AutoLogin.MaxCount".to_string(),
|
||||
Value::from(count.min(5000)),
|
||||
);
|
||||
}
|
||||
config::save(&target.world_root, &meta, Scope::Bots, &changes)?;
|
||||
|
||||
let mut baseline = None;
|
||||
@@ -2175,14 +2298,33 @@ async fn add_companions(
|
||||
if let Ok(admin_db) = coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin) {
|
||||
let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, target.chars_db);
|
||||
}
|
||||
baseline = coa_core::population::query_for_realm(&root, mode)
|
||||
.ok()
|
||||
.map(|p| p.bots_total);
|
||||
let population = coa_core::population::query_for_realm(&root, mode).ok();
|
||||
baseline = population.as_ref().map(|p| p.bots_total);
|
||||
let mut ra = Ra::connect_target(&root, Some(mode))?;
|
||||
if let Some(lvl) = level {
|
||||
Some(ra.spawn_custom(count, lvl, class_id, spec_id, archetype.as_deref())?)
|
||||
} else {
|
||||
Some(ra.spawn_bots(count)?)
|
||||
// Bots that already exist and are offline come back first; only the rest are created.
|
||||
let offline = population
|
||||
.as_ref()
|
||||
.map(|p| p.bots_total.saturating_sub(p.bots_online))
|
||||
.unwrap_or(0);
|
||||
let mut reused = 0;
|
||||
if offline > 0 {
|
||||
match ra.login_offline_bots(count.min(offline)) {
|
||||
Ok(queued) => reused = queued,
|
||||
// An older bots module cannot log in a given number: create them all, as before.
|
||||
Err(Error::CompanionCommandUnsupported) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
// The progress bar counts from the baseline, so reused bots count as done.
|
||||
baseline = baseline.map(|total| total.saturating_sub(reused));
|
||||
if count > reused {
|
||||
Some(ra.spawn_bots(count - reused)?)
|
||||
} else {
|
||||
Some(format!("BotMgr: queued {reused} offline bot(s) for login."))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let _ = coa_core::companions::migrate_legacy_pending_job(&meta, &id);
|
||||
@@ -2591,7 +2733,7 @@ fn open_link(url: String) -> std::result::Result<(), UiError> {
|
||||
"https://login.tailscale.com/",
|
||||
"https://portforward.com/",
|
||||
"https://github.com/Corfirean/",
|
||||
"https://coa-development.org/",
|
||||
"https://conquestofazerothcore.to/",
|
||||
];
|
||||
// A prefilled "new issue" page of one of the places a report can go (the Manager, Companions, SQUID Playerbots): the
|
||||
// address must be exactly that page, and its query may carry `&` between the (percent-encoded) title and text.
|
||||
@@ -3062,7 +3204,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,
|
||||
@@ -3125,6 +3270,9 @@ pub fn run() {
|
||||
repair_server,
|
||||
module_set_enabled,
|
||||
module_settings,
|
||||
pbc_connection,
|
||||
pbc_list_models,
|
||||
pbc_save_connection,
|
||||
module_save_settings,
|
||||
all_settings,
|
||||
all_settings_save,
|
||||
@@ -3152,6 +3300,7 @@ pub fn run() {
|
||||
report_targets,
|
||||
companion_sizes,
|
||||
add_companions,
|
||||
top_up_startup_fleet,
|
||||
get_wildcard_archetypes,
|
||||
remote_connection,
|
||||
remote_connect,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "CoA Server Manager",
|
||||
"version": "0.9.15",
|
||||
"version": "0.9.18",
|
||||
"identifier": "com.coa.servermanager",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
|
||||
@@ -52,7 +52,19 @@
|
||||
"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": "Перезапускайте мир каждую неделю в выбранный день и время",
|
||||
"The game client link points to the new community site, conquestofazerothcore.to": "Ссылка на клиент игры ведёт на новый сайт сообщества conquestofazerothcore.to",
|
||||
"Configure Playerbot Characters from the Modules page": "Настройка Playerbot Characters на странице «Модули»",
|
||||
"Choose Playerbot Characters models from a live provider list": "Выбор модели Playerbot Characters из актуального списка провайдера",
|
||||
"Settings now shows the server version and update button after you have checked for updates": "После проверки обновлений в настройках снова видны версия сервера и кнопка обновления",
|
||||
"Adding companions reuses offline bots and keeps your startup limit": "При добавлении компаньонов сначала входят уже созданные боты, а лимит запуска не меняется",
|
||||
"Custom Races installs the 2.0.3 client with the Snagtooth race": "Custom Races устанавливает клиент 2.0.3 с расой Snagtooth"
|
||||
},
|
||||
"de": {
|
||||
"Choose Parallel or Global level scaling in module settings": "Parallele oder globale Levelskalierung in den Moduleinstellungen wählen",
|
||||
@@ -106,7 +118,19 @@
|
||||
"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",
|
||||
"The game client link points to the new community site, conquestofazerothcore.to": "Der Link zum Spielclient führt jetzt zur neuen Community-Website conquestofazerothcore.to",
|
||||
"Configure Playerbot Characters from the Modules page": "Playerbot Characters auf der Modulseite einrichten",
|
||||
"Choose Playerbot Characters models from a live provider list": "Modelle für Playerbot Characters aus der aktuellen Anbieterliste wählen",
|
||||
"Settings now shows the server version and update button after you have checked for updates": "Die Einstellungen zeigen nach der Updatesuche wieder Serverversion und Aktualisieren-Knopf",
|
||||
"Adding companions reuses offline bots and keeps your startup limit": "Beim Hinzufügen von Begleitern werden vorhandene Bots genutzt, das Startlimit bleibt erhalten",
|
||||
"Custom Races installs the 2.0.3 client with the Snagtooth race": "Custom Races installiert den Client 2.0.3 mit dem Volk der Snagtooth"
|
||||
},
|
||||
"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 +184,19 @@
|
||||
"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",
|
||||
"The game client link points to the new community site, conquestofazerothcore.to": "Le lien vers le client du jeu mène au nouveau site de la communauté, conquestofazerothcore.to",
|
||||
"Configure Playerbot Characters from the Modules page": "Configurez Playerbot Characters depuis la page Modules",
|
||||
"Choose Playerbot Characters models from a live provider list": "Choisissez les modèles de Playerbot Characters dans la liste à jour du fournisseur",
|
||||
"Settings now shows the server version and update button after you have checked for updates": "Les réglages affichent à nouveau la version du serveur et le bouton de mise à jour après une recherche",
|
||||
"Adding companions reuses offline bots and keeps your startup limit": "L’ajout de compagnons réutilise les bots hors ligne et conserve votre limite au démarrage",
|
||||
"Custom Races installs the 2.0.3 client with the Snagtooth race": "Custom Races installe le client 2.0.3 avec la race Snagtooth"
|
||||
},
|
||||
"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 +250,19 @@
|
||||
"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",
|
||||
"The game client link points to the new community site, conquestofazerothcore.to": "El enlace al cliente del juego apunta al nuevo sitio de la comunidad, conquestofazerothcore.to",
|
||||
"Configure Playerbot Characters from the Modules page": "Configura Playerbot Characters desde la página Módulos",
|
||||
"Choose Playerbot Characters models from a live provider list": "Elige los modelos de Playerbot Characters en la lista actual del proveedor",
|
||||
"Settings now shows the server version and update button after you have checked for updates": "Ajustes vuelve a mostrar la versión del servidor y el botón de actualizar tras buscar actualizaciones",
|
||||
"Adding companions reuses offline bots and keeps your startup limit": "Al añadir compañeros se reutilizan los bots desconectados y se mantiene tu límite de inicio",
|
||||
"Custom Races installs the 2.0.3 client with the Snagtooth race": "Custom Races instala el cliente 2.0.3 con la raza Snagtooth"
|
||||
},
|
||||
"zh": {
|
||||
"Choose Parallel or Global level scaling in module settings": "在模块设置中选择并行或全局等级缩放",
|
||||
@@ -268,7 +316,19 @@
|
||||
"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": "每周在选定的日期和时间重启世界",
|
||||
"The game client link points to the new community site, conquestofazerothcore.to": "游戏客户端链接现指向新的社区网站 conquestofazerothcore.to",
|
||||
"Configure Playerbot Characters from the Modules page": "在模块页面中配置 Playerbot Characters",
|
||||
"Choose Playerbot Characters models from a live provider list": "从服务商的实时列表中选择 Playerbot Characters 的模型",
|
||||
"Settings now shows the server version and update button after you have checked for updates": "检查更新后,设置页面会正常显示服务器版本和更新按钮",
|
||||
"Adding companions reuses offline bots and keeps your startup limit": "添加同伴时会优先使用离线机器人,并保留你的启动登录上限",
|
||||
"Custom Races installs the 2.0.3 client with the Snagtooth race": "Custom Races 现在安装包含 Snagtooth 种族的 2.0.3 客户端"
|
||||
}
|
||||
},
|
||||
"server": {
|
||||
|
||||
+3
-1
@@ -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};}
|
||||
|
||||
+41
-1
@@ -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.",
|
||||
|
||||
@@ -648,7 +650,7 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"client.setup.title": "Spielclient einrichten",
|
||||
"client.setup.intro": "Zum Spielen brauchst du den Spielclient. Die Community gibt ihn über ihren offiziellen Launcher heraus.",
|
||||
"client.setup.have": "Ich habe bereits einen Client",
|
||||
"client.setup.getLauncher": "Launcher holen (coa-development.org)",
|
||||
"client.setup.getLauncher": "Launcher holen (conquestofazerothcore.to)",
|
||||
"client.setup.getLauncherHint": "Öffnet die Website der Community im Browser. Lade dort den Launcher herunter, installiere ihn, melde dich mit deinem Konto an und lass ihn das Spiel laden (etwa 43 GB).",
|
||||
"client.setup.haveHint": "Wähle den Ordner, in den der Launcher das Spiel installiert hat, oder eine andere Kopie des Clients.",
|
||||
"client.setup.hdHint": "Standard- oder HD-Grafik wählst du im Launcher: Öffne dort die Einstellungen und schalte „HD graphics“ um. Der Manager kann das nicht ändern.",
|
||||
@@ -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.",
|
||||
@@ -833,7 +844,29 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.restart": "Änderungen werden nach einem Neustart des Weltservers wirksam.",
|
||||
"mod.switch": "{name} ein- oder ausschalten",
|
||||
"mod.notHere": "Nicht Teil dieses Servers",
|
||||
"mod.pbc.chooseModel": "Modell auswählen",
|
||||
"mod.pbc.searchModels": "Modelle suchen",
|
||||
"mod.pbc.manualModel": "Modell-ID manuell eingeben",
|
||||
"mod.pbc.browseModels": "Modelle durchsuchen",
|
||||
"mod.pbc.refreshModels": "Modelle aktualisieren",
|
||||
"mod.pbc.loadingModels": "Modelle werden geladen…",
|
||||
"mod.pbc.modelListFailed": "Modelle konnten nicht geladen werden. Prüfe den Endpunkt und den API-Schlüssel oder gib eine Modell-ID ein.",
|
||||
"mod.pbc.noModels": "Keine Modelle gefunden.",
|
||||
"mod.pbc.modelListNeedsUrl": "Gib die API-Basis-URL ein, um Modelle zu laden.",
|
||||
"mod.pbc.modelListNeedsKey": "Gib einen API-Schlüssel ein, um Modelle zu laden.",
|
||||
"mod.github": "GitHub",
|
||||
"mod.pbc.connection": "Modellverbindung",
|
||||
"mod.pbc.provider": "Modellanbieter",
|
||||
"mod.pbc.compatible": "OpenAI-kompatibler Endpunkt",
|
||||
"mod.pbc.model": "Modellname",
|
||||
"mod.pbc.endpoint": "API-Basis-URL",
|
||||
"mod.pbc.key": "API-Schlüssel",
|
||||
"mod.pbc.savedKey": "Schlüssel gespeichert",
|
||||
"mod.pbc.removeKey": "Gespeicherten Schlüssel löschen",
|
||||
"mod.pbc.keyHint": "Lass das Feld leer, um den Schlüssel für denselben Endpunkt zu behalten. Lokales Ollama braucht meist keinen Schlüssel.",
|
||||
"mod.pbc.save": "Modellverbindung speichern",
|
||||
"mod.pbc.saved": "Modellverbindung gespeichert.",
|
||||
"mod.pbc.useConnection": "Beim Speichern wird diese Verbindung als Standard für mod-pbc auf dem Server festgelegt.",
|
||||
"mod.settings": "Einstellungen",
|
||||
"mod.default": "Zurück zum Standard ({v})",
|
||||
"mod.saved": "Gespeichert ({n} geändert).",
|
||||
@@ -1099,6 +1132,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.",
|
||||
};
|
||||
|
||||
|
||||
+41
-1
@@ -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.",
|
||||
|
||||
@@ -747,7 +758,7 @@ const en = {
|
||||
"client.setup.title": "Set up the game client",
|
||||
"client.setup.intro": "To play you need the game client. The community hands it out through its official launcher.",
|
||||
"client.setup.have": "I already have a client",
|
||||
"client.setup.getLauncher": "Get the launcher (coa-development.org)",
|
||||
"client.setup.getLauncher": "Get the launcher (conquestofazerothcore.to)",
|
||||
"client.setup.getLauncherHint": "Opens the community website in your browser. Download and install the launcher there, sign in with your account and let it download the game (about 43 GB).",
|
||||
"client.setup.haveHint": "Pick the folder the launcher installed the game to, or any other copy of the client.",
|
||||
"client.setup.hdHint": "Standard or HD graphics is chosen in the launcher: open its Settings and switch \"HD graphics\". The Manager cannot change it.",
|
||||
@@ -879,7 +890,29 @@ const en = {
|
||||
"mod.restart": "Changes apply after the world server restarts.",
|
||||
"mod.switch": "Turn {name} on or off",
|
||||
"mod.notHere": "Not part of this server",
|
||||
"mod.pbc.chooseModel": "Choose a model",
|
||||
"mod.pbc.searchModels": "Search models",
|
||||
"mod.pbc.manualModel": "Enter model ID manually",
|
||||
"mod.pbc.browseModels": "Browse models",
|
||||
"mod.pbc.refreshModels": "Refresh models",
|
||||
"mod.pbc.loadingModels": "Loading models…",
|
||||
"mod.pbc.modelListFailed": "Couldn’t load models. Check the endpoint and API key, or enter a model ID manually.",
|
||||
"mod.pbc.noModels": "No models found.",
|
||||
"mod.pbc.modelListNeedsUrl": "Enter the API base URL to load models.",
|
||||
"mod.pbc.modelListNeedsKey": "Enter an API key to load models.",
|
||||
"mod.github": "GitHub",
|
||||
"mod.pbc.connection": "Model connection",
|
||||
"mod.pbc.provider": "Model provider",
|
||||
"mod.pbc.compatible": "OpenAI-compatible endpoint",
|
||||
"mod.pbc.model": "Model name",
|
||||
"mod.pbc.endpoint": "API base URL",
|
||||
"mod.pbc.key": "API key",
|
||||
"mod.pbc.savedKey": "Saved key",
|
||||
"mod.pbc.removeKey": "Remove saved key",
|
||||
"mod.pbc.keyHint": "Leave the key blank to keep it for the same endpoint. Local Ollama usually needs no key.",
|
||||
"mod.pbc.save": "Save model connection",
|
||||
"mod.pbc.saved": "Model connection saved.",
|
||||
"mod.pbc.useConnection": "Saving makes this the server’s default mod-pbc connection.",
|
||||
"mod.settings": "Settings",
|
||||
"mod.default": "Back to the default ({v})",
|
||||
"mod.saved": "Saved ({n} changed).",
|
||||
@@ -1309,6 +1342,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;
|
||||
|
||||
|
||||
+41
-1
@@ -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.",
|
||||
|
||||
@@ -648,7 +650,7 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"client.setup.title": "Configurar el cliente del juego",
|
||||
"client.setup.intro": "Para jugar necesitas el cliente del juego. La comunidad lo entrega a través de su launcher oficial.",
|
||||
"client.setup.have": "Ya tengo un cliente",
|
||||
"client.setup.getLauncher": "Obtener el launcher (coa-development.org)",
|
||||
"client.setup.getLauncher": "Obtener el launcher (conquestofazerothcore.to)",
|
||||
"client.setup.getLauncherHint": "Abre la web de la comunidad en tu navegador. Descarga e instala allí el launcher, inicia sesión con tu cuenta y deja que descargue el juego (unos 43 GB).",
|
||||
"client.setup.haveHint": "Elige la carpeta donde el launcher instaló el juego, o cualquier otra copia del cliente.",
|
||||
"client.setup.hdHint": "Los gráficos estándar o HD se eligen en el launcher: abre sus Ajustes y cambia «HD graphics». El Manager no puede cambiarlo.",
|
||||
@@ -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.",
|
||||
@@ -833,7 +844,29 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.restart": "Los cambios se aplican al reiniciar el servidor del mundo.",
|
||||
"mod.switch": "Activar o desactivar {name}",
|
||||
"mod.notHere": "No forma parte de este servidor",
|
||||
"mod.pbc.chooseModel": "Elegir un modelo",
|
||||
"mod.pbc.searchModels": "Buscar modelos",
|
||||
"mod.pbc.manualModel": "Introducir el ID del modelo manualmente",
|
||||
"mod.pbc.browseModels": "Explorar modelos",
|
||||
"mod.pbc.refreshModels": "Actualizar modelos",
|
||||
"mod.pbc.loadingModels": "Cargando modelos…",
|
||||
"mod.pbc.modelListFailed": "No se pudieron cargar los modelos. Revisa el endpoint y la clave de API o introduce el ID del modelo manualmente.",
|
||||
"mod.pbc.noModels": "No se encontraron modelos.",
|
||||
"mod.pbc.modelListNeedsUrl": "Introduce la URL base de la API para cargar los modelos.",
|
||||
"mod.pbc.modelListNeedsKey": "Introduce una clave de API para cargar los modelos.",
|
||||
"mod.github": "GitHub",
|
||||
"mod.pbc.connection": "Conexión con el modelo",
|
||||
"mod.pbc.provider": "Proveedor del modelo",
|
||||
"mod.pbc.compatible": "Endpoint compatible con OpenAI",
|
||||
"mod.pbc.model": "Nombre del modelo",
|
||||
"mod.pbc.endpoint": "URL base de la API",
|
||||
"mod.pbc.key": "Clave de API",
|
||||
"mod.pbc.savedKey": "Clave guardada",
|
||||
"mod.pbc.removeKey": "Eliminar la clave guardada",
|
||||
"mod.pbc.keyHint": "Deja el campo vacío para conservar la clave del mismo endpoint. Ollama en local normalmente no necesita clave.",
|
||||
"mod.pbc.save": "Guardar la conexión",
|
||||
"mod.pbc.saved": "Conexión con el modelo guardada.",
|
||||
"mod.pbc.useConnection": "Al guardar, esta será la conexión predeterminada de mod-pbc en el servidor.",
|
||||
"mod.settings": "Ajustes",
|
||||
"mod.default": "Volver al valor por defecto ({v})",
|
||||
"mod.saved": "Guardado ({n} cambiado(s)).",
|
||||
@@ -1099,6 +1132,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.",
|
||||
};
|
||||
|
||||
|
||||
+41
-1
@@ -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.",
|
||||
|
||||
@@ -648,7 +650,7 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"client.setup.title": "Configurer le client du jeu",
|
||||
"client.setup.intro": "Pour jouer, il faut le client du jeu. La communauté le distribue via son lanceur officiel.",
|
||||
"client.setup.have": "J’ai déjà un client",
|
||||
"client.setup.getLauncher": "Obtenir le lanceur (coa-development.org)",
|
||||
"client.setup.getLauncher": "Obtenir le lanceur (conquestofazerothcore.to)",
|
||||
"client.setup.getLauncherHint": "Ouvre le site de la communauté dans votre navigateur. Téléchargez et installez-y le lanceur, connectez-vous avec votre compte et laissez-le télécharger le jeu (environ 43 Go).",
|
||||
"client.setup.haveHint": "Choisissez le dossier où le lanceur a installé le jeu, ou toute autre copie du client.",
|
||||
"client.setup.hdHint": "Les graphismes standard ou HD se choisissent dans le lanceur : ouvrez ses Paramètres et basculez « HD graphics ». Le Manager ne peut pas le modifier.",
|
||||
@@ -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.",
|
||||
@@ -833,7 +844,29 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.restart": "Les changements s’appliquent après le redémarrage du serveur de monde.",
|
||||
"mod.switch": "Activer ou désactiver {name}",
|
||||
"mod.notHere": "Ne fait pas partie de ce serveur",
|
||||
"mod.pbc.chooseModel": "Choisir un modèle",
|
||||
"mod.pbc.searchModels": "Rechercher des modèles",
|
||||
"mod.pbc.manualModel": "Saisir l’identifiant du modèle",
|
||||
"mod.pbc.browseModels": "Parcourir les modèles",
|
||||
"mod.pbc.refreshModels": "Actualiser les modèles",
|
||||
"mod.pbc.loadingModels": "Chargement des modèles…",
|
||||
"mod.pbc.modelListFailed": "Impossible de charger les modèles. Vérifiez le point d’accès et la clé API, ou saisissez l’identifiant du modèle.",
|
||||
"mod.pbc.noModels": "Aucun modèle trouvé.",
|
||||
"mod.pbc.modelListNeedsUrl": "Saisissez l’URL de base de l’API pour charger les modèles.",
|
||||
"mod.pbc.modelListNeedsKey": "Saisissez une clé API pour charger les modèles.",
|
||||
"mod.github": "GitHub",
|
||||
"mod.pbc.connection": "Connexion au modèle",
|
||||
"mod.pbc.provider": "Fournisseur du modèle",
|
||||
"mod.pbc.compatible": "Point d’accès compatible OpenAI",
|
||||
"mod.pbc.model": "Nom du modèle",
|
||||
"mod.pbc.endpoint": "URL de base de l’API",
|
||||
"mod.pbc.key": "Clé API",
|
||||
"mod.pbc.savedKey": "Clé enregistrée",
|
||||
"mod.pbc.removeKey": "Supprimer la clé enregistrée",
|
||||
"mod.pbc.keyHint": "Laissez le champ vide pour conserver la clé du même point d’accès. Ollama en local ne demande généralement pas de clé.",
|
||||
"mod.pbc.save": "Enregistrer la connexion",
|
||||
"mod.pbc.saved": "Connexion au modèle enregistrée.",
|
||||
"mod.pbc.useConnection": "Cette connexion deviendra la connexion par défaut de mod-pbc sur le serveur.",
|
||||
"mod.settings": "Réglages",
|
||||
"mod.default": "Revenir à la valeur par défaut ({v})",
|
||||
"mod.saved": "Enregistré ({n} modifié(s)).",
|
||||
@@ -1099,6 +1132,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.",
|
||||
};
|
||||
|
||||
|
||||
+41
-1
@@ -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.",
|
||||
|
||||
@@ -730,7 +741,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"client.setup.title": "Настройка клиента игры",
|
||||
"client.setup.intro": "Чтобы играть, нужен клиент игры. Сообщество выдаёт его через свой официальный лаунчер.",
|
||||
"client.setup.have": "У меня уже есть клиент",
|
||||
"client.setup.getLauncher": "Скачать лаунчер (coa-development.org)",
|
||||
"client.setup.getLauncher": "Скачать лаунчер (conquestofazerothcore.to)",
|
||||
"client.setup.getLauncherHint": "Откроет сайт сообщества в браузере. Скачайте и установите лаунчер, войдите в свой аккаунт и дайте ему скачать игру (около 43 ГБ).",
|
||||
"client.setup.haveHint": "Укажите папку, куда лаунчер установил игру, или любую другую копию клиента.",
|
||||
"client.setup.hdHint": "Стандартная или HD-графика выбирается в лаунчере: откройте его «Настройки» и переключите «HD graphics». Менеджер этого изменить не может.",
|
||||
@@ -862,7 +873,29 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.restart": "Изменения применятся после перезапуска игрового сервера.",
|
||||
"mod.switch": "Включить или выключить {name}",
|
||||
"mod.notHere": "Нет в этом сервере",
|
||||
"mod.pbc.chooseModel": "Выбрать модель",
|
||||
"mod.pbc.searchModels": "Поиск моделей",
|
||||
"mod.pbc.manualModel": "Ввести ID модели вручную",
|
||||
"mod.pbc.browseModels": "Список моделей",
|
||||
"mod.pbc.refreshModels": "Обновить список моделей",
|
||||
"mod.pbc.loadingModels": "Загрузка моделей…",
|
||||
"mod.pbc.modelListFailed": "Не удалось загрузить модели. Проверьте адрес и ключ API или введите ID модели вручную.",
|
||||
"mod.pbc.noModels": "Модели не найдены.",
|
||||
"mod.pbc.modelListNeedsUrl": "Введите базовый URL API для загрузки моделей.",
|
||||
"mod.pbc.modelListNeedsKey": "Введите ключ API для загрузки моделей.",
|
||||
"mod.github": "GitHub",
|
||||
"mod.pbc.connection": "Подключение к модели",
|
||||
"mod.pbc.provider": "Провайдер модели",
|
||||
"mod.pbc.compatible": "Эндпоинт, совместимый с OpenAI",
|
||||
"mod.pbc.model": "Имя модели",
|
||||
"mod.pbc.endpoint": "Базовый URL API",
|
||||
"mod.pbc.key": "Ключ API",
|
||||
"mod.pbc.savedKey": "Ключ сохранён",
|
||||
"mod.pbc.removeKey": "Удалить сохранённый ключ",
|
||||
"mod.pbc.keyHint": "Оставьте поле пустым, чтобы сохранить ключ для того же адреса. Локальной Ollama обычно ключ не нужен.",
|
||||
"mod.pbc.save": "Сохранить подключение",
|
||||
"mod.pbc.saved": "Подключение к модели сохранено.",
|
||||
"mod.pbc.useConnection": "После сохранения это подключение станет основным для mod-pbc на сервере.",
|
||||
"mod.settings": "Настройки",
|
||||
"mod.default": "Вернуть по умолчанию ({v})",
|
||||
"mod.saved": "Сохранено (изменено: {n}).",
|
||||
@@ -1292,6 +1325,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.",
|
||||
};
|
||||
|
||||
|
||||
+41
-1
@@ -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 之间的整数。",
|
||||
|
||||
@@ -701,7 +712,7 @@ const zh = {
|
||||
"client.setup.title": "配置游戏客户端",
|
||||
"client.setup.intro": "进行游戏需要安装客户端。社区通过其官方启动器提供客户端。",
|
||||
"client.setup.have": "已有游戏客户端",
|
||||
"client.setup.getLauncher": "获取启动器(coa-development.org)",
|
||||
"client.setup.getLauncher": "获取启动器(conquestofazerothcore.to)",
|
||||
"client.setup.getLauncherHint": "在浏览器中打开社区网站。在那里下载并安装启动器,用你的账号登录,让它下载游戏(约 43 GB)。",
|
||||
"client.setup.haveHint": "选择启动器安装游戏的文件夹,或任何其他客户端副本。",
|
||||
"client.setup.hdHint": "标准或高清画质在启动器中选择:打开启动器的“设置”,切换“HD graphics”。Manager 无法更改。",
|
||||
@@ -833,7 +844,29 @@ const zh = {
|
||||
"mod.restart": "更改将在世界服务器重启后生效。",
|
||||
"mod.switch": "开启或关闭 {name}",
|
||||
"mod.notHere": "未包含在当前服务器中",
|
||||
"mod.pbc.chooseModel": "选择模型",
|
||||
"mod.pbc.searchModels": "搜索模型",
|
||||
"mod.pbc.manualModel": "手动输入模型 ID",
|
||||
"mod.pbc.browseModels": "浏览模型",
|
||||
"mod.pbc.refreshModels": "刷新模型列表",
|
||||
"mod.pbc.loadingModels": "正在加载模型…",
|
||||
"mod.pbc.modelListFailed": "无法加载模型。请检查端点和 API 密钥,或手动输入模型 ID。",
|
||||
"mod.pbc.noModels": "未找到模型。",
|
||||
"mod.pbc.modelListNeedsUrl": "请输入 API 基础网址以加载模型。",
|
||||
"mod.pbc.modelListNeedsKey": "请输入 API 密钥以加载模型。",
|
||||
"mod.github": "GitHub 页面",
|
||||
"mod.pbc.connection": "模型连接",
|
||||
"mod.pbc.provider": "模型服务商",
|
||||
"mod.pbc.compatible": "兼容 OpenAI 的端点",
|
||||
"mod.pbc.model": "模型名称",
|
||||
"mod.pbc.endpoint": "API 基础网址",
|
||||
"mod.pbc.key": "API 密钥",
|
||||
"mod.pbc.savedKey": "已保存密钥",
|
||||
"mod.pbc.removeKey": "删除已保存的密钥",
|
||||
"mod.pbc.keyHint": "留空会保留同一端点的密钥。本地 Ollama 通常不需要密钥。",
|
||||
"mod.pbc.save": "保存模型连接",
|
||||
"mod.pbc.saved": "模型连接已保存。",
|
||||
"mod.pbc.useConnection": "保存后,此连接将成为该服务器上 mod-pbc 的默认连接。",
|
||||
"mod.settings": "模块设置",
|
||||
"mod.default": "恢复为默认值 ({v})",
|
||||
"mod.saved": "已保存(修改了 {n} 项)。",
|
||||
@@ -1101,6 +1134,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;
|
||||
|
||||
|
||||
+41
-1
@@ -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 }
|
||||
@@ -217,6 +229,26 @@ export interface RealmProfile {
|
||||
data: string;
|
||||
}
|
||||
|
||||
export type PbcApiType = "openai" | "ollama" | "anthropic";
|
||||
export interface PbcConnection {
|
||||
apiType: PbcApiType;
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
}
|
||||
export interface PbcConnectionSetup {
|
||||
active: boolean;
|
||||
connection: (PbcConnection & { hasKey: boolean }) | null;
|
||||
}
|
||||
export interface PbcConnectionUpdate extends PbcConnection {
|
||||
apiKey?: string;
|
||||
removeKey: boolean;
|
||||
}
|
||||
|
||||
export interface PbcModel {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ModuleView {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -502,7 +534,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 }),
|
||||
@@ -530,6 +565,9 @@ export const api = {
|
||||
realmlistDelete: (id: string, profileId: string) => invoke<void>("realmlist_delete", { id, profileId }),
|
||||
realmlistActivate: (id: string, profileId: string) => invoke<string[]>("realmlist_activate", { id, profileId }),
|
||||
modulesList: (id: string) => invoke<ModuleView[]>("modules_list", { id }),
|
||||
pbcConnection: (id: string) => invoke<PbcConnectionSetup>("pbc_connection", { id }),
|
||||
pbcListModels: (id: string, request: Omit<PbcConnectionUpdate, "model">) => invoke<PbcModel[]>("pbc_list_models", { id, request }),
|
||||
pbcSaveConnection: (id: string, update: PbcConnectionUpdate) => invoke<PbcConnectionSetup>("pbc_save_connection", { id, update }),
|
||||
moduleSetEnabled: (id: string, module: string, enabled: boolean) => invoke<void>("module_set_enabled", { id, module, enabled }),
|
||||
moduleSettings: (id: string, module: string) => invoke<ModuleSetting[]>("module_settings", { id, module }),
|
||||
moduleSaveSettings: (id: string, module: string, changes: Record<string, string>) => invoke<string[]>("module_save_settings", { id, module, changes }),
|
||||
@@ -556,6 +594,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 }),
|
||||
|
||||
@@ -63,6 +63,11 @@ export function startServerUpdatePolling(id: string): () => void {
|
||||
return () => clearInterval(t);
|
||||
}
|
||||
|
||||
/** How many update attempts and disk-state refreshes have finished for this server. */
|
||||
export function getServerUpdateRevision(id: string): number {
|
||||
return get(id).stateRevision;
|
||||
}
|
||||
|
||||
export function clearServerUpdateResult(id: string) {
|
||||
set(id, { result: null, uiError: null });
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { Card } from "@/components/ui/card";
|
||||
import { useHuman, useT } from "@/i18n";
|
||||
|
||||
/** Where the community hands out its launcher, which downloads the game client. The Manager does not download it. */
|
||||
export const CLIENT_SITE = "https://coa-development.org/";
|
||||
export const CLIENT_SITE = "https://conquestofazerothcore.to/";
|
||||
|
||||
type Phase = "choose" | "done" | "failed";
|
||||
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -9,6 +9,7 @@ import { useHuman, useI18n, useSchemaText, type Key } from "@/i18n";
|
||||
import { auctionWeightKey, canonicalModuleValue, moduleEnableKey, moduleField, retiredModuleKeys } from "@/lib/moduleSettings";
|
||||
import { AuctionTypes } from "@/screens/AuctionTypes";
|
||||
import { RaceAvailabilitySettings } from "@/screens/RaceAvailabilitySettings";
|
||||
import { PbcConnectionSettings } from "@/screens/PbcConnectionSettings";
|
||||
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
|
||||
|
||||
/** The GitHub mark (lucide dropped its brand icons). */
|
||||
@@ -111,16 +112,18 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
|
||||
}, [serverId]);
|
||||
const [guard, setGuard] = useState<UnsavedChangesGuard | null>(null);
|
||||
const [racesGuard, setRacesGuard] = useState<UnsavedChangesGuard | null>(null);
|
||||
const [pbcGuard, setPbcGuard] = useState<UnsavedChangesGuard | null>(null);
|
||||
const markChanged = useCallback(() => setChanged(true), []);
|
||||
|
||||
useEffect(() => {
|
||||
const guards = [guard, racesGuard].filter((item): item is UnsavedChangesGuard => item !== null);
|
||||
const guards = [guard, racesGuard, pbcGuard].filter((item): item is UnsavedChangesGuard => item !== null);
|
||||
onRegisterGuard?.(guards.length ? {
|
||||
isDirty: () => guards.some(item => item.isDirty()),
|
||||
save: async () => { for (const item of guards) if (item.isDirty() && !await item.save()) return false; return true; },
|
||||
discard: () => guards.forEach(item => item.discard()),
|
||||
} : null);
|
||||
return () => onRegisterGuard?.(null);
|
||||
}, [guard, racesGuard, onRegisterGuard]);
|
||||
}, [guard, racesGuard, pbcGuard, onRegisterGuard]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
@@ -343,6 +346,7 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
|
||||
{selected?.has_settings && !selected.page && selectedAt >= 0 && Math.floor(selectedAt / 2) === Math.floor(i / 2) && (i % 2 === 1 || i === modules.length - 1) && (
|
||||
<SettingsPanel key={selected.id} className="sm:col-span-2">
|
||||
<h2 className="font-semibold">{t("mod.settingsOf", { name: selected.name })}</h2>
|
||||
{selected.id === "mod-pbc" && <PbcConnectionSettings serverId={serverId} onSaved={markChanged} onRegisterGuard={setPbcGuard} />}
|
||||
<ModuleSettings serverId={serverId} module={selected} onSaved={() => setChanged(true)} onRegisterGuard={setGuard} />
|
||||
{selected.id === "custom-races" && <RaceAvailabilitySettings serverId={serverId}
|
||||
blocked={racesInstalling || toggling !== null} onSaved={() => setChanged(true)}
|
||||
@@ -461,7 +465,7 @@ function ModuleSettings({ serverId, module, onSaved, onRegisterGuard }: { server
|
||||
else next[key] = value;
|
||||
return next;
|
||||
});
|
||||
const available = items?.filter(s => s.key !== moduleEnableKey(module.id) && !["CoACustomRaces.DisabledRaceIds", "CoACustomRaces.DisabledRaceCatalogSha256"].includes(s.key) && !retiredModuleKeys.has(s.key)) ?? [];
|
||||
const available = items?.filter(s => s.key !== moduleEnableKey(module.id) && !["CoACustomRaces.DisabledRaceIds", "CoACustomRaces.DisabledRaceCatalogSha256", "PBC.DefaultConnection"].includes(s.key) && !retiredModuleKeys.has(s.key)) ?? [];
|
||||
const advancedCount = available.filter(s => !auctionWeightKey(s.key) && (!moduleField(s.key, locale, s.field) || moduleField(s.key, locale, s.field)?.advanced)).length;
|
||||
const visible = available.filter(s => {
|
||||
if (module.id === "ah-bot" && auctionWeightKey(s.key)) return false;
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useHuman, useI18n } from "@/i18n";
|
||||
import { api, asUiError, type PbcConnection, type PbcConnectionSetup, type UiError } from "@/lib/api";
|
||||
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
|
||||
import { PbcModelPicker, type ModelCatalog } from "@/screens/PbcModelPicker";
|
||||
|
||||
type Provider = "openai" | "ollama" | "anthropic" | "compatible";
|
||||
const presets: Record<Provider, PbcConnection> = {
|
||||
openai: { apiType: "openai", baseUrl: "https://api.openai.com/v1", model: "" },
|
||||
ollama: { apiType: "ollama", baseUrl: "http://127.0.0.1:11434", model: "" },
|
||||
anthropic: { apiType: "anthropic", baseUrl: "https://api.anthropic.com/v1", model: "" },
|
||||
compatible: { apiType: "openai", baseUrl: "", model: "" },
|
||||
};
|
||||
const providerOf = (connection: PbcConnection): Provider => connection.apiType !== "openai" ? connection.apiType
|
||||
: connection.baseUrl === presets.openai.baseUrl ? "openai" : "compatible";
|
||||
const inputClass = "selectable w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold";
|
||||
|
||||
export function PbcConnectionSettings({ serverId, onSaved, onRegisterGuard }: {
|
||||
serverId: string;
|
||||
onSaved: () => void;
|
||||
onRegisterGuard: (guard: UnsavedChangesGuard | null) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const human = useHuman();
|
||||
const [setup, setSetup] = useState<PbcConnectionSetup | null>(null);
|
||||
const [connection, setConnection] = useState<PbcConnection>(presets.openai);
|
||||
const [provider, setProvider] = useState<Provider>("openai");
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [removeKey, setRemoveKey] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<UiError | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [catalog, setCatalog] = useState<ModelCatalog>({ status: "idle", models: [] });
|
||||
const requestId = useRef(0);
|
||||
|
||||
const clearCatalog = useCallback(() => {
|
||||
requestId.current++;
|
||||
setCatalog({ status: "idle", models: [] });
|
||||
}, []);
|
||||
|
||||
const reset = useCallback((value: PbcConnectionSetup) => {
|
||||
const current = value.connection ?? presets.openai;
|
||||
setConnection(current);
|
||||
setProvider(providerOf(current));
|
||||
setApiKey("");
|
||||
setRemoveKey(false);
|
||||
clearCatalog();
|
||||
}, [clearCatalog]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setSetup(null);
|
||||
setSaved(false);
|
||||
setError(null);
|
||||
clearCatalog();
|
||||
void api.pbcConnection(serverId).then(value => {
|
||||
if (cancelled) return;
|
||||
setSetup(value);
|
||||
reset(value);
|
||||
}).catch(e => { if (!cancelled) setError(asUiError(e)); });
|
||||
return () => { cancelled = true; requestId.current++; };
|
||||
}, [serverId, reset, clearCatalog]);
|
||||
|
||||
const previous = setup?.connection ?? presets.openai;
|
||||
const dirty = !!setup && (connection.apiType !== previous.apiType || connection.baseUrl !== previous.baseUrl
|
||||
|| connection.model !== previous.model || !!apiKey || removeKey);
|
||||
const sameEndpoint = connection.apiType === previous.apiType
|
||||
&& connection.baseUrl.trim().replace(/\/+$/, "") === previous.baseUrl;
|
||||
const hasKey = !!setup?.connection?.hasKey && sameEndpoint;
|
||||
const valid = !!connection.baseUrl.trim() && !!connection.model.trim();
|
||||
const needsKey = provider === "openai"
|
||||
|| (provider === "anthropic" && connection.baseUrl.trim().replace(/\/+$/, "") === presets.anthropic.baseUrl);
|
||||
const discoveryBlocked = !connection.baseUrl.trim() ? t("mod.pbc.modelListNeedsUrl")
|
||||
: needsKey && !apiKey.trim() && !(hasKey && !removeKey) ? t("mod.pbc.modelListNeedsKey")
|
||||
: undefined;
|
||||
|
||||
async function loadModels(refresh: boolean) {
|
||||
if (discoveryBlocked || catalog.status === "loading" || (!refresh && catalog.status !== "idle")) return;
|
||||
const current = ++requestId.current;
|
||||
setCatalog(previous => ({ ...previous, status: "loading" }));
|
||||
try {
|
||||
const models = await api.pbcListModels(serverId, {
|
||||
apiType: connection.apiType, baseUrl: connection.baseUrl, apiKey: apiKey || undefined, removeKey,
|
||||
});
|
||||
if (current === requestId.current) setCatalog({ status: "ready", models });
|
||||
} catch {
|
||||
if (current === requestId.current) setCatalog(previous => ({ ...previous, status: "error" }));
|
||||
}
|
||||
}
|
||||
|
||||
const save = useCallback(async () => {
|
||||
if (!setup || !valid || busy) return false;
|
||||
setBusy(true);
|
||||
setSaved(false);
|
||||
setError(null);
|
||||
try {
|
||||
const next = await api.pbcSaveConnection(serverId, { ...connection, apiKey: apiKey || undefined, removeKey });
|
||||
setSetup(next);
|
||||
reset(next);
|
||||
setSaved(true);
|
||||
onSaved();
|
||||
return true;
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, [setup, valid, busy, serverId, connection, apiKey, removeKey, reset, onSaved]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!setup || !dirty) return;
|
||||
onRegisterGuard({ isDirty: () => true, save, discard: () => reset(setup) });
|
||||
return () => onRegisterGuard(null);
|
||||
}, [setup, dirty, save, reset, onRegisterGuard]);
|
||||
|
||||
function changeProvider(value: Provider) {
|
||||
setProvider(value);
|
||||
setConnection(presets[value]);
|
||||
setApiKey("");
|
||||
setRemoveKey(false);
|
||||
setSaved(false);
|
||||
clearCatalog();
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="mt-4 space-y-3 border-t border-line pt-4" aria-labelledby="pbc-connection-heading">
|
||||
<h3 id="pbc-connection-heading" className="font-semibold">{t("mod.pbc.connection")}</h3>
|
||||
{error && <p className="text-sm text-warn" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
|
||||
{setup && (
|
||||
<form className="space-y-3" onSubmit={event => { event.preventDefault(); void save(); }}>
|
||||
{!setup.active && <p className="text-sm text-muted">{t("mod.pbc.useConnection")}</p>}
|
||||
<fieldset disabled={busy} className="grid gap-3 sm:grid-cols-2">
|
||||
<label className="space-y-1 text-sm">
|
||||
<span>{t("mod.pbc.provider")}</span>
|
||||
<select className={inputClass} value={provider} onChange={event => changeProvider(event.target.value as Provider)}>
|
||||
<option value="openai">OpenAI</option>
|
||||
<option value="ollama">Ollama</option>
|
||||
<option value="anthropic">Anthropic</option>
|
||||
<option value="compatible">{t("mod.pbc.compatible")}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="space-y-1 text-sm sm:col-span-2">
|
||||
<span>{t("mod.pbc.endpoint")}</span>
|
||||
<input className={inputClass} value={connection.baseUrl} type="url" required readOnly={provider === "openai"}
|
||||
onChange={event => { setConnection({ ...connection, baseUrl: event.target.value }); setApiKey(""); setRemoveKey(false); setSaved(false); clearCatalog(); }} />
|
||||
</label>
|
||||
<label className="space-y-1 text-sm sm:col-span-2">
|
||||
<span>{t("mod.pbc.key")}</span>
|
||||
<input className={inputClass} value={apiKey} type="password" autoComplete="off" disabled={removeKey}
|
||||
placeholder={hasKey ? t("mod.pbc.savedKey") : undefined}
|
||||
onChange={event => { setApiKey(event.target.value); setSaved(false); clearCatalog(); }} />
|
||||
</label>
|
||||
{hasKey && <label className="flex items-center gap-2 text-sm sm:col-span-2">
|
||||
<input type="checkbox" checked={removeKey} onChange={event => { setRemoveKey(event.target.checked); setApiKey(""); setSaved(false); clearCatalog(); }} />
|
||||
{t("mod.pbc.removeKey")}
|
||||
</label>}
|
||||
<PbcModelPicker key={provider} value={connection.model} catalog={catalog} discoveryBlocked={discoveryBlocked}
|
||||
loadModels={loadModels} onChange={model => { setConnection({ ...connection, model }); setSaved(false); }} />
|
||||
</fieldset>
|
||||
<p className="text-sm text-muted">{t("mod.pbc.keyHint")}</p>
|
||||
<Button size="sm" type="submit" disabled={busy || !valid || (setup.active && !dirty)}>{t("mod.pbc.save")}</Button>
|
||||
{saved && <p className="text-sm text-ok" role="status">{t("mod.pbc.saved")}</p>}
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useI18n } from "@/i18n";
|
||||
import type { PbcModel } from "@/lib/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ModelCatalog = {
|
||||
status: "idle" | "loading" | "ready" | "error";
|
||||
models: PbcModel[];
|
||||
};
|
||||
|
||||
const fieldClass = "selectable w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold";
|
||||
|
||||
export function PbcModelPicker({ value, onChange, catalog, discoveryBlocked, loadModels }: {
|
||||
value: string;
|
||||
onChange: (id: string) => void;
|
||||
catalog: ModelCatalog;
|
||||
discoveryBlocked?: string;
|
||||
loadModels: (refresh: boolean) => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const id = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [manual, setManual] = useState(false);
|
||||
const [query, setQuery] = useState("");
|
||||
const [highlight, setHighlight] = useState(-1);
|
||||
const trigger = useRef<HTMLButtonElement>(null);
|
||||
const search = useRef<HTMLInputElement>(null);
|
||||
const manualInput = useRef<HTMLInputElement>(null);
|
||||
const list = useRef<HTMLUListElement>(null);
|
||||
const term = query.trim().toLocaleLowerCase();
|
||||
const models = catalog.models.filter(model => `${model.name} ${model.id}`.toLocaleLowerCase().includes(term));
|
||||
const selected = catalog.models.find(model => model.id === value);
|
||||
const active = Math.min(highlight, models.length);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) search.current?.focus();
|
||||
else if (manual) manualInput.current?.focus();
|
||||
}, [open, manual]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open && active >= 0) list.current?.children.item(active)?.scrollIntoView({ block: "nearest" });
|
||||
}, [open, active]);
|
||||
|
||||
function browse(refresh = false) {
|
||||
setManual(false);
|
||||
if (!open) {
|
||||
setQuery("");
|
||||
setHighlight(-1);
|
||||
setOpen(true);
|
||||
} else {
|
||||
search.current?.focus();
|
||||
}
|
||||
loadModels(refresh);
|
||||
}
|
||||
|
||||
function choose(index: number) {
|
||||
setOpen(false);
|
||||
if (index === models.length) {
|
||||
setManual(true);
|
||||
} else {
|
||||
onChange(models[index].id);
|
||||
trigger.current?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function navigate(event: KeyboardEvent<HTMLInputElement>) {
|
||||
switch (event.key) {
|
||||
case "ArrowDown":
|
||||
case "ArrowUp":
|
||||
event.preventDefault();
|
||||
setHighlight(event.key === "ArrowDown"
|
||||
? Math.min(active + 1, models.length)
|
||||
: active <= 0 ? models.length : active - 1);
|
||||
break;
|
||||
case "Enter":
|
||||
event.preventDefault();
|
||||
choose(Math.max(0, active));
|
||||
break;
|
||||
case "Escape":
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setOpen(false);
|
||||
trigger.current?.focus();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const status = discoveryBlocked
|
||||
?? (catalog.status === "loading" ? t("mod.pbc.loadingModels")
|
||||
: catalog.status === "error" ? t("mod.pbc.modelListFailed")
|
||||
: !models.length && catalog.status === "ready" ? t("mod.pbc.noModels")
|
||||
: "");
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5 sm:col-span-2" onBlur={event => {
|
||||
if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false);
|
||||
}}>
|
||||
<label htmlFor={id} className="block text-sm">{t("mod.pbc.model")}</label>
|
||||
<div className="flex flex-wrap items-start gap-2">
|
||||
<div className="relative min-w-56 flex-1">
|
||||
{manual ? (
|
||||
<input ref={manualInput} id={id} className={fieldClass} value={value} required
|
||||
placeholder={t("mod.pbc.manualModel")} onChange={event => onChange(event.target.value)} />
|
||||
) : (
|
||||
<button ref={trigger} id={id} type="button" className={cn(fieldClass, "flex items-center justify-between gap-2 text-left")}
|
||||
aria-expanded={open} aria-controls={open ? `${id}-picker` : undefined}
|
||||
onClick={() => open ? setOpen(false) : browse()}
|
||||
onKeyDown={event => {
|
||||
if (!open && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
|
||||
event.preventDefault();
|
||||
browse();
|
||||
}
|
||||
}}>
|
||||
<span className={cn("truncate", !value && "text-muted")}>
|
||||
{selected?.name ?? (value || t("mod.pbc.chooseModel"))}
|
||||
</span>
|
||||
<ChevronDown className="h-4 w-4 shrink-0 text-muted" aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
{open && (
|
||||
<div id={`${id}-picker`} className="absolute z-20 mt-1 w-full rounded-md border border-line bg-bg p-2 shadow-lg">
|
||||
<input ref={search} type="text" role="combobox" aria-expanded="true" aria-autocomplete="list"
|
||||
aria-controls={`${id}-options`} aria-activedescendant={active >= 0 ? `${id}-option-${active}` : undefined}
|
||||
aria-label={t("mod.pbc.searchModels")} placeholder={t("mod.pbc.searchModels")}
|
||||
className={fieldClass} value={query} autoComplete="off"
|
||||
onChange={event => { setQuery(event.target.value); setHighlight(-1); }} onKeyDown={navigate} />
|
||||
{status && <p className="px-2 py-2 text-sm text-muted" role="status">{status}</p>}
|
||||
<ul ref={list} id={`${id}-options`} role="listbox" aria-label={t("mod.pbc.model")} className="mt-1 max-h-56 overflow-auto">
|
||||
{models.map((model, index) => (
|
||||
<li key={model.id} id={`${id}-option-${index}`} role="option" aria-selected={model.id === value}
|
||||
className={cn("cursor-pointer rounded px-2 py-1.5 text-sm hover:bg-gold/10", active === index && "bg-gold/15")}
|
||||
onMouseDown={event => event.preventDefault()} onClick={() => choose(index)}>
|
||||
<span className="block break-all">{model.name}</span>
|
||||
{model.id !== model.name && <span className="block break-all text-xs text-muted">{model.id}</span>}
|
||||
</li>
|
||||
))}
|
||||
<li id={`${id}-option-${models.length}`} role="option" aria-selected={false}
|
||||
className={cn("cursor-pointer rounded border-t border-line px-2 py-1.5 text-sm text-gold hover:bg-gold/10",
|
||||
active === models.length && "bg-gold/15")}
|
||||
onMouseDown={event => event.preventDefault()} onClick={() => choose(models.length)}>
|
||||
{t("mod.pbc.manualModel")}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button size="sm" variant="secondary" type="button" disabled={!manual && (!!discoveryBlocked || catalog.status === "loading")}
|
||||
onClick={() => manual ? browse() : browse(true)}>
|
||||
{t(manual ? "mod.pbc.browseModels" : "mod.pbc.refreshModels")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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>}
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { ChevronDown, ChevronRight, Loader2, RefreshCw, Server } from "lucide-react";
|
||||
import { applyServerUpdate, clearServerUpdateResult, refreshServerUpdateState, useServerUpdate } from "@/lib/serverUpdate";
|
||||
import { applyServerUpdate, clearServerUpdateResult, getServerUpdateRevision, refreshServerUpdateState, useServerUpdate } from "@/lib/serverUpdate";
|
||||
import { isUpdateCurrent } from "@/lib/serverUpdateStatus";
|
||||
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -17,7 +17,12 @@ export function ServerUpdateCard({ serverId, onHistory, onAttention }: { serverI
|
||||
const { t } = useI18n();
|
||||
const upd = useServerUpdate(serverId);
|
||||
const human = useHuman();
|
||||
const [preview, setPreview] = useState<UpdatePreview | null>(upd.preview);
|
||||
// The offer shown here is the shared one the main screen uses (it is checked at start and every five minutes), unless
|
||||
// the owner pressed the check button on this card. A manual check counts only until the next finished update attempt,
|
||||
// which is why it carries the revision it was made at. Nothing is copied from the shared state when this card opens,
|
||||
// so an offer that arrives later, or one found before the card was opened, still shows.
|
||||
const [manual, setManual] = useState<{ revision: number; preview: UpdatePreview | null } | null>(null);
|
||||
const preview = manual && manual.revision === upd.stateRevision ? manual.preview : upd.preview;
|
||||
const [pending, setPending] = useState<UpdateTxn | null>(null);
|
||||
const [pendingChecked, setPendingChecked] = useState(false);
|
||||
const [pendingStateError, setPendingStateError] = useState<UiError | null>(null);
|
||||
@@ -29,7 +34,8 @@ export function ServerUpdateCard({ serverId, onHistory, onAttention }: { serverI
|
||||
const error = pendingStateError ?? localError ?? upd.uiError;
|
||||
const [localDone, setDone] = useState<string | null>(null);
|
||||
const done = upd.result && "committed" in upd.result ? t("upd.updatedTo", { v: upd.result.committed }) : localDone;
|
||||
const [choices, setChoices] = useState<Record<string, "keep" | "replace">>(() => Object.fromEntries((upd.preview?.conflicts ?? []).map(c => [c, "keep" as const])));
|
||||
const [picked, setChoices] = useState<Record<string, "keep" | "replace">>({});
|
||||
const choices: Record<string, "keep" | "replace"> = Object.fromEntries((preview?.conflicts ?? []).map(c => [c, picked[c] ?? "keep"]));
|
||||
const [advanced, setAdvanced] = useState(false);
|
||||
const [source, setSource] = useState("");
|
||||
const [startAfter, setStartAfter] = useStartAfterUpdate("server", serverId);
|
||||
@@ -48,7 +54,6 @@ export function ServerUpdateCard({ serverId, onHistory, onAttention }: { serverI
|
||||
// Every finished attempt refreshes the disk state, including failures in the background.
|
||||
useEffect(() => {
|
||||
if (!upd.stateRevision) return;
|
||||
setPreview(null);
|
||||
setPendingChecked(!upd.stateError);
|
||||
setPendingStateError(upd.stateError);
|
||||
if (!upd.stateError) setPending(upd.result && "pending" in upd.result ? upd.result.pending : null);
|
||||
@@ -72,13 +77,13 @@ export function ServerUpdateCard({ serverId, onHistory, onAttention }: { serverI
|
||||
setError(null);
|
||||
setDone(null);
|
||||
clearServerUpdateResult(serverId);
|
||||
setPreview(null);
|
||||
setManual(null);
|
||||
try {
|
||||
const txn = await refreshPending();
|
||||
if (txn) return;
|
||||
const p = await api.checkUpdate(serverId, source.trim() || undefined);
|
||||
setPreview(p);
|
||||
setChoices(Object.fromEntries(p.conflicts.map((c) => [c, "keep" as const])));
|
||||
setManual({ revision: getServerUpdateRevision(serverId), preview: p });
|
||||
setChoices({});
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
} finally {
|
||||
@@ -116,7 +121,7 @@ export function ServerUpdateCard({ serverId, onHistory, onAttention }: { serverI
|
||||
const result = await api.retryUpdateValidation(serverId, txn.id);
|
||||
if (result.state === "committed") {
|
||||
setPending(null);
|
||||
setPreview(null);
|
||||
setManual(null);
|
||||
setDone(t("upd.updatedTo", { v: result.to_version }));
|
||||
clearServerUpdateResult(serverId);
|
||||
} else setPending(result);
|
||||
|
||||
@@ -1,17 +1,10 @@
|
||||
{
|
||||
"version": "0.9.14",
|
||||
"version": "0.9.18",
|
||||
"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"
|
||||
"Configure Playerbot Characters from the Modules page",
|
||||
"Choose Playerbot Characters models from a live provider list",
|
||||
"Settings now shows the server version and update button after you have checked for updates",
|
||||
"Adding companions reuses offline bots and keeps your startup limit",
|
||||
"Custom Races installs the 2.0.3 client with the Snagtooth race"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { rolldown } from "rolldown";
|
||||
import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
// The Server card in Settings -> Updates, rendered with a tiny hook runtime so that its effects really run (a plain
|
||||
// server render skips them, which is where the offer used to be wiped when the tab was opened after an update attempt
|
||||
// had already finished). The card must show what the shared update state, which the main screen also uses, holds.
|
||||
const stubs = {
|
||||
react: `export const useState=(...a)=>globalThis.__hooks.useState(...a); export const useEffect=(...a)=>globalThis.__hooks.useEffect(...a);`,
|
||||
"@/lib/api": `export const api={pendingUpdate:async()=>null}; export const asUiError=e=>e;`,
|
||||
"@tauri-apps/plugin-dialog": `export const open=async()=>null;`,
|
||||
"@/i18n": `export const useI18n=()=>({t:(k,v)=>v?k+JSON.stringify(v):k}); export const useHuman=()=>h=>h; export const hasKey=()=>false;`,
|
||||
"@/lib/serverUpdate": `export const applyServerUpdate=async()=>false; export const clearServerUpdateResult=()=>{}; export const refreshServerUpdateState=async()=>null; export const getServerUpdateRevision=()=>0; export const useServerUpdate=()=>globalThis.__cardUpdate;`,
|
||||
"@/lib/updatePrefs": `export const useStartAfterUpdate=()=>[false,()=>{}];`,
|
||||
"@/components/ui/button": `import {createElement} from 'react'; export const Button=({children,disabled,onClick,className,...props})=>createElement('button',{disabled,onClick,className,...props},children);`,
|
||||
"@/components/ui/card": `import {createElement} from 'react'; export const Card=({children,...props})=>createElement('div',props,children);`,
|
||||
};
|
||||
const card = fileURLToPath(new URL("../src/screens/ServerUpdateCard.tsx", import.meta.url));
|
||||
const bundle = await rolldown({
|
||||
input: card,
|
||||
transform: { jsx: "react-jsx" },
|
||||
external: (id, importer) => id === "react/jsx-runtime" || id === "lucide-react" || (id === "react" && !importer?.endsWith("ServerUpdateCard.tsx")),
|
||||
plugins: [{ name: "card-test",
|
||||
resolveId(id, importer) {
|
||||
if (id === "@/lib/serverUpdateStatus") return fileURLToPath(new URL("../src/lib/serverUpdateStatus.ts", import.meta.url));
|
||||
if (id.startsWith("@/") || id.startsWith("@tauri-apps/") || (id === "react" && importer?.endsWith("ServerUpdateCard.tsx"))) return "\0" + id;
|
||||
},
|
||||
load(id) {
|
||||
if (!id.startsWith("\0")) return;
|
||||
return stubs[id.slice(1)] ?? `export const ${id.split("/").at(-1)}=()=>null;`;
|
||||
},
|
||||
}],
|
||||
});
|
||||
const result = await bundle.generate({ format: "cjs" });
|
||||
await bundle.close();
|
||||
const module = { exports: {} };
|
||||
new Function("require", "module", "exports", result.output[0].code)(createRequire(import.meta.url), module, module.exports);
|
||||
|
||||
const offer = { from_version: "0.261116.11201", to_version: "0.261119.11401", items: [{ path: "bin/worldserver.exe", action: "replace" }], conflicts: [], migrations: 0, download_bytes: 5 << 20 };
|
||||
async function render(update) {
|
||||
globalThis.__cardUpdate = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null, uiError: null, stateError: null, stateRevision: 0, result: null, ...update };
|
||||
const slots = [], deps = [];
|
||||
let index = 0, effects = [], dirty = false;
|
||||
globalThis.__hooks = {
|
||||
useState(initial) {
|
||||
const i = index++;
|
||||
if (!(i in slots)) slots[i] = typeof initial === "function" ? initial() : initial;
|
||||
return [slots[i], (next) => { const value = typeof next === "function" ? next(slots[i]) : next; if (!Object.is(value, slots[i])) { slots[i] = value; dirty = true; } }];
|
||||
},
|
||||
useEffect(fn, list) {
|
||||
const i = index++;
|
||||
const before = deps[i];
|
||||
if (!before || !list || list.some((d, k) => !Object.is(d, before[k]))) effects.push(fn);
|
||||
deps[i] = list;
|
||||
},
|
||||
};
|
||||
let html = "";
|
||||
for (let pass = 0; pass < 10; pass++) {
|
||||
index = 0; effects = []; dirty = false;
|
||||
html = renderToStaticMarkup(createElement(module.exports.ServerUpdateCard, { serverId: "fixture", onHistory() {}, onAttention() {} }));
|
||||
effects.forEach((fn) => fn());
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
if (!dirty) break;
|
||||
}
|
||||
return html.replaceAll(""", '"');
|
||||
}
|
||||
|
||||
test("Settings card shows the installed version and the update button from the shared offer", async () => {
|
||||
const html = await render({ preview: offer, available: true });
|
||||
assert.match(html, /settings\.version\{"v":"0\.261116\.11201"\}/);
|
||||
assert.match(html, /upd\.availableFrom/);
|
||||
assert.match(html, /upd\.now/);
|
||||
});
|
||||
|
||||
test("Settings card keeps the offer after an update attempt already finished (it is not wiped on open)", async () => {
|
||||
const html = await render({ preview: offer, available: true, stateRevision: 3 });
|
||||
assert.match(html, /settings\.version\{"v":"0\.261116\.11201"\}/);
|
||||
assert.match(html, /upd\.now/);
|
||||
});
|
||||
|
||||
test("Settings card shows an up-to-date server as current, without an update button", async () => {
|
||||
const same = { ...offer, to_version: offer.from_version, items: [{ path: "bin/worldserver.exe", action: "skip" }], pending_migrations: 0 };
|
||||
const html = await render({ preview: same });
|
||||
assert.match(html, /upd\.current/);
|
||||
assert.doesNotMatch(html, /upd\.now/);
|
||||
});
|
||||
|
||||
test("Settings card shows a placeholder while no check has finished", async () => {
|
||||
const html = await render({ checking: true });
|
||||
assert.doesNotMatch(html, /settings\.version/);
|
||||
assert.doesNotMatch(html, /upd\.now/);
|
||||
});
|
||||
Reference in new issue
Block a user