diff --git a/Cargo.lock b/Cargo.lock index 8ea6f07..97bff9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index 236c7b1..2f57649 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/changelog.d/20261005-retry-update-startup.md b/changelog.d/20261005-retry-update-startup.md new file mode 100644 index 0000000..c32ab58 --- /dev/null +++ b/changelog.d/20261005-retry-update-startup.md @@ -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. diff --git a/crates/coa-core/examples/update_startup_e2e.rs b/crates/coa-core/examples/update_startup_e2e.rs new file mode 100644 index 0000000..69f2ec0 --- /dev/null +++ b/crates/coa-core/examples/update_startup_e2e.rs @@ -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"); +} diff --git a/crates/coa-core/src/driver.rs b/crates/coa-core/src/driver.rs index 6385678..573f699 100644 --- a/crates/coa-core/src/driver.rs +++ b/crates/coa-core/src/driver.rs @@ -114,8 +114,22 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result Result Result { + 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::>().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); + } } diff --git a/crates/coa-core/src/fsx.rs b/crates/coa-core/src/fsx.rs index 3b72052..983fa0c 100644 --- a/crates/coa-core/src/fsx.rs +++ b/crates/coa-core/src/fsx.rs @@ -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 { - 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); + } } diff --git a/crates/coa-core/src/update.rs b/crates/coa-core/src/update.rs index 98f0ec8..35412ff 100644 --- a/crates/coa-core/src/update.rs +++ b/crates/coa-core/src/update.rs @@ -259,7 +259,7 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result { 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 { 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 { 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 { + 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) -> Result { @@ -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); diff --git a/package-lock.json b/package-lock.json index 06939a5..a98828c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 59b8264..650bb96 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fc3b271..874169e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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 { + 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, 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, diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index fb87717..6340112 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -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", diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index feb7f7d..76e27d4 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -361,6 +361,7 @@ const de: Partial> = { "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.", diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index f325a59..0687612 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -394,6 +394,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.", diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index bf19888..6144524 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -361,6 +361,7 @@ const es: Partial> = { "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.", diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 0d2b4ee..8731974 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -361,6 +361,7 @@ const fr: Partial> = { "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.", diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 267c6c3..4f9b180 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -392,6 +392,7 @@ const ru: Partial> = { "upd.confirmBack": "Вернуться к предыдущей версии? Ваши персонажи и учётные записи не изменятся.", "upd.wentBack": "Выполнен возврат к предыдущей версии. Ваши данные не затронуты.", "upd.dialogTitle": "Выберите папку с пакетом обновления", + "upd.retryValidation": "Повторить запуск сервера", "upd.pendingBad": "Обновлённый сервер запустился некорректно", "upd.pendingUnfinished": "Предыдущее обновление не завершилось", "upd.safeBack": "Можно безопасно вернуться к предыдущей версии.", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index 0c26d5d..d5c9219 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -373,6 +373,7 @@ const zh = { "upd.confirmBack": "是否回滚至上一个版本?你的角色与账号数据不会受到影响。", "upd.wentBack": "已回滚至上一个版本。你的个人数据完好无损。", "upd.dialogTitle": "选择更新包文件夹", + "upd.retryValidation": "重试启动服务器", "upd.pendingBad": "更新后的服务器未能正常启动", "upd.pendingUnfinished": "先前的更新尚未完成", "upd.safeBack": "你可以安全回滚至先前的稳定版本。", diff --git a/src/lib/api.ts b/src/lib/api.ts index 5865a5b..afa8b38 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -430,6 +430,7 @@ export const api = { applyUpdate: (id: string, resolutions: Record, source?: string) => invoke<{ txn: UpdateTxn }>("apply_update", { id, source: source ?? null, resolutions }), rollbackUpdate: (id: string, txn: string) => invoke("rollback_update", { id, txn }), + retryUpdateValidation: (id: string, txn: string) => invoke("retry_update_validation", { id, txn }), population: (id: string) => invoke("get_population", { id }), stopSpawning: (id: string) => invoke<{ count: number }>("companions_stop_spawning", { id }), takeOffline: (id: string) => invoke<{ count: number }>("companions_take_offline", { id }), diff --git a/src/screens/SettingsHome.tsx b/src/screens/SettingsHome.tsx index b841f05..9d09611 100644 --- a/src/screens/SettingsHome.tsx +++ b/src/screens/SettingsHome.tsx @@ -23,7 +23,7 @@ export function SettingsHome({ serverId }: { serverId: string }) { const human = useHuman(); const [preview, setPreview] = useState(null); const [pending, setPending] = useState(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 }) {

{pending.state === "needs-decision" ? t("upd.pendingBad") : t("upd.pendingUnfinished")}

-

{pending.message ?? t("upd.safeBack")}

+

{pending.message ?? t("upd.safeBack")}

+ {pending.state === "needs-decision" && ( + + )}

{t("upd.backNote")}