Compare commits

..
Author SHA1 Message Date
Дмитрий 30d2f56997 Stabilize server lifecycle, client settings and release qualification 2026-10-30 14:04:18 +05:00
Дмитрий 4d1a6e0b21 Retain experimental Portable Characters notice for Manager 0.9.4 2026-10-29 20:51:31 +05:00
github-actions[bot] bda38b9f26 Update published Manager changelog 2026-10-29 15:31:44 +00:00
Дмитрий c004b90c54 Translate reviewed server candidate notes for Manager 0.9.4 2026-10-29 16:29:04 +05:00
Corfirean d44e00f9ad Merge pull request #177 from Corfirean/feat/settings-update-history
Reorganize settings, stabilize window sizing and group update actions
2026-10-29 16:15:14 +05:00
Дмитрий dad10d8a5d Integrate settings and release history for Manager 0.9.4 2026-10-29 16:10:43 +05:00
Corfirean b33821e7eb Record reviewed Manager 0.9.3 release notes 2026-10-29 10:33:27 +05:00
Corfirean 1288a84da2 Merge pull request #184 from Corfirean/fix/world-startup-deadline
Release Manager 0.9.3 with slow world startup recovery
2026-10-29 10:15:48 +05:00
Дмитрий e7b76137d1 Prepare Manager 0.9.3 and verify platform-specific realm restriction 2026-10-29 10:07:33 +05:00
Дмитрий 7bb0ea9472 Wait for slow CoA worlds before update rollback 2026-10-29 08:33:11 +05:00
Дмитрий 1dab6154c7 Record reviewed 0.9.2 notes and experimental notice 2026-10-28 23:22:07 +05:00
github-actions[bot] 06a6302732 Update published Manager changelog 2026-10-28 18:20:57 +00:00
Corfirean 65631450ff Merge pull request #181 from Corfirean/fix/manager-092-issues
Manager 0.9.2: database startup, recovery and CoA settings
2026-10-28 23:20:11 +05:00
Дмитрий a8ab201d7d Document required changelog translation preparation 2026-10-28 16:39:16 +05:00
Дмитрий 733d73ef76 Keep window density stable and group update and launch actions 2026-10-28 15:42:47 +05:00
Дмитрий 5525325160 Group Manager settings and add translated release history 2026-10-28 15:26:01 +05:00
93 changed files with 5270 additions and 549 deletions

No files matched your search

