From a6ae4e78a35f14cc50264e34e8c27591cdf77766 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Wed, 30 Sep 2026 15:36:07 +0500 Subject: [PATCH] Self-update in the background (install on close), module configs created from .dist, quiet-logging + table fixups in clean-base, backlog notes Co-Authored-By: Claude Sonnet 5.5 --- crates/coa-core/src/cleanbase.rs | 6 ++ crates/coa-core/src/config/mod.rs | 46 ++++++++++ crates/coa-core/src/install.rs | 1 + docs/ARCHITECTURE.md | 19 ++++ src-tauri/capabilities/default.json | 3 +- src-tauri/src/lib.rs | 12 +++ src/App.tsx | 25 +++++- src/components/UpdateBanner.tsx | 25 ++++++ src/i18n/locales/de.ts | 8 ++ src/i18n/locales/en.ts | 8 ++ src/i18n/locales/es.ts | 8 ++ src/i18n/locales/fr.ts | 8 ++ src/i18n/locales/ru.ts | 8 ++ src/lib/selfUpdate.ts | 133 ++++++++++++++++++++++++++++ src/screens/AboutCard.tsx | 103 +++++++++++---------- 15 files changed, 358 insertions(+), 55 deletions(-) create mode 100644 src/components/UpdateBanner.tsx create mode 100644 src/lib/selfUpdate.ts diff --git a/crates/coa-core/src/cleanbase.rs b/crates/coa-core/src/cleanbase.rs index 8830681..efc89a5 100644 --- a/crates/coa-core/src/cleanbase.rs +++ b/crates/coa-core/src/cleanbase.rs @@ -194,6 +194,12 @@ pub fn build(p: &Params, say: &dyn Fn(&str)) -> Result<()> { if let Some((id, why)) = report.failed { return Err(Error::Invalid(format!("Database update {id} failed: {why}"))); } + // 3b. A module script older than a table rename re-creates the old table next to the renamed one (the core then + // logs an error at every start). Fold its rows into the new table and drop it. + let both = db.query("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA='acore_world' AND TABLE_NAME IN ('item_template_ascension_compat','item_template_coa');")?; + if both.trim() == "2" { + db.query("INSERT IGNORE INTO acore_world.item_template_coa SELECT * FROM acore_world.item_template_ascension_compat; DROP TABLE acore_world.item_template_ascension_compat;")?; + } // 4. prove it is clean let accounts = db.query("SELECT COUNT(*) FROM acore_auth.account;")?; let chars = db.query("SELECT COUNT(*) FROM acore_characters.characters;")?; diff --git a/crates/coa-core/src/config/mod.rs b/crates/coa-core/src/config/mod.rs index 891976a..5f53037 100644 --- a/crates/coa-core/src/config/mod.rs +++ b/crates/coa-core/src/config/mod.rs @@ -119,6 +119,30 @@ pub struct SettingsView { } /// Keys whose value in the generated conf differs from the template (i.e. hand edits the launcher will reset). +/// Modules read `Core/configs/modules/.conf`, but packages ship only the documented `.conf.dist` (the active +/// files are the server owner's). Create every missing active file from its `.dist`, so a fresh server runs with the +/// documented defaults (for example `CoA.Enable = 1`, without which the Ascension client is dropped after login). +/// Existing files are never touched. Files the launcher writes itself are skipped. Returns the created file names. +pub fn materialize_module_configs(root: &Path) -> Result> { + let dir = root.join("Core").join("configs").join("modules"); + let mut created = Vec::new(); + let Ok(entries) = fs::read_dir(&dir) else { return Ok(created) }; + for e in entries.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + let Some(stem) = name.strip_suffix(".conf.dist") else { continue }; + if stem == "coa_bugreport" || stem == "mod_ascension_compat" { + continue; // written by the launcher at every start + } + let active = dir.join(format!("{stem}.conf")); + if !active.exists() { + fs::copy(e.path(), &active)?; + created.push(format!("{stem}.conf")); + } + } + created.sort(); + Ok(created) +} + pub fn drift(root: &Path) -> Result> { let t = targets(root, Scope::Server)?; let Some(generated) = &t.generated else { return Ok(Vec::new()) }; @@ -463,6 +487,28 @@ mod tests { pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect() } + #[test] + fn missing_module_configs_are_created_from_their_dist_and_existing_ones_are_kept() { + let (_d, root, _m) = fixture(); + let m = root.join("Core/configs/modules"); + fs::create_dir_all(&m).unwrap(); + fs::write(m.join("coa.conf.dist"), "CoA.Enable = 1 +").unwrap(); + fs::write(m.join("spellbook.conf.dist"), "Spellbook.Enable = 1 +").unwrap(); + fs::write(m.join("spellbook.conf"), "Spellbook.Enable = 0 +").unwrap(); + fs::write(m.join("coa_bugreport.conf.dist"), "x = 1 +").unwrap(); + assert_eq!(materialize_module_configs(&root).unwrap(), vec!["coa.conf".to_string()]); + assert_eq!(fs::read_to_string(m.join("coa.conf")).unwrap(), "CoA.Enable = 1 +"); + assert_eq!(fs::read_to_string(m.join("spellbook.conf")).unwrap(), "Spellbook.Enable = 0 +"); + assert!(!m.join("coa_bugreport.conf").exists()); + assert!(materialize_module_configs(&root).unwrap().is_empty()); + } + #[test] fn schemas_and_presets_are_self_consistent() { for scope in [Scope::Bots, Scope::Server] { diff --git a/crates/coa-core/src/install.rs b/crates/coa-core/src/install.rs index 7471273..4387c05 100644 --- a/crates/coa-core/src/install.rs +++ b/crates/coa-core/src/install.rs @@ -269,6 +269,7 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result { fs::remove_dir(&dest)?; // only succeeds for an empty folder (preflight verified) } fs::rename(&staging_root, &dest)?; + crate::config::materialize_module_configs(&dest)?; let mut meta = InstallMeta::new(InstallKind::New, &dest); meta.core.commit = m.core.commit.clone(); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 514ba08..caad090 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -496,3 +496,22 @@ The reference install classifies as **Healthy (customised)**: repack shape, bina release does not exist yet (only `edge` is published). The message is now human ("package not available yet"). Also open: the base package has no `Data\` (maps/dbc/vmaps, ~3.8 GB); the installer needs a "use my existing Data folder / download" step, and the owner must decide hosting/legal for game data before `base` is published. + +* **Modules tab** (requested 2026-09-30): install/manage optional server modules (bots, AH bot, Solocraft, ...). + Design decision: AzerothCore modules are compiled into `worldserver.exe`, so "install" cannot mean "drop files in". + Plan: CI builds one binary containing a curated set of modules, every one disabled by default; the Manager only + enables/disables and configures them (`Core/configs/modules/.conf`, schema-driven settings editor as for bots). + A `modules.json` catalogue travels with update packages (id, title, description, category, source repo + commit, + licence, conf file, enable key, settings schema, needed DB migrations, conflicts, status tested/experimental). + Adding a module = add it to the CI build list + catalogue entry, released as an ordinary update. Only modules tested + against the CoA fork and licence-compatible (AGPL/GPL, because the binary is distributed) are listed. The fork's own + CoA features (dynamic XP, ethereal bazaar, ...) appear in the same tab as "built in" toggles. +* **Known launcher leftovers:** the repack's `Scripts/manage.py` still renders `mod_ascension_compat.conf` at every start; + the core now ignores it ("is no longer read ... move its settings into coa.conf") - harmless warning, clean up together + with a launcher refresh. Migration-runner root cause for the re-created `item_template_ascension_compat` table (a module + script older than the rename is seen as pending) is worked around in `clean-base`, not fixed in the runner. +* **Bug found by the owner on the first clean install (2026-09-30):** login worked at the auth step but the game dropped + the connection. Causes: (1) the package shipped the maintainer's Trace-level logging templates (gigabytes of log per + hour, world thread stalled); (2) no active `coa.conf` (`CoA.Enable = 1`) because packages contain only `*.conf.dist`. + Fixed: `clean-base` restores quiet templates, `assemble-tree` ships `coa.conf.dist`, and the Manager creates missing + module `.conf` files from their `.dist` on install and before each start of a Manager-installed server. diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index e5b119b..5e22d8d 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -9,6 +9,7 @@ "core:default", "dialog:allow-open", "updater:default", - "process:allow-restart" + "process:allow-restart", + "core:window:allow-destroy" ] } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b30f8a1..2f455f8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -187,6 +187,18 @@ async fn run_verb(state: &AppState, id: String, verb: Verb) -> std::result::Resu #[tauri::command] async fn start_server(state: State<'_, AppState>, id: String) -> std::result::Result { + // Servers installed before module configs were created automatically get them now (missing files only). Imported + // servers are never written to by the Manager outside the launcher's own start-up. + if let Ok(root) = path_of(&state, &id) { + let _ = tauri::async_runtime::spawn_blocking(move || { + let (_, meta) = install_meta(&root)?; + if meta.kind == coa_core::registry::InstallKind::New { + coa_core::config::materialize_module_configs(&root)?; + } + Ok::<(), Error>(()) + }) + .await; + } let out = run_verb(&state, id.clone(), Verb::StartAll).await?; if out.ok { if let Ok(root) = path_of(&state, &id) { diff --git a/src/App.tsx b/src/App.tsx index 5029161..3018e18 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -4,10 +4,12 @@ import { Welcome } from "@/screens/Welcome"; import { ImportServer } from "@/screens/ImportServer"; import { Shell } from "@/screens/Shell"; import { InstallServer } from "@/screens/InstallServer"; +import { UpdateBanner } from "@/components/UpdateBanner"; +import { autoUpdateEnabled, installOnClose, lookForUpdate } from "@/lib/selfUpdate"; type View = "welcome" | "add" | "import" | "install"; -export default function App() { +function Main() { const [servers, setServers] = useState(null); const [view, setView] = useState("welcome"); const [activeId, setActiveId] = useState(null); @@ -75,3 +77,24 @@ export default function App() { /> ); } + +export default function App() { + // Quietly fetch a new Manager version a few seconds after start and install it when the window is closed. + useEffect(() => { + const stop = installOnClose(); + const timer = setTimeout(() => { + if (autoUpdateEnabled()) void lookForUpdate({ download: true }); + }, 5000); + return () => { + clearTimeout(timer); + stop(); + }; + }, []); + + return ( + <> +
+ + + ); +} diff --git a/src/components/UpdateBanner.tsx b/src/components/UpdateBanner.tsx new file mode 100644 index 0000000..6658df9 --- /dev/null +++ b/src/components/UpdateBanner.tsx @@ -0,0 +1,25 @@ +import { Download } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { useT } from "@/i18n"; +import { installNow, useSelfUpdate } from "@/lib/selfUpdate"; + +/** Small notice shown once a new Manager version is downloaded and waiting to be installed. */ +export function UpdateBanner() { + const t = useT(); + const s = useSelfUpdate(); + if (s.phase !== "ready" && s.phase !== "installing") return null; + return ( +
+ +
+

{t("selfupd.ready", { v: s.version ?? "" })}

+

{s.phase === "installing" ? t("selfupd.installing") : t("selfupd.onClose")}

+ {s.phase === "ready" && ( + + )} +
+
+ ); +} diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 91b501a..f99bd68 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -422,6 +422,14 @@ const de: Partial> = { "err.package_not_published.message": "Am Download-Ort wurde noch nichts veröffentlicht. Versuche es später erneut oder installiere aus einem lokalen Paketordner (Erweitert).", "err.network_unreachable.title": "Der Download-Server war nicht erreichbar", "err.network_unreachable.message": "Prüfe deine Internetverbindung und versuche es erneut.", + + // Manager self-update + "selfupd.ready": "Manager {v} ist installationsbereit", + "selfupd.onClose": "Es wird installiert, wenn du den Manager schließt. Deine Server laufen weiter.", + "selfupd.installing": "Installation läuft … der Manager wird geschlossen.", + "selfupd.now": "Jetzt installieren", + "about.auto": "Updates im Hintergrund laden und beim Schließen des Managers installieren", + "about.autoHint": "Ein Manager-Update stoppt oder verändert deine Server nie.", }; export default de; diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 3109abb..00d3c29 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -422,6 +422,14 @@ const en = { "err.package_not_published.message": "Nothing has been published at the download location. Try again later, or install from a local package folder (Advanced).", "err.network_unreachable.title": "Could not reach the download server", "err.network_unreachable.message": "Check your internet connection and try again.", + + // Manager self-update + "selfupd.ready": "Manager {v} is ready to install", + "selfupd.onClose": "It will be installed when you close the Manager. Your servers keep running.", + "selfupd.installing": "Installing… the Manager will close.", + "selfupd.now": "Install now", + "about.auto": "Download updates in the background and install them when I close the Manager", + "about.autoHint": "Your servers are never stopped or changed by a Manager update.", } as const; export default en; diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 19b86eb..a8caa4e 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -422,6 +422,14 @@ const es: Partial> = { "err.package_not_published.message": "Aún no se ha publicado nada en la ubicación de descarga. Inténtalo más tarde o instala desde una carpeta de paquete local (Avanzado).", "err.network_unreachable.title": "No se pudo contactar con el servidor de descargas", "err.network_unreachable.message": "Comprueba tu conexión a internet e inténtalo de nuevo.", + + // Manager self-update + "selfupd.ready": "Manager {v} está listo para instalarse", + "selfupd.onClose": "Se instalará cuando cierres el Manager. Tus servidores siguen funcionando.", + "selfupd.installing": "Instalando… el Manager se cerrará.", + "selfupd.now": "Instalar ahora", + "about.auto": "Descargar las actualizaciones en segundo plano e instalarlas al cerrar el Manager", + "about.autoHint": "Una actualización del Manager nunca detiene ni cambia tus servidores.", }; export default es; diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 4dc36a0..df005b4 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -422,6 +422,14 @@ const fr: Partial> = { "err.package_not_published.message": "Rien n’a encore été publié à l’emplacement de téléchargement. Réessayez plus tard ou installez depuis un dossier de paquet local (Avancé).", "err.network_unreachable.title": "Impossible de joindre le serveur de téléchargement", "err.network_unreachable.message": "Vérifiez votre connexion internet et réessayez.", + + // Manager self-update + "selfupd.ready": "Manager {v} est prêt à être installé", + "selfupd.onClose": "Il sera installé à la fermeture du Manager. Vos serveurs continuent de fonctionner.", + "selfupd.installing": "Installation… le Manager va se fermer.", + "selfupd.now": "Installer maintenant", + "about.auto": "Télécharger les mises à jour en arrière-plan et les installer à la fermeture du Manager", + "about.autoHint": "Une mise à jour du Manager n’arrête ni ne modifie jamais vos serveurs.", }; export default fr; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 1731c8e..7889ffb 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -422,6 +422,14 @@ const ru: Partial> = { "err.package_not_published.message": "В месте загрузки пока ничего не опубликовано. Повторите позже или установите из локальной папки с пакетом (Дополнительно).", "err.network_unreachable.title": "Не удалось связаться с сервером загрузки", "err.network_unreachable.message": "Проверьте подключение к интернету и повторите попытку.", + + // Manager self-update + "selfupd.ready": "Менеджер {v} готов к установке", + "selfupd.onClose": "Он установится, когда вы закроете менеджер. Ваши серверы продолжат работать.", + "selfupd.installing": "Установка… менеджер закроется.", + "selfupd.now": "Установить сейчас", + "about.auto": "Скачивать обновления в фоне и устанавливать их, когда я закрою менеджер", + "about.autoHint": "Обновление менеджера никогда не останавливает и не меняет ваши серверы.", }; export default ru; diff --git a/src/lib/selfUpdate.ts b/src/lib/selfUpdate.ts new file mode 100644 index 0000000..47c498c --- /dev/null +++ b/src/lib/selfUpdate.ts @@ -0,0 +1,133 @@ +import { useSyncExternalStore } from "react"; +import { getCurrentWindow } from "@tauri-apps/api/window"; +import { check, type Update } from "@tauri-apps/plugin-updater"; +import { relaunch } from "@tauri-apps/plugin-process"; + +/** + * Manager self-update: look for a new version in the background, download it quietly, and install it when the window is + * closed (or right away when asked). Servers are separate processes, so updating the Manager never touches them. + */ +export type Phase = "idle" | "checking" | "downloading" | "ready" | "installing" | "error" | "current"; +export interface SelfUpdateState { + phase: Phase; + version?: string; + notes?: string; + percent: number | null; + /** Raw error text, kept for the details line (the UI shows a friendly message). */ + error?: string; +} + +const AUTO_KEY = "coa-auto-update"; +let state: SelfUpdateState = { phase: "idle", percent: null }; +let update: Update | null = null; +const listeners = new Set<() => void>(); + +function set(next: Partial) { + state = { ...state, ...next }; + listeners.forEach((l) => l()); +} + +export function autoUpdateEnabled(): boolean { + try { + return localStorage.getItem(AUTO_KEY) !== "off"; + } catch { + return true; + } +} + +export function setAutoUpdate(on: boolean) { + try { + localStorage.setItem(AUTO_KEY, on ? "on" : "off"); + } catch { + /* ignore */ + } + listeners.forEach((l) => l()); +} + +/** Look for a new version. With `download` it also fetches the installer so it is ready to install on exit. */ +export async function lookForUpdate(opts: { download: boolean }): Promise { + if (state.phase === "checking" || state.phase === "downloading" || state.phase === "installing") return; + set({ phase: "checking", error: undefined, percent: null }); + try { + const u = await check(); + if (!u) { + update = null; + set({ phase: "current", version: undefined }); + return; + } + update = u; + set({ version: u.version, notes: u.body ?? undefined }); + if (!opts.download) { + set({ phase: "idle" }); + return; + } + await downloadPending(); + } catch (e) { + set({ phase: "error", error: String(e) }); + } +} + +async function downloadPending(): Promise { + if (!update) return; + set({ phase: "downloading", percent: 0 }); + let total = 0; + let done = 0; + try { + await update.download((e) => { + if (e.event === "Started") total = e.data.contentLength ?? 0; + if (e.event === "Progress") { + done += e.data.chunkLength; + if (total) set({ percent: Math.round((done / total) * 100) }); + } + }); + set({ phase: "ready", percent: 100 }); + } catch (e) { + set({ phase: "error", error: String(e), percent: null }); + } +} + +/** Download (if needed) and install now. The installer ends this process; `relaunch` is the fallback. */ +export async function installNow(): Promise { + if (!update) return; + try { + if (state.phase !== "ready") await downloadPending(); + if (state.phase !== "ready") return; + set({ phase: "installing" }); + await update.install(); + await relaunch(); + } catch (e) { + set({ phase: "error", error: String(e) }); + } +} + +/** Install a downloaded update when the user closes the window. Call once at start-up. */ +export function installOnClose(): () => void { + let stop: (() => void) | undefined; + void getCurrentWindow() + .onCloseRequested(async (event) => { + if (state.phase !== "ready" || !update || !autoUpdateEnabled()) return; + event.preventDefault(); + try { + set({ phase: "installing" }); + await update.install(); + } catch (e) { + set({ phase: "error", error: String(e) }); + await getCurrentWindow().destroy(); + } + }) + .then((un) => { + stop = un; + }) + .catch(() => {}); + return () => stop?.(); +} + +export function useSelfUpdate(): SelfUpdateState { + return useSyncExternalStore( + (l) => { + listeners.add(l); + return () => listeners.delete(l); + }, + () => state, + ); +} diff --git a/src/screens/AboutCard.tsx b/src/screens/AboutCard.tsx index b9d480d..cc52bab 100644 --- a/src/screens/AboutCard.tsx +++ b/src/screens/AboutCard.tsx @@ -1,81 +1,78 @@ import { useEffect, useState } from "react"; import { getVersion } from "@tauri-apps/api/app"; -import { check, type Update } from "@tauri-apps/plugin-updater"; -import { relaunch } from "@tauri-apps/plugin-process"; import { Loader2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { useT } from "@/i18n"; +import { autoUpdateEnabled, installNow, lookForUpdate, setAutoUpdate, useSelfUpdate } from "@/lib/selfUpdate"; export function AboutCard() { const t = useT(); + const s = useSelfUpdate(); const [version, setVersion] = useState(""); - const [update, setUpdate] = useState(null); - const [busy, setBusy] = useState<"check" | "install" | null>(null); - const [percent, setPercent] = useState(null); - const [note, setNote] = useState(null); - const [error, setError] = useState(null); + const [auto, setAuto] = useState(autoUpdateEnabled()); + const [asked, setAsked] = useState(false); useEffect(() => { void getVersion().then(setVersion).catch(() => {}); }, []); - async function look() { - setBusy("check"); - setError(null); - setNote(null); - try { - const u = await check(); - setUpdate(u); - if (!u) setNote(t("about.upToDate")); - } catch { - setError(t("about.checkFailed")); - } finally { - setBusy(null); - } - } - - async function install() { - if (!update) return; - setBusy("install"); - setError(null); - let total = 0; - let done = 0; - try { - await update.downloadAndInstall((e) => { - if (e.event === "Started") total = e.data.contentLength ?? 0; - if (e.event === "Progress") { - done += e.data.chunkLength; - if (total) setPercent(Math.round((done / total) * 100)); - } - }); - await relaunch(); - } catch { - setError(t("about.installFailed")); - setBusy(null); - } - } + const busy = s.phase === "checking" || s.phase === "downloading" || s.phase === "installing"; return (

{t("app.name")}

{t("about.version", { v: version || "…" })}

-
- - {update && ( - )} - {percent !== null && busy === "install" && {percent}%} + {s.percent !== null && s.phase === "downloading" && ( + + {s.percent}% + + )}
- {update?.body &&

{update.body}

} - {note &&

{note}

} - {error &&

{error}

} + {s.version && s.notes && s.phase !== "current" &&

{s.notes}

} + {s.phase === "ready" &&

{t("selfupd.onClose")}

} + {asked && s.phase === "current" &&

{t("about.upToDate")}

} + {s.phase === "error" && ( +
+

{t("about.checkFailed")}

+ {s.error &&

{s.error}

} +
+ )}
); }