From 838cc07e738c5d6d842c1669aced98a7fc5068d5 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: Thu, 8 Oct 2026 07:33:07 +0500 Subject: [PATCH] Add the SQUID dashboard tab and make a stopped server stay stopped after updating The Dashboard tab (shown with SQUID Playerbots) downloads the dashboard release of the bots' release series, starts it on a free local port and shows it in the window. After an update, a server that was stopped stays stopped unless the owner asked for it to start. Co-Authored-By: Claude Sonnet 5.5 --- changelog.d/20261008-squid-dashboard-tab.md | 7 + .../20261008-start-after-update-options.md | 4 +- crates/coa-core/src/dashboard.rs | 286 ++++++++++++++++++ crates/coa-core/src/lib.rs | 1 + src-tauri/src/lib.rs | 28 ++ src-tauri/tauri.conf.json | 2 +- src/i18n/locales/de.ts | 18 +- src/i18n/locales/en.ts | 18 +- src/i18n/locales/es.ts | 18 +- src/i18n/locales/fr.ts | 18 +- src/i18n/locales/ru.ts | 18 +- src/i18n/locales/zh.ts | 18 +- src/lib/api.ts | 14 + src/lib/serverUpdate.ts | 6 +- src/lib/updatePrefs.ts | 6 +- src/screens/DashboardPage.tsx | 109 +++++++ src/screens/Shell.tsx | 10 +- 17 files changed, 564 insertions(+), 17 deletions(-) create mode 100644 changelog.d/20261008-squid-dashboard-tab.md create mode 100644 crates/coa-core/src/dashboard.rs create mode 100644 src/screens/DashboardPage.tsx diff --git a/changelog.d/20261008-squid-dashboard-tab.md b/changelog.d/20261008-squid-dashboard-tab.md new file mode 100644 index 0000000..3459f42 --- /dev/null +++ b/changelog.d/20261008-squid-dashboard-tab.md @@ -0,0 +1,7 @@ +--- +area: manager +type: added +audience: admins +title: A Dashboard tab shows what the SQUID bots are doing +--- +With SQUID Playerbots on, the Dashboard tab downloads the dashboard release that matches your bots, starts it on this computer and shows it inside the Manager. diff --git a/changelog.d/20261008-start-after-update-options.md b/changelog.d/20261008-start-after-update-options.md index 10144fa..6244b5c 100644 --- a/changelog.d/20261008-start-after-update-options.md +++ b/changelog.d/20261008-start-after-update-options.md @@ -2,6 +2,6 @@ area: manager type: added audience: admins -title: Choose whether the server keeps running after an update and whether the game starts after a client update +title: A stopped server stays stopped after an update, unless you ask it to start --- -Settings has a switch for stopping the server again once its update has finished, and the client card has one for starting the game after the client has been updated. +Updating no longer leaves a server running that was stopped before. Settings has a switch to start it afterwards, and the client card has one to open the game after a client update. diff --git a/crates/coa-core/src/dashboard.rs b/crates/coa-core/src/dashboard.rs new file mode 100644 index 0000000..15b6b14 --- /dev/null +++ b/crates/coa-core/src/dashboard.rs @@ -0,0 +1,286 @@ +//! SQUID's bot dashboard (): a small web page, written in Python with +//! no dependencies, that shows where the bots are and what they do. It is kept in `Extras/SquidDashboard` of the server +//! folder and always comes from the release that matches the installed SQUID bots (same major and minor version), so the +//! page and the bots agree on what the database and the logs contain. +//! +//! The dashboard finds the repack by itself (`Settings/database.json` and `Settings/repack.json` two folders up), so the +//! Manager only has to download it and start it on a free port. Only the process the Manager started and recorded is ever +//! stopped, identified by PID and creation time. + +use std::io::Read; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; +use crate::fsx; +use crate::process::{self, ProcessIdentity}; + +const REPO: &str = "Zyth45/squidbots-dashboard"; +const DIR: &str = "Extras/SquidDashboard"; +const MARKER: &str = ".manager-dashboard.json"; +const PROCESS: &str = ".manager-dashboard-process.json"; +const FIRST_PORT: u16 = 8088; +const MAX_ARCHIVE: u64 = 60 * 1024 * 1024; +const MAX_UNPACKED: u64 = 150 * 1024 * 1024; + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Marker { + /// The dashboard release that is installed. + tag: String, + /// The SQUID release it was chosen for. + squid_tag: String, + port: u16, +} + +#[derive(Debug, Serialize)] +pub struct Status { + pub installed: bool, + /// Dashboard release installed. + pub tag: Option, + /// SQUID bots release found in the server. + pub squid_tag: Option, + /// The installed dashboard belongs to the installed bots' release series. + pub matches: bool, + pub running: bool, + pub port: u16, + pub url: String, +} + +fn dir(root: &Path) -> PathBuf { + root.join(DIR) +} + +fn read_marker(root: &Path) -> Option { + fsx::read_json(&dir(root).join(MARKER)).ok() +} + +/// `v1.9.1` -> `[1, 9, 1]`. +fn parse_tag(tag: &str) -> Option> { + let parts: Vec = tag.trim().trim_start_matches('v').split('.').map(|p| p.parse().ok()).collect::>()?; + (parts.len() >= 2).then_some(parts) +} + +/// Same major and minor version. +fn same_series(a: &str, b: &str) -> bool { + matches!((parse_tag(a), parse_tag(b)), (Some(a), Some(b)) if a[..2] == b[..2]) +} + +/// The newest dashboard release of the bots' series (`v1.9` serves bots `v1.9` and `v1.9.1`). +fn pick_tag(squid_tag: &str, available: &[String]) -> Option { + available.iter() + .filter(|tag| same_series(tag, squid_tag)) + .max_by_key(|tag| parse_tag(tag).unwrap_or_default()) + .cloned() +} + +fn safe_tag(tag: &str) -> bool { + !tag.is_empty() && tag.len() <= 40 && tag.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) +} + +fn squid_tag(root: &Path) -> Option { + crate::squid::release(root).and_then(|r| r.tag).filter(|t| safe_tag(t)) +} + +fn record_alive(root: &Path) -> Option { + let record: ProcessIdentity = fsx::read_json(&dir(root).join(PROCESS)).ok()?; + let inside = Path::new(&record.exe).starts_with(root); + (inside && process::is_alive(&record)).then_some(record) +} + +pub fn status(root: &Path) -> Status { + let marker = read_marker(root); + let installed = dir(root).join("squidbots.py").is_file() && marker.is_some(); + let squid = squid_tag(root); + let port = marker.as_ref().map(|m| m.port).unwrap_or(FIRST_PORT); + let running = installed && record_alive(root).is_some_and(|r| process::listeners().iter().any(|(p, pid)| *p == port && *pid == r.pid)); + Status { + installed, + matches: matches!((&marker, &squid), (Some(m), Some(s)) if same_series(&m.tag, s)), + tag: marker.map(|m| m.tag), + squid_tag: squid, + running, + port, + url: format!("http://localhost:{port}"), + } +} + +fn http() -> Result { + reqwest::blocking::Client::builder() + .user_agent(concat!("CoA-Server-Manager/", env!("CARGO_PKG_VERSION"))) + .timeout(std::time::Duration::from_secs(120)) + .build() + .map_err(|e| Error::Invalid(format!("Cannot prepare the download: {e}"))) +} + +fn download_error(e: impl std::fmt::Display) -> Error { + Error::NetworkUnreachable(e.to_string()) +} + +fn available_tags(client: &reqwest::blocking::Client) -> Result> { + #[derive(Deserialize)] + struct Tag { name: String } + let response = client.get(format!("https://api.github.com/repos/{REPO}/tags?per_page=100")).send().map_err(download_error)?; + if !response.status().is_success() { return Err(download_error(format!("GitHub answered {}", response.status()))); } + let tags: Vec = serde_json::from_str(&response.text().map_err(download_error)?).map_err(download_error)?; + Ok(tags.into_iter().map(|t| t.name).filter(|t| safe_tag(t)).collect()) +} + +/// Download the dashboard release that matches the installed bots and unpack it. A running dashboard is stopped first; +/// maps the owner extracted and other files of theirs are left alone. +pub fn install(root: &Path, report: &dyn Fn(&str)) -> Result { + let squid = squid_tag(root).ok_or_else(|| Error::Invalid("The version of the SQUID bots could not be read, so the matching dashboard cannot be chosen.".into()))?; + report("Looking for the matching dashboard"); + let client = http()?; + let tag = pick_tag(&squid, &available_tags(&client)?) + .ok_or_else(|| Error::Invalid(format!("There is no dashboard release for SQUID bots {squid} yet.")))?; + report("Downloading the dashboard"); + let response = client.get(format!("https://codeload.github.com/{REPO}/zip/refs/tags/{tag}")).send().map_err(download_error)?; + if !response.status().is_success() { return Err(download_error(format!("GitHub answered {}", response.status()))); } + let mut bytes = Vec::new(); + response.take(MAX_ARCHIVE + 1).read_to_end(&mut bytes).map_err(download_error)?; + if bytes.len() as u64 > MAX_ARCHIVE { return Err(Error::Invalid("The dashboard download is larger than expected and was rejected.".into())); } + + stop(root)?; + report("Unpacking the dashboard"); + let target = dir(root); + std::fs::create_dir_all(&target)?; + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| Error::Invalid(format!("The dashboard download is damaged: {e}")))?; + let mut total = 0u64; + let mut wrote_main = false; + for index in 0..archive.len() { + let mut file = archive.by_index(index).map_err(|e| Error::Invalid(format!("The dashboard download is damaged: {e}")))?; + if file.is_dir() { continue; } + // GitHub wraps everything in one folder named after the repository and release. + let Some(relative) = file.name().split_once('/').map(|(_, rest)| rest.to_string()) else { continue; }; + if relative.is_empty() || relative.starts_with(".github/") || relative.starts_with("docs/") { continue; } + total += file.size(); + if total > MAX_UNPACKED { return Err(Error::Invalid("The dashboard download unpacks to more than expected and was rejected.".into())); } + let destination = fsx::safe_join(&target, &relative)?; + let mut content = Vec::with_capacity(file.size() as usize); + file.read_to_end(&mut content)?; + fsx::atomic_write(&destination, &content)?; + wrote_main |= relative == "squidbots.py"; + } + if !wrote_main { return Err(Error::Invalid("The dashboard download did not contain the dashboard.".into())); } + let port = read_marker(root).map(|m| m.port).unwrap_or(FIRST_PORT); + fsx::atomic_write_json(&target.join(MARKER), &Marker { tag, squid_tag: squid, port })?; + Ok(status(root)) +} + +fn free_port(preferred: u16) -> Result { + let used: Vec = process::listeners().into_iter().map(|(port, _)| port).collect(); + std::iter::once(preferred).chain(FIRST_PORT..FIRST_PORT + 40).find(|p| !used.contains(p)) + .ok_or_else(|| Error::Invalid("No free port was found for the dashboard.".into())) +} + +/// Start the dashboard with the repack's own Python. Returns when it answers on its port. +pub fn start(root: &Path) -> Result { + let current = status(root); + if !current.installed { return Err(Error::Invalid("The dashboard is not installed.".into())); } + if current.running { return Ok(current); } + let python = root.join("Runtime/python/python.exe"); + if !python.is_file() { return Err(Error::Invalid("This server has no bundled Python, so the dashboard cannot run.".into())); } + let folder = dir(root); + let mut marker = read_marker(root).ok_or_else(|| Error::Invalid("The dashboard installation is incomplete.".into()))?; + marker.port = free_port(marker.port)?; + fsx::atomic_write_json(&folder.join(MARKER), &marker)?; + + let log_path = folder.join("dashboard.log"); + let log = std::fs::File::create(&log_path)?; + let mut command = std::process::Command::new(&python); + command.arg("-B").arg("squidbots.py").current_dir(&folder).env("COA_DASHBOARD_PORT", marker.port.to_string()) + .stdin(std::process::Stdio::null()).stdout(log.try_clone()?).stderr(log); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + } + let mut child = command.spawn()?; + let identity = process::identity(child.id()).ok_or_else(|| Error::Invalid("The dashboard exited at once.".into()))?; + fsx::atomic_write_json(&folder.join(PROCESS), &identity)?; + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + loop { + if process::listeners().iter().any(|(port, pid)| *port == marker.port && *pid == identity.pid) { return Ok(status(root)); } + if let Ok(Some(_)) = child.try_wait() { + let _ = std::fs::remove_file(folder.join(PROCESS)); + let tail = std::fs::read_to_string(&log_path).unwrap_or_default(); + let lines: Vec<&str> = tail.lines().rev().take(8).collect(); + return Err(Error::Invalid(format!("The dashboard stopped right after starting. {}", lines.into_iter().rev().collect::>().join("\n")))); + } + if std::time::Instant::now() > deadline { + let _ = stop(root); + return Err(Error::Invalid("The dashboard did not start in time. See Extras/SquidDashboard/dashboard.log.".into())); + } + std::thread::sleep(std::time::Duration::from_millis(300)); + } +} + +/// Stop the dashboard this Manager started (by recorded PID and creation time, never by name). +pub fn stop(root: &Path) -> Result<()> { + let record_file = dir(root).join(PROCESS); + if let Some(record) = record_alive(root) { + let mut command = std::process::Command::new("taskkill"); + command.args(["/PID", &record.pid.to_string(), "/T", "/F"]).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x0800_0000); + } + let _ = command.status(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while process::is_alive(&record) && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(200)); + } + if process::is_alive(&record) { return Err(Error::Invalid("The dashboard could not be stopped.".into())); } + } + let _ = std::fs::remove_file(record_file); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tags(list: &[&str]) -> Vec { list.iter().map(|s| s.to_string()).collect() } + + #[test] + fn the_dashboard_follows_the_bots_release_series() { + let available = tags(&["v1.8", "v1.9", "v1.9.2", "v2.0"]); + assert_eq!(pick_tag("v1.9", &available).as_deref(), Some("v1.9.2"), "the newest of the same series"); + assert_eq!(pick_tag("v1.9.1", &tags(&["v1.8", "v1.9"])).as_deref(), Some("v1.9"), "bots 1.9.1 use dashboard 1.9"); + assert_eq!(pick_tag("v1.8.1", &available).as_deref(), Some("v1.8")); + assert_eq!(pick_tag("v1.10", &available), None, "a later series has none yet"); + assert_eq!(pick_tag("main", &available), None); + assert!(same_series("v1.9", "v1.9.1") && !same_series("v1.9", "v1.8.9")); + } + + #[test] + fn tags_are_checked_before_they_reach_a_url() { + assert!(safe_tag("v1.9.1") && !safe_tag("v1.9/../x") && !safe_tag("") && !safe_tag("a b")); + } + + /// Needs the network: `cargo test -p coa-core dashboard -- --ignored`. + #[test] + #[ignore] + fn the_matching_release_is_downloaded_and_unpacked() { + let root = tempfile::tempdir().unwrap(); + let settings = root.path().join("Core/configs/modules/playerbots.conf.settings.json"); + fsx::atomic_write(&settings, br#"{"format":1,"tag":"v1.9.1","settings":[]}"#).unwrap(); + let installed = install(root.path(), &|step| println!("{step}")).unwrap(); + assert!(installed.installed && installed.matches); + assert_eq!(installed.tag.as_deref(), Some("v1.9")); + assert!(root.path().join("Extras/SquidDashboard/squidbots.py").is_file()); + assert!(!installed.running); + } + + #[test] + fn a_folder_without_the_dashboard_is_not_installed_or_running() { + let root = tempfile::tempdir().unwrap(); + let s = status(root.path()); + assert!(!s.installed && !s.running && !s.matches); + assert!(start(root.path()).is_err()); + assert!(stop(root.path()).is_ok()); + } +} diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index 968a16d..b105692 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -7,6 +7,7 @@ pub mod remote_client; pub mod clientdl; pub mod config; pub mod console; +pub mod dashboard; pub mod db; pub mod diag; pub mod docker; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 36a5bb8..06cfeff 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -365,6 +365,30 @@ async fn set_backup_location(state: State<'_, AppState>, id: String, path: Optio blocking(move || backup::set_location(&root, &meta_dir(&root)?, path.as_deref())).await } +#[tauri::command] +async fn dashboard_status(state: State<'_, AppState>, id: String) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || Ok(coa_core::dashboard::status(&root))).await +} + +#[tauri::command] +async fn dashboard_install(app: AppHandle, state: State<'_, AppState>, id: String) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || coa_core::dashboard::install(&root, &|step| { let _ = app.emit("dashboard-progress", step); })).await +} + +#[tauri::command] +async fn dashboard_start(state: State<'_, AppState>, id: String) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || coa_core::dashboard::start(&root)).await +} + +#[tauri::command] +async fn dashboard_stop(state: State<'_, AppState>, id: String) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || { coa_core::dashboard::stop(&root)?; Ok(coa_core::dashboard::status(&root)) }).await +} + #[tauri::command] fn list_backups(state: State<'_, AppState>, id: String) -> std::result::Result, UiError> { let root = path_of(&state, &id)?; @@ -1571,6 +1595,10 @@ pub fn run() { list_config_snapshots, restore_config_snapshot, list_backups, + dashboard_status, + dashboard_install, + dashboard_start, + dashboard_stop, backup_location, set_backup_location, create_backup, diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index eff0631..743c799 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -21,7 +21,7 @@ } ], "security": { - "csp": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost" + "csp": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost; frame-src http://localhost:* http://127.0.0.1:*" } }, "bundle": { diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 7eee400..ac023bd 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -827,7 +827,23 @@ const de: Partial> = { "set.searchAll": "Alle Einstellungen nach Name oder Beschreibung durchsuchen…", "set.search": "Einstellungen durchsuchen…", "upd.current": "Du bist auf dem neuesten Stand (Version {v}).", - "upd.startAfter": "Server nach dem Update starten (ausschalten, damit er nach dem Update wieder angehalten wird)", + "nav.dashboard": "Dashboard", + "q.dashboard": "Was tun die Bots gerade?", + "dash.title": "Bot-Dashboard", + "dash.intro": "SQUIDs Live-Seite zu den Bots: wo sie sind, was sie tun, was sie finden. Läuft nur auf diesem Computer.", + "dash.notInstalled": "Das Dashboard ist noch nicht installiert.", + "dash.willInstall": "Die zu deinen Bots {v} passende Version wird heruntergeladen.", + "dash.noSquid": "Die Version deiner SQUID-Bots konnte nicht gelesen werden.", + "dash.install": "Dashboard herunterladen", + "dash.versions": "Dashboard {dash} für Bots {bots}", + "dash.running": "läuft", + "dash.stopped": "angehalten", + "dash.mismatch": "Dieses Dashboard gehört nicht zu deinen Bots {bots}. Aktualisiere es, damit die Versionen passen.", + "dash.start": "Dashboard starten", + "dash.stop": "Dashboard anhalten", + "dash.openBrowser": "Im Browser öffnen", + "dash.update": "Dashboard aktualisieren", + "upd.startAfter": "Server nach dem Update starten (sonst bleibt ein angehaltener Server angehalten)", "client.startAfter": "Spiel nach dem Client-Update starten", "bk.folder": "Sicherungsordner", "bk.folderDefault": "Standard", diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 4c058c4..4354787 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -850,7 +850,23 @@ const en = { "set.searchAll": "Search all settings by name or description…", "set.search": "Search settings…", "upd.current": "You are up to date (version {v}).", - "upd.startAfter": "Start the server after updating it (turn off to stop it again once the update is done)", + "nav.dashboard": "Dashboard", + "q.dashboard": "What are the bots doing right now?", + "dash.title": "Bot dashboard", + "dash.intro": "SQUID's live page for the bots: where they are, what they do, what they find. It runs on this computer only.", + "dash.notInstalled": "The dashboard is not installed yet.", + "dash.willInstall": "The release that matches your bots {v} will be downloaded.", + "dash.noSquid": "The version of your SQUID bots could not be read.", + "dash.install": "Download the dashboard", + "dash.versions": "Dashboard {dash} for bots {bots}", + "dash.running": "running", + "dash.stopped": "stopped", + "dash.mismatch": "This dashboard does not belong to your bots {bots}. Update it so that they match.", + "dash.start": "Start the dashboard", + "dash.stop": "Stop the dashboard", + "dash.openBrowser": "Open in the browser", + "dash.update": "Update the dashboard", + "upd.startAfter": "Start the server after updating it (otherwise a stopped server stays stopped)", "client.startAfter": "Start the game after the client has been updated", "bk.folder": "Backup folder", "bk.folderDefault": "default", diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 418d13e..15177b3 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -827,7 +827,23 @@ const es: Partial> = { "set.searchAll": "Buscar en todos los ajustes por nombre o descripción…", "set.search": "Buscar ajustes…", "upd.current": "Estás al día (versión {v}).", - "upd.startAfter": "Iniciar el servidor tras actualizarlo (desactívalo para detenerlo de nuevo al terminar)", + "nav.dashboard": "Panel", + "q.dashboard": "¿Qué están haciendo los bots ahora?", + "dash.title": "Panel de bots", + "dash.intro": "La página en vivo de SQUID sobre los bots: dónde están, qué hacen, qué encuentran. Funciona solo en este equipo.", + "dash.notInstalled": "El panel aún no está instalado.", + "dash.willInstall": "Se descargará la versión que corresponde a tus bots {v}.", + "dash.noSquid": "No se pudo leer la versión de tus bots SQUID.", + "dash.install": "Descargar el panel", + "dash.versions": "Panel {dash} para bots {bots}", + "dash.running": "en marcha", + "dash.stopped": "detenido", + "dash.mismatch": "Este panel no corresponde a tus bots {bots}. Actualízalo para que coincidan.", + "dash.start": "Iniciar el panel", + "dash.stop": "Detener el panel", + "dash.openBrowser": "Abrir en el navegador", + "dash.update": "Actualizar el panel", + "upd.startAfter": "Iniciar el servidor tras actualizarlo (si no, un servidor detenido sigue detenido)", "client.startAfter": "Iniciar el juego tras actualizar el cliente", "bk.folder": "Carpeta de copias de seguridad", "bk.folderDefault": "predeterminada", diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index cee9ef5..6e37e65 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -827,7 +827,23 @@ const fr: Partial> = { "set.searchAll": "Rechercher dans tous les réglages par nom ou description…", "set.search": "Rechercher un réglage…", "upd.current": "Vous êtes à jour (version {v}).", - "upd.startAfter": "Démarrer le serveur après la mise à jour (désactivez pour qu’il soit arrêté à nouveau ensuite)", + "nav.dashboard": "Tableau de bord", + "q.dashboard": "Que font les bots en ce moment ?", + "dash.title": "Tableau de bord des bots", + "dash.intro": "La page en direct de SQUID sur les bots : où ils sont, ce qu’ils font, ce qu’ils trouvent. Elle ne tourne que sur cet ordinateur.", + "dash.notInstalled": "Le tableau de bord n’est pas encore installé.", + "dash.willInstall": "La version qui correspond à vos bots {v} sera téléchargée.", + "dash.noSquid": "La version de vos bots SQUID n’a pas pu être lue.", + "dash.install": "Télécharger le tableau de bord", + "dash.versions": "Tableau de bord {dash} pour les bots {bots}", + "dash.running": "en cours", + "dash.stopped": "arrêté", + "dash.mismatch": "Ce tableau de bord ne correspond pas à vos bots {bots}. Mettez-le à jour pour que les versions concordent.", + "dash.start": "Démarrer le tableau de bord", + "dash.stop": "Arrêter le tableau de bord", + "dash.openBrowser": "Ouvrir dans le navigateur", + "dash.update": "Mettre à jour le tableau de bord", + "upd.startAfter": "Démarrer le serveur après la mise à jour (sinon un serveur arrêté reste arrêté)", "client.startAfter": "Lancer le jeu après la mise à jour du client", "bk.folder": "Dossier des sauvegardes", "bk.folderDefault": "par défaut", diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index a8eb78b..71d3ed7 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -848,7 +848,23 @@ const ru: Partial> = { "set.searchAll": "Поиск по всем настройкам: название или описание…", "set.search": "Поиск по настройкам…", "upd.current": "У вас последняя версия ({v}).", - "upd.startAfter": "Запускать сервер после обновления (выключите, чтобы он снова остановился после обновления)", + "nav.dashboard": "Панель", + "q.dashboard": "Что сейчас делают боты?", + "dash.title": "Панель ботов", + "dash.intro": "Страница SQUID о ботах в реальном времени: где они, что делают, что находят. Работает только на этом компьютере.", + "dash.notInstalled": "Панель ещё не установлена.", + "dash.willInstall": "Будет скачан выпуск, подходящий к вашим ботам {v}.", + "dash.noSquid": "Не удалось определить версию ботов SQUID.", + "dash.install": "Скачать панель", + "dash.versions": "Панель {dash} для ботов {bots}", + "dash.running": "работает", + "dash.stopped": "остановлена", + "dash.mismatch": "Эта панель не соответствует вашим ботам {bots}. Обновите её, чтобы версии совпадали.", + "dash.start": "Запустить панель", + "dash.stop": "Остановить панель", + "dash.openBrowser": "Открыть в браузере", + "dash.update": "Обновить панель", + "upd.startAfter": "Запускать сервер после обновления (иначе выключенный сервер останется выключенным)", "client.startAfter": "Запускать игру после обновления клиента", "bk.folder": "Папка резервных копий", "bk.folderDefault": "по умолчанию", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index d0d0ecf..72e8d16 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -827,7 +827,23 @@ const zh = { "set.searchAll": "按名称或描述搜索全部设置…", "set.search": "搜索设置…", "upd.current": "当前已是最新版本 ({v})。", - "upd.startAfter": "更新后启动服务器(关闭则更新完成后再次停止)", + "nav.dashboard": "仪表盘", + "q.dashboard": "机器人现在在做什么?", + "dash.title": "机器人仪表盘", + "dash.intro": "SQUID 的机器人实时页面:它们在哪里、在做什么、发现了什么。仅在本机运行。", + "dash.notInstalled": "尚未安装仪表盘。", + "dash.willInstall": "将下载与你的机器人 {v} 对应的版本。", + "dash.noSquid": "无法读取你的 SQUID 机器人版本。", + "dash.install": "下载仪表盘", + "dash.versions": "适用于机器人 {bots} 的仪表盘 {dash}", + "dash.running": "运行中", + "dash.stopped": "已停止", + "dash.mismatch": "此仪表盘与你的机器人 {bots} 不匹配。请更新使版本一致。", + "dash.start": "启动仪表盘", + "dash.stop": "停止仪表盘", + "dash.openBrowser": "在浏览器中打开", + "dash.update": "更新仪表盘", + "upd.startAfter": "更新后启动服务器(否则已停止的服务器保持停止)", "client.startAfter": "更新客户端后启动游戏", "bk.folder": "备份文件夹", "bk.folderDefault": "默认", diff --git a/src/lib/api.ts b/src/lib/api.ts index 4acf7b2..d79fe75 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -78,6 +78,16 @@ export interface DriverOutcome { output: string; } +export interface DashboardStatus { + installed: boolean; + tag: string | null; + squid_tag: string | null; + matches: boolean; + running: boolean; + port: number; + url: string; +} + export interface BackupLocation { path: string; default_path: string; @@ -431,6 +441,10 @@ export const api = { save: (id: string, scope: Scope, changes: Record) => invoke("save_settings", { id, scope, changes }), presets: (scope: Scope) => invoke("list_presets", { scope }), backups: (id: string) => invoke("list_backups", { id }), + dashboardStatus: (id: string) => invoke("dashboard_status", { id }), + dashboardInstall: (id: string) => invoke("dashboard_install", { id }), + dashboardStart: (id: string) => invoke("dashboard_start", { id }), + dashboardStop: (id: string) => invoke("dashboard_stop", { id }), backupLocation: (id: string) => invoke("backup_location", { id }), /** `null` goes back to the default folder next to the server. */ setBackupLocation: (id: string, path: string | null) => invoke("set_backup_location", { id, path }), diff --git a/src/lib/serverUpdate.ts b/src/lib/serverUpdate.ts index 295faf8..a89e878 100644 --- a/src/lib/serverUpdate.ts +++ b/src/lib/serverUpdate.ts @@ -86,6 +86,9 @@ export async function applyServerUpdate(id: string, opts?: { choices: Record 0)) return false; + // 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. + 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); set(id, { applying: true, step: null, percent: 0, error: null, uiError: null, result: null }); let un: (() => void) | undefined; try { @@ -96,8 +99,7 @@ export async function applyServerUpdate(id: string, opts?: { choices: Record undefined); + if (out.txn.state === "committed" && !wasRunning && !startAfterUpdate("server", id)) await api.stop(id).catch(() => undefined); return true; } catch (e) { const ui = asUiError(e); diff --git a/src/lib/updatePrefs.ts b/src/lib/updatePrefs.ts index 0b5950c..ba2caa3 100644 --- a/src/lib/updatePrefs.ts +++ b/src/lib/updatePrefs.ts @@ -1,13 +1,13 @@ import { useState } from "react"; /** - * What to do when an update has finished: leave the server running (the default, as the update proves the new build - * starts) or stop it again, and whether to open the game after a client update (off by default). + * Whether a finished update starts things. Off by default for both: updating a stopped server leaves it stopped (a + * server that was running is started again, as the update had to stop it) and a client update does not open the game. */ export type AfterUpdate = "server" | "client"; const key = (kind: AfterUpdate, id: string) => `coa-start-after-${kind}-update:${id}`; -const fallback = (kind: AfterUpdate) => kind === "server"; +const fallback = (_kind: AfterUpdate) => false; export function startAfterUpdate(kind: AfterUpdate, id: string): boolean { try { diff --git a/src/screens/DashboardPage.tsx b/src/screens/DashboardPage.tsx new file mode 100644 index 0000000..ee94e0f --- /dev/null +++ b/src/screens/DashboardPage.tsx @@ -0,0 +1,109 @@ +import { useCallback, useEffect, useState } from "react"; +import { listen } from "@tauri-apps/api/event"; +import { Loader2 } from "lucide-react"; +import { api, asUiError, type DashboardStatus, type UiError } from "@/lib/api"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { useHuman, useT } from "@/i18n"; + +/** SQUID's bot dashboard: installed from the release that matches the bots, started on a free port, shown here. */ +export function DashboardPage({ serverId }: { serverId: string }) { + const t = useT(); + const human = useHuman(); + const [status, setStatus] = useState(null); + const [busy, setBusy] = useState<"install" | "start" | "stop" | null>(null); + const [step, setStep] = useState(null); + const [error, setError] = useState(null); + + const load = useCallback(async () => { + try { setStatus(await api.dashboardStatus(serverId)); } catch (e) { setError(asUiError(e)); } + }, [serverId]); + + useEffect(() => { + void load(); + const un = listen("dashboard-progress", (e) => setStep(e.payload)); + return () => { void un.then((f) => f()); }; + }, [load]); + + async function run(kind: "install" | "start" | "stop", fn: () => Promise) { + setBusy(kind); setError(null); setStep(null); + try { setStatus(await fn()); } catch (e) { setError(asUiError(e)); await load(); } + finally { setBusy(null); setStep(null); } + } + + const install = () => run("install", () => api.dashboardInstall(serverId)); + + return ( +
+

{t("dash.title")}

+

{t("dash.intro")}

+ + {!status && !error &&

{t("overview.checking")}

} + + {status && ( + + {!status.installed ? ( + <> +

{t("dash.notInstalled")}

+

{status.squid_tag ? t("dash.willInstall", { v: status.squid_tag }) : t("dash.noSquid")}

+ + + ) : ( + <> +

+ {t("dash.versions", { dash: status.tag ?? "?", bots: status.squid_tag ?? "?" })} + {" · "} + {status.running ? t("dash.running") : t("dash.stopped")} +

+ {!status.matches && status.squid_tag && ( +

{t("dash.mismatch", { bots: status.squid_tag })}

+ )} +
+ {status.running ? ( + <> + + + + ) : ( + + )} + {!status.matches && status.squid_tag && ( + + )} +
+ + )} + {busy === "install" &&

{step ?? t("bk.working")}

} +
+ )} + + {error && ( + +

{error.human.code === "unknown" ? error.technical : human(error.human).message}

+ +
+ )} + + {status?.running && ( +