+10
View File
@@ -35,6 +35,16 @@ Every published Manager version, including a clearly marked Pre-release, belongs
CHANGELOG.md and changelog/history.json. Its GitHub release notes use the same reviewed record. CHANGELOG.md and changelog/history.json. Its GitHub release notes use the same reviewed record.
Promotion updates that entry without duplicating it; Manager and server histories remain separate. Promotion updates that entry without duplicating it; Manager and server histories remain separate.
Translated release notes are a required preparation step before freezing a new Manager source. Follow the
runbook's "Mandatory translated release notes during preparation" checklist: translate every new reviewed
Manager/server note into Russian, German, French, Spanish and Simplified Chinese in
`src/data/latest-note-translations.json`, keyed by exact canonical English text. Preserve existing translations
and released fragments. Refresh the bundled server-history snapshot from a pinned canonical commit and record
its provenance. Run `node --test tools/release-history.test.mjs`, `node tools/check-i18n.mjs` and `npm run build`;
verify each new record, all six viewer languages, English fallback and offline use. Save source/version and checks
in the handoff. Translations ship with Manager: a server-only release must record the carrying Manager version or
pending translation delivery, without forcing another Manager release or changing already signed installers.
Before preparing or publishing a Manager/server release, read the maintained Before preparing or publishing a Manager/server release, read the maintained
[release runbook](https://github.com/Corfirean/coa-server-build/blob/main/docs/server-release.md) [release runbook](https://github.com/Corfirean/coa-server-build/blob/main/docs/server-release.md)
and [build agent instructions](https://github.com/Corfirean/coa-server-build/blob/main/AGENTS.md). and [build agent instructions](https://github.com/Corfirean/coa-server-build/blob/main/AGENTS.md).
+29
View File
@@ -8,6 +8,35 @@ 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. Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
## 0.9.4 — 2026-10-29
**Portable Characters are experimental and may contain bugs.**
- Settings group updates, startup and maintenance with translated release history.
- Update and launch without updating share a divided button.
- Maximizing the window keeps text and controls at a comfortable size.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.4) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.3...v0.9.4)
## 0.9.3 — 2026-10-29
**Portable Characters are experimental and may contain bugs.**
- Slow server startup no longer triggers an early update rollback.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.3) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.2...v0.9.3)
## 0.9.2 — 2026-10-28
**Portable Characters are experimental and may contain bugs.**
- New server installation waits for slower database startup.
- Find and edit CoA options in the existing server settings.
- Simultaneous update checks share results or wait their turn.
- Recovery can stop an unfinished world startup after restoring an older launcher.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.2) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.1...v0.9.2)
## 0.9.1 — 2026-10-28 ## 0.9.1 — 2026-10-28
**Portable Characters are experimental and may contain bugs.** **Portable Characters are experimental and may contain bugs.**
Generated
+20 -3
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]] [[package]]
name = "coa-core" name = "coa-core"
version = "0.9.2" version = "0.9.5"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"chrono", "chrono",
@@ -634,7 +634,7 @@ dependencies = [
[[package]] [[package]]
name = "coa-release" name = "coa-release"
version = "0.9.2" version = "0.9.5"
dependencies = [ dependencies = [
"chrono", "chrono",
"coa-core", "coa-core",
@@ -643,7 +643,7 @@ dependencies = [
[[package]] [[package]]
name = "coa-server-manager" name = "coa-server-manager"
version = "0.9.2" version = "0.9.5"
dependencies = [ dependencies = [
"coa-control-proto", "coa-control-proto",
"coa-core", "coa-core",
@@ -655,6 +655,7 @@ dependencies = [
"tauri-plugin-dialog", "tauri-plugin-dialog",
"tauri-plugin-opener", "tauri-plugin-opener",
"tauri-plugin-process", "tauri-plugin-process",
"tauri-plugin-single-instance",
"tauri-plugin-updater", "tauri-plugin-updater",
"tracing", "tracing",
] ]
@@ -4606,6 +4607,22 @@ dependencies = [
"tauri-plugin", "tauri-plugin",
] ]
[[package]]
name = "tauri-plugin-single-instance"
version = "2.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f"
dependencies = [
"serde",
"serde_json",
"tauri",
"thiserror 2.0.21",
"tokio",
"tracing",
"windows-sys 0.61.2",
"zbus",
]
[[package]] [[package]]
name = "tauri-plugin-updater" name = "tauri-plugin-updater"
version = "2.13.1" version = "2.13.1"
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto",
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"] exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
[workspace.package] [workspace.package]
version = "0.9.2" version = "0.9.5"
edition = "2021" edition = "2021"
license = "AGPL-3.0-only" license = "AGPL-3.0-only"
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Settings group updates, startup and maintenance with translated release history
---
Server and Manager keep separate update controls. Read their published changes in one place, including translations of the latest releases in all six interface languages. Saved notes remain available offline. Find public realm controls under Play with friends.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Update and launch without updating share a divided button
---
Server and game client actions each use two adjacent segments of equal height. Both actions remain visible and keep their own availability checks.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Maximizing the window keeps text and controls at a comfortable size
---
The interface no longer enlarges with window width. System display scaling and browser zoom still work, and large action buttons use more compact spacing.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Slow server startup no longer triggers an early update rollback
---
World startup now allows up to 25 minutes with either bot system and waits for both game and console ports within one deadline. Servers that stop during startup still fail immediately.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Account creation verifies a lost console reply against the requested login
---
Confirm the requested credentials after a lost reply, block creation during another server action, and explicitly report accounts whose administrator access could not be confirmed.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Abandoned game relay tunnels close their local connection immediately
---
Dropping a tunnel shuts down its shared socket directly instead of relying only on a background message, releasing its local read and write connection.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Keep disabled graphics components disabled during client updates
---
Client settings can disable DXVK and graphics enhancements. Existing launcher DISABLED files are respected.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Force-stop an unresponsive world after a failed normal shutdown
---
Confirm the risk of unsaved progress before stopping verified server processes. Shared databases stay running until every owned world has stopped.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Crash history includes reports from every world and Windows text files
---
Create and verify the crash report folder before native startup, and include reports from simultaneous worlds and files containing Windows ANSI text.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Show the online bot count for Playerbots on the overview
---
The overview displays bot population for both supported bot systems.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Disable public server browsing in Settings
---
Turn off public server browsing to block catalog list and detail requests. When browsing is enabled, load the list with Refresh.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Keep deliberate stops and update shutdowns from triggering crash restart
---
Status checks no longer forget a stop request while the world is still shutting down. Update validation and recovery do not trigger automatic crash restarts.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Server startup waits for a responsive console before reporting success
---
An open port no longer marks a loading world as ready. Account creation checks that the console processes commands before sending a create request.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Restore the existing Manager window when launching it again
---
Choose whether closing the window exits the Manager or minimizes it to the tray. Tray actions restore the window on the UI thread.
+56 -1
View File
@@ -149,8 +149,16 @@
"Corfirean/coa-server-manager:20261027-skill-gain-controls.md", "Corfirean/coa-server-manager:20261027-skill-gain-controls.md",
"Corfirean/coa-server-manager:20261027-start-checks-the-realm-class-setting.md", "Corfirean/coa-server-manager:20261027-start-checks-the-realm-class-setting.md",
"Corfirean/coa-server-manager:20261027-start-wildcard-and-reborn-with-coa.md", "Corfirean/coa-server-manager:20261027-start-wildcard-and-reborn-with-coa.md",
"Corfirean/coa-server-manager:20261028-coa-config-search.md",
"Corfirean/coa-server-manager:20261028-existing-character-update-validation.md", "Corfirean/coa-server-manager:20261028-existing-character-update-validation.md",
"Corfirean/coa-server-manager:20261028-portable-settings-and-tray.md" "Corfirean/coa-server-manager:20261028-legacy-world-shutdown.md",
"Corfirean/coa-server-manager:20261028-mysql-install-startup.md",
"Corfirean/coa-server-manager:20261028-portable-settings-and-tray.md",
"Corfirean/coa-server-manager:20261028-settings-release-history.md",
"Corfirean/coa-server-manager:20261028-split-update-actions.md",
"Corfirean/coa-server-manager:20261028-update-check-queue.md",
"Corfirean/coa-server-manager:20261028-window-density.md",
"Corfirean/coa-server-manager:20261029-slow-world-startup.md"
], ],
"releases": [ "releases": [
{ {
@@ -771,6 +779,53 @@
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1", "url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1", "compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1",
"commit": "8bbf16ed4f14e9b78c680783e4be5d8c580cc06b" "commit": "8bbf16ed4f14e9b78c680783e4be5d8c580cc06b"
},
{
"tag": "v0.9.2",
"version": "0.9.2",
"date": "2026-10-28",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.2",
"notes": [
"New server installation waits for slower database startup",
"Find and edit CoA options in the existing server settings",
"Simultaneous update checks share results or wait their turn",
"Recovery can stop an unfinished world startup after restoring an older launcher"
],
"commit": "2d9c6a65bbb1e296dc919e4c9e5785ed9d4a070b",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.1...v0.9.2",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.3",
"version": "0.9.3",
"date": "2026-10-29",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.3",
"notes": [
"Slow server startup no longer triggers an early update rollback"
],
"commit": "e7b76137d1b22a7596c2b1fa05ca9d12403b99d3",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.2...v0.9.3",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.4",
"version": "0.9.4",
"date": "2026-10-29",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.4",
"notes": [
"Settings group updates, startup and maintenance with translated release history",
"Update and launch without updating share a divided button",
"Maximizing the window keeps text and controls at a comfortable size"
],
"commit": "c004b90c54fa358b3037c56b093cf019dfcf02b8",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.3...v0.9.4",
"experimentalFeatures": [
"portable-characters"
]
} }
] ]
} }
@@ -0,0 +1,154 @@
use coa_core::{
db::{Account, Db},
driver::{self, Verb},
ra::Ra,
Result,
};
use std::path::PathBuf;
fn main() -> Result<()> {
let root = PathBuf::from(std::env::args().nth(1).expect("disposable fixture"));
assert!(root
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("coa-update-recovery-fixture-"));
assert!(root.join("recovery-e2e-started").is_file());
let result = std::panic::catch_unwind(|| -> Result<()> {
let started = driver::run(&root, Verb::StartAll)?;
assert!(started.ok, "{}", started.output);
assert!(root.join("Core/Crashes").is_dir());
let db = Db::from_repack(&root, Account::Admin)?;
println!("Account acceptance: server started, connecting to RA");
let mut ra = Ra::connect(&root)?;
println!("Account acceptance: RA authenticated");
let name = "STABILITYACCT2";
assert_eq!(
db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2';")?
.trim(),
"0"
);
println!("Account acceptance: sending create command");
coa_core::accounts::create(&root, name, "PrivateTest773", true)?;
println!("Account acceptance: created");
assert_eq!(db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2' AND LENGTH(salt)=32 AND LENGTH(verifier)=32;")?.trim(), "1");
assert!(ra
.create_account(name, "PrivateTest773")
.unwrap_err()
.to_string()
.contains("already taken"));
ra.set_account_password(name, "PrivateTest774")?;
ra.set_account_access(name, 3)?;
assert_eq!(db.query("SELECT gmlevel FROM acore_auth.account_access WHERE id=(SELECT id FROM acore_auth.account WHERE username='STABILITYACCT2');")?.trim(), "3");
ra.delete_account(name)?;
assert_eq!(
db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2';")?
.trim(),
"0"
);
lost_reply(&root, &db)?;
println!("PASS: native RA account create, SRP salt/verifier, duplicate refusal, password change, administrator access and deletion");
Ok(())
});
let stopped = driver::run(&root, Verb::StopAll)?;
assert!(stopped.ok, "{}", stopped.output);
result.map_err(|_| {
coa_core::Error::Invalid("Native account acceptance failed; fixture stopped".into())
})?
}
fn lost_reply(root: &std::path::Path, db: &Db) -> Result<()> {
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
let path = root.join("Settings/repack.json");
let original = std::fs::read(&path)?;
struct Restore(std::path::PathBuf, Vec<u8>);
impl Drop for Restore {
fn drop(&mut self) {
std::fs::write(&self.0, &self.1).expect("restore disposable fixture settings");
}
}
let restore = Restore(path.clone(), original.clone());
let actual = coa_core::layout::read_ports(root).ra;
for (name, forward, ready) in [
("STABLOSTREPLY", true, true),
("STABNOTCREATED", false, true),
("STABNOTREADY", false, false),
] {
assert_eq!(
db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim(),
"0"
);
let listener = TcpListener::bind(("127.0.0.1", 0))?;
let mut config: serde_json::Value = serde_json::from_slice(&original)?;
config["raPort"] = listener.local_addr()?.port().into();
coa_core::fsx::atomic_write_json(&path, &config)?;
let proxy = std::thread::spawn(move || {
fn until(s: &mut TcpStream, marker: &[u8]) -> Vec<u8> {
s.set_read_timeout(Some(std::time::Duration::from_secs(30)))
.unwrap();
let mut bytes = Vec::new();
let mut byte = [0];
while !bytes.ends_with(marker) {
s.read_exact(&mut byte).unwrap();
bytes.push(byte[0]);
}
bytes
}
let (mut client, _) = listener.accept().unwrap();
let mut server = TcpStream::connect(("127.0.0.1", actual)).unwrap();
for marker in [b"Username: ".as_slice(), b"Password: ".as_slice()] {
client.write_all(&until(&mut server, marker)).unwrap();
server.write_all(&until(&mut client, b"\r\n")).unwrap();
}
client.write_all(&until(&mut server, b"AC>")).unwrap();
let readiness = until(&mut client, b"\r\n");
assert_eq!(readiness, b"server info\r\n");
if !ready {
return;
}
server.write_all(&readiness).unwrap();
client.write_all(&until(&mut server, b"AC>")).unwrap();
let command = until(&mut client, b"\r\n");
if forward {
server.write_all(&command).unwrap();
let _ = until(&mut server, b"AC>");
}
});
let outcome = coa_core::accounts::create(root, name, "PrivateTest773", false);
proxy.join().unwrap();
std::fs::write(&path, &original)?;
if forward {
outcome?;
assert_eq!(
db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim(),
"1"
);
assert!(coa_core::accounts::create(root, name, "DifferentPass77", false).is_err());
Ra::connect(root)?.delete_account(name)?;
} else {
assert!(outcome.is_err());
if !ready {
assert!(outcome
.unwrap_err()
.to_string()
.contains("No create command was sent"));
}
assert_eq!(
db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim(),
"0"
);
}
}
drop(restore);
println!("PASS: a lost native console reply is reconciled by exact SRP credentials; a command that was never executed is rejected");
Ok(())
}
@@ -0,0 +1,11 @@
use coa_core::{crashes, Result};
fn main()->Result<()> {
let root=std::path::PathBuf::from(std::env::args().nth(1).expect("marked native fixture"));
assert!(root.join("recovery-e2e-started").is_file());
let reports=crashes::list(&root,30)?;
let matching:Vec<_>=reports.iter().filter(|r|r.full_log.contains("AllowableRaces")).collect();
assert!(!matching.is_empty());
assert!(matching.iter().all(|r|r.exception_code.as_deref()==Some("C0000420")));
println!("PASS: Manager discovered {} actual worldserver SQL assertion reports from Core/Crashes, including Windows ANSI text",matching.len());
Ok(())
}
@@ -0,0 +1,91 @@
use coa_core::{
db::{Account, Db},
driver::{self, Verb},
ra::Ra,
Result,
};
use std::{
path::PathBuf,
time::{Duration, Instant},
};
fn main() -> Result<()> {
let root = PathBuf::from(
std::env::args()
.nth(1)
.expect("disposable recovery fixture"),
);
assert!(root
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("coa-update-recovery-fixture-"));
assert!(root.join("recovery-e2e-started").is_file());
let result = std::panic::catch_unwind(|| -> Result<()> {
let start = driver::run(&root, Verb::StartAll)?;
assert!(start.ok, "{}", start.output);
let db = Db::from_repack(&root, Account::Admin)?;
coa_core::companions::ensure_templates(&db)?;
let mut ra = Ra::connect(&root)?;
let before = coa_core::population::query(&root)?;
assert_eq!(before.bots_online, 0);
let rejected = db.query("SELECT name, at_login FROM acore_characters.characters WHERE guid=3030 AND account IN (SELECT id FROM acore_auth.account WHERE username LIKE 'COABOTHOST%');")?;
assert!(rejected.contains("Christian Shadowheart"));
assert_eq!(rejected.split_whitespace().last(), Some("1"));
println!("Repair reply: {}", ra.run("botcmd spawnbot 3030")?);
let repair_deadline = Instant::now() + Duration::from_secs(60);
loop {
let row = db.query(
"SELECT name, at_login, online FROM acore_characters.characters WHERE guid=3030;",
)?;
if row.trim().ends_with("0\t1") {
assert!(!row.contains("Christian Shadowheart"));
println!("PASS: the exact previously rejected companion was renamed by server validation and logged in");
break;
}
assert!(
Instant::now() < repair_deadline,
"previously rejected companion logged in"
);
std::thread::sleep(Duration::from_secs(1));
}
let _ = ra.despawn_all()?;
let clear_deadline = Instant::now() + Duration::from_secs(30);
while coa_core::population::query(&root)?.bots_online > 0 {
assert!(Instant::now() < clear_deadline);
std::thread::sleep(Duration::from_secs(1));
}
println!("Spawn reply: {}", ra.spawn_bots(21)?);
let deadline = Instant::now() + Duration::from_secs(180);
loop {
let pop = coa_core::population::query(&root)?;
if pop.bots_online >= 21 {
println!(
"PASS: {} companions logged in; real players={}",
pop.bots_online, pop.players_online
);
break;
}
if Instant::now() > deadline {
return Err(coa_core::Error::Invalid(format!(
"Only {} of 21 companion logins completed",
pop.bots_online
)));
}
std::thread::sleep(Duration::from_secs(2));
}
let _ = ra.cancel_spawning()?;
let _ = ra.despawn_all()?;
let deadline = Instant::now() + Duration::from_secs(30);
while coa_core::population::query(&root)?.bots_online > 0 {
assert!(Instant::now() < deadline, "companions despawned");
std::thread::sleep(Duration::from_secs(1));
}
println!("PASS: companion despawn completed");
Ok(())
});
let stopped = driver::run(&root, Verb::StopAll)?;
assert!(stopped.ok, "{}", stopped.output);
result.map_err(|_| {
coa_core::Error::Invalid("Companion native acceptance panicked; fixture stopped".into())
})?
}
@@ -0,0 +1,12 @@
use coa_core::{crashes, Result};
fn main() -> Result<()> {
let root = std::path::PathBuf::from(std::env::args().nth(1).expect("native crash evidence"));
assert!(root.join(".crash-report-evidence").is_file());
let reports = crashes::list(&root, 10)?;
assert_eq!(reports.len(), 1);
assert_eq!(reports[0].exception_code.as_deref(), Some("C0000005"));
assert_eq!(reports[0].category, "access_violation");
assert!(!reports[0].full_log.is_empty());
println!("PASS: Manager crash history discovers and classifies the actual native handler report from Core/Crashes");
Ok(())
}
@@ -0,0 +1,90 @@
use coa_core::{driver, fsx, process, Result};
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::{
path::Path,
process::{Child, Command, Stdio},
};
struct OwnedChild(Child);
impl Drop for OwnedChild {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn copy_tree(source: &Path, target: &Path) -> Result<()> {
std::fs::create_dir_all(target)?;
for entry in std::fs::read_dir(source)? {
let entry = entry?;
let destination = target.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_tree(&entry.path(), &destination)?;
} else {
std::fs::copy(entry.path(), destination)?;
}
}
Ok(())
}
fn spawn(path: &Path) -> OwnedChild {
let mut cmd = Command::new(path);
cmd.args(["-t", "127.0.0.1"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(windows)]
cmd.creation_flags(0x0800_0000);
OwnedChild(cmd.spawn().unwrap())
}
fn main() -> Result<()> {
assert!(cfg!(windows));
let source = std::path::PathBuf::from(
std::env::args()
.nth(1)
.expect("marked disposable runtime source"),
);
assert_eq!(
std::fs::read(source.join(".release-schema-fixture"))?,
b"disposable release-schema fixture"
);
let temp = tempfile::tempdir()?;
let root = temp.path();
copy_tree(&source.join("Runtime"), &root.join("Runtime"))?;
std::fs::create_dir_all(root.join("Core"))?;
std::fs::create_dir_all(root.join("Scripts"))?;
let system =
std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32/ping.exe");
std::fs::copy(&system, root.join("Core/worldserver.exe"))?;
std::fs::copy(&system, root.join("foreign.exe"))?;
let mut ports = Vec::new();
let mut listeners = Vec::new();
for _ in 0..4 {
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
ports.push(listener.local_addr()?.port());
listeners.push(listener);
}
let config = serde_json::json!({"mysqlPort":ports[0],"authPort":ports[1],"worldPort":ports[2],"raPort":ports[3],"raUsername":"fixture","raPassword":"fixture"});
fsx::atomic_write_json(&root.join("Settings/repack.json"), &config)?;
drop(listeners);
let mut launcher = std::fs::read_to_string(source.join("Scripts/manage.py"))?;
launcher.push_str("\nfrom contextlib import nullcontext\ndef control_lock(): return nullcontext()\ndef stop_all(config):\n assert not process('world'), 'world must stop before database'\n (ROOT/'database-stage').write_text('safe')\n");
fsx::atomic_write(&root.join("Scripts/manage.py"), launcher.as_bytes())?;
let mut foreign = spawn(&root.join("foreign.exe"));
let foreign_identity = process::identity(foreign.0.id()).unwrap();
fsx::atomic_write_json(&root.join(".state/world.json"), &foreign_identity)?;
let rejected = driver::force_stop(root)?;
assert!(!rejected.ok, "a foreign world record must be rejected");
assert!(!root.join("database-stage").exists());
assert!(foreign.0.try_wait()?.is_none());
let mut owned = spawn(&root.join("Core/worldserver.exe"));
let stopped = driver::force_stop(root)?;
assert!(stopped.ok, "{}", stopped.output);
assert!(owned.0.try_wait()?.is_some());
assert!(
foreign.0.try_wait()?.is_none(),
"foreign process was untouched"
);
assert_eq!(std::fs::read(root.join("database-stage"))?, b"safe");
println!("PASS: native Windows forced-stop rejects foreign records, recovers the exact owned world identity, stops it before the database stage, and leaves the foreign process alive");
Ok(())
}
@@ -0,0 +1,199 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use coa_core::{
backup,
db::Db,
driver::{self, Verb},
fsx,
manifest::{Kind, Migration},
package::{self, BuildOptions},
pkgsource::Source,
registry::MetaDir,
update::{self, RepackEnv},
Result,
};
use ed25519_dalek::{Signer, SigningKey};
use std::{collections::BTreeMap, path::PathBuf};
fn main() -> Result<()> {
let root = PathBuf::from(
std::env::args()
.nth(1)
.expect("qualified disposable fixture"),
);
let sql = std::fs::read(std::env::args().nth(2).expect("corrective SQL"))?;
assert_eq!(
root.file_name().unwrap(),
"coa-schema-fixture-stability-upgrade-76-85-20261030"
);
assert!(root.join(".release-schema-fixture").is_file());
assert!(!root.join("legacy-start-data-e2e-started").exists());
fsx::atomic_write(
&root.join("legacy-start-data-e2e-started"),
b"disposable regression test",
)?;
let result = std::panic::catch_unwind(|| -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(&root)?;
let mut identities = String::new();
let mut custom = String::new();
backup::with_database(&root, |db| {
assert_eq!(
db.query(
"SELECT COUNT(*) FROM acore_world.playercreateinfo WHERE race IN (33,45);"
)?
.trim(),
"0"
);
let base: u32 = db
.query("SELECT MAX(guid)+100 FROM acore_characters.characters;")?
.trim()
.parse()
.unwrap();
clone_character(db, base, 33, 12, "Thinprobe")?;
clone_character(db, base + 1, 45, 30, "Leperprobe")?;
identities = db.query(&format!(
"SELECT * FROM acore_characters.characters WHERE guid IN ({base},{});",
base + 1
))?;
let missing = coa_core::character_start_check::missing(db)?;
assert!(missing
.iter()
.any(|c| c.guid == base && c.race == 33 && c.class == 12));
assert!(missing
.iter()
.any(|c| c.guid == base + 1 && c.race == 45 && c.class == 30));
db.query("INSERT INTO acore_world.playercreateinfo SELECT 33,class,map,zone,position_x+0.125,position_y,position_z,orientation FROM acore_world.playercreateinfo WHERE race=1 AND class=32;")?;
custom =
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?;
fsx::atomic_write(
&root.join("legacy-probe-guids.json"),
serde_json::to_string(&[base, base + 1])?.as_bytes(),
)?;
println!("PASS: reproduced missing starting data for existing race 33/class 12 and race 45/class 30 characters");
Ok(())
})?;
let source = root.join("legacy-start-data-source");
let pkg = root.join("legacy-start-data-package");
fsx::atomic_write(
&source.join("Core/legacy-start-data-proof.txt"),
b"corrective migration acceptance",
)?;
fsx::atomic_write(
&source.join("_migrations/world/stabilization_legacy_starts.sql"),
&sql,
)?;
let manifest = package::build(
&source,
&pkg,
&BuildOptions {
kind: Kind::Update,
version: "2.0.0".into(),
core_commit: None,
bots_commit: None,
built_at: "private regression acceptance".into(),
part_size: 1 << 20,
migrations: vec![Migration {
id: "stabilization_legacy_starts".into(),
db: "world".into(),
sha256: fsx::sha256_bytes(&sql),
compatible_sha256: vec![],
destructive: false,
}],
},
&|_| {},
)?;
let key = SigningKey::generate(&mut rand_core::OsRng);
fsx::atomic_write(
&pkg.join("manifest.json.sig"),
STANDARD
.encode(
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
.to_bytes(),
)
.as_bytes(),
)?;
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
let env = RepackEnv {
root: &root,
meta_dir: &meta,
};
let out = update::apply(
&update::Params {
root: &root,
meta_dir: &meta,
source: Source::Dir(pkg),
trusted_key: &trusted,
cancel: Default::default(),
resolutions: BTreeMap::new(),
env: &env,
fail_after_ops: None,
},
&|step, pct| println!("{pct}% {step}"),
)?;
assert_eq!(out.txn.state, update::State::Committed);
assert_eq!(
MetaDir::open(&meta)?.1.core.version.as_deref(),
Some("2.0.0")
);
backup::with_database(&root, |db| {
let guids: Vec<u32> =
serde_json::from_slice(&std::fs::read(root.join("legacy-probe-guids.json"))?)?;
assert_eq!(
db.query(&format!(
"SELECT * FROM acore_characters.characters WHERE guid IN ({},{});",
guids[0], guids[1]
))?,
identities
);
assert!(coa_core::character_start_check::missing(db)?
.iter()
.all(|c| !guids.contains(&c.guid)));
assert_eq!(
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?,
custom
);
assert!(coa_core::migrations::status(db, &manifest.migrations)?
.iter()
.all(|m| m.status == coa_core::migrations::Status::Applied));
let before = counts(db)?;
db.query(&format!(
"USE acore_world; {}",
String::from_utf8_lossy(&sql)
))?;
assert_eq!(counts(db)?, before);
assert_eq!(
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?,
custom
);
println!("PASS: signed Manager update restored legacy starts, preserved complete character rows and custom starts, and remained idempotent on a second SQL execution");
Ok(())
})?;
Ok(())
});
let stopped = driver::run(&root, Verb::StopAll)?;
assert!(stopped.ok, "{}", stopped.output);
result.map_err(|_| {
coa_core::Error::Invalid("Legacy start regression failed; fixture stopped".into())
})?
}
fn counts(db: &Db) -> Result<String> {
db.query("SELECT COUNT(*) FROM acore_world.playercreateinfo WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.playercreateinfo_item WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.playercreateinfo_action WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.player_race_stats WHERE Race IN (33,45); SELECT COUNT(*) FROM acore_world.ascension_custom_class_race WHERE race IN (33,45);")
}
fn clone_character(db: &Db, guid: u32, race: u32, class: u32, name: &str) -> Result<()> {
let columns = db.query("SHOW COLUMNS FROM acore_characters.characters;")?;
let names: Vec<_> = columns
.lines()
.map(|l| l.split('\t').next().unwrap())
.collect();
let values: Vec<String> = names
.iter()
.map(|c| match *c {
"guid" => guid.to_string(),
"name" => format!("'{name}'"),
"race" => race.to_string(),
"class" => class.to_string(),
"online" | "at_login" => "0".into(),
_ => format!("`{c}`"),
})
.collect();
db.query(&format!("INSERT INTO acore_characters.characters ({}) SELECT {} FROM acore_characters.characters WHERE class={class} LIMIT 1;",names.iter().map(|c|format!("`{c}`")).collect::<Vec<_>>().join(","),values.join(",")))?;
Ok(())
}
@@ -0,0 +1,8 @@
use coa_core::{backup, schema_check, Result};
fn main()->Result<()> {
let root=std::path::PathBuf::from(std::env::args().nth(1).unwrap());
let contract=std::path::PathBuf::from(std::env::args().nth(2).unwrap());
assert!(root.join("recovery-e2e-started").is_file());
assert!(contract.join(".release-schema-fixture").is_file());
backup::with_database(&root,|db| {for p in schema_check::check(db,&contract)? {println!("{}.{}.{}: {}",p.database,p.table,p.column,p.detail);} Ok(())})
}
@@ -0,0 +1,132 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use coa_core::{
backup,
driver::{self, Verb},
fsx,
manifest::{Kind, Migration},
package::{self, BuildOptions},
pkgsource::Source,
update::{self, RepackEnv},
Result,
};
use ed25519_dalek::{Signer, SigningKey};
use std::{collections::BTreeMap, path::PathBuf};
fn main() -> Result<()> {
let root = PathBuf::from(std::env::args().nth(1).unwrap());
let core = PathBuf::from(std::env::args().nth(2).unwrap());
let release = PathBuf::from(std::env::args().nth(3).unwrap());
assert!(root.join("recovery-e2e-started").is_file());
let result = std::panic::catch_unwind(|| -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(&root)?;
let source = root.join("schema-sync-source-v2");
let pkg = root.join("schema-sync-package-v2");
assert!(!pkg.exists());
fsx::atomic_write(
&source.join("Core/schema-sync-proof.txt"),
b"official schema migration acceptance",
)?;
let published =
coa_core::manifest::Manifest::parse(&std::fs::read(release.join("manifest.json"))?)?;
let contract_path = PathBuf::from("C:/games/source/coa-schema-fixture-stability-upgrade-76-85-20261030/Scripts/database-schema.json");
let contract = std::fs::read(contract_path)?;
let expected = published
.files
.iter()
.find(|f| f.path == "Scripts/database-schema.json")
.unwrap();
assert_eq!(fsx::sha256_bytes(&contract), expected.sha256);
fsx::atomic_write(&source.join("Scripts/database-schema.json"), &contract)?;
let mut migrations: Vec<Migration> = Vec::new();
for id in [
"rev_1793212891571528600",
"rev_20261027_18_coa_strange_piece_of_scrap_faction_diamond",
] {
let m = published
.migrations
.iter()
.find(|m| m.id == id)
.unwrap()
.clone();
let sql = std::fs::read(
core.join(format!("data/sql/updates/pending_db_{}/{}.sql", m.db, m.id)),
)?;
assert_eq!(fsx::sha256_bytes(&sql), m.sha256);
fsx::atomic_write(
&source.join(format!("_migrations/{}/{}.sql", m.db, m.id)),
&sql,
)?;
migrations.push(m);
}
package::build(
&source,
&pkg,
&BuildOptions {
kind: Kind::Update,
version: "3.0.0".into(),
core_commit: None,
bots_commit: None,
built_at: "private native fixture schema sync".into(),
part_size: 1 << 20,
migrations,
},
&|_| {},
)?;
let key = SigningKey::generate(&mut rand_core::OsRng);
fsx::atomic_write(
&pkg.join("manifest.json.sig"),
STANDARD
.encode(
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
.to_bytes(),
)
.as_bytes(),
)?;
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
let env = RepackEnv {
root: &root,
meta_dir: &meta,
};
let out = update::apply(
&update::Params {
root: &root,
meta_dir: &meta,
source: Source::Dir(pkg),
trusted_key: &trusted,
cancel: Default::default(),
resolutions: BTreeMap::from([(
"Scripts/database-schema.json".into(),
update::Resolution::Replace,
)]),
env: &env,
fail_after_ops: None,
},
&|step, pct| println!("{pct}% {step}"),
)?;
assert_eq!(out.txn.state, update::State::Committed);
backup::with_database(&root, |db| {
assert_eq!(
db.query("SELECT name,at_login FROM acore_characters.characters WHERE guid=3030;")?
.trim(),
"Christian Shadowheart\t1"
);
assert_eq!(
db.query("SELECT id FROM acore_characters.manager_recovery_probe;")?
.trim(),
"42"
);
assert_eq!(
db.query("SELECT id FROM acore_world.manager_recovery_probe;")?
.trim(),
"44"
);
Ok(())
})?;
println!("PASS: the exact two published migrations brought the old fixture schema forward through the Manager updater while preserving the rejected companion and recovery probes");
Ok(())
});
let stop = driver::run(&root, Verb::StopAll)?;
assert!(stop.ok, "{}", stop.output);
result.map_err(|_| {
coa_core::Error::Invalid("Schema sync acceptance failed; fixture stopped".into())
})?
}
@@ -0,0 +1,166 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use coa_core::{
backup, driver, fsx,
manifest::{Kind, Migration},
package::{self, BuildOptions},
pkgsource::Source,
registry::MetaDir,
update::{self, RepackEnv},
Result,
};
use ed25519_dalek::{Signer, SigningKey};
use std::{collections::BTreeMap, path::PathBuf};
fn main() -> Result<()> {
let root = PathBuf::from(
std::env::args()
.nth(1)
.expect("disposable recovery fixture"),
);
assert!(root
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("coa-update-recovery-fixture-"));
assert!(root.join("recovery-e2e-started").is_file());
let cycles_only = std::env::args().nth(2).as_deref() == Some("--cycles-only");
if !cycles_only {
assert!(!root.join("success-e2e-started").exists());
fsx::atomic_write(
&root.join("success-e2e-started"),
b"disposable success acceptance",
)?;
}
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if cycles_only {
restart_cycles(&root)
} else {
exercise(&root)
}
}));
assert!(
driver::run(&root, driver::Verb::StopAll)?.ok,
"fixture shutdown"
);
result.map_err(|_| {
coa_core::Error::Invalid(
"Success acceptance assertion failed; fixture services stopped".into(),
)
})?
}
fn exercise(root: &std::path::Path) -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(root)?;
assert!(update::unfinished(&meta).is_none());
assert!(driver::run(root, driver::Verb::StopAll)?.ok);
let source = root.join("success-source");
let pkg = root.join("success-package");
fsx::atomic_write(
&source.join("Core/stabilization-success.txt"),
b"verified update",
)?;
let sql = b"UPDATE manager_recovery_probe SET id=44 WHERE id=43;";
fsx::atomic_write(
&source.join("_migrations/world/stabilization_success.sql"),
sql,
)?;
let manifest = package::build(
&source,
&pkg,
&BuildOptions {
kind: Kind::Update,
version: "2.0.0".into(),
core_commit: None,
bots_commit: None,
built_at: "disposable acceptance".into(),
part_size: 1 << 20,
migrations: vec![Migration {
id: "stabilization_success".into(),
db: "world".into(),
sha256: fsx::sha256_bytes(sql),
compatible_sha256: vec![],
destructive: false,
}],
},
&|_| {},
)?;
let key = SigningKey::generate(&mut rand_core::OsRng);
fsx::atomic_write(
&pkg.join("manifest.json.sig"),
STANDARD
.encode(
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
.to_bytes(),
)
.as_bytes(),
)?;
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
let env = RepackEnv {
root,
meta_dir: &meta,
};
let outcome = update::apply(
&update::Params {
root,
meta_dir: &meta,
source: Source::Dir(pkg),
trusted_key: &trusted,
cancel: Default::default(),
resolutions: BTreeMap::new(),
env: &env,
fail_after_ops: None,
},
&|step, pct| println!("{pct}% {step}"),
)?;
assert_eq!(outcome.txn.state, update::State::Committed);
assert_eq!(
MetaDir::open(&meta)?.1.core.version.as_deref(),
Some("2.0.0")
);
assert!(update::unfinished(&meta).is_none());
assert_eq!(
std::fs::read(root.join("Core/stabilization-success.txt"))?,
b"verified update"
);
backup::with_database(root, |db| {
assert_eq!(
db.query("SELECT id FROM acore_characters.manager_recovery_probe;")?,
"42"
);
assert_eq!(
db.query("SELECT id FROM acore_characters.manager_recovery_view;")?,
"42"
);
assert_eq!(
db.query("SELECT id FROM acore_world.manager_recovery_probe;")?,
"44"
);
assert!(coa_core::migrations::status(db, &manifest.migrations)?
.iter()
.all(|m| m.status == coa_core::migrations::Status::Applied));
Ok(())
})?;
restart_cycles(root)?;
println!("PASS: signed update committed after failed rehearsal and recovery; SQL, files, metadata and player data verified; two native restart cycles passed");
Ok(())
}
fn restart_cycles(root: &std::path::Path) -> Result<()> {
for cycle in 0..2 {
let stopped = driver::run(root, driver::Verb::StopAll)?;
assert!(
stopped.ok,
"Stop cycle {cycle}: {}",
coa_core::diag::redact(&stopped.output)
);
let started = driver::run(root, driver::Verb::StartAll)?;
assert!(started.ok, "{}", started.output);
let pop = coa_core::population::query(root)?;
println!(
"Restart cycle {cycle}: world ready, players={}, bots={}",
pop.players_online, pop.bots_online
);
}
println!("PASS: two native restart cycles finished");
Ok(())
}
+32 -11
View File
@@ -30,15 +30,27 @@ fn main() -> Result<()> {
.unwrap() .unwrap()
.to_string_lossy() .to_string_lossy()
.starts_with("coa-update-recovery-fixture-")); .starts_with("coa-update-recovery-fixture-"));
assert!( let resume = std::env::args().nth(2).as_deref() == Some("--verify-recovered");
!root.join("recovery-e2e-started").exists(), let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
"Use a new fixture; never reuse an owned server" if resume {
); assert!(root.join("recovery-e2e-started").is_file());
fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?; let manifest = coa_core::manifest::Manifest::parse(&std::fs::read(
let result = exercise(&root); root.join("fixture-package/manifest.json"),
let stopped = driver::run(&root, Verb::StopAll)?; )?)?;
assert!(stopped.ok); verify_recovered(&root, &manifest)
result } else {
assert!(
!root.join("recovery-e2e-started").exists(),
"Use a new fixture"
);
fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?;
exercise(&root)
}
}));
assert!(driver::run(&root, Verb::StopAll)?.ok);
result.map_err(|_| {
Error::Invalid("Recovery acceptance assertion failed; owned services were stopped".into())
})?
} }
fn exercise(root: &Path) -> Result<()> { fn exercise(root: &Path) -> Result<()> {
@@ -122,9 +134,18 @@ fn exercise(root: &Path) -> Result<()> {
assert!( assert!(
error error
.to_string() .to_string()
.contains("private update rehearsal failed"), .contains("files and databases were restored to the recovery point"),
"{error}" "{error}"
); );
verify_recovered(root, &manifest)
}
fn verify_recovered(root: &Path, manifest: &coa_core::manifest::Manifest) -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(root)?;
let env = RepackEnv {
root,
meta_dir: &meta,
};
assert!(!root.join("Core/recovery-probe.txt").exists()); assert!(!root.join("Core/recovery-probe.txt").exists());
assert!(update::unfinished(&meta).is_none()); assert!(update::unfinished(&meta).is_none());
assert_eq!( assert_eq!(
@@ -168,6 +189,6 @@ fn exercise(root: &Path) -> Result<()> {
Db::from_repack(root, Account::Admin)?.realm(), Db::from_repack(root, Account::Admin)?.realm(),
coa_core::realms::Mode::Coa coa_core::realms::Mode::Coa
); );
println!("PASS: private rehearsal caught failed SQL before changing the installed world, characters, ledger, objects, files or version; complete recovery succeeded"); println!("PASS: failed SQL was rolled back; characters, world, ledger, views, triggers, routines, files and version were verified; the saved recovery point was restored again");
Ok(()) Ok(())
} }
+67
View File
@@ -80,6 +80,60 @@ fn upper(name: &str) -> Result<String> {
Ok(name.to_ascii_uppercase()) Ok(name.to_ascii_uppercase())
} }
pub fn create(root: &Path, name: &str, password: &str, administrator: bool) -> Result<()> {
validate_account(name, password)?;
let name = name.to_ascii_uppercase();
let db = Db::from_repack(root, Account::Admin)?;
if db
.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim()
!= "0"
{
return Err(Error::Invalid("That account name is already taken.".into()));
}
let mut ra = Ra::connect(root)?;
ra.performance().map_err(|error| Error::Invalid(format!("The server console is not ready for account creation. No create command was sent. {error}")))?;
let confirmed = ra.create_account(&name, password);
if let Err(error) = confirmed {
let stored = db.query(&format!(
"SELECT HEX(salt), HEX(verifier) FROM acore_auth.account WHERE username='{name}';"
))?;
if !matches_credentials(&stored, &name, password) {
return Err(Error::Invalid(format!("Account creation was not confirmed. Refresh the account list before retrying. {error}")));
}
if administrator {
ra = Ra::connect(root).map_err(|error| Error::Invalid(format!("The account was created, but administrator access was not confirmed. Refresh the account list and check its access level. {error}")))?;
}
}
if administrator {
if let Err(error) = ra.make_administrator(&name) {
let access = db.query(&format!("SELECT COUNT(*) FROM acore_auth.account_access WHERE id=(SELECT id FROM acore_auth.account WHERE username='{name}') AND gmlevel=3 AND RealmID=-1;"))?;
if access.trim() != "1" {
return Err(Error::Invalid(format!("The account was created, but administrator access was not confirmed. Refresh the account list and check its access level. {error}")));
}
}
}
Ok(())
}
fn matches_credentials(stored: &str, name: &str, password: &str) -> bool {
let Some((salt, verifier)) = stored.trim().split_once('\t') else {
return false;
};
let Ok(salt) = hex::decode(salt) else {
return false;
};
let Ok(salt): std::result::Result<[u8; 32], _> = salt.try_into() else {
return false;
};
let Ok(verifier) = hex::decode(verifier) else {
return false;
};
verifier.as_slice() == crate::srp6::verifier(name, password, &salt)
}
/// Give the account a new name. Needs the world console (the new password is what makes the login work again) and an /// Give the account a new name. Needs the world console (the new password is what makes the login work again) and an
/// account that is not logged in. The old name is put back if anything goes wrong. /// account that is not logged in. The old name is put back if anything goes wrong.
pub fn rename(root: &Path, ra: &mut Ra, old: &str, new: &str, password: &str) -> Result<()> { pub fn rename(root: &Path, ra: &mut Ra, old: &str, new: &str, password: &str) -> Result<()> {
@@ -165,6 +219,19 @@ pub fn delete(root: &Path, ra: &mut Ra, name: &str) -> Result<()> {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn lost_reply_requires_the_exact_requested_credentials() {
let salt = [42; 32];
let verifier = crate::srp6::verifier("NewPlayer", "Password77", &salt);
let stored = format!("{}\t{}\n", hex::encode(salt), hex::encode(verifier));
assert!(matches_credentials(&stored, "NEWPLAYER", "password77"));
assert!(!matches_credentials(&stored, "NEWPLAYER", "wrongpass"));
assert!(!matches_credentials(&stored, "OTHERPLAYER", "Password77"));
for value in ["", "NULL\tNULL", "00\t00", "malformed"] {
assert!(!matches_credentials(value, "NewPlayer", "Password77"));
}
}
#[test] #[test]
fn rows_from_the_client_become_accounts() { fn rows_from_the_client_become_accounts() {
let out = "2\tALICE\t3\t0\t2026-09-30 21:04:11\t4\n5\tBOB\t0\t1\t\t0\n7\tBROKEN\n"; let out = "2\tALICE\t3\t0\t2026-09-30 21:04:11\t4\n5\tBOB\t0\t1\t\t0\n7\tBROKEN\n";
+134
View File
@@ -0,0 +1,134 @@
use crate::{fsx, Error, Result};
use serde::{Deserialize, Serialize};
use std::{fs, path::Path};
#[derive(Default, Serialize, Deserialize)]
pub struct Graphics {
pub dxvk_disabled: bool,
pub enhancements_disabled: bool,
}
fn preferences(client: &Path) -> Result<Option<Graphics>> {
match fs::read(client.join(".coa-manager/graphics.json")) {
Ok(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
pub fn status(client: &Path) -> Result<Graphics> {
let saved = preferences(client)?.unwrap_or_default();
let actual = |name: &str, remembered: bool| -> Result<bool> {
let active = client.join(name).is_file();
let inactive = client.join(format!("{name}.DISABLED")).is_file();
if active && inactive {
return Err(Error::Invalid(
"Both enabled and disabled renderer files exist.".into(),
));
}
Ok(inactive || (!active && remembered))
};
Ok(Graphics {
dxvk_disabled: actual("d3d9.dll", saved.dxvk_disabled)?,
enhancements_disabled: actual("dxgi.dll", saved.enhancements_disabled)?,
})
}
pub fn disabled(client: &Path, path: &str) -> Result<bool> {
let name = path.to_ascii_lowercase();
if !matches!(name.as_str(), "d3d9.dll" | "dxgi.dll") {
return Ok(false);
}
let state = status(client)?;
Ok(if name == "d3d9.dll" {
state.dxvk_disabled
} else {
state.enhancements_disabled
})
}
pub fn set(client: &Path, name: &str, disabled: bool) -> Result<Graphics> {
if !matches!(name, "d3d9.dll" | "dxgi.dll") {
return Err(Error::Invalid("Unknown graphics setting.".into()));
}
if crate::client::is_running(client) {
return Err(Error::Invalid(
"Close the game before changing graphics settings.".into(),
));
}
let active = fsx::safe_join(client, name)?;
let inactive = fsx::safe_join(client, &format!("{name}.DISABLED"))?;
if active.exists() && inactive.exists() {
return Err(Error::Invalid("Both enabled and disabled renderer files exist. Resolve the conflict before changing graphics settings.".into()));
}
let mut state = status(client)?;
if name == "d3d9.dll" {
state.dxvk_disabled = disabled;
} else {
state.enhancements_disabled = disabled;
}
let (source, target) = if disabled {
(&active, &inactive)
} else {
(&inactive, &active)
};
// The no-clobber link also preserves an existing destination if another app changes the setting.
if source.is_file() {
if let Err(error) = fs::hard_link(source, target) {
if error.kind() == std::io::ErrorKind::AlreadyExists {
return Err(error.into());
}
let mut output = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(target)?;
let copied = std::fs::File::open(source)
.and_then(|mut input| std::io::copy(&mut input, &mut output))
.and_then(|_| output.sync_all());
drop(output);
if let Err(error) = copied {
let _ = fs::remove_file(target);
return Err(error.into());
}
}
if let Err(error) = fs::remove_file(source) {
let _ = fs::remove_file(target);
return Err(error.into());
}
}
fsx::atomic_write_json(&client.join(".coa-manager/graphics.json"), &state)?;
Ok(state)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn toggles_preserve_bytes_and_refuse_conflicts() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
fs::write(root.join("d3d9.dll"), b"custom renderer").unwrap();
assert!(set(root, "d3d9.dll", true).unwrap().dxvk_disabled);
assert!(!root.join("d3d9.dll").exists());
assert_eq!(
fs::read(root.join("d3d9.dll.DISABLED")).unwrap(),
b"custom renderer"
);
assert!(!set(root, "d3d9.dll", false).unwrap().dxvk_disabled);
fs::write(root.join("d3d9.dll.DISABLED"), b"other").unwrap();
assert!(set(root, "d3d9.dll", false).is_err());
assert_eq!(fs::read(root.join("d3d9.dll")).unwrap(), b"custom renderer");
assert_eq!(fs::read(root.join("d3d9.dll.DISABLED")).unwrap(), b"other");
}
#[test]
fn remembers_missing_wrapper_and_imports_launcher_marker() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
assert!(set(root, "d3d9.dll", true).unwrap().dxvk_disabled);
assert!(disabled(root, "d3d9.dll").unwrap());
fs::write(root.join("dxgi.dll.DISABLED"), b"launcher disabled").unwrap();
assert!(disabled(root, "dxgi.dll").unwrap());
assert!(!disabled(root, "Data/d3d9.dll").unwrap());
}
}
+54
View File
@@ -299,6 +299,11 @@ pub fn plan(
bytes_per_sec: 0, bytes_per_sec: 0,
file: Some(f.path.clone()), file: Some(f.path.clone()),
}); });
if crate::client_graphics::disabled(client, &f.path)? {
kept += 1;
done += f.size;
continue;
}
let path = fsx::safe_join(client, &f.path)?; let path = fsx::safe_join(client, &f.path)?;
let meta = match fs::metadata(&path) { let meta = match fs::metadata(&path) {
Ok(meta) if meta.is_file() => meta, Ok(meta) if meta.is_file() => meta,
@@ -440,6 +445,9 @@ pub fn apply(a: &Apply, on_step: &dyn Fn(Step)) -> Result<()> {
let mut todo = Vec::new(); let mut todo = Vec::new();
for item in &a.plan.items { for item in &a.plan.items {
if crate::client_graphics::disabled(a.client, &item.path)? {
continue;
}
if item.kind == Kind::Modified && a.keep_modified { if item.kind == Kind::Modified && a.keep_modified {
let path = fsx::safe_join(a.client, &item.path)?; let path = fsx::safe_join(a.client, &item.path)?;
let meta = fs::metadata(&path)?; let meta = fs::metadata(&path)?;
@@ -777,6 +785,52 @@ mod tests {
); );
} }
#[test]
fn disabled_launcher_renderers_are_never_restored_even_with_a_stale_plan() {
let dir = tempfile::tempdir().unwrap();
let files: Vec<(&str, &[u8])> = vec![("d3d9.dll", b"dxvk"), ("dxgi.dll", b"enhancements")];
let manifest = manifest("v1", &files);
let cancel = Cancel::default();
let old_plan = plan(dir.path(), &manifest, &State::default(), &cancel, &|_| {}).unwrap();
fs::write(dir.path().join("d3d9.dll.DISABLED"), b"custom disabled").unwrap();
crate::client_graphics::set(dir.path(), "dxgi.dll", true).unwrap();
let server = Server::new(&files);
apply(
&Apply {
client: dir.path(),
manifest: &manifest,
plan: &old_plan,
keep_modified: false,
transport: &server,
objects_url: "https://x.invalid/objects",
cancel: &cancel,
},
&|_| {},
)
.unwrap();
assert!(server.requested.lock().unwrap().is_empty());
assert!(!dir.path().join("d3d9.dll").exists());
assert!(!dir.path().join("dxgi.dll").exists());
assert_eq!(
fs::read(dir.path().join("d3d9.dll.DISABLED")).unwrap(),
b"custom disabled"
);
let after = plan(
dir.path(),
&manifest,
&load_state(dir.path()).unwrap(),
&cancel,
&|_| {},
)
.unwrap();
assert!(after.items.is_empty());
crate::client_graphics::set(dir.path(), "d3d9.dll", false).unwrap();
assert_eq!(
fs::read(dir.path().join("d3d9.dll")).unwrap(),
b"custom disabled"
);
}
#[test] #[test]
fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() { fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() {
let d = tempfile::tempdir().unwrap(); let d = tempfile::tempdir().unwrap();
+69 -13
View File
@@ -214,11 +214,13 @@ fn run(
struct StreamWorker { struct StreamWorker {
tx: Sender<TunnelMsg>, tx: Sender<TunnelMsg>,
reset_on_drop: bool, reset_on_drop: bool,
shutdown: Arc<TcpStream>,
} }
impl Drop for StreamWorker { impl Drop for StreamWorker {
fn drop(&mut self) { fn drop(&mut self) {
if self.reset_on_drop { if self.reset_on_drop {
let _ = self.shutdown.shutdown(std::net::Shutdown::Both);
let _ = self.tx.send(TunnelMsg::Reset { stream_id: 0 }); let _ = self.tx.send(TunnelMsg::Reset { stream_id: 0 });
} }
} }
@@ -388,6 +390,8 @@ fn session(
}; };
match TcpStream::connect(("127.0.0.1", local_port)) { match TcpStream::connect(("127.0.0.1", local_port)) {
Ok(tcp) => { Ok(tcp) => {
let tcp = Arc::new(tcp);
let shutdown = tcp.clone();
let (stream_tx, stream_rx) = channel::<TunnelMsg>(); let (stream_tx, stream_rx) = channel::<TunnelMsg>();
let ws_tx = ws_out_tx.clone(); let ws_tx = ws_out_tx.clone();
@@ -398,6 +402,7 @@ fn session(
StreamWorker { StreamWorker {
tx: stream_tx, tx: stream_tx,
reset_on_drop: true, reset_on_drop: true,
shutdown,
}, },
); );
@@ -456,19 +461,20 @@ fn session(
fn spawn_local_tcp_bridge( fn spawn_local_tcp_bridge(
stream_id: u32, stream_id: u32,
mut tcp: TcpStream, tcp: Arc<TcpStream>,
from_tunnel: Receiver<TunnelMsg>, from_tunnel: Receiver<TunnelMsg>,
to_tunnel: Sender<TunnelMsg>, to_tunnel: Sender<TunnelMsg>,
) { ) {
let _ = tcp.set_nonblocking(false); let _ = tcp.set_nonblocking(false);
let _ = tcp.set_nodelay(true); let _ = tcp.set_nodelay(true);
let mut tcp_read = tcp.try_clone().expect("tcp clone"); let tcp_read = tcp.clone();
let to_tunnel_read = to_tunnel.clone(); let to_tunnel_read = to_tunnel.clone();
// Local TCP read -> to tunnel // Local TCP read -> to tunnel
std::thread::Builder::new() std::thread::Builder::new()
.name(format!("relay-stream-{stream_id}-read")) .name(format!("relay-stream-{stream_id}-read"))
.spawn(move || { .spawn(move || {
let mut tcp_read = tcp_read.as_ref();
let mut buf = [0u8; 16384]; let mut buf = [0u8; 16384];
loop { loop {
match tcp_read.read(&mut buf) { match tcp_read.read(&mut buf) {
@@ -498,11 +504,12 @@ fn spawn_local_tcp_bridge(
std::thread::Builder::new() std::thread::Builder::new()
.name(format!("relay-stream-{stream_id}-write")) .name(format!("relay-stream-{stream_id}-write"))
.spawn(move || { .spawn(move || {
let mut tcp_write = tcp.as_ref();
while let Ok(msg) = from_tunnel.recv() { while let Ok(msg) = from_tunnel.recv() {
match msg { match msg {
TunnelMsg::Data { chunk, .. } => { TunnelMsg::Data { chunk, .. } => {
if let Ok(data) = base64::engine::general_purpose::STANDARD.decode(&chunk) { if let Ok(data) = base64::engine::general_purpose::STANDARD.decode(&chunk) {
if tcp.write_all(&data).is_err() { if tcp_write.write_all(&data).is_err() {
break; break;
} }
} }
@@ -608,22 +615,71 @@ mod tests {
} }
#[test] #[test]
fn dropping_a_tunnel_closes_its_local_tcp_stream() { fn local_tunnel_exchanges_data_in_both_directions_before_reset() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let tcp = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); let tcp = Arc::new(TcpStream::connect(listener.local_addr().unwrap()).unwrap());
let shutdown = tcp.clone();
let (mut peer, _) = listener.accept().unwrap(); let (mut peer, _) = listener.accept().unwrap();
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
let (tx, rx) = channel(); let (tx, rx) = channel();
let (out, _) = channel(); let (out, replies) = channel();
spawn_local_tcp_bridge(7, tcp, rx, out); spawn_local_tcp_bridge(8, tcp, rx, out);
drop(StreamWorker { let worker = StreamWorker {
tx, tx,
reset_on_drop: true, reset_on_drop: true,
}); shutdown,
match peer.read(&mut [0u8; 1]) { };
Ok(0) => {}, worker
Err(error) if matches!(error.kind(), std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted) => {}, .tx
other => panic!("The abandoned relay stream must close, got {other:?}"), .send(TunnelMsg::Data {
stream_id: 8,
chunk: base64::engine::general_purpose::STANDARD.encode(b"request"),
})
.unwrap();
let mut request = [0; 7];
peer.read_exact(&mut request).unwrap();
assert_eq!(&request, b"request");
peer.write_all(b"response").unwrap();
let mut response = Vec::new();
while response.len() < 8 {
match replies.recv_timeout(Duration::from_secs(3)).unwrap() {
TunnelMsg::Data { chunk, .. } => response.extend(
base64::engine::general_purpose::STANDARD
.decode(chunk)
.unwrap(),
),
other => panic!("Expected the local reply, got {other:?}"),
}
}
assert_eq!(response, b"response");
drop(worker);
}
#[test]
fn dropping_a_tunnel_closes_its_local_tcp_stream() {
for _ in 0..32 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let tcp = Arc::new(TcpStream::connect(listener.local_addr().unwrap()).unwrap());
let shutdown = tcp.clone();
let (mut peer, _) = listener.accept().unwrap();
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
let (tx, rx) = channel();
let (out, _) = channel();
spawn_local_tcp_bridge(7, tcp, rx, out);
drop(StreamWorker {
tx,
reset_on_drop: true,
shutdown,
});
match peer.read(&mut [0u8; 1]) {
Ok(0) => {}
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted
) => {}
other => panic!("The abandoned relay stream must close, got {other:?}"),
}
} }
} }
} }
+67 -12
View File
@@ -24,17 +24,25 @@ pub struct CrashItem {
/// Lists recent crash reports from `Core/Crashes`, sorted newest first. /// Lists recent crash reports from `Core/Crashes`, sorted newest first.
pub fn list(root: &Path, limit: usize) -> Result<Vec<CrashItem>> { pub fn list(root: &Path, limit: usize) -> Result<Vec<CrashItem>> {
let dir = root.join("Core/Crashes"); let mut roots = vec![root.to_path_buf()];
roots.extend(crate::multiworld::Tree::ALL.map(|tree| crate::multiworld::tree_root(root, tree)));
let mut files: Vec<(PathBuf, SystemTime)> = Vec::new(); let mut files: Vec<(PathBuf, SystemTime)> = Vec::new();
if let Ok(entries) = fs::read_dir(&dir) { for world_root in roots {
for entry in entries.flatten() { let entries = match fs::read_dir(world_root.join("Core/Crashes")) {
let path = entry.path(); Ok(entries) => Some(entries),
if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("txt") { Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
let mtime = entry Err(e) => return Err(e.into()),
.metadata() };
.and_then(|m| m.modified()) if let Some(entries) = entries {
.unwrap_or(SystemTime::UNIX_EPOCH); for entry in entries.flatten() {
files.push((path, mtime)); let path = entry.path();
if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("txt") {
let mtime = entry
.metadata()
.and_then(|m| m.modified())
.unwrap_or(SystemTime::UNIX_EPOCH);
files.push((path, mtime));
}
} }
} }
} }
@@ -43,8 +51,12 @@ pub fn list(root: &Path, limit: usize) -> Result<Vec<CrashItem>> {
let mut items = Vec::new(); let mut items = Vec::new();
for (path, mtime) in files { for (path, mtime) in files {
if let Ok(content) = fs::read_to_string(&path) { if let Ok(bytes) = fs::read(&path) {
let item = parse_crash_content(&path, mtime, &content); let content = String::from_utf8_lossy(&bytes);
let mut item = parse_crash_content(&path, mtime, &content);
if let Ok(relative) = path.strip_prefix(root) {
item.id = relative.to_string_lossy().replace('\\', "/");
}
items.push(item); items.push(item);
} }
} }
@@ -237,6 +249,49 @@ fn explain(
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn discovers_native_ansi_reports_and_ignores_dump_files() {
let root = tempfile::tempdir().unwrap();
assert!(list(root.path(), 10).unwrap().is_empty());
fs::create_dir_all(root.path().join("Core/Crashes")).unwrap();
fs::write(
root.path().join("Core/Crashes/report.txt"),
b"Exception code: C0000005 \xff\r\n",
)
.unwrap();
fs::write(root.path().join("Core/Crashes/report.dmp"), b"binary").unwrap();
let reports = list(root.path(), 10).unwrap();
assert_eq!(reports.len(), 1);
assert_eq!(reports[0].exception_code.as_deref(), Some("C0000005"));
}
#[test]
fn discovers_reports_from_all_worlds_without_filename_collisions() {
let root = tempfile::tempdir().unwrap();
for relative in [
"Core/Crashes",
".realms/secondary/Core/Crashes",
".realms/reborn/Core/Crashes",
] {
fs::create_dir_all(root.path().join(relative)).unwrap();
fs::write(
root.path().join(relative).join("same.txt"),
b"Exception code: C0000005",
)
.unwrap();
}
let reports = list(root.path(), 10).unwrap();
assert_eq!(reports.len(), 3);
assert_eq!(
reports
.iter()
.map(|r| &r.id)
.collect::<std::collections::HashSet<_>>()
.len(),
3
);
}
#[test] #[test]
fn parses_assertion_report() { fn parses_assertion_report() {
let report = r#"Revision: AzerothCore rev. df5bcdf26092 2026-10-02 22:08:42 +0500 (coa-bots branch) (Win64, RelWithDebInfo, Static) let report = r#"Revision: AzerothCore rev. df5bcdf26092 2026-10-02 22:08:42 +0500 (coa-bots branch) (Win64, RelWithDebInfo, Static)
+85 -28
View File
@@ -31,36 +31,17 @@ impl Verb {
} }
} }
fn timeout(self, root: &Path) -> Duration { fn timeout(self, _root: &Path) -> Duration {
match self { match self {
Verb::StartAll | Verb::StartWorld if squid_enabled(root) => Duration::from_secs(2700), // Includes database startup, optional bot provisioning and the shared 25-minute
Verb::StartAll | Verb::StartWorld => Duration::from_secs(720), // world/console wait in launcher_bridge.py, even for older installed scripts.
Verb::StartAll | Verb::StartWorld => Duration::from_secs(3600),
Verb::StartMysql => Duration::from_secs(360), Verb::StartMysql => Duration::from_secs(360),
Verb::StopAll => Duration::from_secs(240), Verb::StopAll => Duration::from_secs(240),
} }
} }
} }
fn squid_enabled(root: &Path) -> bool {
let active = root.join("Core/configs/modules/playerbots.conf");
let path = if active.exists() {
active
} else {
root.join("Core/configs/modules/playerbots.conf.dist")
};
std::fs::read(path)
.ok()
.and_then(|bytes| crate::config::parser::ConfFile::parse_bytes(&bytes).ok())
.is_some_and(|config| {
config.get("AiPlayerbot.Enabled").is_none_or(|value| {
!matches!(
value.trim().trim_matches('"').to_ascii_lowercase().as_str(),
"0" | "false" | "no" | "off"
)
})
})
}
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct DriverOutcome { pub struct DriverOutcome {
pub ok: bool, pub ok: bool,
@@ -122,7 +103,69 @@ pub(crate) fn validate_update(root: &Path) -> Result<DriverOutcome> {
run_inner(root, Verb::StartAll, true) run_inner(root, Verb::StartAll, true)
} }
pub fn force_stop(root: &Path) -> Result<DriverOutcome> {
if crate::docker::is_docker(root) {
return Err(Error::Invalid(
"Forced shutdown is only available for Windows repacks.".into(),
));
}
for tree in crate::multiworld::Tree::ALL {
let path = crate::multiworld::tree_root(root, tree);
if crate::multiworld::tree_running(root, tree)
|| !crate::process::find_by_exe(&path.join("Core/worldserver.exe")).is_empty()
{
let child = fsx::ensure_within(root, &path)?;
let out = run_inner_mode(&child, Verb::StopAll, false, true)?;
if !out.ok || crate::multiworld::tree_running(root, tree) {
return Err(Error::Invalid(format!(
"An extra world could not stop; the shared database was left running. {}",
out.output
)));
}
}
}
run_inner_mode(root, Verb::StopAll, false, true)
}
fn recover_world_for_forced_stop(root: &Path) -> Result<()> {
let worlds = crate::process::find_by_exe(&root.join("Core/worldserver.exe"));
if worlds.len() > 1 {
return Err(Error::Invalid(
"More than one world process belongs to this folder; its database was left running."
.into(),
));
}
if let Some(world) = worlds.first() {
if !crate::process::is_alive(world) {
return Err(Error::Invalid(
"The world process identity changed; retry the stop.".into(),
));
}
if crate::process::read_state_record(root, "world")
.is_none_or(|saved| !saved.same_as(world))
{
let record = root.join(".state/world.json");
let previous = root.join(".state/world-before-forced-stop-recovery.json");
if record.is_file() && !previous.exists() {
fsx::atomic_write(&previous, &std::fs::read(&record)?)?;
}
fsx::atomic_write_json(&record, world)?;
tracing::warn!(pid = world.pid, root = %root.display(), "Recovered owned world identity before an explicitly requested forced stop");
}
}
Ok(())
}
fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverOutcome> { fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverOutcome> {
run_inner_mode(root, verb, validating_update, false)
}
fn run_inner_mode(
root: &Path,
verb: Verb,
validating_update: bool,
force: bool,
) -> Result<DriverOutcome> {
let root = fsx::canonicalize_lenient(root)?; let root = fsx::canonicalize_lenient(root)?;
let _update_lock = if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) { let _update_lock = if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) {
Some(crate::update::operation_lock_for( Some(crate::update::operation_lock_for(
@@ -143,7 +186,7 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
prepare_headless_world(&root, verb)?; prepare_headless_world(&root, verb)?;
return crate::docker::run(&root, verb); return crate::docker::run(&root, verb);
} }
if verb == Verb::StopAll { if verb == Verb::StopAll && !force {
crate::multiworld::stop(&root)?; crate::multiworld::stop(&root)?;
} }
if verb == Verb::StartAll { if verb == Verb::StartAll {
@@ -186,12 +229,15 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
if matches!(verb, Verb::StopAll | Verb::StartMysql | Verb::StartAll) { if matches!(verb, Verb::StopAll | Verb::StartMysql | Verb::StartAll) {
recover_mysql_launcher_state(&root, verb != Verb::StopAll)?; recover_mysql_launcher_state(&root, verb != Verb::StopAll)?;
} }
if force {
recover_world_for_forced_stop(&root)?;
}
let mut cmd = Command::new(&python); let mut cmd = Command::new(&python);
cmd.arg("-B") cmd.arg("-B")
.arg("-c") .arg("-c")
.arg(LAUNCH_SCRIPT) .arg(LAUNCH_SCRIPT)
.arg(&script) .arg(&script)
.arg(verb.arg()) .arg(if force { "force-stop-all" } else { verb.arg() })
.current_dir(&root) .current_dir(&root)
.stdin(Stdio::null()) .stdin(Stdio::null())
.stdout(Stdio::piped()) .stdout(Stdio::piped())
@@ -230,6 +276,13 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
let mut output = out_t.join().unwrap_or_default(); let mut output = out_t.join().unwrap_or_default();
output.push_str(&err_t.join().unwrap_or_default()); output.push_str(&err_t.join().unwrap_or_default());
let mut output = output.trim().to_string(); let mut output = output.trim().to_string();
if status.is_none() {
output.push_str(&format!(
"\nLauncher {} exceeded its {} second deadline; check the server logs.",
verb.arg(),
verb.timeout(&root).as_secs()
));
}
let (ok, exit_code) = match status { let (ok, exit_code) = match status {
Some(st) => (st.success(), st.code()), Some(st) => (st.success(), st.code()),
None => (false, None), None => (false, None),
@@ -290,6 +343,9 @@ fn prepare_headless_world(root: &Path, verb: Verb) -> Result<()> {
if !matches!(verb, Verb::StartAll | Verb::StartWorld) { if !matches!(verb, Verb::StartAll | Verb::StartWorld) {
return Ok(()); return Ok(());
} }
std::fs::create_dir_all(root.join("Core/Crashes"))?;
let probe = tempfile::NamedTempFile::new_in(root.join("Core/Crashes"))?;
probe.close()?;
for relative in [ for relative in [
"Settings/worldserver.conf.template", "Settings/worldserver.conf.template",
"Core/configs/worldserver.conf", "Core/configs/worldserver.conf",
@@ -587,6 +643,7 @@ mod tests {
let folder = tempfile::tempdir().unwrap(); let folder = tempfile::tempdir().unwrap();
let root = folder.path(); let root = folder.path();
prepare_headless_world(root, Verb::StartAll).unwrap(); prepare_headless_world(root, Verb::StartAll).unwrap();
assert!(root.join("Core/Crashes").is_dir());
std::fs::create_dir_all(root.join("Core/configs")).unwrap(); std::fs::create_dir_all(root.join("Core/configs")).unwrap();
let path = root.join("Core/configs/worldserver.conf"); let path = root.join("Core/configs/worldserver.conf");
for original in [ for original in [
@@ -604,7 +661,7 @@ mod tests {
} }
#[test] #[test]
fn large_squid_provisioning_has_time_to_finish_without_extending_shutdown() { fn slow_world_startup_has_time_with_either_bot_system_without_extending_shutdown() {
let folder = tempfile::tempdir().unwrap(); let folder = tempfile::tempdir().unwrap();
let modules = folder.path().join("Core/configs/modules"); let modules = folder.path().join("Core/configs/modules");
std::fs::create_dir_all(&modules).unwrap(); std::fs::create_dir_all(&modules).unwrap();
@@ -615,7 +672,7 @@ mod tests {
.unwrap(); .unwrap();
assert_eq!( assert_eq!(
Verb::StartAll.timeout(folder.path()), Verb::StartAll.timeout(folder.path()),
Duration::from_secs(2700) Duration::from_secs(3600)
); );
assert_eq!( assert_eq!(
Verb::StopAll.timeout(folder.path()), Verb::StopAll.timeout(folder.path()),
@@ -624,7 +681,7 @@ mod tests {
std::fs::write(modules.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap(); std::fs::write(modules.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
assert_eq!( assert_eq!(
Verb::StartWorld.timeout(folder.path()), Verb::StartWorld.timeout(folder.path()),
Duration::from_secs(720) Duration::from_secs(3600)
); );
assert_eq!( assert_eq!(
Verb::StartMysql.timeout(folder.path()), Verb::StartMysql.timeout(folder.path()),
+49 -14
View File
@@ -1,5 +1,6 @@
import runpy import runpy
import sys import sys
import time
from pathlib import Path from pathlib import Path
script = sys.argv[1] script = sys.argv[1]
@@ -7,21 +8,42 @@ sys.path.insert(0, str(Path(script).resolve().parent))
sys.argv = sys.argv[1:] sys.argv = sys.argv[1:]
launcher = runpy.run_path(script, run_name="coa_manager_launcher") launcher = runpy.run_path(script, run_name="coa_manager_launcher")
original_wait = launcher["wait_ready"] original_wait = launcher["wait_ready"]
world_deadline = None
def wait_ready(name, port, seconds=180): def wait_ready(name, port, seconds=180):
return original_wait(name, port, max(seconds, 300) if name == "mysql" else seconds) global world_deadline
if name == "mysql":
seconds = max(seconds, 300)
elif name == "world":
# Both game and console listeners belong to one startup, including on old repacks.
# Ordinary CoA worlds can load slowly too; this must not depend on SQUID.
if world_deadline is None:
world_deadline = time.monotonic() + max(seconds, 1500)
seconds = max(0, world_deadline - time.monotonic())
return original_wait(name, port, seconds)
launcher["start_mysql"].__globals__["wait_ready"] = wait_ready launcher["start_mysql"].__globals__["wait_ready"] = wait_ready
if sys.argv[1] == "stop-all": if sys.argv[1] in ("stop-all", "force-stop-all"):
shutdown = launcher["stop_all"].__globals__ shutdown = launcher["stop_all"].__globals__
class UnsafeShutdown(Exception):
pass
def stop_owned_world(world):
expected = Path(script).resolve().parents[1] / "Core" / "worldserver.exe"
if Path(world.get("exe", "")) != expected or not shutdown["same_process"](world):
raise UnsafeShutdown("World process ownership could not be verified; the database was left running.")
try:
shutdown["terminate"](world)
except (OSError, RuntimeError) as error:
raise UnsafeShutdown("Worldserver could not be stopped safely; its database was left running.") from error
if not shutdown["wait_stopped"](world, 90):
raise UnsafeShutdown("Worldserver is still stopping; its database was left running.")
if "ra" in shutdown: if "ra" in shutdown:
original_ra = shutdown["ra"] original_ra = shutdown["ra"]
class UnsafeShutdown(Exception):
pass
def shutdown_command(command, config): def shutdown_command(command, config):
try: try:
return original_ra(command, config) return original_ra(command, config)
@@ -31,20 +53,33 @@ if sys.argv[1] == "stop-all":
world = shutdown["process"]("world") world = shutdown["process"]("world")
if not world: if not world:
return "Worldserver has already stopped." return "Worldserver has already stopped."
expected = Path(script).resolve().parents[1] / "Core" / "worldserver.exe" stop_owned_world(world)
if Path(world.get("exe", "")) != expected or not shutdown["same_process"](world):
raise UnsafeShutdown("World process ownership could not be verified; the database was left running.")
try:
shutdown["terminate"](world)
except (OSError, RuntimeError) as error:
raise UnsafeShutdown("Worldserver could not be stopped safely; its database was left running.") from error
if not shutdown["wait_stopped"](world, 90):
raise UnsafeShutdown("Worldserver is still stopping; its database was left running.")
return "Stopped this server's recorded world process without its unavailable console." return "Stopped this server's recorded world process without its unavailable console."
shutdown["ra"] = shutdown_command shutdown["ra"] = shutdown_command
config = launcher["settings"]() config = launcher["settings"]()
with launcher["control_lock"](): with launcher["control_lock"]():
if sys.argv[1] == "force-stop-all":
world = shutdown["process"]("world")
if world:
stop_owned_world(world)
print("Force-stopped this server's verified world process; unsaved progress may be lost.", flush=True)
launcher["stop_all"](config) launcher["stop_all"](config)
else: else:
launcher["main"]() launcher["main"]()
if sys.argv[1] in ("start-all", "start-world"):
config = launcher["settings"]()
deadline = world_deadline if world_deadline is not None else time.monotonic() + 1500
last_error = None
while time.monotonic() < deadline:
if not launcher["process"]("world"):
raise RuntimeError("World startup failed: worldserver stopped before its console accepted commands.")
try:
launcher["ra"]("server info", config)
print("World console is accepting commands.", flush=True)
break
except (OSError, RuntimeError) as error:
last_error = error
time.sleep(0.5)
else:
raise RuntimeError(f"World startup failed: its console is still starting. {last_error}")
+2
View File
@@ -14,6 +14,7 @@ pub mod channels;
pub mod character_start_check; pub mod character_start_check;
pub mod cleanbase; pub mod cleanbase;
pub mod client; pub mod client;
pub mod client_graphics;
pub mod clientdl; pub mod clientdl;
pub mod companions; pub mod companions;
pub mod config; pub mod config;
@@ -55,6 +56,7 @@ pub mod realmlist;
pub mod realms; pub mod realms;
pub mod registry; pub mod registry;
pub mod release; pub mod release;
pub mod release_history;
pub mod release_schema; pub mod release_schema;
pub mod remote_client; pub mod remote_client;
pub mod repair; pub mod repair;
+101 -1
View File
@@ -307,6 +307,51 @@ pub struct Item {
pub error: Option<String>, pub error: Option<String>,
} }
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Audit {
pub total: usize,
pub applied: usize,
pub checksum_verified: usize,
pub legacy_unknown: usize,
}
pub fn inventory_sha256(list: &[Migration]) -> Result<String> {
let inventory: Vec<_> = list
.iter()
.map(|m| (&m.db, &m.id, &m.sha256, &m.compatible_sha256, m.destructive))
.collect();
Ok(fsx::sha256_bytes(&serde_json::to_vec(&inventory)?))
}
pub fn audit_applied(store: &dyn Store, list: &[Migration]) -> Result<Audit> {
let rows = store.load_readonly()?;
check_history(&rows, list)?;
let mut audit = Audit {
total: list.len(),
applied: 0,
checksum_verified: 0,
legacy_unknown: 0,
};
for migration in list {
let row = recorded(&rows, migration)
.filter(|r| r.status == Status::Applied)
.ok_or_else(|| {
Error::Invalid(format!(
"Release migration {} ({}) is not recorded as applied.",
migration.id, migration.db
))
})?;
audit.applied += 1;
if row.sha256 == "0".repeat(64) {
audit.legacy_unknown += 1;
} else {
audit.checksum_verified += 1;
}
}
Ok(audit)
}
pub fn status(store: &dyn Store, list: &[Migration]) -> Result<Vec<Item>> { pub fn status(store: &dyn Store, list: &[Migration]) -> Result<Vec<Item>> {
let rows = store.load()?; let rows = store.load()?;
Ok(list Ok(list
@@ -358,7 +403,7 @@ fn preserve_auth_history(store: &dyn Store, rows: &[LedgerRow], list: &[Migratio
} }
/// Migrations that were published with different bytes but have the same effect, so a server that applied either /// Migrations that were published with different bytes but have the same effect, so a server that applied either
/// version accepts the other. The Wildcard table repair went out as `c1d8…` (0.261005.0, 0.261006.1) and as `9e4a…` /// version accepts the other. The Wildcard table repair went out as `c1d8…` (0.261005.0, 0.261006.1) and as `9e4a…`
/// (0.261005.22, 0.261007.24); the packages carry no list of compatible versions, so the Manager knows this pair. /// (0.261005.22, 0.261007.24); the packages carry no list of compatible versions, so the Manager knows this pair.
const SAME_EFFECT: &[(&str, &[&str])] = &[( const SAME_EFFECT: &[(&str, &[&str])] = &[(
"manager_repair__20261005_missing_wildcard_tables", "manager_repair__20261005_missing_wildcard_tables",
@@ -667,6 +712,61 @@ mod tests {
} }
} }
#[test]
fn qualification_inventory_digest_matches_release_pipeline_encoding() {
let list = vec![Migration {
id: "one".into(),
db: "world".into(),
sha256: "a".repeat(64),
compatible_sha256: vec![],
destructive: false,
}];
assert_eq!(
inventory_sha256(&list).unwrap(),
"b35e45f666304500e69ff352f83103910075ace998afb7915b548765b8c30703"
);
}
#[test]
fn qualification_rejects_missing_interrupted_failed_and_changed_history() {
let (_dir, list) = setup(&[("world", "qualification_probe", "SELECT 1;")]);
let store = Mem::default();
assert!(audit_applied(&store, &list).is_err());
for status in [Status::Running, Status::Failed, Status::Pending] {
store
.put(&LedgerRow {
db: "world".into(),
id: list[0].id.clone(),
sha256: list[0].sha256.clone(),
status,
error: None,
baseline: false,
})
.unwrap();
assert!(audit_applied(&store, &list).is_err());
}
store
.put(&LedgerRow {
db: "world".into(),
id: list[0].id.clone(),
sha256: "a".repeat(64),
status: Status::Applied,
error: None,
baseline: false,
})
.unwrap();
assert!(audit_applied(&store, &list).is_err());
store.rows.borrow_mut()[0].sha256 = list[0].sha256.clone();
assert_eq!(audit_applied(&store, &list).unwrap().checksum_verified, 1);
store.rows.borrow_mut()[0].sha256 = "0".repeat(64);
let audit = audit_applied(&store, &list).unwrap();
assert_eq!(
(audit.applied, audit.checksum_verified, audit.legacy_unknown),
(1, 0, 1)
);
assert!(store.ran.borrow().is_empty());
}
fn setup(files: &[(&str, &str, &str)]) -> (tempfile::TempDir, Vec<Migration>) { fn setup(files: &[(&str, &str, &str)]) -> (tempfile::TempDir, Vec<Migration>) {
let d = tempfile::tempdir().unwrap(); let d = tempfile::tempdir().unwrap();
let mut list = Vec::new(); let mut list = Vec::new();
+6 -1
View File
@@ -497,7 +497,12 @@ mod tests {
) )
.unwrap(); .unwrap();
let err = set_reborn_enabled(t.path(), true).unwrap_err().to_string(); let err = set_reborn_enabled(t.path(), true).unwrap_err().to_string();
assert!(err.contains("Select Conquest of Azeroth first"), "{err}"); let expected = if cfg!(windows) {
"Select Conquest of Azeroth first"
} else {
"Simultaneous realms currently require Windows"
};
assert!(err.contains(expected), "{err}");
assert!(!realms::state(t.path()).unwrap().with_reborn); assert!(!realms::state(t.path()).unwrap().with_reborn);
} }
+69 -30
View File
@@ -21,22 +21,33 @@ pub struct SqlFile {
pub sha256: String, pub sha256: String,
} }
fn sql_in(dir: &Path) -> Vec<PathBuf> { fn entries(dir: &Path) -> Result<Vec<fs::DirEntry>> {
let mut v: Vec<PathBuf> = fs::read_dir(dir) match fs::read_dir(dir) {
.map(|rd| { Ok(rd) => Ok(rd.collect::<std::io::Result<Vec<_>>>()?),
rd.flatten() Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(vec![]),
.map(|e| e.path()) Err(error) => Err(error.into()),
.filter(|p| p.extension().map(|e| e == "sql").unwrap_or(false)) }
.collect() }
})
.unwrap_or_default(); fn sql_in(dir: &Path) -> Result<Vec<PathBuf>> {
v.sort(); let mut paths: Vec<_> = entries(dir)?
v .into_iter()
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|ext| ext == "sql"))
.collect();
paths.sort();
Ok(paths)
} }
/// The order in which files were first added to the repository (a pending script may rely on a table a module /// The order in which files were first added to the repository (a pending script may rely on a table a module
/// created earlier). Files git does not know come last, in name order. /// created earlier). Files git does not know come last, in name order.
fn introduction_rank(repo: &Path, pathspecs: &[&str]) -> std::collections::HashMap<String, usize> { fn introduction_rank(
repo: &Path,
pathspecs: &[&str],
) -> Result<std::collections::HashMap<String, usize>> {
if !repo.join(".git").exists() {
return Ok(Default::default());
}
let mut args = vec![ let mut args = vec![
"log", "log",
"--full-history", "--full-history",
@@ -48,18 +59,22 @@ fn introduction_rank(repo: &Path, pathspecs: &[&str]) -> std::collections::HashM
"--", "--",
]; ];
args.extend_from_slice(pathspecs); args.extend_from_slice(pathspecs);
let out = Command::new("git").current_dir(repo).args(&args).output(); let out = Command::new("git").current_dir(repo).args(&args).output()?;
let mut rank = std::collections::HashMap::new(); if !out.status.success() {
if let Ok(o) = out { return Err(Error::Invalid(format!(
for (i, line) in String::from_utf8_lossy(&o.stdout) "Cannot establish SQL migration order: {}",
.lines() String::from_utf8_lossy(&out.stderr)
.filter(|l| l.ends_with(".sql")) )));
.enumerate()
{
rank.entry(line.to_string()).or_insert(i);
}
} }
rank let mut rank = std::collections::HashMap::new();
for (i, line) in String::from_utf8_lossy(&out.stdout)
.lines()
.filter(|line| line.ends_with(".sql"))
.enumerate()
{
rank.entry(line.to_string()).or_insert(i);
}
Ok(rank)
} }
/// Incremental SQL of a core checkout. Installation-only module bases must never be replayed on a live database. /// Incremental SQL of a core checkout. Installation-only module bases must never be replayed on a live database.
@@ -91,7 +106,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result<Vec<SqlFile>
("world", ["db_world", "pending_db_world"]), ("world", ["db_world", "pending_db_world"]),
] { ] {
for d in dirs { for d in dirs {
for f in sql_in(&core.join("data/sql/updates").join(d)) { for f in sql_in(&core.join("data/sql/updates").join(d))? {
let stem = f.file_stem().unwrap().to_string_lossy().into_owned(); let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
let rel = format!( let rel = format!(
"data/sql/updates/{d}/{}", "data/sql/updates/{d}/{}",
@@ -101,8 +116,8 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result<Vec<SqlFile>
} }
} }
} }
if let Ok(rd) = fs::read_dir(core.join("modules")) { {
let mut mods: Vec<_> = rd.flatten().collect(); let mut mods = entries(&core.join("modules"))?;
mods.sort_by_key(|e| e.file_name()); mods.sort_by_key(|e| e.file_name());
for m in mods { for m in mods {
let name = m.file_name().to_string_lossy().into_owned(); let name = m.file_name().to_string_lossy().into_owned();
@@ -110,7 +125,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result<Vec<SqlFile>
for kind in ["auth", "characters", "world"] { for kind in ["auth", "characters", "world"] {
let base = m.path().join(format!("data/sql/db-{kind}")); let base = m.path().join(format!("data/sql/db-{kind}"));
for f in if include_base { for f in if include_base {
sql_in(&base.join("base")) sql_in(&base.join("base"))?
} else { } else {
vec![] vec![]
} { } {
@@ -121,7 +136,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result<Vec<SqlFile>
); );
push(kind, format!("mod_{mname}__base__{stem}"), f, rel)?; push(kind, format!("mod_{mname}__base__{stem}"), f, rel)?;
} }
for f in sql_in(&base) { for f in sql_in(&base)? {
let stem = f.file_stem().unwrap().to_string_lossy().into_owned(); let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
let rel = format!( let rel = format!(
"modules/{name}/data/sql/db-{kind}/{}", "modules/{name}/data/sql/db-{kind}/{}",
@@ -132,7 +147,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result<Vec<SqlFile>
} }
} }
} }
let rank = introduction_rank(core, &["data/sql/updates", "modules"]); let rank = introduction_rank(core, &["data/sql/updates", "modules"])?;
out.sort_by_key(|f| rank.get(&f.origin).copied().unwrap_or(usize::MAX)); out.sort_by_key(|f| rank.get(&f.origin).copied().unwrap_or(usize::MAX));
Ok(out) Ok(out)
} }
@@ -155,7 +170,7 @@ pub fn export_baseline(server: &Path, out: &Path) -> Result<Vec<(String, u64)>>
/// SQL a bots module checkout ships for the characters database (its `dist/sql`). /// SQL a bots module checkout ships for the characters database (its `dist/sql`).
pub fn collect_bots_sql(bots: &Path) -> Result<Vec<SqlFile>> { pub fn collect_bots_sql(bots: &Path) -> Result<Vec<SqlFile>> {
let mut out = Vec::new(); let mut out = Vec::new();
for f in sql_in(&bots.join("dist/sql")) { for f in sql_in(&bots.join("dist/sql"))? {
let stem = f.file_stem().unwrap().to_string_lossy().into_owned(); let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
out.push(SqlFile { out.push(SqlFile {
db: "characters".into(), db: "characters".into(),
@@ -364,6 +379,30 @@ mod tests {
fs::write(p, c).unwrap(); fs::write(p, c).unwrap();
} }
#[test]
fn sql_collection_rejects_broken_history_in_a_git_checkout() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), ".git", "gitdir: missing-history");
write(dir.path(), "data/sql/updates/db_world/one.sql", "SELECT 1;");
assert!(collect_core_sql(dir.path())
.unwrap_err()
.to_string()
.contains("migration order"));
}
#[test]
fn sql_collection_rejects_unreadable_directories_instead_of_omitting_migrations() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "data/sql/updates/db_world", "not a directory");
assert!(collect_core_sql(dir.path()).is_err());
let bots = tempfile::tempdir().unwrap();
write(bots.path(), "dist/sql", "not a directory");
assert!(collect_bots_sql(bots.path()).is_err());
let modules = tempfile::tempdir().unwrap();
write(modules.path(), "modules", "not a directory");
assert!(collect_core_sql(modules.path()).is_err());
}
#[test] #[test]
fn collects_core_and_module_sql_with_module_base_first_and_stable_ids() { fn collects_core_and_module_sql_with_module_base_first_and_stable_ids() {
let d = tempfile::tempdir().unwrap(); let d = tempfile::tempdir().unwrap();
+170
View File
@@ -0,0 +1,170 @@
//! Read-only, bounded canonical histories. Offline fallback is also bundled in the UI.
use serde_json::Value;
use std::{io::Read, path::Path, time::Duration};
const LIMIT: u64 = 2 * 1024 * 1024;
fn repository(component: &str) -> Result<(&'static str, &'static str), String> {
match component {
"server" => Ok(("Corfirean/coa-server-build", "main")),
"manager" => Ok(("Corfirean/coa-server-manager", "master")),
_ => Err("Unknown release component".into()),
}
}
fn validate(bytes: &[u8], component: &str) -> Result<Value, String> {
let (repo, _) = repository(component)?;
if bytes.len() as u64 > LIMIT {
return Err("Release history is too large".into());
}
let value: Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
if value["schema"] != 1 || value["component"] != component || value["repository"] != repo {
return Err("Release history identity mismatch".into());
}
let releases = value["releases"].as_array().ok_or("Missing releases")?;
if releases.len() > 2000 {
return Err("Too many releases".into());
}
for release in releases {
if release.get("prerelease").is_some_and(|v| !v.is_boolean())
|| release.get("experimentalFeatures").is_some_and(|v| {
v.as_array()
.is_none_or(|items| items.iter().any(|item| !item.is_string()))
})
{
return Err("Invalid release flags".into());
}
for field in ["tag", "date"] {
if release[field]
.as_str()
.is_none_or(|s| s.is_empty() || s.len() > 100)
{
return Err("Invalid release metadata".into());
}
}
let version = release["version"].as_str().ok_or("Missing version")?;
if version.len() > 80
|| !version
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b".-+".contains(&b))
{
return Err("Invalid version".into());
}
let notes = release["notes"].as_array().ok_or("Missing notes")?;
if notes.len() > 500
|| notes
.iter()
.any(|n| n.as_str().is_none_or(|s| s.len() > 10000))
{
return Err("Invalid release notes".into());
}
}
Ok(value)
}
pub fn load(component: &str, cache_dir: &Path) -> Result<Value, String> {
let (repo, branch) = repository(component)?;
let cache = cache_dir.join(format!("{component}.json"));
let cached = || {
let mut bytes = Vec::new();
std::fs::File::open(&cache)
.ok()?
.take(LIMIT + 1)
.read_to_end(&mut bytes)
.ok()?;
validate(&bytes, component).ok()
};
if cache
.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.elapsed().ok())
.is_some_and(|age| age < Duration::from_secs(3600))
{
if let Some(mut v) = cached() {
v["source"] = "cache".into();
return Ok(v);
}
}
let remote = || -> Result<Value, String> {
let client = reqwest::blocking::Client::builder()
.timeout(Duration::from_secs(8))
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|e| e.to_string())?;
let response = client
.get(format!(
"https://raw.githubusercontent.com/{repo}/{branch}/changelog/history.json"
))
.send()
.and_then(|r| r.error_for_status())
.map_err(|e| e.to_string())?;
let mut bytes = Vec::new();
response
.take(LIMIT + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
let mut value = validate(&bytes, component)?;
if std::fs::create_dir_all(cache_dir).is_ok() {
let _ = std::fs::write(&cache, &bytes);
}
value["source"] = "remote".into();
Ok(value)
};
remote().or_else(|error| {
cached()
.map(|mut v| {
v["source"] = "cache".into();
v
})
.ok_or(error)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_both_complete_bundled_canonical_histories() {
assert!(validate(include_bytes!("../../../changelog/history.json"), "manager").is_ok());
assert!(validate(
include_bytes!("../../../src/data/server-history.json"),
"server"
)
.is_ok());
}
#[test]
fn rejects_cross_component_and_untrusted_components() {
let bytes = br#"{"schema":1,"component":"manager","repository":"Corfirean/coa-server-manager","releases":[]}"#;
assert!(validate(bytes, "manager").is_ok());
assert!(validate(bytes, "server").is_err());
assert!(repository("../../other").is_err());
assert!(validate(&vec![b' '; LIMIT as usize + 1], "manager").is_err());
}
#[test]
fn rejects_malformed_records_before_the_ui_can_use_them() {
let mut value = serde_json::json!({"schema": 1, "component": "server",
"repository": "Corfirean/coa-server-build", "releases": [{
"version": "0.261028.83", "tag": "0.261028.83", "date": "2026-10-28",
"notes": ["Reviewed note"]
}]});
assert!(validate(&serde_json::to_vec(&value).unwrap(), "server").is_ok());
value["releases"][0]["date"] = Value::Null;
assert!(validate(&serde_json::to_vec(&value).unwrap(), "server").is_err());
value["releases"][0]["date"] = "2026-10-28".into();
value["releases"][0]["notes"] = serde_json::json!([{"html": "not a text note"}]);
assert!(validate(&serde_json::to_vec(&value).unwrap(), "server").is_err());
}
#[test]
fn fresh_valid_cache_is_available_without_network() {
let dir = std::env::temp_dir().join(format!("coa-history-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("manager.json"), br#"{"schema":1,"component":"manager","repository":"Corfirean/coa-server-manager","releases":[]}"#).unwrap();
let result = load("manager", &dir).unwrap();
assert_eq!(result["source"], "cache");
std::fs::remove_file(dir.join("manager.json")).unwrap();
std::fs::remove_dir(dir).unwrap();
}
}
+152 -4
View File
@@ -96,7 +96,7 @@ pub fn qualify_upgrade(
pkgsource::fetch_manifest(&pkgsource::Source::Dir(base.into()), trusted_key)?; pkgsource::fetch_manifest(&pkgsource::Source::Dir(base.into()), trusted_key)?;
let (source_manifest, source_bytes) = let (source_manifest, source_bytes) =
pkgsource::fetch_manifest(&pkgsource::Source::Dir(source.into()), trusted_key)?; pkgsource::fetch_manifest(&pkgsource::Source::Dir(source.into()), trusted_key)?;
let (candidate_manifest, _) = let (candidate_manifest, candidate_bytes) =
pkgsource::fetch_manifest(&pkgsource::Source::Dir(candidate.into()), trusted_key)?; pkgsource::fetch_manifest(&pkgsource::Source::Dir(candidate.into()), trusted_key)?;
if candidate_manifest.kind != Kind::Update if candidate_manifest.kind != Kind::Update
|| !matches!(source_manifest.kind, Kind::Base | Kind::Update) || !matches!(source_manifest.kind, Kind::Base | Kind::Update)
@@ -149,6 +149,7 @@ pub fn qualify_upgrade(
} }
env.ensure_stopped() env.ensure_stopped()
}; };
let mut migration_audit = None;
install::with_scratch_ports(fixture, || { install::with_scratch_ports(fixture, || {
if source_manifest.kind == Kind::Update { if source_manifest.kind == Kind::Update {
apply(source)?; apply(source)?;
@@ -157,6 +158,7 @@ pub fn qualify_upgrade(
let user_bytes = b"Qualification.UserSetting = 7391\r\n"; let user_bytes = b"Qualification.UserSetting = 7391\r\n";
fsx::atomic_write(&user_file, user_bytes)?; fsx::atomic_write(&user_file, user_bytes)?;
apply(candidate)?; apply(candidate)?;
migration_audit = Some(audit_migrations(fixture, &candidate_manifest.migrations)?);
if std::fs::read(&user_file)?.as_slice() != user_bytes { if std::fs::read(&user_file)?.as_slice() != user_bytes {
return Err(Error::Invalid( return Err(Error::Invalid(
"The update changed a user configuration file.".into(), "The update changed a user configuration file.".into(),
@@ -175,9 +177,10 @@ pub fn qualify_upgrade(
})?; })?;
Ok(serde_json::json!({ Ok(serde_json::json!({
"schema": 1, "result": "passed", "fromVersion": source_manifest.version, "schema": 1, "result": "passed", "fromVersion": source_manifest.version,
"toVersion": candidate_manifest.version, "fromManifestSha256": fsx::sha256_bytes(&source_bytes), "toVersion": candidate_manifest.version, "toManifestSha256": fsx::sha256_bytes(&candidate_bytes),
"migrationInventorySha256": migrations::inventory_sha256(&candidate_manifest.migrations)?, "migrations": migration_audit, "fromManifestSha256": fsx::sha256_bytes(&source_bytes),
"fromSchemaSha256": source_manifest.files.iter().find(|file| file.path == schema_check::CONTRACT).map(|file| &file.sha256), "fromSchemaSha256": source_manifest.files.iter().find(|file| file.path == schema_check::CONTRACT).map(|file| &file.sha256),
"checks": ["manager-transaction", "recovery-backed-database-update", "database-schema", "private-auth-world-startup", "existing-identities", "user-file-preservation"], "checks": ["legacy-race-start-data", "migration-ledger", "manager-transaction", "recovery-backed-database-update", "database-schema", "private-auth-world-startup", "existing-identities", "user-file-preservation"],
})) }))
} }
@@ -238,6 +241,15 @@ pub fn qualify_install(
package: &Path, package: &Path,
fixture: &Path, fixture: &Path,
trusted_key: &str, trusted_key: &str,
) -> Result<serde_json::Value> {
qualify_install_against(package, None, fixture, trusted_key)
}
pub fn qualify_install_against(
package: &Path,
update: Option<&Path>,
fixture: &Path,
trusted_key: &str,
) -> Result<serde_json::Value> { ) -> Result<serde_json::Value> {
use crate::update::Env; use crate::update::Env;
if !cfg!(windows) if !cfg!(windows)
@@ -254,6 +266,21 @@ pub fn qualify_install(
let package = fsx::canonicalize_lenient(package)?; let package = fsx::canonicalize_lenient(package)?;
let (manifest, bytes) = let (manifest, bytes) =
pkgsource::fetch_manifest(&pkgsource::Source::Dir(package.clone()), trusted_key)?; pkgsource::fetch_manifest(&pkgsource::Source::Dir(package.clone()), trusted_key)?;
let expected_update = update
.map(|path| pkgsource::fetch_manifest(&pkgsource::Source::Dir(path.into()), trusted_key))
.transpose()?;
if let Some((expected, _)) = &expected_update {
if expected.kind != Kind::Update
|| expected.version != manifest.version
|| expected.core.commit != manifest.core.commit
|| expected.bots.as_ref().and_then(|b| b.commit.as_ref())
!= manifest.bots.as_ref().and_then(|b| b.commit.as_ref())
{
return Err(Error::Invalid(
"Clean installation image does not match the selected release.".into(),
));
}
}
let registry_dir = tempfile::tempdir()?; let registry_dir = tempfile::tempdir()?;
let registry = crate::registry::Registry::at(registry_dir.path().join("registry.json")); let registry = crate::registry::Registry::at(registry_dir.path().join("registry.json"));
let installed = install::install_base( let installed = install::install_base(
@@ -280,13 +307,84 @@ pub fn qualify_install(
"Clean installation did not finish at the packaged release.".into(), "Clean installation did not finish at the packaged release.".into(),
)); ));
} }
let migration_audit = expected_update
.as_ref()
.map(|(expected, _)| audit_migrations(&fixture, &expected.migrations))
.transpose()?;
env.ensure_stopped()?;
crate::mysql_snapshot::stop(&fixture)?;
let inventory = expected_update
.as_ref()
.map(|(expected, _)| migrations::inventory_sha256(&expected.migrations))
.transpose()?;
let mut checks = vec![
"clean-install",
"signed-full-package",
"credential-rotation",
"schema-contract",
"private-auth-world-startup",
];
if expected_update.is_some() {
checks.push("migration-ledger");
checks.push("legacy-race-start-data");
}
Ok( Ok(
serde_json::json!({ "schema": 1, "result": "passed", "version": installed.version, serde_json::json!({ "schema": 1, "result": "passed", "version": installed.version,
"manifestSha256": fsx::sha256_bytes(&bytes), "manifestSha256": fsx::sha256_bytes(&bytes),
"checks": ["clean-install", "signed-full-package", "credential-rotation", "schema-contract", "private-auth-world-startup"] }), "checks": checks, "migrationInventorySha256": inventory, "migrations": migration_audit }),
) )
} }
fn audit_migrations(
root: &Path,
list: &[Migration],
) -> Result<std::collections::BTreeMap<String, migrations::Audit>> {
install::with_scratch_ports(root, || {
backup::with_database(root, |db| {
crate::realms::state(root)?
.modes()
.into_iter()
.map(|mode| {
if mode == crate::realms::Mode::Coa {
let rows = db
.clone()
.for_realm(mode)
.query("SELECT race,class FROM acore_world.playercreateinfo;")?;
let missing = missing_legacy_starts(&rows);
if !missing.is_empty() {
return Err(Error::Invalid(format!(
"Release is missing legacy race starting data: {}",
missing.join(", ")
)));
}
}
Ok((
mode.name().to_string(),
migrations::audit_applied(&db.clone().for_realm(mode), list)?,
))
})
.collect()
})
})
}
fn missing_legacy_starts(rows: &str) -> Vec<String> {
let pairs: std::collections::BTreeSet<(u32, u32)> = rows
.lines()
.filter_map(|line| line.split_once('\t'))
.filter_map(|(race, class)| Some((race.parse().ok()?, class.parse().ok()?)))
.collect();
let mut missing = Vec::new();
for (race, parent) in [(33, 1), (45, 8)] {
for &(source, class) in &pairs {
if source == parent && !pairs.contains(&(race, class)) {
missing.push(format!("race {race} / class {class}"));
}
}
}
missing
}
pub fn collect(core: &Path, bots: Option<&Path>, repairs: Option<&Path>) -> Result<Vec<SqlFile>> { pub fn collect(core: &Path, bots: Option<&Path>, repairs: Option<&Path>) -> Result<Vec<SqlFile>> {
let mut files = release::collect_core_sql(core)?; let mut files = release::collect_core_sql(core)?;
if let Some(bots) = bots { if let Some(bots) = bots {
@@ -617,6 +715,56 @@ mod tests {
use base64::{engine::general_purpose::STANDARD, Engine}; use base64::{engine::general_purpose::STANDARD, Engine};
use ed25519_dalek::{Signer, SigningKey}; use ed25519_dalek::{Signer, SigningKey};
#[test]
#[ignore = "Requires the disposable current-release installation audit fixture"]
fn real_current_image_is_blocked_until_legacy_start_data_is_restored() {
let root = std::path::PathBuf::from(std::env::var_os("COA_RELEASE_AUDIT_FIXTURE").unwrap());
assert_eq!(
root.file_name().unwrap(),
"coa-schema-fixture-latest-install-audit-20261030"
);
assert!(root.join(".release-schema-fixture").is_file());
assert!(!root.join("legacy-release-gate-probe-started").exists());
fsx::atomic_write(
&root.join("legacy-release-gate-probe-started"),
b"disposable regression test",
)
.unwrap();
let candidate =
std::path::PathBuf::from(std::env::var_os("COA_RELEASE_AUDIT_PACKAGE").unwrap());
let (manifest, _) = pkgsource::fetch_manifest(
&pkgsource::Source::Dir(candidate),
crate::signing::EMBEDDED_PUBLIC_KEY,
)
.unwrap();
let failure = audit_migrations(&root, &manifest.migrations).unwrap_err();
assert!(failure.to_string().contains("race 33 / class 12"));
assert!(failure.to_string().contains("race 45 / class 30"));
println!("PASS: signed current image is blocked for missing legacy starts despite a complete migration ledger");
let sql =
fs::read_to_string(std::env::var_os("COA_RELEASE_AUDIT_CORRECTION").unwrap()).unwrap();
install::with_scratch_ports(&root, || backup::with_database(&root, |db| {
let before = db.query("SELECT * FROM acore_characters.characters ORDER BY guid;")?;
db.query(&format!("USE acore_world;\n{sql}"))?;
let once = db.query("SELECT * FROM acore_world.playercreateinfo WHERE race IN (33,45) ORDER BY race,class;")?;
db.query(&format!("USE acore_world;\n{sql}"))?;
assert_eq!(once, db.query("SELECT * FROM acore_world.playercreateinfo WHERE race IN (33,45) ORDER BY race,class;")?);
assert_eq!(before, db.query("SELECT * FROM acore_characters.characters ORDER BY guid;")?);
Ok(())
})).unwrap();
let audits = audit_migrations(&root, &manifest.migrations).unwrap();
println!("PASS: corrected data passes the release gate; characters unchanged; correction idempotent; audit={}", serde_json::to_string(&audits).unwrap());
}
#[test]
fn release_rejects_missing_legacy_starts_even_without_existing_characters() {
assert_eq!(
missing_legacy_starts("1\t12\n8\t30\n"),
["race 33 / class 12", "race 45 / class 30"]
);
assert!(missing_legacy_starts("1\t12\n8\t30\n33\t12\n45\t30\n").is_empty());
}
#[test] #[test]
#[ignore = "Requires a composed disposable installation image"] #[ignore = "Requires a composed disposable installation image"]
fn real_full_package_installs_the_current_version_without_an_update_transaction() { fn real_full_package_installs_the_current_version_without_an_update_transaction() {
+2 -1
View File
@@ -94,8 +94,9 @@ fn run() -> Result<(), String> {
.map_err(e)?; .map_err(e)?;
} }
"qualify-install" => { "qualify-install" => {
let report = coa_core::release_schema::qualify_install( let report = coa_core::release_schema::qualify_install_against(
&PathBuf::from(need(&a, "package")?), &PathBuf::from(need(&a, "package")?),
Some(&PathBuf::from(need(&a, "update")?)),
&PathBuf::from(need(&a, "fixture")?), &PathBuf::from(need(&a, "fixture")?),
coa_core::signing::EMBEDDED_PUBLIC_KEY, coa_core::signing::EMBEDDED_PUBLIC_KEY,
) )
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "coa-server-manager", "name": "coa-server-manager",
"version": "0.9.2", "version": "0.9.5",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "coa-server-manager", "name": "coa-server-manager",
"version": "0.9.2", "version": "0.9.5",
"dependencies": { "dependencies": {
"@tauri-apps/api": "^2.12.0", "@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-dialog": "^2.8.0", "@tauri-apps/plugin-dialog": "^2.8.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "coa-server-manager", "name": "coa-server-manager",
"private": true, "private": true,
"version": "0.9.2", "version": "0.9.5",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"type": "module", "type": "module",
"scripts": { "scripts": {
+1
View File
@@ -16,6 +16,7 @@ tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-dialog = "2" tauri-plugin-dialog = "2"
tauri-plugin-updater = "2" tauri-plugin-updater = "2"
tauri-plugin-process = "2" tauri-plugin-process = "2"
tauri-plugin-single-instance = "2"
tauri-plugin-opener = "2" tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
+52
View File
@@ -0,0 +1,52 @@
use std::path::Path;
pub fn enabled(dir: &Path) -> coa_core::Result<bool> {
match std::fs::read(dir.join("public-server-browsing.json")) {
Ok(bytes) => Ok(serde_json::from_slice(&bytes)?),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
Err(e) => Err(e.into()),
}
}
pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> {
coa_core::fsx::atomic_write_json(&dir.join("public-server-browsing.json"), &enabled)
}
pub fn require_enabled(dir: &Path) -> coa_core::Result<()> {
if enabled(dir)? {
Ok(())
} else {
Err(coa_core::Error::Invalid(
"Public server browsing is disabled in Settings.".into(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn disabled_and_corrupt_preferences_block_browsing() {
let dir = std::env::temp_dir().join(format!(
"coa-browse-prefs-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
assert!(enabled(&dir).unwrap());
save(&dir, false).unwrap();
assert!(!enabled(&dir).unwrap());
assert!(require_enabled(&dir).is_err());
save(&dir, true).unwrap();
assert!(require_enabled(&dir).is_ok());
let file = dir.join("public-server-browsing.json");
std::fs::write(&file, b"broken").unwrap();
assert!(require_enabled(&dir).is_err());
std::fs::remove_file(file).unwrap();
std::fs::remove_dir(dir).unwrap();
}
}
+190 -37
View File
@@ -5,7 +5,9 @@ use std::collections::HashSet;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
mod browse_preferences;
mod docker_install; mod docker_install;
mod window_preferences;
use coa_core::backup::{self, Kind, RecoveryPoint, Trigger, VerifyReport}; use coa_core::backup::{self, Kind, RecoveryPoint, Trigger, VerifyReport};
use coa_core::config::{self, Scope, SettingsView}; use coa_core::config::{self, Scope, SettingsView};
@@ -28,6 +30,16 @@ use tauri::{AppHandle, Emitter, Manager, State};
mod control_cmds; mod control_cmds;
/// Informational release notes only; never used to select or authorize an update.
#[tauri::command]
async fn release_history(component: String) -> std::result::Result<Value, String> {
tauri::async_runtime::spawn_blocking(move || {
coa_core::release_history::load(&component, &data_dir().join("release-history"))
})
.await
.map_err(|e| e.to_string())?
}
struct AppState { struct AppState {
registry: Registry, registry: Registry,
/// Installation ids with a start/stop currently running (one action at a time per server). /// Installation ids with a start/stop currently running (one action at a time per server).
@@ -291,10 +303,39 @@ fn installation_source(custom: Option<String>) -> Result<Source> {
.ok() .ok()
.filter(|value| !value.trim().is_empty()) .filter(|value| !value.trim().is_empty())
}); });
select_installation_source(custom, || update_source(None))
}
fn select_installation_source(
custom: Option<String>,
latest: impl FnOnce() -> Result<Source>,
) -> Result<Source> {
if custom.is_some() { if custom.is_some() {
return Ok(package_source(custom)); return Ok(package_source(custom));
} }
Ok(Source::Installation(Box::new(update_source(None)?))) Ok(Source::Installation(Box::new(latest()?)))
}
#[cfg(test)]
mod installation_source_tests {
use super::*;
#[test]
fn fresh_install_uses_the_selected_current_release_full_image() {
let source = select_installation_source(None, || {
Ok(Source::Url("https://example.test/releases/current".into()))
}).unwrap();
assert!(matches!(source, Source::Installation(inner)
if matches!(*inner, Source::Url(ref url) if url.ends_with("/current"))));
}
#[test]
fn unavailable_current_release_does_not_fall_back_to_an_old_base() {
let result = select_installation_source(None, || {
Err(Error::PackageNotPublished("current unavailable".into()))
});
assert!(matches!(result, Err(Error::PackageNotPublished(_))));
}
} }
#[derive(Serialize)] #[derive(Serialize)]
@@ -612,7 +653,10 @@ async fn start_server(
&& coa_core::friends::load(&meta).mode != coa_core::friends::Mode::Local && coa_core::friends::load(&meta).mode != coa_core::friends::Mode::Local
{ {
let extra = coa_core::realms::state(&root)?.extra_world_ports(); let extra = coa_core::realms::state(&root)?.extra_world_ports();
if let Err(e) = coa_core::firewall::ensure_rules_with_extra(&layout::read_ports(&root), &extra) { if let Err(e) = coa_core::firewall::ensure_rules_with_extra(
&layout::read_ports(&root),
&extra,
) {
tracing::warn!("firewall rules for the running worlds were not added: {e}"); tracing::warn!("firewall rules for the running worlds were not added: {e}");
} }
} }
@@ -624,6 +668,16 @@ async fn start_server(
Ok(out) Ok(out)
} }
#[tauri::command]
async fn force_stop_server(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<DriverOutcome, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || driver::force_stop(&root)).await
}
#[tauri::command] #[tauri::command]
async fn stop_server( async fn stop_server(
state: State<'_, AppState>, state: State<'_, AppState>,
@@ -1030,14 +1084,10 @@ async fn create_account(
password: String, password: String,
administrator: bool, administrator: bool,
) -> std::result::Result<(), UiError> { ) -> std::result::Result<(), UiError> {
let _guard = BusyGuard::acquire(&state, &id)?;
let root = path_of(&state, &id)?; let root = path_of(&state, &id)?;
blocking(move || { blocking(move || {
coa_core::ra::validate_account(&username, &password)?; coa_core::accounts::create(&root, &username, &password, administrator)?;
let mut ra = Ra::connect(&root)?;
ra.create_account(&username, &password)?;
if administrator {
ra.make_administrator(&username)?;
}
tracing::info!(%username, administrator, "account created"); tracing::info!(%username, administrator, "account created");
Ok(()) Ok(())
}) })
@@ -1987,6 +2037,34 @@ fn client_of(root: &std::path::Path) -> Result<(PathBuf, InstallMeta, Option<Pat
Ok((dir, meta, Some(client))) Ok((dir, meta, Some(client)))
} }
#[tauri::command]
fn client_graphics(
state: State<'_, AppState>,
id: String,
) -> std::result::Result<coa_core::client_graphics::Graphics, UiError> {
Ok(coa_core::client_graphics::status(
&client_context(&state, &id)?.require()?,
)?)
}
#[tauri::command]
fn client_set_graphics(
state: State<'_, AppState>,
id: String,
name: String,
disabled: bool,
) -> std::result::Result<coa_core::client_graphics::Graphics, UiError> {
let job = state.client_cancel.lock().unwrap();
if job.is_some() {
return Err(Error::Invalid("Wait for the client operation to finish.".into()).into());
}
Ok(coa_core::client_graphics::set(
&client_context(&state, &id)?.require()?,
&name,
disabled,
)?)
}
#[tauri::command] #[tauri::command]
fn client_info( fn client_info(
state: State<'_, AppState>, state: State<'_, AppState>,
@@ -2482,7 +2560,7 @@ async fn report_context(
.into_iter() .into_iter()
.flatten() .flatten()
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(" · "); .join(" В· ");
Ok(ReportContext { Ok(ReportContext {
manager_version: coa_core::MANAGER_VERSION.to_string(), manager_version: coa_core::MANAGER_VERSION.to_string(),
windows: windows_version(), windows: windows_version(),
@@ -2782,30 +2860,68 @@ async fn console_command(
.await .await
} }
#[tauri::command]
fn manager_installing(enabled: bool) {
QUIT_REQUESTED.store(enabled, std::sync::atomic::Ordering::SeqCst);
}
#[tauri::command]
fn close_manager(app: AppHandle) -> std::result::Result<(), UiError> {
if window_preferences::close_to_tray(&data_dir()).unwrap_or(false) {
QUIT_REQUESTED.store(false, std::sync::atomic::Ordering::SeqCst);
if let Some(window) = app.get_webview_window("main") {
window.hide().map_err(|e| Error::Invalid(e.to_string()))?;
}
} else {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
app.exit(0);
}
Ok(())
}
#[tauri::command]
fn close_to_tray() -> std::result::Result<bool, UiError> {
Ok(window_preferences::close_to_tray(&data_dir())?)
}
#[tauri::command]
fn set_close_to_tray(enabled: bool) -> std::result::Result<(), UiError> {
Ok(window_preferences::save(&data_dir(), enabled)?)
}
fn show_main_window(app: &AppHandle) {
let handle = app.clone();
if let Err(error) = app.run_on_main_thread(move || {
if let Some(window) = handle.get_webview_window("main") {
let result = window
.unminimize()
.and_then(|_| window.show())
.and_then(|_| window.set_focus());
if let Err(error) = result {
tracing::error!(%error, "Could not restore the Manager window");
}
} else {
tracing::error!("The Manager main window is missing");
}
}) {
tracing::error!(%error, "Could not schedule Manager window restoration");
}
}
static QUIT_REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); static QUIT_REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn run() { pub fn run() {
let dir = data_dir(); let dir = data_dir();
let _ = coa_core::logging::init(&dir.join("logs").join("manager.log")); let _ = coa_core::logging::init(&dir.join("logs").join("manager.log"));
// Crash safety: recover any unfinished client realmlist overrides from previous abnormal termination
let _ = coa_core::client::revert_realmlist_override(&dir);
let portable = start_portable(&dir);
let (control, host_control) = control_cmds::start(&dir, portable.clone());
tauri::Builder::default() tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, _, _| {
show_main_window(app)
}))
.plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_process::init()) .plugin(tauri_plugin_process::init())
.manage(AppState {
registry: Registry::at(dir.join("installs.json")),
busy: Mutex::new(HashSet::new()),
install_cancel: Mutex::new(None),
client_cancel: Mutex::new(None),
portable,
realm_registry: start_realm_registry(&dir),
control,
host_control,
})
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
release_history,
default_install_dir, default_install_dir,
game_data_folder, game_data_folder,
set_game_data_folder, set_game_data_folder,
@@ -2817,6 +2933,7 @@ pub fn run() {
server_status, server_status,
start_server, start_server,
stop_server, stop_server,
force_stop_server,
get_settings, get_settings,
save_settings, save_settings,
list_presets, list_presets,
@@ -2881,6 +2998,8 @@ pub fn run() {
remote_connection, remote_connection,
remote_connect, remote_connect,
client_info, client_info,
client_graphics,
client_set_graphics,
set_client, set_client,
client_realmlist, client_realmlist,
client_install_addon, client_install_addon,
@@ -2921,6 +3040,12 @@ pub fn run() {
portable_launch, portable_launch,
registry_status, registry_status,
portable_preflight_remote, portable_preflight_remote,
manager_installing,
close_manager,
close_to_tray,
set_close_to_tray,
browse_enabled,
browse_set_enabled,
browse_list, browse_list,
browse_detail, browse_detail,
module_catalog, module_catalog,
@@ -2941,18 +3066,43 @@ pub fn run() {
]) ])
.on_window_event(|window, event| { .on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event { if let tauri::WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close(); if window.label() != "main" {
let _ = window.hide(); return;
}
if window_preferences::close_to_tray(&data_dir()).unwrap_or(false) {
api.prevent_close();
if let Err(error) = window.hide() {
tracing::warn!(%error, "Could not hide the Manager window");
}
} else {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
}
} }
}) })
.setup(|app| { .setup(|app| {
let dir = data_dir();
// Crash safety: recover any unfinished client realmlist overrides from previous abnormal termination
let _ = coa_core::client::revert_realmlist_override(&dir);
let portable = start_portable(&dir);
let (control, host_control) = control_cmds::start(&dir, portable.clone());
app.manage(AppState {
registry: Registry::at(dir.join("installs.json")),
busy: Mutex::new(HashSet::new()),
install_cancel: Mutex::new(None),
client_cancel: Mutex::new(None),
portable,
realm_registry: start_realm_registry(&dir),
control,
host_control,
});
#[cfg(desktop)] #[cfg(desktop)]
{ {
use tauri::menu::{Menu, MenuItem}; use tauri::menu::{Menu, MenuItem};
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}; use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
use tauri::Manager;
let show = MenuItem::with_id(app, "show", "Open CoA Server Manager", true, None::<&str>)?; let show =
MenuItem::with_id(app, "show", "Open CoA Server Manager", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Exit", true, None::<&str>)?; let quit = MenuItem::with_id(app, "quit", "Exit", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&show, &quit])?; let menu = Menu::with_items(app, &[&show, &quit])?;
@@ -2962,11 +3112,7 @@ pub fn run() {
.show_menu_on_left_click(false) .show_menu_on_left_click(false)
.on_menu_event(|app, event| match event.id.as_ref() { .on_menu_event(|app, event| match event.id.as_ref() {
"show" => { "show" => {
if let Some(window) = app.get_webview_window("main") { show_main_window(app);
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
} }
"quit" => { "quit" => {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst); QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
@@ -2982,11 +3128,7 @@ pub fn run() {
} = event } = event
{ {
let app = tray.app_handle(); let app = tray.app_handle();
if let Some(window) = app.get_webview_window("main") { show_main_window(app);
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
} }
}); });
@@ -3046,6 +3188,7 @@ async fn portable_preflight_remote(
} }
fn browse_client() -> std::result::Result<coa_core::realm_registry::BrowseClient, UiError> { fn browse_client() -> std::result::Result<coa_core::realm_registry::BrowseClient, UiError> {
browse_preferences::require_enabled(&data_dir())?;
let settings = coa_core::realm_registry::settings::load(&data_dir().join("registry"))?; let settings = coa_core::realm_registry::settings::load(&data_dir().join("registry"))?;
let url = std::env::var("COA_REGISTRY_URL") let url = std::env::var("COA_REGISTRY_URL")
.ok() .ok()
@@ -3054,6 +3197,16 @@ fn browse_client() -> std::result::Result<coa_core::realm_registry::BrowseClient
Ok(coa_core::realm_registry::BrowseClient::new(&url)?) Ok(coa_core::realm_registry::BrowseClient::new(&url)?)
} }
#[tauri::command]
fn browse_enabled() -> std::result::Result<bool, UiError> {
Ok(browse_preferences::enabled(&data_dir())?)
}
#[tauri::command]
fn browse_set_enabled(enabled: bool) -> std::result::Result<(), UiError> {
Ok(browse_preferences::save(&data_dir(), enabled)?)
}
fn browse_error(e: coa_core::realm_registry::ClientError) -> UiError { fn browse_error(e: coa_core::realm_registry::ClientError) -> UiError {
Error::Invalid(e.to_string()).into() Error::Invalid(e.to_string()).into()
} }
+13
View File
@@ -0,0 +1,13 @@
use std::path::Path;
pub fn close_to_tray(dir: &Path) -> coa_core::Result<bool> {
match std::fs::read(dir.join("close-to-tray.json")) {
Ok(bytes) => Ok(serde_json::from_slice(&bytes)?),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e.into()),
}
}
pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> {
coa_core::fsx::atomic_write_json(&dir.join("close-to-tray.json"), &enabled)
}
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "CoA Server Manager", "productName": "CoA Server Manager",
"version": "0.9.2", "version": "0.9.5",
"identifier": "com.coa.servermanager", "identifier": "com.coa.servermanager",
"build": { "build": {
"beforeDevCommand": "npm run dev", "beforeDevCommand": "npm run dev",
+1 -1
View File
@@ -15,7 +15,7 @@ const buttonVariants = cva(
size: { size: {
sm: "h-9 px-3 text-sm", sm: "h-9 px-3 text-sm",
md: "h-11 px-5 text-[15px]", md: "h-11 px-5 text-[15px]",
xl: "h-16 px-10 text-lg tracking-wide", xl: "h-12 px-6 text-base",
}, },
}, },
defaultVariants: { variant: "secondary", size: "md" }, defaultVariants: { variant: "secondary", size: "md" },
+15
View File
@@ -0,0 +1,15 @@
import { Button, type ButtonProps } from "./button";
/** Two explicit actions, each with its own enabled state and keyboard focus. */
export function SplitButton({ label, primary, secondary }: {
label: string;
primary: ButtonProps;
secondary: ButtonProps;
}) {
return <div role="group" aria-label={label} className="inline-flex max-w-full items-stretch rounded-md">
<Button type="button" variant="primary" {...primary}
className="h-auto min-h-12 min-w-0 rounded-r-none px-5 py-2 text-sm whitespace-normal" />
<Button type="button" variant="secondary" {...secondary}
className="h-auto min-h-12 min-w-0 rounded-l-none border-l border-l-gold/30 px-4 py-2 text-sm whitespace-normal" />
</div>;
}
+28
View File
@@ -0,0 +1,28 @@
# Release history data (internal)
The Manager feed is imported from the canonical `changelog/history.json`. The
server snapshot in this directory is copied from `Corfirean/coa-server-build`
commit `15687243bd3f4d60dfedf70b938b6076c1bd6393`, path
`changelog/history.json`, on 2026-10-30. Only schema, component, repository and
releases are retained. Do not independently edit historical records here.
At runtime the native read-only command fetches the fixed canonical URL, bounds
and validates the feed, and caches it for offline use. The bundled records appear
immediately and remain available if neither network nor cache is usable. These
records cannot select a package or authorize an update.
`latest-note-translations.json` contains the reviewed Manager notes through 0.9.3, the new
0.9.4 Manager entries, and the 0.261028.83 server notes in Russian, German, French, Spanish and Simplified
Chinese. English remains canonical. Translations are keyed by exact original
text: changing an original invalidates its translation. A partly translated
release falls back entirely to English and displays an explicit notice.
When preparing future release notes, refresh the server snapshot from a pinned
canonical commit and add all five translations for each new original note.
Never rewrite released fragments to add translations. Run
`node --test tools/release-history.test.mjs`; its completeness check expects the
latest bundled record of each component to have every translation.
Manager 0.9.5 prepares all five translations of the ten reviewed stabilization notes and
three server stabilization notes before their release. The bundled snapshot includes server
0.261029.85 from the pinned commit above. Pending notes do not fabricate published records.
+327 -6
View File
@@ -1,40 +1,361 @@
{ {
"manager": { "manager": {
"ru": { "ru": {
"Choose Parallel or Global level scaling in module settings": "Выбирайте параллельное или глобальное масштабирование уровней в настройках модуля",
"Report Content Scaling problems directly to its repository": "Отправляйте отчёты о проблемах Content Scaling прямо в его репозиторий",
"Send custom race problem reports directly to their maintainer": "Отправляйте отчёты о проблемах дополнительных рас напрямую их разработчику",
"Internet sharing restores the LAN address after server restarts": "Общий доступ через интернет восстанавливает адрес локальной сети после перезапуска сервера",
"Configure custom race availability for new characters": "Настраивайте доступность дополнительных рас для новых персонажей",
"Public listing offers every realm that starts together, not just the main one": "Публиковать можно каждый реалм, запускаемый вместе с основным",
"Public listing is a short list of realms with a window for the details": "Публичные реалмы представлены компактным списком с отдельным окном подробностей",
"Configure profession and defense skill gains in server settings": "Настраивайте рост навыков профессий и защиты в настройках сервера",
"Starting a server sets the character classes of the realm chosen on Overview": "При запуске применяются классы персонажей реалма, выбранного на экране «Обзор»",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth": "Запускайте Wildcard и Warcraft Reborn вместе с Conquest of Azeroth",
"Control portable characters and keep Manager running in the system tray": "Управляйте переносимыми персонажами и оставляйте Manager работать в системном трее",
"Existing unsupported character records no longer block unrelated server updates": "Старые неподдерживаемые записи персонажей больше не блокируют несвязанные обновления сервера", "Existing unsupported character records no longer block unrelated server updates": "Старые неподдерживаемые записи персонажей больше не блокируют несвязанные обновления сервера",
"New server installation waits for slower database startup": "Установка нового сервера дольше ожидает запуска базы на медленных дисках", "New server installation waits for slower database startup": "Установка нового сервера дольше ожидает запуска базы на медленных дисках",
"Find and edit CoA options in the existing server settings": "Параметры CoA доступны для поиска и редактирования в настройках сервера", "Find and edit CoA options in the existing server settings": "Параметры CoA доступны для поиска и редактирования в настройках сервера",
"Simultaneous update checks share results or wait their turn": "Одновременные проверки обновлений используют общий результат или ожидают своей очереди", "Simultaneous update checks share results or wait their turn": "Одновременные проверки обновлений используют общий результат или ожидают своей очереди",
"Recovery can stop an unfinished world startup after restoring an older launcher": "Восстановление может остановить зависший запуск мира после возврата старого launcher" "Recovery can stop an unfinished world startup after restoring an older launcher": "Восстановление может остановить зависший запуск мира после возврата старого launcher",
"Slow server startup no longer triggers an early update rollback": "Медленный запуск сервера больше не вызывает преждевременный откат обновления",
"Settings group updates, startup and maintenance with translated release history": "Настройки сгруппированы по обновлениям, запуску и обслуживанию с переведённой историей выпусков",
"Update and launch without updating share a divided button": "Обновление и запуск без обновления объединены в разделённую кнопку",
"Maximizing the window keeps text and controls at a comfortable size": "При разворачивании окна текст и элементы управления сохраняют удобный размер",
"Account creation verifies a lost console reply against the requested login": "Создание аккаунта проверяет запрошенные данные входа при потере ответа консоли",
"Abandoned game relay tunnels close their local connection immediately": "Закрытые игровые туннели немедленно освобождают локальное соединение",
"Keep disabled graphics components disabled during client updates": "Обновление клиента сохраняет отключённые графические компоненты",
"Force-stop an unresponsive world after a failed normal shutdown": "Принудительно останавливайте зависший мир после неудачной обычной остановки",
"Crash history includes reports from every world and Windows text files": "История сбоев включает отчёты всех миров и текстовые файлы Windows",
"Show the online bot count for Playerbots on the overview": "Обзор показывает количество ботов Playerbots в игре",
"Disable public server browsing in Settings": "Отключайте просмотр публичных серверов в настройках",
"Keep deliberate stops and update shutdowns from triggering crash restart": "Ручная остановка и остановка для обновления не вызывают перезапуск после сбоя",
"Server startup waits for a responsive console before reporting success": "Запуск сервера ожидает ответа консоли перед сообщением об успехе",
"Restore the existing Manager window when launching it again": "Повторный запуск открывает уже существующее окно менеджера"
}, },
"de": { "de": {
"Choose Parallel or Global level scaling in module settings": "Parallele oder globale Levelskalierung in den Moduleinstellungen wählen",
"Report Content Scaling problems directly to its repository": "Probleme mit Content Scaling direkt in dessen Repository melden",
"Send custom race problem reports directly to their maintainer": "Probleme mit zusätzlichen Völkern direkt an deren Entwickler melden",
"Internet sharing restores the LAN address after server restarts": "Internetfreigabe stellt nach Serverneustarts die LAN-Adresse wieder her",
"Configure custom race availability for new characters": "Verfügbarkeit zusätzlicher Völker für neue Charaktere festlegen",
"Public listing offers every realm that starts together, not just the main one": "Alle gemeinsam gestarteten Realms können veröffentlicht werden, nicht nur der Hauptrealm",
"Public listing is a short list of realms with a window for the details": "Öffentliche Realms erscheinen als kurze Liste mit einem Detailfenster",
"Configure profession and defense skill gains in server settings": "Zuwachs von Berufs- und Verteidigungsfertigkeiten in den Servereinstellungen festlegen",
"Starting a server sets the character classes of the realm chosen on Overview": "Beim Serverstart werden die Charakterklassen des in der Übersicht gewählten Realms angewendet",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth": "Wildcard und Warcraft Reborn gemeinsam mit Conquest of Azeroth starten",
"Control portable characters and keep Manager running in the system tray": "Portable Charaktere verwalten und Manager im Infobereich weiterlaufen lassen",
"Existing unsupported character records no longer block unrelated server updates": "Bestehende nicht unterstützte Charakterdatensätze blockieren keine unabhängigen Serverupdates mehr", "Existing unsupported character records no longer block unrelated server updates": "Bestehende nicht unterstützte Charakterdatensätze blockieren keine unabhängigen Serverupdates mehr",
"New server installation waits for slower database startup": "Die Neuinstallation wartet länger auf einen langsamen Datenbankstart", "New server installation waits for slower database startup": "Die Neuinstallation wartet länger auf einen langsamen Datenbankstart",
"Find and edit CoA options in the existing server settings": "CoA-Optionen in den bestehenden Servereinstellungen suchen und bearbeiten", "Find and edit CoA options in the existing server settings": "CoA-Optionen in den bestehenden Servereinstellungen suchen und bearbeiten",
"Simultaneous update checks share results or wait their turn": "Gleichzeitige Updateprüfungen teilen Ergebnisse oder warten aufeinander", "Simultaneous update checks share results or wait their turn": "Gleichzeitige Updateprüfungen teilen Ergebnisse oder warten aufeinander",
"Recovery can stop an unfinished world startup after restoring an older launcher": "Die Wiederherstellung stoppt einen unvollständigen Weltstart auch mit altem Launcher" "Recovery can stop an unfinished world startup after restoring an older launcher": "Die Wiederherstellung stoppt einen unvollständigen Weltstart auch mit altem Launcher",
"Slow server startup no longer triggers an early update rollback": "Ein langsamer Serverstart löst keinen vorzeitigen Update-Rollback mehr aus",
"Settings group updates, startup and maintenance with translated release history": "Einstellungen bündeln Updates, Start und Wartung mit übersetztem Versionsverlauf",
"Update and launch without updating share a divided button": "Aktualisieren und ohne Update starten teilen sich eine geteilte Schaltfläche",
"Maximizing the window keeps text and controls at a comfortable size": "Beim Maximieren bleiben Text und Bedienelemente angenehm groß",
"Account creation verifies a lost console reply against the requested login": "Bei verlorener Konsolenantwort werden die angeforderten Kontodaten geprüft",
"Abandoned game relay tunnels close their local connection immediately": "Verlassene Spieltunnel schließen ihre lokale Verbindung sofort",
"Keep disabled graphics components disabled during client updates": "Deaktivierte Grafikkomponenten bleiben bei Client-Updates deaktiviert",
"Force-stop an unresponsive world after a failed normal shutdown": "Eine nicht reagierende Welt nach fehlgeschlagenem normalem Herunterfahren zwangsweise stoppen",
"Crash history includes reports from every world and Windows text files": "Der Absturzverlauf enthält Berichte aller Welten und Windows-Textdateien",
"Show the online bot count for Playerbots on the overview": "Die Übersicht zeigt die Anzahl angemeldeter Playerbots",
"Disable public server browsing in Settings": "Öffentliche Serversuche in den Einstellungen deaktivieren",
"Keep deliberate stops and update shutdowns from triggering crash restart": "Bewusstes Stoppen und Herunterfahren für Updates lösen keinen Absturzneustart aus",
"Server startup waits for a responsive console before reporting success": "Der Serverstart wartet vor der Erfolgsmeldung auf eine reagierende Konsole",
"Restore the existing Manager window when launching it again": "Erneutes Starten stellt das vorhandene Manager-Fenster wieder her"
}, },
"fr": { "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",
"Report Content Scaling problems directly to its repository": "Signalez les problèmes de Content Scaling directement dans son dépôt",
"Send custom race problem reports directly to their maintainer": "Envoyez les signalements concernant les races supplémentaires directement à leur développeur",
"Internet sharing restores the LAN address after server restarts": "Le partage Internet rétablit l’adresse du réseau local après un redémarrage du serveur",
"Configure custom race availability for new characters": "Configurez les races supplémentaires disponibles pour les nouveaux personnages",
"Public listing offers every realm that starts together, not just the main one": "Tous les royaumes démarrant ensemble peuvent être publiés, pas seulement le principal",
"Public listing is a short list of realms with a window for the details": "Les royaumes publics apparaissent dans une liste compacte avec une fenêtre de détails",
"Configure profession and defense skill gains in server settings": "Configurez les gains de compétences de métier et de défense dans les paramètres du serveur",
"Starting a server sets the character classes of the realm chosen on Overview": "Le démarrage applique les classes du royaume choisi sur l’écran Aperçu",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth": "Démarrez Wildcard et Warcraft Reborn avec Conquest of Azeroth",
"Control portable characters and keep Manager running in the system tray": "Gérez les personnages portables et laissez Manager fonctionner dans la zone de notification",
"Existing unsupported character records no longer block unrelated server updates": "Les anciennes fiches de personnage non prises en charge ne bloquent plus les mises à jour sans rapport", "Existing unsupported character records no longer block unrelated server updates": "Les anciennes fiches de personnage non prises en charge ne bloquent plus les mises à jour sans rapport",
"New server installation waits for slower database startup": "L’installation attend le démarrage de la base sur les disques plus lents", "New server installation waits for slower database startup": "L’installation attend le démarrage de la base sur les disques plus lents",
"Find and edit CoA options in the existing server settings": "Recherchez et modifiez les options CoA dans les paramètres du serveur", "Find and edit CoA options in the existing server settings": "Recherchez et modifiez les options CoA dans les paramètres du serveur",
"Simultaneous update checks share results or wait their turn": "Les vérifications simultanées partagent leurs résultats ou attendent leur tour", "Simultaneous update checks share results or wait their turn": "Les vérifications simultanées partagent leurs résultats ou attendent leur tour",
"Recovery can stop an unfinished world startup after restoring an older launcher": "La restauration peut arrêter un démarrage du monde inachevé avec un ancien lanceur" "Recovery can stop an unfinished world startup after restoring an older launcher": "La restauration peut arrêter un démarrage du monde inachevé avec un ancien lanceur",
"Slow server startup no longer triggers an early update rollback": "Un démarrage lent du serveur ne déclenche plus un retour arrière prématuré",
"Settings group updates, startup and maintenance with translated release history": "Les paramètres regroupent les mises à jour, le démarrage et la maintenance avec un historique traduit",
"Update and launch without updating share a divided button": "La mise à jour et le lancement sans mise à jour partagent un bouton divisé",
"Maximizing the window keeps text and controls at a comfortable size": "Le texte et les commandes gardent une taille confortable lorsque la fenêtre est maximisée",
"Account creation verifies a lost console reply against the requested login": "La création de compte vérifie les identifiants demandés si la réponse de la console est perdue",
"Abandoned game relay tunnels close their local connection immediately": "Les tunnels de jeu abandonnés ferment immédiatement leur connexion locale",
"Keep disabled graphics components disabled during client updates": "Les composants graphiques désactivés le restent lors des mises à jour du client",
"Force-stop an unresponsive world after a failed normal shutdown": "Arrêtez de force un monde bloqué après un échec de l’arrêt normal",
"Crash history includes reports from every world and Windows text files": "L’historique des plantages inclut les rapports de tous les mondes et les fichiers texte Windows",
"Show the online bot count for Playerbots on the overview": "La vue d’ensemble affiche le nombre de Playerbots connectés",
"Disable public server browsing in Settings": "Désactivez la consultation des serveurs publics dans les paramètres",
"Keep deliberate stops and update shutdowns from triggering crash restart": "Les arrêts volontaires et ceux des mises à jour ne déclenchent plus de redémarrage après plantage",
"Server startup waits for a responsive console before reporting success": "Le démarrage du serveur attend une console réactive avant d’annoncer sa réussite",
"Restore the existing Manager window when launching it again": "Un nouveau lancement restaure la fenêtre existante du gestionnaire"
}, },
"es": { "es": {
"Choose Parallel or Global level scaling in module settings": "Elige escalado de nivel paralelo o global en los ajustes del módulo",
"Report Content Scaling problems directly to its repository": "Informa de problemas de Content Scaling directamente en su repositorio",
"Send custom race problem reports directly to their maintainer": "Envía los informes sobre razas adicionales directamente a su desarrollador",
"Internet sharing restores the LAN address after server restarts": "El acceso por Internet restaura la dirección de red local tras reiniciar el servidor",
"Configure custom race availability for new characters": "Configura las razas adicionales disponibles para personajes nuevos",
"Public listing offers every realm that starts together, not just the main one": "Puedes publicar todos los reinos que se inician juntos, no solo el principal",
"Public listing is a short list of realms with a window for the details": "Los reinos públicos se muestran en una lista breve con una ventana de detalles",
"Configure profession and defense skill gains in server settings": "Configura las mejoras de habilidades de profesión y defensa en los ajustes del servidor",
"Starting a server sets the character classes of the realm chosen on Overview": "Al iniciar el servidor se aplican las clases del reino elegido en Resumen",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth": "Inicia Wildcard y Warcraft Reborn junto con Conquest of Azeroth",
"Control portable characters and keep Manager running in the system tray": "Gestiona personajes portátiles y mantén Manager en la bandeja del sistema",
"Existing unsupported character records no longer block unrelated server updates": "Los registros antiguos de personajes no compatibles ya no bloquean actualizaciones del servidor no relacionadas", "Existing unsupported character records no longer block unrelated server updates": "Los registros antiguos de personajes no compatibles ya no bloquean actualizaciones del servidor no relacionadas",
"New server installation waits for slower database startup": "La instalación espera más tiempo al inicio de la base de datos en discos lentos", "New server installation waits for slower database startup": "La instalación espera más tiempo al inicio de la base de datos en discos lentos",
"Find and edit CoA options in the existing server settings": "Busca y edita opciones de CoA en la configuración actual del servidor", "Find and edit CoA options in the existing server settings": "Busca y edita opciones de CoA en la configuración actual del servidor",
"Simultaneous update checks share results or wait their turn": "Las comprobaciones simultáneas comparten resultados o esperan su turno", "Simultaneous update checks share results or wait their turn": "Las comprobaciones simultáneas comparten resultados o esperan su turno",
"Recovery can stop an unfinished world startup after restoring an older launcher": "La recuperación puede detener el inicio del mundo tras restaurar un lanzador antiguo" "Recovery can stop an unfinished world startup after restoring an older launcher": "La recuperación puede detener el inicio del mundo tras restaurar un lanzador antiguo",
"Slow server startup no longer triggers an early update rollback": "El inicio lento del servidor ya no provoca una reversión prematura de la actualización",
"Settings group updates, startup and maintenance with translated release history": "Los ajustes agrupan actualizaciones, inicio y mantenimiento con un historial de versiones traducido",
"Update and launch without updating share a divided button": "Actualizar e iniciar sin actualizar comparten un botón dividido",
"Maximizing the window keeps text and controls at a comfortable size": "Al maximizar la ventana, el texto y los controles mantienen un tamaño cómodo",
"Account creation verifies a lost console reply against the requested login": "La creación de cuentas verifica las credenciales solicitadas si se pierde la respuesta de la consola",
"Abandoned game relay tunnels close their local connection immediately": "Los túneles de juego abandonados cierran su conexión local de inmediato",
"Keep disabled graphics components disabled during client updates": "Los componentes gráficos desactivados permanecen así al actualizar el cliente",
"Force-stop an unresponsive world after a failed normal shutdown": "Detén por la fuerza un mundo bloqueado si falla el cierre normal",
"Crash history includes reports from every world and Windows text files": "El historial de fallos incluye informes de todos los mundos y archivos de texto de Windows",
"Show the online bot count for Playerbots on the overview": "El resumen muestra la cantidad de Playerbots conectados",
"Disable public server browsing in Settings": "Desactiva la consulta de servidores públicos en los ajustes",
"Keep deliberate stops and update shutdowns from triggering crash restart": "Las paradas voluntarias y las de actualización no activan el reinicio por fallo",
"Server startup waits for a responsive console before reporting success": "El arranque del servidor espera a que responda la consola antes de indicar que ha terminado",
"Restore the existing Manager window when launching it again": "Al volver a iniciar el gestor se restaura su ventana existente"
}, },
"zh": { "zh": {
"Choose Parallel or Global level scaling in module settings": "在模块设置中选择并行或全局等级缩放",
"Report Content Scaling problems directly to its repository": "直接向 Content Scaling 仓库报告问题",
"Send custom race problem reports directly to their maintainer": "将自定义种族问题直接报告给其维护者",
"Internet sharing restores the LAN address after server restarts": "服务器重启后,互联网共享会恢复局域网地址",
"Configure custom race availability for new characters": "设置新角色可选的自定义种族",
"Public listing offers every realm that starts together, not just the main one": "可以发布所有同时启动的服务器,而不仅是主服务器",
"Public listing is a short list of realms with a window for the details": "公开服务器使用简短列表展示,详情在单独窗口中查看",
"Configure profession and defense skill gains in server settings": "在服务器设置中调整专业和防御技能的提升",
"Starting a server sets the character classes of the realm chosen on Overview": "启动时会应用“概览”中所选服务器的角色职业",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth": "将 Wildcard 和 Warcraft Reborn 与 Conquest of Azeroth 一同启动",
"Control portable characters and keep Manager running in the system tray": "管理可携带角色,并让 Manager 继续在系统托盘中运行",
"Existing unsupported character records no longer block unrelated server updates": "已有的不受支持角色记录不再阻止无关的服务器更新", "Existing unsupported character records no longer block unrelated server updates": "已有的不受支持角色记录不再阻止无关的服务器更新",
"New server installation waits for slower database startup": "安装新服务器时会等待较慢的数据库启动", "New server installation waits for slower database startup": "安装新服务器时会等待较慢的数据库启动",
"Find and edit CoA options in the existing server settings": "在现有服务器设置中查找和编辑 CoA 选项", "Find and edit CoA options in the existing server settings": "在现有服务器设置中查找和编辑 CoA 选项",
"Simultaneous update checks share results or wait their turn": "同时进行的更新检查会共用结果或依次执行", "Simultaneous update checks share results or wait their turn": "同时进行的更新检查会共用结果或依次执行",
"Recovery can stop an unfinished world startup after restoring an older launcher": "恢复旧版启动器后,恢复流程也能停止未完成启动的世界服务器" "Recovery can stop an unfinished world startup after restoring an older launcher": "恢复旧版启动器后,恢复流程也能停止未完成启动的世界服务器",
"Slow server startup no longer triggers an early update rollback": "服务器启动缓慢不再导致更新过早回滚",
"Settings group updates, startup and maintenance with translated release history": "设置按更新、启动和维护分组,并提供已翻译的版本历史",
"Update and launch without updating share a divided button": "更新和不更新直接启动使用同一个分段按钮",
"Maximizing the window keeps text and controls at a comfortable size": "最大化窗口时,文字和控件仍保持舒适的大小",
"Account creation verifies a lost console reply against the requested login": "控制台响应丢失时,创建账号会核验所请求的登录凭据",
"Abandoned game relay tunnels close their local connection immediately": "废弃的游戏中继隧道会立即关闭本地连接",
"Keep disabled graphics components disabled during client updates": "客户端更新时保留已禁用的图形组件状态",
"Force-stop an unresponsive world after a failed normal shutdown": "正常关闭失败后可强制停止无响应的世界服务器",
"Crash history includes reports from every world and Windows text files": "崩溃历史包含所有世界的报告和 Windows 文本文件",
"Show the online bot count for Playerbots on the overview": "概览中显示在线 Playerbots 数量",
"Disable public server browsing in Settings": "可在设置中禁用公共服务器浏览",
"Keep deliberate stops and update shutdowns from triggering crash restart": "主动停止及更新时关闭不会触发崩溃自动重启",
"Server startup waits for a responsive console before reporting success": "服务器启动会等待控制台响应后再报告成功",
"Restore the existing Manager window when launching it again": "再次启动时恢复已有的管理器窗口"
} }
}, },
"server": {} "server": {
"ru": {
"Restrict new characters by custom race without changing existing characters": "Ограничивайте выбор дополнительных рас для новых персонажей, не меняя существующих",
"More class abilities, items and Pale Reach quests work as intended": "Исправлена работа ряда классовых способностей, предметов и заданий Pale Reach",
"Witch Doctor and Guardian bots use their totems and standards, and fewer casts are refused": "Боты Witch Doctor и Guardian используют тотемы и штандарты; заклинания реже отклоняются",
"Venomancer Fortitude tanks use their real defensive abilities": "Танки Venomancer Fortitude используют свои настоящие защитные способности",
"Healer bots waste fewer big heals and tank bots spread their defensives": "Лекари реже тратят мощное исцеление впустую, а танки распределяют защитные способности",
"Dungeon bots drink and rest until the tank is ready to go on": "Боты в подземельях пьют и отдыхают, пока танк не будет готов продолжить",
"Archery Rangers use Precision Shot and Brutal Shot": "Archery Ranger использует Precision Shot и Brutal Shot",
"Black Knight tank bots can pull in auto-dungeon mode": "Танк Black Knight может начинать бой в автоматическом режиме подземелий",
"Boltslinger bots use spells they actually know": "Boltslinger использует только изученные заклинания",
"Bots with unsuitable gear are refitted at login": "Боты с неподходящим снаряжением переодеваются при входе",
"Bots with full bags make room to hand in finished quests": "Боты с полными сумками освобождают место для сдачи выполненных заданий",
"Bots pick weapons and shields for their combat spells, not for enchanting recipes": "Боты подбирают оружие и щиты для боевых способностей, а не для рецептов зачарования",
"Bots get their gear repaired and stop looping to the repairer": "Боты чинят снаряжение и перестают ходить к ремонтнику по кругу",
"Bots stay out of Outland and Northrend when those are not scaled to the level cap": "Боты не отправляются в Запределье и Нордскол, если те не масштабированы под предел уровня",
"Bots plan long walks around areas too strong for them": "При дальних переходах боты обходят слишком опасные для них области",
"Dead bots run back to their bodies and come back healthy": "Погибшие боты возвращаются к телам и воскресают здоровыми",
"Meet travelling companions and rivals in dynamic open-world encounters": "Встречайте попутчиков и соперников в динамических событиях открытого мира",
"New companions respect the server's custom race restrictions": "Новые компаньоны соблюдают ограничения сервера на кастомные расы",
"Ranged bots no longer stand still while Auto Shot or Shoot is active": "Боты дальнего боя больше не замирают при активном Auto Shot или Shoot",
"Battleground bots no longer travel in a straight line": "Боты на полях боя больше не перемещаются по прямой",
"Far less server lag with hundreds of bots online": "Значительно снижены задержки сервера при сотнях ботов в сети",
"Inspect the mana restoration spells recognized by an online companion": "Просматривайте заклинания восстановления маны, распознанные у спутника в сети",
"Bots stop hitting mobs they cannot reach": "Боты прекращают атаковать недоступных противников",
"Bot economy errands skip groups, battlegrounds and dungeons": "Экономические поручения ботов не выполняются в группах, на полях боя и в подземельях",
"Dungeon finder fills your group with bots that really join you": "Поиск подземелий заполняет группу ботами, которые действительно присоединяются к вам",
"Stop an unfinished server startup before restoring its database": "Перед восстановлением базы данных можно остановить незавершённый запуск сервера",
"Imported 40 upstream commits with class, item and Pale Reach quest fixes, optional account-wide friends, and corrected Vanity purchases": "Включены 40 изменений апстрима: исправления классов, предметов и заданий Pale Reach, необязательные друзья на весь аккаунт и исправленные покупки Vanity",
"Server includes newer upstream class, quest and dungeon updates": "Сервер включает новые обновления классов, заданий и подземелий из апстрима",
"Dungeon scaling preserves the level differences between creatures": "Масштабирование подземелий сохраняет разницу уровней между существами",
"Normal Classic dungeons retain their authored damage at full party size": "Обычные подземелья классики сохраняют исходный урон при полной группе",
"Interactive World Map displays allied bots, guild tasks and events": "Интерактивная карта мира показывает союзных ботов, задания гильдии и события",
"Database startup allows time for slower hard drives": "Запуск базы данных допускает более долгое ожидание на медленных дисках",
"Option to make low-health runners walk": "Добавлена возможность замедлить убегающих существ с низким здоровьем до шага",
"Prevent crashes while players update Apex Hunt quest markers on different maps": "Устранены падения при обновлении меток заданий Apex Hunt игроками на разных картах",
"Thin Human and Leper Troll characters retain their starting data after updates": "Персонажи Thin Human и Leper Troll сохраняют стартовые данные после обновлений",
"Companions avoid rejected names and recover from forced rename login failures": "Компаньоны получают допустимые имена и восстанавливают вход при требовании переименования",
"Updated the reviewed CoA upstream snapshot": "Обновлена проверенная версия исходников CoA"
},
"de": {
"Restrict new characters by custom race without changing existing characters": "Neue Charaktere nach zusätzlichem Volk beschränken, ohne bestehende Charaktere zu ändern",
"More class abilities, items and Pale Reach quests work as intended": "Weitere Klassenfähigkeiten, Gegenstände und Pale-Reach-Quests funktionieren korrekt",
"Witch Doctor and Guardian bots use their totems and standards, and fewer casts are refused": "Witch-Doctor- und Guardian-Bots nutzen Totems und Standarten; weniger Zauber werden abgelehnt",
"Venomancer Fortitude tanks use their real defensive abilities": "Venomancer-Fortitude-Tanks nutzen ihre tatsächlichen Defensivfähigkeiten",
"Healer bots waste fewer big heals and tank bots spread their defensives": "Heiler verschwenden weniger große Heilungen und Tanks verteilen ihre Defensivfähigkeiten",
"Dungeon bots drink and rest until the tank is ready to go on": "Dungeon-Bots trinken und ruhen, bis der Tank bereit ist",
"Archery Rangers use Precision Shot and Brutal Shot": "Archery Ranger nutzen Precision Shot und Brutal Shot",
"Black Knight tank bots can pull in auto-dungeon mode": "Black-Knight-Tanks können im automatischen Dungeonmodus Gegner heranziehen",
"Boltslinger bots use spells they actually know": "Boltslinger nutzen nur tatsächlich erlernte Zauber",
"Bots with unsuitable gear are refitted at login": "Bots mit ungeeigneter Ausrüstung werden beim Anmelden neu ausgestattet",
"Bots with full bags make room to hand in finished quests": "Bots mit vollen Taschen schaffen Platz zum Abgeben erledigter Quests",
"Bots pick weapons and shields for their combat spells, not for enchanting recipes": "Bots wählen Waffen und Schilde nach Kampffähigkeiten statt Verzauberungsrezepten",
"Bots get their gear repaired and stop looping to the repairer": "Bots reparieren Ausrüstung und laufen nicht mehr wiederholt zum Reparateur",
"Bots stay out of Outland and Northrend when those are not scaled to the level cap": "Bots meiden Scherbenwelt und Nordend, wenn diese nicht auf das Levellimit skaliert sind",
"Bots plan long walks around areas too strong for them": "Bots umgehen auf langen Wegen Gebiete mit zu starken Gegnern",
"Dead bots run back to their bodies and come back healthy": "Tote Bots kehren zu ihren Körpern zurück und werden gesund wiederbelebt",
"Meet travelling companions and rivals in dynamic open-world encounters": "Begegne reisenden Begleitern und Rivalen in dynamischen Ereignissen der offenen Welt",
"New companions respect the server's custom race restrictions": "Neue Begleiter beachten die serverseitigen Beschränkungen eigener Völker",
"Ranged bots no longer stand still while Auto Shot or Shoot is active": "Fernkampf-Bots bleiben bei aktivem Auto Shot oder Shoot nicht mehr stehen",
"Battleground bots no longer travel in a straight line": "Schlachtfeld-Bots bewegen sich nicht mehr geradlinig",
"Far less server lag with hundreds of bots online": "Deutlich weniger Serververzögerungen bei Hunderten aktiven Bots",
"Inspect the mana restoration spells recognized by an online companion": "Erkannte Manaregeneration-Zauber eines aktiven Begleiters anzeigen",
"Bots stop hitting mobs they cannot reach": "Bots greifen unerreichbare Gegner nicht weiter an",
"Bot economy errands skip groups, battlegrounds and dungeons": "Wirtschaftsaufgaben der Bots überspringen Gruppen, Schlachtfelder und Dungeons",
"Dungeon finder fills your group with bots that really join you": "Der Dungeonfinder füllt Gruppen mit Bots, die sich tatsächlich anschließen",
"Stop an unfinished server startup before restoring its database": "Unvollständigen Serverstart vor dem Wiederherstellen der Datenbank stoppen",
"Imported 40 upstream commits with class, item and Pale Reach quest fixes, optional account-wide friends, and corrected Vanity purchases": "40 Upstream-Änderungen mit Klassen-, Gegenstands- und Pale-Reach-Questkorrekturen, optionalen accountweiten Freunden und korrigierten Vanity-Käufen übernommen",
"Server includes newer upstream class, quest and dungeon updates": "Der Server enthält neuere Upstream-Updates für Klassen, Quests und Dungeons",
"Dungeon scaling preserves the level differences between creatures": "Die Dungeon-Skalierung erhält die Stufenunterschiede zwischen Kreaturen",
"Normal Classic dungeons retain their authored damage at full party size": "Normale Classic-Dungeons behalten bei voller Gruppe ihren ursprünglichen Schaden",
"Interactive World Map displays allied bots, guild tasks and events": "Die interaktive Weltkarte zeigt verbündete Bots, Gildenaufgaben und Ereignisse",
"Database startup allows time for slower hard drives": "Der Datenbankstart lässt langsameren Festplatten mehr Zeit",
"Option to make low-health runners walk": "Fliehende Kreaturen mit wenig Gesundheit können im Schritttempo laufen",
"Prevent crashes while players update Apex Hunt quest markers on different maps": "Abstürze beim Aktualisieren von Apex-Hunt-Questmarkierungen auf verschiedenen Karten verhindern",
"Thin Human and Leper Troll characters retain their starting data after updates": "Charaktere der Völker Thin Human und Leper Troll behalten ihre Startdaten nach Updates",
"Companions avoid rejected names and recover from forced rename login failures": "Begleiter vermeiden unzulässige Namen und können sich nach erzwungener Umbenennung wieder anmelden",
"Updated the reviewed CoA upstream snapshot": "Geprüften CoA-Upstream-Stand aktualisiert"
},
"fr": {
"Restrict new characters by custom race without changing existing characters": "Restreignez les races supplémentaires des nouveaux personnages sans modifier les personnages existants",
"More class abilities, items and Pale Reach quests work as intended": "Davantage de capacités de classe, d’objets et de quêtes de Pale Reach fonctionnent correctement",
"Witch Doctor and Guardian bots use their totems and standards, and fewer casts are refused": "Les bots Witch Doctor et Guardian utilisent leurs totems et étendards ; moins de sorts sont refusés",
"Venomancer Fortitude tanks use their real defensive abilities": "Les tanks Venomancer Fortitude utilisent leurs véritables capacités défensives",
"Healer bots waste fewer big heals and tank bots spread their defensives": "Les soigneurs gaspillent moins de gros soins et les tanks répartissent leurs défenses",
"Dungeon bots drink and rest until the tank is ready to go on": "Les bots de donjon boivent et se reposent jusqu’à ce que le tank soit prêt",
"Archery Rangers use Precision Shot and Brutal Shot": "Les Archery Rangers utilisent Precision Shot et Brutal Shot",
"Black Knight tank bots can pull in auto-dungeon mode": "Les tanks Black Knight peuvent engager les ennemis en mode donjon automatique",
"Boltslinger bots use spells they actually know": "Les Boltslingers utilisent les sorts qu’ils connaissent réellement",
"Bots with unsuitable gear are refitted at login": "Les bots mal équipés reçoivent un équipement adapté à la connexion",
"Bots with full bags make room to hand in finished quests": "Les bots aux sacs pleins font de la place pour rendre les quêtes terminées",
"Bots pick weapons and shields for their combat spells, not for enchanting recipes": "Les bots choisissent armes et boucliers selon leurs sorts de combat, pas les recettes d’enchantement",
"Bots get their gear repaired and stop looping to the repairer": "Les bots font réparer leur équipement sans retourner en boucle chez le réparateur",
"Bots stay out of Outland and Northrend when those are not scaled to the level cap": "Les bots évitent l’Outreterre et le Norfendre si leur niveau n’est pas adapté au plafond",
"Bots plan long walks around areas too strong for them": "Les bots contournent les zones trop dangereuses lors des longs trajets",
"Dead bots run back to their bodies and come back healthy": "Les bots morts rejoignent leur corps et reviennent en bonne santé",
"Meet travelling companions and rivals in dynamic open-world encounters": "Rencontrez des compagnons voyageurs et des rivaux lors d’événements dynamiques en monde ouvert",
"New companions respect the server's custom race restrictions": "Les nouveaux compagnons respectent les restrictions du serveur sur les races personnalisées",
"Ranged bots no longer stand still while Auto Shot or Shoot is active": "Les bots à distance ne restent plus immobiles lorsque Auto Shot ou Shoot est actif",
"Battleground bots no longer travel in a straight line": "Les bots des champs de bataille ne se déplacent plus en ligne droite",
"Far less server lag with hundreds of bots online": "Beaucoup moins de ralentissements avec des centaines de bots connectés",
"Inspect the mana restoration spells recognized by an online companion": "Consultez les sorts de restauration de mana reconnus chez un compagnon connecté",
"Bots stop hitting mobs they cannot reach": "Les bots cessent d’attaquer les ennemis inaccessibles",
"Bot economy errands skip groups, battlegrounds and dungeons": "Les tâches économiques des bots ignorent groupes, champs de bataille et donjons",
"Dungeon finder fills your group with bots that really join you": "La recherche de donjon remplit votre groupe avec des bots qui vous rejoignent réellement",
"Stop an unfinished server startup before restoring its database": "Arrêtez un démarrage de serveur inachevé avant de restaurer sa base de données",
"Imported 40 upstream commits with class, item and Pale Reach quest fixes, optional account-wide friends, and corrected Vanity purchases": "Intégration de 40 changements amont : classes, objets et quêtes de Pale Reach corrigés, amis de compte facultatifs et achats Vanity corrigés",
"Server includes newer upstream class, quest and dungeon updates": "Le serveur intègre de nouvelles mises à jour des classes, quêtes et donjons provenant du projet amont",
"Dungeon scaling preserves the level differences between creatures": "La mise à l’échelle des donjons conserve les écarts de niveau entre les créatures",
"Normal Classic dungeons retain their authored damage at full party size": "Les donjons Classic normaux conservent leurs dégâts d’origine avec un groupe complet",
"Interactive World Map displays allied bots, guild tasks and events": "La carte du monde interactive affiche les bots alliés, les tâches de guilde et les événements",
"Database startup allows time for slower hard drives": "Le démarrage de la base de données laisse plus de temps aux disques lents",
"Option to make low-health runners walk": "Une option permet aux créatures affaiblies de fuir en marchant",
"Prevent crashes while players update Apex Hunt quest markers on different maps": "Évite les plantages lorsque les joueurs actualisent les marqueurs de quête Apex Hunt sur différentes cartes",
"Thin Human and Leper Troll characters retain their starting data after updates": "Les personnages Thin Human et Leper Troll conservent leurs données de départ après les mises à jour",
"Companions avoid rejected names and recover from forced rename login failures": "Les compagnons évitent les noms refusés et récupèrent leur connexion après un renommage imposé",
"Updated the reviewed CoA upstream snapshot": "Version amont vérifiée de CoA mise à jour"
},
"es": {
"Restrict new characters by custom race without changing existing characters": "Restringe las razas adicionales de personajes nuevos sin modificar los existentes",
"More class abilities, items and Pale Reach quests work as intended": "Más habilidades de clase, objetos y misiones de Pale Reach funcionan correctamente",
"Witch Doctor and Guardian bots use their totems and standards, and fewer casts are refused": "Los bots Witch Doctor y Guardian usan sus tótems y estandartes y se rechazan menos hechizos",
"Venomancer Fortitude tanks use their real defensive abilities": "Los tanques Venomancer Fortitude usan sus verdaderas habilidades defensivas",
"Healer bots waste fewer big heals and tank bots spread their defensives": "Los sanadores desperdician menos curas grandes y los tanques distribuyen sus defensivos",
"Dungeon bots drink and rest until the tank is ready to go on": "Los bots de mazmorra beben y descansan hasta que el tanque está listo",
"Archery Rangers use Precision Shot and Brutal Shot": "Los Archery Rangers usan Precision Shot y Brutal Shot",
"Black Knight tank bots can pull in auto-dungeon mode": "Los tanques Black Knight pueden iniciar combates en el modo automático de mazmorras",
"Boltslinger bots use spells they actually know": "Los Boltslingers usan hechizos que realmente conocen",
"Bots with unsuitable gear are refitted at login": "Los bots con equipo inadecuado reciben equipo apropiado al conectarse",
"Bots with full bags make room to hand in finished quests": "Los bots con bolsas llenas hacen espacio para entregar misiones completadas",
"Bots pick weapons and shields for their combat spells, not for enchanting recipes": "Los bots eligen armas y escudos por sus hechizos de combate, no por recetas de encantamiento",
"Bots get their gear repaired and stop looping to the repairer": "Los bots reparan su equipo y dejan de volver al reparador en bucle",
"Bots stay out of Outland and Northrend when those are not scaled to the level cap": "Los bots evitan Terrallende y Rasganorte si no están escalados al límite de nivel",
"Bots plan long walks around areas too strong for them": "Los bots evitan zonas demasiado peligrosas en los viajes largos",
"Dead bots run back to their bodies and come back healthy": "Los bots muertos vuelven a sus cuerpos y regresan con buena salud",
"Meet travelling companions and rivals in dynamic open-world encounters": "Encuentra compañeros viajeros y rivales en encuentros dinámicos de mundo abierto",
"New companions respect the server's custom race restrictions": "Los nuevos compañeros respetan las restricciones del servidor sobre razas personalizadas",
"Ranged bots no longer stand still while Auto Shot or Shoot is active": "Los bots a distancia ya no se quedan inmóviles con Auto Shot o Shoot activo",
"Battleground bots no longer travel in a straight line": "Los bots de campos de batalla ya no viajan en línea recta",
"Far less server lag with hundreds of bots online": "Mucho menos lag del servidor con cientos de bots conectados",
"Inspect the mana restoration spells recognized by an online companion": "Consulta los hechizos de restauración de maná reconocidos en un compañero conectado",
"Bots stop hitting mobs they cannot reach": "Los bots dejan de atacar a enemigos inalcanzables",
"Bot economy errands skip groups, battlegrounds and dungeons": "Las tareas económicas de los bots omiten grupos, campos de batalla y mazmorras",
"Dungeon finder fills your group with bots that really join you": "El buscador de mazmorras llena tu grupo con bots que realmente se unen",
"Stop an unfinished server startup before restoring its database": "Detén un inicio de servidor incompleto antes de restaurar su base de datos",
"Imported 40 upstream commits with class, item and Pale Reach quest fixes, optional account-wide friends, and corrected Vanity purchases": "Integrados 40 cambios del proyecto original: correcciones de clases, objetos y misiones de Pale Reach, amigos opcionales de toda la cuenta y compras Vanity corregidas",
"Server includes newer upstream class, quest and dungeon updates": "El servidor incorpora nuevas actualizaciones de clases, misiones y mazmorras del proyecto original",
"Dungeon scaling preserves the level differences between creatures": "El escalado de las mazmorras conserva las diferencias de nivel entre criaturas",
"Normal Classic dungeons retain their authored damage at full party size": "Las mazmorras Classic normales conservan su daño original con un grupo completo",
"Interactive World Map displays allied bots, guild tasks and events": "El mapa del mundo interactivo muestra bots aliados, tareas de hermandad y eventos",
"Database startup allows time for slower hard drives": "El inicio de la base de datos permite más tiempo en discos lentos",
"Option to make low-health runners walk": "Una opción permite que las criaturas con poca salud huyan caminando",
"Prevent crashes while players update Apex Hunt quest markers on different maps": "Evita fallos al actualizar marcadores de misiones Apex Hunt en distintos mapas",
"Thin Human and Leper Troll characters retain their starting data after updates": "Los personajes Thin Human y Leper Troll conservan sus datos iniciales tras actualizar",
"Companions avoid rejected names and recover from forced rename login failures": "Los compañeros evitan nombres rechazados y recuperan el acceso tras un cambio de nombre obligatorio",
"Updated the reviewed CoA upstream snapshot": "Actualizada la versión revisada del código original de CoA"
},
"zh": {
"Restrict new characters by custom race without changing existing characters": "限制新角色可选的自定义种族,不影响现有角色",
"More class abilities, items and Pale Reach quests work as intended": "修复更多职业技能、物品和 Pale Reach 任务",
"Witch Doctor and Guardian bots use their totems and standards, and fewer casts are refused": "Witch Doctor 和 Guardian 机器人会使用图腾和旗帜,施法被拒绝的情况减少",
"Venomancer Fortitude tanks use their real defensive abilities": "Venomancer Fortitude 坦克会使用实际拥有的防御技能",
"Healer bots waste fewer big heals and tank bots spread their defensives": "治疗机器人减少浪费大型治疗,坦克会错开使用防御技能",
"Dungeon bots drink and rest until the tank is ready to go on": "副本机器人会喝水和休息,直到坦克准备好继续",
"Archery Rangers use Precision Shot and Brutal Shot": "Archery Ranger 会使用 Precision Shot 和 Brutal Shot",
"Black Knight tank bots can pull in auto-dungeon mode": "Black Knight 坦克可以在自动副本模式中拉怪",
"Boltslinger bots use spells they actually know": "Boltslinger 只会使用实际学会的法术",
"Bots with unsuitable gear are refitted at login": "装备不合适的机器人会在登录时更换装备",
"Bots with full bags make room to hand in finished quests": "背包已满的机器人会腾出空间以提交已完成的任务",
"Bots pick weapons and shields for their combat spells, not for enchanting recipes": "机器人根据战斗法术选择武器和盾牌,而不是根据附魔配方",
"Bots get their gear repaired and stop looping to the repairer": "机器人会修理装备,不再反复往返修理商",
"Bots stay out of Outland and Northrend when those are not scaled to the level cap": "如果外域和诺森德未缩放到等级上限,机器人会避开这些地区",
"Bots plan long walks around areas too strong for them": "机器人长途行走时会绕开过于危险的区域",
"Dead bots run back to their bodies and come back healthy": "死亡的机器人会跑回尸体并以健康状态复活",
"Meet travelling companions and rivals in dynamic open-world encounters": "在动态开放世界事件中遇见旅行伙伴和对手",
"New companions respect the server's custom race restrictions": "新同伴遵守服务器对自定义种族的限制",
"Ranged bots no longer stand still while Auto Shot or Shoot is active": "远程机器人不再因 Auto Shot 或 Shoot 启用而原地不动",
"Battleground bots no longer travel in a straight line": "战场机器人不再沿直线移动",
"Far less server lag with hundreds of bots online": "数百个机器人在线时,服务器延迟显著降低",
"Inspect the mana restoration spells recognized by an online companion": "查看在线伙伴所识别的法力恢复法术",
"Bots stop hitting mobs they cannot reach": "机器人会停止攻击无法接近的敌人",
"Bot economy errands skip groups, battlegrounds and dungeons": "机器人的经济事务会跳过队伍、战场和副本",
"Dungeon finder fills your group with bots that really join you": "地下城查找器会用真正加入队伍的机器人补齐队伍",
"Stop an unfinished server startup before restoring its database": "恢复数据库前可以停止尚未完成的服务器启动",
"Imported 40 upstream commits with class, item and Pale Reach quest fixes, optional account-wide friends, and corrected Vanity purchases": "合入 40 项上游更改:职业、物品及 Pale Reach 任务修复,可选的账号共享好友,以及 Vanity 购买修复",
"Server includes newer upstream class, quest and dungeon updates": "服务器整合了上游新的职业、任务和地下城更新",
"Dungeon scaling preserves the level differences between creatures": "地下城缩放保留生物之间的等级差异",
"Normal Classic dungeons retain their authored damage at full party size": "普通经典地下城在满员队伍下保留原始伤害",
"Interactive World Map displays allied bots, guild tasks and events": "交互式世界地图显示友方机器人、公会任务和事件",
"Database startup allows time for slower hard drives": "数据库启动为较慢的硬盘预留更多等待时间",
"Option to make low-health runners walk": "新增选项,可让低生命值的逃跑生物改为步行",
"Prevent crashes while players update Apex Hunt quest markers on different maps": "防止玩家在不同地图更新 Apex Hunt 任务标记时崩溃",
"Thin Human and Leper Troll characters retain their starting data after updates": "Thin Human 和 Leper Troll 角色在更新后保留初始数据",
"Companions avoid rejected names and recover from forced rename login failures": "同伴避免使用被拒绝的名称,并修复强制改名导致的登录失败",
"Updated the reviewed CoA upstream snapshot": "更新已审核的 CoA 上游版本"
}
}
} }
File diff suppressed because it is too large. Load diff
+14 -2
View File
@@ -25,9 +25,20 @@ export {};
notes:["worldserver.exe differs from the one listed in RELEASE.json (release 2026-09-11); this looks like a customised build."],modifies_files:false}; notes:["worldserver.exe differs from the one listed in RELEASE.json (release 2026-09-11); this looks like a customised build."],modifies_files:false};
const svc=(n: string,p: number,st: string)=>({name:n,state:st,pid:st==="running"?100:null,port:p,port_ready:st==="running",conflict:null,uptime_secs:st==="running"?4206:null}); const svc=(n: string,p: number,st: string)=>({name:n,state:st,pid:st==="running"?100:null,port:p,port_ready:st==="running",conflict:null,uptime_secs:st==="running"?4206:null});
{ const q = new URLSearchParams(location.search); const w0 = window as any; if (q.get("client")) w0.__client = q.get("client"); if (q.get("modified")) w0.__modified = true; } { const q = new URLSearchParams(location.search); const w0 = window as any; if (q.get("client")) w0.__client = q.get("client"); if (q.get("modified")) w0.__modified = true; }
(window as any).__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
(window as any).__TAURI_INTERNALS__ = { (window as any).__TAURI_INTERNALS__ = {
transformCallback: (cb: unknown)=>cb, unregisterCallback(){}, convertFileSrc:(x: unknown)=>x, transformCallback: (cb: unknown)=>cb, unregisterCallback(){}, convertFileSrc:(x: unknown)=>x,
invoke: async (cmd: string, args?: any)=>{ invoke: async (cmd: string, args?: any)=>{
if(cmd==="close_to_tray") return localStorage.getItem("demo-close-tray")==="1";
if(cmd==="set_close_to_tray"){localStorage.setItem("demo-close-tray",args.enabled?"1":"0");return;}
if(cmd==="client_graphics") return JSON.parse(localStorage.getItem("demo-graphics")??'{"dxvk_disabled":false,"enhancements_disabled":false}');
if(cmd==="client_set_graphics"){const g=JSON.parse(localStorage.getItem("demo-graphics")??'{"dxvk_disabled":false,"enhancements_disabled":false}');g[args.name==="d3d9.dll"?"dxvk_disabled":"enhancements_disabled"]=args.disabled;localStorage.setItem("demo-graphics",JSON.stringify(g));return g;}
if(cmd==="browse_enabled") return localStorage.getItem("demo-browse-enabled") !== "0";
if(cmd==="browse_set_enabled"){localStorage.setItem("demo-browse-enabled", args.enabled ? "1" : "0");return;}
if(cmd==="open_link") return null;
if(cmd==="pending_update") return null;
if(cmd==="plugin:app|version") return "0.8.2";
if(cmd==="release_history") throw new Error("Offline demo: using bundled notes");
if(cmd==="realm_profiles") return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:simultaneous&&running,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:withReborn&&running}; if(cmd==="realm_profiles") return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:simultaneous&&running,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:withReborn&&running};
if(cmd==="realm_simultaneous") { if(running) throw new Error("Stop both realms before changing simultaneous startup."); simultaneous=args.enabled; wildcardCreated ||= simultaneous; return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:false,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:false}; } if(cmd==="realm_simultaneous") { if(running) throw new Error("Stop both realms before changing simultaneous startup."); simultaneous=args.enabled; wildcardCreated ||= simultaneous; return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:false,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:false}; }
if(cmd==="realm_with_reborn") { if(running) throw new Error("Stop all realms before changing which realms start together."); withReborn=args.enabled; rebornCreated ||= withReborn; return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:false,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:false}; } if(cmd==="realm_with_reborn") { if(running) throw new Error("Stop all realms before changing which realms start together."); withReborn=args.enabled; rebornCreated ||= withReborn; return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:false,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:false}; }
@@ -42,6 +53,7 @@ export {};
if(cmd==="add_server"){added=true;return {id:"1",name:"CoA-Repack",path:report.path};} if(cmd==="add_server"){added=true;return {id:"1",name:"CoA-Repack",path:report.path};}
if(cmd==="server_status"){const s=running?"running":"stopped";return {observed:{mysql:svc("mysql",3307,s),auth:svc("auth",3724,s),world:svc("world",8085,s),secondary_world:simultaneous?svc("world-secondary",8086,s):null,reborn_world:withReborn?svc("world-reborn",8087,s):null},busy:false,path_exists:true};} if(cmd==="server_status"){const s=running?"running":"stopped";return {observed:{mysql:svc("mysql",3307,s),auth:svc("auth",3724,s),world:svc("world",8085,s),secondary_world:simultaneous?svc("world-secondary",8086,s):null,reborn_world:withReborn?svc("world-reborn",8087,s):null},busy:false,path_exists:true};}
if(cmd==="start_server"){await new Promise((r: any)=>setTimeout(r,1500));running=true;return {ok:true,exit_code:0,code:null,human:null,output:""};} if(cmd==="start_server"){await new Promise((r: any)=>setTimeout(r,1500));running=true;return {ok:true,exit_code:0,code:null,human:null,output:""};}
if(cmd==="force_stop_server"){running=false;return {ok:true,exit_code:0,code:null,human:null,output:""};}
if(cmd==="stop_server"){await new Promise((r: any)=>setTimeout(r,1500));running=false;return {ok:true,exit_code:0,code:null,human:null,output:""};} if(cmd==="stop_server"){await new Promise((r: any)=>setTimeout(r,1500));running=false;return {ok:true,exit_code:0,code:null,human:null,output:""};}
if(cmd.startsWith("plugin:dialog")) return "C:\\games\\CoA-Repack"; if(cmd.startsWith("plugin:dialog")) return "C:\\games\\CoA-Repack";
if(cmd==="get_settings"){const sc=args?.scope==="server"?serverSchema:botsSchema;return {scope:args?.scope,categories:sc.categories,settings:(sc.settings as any[]).map(x=>({...x,options:x.options??[],value:x.default,is_default:true,present:true,problem:null,drift:false})),unknown_keys:3,drift_keys:[],files:[]};} if(cmd==="get_settings"){const sc=args?.scope==="server"?serverSchema:botsSchema;return {scope:args?.scope,categories:sc.categories,settings:(sc.settings as any[]).map(x=>({...x,options:x.options??[],value:x.default,is_default:true,present:true,problem:null,drift:false})),unknown_keys:3,drift_keys:[],files:[]};}
@@ -49,8 +61,8 @@ export {};
if(cmd==="preview_preset"){const a=args;const sc=a.scope==="server"?serverSchema:botsSchema;const pr=(a.scope==="server"?serverPresets:botsPresets).presets as any[];const p=pr.find(x=>x.id===a.preset)??{id:a.preset??"defaults",title:"Recommended defaults",description:"Every setting returns to its default value."};const st=(sc.settings as any[]).filter(x=>x.type==="int"||x.type==="float"||x.type==="enum").slice(0,3);return {id:p.id,title:p.title,description:p.description,changes:st.map(x=>({key:x.key,title:x.title,from:x.default,to:x.type==="enum"?(x.options?.[1]?.value??x.default):(Number(x.default)||1)*2,dangerous:false}))};} if(cmd==="preview_preset"){const a=args;const sc=a.scope==="server"?serverSchema:botsSchema;const pr=(a.scope==="server"?serverPresets:botsPresets).presets as any[];const p=pr.find(x=>x.id===a.preset)??{id:a.preset??"defaults",title:"Recommended defaults",description:"Every setting returns to its default value."};const st=(sc.settings as any[]).filter(x=>x.type==="int"||x.type==="float"||x.type==="enum").slice(0,3);return {id:p.id,title:p.title,description:p.description,changes:st.map(x=>({key:x.key,title:x.title,from:x.default,to:x.type==="enum"?(x.options?.[1]?.value??x.default):(Number(x.default)||1)*2,dangerous:false}))};}
if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]}; if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]};
if(cmd==="add_companions"){const base=(window as any).__bots??85;(window as any).__target=base+args.count;return {spawned:"queued",created:null,baseline:base};} if(cmd==="add_companions"){const base=(window as any).__bots??85;(window as any).__target=base+args.count;return {spawned:"queued",created:null,baseline:base};}
if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261001.8":"0.260930.5",to_version:"0.261001.8",items:[],conflicts:[],migrations:5,pending_migrations:(window as any).__updated?0:5,download_bytes:6000000}; if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261028.83":"0.261026.81",to_version:"0.261028.83",items:[],conflicts:[],migrations:5,pending_migrations:(window as any).__updated?0:5,download_bytes:6000000};
if(cmd==="apply_update"){const w=window as any;for(let i=1;i<=8;i++){await new Promise((r: any)=>setTimeout(r,700));(w.__handlers?.["update-progress"]??[]).forEach((h: any)=>h({event:"update-progress",id:1,payload:{step:i<4?"Downloading the update":i<7?"Applying the update":"Finishing",percent:i*12}}));}(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261001.8"},migrations:null};} if(cmd==="apply_update"){const w=window as any;for(let i=1;i<=8;i++){await new Promise((r: any)=>setTimeout(r,700));(w.__handlers?.["update-progress"]??[]).forEach((h: any)=>h({event:"update-progress",id:1,payload:{step:i<4?"Downloading the update":i<7?"Applying the update":"Finishing",percent:i*12}}));}(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261028.83"},migrations:null};}
if(cmd==="get_population"){if(!running) return null;let b=(window as any).__bots??85;const t=(window as any).__target??0;if(t>b){b=Math.min(t,b+25);(window as any).__bots=b;}return {online_total:b,bots_online:Math.max(0,b-7),players_online:0,bots_total:b};} if(cmd==="get_population"){if(!running) return null;let b=(window as any).__bots??85;const t=(window as any).__target??0;if(t>b){b=Math.min(t,b+25);(window as any).__bots=b;}return {online_total:b,bots_online:Math.max(0,b-7),players_online:0,bots_total:b};}
if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null; if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null;
if(cmd==="run_diagnostics") return {problems:2,checks:[{id:"files",title:"Server files",level:"ok",detail:"All expected server parts were found."},{id:"world",title:"World server",level:"warn",detail:"Not running."},{id:"disk",title:"Free disk space",level:"warn",detail:"Only 3 GB free; backups and updates need room."},{id:"exposure",title:"Private services",level:"ok",detail:"Database and server console are not reachable from the network."}]}; if(cmd==="run_diagnostics") return {problems:2,checks:[{id:"files",title:"Server files",level:"ok",detail:"All expected server parts were found."},{id:"world",title:"World server",level:"warn",detail:"Not running."},{id:"disk",title:"Free disk space",level:"warn",detail:"Only 3 GB free; backups and updates need room."},{id:"exposure",title:"Private services",level:"ok",detail:"Database and server console are not reachable from the network."}]};
+43
View File
@@ -3,6 +3,32 @@ import type en from "./en";
/** Deutsch. Entwurf einer Übersetzung; vor der Veröffentlichung von Muttersprachlern zu prüfen. */ /** Deutsch. Entwurf einer Übersetzung; vor der Veröffentlichung von Muttersprachlern zu prüfen. */
const de: Partial<Record<keyof typeof en, string>> = { const de: Partial<Record<keyof typeof en, string>> = {
"upd.preexistingCharacters": "Bereits vor dem Update fehlten bei {n} Charakterdatensätzen die Startdaten für Volk/Klasse. Unveränderte Datensätze wurden bewahrt und blockierten das Update nicht. Details stehen in der Diagnose; diese älteren Unstimmigkeiten wurden nicht automatisch behoben.", "upd.preexistingCharacters": "Bereits vor dem Update fehlten bei {n} Charakterdatensätzen die Startdaten für Volk/Klasse. Unveränderte Datensätze wurden bewahrt und blockierten das Update nicht. Details stehen in der Diagnose; diese älteren Unstimmigkeiten wurden nicht automatisch behoben.",
"settings.autoManager": "Updates im Hintergrund herunterladen",
"settings.startServer": "Nach dem Update starten",
"settings.version": "Version {v}",
"settings.startupHelp": "Details zum Start",
"settings.section.updates": "Updates",
"settings.section.startup": "Start",
"settings.section.client": "Client und Dateien",
"settings.section.service": "Wartung",
"settings.section.interface": "Oberfläche",
"settings.organized": "Updates, Serverstart und Spieldateien verwalten",
"settings.clientLink": "Clientdateien und Spieldaten",
"history.title": "Änderungsverlauf",
"history.open": "Was sich ändert",
"history.server": "Server",
"history.manager": "Manager",
"history.all": "Alle Versionen",
"history.range": "Für dieses Update",
"history.language": "Sprache der Einträge",
"history.fallback": "Englisches Original: Diese Version wurde noch nicht übersetzt",
"history.empty": "Für dieses Update sind noch keine Einträge veröffentlicht",
"history.files": "Dateiänderungen",
"history.offline": "Gespeicherter Verlauf · offline verfügbar",
"history.refreshed": "Veröffentlichter Verlauf aktualisiert",
"history.experimental": "Portable Charaktere sind experimentell. Sichere deine Charaktere vor der Verwendung.",
"settings.attention": "Ein Update erfordert Aufmerksamkeit. Öffne Updates für die Wiederherstellungsoptionen.",
"races.unknownIds": "Nicht mehr im Katalog vorhandene Völker-IDs: {ids}. Beim Speichern werden diese alten Einschränkungen entfernt.", "races.unknownIds": "Nicht mehr im Katalog vorhandene Völker-IDs: {ids}. Beim Speichern werden diese alten Einschränkungen entfernt.",
"races.reviewCatalog": "Der Völkerkatalog wurde geändert oder noch nicht geprüft. Prüfe die Liste und speichere sie erneut.", "races.reviewCatalog": "Der Völkerkatalog wurde geändert oder noch nicht geprüft. Prüfe die Liste und speichere sie erneut.",
@@ -1040,6 +1066,23 @@ const de: Partial<Record<keyof typeof en, string>> = {
"registry.realmStoppedHint": "Der Realm ist gestoppt. Den Server starten, damit Spieler beitreten und Charaktersitzungen verfolgen können.", "registry.realmStoppedHint": "Der Realm ist gestoppt. Den Server starten, damit Spieler beitreten und Charaktersitzungen verfolgen können.",
"access.portableEnabled": "Portable Charaktere zulassen", "access.portableEnabled": "Portable Charaktere zulassen",
"access.portableEnabledHint": "Spieler können auf diesem Realm mit ihren im Manager gespeicherten Charakteren spielen.", "access.portableEnabledHint": "Spieler können auf diesem Realm mit ihren im Manager gespeicherten Charakteren spielen.",
"settings.publicServers": "Öffentliche Server anzeigen",
"settings.publicServersHint": "Wenn deaktiviert, ruft der Manager keine öffentlichen Serverlisten oder Details ab. Wenn aktiviert, lädt Aktualisieren die Liste.",
"browse.disabled": "Die Anzeige öffentlicher Server ist deaktiviert. Aktiviere sie in den Einstellungen, um den Katalog zu laden.",
"client.graphics.dxvk": "Kompatible Grafik verwenden (DXVK deaktivieren)",
"client.graphics.enhancements": "Zusätzliche Grafikverbesserungen deaktivieren",
"client.graphics.hint": "Schließe das Spiel vor Änderungen. Client-Updates lassen deaktivierte Grafikkomponenten ausgeschaltet.",
"settings.closeToTray": "Beim Schließen in den Infobereich minimieren",
"settings.closeToTrayHint": "Wenn ausgeschaltet, beendet das Schließen des Fensters den Manager. Ein erneuter Start öffnet das bereits laufende Fenster.",
"overview.bots": "+ {n} Bots",
"stop.force": "Beenden erzwingen",
"stop.forceTitle": "Diesen Server zwangsweise beenden?",
"stop.forceWarning": "Ungespeicherter Spielfortschritt kann verloren gehen. Nur geprüfte Prozesse dieses Servers werden beendet. Die Datenbank läuft weiter, bis alle Welten beendet sind.",
"stop.cancel": "Abbrechen",
}; };
export default de; export default de;
+43 -1
View File
@@ -1,6 +1,32 @@
/** English is the source of truth: every key must exist here; other locales fall back to it. */ /** English is the source of truth: every key must exist here; other locales fall back to it. */
const en = { const en = {
"upd.preexistingCharacters": "Before the update, {n} character records already lacked race/class starting data. Unchanged records were preserved and did not block the update. Details are saved in diagnostics; these older inconsistencies have not been automatically repaired.", "upd.preexistingCharacters": "Before the update, {n} character records already lacked race/class starting data. Unchanged records were preserved and did not block the update. Details are saved in diagnostics; these older inconsistencies have not been automatically repaired.",
"settings.autoManager": "Download updates in the background",
"settings.startServer": "Start after updating",
"settings.version": "Version {v}",
"settings.startupHelp": "Startup details",
"settings.section.updates": "Updates",
"settings.section.startup": "Startup",
"settings.section.client": "Client and files",
"settings.section.service": "Maintenance",
"settings.section.interface": "Interface",
"settings.organized": "Manage updates, startup and your game files",
"settings.clientLink": "Client files and game data",
"history.title": "Release history",
"history.open": "What changed",
"history.server": "Server",
"history.manager": "Manager",
"history.all": "All versions",
"history.range": "For this update",
"history.language": "Notes language",
"history.fallback": "Original English notes: this release has not been translated yet",
"history.empty": "No published notes for this update",
"history.files": "File changes",
"history.offline": "Saved release history · available offline",
"history.refreshed": "Published notes refreshed",
"history.experimental": "Portable Characters is experimental. Back up your characters before using it.",
"settings.attention": "An update needs attention. Open Updates to review recovery options.",
"races.unknownIds": "RaceIDs no longer in this catalog: {ids}. Saving the reviewed list removes these old restrictions.", "races.unknownIds": "RaceIDs no longer in this catalog: {ids}. Saving the reviewed list removes these old restrictions.",
"races.reviewCatalog": "The race catalog changed or has not been verified. Review the list and save it before applying restrictions.", "races.reviewCatalog": "The race catalog changed or has not been verified. Review the list and save it before applying restrictions.",
@@ -1125,7 +1151,7 @@ const en = {
"browse.offlineWarning": "The server is currently offline. Joining with a portable character will become available once the host starts the server.", "browse.offlineWarning": "The server is currently offline. Joining with a portable character will become available once the host starts the server.",
"browse.play": "Play", "browse.play": "Play",
"browse.playSoon": "Joining arrives with the account support of the next step.", "browse.playSoon": "Joining arrives with the account support of the next step.",
"registry.title": "Public listing", "registry.title": "Public realms",
"registry.dialogTitle": "Public listing · {realm}", "registry.dialogTitle": "Public listing · {realm}",
"registry.publishAll": "Publish all realms", "registry.publishAll": "Publish all realms",
"registry.publishAllText": "One description, language and region for every realm that is not listed yet. Each realm is listed under the server name; the realms that start next to the main one get their realm name added.", "registry.publishAllText": "One description, language and region for every realm that is not listed yet. Each realm is listed under the server name; the realms that start next to the main one get their realm name added.",
@@ -1251,6 +1277,22 @@ const en = {
"access.relay": "Relay", "access.relay": "Relay",
"access.relayUp": "Game relay connected", "access.relayUp": "Game relay connected",
"access.relayDown": "Game relay disconnected", "access.relayDown": "Game relay disconnected",
"settings.publicServers": "Allow public server browsing",
"settings.publicServersHint": "When disabled, the Manager does not request public server lists or details. When enabled, load the list with Refresh.",
"browse.disabled": "Public server browsing is disabled. Enable it in Settings to load the catalog.",
"client.graphics.dxvk": "Use compatibility graphics (disable DXVK)",
"client.graphics.enhancements": "Disable additional graphics enhancements",
"client.graphics.hint": "Close the game before changing these settings. Disabled renderers stay disabled during client updates.",
"settings.closeToTray": "Minimize to tray when closing the window",
"settings.closeToTrayHint": "When off, closing the window exits the Manager. Launching it again opens the existing window if it is already running.",
"overview.bots": "+ {n} bots",
"stop.force": "Force stop",
"stop.forceTitle": "Force-stop this server?",
"stop.forceWarning": "Unsaved player progress may be lost. Only verified processes belonging to this server will be stopped. The database will remain running until every world has stopped.",
"stop.cancel": "Cancel",
} as const; } as const;
export default en; export default en;
+43
View File
@@ -3,6 +3,32 @@ import type en from "./en";
/** Español. Traducción provisional; debe revisarla un hablante nativo antes de publicarse. */ /** Español. Traducción provisional; debe revisarla un hablante nativo antes de publicarse. */
const es: Partial<Record<keyof typeof en, string>> = { const es: Partial<Record<keyof typeof en, string>> = {
"upd.preexistingCharacters": "Antes de actualizar, a {n} registros de personaje ya les faltaban datos iniciales de raza/clase. Los registros sin cambios se conservaron y no bloquearon la actualización. Los detalles están en el diagnóstico; estas inconsistencias anteriores no se repararon automáticamente.", "upd.preexistingCharacters": "Antes de actualizar, a {n} registros de personaje ya les faltaban datos iniciales de raza/clase. Los registros sin cambios se conservaron y no bloquearon la actualización. Los detalles están en el diagnóstico; estas inconsistencias anteriores no se repararon automáticamente.",
"settings.autoManager": "Descargar actualizaciones en segundo plano",
"settings.startServer": "Iniciar tras actualizar",
"settings.version": "Versión {v}",
"settings.startupHelp": "Detalles del inicio",
"settings.section.updates": "Actualizaciones",
"settings.section.startup": "Inicio",
"settings.section.client": "Cliente y archivos",
"settings.section.service": "Mantenimiento",
"settings.section.interface": "Interfaz",
"settings.organized": "Gestiona actualizaciones, inicio y archivos del juego",
"settings.clientLink": "Archivos del cliente y datos del juego",
"history.title": "Historial de cambios",
"history.open": "Qué cambia",
"history.server": "Servidor",
"history.manager": "Manager",
"history.all": "Todas las versiones",
"history.range": "Para esta actualización",
"history.language": "Idioma de las notas",
"history.fallback": "Original en inglés: esta versión aún no está traducida",
"history.empty": "No hay notas publicadas para esta actualización",
"history.files": "Cambios en archivos",
"history.offline": "Historial guardado · disponible sin conexión",
"history.refreshed": "Historial publicado actualizado",
"history.experimental": "Los personajes portátiles son experimentales. Haz una copia de seguridad de tus personajes antes de usarlos.",
"settings.attention": "Una actualización requiere atención. Abre Actualizaciones para ver las opciones de recuperación.",
"races.unknownIds": "RaceID que ya no están en el catálogo: {ids}. Al guardar la lista revisada se eliminan estas restricciones antiguas.", "races.unknownIds": "RaceID que ya no están en el catálogo: {ids}. Al guardar la lista revisada se eliminan estas restricciones antiguas.",
"races.reviewCatalog": "El catálogo de razas ha cambiado o aún no está verificado. Revisa la lista y guárdala.", "races.reviewCatalog": "El catálogo de razas ha cambiado o aún no está verificado. Revisa la lista y guárdala.",
@@ -1040,6 +1066,23 @@ const es: Partial<Record<keyof typeof en, string>> = {
"registry.realmStoppedHint": "El reino está detenido. Inicia el servidor para que los jugadores entren y se registren las sesiones de personajes.", "registry.realmStoppedHint": "El reino está detenido. Inicia el servidor para que los jugadores entren y se registren las sesiones de personajes.",
"access.portableEnabled": "Permitir personajes portátiles", "access.portableEnabled": "Permitir personajes portátiles",
"access.portableEnabledHint": "Los jugadores pueden usar en este reino sus personajes guardados en Manager.", "access.portableEnabledHint": "Los jugadores pueden usar en este reino sus personajes guardados en Manager.",
"settings.publicServers": "Permitir consultar servidores públicos",
"settings.publicServersHint": "Si se desactiva, el gestor no solicita listas ni detalles de servidores públicos. Si se activa, carga la lista con Actualizar.",
"browse.disabled": "La consulta de servidores públicos está desactivada. Actívala en los ajustes para cargar el catálogo.",
"client.graphics.dxvk": "Usar gráficos compatibles (desactivar DXVK)",
"client.graphics.enhancements": "Desactivar mejoras gráficas adicionales",
"client.graphics.hint": "Cierra el juego antes de cambiar estos ajustes. Las actualizaciones mantienen desactivados los componentes gráficos elegidos.",
"settings.closeToTray": "Minimizar a la bandeja al cerrar la ventana",
"settings.closeToTrayHint": "Si se desactiva, cerrar la ventana sale del gestor. Volver a iniciarlo abre la ventana existente si ya está en ejecución.",
"overview.bots": "+ {n} bots",
"stop.force": "Forzar detención",
"stop.forceTitle": "¿Forzar la detención de este servidor?",
"stop.forceWarning": "Puede perderse el progreso sin guardar. Solo se detendrán los procesos verificados de este servidor. La base de datos seguirá activa hasta que se detengan todos los mundos.",
"stop.cancel": "Cancelar",
}; };
export default es; export default es;
+43
View File
@@ -3,6 +3,32 @@ import type en from "./en";
/** Français. Traduction provisoire ; à faire relire par un locuteur natif avant la publication. */ /** Français. Traduction provisoire ; à faire relire par un locuteur natif avant la publication. */
const fr: Partial<Record<keyof typeof en, string>> = { const fr: Partial<Record<keyof typeof en, string>> = {
"upd.preexistingCharacters": "Avant la mise à jour, {n} fiches de personnage n’avaient déjà pas de données de départ pour leur race/classe. Les fiches inchangées ont été conservées sans bloquer la mise à jour. Les détails sont dans le diagnostic ; ces incohérences anciennes n’ont pas été corrigées automatiquement.", "upd.preexistingCharacters": "Avant la mise à jour, {n} fiches de personnage n’avaient déjà pas de données de départ pour leur race/classe. Les fiches inchangées ont été conservées sans bloquer la mise à jour. Les détails sont dans le diagnostic ; ces incohérences anciennes n’ont pas été corrigées automatiquement.",
"settings.autoManager": "Télécharger les mises à jour en arrière-plan",
"settings.startServer": "Démarrer après la mise à jour",
"settings.version": "Version {v}",
"settings.startupHelp": "Détails du démarrage",
"settings.section.updates": "Mises à jour",
"settings.section.startup": "Démarrage",
"settings.section.client": "Client et fichiers",
"settings.section.service": "Maintenance",
"settings.section.interface": "Interface",
"settings.organized": "Gérer les mises à jour, le démarrage et les fichiers du jeu",
"settings.clientLink": "Fichiers du client et données du jeu",
"history.title": "Historique des changements",
"history.open": "Ce qui change",
"history.server": "Serveur",
"history.manager": "Manager",
"history.all": "Toutes les versions",
"history.range": "Pour cette mise à jour",
"history.language": "Langue des notes",
"history.fallback": "Original anglais : cette version n’est pas encore traduite",
"history.empty": "Aucune note publiée pour cette mise à jour",
"history.files": "Fichiers modifiés",
"history.offline": "Historique enregistré · disponible hors ligne",
"history.refreshed": "Historique publié actualisé",
"history.experimental": "Les personnages portables sont expérimentaux. Sauvegardez vos personnages avant utilisation.",
"settings.attention": "Une mise à jour nécessite votre attention. Ouvrez Mises à jour pour les options de récupération.",
"races.unknownIds": "RaceID absents de ce catalogue : {ids}. Sauvegarder la liste vérifiée supprime ces anciennes restrictions.", "races.unknownIds": "RaceID absents de ce catalogue : {ids}. Sauvegarder la liste vérifiée supprime ces anciennes restrictions.",
"races.reviewCatalog": "Le catalogue des races a changé ou n’a pas été vérifié. Vérifiez la liste et sauvegardez-la.", "races.reviewCatalog": "Le catalogue des races a changé ou n’a pas été vérifié. Vérifiez la liste et sauvegardez-la.",
@@ -1040,6 +1066,23 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"registry.realmStoppedHint": "Le royaume est arrêté. Démarrez le serveur pour permettre la connexion et le suivi des sessions des personnages.", "registry.realmStoppedHint": "Le royaume est arrêté. Démarrez le serveur pour permettre la connexion et le suivi des sessions des personnages.",
"access.portableEnabled": "Autoriser les personnages portables", "access.portableEnabled": "Autoriser les personnages portables",
"access.portableEnabledHint": "Les joueurs peuvent utiliser sur ce royaume leurs personnages enregistrés dans Manager.", "access.portableEnabledHint": "Les joueurs peuvent utiliser sur ce royaume leurs personnages enregistrés dans Manager.",
"settings.publicServers": "Autoriser la consultation des serveurs publics",
"settings.publicServersHint": "Si cette option est désactivée, le gestionnaire ne demande ni liste ni détails des serveurs publics. Sinon, chargez la liste avec Actualiser.",
"browse.disabled": "La consultation des serveurs publics est désactivée. Activez-la dans les paramètres pour charger le catalogue.",
"client.graphics.dxvk": "Utiliser le mode graphique compatible (désactiver DXVK)",
"client.graphics.enhancements": "Désactiver les améliorations graphiques supplémentaires",
"client.graphics.hint": "Fermez le jeu avant toute modification. Les mises à jour du client conservent les composants graphiques désactivés.",
"settings.closeToTray": "Réduire dans la zone de notification à la fermeture",
"settings.closeToTrayHint": "Sinon, fermer la fenêtre quitte le gestionnaire. Un nouveau lancement ouvre la fenêtre existante si le gestionnaire est déjà actif.",
"overview.bots": "+ {n} bots",
"stop.force": "Forcer l’arrêt",
"stop.forceTitle": "Forcer l’arrêt de ce serveur ?",
"stop.forceWarning": "La progression non enregistrée peut être perdue. Seuls les processus vérifiés de ce serveur seront arrêtés. La base de données reste active jusqu’à l’arrêt de tous les mondes.",
"stop.cancel": "Annuler",
}; };
export default fr; export default fr;
+44 -1
View File
@@ -3,6 +3,32 @@ import type en from "./en";
/** Русский. Черновой перевод; требует проверки носителем перед релизом. */ /** Русский. Черновой перевод; требует проверки носителем перед релизом. */
const ru: Partial<Record<keyof typeof en, string>> = { const ru: Partial<Record<keyof typeof en, string>> = {
"upd.preexistingCharacters": "До обновления у {n} записей персонажей уже отсутствовали стартовые данные расы/класса. Неизменившиеся записи сохранены и не заблокировали обновление. Подробности есть в диагностике; эти старые несоответствия автоматически не исправлялись.", "upd.preexistingCharacters": "До обновления у {n} записей персонажей уже отсутствовали стартовые данные расы/класса. Неизменившиеся записи сохранены и не заблокировали обновление. Подробности есть в диагностике; эти старые несоответствия автоматически не исправлялись.",
"settings.autoManager": "Скачивать обновления в фоне",
"settings.startServer": "Запустить после обновления",
"settings.version": "Версия {v}",
"settings.startupHelp": "Подробнее о запуске",
"settings.section.updates": "Обновления",
"settings.section.startup": "Запуск",
"settings.section.client": "Клиент и файлы",
"settings.section.service": "Обслуживание",
"settings.section.interface": "Интерфейс",
"settings.organized": "Обновления, запуск сервера и файлы игры",
"settings.clientLink": "Файлы клиента и игровые данные",
"history.title": "История изменений",
"history.open": "Что изменится",
"history.server": "Сервер",
"history.manager": "Manager",
"history.all": "Все версии",
"history.range": "К обновлению",
"history.language": "Язык записей",
"history.fallback": "Английский оригинал: этот выпуск пока не переведён",
"history.empty": "Для этого обновления пока нет опубликованных записей",
"history.files": "Изменения файлов",
"history.offline": "Сохранённая история · доступна без сети",
"history.refreshed": "Опубликованная история обновлена",
"history.experimental": "Переносимые персонажи — экспериментальная функция. Перед использованием сохраните резервную копию персонажей.",
"settings.attention": "Обновление требует внимания. Откройте «Обновления», чтобы выбрать способ восстановления.",
"races.unknownIds": "RaceID, которых больше нет в каталоге: {ids}. Сохранение проверенного списка удалит эти старые ограничения.", "races.unknownIds": "RaceID, которых больше нет в каталоге: {ids}. Сохранение проверенного списка удалит эти старые ограничения.",
"races.reviewCatalog": "Каталог рас изменился или ещё не проверен. Проверьте список и сохраните его перед применением ограничений.", "races.reviewCatalog": "Каталог рас изменился или ещё не проверен. Проверьте список и сохраните его перед применением ограничений.",
@@ -1107,7 +1133,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"browse.offlineWarning": "Сервер сейчас не запущен хостом. Игра переносимым персонажем станет доступна, когда владелец включит сервер.", "browse.offlineWarning": "Сервер сейчас не запущен хостом. Игра переносимым персонажем станет доступна, когда владелец включит сервер.",
"browse.play": "Играть", "browse.play": "Играть",
"browse.playSoon": "Вход на сервер появится вместе с поддержкой аккаунтов на следующем шаге.", "browse.playSoon": "Вход на сервер появится вместе с поддержкой аккаунтов на следующем шаге.",
"registry.title": "Публичный список", "registry.title": "Публичные реалмы",
"registry.dialogTitle": "Публичный список · {realm}", "registry.dialogTitle": "Публичный список · {realm}",
"registry.publishAll": "Опубликовать все реалмы", "registry.publishAll": "Опубликовать все реалмы",
"registry.publishAllText": "Одно описание, язык и регион для каждого реалма, которого ещё нет в списке. Реалмы публикуются под названием сервера; к реалмам, которые запускаются рядом с основным, добавляется название реалма.", "registry.publishAllText": "Одно описание, язык и регион для каждого реалма, которого ещё нет в списке. Реалмы публикуются под названием сервера; к реалмам, которые запускаются рядом с основным, добавляется название реалма.",
@@ -1233,6 +1259,23 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"access.relay": "Relay", "access.relay": "Relay",
"access.relayUp": "Игровой relay подключён", "access.relayUp": "Игровой relay подключён",
"access.relayDown": "Игровой relay не подключён", "access.relayDown": "Игровой relay не подключён",
"settings.publicServers": "Разрешить просмотр публичных серверов",
"settings.publicServersHint": "Если выключено, менеджер не запрашивает списки и сведения о публичных серверах. Если включено, список загружается кнопкой «Обновить».",
"browse.disabled": "Просмотр публичных серверов отключён. Включите его в настройках, чтобы загрузить каталог.",
"client.graphics.dxvk": "Совместимый режим графики (отключить DXVK)",
"client.graphics.enhancements": "Отключить дополнительные графические улучшения",
"client.graphics.hint": "Перед изменением закройте игру. Обновление клиента сохраняет отключённые графические компоненты.",
"settings.closeToTray": "Сворачивать в трей при закрытии окна",
"settings.closeToTrayHint": "Если выключено, закрытие окна завершает менеджер. Повторный запуск открывает уже работающий экземпляр.",
"overview.bots": "+ {n} ботов",
"stop.force": "Принудительно остановить",
"stop.forceTitle": "Принудительно остановить этот сервер?",
"stop.forceWarning": "Несохранённый прогресс игроков может быть потерян. Будут остановлены только проверенные процессы этого сервера. База данных останется работать до остановки всех миров.",
"stop.cancel": "Отмена",
}; };
export default ru; export default ru;
+43
View File
@@ -1,6 +1,32 @@
/** Simplified Chinese localization (zh-CN) */ /** Simplified Chinese localization (zh-CN) */
const zh = { const zh = {
"upd.preexistingCharacters": "更新前已有 {n} 条角色记录缺少种族/职业初始数据。未变化的记录已保留,不会阻止更新。详情已保存到诊断报告;这些既有问题尚未自动修复。", "upd.preexistingCharacters": "更新前已有 {n} 条角色记录缺少种族/职业初始数据。未变化的记录已保留,不会阻止更新。详情已保存到诊断报告;这些既有问题尚未自动修复。",
"settings.autoManager": "在后台下载更新",
"settings.startServer": "更新后启动",
"settings.version": "版本 {v}",
"settings.startupHelp": "启动详情",
"settings.section.updates": "更新",
"settings.section.startup": "启动",
"settings.section.client": "客户端与文件",
"settings.section.service": "维护",
"settings.section.interface": "界面",
"settings.organized": "管理更新、服务器启动与游戏文件",
"settings.clientLink": "客户端文件与游戏数据",
"history.title": "更新日志",
"history.open": "更新内容",
"history.server": "服务器",
"history.manager": "Manager",
"history.all": "所有版本",
"history.range": "本次更新",
"history.language": "日志语言",
"history.fallback": "英文原文:此版本尚未翻译",
"history.empty": "本次更新暂无已发布的日志",
"history.files": "文件变更",
"history.offline": "已保存的日志 · 离线可用",
"history.refreshed": "已刷新发布日志",
"history.experimental": "可携带角色功能仍处于实验阶段。使用前请备份角色。",
"settings.attention": "某次更新需要处理。请打开“更新”查看恢复选项。",
"races.unknownIds": "此目录中已不存在的种族 ID:{ids}。保存检查后的列表将移除这些旧限制。", "races.unknownIds": "此目录中已不存在的种族 ID:{ids}。保存检查后的列表将移除这些旧限制。",
"races.reviewCatalog": "种族目录已更改或尚未验证。请检查列表并保存后再应用限制。", "races.reviewCatalog": "种族目录已更改或尚未验证。请检查列表并保存后再应用限制。",
@@ -1042,6 +1068,23 @@ const zh = {
"registry.realmStoppedHint": "世界当前已停止。请启动服务器,以便玩家加入并跟踪角色会话。", "registry.realmStoppedHint": "世界当前已停止。请启动服务器,以便玩家加入并跟踪角色会话。",
"access.portableEnabled": "允许便携角色", "access.portableEnabled": "允许便携角色",
"access.portableEnabledHint": "允许玩家在此服务器使用保存在 Manager 中的角色。", "access.portableEnabledHint": "允许玩家在此服务器使用保存在 Manager 中的角色。",
"settings.publicServers": "允许浏览公共服务器",
"settings.publicServersHint": "关闭后,管理器不会请求公共服务器列表或详情。启用后,点击“刷新”加载列表。",
"browse.disabled": "公共服务器浏览已关闭。请在设置中启用以加载目录。",
"client.graphics.dxvk": "使用兼容图形模式(禁用 DXVK)",
"client.graphics.enhancements": "禁用额外图形增强",
"client.graphics.hint": "更改前请关闭游戏。客户端更新会保留已禁用的图形组件。",
"settings.closeToTray": "关闭窗口时最小化到托盘",
"settings.closeToTrayHint": "关闭此选项后,关闭窗口将退出管理器。再次启动会打开已运行的窗口。",
"overview.bots": "+ {n} 个机器人",
"stop.force": "强制停止",
"stop.forceTitle": "强制停止此服务器?",
"stop.forceWarning": "玩家未保存的进度可能丢失。只会停止经验证属于此服务器的进程。所有世界停止后才会关闭数据库。",
"stop.cancel": "取消",
} as const; } as const;
export default zh; export default zh;
+3 -3
View File
@@ -16,10 +16,10 @@
--font-sans: "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif; --font-sans: "Segoe UI Variable Text", "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
} }
/* Everything is sized in rem, so scaling the root font grows the whole interface with the window /* Window size changes layout, not UI density. Keep rem tied to the user's default
(16px up to about 1280px wide, then gradually larger; capped at 26px). */ font size; browser zoom and operating-system display scaling still apply. */
html { html {
font-size: clamp(16px, calc(0.75vw + 6.4px), 26px); font-size: 100%;
} }
html, html,
+3
View File
@@ -496,6 +496,7 @@ export const api = {
forget: (id: string) => invoke<void>("forget_server", { id }), forget: (id: string) => invoke<void>("forget_server", { id }),
status: (id: string) => invoke<StatusView>("server_status", { id }), status: (id: string) => invoke<StatusView>("server_status", { id }),
start: (id: string) => invoke<DriverOutcome>("start_server", { id }), start: (id: string) => invoke<DriverOutcome>("start_server", { id }),
forceStop: (id: string) => invoke<DriverOutcome>("force_stop_server", { id }),
stop: (id: string) => invoke<DriverOutcome>("stop_server", { id }), stop: (id: string) => invoke<DriverOutcome>("stop_server", { id }),
settings: (id: string, scope: Scope) => invoke<SettingsView>("get_settings", { id, scope }), settings: (id: string, scope: Scope) => invoke<SettingsView>("get_settings", { id, scope }),
save: (id: string, scope: Scope, changes: Record<string, JsonValue>) => invoke<SaveReport>("save_settings", { id, scope, changes }), save: (id: string, scope: Scope, changes: Record<string, JsonValue>) => invoke<SaveReport>("save_settings", { id, scope, changes }),
@@ -560,6 +561,8 @@ export const api = {
performance: (id: string) => invoke<Performance | null>("get_performance", { id }), performance: (id: string) => invoke<Performance | null>("get_performance", { id }),
companionSizes: () => invoke<CompanionSizes>("companion_sizes"), companionSizes: () => invoke<CompanionSizes>("companion_sizes"),
addCompanions: (id: string, count: number) => invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count }), addCompanions: (id: string, count: number) => invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count }),
clientGraphics: (id: string) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_graphics", { id }),
clientSetGraphics: (id: string, name: string, disabled: boolean) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_set_graphics", { id, name, disabled }),
clientInfo: (id: string) => invoke<ClientInfo | null>("client_info", { id }), clientInfo: (id: string) => invoke<ClientInfo | null>("client_info", { id }),
setClient: (id: string, path: string) => invoke<ClientInfo>("set_client", { id, path }), setClient: (id: string, path: string) => invoke<ClientInfo>("set_client", { id, path }),
setRealmlist: (id: string, host: string) => invoke<string[]>("client_realmlist", { id, host }), setRealmlist: (id: string, host: string) => invoke<string[]>("client_realmlist", { id, host }),
+2
View File
@@ -69,6 +69,8 @@ export interface BrowseParams {
} }
export const browse = { export const browse = {
enabled: () => invoke<boolean>("browse_enabled"),
setEnabled: (enabled: boolean) => invoke<void>("browse_set_enabled", { enabled }),
list: (params: BrowseParams) => invoke<RealmPage>("browse_list", { params }), list: (params: BrowseParams) => invoke<RealmPage>("browse_list", { params }),
detail: (realmId: string) => invoke<RealmDetail>("browse_detail", { realmId }), detail: (realmId: string) => invoke<RealmDetail>("browse_detail", { realmId }),
modules: () => invoke<ModuleInfo[]>("module_catalog"), modules: () => invoke<ModuleInfo[]>("module_catalog"),
+16
View File
@@ -0,0 +1,16 @@
import manager from "../../changelog/history.json";
import server from "@/data/server-history.json";
import translations from "@/data/latest-note-translations.json";
import type { Locale } from "@/i18n";
import { localizeNotes, type Component, type History, type Release } from "./releaseHistoryModel";
export { compareVersions, releasesForUpdate } from "./releaseHistoryModel";
export type { Component, History } from "./releaseHistoryModel";
export const bundledHistories: Record<Component, History> = { manager: manager as History, server: server as History };
export const repositories = { manager: "Corfirean/coa-server-manager", server: "Corfirean/coa-server-build" };
export function translatedNotes(component: Component, release: Release, locale: Locale): { notes: string[]; fallback: boolean } {
if (locale === "en") return { notes: release.notes, fallback: false };
const dict = (translations[component] as Record<string, Record<string, string>>)[locale] ?? {};
return localizeNotes(release.notes, dict);
}
+23
View File
@@ -0,0 +1,23 @@
export type Component = "server" | "manager";
export interface Release { version: string; tag: string; date: string; notes: string[]; prerelease?: boolean; experimentalFeatures?: string[] }
export interface History { component: Component; releases: Release[]; source?: "remote" | "cache" }
// Only stable numeric versions participate in an installed-to-target update range.
export function compareVersions(a: string, b: string): number {
const aa = a.split(".").map(Number), bb = b.split(".").map(Number);
for (let i = 0; i < Math.max(aa.length, bb.length); i++) {
const d = (aa[i] ?? 0) - (bb[i] ?? 0);
if (d) return d;
}
return 0;
}
export function releasesForUpdate(releases: Release[], from?: string, to?: string): Release[] {
if (!to || !/^\d+(\.\d+)+$/.test(to)) return [];
const knownFrom = from && /^\d+(\.\d+)+$/.test(from);
return releases.filter(r => !r.prerelease && /^\d+(\.\d+)+$/.test(r.version) &&
(knownFrom ? compareVersions(r.version, from) > 0 && compareVersions(r.version, to) <= 0 : r.version === to));
}
export function localizeNotes(notes: string[], dictionary: Record<string, string> = {}) {
const complete = notes.every(note => dictionary[note]);
return { notes: complete ? notes.map(note => dictionary[note]) : notes, fallback: !complete };
}
+14 -2
View File
@@ -1,3 +1,4 @@
import { invoke } from "@tauri-apps/api/core";
import { useSyncExternalStore } from "react"; import { useSyncExternalStore } from "react";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import { check, type Update } from "@tauri-apps/plugin-updater"; import { check, type Update } from "@tauri-apps/plugin-updater";
@@ -93,9 +94,11 @@ export async function installNow(): Promise<void> {
if (state.phase !== "ready") await downloadPending(); if (state.phase !== "ready") await downloadPending();
if (state.phase !== "ready") return; if (state.phase !== "ready") return;
set({ phase: "installing" }); set({ phase: "installing" });
await invoke("manager_installing", { enabled: true });
await update.install(); await update.install();
await relaunch(); await relaunch();
} catch (e) { } catch (e) {
await invoke("manager_installing", { enabled: false }).catch(() => {});
set({ phase: "error", error: String(e) }); set({ phase: "error", error: String(e) });
} }
} }
@@ -107,14 +110,23 @@ export function installOnClose(): () => void {
const win = getCurrentWindow(); const win = getCurrentWindow();
void win void win
.onCloseRequested(async (event) => { .onCloseRequested(async (event) => {
if (state.phase !== "ready" || !update || !autoUpdateEnabled()) return;
event.preventDefault(); event.preventDefault();
if (state.phase !== "ready" || !update || !autoUpdateEnabled()) {
await invoke("close_manager");
return;
}
if (await invoke<boolean>("close_to_tray")) {
await invoke("close_manager");
return;
}
try { try {
set({ phase: "installing" }); set({ phase: "installing" });
await invoke("manager_installing", { enabled: true });
await update.install(); await update.install();
} catch (e) { } catch (e) {
await invoke("manager_installing", { enabled: false }).catch(() => {});
set({ phase: "error", error: String(e) }); set({ phase: "error", error: String(e) });
await win.destroy(); await invoke("close_manager");
} }
}) })
.then((un) => { .then((un) => {
+38
View File
@@ -0,0 +1,38 @@
export class ServerLifecycle {
private wasRunning = false;
private maintenance = false;
private stopRequested = false;
private operationPending = false;
request(action: "starting" | "stopping" | "restarting") {
this.stopRequested = action !== "starting";
this.operationPending = true;
}
complete(action: "starting" | "stopping" | "restarting") {
this.operationPending = false;
if (action !== "stopping") { this.stopRequested = false; this.wasRunning = false; }
}
beginMaintenance() { this.maintenance = true; this.wasRunning = false; }
endMaintenance() { this.maintenance = false; this.wasRunning = false; }
observe(running: boolean, busy: boolean, updating: boolean): boolean {
if (this.maintenance) { this.wasRunning = false; return false; }
if (running) { this.wasRunning = true; return false; }
if (this.stopRequested || updating || this.operationPending) {
this.wasRunning = false;
if (!busy && !this.operationPending) this.stopRequested = false;
return false;
}
if (this.wasRunning && !busy) { this.wasRunning = false; return true; }
return false;
}
}
const lifecycles = new Map<string, ServerLifecycle>();
export function serverLifecycle(id: string) {
let lifecycle = lifecycles.get(id);
if (!lifecycle) { lifecycle = new ServerLifecycle(); lifecycles.set(id, lifecycle); }
return lifecycle;
}
+8
View File
@@ -1,3 +1,4 @@
import { serverLifecycle } from "@/lib/serverLifecycle";
import { useSyncExternalStore } from "react"; import { useSyncExternalStore } from "react";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api"; import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
@@ -30,6 +31,11 @@ const listeners = new Set<() => void>();
export const CHECK_EVERY_MS = 5 * 60 * 1000; export const CHECK_EVERY_MS = 5 * 60 * 1000;
const get = (id: string) => states.get(id) ?? EMPTY; const get = (id: string) => states.get(id) ?? EMPTY;
export function serverUpdateBlocksRestart(id: string): boolean {
const state = get(id);
return state.applying || state.stateError !== null || !!(state.result && "pending" in state.result);
}
function set(id: string, next: Partial<ServerUpdateState>) { function set(id: string, next: Partial<ServerUpdateState>) {
states.set(id, { ...get(id), ...next }); states.set(id, { ...get(id), ...next });
listeners.forEach((l) => l()); listeners.forEach((l) => l());
@@ -89,6 +95,7 @@ export async function applyServerUpdate(id: string, opts?: { choices: Record<str
// The update stops a running server and proves the new build by starting it; a server that was stopped stays stopped // The update stops a running server and proves the new build by starting it; a server that was stopped stays stopped
// unless the owner asked for it to start. // unless the owner asked for it to start.
const wasRunning = await api.status(id).then((s) => [s.observed.mysql, s.observed.auth, s.observed.world].some((x) => x.state === "running" || x.state === "starting")).catch(() => true); const wasRunning = await api.status(id).then((s) => [s.observed.mysql, s.observed.auth, s.observed.world].some((x) => x.state === "running" || x.state === "starting")).catch(() => true);
serverLifecycle(id).beginMaintenance();
set(id, { applying: true, step: null, percent: 0, error: null, uiError: null, result: null }); set(id, { applying: true, step: null, percent: 0, error: null, uiError: null, result: null });
let un: (() => void) | undefined; let un: (() => void) | undefined;
try { try {
@@ -110,6 +117,7 @@ export async function applyServerUpdate(id: string, opts?: { choices: Record<str
try { try {
await refreshServerUpdateState(id); await refreshServerUpdateState(id);
} catch { /* The state error remains visible and prevents another apply. */ } } catch { /* The state error remains visible and prevents another apply. */ }
serverLifecycle(id).endMaintenance();
set(id, { applying: false }); set(id, { applying: false });
void checkServerUpdate(id); void checkServerUpdate(id);
} }
+11 -33
View File
@@ -1,12 +1,12 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { getVersion } from "@tauri-apps/api/app"; import { getVersion } from "@tauri-apps/api/app";
import { Loader2 } from "lucide-react"; import { Loader2, RefreshCw, Monitor } from "lucide-react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
import { useT } from "@/i18n"; import { useT } from "@/i18n";
import { autoUpdateEnabled, installNow, lookForUpdate, setAutoUpdate, useSelfUpdate } from "@/lib/selfUpdate"; import { autoUpdateEnabled, installNow, lookForUpdate, setAutoUpdate, useSelfUpdate } from "@/lib/selfUpdate";
export function AboutCard() { export function AboutCard({ onHistory }: { onHistory?: () => void }) {
const t = useT(); const t = useT();
const s = useSelfUpdate(); const s = useSelfUpdate();
const [version, setVersion] = useState(""); const [version, setVersion] = useState("");
@@ -21,37 +21,12 @@ export function AboutCard() {
return ( return (
<Card className="mt-6 p-6"> <Card className="mt-6 p-6">
<h2 className="font-semibold">{t("app.name")}</h2> <div className="flex items-start justify-between gap-3">
<p className="mt-1 text-sm text-muted">{t("about.version", { v: version || "…" })}</p> <div><h2 className="flex items-center gap-2 font-semibold"><Monitor className="h-4 w-4 text-gold" aria-hidden />{t("history.manager")}</h2><p className="mt-2 text-sm text-muted">{t("settings.version", { v: version || "…" })}</p></div>
<Button size="sm" disabled={busy} aria-label={t("about.check")} title={t("about.check")} onClick={() => { setAsked(true); void lookForUpdate({ download: false }); }}><RefreshCw className={`h-4 w-4 ${s.phase === "checking" ? "animate-spin" : ""}`} aria-hidden /></Button>
<label className="mt-3 flex cursor-pointer items-start gap-2 text-sm"> </div>
<input <p className="mt-3 text-xs text-muted">{t("about.autoHint")}</p>
type="checkbox"
className="mt-1"
checked={auto}
onChange={(e) => {
setAuto(e.target.checked);
setAutoUpdate(e.target.checked);
}}
/>
<span>
{t("about.auto")}
<span className="block text-xs text-muted">{t("about.autoHint")}</span>
</span>
</label>
<div className="mt-4 flex flex-wrap items-center gap-3"> <div className="mt-4 flex flex-wrap items-center gap-3">
<Button
size="sm"
disabled={busy}
onClick={() => {
setAsked(true);
void lookForUpdate({ download: false });
}}
>
{s.phase === "checking" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("about.check")}
</Button>
{s.version && s.phase !== "current" && ( {s.version && s.phase !== "current" && (
<Button size="sm" variant="primary" disabled={busy} onClick={() => void installNow()}> <Button size="sm" variant="primary" disabled={busy} onClick={() => void installNow()}>
{(s.phase === "downloading" || s.phase === "installing") && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />} {(s.phase === "downloading" || s.phase === "installing") && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
@@ -64,7 +39,7 @@ export function AboutCard() {
</span> </span>
)} )}
</div> </div>
{s.version && s.notes && s.phase !== "current" && <p className="mt-3 whitespace-pre-line text-sm text-muted">{s.notes}</p>} {onHistory ? <button className="mt-3 cursor-pointer text-sm text-gold hover:underline" onClick={onHistory}>{t(s.version && s.phase !== "current" ? "history.open" : "history.title")}</button> : s.version && s.notes && s.phase !== "current" && <p className="mt-3 whitespace-pre-line text-sm text-muted">{s.notes}</p>}
{s.phase === "ready" && <p className="mt-3 text-sm text-ok" role="status">{t("selfupd.onClose")}</p>} {s.phase === "ready" && <p className="mt-3 text-sm text-ok" role="status">{t("selfupd.onClose")}</p>}
{asked && s.phase === "current" && <p className="mt-3 text-sm text-ok" role="status">{t("about.upToDate")}</p>} {asked && s.phase === "current" && <p className="mt-3 text-sm text-ok" role="status">{t("about.upToDate")}</p>}
{s.phase === "error" && ( {s.phase === "error" && (
@@ -73,6 +48,9 @@ export function AboutCard() {
{s.error && <p className="selectable mt-1 break-all text-xs text-muted">{s.error}</p>} {s.error && <p className="selectable mt-1 break-all text-xs text-muted">{s.error}</p>}
</div> </div>
)} )}
<label className="mt-5 flex cursor-pointer items-center justify-between gap-3 border-t border-line pt-4 text-sm" title={t("about.auto")}>
<span>{t("settings.autoManager")}</span><input type="checkbox" role="switch" aria-description={t("about.auto")} checked={auto} onChange={e => { setAuto(e.target.checked); setAutoUpdate(e.target.checked); }} className="h-4 w-4 accent-[#c9a24a]" />
</label>
</Card> </Card>
); );
} }
+15 -3
View File
@@ -193,6 +193,17 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog:
} }
export function BrowsePage() { export function BrowsePage() {
const { t } = useI18n();
const [enabled, setEnabled] = useState<boolean | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => { void browse.enabled().then(setEnabled).catch(e => setError(asUiError(e).technical)); }, []);
if (error) return <p role="alert" className="text-bad">{error}</p>;
if (enabled === null) return <Loader2 className="h-5 w-5 animate-spin" aria-label={t("portable.make.loading")} />;
if (!enabled) return <div><h1 className="text-2xl font-semibold">{t("browse.title")}</h1><p className="mt-2 text-muted">{t("browse.disabled")}</p></div>;
return <EnabledBrowsePage />;
}
function EnabledBrowsePage() {
const { t } = useI18n(); const { t } = useI18n();
const { status } = useRegistryStatus(5000); const { status } = useRegistryStatus(5000);
const [q, setQ] = useState(""); const [q, setQ] = useState("");
@@ -213,6 +224,7 @@ export function BrowsePage() {
const [preferredSaved, setPreferredSaved] = useState(""); const [preferredSaved, setPreferredSaved] = useState("");
const [preferredNote, setPreferredNote] = useState<string | null>(null); const [preferredNote, setPreferredNote] = useState<string | null>(null);
const ticket = useRef(0); const ticket = useRef(0);
const [requested, setRequested] = useState(false);
useEffect(() => { void control.status().then((c) => { setPreferred(c.preferred_username); setPreferredSaved(c.preferred_username); }).catch(() => {}); }, []); useEffect(() => { void control.status().then((c) => { setPreferred(c.preferred_username); setPreferredSaved(c.preferred_username); }).catch(() => {}); }, []);
useEffect(() => { void browse.modules().then((m) => setCatalog(Object.fromEntries(m.map((x) => [x.id, x])))).catch(() => {}); }, []); useEffect(() => { void browse.modules().then((m) => setCatalog(Object.fromEntries(m.map((x) => [x.id, x])))).catch(() => {}); }, []);
@@ -244,10 +256,10 @@ export function BrowsePage() {
}, [params]); }, [params]);
useEffect(() => { useEffect(() => {
if (!status?.url) return; if (!requested || !status?.url) return;
const timer = setTimeout(() => void load(), q ? 300 : 0); const timer = setTimeout(() => void load(), q ? 300 : 0);
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, [load, status?.url]); // eslint-disable-line react-hooks/exhaustive-deps }, [load, status?.url, requested]); // eslint-disable-line react-hooks/exhaustive-deps
function onSort(k: SortKey) { function onSort(k: SortKey) {
if (k === sort) setOrder((o) => (o === "asc" ? "desc" : "asc")); if (k === sort) setOrder((o) => (o === "asc" ? "desc" : "asc"));
@@ -263,7 +275,7 @@ export function BrowsePage() {
<h1 className="text-2xl font-semibold">{t("browse.title")}</h1> <h1 className="text-2xl font-semibold">{t("browse.title")}</h1>
<p className="mt-1 text-sm text-muted">{t("browse.text")}</p> <p className="mt-1 text-sm text-muted">{t("browse.text")}</p>
</div> </div>
<Button size="sm" onClick={() => void load()} disabled={loading || noUrl}>{loading ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : <RefreshCw className="h-4 w-4" aria-hidden />}{t("browse.refresh")}</Button> <Button size="sm" onClick={() => { if (requested) void load(); else setRequested(true); }} disabled={loading || noUrl}>{loading ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : <RefreshCw className="h-4 w-4" aria-hidden />}{t("browse.refresh")}</Button>
</div> </div>
{noUrl && <p className="mt-2 text-sm text-warn">{t("browse.noUrl")}</p>} {noUrl && <p className="mt-2 text-sm text-warn">{t("browse.noUrl")}</p>}
+2
View File
@@ -3,6 +3,7 @@ import { listen } from "@tauri-apps/api/event";
import { open } from "@tauri-apps/plugin-dialog"; import { open } from "@tauri-apps/plugin-dialog";
import { api, asUiError, type ClientInfo, type ClientStatus, type UiError } from "@/lib/api"; import { api, asUiError, type ClientInfo, type ClientStatus, type UiError } from "@/lib/api";
import { checkClient } from "@/lib/clientUpdate"; import { checkClient } from "@/lib/clientUpdate";
import { ClientGraphics } from "./ClientGraphics";
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog"; import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
@@ -95,6 +96,7 @@ export function ClientCard({ serverId, remote = false }: { serverId: string; rem
<dt className="text-muted">{t("client.otherAddons")}</dt> <dt className="text-muted">{t("client.otherAddons")}</dt>
<dd>{t("client.leftAsIs", { n: info.other_addons })}</dd> <dd>{t("client.leftAsIs", { n: info.other_addons })}</dd>
</dl> </dl>
<ClientGraphics key={info.path} serverId={serverId} />
{!remote && ( {!remote && (
<label className="mt-4 flex cursor-pointer items-center gap-2 text-sm"> <label className="mt-4 flex cursor-pointer items-center gap-2 text-sm">
<input type="checkbox" checked={playAfter} onChange={(e) => setPlayAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" /> <input type="checkbox" checked={playAfter} onChange={(e) => setPlayAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
+24
View File
@@ -0,0 +1,24 @@
import { useEffect, useState } from "react";
import { api, asUiError } from "@/lib/api";
import { checkClient } from "@/lib/clientUpdate";
import { useI18n } from "@/i18n";
export function ClientGraphics({ serverId }: { serverId: string }) {
const { t } = useI18n();
const [state, setState] = useState<{ dxvk_disabled: boolean; enhancements_disabled: boolean } | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => { void api.clientGraphics(serverId).then(setState).catch(e => setError(asUiError(e).technical)); }, [serverId]);
async function change(name: string, disabled: boolean) {
setBusy(true); setError(null);
try { setState(await api.clientSetGraphics(serverId, name, disabled)); await checkClient(serverId); }
catch (e) { setError(asUiError(e).technical); }
finally { setBusy(false); }
}
return <div className="mt-5 space-y-3 border-t border-line pt-4">
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={state?.dxvk_disabled ?? false} disabled={!state || busy} onChange={e => void change("d3d9.dll", e.target.checked)} />{t("client.graphics.dxvk")}</label>
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={state?.enhancements_disabled ?? false} disabled={!state || busy} onChange={e => void change("dxgi.dll", e.target.checked)} />{t("client.graphics.enhancements")}</label>
<p className="text-xs text-muted">{t("client.graphics.hint")}</p>
{error && <p className="text-sm text-bad" role="alert">{error}</p>}
</div>;
}
+28
View File
@@ -0,0 +1,28 @@
import { useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { useI18n } from "@/i18n";
export function ForceStopDialog({ onCancel, onConfirm }: { onCancel: () => void; onConfirm: () => void }) {
const { t } = useI18n();
const panel = useRef<HTMLDivElement>(null);
useEffect(() => {
const previous = document.activeElement;
panel.current?.querySelector<HTMLButtonElement>("button")?.focus();
return () => { if (previous instanceof HTMLElement) previous.focus(); };
}, []);
return <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-5">
<div ref={panel} role="alertdialog" aria-modal="true" aria-labelledby="force-stop-title" aria-describedby="force-stop-warning" className="w-full max-w-lg rounded-lg border border-bad/40 bg-card p-6" onKeyDown={e => {
if (e.key === "Escape") { e.preventDefault(); onCancel(); }
if (e.key === "Tab") {
const buttons = panel.current?.querySelectorAll<HTMLButtonElement>("button");
if (!buttons?.length) return;
if (e.shiftKey && document.activeElement === buttons[0]) { e.preventDefault(); buttons[buttons.length - 1].focus(); }
else if (!e.shiftKey && document.activeElement === buttons[buttons.length - 1]) { e.preventDefault(); buttons[0].focus(); }
}
}}>
<h2 id="force-stop-title" className="text-lg font-semibold">{t("stop.forceTitle")}</h2>
<p id="force-stop-warning" className="mt-3 text-sm text-muted">{t("stop.forceWarning")}</p>
<div className="mt-5 flex justify-end gap-3"><Button onClick={onCancel}>{t("stop.cancel")}</Button><Button variant="secondary" onClick={onConfirm}>{t("stop.force")}</Button></div>
</div>
</div>;
}
+40 -41
View File
@@ -1,3 +1,6 @@
import { ForceStopDialog } from "./ForceStopDialog";
import { serverLifecycle } from "@/lib/serverLifecycle";
import { serverUpdateBlocksRestart } from "@/lib/serverUpdate";
import { dismissClientJob, startClientUpdate, stopClientJob, syncClient, useClientJob } from "@/lib/clientJob"; import { dismissClientJob, startClientUpdate, stopClientJob, syncClient, useClientJob } from "@/lib/clientJob";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { AlertTriangle, Loader2, X } from "lucide-react"; import { AlertTriangle, Loader2, X } from "lucide-react";
@@ -15,6 +18,7 @@ import { PublishRealmDialog } from "@/screens/PublishDialog";
import { useRegistryStatus } from "@/lib/registry"; import { useRegistryStatus } from "@/lib/registry";
import { usePublishRealms, type PublishRealm } from "@/lib/publishRealms"; import { usePublishRealms, type PublishRealm } from "@/lib/publishRealms";
import { useAutoRestart } from "@/lib/autoRestartPrefs"; import { useAutoRestart } from "@/lib/autoRestartPrefs";
import { SplitButton } from "@/components/ui/split-button";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
@@ -90,6 +94,8 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
}, [bothWorlds, server.id]); }, [bothWorlds, server.id]);
const [action, setAction] = useState<Action>(null); const [action, setAction] = useState<Action>(null);
const [realmBusy, setRealmBusy] = useState(false); const [realmBusy, setRealmBusy] = useState(false);
const [stopFailed, setStopFailed] = useState(false);
const [confirmForce, setConfirmForce] = useState(false);
const [failure, setFailure] = useState<Failure | null>(null); const [failure, setFailure] = useState<Failure | null>(null);
const [showDetails, setShowDetails] = useState(false); const [showDetails, setShowDetails] = useState(false);
const [pop, setPop] = useState<Population | null>(null); const [pop, setPop] = useState<Population | null>(null);
@@ -130,8 +136,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
const [crashLoopPaused, setCrashLoopPaused] = useState(false); const [crashLoopPaused, setCrashLoopPaused] = useState(false);
const [crashRestartNotice, setCrashRestartNotice] = useState<string | null>(null); const [crashRestartNotice, setCrashRestartNotice] = useState<string | null>(null);
const userStoppedRef = useRef(false); const lifecycle = serverLifecycle(server.id);
const wasWorldRunningRef = useRef(false);
const actionRef = useRef<Action>(null); const actionRef = useRef<Action>(null);
const crashTimestampsRef = useRef<number[]>([]); const crashTimestampsRef = useRef<number[]>([]);
const pollRef = useRef<() => Promise<void>>(undefined); const pollRef = useRef<() => Promise<void>>(undefined);
@@ -167,10 +172,9 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
const run = useCallback( const run = useCallback(
async (kind: Exclude<Action, null>) => { async (kind: Exclude<Action, null>) => {
if (kind === "stopping") { setStopFailed(false);
userStoppedRef.current = true; lifecycle.request(kind);
} else { if (kind !== "stopping") {
userStoppedRef.current = false;
setCrashLoopPaused(false); setCrashLoopPaused(false);
setCrashRestartNotice(null); setCrashRestartNotice(null);
} }
@@ -180,8 +184,8 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
actionRef.current = kind; actionRef.current = kind;
try { try {
if (kind !== "starting") { if (kind !== "starting") {
const out = await api.stop(server.id); const out = await api.stop(server.id).catch(e => { setStopFailed(true); throw e; });
if (!out.ok) throw { human: out.human, technical: out.output }; if (!out.ok) { setStopFailed(true); throw { human: out.human, technical: out.output }; }
} }
if (kind !== "stopping") { if (kind !== "stopping") {
setAction("starting"); setAction("starting");
@@ -193,6 +197,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
const ui = asUiError(e); const ui = asUiError(e);
setFailure({ human: ui.human ?? asUiError(String(e)).human, technical: ui.technical }); setFailure({ human: ui.human ?? asUiError(String(e)).human, technical: ui.technical });
} finally { } finally {
lifecycle.complete(kind);
setAction(null); setAction(null);
actionRef.current = null; actionRef.current = null;
void pollRef.current?.(); void pollRef.current?.();
@@ -201,24 +206,30 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
[server.id], [server.id],
); );
async function forceStop() {
setConfirmForce(false); setFailure(null); setShowDetails(false); setStopFailed(false);
lifecycle.request("stopping"); setAction("stopping"); actionRef.current = "stopping";
try {
const out = await api.forceStop(server.id);
if (!out.ok) throw { human: out.human, technical: out.output };
} catch (e) { setStopFailed(true); setFailure(asUiError(e)); }
finally { lifecycle.complete("stopping"); setAction(null); actionRef.current = null; void pollRef.current?.(); }
}
const poll = useCallback(async () => { const poll = useCallback(async () => {
try { try {
const s = await api.status(server.id); const s = await api.status(server.id);
if (alive.current) setStatus(s); if (alive.current) setStatus(s);
const isWorldRunning = s.observed.world.state === "running"; const isWorldRunning = s.observed.world.state === "running";
if (isWorldRunning) { if (isWorldRunning) {
wasWorldRunningRef.current = true; lifecycle.observe(true, actionRef.current !== null, serverUpdateBlocksRestart(server.id));
userStoppedRef.current = false;
const p = await api.population(server.id).catch(() => null); const p = await api.population(server.id).catch(() => null);
if (alive.current) setPop(p); if (alive.current) setPop(p);
} else { } else {
if (alive.current) setPop(null); if (alive.current) setPop(null);
if ( if (
wasWorldRunningRef.current && lifecycle.observe(false, actionRef.current !== null, serverUpdateBlocksRestart(server.id))
!userStoppedRef.current &&
actionRef.current === null
) { ) {
wasWorldRunningRef.current = false;
setHasCrashHistory(true); setHasCrashHistory(true);
const now = Date.now(); const now = Date.now();
const recent = crashTimestampsRef.current.filter((ts) => now - ts < 180000); const recent = crashTimestampsRef.current.filter((ts) => now - ts < 180000);
@@ -400,7 +411,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
</div> </div>
<div> <div>
<dt className="text-muted">{t("overview.players")}</dt> <dt className="text-muted">{t("overview.players")}</dt>
<dd className="mt-0.5 text-lg">{pop ? `${pop.players_online}` : "—"}{companions && pop && pop.bots_online > 0 ? <span className="ml-2 text-sm text-muted">{t("overview.companions", { n: pop.bots_online })}</span> : null}</dd> <dd className="mt-0.5 text-lg">{pop ? `${pop.players_online}` : "—"}{pop && pop.bots_online > 0 ? <span className="ml-2 text-sm text-muted">{t("overview.bots", { n: pop.bots_online })}</span> : null}</dd>
</div> </div>
</dl> </dl>
{companions && startBots !== undefined && ( {companions && startBots !== undefined && (
@@ -410,32 +421,21 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<div className="mt-7 flex flex-wrap items-center gap-x-4 gap-y-3"> <div className="mt-7 flex flex-wrap items-center gap-x-4 gap-y-3">
{running ? ( {running ? (
<Button variant="secondary" size="xl" disabled={transitioning} onClick={() => run("stopping")} className="min-w-56"> <Button variant="secondary" size="xl" disabled={transitioning} onClick={() => run("stopping")} className="min-w-40">
{transitioning && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />} {transitioning && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{t("btn.stop")} {t("btn.stop")}
</Button> </Button>
) : upd.available ? ( ) : upd.available ? (
<Button <SplitButton label={t("overview.server")}
variant="primary" primary={{ disabled: transitioning || upd.applying, onClick: () => (needsDecision ? onOpenUpdates() : void runServerUpdate()), children: <>{upd.applying && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{upd.applying ? t("btn.updating") : needsDecision ? t("overview.openUpdates") : t("btn.update")}</> }}
size="xl" secondary={{ disabled: transitioning || upd.applying, onClick: () => run("starting"), children: t("btn.startWithoutUpdate") }}
disabled={transitioning || upd.applying} />
onClick={() => (needsDecision ? onOpenUpdates() : void runServerUpdate())}
className="min-w-56"
>
{upd.applying && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{upd.applying ? t("btn.updating") : needsDecision ? t("overview.openUpdates") : t("btn.update")}
</Button>
) : ( ) : (
<Button variant="primary" size="xl" disabled={transitioning} onClick={() => run("starting")} className="min-w-56"> <Button variant="primary" size="xl" disabled={transitioning} onClick={() => run("starting")} className="min-w-40">
{transitioning && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />} {transitioning && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{transitioning ? (action === "stopping" ? t("btn.stoppingCaps") : t("btn.startingCaps")) : t("btn.start")} {transitioning ? (action === "stopping" ? t("btn.stoppingCaps") : t("btn.startingCaps")) : t("btn.start")}
</Button> </Button>
)} )}
{!running && upd.available && (
<Button variant="secondary" size="sm" disabled={transitioning || upd.applying} onClick={() => run("starting")}>
{t("btn.startWithoutUpdate")}
</Button>
)}
{running && ( {running && (
<Button variant="ghost" size="sm" disabled={transitioning || upd.applying} onClick={() => run("restarting")}> <Button variant="ghost" size="sm" disabled={transitioning || upd.applying} onClick={() => run("restarting")}>
{t("btn.restart")} {t("btn.restart")}
@@ -456,7 +456,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{client && <RealmlistMenu serverId={server.id} />} {client && <RealmlistMenu serverId={server.id} />}
{client && jobBusy ? ( {client && jobBusy ? (
<div <div
className="relative flex h-16 min-w-64 items-center overflow-hidden rounded-md border border-gold/50 bg-card-2" className="relative flex h-12 min-w-64 items-center overflow-hidden rounded-md border border-gold/50 bg-card-2"
role="progressbar" role="progressbar"
aria-valuenow={jobPct} aria-valuenow={jobPct}
aria-valuemin={0} aria-valuemin={0}
@@ -482,9 +482,10 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
</button> </button>
</div> </div>
) : client && (clientStatus?.update_available || job.phase === "choose") ? ( ) : client && (clientStatus?.update_available || job.phase === "choose") ? (
<Button variant="primary" size="xl" disabled={playing || job.phase === "choose"} onClick={() => void startClientUpdate(server.id)} className="min-w-40"> <SplitButton label={t("btn.play")}
{t("btn.updateClient")} primary={{ disabled: playing || job.phase === "choose", onClick: () => void startClientUpdate(server.id), children: t("btn.updateClient") }}
</Button> secondary={{ disabled: realmBusy || playing || upd.applying, onClick: () => void play(), children: <>{playing && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("btn.playWithoutUpdate")}</> }}
/>
) : client ? ( ) : client ? (
<Button variant="primary" size="xl" disabled={realmBusy || playing} onClick={() => void play()} className="min-w-40"> <Button variant="primary" size="xl" disabled={realmBusy || playing} onClick={() => void play()} className="min-w-40">
{playing && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />} {playing && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
@@ -495,11 +496,6 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{t("btn.setupClient")} {t("btn.setupClient")}
</Button> </Button>
) : null} ) : null}
{client && !jobBusy && (clientStatus?.update_available || job.phase === "choose") && (
<Button variant="secondary" size="sm" disabled={realmBusy || playing || upd.applying} onClick={() => void play()}>
{t("btn.playWithoutUpdate")}
</Button>
)}
</div> </div>
</div> </div>
<div className="mt-6 flex flex-wrap items-center justify-between gap-3 border-t border-line/60 pt-4 text-xs text-muted"> <div className="mt-6 flex flex-wrap items-center justify-between gap-3 border-t border-line/60 pt-4 text-xs text-muted">
@@ -559,6 +555,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<div className="mt-4 rounded-md border border-gold/40 bg-gold/5 p-3 text-sm"> <div className="mt-4 rounded-md border border-gold/40 bg-gold/5 p-3 text-sm">
<p>{t("overview.updateAvail", { to: upd.preview.to_version, from: upd.preview.from_version ?? "?" })}</p> <p>{t("overview.updateAvail", { to: upd.preview.to_version, from: upd.preview.from_version ?? "?" })}</p>
{upd.preview.latest_version && <p>{t("upd.intermediate", { to: upd.preview.to_version, latest: upd.preview.latest_version })}</p>} {upd.preview.latest_version && <p>{t("upd.intermediate", { to: upd.preview.to_version, latest: upd.preview.latest_version })}</p>}
<button className="mt-2 cursor-pointer text-gold hover:underline" onClick={onOpenUpdates}>{t("history.open")}</button>
{needsDecision && <p className="mt-1 text-muted">{t("overview.updateConflicts")}</p>} {needsDecision && <p className="mt-1 text-muted">{t("overview.updateConflicts")}</p>}
{upd.applying && ( {upd.applying && (
<div className="mt-2"> <div className="mt-2">
@@ -633,6 +630,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<Card className="mt-4 border-bad/40 p-5" role="alert"> <Card className="mt-4 border-bad/40 p-5" role="alert">
<p className="font-medium text-bad">{human(visibleFailure.human).title}</p> <p className="font-medium text-bad">{human(visibleFailure.human).title}</p>
<p className="mt-1 text-sm text-muted">{human(visibleFailure.human).message}</p> <p className="mt-1 text-sm text-muted">{human(visibleFailure.human).message}</p>
{anyUp && (stopFailed || /still stopping|could not be stopped|Stop the server before updating/i.test(visibleFailure.technical)) && <Button className="mt-3" size="sm" variant="secondary" disabled={transitioning || upd.applying} onClick={() => setConfirmForce(true)}>{t("stop.force")}</Button>}
<div className="mt-3 flex gap-2"> <div className="mt-3 flex gap-2">
<Button size="sm" onClick={() => setShowDetails((v) => !v)}> <Button size="sm" onClick={() => setShowDetails((v) => !v)}>
{showDetails ? t("common.hideDetails") : t("common.viewDetails")} {showDetails ? t("common.hideDetails") : t("common.viewDetails")}
@@ -663,6 +661,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
)} )}
{publishing && <PublishRealmDialog realm={publishing} onClose={() => setPublishing(null)} />} {publishing && <PublishRealmDialog realm={publishing} onClose={() => setPublishing(null)} />}
{confirmForce && <ForceStopDialog onCancel={() => setConfirmForce(false)} onConfirm={() => void forceStop()} />}
{showCrashModal && ( {showCrashModal && (
<CrashHistoryModal <CrashHistoryModal
serverId={server.id} serverId={server.id}
+3 -2
View File
@@ -2,10 +2,11 @@ import { useState } from "react";
import { Globe, Network } from "lucide-react"; import { Globe, Network } from "lucide-react";
import { useT } from "@/i18n"; import { useT } from "@/i18n";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { PublishCard } from "./PublishCard";
import { BrowsePage } from "@/screens/BrowsePage"; import { BrowsePage } from "@/screens/BrowsePage";
import { FriendsPage } from "@/screens/FriendsPage"; import { FriendsPage } from "@/screens/FriendsPage";
export function PlayWithFriends({ serverId }: { serverId: string; path?: string }) { export function PlayWithFriends({ serverId, serverName = "" }: { serverId: string; serverName?: string; path?: string }) {
const t = useT(); const t = useT();
const [tab, setTab] = useState<"servers" | "lan">("servers"); const [tab, setTab] = useState<"servers" | "lan">("servers");
@@ -38,7 +39,7 @@ export function PlayWithFriends({ serverId }: { serverId: string; path?: string
</button> </button>
</div> </div>
{tab === "servers" && <BrowsePage />} {tab === "servers" && <><PublishCard serverId={serverId} serverName={serverName} /><BrowsePage /></>}
{tab === "lan" && <FriendsPage serverId={serverId} />} {tab === "lan" && <FriendsPage serverId={serverId} />}
</div> </div>
); );
+1 -1
View File
@@ -36,12 +36,12 @@ export function PlayersPage({ serverId }: { serverId: string }) {
try { try {
await api.createAccount(serverId, username, password, admin); await api.createAccount(serverId, username, password, admin);
setDone(username); setDone(username);
setCreated((n) => n + 1);
setUsername(""); setUsername("");
setPassword(""); setPassword("");
} catch (e) { } catch (e) {
setError(asUiError(e)); setError(asUiError(e));
} finally { } finally {
setCreated((n) => n + 1);
setBusy(false); setBusy(false);
} }
} }
+24
View File
@@ -0,0 +1,24 @@
import { useEffect, useState } from "react";
import { Card } from "@/components/ui/card";
import { useI18n } from "@/i18n";
import { browse } from "@/lib/browse";
import { asUiError } from "@/lib/api";
export function PublicServerSettings() {
const { t } = useI18n();
const [enabled, setEnabled] = useState<boolean | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => { void browse.enabled().then(setEnabled).catch(e => setError(asUiError(e).technical)); }, []);
async function change(next: boolean) {
setBusy(true); setError(null);
try { await browse.setEnabled(next); setEnabled(next); }
catch (e) { setError(asUiError(e).technical); }
finally { setBusy(false); }
}
return <Card className="mt-6 p-6">
<label className="flex items-center gap-3 font-semibold"><input type="checkbox" checked={enabled === true} disabled={enabled === null || busy} onChange={e => void change(e.target.checked)} aria-describedby="public-server-hint" />{t("settings.publicServers")}</label>
<p id="public-server-hint" className="mt-2 text-sm text-muted">{t("settings.publicServersHint")}</p>
{error && <p role="alert" className="mt-2 text-sm text-bad">{error}</p>}
</Card>;
}
+1 -1
View File
@@ -33,7 +33,7 @@ export function RealmStartupSettings({ serverId }: { serverId: string }) {
{view?.with_reborn && <p className="mt-1 text-sm text-muted">{t("realm.rebornPort", { port: view.reborn_world_port ?? "—" })}</p>} {view?.with_reborn && <p className="mt-1 text-sm text-muted">{t("realm.rebornPort", { port: view.reborn_world_port ?? "—" })}</p>}
{view && view.active !== "coa" && !view.with_reborn && <p className="mt-1 text-sm text-warn">{t("realm.rebornNeedsCoa")}</p>} {view && view.active !== "coa" && !view.with_reborn && <p className="mt-1 text-sm text-warn">{t("realm.rebornNeedsCoa")}</p>}
{view?.simultaneous && view.with_reborn && <p className="mt-3 text-sm">{t("realm.allThree")}</p>} {view?.simultaneous && view.with_reborn && <p className="mt-3 text-sm">{t("realm.allThree")}</p>}
<p className="mt-3 text-sm text-muted">{t("realm.simultaneousHint")}</p> <details className="mt-4 text-sm text-muted"><summary className="cursor-pointer">{t("settings.startupHelp")}</summary><p className="mt-2 leading-relaxed">{t("realm.simultaneousHint")}</p></details>
{busy && <p className="mt-2 text-sm" role="status">{t("realm.preparing")}</p>} {busy && <p className="mt-2 text-sm" role="status">{t("realm.preparing")}</p>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>} {error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Card>; </Card>;
+1 -1
View File
@@ -92,7 +92,7 @@ export function RealmlistMenu({ serverId, className }: { serverId: string; class
onClick={() => setOpen((v) => !v)} onClick={() => setOpen((v) => !v)}
aria-haspopup="menu" aria-haspopup="menu"
aria-expanded={open} aria-expanded={open}
className="flex h-16 cursor-pointer items-center gap-3 rounded-md border border-line bg-card-2 px-4 text-left transition-colors hover:border-gold/50" className="flex h-12 cursor-pointer items-center gap-3 rounded-md border border-line bg-card-2 px-4 text-left transition-colors hover:border-gold/50"
> >
<span> <span>
<span className="block text-[11px] uppercase tracking-wide text-muted">{t("realm.label")}</span> <span className="block text-[11px] uppercase tracking-wide text-muted">{t("realm.label")}</span>
+76
View File
@@ -0,0 +1,76 @@
import { useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { getVersion } from "@tauri-apps/api/app";
import { useI18n, LOCALES, type Locale } from "@/i18n";
import { useSelfUpdate } from "@/lib/selfUpdate";
import { bundledHistories, compareVersions, releasesForUpdate, repositories, translatedNotes, type Component, type History } from "@/lib/releaseHistory";
import { api } from "@/lib/api";
import { Card } from "@/components/ui/card";
export interface HistorySelection { component: Component; from?: string; to?: string }
export function ReleaseHistory({ selection, onSelect }: { selection: HistorySelection; onSelect: (selection: HistorySelection) => void }) {
const { locale, t } = useI18n();
const [language, setLanguage] = useState<Locale>(locale);
const [feeds, setFeeds] = useState(bundledHistories);
const [fresh, setFresh] = useState<Partial<Record<Component, boolean>>>({});
const [mode, setMode] = useState<"all" | "range">("all");
const [selected, setSelected] = useState("");
const [installed, setInstalled] = useState<string>();
const updater = useSelfUpdate();
const { component } = selection;
const lastServer = useRef<HistorySelection>({ component: "server" });
const [linkError, setLinkError] = useState<string>();
useEffect(() => { if (component === "server") lastServer.current = selection; setLinkError(undefined); }, [selection, component]);
const target = component === "manager" ? updater.version : selection.to;
const from = component === "manager" ? installed : selection.from;
useEffect(() => setLanguage(locale), [locale]);
useEffect(() => { void getVersion().then(setInstalled).catch(() => {}); }, []);
useEffect(() => {
setSelected("");
setMode(selection.to || (component === "manager" && updater.version) ? "range" : "all");
}, [selection, component, updater.version]);
useEffect(() => {
let live = true;
void invoke<History>("release_history", { component }).then(feed => {
if (live && feed.component === component && Array.isArray(feed.releases)) {
setFeeds(previous => ({ ...previous, [component]: feed }));
setFresh(previous => ({ ...previous, [component]: feed.source === "remote" }));
}
}).catch(() => {}); // Bundled reviewed notes remain visible offline.
return () => { live = false; };
}, [component]);
const releases = [...(mode === "range" ? releasesForUpdate(feeds[component].releases, from, target) : feeds[component].releases)]
.sort((a, b) => compareVersions(b.version.split("-")[0], a.version.split("-")[0]) || b.date.localeCompare(a.date));
const record = releases.find(r => r.version === selected) ?? releases[0];
const notes = record ? translatedNotes(component, record, language) : undefined;
return <Card id="release-history" tabIndex={-1} className="mt-6 scroll-mt-4 overflow-hidden">
<div className="flex flex-wrap items-center justify-between gap-4 border-b border-line p-5">
<h2 className="font-semibold">{t("history.title")}</h2>
<div className="flex rounded-md border border-line p-1" aria-label={t("history.title")}>
{(["server", "manager"] as const).map(c => <button key={c} aria-pressed={component === c} onClick={() => onSelect(c === "server" ? lastServer.current : { component: c })} className={`cursor-pointer rounded px-3 py-1.5 text-sm ${component === c ? "bg-gold/10 text-gold" : "text-muted hover:text-ink"}`}>{t(`history.${c}`)}</button>)}
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-line px-5 py-3 text-sm">
<div className="flex gap-3">
<button className={mode === "all" ? "text-gold" : "cursor-pointer text-muted"} aria-pressed={mode === "all"} onClick={() => setMode("all")}>{t("history.all")}</button>
{target && <button className={mode === "range" ? "text-gold" : "cursor-pointer text-muted"} aria-pressed={mode === "range"} onClick={() => setMode("range")}>{t("history.range")}{from ? ` · ${from} → ${target}` : ` · ${target}`}</button>}
</div>
<label className="flex items-center gap-2 text-muted">{t("history.language")}<select value={language} onChange={e => setLanguage(e.target.value as Locale)} className="rounded border border-line bg-panel px-2 py-1 text-ink">{LOCALES.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}</select></label>
</div>
<div className="grid min-h-64 md:grid-cols-[180px_1fr]">
<div className="flex max-h-96 gap-1 overflow-auto border-b border-line p-3 md:block md:border-r md:border-b-0" aria-label={t("history.all")}>
{releases.map(r => <button key={r.tag} aria-pressed={r.version === record?.version} onClick={() => setSelected(r.version)} className={`mb-1 block shrink-0 cursor-pointer rounded-md px-3 py-2 text-left text-sm md:w-full ${r.version === record?.version ? "bg-gold/10 text-gold" : "text-muted hover:bg-white/5"}`}><span className="block font-medium">{r.version}</span><span className="text-xs text-muted">{r.date}{r.prerelease ? " · Pre-release" : ""}</span></button>)}
</div>
<div className="min-w-0 p-5" aria-live="polite">
{record && notes ? <><h3 className="text-lg font-semibold">{t(`history.${component}`)} {record.version}</h3>
{notes.fallback && <p className="mt-2 text-xs text-warn">{t("history.fallback")}</p>}
<ul lang={notes.fallback ? "en" : language} className="mt-4 list-disc space-y-2 pl-5 text-sm leading-relaxed">{notes.notes.map((note, i) => <li key={i}>{note}</li>)}</ul>
{record.experimentalFeatures?.includes("portable-characters") && <p className="mt-4 rounded border border-warn/30 p-3 text-sm text-warn">{t("history.experimental")}</p>}
<a className="mt-5 inline-block text-sm text-gold hover:underline" href={`https://github.com/${repositories[component]}/releases/tag/${encodeURIComponent(record.tag)}`} onClick={e => { e.preventDefault(); void api.openLink(e.currentTarget.href).catch(error => setLinkError(String(error))); }}>GitHub ↗</a>
{linkError && <p className="mt-2 break-words text-xs text-bad" role="alert">{linkError}</p>}
</> : <p className="text-sm text-muted">{t("history.empty")}</p>}
</div>
</div>
<p className="border-t border-line px-5 py-3 text-xs text-muted">{fresh[component] ? t("history.refreshed") : t("history.offline")}</p>
</Card>;
}
+3 -1
View File
@@ -7,6 +7,8 @@ import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { AboutCard } from "@/screens/AboutCard"; import { AboutCard } from "@/screens/AboutCard";
import { PortablePage } from "@/screens/PortablePage"; import { PortablePage } from "@/screens/PortablePage";
import { BrowsePage } from "@/screens/BrowsePage"; import { BrowsePage } from "@/screens/BrowsePage";
import { WindowSettings } from "./WindowSettings";
import { PublicServerSettings } from "./PublicServerSettings";
import { LanguagePicker } from "@/components/LanguagePicker"; import { LanguagePicker } from "@/components/LanguagePicker";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card"; import { Card } from "@/components/ui/card";
@@ -65,7 +67,7 @@ export function RemoteClient({ onHost }: { onHost: () => void }) {
<div className="mt-auto border-t border-line pt-3"><Button variant="ghost" size="sm" className="w-full justify-start" onClick={onHost}>{t("remote.hostInstead")}</Button></div> <div className="mt-auto border-t border-line pt-3"><Button variant="ghost" size="sm" className="w-full justify-start" onClick={onHost}>{t("remote.hostInstead")}</Button></div>
</nav> </nav>
<main className="h-full flex-1 overflow-y-auto px-10 py-8"> <main className="h-full flex-1 overflow-y-auto px-10 py-8">
{page === "servers" ? <BrowsePage /> : page === "characters" ? <PortablePage /> : page === "settings" ? <><div className="flex items-center justify-between"><h1 className="text-2xl font-semibold">{t("nav.settings")}</h1><LanguagePicker /></div><AboutCard /></> : <> {page === "servers" ? <BrowsePage /> : page === "characters" ? <PortablePage /> : page === "settings" ? <><div className="flex items-center justify-between"><h1 className="text-2xl font-semibold">{t("nav.settings")}</h1><LanguagePicker /></div><WindowSettings /><PublicServerSettings /><AboutCard /></> : <>
<div className="flex items-center justify-between"><h1 className="text-2xl font-semibold">{t("welcome.connect.title")}</h1><LanguagePicker /></div> <div className="flex items-center justify-between"><h1 className="text-2xl font-semibold">{t("welcome.connect.title")}</h1><LanguagePicker /></div>
<p className="mt-2 text-muted">{t("remote.intro")}</p> <p className="mt-2 text-muted">{t("remote.intro")}</p>
<Card className="mt-6 p-6"> <Card className="mt-6 p-6">
+256
View File
@@ -0,0 +1,256 @@
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 { isUpdateCurrent } from "@/lib/serverUpdateStatus";
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useStartAfterUpdate } from "@/lib/updatePrefs";
import { hasKey, useHuman, useI18n, type Key } from "@/i18n";
function mb(bytes: number) {
return bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
}
export function ServerUpdateCard({ serverId, onHistory, onAttention }: { serverId: string; onHistory: (from?: string | null, to?: string) => void; onAttention: (value: boolean) => void }) {
const { t } = useI18n();
const upd = useServerUpdate(serverId);
const human = useHuman();
const [preview, setPreview] = useState<UpdatePreview | null>(upd.preview);
const [pending, setPending] = useState<UpdateTxn | null>(null);
const [pendingChecked, setPendingChecked] = useState(false);
const [pendingStateError, setPendingStateError] = useState<UiError | null>(null);
const [localBusy, setBusy] = useState<"check" | "rollback" | "retry" | null>(null);
// an update keeps running in the background when this tab is left, so its state is the shared one
const busy = upd.applying ? "update" : localBusy;
const progress = upd.applying ? { step: upd.step ?? "Starting", percent: upd.percent } : null;
const [localError, setError] = useState<UiError | null>(null);
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 [advanced, setAdvanced] = useState(false);
const [source, setSource] = useState("");
const [startAfter, setStartAfter] = useStartAfterUpdate("server", serverId);
useEffect(() => {
let active = true;
setPendingChecked(false);
setPending(null);
setPendingStateError(null);
void api.pendingUpdate(serverId).then((txn) => {
if (active) { setPending(txn); setPendingChecked(true); }
}).catch((e) => { if (active) setPendingStateError(asUiError(e)); });
return () => { active = false; };
}, [serverId]);
// 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);
}, [upd.stateRevision, serverId]);
useEffect(() => { onAttention(!!pending || !!pendingStateError); }, [pending, pendingStateError, onAttention]);
async function refreshPending() {
setPendingChecked(false);
try {
const txn = await refreshServerUpdateState(serverId);
setPending(txn);
setPendingStateError(null);
setPendingChecked(true);
return txn;
} catch (e) { setPendingStateError(asUiError(e)); throw e; }
}
async function check() {
setBusy("check");
setError(null);
setDone(null);
clearServerUpdateResult(serverId);
setPreview(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])));
} catch (e) {
setError(asUiError(e));
} finally {
setBusy(null);
}
}
async function update() {
if (!pendingChecked || pendingStateError || pending) return;
setError(null);
setDone(null);
await applyServerUpdate(serverId, { choices, source: source.trim() || undefined });
}
async function rollback(txn: UpdateTxn) {
if (!window.confirm(t("upd.confirmBack"))) return;
setBusy("rollback");
setError(null);
try {
await api.rollbackUpdate(serverId, txn.id);
setPending(null);
setDone(t("upd.wentBack"));
} catch (e) {
setError(asUiError(e));
} finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function retryValidation(txn: UpdateTxn) {
setBusy("retry");
setError(null);
try {
const result = await api.retryUpdateValidation(serverId, txn.id);
if (result.state === "committed") {
setPending(null);
setPreview(null);
setDone(t("upd.updatedTo", { v: result.to_version }));
clearServerUpdateResult(serverId);
} else setPending(result);
} catch (e) { setError(asUiError(e)); }
finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function browse() {
const p = await open({ directory: true, multiple: false, title: t("upd.dialogTitle") });
if (typeof p === "string") setSource(p);
}
return (
<div>
{pending && (
<Card className="mt-6 border-warn/40 p-5" role="alert">
<p className="font-medium text-warn">
{pending.state === "needs-decision" ? t("upd.pendingBad") : t("upd.pendingUnfinished")}
</p>
<p className="mt-1 whitespace-pre-wrap text-sm text-muted">{pending.message ?? t("upd.safeBack")}</p>
{pending.state === "needs-decision" && (
<Button className="mt-3 mr-3" size="sm" disabled={!!busy} onClick={() => void retryValidation(pending)}>
{busy === "retry" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.retryValidation")}
</Button>
)}
<p className="mt-1 text-sm text-muted">{t("upd.backNote")}</p>
<Button className="mt-3" size="sm" disabled={!!busy} onClick={() => void rollback(pending)}>
{busy === "rollback" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{pending.from_version ? t("upd.goBackTo", { v: pending.from_version }) : t("upd.goBackBefore")}
</Button>
</Card>
)}
<Card className="mt-6 p-6">
<div className="flex items-start justify-between gap-3">
<div><h2 className="flex items-center gap-2 font-semibold"><Server className="h-4 w-4 text-gold" aria-hidden />{t("history.server")}</h2>
<p className="mt-2 text-sm text-muted">{preview?.from_version ? t("settings.version", { v: preview.from_version }) : "…"}</p></div>
<Button size="sm" disabled={!!busy} onClick={() => void check()} aria-label={t("upd.check")} title={t("upd.check")}><RefreshCw className={`h-4 w-4 ${busy === "check" ? "animate-spin" : ""}`} aria-hidden /></Button>
</div>
<button className="mt-3 cursor-pointer text-sm text-gold hover:underline" onClick={() => onHistory(preview?.from_version, preview && !isUpdateCurrent(preview) ? preview.to_version : undefined)}>{t(preview && !isUpdateCurrent(preview) ? "history.open" : "history.title")}</button>
<div className="mt-3"><button onClick={() => setAdvanced((v) => !v)} aria-expanded={advanced} className="flex cursor-pointer items-center gap-1 text-xs text-muted hover:text-ink">
{advanced ? <ChevronDown className="h-3 w-3" aria-hidden /> : <ChevronRight className="h-3 w-3" aria-hidden />}{t("install.advanced")}
</button></div>
{advanced && (
<div className="mt-3 flex gap-2">
<input aria-label={t("upd.folderLabel")} value={source} onChange={(e) => setSource(e.target.value)} placeholder={t("upd.folderHint")} className="selectable flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" />
<Button size="sm" onClick={browse}>{t("install.browse")}</Button>
</div>
)}
{done && pendingChecked && !pendingStateError && <p className="mt-4 text-sm text-ok" role="status">{done}</p>}
{error && (
<div className="mt-4" role="alert">
<p className="selectable whitespace-pre-wrap break-words text-sm text-bad">
{error.human.code === "unknown" ? error.technical : human(error.human).message}
</p>
<button className="mt-1 cursor-pointer text-xs text-muted underline" onClick={() => void navigator.clipboard.writeText(error.technical)}>
{t("common.copyError")}
</button>
</div>
)}
{preview?.database_check_error && (
<p className="selectable mt-4 break-words text-sm text-warn" role="status">{t("upd.dbUnchecked", { why: preview.database_check_error })}</p>
)}
{preview && isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium text-ok" role="status">{t("upd.current", { v: preview.to_version })}</p>
</div>
)}
{preview && !isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium">
{preview.from_version ? t("upd.availableFrom", { to: preview.to_version, from: preview.from_version }) : t("upd.available", { to: preview.to_version })}
</p>
{preview.latest_version && <p className="mt-1 text-sm text-warn" role="status">{t("upd.intermediate", { to: preview.to_version, latest: preview.latest_version })}</p>}
<p className="mt-1 text-sm text-muted">
{!preview.database_check_error && (preview.pending_migrations ?? preview.migrations) > 0
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.pending_migrations ?? preview.migrations })
: t("upd.summary", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length })}
</p>
<details className="mt-3" open={preview.items.some(i => i.action === "conflict")}><summary className="cursor-pointer text-sm text-muted">{t("history.files")}</summary><ul className="mt-3 max-h-56 divide-y divide-line overflow-auto text-sm">
{preview.items.filter((i) => i.action !== "skip").map((i) => (
<li key={i.path} className="py-2">
<div className="flex justify-between gap-3">
<span className="selectable break-all">{i.path}</span>
<span className={i.action === "conflict" ? "shrink-0 text-warn" : "shrink-0 text-muted"}>{t(`upd.act.${i.action}` as Key)}</span>
</div>
{i.action === "conflict" && (
<fieldset className="mt-2 flex flex-wrap gap-4 text-xs text-muted">
<legend className="sr-only">{t("upd.conflict")}</legend>
<span className="text-warn">{t("upd.conflict")}</span>
{(["keep", "replace"] as const).map((c) => (
<label key={c} className="flex cursor-pointer items-center gap-1">
<input type="radio" name={i.path} checked={choices[i.path] === c} onChange={() => setChoices((x) => ({ ...x, [i.path]: c }))} />
{c === "keep" ? t("upd.keep") : t("upd.replace")}
</label>
))}
</fieldset>
)}
</li>
))}
</ul></details>
<Button className="mt-4" variant="primary" disabled={!!busy || !pendingChecked || !!pendingStateError || !!pending} onClick={() => void update()}>
{busy === "update" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.now")}
</Button>
<p className="mt-2 text-xs text-muted">{t("upd.stopNote")}</p>
</div>
)}
{busy === "update" && progress && (
<div className="mt-5">
<div className="flex justify-between text-sm">
<span role="status">{hasKey(`ustep.${progress.step}`) ? t(`ustep.${progress.step}` as Key) : progress.step}</span>
<span className="text-muted">{progress.percent}%</span>
</div>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={progress.percent} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${progress.percent}%` }} />
</div>
</div>
)}
<label className="mt-5 flex cursor-pointer items-center justify-between gap-3 border-t border-line pt-4 text-sm" title={t("upd.startAfter")}>
<span>{t("settings.startServer")}</span><input type="checkbox" role="switch" checked={startAfter} onChange={(e) => setStartAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
</label>
</Card>
</div>
);
}
+51 -286
View File
@@ -1,292 +1,57 @@
import { useEffect, useState } from "react"; import { useState } from "react";
import { open } from "@tauri-apps/plugin-dialog"; import { Download, Power, FolderOpen, Wrench, Languages } from "lucide-react";
import { ChevronDown, ChevronRight, Loader2 } from "lucide-react"; import { useI18n } from "@/i18n";
import { applyServerUpdate, clearServerUpdateResult, refreshServerUpdateState, useServerUpdate } from "@/lib/serverUpdate"; import { WindowSettings } from "./WindowSettings";
import { isUpdateCurrent } from "@/lib/serverUpdateStatus"; import { PublicServerSettings } from "./PublicServerSettings";
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { ClientCard } from "@/screens/ClientCard";
import { GameDataCard } from "@/screens/GameDataCard";
import { DiagnosticsCard } from "@/screens/DiagnosticsCard";
import { AboutCard } from "@/screens/AboutCard";
import { RemoveServerCard } from "@/screens/RemoveServerCard";
import { useStartAfterUpdate } from "@/lib/updatePrefs";
import { hasKey, useHuman, useI18n, type Key } from "@/i18n";
import { LanguagePicker } from "@/components/LanguagePicker"; import { LanguagePicker } from "@/components/LanguagePicker";
import { RealmStartupSettings } from "@/screens/RealmStartupSettings"; import { Card } from "@/components/ui/card";
import { RepairCard } from "@/screens/RepairCard"; import { useServerUpdate } from "@/lib/serverUpdate";
import { PublishCard } from "@/screens/PublishCard"; import { ServerUpdateCard } from "./ServerUpdateCard";
import { AutoRestartSettings } from "@/screens/AutoRestartSettings"; import { AboutCard } from "./AboutCard";
import { ReleaseHistory, type HistorySelection } from "./ReleaseHistory";
import { ClientCard } from "./ClientCard";
import { GameDataCard } from "./GameDataCard";
import { RealmStartupSettings } from "./RealmStartupSettings";
import { AutoRestartSettings } from "./AutoRestartSettings";
import { DiagnosticsCard } from "./DiagnosticsCard";
import { RepairCard } from "./RepairCard";
import { RemoveServerCard } from "./RemoveServerCard";
function mb(bytes: number) { const sections = [["updates", Download], ["startup", Power], ["client", FolderOpen], ["service", Wrench], ["interface", Languages]] as const;
return bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`; export function SettingsHome({ serverId, path, onForget }: { serverId: string; serverName?: string; path: string; onForget: () => Promise<void> }) {
}
export function SettingsHome({ serverId, serverName = "", path, onForget }: { serverId: string; serverName?: string; path: string; onForget: () => Promise<void> }) {
const { t } = useI18n(); const { t } = useI18n();
const upd = useServerUpdate(serverId); const [section, setSection] = useState<(typeof sections)[number][0]>("updates");
const human = useHuman(); const [attention, setAttention] = useState(false);
const [preview, setPreview] = useState<UpdatePreview | null>(null); const update = useServerUpdate(serverId);
const [pending, setPending] = useState<UpdateTxn | null>(null); const [history, setHistory] = useState<HistorySelection>(() => ({ component: "server", from: update.preview?.from_version ?? undefined, to: update.available ? update.preview?.to_version : undefined }));
const [pendingChecked, setPendingChecked] = useState(false); function showHistory(selection: HistorySelection) {
const [pendingStateError, setPendingStateError] = useState<UiError | null>(null); setHistory(selection);
const [localBusy, setBusy] = useState<"check" | "rollback" | "retry" | null>(null); requestAnimationFrame(() => {
// an update keeps running in the background when this tab is left, so its state is the shared one const element = document.getElementById("release-history");
const busy = upd.applying ? "update" : localBusy; element?.scrollIntoView({ behavior: "smooth", block: "start" });
const progress = upd.applying ? { step: upd.step ?? "Starting", percent: upd.percent } : null; element?.focus({ preventScroll: true });
const [localError, setError] = useState<UiError | null>(null); });
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">>({});
const [advanced, setAdvanced] = useState(false);
const [source, setSource] = useState("");
const [startAfter, setStartAfter] = useStartAfterUpdate("server", serverId);
useEffect(() => {
let active = true;
setPendingChecked(false);
setPending(null);
setPreview(null);
setPendingStateError(null);
void api.pendingUpdate(serverId).then((txn) => {
if (active) { setPending(txn); setPendingChecked(true); }
}).catch((e) => { if (active) setPendingStateError(asUiError(e)); });
return () => { active = false; };
}, [serverId]);
// 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);
}, [upd.stateRevision, serverId]);
async function refreshPending() {
setPendingChecked(false);
try {
const txn = await refreshServerUpdateState(serverId);
setPending(txn);
setPendingStateError(null);
setPendingChecked(true);
return txn;
} catch (e) { setPendingStateError(asUiError(e)); throw e; }
} }
return <div className="mx-auto w-full max-w-5xl pb-8">
async function check() { <h1 className="text-2xl font-semibold">{t("settings.title")}</h1>
setBusy("check"); <p className="mt-1 text-sm text-muted">{t("settings.organized")}</p>
setError(null); <nav aria-label={t("settings.title")} className="mt-6 flex flex-wrap gap-1 border-b border-line pb-3">
setDone(null); {sections.map(([id, Icon]) => <button key={id} aria-current={section === id ? "page" : undefined} onClick={() => setSection(id)} className={`flex cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-sm ${section === id ? "bg-gold/10 text-gold" : "text-muted hover:bg-white/5 hover:text-ink"}`}>
clearServerUpdateResult(serverId); <Icon className="h-4 w-4" aria-hidden />{t(`settings.section.${id}`)}
setPreview(null); </button>)}
try { </nav>
const txn = await refreshPending(); {attention && section !== "updates" && <button role="alert" onClick={() => setSection("updates")} className="mt-4 w-full cursor-pointer rounded-lg border border-warn/40 p-4 text-left text-sm text-warn">{t("settings.attention")}</button>}
if (txn) return; <div hidden={section !== "updates"}>
const p = await api.checkUpdate(serverId, source.trim() || undefined); <div className="grid items-start gap-x-5 lg:grid-cols-2">
setPreview(p); <ServerUpdateCard onAttention={setAttention} serverId={serverId} onHistory={(from, to) => showHistory({ component: "server", from: from ?? undefined, to })} />
setChoices(Object.fromEntries(p.conflicts.map((c) => [c, "keep" as const]))); <AboutCard onHistory={() => showHistory({ component: "manager" })} />
} catch (e) { </div>
setError(asUiError(e)); <button onClick={() => setSection("client")} className="mt-5 flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg border border-line px-5 py-4 text-left text-sm hover:bg-white/5"><span>{t("settings.clientLink")}</span><span aria-hidden>→</span></button>
} finally { <ReleaseHistory selection={history} onSelect={setHistory} />
setBusy(null);
}
}
async function update() {
if (!pendingChecked || pendingStateError || pending) return;
setError(null);
setDone(null);
await applyServerUpdate(serverId, { choices, source: source.trim() || undefined });
}
async function rollback(txn: UpdateTxn) {
if (!window.confirm(t("upd.confirmBack"))) return;
setBusy("rollback");
setError(null);
try {
await api.rollbackUpdate(serverId, txn.id);
setPending(null);
setDone(t("upd.wentBack"));
} catch (e) {
setError(asUiError(e));
} finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function retryValidation(txn: UpdateTxn) {
setBusy("retry");
setError(null);
try {
const result = await api.retryUpdateValidation(serverId, txn.id);
if (result.state === "committed") {
setPending(null);
setPreview(null);
setDone(t("upd.updatedTo", { v: result.to_version }));
clearServerUpdateResult(serverId);
} else setPending(result);
} catch (e) { setError(asUiError(e)); }
finally {
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
setBusy(null);
}
}
async function browse() {
const p = await open({ directory: true, multiple: false, title: t("upd.dialogTitle") });
if (typeof p === "string") setSource(p);
}
return (
<div className="max-w-2xl">
<h1 className="text-2xl font-semibold">{t("settings.title")}</h1>
<p className="mt-1 text-muted">{t("q.settings")}</p>
{pending && (
<Card className="mt-6 border-warn/40 p-5" role="alert">
<p className="font-medium text-warn">
{pending.state === "needs-decision" ? t("upd.pendingBad") : t("upd.pendingUnfinished")}
</p>
<p className="mt-1 whitespace-pre-wrap text-sm text-muted">{pending.message ?? t("upd.safeBack")}</p>
{pending.state === "needs-decision" && (
<Button className="mt-3 mr-3" size="sm" disabled={!!busy} onClick={() => void retryValidation(pending)}>
{busy === "retry" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.retryValidation")}
</Button>
)}
<p className="mt-1 text-sm text-muted">{t("upd.backNote")}</p>
<Button className="mt-3" size="sm" disabled={!!busy} onClick={() => void rollback(pending)}>
{busy === "rollback" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{pending.from_version ? t("upd.goBackTo", { v: pending.from_version }) : t("upd.goBackBefore")}
</Button>
</Card>
)}
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("settings.language")}</h2>
<p className="mt-1 text-sm text-muted">{t("settings.languageHint")}</p>
<LanguagePicker className="mt-3" />
</Card>
<ClientCard serverId={serverId} />
<RealmStartupSettings serverId={serverId} />
<AutoRestartSettings serverId={serverId} />
<GameDataCard serverId={serverId} />
<DiagnosticsCard serverId={serverId} />
<RepairCard key={serverId} serverId={serverId} />
<PublishCard key={`publish-${serverId}`} serverId={serverId} serverName={serverName} />
<AboutCard />
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("upd.title")}</h2>
<p className="mt-1 text-sm text-muted">{t("upd.text")}</p>
<label className="mt-3 flex cursor-pointer items-center gap-2 text-sm">
<input type="checkbox" checked={startAfter} onChange={(e) => setStartAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
<span>{t("upd.startAfter")}</span>
</label>
<div className="mt-4 flex items-center gap-3">
<Button variant="primary" disabled={!!busy} onClick={() => void check()}>
{busy === "check" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.check")}
</Button>
<button onClick={() => setAdvanced((v) => !v)} aria-expanded={advanced} className="flex cursor-pointer items-center gap-1 text-sm text-muted hover:text-ink">
{advanced ? <ChevronDown className="h-4 w-4" aria-hidden /> : <ChevronRight className="h-4 w-4" aria-hidden />}
{t("install.advanced")}
</button>
</div>
{advanced && (
<div className="mt-3 flex gap-2">
<input aria-label={t("upd.folderLabel")} value={source} onChange={(e) => setSource(e.target.value)} placeholder={t("upd.folderHint")} className="selectable flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" />
<Button size="sm" onClick={browse}>{t("install.browse")}</Button>
</div>
)}
{done && pendingChecked && !pendingStateError && <p className="mt-4 text-sm text-ok" role="status">{done}</p>}
{upd.result && "committed" in upd.result && !!upd.result.preexistingCharacters && <p className="mt-3 text-sm text-warn" role="status">{t("upd.preexistingCharacters", { n: upd.result.preexistingCharacters })}</p>}
{error && (
<div className="mt-4" role="alert">
<p className="selectable whitespace-pre-wrap break-words text-sm text-bad">
{error.human.code === "unknown" ? error.technical : human(error.human).message}
</p>
<button className="mt-1 cursor-pointer text-xs text-muted underline" onClick={() => void navigator.clipboard.writeText(error.technical)}>
{t("common.copyError")}
</button>
</div>
)}
{preview?.database_check_error && (
<p className="selectable mt-4 break-words text-sm text-warn" role="status">{t("upd.dbUnchecked", { why: preview.database_check_error })}</p>
)}
{preview && isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium text-ok" role="status">{t("upd.current", { v: preview.to_version })}</p>
</div>
)}
{preview && !isUpdateCurrent(preview) && (
<div className="mt-5 border-t border-line pt-4">
<p className="font-medium">
{preview.from_version ? t("upd.availableFrom", { to: preview.to_version, from: preview.from_version }) : t("upd.available", { to: preview.to_version })}
</p>
{preview.latest_version && <p className="mt-1 text-sm text-warn" role="status">{t("upd.intermediate", { to: preview.to_version, latest: preview.latest_version })}</p>}
<p className="mt-1 text-sm text-muted">
{!preview.database_check_error && (preview.pending_migrations ?? preview.migrations) > 0
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.pending_migrations ?? preview.migrations })
: t("upd.summary", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length })}
</p>
<ul className="mt-3 max-h-56 divide-y divide-line overflow-auto text-sm">
{preview.items.filter((i) => i.action !== "skip").map((i) => (
<li key={i.path} className="py-2">
<div className="flex justify-between gap-3">
<span className="selectable break-all">{i.path}</span>
<span className={i.action === "conflict" ? "shrink-0 text-warn" : "shrink-0 text-muted"}>{t(`upd.act.${i.action}` as Key)}</span>
</div>
{i.action === "conflict" && (
<fieldset className="mt-2 flex flex-wrap gap-4 text-xs text-muted">
<legend className="sr-only">{t("upd.conflict")}</legend>
<span className="text-warn">{t("upd.conflict")}</span>
{(["keep", "replace"] as const).map((c) => (
<label key={c} className="flex cursor-pointer items-center gap-1">
<input type="radio" name={i.path} checked={choices[i.path] === c} onChange={() => setChoices((x) => ({ ...x, [i.path]: c }))} />
{c === "keep" ? t("upd.keep") : t("upd.replace")}
</label>
))}
</fieldset>
)}
</li>
))}
</ul>
<Button className="mt-4" variant="primary" disabled={!!busy || !pendingChecked || !!pendingStateError || !!pending} onClick={() => void update()}>
{busy === "update" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{t("upd.now")}
</Button>
<p className="mt-2 text-xs text-muted">{t("upd.stopNote")}</p>
</div>
)}
{busy === "update" && progress && (
<div className="mt-5">
<div className="flex justify-between text-sm">
<span role="status">{hasKey(`ustep.${progress.step}`) ? t(`ustep.${progress.step}` as Key) : progress.step}</span>
<span className="text-muted">{progress.percent}%</span>
</div>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={progress.percent} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${progress.percent}%` }} />
</div>
</div>
)}
</Card>
<RemoveServerCard serverId={serverId} path={path} onForget={onForget} />
</div> </div>
); <div hidden={section !== "startup"} className="max-w-3xl"><RealmStartupSettings serverId={serverId} /><AutoRestartSettings serverId={serverId} /></div>
<div hidden={section !== "client"} className="max-w-3xl"><ClientCard serverId={serverId} /><GameDataCard serverId={serverId} /></div>
<div hidden={section !== "service"} className="max-w-3xl"><DiagnosticsCard serverId={serverId} /><RepairCard serverId={serverId} /><RemoveServerCard serverId={serverId} path={path} onForget={onForget} /></div>
<div hidden={section !== "interface"} className="max-w-3xl"><Card className="mt-6 p-6"><h2 className="font-semibold">{t("settings.language")}</h2><p className="mt-1 text-sm text-muted">{t("settings.languageHint")}</p><LanguagePicker className="mt-4" /></Card><WindowSettings /><PublicServerSettings /></div>
</div>;
} }
+1 -1
View File
@@ -161,7 +161,7 @@ export function Shell(props: {
) : page === "report" ? ( ) : page === "report" ? (
<ReportPage key={server.id} serverId={server.id} /> <ReportPage key={server.id} serverId={server.id} />
) : page === "friends" ? ( ) : page === "friends" ? (
<PlayWithFriends key={server.id} serverId={server.id} path={server.path} /> <PlayWithFriends key={server.id} serverName={server.name} serverId={server.id} path={server.path} />
) : page === "settings" ? ( ) : page === "settings" ? (
<SettingsHome key={server.id} serverId={server.id} serverName={server.name} path={server.path} onForget={() => props.onForget(server.id)} /> <SettingsHome key={server.id} serverId={server.id} serverName={server.name} path={server.path} onForget={() => props.onForget(server.id)} />
) : page === "characters" ? ( ) : page === "characters" ? (
+24
View File
@@ -0,0 +1,24 @@
import { useEffect, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { Card } from "@/components/ui/card";
import { useI18n } from "@/i18n";
import { asUiError } from "@/lib/api";
export function WindowSettings() {
const { t } = useI18n();
const [enabled, setEnabled] = useState<boolean | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => { void invoke<boolean>("close_to_tray").then(setEnabled).catch(e => setError(asUiError(e).technical)); }, []);
async function change(next: boolean) {
setBusy(true); setError(null);
try { await invoke("set_close_to_tray", { enabled: next }); setEnabled(next); }
catch (e) { setError(asUiError(e).technical); }
finally { setBusy(false); }
}
return <Card className="mt-6 p-6">
<label className="flex items-center gap-3 font-semibold"><input type="checkbox" checked={enabled === true} disabled={enabled === null || busy} onChange={e => void change(e.target.checked)} aria-describedby="close-window-hint" />{t("settings.closeToTray")}</label>
<p id="close-window-hint" className="mt-2 text-sm text-muted">{t("settings.closeToTrayHint")}</p>
{error && <p role="alert" className="mt-2 text-sm text-bad">{error}</p>}
</Card>;
}
+5 -1
View File
@@ -11,10 +11,11 @@ const stubs = {
"@/lib/api": `export const api={}; export const asUiError=e=>e;`, "@/lib/api": `export const api={}; export const asUiError=e=>e;`,
"@/lib/utils": `export const cn=(...s)=>s.filter(Boolean).join(' '); export const formatBytes=String; export const formatUptime=String;`, "@/lib/utils": `export const cn=(...s)=>s.filter(Boolean).join(' '); export const formatBytes=String; export const formatUptime=String;`,
"@/i18n": `export const useT=()=>k=>k; export const useHuman=()=>h=>h;`, "@/i18n": `export const useT=()=>k=>k; export const useHuman=()=>h=>h;`,
"@/lib/serverUpdate": `export const applyServerUpdate=async()=>false; export const useServerUpdate=()=>globalThis.__overviewUpdate;`, "@/lib/serverUpdate": `export const serverUpdateBlocksRestart=()=>false; export const applyServerUpdate=async()=>false; export const useServerUpdate=()=>globalThis.__overviewUpdate;`,
"@/lib/clientJob": `export const dismissClientJob=()=>{}; export const startClientUpdate=()=>{}; export const stopClientJob=()=>{}; export const syncClient=()=>{}; export const useClientJob=()=>({phase:'idle'});`, "@/lib/clientJob": `export const dismissClientJob=()=>{}; export const startClientUpdate=()=>{}; export const stopClientJob=()=>{}; export const syncClient=()=>{}; export const useClientJob=()=>({phase:'idle'});`,
"@/lib/clientUpdate": `export const checkClient=()=>{}; export const useClientStatus=()=>({status:null});`, "@/lib/clientUpdate": `export const checkClient=()=>{}; export const useClientStatus=()=>({status:null});`,
"@/lib/autoRestartPrefs": `export const useAutoRestart=()=>[false,()=>{}];`, "@/lib/autoRestartPrefs": `export const useAutoRestart=()=>[false,()=>{}];`,
"./ForceStopDialog": `export const ForceStopDialog=()=>null;`,
"@/screens/PublishCard": `export const ListingChip=()=>null;`, "@/screens/PublishCard": `export const ListingChip=()=>null;`,
"@/screens/PublishDialog": `export const PublishRealmDialog=()=>null;`, "@/screens/PublishDialog": `export const PublishRealmDialog=()=>null;`,
"@/lib/registry": `export const useRegistryStatus=()=>({status:null});`, "@/lib/registry": `export const useRegistryStatus=()=>({status:null});`,
@@ -28,6 +29,9 @@ const bundle = await rolldown({
external: (id, importer) => id === "react/jsx-runtime" || id === "lucide-react" || (id === "react" && !importer?.endsWith("Overview.tsx")), external: (id, importer) => id === "react/jsx-runtime" || id === "lucide-react" || (id === "react" && !importer?.endsWith("Overview.tsx")),
plugins: [{ name: "overview-test", plugins: [{ name: "overview-test",
resolveId(id, importer) { resolveId(id, importer) {
if (id === "./ForceStopDialog") return "\0" + id;
if (id === "@/lib/serverLifecycle") return fileURLToPath(new URL("../src/lib/serverLifecycle.ts", import.meta.url));
if (id === "@/components/ui/split-button") return fileURLToPath(new URL("../src/components/ui/split-button.tsx", import.meta.url));
if (id.startsWith("@/") || (id === "react" && importer?.endsWith("Overview.tsx"))) return "\0" + id; if (id.startsWith("@/") || (id === "react" && importer?.endsWith("Overview.tsx"))) return "\0" + id;
}, },
load(id) { load(id) {
+27
View File
@@ -0,0 +1,27 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";
import { releasesForUpdate, localizeNotes } from "../src/lib/releaseHistoryModel.ts";
const release = (version, prerelease = false) => ({ version, prerelease, notes: [], tag: version, date: "2026-10-28" });
test("intermediate update shows only versions actually being installed", () => {
const records = [release("0.9.0"), release("0.10.0"), release("0.11.0"), release("0.10.1", true)];
assert.deepEqual(releasesForUpdate(records, "0.9.0", "0.10.0").map(r => r.version), ["0.10.0"]);
assert.deepEqual(releasesForUpdate(records, "0.9.0", "0.11.0").map(r => r.version), ["0.10.0", "0.11.0"]);
assert.deepEqual(releasesForUpdate(records, "custom", "0.10.0").map(r => r.version), ["0.10.0"]);
assert.deepEqual(releasesForUpdate(records, "0.10.0", "0.10.0"), []);
});
test("a changed or partly translated record falls back as a whole", () => {
assert.deepEqual(localizeNotes(["Changed", "New"], { Changed: "Переведено" }), { notes: ["Changed", "New"], fallback: true });
});
test("latest published Manager and server records have complete translations in five languages", () => {
const translations = JSON.parse(readFileSync(new URL("../src/data/latest-note-translations.json", import.meta.url)));
for (const component of ["server", "manager"]) {
const path = component === "server" ? "../src/data/server-history.json" : "../changelog/history.json";
const history = JSON.parse(readFileSync(new URL(path, import.meta.url)));
const latest = history.releases.at(-1);
for (const locale of ["ru", "de", "fr", "es", "zh"]) {
assert.equal(localizeNotes(latest.notes, translations[component][locale]).fallback, false, `${component}/${locale}`);
}
}
});
+62
View File
@@ -0,0 +1,62 @@
import assert from "node:assert/strict";
import test from "node:test";
import { registerHooks } from "node:module";
let handler;
let enabled = true;
let closeToTray = false;
let nextUpdate = null;
const calls = [];
globalThis.__closeTest = {
invoke: async (cmd, args) => { calls.push([cmd, args]); return cmd === "close_to_tray" ? closeToTray : undefined; },
window: { onCloseRequested: async cb => { handler = cb; return () => { handler = null; }; } },
check: async () => nextUpdate,
};
globalThis.localStorage = { getItem: () => enabled ? "on" : "off", setItem() {} };
registerHooks({ resolve(id, context, next) {
const stubs = {
react: "export const useSyncExternalStore=(subscribe,read)=>read();",
"@tauri-apps/api/core": "export const invoke=(...a)=>globalThis.__closeTest.invoke(...a);",
"@tauri-apps/api/window": "export const getCurrentWindow=()=>globalThis.__closeTest.window;",
"@tauri-apps/plugin-updater": "export const check=()=>globalThis.__closeTest.check();",
"@tauri-apps/plugin-process": "export const relaunch=async()=>{};",
};
if (id in stubs) return { shortCircuit:true, url:"data:text/javascript,"+encodeURIComponent(stubs[id]) };
return next(id, context);
}});
const { installOnClose, lookForUpdate } = await import("../src/lib/selfUpdate.ts");
async function close() {
const stop = installOnClose();
await Promise.resolve();
let prevented = false;
await handler({ preventDefault() { prevented = true; } });
assert.equal(prevented, true, "Tauri must never auto-destroy the hidden main window");
stop();
}
test("ordinary close delegates to native preferences without destroying the window", async () => {
calls.length = 0;
await close();
assert.deepEqual(calls, [["close_manager", undefined]]);
});
test("a cached update with automatic updates off still uses native close preferences", async () => {
nextUpdate = { version:"99", download:async()=>{}, install:async()=>{throw new Error("should not install")} };
await lookForUpdate({download:true});
enabled=false;calls.length=0;
await close();
assert.deepEqual(calls, [["close_manager", undefined]]);
});
test("failed automatic installation releases exit mode and preserves ordinary close handling", async () => {
enabled=true;calls.length=0;
await close();
assert.deepEqual(calls, [["close_to_tray",undefined],["manager_installing",{enabled:true}],["manager_installing",{enabled:false}],["close_manager",undefined]]);
});
test("minimizing to tray never starts a cached automatic installation", async () => {
await lookForUpdate({download:true});
closeToTray=true;calls.length=0;
await close();
assert.deepEqual(calls, [["close_to_tray",undefined],["close_manager",undefined]]);
});
+64
View File
@@ -0,0 +1,64 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ServerLifecycle, serverLifecycle } from "../src/lib/serverLifecycle.ts";
test("polls during a slow deliberate stop never rearm crash restart", () => {
const state = new ServerLifecycle();
state.observe(true, false, false);
state.request("stopping");
for (let i = 0; i < 50; i++) assert.equal(state.observe(true, true, false), false);
assert.equal(state.observe(false, false, false), false);
assert.equal(state.observe(false, false, false), false);
state.request("starting");
state.complete("starting");
state.observe(true, false, false);
assert.equal(state.observe(false, false, false), true);
assert.equal(state.observe(false, false, false), false);
});
test("update validation and rollback shutdowns are not crashes", () => {
const state = new ServerLifecycle();
state.observe(true, false, false);
assert.equal(state.observe(false, false, true), false);
assert.equal(state.observe(false, false, false), false);
state.observe(true, false, false);
assert.equal(state.observe(false, false, true), false);
state.observe(true, false, false);
assert.equal(state.observe(false, false, false), true);
});
test("navigation retains a pending stop and a later external start rearms detection", () => {
const state = serverLifecycle("navigation");
state.observe(true, false, false);
state.request("stopping");
const returned = serverLifecycle("navigation");
assert.equal(returned, state);
assert.equal(returned.observe(false, false, false), false);
returned.complete("stopping");
assert.equal(returned.observe(false, false, false), false);
returned.observe(true, false, false);
assert.equal(returned.observe(false, false, false), true);
});
test("an update between status polls cannot look like a crash after completion", () => {
const state = new ServerLifecycle();
state.observe(true, false, false);
state.beginMaintenance();
state.endMaintenance();
assert.equal(state.observe(false, false, false), false);
state.observe(true, false, false);
assert.equal(state.observe(false, false, false), true);
});
test("an intentional restart remains suppressed across navigation until the action completes", () => {
const state = serverLifecycle("restart-navigation");
state.observe(true, false, false);
state.request("restarting");
const returned = serverLifecycle("restart-navigation");
assert.equal(returned.observe(false, false, false), false);
assert.equal(returned.observe(true, false, false), false);
returned.complete("restarting");
returned.observe(true, false, false);
assert.equal(returned.observe(false, false, false), true);
});
+1
View File
@@ -16,6 +16,7 @@ globalThis.__hotfixApi = {
}; };
registerHooks({ resolve(specifier, context, next) { registerHooks({ resolve(specifier, context, next) {
if (specifier === "react") return { shortCircuit: true, url: "data:text/javascript,export const useSyncExternalStore=(subscribe,getSnapshot)=>getSnapshot();export const useState=()=>{throw new Error('React state is not used in this test');};" }; if (specifier === "react") return { shortCircuit: true, url: "data:text/javascript,export const useSyncExternalStore=(subscribe,getSnapshot)=>getSnapshot();export const useState=()=>{throw new Error('React state is not used in this test');};" };
if (specifier === "@/lib/serverLifecycle") return { shortCircuit: true, url: new URL("../src/lib/serverLifecycle.ts", import.meta.url).href };
if (specifier === "@/lib/api") return { shortCircuit: true, url: "data:text/javascript,export const api=globalThis.__hotfixApi;export const asUiError=e=>({human:{code:'unknown'},technical:e.message});" }; if (specifier === "@/lib/api") return { shortCircuit: true, url: "data:text/javascript,export const api=globalThis.__hotfixApi;export const asUiError=e=>({human:{code:'unknown'},technical:e.message});" };
if (specifier === "@tauri-apps/api/event") return { shortCircuit: true, url: "data:text/javascript,export const listen=async()=>()=>{};" }; if (specifier === "@tauri-apps/api/event") return { shortCircuit: true, url: "data:text/javascript,export const listen=async()=>()=>{};" };
if (specifier === "./serverUpdateStatus" && context.parentURL?.endsWith("/serverUpdate.ts")) return { shortCircuit: true, url: new URL("../src/lib/serverUpdateStatus.ts", import.meta.url).href }; if (specifier === "./serverUpdateStatus" && context.parentURL?.endsWith("/serverUpdate.ts")) return { shortCircuit: true, url: new URL("../src/lib/serverUpdateStatus.ts", import.meta.url).href };
+101 -1
View File
@@ -3,6 +3,7 @@ import runpy
import sys import sys
import tempfile import tempfile
import unittest import unittest
import time
from unittest.mock import patch from unittest.mock import patch
BRIDGE = pathlib.Path(__file__).resolve().parents[1] / 'crates/coa-core/src/launcher_bridge.py' BRIDGE = pathlib.Path(__file__).resolve().parents[1] / 'crates/coa-core/src/launcher_bridge.py'
@@ -63,6 +64,21 @@ def stop_all(config):
result = self.launch('stop-all', self.shutdown_fixture(console_error=error)) result = self.launch('stop-all', self.shutdown_fixture(console_error=error))
self.assertEqual(result['launcher']['calls'], ['console', 'terminate', 'wait', 'wait', 'mysql-shutdown']) self.assertEqual(result['launcher']['calls'], ['console', 'terminate', 'wait', 'wait', 'mysql-shutdown'])
def test_force_stop_terminates_only_the_owned_world_before_mysql(self):
body = self.shutdown_fixture(console_error=None)
body = body.replace("return world if name == 'world' else None", "return world if name == 'world' and 'terminate' not in calls else None")
result = self.launch('force-stop-all', body)
self.assertEqual(result['launcher']['calls'], ['terminate', 'wait', 'mysql-shutdown'])
def test_force_stop_rejects_foreign_or_reused_pids_and_a_world_that_stays_alive(self):
for options, message in [({'foreign': True}, 'ownership could not be verified'),
({'same': False}, 'ownership could not be verified'),
({'stopped': False}, 'database was left running')]:
with self.subTest(options=options):
with self.assertRaisesRegex(Exception, message):
self.launch('force-stop-all', self.shutdown_fixture(**options))
self.assertNotIn('mysql-shutdown', self.launcher['calls'])
def test_healthy_console_keeps_graceful_shutdown(self): def test_healthy_console_keeps_graceful_shutdown(self):
result = self.launch('stop-all', self.shutdown_fixture(console_error=None)) result = self.launch('stop-all', self.shutdown_fixture(console_error=None))
self.assertEqual(result['launcher']['calls'], ['console', 'wait', 'mysql-shutdown']) self.assertEqual(result['launcher']['calls'], ['console', 'wait', 'mysql-shutdown'])
@@ -103,7 +119,91 @@ def main():
wait_ready('world', 23456, 180) wait_ready('world', 23456, 180)
wait_ready('mysql', 12345, 900) wait_ready('mysql', 12345, 900)
''') ''')
self.assertEqual(result['launcher']['calls'], [('mysql', 300), ('world', 180), ('mysql', 900)]) calls = result['launcher']['calls']
self.assertEqual(calls[0], ('mysql', 300))
self.assertEqual(calls[2], ('mysql', 900))
self.assertEqual(calls[1][0], 'world')
self.assertAlmostEqual(calls[1][1], 1500, delta=1)
def world_start(self, *, game_at=420, console_at=480, dies_at=None, requested=180):
clock = [0.0]
def sleep(seconds): clock[0] += seconds
body = f'''
import time
calls = []
dies_at = {dies_at!r}
def wait_ready(name, port, seconds=180):
until = time.monotonic() + seconds
while time.monotonic() < until:
if dies_at is not None and time.monotonic() >= dies_at:
raise RuntimeError('world stopped during startup')
if time.monotonic() >= ({game_at!r} if port == 1 else {console_at!r}):
calls.append(port)
return
time.sleep(0.5)
raise RuntimeError('world is still starting')
def start_mysql(): pass
def settings(): return {{}}
def process(name): return {{'pid': 1}}
def ra(command, config): return 'server info ready'
def main():
wait_ready('world', 1, {requested})
wait_ready('world', 2, {requested})
'''
with patch('time.monotonic', side_effect=lambda: clock[0]), patch('time.sleep', side_effect=sleep):
result = self.launch('start-all', body)
return clock[0], result['launcher']['calls']
def test_open_ports_do_not_finish_startup_until_commands_are_processed(self):
clock = [0.0]
def sleep(seconds): clock[0] += seconds
body = """
import time
calls=[]
def wait_ready(*args): pass
def start_mysql(): pass
def settings(): return {}
def process(name): return {'pid': 1}
def ra(command, config):
calls.append(command)
if time.monotonic() < 5: raise TimeoutError('main loop is loading')
return 'ready'
def main():
wait_ready('world',1)
wait_ready('world',2)
"""
with patch('time.monotonic', side_effect=lambda: clock[0]), patch('time.sleep', side_effect=sleep):
result=self.launch('start-all',body)
self.assertEqual(clock[0],5)
self.assertEqual(set(result['launcher']['calls']),{'server info'})
def test_world_death_after_ports_open_is_a_startup_failure(self):
body="""
def wait_ready(*args): pass
def start_mysql(): pass
def settings(): return {}
def process(name): return None
def main(): pass
"""
with self.assertRaisesRegex(RuntimeError,'stopped before its console accepted'):
self.launch('start-world',body)
def test_legacy_coa_world_waits_for_both_ports_after_three_minutes(self):
elapsed, calls = self.world_start()
self.assertEqual((elapsed, calls), (480, [1, 2]))
def test_console_wait_shares_the_world_deadline(self):
with self.assertRaisesRegex(RuntimeError, 'still starting'):
self.world_start(game_at=1490, console_at=1510)
self.assertEqual(self.launcher['calls'], [1])
def test_world_exit_is_reported_without_waiting_out_the_extended_budget(self):
with self.assertRaisesRegex(RuntimeError, 'stopped during startup'):
self.world_start(dies_at=12)
self.assertEqual(self.launcher['calls'], [])
def test_existing_longer_world_timeout_is_preserved(self):
self.assertEqual(self.world_start(game_at=1600, console_at=1700, requested=1800), (1700, [1, 2]))
def test_stop_dispatch_does_not_prepare_or_start_anything(self): def test_stop_dispatch_does_not_prepare_or_start_anything(self):
result = self.launch('stop-all', ''' result = self.launch('stop-all', '''