mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 03:25:56 +00:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88ccce8280 | ||
|
|
17eba1c30e | ||
|
|
dbf494c2c2 | ||
|
|
086534f849 | ||
|
|
1b0adbf94c | ||
|
|
a8afe88c83 | ||
|
|
657229aafc | ||
|
|
b5abc6fc4f | ||
|
|
81c5556ffe | ||
|
|
4b51301230 | ||
|
|
6f1eaac719 | ||
|
|
206d4844c9 | ||
|
|
10cfdcf5a2 | ||
|
|
316ef078e8 |
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.16"
|
||||
version = "0.9.18"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -621,7 +621,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-launcher"
|
||||
version = "0.9.16"
|
||||
version = "0.9.18"
|
||||
dependencies = [
|
||||
"coa-core",
|
||||
"serde_json",
|
||||
@@ -644,7 +644,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-release"
|
||||
version = "0.9.16"
|
||||
version = "0.9.18"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"coa-core",
|
||||
@@ -653,7 +653,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-server-manager"
|
||||
version = "0.9.16"
|
||||
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.16"
|
||||
version = "0.9.18"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
|
||||
@@ -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: 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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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(())
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.16",
|
||||
"version": "0.9.18",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "coa-server-manager",
|
||||
"version": "0.9.16",
|
||||
"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.16",
|
||||
"version": "0.9.18",
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
+68
-12
@@ -1710,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>,
|
||||
@@ -2243,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
|
||||
@@ -2250,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;
|
||||
@@ -2264,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);
|
||||
@@ -2680,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.
|
||||
@@ -3217,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,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "CoA Server Manager",
|
||||
"version": "0.9.16",
|
||||
"version": "0.9.18",
|
||||
"identifier": "com.coa.servermanager",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
|
||||
@@ -58,7 +58,13 @@
|
||||
"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": "Перезапускайте мир каждую неделю в выбранный день и время"
|
||||
"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",
|
||||
@@ -118,7 +124,13 @@
|
||||
"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"
|
||||
"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",
|
||||
@@ -178,7 +190,13 @@
|
||||
"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"
|
||||
"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",
|
||||
@@ -238,7 +256,13 @@
|
||||
"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"
|
||||
"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": "在模块设置中选择并行或全局等级缩放",
|
||||
@@ -298,7 +322,13 @@
|
||||
"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": "每周在选定的日期和时间重启世界"
|
||||
"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": {
|
||||
|
||||
+23
-1
@@ -650,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.",
|
||||
@@ -844,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).",
|
||||
|
||||
+23
-1
@@ -758,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.",
|
||||
@@ -890,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).",
|
||||
|
||||
+23
-1
@@ -650,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.",
|
||||
@@ -844,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)).",
|
||||
|
||||
+23
-1
@@ -650,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.",
|
||||
@@ -844,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)).",
|
||||
|
||||
+23
-1
@@ -741,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». Менеджер этого изменить не может.",
|
||||
@@ -873,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}).",
|
||||
|
||||
+23
-1
@@ -712,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 无法更改。",
|
||||
@@ -844,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} 项)。",
|
||||
|
||||
@@ -229,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;
|
||||
@@ -545,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 }),
|
||||
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -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,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,10 +1,10 @@
|
||||
{
|
||||
"version": "0.9.16",
|
||||
"version": "0.9.18",
|
||||
"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"
|
||||
"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