Compare commits

...
2 Commits
22 changed files with 298 additions and 34 deletions

No files matched your search

Generated
+3 -3
View File
@@ -491,7 +491,7 @@ dependencies = [
[[package]]
name = "coa-core"
version = "0.6.3"
version = "0.6.4"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -519,7 +519,7 @@ dependencies = [
[[package]]
name = "coa-release"
version = "0.6.3"
version = "0.6.4"
dependencies = [
"chrono",
"coa-core",
@@ -528,7 +528,7 @@ dependencies = [
[[package]]
name = "coa-server-manager"
version = "0.6.3"
version = "0.6.4"
dependencies = [
"coa-core",
"serde",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/coa-core", "crates/coa-release", "src-tauri"]
[workspace.package]
version = "0.6.3"
version = "0.6.4"
edition = "2021"
license = "AGPL-3.0-only"
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: players
title: Start your installed server or client without downloading an available update
---
Choose to update later and keep playing with your installed version. Interrupted server updates still require recovery before startup.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Finish a server update that was blocked by a startup failure
---
The Manager repairs the launcher import path and lets you retry startup for an already applied update. Successful validation finishes the update without replaying SQL or restoring old databases. Failure details are preserved and rollback remains available.
@@ -0,0 +1,19 @@
use coa_core::update::{Env, RepackEnv};
use std::path::PathBuf;
fn main() {
let root = PathBuf::from(std::env::args().nth(1).expect("disposable fixture path"));
assert_eq!(std::fs::read(root.join(".release-schema-fixture")).unwrap(), b"disposable release-schema fixture");
let meta = coa_core::registry::metadata_dir_for(&root).unwrap();
let env = RepackEnv { root: &root, meta_dir: &meta };
let result = env.validate();
let _ = coa_core::driver::run(&root, coa_core::driver::Verb::StopAll);
if let Err(error) = result {
eprintln!("{}", error);
for log in ["Core/Logs/auth-console.log", "Core/Logs/world-console.log", "Core/Logs/supervisor.log"] {
eprintln!("{log}:\n{}", coa_core::diag::redact(&coa_core::health::tail(&root.join(log), 8192)));
}
std::process::exit(1);
}
println!("Published server startup validation passed on the disposable fixture");
}
+65 -1
View File
@@ -114,8 +114,22 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
}
if matches!(verb, Verb::StartAll | Verb::StartWorld) { crate::modules::ensure_bot_exclusivity(&root)?; }
let (python, script) = launcher(&root)?;
let original = std::fs::read_to_string(&script)?;
let patched = patch_launcher_imports(&original)?;
if original != patched {
fsx::atomic_write(&script, patched.as_bytes())?;
if let Ok(dir) = crate::registry::metadata_dir_for(&root) {
if let Ok((_, mut meta)) = crate::registry::MetaDir::open(&dir) {
if meta.original_hashes.get("Scripts/manage.py") == Some(&fsx::sha256_bytes(original.as_bytes())) {
meta.original_hashes.insert("Scripts/manage.py".into(), fsx::sha256_bytes(patched.as_bytes()));
fsx::atomic_write_json(&dir.join("install.json"), &meta)?;
}
}
}
}
let mut cmd = Command::new(&python);
cmd.arg("-B").arg(&script).arg(verb.arg()).current_dir(&root).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
cmd.arg("-B").arg("-c").arg(LAUNCH_SCRIPT).arg(&script).arg(verb.arg())
.current_dir(&root).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
@@ -169,6 +183,35 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
Ok(DriverOutcome { ok, exit_code, code, human: code.map(ErrorCode::human), output })
}
const LAUNCH_SCRIPT: &str = "import runpy,sys;from pathlib import Path;script=sys.argv[1];sys.path.insert(0,str(Path(script).resolve().parent));sys.argv=sys.argv[1:];runpy.run_path(script,run_name='__main__')";
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
if !text.contains("from squid_playerbots import") || text.contains(line) { return Ok(text.into()); }
let root = "ROOT = Path(__file__).resolve().parents[1]";
if !text.contains(root) || !text.lines().any(|line| line.trim() == "import sys") {
return Err(Error::Invalid("The server launcher cannot load its integration scripts. Repair its program files.".into()));
}
Ok(text.replacen(root, &format!("{root}\n{line}"), 1))
}
pub(crate) fn launcher_matches(signed: &str, actual: &[u8]) -> bool {
if signed.as_bytes() == actual { return true; }
if patch_launcher_imports(signed).is_ok_and(|s| s.as_bytes() == actual) { return true; }
crate::realms::patch_launcher(signed).is_ok_and(|s| s.as_bytes() == actual
|| patch_launcher_imports(&s).is_ok_and(|p| p.as_bytes() == actual))
}
pub(crate) fn startup_failure(root: &Path, started: &DriverOutcome) -> String {
let code = started.code.filter(|c| *c != ErrorCode::Unknown)
.or_else(|| crate::health::diagnose_installation(root));
let title = code.map(|c| c.human().title).unwrap_or("The server did not become ready");
let output = crate::diag::redact(&started.output);
let lines: Vec<_> = output.lines().rev().take(12).collect();
if lines.is_empty() { title.into() }
else { format!("{title}\n{}", lines.into_iter().rev().collect::<Vec<_>>().join("\n")) }
}
#[cfg(test)]
mod tests {
use super::*;
@@ -187,4 +230,25 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
assert!(run(dir.path(), Verb::StartAll).is_err());
}
#[test]
fn startup_failure_keeps_the_launcher_reason_without_secrets() {
let dir = tempfile::tempdir().unwrap();
let started = DriverOutcome { ok: false, exit_code: Some(1), code: Some(ErrorCode::Unknown),
human: Some(ErrorCode::Unknown.human()),
output: "appPassword=private\nModuleNotFoundError: No module named 'squid_playerbots'".into() };
let reason = startup_failure(dir.path(), &started);
assert!(reason.contains("ModuleNotFoundError"));
assert!(!reason.contains("private"));
assert!(!reason.contains("Something went wrong"));
}
#[test]
fn launcher_import_fix_is_idempotent_and_retains_other_code() {
let text = "import sys\nROOT = Path(__file__).resolve().parents[1]\nfrom squid_playerbots import validate_bots\ncustom = 42\n";
let fixed = patch_launcher_imports(text).unwrap();
assert!(fixed.contains("sys.path.insert(0, str(Path(__file__).resolve().parent))"));
assert!(fixed.ends_with("custom = 42\n"));
assert_eq!(patch_launcher_imports(&fixed).unwrap(), fixed);
}
}
+9 -1
View File
@@ -174,7 +174,8 @@ pub fn sha256_bytes(bytes: &[u8]) -> String {
/// Free bytes on the volume that holds `path` (or its nearest existing ancestor).
pub fn free_space(path: &Path) -> Result<u64> {
let mut cursor = Some(path);
let path = std::path::absolute(path)?;
let mut cursor = Some(path.as_path());
while let Some(p) = cursor {
if p.exists() {
return Ok(fs4::available_space(p)?);
@@ -281,4 +282,11 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
assert!(matches!(require_space(dir.path(), u64::MAX / 2), Err(Error::InsufficientSpace { .. })));
}
#[test]
fn free_space_resolves_a_new_relative_directory() {
let path = Path::new("coa-schema-fixture-not-created").join("nested");
assert!(!path.exists());
assert!(free_space(&path).unwrap() > 0);
}
}
+116 -22
View File
@@ -259,7 +259,7 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
let _ = md;
step(report, "Checking the update", 2);
let (m, _) = fetch_manifest(&p.source, p.trusted_key)?;
let (m, manifest_bytes) = fetch_manifest(&p.source, p.trusted_key)?;
tracing::info!(root = %root.display(), from_version = ?meta.core.version, to_version = %m.version, migrations = m.migrations.len(), "server update selected");
check_manifest(&m)?;
let archive = m.archive.clone().ok_or_else(|| Error::InvalidManifest("no archive".into()))?;
@@ -267,6 +267,10 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
let tdir = txn_dir(meta_dir, &id)?;
let (tree, before) = (tdir.join("tree"), tdir.join("before"));
fs::create_dir_all(&before)?;
let signature = crate::pkgsource::fetch_small(&p.source, "manifest.json.sig")?;
crate::signing::verify(&manifest_bytes, &String::from_utf8_lossy(&signature), p.trusted_key)?;
fsx::atomic_write(&tdir.join("manifest.json"), &manifest_bytes)?;
fsx::atomic_write(&tdir.join("manifest.json.sig"), &signature)?;
fsx::atomic_write(&before.join("manager-install.json"), &fs::read(meta_dir.join("install.json"))?)?;
let mut txn = Txn { id: id.clone(), state: State::Prepared, from_version: meta.core.version.clone(), to_version: m.version.clone(), recovery_point: None, databases_started: false, ops: Vec::new(), message: None };
@@ -352,37 +356,80 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
return Ok(Outcome { txn, migrations: migrated });
}
// Commit
step(report, "Finishing", 96);
finish(root, meta_dir, &mut meta, &m, &tree, &mut txn)?;
step(report, "Done", 100);
let _ = archive;
Ok(Outcome { txn, migrations: migrated })
}
fn finish(root: &Path, meta_dir: &Path, meta: &mut InstallMeta, m: &Manifest, tree: &Path, txn: &mut Txn) -> Result<()> {
meta.core.version = Some(m.version.clone());
meta.core.commit = m.core.commit.clone().or(meta.core.commit);
meta.core.commit = m.core.commit.clone().or(meta.core.commit.clone());
for op in &txn.ops {
let hash = if op.path == "Scripts/manage.py" {
let staged = fs::read_to_string(tree.join(&op.path)).ok().and_then(|s| crate::realms::patch_launcher(&s).ok());
match (staged, fs::read(root.join(&op.path))) {
(Some(expected), Ok(actual)) if expected.as_bytes() == actual => fsx::sha256_bytes(&actual),
match (fs::read_to_string(tree.join(&op.path)), fs::read(root.join(&op.path))) {
(Ok(signed), Ok(actual)) if crate::driver::launcher_matches(&signed, &actual) => fsx::sha256_bytes(&actual),
_ => op.new_sha256.clone(),
}
} else { op.new_sha256.clone() };
meta.original_hashes.insert(op.path.clone(), hash);
if !meta.managed_files.contains(&op.path) {
meta.managed_files.push(op.path.clone());
if !meta.managed_files.contains(&op.path) { meta.managed_files.push(op.path.clone()); }
}
for file in &m.files {
if !txn.ops.iter().any(|op| op.path == file.path) {
let path = fsx::safe_join(root, &file.path)?;
if path.is_file() && fsx::sha256_file(&path)? == file.sha256 {
meta.original_hashes.insert(file.path.clone(), file.sha256.clone());
}
}
}
for i in items.iter().filter(|i| i.action == Action::Skip && i.reason.as_deref() == Some("already up to date")) {
if let Some(f) = m.files.iter().find(|f| f.path == i.path) {
meta.original_hashes.insert(f.path.clone(), f.sha256.clone());
}
}
fsx::atomic_write_json(&meta_dir.join("install.json"), &meta)?;
fsx::atomic_write(&meta_dir.join("manifests").join(format!("update-{}.json", m.version)), &serde_json::to_vec_pretty(&m)?)?;
fsx::atomic_write_json(&meta_dir.join("install.json"), meta)?;
fsx::atomic_write(&meta_dir.join("manifests").join(format!("update-{}.json", m.version)), &serde_json::to_vec_pretty(m)?)?;
txn.state = State::Committed;
save(meta_dir, &txn)?;
let _ = fs::remove_dir_all(&tree);
txn.message = None;
save(meta_dir, txn)?;
let _ = fs::remove_dir_all(tree);
prune(meta_dir, 3);
step(report, "Done", 100);
let _ = archive;
Ok(Outcome { txn, migrations: migrated })
Ok(())
}
pub fn retry_validation(root: &Path, meta_dir: &Path, id: &str, fallback: &Source, trusted_key: &str, env: &dyn Env) -> Result<Txn> {
let _lock = operation_lock(meta_dir)?;
let mut txn = load(meta_dir, id)?;
if txn.state != State::NeedsDecision || unfinished(meta_dir).is_none_or(|t| t.id != id) {
return Err(Error::Invalid("Only an applied update awaiting startup validation can be retried.".into()));
}
let dir = txn_dir(meta_dir, id)?;
let source = if dir.join("manifest.json").is_file() { Source::Dir(dir.clone()) } else { fallback.clone() };
let (manifest, _) = fetch_manifest(&source, trusted_key)?;
check_manifest(&manifest)?;
if manifest.version != txn.to_version || txn.ops.iter().any(|op| !op.done) {
return Err(Error::Invalid("The saved update does not match the applied transaction.".into()));
}
for op in txn.ops.iter().filter(|op| matches!(op.action, Action::Create | Action::Replace)) {
let path = fsx::safe_join(root, &op.path)?;
let file = manifest.files.iter().find(|f| f.path == op.path)
.ok_or_else(|| Error::Invalid("The update journal contains a file absent from the signed package.".into()))?;
if matches!(file.policy, ReplacePolicy::CreateIfMissing | ReplacePolicy::MergeConfig | ReplacePolicy::NeverTouch) { continue; }
let bytes = fs::read(&path)?;
let actual = fsx::sha256_bytes(&bytes);
let launcher = op.path == "Scripts/manage.py"
&& fs::read_to_string(dir.join("tree").join(&op.path)).ok()
.filter(|s| fsx::sha256_bytes(s.as_bytes()) == file.sha256)
.is_some_and(|s| crate::driver::launcher_matches(&s, &bytes));
if actual != file.sha256 && !launcher {
return Err(Error::Invalid(format!("{} changed since the update was applied; use repair or rollback.", op.path)));
}
}
env.ensure_stopped()?;
if let Err(error) = env.validate() {
txn.message = Some(format!("The updated server did not start correctly: {error}"));
save(meta_dir, &txn)?;
return Ok(txn);
}
let (_, mut meta) = MetaDir::open(meta_dir)?;
finish(root, meta_dir, &mut meta, &manifest, &dir.join("tree"), &mut txn)?;
Ok(txn)
}
fn fail_after_apply(p: &Params, txn: &mut Txn, before: &Path, tree: &Path, why: String, report: Option<ApplyReport>) -> Result<Outcome> {
@@ -696,7 +743,7 @@ impl Env for RepackEnv<'_> {
if healthy {
return Ok(());
}
let cause = started.human.map(|h| h.title.to_string()).or_else(|| crate::health::diagnose_installation(self.root).map(|c| c.human().title.to_string())).unwrap_or_else(|| "the server did not become ready".into());
let cause = crate::driver::startup_failure(self.root, &started);
// Leave the files unlocked so that a rollback can replace them.
let _ = crate::driver::run(self.root, crate::driver::Verb::StopAll);
Err(Error::Invalid(cause))
@@ -901,6 +948,53 @@ mod tests {
assert!(rollback(&w.root, &w.meta, &out.txn.id, &env).is_err(), "already rolled back");
}
#[test]
fn retrying_startup_commits_without_reapplying_sql_or_restoring_databases() {
let w = world(&[], true);
let env = Fake::ok();
env.healthy.set(false);
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
let calls = env.calls.borrow().len();
env.healthy.set(true);
let done = retry_validation(&w.root, &w.meta, &out.txn.id, &Source::Dir(w.pkg.clone()), &w.key, &env).unwrap();
assert_eq!(done.state, State::Committed);
assert_eq!(done.recovery_point, out.txn.recovery_point);
assert_eq!(&env.calls.borrow()[calls..], &["stop", "validate"]);
assert!(unfinished(&w.meta).is_none());
assert_eq!(MetaDir::open(&w.meta).unwrap().1.core.version.as_deref(), Some("2.0.0"));
}
#[test]
fn legacy_retry_uses_the_exact_signed_release_and_preserves_failure() {
let w = world(&[], false);
let env = Fake::ok();
env.healthy.set(false);
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
let dir = txn_dir(&w.meta, &out.txn.id).unwrap();
fs::remove_file(dir.join("manifest.json")).unwrap();
fs::remove_file(dir.join("manifest.json.sig")).unwrap();
let pending = retry_validation(&w.root, &w.meta, &out.txn.id, &Source::Dir(w.pkg.clone()), &w.key, &env).unwrap();
assert_eq!(pending.state, State::NeedsDecision);
assert_eq!(pending.recovery_point, out.txn.recovery_point);
assert!(pending.message.unwrap().contains("worldserver exited"));
rollback(&w.root, &w.meta, &out.txn.id, &env).unwrap();
assert!(retry_validation(&w.root, &w.meta, &out.txn.id, &Source::Dir(w.pkg.clone()), &w.key, &env).is_err());
}
#[test]
fn retry_rejects_modified_binaries_and_unsigned_manifests() {
let w = world(&[], false);
let env = Fake::ok();
env.healthy.set(false);
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
write(&w.root, "Core/worldserver.exe", b"unexpected binary");
assert!(retry_validation(&w.root, &w.meta, &out.txn.id, &Source::Dir(w.pkg.clone()), &w.key, &env).is_err());
write(&w.root, "Core/worldserver.exe", b"world-v2");
fs::write(txn_dir(&w.meta, &out.txn.id).unwrap().join("manifest.json.sig"), "invalid").unwrap();
assert!(retry_validation(&w.root, &w.meta, &out.txn.id, &Source::Dir(w.pkg.clone()), &w.key, &env).is_err());
assert_eq!(unfinished(&w.meta).unwrap().state, State::NeedsDecision);
}
#[test]
fn crash_recovery_uses_the_journal() {
let w = world(&[], false);
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "coa-server-manager",
"version": "0.6.3",
"version": "0.6.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "coa-server-manager",
"version": "0.6.3",
"version": "0.6.4",
"dependencies": {
"@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-dialog": "^2.8.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "coa-server-manager",
"private": true,
"version": "0.6.3",
"version": "0.6.4",
"license": "AGPL-3.0-only",
"type": "module",
"scripts": {
+14
View File
@@ -744,6 +744,19 @@ async fn rollback_update(state: State<'_, AppState>, id: String, txn: String) ->
.await
}
#[tauri::command]
async fn retry_update_validation(state: State<'_, AppState>, id: String, txn: String) -> std::result::Result<update::Txn, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || {
let dir = meta_dir(&root)?;
let pending = update::load(&dir, &txn)?;
let source = coa_core::pkgsource::Source::Url(format!("https://github.com/Corfirean/coa-server-build/releases/download/server-{}/", pending.to_version));
let env = update::RepackEnv { root: &root, meta_dir: &dir };
update::retry_validation(&root, &dir, &txn, &source, coa_core::signing::EMBEDDED_PUBLIC_KEY, &env)
}).await
}
#[tauri::command]
async fn get_population(state: State<'_, AppState>, id: String) -> std::result::Result<Option<coa_core::population::Population>, UiError> {
let root = path_of(&state, &id)?;
@@ -1558,6 +1571,7 @@ pub fn run() {
pending_update,
apply_update,
rollback_update,
retry_update_validation,
get_population,
get_performance,
companions_stop_spawning,
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "CoA Server Manager",
"version": "0.6.3",
"version": "0.6.4",
"identifier": "com.coa.servermanager",
"build": {
"beforeDevCommand": "npm run dev",
+3
View File
@@ -73,6 +73,8 @@ const de: Partial<Record<keyof typeof en, string>> = {
"btn.stop": "SERVER STOPPEN",
"btn.stopSmall": "Stoppen",
"btn.restart": "Neustart",
"btn.startWithoutUpdate": "Ohne Update starten",
"btn.playWithoutUpdate": "Ohne Update spielen",
"btn.play": "SPIELEN",
"btn.startPlay": "STARTEN & SPIELEN",
"btn.startingCaps": "STARTET …",
@@ -361,6 +363,7 @@ const de: Partial<Record<keyof typeof en, string>> = {
"upd.confirmBack": "Zur vorherigen Version zurückkehren? Deine Charaktere und Konten werden nicht verändert.",
"upd.wentBack": "Zur vorherigen Version zurückgekehrt. Deine Daten wurden nicht angetastet.",
"upd.dialogTitle": "Wähle einen Update-Paketordner",
"upd.retryValidation": "Serverstart erneut prüfen",
"upd.pendingBad": "Der aktualisierte Server ist nicht korrekt gestartet",
"upd.pendingUnfinished": "Ein früheres Update wurde nicht abgeschlossen",
"upd.safeBack": "Du kannst sicher zur vorherigen Version zurückkehren.",
+3
View File
@@ -104,6 +104,8 @@ const en = {
"btn.stop": "STOP SERVER",
"btn.stopSmall": "Stop",
"btn.restart": "Restart",
"btn.startWithoutUpdate": "Start without updating",
"btn.playWithoutUpdate": "Play without updating",
"btn.play": "PLAY",
"btn.startPlay": "START & PLAY",
"btn.startingCaps": "STARTING…",
@@ -394,6 +396,7 @@ const en = {
"upd.confirmBack": "Go back to the previous version? Your characters and accounts are not changed.",
"upd.wentBack": "Went back to the previous version. Your data was not touched.",
"upd.dialogTitle": "Choose an update package folder",
"upd.retryValidation": "Retry server startup",
"upd.pendingBad": "The updated server did not start correctly",
"upd.pendingUnfinished": "An earlier update did not finish",
"upd.safeBack": "You can safely go back to the previous version.",
+3
View File
@@ -73,6 +73,8 @@ const es: Partial<Record<keyof typeof en, string>> = {
"btn.stop": "DETENER SERVIDOR",
"btn.stopSmall": "Detener",
"btn.restart": "Reiniciar",
"btn.startWithoutUpdate": "Iniciar sin actualizar",
"btn.playWithoutUpdate": "Jugar sin actualizar",
"btn.play": "JUGAR",
"btn.startPlay": "INICIAR Y JUGAR",
"btn.startingCaps": "INICIANDO…",
@@ -361,6 +363,7 @@ const es: Partial<Record<keyof typeof en, string>> = {
"upd.confirmBack": "¿Volver a la versión anterior? Tus personajes y cuentas no se modifican.",
"upd.wentBack": "Se volvió a la versión anterior. Tus datos no se tocaron.",
"upd.dialogTitle": "Elige una carpeta de paquete de actualización",
"upd.retryValidation": "Reintentar iniciar el servidor",
"upd.pendingBad": "El servidor actualizado no se inició correctamente",
"upd.pendingUnfinished": "Una actualización anterior no terminó",
"upd.safeBack": "Puedes volver con seguridad a la versión anterior.",
+3
View File
@@ -73,6 +73,8 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"btn.stop": "ARRÊTER LE SERVEUR",
"btn.stopSmall": "Arrêter",
"btn.restart": "Redémarrer",
"btn.startWithoutUpdate": "Démarrer sans mise à jour",
"btn.playWithoutUpdate": "Jouer sans mise à jour",
"btn.play": "JOUER",
"btn.startPlay": "DÉMARRER ET JOUER",
"btn.startingCaps": "DÉMARRAGE…",
@@ -361,6 +363,7 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"upd.confirmBack": "Revenir à la version précédente ? Vos personnages et comptes ne sont pas modifiés.",
"upd.wentBack": "Retour à la version précédente effectué. Vos données n’ont pas été touchées.",
"upd.dialogTitle": "Choisissez un dossier de paquet de mise à jour",
"upd.retryValidation": "Réessayer de démarrer le serveur",
"upd.pendingBad": "Le serveur mis à jour n’a pas démarré correctement",
"upd.pendingUnfinished": "Une mise à jour précédente ne s’est pas terminée",
"upd.safeBack": "Vous pouvez revenir en toute sécurité à la version précédente.",
+3
View File
@@ -104,6 +104,8 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"btn.stop": "ОСТАНОВИТЬ СЕРВЕР",
"btn.stopSmall": "Остановить",
"btn.restart": "Перезапустить",
"btn.startWithoutUpdate": "Запустить без обновления",
"btn.playWithoutUpdate": "Играть без обновления",
"btn.play": "ИГРАТЬ",
"btn.startPlay": "ЗАПУСТИТЬ И ИГРАТЬ",
"btn.startingCaps": "ЗАПУСК…",
@@ -392,6 +394,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"upd.confirmBack": "Вернуться к предыдущей версии? Ваши персонажи и учётные записи не изменятся.",
"upd.wentBack": "Выполнен возврат к предыдущей версии. Ваши данные не затронуты.",
"upd.dialogTitle": "Выберите папку с пакетом обновления",
"upd.retryValidation": "Повторить запуск сервера",
"upd.pendingBad": "Обновлённый сервер запустился некорректно",
"upd.pendingUnfinished": "Предыдущее обновление не завершилось",
"upd.safeBack": "Можно безопасно вернуться к предыдущей версии.",
+3
View File
@@ -85,6 +85,8 @@ const zh = {
"btn.stop": "停止服务器",
"btn.stopSmall": "停止",
"btn.restart": "重启",
"btn.startWithoutUpdate": "不更新启动服务器",
"btn.playWithoutUpdate": "不更新开始游戏",
"btn.play": "开始游戏",
"btn.startPlay": "启动并开始游戏",
"btn.startingCaps": "正在启动…",
@@ -373,6 +375,7 @@ const zh = {
"upd.confirmBack": "是否回滚至上一个版本?你的角色与账号数据不会受到影响。",
"upd.wentBack": "已回滚至上一个版本。你的个人数据完好无损。",
"upd.dialogTitle": "选择更新包文件夹",
"upd.retryValidation": "重试启动服务器",
"upd.pendingBad": "更新后的服务器未能正常启动",
"upd.pendingUnfinished": "先前的更新尚未完成",
"upd.safeBack": "你可以安全回滚至先前的稳定版本。",
+1
View File
@@ -430,6 +430,7 @@ export const api = {
applyUpdate: (id: string, resolutions: Record<string, "keep" | "replace">, source?: string) =>
invoke<{ txn: UpdateTxn }>("apply_update", { id, source: source ?? null, resolutions }),
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }),
population: (id: string) => invoke<Population | null>("get_population", { id }),
stopSpawning: (id: string) => invoke<{ count: number }>("companions_stop_spawning", { id }),
takeOffline: (id: string) => invoke<{ count: number }>("companions_take_offline", { id }),
+10
View File
@@ -274,6 +274,11 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{transitioning ? (action === "stopping" ? t("btn.stoppingCaps") : t("btn.startingCaps")) : t("btn.start")}
</Button>
)}
{!running && upd.available && (
<Button variant="secondary" size="sm" disabled={transitioning || upd.applying} onClick={() => run("starting")}>
{t("btn.startWithoutUpdate")}
</Button>
)}
{running && (
<Button variant="ghost" size="sm" disabled={transitioning || upd.applying} onClick={() => run("restarting")}>
{t("btn.restart")}
@@ -333,6 +338,11 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{t("btn.setupClient")}
</Button>
) : 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>
{anyUp && !running && !transitioning && (
+1
View File
@@ -74,6 +74,7 @@ export function RemoteClient({ onHost }: { onHost: () => void }) {
</form>
<p className="mt-3 text-sm text-muted">{t("remote.accountHint")}</p>
<Button variant="primary" className="mt-4" disabled={loading || busy || !savedHost || host.trim() !== savedHost || status === null} onClick={play}>{t("btn.play")}</Button>
{status?.linked && status.update_available && <Button variant="secondary" className="mt-4 ml-3" disabled={loading || busy || !savedHost || host.trim() !== savedHost} onClick={() => void launch()}>{t("btn.playWithoutUpdate")}</Button>}
{note && <p className="mt-3 text-sm text-ok" role="status">{note}</p>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Card>
+23 -2
View File
@@ -23,7 +23,7 @@ export function SettingsHome({ serverId }: { serverId: string }) {
const human = useHuman();
const [preview, setPreview] = useState<UpdatePreview | null>(null);
const [pending, setPending] = useState<UpdateTxn | null>(null);
const [localBusy, setBusy] = useState<"check" | "rollback" | 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;
@@ -85,6 +85,21 @@ export function SettingsHome({ serverId }: { serverId: string }) {
}
}
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 { setBusy(null); }
}
async function browse() {
const p = await open({ directory: true, multiple: false, title: t("upd.dialogTitle") });
if (typeof p === "string") setSource(p);
@@ -100,7 +115,13 @@ export function SettingsHome({ serverId }: { serverId: string }) {
<p className="font-medium text-warn">
{pending.state === "needs-decision" ? t("upd.pendingBad") : t("upd.pendingUnfinished")}
</p>
<p className="mt-1 text-sm text-muted">{pending.message ?? t("upd.safeBack")}</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 />}