diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 83a0c5e..a08671e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -70,35 +70,22 @@ jobs: ### What's new in ${{ github.ref_name }} - **Wild dino wipe scheduling** - A new `wipe_dinos` schedule type fires `destroywilddinos` via RCON at a configured interval. A pre-wipe chat warning is automatically sent to players before the wipe executes. + This is a bug-fix release focused on custom/mod map handling and a couple of server-lifecycle edge cases. - **Pre-backup RCON broadcast** - A configurable message can be sent to players in-game before any scheduled backup runs, so they know a backup (and brief lag spike) is coming. + **Fix: Custom mod maps not working** + A server created (or switched) to a custom mod map now actually launches on that map. Previously the launch arguments silently fell back to The Island, the server details page showed a garbled internal ID instead of the map's name, and custom maps didn't appear in the Settings map dropdown at all — all four were symptoms of the same missing wiring between the custom maps table and the rest of the app, which is now fixed everywhere it was needed (launch args, backups, the scheduler, display labels, and the dropdown). - **Memory limit restart** - Each server can be given a RAM ceiling (in GB). When the stats poller detects the process exceeding that limit, LokiASAM performs a graceful restart — `saveworld`, `doexit`, then relaunch — with a cooldown to prevent restart loops. + **Fix: Map's required mod not enforced on an existing server** + Changing a server's map in Settings now properly adds and locks the new map's required mod (so it can't be disabled or removed while that map is selected) and removes the previous map's mod — matching what already happened correctly during server creation. - **Start All / Stop All / Restart All** - Global action buttons in the server list header let you start every stopped server, stop every running server, or restart all running servers with a single click. + **Fix: Copying mods from another server could drop the current map's required mod** + The server creation wizard's "copy from server" step now merges the copied mod list instead of replacing it outright, so a mod map's required mod picked earlier in the wizard survives the copy. - **Backup path reconciliation** - Scheduled and manual backups now use the server's `save_folder_name` as the effective save directory when configured, falling back to the map default. Fixes cases where saves were backed up from the wrong path. + **Fix: Map mod display name and ordering** + A map's required mod now shows the map's own name in the Mods tab instead of "Unknown Mod", and always sorts to the top of the installed mods list. - **Setup wizard — automation step rewrite** - The automation step now matches the full TimeShift tier system from the server overview: hourly / daily / weekly / monthly tiers for server saves, player data, full backups, and login backups — instead of the old single cron picker. - - **Crossplay toggle fix** - The Network step in the setup wizard was writing the old `AllPlatforms` flag (ASE). It now correctly writes the `crossplay` flag to stay in sync with the CLI args step. - - **Launch at login** - A new OS-level autostart option (via `tauri-plugin-autostart`) lets LokiASAM start with your system. The toggle is available in the setup wizard tray step and in Settings → System Tray. Pairs well with the existing minimize-to-tray option. - - **Additional launch parameters** - New performance tuning, anti-cheat, and gameplay flags added. Save folder override (`-SaveDirectoryOverride`) and active in-game event flags are now applied when starting servers. - - **Fix: Club ARK map path** - Corrected the save path for Club ARK (`BobsMissions`) in both the backup manager and game data definitions. + **Fix: Servers stuck on "Updating…" after a stopped server's auto-update** + A scheduled or startup-triggered auto-update on a stopped server would apply successfully but leave the server's status stuck showing the update-in-progress spinner, requiring a manual Cancel + Reinstall to clear. The status now correctly resets once the update finishes. ### Installation diff --git a/eslint.config.mjs b/eslint.config.mjs index 05e726d..a37833f 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -12,6 +12,8 @@ const eslintConfig = defineConfig([ "out/**", "build/**", "next-env.d.ts", + // Rust/Tauri build output — not JS/TS source, was being linted by accident. + "src-tauri/**", ]), ]); diff --git a/package.json b/package.json index 8d457e3..00dfb31 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lokiasam", - "version": "0.14.1", + "version": "0.14.2", "private": true, "scripts": { "dev": "next dev", diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index 9a089d9..6c939b2 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -1,6 +1,6 @@ # Maintainer: Arron Ohnemus pkgname=lokiasam -pkgver=0.14.1 +pkgver=0.14.2 pkgrel=1 pkgdesc="Loki ARK Survival Ascended Server Manager — a desktop app for managing dedicated ASA servers" arch=("x86_64") diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 406aa31..2dd59eb 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -764,12 +764,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "configparser" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57e3272f0190c3f1584272d613719ba5fc7df7f4942fe542e63d949cf3a649b" - [[package]] name = "const-oid" version = "0.9.6" @@ -2768,9 +2762,8 @@ dependencies = [ [[package]] name = "lokiasam" -version = "0.14.1" +version = "0.14.2" dependencies = [ - "configparser", "flate2", "junction", "lettre", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 50db92a..b0596be 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lokiasam" -version = "0.14.1" +version = "0.14.2" description = "Loki Ark Survival Ascended Server Manager" authors = ["Loki"] license = "GPL-3.0-or-later" @@ -52,9 +52,6 @@ lettre = { version = "0.11", features = ["tokio1", "tokio1-rustls-tls", "builder # System process stats (CPU / RAM per PID, cross-platform) sysinfo = { version = "0.32" } -# INI file parsing -configparser = { version = "3" } - # Archive extraction for SteamCMD download (zip on Windows, tar.gz on Linux) zip = { version = "2" } flate2 = { version = "1" } diff --git a/src-tauri/src/commands/backup.rs b/src-tauri/src/commands/backup.rs index a66f97b..778ebed 100644 --- a/src-tauri/src/commands/backup.rs +++ b/src-tauri/src/commands/backup.rs @@ -3,14 +3,16 @@ use std::io::BufReader; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; -use tauri::{AppHandle, Emitter, State}; +use tauri::{AppHandle, Emitter, Manager, State}; use tokio::sync::oneshot; use tokio::time::{timeout, sleep, Duration}; use uuid::Uuid; use sevenz_rust::{SevenZWriter, SevenZArchiveEntry}; use crate::events; +use crate::state::AppState; use crate::state::rcon_pool::{RconCmd, RconPool}; +use super::utils::{fmt_size, tier_suffix, copy_dir_recursive}; // --------------------------------------------------------------------------- // Shared types @@ -84,41 +86,12 @@ fn days_to_ymd(mut days: u64) -> (u64, u64, u64) { (y, m, d) } -fn fmt_size(bytes: u64) -> String { - if bytes >= 1_073_741_824 { - format!("{:.1} GB", bytes as f64 / 1_073_741_824.0) - } else if bytes >= 1_048_576 { - format!("{:.1} MB", bytes as f64 / 1_048_576.0) - } else { - format!("{:.1} KB", bytes as f64 / 1_024.0) - } -} - fn sanitize_name(name: &str) -> String { name.chars() .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }) .collect() } -/// Build a filename tier suffix like "-DH" from a tiers string like "D,H" or "H". -/// Tiers are sorted in canonical priority order (M W D H). -fn tier_suffix(tiers: &str) -> String { - if tiers.is_empty() { - return String::new(); - } - const ORDER: &[char] = &['M', 'W', 'D', 'H']; - let flags: Vec = tiers.split(',') - .filter_map(|t| t.trim().chars().next()) - .filter(|c| ORDER.contains(c)) - .collect(); - if flags.is_empty() { - return String::new(); - } - let mut sorted: Vec = ORDER.iter().copied().filter(|c| flags.contains(c)).collect(); - sorted.dedup(); - format!("-{}", sorted.iter().collect::()) -} - /// Find and parse a `YYYY-MM-DD_HH-MM-SS` timestamp embedded in a filename stem. /// Returns `(ts_iso, tiers_str)` where `tiers_str` may be empty for files without /// the tier suffix (e.g. manual backups or pre-tier-feature archives). @@ -128,9 +101,20 @@ pub fn parse_backup_filename(stem: &str) -> Option<(String, String)> { if len < 19 { return None; } for i in 0..=(len - 19) { - let candidate = &stem[i..i + 19]; - if is_timestamp(candidate.as_bytes()) { - let after = &stem[i + 19..]; + // Index the byte slice (not `stem`) — `i`/`i+19` may not land on UTF-8 + // char boundaries for non-ASCII filenames, and `&str` indexing panics + // in that case, while byte-slice indexing does not. + let candidate = &bytes[i..i + 19]; + if is_timestamp(candidate) { + // `is_timestamp` only matches ASCII digits/separators, so this is + // always valid UTF-8. + let candidate = std::str::from_utf8(candidate).unwrap(); + let after = match std::str::from_utf8(&bytes[i + 19..]) { + Ok(s) => s, + // `i + 19` doesn't land on a char boundary for the remainder — + // treat as no match rather than panicking. + Err(_) => continue, + }; // After timestamp: either empty, or "-{MWDH letters}", or something else (no tier) let tiers = if let Some(rest) = after.strip_prefix('-') { if !rest.is_empty() && rest.chars().all(|c| matches!(c, 'M' | 'W' | 'D' | 'H')) { @@ -235,6 +219,7 @@ pub async fn rcon_broadcast(pool: &RconPool, server_id: &str, message: &str) { /// Write `files` into a 7z archive at `dest_path`. /// `root` is stripped from each file path to produce the archive entry name. +/// `alt_root` is an alternative root tried if primary root fails (used for mixed-source backups). /// Emits progress events keyed on `server_id`. /// Returns Ok(skipped_count) on success. A non-zero skipped_count means some /// files disappeared between enumeration and compression — the caller should @@ -247,22 +232,65 @@ fn compress_to_7z( dest_path: &Path, label: &str, ) -> Result { - let total = files.len().max(1) as f32; + compress_to_7z_with_alt_root(app, server_id, files, root, None, dest_path, label) +} + +fn compress_to_7z_with_alt_root( + app: &AppHandle, + server_id: &str, + files: &[PathBuf], + root: &Path, + alt_root: Option<&Path>, + dest_path: &Path, + label: &str, +) -> Result { + compress_to_7z_with_entries( + app, + server_id, + &files.iter().map(|f| (f.clone(), None)).collect::>(), + root, + alt_root, + dest_path, + label, + ) +} + +/// Compress files with explicit entry names for archive structure. +/// `entries` is a vec of (file_path, optional_custom_entry_name). +/// If custom entry name is None, it's calculated by stripping the root paths. +fn compress_to_7z_with_entries( + app: &AppHandle, + server_id: &str, + entries: &[(PathBuf, Option)], + root: &Path, + alt_root: Option<&Path>, + dest_path: &Path, + label: &str, +) -> Result { + let total = entries.len().max(1) as f32; let mut writer = SevenZWriter::create(dest_path).map_err(|e| e.to_string())?; let mut skipped = 0usize; - for (idx, file_path) in files.iter().enumerate() { - let rel = file_path - .strip_prefix(root) - .map_err(|e| e.to_string())?; - let entry_name = rel.to_string_lossy().replace('\\', "/"); + for (idx, (file_path, custom_entry)) in entries.iter().enumerate() { + let entry_name = if let Some(custom) = custom_entry { + custom.clone() + } else { + let rel = file_path + .strip_prefix(root) + .or_else(|_| { + alt_root.ok_or(()).and_then(|alt| file_path.strip_prefix(alt).map_err(|_| ())) + }) + .map_err(|_| format!( + "File {} doesn't match root {} or alt root {:?}", + file_path.display(), root.display(), alt_root.map(|r| r.display()) + ))?; + rel.to_string_lossy().replace('\\', "/") + }; let pct = (idx as f32 / total * 99.0).min(99.0); emit_progress(app, server_id, pct, &entry_name, label); - // Skip files that disappeared between enumeration and compression (ASA - // uses delete+rename atomic writes, which creates a brief window where - // the file doesn't exist). Count skips so callers can retry. + // Skip files that disappeared between enumeration and compression let file = match File::open(file_path) { Ok(f) => f, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { @@ -273,7 +301,7 @@ fn compress_to_7z( }; let metadata = file.metadata().map_err(|e| e.to_string())?; let mut entry = SevenZArchiveEntry::new(); - entry.name = entry_name.clone(); + entry.name = entry_name; entry.size = metadata.len(); entry.is_directory = false; writer @@ -289,12 +317,18 @@ fn compress_to_7z( // Cleanup: delete ARK's own auto-generated backup files // --------------------------------------------------------------------------- -/// Delete ARK's own auto-generated rolling copies from SavedArks/{mapPath}: +/// Delete ARK's own auto-generated rolling copies from SavedArks/{saveFolder}: /// - `{mapPath}_*.ark` — ARK's own timestamped world-save backups /// - `{mapPath}_*.arkrbf` — ASA rollback files /// - `*.profilebak` — ARK player-profile backups /// - `*.tribebak` — ARK tribe backups /// +/// `save_folder` is the real on-disk SavedArks subfolder name (see +/// `ArkMap.saveFolder` in game-data.ts) — for almost every map this equals +/// `map_path`, but they diverge for Club ARK. The file-name prefix inside the +/// folder always uses `map_path` regardless (ASA keeps the `_WP` suffix there +/// even when the folder itself drops it). +/// /// Never touches the live `{mapPath}.ark`, `_AntiCorruptionBackup.bak`, /// `*.arkprofile`, or `*.arktribe` files. /// @@ -303,12 +337,13 @@ fn compress_to_7z( pub async fn cleanup_ark_own_backups( install_path: String, map_path: String, + save_folder: String, ) -> Result { let saved_dir = PathBuf::from(&install_path) .join("ShooterGame") .join("Saved") .join("SavedArks") - .join(&map_path); + .join(&save_folder); if !saved_dir.exists() { return Ok(0); @@ -347,26 +382,33 @@ pub async fn cleanup_ark_own_backups( // Server backup (SavedArks + SaveGames → .7z) // --------------------------------------------------------------------------- -/// Inner implementation for server backup — callable from both the Tauri command -/// and the Rust backup_manager tick handler (which cannot use State<'_> wrappers). +/// Inner implementation callable from both the Tauri command and the Rust +/// backup_manager tick handler (which cannot use State<'_> wrappers). /// -/// `skip_world_save`: pass `true` when the caller has already issued SaveWorld -/// (e.g. the scheduler tick that consolidates the save across backup types). -/// Pass `false` for manual/UI-triggered backups so they save on their own. +/// `map_path` is the launch/CLI map name, used for the SaveGames archive-internal +/// naming convention (LokiASAM's own symlink structure). `save_folder` is the +/// real on-disk `SavedArks/{X}` subfolder name — identical to `map_path` for +/// almost every map, but diverges for Club ARK (see `ArkMap.saveFolder`). +/// `skip_world_save`: pass `true` when the caller has already issued SaveWorld. +/// `base_dir`: when non-empty, resolves the canonical save path +/// `{base_dir}/Saves/{server_id}/SavedArks/{save_folder}` instead of following +/// the SavedArks symlink inside the install directory. pub async fn create_server_backup_inner( app: &AppHandle, server_id: &str, server_name: &str, install_path: &str, map_path: &str, + save_folder: &str, map_id: &str, backup_dir: &str, triggered_by: &str, tier: &str, pool: &RconPool, skip_world_save: bool, + base_dir: &str, ) -> Result { - create_server_backup_impl(app, server_id, server_name, install_path, map_path, map_id, backup_dir, triggered_by, tier, pool, skip_world_save).await + create_server_backup_impl(app, server_id, server_name, install_path, map_path, save_folder, map_id, backup_dir, triggered_by, tier, pool, skip_world_save, base_dir).await } /// Tauri command: exposed to the frontend for manual/UI-triggered backups. @@ -377,23 +419,23 @@ pub async fn create_server_backup( server_name: String, install_path: String, map_path: String, + save_folder: String, map_id: String, backup_dir: String, triggered_by: String, tier: String, - save_folder_name: Option, + base_dir: String, pool: State<'_, RconPool>, ) -> Result { - // Use save_folder_name as the save dir when set (new symlink-based layout) - let effective_map_path = save_folder_name - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| map_path.clone()); - let result = create_server_backup_inner(&app, &server_id, &server_name, &install_path, &effective_map_path, &map_id, &backup_dir, &triggered_by, &tier, &pool, false).await; + let state = app.state::(); + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + let result = create_server_backup_inner(&app, &server_id, &server_name, &install_path, &map_path, &save_folder, &map_id, &backup_dir, &triggered_by, &tier, &pool, false, &base_dir).await; if let Ok(ref rec) = result { let size = fmt_size(rec.file_size_bytes); crate::commands::notifications::dispatch_notification( &app, "backup_completed", Some(&server_id), &server_name, - "Backup Complete", &format!("Server backup completed ({size})"), "success", + "Server Backup", &format!("{server_name} — server backup complete ({size})"), "success", ).await; } result @@ -405,12 +447,14 @@ async fn create_server_backup_impl( server_name: &str, install_path: &str, map_path: &str, + save_folder: &str, map_id: &str, backup_dir: &str, triggered_by: &str, tier: &str, pool: &RconPool, skip_world_save: bool, + base_dir: &str, ) -> Result { const MAX_ATTEMPTS: u32 = 3; const RETRY_DELAY_SECS: u64 = 15; @@ -427,11 +471,29 @@ async fn create_server_backup_impl( sleep(Duration::from_secs(POST_SAVE_WAIT_SECS)).await; } - let saved_arks = PathBuf::from(&install_path) - .join("ShooterGame").join("Saved").join("SavedArks").join(&map_path); + // Use canonical path when base_dir is known, otherwise fall back to following the symlink. + let saved_arks = if !base_dir.is_empty() { + PathBuf::from(base_dir).join("saves").join(server_id).join("SavedArks").join(save_folder) + } else { + PathBuf::from(&install_path).join("ShooterGame").join("Saved").join("SavedArks").join(save_folder) + }; let save_games = PathBuf::from(&install_path) .join("ShooterGame").join("Saved").join("SaveGames"); - let saved_root = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); + + // When base_dir is used, files come from two roots: canonical saves and install_path SaveGames. + // Calculate the primary root based on whether base_dir is used. + let saved_root = if !base_dir.is_empty() { + PathBuf::from(base_dir).join("saves").join(server_id) + } else { + PathBuf::from(&install_path).join("ShooterGame").join("Saved") + }; + + // The alternate root is always install_path/ShooterGame/Saved for SaveGames compatibility. + let alt_root = if !base_dir.is_empty() { + Some(PathBuf::from(&install_path).join("ShooterGame").join("Saved")) + } else { + None + }; let out_dir = PathBuf::from(&backup_dir).join(&server_id).join("server"); fs::create_dir_all(&out_dir).map_err(|e| e.to_string())?; @@ -450,7 +512,7 @@ async fn create_server_backup_impl( // Fresh cleanup and enumeration on every attempt so each retry gets a // stable snapshot after ASA has finished writing. emit_progress(&app, &server_id, 2.0, "", "Cleaning ARK backups…"); - let _ = cleanup_ark_own_backups(install_path.to_string(), map_path.to_string()).await; + let _ = cleanup_ark_own_backups(install_path.to_string(), map_path.to_string(), save_folder.to_string()).await; let mut all_files: Vec = Vec::new(); if saved_arks.exists() { @@ -460,7 +522,29 @@ async fn create_server_backup_impl( collect_files(&save_games, &mut all_files).map_err(|e| e.to_string())?; } if all_files.is_empty() { - return Err("No save files found to back up".to_string()); + // Transient (server just started, hasn't autosaved yet) rather than a + // permanent condition — let the retry loop below give ASA more time + // instead of failing outright on the very first empty snapshot. + last_error = "No save files found to back up".to_string(); + continue; + } + + // Build entries with custom names for SaveGames files to include map path + let mut entries: Vec<(PathBuf, Option)> = Vec::new(); + for file_path in all_files { + let custom_name = if file_path.starts_with(&save_games) { + // For SaveGames files, prepend Mods/{map_path}/SaveGames/ + let rel_path = file_path.strip_prefix(&save_games) + .ok() + .and_then(|p| p.to_str()) + .unwrap_or(""); + let rel_clean = rel_path.trim_start_matches(|c| c == '/' || c == '\\'); + Some(format!("Mods/{}/SaveGames/{}", map_path, rel_clean.replace('\\', "/"))) + } else { + // For SavedArks files, let compress_to_7z_with_entries handle it + None + }; + entries.push((file_path, custom_name)); } let (ts_file, ts_iso) = now_timestamp(); @@ -469,11 +553,11 @@ async fn create_server_backup_impl( let app_c = app.clone(); let sid = server_id.to_string(); - let files = all_files; let root = saved_root.clone(); + let alt = alt_root.clone(); let dest = archive_path.clone(); let compress_result = tokio::task::spawn_blocking(move || { - compress_to_7z(&app_c, &sid, &files, &root, &dest, "Creating server backup…") + compress_to_7z_with_entries(&app_c, &sid, &entries, &root, alt.as_deref(), &dest, "Creating server backup…") }) .await .map_err(|e| format!("Backup task panicked: {e}"))?; @@ -486,6 +570,17 @@ async fn create_server_backup_impl( let _ = tokio::fs::remove_file(&archive_path).await; continue; } + if skipped > 0 { + // Ran out of retries with files still vanishing mid-compression — + // accept the archive (better than no backup) but say so, instead + // of reporting it identically to a clean run. + crate::commands::notifications::dispatch_notification( + &app, "backup_completed", Some(&server_id), server_name, + &format!("{server_name} Backup Incomplete"), + &format!("Backup created, but {skipped} file(s) changed during compression and were skipped."), + "warning", + ).await; + } // Clean run, or last attempt — accept the archive emit_progress(&app, &server_id, 100.0, &archive_name, "Done"); let file_size = fs::metadata(&archive_path) @@ -522,19 +617,23 @@ async fn create_server_backup_impl( /// Inner implementation for all-players backup — callable from both the Tauri /// command and the Rust backup_manager tick handler. +/// +/// `save_folder` is the real on-disk `SavedArks/{X}` subfolder name — identical +/// to the launch map path for almost every map, but diverges for Club ARK +/// (see `ArkMap.saveFolder` in game-data.ts). pub async fn backup_all_players_inner( app: &AppHandle, server_id: &str, server_name: &str, install_path: &str, - map_path: &str, + save_folder: &str, map_id: &str, backup_dir: &str, triggered_by: &str, ) -> Result, String> { let saved_dir = PathBuf::from(install_path) .join("ShooterGame").join("Saved") - .join("SavedArks").join(map_path); + .join("SavedArks").join(save_folder); if !saved_dir.exists() { return Ok(vec![]); @@ -559,7 +658,7 @@ pub async fn backup_all_players_inner( server_id, server_name, install_path, - map_path, + save_folder, map_id, backup_dir, eos_id, @@ -580,22 +679,21 @@ pub async fn backup_all_players( server_id: String, server_name: String, install_path: String, - map_path: String, + save_folder: String, map_id: String, backup_dir: String, triggered_by: String, - save_folder_name: Option, ) -> Result, String> { - let effective_map_path = save_folder_name - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| map_path.clone()); - let result = backup_all_players_inner(&app, &server_id, &server_name, &install_path, &effective_map_path, &map_id, &backup_dir, &triggered_by).await; + let state = app.state::(); + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + let result = backup_all_players_inner(&app, &server_id, &server_name, &install_path, &save_folder, &map_id, &backup_dir, &triggered_by).await; if let Ok(ref recs) = result { let count = recs.len(); if count > 0 { crate::commands::notifications::dispatch_notification( &app, "backup_completed", Some(&server_id), &server_name, - "Backup Complete", &format!("Player backups completed ({count} players)"), "success", + "Player Backup", &format!("{server_name} — {count} player backups complete"), "success", ).await; } } @@ -607,12 +705,15 @@ pub async fn backup_all_players( // --------------------------------------------------------------------------- /// Inner implementation for single-player backup — callable without Tauri State wrappers. +/// `save_folder` is the real on-disk `SavedArks/{X}` subfolder name — identical +/// to the launch map path for almost every map, but diverges for Club ARK +/// (see `ArkMap.saveFolder` in game-data.ts). pub async fn create_player_backup_inner( app: &AppHandle, server_id: &str, server_name: &str, install_path: &str, - map_path: &str, + save_folder: &str, map_id: &str, backup_dir: &str, eos_id: &str, @@ -622,7 +723,7 @@ pub async fn create_player_backup_inner( ) -> Result { let profile_file = PathBuf::from(install_path) .join("ShooterGame").join("Saved") - .join("SavedArks").join(map_path) + .join("SavedArks").join(save_folder) .join(format!("{eos_id}.arkprofile")); if !profile_file.exists() { @@ -685,7 +786,7 @@ pub async fn create_player_backup( server_id: String, server_name: String, install_path: String, - map_path: String, + save_folder: String, map_id: String, backup_dir: String, eos_id: String, @@ -693,8 +794,11 @@ pub async fn create_player_backup( triggered_by: String, tier: String, ) -> Result { + let state = app.state::(); + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; let result = create_player_backup_inner( - &app, &server_id, &server_name, &install_path, &map_path, + &app, &server_id, &server_name, &install_path, &save_folder, &map_id, &backup_dir, &eos_id, &player_name, &triggered_by, &tier, ).await; if let Ok(ref rec) = result { @@ -702,7 +806,7 @@ pub async fn create_player_backup( let display_name = rec.player_name.as_deref().unwrap_or(&eos_id); crate::commands::notifications::dispatch_notification( &app, "backup_completed", Some(&server_id), &server_name, - "Backup Complete", &format!("Player backup for {display_name} completed ({size})"), "success", + "Player Backup", &format!("{server_name} — backup for {display_name} complete ({size})"), "success", ).await; } result @@ -727,17 +831,19 @@ pub struct IniBackupRecord { /// timestamp folder and a new "current" copy is written. #[tauri::command] pub async fn create_ini_backup( + app: AppHandle, server_id: String, install_path: String, backup_dir: String, ) -> Result { - #[cfg(target_os = "windows")] - let platform = "WindowsServer"; - #[cfg(not(target_os = "windows"))] - let platform = "LinuxServer"; - + let state = app.state::(); + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + // ASA ships only a Windows dedicated server binary. On Linux it runs under + // Proton/Wine, so the server process always writes its config to the + // WindowsServer subfolder regardless of the host OS running LokiASAM. let config_dir = PathBuf::from(&install_path) - .join("ShooterGame").join("Saved").join("Config").join(platform); + .join("ShooterGame").join("Saved").join("Config").join("WindowsServer"); let ini_files = ["GameUserSettings.ini", "Game.ini"]; let sources: Vec = ini_files.iter() @@ -776,53 +882,55 @@ pub async fn create_ini_backup( }) } -/// Create the save directory link used with -SaveDirectoryOverride. +/// Create the save directory link for a server. /// /// Creates: -/// `{base_dir}/Saves/{save_folder_name}/` ← the real save location -/// `{install_path}/ShooterGame/Saved/SavedArks/{save_folder_name}` ← the link target +/// `{base_dir}/Saves/{server_id}/SavedArks/` ← the real save location +/// `{install_path}/ShooterGame/Saved/SavedArks` → symlink ← replaces the whole SavedArks dir /// -/// On Linux: a symlink pointing to the base_dir/Saves/ subdirectory. -/// On Windows: an NTFS junction point (no admin rights required for junctions on local filesystems). +/// On Linux: a symlink. On Windows: an NTFS junction (no admin rights required). /// -/// If the link already exists and already points to the correct target, returns success without changes. +/// If `SavedArks` already exists as a regular directory (first-run or leftover from a +/// previous install), it is removed so the symlink/junction can be placed at that path. +/// If the link already points to the correct target, returns success without changes. #[tauri::command] pub async fn create_save_link( install_path: String, - save_folder_name: String, + server_id: String, base_dir: String, ) -> Result<(), String> { - if save_folder_name.is_empty() { - return Err("save_folder_name must not be empty".to_string()); + if server_id.is_empty() { + return Err("server_id must not be empty".to_string()); } - // The real save storage directory - let save_target = PathBuf::from(&base_dir).join("Saves").join(&save_folder_name); + // The canonical save storage directory (real data lives here) + let save_target = PathBuf::from(&base_dir).join("saves").join(&server_id).join("SavedArks"); fs::create_dir_all(&save_target).map_err(|e| format!("Failed to create save target dir: {e}"))?; - // The path where the server expects saves (must be the link) - let saved_arks = PathBuf::from(&install_path) - .join("ShooterGame").join("Saved").join("SavedArks"); - fs::create_dir_all(&saved_arks).map_err(|e| format!("Failed to create SavedArks dir: {e}"))?; + // The path inside the server install where SavedArks should be (will become the link) + let saved_dir = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); + fs::create_dir_all(&saved_dir).map_err(|e| format!("Failed to create Saved dir: {e}"))?; + let link_path = saved_dir.join("SavedArks"); - let link_path = saved_arks.join(&save_folder_name); - - // If already correctly linked, do nothing + // If something already exists at link_path, check it and remove if wrong if link_path.exists() || link_path.is_symlink() { - #[cfg(target_os = "linux")] - { - if let Ok(existing) = std::fs::read_link(&link_path) { - if existing == save_target { - return Ok(()); - } + if let Ok(existing) = std::fs::read_link(&link_path) { + if existing == save_target { + return Ok(()); } - // Wrong target or broken link — remove and recreate - let _ = fs::remove_file(&link_path); } - #[cfg(target_os = "windows")] - { - // Junction already exists — leave it; user can manage via OS if needed - return Ok(()); + // Wrong target, broken link, or plain directory — remove so we can recreate. + // On Windows, junctions must be removed with remove_dir (not remove_dir_all, + // which would follow the junction and delete the actual save data). + if link_path.is_symlink() { + #[cfg(target_os = "windows")] + { let _ = fs::remove_dir(&link_path); } + #[cfg(not(target_os = "windows"))] + { let _ = fs::remove_file(&link_path); } + } else if link_path.is_dir() { + let _ = fs::remove_dir_all(&link_path); + } else { + let _ = fs::remove_file(&link_path); } } @@ -841,29 +949,102 @@ pub async fn create_save_link( Ok(()) } +/// Create the mods saves directory link for a server (per-map SaveGames). +/// +/// Creates: +/// `{base_dir}/Saves/{server_id}/Mods/{map_path}/SaveGames/` ← the real mod save location +/// `{install_path}/ShooterGame/Saved/SaveGames` → symlink/junction ← points to current map's mod data +/// +/// On Linux: a symlink. On Windows: an NTFS junction (no admin rights required). +/// +/// This is called when the server starts or when the map changes to ensure the +/// SaveGames symlink points to the current map's mod save data. +#[tauri::command] +pub async fn create_mods_saves_link( + install_path: String, + server_id: String, + base_dir: String, + map_path: String, +) -> Result<(), String> { + if server_id.is_empty() || map_path.is_empty() { + return Err("server_id and map_path must not be empty".to_string()); + } + + // The canonical mod save storage directory for this map (real data lives here) + let mods_target = PathBuf::from(&base_dir) + .join("saves") + .join(&server_id) + .join("Mods") + .join(&map_path) + .join("SaveGames"); + fs::create_dir_all(&mods_target).map_err(|e| format!("Failed to create mods target dir: {e}"))?; + + // The path inside the server install where SaveGames should be (will become the link) + let saved_dir = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); + fs::create_dir_all(&saved_dir).map_err(|e| format!("Failed to create Saved dir: {e}"))?; + let link_path = saved_dir.join("SaveGames"); + + // If something already exists at link_path, check it and remove if it points to wrong target + if link_path.exists() || link_path.is_symlink() { + if let Ok(existing) = std::fs::read_link(&link_path) { + if existing == mods_target { + return Ok(()); + } + } + // Wrong target, broken link, or plain directory — remove so we can recreate. + if link_path.is_symlink() { + #[cfg(target_os = "windows")] + { let _ = fs::remove_dir(&link_path); } + #[cfg(not(target_os = "windows"))] + { let _ = fs::remove_file(&link_path); } + } else if link_path.is_dir() { + let _ = fs::remove_dir_all(&link_path); + } else { + let _ = fs::remove_file(&link_path); + } + } + + #[cfg(target_os = "linux")] + { + std::os::unix::fs::symlink(&mods_target, &link_path) + .map_err(|e| format!("Failed to create symlink: {e}"))?; + } + + #[cfg(target_os = "windows")] + { + junction::create(&mods_target, &link_path) + .map_err(|e| format!("Failed to create junction point: {e}"))?; + } + + Ok(()) +} + /// Wipe server save files at one of three tiers: /// /// - `"map"` — delete world `.ark` files only (clears map state, preserves characters). /// - `"players"` — delete `.arkprofile` and `.arktribe` files only (resets characters/tribes). /// - `"full"` — delete all save files (world + characters + tribe + mod saves). /// -/// The save directory is `{install_path}/ShooterGame/Saved/SavedArks/{save_folder_name}/` -/// when save_folder_name is non-empty, otherwise `{install_path}/ShooterGame/Saved/SavedArks/`. +/// `SavedArks` is a symlink to the canonical save directory, so all tiers operate +/// on the real data transparently. `save_folder` is the real on-disk SavedArks +/// subfolder name (e.g. `TheIsland_WP` — identical to the launch map path for +/// almost every map, but diverges for Club ARK; see `ArkMap.saveFolder`). /// /// The server MUST NOT be running when this is called (enforced on the frontend). #[tauri::command] pub async fn wipe_server_saves( + app: AppHandle, + server_id: String, install_path: String, - save_folder_name: String, + save_folder: String, tier: String, ) -> Result<(), String> { - let saves_root = if save_folder_name.is_empty() { - PathBuf::from(&install_path).join("ShooterGame").join("Saved").join("SavedArks") - } else { - PathBuf::from(&install_path) - .join("ShooterGame").join("Saved").join("SavedArks") - .join(&save_folder_name) - }; + let state = app.state::(); + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + let saves_root = PathBuf::from(&install_path) + .join("ShooterGame").join("Saved").join("SavedArks") + .join(&save_folder); if !saves_root.exists() { return Ok(()); @@ -914,6 +1095,58 @@ pub async fn wipe_server_saves( Ok(()) } +/// Copy the save data for a specific map from one server to another. +/// +/// Source: `{base_dir}/Saves/{source_server_id}/SavedArks/{save_folder}/` +/// Target: `{base_dir}/Saves/{target_server_id}/SavedArks/{save_folder}/` +/// +/// `save_folder` is the real on-disk SavedArks subfolder name — identical to +/// the launch map path for almost every map, but diverges for Club ARK (see +/// `ArkMap.saveFolder`). The target map subfolder is cleared before the copy +/// so the result is an exact mirror of the source. Both servers must be +/// stopped before calling this. +#[tauri::command] +pub async fn import_server_saves( + app: AppHandle, + source_server_id: String, + target_server_id: String, + base_dir: String, + save_folder: String, +) -> Result<(), String> { + if source_server_id == target_server_id { + return Err("Source and target server must be different".to_string()); + } + + // Locks both — the source is only read, but a concurrent backup reading + // it at the same time as this copy is exactly the same race this guards + // against everywhere else. + let state = app.state::(); + let _lock_source = state.try_lock_server(&source_server_id) + .ok_or_else(|| format!("An operation is already in progress for {source_server_id} — try again in a moment"))?; + let _lock_target = state.try_lock_server(&target_server_id) + .ok_or_else(|| format!("An operation is already in progress for {target_server_id} — try again in a moment"))?; + + let source = PathBuf::from(&base_dir) + .join("saves").join(&source_server_id).join("SavedArks").join(&save_folder); + let target = PathBuf::from(&base_dir) + .join("saves").join(&target_server_id).join("SavedArks").join(&save_folder); + + if !source.exists() { + return Err(format!("Source save directory does not exist: {}", source.display())); + } + + // Clear the target map subfolder first + if target.exists() { + fs::remove_dir_all(&target).map_err(|e| format!("Failed to clear target save dir: {e}"))?; + } + fs::create_dir_all(&target).map_err(|e| format!("Failed to create target save dir: {e}"))?; + + // Recursively copy everything from source into target + copy_dir_recursive(&source, &target, &[], None) + .map_err(|e| format!("Failed to copy save files: {e}"))?; + Ok(()) +} + /// List timestamped INI snapshot folders for a server (newest first). #[tauri::command] pub async fn list_ini_backups( @@ -958,6 +1191,9 @@ pub async fn create_full_backup( triggered_by: String, tier: String, ) -> Result { + let state = app.state::(); + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; let install_dir = PathBuf::from(&install_path); if !install_dir.exists() { return Err(format!("Install path not found: {install_path}")); @@ -1013,7 +1249,7 @@ pub async fn create_full_backup( let size = fmt_size(rec.file_size_bytes); crate::commands::notifications::dispatch_notification( &app, "backup_completed", Some(&rec.server_id), &server_name, - "Backup Complete", &format!("Full backup completed ({size})"), "success", + "Full Backup", &format!("{server_name} — full backup complete ({size})"), "success", ).await; Ok(rec) } @@ -1022,44 +1258,133 @@ pub async fn create_full_backup( // Restore // --------------------------------------------------------------------------- -/// Restore a Server backup: extract 7z over SavedArks/{mapPath} and SaveGames. +/// Restore a Server backup: extract 7z to correct canonical locations and recreate symlinks. +/// Archive structure: +/// SavedArks/{save_folder}/... → restored to {install_path}/ShooterGame/Saved/SavedArks/{save_folder}/ +/// Mods/{map_path}/SaveGames/... → restored to {base_dir}/Saves/{server_id}/Mods/{map_path}/SaveGames/ +/// +/// `save_folder` is the real on-disk SavedArks subfolder name — identical to +/// `map_path` for almost every map, but diverges for Club ARK (see +/// `ArkMap.saveFolder` in game-data.ts). The archive's internal SavedArks +/// entries were written using `save_folder` too (create_server_backup_impl +/// reads from the real folder), so both sides must agree here. #[tauri::command] pub async fn restore_server_backup( app: AppHandle, server_id: String, backup_file_path: String, install_path: String, + base_dir: String, + map_path: String, + save_folder: String, ) -> Result<(), String> { - let saved_root = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); - extract_7z_with_progress(&app, &server_id, &backup_file_path, &saved_root, "Restoring server backup…").await + use std::fs; + + // Validate inputs + if server_id.is_empty() || map_path.is_empty() { + return Err("server_id and map_path must not be empty".to_string()); + } + + let state = app.state::(); + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + + // Step 1: Extract backup to a temp directory FIRST — validating the archive + // before touching any live save data. A corrupt/truncated/missing archive + // must fail here, before Step 2 clears the real SavedArks/SaveGames + // directories, or a bad restore destroys the only copy of the save. + // The temp dir is UUID-suffixed (not just keyed by server_id) so a second + // restore for the same server started before this one finishes can't + // delete this one's in-progress extraction out from under it. + emit_progress(&app, &server_id, 10.0, "", "Extracting backup…"); + let temp_dir = std::env::temp_dir().join(format!("lokiasam-restore-{}-{}", server_id, Uuid::new_v4())); + fs::create_dir_all(&temp_dir).map_err(|e| e.to_string())?; + + sevenz_rust::decompress_file(&backup_file_path, &temp_dir) + .map_err(|e| { let _ = fs::remove_dir_all(&temp_dir); e.to_string() })?; + + // Step 2: Clear existing save locations — only now that the archive is + // known-good. + emit_progress(&app, &server_id, 40.0, "", "Clearing existing saves…"); + let saved_arks_path = PathBuf::from(&base_dir).join("saves").join(&server_id).join("SavedArks").join(&save_folder); + if saved_arks_path.exists() { + fs::remove_dir_all(&saved_arks_path).map_err(|e| format!("Failed to clear SavedArks: {e}"))?; + } + + let mods_saves_path = PathBuf::from(&base_dir).join("saves").join(&server_id).join("Mods").join(&map_path).join("SaveGames"); + if mods_saves_path.exists() { + fs::remove_dir_all(&mods_saves_path).map_err(|e| format!("Failed to clear SaveGames: {e}"))?; + } + + // Step 3: Move extracted files to correct locations + emit_progress(&app, &server_id, 50.0, "", "Moving files to correct locations…"); + + // Process SavedArks files + let temp_saved_arks = temp_dir.join("SavedArks").join(&save_folder); + if temp_saved_arks.exists() { + fs::create_dir_all(&saved_arks_path).map_err(|e| e.to_string())?; + copy_dir_recursive(&temp_saved_arks, &saved_arks_path, &[], None).map_err(|e| e.to_string())?; + } + + // Process Mods/SaveGames files + let temp_mods = temp_dir.join("Mods").join(&map_path).join("SaveGames"); + if temp_mods.exists() { + fs::create_dir_all(&mods_saves_path).map_err(|e| e.to_string())?; + copy_dir_recursive(&temp_mods, &mods_saves_path, &[], None).map_err(|e| e.to_string())?; + } + + // Step 4: Recreate symlinks + emit_progress(&app, &server_id, 80.0, "", "Recreating symlinks…"); + create_save_link(install_path.clone(), server_id.clone(), base_dir.clone()).await?; + create_mods_saves_link(install_path, server_id.clone(), base_dir, map_path).await?; + + // Step 5: Cleanup temp directory + emit_progress(&app, &server_id, 95.0, "", "Cleaning up…"); + let _ = fs::remove_dir_all(&temp_dir); + + emit_progress(&app, &server_id, 100.0, "", "Restore complete"); + Ok(()) } -/// Restore a Player backup: extract 7z into SavedArks/{mapPath}. +/// Restore a Player backup: extract 7z into SavedArks/{save_folder}. +/// `save_folder` is the real on-disk SavedArks subfolder name — identical to +/// the launch map path for almost every map, but diverges for Club ARK. #[tauri::command] pub async fn restore_player_backup( app: AppHandle, server_id: String, backup_file_path: String, install_path: String, - map_path: String, + save_folder: String, ) -> Result<(), String> { + let state = app.state::(); + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; let target = PathBuf::from(&install_path) .join("ShooterGame").join("Saved") - .join("SavedArks").join(&map_path); + .join("SavedArks").join(&save_folder); fs::create_dir_all(&target).map_err(|e| e.to_string())?; extract_7z_with_progress(&app, &server_id, &backup_file_path, &target, "Restoring player backup…").await } /// Restore an INI backup from a snapshot folder. +/// +/// Always restores into the WindowsServer config subfolder — ASA ships only a +/// Windows dedicated server binary, so that's what the server process reads +/// regardless of the host OS running LokiASAM (see config.rs::config_dir). #[tauri::command] pub async fn restore_ini_backup( + app: AppHandle, + server_id: String, backup_folder_path: String, install_path: String, - platform: String, ) -> Result<(), String> { + let state = app.state::(); + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; let src_dir = PathBuf::from(&backup_folder_path); let dst_dir = PathBuf::from(&install_path) - .join("ShooterGame").join("Saved").join("Config").join(&platform); + .join("ShooterGame").join("Saved").join("Config").join("WindowsServer"); fs::create_dir_all(&dst_dir).map_err(|e| e.to_string())?; @@ -1083,6 +1408,9 @@ pub async fn restore_full_backup( backup_file_path: String, install_path: String, ) -> Result<(), String> { + let state = app.state::(); + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; let target = PathBuf::from(&install_path); extract_7z_with_progress(&app, &server_id, &backup_file_path, &target, "Restoring full backup…").await } diff --git a/src-tauri/src/commands/backup_manager.rs b/src-tauri/src/commands/backup_manager.rs index 1e7e401..768f4c8 100644 --- a/src-tauri/src/commands/backup_manager.rs +++ b/src-tauri/src/commands/backup_manager.rs @@ -14,6 +14,7 @@ /// 6. Emits `backup://completed/{serverId}` so the UI can refresh. use std::collections::HashMap; +use rusqlite::Connection; use tauri::{AppHandle, Emitter, Manager}; use crate::db; @@ -24,22 +25,16 @@ use super::backup::{ create_server_backup_inner, backup_all_players_inner, create_player_backup_inner, rcon_save_world, rcon_broadcast, BackupRecord, }; - -fn fmt_size(bytes: u64) -> String { - if bytes >= 1_073_741_824 { - format!("{:.1} GB", bytes as f64 / 1_073_741_824.0) - } else if bytes >= 1_048_576 { - format!("{:.1} MB", bytes as f64 / 1_048_576.0) - } else { - format!("{:.1} KB", bytes as f64 / 1_024.0) - } -} +use super::utils::{fmt_size, tier_suffix}; // --------------------------------------------------------------------------- // Map ID → ASA map path (matches ARK_MAPS in game-data.ts) // --------------------------------------------------------------------------- -fn map_id_to_path(map_id: &str) -> &'static str { +fn map_id_to_path(conn: &Connection, map_id: &str) -> String { + if let Some(custom_path) = db::get_custom_map_path(conn, map_id) { + return custom_path; + } match map_id { "theisland" => "TheIsland_WP", "thecenter" => "TheCenter_WP", @@ -60,6 +55,21 @@ fn map_id_to_path(map_id: &str) -> &'static str { "clubark" => "BobsMissions_WP", _ => "TheIsland_WP", } + .to_string() +} + +/// Real on-disk `SavedArks/{X}` subfolder name for a map, when it differs from +/// the launch/CLI map path returned by `map_id_to_path`. Club ARK (Bob's +/// Missions) is the one known built-in case: it launches as `BobsMissions_WP` +/// and its save files keep that `_WP` prefix, but ASA creates the folder +/// itself as just `SavedArks/BobsMissions/` (no `_WP`). User-added custom mod +/// maps have no such override — they always use `map_path` verbatim. Mirrors +/// `getSaveFolder`/`saveFolder` on `ArkMap` in game-data.ts — keep both in sync. +fn map_id_to_save_folder(conn: &Connection, map_id: &str) -> String { + match map_id { + "clubark" => "BobsMissions".to_string(), + _ => map_id_to_path(conn, map_id), + } } // --------------------------------------------------------------------------- @@ -133,20 +143,6 @@ fn tier_config_any_enabled(cfg: &TierConfig) -> bool { // Path helpers (mirrors computeRenamedPath from SchedulerManager.tsx) // --------------------------------------------------------------------------- -/// Build a tier suffix string like "-MWD" from a comma-separated tiers string like "M,W,D". -fn tier_suffix(tiers: &str) -> String { - if tiers.is_empty() { - return String::new(); - } - const ORDER: [char; 4] = ['M', 'W', 'D', 'H']; - let flags: Vec = tiers - .split(',') - .filter_map(|t| t.trim().chars().next()) - .collect(); - let sorted: String = ORDER.iter().filter(|c| flags.contains(c)).collect(); - if sorted.is_empty() { String::new() } else { format!("-{sorted}") } -} - /// Rename a backup file path to embed the new tier suffix. /// "server-2024-01-15_10-00-00.7z" → "server-2024-01-15_10-00-00-DH.7z" /// "server-2024-01-15_10-00-00-H.7z" + "D,H" → "server-2024-01-15_10-00-00-DH.7z" @@ -387,7 +383,7 @@ pub async fn handle_player_login(app: &AppHandle, server_id: &str, eos_id: &str, _ => return, }; - let map_path = map_id_to_path(&server.map_id); + let save_folder = map_id_to_save_folder(&conn, &server.map_id); // Create the archive (eos_id used as player_name for the filename). let rec = match create_player_backup_inner( @@ -395,7 +391,7 @@ pub async fn handle_player_login(app: &AppHandle, server_id: &str, eos_id: &str, server_id, &server.name, &server.install_path, - map_path, + &save_folder, &server.map_id, &backup_dir, eos_id, @@ -479,6 +475,8 @@ pub async fn execute_tick(app: &AppHandle) { } }; + let base_dir = db::get_app_setting(&conn, "base_dir").unwrap_or_default(); + let servers = db::get_servers(&conn); let pool = app.state::(); @@ -487,11 +485,19 @@ pub async fn execute_tick(app: &AppHandle) { continue; } + // Skip a server currently undergoing a scheduled restart/update — + // reading its files while they're mid-overwrite could produce a + // silently incomplete archive. Picked up again on the next hourly + // tick. Held for the rest of this iteration. + let app_state = app.state::(); + let Some(_lock) = app_state.try_lock_server(&server.id) else { + eprintln!("[backup_manager] Skipping backup for {} — restart/update in progress", server.id); + continue; + }; + let schedules = db::get_server_schedules(&conn, &server.id); - let base_map_path = map_id_to_path(&server.map_id); - let map_path = server.save_folder_name.as_deref() - .filter(|s| !s.is_empty()) - .unwrap_or(base_map_path); + let map_path = map_id_to_path(&conn, &server.map_id); + let save_folder = map_id_to_save_folder(&conn, &server.map_id); // Parse both schedule configs up front so we can decide whether a // world save is needed before starting either backup. @@ -529,13 +535,15 @@ pub async fn execute_tick(app: &AppHandle) { &server.id, &server.name, &server.install_path, - map_path, + &map_path, + &save_folder, &server.map_id, &backup_dir, "schedule", "", // tier assigned after tier computation &pool, true, // world save already done above + &base_dir, ).await { Ok(rec) => { handle_backup_record(&conn, &rec, &cfg, "server", None); @@ -561,7 +569,7 @@ pub async fn execute_tick(app: &AppHandle) { &server.id, &server.name, &server.install_path, - map_path, + &save_folder, &server.map_id, &backup_dir, "schedule", @@ -590,63 +598,64 @@ pub async fn execute_tick(app: &AppHandle) { // One notification per server per tick regardless of how many backup // types ran. Titles are specific when only one type ran; generic when // both ran so the body can carry the combined detail. + let sname = &server.name; let notification: Option<(&str, &str, String, &str)> = match (&server_outcome, &player_outcome) { // Both ran — both succeeded (Some(Ok(size)), Some(Ok(count))) if *count > 0 => Some(( - "backup_completed", "Backup Complete", - format!("Server backup: {size} · {count} players backed up"), + "backup_completed", "Server & Player Backup", + format!("{sname} — server backup: {size} · {count} players"), "success", )), // Both ran — server ok, players ran but 0 profiles found (Some(Ok(size)), Some(Ok(_))) => Some(( - "backup_completed", "Server Backup Complete", - format!("Scheduled server backup completed ({size})"), + "backup_completed", "Server Backup", + format!("{sname} — server backup complete ({size})"), "success", )), // Both ran — server ok, players failed (Some(Ok(size)), Some(Err(pe))) => Some(( "backup_failed", "Backup Partially Failed", - format!("Server backup complete ({size}) · Player backup failed: {pe}"), + format!("{sname} — server backup: {size} · player backup failed: {pe}"), "error", )), // Both ran — server failed, players ok (Some(Err(se)), Some(Ok(count))) if *count > 0 => Some(( "backup_failed", "Backup Partially Failed", - format!("Server backup failed: {se} · {count} player backups complete"), + format!("{sname} — server backup failed: {se} · {count} player backups complete"), "error", )), // Both ran — server failed, 0 players (Some(Err(se)), Some(Ok(_))) => Some(( "backup_failed", "Server Backup Failed", - format!("Scheduled server backup failed: {se}"), + format!("{sname} — server backup failed: {se}"), "error", )), // Both ran — both failed (Some(Err(se)), Some(Err(pe))) => Some(( "backup_failed", "Backup Failed", - format!("Server backup failed: {se} · Player backup failed: {pe}"), + format!("{sname} — server backup failed: {se} · player backup failed: {pe}"), "error", )), // Server only (Some(Ok(size)), None) => Some(( - "backup_completed", "Server Backup Complete", - format!("Scheduled server backup completed ({size})"), + "backup_completed", "Server Backup", + format!("{sname} — server backup complete ({size})"), "success", )), (Some(Err(se)), None) => Some(( "backup_failed", "Server Backup Failed", - format!("Scheduled server backup failed: {se}"), + format!("{sname} — server backup failed: {se}"), "error", )), // Player only (None, Some(Ok(count))) if *count > 0 => Some(( - "backup_completed", "Player Backup Complete", - format!("Scheduled player backups completed ({count} players)"), + "backup_completed", "Player Backup", + format!("{sname} — {count} player backups complete"), "success", )), (None, Some(Err(pe))) => Some(( "backup_failed", "Player Backup Failed", - format!("Scheduled player backup failed: {pe}"), + format!("{sname} — player backup failed: {pe}"), "error", )), // Player only with 0 profiles, or nothing ran diff --git a/src-tauri/src/commands/build_version.rs b/src-tauri/src/commands/build_version.rs index 819f8a8..7e9e1bc 100644 --- a/src-tauri/src/commands/build_version.rs +++ b/src-tauri/src/commands/build_version.rs @@ -158,14 +158,13 @@ pub async fn source_query_version(port: u16) -> Option { /// strings), app_id(2), players(1), max_players(1), bots(1), server_type(1), /// environment(1), visibility(1), vac(1), version (null-term string). fn parse_a2s_version(data: &[u8]) -> Option { + use super::utils::read_cstring; + let mut pos = 1; // skip protocol byte // Skip four null-terminated strings: name, map, folder, game for _ in 0..4 { - while pos < data.len() && data[pos] != 0 { - pos += 1; - } - pos += 1; // consume null terminator + read_cstring(data, &mut pos).ok()?; } // Skip: app_id(2) + players(1) + max_players(1) + bots(1) + @@ -176,12 +175,7 @@ fn parse_a2s_version(data: &[u8]) -> Option { return None; } - // Version string (null-terminated) - let start = pos; - while pos < data.len() && data[pos] != 0 { - pos += 1; - } - let version = std::str::from_utf8(&data[start..pos]).ok()?; + let version = read_cstring(data, &mut pos).ok()?; if version.is_empty() { return None; } @@ -191,7 +185,7 @@ fn parse_a2s_version(data: &[u8]) -> Option { if parts.len() >= 2 { Some(format!("{}.{}", parts[0], parts[1])) } else { - Some(version.to_string()) + Some(version) } } diff --git a/src-tauri/src/commands/certs.rs b/src-tauri/src/commands/certs.rs index 18d06a0..96a34af 100644 --- a/src-tauri/src/commands/certs.rs +++ b/src-tauri/src/commands/certs.rs @@ -104,7 +104,12 @@ async fn install_windows(cert_path: &str) -> Result<(), String> { #[cfg(target_os = "linux")] async fn install_linux(cert_path: &str, proton_path: &str, prefix_path: &str) -> Result<(), String> { let proton_script = format!("{proton_path}/proton"); - let wine_bin = format!("{proton_path}/files/bin/wine64"); + // Wine 10 (GE-Proton 11+) unified wine64 into a single wine binary. + // Fall back to wine if wine64 is absent. + let wine_bin = { + let w64 = format!("{proton_path}/files/bin/wine64"); + if PathBuf::from(&w64).exists() { w64 } else { format!("{proton_path}/files/bin/wine") } + }; let wine_pfx = format!("{prefix_path}/pfx"); let marker = PathBuf::from(prefix_path).join(CERT_MARKER_FILENAME); @@ -160,8 +165,15 @@ async fn install_linux(cert_path: &str, proton_path: &str, prefix_path: &str) -> )); } - // Write marker so future checks are instant. - let _ = tokio::fs::write(&marker, b"1").await; + // Write marker so future checks are instant. This must not be silently + // discarded: Linux has no direct way to query Wine's cert store, so + // check_amazon_root_ca_installed relies entirely on this file — if the + // write fails, a future check would report "not installed" forever even + // though wine certutil above genuinely succeeded. Surface the failure so + // the caller knows to retry rather than silently mismatching. + tokio::fs::write(&marker, b"1").await.map_err(|e| { + format!("Certificate installed, but failed to write install marker: {e}. Please try installing again.") + })?; Ok(()) } diff --git a/src-tauri/src/commands/cluster.rs b/src-tauri/src/commands/cluster.rs index a8db29e..977bfba 100644 --- a/src-tauri/src/commands/cluster.rs +++ b/src-tauri/src/commands/cluster.rs @@ -34,11 +34,34 @@ pub async fn create_cluster( Ok(id) } -/// No-op — the cluster directory is intentionally not deleted automatically. -/// The frontend removes the SQLite record and can prompt the user to delete -/// the directory manually if desired. +/// Delete the cluster directory from disk when `delete_files` is true. +/// The frontend removes the SQLite record and clears cluster_id on member servers. +/// +/// `cluster_dir` can be a free-text user-entered override (see +/// `create_cluster`) rather than an app-managed path, so before recursively +/// deleting anything this requires the resolved path to actually be inside +/// `base_dir` — otherwise a mistyped or overly broad override entered at +/// cluster-creation time (e.g. pointing at a home folder) would let this +/// silently `remove_dir_all` something far outside the app's own directories. #[tauri::command] -pub async fn delete_cluster(_cluster_id: String) -> Result<(), String> { +pub async fn delete_cluster(cluster_dir: String, base_dir: String, delete_files: bool) -> Result<(), String> { + if delete_files && !cluster_dir.is_empty() { + let p = std::path::Path::new(&cluster_dir); + if p.exists() { + let resolved = std::fs::canonicalize(p) + .map_err(|e| format!("Failed to resolve cluster directory: {e}"))?; + let resolved_base = std::fs::canonicalize(&base_dir) + .map_err(|e| format!("Failed to resolve base directory: {e}"))?; + if !resolved.starts_with(&resolved_base) { + return Err(format!( + "Refusing to delete '{}' — it is outside the configured base directory", + cluster_dir + )); + } + std::fs::remove_dir_all(&resolved) + .map_err(|e| format!("Failed to delete cluster directory: {e}"))?; + } + } Ok(()) } diff --git a/src-tauri/src/commands/countdown.rs b/src-tauri/src/commands/countdown.rs index bc9f770..2561168 100644 --- a/src-tauri/src/commands/countdown.rs +++ b/src-tauri/src/commands/countdown.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; use crate::state::AppState; use crate::state::CountdownSignal; -use super::server::{inner_stop_server, inner_start_server, StartServerParams}; +use super::server::{emit_status, ServerStatus, StartServerParams}; // --------------------------------------------------------------------------- // Tauri event payload @@ -108,10 +108,16 @@ pub async fn run_countdown( total_secs, }); emit_clear(app, server_id); + // With no countdown badge ever shown (nothing to warn anyone + // about), the card would otherwise sit on "running" right up + // until the final post-restart status — emit an explicit + // "stopping" so there's a visible transition in the meantime. + emit_stopping(app, server_id); return CountdownResult::Proceed; } } else { emit_clear(app, server_id); + emit_stopping(app, server_id); return CountdownResult::Proceed; } @@ -167,6 +173,25 @@ pub async fn run_countdown( rcon_send(rcon_port, rcon_password, &format!("ServerChat {cancel_message}")).await; } emit_clear(app, server_id); + // Callers that write "stopping" up front (Restart + // All, the manual Restart/Update-now buttons) need + // this reverted — the server was never actually + // touched. Every run_countdown caller only starts a + // countdown for an already-running server, so + // reverting to "running" is always correct here. + // Keep the real pid — it's still the same live + // process, nulling it out would break anything keyed + // off server.pid (RCON, stats polling, Stop button). + let pid = app.state::() + .running_servers.lock().unwrap() + .get(server_id).map(|rs| rs.pid); + emit_status(app, &ServerStatus { + server_id: server_id.to_string(), + status: "running".into(), + pid, + uptime_seconds: None, + error: None, + }); return CountdownResult::Cancel; } } @@ -187,14 +212,38 @@ fn emit_clear(app: &AppHandle, server_id: &str) { }); } +/// Emit a "stopping" status update. Used when a countdown is skipped +/// entirely (no players online, or a zero-length warning) so the UI still +/// shows a visible transition instead of sitting on the prior status right +/// up until the restart/update's final result arrives. +fn emit_stopping(app: &AppHandle, server_id: &str) { + emit_status(app, &ServerStatus { + server_id: server_id.to_string(), + status: "stopping".into(), + pid: None, + uptime_seconds: None, + error: None, + }); +} + // --------------------------------------------------------------------------- // Register / deregister countdown channels in AppState // --------------------------------------------------------------------------- -fn register_countdown(state: &AppState, server_id: &str) -> mpsc::Receiver { +/// Atomically checks for and registers a countdown in one lock acquisition — +/// checking `contains_key` and inserting under two separate locks (as this +/// used to do) leaves a window where two near-simultaneous callers for the +/// same server_id can both pass the check before either inserts, silently +/// overwriting one Sender with the other and leaving the first countdown +/// un-cancellable and running unsupervised. +fn try_register_countdown(state: &AppState, server_id: &str) -> Result, String> { let (tx, rx) = mpsc::channel::(1); - state.countdowns.lock().unwrap().insert(server_id.to_string(), tx); - rx + let mut cd = state.countdowns.lock().unwrap(); + if cd.contains_key(server_id) { + return Err(format!("A countdown is already in progress for {server_id}")); + } + cd.insert(server_id.to_string(), tx); + Ok(rx) } fn deregister_countdown(state: &AppState, server_id: &str) { @@ -231,15 +280,21 @@ pub async fn start_graceful_restart( } } - // Guard: no concurrent countdown. - { - let cd = state.countdowns.lock().unwrap(); - if cd.contains_key(¶ms.server_id) { - return Err("A countdown is already in progress for this server".into()); - } + // Guard: no concurrent countdown (checked and registered atomically). + let mut rx = try_register_countdown(&state, ¶ms.server_id)?; + + // Fail fast if a backup/update is already in progress for this server — + // held for the whole operation, including the countdown, since a backup + // that started mid-countdown and was still running when doexit fires + // would hit the same race this guards against. Not a `ServerLockGuard` + // (RAII) since that can't cross into the spawned 'static task below — + // released manually on every exit path instead, the same way + // `stopping_servers`/`countdowns` already span this spawn boundary. + if !state.busy_servers.lock().unwrap().insert(params.server_id.clone()) { + deregister_countdown(&state, ¶ms.server_id); + return Err(format!("An operation is already in progress for {} — try again in a moment", params.server_id)); } - let mut rx = register_countdown(&state, ¶ms.server_id); let app2 = app.clone(); // Spawn so the command returns immediately. @@ -260,26 +315,27 @@ pub async fn start_graceful_restart( deregister_countdown(&state2, ¶ms.server_id); if matches!(result, CountdownResult::Proceed) { - // saveworld → doexit → wait → restart - let _ = super::rcon::transient_rcon_command( - params.rcon_port, ¶ms.rcon_password, "saveworld" + let notify = state2.register_stop_handoff(¶ms.server_id); + super::server::graceful_shutdown_via_rcon( + &app2, ¶ms.server_id, params.rcon_port, ¶ms.rcon_password, ).await; - sleep(Duration::from_secs(3)).await; - let _ = super::rcon::transient_rcon_command( - params.rcon_port, ¶ms.rcon_password, "doexit" - ).await; - - // Wait up to 30s for graceful exit. - for _ in 0..60 { - sleep(Duration::from_millis(500)).await; - let still_running = state2.running_servers.lock().unwrap().contains_key(¶ms.server_id); - if !still_running { break; } - } - // Force-kill if still alive. - let _ = inner_stop_server(&app2, ¶ms.server_id, false); - - let _ = inner_start_server(app2, params.start_params).await; + // Wait for the watcher's own cleanup to finish before emitting + // our next status — otherwise its delayed "stopped" can race in + // afterward and silently overwrite it. + state2.wait_for_stop_handoff(¶ms.server_id, notify).await; + // Hand off to the staggered startup queue instead of restarting + // directly — same reason fire_restart/inner_restart_server do, + // so several servers warn-restarting together (e.g. Restart All) + // don't all cold-boot at once. + emit_status(&app2, &ServerStatus { + server_id: params.server_id.clone(), + status: "startup_queued".into(), + pid: None, + uptime_seconds: None, + error: None, + }); } + state2.busy_servers.lock().unwrap().remove(¶ms.server_id); }); Ok(()) @@ -312,20 +368,30 @@ pub async fn start_graceful_update( state: State<'_, AppState>, params: GracefulUpdateParams, ) -> Result<(), String> { - // Guard: no concurrent countdown. - { - let cd = state.countdowns.lock().unwrap(); - if cd.contains_key(¶ms.server_id) { - return Err("A countdown is already in progress for this server".into()); - } + let was_running = state.running_servers.lock().unwrap().contains_key(¶ms.server_id); + // Guard: no concurrent countdown (checked and registered atomically). + let mut rx = try_register_countdown(&state, ¶ms.server_id)?; + + // Fail fast if a backup/restart is already in progress for this server — + // see start_graceful_restart's comment for why this can't be a + // `ServerLockGuard` (RAII) across the spawn boundary below. Released by + // `ReleaseBusyOnDrop` inside the spawned task instead, since that task + // has several early-return exit points this needs to cover uniformly. + if !state.busy_servers.lock().unwrap().insert(params.server_id.clone()) { + deregister_countdown(&state, ¶ms.server_id); + return Err(format!("An operation is already in progress for {} — try again in a moment", params.server_id)); } - let was_running = state.running_servers.lock().unwrap().contains_key(¶ms.server_id); - let mut rx = register_countdown(&state, ¶ms.server_id); let app2 = app.clone(); tauri::async_runtime::spawn(async move { let state2 = app2.state::(); + struct ReleaseBusyOnDrop<'a> { state: &'a AppState, server_id: &'a str } + impl Drop for ReleaseBusyOnDrop<'_> { + fn drop(&mut self) { self.state.busy_servers.lock().unwrap().remove(self.server_id); } + } + let _release_busy = ReleaseBusyOnDrop { state: &state2, server_id: ¶ms.server_id }; + // Only run countdown if server is actually running. let proceed = if was_running { let r = run_countdown( @@ -348,27 +414,19 @@ pub async fn start_graceful_update( if !proceed { return; } - // Stop the server gracefully if it was running. + // Stop the server gracefully if it was running, and wait for the + // watcher's own cleanup to finish before proceeding — otherwise its + // delayed "stopped" can race in after our own status emissions below + // (updating / startup_queued / stopped) and silently overwrite them. if was_running { - let _ = super::rcon::transient_rcon_command( - params.rcon_port, ¶ms.rcon_password, "saveworld" + let notify = state2.register_stop_handoff(¶ms.server_id); + super::server::graceful_shutdown_via_rcon( + &app2, ¶ms.server_id, params.rcon_port, ¶ms.rcon_password, ).await; - sleep(Duration::from_secs(3)).await; - let _ = super::rcon::transient_rcon_command( - params.rcon_port, ¶ms.rcon_password, "doexit" - ).await; - - for _ in 0..60 { - sleep(Duration::from_millis(500)).await; - let still = state2.running_servers.lock().unwrap().contains_key(¶ms.server_id); - if !still { break; } - } - let _ = inner_stop_server(&app2, ¶ms.server_id, false); + state2.wait_for_stop_handoff(¶ms.server_id, notify).await; } // Emit "updating" status so server card shows spinner. - use crate::commands::server::emit_status; - use crate::commands::server::ServerStatus; emit_status(&app2, &ServerStatus { server_id: params.server_id.clone(), status: "updating".into(), @@ -407,8 +465,12 @@ pub async fn start_graceful_update( // Sync updated cache to server directory. let cache_path = std::path::PathBuf::from(¶ms.cache_dir); let server_path = std::path::PathBuf::from(¶ms.install_path); + let app_clone = app2.clone(); + let channel_clone = channel.clone(); if let Err(e) = tokio::task::spawn_blocking(move || { - crate::commands::steamcmd::sync_cache_to_server(&cache_path, &server_path) + // Not individually cancellable from this countdown-triggered path — a never-set flag is correct here. + let no_abort = std::sync::atomic::AtomicBool::new(false); + crate::commands::steamcmd::sync_cache_to_server(&cache_path, &server_path, &app_clone, &channel_clone, &no_abort) }).await.map_err(|e| e.to_string()).and_then(|r| r.map_err(|e| e.to_string())) { eprintln!("Cache sync failed: {e}"); } @@ -418,15 +480,26 @@ pub async fn start_graceful_update( "updateApplied": true, "serverId": params.server_id, })); - - // Restart if requested and we have start params. - if params.restart_after { - if let Some(sp) = params.start_params { - let _ = inner_start_server(app2, sp).await; - return; + if let Some(db_path) = state2.get_db_path() { + if let Ok(conn) = crate::db::open(&db_path) { + crate::db::clear_update_available(&conn, ¶ms.server_id); } } + // Restart if requested — hand off to the staggered startup queue + // rather than starting directly, same as the scheduler's post-update + // restart and the plain graceful-restart command above. + if params.restart_after && params.start_params.is_some() { + emit_status(&app2, &ServerStatus { + server_id: params.server_id.clone(), + status: "startup_queued".into(), + pid: None, + uptime_seconds: None, + error: None, + }); + return; + } + emit_status(&app2, &ServerStatus { server_id: params.server_id.clone(), status: "stopped".into(), diff --git a/src-tauri/src/commands/firewall.rs b/src-tauri/src/commands/firewall.rs index e54a55d..63f6fdd 100644 --- a/src-tauri/src/commands/firewall.rs +++ b/src-tauri/src/commands/firewall.rs @@ -11,6 +11,18 @@ pub struct PortDef { pub protocol: String, // "tcp" | "udp" } +/// Drop any entry whose `protocol` isn't exactly "tcp"/"udp". `protocol` is +/// only constrained to those two values at the TypeScript type level, which +/// isn't enforced across the IPC boundary — on Linux, `add_iptables` and +/// `add_firewalld` interpolate `protocol` directly into a shell command +/// string run via `pkexec`, so an unvalidated value here would be arbitrary +/// root command injection. Filtering (rather than erroring) fails closed: +/// a malformed entry is silently excluded from the firewall-open set instead +/// of blocking every other legitimate port in the batch. +fn sanitize_ports(ports: Vec) -> Vec { + ports.into_iter().filter(|p| p.protocol == "tcp" || p.protocol == "udp").collect() +} + #[derive(Debug, Serialize)] pub struct PortStatus { pub port: u16, @@ -72,22 +84,31 @@ mod windows_impl { continue; } - let status = runas::Command::new("netsh") - .args(&[ - "advfirewall", "firewall", "add", "rule", - &format!("name={name}"), - "dir=in", "action=allow", - &format!("protocol={proto}"), - &format!("localport={port_str}"), - ]) - .status() - .map_err(|e| format!("Failed to run elevated netsh for port {}: {e}", p.port))?; + let port = p.port; + // runas::Command::status() blocks the calling thread until the + // (possibly UAC-elevated) process exits — a user who leaves the + // UAC prompt unanswered would otherwise stall this tokio worker + // thread indefinitely, starving unrelated async work (RCON + // polling, log tailing) on the same small pool. + let status = tokio::task::spawn_blocking(move || { + runas::Command::new("netsh") + .args(&[ + "advfirewall", "firewall", "add", "rule", + &format!("name={name}"), + "dir=in", "action=allow", + &format!("protocol={proto}"), + &format!("localport={port_str}"), + ]) + .status() + }) + .await + .map_err(|e| format!("spawn_blocking panicked for port {port}: {e}"))? + .map_err(|e| format!("Failed to run elevated netsh for port {port}: {e}"))?; if !status.success() { return Err(format!( - "netsh exited with code {} for port {}", + "netsh exited with code {} for port {port}", status.code().unwrap_or(-1), - p.port )); } } @@ -97,17 +118,22 @@ mod windows_impl { pub async fn remove_rules(ports: &[PortDef]) -> Result<(), String> { for p in ports { let name = rule_name(p.port, &p.protocol); - let status = runas::Command::new("netsh") - .args(&[ - "advfirewall", "firewall", "delete", "rule", - &format!("name={name}"), - ]) - .status() - .map_err(|e| format!("Failed to run elevated netsh delete for port {}: {e}", p.port))?; + let port = p.port; + let status = tokio::task::spawn_blocking(move || { + runas::Command::new("netsh") + .args(&[ + "advfirewall", "firewall", "delete", "rule", + &format!("name={name}"), + ]) + .status() + }) + .await + .map_err(|e| format!("spawn_blocking panicked for port {port}: {e}"))? + .map_err(|e| format!("Failed to run elevated netsh delete for port {port}: {e}"))?; if !status.success() { // Non-fatal: rule may already be gone - log::warn!("netsh delete exited {} for port {}", status.code().unwrap_or(-1), p.port); + log::warn!("netsh delete exited {} for port {port}", status.code().unwrap_or(-1)); } } Ok(()) @@ -179,7 +205,7 @@ mod linux_impl { // ── UFW ───────────────────────────────────────────────────────────────── const UFW_PROFILE_PATH: &str = "/etc/ufw/applications.d/lokiasam"; - const UFW_APP_NAME: &str = "LokiASAM"; + const UFW_APP_NAME: &str = "lokiasam"; /// Parse the ports line from the lokiasam ufw profile. /// Returns a set of "port/proto" strings like {"7777/udp", "27020/tcp"}. @@ -211,8 +237,11 @@ mod linux_impl { } /// Build the ports= line for the ufw profile from a list of PortDef. + /// Each port is its own `|`-separated segment (e.g. `27020/tcp|7777/udp|27015/udp`). + /// Comma-grouping (`7777,27015/udp`) is avoided because some UFW versions silently + /// drop segments that follow a comma-grouped entry when mixed protocols are present. + /// TCP entries come first to match the convention used by other application profiles. fn build_ufw_ports_line(ports: &[PortDef]) -> String { - // Group by protocol let mut udp: Vec = ports.iter().filter(|p| p.protocol == "udp").map(|p| p.port).collect(); let mut tcp: Vec = ports.iter().filter(|p| p.protocol == "tcp").map(|p| p.port).collect(); udp.sort_unstable(); @@ -220,15 +249,9 @@ mod linux_impl { tcp.sort_unstable(); tcp.dedup(); - let mut segments = Vec::new(); - if !udp.is_empty() { - let ports_str = udp.iter().map(|p| p.to_string()).collect::>().join(","); - segments.push(format!("{ports_str}/udp")); - } - if !tcp.is_empty() { - let ports_str = tcp.iter().map(|p| p.to_string()).collect::>().join(","); - segments.push(format!("{ports_str}/tcp")); - } + let mut segments: Vec = Vec::new(); + for p in &udp { segments.push(format!("{p}/udp")); } + for p in &tcp { segments.push(format!("{p}/tcp")); } segments.join("|") } @@ -256,120 +279,51 @@ mod linux_impl { FirewallStatus { firewall_type: "ufw".into(), active: true, ports: statuses } } - pub async fn add_ufw(new_ports: &[PortDef], existing_covered: &std::collections::HashSet) -> Result<(), String> { - // Read current profile ports, merge with new ones - let current = parse_ufw_profile(); - let mut all_ports: Vec = Vec::new(); - - // Keep existing covered ports that are already in the profile - for entry in ¤t { - if let Some(slash) = entry.rfind('/') { - if let Ok(p) = entry[..slash].parse::() { - let proto = entry[slash + 1..].to_string(); - all_ports.push(PortDef { port: p, protocol: proto }); - } - } - } - // Add new ports (dedup handled by build) - for p in new_ports { - let key = format!("{}/{}", p.port, p.protocol); - if !existing_covered.contains(&key) { - all_ports.push(p.clone()); - } - } - // Also include uncovered ones from the original new_ports list - for p in new_ports { - if !all_ports.iter().any(|e| e.port == p.port && e.protocol == p.protocol) { - all_ports.push(p.clone()); + /// Set the UFW application profile to exactly `desired_ports` and apply it. + /// Writes a fresh profile (TCP entries first, one port per `|` segment) then does + /// delete → re-allow so UFW picks up the new profile cleanly. + /// If `desired_ports` is empty, deletes the rule and the profile file entirely. + pub async fn apply_ufw_state(desired_ports: &[PortDef]) -> Result<(), String> { + if desired_ports.is_empty() { + let cmd = format!("ufw delete allow '{UFW_APP_NAME}' ; rm -f '{UFW_PROFILE_PATH}'"); + let status = Command::new("pkexec") + .args(["sh", "-c", &cmd]) + .status() + .await + .map_err(|e| format!("pkexec ufw delete failed: {e}"))?; + if !status.success() { + return Err(format!("pkexec ufw delete exited {}", status.code().unwrap_or(-1))); } + return Ok(()); } - let profile_content = build_ufw_profile(&all_ports); - - // Write profile with pkexec tee - let mut child = Command::new("pkexec") - .args(["tee", UFW_PROFILE_PATH]) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::null()) - .spawn() - .map_err(|e| format!("Failed to spawn pkexec tee: {e}"))?; - - if let Some(mut stdin) = child.stdin.take() { - use tokio::io::AsyncWriteExt; - stdin.write_all(profile_content.as_bytes()).await - .map_err(|e| format!("Failed to write profile: {e}"))?; - } - - let output = child.wait_with_output().await - .map_err(|e| format!("pkexec tee failed: {e}"))?; - - if !output.status.success() { - return Err(format!("pkexec tee exited {}", output.status.code().unwrap_or(-1))); - } - - // Activate the rule - let allow_status = Command::new("pkexec") - .args(["ufw", "allow", UFW_APP_NAME]) + let tmp_path = std::env::temp_dir().join("lokiasam_ufw_profile"); + std::fs::write(&tmp_path, build_ufw_profile(desired_ports)) + .map_err(|e| format!("Failed to write UFW temp profile: {e}"))?; + + let tmp_str = tmp_path.to_string_lossy(); + // Copy profile first, then delete the old rule and re-allow from the + // updated profile. The delete+allow pair is grouped in `(...)` so `&&` + // gates the *whole group* on `cp` succeeding — without the group, + // `;` has lower precedence than `&&` and `ufw allow` would run + // unconditionally even when `cp` failed, applying rules from a stale + // or missing profile. Inside the group, `;` (not `&&`) separates + // delete from allow so allow still runs even if no prior rule existed + // to delete. + let cmd = format!( + "cp '{tmp_str}' '{UFW_PROFILE_PATH}' && ( ufw delete allow '{UFW_APP_NAME}' ; ufw allow '{UFW_APP_NAME}' )" + ); + let status = Command::new("pkexec") + .args(["sh", "-c", &cmd]) .status() .await - .map_err(|e| format!("Failed to run pkexec ufw allow: {e}"))?; + .map_err(|e| format!("pkexec ufw apply failed: {e}"))?; - if !allow_status.success() { - return Err(format!("pkexec ufw allow exited {}", allow_status.code().unwrap_or(-1))); - } - Ok(()) - } - - pub async fn remove_ufw(ports_to_remove: &[PortDef]) -> Result<(), String> { - let current = parse_ufw_profile(); - let remove_set: std::collections::HashSet = ports_to_remove - .iter().map(|p| format!("{}/{}", p.port, p.protocol)).collect(); - - let remaining: Vec = current.iter() - .filter(|k| !remove_set.contains(*k)) - .filter_map(|entry| { - let slash = entry.rfind('/')?; - let p = entry[..slash].parse::().ok()?; - Some(PortDef { port: p, protocol: entry[slash + 1..].to_string() }) - }) - .collect(); + let _ = std::fs::remove_file(&tmp_path); - let profile_content = if remaining.is_empty() { - // Delete the profile and the rule - let _ = Command::new("pkexec") - .args(["ufw", "delete", "allow", UFW_APP_NAME]) - .status().await; - let _ = Command::new("pkexec") - .args(["rm", "-f", UFW_PROFILE_PATH]) - .status().await; - return Ok(()); - } else { - build_ufw_profile(&remaining) - }; - - // Rewrite profile - let mut child = Command::new("pkexec") - .args(["tee", UFW_PROFILE_PATH]) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::null()) - .spawn() - .map_err(|e| format!("Failed to spawn pkexec tee: {e}"))?; - - if let Some(mut stdin) = child.stdin.take() { - use tokio::io::AsyncWriteExt; - stdin.write_all(profile_content.as_bytes()).await - .map_err(|e| format!("Failed to write profile: {e}"))?; + if !status.success() { + return Err(format!("pkexec ufw apply exited {}", status.code().unwrap_or(-1))); } - let out = child.wait_with_output().await - .map_err(|e| format!("pkexec tee failed: {e}"))?; - if !out.status.success() { - return Err(format!("pkexec tee exited {}", out.status.code().unwrap_or(-1))); - } - - // Re-apply - let _ = Command::new("pkexec") - .args(["ufw", "allow", UFW_APP_NAME]) - .status().await; Ok(()) } @@ -391,66 +345,119 @@ mod linux_impl { } pub async fn add_firewalld(ports: &[PortDef]) -> Result<(), String> { + // Check which ports aren't already open (no elevation needed for --query-port) + let mut to_add = Vec::new(); for p in ports { let arg = format!("{}/{}", p.port, p.protocol); let already = Command::new("firewall-cmd") .args(["--query-port", &arg]) .status().await .map(|s| s.success()).unwrap_or(false); - if already { continue; } - - let s = Command::new("pkexec") - .args(["firewall-cmd", "--permanent", &format!("--add-port={arg}")]) - .status().await - .map_err(|e| format!("pkexec firewall-cmd failed: {e}"))?; - if !s.success() { - return Err(format!("firewall-cmd --add-port exited {}", s.code().unwrap_or(-1))); - } + if !already { to_add.push(arg); } + } + if to_add.is_empty() { return Ok(()); } + + // Batch all --add-port flags + --reload into a single pkexec sh call + let add_flags = to_add.iter().map(|a| format!("--add-port={a}")).collect::>().join(" "); + let cmd = format!("firewall-cmd --permanent {add_flags} && firewall-cmd --reload"); + let s = Command::new("pkexec") + .args(["sh", "-c", &cmd]) + .status().await + .map_err(|e| format!("pkexec firewall-cmd failed: {e}"))?; + if !s.success() { + return Err(format!("firewall-cmd add/reload exited {}", s.code().unwrap_or(-1))); } - // Reload once after all ports added - let _ = Command::new("pkexec") - .args(["firewall-cmd", "--reload"]) - .status().await; Ok(()) } - pub async fn remove_firewalld(ports: &[PortDef]) -> Result<(), String> { - for p in ports { - let arg = format!("{}/{}", p.port, p.protocol); - let _ = Command::new("pkexec") - .args(["firewall-cmd", "--permanent", &format!("--remove-port={arg}")]) - .status().await; + /// Remove firewall rules for ports NOT in `remaining_ports`. + /// Queries `firewall-cmd --list-ports` (no elevation) to find what is currently + /// open, then removes only the excess — never touches ports still in use. + pub async fn remove_firewalld(remaining_ports: &[PortDef]) -> Result<(), String> { + let remaining_set: std::collections::HashSet = remaining_ports + .iter().map(|p| format!("{}/{}", p.port, p.protocol)).collect(); + + // Query current open ports without elevation + let text = match Command::new("firewall-cmd").args(["--list-ports"]).output().await { + Ok(o) => String::from_utf8_lossy(&o.stdout).into_owned(), + Err(_) => return Ok(()), // can't query current state — skip rather than error + }; + + let to_remove: Vec = text + .split_whitespace() + .filter(|s| !remaining_set.contains(*s)) + .map(|s| s.to_string()) + .collect(); + + if to_remove.is_empty() { return Ok(()); } + + let remove_flags = to_remove.iter() + .map(|s| format!("--remove-port={s}")) + .collect::>().join(" "); + let cmd = format!("firewall-cmd --permanent {remove_flags} && firewall-cmd --reload"); + let status = Command::new("pkexec") + .args(["sh", "-c", &cmd]) + .status() + .await + .map_err(|e| format!("pkexec firewall-cmd remove failed: {e}"))?; + if !status.success() { + return Err(format!("firewall-cmd remove/reload exited {}", status.code().unwrap_or(-1))); } - let _ = Command::new("pkexec") - .args(["firewall-cmd", "--reload"]) - .status().await; Ok(()) } // ── iptables (DB-backed fallback) ──────────────────────────────────────── pub async fn add_iptables(ports: &[PortDef]) -> Result<(), String> { - for p in ports { - let proto = &p.protocol; - let port_str = p.port.to_string(); - let s = Command::new("pkexec") - .args(["iptables", "-A", "INPUT", "-p", proto, "--dport", &port_str, "-j", "ACCEPT"]) - .status().await - .map_err(|e| format!("pkexec iptables failed: {e}"))?; - if !s.success() { - return Err(format!("iptables -A exited {} for port {}", s.code().unwrap_or(-1), p.port)); - } + if ports.is_empty() { return Ok(()); } + let cmds = ports.iter() + .map(|p| format!("iptables -A INPUT -p {} --dport {} -j ACCEPT", p.protocol, p.port)) + .collect::>().join(" && "); + let s = Command::new("pkexec") + .args(["sh", "-c", &cmds]) + .status().await + .map_err(|e| format!("pkexec iptables failed: {e}"))?; + if !s.success() { + return Err(format!("iptables add exited {}", s.code().unwrap_or(-1))); } Ok(()) } - pub async fn remove_iptables(ports: &[PortDef]) -> Result<(), String> { - for p in ports { - let proto = &p.protocol; - let port_str = p.port.to_string(); - let _ = Command::new("pkexec") - .args(["iptables", "-D", "INPUT", "-p", proto, "--dport", &port_str, "-j", "ACCEPT"]) - .status().await; + /// Remove iptables rules for ports NOT in `remaining_ports`. + /// Parses `iptables -S INPUT` (no elevation) to find current ACCEPT rules, + /// then removes only the ones that are no longer needed. + pub async fn remove_iptables(remaining_ports: &[PortDef]) -> Result<(), String> { + let remaining_set: std::collections::HashSet = remaining_ports + .iter().map(|p| format!("{}/{}", p.protocol, p.port)).collect(); + + let text = match Command::new("iptables").args(["-S", "INPUT"]).output().await { + Ok(o) => String::from_utf8_lossy(&o.stdout).into_owned(), + Err(_) => return Ok(()), // can't query current state — skip rather than error + }; + + // Match lines like: -A INPUT -p udp --dport 7777 -j ACCEPT + let mut to_remove: Vec = Vec::new(); + for line in text.lines() { + if !line.contains("-j ACCEPT") { continue; } + let proto = ["udp", "tcp"].iter().find(|&&pr| line.contains(&format!("-p {pr} "))); + let dport = line.split("--dport ").nth(1).and_then(|s| s.split_whitespace().next()); + if let (Some(proto), Some(port)) = (proto, dport) { + if !remaining_set.contains(&format!("{proto}/{port}")) { + to_remove.push(format!("iptables -D INPUT -p {proto} --dport {port} -j ACCEPT")); + } + } + } + + if to_remove.is_empty() { return Ok(()); } + // Use ; so a missing rule doesn't abort removal of the remaining ones + let cmds = to_remove.join(" ; "); + let status = Command::new("pkexec") + .args(["sh", "-c", &cmds]) + .status() + .await + .map_err(|e| format!("pkexec iptables remove failed: {e}"))?; + if !status.success() { + return Err(format!("iptables remove exited {}", status.code().unwrap_or(-1))); } Ok(()) } @@ -474,14 +481,14 @@ pub async fn check_firewall_ports(ports: Vec) -> Result Ok(check_ufw(&ports).await), FirewallKind::Firewalld => Ok(check_firewalld(&ports).await), - FirewallKind::Iptables | FirewallKind::None => { + kind @ (FirewallKind::Iptables | FirewallKind::None) => { // For iptables we rely on DB state (checked by the frontend). // Return active:false so the frontend falls back to DB. let statuses = ports.iter().map(|p| PortStatus { port: p.port, protocol: p.protocol.clone(), covered: false, }).collect(); Ok(FirewallStatus { - firewall_type: if matches!(detect().await, FirewallKind::Iptables) { + firewall_type: if matches!(kind, FirewallKind::Iptables) { "iptables".into() } else { "none".into() @@ -502,9 +509,13 @@ pub async fn check_firewall_ports(ports: Vec) -> Result, _proton_path: Option) -> Result<(), String> { + let ports = sanitize_ports(ports); #[cfg(target_os = "windows")] { windows_impl::add_rules(&ports).await @@ -514,13 +525,10 @@ pub async fn add_firewall_rules(ports: Vec, _proton_path: Option { - let current = parse_ufw_profile(); - add_ufw(&ports, ¤t).await - } + FirewallKind::Ufw => apply_ufw_state(&ports).await, FirewallKind::Firewalld => add_firewalld(&ports).await, FirewallKind::Iptables => add_iptables(&ports).await, - FirewallKind::None => Ok(()), // nothing to do + FirewallKind::None => Ok(()), } } @@ -530,11 +538,17 @@ pub async fn add_firewall_rules(ports: Vec, _proton_path: Option) -> Result<(), String> { + let ports = sanitize_ports(ports); #[cfg(target_os = "windows")] { + // On Windows, remove_rules takes ports-to-remove, so we can't use the + // remaining-ports model directly. For now keep existing per-rule deletion. windows_impl::remove_rules(&ports).await } @@ -542,7 +556,7 @@ pub async fn remove_firewall_rules(ports: Vec) -> Result<(), String> { { use linux_impl::*; match detect().await { - FirewallKind::Ufw => remove_ufw(&ports).await, + FirewallKind::Ufw => apply_ufw_state(&ports).await, FirewallKind::Firewalld => remove_firewalld(&ports).await, FirewallKind::Iptables => remove_iptables(&ports).await, FirewallKind::None => Ok(()), diff --git a/src-tauri/src/commands/logs.rs b/src-tauri/src/commands/logs.rs index 34d56a7..a45a876 100644 --- a/src-tauri/src/commands/logs.rs +++ b/src-tauri/src/commands/logs.rs @@ -556,8 +556,6 @@ fn extract_timestamp_from_filename(name: &str) -> String { name.trim_start_matches("ShooterGame_") .trim_end_matches(".log") .replace('_', " ") - .replace('-', if name.contains("_") { "-" } else { "-" }) - .to_string() } /// Convert a UE5 crash folder name (e.g. `UE5-ShooterGame-Win64-2026.06.08-14.30.00`) to a readable string. diff --git a/src-tauri/src/commands/mods.rs b/src-tauri/src/commands/mods.rs index 89c8a0d..19d13f3 100644 --- a/src-tauri/src/commands/mods.rs +++ b/src-tauri/src/commands/mods.rs @@ -40,14 +40,19 @@ fn emit_mod_line( } /// Stream stdout + stderr from a child process to a Tauri event channel, -/// tagging each line with an optional mod ID. +/// tagging each line with an optional mod ID. Kills the full process tree +/// and returns an "Aborted" error if `abort` is set before the process +/// exits — mirrors `utils::stream_process_abortable`, which this can't reuse +/// directly since lines here also carry a mod ID tag. async fn stream_process_mod( app: &tauri::AppHandle, child: &mut tokio::process::Child, channel: &str, mod_id: Option<&str>, + abort: &std::sync::Arc, ) -> Result { use tokio::io::{AsyncBufReadExt, BufReader}; + use std::sync::atomic::Ordering; let stdout = child.stdout.take().ok_or("failed to capture stdout")?; let stderr = child.stderr.take().ok_or("failed to capture stderr")?; @@ -73,9 +78,36 @@ async fn stream_process_mod( } }); - let _ = tokio::join!(stdout_task, stderr_task); - let status = child.wait().await.map_err(|e| e.to_string())?; - Ok(status.code().unwrap_or(-1)) + loop { + if abort.load(Ordering::Relaxed) { + // Kill the full process tree so SteamCMD's own child processes + // don't keep running after the parent is killed. + if let Some(raw_pid) = child.id() { + use sysinfo::{Pid, ProcessesToUpdate, System}; + let mut sys = System::new(); + sys.refresh_processes(ProcessesToUpdate::All, false); + let root = Pid::from_u32(raw_pid); + for pid in super::utils::collect_subtree(&sys, root) { + if let Some(proc) = sys.process(pid) { + proc.kill(); + } + } + } + stdout_task.abort(); + stderr_task.abort(); + let _ = child.kill().await; + let _ = child.wait().await; + return Err("Aborted".into()); + } + match tokio::time::timeout(std::time::Duration::from_millis(250), child.wait()).await { + Ok(Ok(status)) => { + let _ = tokio::join!(stdout_task, stderr_task); + return Ok(status.code().unwrap_or(-1)); + } + Ok(Err(e)) => return Err(e.to_string()), + Err(_) => { /* still running, loop */ } + } + } } // --------------------------------------------------------------------------- @@ -284,6 +316,7 @@ pub async fn install_mods( install_path: String, mod_ids: Vec, app: tauri::AppHandle, + state: tauri::State<'_, crate::state::AppState>, ) -> Result<(), String> { let channel = format!("mods://progress/{}", server_id); @@ -292,7 +325,30 @@ pub async fn install_mods( return Ok(()); } - let steamcmd_dir = Path::new(&steamcmd_path) + // Registered so CloseWarningManager's running-ops check (and the manual + // Cancel action) can see and stop an in-flight mod download — previously + // this was invisible to both, so closing the app mid-download orphaned + // the SteamCMD process with no warning and no record the install was + // ever incomplete. + let op_key = format!("mods_{server_id}"); + let abort = state.register_abort(&op_key); + + let result = install_mods_body(&steamcmd_path, &base_dir, &install_path, &mod_ids, &app, &channel, &abort).await; + + state.clear_abort(&op_key, &abort); + result +} + +async fn install_mods_body( + steamcmd_path: &str, + base_dir: &str, + install_path: &str, + mod_ids: &[String], + app: &tauri::AppHandle, + channel: &str, + abort: &std::sync::Arc, +) -> Result<(), String> { + let steamcmd_dir = Path::new(steamcmd_path) .parent() .ok_or("Cannot determine SteamCMD directory from path")? .to_path_buf(); @@ -305,7 +361,10 @@ pub async fn install_mods( None, ); - for mod_id in &mod_ids { + for mod_id in mod_ids { + if abort.load(std::sync::atomic::Ordering::Relaxed) { + return Err("Aborted".into()); + } emit_mod_line( &app, &channel, @@ -328,7 +387,7 @@ pub async fn install_mods( .spawn() .map_err(|e| format!("Failed to launch SteamCMD: {e}"))?; - let exit_code = stream_process_mod(&app, &mut child, &channel, Some(mod_id)).await?; + let exit_code = stream_process_mod(app, &mut child, channel, Some(mod_id), abort).await?; if exit_code != 0 { let msg = format!( diff --git a/src-tauri/src/commands/notifications.rs b/src-tauri/src/commands/notifications.rs index b4f14f7..bce64aa 100644 --- a/src-tauri/src/commands/notifications.rs +++ b/src-tauri/src/commands/notifications.rs @@ -91,18 +91,7 @@ pub async fn dispatch_notification( serde_json::from_str(&cfg.config_json).unwrap_or_default(); if let Some(url) = cfg_json.get("webhookUrl").and_then(|u| u.as_str()) { let state = app.state::(); - let payload = serde_json::json!({ - "embeds": [{ - "title": title, - "description": body, - "color": severity_color(severity), - "fields": [ - { "name": "Event", "value": event_type, "inline": true }, - { "name": "Server", "value": server_name, "inline": true } - ], - "footer": { "text": "LokiASAM" } - }] - }); + let payload = build_discord_embed(title, body, severity_color(severity), event_type, server_name); let client = state.http_client.clone(); let url = url.to_string(); tauri::async_runtime::spawn(async move { @@ -145,6 +134,24 @@ pub async fn dispatch_notification( })); } +/// Build the Discord embed JSON body shared by the auto-dispatch "discord" +/// channel and the manual `send_discord_notification` command, so the two +/// can't drift out of sync with each other. +fn build_discord_embed(title: &str, description: &str, color: u32, event_type: &str, server_name: &str) -> serde_json::Value { + serde_json::json!({ + "embeds": [{ + "title": title, + "description": description, + "color": color, + "fields": [ + { "name": "Event", "value": event_type, "inline": true }, + { "name": "Server", "value": server_name, "inline": true } + ], + "footer": { "text": "LokiASAM" } + }] + }) +} + fn severity_color(severity: &str) -> u32 { match severity { "success" => 0x00ff88, @@ -198,18 +205,7 @@ pub async fn send_discord_notification( webhook_url: String, payload: DiscordPayload, ) -> Result<(), String> { - let body = serde_json::json!({ - "embeds": [{ - "title": payload.title, - "description": payload.description, - "color": payload.color, - "fields": [ - { "name": "Event", "value": payload.event_type, "inline": true }, - { "name": "Server", "value": payload.server_name, "inline": true } - ], - "footer": { "text": "LokiASAM" } - }] - }); + let body = build_discord_embed(&payload.title, &payload.description, payload.color, &payload.event_type, &payload.server_name); let response = state .http_client diff --git a/src-tauri/src/commands/proton.rs b/src-tauri/src/commands/proton.rs index ba3e306..9e396c0 100644 --- a/src-tauri/src/commands/proton.rs +++ b/src-tauri/src/commands/proton.rs @@ -98,7 +98,7 @@ pub async fn download_proton_ge( ) -> Result { let abort = state.register_abort("proton_download"); let result = download_proton_ge_inner(&app_handle, &target_dir, &abort).await; - state.clear_abort("proton_download"); + state.clear_abort("proton_download", &abort); result } @@ -141,10 +141,10 @@ async fn download_proton_ge_inner( .find(|a| { a["name"] .as_str() - .map(|n| n.ends_with(".tar.gz")) + .map(|n| n.ends_with(".tar.gz") && !n.contains("aarch64")) .unwrap_or(false) }) - .ok_or("No .tar.gz asset found in release")?; + .ok_or("No x86_64 .tar.gz asset found in release")?; let asset_name = asset["name"] .as_str() @@ -173,6 +173,23 @@ async fn download_proton_ge_inner( let tmp_path = target.join(format!("{asset_name}.tmp")); let tar_path = target.join(&asset_name); + // Removes the file on drop unless `.disarm()` is called — covers every + // early-return path (a genuine network/write/archive error via `?`, not + // just the explicit abort checks below) so a failed download doesn't + // leave a partial file behind permanently. + struct CleanupOnDrop(Option); + impl CleanupOnDrop { + fn disarm(&mut self) { self.0 = None; } + } + impl Drop for CleanupOnDrop { + fn drop(&mut self) { + if let Some(p) = self.0.take() { + let _ = std::fs::remove_file(&p); + } + } + } + let mut tmp_guard = CleanupOnDrop(Some(tmp_path.clone())); + let mut response = client .get(&download_url) .send() @@ -193,7 +210,7 @@ async fn download_proton_ge_inner( { if abort.load(Ordering::Relaxed) { drop(file); - let _ = tokio::fs::remove_file(&tmp_path).await; + // tmp_guard cleans up tmp_path on drop. return Err("Aborted".into()); } file.write_all(&chunk) @@ -223,6 +240,9 @@ async fn download_proton_ge_inner( tokio::fs::rename(&tmp_path, &tar_path) .await .map_err(|e| format!("Failed to finalize download: {e}"))?; + // tmp_path no longer exists (renamed to tar_path) — tar_path's own + // cleanup is handled inside the extraction block below. + tmp_guard.disarm(); emit_download_line(&app_handle, "Download complete. Extracting archive..."); @@ -234,27 +254,42 @@ async fn download_proton_ge_inner( use flate2::read::GzDecoder; use tar::Archive; - let f = std::fs::File::open(&tar_path_clone) - .map_err(|e| format!("Failed to open archive: {e}"))?; - let gz = GzDecoder::new(f); - let mut archive = Archive::new(gz); + // Inner closure so every early-return `?` — not just the explicit + // abort check — funnels through the same cleanup below instead of + // leaving the downloaded archive (and any partially-extracted files) + // behind on a genuine extraction error. + let result: Result<(), String> = (|| { + let f = std::fs::File::open(&tar_path_clone) + .map_err(|e| format!("Failed to open archive: {e}"))?; + let gz = GzDecoder::new(f); + let mut archive = Archive::new(gz); + + // Iterate entries one-by-one so we can check the abort flag between + // files. unpack() has no cancellation hook. + for entry in archive.entries().map_err(|e| format!("Failed to read archive: {e}"))? { + if abort_extract.load(Ordering::Relaxed) { + return Err("Aborted".into()); + } + let mut entry = entry.map_err(|e| format!("Archive entry error: {e}"))?; + entry + .unpack_in(&target_clone) + .map_err(|e| format!("Failed to extract entry: {e}"))?; + } + Ok(()) + })(); - // Iterate entries one-by-one so we can check the abort flag between - // files. unpack() has no cancellation hook. - for entry in archive.entries().map_err(|e| format!("Failed to read archive: {e}"))? { - if abort_extract.load(Ordering::Relaxed) { + match &result { + Ok(()) => { + let _ = std::fs::remove_file(&tar_path_clone); + } + Err(_) => { + // Covers both "Aborted" and a genuine extraction error — + // either way the archive and any partial extraction are junk. let _ = std::fs::remove_file(&tar_path_clone); let _ = std::fs::remove_dir_all(target_clone.join(&tag_clone)); - return Err("Aborted".into()); } - let mut entry = entry.map_err(|e| format!("Archive entry error: {e}"))?; - entry - .unpack_in(&target_clone) - .map_err(|e| format!("Failed to extract entry: {e}"))?; } - - let _ = std::fs::remove_file(&tar_path_clone); - Ok::<(), String>(()) + result }) .await .map_err(|e| format!("Extraction task error: {e}"))??; @@ -308,7 +343,7 @@ pub async fn check_proton_ge_update(current_path: String) -> Result(); - let mut guard = pool.cmd_channels.lock().await; - let is_superseded = guard - .get(&server_id) - .map(|(_, id)| *id != conn_id) - .unwrap_or(false); + let is_superseded = { + let guard = pool.cmd_channels.lock().await; + guard + .get(&server_id) + .map(|(_, id)| *id != conn_id) + .unwrap_or(false) + }; if is_superseded { return; } - guard.remove(&server_id); + // Clears cmd_channels too (a no-op re-remove) plus log_buffer and + // player_cache — a connection that dies on its own (TCP error, server + // crash) previously only had cmd_channels cleared here, leaking the + // other two maps for the server's lifetime. + pool.remove_server(&server_id).await; } emit_log(&app, &server_id, RconLogLine { @@ -522,7 +528,9 @@ pub async fn rcon_disconnect( if let Some((tx, _)) = pool.cmd_channels.lock().await.remove(&server_id) { let _ = tx.send(RconCmd::Disconnect).await; } - pool.log_buffer.lock().await.remove(&server_id); + // cmd_channels is already gone (removed above); this clears log_buffer + // and player_cache too, so no RCON state lingers after a manual disconnect. + pool.remove_server(&server_id).await; Ok(()) } diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index 47cd841..6339ef9 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -2,9 +2,7 @@ use crate::state::{scheduler::SchedulerState, AppState}; use serde::Serialize; use std::time::{SystemTime, UNIX_EPOCH}; use tauri::{AppHandle, Emitter, Manager}; -use tokio::time::{sleep, Duration}; - -use super::server::{inner_start_server, inner_stop_server, StartServerParams}; +use tokio::time::Duration; // --------------------------------------------------------------------------- // Types @@ -21,8 +19,6 @@ pub struct SchedulerFiredPayload { pub schedule_type: String, pub success: bool, pub error: Option, - /// All backup records created by this firing (player backups produce one per player). - pub backup_records: Vec, } // --------------------------------------------------------------------------- @@ -35,21 +31,28 @@ pub struct SchedulerFiredPayload { /// and once on startup after the DB is ready. Rust fires entries purely based on /// `next_run_ms` — cron parsing lives entirely in the frontend (cron-parser). /// -/// Preserves `u64::MAX` for any entry that is currently in-flight (still running a -/// backup). The frontend may push a stale `next_run_ms` for such entries before it -/// has had a chance to update the DB; overwriting `u64::MAX` would cause an immediate -/// re-fire on the next tick. +/// Preserves `u64::MAX` for any entry that is currently in-flight. The frontend +/// may push a stale (already-past) `next_run_ms` for such entries before it has +/// had a chance to update the DB with the fire's real result — overwriting +/// `u64::MAX` with that stale value would cause an immediate re-fire on the +/// next tick. Only guard against *stale* incoming values though: the resync +/// that runs right after the fire actually completes carries a genuinely +/// future `next_run_ms`, and must be allowed through — otherwise the entry +/// would stay locked at `u64::MAX` forever (every later resync would see the +/// still-MAX stored value and re-lock its own fresh value too), so a schedule +/// would only ever fire once per app session. #[tauri::command] pub async fn sync_schedules( entries: Vec, state: tauri::State<'_, SchedulerState>, ) -> Result<(), String> { + let now = now_ms(); let mut store = state.entries.lock().unwrap(); let mut updated = entries; for entry in updated.iter_mut() { if let Some(existing) = store.iter().find(|e| e.schedule_id == entry.schedule_id) { - if existing.next_run_ms == u64::MAX { - // Entry is currently in-flight — don't overwrite the guard. + if existing.next_run_ms == u64::MAX && entry.next_run_ms <= now { + // Entry is in-flight and this push still looks stale — keep the guard. entry.next_run_ms = u64::MAX; } } @@ -124,59 +127,107 @@ async fn fire_wipe_dinos(app: &AppHandle, entry: &crate::state::scheduler::Sched } async fn fire_restart(app: &AppHandle, entry: &crate::state::scheduler::ScheduleEntry) -> Result<(), String> { - if !is_server_running(app, &entry.server_id) { + if !super::server::is_server_running(app, &entry.server_id) { return Ok(()); } + // Mid-boot (spawned but not yet RCON-confirmed) — see fire_update for why + // this skips the countdown/graceful handshake entirely. + let is_confirmed_running = { + let state = app.state::(); + let registry = state.running_servers.lock().unwrap(); + registry.get(&entry.server_id).map(|rs| rs.confirmed_running).unwrap_or(false) + }; - let cfg: serde_json::Value = serde_json::from_str(&entry.config_json).unwrap_or_default(); - let warn_minutes = if cfg["broadcastWarning"].as_bool().unwrap_or(false) { cfg["warningMinutes"].as_u64().unwrap_or(0) } else { 0 }; - let message = cfg["message"].as_str().unwrap_or("Server restarting in {time}.").to_string(); - let cancel_msg = cfg["cancelMessage"].as_str().unwrap_or("").to_string(); + // Refuse to restart a server whose hourly backup is currently in + // progress — killing the process mid-backup can produce a silently + // incomplete archive. The restart will fire again at its next scheduled + // occurrence. + let state = app.state::(); + let _lock = state.try_lock_server(&entry.server_id) + .ok_or_else(|| format!("A backup is currently in progress for {} — restart will retry next time", entry.server_id))?; - let (tx, mut rx) = tokio::sync::mpsc::channel::(1); - { - let state = app.state::(); - state.countdowns.lock().unwrap().insert(entry.server_id.clone(), tx); - } + if is_confirmed_running { + let cfg: serde_json::Value = serde_json::from_str(&entry.config_json).unwrap_or_default(); + let warn_minutes = if cfg["broadcastWarning"].as_bool().unwrap_or(false) { cfg["warningMinutes"].as_u64().unwrap_or(0) } else { 0 }; + let message = cfg["message"].as_str().unwrap_or("Server restarting in {time}.").to_string(); + let cancel_msg = cfg["cancelMessage"].as_str().unwrap_or("").to_string(); - let result = super::countdown::run_countdown( - app, - &entry.server_id, - warn_minutes * 60, - entry.rcon_port, - &entry.rcon_password, - &message, - &cancel_msg, - "restart", - &mut rx, - ).await; - - { - let state = app.state::(); - state.countdowns.lock().unwrap().remove(&entry.server_id); - } + let (tx, mut rx) = tokio::sync::mpsc::channel::(1); + { + let state = app.state::(); + let mut cd = state.countdowns.lock().unwrap(); + // Refuse to start a second countdown for this server — otherwise a + // restart and an update schedule (or two restarts) becoming due in + // the same tick would silently overwrite each other's countdown + // handle and both run their own stop/start sequence concurrently. + if cd.contains_key(&entry.server_id) { + return Err(format!("A countdown is already in progress for {}", entry.server_id)); + } + cd.insert(entry.server_id.clone(), tx); + } - if matches!(result, super::countdown::CountdownResult::Cancel) { - return Ok(()); - } + let result = super::countdown::run_countdown( + app, + &entry.server_id, + warn_minutes * 60, + entry.rcon_port, + &entry.rcon_password, + &message, + &cancel_msg, + "restart", + &mut rx, + ).await; - transient_rcon_send(entry.rcon_port, &entry.rcon_password, "saveworld").await; - sleep(Duration::from_secs(3)).await; - transient_rcon_send(entry.rcon_port, &entry.rcon_password, "doexit").await; + { + let state = app.state::(); + state.countdowns.lock().unwrap().remove(&entry.server_id); + } - for _ in 0..60 { - sleep(Duration::from_millis(500)).await; - if !is_server_running(app, &entry.server_id) { break; } + if matches!(result, super::countdown::CountdownResult::Cancel) { + return Ok(()); + } + + // Registered immediately before the kill (not earlier — cancelling + // above never touches the process, so registering any sooner would + // leak a handoff entry nothing will ever wait on or clear). + let notify = state.register_stop_handoff(&entry.server_id); + super::server::graceful_shutdown_via_rcon(app, &entry.server_id, entry.rcon_port, &entry.rcon_password).await; + // Wait for the watcher's own cleanup to finish before we emit our + // next status below, so its delayed "stopped" can't race in after. + state.wait_for_stop_handoff(&entry.server_id, notify).await; + } else { + // Nothing loaded to save, no players connected yet — go straight to a + // synchronous hard kill rather than waiting out an RCON handshake + // that isn't up yet. + let notify = state.register_stop_handoff(&entry.server_id); + let _ = super::server::inner_stop_server(app, &entry.server_id, false); + state.wait_for_stop_handoff(&entry.server_id, notify).await; } - let _ = inner_stop_server(app, &entry.server_id, false); - let params = entry_to_start_params(entry); - inner_start_server(app.clone(), params).await.map(|_| ()) + // Hand off to the frontend's staggered startup queue instead of starting + // directly, so a batch of same-time restart schedules doesn't cold-boot + // several servers at once — the "server://any-change" listener re-enqueues + // on this status. + use crate::commands::server::{emit_status, ServerStatus}; + emit_status(app, &ServerStatus { + server_id: entry.server_id.clone(), + status: "startup_queued".into(), + pid: None, + uptime_seconds: None, + error: None, + }); + Ok(()) } /// Run a global cache update check: update the shared SteamCMD cache, compare /// old vs new build IDs, and emit `asa://update-check` so the frontend can /// mark outdated servers and prompt the user. +/// +/// Shares `update_cache_inner`'s mutual-exclusion guard with the manual +/// "Check for Updates" flow (both key on `ASA_CACHE_CHECK_KEY`) so a +/// background tick can never run a second concurrent SteamCMD process +/// against the same cache dir if the user triggers a manual check at the +/// same moment — it just skips this tick silently and retries next time. async fn fire_global_update_check( app: &AppHandle, entry: &crate::state::scheduler::ScheduleEntry, @@ -187,27 +238,27 @@ async fn fire_global_update_check( let old_build = crate::commands::steamcmd::get_cache_build_id(&cache_dir) .unwrap_or_else(|| "0".to_string()); - tokio::fs::create_dir_all(&cache_dir) - .await - .map_err(|e| format!("Failed to create cache dir: {e}"))?; - - crate::commands::steamcmd::steamcmd_app_update( - app, - &entry.steamcmd_path, + let state = app.state::(); + let _ = app.emit(crate::events::ASA_UPDATE_CHECK_RUNNING, serde_json::json!({ "running": true })); + let result = crate::commands::steamcmd::update_cache_inner( + crate::commands::steamcmd::ASA_CACHE_CHECK_KEY, &cache_dir, - false, - "steamcmd://output/global-update-check", - None, + &entry.steamcmd_path, + &state, + app, ) - .await?; - - let new_build = crate::commands::steamcmd::get_cache_build_id(&cache_dir) - .unwrap_or_else(|| old_build.clone()); + .await; + let _ = app.emit(crate::events::ASA_UPDATE_CHECK_RUNNING, serde_json::json!({ "running": false })); - // Trigger internet version fetch for a newly-downloaded build - if new_build != "0" { - crate::commands::build_version::maybe_fetch_internet(app, &new_build); - } + let new_build = match result { + Ok(b) => b, + Err(e) if e.contains("already in progress") => { + // A manual check is running right now — skip this tick silently, + // the next scheduled tick will retry. + return Ok(()); + } + Err(e) => return Err(e), + }; let _ = app.emit( crate::events::ASA_UPDATE_CHECK, @@ -227,10 +278,34 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE let sep = if entry.base_dir.contains('\\') { '\\' } else { '/' }; let cache_dir = format!("{}{sep}lokiasam{sep}cache{sep}asa-server", entry.base_dir); - let is_running = is_server_running(app, &entry.server_id); + let is_running = super::server::is_server_running(app, &entry.server_id); + // Distinguish "fully up and joinable" from "spawned but still mid-boot" — + // the confirmed_running flag on the running_servers entry tells them apart. + let is_confirmed_running = { + let state = app.state::(); + let registry = state.running_servers.lock().unwrap(); + registry.get(&entry.server_id).map(|rs| rs.confirmed_running).unwrap_or(false) + }; + // A server that hadn't even been spawned yet, but was sitting in the + // startup queue, isn't caught by is_running at all — read the live DB + // status directly to catch that case too. + let was_queued_for_startup = app.state::().get_db_path() + .and_then(|p| crate::db::open(&p).ok()) + .and_then(|conn| crate::db::get_server_status(&conn, &entry.server_id)) + .as_deref() == Some("startup_queued"); + // Either of these means the server was on its way up (mid-boot or merely + // queued for its turn) when this update interrupted it — see the restart + // branch below for why that always finishes the launch regardless of + // only_if_running, and does so via the startup queue rather than directly. + let interrupted_startup = (is_running && !is_confirmed_running) || was_queued_for_startup; let warn_minutes = if cfg["broadcastWarning"].as_bool().unwrap_or(false) { cfg["warningMinutes"].as_u64().unwrap_or(0) } else { 0 }; let skip_if_players = cfg["skipIfPlayersOnline"].as_bool().unwrap_or(false); let restart_after = cfg["restartAfterUpdate"].as_bool().unwrap_or(true); + // When false, restart_after applies even if the server was stopped before + // the update (used by per-server Auto-Update automation's "Only restart if + // server was already running" toggle — unchecked means "always end up + // running after an update"). + let only_if_running = cfg["onlyIfRunning"].as_bool().unwrap_or(true); let message = cfg["message"].as_str().unwrap_or("Server going down for update in {time}.").to_string(); let cancel_msg = cfg["cancelMessage"].as_str().unwrap_or("").to_string(); @@ -245,11 +320,42 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE } } - if is_running { + // Refuse to update a server whose hourly backup is currently reading its + // files — overwriting them mid-backup can produce a silently incomplete + // archive. The per-server auto-update entry is regenerated on the next + // schedule sync as long as update_available stays set, so this retries + // shortly rather than being lost. + let state = app.state::(); + let _lock = state.try_lock_server(&entry.server_id) + .ok_or_else(|| format!("A backup is currently in progress for {} — update will retry shortly", entry.server_id))?; + + if is_running && !is_confirmed_running { + // Mid-boot: the process is spawned but RCON isn't up yet, so there's no + // world state to save and no players to warn — the countdown and the + // RCON SaveWorld/doexit handshake would just run out the clock (up to + // the full warn duration, then up to 30s of polling in + // graceful_shutdown_via_rcon) before falling back to a hard kill + // anyway. Skip straight to it. SIGKILL (not SIGTERM) specifically, + // since it's synchronous — sync_cache_to_server below must never race + // a process that might still be exiting. + let notify = state.register_stop_handoff(&entry.server_id); + let _ = super::server::inner_stop_server(app, &entry.server_id, false); + // Wait for the watcher's own cleanup to finish before proceeding — + // otherwise its delayed "stopped" can race in after our own status + // emissions below and silently overwrite them. + state.wait_for_stop_handoff(&entry.server_id, notify).await; + } else if is_confirmed_running { let (tx, mut rx) = tokio::sync::mpsc::channel::(1); { let state = app.state::(); - state.countdowns.lock().unwrap().insert(entry.server_id.clone(), tx); + let mut cd = state.countdowns.lock().unwrap(); + // See fire_restart — refuse to clobber a countdown already in + // progress for this server (e.g. a restart schedule racing this + // update schedule in the same tick). + if cd.contains_key(&entry.server_id) { + return Err(format!("A countdown is already in progress for {}", entry.server_id)); + } + cd.insert(entry.server_id.clone(), tx); } let result = super::countdown::run_countdown( @@ -273,15 +379,12 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE return Ok(()); } - transient_rcon_send(entry.rcon_port, &entry.rcon_password, "saveworld").await; - sleep(Duration::from_secs(3)).await; - transient_rcon_send(entry.rcon_port, &entry.rcon_password, "doexit").await; - - for _ in 0..60 { - sleep(Duration::from_millis(500)).await; - if !is_server_running(app, &entry.server_id) { break; } - } - let _ = inner_stop_server(app, &entry.server_id, false); + // Registered immediately before the kill (not earlier — cancelling + // above never touches the process, so registering any sooner would + // leak a handoff entry nothing will ever wait on or clear). + let notify = state.register_stop_handoff(&entry.server_id); + super::server::graceful_shutdown_via_rcon(app, &entry.server_id, entry.rcon_port, &entry.rcon_password).await; + state.wait_for_stop_handoff(&entry.server_id, notify).await; } // Emit "updating" so the server card shows the spinner. @@ -294,21 +397,31 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE error: None, }); - // Update shared cache via SteamCMD. + // Sync the shared cache to the server directory (preserving Saved/). The + // cache itself is NOT re-validated/re-downloaded here — it was already + // brought current by the global check that flagged this server as + // outdated in the first place (same as the manual/bulk apply path, which + // only ever calls apply_cache_to_server, never steamcmd_app_update). + // Re-running a full SteamCMD app_update per server was not just redundant + // but actively unsafe: when several servers' "When Found" automation + // fires in the same tick, each spawned its own SteamCMD process against + // this same shared cache directory concurrently, which SteamCMD does not + // handle safely (lock contention/hangs between instances) — this was the + // actual cause of updates appearing to stall the startup queue. let channel = format!("steamcmd://output/{}", entry.server_id); tokio::fs::create_dir_all(&cache_dir) .await .map_err(|e| format!("Failed to create cache dir: {e}"))?; - crate::commands::steamcmd::steamcmd_app_update( - app, &entry.steamcmd_path, &cache_dir, false, &channel, None, - ).await?; - // Sync updated files to the server directory (preserving Saved/). let cache_path = std::path::PathBuf::from(&cache_dir); let server_path = std::path::PathBuf::from(&entry.install_path); + let app_clone = app.clone(); + let channel_clone = channel.clone(); tokio::task::spawn_blocking(move || { - crate::commands::steamcmd::sync_cache_to_server(&cache_path, &server_path) + // Scheduled updates aren't individually cancellable — a never-set flag is correct here. + let no_abort = std::sync::atomic::AtomicBool::new(false); + crate::commands::steamcmd::sync_cache_to_server(&cache_path, &server_path, &app_clone, &channel_clone, &no_abort) }) .await .map_err(|e| format!("Sync task panicked: {e}"))? @@ -326,39 +439,53 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE "serverId": entry.server_id, })); - // Restart if requested and server was running. - if restart_after && is_running { - let params = entry_to_start_params(entry); - inner_start_server(app.clone(), params).await.map(|_| ())?; + // Clear the per-server update flag — otherwise the UI keeps showing + // "Update Available" and, for "immediately" mode, the next scheduler + // sync would generate this same auto-update entry all over again. + if let Some(db_path) = app.state::().get_db_path() { + if let Ok(conn) = crate::db::open(&db_path) { + crate::db::clear_update_available(&conn, &entry.server_id); + } } - Ok(()) -} - -fn entry_to_start_params(entry: &crate::state::scheduler::ScheduleEntry) -> StartServerParams { - StartServerParams { - server_id: entry.server_id.clone(), - server_name: entry.server_name.clone(), - install_path: entry.install_path.clone(), - map_path: entry.map_path.clone(), - port: entry.port, - query_port: entry.query_port, - rcon_port: entry.rcon_port, - rcon_password: entry.rcon_password.clone(), - extra_args: entry.extra_args.clone(), - mod_ids: entry.mod_ids.clone(), - proton_path: entry.proton_path.clone(), - prefix_path: entry.prefix_path.clone(), + // Restart if requested — either the server was already fully running, the + // schedule says to bring it up regardless (only_if_running = false), or it + // was on its way up (mid-boot or queued) when this update interrupted it. + // The last case always finishes the launch regardless of only_if_running — + // that toggle is about whether a server that was merely *stopped* should + // come back up, not about abandoning a launch already in motion. + // + // Always hands off to the frontend's staggered startup queue rather than + // starting directly — several servers restarting after the same update + // check shouldn't all cold-boot at once. The "server://any-change" + // listener re-enqueues on this status. + if restart_after && (is_confirmed_running || !only_if_running || interrupted_startup) { + use crate::commands::server::{emit_status, ServerStatus}; + emit_status(app, &ServerStatus { + server_id: entry.server_id.clone(), + status: "startup_queued".into(), + pid: None, + uptime_seconds: None, + error: None, + }); + } else { + // No restart is coming — the server was already stopped and the + // automation config says to leave it that way (or restart_after is + // off). Nothing else ever clears the "updating" status set above for + // this case, so without this the server sits stuck showing the + // in-progress spinner (Overview/dashboard) until the user manually + // Cancels and Reinstalls, even though the update itself succeeded. + use crate::commands::server::{emit_status, ServerStatus}; + emit_status(app, &ServerStatus { + server_id: entry.server_id.clone(), + status: "stopped".into(), + pid: None, + uptime_seconds: None, + error: None, + }); } -} -/// Returns true if a server is currently running (checked via AppState). -fn is_server_running(app: &AppHandle, server_id: &str) -> bool { - app.state::() - .running_servers - .lock() - .unwrap() - .contains_key(server_id) + Ok(()) } /// Called by the background scheduler loop in lib.rs. @@ -388,28 +515,28 @@ pub fn tick_scheduler(app: &AppHandle) { let server_id = entry.server_id.clone(); let server_name = entry.server_name.clone(); - let (success, error, backup_records) = match schedule_type.as_str() { + let (success, error) = match schedule_type.as_str() { "broadcast" => match fire_broadcast(&app, &entry).await { - Ok(_) => (true, None, vec![]), - Err(e) => (false, Some(e), vec![]), + Ok(_) => (true, None), + Err(e) => (false, Some(e)), }, "restart" => match fire_restart(&app, &entry).await { - Ok(_) => (true, None, vec![]), - Err(e) => (false, Some(e), vec![]), + Ok(_) => (true, None), + Err(e) => (false, Some(e)), }, "update" => match fire_update(&app, &entry).await { - Ok(_) => (true, None, vec![]), - Err(e) => (false, Some(e), vec![]), + Ok(_) => (true, None), + Err(e) => (false, Some(e)), }, "global_update_check" => match fire_global_update_check(&app, &entry).await { - Ok(_) => (true, None, vec![]), - Err(e) => (false, Some(e), vec![]), + Ok(_) => (true, None), + Err(e) => (false, Some(e)), }, "wipe_dinos" => match fire_wipe_dinos(&app, &entry).await { - Ok(_) => (true, None, vec![]), - Err(e) => (false, Some(e), vec![]), + Ok(_) => (true, None), + Err(e) => (false, Some(e)), }, - _ => (false, Some(format!("Unknown schedule type: {schedule_type}")), vec![]), + _ => (false, Some(format!("Unknown schedule type: {schedule_type}"))), }; let _ = app.emit( @@ -421,7 +548,6 @@ pub fn tick_scheduler(app: &AppHandle) { schedule_type, success, error, - backup_records, }, ); }); diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 8119f9b..092dc9b 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -184,6 +184,78 @@ fn pid_alive(pid: u32) -> bool { sys.process(spid).is_some() } +/// Returns true if a server is currently tracked as running in AppState. +pub fn is_server_running(app: &tauri::AppHandle, server_id: &str) -> bool { + app.state::() + .running_servers + .lock() + .unwrap() + .contains_key(server_id) +} + +/// The graceful-shutdown-via-RCON sequence shared by every restart/update +/// path (scheduled and manually-triggered via the countdown commands): +/// SaveWorld → wait 3s for the save to flush → doexit → poll for the process +/// to actually exit (up to 30s) → force-kill if it's still alive. Previously +/// reimplemented six times across server.rs/scheduler.rs/countdown.rs, with +/// two copies having drifted to a 2s wait instead of 3s. +pub async fn graceful_shutdown_via_rcon( + app: &tauri::AppHandle, + server_id: &str, + rcon_port: u16, + rcon_password: &str, +) { + use tokio::time::{sleep, Duration}; + + // Mark intentional before sending doexit, not after polling confirms the + // process is gone — the exit watcher can resolve within milliseconds of + // doexit, and it decides "stopped" vs "crashed" by checking this set. Every + // other stop path marks it before touching the process; this one used to + // mark it only at the very end (via inner_stop_server), so a fast exit + // would already be reported as a crash by the time we got there. + app.state::().stopping_servers.lock().unwrap().insert(server_id.to_string()); + + let _ = super::rcon::transient_rcon_command(rcon_port, rcon_password, "saveworld").await; + sleep(Duration::from_secs(3)).await; + let _ = super::rcon::transient_rcon_command(rcon_port, rcon_password, "doexit").await; + + for _ in 0..60 { + sleep(Duration::from_millis(500)).await; + if !is_server_running(app, server_id) { break; } + } + let _ = inner_stop_server(app, server_id, false); +} + +/// PID-based variant of `graceful_shutdown_via_rcon`, for the two call sites +/// (`graceful_stop_server`, `inner_restart_server`) that only clear the +/// `running_servers` registry entry themselves *after* this returns — for +/// them, polling the registry mid-wait would never observe the process as +/// gone, so this polls the OS process table directly instead. SaveWorld → +/// wait 3s → doexit → poll `pid_alive` (up to 30s) → force-kill via +/// `kill_process_tree` if still alive. +async fn graceful_shutdown_via_rcon_pid( + pid: u32, + install_path: &str, + rcon_port: u16, + rcon_password: &str, +) { + use super::rcon::transient_rcon_command; + use tokio::time::{sleep, Duration}; + + let _ = transient_rcon_command(rcon_port, rcon_password, "saveworld").await; + sleep(Duration::from_secs(3)).await; + let _ = transient_rcon_command(rcon_port, rcon_password, "doexit").await; + + for _ in 0..60 { + sleep(Duration::from_millis(500)).await; + if !pid_alive(pid) { break; } + } + if pid_alive(pid) { + kill_process_tree(pid, false, install_path); + sleep(Duration::from_millis(500)).await; + } +} + // --------------------------------------------------------------------------- // Commands // --------------------------------------------------------------------------- @@ -415,21 +487,30 @@ async fn inner_start_server_with_state( // ── Intentional stop ───────────────────────────────────────────────── if was_intentional { app_state.running_servers.lock().unwrap().remove(&sid); + handle_clone.state::().remove_server(&sid).await; LogManagerState::archive_all_server_logs(&handle_clone, &sid, &install_path_watcher).await; - crate::commands::notifications::dispatch_notification( - &handle_clone, "server_stopped", Some(&sid), &server_name_notif, - &format!("{} stopped", server_name_notif), "Server has shut down.", "info", - ).await; - emit_status(&handle_clone, &ServerStatus { - server_id: sid, status: "stopped".into(), - pid: None, uptime_seconds: None, error: None, - }); + + // If a restart/update flow is waiting on this stop, wake it now + // that cleanup above is actually done — it'll emit whatever + // comes next (startup_queued, updating, etc.) itself. Otherwise + // this is a plain stop: report "stopped" ourselves. + if !app_state.handoff_stop_to_restart_flow(&sid) { + crate::commands::notifications::dispatch_notification( + &handle_clone, "server_stopped", Some(&sid), &server_name_notif, + &format!("{} stopped", server_name_notif), "Server has shut down.", "info", + ).await; + emit_status(&handle_clone, &ServerStatus { + server_id: sid, status: "stopped".into(), + pid: None, uptime_seconds: None, error: None, + }); + } return; } // ── Runtime crash (was confirmed running) ──────────────────────────── if confirmed_clone.load(Ordering::Relaxed) { app_state.running_servers.lock().unwrap().remove(&sid); + handle_clone.state::().remove_server(&sid).await; LogManagerState::archive_all_server_logs(&handle_clone, &sid, &install_path_watcher).await; crate::commands::notifications::dispatch_notification( &handle_clone, "server_crashed", Some(&sid), &server_name_notif, @@ -796,16 +877,17 @@ pub async fn stop_server( } /// Restart a server: kill the current process (gracefully if requested), -/// wait up to 15 s for it to exit, then re-spawn with the same params. -/// -/// Returns the new process ID. +/// wait up to 15 s for it to exit, then hand off to the staggered startup +/// queue rather than re-spawning directly — so a batch of restarts (Restart +/// All, or several servers hitting their memory limit around the same time) +/// doesn't cold-boot all of them at once. #[tauri::command] pub async fn restart_server( app_handle: tauri::AppHandle, _state: tauri::State<'_, AppState>, params: StartServerParams, graceful: bool, -) -> Result { +) -> Result<(), String> { inner_restart_server(app_handle, params, graceful).await } @@ -814,32 +896,36 @@ pub async fn inner_restart_server( app_handle: tauri::AppHandle, params: StartServerParams, graceful: bool, -) -> Result { +) -> Result<(), String> { + let state = app_handle.state::(); + let running_info = { - let state = app_handle.state::(); let registry = state.running_servers.lock().unwrap(); registry.get(¶ms.server_id).map(|rs| (rs.pid, rs.install_path.clone())) }; + // Fail fast rather than kill/restart a server whose files a scheduled + // backup is currently reading — held for the whole function so it also + // covers the memory-limit auto-restart path, which calls this directly, + // and guards against two concurrent restart triggers for the same + // server_id (manual + scheduled + memory-limit) stepping on each other. + let _lock = if running_info.is_some() { + Some(state.try_lock_server(¶ms.server_id) + .ok_or_else(|| format!("An operation is already in progress for {} — try again in a moment", params.server_id))?) + } else { + None + }; + if let Some((pid, install_path)) = running_info { - { - let state = app_handle.state::(); - state.stopping_servers.lock().unwrap().insert(params.server_id.clone()); - } + // Register before killing — the exit watcher can resolve almost + // immediately, so this must be visible before the process actually dies. + let notify = state.register_stop_handoff(¶ms.server_id); + state.stopping_servers.lock().unwrap().insert(params.server_id.clone()); if graceful { // Graceful path: ask the server to save and exit via RCON so it // flushes world data cleanly (same as the Stop button does). - use crate::commands::rcon::transient_rcon_command; - let _ = transient_rcon_command(params.rcon_port, ¶ms.rcon_password, "saveworld").await; - tokio::time::sleep(tokio::time::Duration::from_secs(2)).await; - let _ = transient_rcon_command(params.rcon_port, ¶ms.rcon_password, "doexit").await; - - // Wait up to 30 s for the server to exit cleanly. - for _ in 0..60 { - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - if !pid_alive(pid) { break; } - } + graceful_shutdown_via_rcon_pid(pid, &install_path, params.rcon_port, ¶ms.rcon_password).await; } else { kill_process_tree(pid, false, &install_path); tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; @@ -851,13 +937,31 @@ pub async fn inner_restart_server( tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; } - // Clean up state (the watcher task may have already done this, that's fine). - let state = app_handle.state::(); + // Wait for the watcher task to confirm its own cleanup (registry, + // RCON pool, log rotation) is actually done before we proceed — + // otherwise its delayed "stopped" report can race in after our + // "startup_queued" below and silently overwrite it. + state.wait_for_stop_handoff(¶ms.server_id, notify).await; + + // Fallback cleanup in case the watcher's handoff timed out. state.stopping_servers.lock().unwrap().remove(¶ms.server_id); state.running_servers.lock().unwrap().remove(¶ms.server_id); + // Drop any RCON state tied to the process we just killed — the new + // instance gets a fresh connection, and this avoids briefly showing + // a stale pre-restart player list. + app_handle.state::().remove_server(¶ms.server_id).await; } - inner_start_server(app_handle, params).await + // Hand off to the frontend's staggered startup queue instead of starting + // directly — the "server://any-change" listener re-enqueues on this status. + emit_status(&app_handle, &ServerStatus { + server_id: params.server_id.clone(), + status: "startup_queued".into(), + pid: None, + uptime_seconds: None, + error: None, + }); + Ok(()) } /// Return the current runtime status of a server. @@ -985,20 +1089,27 @@ pub async fn scan_running_servers( // frontend can display the archived last-session log immediately. LogManagerState::archive_all_server_logs(&handle, &sid, &install_path_watcher).await; - let status = if was_intentional { "stopped" } else { "crashed" }; - let payload = ServerStatus { - server_id: sid.clone(), - status: status.into(), - pid: None, - uptime_seconds: None, - error: None, - }; - - let _ = handle.emit( - &events::server_event(events::SERVER_STATUS, &sid), - payload.clone(), - ); - let _ = handle.emit(events::SERVER_ANY_CHANGE, payload); + // If a restart/update flow is waiting on this stop, + // wake it now that cleanup above is actually done — + // it'll emit whatever comes next itself. See the same + // handoff in inner_start_server's watcher task. + let handed_off = was_intentional && app_state.handoff_stop_to_restart_flow(&sid); + if !handed_off { + let status = if was_intentional { "stopped" } else { "crashed" }; + let payload = ServerStatus { + server_id: sid.clone(), + status: status.into(), + pid: None, + uptime_seconds: None, + error: None, + }; + + let _ = handle.emit( + &events::server_event(events::SERVER_STATUS, &sid), + payload.clone(), + ); + let _ = handle.emit(events::SERVER_ANY_CHANGE, payload); + } break; } } @@ -1067,40 +1178,170 @@ fn find_server_process(install_path: &str) -> Option { None } +/// Return the total on-disk size (in bytes) of an arbitrary directory tree. +/// Returns 0 if the path doesn't exist. +#[tauri::command] +pub async fn get_dir_size(path: String) -> u64 { + fn walk(p: &std::path::Path) -> u64 { + if !p.exists() { return 0; } + let mut total = 0u64; + if let Ok(rd) = std::fs::read_dir(p) { + for entry in rd.flatten() { + let ep = entry.path(); + if ep.is_dir() { total += walk(&ep); } + else if let Ok(m) = ep.metadata() { total += m.len(); } + } + } + total + } + walk(std::path::Path::new(&path)) +} + +/// Return the total on-disk size (in bytes) of a server's backup, log, and save data. +/// Values are 0 if the directories don't exist. +#[tauri::command] +pub async fn get_server_disk_usage( + app: tauri::AppHandle, + server_id: String, + backup_dir: String, + base_dir: String, +) -> Result { + fn dir_size(path: &std::path::Path) -> u64 { + if !path.exists() { return 0; } + // Follow symlinks for the top-level dir but not recursively, to handle + // the SavedArks symlink case where the real data is under base_dir/Saves/. + let mut total = 0u64; + if let Ok(walker) = std::fs::read_dir(path) { + for entry in walker.flatten() { + let p = entry.path(); + if p.is_dir() { + total += dir_size(&p); + } else if let Ok(meta) = p.metadata() { + total += meta.len(); + } + } + } + total + } + + let backup_bytes = if !backup_dir.is_empty() { + let p = std::path::PathBuf::from(&backup_dir).join(&server_id); + dir_size(&p) + } else { + 0 + }; + + let log_bytes = { + use crate::state::log_manager::LogManagerState; + let p = LogManagerState::server_logs_dir(&app, &server_id); + p.map(|d| dir_size(&d)).unwrap_or(0) + }; + + let save_bytes = if !base_dir.is_empty() { + let p = std::path::PathBuf::from(&base_dir).join("saves").join(&server_id).join("SavedArks"); + dir_size(&p) + } else { + 0 + }; + + Ok(serde_json::json!({ + "backupBytes": backup_bytes, + "logBytes": log_bytes, + "saveBytes": save_bytes, + })) +} + /// Delete a server from disk (optionally) and clean up in-memory state. /// /// Database record deletion is handled by the frontend via `db.deleteServerRecord()`. /// This command only removes the install directory when `delete_files` is true. #[tauri::command] pub async fn delete_server( + app: tauri::AppHandle, state: tauri::State<'_, AppState>, server_id: String, install_path: String, + backup_dir: String, + base_dir: String, delete_files: bool, + delete_backups: bool, + delete_logs: bool, + delete_saves: bool, ) -> Result<(), String> { + // Held for the whole delete so a scheduled backup/update can't be + // touching this server's files at the same moment we start removing them. + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + // If the server is running, force-stop it first. let pid = { let registry = state.running_servers.lock().unwrap(); registry.get(&server_id).map(|rs| rs.pid) }; if let Some(pid) = pid { + // Register before killing so the exit watcher hands its cleanup off + // to us — otherwise it can independently recreate the log directory + // (via its own archive step) moments after we delete it below. + let notify = state.register_stop_handoff(&server_id); state .stopping_servers .lock() .unwrap() .insert(server_id.clone()); kill_process_tree(pid, false, &install_path); - // Brief wait — we don't block long here. - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; + // Wait for the process to actually exit (up to 15 s) before touching + // its files — a fixed 500 ms wait isn't enough on a slow-to-release + // process (common on Windows under antivirus scanning), and would + // make remove_dir_all below fail with "file in use". + for _ in 0..30 { + tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; + if !pid_alive(pid) { break; } + } + if pid_alive(pid) { + kill_process_tree(pid, false, &install_path); + tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; + } + // Wait for the watcher's own cleanup (including log archiving) to + // actually finish before we proceed to delete files below. + state.wait_for_stop_handoff(&server_id, notify).await; state.running_servers.lock().unwrap().remove(&server_id); state.stopping_servers.lock().unwrap().remove(&server_id); } + // The server is being permanently removed — always drop its RCON state, + // regardless of which delete_* flags were set. + app.state::().remove_server(&server_id).await; if delete_files && !install_path.is_empty() { std::fs::remove_dir_all(&install_path) .map_err(|e| format!("Failed to delete server files at {install_path}: {e}"))?; } + if delete_backups && !backup_dir.is_empty() { + let p = std::path::PathBuf::from(&backup_dir).join(&server_id); + if p.exists() { + std::fs::remove_dir_all(&p) + .map_err(|e| format!("Failed to delete backup data: {e}"))?; + } + } + + if delete_logs { + use crate::state::log_manager::LogManagerState; + if let Some(p) = LogManagerState::server_logs_dir(&app, &server_id) { + if p.exists() { + std::fs::remove_dir_all(&p) + .map_err(|e| format!("Failed to delete log data: {e}"))?; + } + } + } + + if delete_saves && !base_dir.is_empty() { + let p = std::path::PathBuf::from(&base_dir).join("saves").join(&server_id); + if p.exists() { + std::fs::remove_dir_all(&p) + .map_err(|e| format!("Failed to delete save data: {e}"))?; + } + } + Ok(()) } @@ -1129,7 +1370,7 @@ pub async fn clone_server( } tokio::task::spawn_blocking(move || { - copy_dir_recursive(&src, &dst, &["Saved"]) + copy_dir_recursive(&src, &dst, &["Saved"], None) .map_err(|e| format!("Failed to clone server files: {e}")) }) .await @@ -1167,14 +1408,24 @@ pub async fn graceful_stop_server( let state = app_handle.state::(); let pool = app_handle.state::(); - let (pid, install_path) = { + // Held for the whole operation (including the player-warning countdown, + // which can run for several minutes) so a scheduled backup can't start + // mid-shutdown and produce a truncated archive. + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + + let (pid, install_path, server_name) = { let registry = state.running_servers.lock().unwrap(); registry .get(&server_id) - .map(|rs| (rs.pid, rs.install_path.clone())) + .map(|rs| (rs.pid, rs.install_path.clone(), rs.start_params.server_name.clone())) .ok_or_else(|| format!("Server {server_id} is not running"))? }; + // Register before killing — see inner_restart_server for why. Ensures the + // exit watcher hands its cleanup off to us instead of emitting its own + // "stopped" (and notification) concurrently with what we emit below. + let notify = state.register_stop_handoff(&server_id); state.stopping_servers.lock().unwrap().insert(server_id.clone()); emit_status(&app_handle, &ServerStatus { @@ -1234,33 +1485,25 @@ pub async fn graceful_stop_server( } } - // SaveWorld then DoExit - let _ = transient_rcon_command(rcon_port, &rcon_password, "saveworld").await; - sleep(tokio::time::Duration::from_secs(2)).await; - let _ = transient_rcon_command(rcon_port, &rcon_password, "doexit").await; + // SaveWorld → wait → DoExit → poll for exit → force-kill if still alive. + graceful_shutdown_via_rcon_pid(pid, &install_path, rcon_port, &rcon_password).await; - // Wait up to 30 s for process to exit - for _ in 0..60 { - sleep(tokio::time::Duration::from_millis(500)).await; - if !pid_alive(pid) { break; } - } - if pid_alive(pid) { - kill_process_tree(pid, false, &install_path); - sleep(tokio::time::Duration::from_millis(500)).await; - } + // Wait for the exit watcher's own cleanup (registry, RCON pool, log + // archiving) to actually finish before we report "stopped" — otherwise + // its delayed completion could race in after we've already moved on. + state.wait_for_stop_handoff(&server_id, notify).await; - // Clean up state + // Fallback cleanup in case the watcher's handoff timed out (30s) — + // log archiving isn't repeated here since the watcher always does that + // unconditionally as part of its own cleanup, handoff or not. state.stopping_servers.lock().unwrap().remove(&server_id); state.running_servers.lock().unwrap().remove(&server_id); - pool.cmd_channels.lock().await.remove(&server_id); - pool.log_buffer.lock().await.remove(&server_id); - pool.player_cache.lock().await.remove(&server_id); - - // Rotate logs now that the process is confirmed dead. Covers servers that - // were found running at startup (watched by the scan watcher which exits - // cleanly when running_servers is cleared above, bypassing its rotation). - LogManagerState::archive_all_server_logs(&app_handle, &server_id, &install_path).await; + pool.remove_server(&server_id).await; + crate::commands::notifications::dispatch_notification( + &app_handle, "server_stopped", Some(&server_id), &server_name, + &format!("{server_name} stopped"), "Server has shut down.", "info", + ).await; emit_status(&app_handle, &ServerStatus { server_id, status: "stopped".into(), diff --git a/src-tauri/src/commands/steamcmd.rs b/src-tauri/src/commands/steamcmd.rs index a39683c..6ee9240 100644 --- a/src-tauri/src/commands/steamcmd.rs +++ b/src-tauri/src/commands/steamcmd.rs @@ -168,12 +168,14 @@ pub async fn steamcmd_app_update( let mut child2 = build_steamcmd_cmd(steamcmd_path, &base_args) .spawn() .map_err(|e| format!("Failed to re-launch SteamCMD: {e}"))?; + // Don't pre-check the abort flag and bail before calling + // stream_process_abortable — that would skip its kill logic and leave + // this freshly-spawned process orphaned. stream_process_abortable checks + // the flag immediately on entry and kills the process tree if it's + // already set, so it's always safe to hand off to directly. let exit_code2 = match &abort { - Some(flag) => { - if flag.load(Ordering::Relaxed) { return Err("Aborted".into()); } - stream_process_abortable(app, &mut child2, channel, std::sync::Arc::clone(flag)).await? - } - None => stream_process(app, &mut child2, channel).await?, + Some(flag) => stream_process_abortable(app, &mut child2, channel, std::sync::Arc::clone(flag)).await?, + None => stream_process(app, &mut child2, channel).await?, }; if exit_code2 == 0 { Ok(()) @@ -184,20 +186,34 @@ pub async fn steamcmd_app_update( /// Copy from `cache` to `server`, skipping subdirectories that contain user /// data (ShooterGame/Saved). Directory names are compared case-insensitively. -pub fn sync_cache_to_server(cache: &Path, server: &Path) -> std::io::Result<()> { +/// Emits a progress line per top-level entry and checks `abort` between them +/// so a caller can cancel and so the operation isn't silently invisible for +/// the many minutes a full ShooterGame/ copy can take. +pub fn sync_cache_to_server( + cache: &Path, + server: &Path, + app: &tauri::AppHandle, + channel: &str, + abort: &std::sync::atomic::AtomicBool, +) -> std::io::Result<()> { std::fs::create_dir_all(server)?; for entry in std::fs::read_dir(cache)? { + if abort.load(Ordering::Relaxed) { + return Err(std::io::Error::new(std::io::ErrorKind::Interrupted, "Aborted")); + } let entry = entry?; let name = entry.file_name(); let name_lower = name.to_string_lossy().to_lowercase(); let src = entry.path(); let dst = server.join(&name); + let _ = emit_line(app, channel, "stdout", &format!("Syncing {}…", name.to_string_lossy())); + if src.is_dir() { if name_lower == "shootergame" { - sync_shootergame(&src, &dst)?; + sync_shootergame(&src, &dst, Some(abort))?; } else { - copy_dir_recursive(&src, &dst, &[])?; + copy_dir_recursive(&src, &dst, &[], Some(abort))?; } } else { std::fs::copy(&src, &dst)?; @@ -207,9 +223,15 @@ pub fn sync_cache_to_server(cache: &Path, server: &Path) -> std::io::Result<()> } /// Recurse into `ShooterGame/`, skipping `Saved/` so player data is preserved. -fn sync_shootergame(cache_sg: &Path, server_sg: &Path) -> std::io::Result<()> { +/// `ShooterGame/` is the overwhelming majority of a server's install size, so +/// checking `abort` here (not just once per top-level entry in the caller) +/// is what actually makes Cancel responsive during the dominant copy phase. +fn sync_shootergame(cache_sg: &Path, server_sg: &Path, abort: Option<&std::sync::atomic::AtomicBool>) -> std::io::Result<()> { std::fs::create_dir_all(server_sg)?; for entry in std::fs::read_dir(cache_sg)? { + if abort.is_some_and(|a| a.load(Ordering::Relaxed)) { + return Err(std::io::Error::new(std::io::ErrorKind::Interrupted, "Aborted")); + } let entry = entry?; let name = entry.file_name(); if name.to_string_lossy().to_lowercase() == "saved" { @@ -218,7 +240,7 @@ fn sync_shootergame(cache_sg: &Path, server_sg: &Path) -> std::io::Result<()> { let src = entry.path(); let dst = server_sg.join(&name); if src.is_dir() { - copy_dir_recursive(&src, &dst, &[])?; + copy_dir_recursive(&src, &dst, &[], abort)?; } else { std::fs::copy(&src, &dst)?; } @@ -247,7 +269,7 @@ pub async fn install_steamcmd( let result = install_steamcmd_inner(&app_handle, &channel, dir, &abort).await; - state.clear_abort("steamcmd_install"); + state.clear_abort("steamcmd_install", &abort); if result.is_err() { // Clean up on abort or error. @@ -326,10 +348,17 @@ async fn install_steamcmd_inner( emit_line(app_handle, channel, "stdout", &format!("Downloaded {} bytes. Extracting...", bytes.len()))?; if is_zip { - let cursor = std::io::Cursor::new(bytes); - let mut archive = zip::ZipArchive::new(cursor) - .map_err(|e| format!("Failed to open ZIP: {e}"))?; - archive.extract(dir).map_err(|e| format!("Failed to extract ZIP: {e}"))?; + // ZIP extraction is blocking (sync std I/O under the hood) — run it + // off the async executor like the tar.gz path below already does. + let dir_owned = dir.to_path_buf(); + tokio::task::spawn_blocking(move || { + let cursor = std::io::Cursor::new(bytes); + let mut archive = zip::ZipArchive::new(cursor) + .map_err(|e| format!("Failed to open ZIP: {e}"))?; + archive.extract(&dir_owned).map_err(|e| format!("Failed to extract ZIP: {e}")) + }) + .await + .map_err(|e| format!("ZIP extraction task panicked: {e}"))??; } else { let dir_owned = dir.to_path_buf(); let abort_extract = std::sync::Arc::clone(abort); @@ -396,7 +425,7 @@ pub async fn validate_steamcmd( ) -> Result { let abort = state.register_abort("steamcmd_install"); let result = validate_steamcmd_inner(&path, &app_handle, &abort).await; - state.clear_abort("steamcmd_install"); + state.clear_abort("steamcmd_install", &abort); result } @@ -464,6 +493,12 @@ pub async fn install_server( app_handle: tauri::AppHandle, state: tauri::State<'_, crate::state::AppState>, ) -> Result<(), String> { + // Guards against a duplicate install trigger for the same server_id + // (double-click, a wizard retry) racing itself, and against a backup + // reading this server's files concurrently with a later re-install. + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + let op_key = format!("server_{server_id}"); let abort = state.register_abort(&op_key); let channel = format!("{}/{}", events::STEAMCMD_OUTPUT, server_id); @@ -489,8 +524,9 @@ pub async fn install_server( let src = std::path::PathBuf::from(&cache_dir); let dst = std::path::PathBuf::from(&install_path); + let abort_copy = std::sync::Arc::clone(&abort); - tokio::task::spawn_blocking(move || copy_dir_recursive(&src, &dst, &[])) + tokio::task::spawn_blocking(move || copy_dir_recursive(&src, &dst, &[], Some(&abort_copy))) .await .map_err(|e| format!("Copy task panicked: {e}"))? .map_err(|e| format!("Failed to copy server files: {e}"))?; @@ -506,7 +542,7 @@ pub async fn install_server( Ok(()) }.await; - state.clear_abort(&op_key); + state.clear_abort(&op_key, &abort); result } @@ -521,6 +557,9 @@ pub async fn update_server( app_handle: tauri::AppHandle, state: tauri::State<'_, crate::state::AppState>, ) -> Result<(), String> { + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + let op_key = format!("server_{server_id}"); let abort = state.register_abort(&op_key); let channel = format!("{}/{}", events::STEAMCMD_OUTPUT, server_id); @@ -540,11 +579,16 @@ pub async fn update_server( let cache_path = std::path::PathBuf::from(&cache_dir); let server_path = std::path::PathBuf::from(&install_path); + let app_clone = app_handle.clone(); + let channel_clone = channel.clone(); + let abort_clone = std::sync::Arc::clone(&abort); - tokio::task::spawn_blocking(move || sync_cache_to_server(&cache_path, &server_path)) - .await - .map_err(|e| format!("Sync task panicked: {e}"))? - .map_err(|e| format!("Failed to sync server files: {e}"))?; + tokio::task::spawn_blocking(move || { + sync_cache_to_server(&cache_path, &server_path, &app_clone, &channel_clone, &abort_clone) + }) + .await + .map_err(|e| format!("Sync task panicked: {e}"))? + .map_err(|e| format!("Failed to sync server files: {e}"))?; emit_line(&app_handle, &channel, "stdout", "Server update complete.")?; @@ -557,7 +601,7 @@ pub async fn update_server( Ok(()) }.await; - state.clear_abort(&op_key); + state.clear_abort(&op_key, &abort); result } @@ -581,10 +625,17 @@ pub async fn validate_server_files( let cache_path = std::path::PathBuf::from(&cache_dir); let server_path = std::path::PathBuf::from(&install_path); - tokio::task::spawn_blocking(move || sync_cache_to_server(&cache_path, &server_path)) - .await - .map_err(|e| format!("Sync task panicked: {e}"))? - .map_err(|e| format!("Failed to sync after validate: {e}"))?; + let app_clone = app_handle.clone(); + let channel_clone = channel.clone(); + tokio::task::spawn_blocking(move || { + // No cancellation for this path today — there's no Cancel affordance + // wired up to the Verify Files button, so a never-set flag is correct. + let no_abort = std::sync::atomic::AtomicBool::new(false); + sync_cache_to_server(&cache_path, &server_path, &app_clone, &channel_clone, &no_abort) + }) + .await + .map_err(|e| format!("Sync task panicked: {e}"))? + .map_err(|e| format!("Failed to sync after validate: {e}"))?; emit_line(&app_handle, &channel, "stdout", "Server files validated and synced.")?; Ok(()) @@ -651,6 +702,11 @@ pub async fn get_installed_build_id(install_path: String) -> Result, app_handle: tauri::AppHandle, ) -> Result { + update_cache_inner(&server_id, &cache_dir, &steamcmd_path, &state, &app_handle).await +} + +/// Shared implementation behind `update_cache` — extracted so the scheduled +/// background check (`fire_global_update_check` in scheduler.rs) can reuse +/// the exact same mutual-exclusion guard instead of running its own +/// independent, un-coordinated SteamCMD invocation against the same cache dir. +pub async fn update_cache_inner( + server_id: &str, + cache_dir: &str, + steamcmd_path: &str, + state: &crate::state::AppState, + app_handle: &tauri::AppHandle, +) -> Result { + { + let flags = state.abort_flags.lock().unwrap(); + if flags.contains_key(server_id) { + return Err("An ASA update check is already in progress".into()); + } + } + let channel = format!("{}/{}", events::STEAMCMD_OUTPUT, server_id); + let abort = state.register_abort(server_id); - emit_line(&app_handle, &channel, "stdout", "Updating server cache from Steam…")?; - tokio::fs::create_dir_all(&cache_dir) - .await - .map_err(|e| format!("Failed to create cache directory: {e}"))?; + let result: Result = async { + emit_line(app_handle, &channel, "stdout", "Updating server cache from Steam…")?; + tokio::fs::create_dir_all(&cache_dir) + .await + .map_err(|e| format!("Failed to create cache directory: {e}"))?; - steamcmd_app_update(&app_handle, &steamcmd_path, &cache_dir, false, &channel, None).await?; + steamcmd_app_update( + app_handle, + steamcmd_path, + cache_dir, + false, + &channel, + Some(std::sync::Arc::clone(&abort)), + ) + .await?; - let acf_path = Path::new(&cache_dir).join(ACF_REL_PATH); - let build_id = read_acf_build_id(&acf_path).unwrap_or_else(|| "0".to_string()); + let acf_path = Path::new(cache_dir).join(ACF_REL_PATH); + let build_id = read_acf_build_id(&acf_path).unwrap_or_else(|| "0".to_string()); - emit_line(&app_handle, &channel, "stdout", &format!("Cache updated to build {build_id}."))?; + emit_line(app_handle, &channel, "stdout", &format!("Cache updated to build {build_id}."))?; - // Trigger internet version fetch for this build in the background - if build_id != "0" { - crate::commands::build_version::maybe_fetch_internet(&app_handle, &build_id); + if build_id != "0" { + crate::commands::build_version::maybe_fetch_internet(app_handle, &build_id); + } + + Ok(build_id) } + .await; - Ok(build_id) + state.clear_abort(server_id, &abort); + result } /// Copy the shared cache to a specific server directory without re-running SteamCMD. /// Preserves ShooterGame/Saved so player data is never overwritten. /// Streams output to `steamcmd://output/{server_id}`. +/// Abort key: "server_{server_id}" — matches `install_server`/`update_server` so +/// `get_running_ops` and `abort_operation` behave consistently across all three. #[tauri::command] pub async fn apply_cache_to_server( server_id: String, install_path: String, cache_dir: String, app_handle: tauri::AppHandle, + state: tauri::State<'_, crate::state::AppState>, ) -> Result<(), String> { + // The key fix for the race between this (manual "Update All"/Settings + // apply-all/single-server update) and a server's own scheduled "at time" + // Auto-Update landing on the same server around the same moment — both + // used to sync the cache into the same install directory concurrently + // with no coordination at all. + let _lock = state.try_lock_server(&server_id) + .ok_or_else(|| format!("An operation is already in progress for {server_id} — try again in a moment"))?; + + let op_key = format!("server_{server_id}"); + let abort = state.register_abort(&op_key); let channel = format!("{}/{}", events::STEAMCMD_OUTPUT, server_id); - emit_line(&app_handle, &channel, "stdout", - "Syncing updated files to server (preserving Saved/ data)…")?; + let result = async { + emit_line(&app_handle, &channel, "stdout", + "Syncing updated files to server (preserving Saved/ data)…")?; - let cache_path = std::path::PathBuf::from(&cache_dir); - let server_path = std::path::PathBuf::from(&install_path); + let cache_path = std::path::PathBuf::from(&cache_dir); + let server_path = std::path::PathBuf::from(&install_path); + let app_clone = app_handle.clone(); + let channel_clone = channel.clone(); + let abort_clone = std::sync::Arc::clone(&abort); - tokio::task::spawn_blocking(move || sync_cache_to_server(&cache_path, &server_path)) + tokio::task::spawn_blocking(move || { + sync_cache_to_server(&cache_path, &server_path, &app_clone, &channel_clone, &abort_clone) + }) .await .map_err(|e| format!("Sync task panicked: {e}"))? .map_err(|e| format!("Failed to sync server files: {e}"))?; - // Record updated build ID for version tracking - let acf = std::path::Path::new(&install_path).join(ACF_REL_PATH); - if let Some(build_id) = read_acf_build_id(&acf) { - crate::commands::build_version::record_install(&app_handle, &server_id, &build_id); + // Record updated build ID for version tracking + let acf = std::path::Path::new(&install_path).join(ACF_REL_PATH); + if let Some(build_id) = read_acf_build_id(&acf) { + crate::commands::build_version::record_install(&app_handle, &server_id, &build_id); + } + + emit_line(&app_handle, &channel, "stdout", "Server update applied.")?; + Ok(()) } + .await; - emit_line(&app_handle, &channel, "stdout", "Server update applied.")?; - Ok(()) + state.clear_abort(&op_key, &abort); + result } /// Inspect an existing installation folder: checks for the server executable and diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs index 7058029..e64ffd9 100644 --- a/src-tauri/src/commands/system.rs +++ b/src-tauri/src/commands/system.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; use std::path::Path; use tauri::{Emitter, Manager}; -use super::utils::collect_subtree; +use super::utils::{collect_subtree, read_cstring}; // --------------------------------------------------------------------------- // Bootstrap @@ -139,7 +139,16 @@ pub struct DirCheckResult { /// the wizard (via write_bootstrap / the actual install commands). #[tauri::command] pub async fn check_dir(path: String) -> Result { - let p = Path::new(&path); + // Entirely synchronous filesystem/sysinfo work — run it off the async + // executor so it can't block other in-flight commands (RCON polling, + // log tailing) on the same worker thread pool. + tokio::task::spawn_blocking(move || check_dir_blocking(&path)) + .await + .map_err(|e| format!("check_dir task panicked: {e}"))? +} + +fn check_dir_blocking(path: &str) -> Result { + let p = Path::new(path); // Whether the target path itself exists (vs. needing to be created). let is_new = !p.exists(); @@ -263,117 +272,171 @@ pub async fn wipe_lokiasam_dir(path: String, full_wipe: bool) -> Result<(), Stri Ok(()) } -/// Return CPU % and RSS memory (MB) for a server process and ALL its descendants. -/// -/// On Linux the tracked PID is the Proton launcher. When Steam is installed, -/// Proton uses `steam-runtime-launcher-interface-0` to run Wine inside the Steam -/// Runtime container daemon; Wine processes are children of that *daemon service* -/// rather than of the Proton PID, so a pure subtree walk returns only ~60 MB -/// (the Python script itself). We supplement the BFS with a cmdline scan using -/// `install_path`, which is unique per server instance and present in every Wine -/// process's argv. +// --------------------------------------------------------------------------- +// Centralized stats collection +// --------------------------------------------------------------------------- +// +// The stats-recorder background task in lib.rs used to call a per-server +// get_process_stats command once per running server, every 5 s. Each call did +// its own full-system +// sysinfo refresh AND (on Linux) its own full /proc cmdline scan — meaning N +// running servers meant N independent full-system scans every tick, all doing +// synchronous/blocking file I/O directly on the async runtime's worker +// threads (no spawn_blocking). That's both wasted CPU that scales with total +// system process count and a real risk of starving every other command +// (including the Quit button) behind that blocking work. +// +// `collect_all_server_stats` replaces that with one refresh + one blocking +// pass covering every running server, using a `System` that persists across +// ticks (so CPU deltas come from the natural 5 s tick interval instead of an +// artificial extra sleep-and-refresh), and caching each server's expensive +// install-path PID discovery so it only re-scans /proc periodically instead +// of every single tick. + +/// Per-server cache of install-path-matched "extra root" PIDs. On Linux, when +/// Steam is installed, Proton uses `steam-runtime-launcher-interface-0` to run +/// Wine inside the Steam Runtime container daemon; Wine processes are children +/// of that daemon service rather than of the tracked Proton PID, so a pure +/// subtree walk misses them — this cmdline scan by `install_path` (unique per +/// server, present in every Wine process's argv) finds them instead. +/// Rediscovery via a full /proc cmdline scan is the expensive part, so it's only redone +/// every `REDISCOVERY_INTERVAL_TICKS` ticks; in between we just re-walk the +/// subtree of the previously-found roots against the freshly refreshed +/// snapshot, which touches no files and is effectively free. +#[derive(Default)] +pub struct PidDiscoveryCache { + extra_roots: Vec, + ticks_since_scan: u32, +} + +const REDISCOVERY_INTERVAL_TICKS: u32 = 6; // ~30 s at the stats recorder's 5 s cadence + +/// Compute CPU%/memory for every currently-running server in a single pass. /// -/// CPU usage requires two sysinfo samples separated by a short delay; -/// the 200 ms sleep inside this command is intentional and negligible. -#[tauri::command] -pub async fn get_process_stats(pid: u32, install_path: Option) -> Result { - use sysinfo::{Pid, ProcessesToUpdate, System}; +/// Synchronous and blocking (sysinfo refresh + procfs reads) — callers must +/// run this inside `tokio::task::spawn_blocking`. `sys` and `discovery` +/// should be owned by the caller and threaded through call to call so the +/// System and the discovery cache persist across ticks. +pub fn collect_all_server_stats( + sys: &mut sysinfo::System, + discovery: &mut std::collections::HashMap, + servers: &[(String, u32, String)], // (server_id, pid, install_path) +) -> std::collections::HashMap { + use sysinfo::{Pid, ProcessesToUpdate}; use std::collections::HashSet; - let root = Pid::from_u32(pid); - let mut sys = System::new(); + // remove_dead_processes = true: unlike get_process_stats (which builds a + // fresh System per call), this System is long-lived across ticks, so + // dead PIDs must actually be pruned or they'd accumulate forever. + sys.refresh_processes(ProcessesToUpdate::All, true); - // First sample — establishes the CPU time baseline for ALL processes. - // This must cover Wine processes too, so we always refresh everything. - sys.refresh_processes(ProcessesToUpdate::All, false); + let mut out = std::collections::HashMap::new(); - // Build the initial PID set from the subtree walk. - let mut all_pids: HashSet = collect_subtree(&sys, root).into_iter().collect(); - - // On Linux, supplement with processes found via install-path cmdline search. + // Servers usually all started around the same time, so their rediscovery + // windows tend to land on the same tick — resolve every due server's + // install-path PIDs in one shared /proc walk instead of one walk each, + // which would reproduce the very "N scans per cycle" burst this whole + // cache exists to avoid (just every 30s instead of every 5s). #[cfg(target_os = "linux")] - if let Some(ref path) = install_path { - use super::utils::collect_by_install_path; - for extra_root in collect_by_install_path(&sys, path) { - if all_pids.insert(extra_root) { - for sp in collect_subtree(&sys, extra_root) { - all_pids.insert(sp); + let rescanned_this_tick: HashSet = { + let due: Vec<&(String, u32, String)> = servers.iter() + .filter(|(server_id, _, install_path)| { + !install_path.is_empty() && { + let ticks = discovery.get(server_id).map(|c| c.ticks_since_scan).unwrap_or(0); + ticks == 0 || ticks >= REDISCOVERY_INTERVAL_TICKS } - } + }) + .collect(); + + if due.is_empty() { + HashSet::new() + } else { + let due_paths: Vec<&str> = due.iter().map(|(_, _, p)| p.as_str()).collect(); + let found = super::utils::find_pids_by_install_paths_batch(&due_paths); + due.iter().map(|(server_id, _, install_path)| { + let cache = discovery.entry(server_id.clone()).or_default(); + cache.extra_roots = found.get(install_path.as_str()) + .map(|pids| pids.iter().map(|p| Pid::from_u32(*p)).collect()) + .unwrap_or_default(); + cache.ticks_since_scan = 1; + server_id.clone() + }).collect() } - } + }; - tokio::time::sleep(std::time::Duration::from_millis(200)).await; + for (server_id, pid, install_path) in servers { + let root = Pid::from_u32(*pid); + let cache = discovery.entry(server_id.clone()).or_default(); - // Second sample — CPU deltas are now meaningful for every process seen above. - sys.refresh_processes(ProcessesToUpdate::All, false); + #[cfg(target_os = "linux")] + { + let _ = install_path; + if !rescanned_this_tick.contains(server_id) { + cache.ticks_since_scan += 1; + } + } + #[cfg(not(target_os = "linux"))] + { + let _ = install_path; + } - // On Linux, re-run the install-path search against the fresh snapshot so - // we catch any Wine processes that appeared between the two samples. - #[cfg(target_os = "linux")] - if let Some(ref path) = install_path { - use super::utils::collect_by_install_path; - for extra_root in collect_by_install_path(&sys, path) { - if all_pids.insert(extra_root) { - for sp in collect_subtree(&sys, extra_root) { + // Rebuild the full PID set from the (possibly cached) roots against the + // freshly refreshed snapshot — cheap, no additional syscalls. + let mut all_pids: HashSet = collect_subtree(sys, root).into_iter().collect(); + for extra_root in &cache.extra_roots { + if all_pids.insert(*extra_root) { + for sp in collect_subtree(sys, *extra_root) { all_pids.insert(sp); } } } - } - // On Linux, the Proton launcher (the tracked root PID) often exits before the - // game does — the Steam Runtime container re-parents Wine processes to PID 1. - // Only fail if there are genuinely no live processes in our collected set. - let root_alive = sys.process(root).is_some(); - if !root_alive { - let any_live = all_pids.iter().any(|p| sys.process(*p).is_some()); - if !any_live { - return Err(format!("Process {pid} not found or no longer running")); + let root_alive = sys.process(root).is_some(); + if !root_alive && !all_pids.iter().any(|p| sys.process(*p).is_some()) { + // Process genuinely gone this tick — skip it rather than failing + // the whole batch; the caller's own watchers handle crash/exit + // detection separately. + continue; } - } - let mut total_cpu = 0.0f32; - let mut total_mem_bytes = 0u64; + let mut total_cpu = 0.0f32; + let mut total_mem_bytes = 0u64; - for p in &all_pids { - // CPU still comes from sysinfo (needs the two-sample delta calculation). - if let Some(proc) = sys.process(*p) { - total_cpu += proc.cpu_usage(); + for p in &all_pids { + if let Some(proc) = sys.process(*p) { + total_cpu += proc.cpu_usage(); + } + #[cfg(target_os = "linux")] + if super::utils::is_process_leader(p.as_u32()) { + total_mem_bytes += super::utils::read_proc_pss_bytes(p.as_u32()); + } + #[cfg(not(target_os = "linux"))] + if let Some(proc) = sys.process(*p) { + total_mem_bytes += proc.memory(); + } } - // Memory via procfs PSS — only for process leaders (Tgid == Pid). - // Threads share the same virtual address space; counting each TID's - // smaps_rollup separately would multiply the true footprint by the - // thread count (e.g. 50 threads × 7 GB = 350 GB). - #[cfg(target_os = "linux")] - if super::utils::is_process_leader(p.as_u32()) { - total_mem_bytes += super::utils::read_proc_pss_bytes(p.as_u32()); - } - #[cfg(not(target_os = "linux"))] - if let Some(proc) = sys.process(*p) { - total_mem_bytes += proc.memory(); - } + #[cfg(not(target_os = "windows"))] + let cpu_percent = { + let cores = std::thread::available_parallelism() + .map(|n| n.get() as f32) + .unwrap_or(1.0); + total_cpu / cores + }; + #[cfg(target_os = "windows")] + let cpu_percent = total_cpu; + + out.insert( + server_id.clone(), + ProcessStats { + cpu_percent, + memory_mb: total_mem_bytes as f32 / 1_048_576.0, + pid: *pid, + }, + ); } - // On Linux, sysinfo reports cpu_usage() as % of ONE logical core, so a - // process fully occupying two of sixteen cores shows 200 %. Divide by the - // number of available cores to normalise to 0–100 % of total CPU capacity. - #[cfg(not(target_os = "windows"))] - let cpu_percent = { - let cores = std::thread::available_parallelism() - .map(|n| n.get() as f32) - .unwrap_or(1.0); - total_cpu / cores - }; - #[cfg(target_os = "windows")] - let cpu_percent = total_cpu; - - Ok(ProcessStats { - cpu_percent, - memory_mb: total_mem_bytes as f32 / 1_048_576.0, - pid, - }) + out } /// Send a Source Query UDP A2S_INFO packet to a game server and parse the response. @@ -642,37 +705,44 @@ pub async fn move_base_dir( return Err("Destination is inside the source directory.".into()); } - // Space check on the destination volume. + // Space check on the destination volume — the sysinfo Disks scan and + // directory read-dir below are blocking; run them off the async executor. { let check_against = new.parent().unwrap_or(&new).to_path_buf(); let _ = tokio::fs::create_dir_all(&check_against).await; - let free_bytes = { - use sysinfo::Disks; - let disks = Disks::new_with_refreshed_list(); - disks.iter() - .filter(|d| check_against.starts_with(d.mount_point())) - .max_by_key(|d| d.mount_point().components().count()) - .map(|d| d.available_space()) - .unwrap_or(0) - }; - // Estimate source size by sampling (du-equivalent). - let src_size_est: u64 = { - let mut total = 0u64; - if let Ok(rd) = std::fs::read_dir(&old) { - for entry in rd.flatten() { - if let Ok(meta) = entry.metadata() { - total += meta.len(); + let old_for_check = old.clone(); + tokio::task::spawn_blocking(move || -> Result<(), String> { + let free_bytes = { + use sysinfo::Disks; + let disks = Disks::new_with_refreshed_list(); + disks.iter() + .filter(|d| check_against.starts_with(d.mount_point())) + .max_by_key(|d| d.mount_point().components().count()) + .map(|d| d.available_space()) + .unwrap_or(0) + }; + // Estimate source size by sampling (du-equivalent). + let src_size_est: u64 = { + let mut total = 0u64; + if let Ok(rd) = std::fs::read_dir(&old_for_check) { + for entry in rd.flatten() { + if let Ok(meta) = entry.metadata() { + total += meta.len(); + } } } + total * 10 // rough multiplier for subdirs + }; + if free_bytes > 0 && free_bytes < src_size_est { + return Err(format!( + "Insufficient disk space at destination. Available: {:.1} GB", + free_bytes as f64 / 1_073_741_824.0 + )); } - total * 10 // rough multiplier for subdirs - }; - if free_bytes > 0 && free_bytes < src_size_est { - return Err(format!( - "Insufficient disk space at destination. Available: {:.1} GB", - free_bytes as f64 / 1_073_741_824.0 - )); - } + Ok(()) + }) + .await + .map_err(|e| format!("Space check task panicked: {e}"))??; } emit_migrate(&app, "checking", "Space check passed.", 5); @@ -828,21 +898,6 @@ fn parse_a2s_info(data: &[u8]) -> Result { }) } -/// Read a null-terminated UTF-8 string from `data` starting at `*cursor`, -/// advancing `*cursor` past the null byte. -fn read_cstring(data: &[u8], cursor: &mut usize) -> Result { - let start = *cursor; - while *cursor < data.len() && data[*cursor] != 0 { - *cursor += 1; - } - if *cursor >= data.len() { - return Err("Unterminated string in A2S_INFO response".into()); - } - let s = String::from_utf8_lossy(&data[start..*cursor]).into_owned(); - *cursor += 1; // consume the null byte - Ok(s) -} - // --------------------------------------------------------------------------- // AppImage desktop integration (Linux only) // @@ -873,6 +928,14 @@ pub fn get_install_method() -> &'static str { "binary" } +/// Returns the IDs of all currently active background operations. +/// An operation is active from `register_abort` until `clear_abort` is called. +#[tauri::command] +pub fn get_running_ops(state: tauri::State<'_, crate::state::AppState>) -> Vec { + state.abort_flags.lock().unwrap().keys().cloned().collect() +} + + #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AppImageIntegrationStatus { @@ -981,3 +1044,66 @@ pub fn uninstall_appimage_integration() -> Result<(), String> { Ok(()) } + +/// Remap all paths in the database from old_base_dir to new_base_dir during import. +/// Updates: app_settings (base_dir, backup_dir, steamcmd_path, proton_path, proton_prefix_path), +/// servers (install_path), and backups (file_path). +#[tauri::command] +pub async fn remap_import_paths( + db_path: String, + old_base_dir: String, + new_base_dir: String, +) -> Result<(), String> { + use rusqlite::Connection; + + // Normalize paths (remove trailing slashes) + let old_base = old_base_dir.trim_end_matches('/').trim_end_matches('\\'); + let new_base = new_base_dir.trim_end_matches('/').trim_end_matches('\\'); + + let conn = Connection::open(&db_path) + .map_err(|e| format!("Failed to open database '{}': {}", db_path, e))?; + + // Update app_settings paths + let settings_to_update = vec![ + "base_dir", + "backup_dir", + "steamcmd_path", + "proton_path", + "proton_prefix_path", + ]; + + for setting_key in settings_to_update { + let old_value: Option = conn.query_row( + "SELECT value FROM app_settings WHERE key = ?1", + [setting_key], + |row| row.get(0), + ).ok(); + + if let Some(val) = old_value { + if val.contains(old_base) { + let new_value = val.replace(old_base, new_base); + conn.execute( + "UPDATE app_settings SET value = ?1, updated_at = CURRENT_TIMESTAMP WHERE key = ?2", + rusqlite::params![new_value, setting_key], + ) + .map_err(|e| format!("Failed to update app_settings '{}': {}", setting_key, e))?; + } + } + } + + // Update servers.install_path using simple REPLACE + conn.execute( + "UPDATE servers SET install_path = REPLACE(install_path, ?1, ?2)", + rusqlite::params![old_base, new_base], + ) + .map_err(|e| format!("Failed to update server install_path: {}", e))?; + + // Update backups.file_path using simple REPLACE + conn.execute( + "UPDATE backups SET file_path = REPLACE(file_path, ?1, ?2)", + rusqlite::params![old_base, new_base], + ) + .map_err(|e| format!("Failed to update backup file_path: {}", e))?; + + Ok(()) +} diff --git a/src-tauri/src/commands/utils.rs b/src-tauri/src/commands/utils.rs index d213df5..ff82bf8 100644 --- a/src-tauri/src/commands/utils.rs +++ b/src-tauri/src/commands/utils.rs @@ -154,9 +154,23 @@ pub async fn stream_process_abortable( /// Recursively copy `src` into `dst`, skipping any top-level entry whose name /// case-insensitively matches a name in `skip_rel`. /// Creates `dst` if it doesn't exist; existing files in `dst` are overwritten. -pub fn copy_dir_recursive(src: &Path, dst: &Path, skip_rel: &[&str]) -> std::io::Result<()> { +/// `abort`, when given, is checked before copying each entry (files and +/// directories alike, not just once per top-level call) — the recursive +/// calls each check it too, so cancelling actually takes effect within a +/// single file/subdirectory of the largest copy (e.g. ShooterGame/) instead +/// of only between top-level entries. +pub fn copy_dir_recursive( + src: &Path, + dst: &Path, + skip_rel: &[&str], + abort: Option<&std::sync::atomic::AtomicBool>, +) -> std::io::Result<()> { std::fs::create_dir_all(dst)?; for entry in std::fs::read_dir(src)? { + if abort.is_some_and(|a| a.load(std::sync::atomic::Ordering::Relaxed)) { + return Err(std::io::Error::new(std::io::ErrorKind::Interrupted, "Aborted")); + } + let entry = entry?; let file_name = entry.file_name(); let name_str = file_name.to_string_lossy(); @@ -169,7 +183,7 @@ pub fn copy_dir_recursive(src: &Path, dst: &Path, skip_rel: &[&str]) -> std::io: let dst_path = dst.join(&file_name); if src_path.is_dir() { - copy_dir_recursive(&src_path, &dst_path, &[])?; + copy_dir_recursive(&src_path, &dst_path, &[], abort)?; } else { std::fs::copy(&src_path, &dst_path)?; } @@ -177,6 +191,100 @@ pub fn copy_dir_recursive(src: &Path, dst: &Path, skip_rel: &[&str]) -> std::io: Ok(()) } +// --------------------------------------------------------------------------- +// Backup helpers — shared between backup.rs (manual/on-demand backups) and +// backup_manager.rs (the hourly scheduled tick), which previously each had +// their own copy of both of these. +// --------------------------------------------------------------------------- + +/// Current UTC time as `YYYY-MM-DDTHH:MM:SS.sssZ` — the same shape +/// JavaScript's `Date.prototype.toISOString()` produces. Rows inserted from +/// Rust (e.g. `db::log_notification`) must use this rather than relying on +/// SQLite's `CURRENT_TIMESTAMP` default (`YYYY-MM-DD HH:MM:SS`, no `T`/`Z`, +/// second precision): the two formats are both valid-looking timestamps but +/// sort lexicographically out of true chronological order when interleaved +/// in the same `ORDER BY created_at DESC` — a space (0x20) sorts before `T` +/// (0x54), so every JS-inserted row for a given day would sort as "newer" +/// than every Rust-inserted row from that same day regardless of actual time. +pub fn now_iso_utc() -> String { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + let total_ms = now.as_millis(); + let secs = (total_ms / 1000) as u64; + let ms = total_ms % 1000; + + // Howard Hinnant's civil_from_days algorithm — same approach used + // elsewhere in this codebase for turning a day count into y/m/d. + let days = secs / 86_400; + let day_secs = secs % 86_400; + let (hh, mm, ss) = (day_secs / 3600, (day_secs % 3600) / 60, day_secs % 60); + + let z = days as i64 + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = (z - era * 146_097) as u64; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; + let y = yoe as i64 + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + + format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}.{ms:03}Z") +} + +/// Format a byte count as a human-readable "X.Y GB/MB/KB" string. +pub fn fmt_size(bytes: u64) -> String { + if bytes >= 1_073_741_824 { + format!("{:.1} GB", bytes as f64 / 1_073_741_824.0) + } else if bytes >= 1_048_576 { + format!("{:.1} MB", bytes as f64 / 1_048_576.0) + } else { + format!("{:.1} KB", bytes as f64 / 1_024.0) + } +} + +// --------------------------------------------------------------------------- +// A2S_INFO parsing primitive — shared by system.rs's query_server (full +// ServerQueryResult, 3s timeout, live UI display) and build_version.rs's +// source_query_version (just the version string, 5s timeout, up to 2 +// challenge-response rounds). Those two differ enough in return type, retry +// policy, and input slicing convention that only this lowest-level, most +// fragile piece — walking null-terminated strings out of the byte buffer — +// is shared; duplicating that specific logic was the actual maintenance risk. +// --------------------------------------------------------------------------- + +/// Read a null-terminated UTF-8 string from `data` starting at `*cursor`, +/// advancing `*cursor` past the null byte. +pub fn read_cstring(data: &[u8], cursor: &mut usize) -> Result { + let start = *cursor; + while *cursor < data.len() && data[*cursor] != 0 { + *cursor += 1; + } + if *cursor >= data.len() { + return Err("Unterminated string in A2S_INFO response".into()); + } + let s = String::from_utf8_lossy(&data[start..*cursor]).into_owned(); + *cursor += 1; // consume the null byte + Ok(s) +} + +/// Build a filename tier suffix like "-DH" from a tiers string like "D,H" or +/// "H", sorted into canonical priority order (M W D H). +pub fn tier_suffix(tiers: &str) -> String { + if tiers.is_empty() { + return String::new(); + } + const ORDER: [char; 4] = ['M', 'W', 'D', 'H']; + let flags: Vec = tiers + .split(',') + .filter_map(|t| t.trim().chars().next()) + .collect(); + let sorted: String = ORDER.iter().filter(|c| flags.contains(c)).collect(); + if sorted.is_empty() { String::new() } else { format!("-{sorted}") } +} + /// Async version of `copy_dir_recursive` — all I/O runs on the async executor. /// Runs in an infinite-depth recursion via `Box::pin`; suitable for smaller /// trees (mod directories). For very large trees (server installs) prefer @@ -296,23 +404,56 @@ pub fn find_pids_by_install_path(install_path: &str) -> Vec { if install_path.is_empty() { return Vec::new(); } - let base = install_path.trim_end_matches('/').to_lowercase(); - let needle_linux = format!("{}/", base); - let needle_wine = format!("z:{}\\" , base.replace('/', "\\")); + find_pids_by_install_paths_batch(&[install_path]) + .remove(install_path) + .unwrap_or_default() +} + +/// Batched form of `find_pids_by_install_path` — does a single `/proc` walk +/// and matches every process's cmdline against all `install_paths` at once, +/// instead of one full walk per path. Used by the stats-recorder's periodic +/// PID rediscovery: servers due for rescan tend to land on the same tick +/// (they usually all started around the same time), so calling the +/// single-path version once per due server was reproducing an N-scans burst +/// every rediscovery interval instead of the one shared pass the batching +/// elsewhere in this file was meant to achieve. +#[cfg(target_os = "linux")] +pub fn find_pids_by_install_paths_batch( + install_paths: &[&str], +) -> std::collections::HashMap> { + let mut out: std::collections::HashMap> = + install_paths.iter().map(|p| (p.to_string(), Vec::new())).collect(); + + let needles: Vec<(&str, String, String)> = install_paths.iter() + .filter(|p| !p.is_empty()) + .map(|p| { + let base = p.trim_end_matches('/').to_lowercase(); + let needle_linux = format!("{}/", base); + let needle_wine = format!("z:{}\\", base.replace('/', "\\")); + (*p, needle_linux, needle_wine) + }) + .collect(); + if needles.is_empty() { + return out; + } - let Ok(procs) = procfs::process::all_processes() else { return Vec::new(); }; - let mut out = Vec::new(); + let Ok(procs) = procfs::process::all_processes() else { return out; }; for proc_result in procs { let Ok(proc) = proc_result else { continue }; let Ok(cmd) = proc.cmdline() else { continue }; let flat = cmd.join("\0").to_lowercase(); - if !flat.contains(&needle_linux) && !flat.contains(&needle_wine) { continue; } + for (install_path, needle_linux, needle_wine) in &needles { + if !flat.contains(needle_linux) && !flat.contains(needle_wine) { continue; } - let Ok(status) = proc.status() else { continue }; - if status.pid == status.tgid { - out.push(proc.pid as u32); + let Ok(status) = proc.status() else { continue }; + if status.pid == status.tgid { + out.entry(install_path.to_string()).or_default().push(proc.pid as u32); + } + // A process's cmdline can only belong to one server's install + // path in practice — stop checking the rest once matched. + break; } } out @@ -356,12 +497,3 @@ pub fn signal_pid(pid: u32, graceful: bool) { unsafe { kill(pid as i32, sig); } } -/// Wrapper kept for callers in server.rs / system.rs that already pass `sys`. -/// Delegates to the procfs-based /proc reader — sysinfo is not used. -#[cfg(target_os = "linux")] -pub fn collect_by_install_path(_sys: &sysinfo::System, install_path: &str) -> Vec { - find_pids_by_install_path(install_path) - .into_iter() - .map(sysinfo::Pid::from_u32) - .collect() -} diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index 2cdfe1a..c983d63 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -78,14 +78,13 @@ pub struct ServerRow { pub name: String, pub map_id: String, pub install_path: String, - pub save_folder_name: Option, pub backup_broadcast_message: Option, pub memory_limit_gb: Option, } pub fn get_server(conn: &Connection, server_id: &str) -> Option { conn.query_row( - "SELECT id, name, map_id, install_path, save_folder_name, backup_broadcast_message, memory_limit_gb FROM servers WHERE id = ?1", + "SELECT id, name, map_id, install_path, backup_broadcast_message, memory_limit_gb FROM servers WHERE id = ?1", [server_id], |row| { Ok(ServerRow { @@ -93,9 +92,8 @@ pub fn get_server(conn: &Connection, server_id: &str) -> Option { name: row.get(1)?, map_id: row.get(2)?, install_path: row.get(3)?, - save_folder_name: row.get(4)?, - backup_broadcast_message: row.get(5)?, - memory_limit_gb: row.get(6)?, + backup_broadcast_message: row.get(4)?, + memory_limit_gb: row.get(5)?, }) }, ) @@ -104,7 +102,7 @@ pub fn get_server(conn: &Connection, server_id: &str) -> Option { pub fn get_servers(conn: &Connection) -> Vec { let mut stmt = match conn.prepare( - "SELECT id, name, map_id, install_path, save_folder_name, backup_broadcast_message, memory_limit_gb FROM servers", + "SELECT id, name, map_id, install_path, backup_broadcast_message, memory_limit_gb FROM servers", ) { Ok(s) => s, Err(e) => { @@ -118,15 +116,52 @@ pub fn get_servers(conn: &Connection) -> Vec { name: row.get(1)?, map_id: row.get(2)?, install_path: row.get(3)?, - save_folder_name: row.get(4)?, - backup_broadcast_message: row.get(5)?, - memory_limit_gb: row.get(6)?, + backup_broadcast_message: row.get(4)?, + memory_limit_gb: row.get(5)?, }) }) .map(|rows| rows.filter_map(|r| r.ok()).collect()) .unwrap_or_default() } +/// Look up the on-disk map path for a user-added custom mod map, stored in +/// the `custom_maps` table (see `ArkMap`/`useAllMaps` in game-data.ts — +/// `map_id` values for custom maps are `custom_`, where `` is the +/// `custom_maps.id` primary key). Returns `None` for a built-in map id or an +/// id that no longer exists (map was deleted). +pub fn get_custom_map_path(conn: &Connection, map_id: &str) -> Option { + let raw_id = map_id.strip_prefix("custom_")?; + conn.query_row( + "SELECT map_path FROM custom_maps WHERE id = ?1", + [raw_id], + |row| row.get::<_, String>(0), + ) + .ok() +} + +/// Read a server's current `status` column directly — used by the scheduler +/// to detect a server that was sitting in the startup queue (not yet spawned) +/// when its auto-update fired, which `running_servers` alone can't tell it, +/// since that map only ever holds servers that have actually been spawned. +pub fn get_server_status(conn: &Connection, server_id: &str) -> Option { + conn.query_row( + "SELECT status FROM servers WHERE id = ?1", + [server_id], + |row| row.get::<_, String>(0), + ) + .ok() +} + +/// Clear the update_available flag after a scheduled update has been applied, +/// so the UI stops showing "Update Available" and the auto-update scheduler +/// (which only fires while this flag is set) doesn't keep re-firing. +pub fn clear_update_available(conn: &Connection, server_id: &str) { + let _ = conn.execute( + "UPDATE servers SET update_available = 0, updated_at = CURRENT_TIMESTAMP WHERE id = ?1", + [server_id], + ); +} + // --------------------------------------------------------------------------- // schedules // --------------------------------------------------------------------------- @@ -396,12 +431,17 @@ pub struct NotifInsert<'a> { } pub fn log_notification(conn: &Connection, n: &NotifInsert) -> Result<(), String> { + // Explicit created_at (not SQLite's CURRENT_TIMESTAMP default) — must + // match the `YYYY-MM-DDTHH:MM:SS.sssZ` shape the frontend's own inserts + // use, or the two interleave out of chronological order under a plain + // text ORDER BY. See `commands::utils::now_iso_utc` for why. conn.execute( "INSERT INTO in_app_notifications \ - (id, server_id, event_type, title, body, severity, read) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + (id, server_id, event_type, title, body, severity, read, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", rusqlite::params![ n.id, n.server_id, n.event_type, n.title, n.body, n.severity, n.read, + crate::commands::utils::now_iso_utc(), ], ) .map_err(|e| format!("log_notification failed: {e}"))?; diff --git a/src-tauri/src/events/mod.rs b/src-tauri/src/events/mod.rs index ac4dd0d..f4a39b5 100644 --- a/src-tauri/src/events/mod.rs +++ b/src-tauri/src/events/mod.rs @@ -16,6 +16,11 @@ pub const LOG_BACKFILL: &str = "log://backfill"; pub const BACKUP_PROGRESS: &str = "backup://progress"; /// ASA update check result (or update-applied notification). pub const ASA_UPDATE_CHECK: &str = "asa://update-check"; +/// Fired when the scheduled background ASA cache check starts/stops, carrying +/// `{ running: bool }`. The manual "Check for Updates" flow sets the same +/// TopBar spinner state directly from the frontend, so this only needs to +/// cover the path the frontend can't otherwise observe. +pub const ASA_UPDATE_CHECK_RUNNING: &str = "asa://update-check/running"; /// Player login detected from ShooterGame.log — carries { eosId, ip }. /// Emitted on the per-server channel `player://login/{server_id}`. pub const PLAYER_LOGIN: &str = "player://login"; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 80fe524..39799aa 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -208,9 +208,8 @@ pub fn run() { // close button and hide to tray instead of exiting. // During setup or when close_to_tray=false, the X button exits normally. let handle_for_close = app.handle().clone(); - app.get_webview_window("main") - .unwrap() - .on_window_event(move |event| { + if let Some(main_window) = app.get_webview_window("main") { + main_window.on_window_event(move |event| { if let tauri::WindowEvent::CloseRequested { api, .. } = event { let app_state = handle_for_close.state::(); let setup_done = app_state @@ -225,6 +224,9 @@ pub fn run() { } } }); + } else { + eprintln!("Warning: main window not found at setup — close-to-tray handler not attached."); + } // ── Scheduler background task ────────────────────────────────── let scheduler_handle = app.handle().clone(); @@ -287,6 +289,12 @@ pub fn run() { let mem_restarting: std::sync::Arc>> = std::sync::Arc::new(std::sync::Mutex::new(HashSet::new())); + // Shared sysinfo System + per-server PID discovery cache, both + // persisted across ticks (not rebuilt per server, not rebuilt per + // tick) — see collect_all_server_stats' doc comment for why. + let mut sys = sysinfo::System::new(); + let mut discovery: HashMap = HashMap::new(); + let mut interval = tokio::time::interval(std::time::Duration::from_secs(5)); interval.set_missed_tick_behavior( @@ -346,42 +354,34 @@ pub fn run() { recorder.close_uptime_session(&sid, now_ms); } poll_counters.remove(id); + discovery.remove(id); } prev_active = active_now; - // Sample all active servers concurrently so the 200 ms - // CPU-delta sleeps inside get_process_stats overlap. + // One shared refresh + one blocking pass covers every running + // server, instead of each server independently refreshing the + // whole system and re-scanning /proc on its own worker thread. + let servers_for_blocking = servers.clone(); + let (sys_back, discovery_back, stats_map) = tokio::task::spawn_blocking(move || { + let stats_map = commands::system::collect_all_server_stats(&mut sys, &mut discovery, &servers_for_blocking); + (sys, discovery, stats_map) + }).await.unwrap_or_else(|_| (sysinfo::System::new(), HashMap::new(), HashMap::new())); + sys = sys_back; + discovery = discovery_back; + let rcon_pool = stats_handle.state::(); - let mut tasks = tokio::task::JoinSet::new(); - for (server_id, pid, install_path) in &servers { + for (server_id, _pid, _install_path) in &servers { let server_id = server_id.clone(); - let pid = *pid; - let install_path = install_path.clone(); - // Snapshot player count without holding the lock inside the task. - let player_count: Option = rcon_pool + let ps = stats_map.get(&server_id).cloned(); + let players: Option = rcon_pool .player_cache .lock() .await .get(&server_id) .map(|v| v.len() as i32); - tasks.spawn(async move { - let ps = - commands::system::get_process_stats( - pid, - Some(install_path), - ) - .await - .ok(); - (server_id, ps, player_count) - }); - } - - while let Some(Ok((server_id, ps, players))) = - tasks.join_next().await - { let cpu = ps.as_ref().map(|s| s.cpu_percent); let mem = ps.as_ref().map(|s| s.memory_mb); @@ -488,6 +488,8 @@ pub fn run() { commands::server::scan_running_servers, commands::server::clone_server, commands::server::delete_server, + commands::server::get_server_disk_usage, + commands::server::get_dir_size, commands::server::force_server_start_failed, // Certificates commands::certs::download_amazon_root_ca, @@ -547,7 +549,9 @@ pub fn run() { commands::backup::backup_all_players, commands::backup::create_ini_backup, commands::backup::create_save_link, + commands::backup::create_mods_saves_link, commands::backup::wipe_server_saves, + commands::backup::import_server_saves, commands::backup::create_full_backup, commands::backup::list_ini_backups, commands::backup::restore_server_backup, @@ -573,13 +577,13 @@ pub fn run() { commands::system::install_appimage_integration, commands::system::uninstall_appimage_integration, commands::system::get_install_method, + commands::system::get_running_ops, commands::system::check_dir, commands::system::check_file_exists, commands::system::wipe_lokiasam_dir, commands::system::delete_directory, commands::system::move_base_dir, commands::system::abort_operation, - commands::system::get_process_stats, commands::system::get_platform, commands::system::set_setup_complete, commands::system::set_close_to_tray, @@ -589,6 +593,7 @@ pub fn run() { commands::system::read_bootstrap, commands::system::write_bootstrap, commands::system::open_folder, + commands::system::remap_import_paths, // Proton-GE (Linux) commands::proton::scan_for_proton, commands::proton::validate_proton_path, diff --git a/src-tauri/src/state/log_manager.rs b/src-tauri/src/state/log_manager.rs index e066419..150935c 100644 --- a/src-tauri/src/state/log_manager.rs +++ b/src-tauri/src/state/log_manager.rs @@ -278,26 +278,50 @@ async fn tail_log_with_backfill( } }; - // ── Backfill: read all existing content from start ─────────────────────── + // ── Backfill: read only the tail of the file, not the whole thing ──────── + // Long-running servers can accumulate a ShooterGame.log hundreds of MB to + // GB in size. Reading the entire file into memory and shipping it as one + // giant IPC payload every time the Logs tab (re)connects was a real source + // of CPU/memory spikes — cap both the bytes read and the lines kept. + const BACKFILL_CAP_BYTES: u64 = 2 * 1024 * 1024; // 2 MB of recent content + const BACKFILL_CAP_LINES: usize = 5000; + let backfill_event = format!("{}/{server_id}", events::LOG_BACKFILL); - let mut backfill: Vec = Vec::new(); + let file_len = file.metadata().await.map(|m| m.len()).unwrap_or(0); + let start_offset = file_len.saturating_sub(BACKFILL_CAP_BYTES); + if start_offset > 0 { + let _ = file.seek(SeekFrom::Start(start_offset)).await; + } + + let mut backfill: std::collections::VecDeque = std::collections::VecDeque::new(); let mut buf = String::new(); let mut reader = BufReader::new(&mut file); + let mut first_line = start_offset > 0; // seeked mid-file — first read is likely a partial line loop { buf.clear(); match reader.read_line(&mut buf).await { Ok(0) => break, Ok(_) => { + if first_line { + // Discard: we seeked into the middle of the file, so this + // line is truncated at the start — not worth showing. + first_line = false; + continue; + } let trimmed = buf.trim_end_matches(['\n', '\r']).to_string(); if !trimmed.is_empty() { let level = classify_level(&trimmed).to_string(); - backfill.push(LogLine { line: trimmed, level }); + backfill.push_back(LogLine { line: trimmed, level }); + if backfill.len() > BACKFILL_CAP_LINES { + backfill.pop_front(); + } } } Err(_) => break, } } if !backfill.is_empty() { + let backfill: Vec = backfill.into(); let _ = app.emit(&backfill_event, &backfill); } diff --git a/src-tauri/src/state/mod.rs b/src-tauri/src/state/mod.rs index 97ee592..b3817af 100644 --- a/src-tauri/src/state/mod.rs +++ b/src-tauri/src/state/mod.rs @@ -60,8 +60,42 @@ pub struct AppState { /// Used by Rust-side business logic (backup manager, notification dispatch) to open /// their own rusqlite connections without blocking the Tauri plugin-sql connection. pub db_path: Mutex>, + /// Server IDs currently undergoing a backup, restart, or update — held for + /// the whole operation so the hourly backup tick and a scheduled + /// restart/update can never run concurrently against the same server + /// (a restart/update killing or overwriting files mid-backup can produce + /// a silently-incomplete archive). Acquire via `try_lock_server`. + pub busy_servers: Mutex>, + /// Server IDs whose current stop is being orchestrated by a restart/update + /// flow rather than a plain Stop. The process-exit watcher spawned back + /// when the server was originally started predates that flow and + /// independently notices the same exit — a time-based marker isn't enough + /// to avoid the race (the watcher's own cleanup, e.g. archiving logs, can + /// take longer than the restart flow's, so a marker cleared when the + /// restart flow finishes can already be gone by the time the watcher + /// checks it). Instead, the restart flow registers a `Notify` here before + /// killing the process; the watcher, once its *own* cleanup is done, + /// fires the notification instead of emitting "stopped" itself, and the + /// restart flow awaits it before emitting whatever comes next — a real + /// happens-before relationship instead of two tasks racing a shared flag. + pub restart_handoff: Mutex>>, } +/// RAII guard returned by `AppState::try_lock_server` — releases the lock +/// when dropped, on every exit path (return, `?`, panic unwind) of whichever +/// scope holds it. +pub struct ServerLockGuard<'a> { + state: &'a AppState, + server_id: String, +} + +impl Drop for ServerLockGuard<'_> { + fn drop(&mut self) { + self.state.busy_servers.lock().unwrap().remove(&self.server_id); + } +} + + impl AppState { pub fn new() -> Self { Self { @@ -77,6 +111,20 @@ impl AppState { abort_flags: Mutex::new(HashMap::new()), countdowns: Mutex::new(HashMap::new()), db_path: Mutex::new(None), + busy_servers: Mutex::new(HashSet::new()), + restart_handoff: Mutex::new(HashMap::new()), + } + } + + /// Attempt to mark a server as busy (backup/restart/update in progress). + /// Returns `None` if another operation already holds the lock; otherwise + /// a guard that releases it when dropped. + pub fn try_lock_server(&self, server_id: &str) -> Option> { + let inserted = self.busy_servers.lock().unwrap().insert(server_id.to_string()); + if inserted { + Some(ServerLockGuard { state: self, server_id: server_id.to_string() }) + } else { + None } } @@ -98,8 +146,61 @@ impl AppState { flag } - /// Clear the abort flag for `op_id` (called when the operation finishes or is aborted). - pub fn clear_abort(&self, op_id: &str) { - self.abort_flags.lock().unwrap().remove(op_id); + /// Clear the abort flag for `op_id` (called when the operation finishes or + /// is aborted). Only removes the entry if it's still the same `Arc` this + /// caller registered — if a second operation of the same kind (e.g. two + /// concurrent Proton-GE downloads, which share the static key + /// "proton_download") has since overwritten it, this leaves that second + /// operation's flag in place instead of deleting it out from under it. + /// Without this, the first operation to finish would silently disable the + /// second one's Cancel button and drop it from `get_running_ops`, even + /// though it's still running. + pub fn clear_abort(&self, op_id: &str, flag: &Arc) { + let mut flags = self.abort_flags.lock().unwrap(); + if flags.get(op_id).is_some_and(|current| Arc::ptr_eq(current, flag)) { + flags.remove(op_id); + } + } + + /// Register that `server_id`'s upcoming stop is being orchestrated by a + /// restart/update flow. Call this *before* killing the process. Returns + /// the `Notify` the caller should `.notified().await` (with a timeout — + /// see `wait_for_stop_handoff`) after triggering the kill, to block until + /// the process-exit watcher's own cleanup has actually finished. + pub fn register_stop_handoff(&self, server_id: &str) -> Arc { + let notify = Arc::new(tokio::sync::Notify::new()); + self.restart_handoff.lock().unwrap().insert(server_id.to_string(), Arc::clone(¬ify)); + notify + } + + /// Wait (up to 30s) for the process-exit watcher to confirm it has + /// finished handling this server's stop. Always returns — the timeout + /// is a safety net so a restart/update flow can't hang forever if the + /// watcher is unusually slow (e.g. archiving logs for several servers + /// concurrently during a bulk restart can easily exceed 30s under disk + /// contention). Deliberately does NOT remove the registration itself: + /// the watcher may still be working and must find it whenever it does + /// finish, however much later, so it hands off silently instead of + /// reporting a stale "stopped" after we've already moved on. Only the + /// watcher (via `handoff_stop_to_restart_flow`) ever removes the entry. + pub async fn wait_for_stop_handoff(&self, _server_id: &str, notify: Arc) { + let _ = tokio::time::timeout(std::time::Duration::from_secs(30), notify.notified()).await; + } + + /// Called by the process-exit watcher once its own cleanup (registry, + /// RCON pool, log rotation) is done. If a restart/update flow registered + /// this server (via `register_stop_handoff`), consumes that registration + /// and wakes it — instead of the watcher emitting its own "stopped" + /// status — returning true so the watcher knows to skip that emission. + /// This is the only place the registration is ever removed, so it stays + /// valid for however long this watcher takes to get here, even well past + /// the waiter's own 30s timeout. + pub fn handoff_stop_to_restart_flow(&self, server_id: &str) -> bool { + if let Some(notify) = self.restart_handoff.lock().unwrap().remove(server_id) { + notify.notify_one(); + true + } else { + false + } } } diff --git a/src-tauri/src/state/rcon_pool.rs b/src-tauri/src/state/rcon_pool.rs index d8a0744..5304f3c 100644 --- a/src-tauri/src/state/rcon_pool.rs +++ b/src-tauri/src/state/rcon_pool.rs @@ -154,6 +154,19 @@ impl RconPool { } deque.push_back(line); } + + /// Remove all in-memory RCON state for a server: its manager-task channel, + /// console log buffer, and cached player list. Call this on every path that + /// stops tracking a server (stop, restart, delete) — not just graceful + /// stop — so these maps don't grow unbounded over the app's lifetime as + /// servers are created and removed. Safe to call even if some/all entries + /// are already gone (e.g. a caller that already extracted `cmd_channels` + /// to signal a graceful disconnect before calling this). + pub async fn remove_server(&self, server_id: &str) { + self.cmd_channels.lock().await.remove(server_id); + self.log_buffer.lock().await.remove(server_id); + self.player_cache.lock().await.remove(server_id); + } } /// Returns the platform binary subdirectory within a server install path. diff --git a/src-tauri/src/state/server_registry.rs b/src-tauri/src/state/server_registry.rs deleted file mode 100644 index 0ca5476..0000000 --- a/src-tauri/src/state/server_registry.rs +++ /dev/null @@ -1,3 +0,0 @@ -/// Tracks running server process IDs keyed by server UUID. -/// Used to send signals, poll stats, and detect crashes. -pub struct ServerRegistry; diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ca194c5..5b7fc74 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": "LokiASAM", - "version": "0.14.1", + "version": "0.14.2", "identifier": "xyz.lokisoft.lokiasam", "build": { "frontendDist": "../out", diff --git a/src/app/backups/page.tsx b/src/app/backups/page.tsx index 2be893d..9dfbca5 100644 --- a/src/app/backups/page.tsx +++ b/src/app/backups/page.tsx @@ -1,124 +1,18 @@ "use client"; -import { useState, useEffect, useCallback } from "react"; -import { useSearchParams, useRouter } from "next/navigation"; -import { Archive, ChevronDown } from "lucide-react"; -import { useServers } from "@/hooks/useServers"; +import { Archive } from "lucide-react"; +import { ServerScopedTabPage } from "@/components/shared/ServerScopedTabPage"; import { BackupsTab } from "@/components/server/tabs/BackupsTab"; -import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; -import type { ServerRow } from "@/lib/db"; export default function BackupsPage() { - const searchParams = useSearchParams(); - const router = useRouter(); - const { data: servers = [], isLoading } = useServers(); - - const [selectedId, setSelectedId] = useState( - searchParams.get("server") ?? "" - ); - - useEffect(() => { - if (!selectedId && servers.length > 0) { - setSelectedId(servers[0].id); - } - }, [servers, selectedId]); - - const selectedServer: ServerRow | undefined = servers.find( - (s) => s.id === selectedId - ); - - const handleSelect = (id: string) => { - setSelectedId(id); - const url = new URL(window.location.href); - url.searchParams.set("server", id); - router.replace(url.pathname + url.search); - }; - return ( -
- {/* Page header */} -
- -

- Backups -

-
- - {/* Server selector */} -
- - Server: - - - {isLoading ? ( -
- ) : servers.length === 0 ? ( - - No servers configured - - ) : ( -
- - -
- )} - - {selectedServer && ( -
- - - Port {selectedServer.port} - -
- )} -
- - {/* Backup content */} - {selectedServer ? ( -
- -
- ) : !isLoading && servers.length === 0 ? ( -
- -

- No servers yet -

-

- Add a server from the Dashboard to start using backups. -

-
- ) : null} -
+ ); } diff --git a/src/app/clusters/detail/page.tsx b/src/app/clusters/detail/page.tsx index 02cb1c9..8e8f655 100644 --- a/src/app/clusters/detail/page.tsx +++ b/src/app/clusters/detail/page.tsx @@ -1,11 +1,11 @@ "use client"; -import { Suspense, useState, useCallback } from "react"; +import { Suspense, useState, useCallback, useEffect } from "react"; import { useSearchParams, useRouter } from "next/navigation"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { Network, Server, ArrowLeft, UserPlus, UserMinus, - Play, Square, Folder, Copy, ChevronDown, + Folder, Copy, } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; @@ -35,9 +35,10 @@ import { type ClusterRow, type ServerRow, } from "@/lib/db"; -import { ARK_MAPS } from "@/data/game-data"; +import { useAllMaps } from "@/hooks/useAllMaps"; import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; // --------------------------------------------------------------------------- // Add Server Dialog @@ -121,17 +122,21 @@ function AddServerDialog({ cluster, open, onClose, onAdded }: AddServerDialogPro )} - @@ -152,7 +157,8 @@ interface MemberRowProps { function MemberRow({ server, onRemove }: MemberRowProps) { const router = useRouter(); - const map = ARK_MAPS.find((m) => m.id === server.map_id); + const allMaps = useAllMaps(); + const map = allMaps.find((m) => m.id === server.map_id); const versionCache = useBuildVersionCache(); return ( @@ -233,9 +239,14 @@ function ClusterDetailContent() { queryClient.invalidateQueries({ queryKey: ["servers"] }); }, [queryClient, id]); - const baseDir = cluster?.cluster_dir_override - ? null - : null; // shown as note + const [baseDir, setBaseDir] = useState(""); + useEffect(() => { + getAppSetting("base_dir").then((v) => setBaseDir(v ?? "")); + }, []); + + const resolvedClusterDir = cluster + ? (cluster.cluster_dir_override?.trim() || `${baseDir}/clusters/${cluster.id}`) + : ""; async function handleRemove(server: ServerRow) { setRemoving(true); @@ -289,37 +300,48 @@ function ClusterDetailContent() { return (
{/* Header */} -
- -
-
+
+
-
-

+ +
+
- {cluster.name} -

-

- {members.length} member server{members.length !== 1 ? "s" : ""} -

+ +
+
+

+ {cluster.name} +

+

+ {members.length} server{members.length !== 1 ? "s" : ""} in cluster +

+
+
{/* Cluster Info Card */} @@ -327,73 +349,79 @@ function ClusterDetailContent() { className="glass-card p-5 rounded-xl flex flex-col gap-3" style={{ border: "1px solid var(--border)" }} > -

+

Cluster Settings

-

Cluster ID

+

Cluster ID

{cluster.id} - + + + + + Copy cluster ID +
-

Cluster Directory

-

- {cluster.cluster_dir_override ?? "Auto (base_dir/clusters/" + cluster.id.slice(0, 8) + "…)"} -

+

Cluster Directory

+
+

+ {resolvedClusterDir || "…"} +

+ + + + + Open cluster folder + +

This Cluster ID is passed as{" "} - -ClusterID={cluster.id} to each member server's + -ClusterID={cluster.id} to each member server's launch arguments so they can share player and tribe data.

- {/* Member Servers */} + {/* Servers in Cluster */}
-
-

- Member Servers -

- -
+

+ Servers in Cluster +

{loadingMembers ? (
@@ -415,15 +443,12 @@ function ClusterDetailContent() { No servers in this cluster yet.

@@ -470,20 +495,20 @@ function ClusterDetailContent() {

diff --git a/src/app/clusters/page.tsx b/src/app/clusters/page.tsx index 18293b6..f10df85 100644 --- a/src/app/clusters/page.tsx +++ b/src/app/clusters/page.tsx @@ -1,10 +1,10 @@ "use client"; -import { useState, useCallback } from "react"; +import { useState, useCallback, useEffect } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useRouter } from "next/navigation"; import { - Network, Plus, Trash2, ChevronRight, Server, Folder, + Network, Plus, Trash2, ChevronRight, Server, Folder, ToggleLeft, ToggleRight, } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; @@ -84,7 +84,7 @@ function NewClusterDialog({ open, onClose, onCreated }: NewClusterDialogProps) {
- + setName(e.target.value)} @@ -94,7 +94,7 @@ function NewClusterDialog({ open, onClose, onCreated }: NewClusterDialogProps) { />
-
- @@ -144,19 +142,55 @@ interface DeleteDialogProps { onDeleted: () => void; } +function formatBytes(bytes: number): string { + if (bytes === 0) return "empty"; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + function DeleteDialog({ cluster, onClose, onDeleted }: DeleteDialogProps) { - const [busy, setBusy] = useState(false); + const [busy, setBusy] = useState(false); + const [deleteFiles, setDeleteFiles] = useState(true); + const [clusterDir, setClusterDir] = useState(""); + const [dirBytes, setDirBytes] = useState(null); + + useEffect(() => { + // The parent mounts a fresh DeleteDialog (key={cluster.id}) per target, + // so deleteFiles/dirBytes already start at their useState initial values + // for each cluster — this effect only needs to resolve the async dir size. + if (!cluster) return; + + let cancelled = false; + getAppSetting("base_dir").then((baseDir) => { + if (cancelled) return; + const dir = cluster.cluster_dir_override?.trim() + ? cluster.cluster_dir_override + : `${(baseDir ?? "").replace(/[/\\]$/, "")}/clusters/${cluster.id}`; + setClusterDir(dir); + + return tauriCmd.getDirSize(dir) + .then((bytes) => { if (!cancelled) setDirBytes(bytes); }) + .catch(() => { if (!cancelled) setDirBytes(-1); }); + }).catch(() => {}); + + return () => { cancelled = true; }; + }, [cluster]); async function handleDelete() { if (!cluster) return; setBusy(true); try { - // Clear cluster_id on all member servers first const members = await getServersInCluster(cluster.id); + const baseDir = (await getAppSetting("base_dir")) ?? ""; + // Delete on the Rust side first — if this throws (permission error + // removing the folder, etc.), no member has been detached yet and a + // retry behaves identically to the first attempt, instead of leaving + // members silently detached from a cluster that still exists. + await tauriCmd.deleteCluster(clusterDir, baseDir, deleteFiles); for (const s of members) { await setServerCluster(s.id, null); } - await tauriCmd.deleteCluster(cluster.id); await deleteClusterRecord(cluster.id); toast.success(`Cluster "${cluster.name}" deleted.`); onDeleted(); @@ -182,26 +216,48 @@ function DeleteDialog({ cluster, onClose, onDeleted }: DeleteDialogProps) { Confirm cluster deletion. -

- Are you sure you want to delete{" "} - - {cluster?.name} - - ? All member servers will be detached from the cluster. Server files are - not affected. The cluster directory on disk will not be deleted. + +

+ All member servers will be detached. Server files are not affected.

- - +
+ + + @@ -225,7 +281,7 @@ function ClusterCard({ cluster, onDelete }: ClusterCardProps) { return (
router.push(`/clusters/detail?id=${cluster.id}`)} style={{ border: "1px solid var(--border)", @@ -262,7 +318,7 @@ function ClusterCard({ cluster, onDelete }: ClusterCardProps) { e.stopPropagation(); onDelete(cluster); }} - style={{ color: "var(--text-muted)" }} + style={{ color: "var(--neon-red)" }} > @@ -310,12 +366,16 @@ export default function ClustersPage() { const refresh = useCallback(() => { queryClient.invalidateQueries({ queryKey: ["clusters"] }); + // Deleting a cluster detaches every member server (setServerCluster -> + // null) — without this, the dashboard and cluster-aware menus keep + // showing those servers as still belonging to the deleted cluster. + queryClient.invalidateQueries({ queryKey: ["servers"] }); }, [queryClient]); return (
{/* Header */} -
+
@@ -331,14 +391,12 @@ export default function ClustersPage() {

@@ -352,30 +410,26 @@ export default function ClustersPage() { ))}
) : clusters.length === 0 ? ( -
- +
+
+ +
-

- No clusters yet -

-

+

No clusters yet

+

Create a cluster to enable cross-ARK travel between servers.

) : ( @@ -393,6 +447,7 @@ export default function ClustersPage() { onCreated={refresh} /> setDeleteTarget(null)} onDeleted={refresh} diff --git a/src/app/fonts/geist-latin-ext.woff2 b/src/app/fonts/geist-latin-ext.woff2 new file mode 100644 index 0000000..e366499 Binary files /dev/null and b/src/app/fonts/geist-latin-ext.woff2 differ diff --git a/src/app/fonts/geist-latin.woff2 b/src/app/fonts/geist-latin.woff2 new file mode 100644 index 0000000..445e0e5 Binary files /dev/null and b/src/app/fonts/geist-latin.woff2 differ diff --git a/src/app/fonts/geist-mono-latin-ext.woff2 b/src/app/fonts/geist-mono-latin-ext.woff2 new file mode 100644 index 0000000..944424f Binary files /dev/null and b/src/app/fonts/geist-mono-latin-ext.woff2 differ diff --git a/src/app/fonts/geist-mono-latin.woff2 b/src/app/fonts/geist-mono-latin.woff2 new file mode 100644 index 0000000..68eeb7f Binary files /dev/null and b/src/app/fonts/geist-mono-latin.woff2 differ diff --git a/src/app/globals.css b/src/app/globals.css index 93fd26f..29b52d0 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -40,7 +40,7 @@ --color-input: rgba(var(--neon-purple-rgb), 0.2); --color-ring: var(--neon-purple); --color-muted: rgba(20, 20, 52, 0.85); - --color-muted-foreground: #5858a0; + --color-muted-foreground: rgba(var(--neon-purple-rgb), 0.45); /* Fonts */ --font-sans: var(--font-geist-sans); @@ -76,8 +76,8 @@ --neon-orange: #ff8800; /* Text — defaults match storm preset */ - --foreground: #e0e0ff; - --text-primary: #e0e0ff; + --foreground: #dfe4f2; + --text-primary: #dfe4f2; --text-muted: #606880; --text-subtle: #464e64; @@ -93,12 +93,12 @@ --glass-blur: 12px; /* Popover / dropdown surface */ - --popover: #12161e; - --popover-foreground: #e0e0ff; + --popover: rgba(18, 20, 32, 0.97); + --popover-foreground: #dfe4f2; /* Accent — subtle highlight for menu item hover/focus */ --accent: rgba(64, 128, 255, 0.15); - --accent-foreground: #e0e0ff; + --accent-foreground: #dfe4f2; } /* --------------------------------------------------------------------------- diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 2f298f1..14c886a 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,17 +1,23 @@ import type { Metadata } from "next"; -import { Geist, Geist_Mono } from "next/font/google"; +import localFont from "next/font/local"; import "./globals.css"; import { AppShell } from "@/components/layout/AppShell"; -const geistSans = Geist({ +const geistSans = localFont({ + src: [ + { path: "./fonts/geist-latin.woff2", weight: "100 900" }, + { path: "./fonts/geist-latin-ext.woff2", weight: "100 900" }, + ], variable: "--font-geist-sans", - subsets: ["latin"], display: "swap", }); -const geistMono = Geist_Mono({ +const geistMono = localFont({ + src: [ + { path: "./fonts/geist-mono-latin.woff2", weight: "100 900" }, + { path: "./fonts/geist-mono-latin-ext.woff2", weight: "100 900" }, + ], variable: "--font-geist-mono", - subsets: ["latin"], display: "swap", }); diff --git a/src/app/logs/page.tsx b/src/app/logs/page.tsx index 4aea937..7d77121 100644 --- a/src/app/logs/page.tsx +++ b/src/app/logs/page.tsx @@ -1,124 +1,18 @@ "use client"; -import { useState, useEffect } from "react"; -import { useSearchParams, useRouter } from "next/navigation"; -import { ScrollText, ChevronDown } from "lucide-react"; -import { useServers } from "@/hooks/useServers"; +import { ScrollText } from "lucide-react"; +import { ServerScopedTabPage } from "@/components/shared/ServerScopedTabPage"; import { LogsTab } from "@/components/server/tabs/LogsTab"; -import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; -import type { ServerRow } from "@/lib/db"; export default function LogsPage() { - const searchParams = useSearchParams(); - const router = useRouter(); - const { data: servers = [], isLoading } = useServers(); - - const [selectedId, setSelectedId] = useState( - searchParams.get("server") ?? "" - ); - - useEffect(() => { - if (!selectedId && servers.length > 0) { - setSelectedId(servers[0].id); - } - }, [servers, selectedId]); - - const selectedServer: ServerRow | undefined = servers.find( - (s) => s.id === selectedId - ); - - const handleSelect = (id: string) => { - setSelectedId(id); - const url = new URL(window.location.href); - url.searchParams.set("server", id); - router.replace(url.pathname + url.search); - }; - return ( -
- {/* ── Page header ── */} -
- -

- Logs -

-
- - {/* ── Server selector ── */} -
- - Server: - - - {isLoading ? ( -
- ) : servers.length === 0 ? ( - - No servers configured - - ) : ( -
- - -
- )} - - {selectedServer && ( -
- - - Port {selectedServer.port} - -
- )} -
- - {/* ── Log viewer — fills remaining height ── */} - {selectedServer ? ( -
- -
- ) : !isLoading && servers.length === 0 ? ( -
- -

- No servers yet -

-

- Add a server from the Dashboard to start viewing logs. -

-
- ) : null} -
+ ); } diff --git a/src/app/mod-maps/page.tsx b/src/app/mod-maps/page.tsx new file mode 100644 index 0000000..cde9f97 --- /dev/null +++ b/src/app/mod-maps/page.tsx @@ -0,0 +1,332 @@ +"use client"; + +import React, { useState, useCallback } from "react"; +import { useOnMount } from "@/hooks/useOnMount"; +import { Map, Plus, Trash2, Loader2, Pencil } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, +} from "@/components/ui/dialog"; +import { toast } from "sonner"; +import { getCustomMaps, insertCustomMap, updateCustomMap, deleteCustomMap, type CustomMapRow } from "@/lib/db"; +import { setCustomMapsCache } from "@/lib/maps"; +import { ARK_MAPS } from "@/data/game-data"; + +const TH = ({ children }: { children: React.ReactNode }) => ( + + {children} + +); + +export default function ModMapsPage() { + const [customMaps, setCustomMaps] = useState([]); + const [loading, setLoading] = useState(true); + const [showAdd, setShowAdd] = useState(false); + const [editTarget, setEditTarget] = useState(null); + const [displayName, setDisplayName] = useState(""); + const [modId, setModId] = useState(""); + const [mapPath, setMapPath] = useState(""); + const [saving, setSaving] = useState(false); + + const load = useCallback(async () => { + setLoading(true); + try { + const rows = await getCustomMaps(); + setCustomMaps(rows); + setCustomMapsCache(rows); + } catch (e) { + toast.error(`Failed to load custom maps: ${e}`); + } finally { + setLoading(false); + } + }, []); + + useOnMount(load); + + const closeDialog = () => { + if (saving) return; + setShowAdd(false); + setEditTarget(null); + setDisplayName(""); setModId(""); setMapPath(""); + }; + + const openEdit = (map: CustomMapRow) => { + setEditTarget(map); + setDisplayName(map.display_name); + setModId(map.mod_id); + setMapPath(map.map_path); + }; + + const handleSave = async () => { + const name = displayName.trim(); + const id = modId.trim(); + const path = mapPath.trim(); + if (!name || !id || !path) { toast.error("All fields are required."); return; } + if (!/^\d+$/.test(id)) { toast.error("Mod ID must be numeric."); return; } + setSaving(true); + try { + if (editTarget) { + await updateCustomMap(editTarget.id, name, id, path); + toast.success(`"${name}" updated.`); + } else { + await insertCustomMap(crypto.randomUUID(), name, id, path); + toast.success(`Custom map "${name}" added.`); + } + closeDialog(); + await load(); + } catch (e) { + toast.error(`Failed to ${editTarget ? "update" : "add"} map: ${e}`); + } finally { + setSaving(false); + } + }; + + const [deleteTarget, setDeleteTarget] = useState(null); + + const handleDelete = async (map: CustomMapRow) => { + try { + await deleteCustomMap(map.id); + await load(); + toast.success(`"${map.display_name}" removed.`); + } catch (e) { + toast.error(`Failed to delete map: ${e}`); + } finally { + setDeleteTarget(null); + } + }; + + return ( +
+ {/* Header */} +
+
+
+ +

+ Mod Maps +

+
+

+ Add community mod maps so they appear in the server map dropdown. +

+
+ +
+ + {/* Add / Edit dialog */} + { if (!open) closeDialog(); }}> + + + + {editTarget ? "Edit Custom Map" : "New Custom Map"} + + +
+
+ + setDisplayName(e.target.value)} + placeholder="e.g. Fjordur Reborn" + disabled={saving} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + /> +
+
+ + setModId(e.target.value.replace(/\D/g, ""))} + placeholder="e.g. 965379" + inputMode="numeric" + disabled={saving} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + /> +
+
+ + setMapPath(e.target.value)} + placeholder="e.g. MyMap_WP" + disabled={saving} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + /> +

+ The exact map path string passed at server launch (e.g. TheIsland_WP). +

+
+
+ + + + +
+
+ + {/* Built-in mod maps reference */} + {ARK_MAPS.filter((m) => m.isMod && m.released).length > 0 && ( +
+

+ Built-in Mod Maps (read-only reference) +

+
+ + + + + + + + + + {ARK_MAPS.filter((m) => m.isMod && m.released).map((m, i, arr) => ( + + + + + + ))} + +
Display NameMap Launch ParameterCurseForge Mod ID +
{m.displayName}{m.mapPath}{m.requiredModId ?? "—"} +
+
+
+ )} + + {/* Custom maps */} +
+

+ Your Custom Maps +

+ {loading ? ( +
+ ) : customMaps.length === 0 ? ( +
+
+ +
+
+

No custom maps yet

+

+ Register a community mod map so it appears in the server map dropdown. +

+
+ +
+ ) : ( +
+ + + + + + + + + + {customMaps.map((m, i) => ( + + + + + + + ))} + +
Display NameMap Launch ParameterCurseForge Mod ID +
{m.display_name}{m.map_path}{m.mod_id} +
+ + +
+
+
+ )} +
+ + {/* ── Delete confirmation ── */} + !v && setDeleteTarget(null)}> + + + Remove Mod Map? + +

+ Remove "{deleteTarget?.display_name}" from the mod maps list? This does not uninstall the mod itself. +

+ + + + +
+
+
+ ); +} diff --git a/src/app/notifications/page.tsx b/src/app/notifications/page.tsx index 85f7032..140e2b5 100644 --- a/src/app/notifications/page.tsx +++ b/src/app/notifications/page.tsx @@ -186,8 +186,7 @@ function NotificationsContent() { }, 3000); return () => clearTimeout(timeout); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, [resetUnreadBump, queryClient, highlightId, router]); const filtered = notifications.filter((n) => { if (severityFilter !== "all" && n.severity !== severityFilter) return false; @@ -206,7 +205,11 @@ function NotificationsContent() { const handleDelete = useCallback(async (id: string) => { await deleteNotification(id); refetch(); - }, [refetch]); + // Deleting an unread notification must also refresh the bell badge — + // that reads a separate ["notifications", "unread", ...] query this + // page's own `refetch` (scoped to the list query) doesn't touch. + queryClient.invalidateQueries({ queryKey: ["notifications"] }); + }, [refetch, queryClient]); const handleBulkDelete = useCallback(async (days?: number) => { const daysLabel = days ? `older than ${days} day${days === 1 ? "" : "s"}` : "all"; @@ -216,13 +219,14 @@ function NotificationsContent() { eventType: eventTypeFilter !== "all" ? eventTypeFilter : undefined, }); refetch(); + queryClient.invalidateQueries({ queryKey: ["notifications"] }); toast.success(`Deleted ${daysLabel} notifications${severityFilter !== "all" || eventTypeFilter !== "all" ? " matching current filter" : ""}.`); - }, [refetch, severityFilter, eventTypeFilter]); + }, [refetch, severityFilter, eventTypeFilter, queryClient]); return (
{/* Header */} -
+
@@ -241,12 +245,11 @@ function NotificationsContent() { @@ -331,16 +334,18 @@ function NotificationsContent() { {/* List */}
{filtered.length === 0 ? ( -
- +
+
+ +
-

+

{notifications.length === 0 ? "No notifications yet" : "No matching notifications"} -

-

+

+

{notifications.length === 0 ? "Events like server starts, stops, crashes, and backups will appear here." : "Try adjusting your filters."} diff --git a/src/app/page.tsx b/src/app/page.tsx index fb86b08..2fb4354 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,9 +1,9 @@ "use client"; -import { useEffect, useState, useCallback, useRef } from "react"; +import { useEffect, useState, useCallback } from "react"; import { Plus, Server, Activity, RefreshCw, Upload, - ArrowUp, Loader2, CheckCircle2, AlertTriangle, LayoutDashboard, + ArrowUp, Loader2, AlertTriangle, LayoutDashboard, Play, Square, RotateCcw, } from "lucide-react"; import { Button } from "@/components/ui/button"; @@ -18,15 +18,14 @@ import { StatCard } from "@/components/shared/StatCard"; import { ServerCard } from "@/components/server/ServerCard"; import { ImportServerWizard } from "@/components/server/ImportServerWizard"; import { useServers } from "@/hooks/useServers"; -import { getAppSetting, setAppSetting, updateServerStatus } from "@/lib/db"; -import { tauriCmd, type UpdateCheckResult } from "@/lib/tauri-commands"; -import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToServer, type ServerUpdateInfo } from "@/lib/update-utils"; -import { buildStartParams } from "@/lib/server-utils"; +import { getAppSetting, updateServerStatus } from "@/lib/db"; +import { tauriCmd } from "@/lib/tauri-commands"; +import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToAllServers, isAutoUpdateImmediate, type ServerUpdateInfo } from "@/lib/update-utils"; +import { restartServerGracefully, stopServerGracefully } from "@/lib/server-utils"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; import { useQueryClient } from "@tanstack/react-query"; import { useAppStore } from "@/store/useAppStore"; -import { useTauriEvent } from "@/hooks/useTauriEvent"; import { toast } from "sonner"; import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; import { formatServerVersion } from "@/lib/db"; @@ -45,41 +44,14 @@ interface UpdateStatusChipProps { function UpdateStatusChip({ servers = [], onUpdateAllClick, onUpdatesFound }: UpdateStatusChipProps) { const queryClient = useQueryClient(); const [checking, setChecking] = useState(false); - const [latestBuild, setLatestBuild] = useState(""); - const [cachedBuild, setCachedBuild] = useState(""); - - const load = useCallback(async () => { - const [cached, latest] = await Promise.all([ - getAppSetting("asa_cached_build_id"), - getAppSetting("asa_latest_build_id"), - ]); - setCachedBuild(cached ?? ""); - setLatestBuild(latest ?? ""); - }, []); + const asaCacheOpLabel = useAppStore((s) => s.asaCacheOpLabel); - useEffect(() => { load(); }, [load]); - - // Background check result — refresh state + run per-server check (with toasts). - useTauriEvent("asa://update-check", async (payload) => { - if ("updateApplied" in payload && payload.updateApplied) { - await setAppSetting("asa_update_available", "false"); - await setAppSetting("asa_cached_build_id", latestBuild || cachedBuild); - load(); - return; - } - if ("updateAvailable" in payload) { - const r = payload as UpdateCheckResult; - const now = new Date().toISOString(); - await setAppSetting("asa_update_available", String(r.updateAvailable)); - await setAppSetting("asa_cached_build_id", r.cachedBuildId); - await setAppSetting("asa_latest_build_id", r.latestBuildId); - await setAppSetting("asa_last_checked", now); - load(); - // Background check: toasts fire per-server, no dialog. - await runPerServerUpdateCheck(false); - queryClient.invalidateQueries({ queryKey: ["servers"] }); - } - }); + // Background checks (scheduled or per-server auto-apply) are handled + // globally in SchedulerManager, which invalidates the ["servers"] query — + // this component just re-renders from the refreshed `servers` prop, so it + // doesn't need its own asa://update-check listener. It does watch + // asaCacheOpLabel (also set by SchedulerManager for the background check) + // so the button disables and shows the same spinner state either way. const handleCheck = async () => { setChecking(true); @@ -93,11 +65,17 @@ function UpdateStatusChip({ servers = [], onUpdateAllClick, onUpdatesFound }: Up // Manual check: silent mode suppresses per-server toasts; we show dialog. const summary = await runPerServerUpdateCheck(true); queryClient.invalidateQueries({ queryKey: ["servers"] }); - load(); if (summary.allWithUpdates.length > 0) { - // Show the updates-found dialog to the user. - onUpdatesFound(summary.allWithUpdates); + const manualNeeded = summary.allWithUpdates.filter((s) => !s.autoUpdateImmediate); + if (manualNeeded.length > 0) { + // Show the updates-found dialog — includes auto-updating servers too + // (marked, non-actionable) so the list is a complete picture. + onUpdatesFound(summary.allWithUpdates); + } else { + const n = summary.allWithUpdates.length; + toast.info(`Update found — applying automatically to ${n} server${n === 1 ? "" : "s"}.`); + } } else { toast.success("All servers are up to date."); } @@ -120,10 +98,12 @@ function UpdateStatusChip({ servers = [], onUpdateAllClick, onUpdatesFound }: Up } }; - const serversWithUpdates = (servers ?? []).filter((s) => s.update_available === 1); - const anyStarting = (servers ?? []).some( - (s) => s.update_available === 1 && s.status === "starting" + // Servers with "When Found" automation are excluded here — nothing for a + // manual bulk action to do for them, they update themselves within seconds. + const serversWithUpdates = (servers ?? []).filter( + (s) => s.update_available === 1 && !isAutoUpdateImmediate(s) ); + const anyStarting = serversWithUpdates.some((s) => s.status === "starting"); return (

@@ -148,15 +128,16 @@ function UpdateStatusChip({ servers = [], onUpdateAllClick, onUpdatesFound }: Up
); @@ -175,8 +156,13 @@ interface UpdatesFoundDialogProps { function UpdatesFoundDialog({ open, onOpenChange, updates, onUpdateAll }: UpdatesFoundDialogProps) { const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); - const anyRunning = updates.some((s) => s.status === "running"); - const anyStarting = updates.some((s) => s.status === "starting"); + // Servers with "When Found" automation are handled by the scheduler within + // seconds — shown here for visibility, but excluded from the warnings and + // from what "Update All" actually targets (that filter lives in runUpdateAll, + // this just keeps the copy in this dialog honest about what it will do). + const manualUpdates = updates.filter((s) => !s.autoUpdateImmediate); + const anyRunning = manualUpdates.some((s) => s.status === "running"); + const anyStarting = manualUpdates.some((s) => s.status === "starting"); const versionCache = useBuildVersionCache(); return ( @@ -198,7 +184,11 @@ function UpdatesFoundDialog({ open, onOpenChange, updates, onUpdateAll }: Update
{s.name} @@ -208,23 +198,39 @@ function UpdatesFoundDialog({ open, onOpenChange, updates, onUpdateAll }: Update )}
- - {s.status} - + {s.autoUpdateImmediate ? ( + + Auto-updating + + ) : ( + + {s.status} + + )}
))}
+ {manualUpdates.length < updates.length && ( +

+ Servers marked "Auto-updating" have When Found automation enabled and will update on their own — + no action needed. +

+ )} + {/* Warnings */} {anyRunning && (
@@ -402,6 +411,7 @@ function UpdateAllDialog({ open, onOpenChange, updates, anyStarting, onConfirm } export default function DashboardPage() { const { data: servers = [], isLoading } = useServers(); const { setShowNewServerWizard, enqueueStartup } = useAppStore(); + const countdowns = useAppStore((s) => s.countdowns); const [showImport, setShowImport] = useState(false); const [appVersion, setAppVersion] = useState(""); @@ -416,15 +426,18 @@ export default function DashboardPage() { const total = servers.length; - // Build the ServerUpdateInfo list from the live servers data. + // Build the ServerUpdateInfo list from the live servers data. Servers with + // "When Found" automation are excluded — the header "Update All" button is + // a pure manual-bulk-action, and those servers update themselves already. const serversWithUpdates: ServerUpdateInfo[] = servers - .filter((s) => s.update_available === 1) + .filter((s) => s.update_available === 1 && !isAutoUpdateImmediate(s)) .map((s) => ({ - id: s.id, - name: s.name, - status: s.status, - installedBuild: "—", - cachedBuild: "—", + id: s.id, + name: s.name, + status: s.status, + installedBuild: "—", + cachedBuild: "—", + autoUpdateImmediate: false, })); const anyUpdatesStarting = serversWithUpdates.some((s) => s.status === "starting"); @@ -439,46 +452,80 @@ export default function DashboardPage() { if (stopped.length === 0) return; setGlobalActionPending(true); try { - for (const s of stopped) { - await updateServerStatus(s.id, "starting", null); - const params = await buildStartParams(s); - tauriCmd.startServer(params) - .then((pid) => updateServerStatus(s.id, "starting", pid)) - .catch(async (e) => { - await updateServerStatus(s.id, "start-failed", null); - toast.error(`Failed to start ${s.name}: ${e}`); - }); - } + // Hand off to the staggered startup queue instead of starting every + // server directly/concurrently — same reason the manual per-server + // Start button queues now, just avoided at a bigger scale here. + await Promise.all(stopped.map((s) => updateServerStatus(s.id, "startup_queued", null))); queryClient.invalidateQueries({ queryKey: ["servers"] }); - toast.info(`Starting ${stopped.length} server${stopped.length === 1 ? "" : "s"}…`); + enqueueStartup(stopped.map((s) => s.id)); + toast.info(`Queued ${stopped.length} server${stopped.length === 1 ? "" : "s"} to start…`); } finally { setGlobalActionPending(false); } - }, [servers, queryClient]); + }, [servers, queryClient, enqueueStartup]); + + // Any server still in its graceful-stop warning/RCON-save window — a second + // click on Stop All targets exactly these for a hard kill. Derived from live + // status rather than tracked separately, so it also picks up servers that + // were stopped individually (not just via a prior Stop All click). + const stoppingServers = servers.filter((s) => s.status === "stopping"); + // Same idea for Restart All — servers currently sitting in a restart + // countdown (warning broadcast phase), regardless of what started it. + const restartCountdownServers = servers.filter( + (s) => s.status === "running" && countdowns[s.id]?.action === "restart" + ); + + const handleStopAll = useCallback(() => { + if (stoppingServers.length > 0) { + // Force: hard-kill everything still in its graceful stop window — no + // RCON save, matches the per-server Force Stop button. + setGlobalActionPending(true); + const jobs = stoppingServers.map((s) => + tauriCmd.stopServer(s.id, false) + .catch((e) => toast.error(`Failed to force stop ${s.name}: ${e}`)) + .finally(() => queryClient.invalidateQueries({ queryKey: ["servers"] })) + ); + Promise.allSettled(jobs).finally(() => setGlobalActionPending(false)); + toast.info(`Force stopping ${stoppingServers.length} server${stoppingServers.length === 1 ? "" : "s"}…`); + return; + } - const handleStopAll = useCallback(async () => { const running = servers.filter((s) => s.status === "running" || s.status === "starting"); if (running.length === 0) return; setGlobalActionPending(true); - try { - await Promise.all(running.map((s) => tauriCmd.stopServer(s.id, false).catch(() => null))); - queryClient.invalidateQueries({ queryKey: ["servers"] }); - toast.info(`Stopping ${running.length} server${running.length === 1 ? "" : "s"}…`); - } finally { setGlobalActionPending(false); } - }, [servers, queryClient]); + const jobs = running.map((s) => + stopServerGracefully(s, { + onInvalidate: () => queryClient.invalidateQueries({ queryKey: ["servers"] }), + }).catch((e) => toast.error(`Failed to stop ${s.name}: ${e}`)) + ); + Promise.allSettled(jobs).finally(() => setGlobalActionPending(false)); + toast.info(`Stopping ${running.length} server${running.length === 1 ? "" : "s"}…`); + }, [servers, stoppingServers, queryClient]); + + const handleRestartAll = useCallback(() => { + if (restartCountdownServers.length > 0) { + // Force: skip the remaining warning wait, but still let the graceful + // RCON SaveWorld+doexit the countdown ends with proceed normally — + // same as the per-server "Restart Now" button. + setGlobalActionPending(true); + const jobs = restartCountdownServers.map((s) => + tauriCmd.proceedNow(s.id).catch((e) => toast.error(`Failed to skip wait for ${s.name}: ${e}`)) + ); + Promise.allSettled(jobs).finally(() => setGlobalActionPending(false)); + toast.info(`Skipping wait for ${restartCountdownServers.length} server${restartCountdownServers.length === 1 ? "" : "s"}…`); + return; + } - const handleRestartAll = useCallback(async () => { const running = servers.filter((s) => s.status === "running"); if (running.length === 0) return; + setGlobalActionPending(true); - try { - for (const s of running) { - const params = await buildStartParams(s); - tauriCmd.restartServer(params, true).catch((e) => - toast.error(`Failed to restart ${s.name}: ${e}`) - ); - } - toast.info(`Restarting ${running.length} server${running.length === 1 ? "" : "s"}…`); - } finally { setGlobalActionPending(false); } - }, [servers]); + const jobs = running.map((s) => + restartServerGracefully(s, { + onInvalidate: () => queryClient.invalidateQueries({ queryKey: ["servers"] }), + }).catch((e) => toast.error(`Failed to restart ${s.name}: ${e}`)) + ); + Promise.allSettled(jobs).finally(() => setGlobalActionPending(false)); + toast.info(`Queuing restart for ${running.length} server${running.length === 1 ? "" : "s"}…`); + }, [servers, restartCountdownServers, queryClient]); // ── Update All handler ──────────────────────────────────────────────────── @@ -486,57 +533,17 @@ export default function DashboardPage() { if (updatingAll) return; setUpdatingAll(true); - const targets = servers.filter((s) => s.update_available === 1); + // Excludes servers with "When Found" automation — those are already + // being handled by the scheduler and shouldn't be double-applied here. + const targets = servers.filter((s) => s.update_available === 1 && !isAutoUpdateImmediate(s)); if (targets.length === 0) { setUpdatingAll(false); return; } try { - // First: mark all targets with their initial status. - // Active server = first in list → "updating" - // Rest → "update_queued" - const [first, ...rest] = targets; - - if (rest.length > 0) { - await Promise.all( - rest.map((s) => updateServerStatus(s.id, "update_queued", null)) - ); - queryClient.invalidateQueries({ queryKey: ["servers"] }); - } - - // Process sequentially - for (const server of targets) { - await updateServerStatus(server.id, "updating", null); - queryClient.invalidateQueries({ queryKey: ["servers"] }); - - const wasRunning = server.status === "running" || server.status === "starting"; - - try { - await applyUpdateToServer( - server.id, - server.name, - server.install_path, - wasRunning, - restartAfterUpdate, - (msg) => toast.info(msg, { id: `update-${server.id}` }), - ); - } catch (err) { - if (err && typeof err === "object" && "restartNeeded" in err) { - // Queue this server for startup after update - await updateServerStatus(server.id, "startup_queued", null); - queryClient.invalidateQueries({ queryKey: ["servers"] }); - const serverData = servers.find((s) => s.id === server.id); - if (serverData) enqueueStartup([serverData.id]); - continue; - } - toast.error(`Failed to update ${server.name}`, { description: String(err) }); - await updateServerStatus(server.id, "stopped", null).catch(() => {}); - queryClient.invalidateQueries({ queryKey: ["servers"] }); - } - - await updateServerStatus(server.id, "stopped", null).catch(() => {}); - queryClient.invalidateQueries({ queryKey: ["servers"] }); - } - - toast.success(`Updated ${targets.length} server${targets.length === 1 ? "" : "s"} successfully.`); + await applyUpdateToAllServers(targets, restartAfterUpdate, { + enqueueStartup, + onInvalidate: () => queryClient.invalidateQueries({ queryKey: ["servers"] }), + onProgress: (serverId, msg) => toast.info(msg, { id: `update-${serverId}` }), + }); } finally { setUpdatingAll(false); queryClient.invalidateQueries({ queryKey: ["servers"] }); @@ -582,19 +589,23 @@ export default function DashboardPage() { )} @@ -621,11 +632,11 @@ export default function DashboardPage() {
{/* ── Needs Attention warning — only shown when servers are in a bad state ── */} - {total > 0 && servers.some((s) => s.status === "crashed" || s.status === "error") && ( + {total > 0 && servers.some((s) => s.status === "crashed" || s.status === "error" || s.status === "start-failed") && (
s.status === "crashed" || s.status === "error").length} + value={servers.filter((s) => s.status === "crashed" || s.status === "error" || s.status === "start-failed").length} icon={Activity} color="var(--neon-red)" /> diff --git a/src/app/servers/detail/page.tsx b/src/app/servers/detail/page.tsx index 7c23c6a..edf0bf9 100644 --- a/src/app/servers/detail/page.tsx +++ b/src/app/servers/detail/page.tsx @@ -5,7 +5,7 @@ import { useSearchParams, useRouter } from "next/navigation"; import Link from "next/link"; import { ArrowLeft, Server, LayoutDashboard, Settings2, Terminal, - ScrollText, Package, Archive, CalendarClock, + ScrollText, Package, Archive, CalendarClock, Wrench, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; @@ -17,23 +17,21 @@ import { LogsTab } from "@/components/server/tabs/LogsTab"; import { ModsTab } from "@/components/server/tabs/ModsTab"; import { BackupsTab } from "@/components/server/tabs/BackupsTab"; import { AutomationTab } from "@/components/server/tabs/AutomationTab"; -import { getServer, formatServerVersion } from "@/lib/db"; -import { ARK_MAPS } from "@/data/game-data"; -import { useTauriEvent } from "@/hooks/useTauriEvent"; -import { useQueryClient } from "@tanstack/react-query"; -import { updateServerStatus } from "@/lib/db"; -import type { ServerRow } from "@/lib/db"; -import type { ServerStatus } from "@/lib/tauri-commands"; +import { MaintenanceTab } from "@/components/server/tabs/MaintenanceTab"; +import { formatServerVersion } from "@/lib/db"; +import { useAllMaps } from "@/hooks/useAllMaps"; +import { useServers } from "@/hooks/useServers"; import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; const TABS = [ - { value: "overview", label: "Overview", icon: LayoutDashboard }, - { value: "config", label: "Config", icon: Settings2 }, - { value: "rcon", label: "RCON", icon: Terminal }, - { value: "logs", label: "Logs", icon: ScrollText }, - { value: "mods", label: "Mods", icon: Package }, - { value: "backups", label: "Backups", icon: Archive }, - { value: "automation", label: "Automation", icon: CalendarClock }, + { value: "overview", label: "Overview", icon: LayoutDashboard }, + { value: "config", label: "Config", icon: Settings2 }, + { value: "rcon", label: "RCON", icon: Terminal }, + { value: "logs", label: "Logs", icon: ScrollText }, + { value: "mods", label: "Mods", icon: Package }, + { value: "backups", label: "Backups", icon: Archive }, + { value: "automation", label: "Automation", icon: CalendarClock }, + { value: "maintenance", label: "Maintenance", icon: Wrench }, ] as const; type TabValue = typeof TABS[number]["value"]; @@ -47,42 +45,29 @@ type TabValue = typeof TABS[number]["value"]; export default function ServerDetailPage() { const params = useSearchParams(); const router = useRouter(); - const queryClient = useQueryClient(); const serverId = params.get("id") ?? ""; const tabParam = (params.get("tab") as TabValue | null) ?? "overview"; - const [server, setServer] = useState(null); - const [loading, setLoading] = useState(true); - const [notFound, setNotFound] = useState(false); const [activeTab, setActiveTab] = useState(tabParam); const versionCache = useBuildVersionCache(); - - // ── Load server row ────────────────────────────────────────────────────── - const reload = async () => { - if (!serverId) return; - try { - const s = await getServer(serverId); - if (!s) { setNotFound(true); } else { setServer(s); } - } catch { setNotFound(true); } - finally { setLoading(false); } - }; + const allMaps = useAllMaps(); + + // Shares the same ["servers"] cache as the dashboard and every mutation + // across the app (Config/Automation saves, status events, etc. all + // invalidate this same key) — previously this page kept its own local copy + // of the row, refreshed only by its own narrow server://status/{id} + // listener, so a save from one tab (e.g. Config) wasn't reflected here + // until a later, unrelated status event happened to trigger a reload — + // in the meantime a second save from another tab (e.g. Automation) would + // silently overwrite the first using this page's stale copy as its base. + const { data: servers = [], isLoading } = useServers(); + const server = servers.find((s) => s.id === serverId) ?? null; + const notFound = !isLoading && !server; useEffect(() => { - if (!serverId) { router.replace("/"); return; } - reload(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [serverId]); - - // ── Live status updates from backend ──────────────────────────────────── - useTauriEvent(`server://status/${serverId}`, async (payload) => { - if (!serverId) return; - // Sync status + pid to SQLite then reload the row so UI reflects the change - await updateServerStatus(serverId, payload.status, payload.pid ?? null); - queryClient.invalidateQueries({ queryKey: ["servers"] }); - const updated = await getServer(serverId); - if (updated) setServer(updated); - }); + if (!serverId) router.replace("/"); + }, [serverId, router]); // ── Tab change: keep ?tab= in sync ────────────────────────────────────── const handleTabChange = (value: string) => { @@ -93,8 +78,18 @@ export default function ServerDetailPage() { window.history.replaceState(null, "", url.toString()); }; + // Switch tabs, then (if given) scroll a target section into view once the + // new tab's content has mounted. Used by cross-tab "Configure →" / "Edit →" + // links (Overview's Active Event, Automation's warning-message links). + const navigateToTab = (tab: TabValue, anchor?: string) => { + handleTabChange(tab); + if (anchor) { + setTimeout(() => document.getElementById(anchor)?.scrollIntoView({ behavior: "smooth", block: "start" }), 150); + } + }; + // ── Loading / error states ─────────────────────────────────────────────── - if (loading) { + if (isLoading) { return (
@@ -124,7 +119,7 @@ export default function ServerDetailPage() { ); } - const mapDisplay = ARK_MAPS.find((m) => m.id === server.map_id)?.displayName ?? server.map_id; + const mapDisplay = allMaps.find((m) => m.id === server.map_id)?.displayName ?? server.map_id; return (
@@ -198,16 +193,32 @@ export default function ServerDetailPage() { {/* ── Tab content ── */} {(activeTab === "rcon" || activeTab === "logs" || activeTab === "mods") ? (
- {activeTab === "rcon" && } + {activeTab === "rcon" && } {activeTab === "logs" && } {activeTab === "mods" && }
) : (
- {activeTab === "overview" && } - {activeTab === "config" && } - {activeTab === "backups" && } - {activeTab === "automation" && } + {activeTab === "overview" && ( + navigateToTab("config", anchor)} + /> + )} + {activeTab === "config" && } + {activeTab === "backups" && ( + navigateToTab("automation", "backup-schedules-section")} + /> + )} + {activeTab === "automation" && ( + navigateToTab("config", anchor)} + /> + )} + {activeTab === "maintenance" && }
)}
diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index fdeb751..6492da3 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -1,16 +1,19 @@ "use client"; -import { useState, useEffect, useCallback } from "react"; +import { useState, useEffect, useCallback, useRef } from "react"; +import { useSearchParams } from "next/navigation"; +import { useQueryClient } from "@tanstack/react-query"; import { Folder, Terminal, Info, Archive, Copy, FolderOpen, CheckCircle2, AlertCircle, Loader2, Save, RefreshCw, ArrowUp, Bell, MessageSquare, Mail, Monitor, Send, Download, - Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, Power, ShieldCheck, + Server, Palette, StopCircle, ToggleLeft, ToggleRight, Layers, Power, ShieldCheck, Settings, TriangleAlert, } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; import { Separator } from "@/components/ui/separator"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, @@ -19,7 +22,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; -import { CommandOutputPanel } from "@/components/shared/CommandOutputPanel"; +import { CommandOutputPanel, hasOutputBuffer } from "@/components/shared/CommandOutputPanel"; import { NotificationMatrix } from "@/components/shared/NotificationMatrix"; import { getAppSetting, setAppSetting, @@ -29,21 +32,24 @@ import { } from "@/lib/db"; import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; import { useAutostart } from "@/hooks/useAutostart"; -import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToServer } from "@/lib/update-utils"; +import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToAllServers, isAutoUpdateImmediate } from "@/lib/update-utils"; import { check } from "@tauri-apps/plugin-updater"; import { getVersion } from "@tauri-apps/api/app"; +import { invoke } from "@tauri-apps/api/core"; import { tempDir } from "@tauri-apps/api/path"; import { tauriCmd, type DirCheckResult, type ProtonUpdateInfo, type MigrateProgress, type PortDef, type FirewallStatus } from "@/lib/tauri-commands"; import { getServerFirewallPorts } from "@/lib/firewall-utils"; import { listen } from "@tauri-apps/api/event"; import { - applyTheme, applyThemeAccent, applyThemePreset, + applyTheme, applyThemeAccent, ACCENT_OPTIONS, THEME_PRESETS, type ThemeAccent, type ThemePreset, } from "@/lib/theme"; import { open } from "@tauri-apps/plugin-dialog"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; +import { useAppStore } from "@/store/useAppStore"; +import { useOnMount } from "@/hooks/useOnMount"; // --------------------------------------------------------------------------- // Helpers @@ -189,6 +195,20 @@ function BaseDirMigrationSection() { const handleMigrate = async () => { if (!newDir.trim()) { toast.error("Please enter a destination directory."); return; } + + // The warning text below says servers should be stopped first, but + // nothing actually enforced it — moving install files out from under a + // live process while the DB is rewritten to point elsewhere leaves that + // process and the new location out of sync. + const servers = await getServers(); + const active = servers.filter((s) => s.status === "running" || s.status === "starting" || s.status === "stopping"); + if (active.length > 0) { + toast.error( + `Stop ${active.length === 1 ? "this server" : "these servers"} before migrating: ${active.map((s) => s.name).join(", ")}` + ); + return; + } + setMigrating(true); setProgress(null); setMigrationDone(false); const unlisten = await listen("base-dir://migrate-progress", (e) => { @@ -239,7 +259,7 @@ function BaseDirMigrationSection() { Root folder for all server installs. To relocate, enter a new path and click Verify & Move.

@@ -428,17 +448,27 @@ interface ToolPathFieldProps { validateFn: (path: string) => Promise; validLabel?: string; invalidLabel?: string; + /** When provided and validation fails, show a dialog offering to install + * rather than a toast. The callback receives the typed path as targetDir + * and should return the final installed path to save. */ + onInstallOffer?: (targetDir: string) => Promise; + installOfferTitle?: string; + installOfferBody?: string; } function ToolPathField({ label, settingKey, placeholder, hint, pickDirectory = false, validateFn, validLabel = "Valid", invalidLabel = "Validation failed — check the path.", + onInstallOffer, installOfferTitle = "Not Found", installOfferBody, }: ToolPathFieldProps) { const [value, setValue] = useState(""); const [original, setOriginal] = useState(""); const [verifying, setVerifying] = useState(false); const [valid, setValid] = useState(null); + const [showInstallDialog, setShowInstallDialog] = useState(false); + const [installing, setInstalling] = useState(false); + const [installError, setInstallError] = useState(null); useEffect(() => { getAppSetting(settingKey).then((v) => { const val = v ?? ""; setValue(val); setOriginal(val); }); @@ -461,10 +491,18 @@ function ToolPathField({ await setAppSetting(settingKey, value.trim()); setOriginal(value.trim()); toast.success(`${label} saved.`); + } else if (onInstallOffer) { + setInstallError(null); + setShowInstallDialog(true); } else { toast.error(invalidLabel); } } catch (e) { + // validateFn threw (permission error, transient IPC failure, malformed + // path) — a genuine unexpected error, not "not found". Only route to + // the install-offer dialog when validateFn actually reports "not + // found" (the `ok === false` branch above); otherwise show what + // actually went wrong instead of offering an install that won't fix it. setValid(false); toast.error(`Verification failed: ${e}`); } finally { @@ -472,6 +510,25 @@ function ToolPathField({ } }; + const handleInstall = async () => { + if (!onInstallOffer) return; + setInstalling(true); + setInstallError(null); + try { + const newPath = await onInstallOffer(value.trim()); + await setAppSetting(settingKey, newPath); + setValue(newPath); + setOriginal(newPath); + setValid(true); + setShowInstallDialog(false); + toast.success(`${label} installed successfully.`); + } catch (e) { + setInstallError(String(e)); + } finally { + setInstalling(false); + } + }; + const dirty = value !== original; return ( @@ -499,7 +556,47 @@ function ToolPathField({
{valid === true &&

{validLabel}

} - {valid === false && !verifying &&

{invalidLabel}

} + {valid === false && !verifying && !onInstallOffer &&

{invalidLabel}

} + + {onInstallOffer && ( + { if (!installing) setShowInstallDialog(v); }}> + + + + {installOfferTitle} + + + {installOfferBody && {installOfferBody}} + {value} + + + {installError && ( +

{installError}

+ )} + + + + +
+
+ )}
); } @@ -637,9 +734,12 @@ function AboutSection() { const [appVersion, setAppVersion] = useState("…"); const [asaBuild, setAsaBuild] = useState("—"); const [protonVersion, setProtonVer] = useState("—"); - const [paths, setPaths] = useState({ + const [protonPath, setProtonPath] = useState("—"); + const [configured, setConfigured] = useState({ baseDir: "—", backupDir: "—", steamcmd: "—", - dbPath: "—", cachePath: "—", logRoot: "—", + }); + const [managed, setManaged] = useState({ + dbPath: "—", cachePath: "—", savesRoot: "—", clustersRoot: "—", logRoot: "—", }); const [copied, setCopied] = useState(false); const versionCache = useBuildVersionCache(); @@ -647,7 +747,7 @@ function AboutSection() { useEffect(() => { getVersion().then(setAppVersion).catch(() => setAppVersion("0.10.0")); (async () => { - const [baseDir, backupDir, steamcmd, asaCached, protonPath, logRoot] = await Promise.all([ + const [baseDir, backupDir, steamcmd, asaCached, protonRaw, logRoot] = await Promise.all([ getAppSetting("base_dir"), getAppSetting("backup_dir"), getAppSetting("steamcmd_path"), @@ -658,20 +758,25 @@ function AboutSection() { setAsaBuild(asaCached || "—"); - if (protonPath) { - const ver = protonPath.replace(/[/\\]$/, "").split(/[/\\]/).pop() ?? ""; + if (protonRaw) { + const ver = protonRaw.replace(/[/\\]$/, "").split(/[/\\]/).pop() ?? ""; setProtonVer(ver || "—"); + setProtonPath(protonRaw); } const sep = (baseDir ?? "").includes("\\") ? "\\" : "/"; const base = (baseDir ?? "").replace(/[/\\]$/, ""); - setPaths({ + setConfigured({ baseDir: baseDir || "—", backupDir: backupDir || "—", steamcmd: steamcmd || "—", - dbPath: base ? `${base}${sep}lokiasam${sep}lokiasam.db` : "—", - cachePath: base ? `${base}${sep}lokiasam${sep}cache${sep}asa-server` : "—", - logRoot: logRoot || "—", + }); + setManaged({ + dbPath: base ? `${base}${sep}lokiasam${sep}lokiasam.db` : "—", + cachePath: base ? `${base}${sep}lokiasam${sep}cache${sep}asa-server` : "—", + savesRoot: base ? `${base}${sep}saves` : "—", + clustersRoot: base ? `${base}${sep}clusters` : "—", + logRoot: logRoot || "—", }); })(); }, []); @@ -691,14 +796,20 @@ function AboutSection() { ...(IS_LINUX ? [{ label: "Proton-GE", value: protonVersion }] : []), ]; - const pathRows = [ - { label: "Base Directory", value: paths.baseDir }, - { label: "Backup Directory", value: paths.backupDir }, - { label: "SteamCMD", value: paths.steamcmd }, - { label: "Database", value: paths.dbPath }, - { label: "Server Cache", value: paths.cachePath }, - { label: "Log Storage", value: paths.logRoot }, - { label: "Bootstrap", value: bootstrapHint }, + const configuredRows = [ + { label: "Base Directory", value: configured.baseDir }, + { label: "Backup Directory", value: configured.backupDir }, + { label: "SteamCMD", value: configured.steamcmd }, + ...(IS_LINUX ? [{ label: "Proton-GE", value: protonPath }] : []), + ]; + + const managedRows = [ + { label: "Database", value: managed.dbPath }, + { label: "Server Cache", value: managed.cachePath }, + { label: "Saves", value: managed.savesRoot }, + { label: "Clusters", value: managed.clustersRoot }, + { label: "Log Storage", value: managed.logRoot }, + { label: "Bootstrap", value: bootstrapHint }, ]; const handleCopy = () => { @@ -706,8 +817,11 @@ function AboutSection() { "Versions:", ...versionRows.map((r) => ` ${r.label}: ${r.value}`), "", - "Directories:", - ...pathRows.map((r) => ` ${r.label}: ${r.value}`), + "Configured Directories:", + ...configuredRows.map((r) => ` ${r.label}: ${r.value}`), + "", + "Managed Directories:", + ...managedRows.map((r) => ` ${r.label}: ${r.value}`), ].join("\n"); navigator.clipboard.writeText(text).catch(() => null); setCopied(true); @@ -745,9 +859,14 @@ function AboutSection() { {versionRows.map((r) => )}
- Directories + Configured Directories +
+ {configuredRows.map((r) => )} +
+ + Managed Directories
- {pathRows.map((r) => )} + {managedRows.map((r) => )}
@@ -764,35 +883,29 @@ const AUTO_CHECK_OPTIONS = [ { value: "startup_hourly", label: "On startup + hourly" }, ]; -function ServerUpdatesSection() { +function ServerUpdatesSection({ onPreDownload }: { onPreDownload?: () => void }) { + const queryClient = useQueryClient(); + const asaCacheOpLabel = useAppStore((s) => s.asaCacheOpLabel); + const enqueueStartup = useAppStore((s) => s.enqueueStartup); const [checking, setChecking] = useState(false); const [cachedBuild, setCached] = useState(""); const [lastChecked, setLastChecked] = useState(""); const [autoCheckHours, setAutoCheck] = useState("disabled"); - const [hasCacheInstalled, setHasCacheInstalled] = useState(null); const [showApplyAll, setShowApplyAll] = useState(false); const [applyAllInfo, setApplyAllInfo] = useState<{ total: number; running: number }>({ total: 0, running: 0 }); const [applyingAll, setApplyingAll] = useState(false); + const [restartAfterApplyAll, setRestartAfterApplyAll] = useState(true); const load = useCallback(async () => { - const [cached, checked, hours, baseDir] = await Promise.all([ + const [cached, checked, hours] = await Promise.all([ getAppSetting("asa_cached_build_id"), getAppSetting("asa_last_checked"), getAppSetting("asa_auto_check_hours"), - getAppSetting("base_dir"), ]); setCached(cached ?? ""); setLastChecked(checked ?? ""); setAutoCheck(hours ?? "disabled"); - if (baseDir) { - const sep = baseDir.includes("\\") ? "\\" : "/"; - const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; - const has = await tauriCmd.checkDir(cacheDir).then((r) => r.writable).catch(() => false); - setHasCacheInstalled(has); - } else { - setHasCacheInstalled(false); - } }, []); - useEffect(() => { load(); }, [load]); + useOnMount(load); const handleCheck = async () => { setChecking(true); @@ -803,8 +916,11 @@ function ServerUpdatesSection() { const cacheUpdated = newBuild !== oldBuild; - // Run per-server check now that the cache build ID is current. - await runPerServerUpdateCheck(); + // Run per-server check now that the cache build ID is current. Silent + // (matches the dashboard's manual check) — this section shows its own + // dialog below, so the internal consolidated notification would just + // be a duplicate. + await runPerServerUpdateCheck(true); const servers = await getServers(); const outdated = servers.filter((s) => s.update_available === 1); @@ -825,10 +941,16 @@ function ServerUpdatesSection() { toast.success(`Cache is up to date (build ${newBuild}).`); } - if (outdated.length > 0) { - const running = outdated.filter((s) => s.status === "running").length; - setApplyAllInfo({ total: outdated.length, running }); + // Servers with "When Found" automation apply themselves within seconds — + // exclude them so this confirm isn't offering to double-apply, and skip + // the confirm entirely (just a toast) if that's every outdated server. + const manualOutdated = outdated.filter((s) => !isAutoUpdateImmediate(s)); + if (manualOutdated.length > 0) { + const running = manualOutdated.filter((s) => s.status === "running").length; + setApplyAllInfo({ total: manualOutdated.length, running }); setShowApplyAll(true); + } else if (outdated.length > 0) { + toast.info(`Update found — applying automatically to ${outdated.length} server${outdated.length === 1 ? "" : "s"}.`); } } catch (e) { await dispatchNotification({ @@ -849,37 +971,10 @@ function ServerUpdatesSection() { setApplyingAll(true); try { const servers = await getServers(); - const outdated = servers.filter((s) => s.update_available === 1); - for (const server of outdated) { - try { - await applyUpdateToServer( - server.id, - server.name, - server.install_path, - server.status === "running", - false, - ); - } catch (err) { - // restartNeeded signal — server updated successfully, restart handled inside. - if (!(err && typeof err === "object" && "restartNeeded" in err)) { - await dispatchNotification({ - eventType: NOTIFICATION_EVENTS.UPDATE_FAILED, - serverId: server.id, - serverName: server.name, - title: `${server.name} Update Failed`, - body: `Failed to update ${server.name}: ${err}`, - severity: "error", - }); - } - } - } - await dispatchNotification({ - eventType: NOTIFICATION_EVENTS.SERVER_UPDATED, - serverId: null, - serverName: "All Servers", - title: `${outdated.length} Server${outdated.length !== 1 ? "s" : ""} Updated`, - body: `${outdated.length} server${outdated.length !== 1 ? "s have" : " has"} been updated from the cache.`, - severity: "success", + const outdated = servers.filter((s) => s.update_available === 1 && !isAutoUpdateImmediate(s)); + await applyUpdateToAllServers(outdated, restartAfterApplyAll, { + enqueueStartup, + onInvalidate: () => queryClient.invalidateQueries({ queryKey: ["servers"] }), }); } catch (e) { await dispatchNotification({ @@ -892,6 +987,7 @@ function ServerUpdatesSection() { }); } finally { setApplyingAll(false); + queryClient.invalidateQueries({ queryKey: ["servers"] }); } }; @@ -916,14 +1012,26 @@ function ServerUpdatesSection() {
- - {hasCacheInstalled === false && ( + {!cachedBuild && !asaCacheOpLabel && ( - No server cache installed yet — install a server first. + No server files cached yet — this will download them via SteamCMD. )}
@@ -953,10 +1061,25 @@ function ServerUpdatesSection() { {applyAllInfo.total} server{applyAllInfo.total !== 1 ? "s are" : " is"} behind the cache. {applyAllInfo.running > 0 && ( - <> {applyAllInfo.running} currently running server{applyAllInfo.running !== 1 ? "s" : ""} will be stopped and restarted after the update. + <> {applyAllInfo.running} currently running server{applyAllInfo.running !== 1 ? "s" : ""} will be stopped to apply the update. )} + {applyAllInfo.running > 0 && ( +
+ + +
+ )} + +
+ + + {updateResult?.available && installMethod !== "pkgbuild" && ( + + )} +
+ + {updateResult && ( +
+ {currentVersion && ( +
+ Current: + {currentVersion} + → + {updateResult.version} +
+ )} + {updateResult.available ? ( + installMethod === "pkgbuild" ? ( +

+ Manual update required — run makepkg -si in your LokiASAM folder to update. +

+ ) : ( +

A newer version is available.

+ ) + ) : ( +

You are on the latest version.

+ )} +
+ )} +
@@ -1060,6 +1237,208 @@ function AppUpdateSection() { ); } +// --------------------------------------------------------------------------- +// ASA Server Cache row — Install / Reinstall / Verify the shared server cache +// --------------------------------------------------------------------------- + +// Persists the active operation type across navigation (component remounts) +let _asaCacheActiveOp: "install" | "reinstall" | "verify" = "install"; + +const CACHE_OP_LABELS: Record = { + install: "Installing ASA cache…", + reinstall: "Reinstalling ASA cache…", + verify: "Verifying ASA cache…", +}; + +function AsaServerCacheRow({ autoStart = false, onAutoStartConsumed }: { autoStart?: boolean; onAutoStartConsumed?: () => void }) { + const [cachedBuild, setCachedBuild] = useState(""); + const [baseDir, setBaseDir] = useState(""); + const [phase, setPhase] = useState<"idle" | "running" | "done" | "error">("idle"); + const [operation, setOperation] = useState<"install" | "reinstall" | "verify">("install"); + // Latches the initial autoStart prop value — the prop itself flips back to + // false as soon as onAutoStartConsumed fires below, but the install still + // needs to wait for baseDir to finish loading before it can actually start. + const autoStartLatchedRef = useRef(autoStart); + const autoStartFiredRef = useRef(false); + // True only when we reconnected to an op that was already running (navigation case). + // When runCacheOp starts the op directly, it manages phase itself — no polling needed. + const reconnectedRef = useRef(false); + const containerRef = useRef(null); + + const getCacheDir = useCallback((dir: string) => { + if (!dir) return ""; + const sep = dir.includes("\\") ? "\\" : "/"; + return `${dir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; + }, []); + + const runCacheOp = useCallback(async (op: "install" | "reinstall" | "verify") => { + if (!baseDir) { toast.error("Base directory not configured."); return; } + reconnectedRef.current = false; // Direct mode: runCacheOp manages phase + _asaCacheActiveOp = op; + setOperation(op); + setPhase("running"); + try { + if (op === "reinstall") { + try { + await tauriCmd.deleteDirectory(getCacheDir(baseDir)); + } catch (e) { + // Old directory couldn't be cleared (e.g. a file still locked) — + // don't silently proceed to install on top of stale leftovers. + toast.error(`Couldn't clear the existing cache directory: ${e}`); + setPhase("error"); + return; + } + await setAppSetting("asa_cached_build_id", ""); + } + const newBuild = await runAsaCacheUpdate(CACHE_OP_LABELS[op]); + if (newBuild) { + setCachedBuild(newBuild); + setPhase("done"); + const label = op === "reinstall" ? "reinstalled" : op === "install" ? "installed" : "verified"; + toast.success(`Server cache ${label} (build ${newBuild}).`); + } else { + setPhase("error"); + } + } catch (e) { + if (!String(e).includes("Aborted")) toast.error(`Cache ${op} failed: ${e}`); + setPhase("error"); + } + }, [baseDir, getCacheDir]); + + const load = useCallback(async () => { + const [build, dir] = await Promise.all([ + getAppSetting("asa_cached_build_id"), + getAppSetting("base_dir"), + ]); + setCachedBuild(build ?? ""); + setBaseDir(dir ?? ""); + return dir ?? ""; + }, []); + + // onAutoStartConsumed is a fresh inline callback from the parent every + // render; keep the latest in a ref so the mount-only effect below doesn't + // need it as a dependency (and doesn't re-fire on every parent re-render). + const onAutoStartConsumedRef = useRef(onAutoStartConsumed); + useEffect(() => { + onAutoStartConsumedRef.current = onAutoStartConsumed; + }); + + // On mount: check if a cache operation is already running in the background + // (e.g. user navigated away and came back). Restore running state if so. + const initMount = useCallback(() => { + if (autoStartLatchedRef.current) onAutoStartConsumedRef.current?.(); + load().then((dir) => { + if (autoStartLatchedRef.current && dir) return; // autoStartLatchedRef drives the start via the effect below + tauriCmd.getRunningOps().then((ops) => { + if (ops.includes("check")) { + reconnectedRef.current = true; + setOperation(_asaCacheActiveOp); + setPhase("running"); + } + }).catch(() => {}); + }); + }, [load]); + useOnMount(initMount); + + // After an auto-start navigation: once baseDir is loaded, scroll into view and + // start install. autoStartFiredRef guards against firing more than once — + // it's mutated inside the effect (not during render), and doesn't need to + // trigger a re-render itself the way state would. + useEffect(() => { + if (!autoStartLatchedRef.current || !baseDir || autoStartFiredRef.current) return; + autoStartFiredRef.current = true; + containerRef.current?.scrollIntoView({ behavior: "smooth", block: "start" }); + runCacheOp("install"); + }, [baseDir, runCacheOp]); + + // Poll for completion — only when we reconnected to a background op. + // When runCacheOp started the op directly, it awaits the result itself. + useEffect(() => { + if (phase !== "running" || !reconnectedRef.current) return; + const interval = setInterval(async () => { + try { + const ops = await tauriCmd.getRunningOps(); + if (!ops.includes("check")) { + clearInterval(interval); + reconnectedRef.current = false; + // Brief delay so the JS side of runAsaCacheUpdate() can finish saving + // asa_cached_build_id before we read it. + await new Promise((r) => setTimeout(r, 400)); + const build = await getAppSetting("asa_cached_build_id"); + setCachedBuild(build ?? ""); + setPhase(build ? "done" : "error"); + } + } catch { /* ignore poll errors */ } + }, 2000); + return () => clearInterval(interval); + }, [phase]); + + const hasCache = !!cachedBuild; + const busy = phase === "running"; + + return ( +
+
+
+

+ ARK: Survival Ascended Server +

+

+ {hasCache ? ( + <>Shared cache build: {cachedBuild} + ) : ( + "Shared server cache not yet downloaded." + )} +

+

+ This is the shared cache used by all server instances, not an individual server install. +

+
+
+ {busy && ( + + )} + {hasCache && ( + + )} + +
+
+ {(busy || phase === "done") && ( + + )} +
+ ); +} + // --------------------------------------------------------------------------- // SteamCMD reinstall row (shown inline under the SteamCMD path field) // --------------------------------------------------------------------------- @@ -1069,14 +1448,16 @@ function SteamcmdReinstallRow() { const [done, setDone] = useState(false); const handleReinstall = async () => { - const baseDir = await getAppSetting("base_dir"); - if (!baseDir) { toast.error("Base directory not configured."); return; } - const sep = baseDir.includes("\\") ? "\\" : "/"; - const targetDir = `${baseDir.replace(/[/\\]$/, "")}${sep}steamcmd`; + const currentPath = await getAppSetting("steamcmd_path"); + if (!currentPath) { toast.error("SteamCMD path not configured."); return; } + // Reinstall to the same directory the current executable lives in + const targetDir = currentPath.replace(/[/\\][^/\\]+$/, ""); setReinstalling(true); setDone(false); try { await tauriCmd.installSteamcmd(targetDir); - const newPath = targetDir + (navigator.userAgent.includes("Windows") ? "\\steamcmd.exe" : "/steamcmd.sh"); + const sep = targetDir.includes("\\") ? "\\" : "/"; + const exe = navigator.userAgent.includes("Windows") ? "steamcmd.exe" : "steamcmd.sh"; + const newPath = `${targetDir}${sep}${exe}`; await setAppSetting("steamcmd_path", newPath); setDone(true); toast.success("SteamCMD reinstalled successfully."); @@ -1112,13 +1493,210 @@ function SteamcmdReinstallRow() { ); } +// --------------------------------------------------------------------------- +// Proton-GE install/reinstall row (managed installs only, Linux only) +// --------------------------------------------------------------------------- + +const PROTON_CHANNEL = "proton://output/download"; + +/** + * "Unmanaged Proton-GE" warning box + "Allow management" confirm dialog — + * previously implemented twice, independently, by ProtonGeInstallRow and + * ProtonGeUpdateSection (identical copy, identical dialog), kept in sync + * only by remembering to edit both. + */ +function ProtonUnmanagedNotice({ extraText, alignRight, onManaged }: { + extraText?: string; + alignRight?: boolean; + onManaged: () => void; +}) { + const [showConfirm, setShowConfirm] = useState(false); + + const handleConfirm = async () => { + await setAppSetting("proton_ge_managed", "true"); + setShowConfirm(false); + toast.success("LokiASAM will now manage Proton-GE updates."); + onManaged(); + }; + + return ( +
+
+ +

+ Proton-GE is in unmanaged mode — LokiASAM will not check for or update it. + {extraText} +

+
+
+ +
+ { if (!v) setShowConfirm(false); }}> + + + + Allow LokiASAM to Manage Proton-GE? + + + + Switching to managed mode gives LokiASAM full control over your Proton-GE installation — it may download new versions and replace the current one. + + + If this Proton-GE was installed by Steam, Lutris, or another tool, LokiASAM may overwrite it and break other applications that depend on it. + + + For the safest experience, let LokiASAM download and install its own dedicated copy of Proton-GE instead. + + + + + + + + + +
+ ); +} + +function ProtonGeInstallRow() { + const protonOpLabel = useAppStore((s) => s.protonOpLabel); + const protonOpDone = useAppStore((s) => s.protonOpDone); + const setProtonOpLabel = useAppStore((s) => s.setProtonOpLabel); + const setProtonOpDone = useAppStore((s) => s.setProtonOpDone); + + const [protonPath, setProtonPath] = useState(""); + const [isManaged, setIsManaged] = useState(false); + // Initialized from Zustand (synchronously available on first render) so + // nav-away/back shows the right state immediately — no effect needed to + // "restore" it after mount. + const [phase, setPhase] = useState<"idle" | "running" | "done" | "error">(() => { + if (protonOpLabel !== null) return "running"; + if (protonOpDone) return "done"; + return "idle"; + }); + useEffect(() => { + Promise.all([ + getAppSetting("proton_path"), + getAppSetting("proton_ge_managed"), + ]).then(([p, managed]) => { + setProtonPath(p ?? ""); + setIsManaged(managed === "true"); + }); + }, []); + + const hasInstall = !!protonPath; + const busy = phase === "running"; + + const handleRun = async (reinstall: boolean) => { + const baseDir = await getAppSetting("base_dir"); + if (!baseDir) { toast.error("Base directory not configured."); return; } + const sep = baseDir.includes("\\") ? "\\" : "/"; + // Reinstall: go back to the same parent directory we deleted from. + // Fresh install: fall back to the managed default location. + const targetDir = protonPath + ? protonPath.replace(/[/\\][^/\\]+$/, "") + : `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}proton`; + setPhase("running"); + setProtonOpLabel(reinstall ? "Reinstalling Proton-GE…" : "Installing Proton-GE…"); + setProtonOpDone(false); + try { + if (reinstall && protonPath) { + // Let a delete failure fall through to the catch below instead of + // silently proceeding to download on top of stale leftover files. + await tauriCmd.deleteDirectory(protonPath); + } + const newPath = await tauriCmd.downloadProtonGe(targetDir); + await setAppSetting("proton_path", newPath); + setProtonPath(newPath); + setPhase("done"); + setProtonOpLabel(null); + setProtonOpDone(true); + toast.success(`Proton-GE ${reinstall ? "reinstalled" : "installed"} successfully.`); + } catch (e) { + if (!String(e).includes("Aborted")) toast.error(`Proton-GE ${reinstall ? "reinstall" : "install"} failed: ${e}`); + setPhase("error"); + setProtonOpLabel(null); + setProtonOpDone(false); + } + }; + + if (!isManaged) { + return ( +
+ setIsManaged(true)} /> +
+ ); + } + + return ( +
+
+

+ {hasInstall + ? "Re-download and replace the managed Proton-GE installation." + : "Download and install Proton-GE to the managed location."} +

+
+ {busy && ( + + )} + +
+
+ {(phase === "running" || phase === "done" || hasOutputBuffer(PROTON_CHANNEL)) && ( + + )} +
+ ); +} + // --------------------------------------------------------------------------- // Amazon Root CA certificate install row // --------------------------------------------------------------------------- function CertInstallRow() { - const [phase, setPhase] = useState<"idle" | "downloading" | "installing" | "done" | "error">("idle"); - const [error, setError] = useState(""); + const [phase, setPhase] = useState<"idle" | "downloading" | "installing" | "done" | "error">("idle"); + const [error, setError] = useState(""); + const [isInstalled, setIsInstalled] = useState(false); + + useEffect(() => { + (async () => { + const protonPath = IS_LINUX ? (await getAppSetting("proton_path")) ?? undefined : undefined; + const prefixPath = IS_LINUX ? (await getAppSetting("proton_prefix_path")) ?? undefined : undefined; + const installed = await tauriCmd.checkAmazonRootCaInstalled(protonPath, prefixPath).catch(() => false); + setIsInstalled(installed); + })(); + }, []); const handleInstall = async () => { setError(""); @@ -1140,6 +1718,7 @@ function CertInstallRow() { : undefined); await tauriCmd.installAmazonRootCa(certPath, protonPath, resolvedPrefix); setPhase("done"); + setIsInstalled(true); toast.success("Amazon Root CA 1 installed successfully."); } catch (e) { setError(String(e)); @@ -1181,7 +1760,7 @@ function CertInstallRow() { ? (phase === "downloading" ? "Downloading…" : "Installing…") : phase === "done" ? "Installed" - : "Install / Reinstall"} + : isInstalled ? "Reinstall Certs" : "Install Certs"}
{phase === "error" && ( @@ -1231,13 +1810,14 @@ function FirewallRepairRow() { const handleFix = async () => { if (!fwStatus) return; - const missingPorts: PortDef[] = fwStatus.ports - .filter((p) => !p.covered) - .map((p) => ({ port: p.port, protocol: p.protocol as "tcp" | "udp" })); setIsFixing(true); try { + // Pass the complete desired port set so the backend can rebuild from scratch, + // removing any stale entries from previously deleted servers. + const allPorts: PortDef[] = fwStatus.ports + .map((p) => ({ port: p.port, protocol: p.protocol as "tcp" | "udp" })); const protonPath = IS_LINUX ? (await getAppSetting("proton_path")) ?? undefined : undefined; - await tauriCmd.addFirewallRules(missingPorts, protonPath); + await tauriCmd.addFirewallRules(allPorts, protonPath); toast.success("Firewall rules added."); await runCheck(); } catch (e) { @@ -1278,7 +1858,7 @@ function FirewallRepairRow() { : allGood ? : } - {phase === "checking" ? "Checking…" : allGood ? "All Good" : "Check & Repair"} + {phase === "checking" ? "Checking…" : allGood ? "All Good" : "Check & Repair Firewall"}
@@ -1338,14 +1918,24 @@ function FirewallRepairRow() { // Proton-GE Update section (Linux only) // --------------------------------------------------------------------------- -function ProtonGeUpdateSection() { - const [protonPath, setProtonPath] = useState(""); - const [isManaged, setIsManaged] = useState(false); - const [checking, setChecking] = useState(false); - const [updateInfo, setUpdateInfo] = useState(null); - const [downloading, setDownloading] = useState(false); - const [downloadDone, setDownloadDone] = useState(false); - const [checkMode, setCheckMode] = useState("startup_hourly"); +function ProtonGeUpdateSection({ autoStart }: { autoStart?: boolean }) { + const protonOpLabel = useAppStore((s) => s.protonOpLabel); + const protonOpDone = useAppStore((s) => s.protonOpDone); + const setProtonOpLabel = useAppStore((s) => s.setProtonOpLabel); + const setProtonOpDone = useAppStore((s) => s.setProtonOpDone); + + const [protonPath, setProtonPath] = useState(""); + const [isManaged, setIsManaged] = useState(false); + const [checking, setChecking] = useState(false); + const [updateInfo, setUpdateInfo] = useState(null); + // Initialized from Zustand (synchronously available on first render) so + // nav-away/back shows the right state immediately — no effect needed to + // "restore" it after mount. + const [downloading, setDownloading] = useState(() => protonOpLabel !== null); + const [downloadDone, setDownloadDone] = useState(() => protonOpLabel === null && protonOpDone); + const [checkMode, setCheckMode] = useState("disabled"); + const autoStartedRef = useRef(false); + const sectionRef = useRef(null); useEffect(() => { Promise.all([ @@ -1355,26 +1945,40 @@ function ProtonGeUpdateSection() { ]).then(([p, managed, mode]) => { setProtonPath(p ?? ""); setIsManaged(managed === "true"); - setCheckMode(mode ?? "startup_hourly"); + setCheckMode(mode ?? "disabled"); }); }, []); + // Scroll this section into view when navigated here from the update toast. + useEffect(() => { + if (!autoStart) return; + const frame = requestAnimationFrame(() => { + sectionRef.current?.scrollIntoView({ behavior: "smooth", block: "start" }); + }); + return () => cancelAnimationFrame(frame); + }, [autoStart]); + const handleCheckUpdate = async () => { setChecking(true); setUpdateInfo(null); try { const info = await tauriCmd.checkProtonGeUpdate(protonPath); setUpdateInfo(info); + if (info.updateAvailable) { + toast.info(`Proton-GE ${info.latestVersion} is available.`); + } else { + toast.success("Proton-GE is up to date."); + } } catch (e) { toast.error(`Failed to check for updates: ${e}`); } finally { setChecking(false); } }; - const handleDownload = async () => { - const baseDir = await getAppSetting("base_dir"); - if (!baseDir) { toast.error("Base directory not configured."); return; } - const sep = baseDir.includes("\\") ? "\\" : "/"; - const targetDir = `${baseDir.replace(/[/\\]$/, "")}${sep}proton`; + const handleDownload = useCallback(async () => { + if (!protonPath) { toast.error("Proton-GE path not configured."); return; } + const targetDir = protonPath.replace(/[/\\][^/\\]+$/, ""); setDownloading(true); setDownloadDone(false); + setProtonOpLabel("Updating Proton-GE…"); + setProtonOpDone(false); try { const newPath = await tauriCmd.downloadProtonGe(targetDir); await setAppSetting("proton_path", newPath); @@ -1383,22 +1987,29 @@ function ProtonGeUpdateSection() { setIsManaged(true); setDownloadDone(true); setUpdateInfo(null); + setProtonOpLabel(null); + setProtonOpDone(true); toast.success("Proton-GE updated successfully."); - } catch (e) { toast.error(`Proton-GE update failed: ${e}`); } + } catch (e) { + setProtonOpLabel(null); + setProtonOpDone(false); + if (!String(e).includes("Aborted")) toast.error(`Proton-GE update failed: ${e}`); + } finally { setDownloading(false); } - }; - - const handleTakeOwnership = async () => { - await setAppSetting("proton_ge_managed", "true"); - setIsManaged(true); - toast.success("LokiASAM will now manage Proton-GE updates."); - }; + }, [protonPath, setProtonOpLabel, setProtonOpDone]); const handleCheckModeChange = async (value: string) => { setCheckMode(value); await setAppSetting("proton_ge_check_mode", value); }; + // When navigated here via the update toast, auto-start the download once settings are loaded. + useEffect(() => { + if (!autoStart || autoStartedRef.current || !protonPath || !isManaged) return; + autoStartedRef.current = true; + handleDownload(); + }, [autoStart, protonPath, isManaged, handleDownload]); + // Determine if the current path is inside the managed location const managedPattern = /[/\\]proton[/\\]GE-Proton/; const looksExternal = protonPath && !managedPattern.test(protonPath); @@ -1407,7 +2018,7 @@ function ProtonGeUpdateSection() { : ""; return ( -
+
{/* Current version row */} {currentVersion && (
@@ -1423,20 +2034,12 @@ function ProtonGeUpdateSection() {
)} - {/* External path notice */} - {looksExternal && !isManaged && ( -
-
- -

- This Proton-GE path is outside LokiASAM's managed directory. Automatic updates are suppressed. -

-
- -
+ {/* Unmanaged notice — shown whenever isManaged is false */} + {!isManaged && ( + setIsManaged(true)} + /> )} {/* Update check result */} @@ -1468,14 +2071,14 @@ function ProtonGeUpdateSection() { {/* Action buttons */}
- {(updateInfo?.updateAvailable || (!protonPath && updateInfo)) && (isManaged || !looksExternal) && ( -
{/* Auto-check mode */} -
+

Automatically check GitHub for new GE-Proton releases. @@ -1519,8 +2122,8 @@ function ProtonGeUpdateSection() {

{/* Download output */} - {(downloading || downloadDone) && ( - + {(downloading || downloadDone || hasOutputBuffer(PROTON_CHANNEL)) && ( + )}
); @@ -1558,7 +2161,7 @@ function GlobalNotificationsSection({ onCredentialSaved }: { onCredentialSaved?: try { setConfigs(await getNotificationConfigs(null)); } catch (err) { toast.error("Failed to load notification configs", { description: String(err) }); } }, []); - useEffect(() => { loadConfigs(); }, [loadConfigs]); + useOnMount(loadConfigs); function getConfig(channelId: string) { return configs.find((c) => c.channel === channelId); } @@ -1641,13 +2244,22 @@ interface GlobalChannelCardProps { onTest: (cfgJson: string) => Promise; } -function GlobalChannelCard({ channelId: _channelId, icon: Icon, label, desc, fields, enabled, cfg, saving, onToggle, onSave, onTest }: GlobalChannelCardProps) { +function GlobalChannelCard({ icon: Icon, label, desc, fields, enabled, cfg, saving, onToggle, onSave, onTest }: GlobalChannelCardProps) { const [localCfg, setLocalCfg] = useState>(cfg); const [testing, setTesting] = useState(false); const [testPassed, setTestPassed] = useState(false); - - // eslint-disable-next-line react-hooks/exhaustive-deps - useEffect(() => { setLocalCfg(cfg); }, [JSON.stringify(cfg)]); + const cfgKey = JSON.stringify(cfg); + const [prevCfgKey, setPrevCfgKey] = useState(cfgKey); + // Re-sync the local editable copy when the upstream cfg genuinely changes + // (not on every render — cfg is a fresh object each render even when its + // contents are the same). Comparing during render and updating state here + // is React's documented pattern for "adjusting state when a prop changes" + // without needing a separate effect (refs can't be read/written during + // render, so the "previous value" has to be state too). + if (prevCfgKey !== cfgKey) { + setPrevCfgKey(cfgKey); + setLocalCfg(cfg); + } const handleTestClick = async () => { setTesting(true); @@ -1769,53 +2381,59 @@ function AppImageIntegrationSection() { }; return ( -
-

- Adds LokiASAM to your desktop application launcher so you can find, launch, and pin it - without navigating to the AppImage file each time. Writes a .desktop file and - icon to ~/.local/share/ only — no files are placed outside that folder. - Removing it restores the system to its original state. -

- {status.isInstalled ? ( -
-
- - - Installed in application menu - +
+
+

+ Adds LokiASAM to your desktop application launcher so you can find, launch, and pin it + without navigating to the AppImage file each time. Writes a .desktop file and + icon to ~/.local/share/ only — no files are placed outside that folder. + Removing it restores the system to its original state. +

+ {status.isInstalled ? ( +
+
+ + + Installed in application menu + + +
+

+ If the icon doesn't appear in your launcher, log out and back in (or reboot). +

+
+ ) : ( -
-

- If the icon doesn't appear in your launcher, log out and back in (or reboot). -

-
- ) : ( - - )} -
+ )} +
+ ); } @@ -1828,7 +2446,15 @@ function CloseToTraySection() { const handleToggle = async (enabled: boolean) => { setCloseToTrayState(enabled); await setAppSetting("close_to_tray", String(enabled)); - tauriCmd.setCloseToTray(enabled).catch(() => {}); + try { + await tauriCmd.setCloseToTray(enabled); + } catch (e) { + // Backend didn't pick up the change — revert the toggle rather than + // leaving the UI showing a state that diverges from actual behavior. + setCloseToTrayState(!enabled); + await setAppSetting("close_to_tray", String(!enabled)); + toast.error(`Failed to update close-to-tray setting: ${e}`); + } }; return ( @@ -1896,16 +2522,16 @@ function StartupSection() {

- When the app starts and detects servers that were running during the previous session but - are now offline, LokiASAM can prompt you to restart them, restart them automatically, - or do nothing. + When the app starts, if servers were running during the last session but are now + offline (e.g. after a power loss or system reboot), LokiASAM can prompt you to + restart them, restart them automatically, or do nothing.

{pref === "never" && (

- The downed-servers dialog is suppressed. Change this setting back to{" "} + The restart prompt is suppressed. Change this setting back to{" "} Ask each time to re-enable it.

)} @@ -1913,11 +2539,11 @@ function StartupSection() { patchConfig({ broadcastWarning: e.target.checked })} - className="w-3.5 h-3.5" - style={{ accentColor: "var(--neon-purple)" }} /> - - Send in-game warning before restart - - - {c.broadcastWarning && ( -
-
- - patchConfig({ warningMinutes: parseInt(e.target.value, 10) || 15 })} - className="h-7 w-20 text-xs" - style={{ background: "rgba(0,0,0,0.4)", border: "1px solid rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} /> -
-
- - patchConfig({ message: e.target.value })} - placeholder="Server restarting in {minutes} minutes." - className="h-7 text-xs" - style={{ background: "rgba(0,0,0,0.4)", border: "1px solid rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} /> -
-
- )} - +
+ + {restartWarnPlayers && ( + + )} +
+

+ Same warning message and timing as the manual Restart button — edit it in Settings. +

)} @@ -523,11 +496,6 @@ function effectiveCron(tiers: Record): string { return "0 * * * *"; } -/** Find the single consolidated backup schedule row for a given type. */ -function findBackupSchedule(schedules: ScheduleRow[], type: BackupScheduleType): ScheduleRow | null { - return schedules.find((s) => s.schedule_type === type) ?? null; -} - function findFullSchedule(schedules: ScheduleRow[]): ScheduleRow | null { return schedules.find((s) => s.schedule_type === "backup_full") ?? null; } @@ -537,14 +505,13 @@ function findFullSchedule(schedules: ScheduleRow[]): ScheduleRow | null { // --------------------------------------------------------------------------- function BackupTypeSection({ - title, scheduleType, serverId, schedules, onRefresh, accentHex, + title, scheduleType, serverId, schedules, onRefresh, }: { title: string; scheduleType: BackupScheduleType; serverId: string; schedules: ScheduleRow[]; onRefresh: () => void; - accentHex: string; }) { const buildState = (): Record => { const s = {} as Record; @@ -583,9 +550,18 @@ function BackupTypeSection({ const [tiers, setTiers] = useState>(buildState); const [saving, setSaving] = useState(false); - const [saved, setSaved] = useState(false); - - useEffect(() => { setTiers(buildState()); }, [schedules.length, serverId, scheduleType]); + const [saved, triggerSaved] = useSavedFlash(); + + // Re-derive tiers when the upstream schedules genuinely change, compared + // during render (React's documented "adjusting state" pattern) rather than + // via an effect — buildState() is a pure computation from schedules/ + // serverId/scheduleType, not an async fetch. + const tiersKey = `${serverId}:${scheduleType}:${schedules.length}`; + const [prevTiersKey, setPrevTiersKey] = useState(tiersKey); + if (tiersKey !== prevTiersKey) { + setPrevTiersKey(tiersKey); + setTiers(buildState()); + } const patch = (tier: BackupTier, delta: Partial) => setTiers((s) => ({ ...s, [tier]: { ...s[tier], ...delta } })); @@ -624,8 +600,7 @@ function BackupTypeSection({ await updateScheduleConfig(newId, cron, configJson, nextIso); } - setSaved(true); - setTimeout(() => setSaved(false), 2000); + triggerSaved(); onRefresh(); syncSchedulesToRust(); } catch (e) { @@ -698,14 +673,19 @@ function FullBackupScheduleSection({ serverId, schedules, onRefresh }: { const [keep, setKeep] = useState((cfg.keep as number) ?? 3); const [enabled, setEnabled] = useState(existing ? existing.enabled === 1 : false); const [saving, setSaving] = useState(false); - const [saved, setSaved] = useState(false); - - useEffect(() => { + const [saved, triggerSaved] = useSavedFlash(); + + // Re-derive keep/enabled when the upstream schedules genuinely change, + // compared during render rather than via an effect. + const fullKey = `${serverId}:${schedules.length}`; + const [prevFullKey, setPrevFullKey] = useState(fullKey); + if (fullKey !== prevFullKey) { + setPrevFullKey(fullKey); const row = findFullSchedule(schedules); const c = parseCfg(row?.config_json); setKeep((c.keep as number) ?? 3); setEnabled(row ? row.enabled === 1 : false); - }, [schedules.length, serverId]); + } async function handleSave() { setSaving(true); @@ -721,8 +701,7 @@ function FullBackupScheduleSection({ serverId, schedules, onRefresh }: { await createSchedule({ id: newId, serverId, scheduleType: "backup_full", cronExpression: cron, enabled: true, configJson }); await updateScheduleConfig(newId, cron, configJson, nextIso); } - setSaved(true); - setTimeout(() => setSaved(false), 2000); + triggerSaved(); onRefresh(); syncSchedulesToRust(); } catch (e) { @@ -782,7 +761,7 @@ function LoginBackupRow({ serverId }: { serverId: string }) { const [keep, setKeep] = useState(3); const [enabled, setEnabled] = useState(false); const [saving, setSaving] = useState(false); - const [saved, setSaved] = useState(false); + const [saved, triggerSaved] = useSavedFlash(); useEffect(() => { getAppSetting(`login_backup_keep_${serverId}`).then((v) => { @@ -796,8 +775,7 @@ function LoginBackupRow({ serverId }: { serverId: string }) { setSaving(true); try { await setAppSetting(`login_backup_keep_${serverId}`, enabled ? String(keep) : "0"); - setSaved(true); - setTimeout(() => setSaved(false), 2000); + triggerSaved(); } catch (e) { toast.error(`Failed to save login backup config: ${e}`); } finally { @@ -860,7 +838,7 @@ function LoginBackupRow({ serverId }: { serverId: string }) { function ManualBackupRow({ serverId }: { serverId: string }) { const [keep, setKeep] = useState(5); const [saving, setSaving] = useState(false); - const [saved, setSaved] = useState(false); + const [saved, triggerSaved] = useSavedFlash(); useEffect(() => { getAppSetting(`manual_backup_keep_${serverId}`).then((v) => { @@ -873,8 +851,7 @@ function ManualBackupRow({ serverId }: { serverId: string }) { setSaving(true); try { await setAppSetting(`manual_backup_keep_${serverId}`, String(Math.max(1, keep))); - setSaved(true); - setTimeout(() => setSaved(false), 2000); + triggerSaved(); } catch (e) { toast.error(`Failed to save manual backup config: ${e}`); } finally { @@ -950,12 +927,10 @@ function BackupScheduleSection({ serverId, schedules, onRefresh }: {
+ serverId={serverId} schedules={schedules} onRefresh={onRefresh} />
+ serverId={serverId} schedules={schedules} onRefresh={onRefresh} />
@@ -976,16 +951,39 @@ const DEFAULT_UPDATE_AUTOMATION: UpdateAutomation = { only_if_running: true, }; -function UpdateAutomationCard({ server }: { server: ServerRow }) { +function UpdateAutomationCard({ server, onNavigateToConfig }: { server: ServerRow; onNavigateToConfig?: (anchor?: string) => void }) { + const queryClient = useQueryClient(); const [automation, setAutomation] = useState(DEFAULT_UPDATE_AUTOMATION); const [autoCheckEnabled, setAutoCheckEnabled] = useState(true); const [saving, setSaving] = useState(false); - const [saved, setSaved] = useState(false); + const [saved, triggerSaved] = useSavedFlash(); + const [updateWarnPlayers, setUpdateWarnPlayers] = useState(server.update_warn_players !== 0); + const [savingUpdateWarn, setSavingUpdateWarn] = useState(false); + + const handleToggleUpdateWarn = async (checked: boolean) => { + setUpdateWarnPlayers(checked); + setSavingUpdateWarn(true); + try { + await updateServerUpdateSettings( + server.id, checked, + server.update_warn_minutes ?? 5, + server.update_message || "Server going down for update in {time}.", + server.update_cancel_message || "Update has been canceled.", + ); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + syncSchedulesToRust(); + } catch (e) { + setUpdateWarnPlayers(!checked); + toast.error(`Failed to save: ${e}`); + } finally { + setSavingUpdateWarn(false); + } + }; useEffect(() => { (async () => { const hours = await getAppSetting("asa_auto_check_hours"); - setAutoCheckEnabled((hours ?? "0") !== "0"); + setAutoCheckEnabled((hours ?? "disabled") !== "disabled"); try { const raw = server.update_automation_json; if (raw && raw !== "{}") { @@ -996,14 +994,22 @@ function UpdateAutomationCard({ server }: { server: ServerRow }) { }, [server.id, server.update_automation_json]); const handleSave = async (patch: Partial) => { + const prev = automation; const next = { ...automation, ...patch }; setAutomation(next); setSaving(true); try { await setServerUpdateAutomation(server.id, next); - setSaved(true); - setTimeout(() => setSaved(false), 2000); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + triggerSaved(); + // Otherwise this change (e.g. enabling "When Found") sits inert until + // some unrelated schedule fire or app restart happens to resync. + syncSchedulesToRust(); } catch (e) { + // Revert the optimistic update — otherwise the card keeps showing the + // unsaved change as if it persisted, silently diverging from the DB + // (and thus from what automation actually does) until remount. + setAutomation(prev); toast.error(`Failed to save update automation: ${e}`); } finally { setSaving(false); @@ -1085,9 +1091,10 @@ function UpdateAutomationCard({ server }: { server: ServerRow }) { style={{ background: "rgba(var(--neon-purple-rgb),0.04)", border: "1px solid rgba(var(--neon-purple-rgb),0.12)", color: "var(--text-muted)" }}> - Automated triggers are coming in a future update once proper RCON shutdown is implemented. - Settings are saved now so configuration is ready when the feature ships. Use the{" "} - Update button on server cards for manual updates. + Updates apply automatically once an update is detected — this requires the ASA cache + check in Settings → ASA Server Updates{" "} + to be set to On Startup or On Startup + Hourly. Applying an update uses the same graceful + shutdown as the Update button on server cards.
)} @@ -1095,6 +1102,29 @@ function UpdateAutomationCard({ server }: { server: ServerRow }) { {automation.mode !== "off" && (
+
+ + {updateWarnPlayers && ( + + )} +
+

+ Same warning message and timing as the manual Apply Update button — edit it in Settings. +

) : (
- + {CARD_DEFS.map((def) => ( ))}
diff --git a/src/components/server/tabs/BackupsTab.tsx b/src/components/server/tabs/BackupsTab.tsx index 4072b7c..4b1a35d 100644 --- a/src/components/server/tabs/BackupsTab.tsx +++ b/src/components/server/tabs/BackupsTab.tsx @@ -1,6 +1,8 @@ "use client"; import { useState, useCallback, useEffect } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { useOnMount } from "@/hooks/useOnMount"; import { Archive, Plus, Trash2, RotateCcw, HardDrive, User, FileText, AlertCircle, Loader2, RefreshCw, CalendarClock, @@ -13,8 +15,10 @@ import { type BackupRow, } from "@/lib/db"; import { tauriCmd } from "@/lib/tauri-commands"; +import { stopServerGracefully } from "@/lib/server-utils"; import { useTauriEvent } from "@/hooks/useTauriEvent"; -import { ARK_MAPS } from "@/data/game-data"; +import { getSaveFolder } from "@/data/game-data"; +import { useAllMaps } from "@/hooks/useAllMaps"; import type { ServerRow } from "@/lib/db"; import type { BackupRecord } from "@/lib/tauri-commands"; @@ -41,12 +45,6 @@ function formatHumanDate(iso: string): string { return `${datePart} ${timePart}`; } -function platform(): string { - return typeof navigator !== "undefined" && !navigator.userAgent.includes("Windows") - ? "LinuxServer" - : "WindowsServer"; -} - // --------------------------------------------------------------------------- // Tier tags // --------------------------------------------------------------------------- @@ -221,7 +219,6 @@ function BackupRowCard({ }) { const isLogin = backup.triggered_by === "login"; const tiers = !isLogin && backup.tiers ? backup.tiers.split(",").filter(Boolean) : []; - const fname = backup.file_path.split(/[\\/]/).pop() ?? backup.file_path; const displayName = backup.backup_type === "player" && backup.player_name ? backup.player_name : null; @@ -543,6 +540,7 @@ function IniBackupSection({ const [loading, setLoading] = useState(true); const load = useCallback(async () => { + if (!backupDir) return; setLoading(true); try { setSnapshots(await tauriCmd.listIniBackups(serverId, backupDir)); @@ -551,12 +549,12 @@ function IniBackupSection({ } }, [serverId, backupDir]); - useEffect(() => { if (backupDir) load(); }, [load, backupDir]); + useOnMount(load); async function handleRestore(timestamp: string) { onBusyChange(true); try { - await tauriCmd.restoreIniBackup(`${backupDir}/${serverId}/ini/${timestamp}`, installPath, platform()); + await tauriCmd.restoreIniBackup(serverId, `${backupDir}/${serverId}/ini/${timestamp}`, installPath); toast.success(`Config restored from ${timestamp}.`); } catch (e) { toast.error(`INI restore failed: ${e}`); @@ -648,9 +646,10 @@ function IniBackupSection({ // --------------------------------------------------------------------------- function SyncConfirmDialog({ - importCount, onConfirm, onCancel, + importCount, deleteCount, onConfirm, onCancel, }: { importCount: number; + deleteCount: number; onConfirm: () => void; onCancel: () => void; }) { @@ -671,20 +670,33 @@ function SyncConfirmDialog({ Sync from Disk
-

- Found{" "} - - {importCount} file{importCount !== 1 ? "s" : ""} - {" "} - to import. -

+
+ {importCount > 0 && ( +

+ Found{" "} + + {importCount} file{importCount !== 1 ? "s" : ""} + {" "} + to import. +

+ )} + {deleteCount > 0 && ( +

+ + {deleteCount} record{deleteCount !== 1 ? "s" : ""} + {" "} + will be removed from history — their files were not found in the backup directory. + If the directory is temporarily unreachable, cancel and check it before continuing. +

+ )} +
+ onClick={onConfirm}>{importCount > 0 ? "Import" : "Continue"}
@@ -701,7 +713,11 @@ interface Props { } export function BackupsTab({ server, onNavigateToAutomation }: Props) { - const mapPath = ARK_MAPS.find((m) => m.id === server.map_id)?.mapPath ?? "TheIsland_WP"; + const queryClient = useQueryClient(); + const allMaps = useAllMaps(); + const mapDef = allMaps.find((m) => m.id === server.map_id); + const mapPath = mapDef?.mapPath ?? "TheIsland_WP"; + const saveFolder = mapDef ? getSaveFolder(mapDef) : mapPath; const [serverBackups, setServerBackups] = useState([]); const [playerBackups, setPlayerBackups] = useState([]); @@ -715,22 +731,25 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { const [showFullWarning, setShowFullWarning] = useState(false); const [fullEstimate, setFullEstimate] = useState(0); const [backupDir, setBackupDir] = useState(""); - const [syncPending, setSyncPending] = useState<{ toImport: BackupRecord[] } | null>(null); + const [baseDir, setBaseDir] = useState(""); + const [syncPending, setSyncPending] = useState<{ toImport: BackupRecord[]; toDelete: string[] } | null>(null); const [syncing, setSyncing] = useState(false); const loadAll = useCallback(async () => { setLoading(true); try { - const [srv, plr, ful, bdir] = await Promise.all([ + const [srv, plr, ful, bdir, bsdir] = await Promise.all([ getServerBackupsByType(server.id, "server"), getServerBackupsByType(server.id, "player"), getServerBackupsByType(server.id, "full"), getAppSetting("backup_dir"), + getAppSetting("base_dir"), ]); setServerBackups(srv); setPlayerBackups(plr); setFullBackups(ful); setBackupDir(bdir ?? ""); + setBaseDir(bsdir ?? ""); } catch (e) { toast.error(`Failed to load backups: ${e}`); } finally { @@ -738,7 +757,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { } }, [server.id]); - useEffect(() => { loadAll(); }, [loadAll]); + useOnMount(loadAll); useTauriEvent<{ percent: number; currentFile: string; label: string }>( `backup://progress/${server.id}`, @@ -764,7 +783,8 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { setProgress({ active: true, percent: 0, currentFile: "", label: "Starting server backup…" }); try { const rec: BackupRecord = await tauriCmd.createServerBackup( - server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual" + server.id, server.name, server.install_path, mapPath, saveFolder, server.map_id, backupDir, "manual", + "", baseDir ); await insertBackup({ id: rec.id, server_id: rec.serverId, file_path: rec.filePath, @@ -788,7 +808,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { setProgress({ active: true, percent: 0, currentFile: "", label: "Starting player backups…" }); try { const records = await tauriCmd.backupAllPlayers( - server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual" + server.id, server.name, server.install_path, saveFolder, server.map_id, backupDir, "manual" ); if (records.length === 0) { toast.info("No player profiles found to back up."); @@ -864,13 +884,18 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { try { if (server.status === "running") { setProgress((p) => ({ ...p, label: "Stopping server…" })); - await tauriCmd.stopServer(server.id, true); - await new Promise((r) => setTimeout(r, 2000)); + // Graceful (RCON SaveWorld + doexit, same as the Stop button) rather + // than a raw kill signal, and this only resolves once the process is + // actually confirmed dead — no arbitrary fixed sleep needed, and no + // risk of restoring over files a still-exiting process is writing. + await stopServerGracefully(server, { + onInvalidate: () => queryClient.invalidateQueries({ queryKey: ["servers"] }), + }); } if (target.backup_type === "server") { - await tauriCmd.restoreServerBackup(server.id, target.file_path, server.install_path); + await tauriCmd.restoreServerBackup(server.id, target.file_path, server.install_path, baseDir, mapPath, saveFolder); } else if (target.backup_type === "player") { - await tauriCmd.restorePlayerBackup(server.id, target.file_path, server.install_path, mapPath); + await tauriCmd.restorePlayerBackup(server.id, target.file_path, server.install_path, saveFolder); } else if (target.backup_type === "full") { await tauriCmd.restoreFullBackup(server.id, target.file_path, server.install_path); } @@ -912,23 +937,22 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { const diskPaths = new Set(diskRecords.map((r) => r.filePath)); const dbPaths = new Set(allDb.map((r) => r.file_path)); - // Silently remove stale DB records (files no longer on disk). - for (const dbRec of allDb) { - if (!diskPaths.has(dbRec.file_path)) { - await deleteBackupRecord(dbRec.id).catch(() => {}); - } - } + // DB records whose file wasn't found on disk — held for confirmation + // rather than deleted immediately. If the backup directory is briefly + // unreachable, a scan returning few/no files must not silently wipe + // history for files that are actually still there. + const toDelete = allDb.filter((r) => !diskPaths.has(r.file_path)).map((r) => r.id); // Find disk files not yet in DB. const toImport = diskRecords.filter((r) => !dbPaths.has(r.filePath)); - if (toImport.length === 0) { + if (toImport.length === 0 && toDelete.length === 0) { toast.info("Backups are up to date."); await loadAll(); return; } - setSyncPending({ toImport }); + setSyncPending({ toImport, toDelete }); } catch (e) { toast.error(`Scan failed: ${e}`); } finally { @@ -938,10 +962,18 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { async function handleSyncConfirmed() { if (!syncPending) return; - const { toImport } = syncPending; + const { toImport, toDelete } = syncPending; setSyncPending(null); setSyncing(true); try { + for (const id of toDelete) { + await deleteBackupRecord(id).catch(() => {}); + } + if (toImport.length === 0) { + toast.success(`Removed ${toDelete.length} record${toDelete.length !== 1 ? "s" : ""} not found on disk.`); + await loadAll(); + return; + } // Load existing records so we know which higher tiers are already covered. const [dbSrv, dbPlr, dbFul] = await Promise.all([ getServerBackupsByType(server.id, "server"), @@ -995,7 +1027,8 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { seenByType[rec.backupType] = seen; } - toast.success(`Imported ${toImport.length} backup${toImport.length !== 1 ? "s" : ""}.`); + const deletedNote = toDelete.length > 0 ? `, removed ${toDelete.length} not found on disk` : ""; + toast.success(`Imported ${toImport.length} backup${toImport.length !== 1 ? "s" : ""}${deletedNote}.`); await loadAll(); } catch (e) { toast.error(`Import failed: ${e}`); @@ -1148,6 +1181,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { {syncPending && ( setSyncPending(null)} /> diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index c787133..c559ba3 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -1,10 +1,12 @@ "use client"; -import { useState, useEffect, useCallback } from "react"; +import { Fragment, useState, useEffect, useCallback } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { useSavedFlash } from "@/hooks/useSavedFlash"; import { Save, Code, LayoutList, RefreshCw, ChevronDown, ChevronRight, - Settings2, X, AlertCircle, ToggleLeft, ToggleRight, Terminal, - HelpCircle, Upload, Search, FileText, Clipboard, Wand2, + Settings2, X, ToggleLeft, ToggleRight, Terminal, + HelpCircle, Upload, FileText, Clipboard, Wand2, Sparkles, Package, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -16,13 +18,28 @@ import { DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, +} from "@/components/ui/dialog"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; import { tauriCmd, type ServerConfigJson } from "@/lib/tauri-commands"; import { INI_FIELD_GROUPS, LAUNCH_PARAMETERS, GAME_MODES, PRESET_STYLES, buildPresetConfig, ARK_EVENTS, type IniFieldDef, type LaunchParameter, } from "@/data/game-data"; -import { getServerConfig, saveServerConfig, updateServerShutdownSettings, updateServerRestartSettings, updateServerUpdateSettings, getAppSetting, setServerActiveEvent, getServers, copyServerConfig, updateServerMemoryLimit, type ServerRow } from "@/lib/db"; +import { useAllMaps } from "@/hooks/useAllMaps"; +import { getServerConfig, saveServerConfig, updateServerShutdownSettings, updateServerRestartSettings, updateServerUpdateSettings, getAppSetting, setServerActiveEvent, getServers, copyServerConfig, updateServerMemoryLimit, updateServerMap, updateServerAdminPassword, addServerMod, removeServerMod, setModMapLock, type ServerRow } from "@/lib/db"; import { toast } from "sonner"; import { NumberField } from "@/components/shared/NumberField"; import { open as openFilePicker } from "@tauri-apps/plugin-dialog"; @@ -32,12 +49,6 @@ interface Props { server: ServerRow; } -// Keys excluded from the "Full INI Editor" — handled on the server overview/setup pages. -const OVERVIEW_KEYS = new Set([ - "SessionName", "ServerPassword", "ServerAdminPassword", - "Port", "QueryPort", "RCONPort", "RCONEnabled", "MaxPlayers", -]); - // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- @@ -143,7 +154,8 @@ function FieldRow({ } if (field.type === "number" && field.min !== undefined && field.max !== undefined) { - const numVal = parseFloat(value) || 0; + const parsed = parseFloat(value); + const numVal = isNaN(parsed) ? (field.defaultValue as number ?? 0) : parsed; return (
@@ -153,7 +165,7 @@ function FieldRow({ min={field.min} max={field.max} step={field.step} - defaultValue={field.defaultValue} + defaultValue={typeof field.defaultValue === "number" ? field.defaultValue : undefined} />
); @@ -319,139 +331,6 @@ function SectionGroup({ ); } -// --------------------------------------------------------------------------- -// Full INI Editor Modal -// --------------------------------------------------------------------------- - -function FullIniModal({ - config, - onSave, - onClose, -}: { - config: ServerConfigJson; - onSave: (updated: ServerConfigJson) => void; - onClose: () => void; -}) { - const [local, setLocal] = useState(config); - const [expandedGroups, setExpandedGroups] = useState>(new Set()); - const [search, setSearch] = useState(""); - - const q = search.trim().toLowerCase(); - - const toggleGroup = (id: string) => - setExpandedGroups((prev) => { - const n = new Set(prev); - n.has(id) ? n.delete(id) : n.add(id); - return n; - }); - - const handleChange = (f: IniFieldDef, val: string) => { - setLocal((prev) => setIniValue(prev, f.section, f.iniSection, f.key, val)); - }; - - return ( -
-
- {/* Header */} -
-
- - Full INI Editor -
- -
- -
-

- - Server name, passwords, and ports are managed on the overview page and are excluded here. - Changes take effect on the next server restart. -

- {/* Search */} -
- - setSearch(e.target.value)} - placeholder="Search settings…" - className="h-8 pl-8 text-xs" - style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} - /> -
-
- - {/* Scrollable body */} -
- {INI_FIELD_GROUPS.map((group) => { - let visibleFields = group.fields.filter((f) => !OVERVIEW_KEYS.has(f.key)); - if (q) { - visibleFields = visibleFields.filter( - (f) => - f.label.toLowerCase().includes(q) || - f.key.toLowerCase().includes(q) || - (f.description?.toLowerCase().includes(q) ?? false), - ); - } - if (visibleFields.length === 0) return null; - const open = q ? true : expandedGroups.has(group.id); - return ( -
- - {open && ( -
- {visibleFields.map((f) => ( - handleChange(f, val)} - /> - ))} -
- )} -
- ); - })} -
- - {/* Footer */} -
- - -
-
-
- ); -} - // --------------------------------------------------------------------------- // Paste INI Modal // --------------------------------------------------------------------------- @@ -545,28 +424,159 @@ function PasteIniModal({ // --------------------------------------------------------------------------- type CustomSection = { - sectionName: string; // The [SectionName] key in Game.ini + sectionName: string; rows: { key: string; value: string }[]; }; +type SettingType = "string" | "boolean" | "integer" | "float"; + +function inferType(value: string): SettingType { + if (value === "True" || value === "False") return "boolean"; + if (/^-?\d+$/.test(value)) return "integer"; + if (/^-?\d*\.\d+$/.test(value)) return "float"; + return "string"; +} + +function defaultForType(t: SettingType): string { + if (t === "boolean") return "False"; + if (t === "integer") return "0"; + if (t === "float") return "0.0"; + return ""; +} + +// --------------------------------------------------------------------------- +// Dialog for adding a new setting to a mod section +// --------------------------------------------------------------------------- + +function AddSettingDialog({ + open, + onClose, + onAdd, +}: { + open: boolean; + onClose: () => void; + onAdd: (key: string, value: string) => void; +}) { + const [name, setName] = useState(""); + const [type, setType] = useState("string"); + + const handleAdd = () => { + const k = name.trim(); + if (!k) return; + onAdd(k, defaultForType(type)); + setName(""); + setType("string"); + onClose(); + }; + + return ( + { if (!v) onClose(); }}> + + + Add Setting + +
+
+ + setName(e.target.value)} + onKeyDown={(e) => { if (e.key === "Enter") handleAdd(); }} + placeholder="e.g. MaxDinos" + autoFocus + className="h-8 text-xs font-mono" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + /> +
+
+ + +
+

+ Initial value: {defaultForType(type) || '""'} +

+
+ + + + +
+
+ ); +} + +// --------------------------------------------------------------------------- +// Type-aware value editor for a single mod setting row +// --------------------------------------------------------------------------- + +function ModSettingValue({ + value, + onChange, +}: { + value: string; + onChange: (v: string) => void; +}) { + const type = inferType(value); + + if (type === "boolean") { + const checked = value === "True"; + return ( + + ); + } + + return ( + onChange(e.target.value)} + placeholder="Value" + className="h-7 text-xs font-mono flex-1" + style={{ background: "rgba(0,0,0,0.35)", borderColor: "rgba(var(--neon-purple-rgb),0.18)", color: "var(--text-primary)" }} + /> + ); +} + +// --------------------------------------------------------------------------- +// Custom mod sections editor +// --------------------------------------------------------------------------- + +// Standard GameUserSettings.ini sections this app already manages elsewhere — +// never touched by the custom mod-section editor below. +const GUS_STANDARD_SECTIONS = new Set([ + "serversettings", + "sessionsettings", + "messageoftheday", + "ragnarok", + "/script/engine.gamesession", +]); + function CustomModSections({ - gameIni, + gameUserSettings, onChange, }: { - gameIni: Record>; + gameUserSettings: Record>; onChange: (updated: Record>) => void; }) { - // Only show sections that are NOT standard ARK sections - const STANDARD_SECTIONS = new Set([ - "/script/shootergame.shootergamemode", - "ServerSettings", - "SessionSettings", - "MessageOfTheDay", - "Ragnarok", - ]); - - const customSections: CustomSection[] = Object.entries(gameIni) - .filter(([name]) => !STANDARD_SECTIONS.has(name.toLowerCase()) && !STANDARD_SECTIONS.has(name)) + const customSections: CustomSection[] = Object.entries(gameUserSettings) + .filter(([name]) => !GUS_STANDARD_SECTIONS.has(name.toLowerCase())) .map(([name, kvs]) => ({ sectionName: name, rows: Object.entries(kvs).map(([key, value]) => ({ key, value })), @@ -574,16 +584,15 @@ function CustomModSections({ const [newSectionName, setNewSectionName] = useState(""); const [deletingSection, setDeletingSection] = useState(null); + const [addSettingFor, setAddSettingFor] = useState(null); const commit = (sections: CustomSection[]) => { - const updated = { ...gameIni }; - // Remove all existing custom sections + const updated = { ...gameUserSettings }; for (const key of Object.keys(updated)) { - if (!STANDARD_SECTIONS.has(key.toLowerCase()) && !STANDARD_SECTIONS.has(key)) { + if (!GUS_STANDARD_SECTIONS.has(key.toLowerCase())) { delete updated[key]; } } - // Re-add from editor state for (const sec of sections) { if (!sec.sectionName.trim()) continue; updated[sec.sectionName] = Object.fromEntries( @@ -596,9 +605,8 @@ function CustomModSections({ const addSection = () => { const name = newSectionName.trim(); if (!name) return; - const updated = [...customSections, { sectionName: name, rows: [{ key: "", value: "" }] }]; + commit([...customSections, { sectionName: name, rows: [] }]); setNewSectionName(""); - commit(updated); }; const deleteSection = (idx: number) => { @@ -606,19 +614,19 @@ function CustomModSections({ setDeletingSection(null); }; - const updateRow = (secIdx: number, rowIdx: number, field: "key" | "value", val: string) => { + const addRowWithValue = (secIdx: number, key: string, value: string) => { const updated = customSections.map((sec, si) => - si !== secIdx ? sec : { - ...sec, - rows: sec.rows.map((row, ri) => ri !== rowIdx ? row : { ...row, [field]: val }), - }, + si !== secIdx ? sec : { ...sec, rows: [...sec.rows, { key, value }] }, ); commit(updated); }; - const addRow = (secIdx: number) => { + const updateRow = (secIdx: number, rowIdx: number, field: "key" | "value", val: string) => { const updated = customSections.map((sec, si) => - si !== secIdx ? sec : { ...sec, rows: [...sec.rows, { key: "", value: "" }] }, + si !== secIdx ? sec : { + ...sec, + rows: sec.rows.map((row, ri) => ri !== rowIdx ? row : { ...row, [field]: val }), + }, ); commit(updated); }; @@ -631,96 +639,98 @@ function CustomModSections({ }; return ( -
-
- Custom / Mod Settings (Game.ini) - New [SectionName] blocks for mods -
+ <> + {addSettingFor !== null && ( + setAddSettingFor(null)} + onAdd={(key, value) => addRowWithValue(addSettingFor, key, value)} + /> + )} -
- {customSections.length === 0 && ( -

- No custom sections yet. Add one below to configure mod-specific INI settings. -

- )} +
+
+
+ Mod Settings +

Custom GameUserSettings.ini sections for mods — add a section per mod, then add its settings.

+
+
- {customSections.map((sec, si) => ( -
-
- [{sec.sectionName}] - {deletingSection === sec.sectionName ? ( -
- Delete this section? - - -
- ) : ( - - )} -
-
- {sec.rows.map((row, ri) => ( -
- updateRow(si, ri, "key", e.target.value)} - placeholder="Key" - className="h-7 text-xs font-mono flex-1" - style={{ background: "rgba(0,0,0,0.35)", borderColor: "rgba(var(--neon-purple-rgb),0.18)", color: "var(--text-primary)" }} - /> - = - updateRow(si, ri, "value", e.target.value)} - placeholder="Value" - className="h-7 text-xs font-mono flex-1" - style={{ background: "rgba(0,0,0,0.35)", borderColor: "rgba(var(--neon-purple-rgb),0.18)", color: "var(--text-primary)" }} - /> - + +
+ ) : ( + -
- ))} - + )} +
+ +
+ {sec.rows.length === 0 && ( +

No settings yet — click "Add Setting" below.

+ )} + {sec.rows.map((row, ri) => ( +
+ {row.key} + = +
+ updateRow(si, ri, "value", v)} /> +
+ +
+ ))} + +
-
- ))} + ))} - {/* Add new section */} -
- setNewSectionName(e.target.value)} - onKeyDown={(e) => { if (e.key === "Enter") addSection(); }} - placeholder="New section name (e.g. MyMod)" - className="h-7 text-xs font-mono flex-1" - style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} - /> - + {/* Add new section */} +
+ setNewSectionName(e.target.value)} + onKeyDown={(e) => { if (e.key === "Enter") addSection(); }} + placeholder="New section name (e.g. MyMod)" + className="h-8 text-xs font-mono flex-1" + style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(180,100,255,0.25)", color: "var(--text-primary)" }} + /> + +
-

- Custom sections are written directly to Game.ini alongside standard settings. -

-
+ ); } @@ -907,20 +917,20 @@ function QuickSetupModal({ // Active Event card // --------------------------------------------------------------------------- -function EventCard({ server }: { server: ServerRow }) { +function ActiveEventCard({ server }: { server: ServerRow }) { + const queryClient = useQueryClient(); const [activeEventId, setActiveEventId] = useState(server.active_event ?? null); const [saving, setSaving] = useState(false); - const [saved, setSaved] = useState(false); const currentEvent = ARK_EVENTS.find((e) => e.id === activeEventId) ?? null; - const handleSelect = async (eventId: string | null) => { - setActiveEventId(eventId); + const handleSelect = async (val: string) => { + const newId = val === "none" ? null : val; + setActiveEventId(newId); setSaving(true); try { - await setServerActiveEvent(server.id, eventId); - setSaved(true); - setTimeout(() => setSaved(false), 2000); + await setServerActiveEvent(server.id, newId); + queryClient.invalidateQueries({ queryKey: ["servers"] }); } catch (e) { toast.error(`Failed to save event: ${e}`); } finally { @@ -930,77 +940,84 @@ function EventCard({ server }: { server: ServerRow }) { return (
-
-
- 🎃 -

Active Event

+
+
+ +
+

Active Event

+

+ Loads the event mod and passes -ActiveEvent= on next server start. +

+
+
+
+ {saving && Saving…} +
- {saved && Saved} - {saving && !saved && Saving…} -
- -

- Activating an event auto-loads its mod on server start and passes -ActiveEvent= to the launcher. - The mod will be locked in the mod list while the event is active. -

- -
- - {ARK_EVENTS.map((evt) => ( - - ))}
- {currentEvent && ( -
- {currentEvent.description} - Mod: {currentEvent.modId} -
+

+ {currentEvent.description} Mod: {currentEvent.modId} +

)}
); } -function ShutdownSettingsCard({ server }: { server: ServerRow }) { - const [warnPlayers, setWarnPlayers] = useState(server.shutdown_warn_players !== 0); - const [warnMinutes, setWarnMinutes] = useState(server.shutdown_warn_minutes ?? 5); - const [message, setMessage] = useState( - server.shutdown_message || "Server will shut down in {time}." - ); +/** + * Shared shape behind Shutdown/Restart/Update Warning cards — previously + * three independent ~90-line copies differing only in which + * `updateServer*Settings` DB call they made, their copy, and whether a + * Cancel Message field applies (Shutdown has no countdown to cancel). + */ +function WarningSettingsCard({ + sectionId, title, description, warnLabel, messageLabel, messagePlaceholder, + cancelMessagePlaceholder, initialWarnPlayers, initialWarnMinutes, initialMessage, + initialCancelMessage, errorLabel, onSave, +}: { + sectionId?: string; + title: string; + description: string; + warnLabel: string; + messageLabel: string; + messagePlaceholder: string; + /** Omit to hide the Cancel Message field. */ + cancelMessagePlaceholder?: string; + initialWarnPlayers: boolean; + initialWarnMinutes: number; + initialMessage: string; + initialCancelMessage?: string; + errorLabel: string; + onSave: (params: { warnPlayers: boolean; warnMinutes: number; message: string; cancelMessage: string }) => Promise; +}) { + const [warnPlayers, setWarnPlayers] = useState(initialWarnPlayers); + const [warnMinutes, setWarnMinutes] = useState(initialWarnMinutes); + const [message, setMessage] = useState(initialMessage); + const [cancelMessage, setCancelMessage] = useState(initialCancelMessage ?? ""); const [saving, setSaving] = useState(false); - const [saved, setSaved] = useState(false); + const [saved, triggerSaved] = useSavedFlash(); const handleSave = async () => { setSaving(true); try { - await updateServerShutdownSettings(server.id, warnPlayers, warnMinutes, message); - setSaved(true); - setTimeout(() => setSaved(false), 2000); + await onSave({ warnPlayers, warnMinutes, message, cancelMessage }); + triggerSaved(); } catch (e) { - toast.error(`Failed to save shutdown settings: ${e}`); + toast.error(`Failed to save ${errorLabel}: ${e}`); } finally { setSaving(false); } @@ -1008,13 +1025,15 @@ function ShutdownSettingsCard({ server }: { server: ServerRow }) { return (
-

Graceful Shutdown

+

{title}

+

{description}

@@ -1042,16 +1059,28 @@ function ShutdownSettingsCard({ server }: { server: ServerRow }) {
setMessage(e.target.value)} - placeholder="Server will shut down in {time}." + placeholder={messagePlaceholder} className="h-7 text-xs" style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} />
+ {cancelMessagePlaceholder !== undefined && ( +
+ + setCancelMessage(e.target.value)} + placeholder={cancelMessagePlaceholder} + className="h-7 text-xs" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + /> +
+ )}
-
+ { + await updateServerRestartSettings(server.id, warnPlayers, warnMinutes, message, cancelMessage); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + }} + /> ); } -// --------------------------------------------------------------------------- -// Update Warning Settings Card -// --------------------------------------------------------------------------- - function UpdateSettingsCard({ server }: { server: ServerRow }) { - const [warnPlayers, setWarnPlayers] = useState(server.update_warn_players !== 0); - const [warnMinutes, setWarnMinutes] = useState(server.update_warn_minutes ?? 5); - const [message, setMessage] = useState(server.update_message || "Server going down for update in {time}."); - const [cancelMessage, setCancelMessage] = useState(server.update_cancel_message || "Update has been canceled."); - const [saving, setSaving] = useState(false); - const [saved, setSaved] = useState(false); - - const handleSave = async () => { - setSaving(true); - try { - await updateServerUpdateSettings(server.id, warnPlayers, warnMinutes, message, cancelMessage); - setSaved(true); - setTimeout(() => setSaved(false), 2000); - } catch (e) { - toast.error(`Failed to save update settings: ${e}`); - } finally { - setSaving(false); - } - }; - + const queryClient = useQueryClient(); return ( -
-
- -

Update Warning

-
- - - -
-
- - setWarnMinutes(parseInt(e.target.value, 10) || 5)} - className="h-7 w-24 text-xs" - style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} - /> -
-
- - setMessage(e.target.value)} - placeholder="Server going down for update in {time}." - className="h-7 text-xs" - style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} - /> -
-
- - setCancelMessage(e.target.value)} - placeholder="Update has been canceled." - className="h-7 text-xs" - style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} - /> -
-
- - -
+ { + await updateServerUpdateSettings(server.id, warnPlayers, warnMinutes, message, cancelMessage); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + }} + /> ); } @@ -1328,7 +1228,7 @@ function AdvancedConfigTab({ value={currentThread} onChange={(e) => handleThreadChange(e.target.value)} className="w-full text-xs rounded-lg px-2 py-1.5" - style={{ background: "rgba(10,10,30,0.8)", border: "1px solid rgba(255,165,0,0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", border: "1px solid rgba(255,165,0,0.3)", color: "var(--text-primary)" }} > {THREAD_OPTIONS.map((o) => )} @@ -1365,7 +1265,7 @@ function AdvancedConfigTab({ onChange={(e) => setArg("_customCli", e.target.value)} placeholder="-SomeFlag -AnotherFlag=value" className="font-mono text-xs" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(255,165,0,0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(255,165,0,0.3)", color: "var(--text-primary)" }} />
@@ -1384,7 +1284,7 @@ function AdvancedConfigTab({ min={1} step={0.5} className="w-32 text-xs" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(255,165,0,0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(255,165,0,0.3)", color: "var(--text-primary)" }} /> GB
))} @@ -1422,15 +1322,16 @@ function AdvancedConfigTab({ } export function ConfigTab({ server }: Props) { + const queryClient = useQueryClient(); + const allMaps = useAllMaps(); const [config, setConfig] = useState(null); const [rawGus, setRawGus] = useState(""); const [rawGame, setRawGame] = useState(""); - const [rawMode, setRawMode] = useState(false); - const [advancedMode, setAdvancedMode] = useState(false); + const [activeTab, setActiveTab] = useState<"settings" | "mods" | "advanced" | "raw">("settings"); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [readingIni, setReadingIni] = useState(false); - const [savedFlash, setSavedFlash] = useState(false); + const [savedFlash, triggerSavedFlash] = useSavedFlash(); const [isDirty, setIsDirty] = useState(false); const [error, setError] = useState(null); const [showPasteModal, setShowPasteModal] = useState(false); @@ -1527,20 +1428,26 @@ export function ConfigTab({ server }: Props) { const text = await readTextFile(selected); const sections = rawTextToSections(text); if (!config) return; - // Determine which file was picked by looking at key section names - const isGus = Object.keys(sections).some((s) => - ["ServerSettings", "SessionSettings", "MessageOfTheDay", "Ragnarok"].includes(s), - ); - const isGame = Object.keys(sections).some((s) => - s.toLowerCase().includes("shootergame"), - ); + // Route each section to its file individually — an imported file + // containing sections that belong to both files (a combined export, + // or a custom mod section whose name happens to mention "shootergame") + // must not dump its entire contents into both; only Game.ini actually + // uses "/script/shootergame..." sections, everything else is GUS. + const gusSections: Record> = {}; + const gameSections: Record> = {}; + for (const [name, kv] of Object.entries(sections)) { + if (name.toLowerCase().startsWith("/script/shootergame")) { + gameSections[name] = kv; + } else { + gusSections[name] = kv; + } + } setConfig((prev) => { if (!prev) return prev; return { ...prev, - ...(isGus ? { gameUserSettings: { ...(prev.gameUserSettings as Record>), ...sections } } : {}), - ...(isGame ? { gameIni: { ...(prev.gameIni as Record>), ...sections } } : {}), - ...(!isGus && !isGame ? { gameUserSettings: { ...(prev.gameUserSettings as Record>), ...sections } } : {}), + gameUserSettings: { ...(prev.gameUserSettings as Record>), ...gusSections }, + gameIni: { ...(prev.gameIni as Record>), ...gameSections }, }; }); setIsDirty(true); @@ -1588,7 +1495,7 @@ export function ConfigTab({ server }: Props) { setError(null); try { let toSave = toWrite; - if (rawMode && !cfg) { + if (activeTab === "raw" && !cfg) { toSave = { ...toWrite, gameUserSettings: rawTextToSections(rawGus), @@ -1600,16 +1507,40 @@ export function ConfigTab({ server }: Props) { } // Write to disk await tauriCmd.writeServerConfig(server.install_path, toSave); - // Persist to DB so Config tab loads our version next time, not the server's overwrite - await saveServerConfig( - server.id, - JSON.stringify(toSave.gameUserSettings), - JSON.stringify(toSave.gameIni), - JSON.stringify(toSave.launchArgs ?? {}), - ); + // Persist to DB so Config tab loads our version next time, not the + // server's overwrite. This can't be made truly atomic with the disk + // write above (different systems), so on failure here we give a + // distinct message: the file IS already updated, only the DB record + // of it failed — the reload-from-DB path would otherwise silently + // revert the file back next time this tab loads. + try { + await saveServerConfig( + server.id, + JSON.stringify(toSave.gameUserSettings), + JSON.stringify(toSave.gameIni), + JSON.stringify(toSave.launchArgs ?? {}), + ); + } catch (dbErr) { + throw new Error( + `Config was written to disk, but saving it to the app database failed: ${dbErr}. ` + + `Click Save again — your disk changes are already applied and will not be lost by retrying.` + ); + } + + // admin_password is the single source of truth for both the INI value and + // RCON auth. If this save changed ServerAdminPassword (e.g. via the raw + // editor), keep the DB in sync so RCON doesn't silently start failing — + // then bounce the live RCON connection so it reconnects with the new + // password immediately instead of waiting for the next failed command. + const newAdminPassword = (toSave.gameUserSettings as Record>) + ?.ServerSettings?.ServerAdminPassword; + if (newAdminPassword && newAdminPassword !== server.admin_password) { + await updateServerAdminPassword(server.id, newAdminPassword); + tauriCmd.rconDisconnect(server.id).catch(() => {}); + } + setIsDirty(false); - setSavedFlash(true); - setTimeout(() => setSavedFlash(false), 2000); + triggerSavedFlash(); // Snapshot INI files into the backup system (best-effort, non-blocking) const backupDir = await getAppSetting("backup_dir").catch(() => null); @@ -1628,15 +1559,60 @@ export function ConfigTab({ server }: Props) { setRawGus(configToRawText(config.gameUserSettings as Record>)); setRawGame(configToRawText(config.gameIni as Record>)); } - setRawMode(true); + setActiveTab("raw"); }; - const switchToStructured = () => { + const handleMapChange = async (newMapId: string) => { + if (server.status !== "stopped") { + toast.error("Server must be stopped to change maps"); + return; + } + try { + const baseDir = await getAppSetting("base_dir"); + if (!baseDir) { + toast.error("Base directory not configured"); + return; + } + const newMapData = allMaps.find((m) => m.id === newMapId); + if (!newMapData) { + toast.error("Map not found"); + return; + } + const oldMapData = allMaps.find((m) => m.id === server.map_id); + // Update the SaveGames symlink for the new map + await tauriCmd.createModsSavesLink(server.install_path, server.id, baseDir, newMapData.mapPath); + // Update the database + await updateServerMap(server.id, newMapId); + + // Swap the map-required mod: the old map's required mod is dropped + // from the list entirely (unless the new map needs the exact same + // mod) — mirrors the wizard's handleMapSelect, which drops the + // previous map's mod from the list the same way when switching maps + // pre-creation. The new map's required mod is added/locked so it + // can't be disabled or removed from the Mods tab while selected. + if (oldMapData?.isMod && oldMapData.requiredModId && oldMapData.requiredModId !== newMapData.requiredModId) { + await removeServerMod(server.id, oldMapData.requiredModId); + } + if (newMapData.isMod && newMapData.requiredModId) { + // The map's required mod never goes through the "paste ID" + // CurseForge verification, so it has no real name available — fall + // back to the custom/mod map's own display name instead of a bare + // "Unknown Mod". + await addServerMod(server.id, newMapData.requiredModId, newMapData.displayName); + await setModMapLock(server.id, newMapData.requiredModId, true); + } + + queryClient.invalidateQueries({ queryKey: ["servers"] }); + toast.success(`Map changed to ${newMapData.displayName}`); + } catch (e) { + toast.error(`Failed to change map: ${e}`); + } + }; + + const switchFromRaw = () => { const gus = rawTextToSections(rawGus); const game = rawTextToSections(rawGame); if (config) setConfig({ ...config, gameUserSettings: gus, gameIni: game }); - setRawMode(false); - setAdvancedMode(false); }; if (loading) { @@ -1660,18 +1636,27 @@ export function ConfigTab({ server }: Props) { {/* Tab selectors */}
+
)} - {/* ── Structured view — ALL INI groups ──────────────────────────────── */} - {!rawMode && config && ( + {/* ── Settings view — all INI field groups plus session/warning settings ── */} + {activeTab === "settings" && config && (
+ {/* Map Selector */} +
+
+
+

Server Map

+

+ Current map: {allMaps.find((m) => m.id === server.map_id)?.displayName ?? server.map_id} +

+
+ {server.status !== "stopped" && ( +
+ Stop to change +
+ )} +
+ +
+ + {/* INI Field Groups — Active Event slots in right after Session, since + it's session-scoped state (like the map/name/password above it) + even though it isn't an INI field. */} {INI_FIELD_GROUPS.map((g, idx) => ( - + + + {g.id === "session" && } + ))} - >} - onChange={(updated) => { - setConfig({ ...config, gameIni: updated }); - setIsDirty(true); - }} - /> + + {/* Warnings — governs both the manual action buttons and (for + restart/update) their scheduled counterparts in the Automation tab. */} +
+

Warnings

+
+ + +
)} + {/* ── Mod Settings tab ─────────────────────────────────────────────── */} + {activeTab === "mods" && config && ( + >} + onChange={(updated) => { + setConfig({ ...config, gameUserSettings: updated }); + setIsDirty(true); + }} + /> + )} + + {/* ── Advanced tab ──────────────────────────────────────────────────── */} + {activeTab === "advanced" && config && ( + { setConfig({ ...config, ...patch }); setIsDirty(true); }} /> + )} + {/* ── Raw INI editor ────────────────────────────────────────────────── */} - {rawMode && ( + {activeTab === "raw" && (

GameUserSettings.ini

@@ -1809,17 +1846,6 @@ export function ConfigTab({ server }: Props) {
)} - {/* ── Advanced tab ──────────────────────────────────────────────────── */} - {advancedMode && config && ( - { setConfig({ ...config, ...patch }); setIsDirty(true); }} /> - )} - - {/* ── Server behaviour cards (always visible) ───────────────────────── */} - - - - - {/* Paste INI modal */} {showPasteModal && ( setCopyFromServerId(e.target.value)} className="w-full text-xs rounded-lg px-2 py-1.5" - style={{ background: "rgba(10,10,30,0.8)", border: "1px solid rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", border: "1px solid rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} > {otherServers.map((s) => ( diff --git a/src/components/server/tabs/LogsTab.tsx b/src/components/server/tabs/LogsTab.tsx index 97cbd86..1faf805 100644 --- a/src/components/server/tabs/LogsTab.tsx +++ b/src/components/server/tabs/LogsTab.tsx @@ -13,6 +13,7 @@ import type { ArchivedLogInfo, CrashInfo, CrashReport, ChatLogInfo, OtherLogInfo, RconLogLine, } from "@/lib/tauri-commands"; import { useTauriEvent } from "@/hooks/useTauriEvent"; +import { useOnMount } from "@/hooks/useOnMount"; import { getKnownPlayers, getPlayerKnownIps, getPlayerConnectionHistory, getPossibleAlts, type PlayerConnectionRow, @@ -166,17 +167,26 @@ function LivePanel({ server }: { server: ServerRow }) { } }, [server.id]); + // Reset display state the moment we transition to active — compared during + // render rather than inside the effect below, since it's a synchronous + // reset with no async work of its own. + const [wasActive, setWasActive] = useState(isActive); + if (isActive !== wasActive) { + setWasActive(isActive); + if (isActive) { + setLastSessionFilename(null); + setLines([]); + setReady(false); + } + } + // Single effect that registers both event listeners BEFORE starting the watcher. // This eliminates a race where the Rust watcher emits the backfill event before // the frontend listeners are ready (the Tauri listen() IPC is async/microtask, // so a synchronous watchServerLog call would arrive at Rust first, causing the // backfill to be emitted with no registered listeners and silently dropped). - useEffect(() => { + const syncWatcher = useCallback(() => { if (isActive) { - setLastSessionFilename(null); - setLines([]); - setReady(false); - let cancelled = false; let unlistenBackfill: (() => void) | undefined; let unlistenLine: (() => void) | undefined; @@ -219,13 +229,18 @@ function LivePanel({ server }: { server: ServerRow }) { cancelled = true; unlistenBackfill?.(); unlistenLine?.(); + // Stop the Rust-side file watcher too — without this, switching away + // from the Live tab (or navigating off the page) while the server is + // still running leaves it tailing the log file indefinitely, and + // reopening Live starts a second watcher on top of it. + tauriCmd.stopLogWatch(server.id).catch(() => null); }; } else { tauriCmd.stopLogWatch(server.id).catch(() => null); loadLastSession(); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [server.id, isActive]); + }, [server.id, server.install_path, isActive, loadLastSession]); + useOnMount(syncWatcher); // Auto-scroll on new live lines and when last-session content is first loaded. useEffect(() => { @@ -392,7 +407,7 @@ function ArchivePanel({ server }: { server: ServerRow }) { finally { setLoading(false); } }, [server.id]); - useEffect(() => { load(); }, [load]); + useOnMount(load); const openFile = useCallback(async (filename: string, type: "shootergame" | "other") => { setSelected({ filename, type }); @@ -580,7 +595,7 @@ function CrashesPanel({ server }: { server: ServerRow }) { finally { setLoading(false); } }, [server.id]); - useEffect(() => { load(); }, [load]); + useOnMount(load); const openCrash = useCallback(async (crash: CrashInfo) => { setSelected(crash); @@ -717,7 +732,7 @@ function ChatPanel({ server }: { server: ServerRow }) { finally { setLoading(false); } }, [server.id]); - useEffect(() => { load(); }, [load]); + useOnMount(load); const openFile = useCallback(async (info: ChatLogInfo) => { setSelected(info); @@ -730,10 +745,10 @@ function ChatPanel({ server }: { server: ServerRow }) { finally { setLoadingFile(false); } }, [server.id]); - useEffect(() => { + const autoSelectFirst = useCallback(() => { if (chatLogs.length > 0 && !selected) openFile(chatLogs[0]); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [chatLogs]); + }, [chatLogs, selected, openFile]); + useOnMount(autoSelectFirst); // Live-append incoming chat lines so the panel updates without manual refresh. const todayFilename = `chat_${new Date().toISOString().slice(0, 10)}.log`; @@ -829,24 +844,47 @@ function PlayersPanel({ server }: { server: ServerRow }) { const [knownIps, setKnownIps] = useState<{ ip: string; lastSeen: string }[]>([]); const [history, setHistory] = useState([]); const [alts, setAlts] = useState<{ eosId: string; sharedIps: string[] }[]>([]); - const [loading, setLoading] = useState(false); + // Derived by comparing the requested player against the last completed + // fetch, rather than an explicit setLoading(true) at the top of the effect. + const [loadedEosId, setLoadedEosId] = useState(""); + const loading = !!selectedEosId && selectedEosId !== loadedEosId; useEffect(() => { getKnownPlayers(server.id).then(setKnownPlayers).catch(() => {}); }, [server.id]); + // Clear the previous player's data the moment the selection changes — + // compared during render rather than inside the effect below. + const [prevSelectedEosId, setPrevSelectedEosId] = useState(selectedEosId); + if (selectedEosId !== prevSelectedEosId) { + setPrevSelectedEosId(selectedEosId); + if (!selectedEosId) { + setKnownIps([]); setHistory([]); setAlts([]); + } + } + + // Guards against an older, slower-resolving fetch (e.g. from rapidly + // switching the selected player) overwriting a newer one's result if + // responses arrive out of order. + const playerReqIdRef = useRef(0); useEffect(() => { - if (!selectedEosId) { setKnownIps([]); setHistory([]); setAlts([]); return; } - setLoading(true); + if (!selectedEosId) return; + const eosId = selectedEosId; + const reqId = ++playerReqIdRef.current; Promise.all([ - getPlayerKnownIps(server.id, selectedEosId), - getPlayerConnectionHistory(server.id, selectedEosId, 200), - getPossibleAlts(server.id, selectedEosId), + getPlayerKnownIps(server.id, eosId), + getPlayerConnectionHistory(server.id, eosId, 200), + getPossibleAlts(server.id, eosId), ]).then(([ips, hist, altList]) => { + if (reqId !== playerReqIdRef.current) return; setKnownIps(ips); setHistory(hist); setAlts(altList); - }).catch(() => {}).finally(() => setLoading(false)); + setLoadedEosId(eosId); + }).catch(() => { + if (reqId !== playerReqIdRef.current) return; + setLoadedEosId(eosId); + }); }, [server.id, selectedEosId]); const nameFor = (eosId: string) => diff --git a/src/components/server/tabs/MaintenanceTab.tsx b/src/components/server/tabs/MaintenanceTab.tsx new file mode 100644 index 0000000..23e3ff3 --- /dev/null +++ b/src/components/server/tabs/MaintenanceTab.tsx @@ -0,0 +1,358 @@ +"use client"; + +import { useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { + ShieldCheck, RotateCcw, X, Save, Loader2, FolderOpen, +} from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { + Select, SelectContent, SelectItem, SelectTrigger, SelectValue, +} from "@/components/ui/select"; +import { + Dialog, DialogContent, DialogDescription, + DialogFooter, DialogHeader, DialogTitle, +} from "@/components/ui/dialog"; +import { tauriCmd } from "@/lib/tauri-commands"; +import { getAppSetting, getServers } from "@/lib/db"; +import { reinstallServer } from "@/lib/server-actions"; +import { getSaveFolder } from "@/data/game-data"; +import { useAllMaps } from "@/hooks/useAllMaps"; +import type { ServerRow } from "@/lib/db"; + +interface Props { + server: ServerRow; +} + +// --------------------------------------------------------------------------- +// Verify Files card — re-validates the shared cache against Steam then +// re-syncs it to this server (skips ShooterGame/Saved, so world/config data +// is never touched). Same command the old Overview "Verify Files" button used. +// --------------------------------------------------------------------------- + +function VerifyFilesCard({ server }: Props) { + const [validating, setValidating] = useState(false); + const isRunning = server.status === "running"; + + const handleVerify = async () => { + setValidating(true); + try { + const [steamcmdPath, baseDir] = await Promise.all([ + getAppSetting("steamcmd_path"), + getAppSetting("base_dir"), + ]); + if (!steamcmdPath) { toast.error("SteamCMD path not configured"); return; } + if (!baseDir) { toast.error("Base directory not configured"); return; } + const sep = baseDir.includes("\\") ? "\\" : "/"; + const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; + await tauriCmd.validateServerFiles(server.id, server.install_path, cacheDir, steamcmdPath); + toast.success("Game files verified"); + } catch (e) { + toast.error(`Validation failed: ${e}`); + } finally { + setValidating(false); + } + }; + + return ( +
+
+ +

Verify Files

+
+

+ Re-checks the shared cache against Steam (re-downloading anything missing or corrupted), then + re-syncs it to this server. Never touches ShooterGame/Saved — + your world data and INI configs are untouched. Use this if a server was left in an unclear state + after an interrupted update. +

+
+ + +
+
+ ); +} + +// --------------------------------------------------------------------------- +// Reinstall card — always-available recovery action, not gated behind a +// failure status like the server card's Reinstall button. +// --------------------------------------------------------------------------- + +function ReinstallCard({ server }: Props) { + const queryClient = useQueryClient(); + const [confirming, setConfirming] = useState(false); + const [reinstalling, setReinstalling] = useState(false); + const isRunning = server.status === "running" || server.status === "starting"; + + const handleReinstall = async () => { + setReinstalling(true); + setConfirming(false); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + try { + // reinstallServer already dispatches a success/failure notification + // (which shows its own toast) — no need to show a second one here. + await reinstallServer(server); + } catch { + // Failure notification already dispatched by reinstallServer. + } finally { + setReinstalling(false); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + }; + + return ( +
+
+ +

Reinstall

+
+

+ Re-copies the full shared cache to this server's install folder. Preserves{" "} + ShooterGame/Saved — safe to run on a server with existing save + data. Use this if the install looks corrupted or incomplete and Verify Files didn't resolve it. +

+ {confirming ? ( +
+ + +
+ ) : ( + + )} +
+ ); +} + +// --------------------------------------------------------------------------- +// Wipe Save Data card +// --------------------------------------------------------------------------- + +function WipeSaveDataCard({ server }: Props) { + const allMaps = useAllMaps(); + const [wipeConfirm, setWipeConfirm] = useState<"map" | "players" | "full" | null>(null); + const [wiping, setWiping] = useState(false); + const isRunning = server.status === "running"; + + const handleWipe = async (tier: "map" | "players" | "full") => { + setWiping(true); + const mapDef = allMaps.find((m) => m.id === server.map_id); + const saveFolder = mapDef ? getSaveFolder(mapDef) : server.map_id; + try { + await tauriCmd.wipeServerSaves(server.id, server.install_path, saveFolder, tier); + setWipeConfirm(null); + toast.success(`Save wipe complete (${tier})`); + } catch (e) { + toast.error(`Save wipe failed: ${e}`); + } finally { + setWiping(false); + } + }; + + return ( +
+
+ +

Wipe Save Data

+
+

+ Permanently delete save files. This cannot be undone. Take a backup first. +

+ + {isRunning ? ( +

Stop the server before wiping save data.

+ ) : wipeConfirm ? ( +
+

+ {wipeConfirm === "map" && "Wipe Map Data — this will delete all world state (*.ark). Character and tribe data will be preserved."} + {wipeConfirm === "players" && "Wipe Player & Tribe Data — this will delete all character profiles and tribe records. World state will be preserved."} + {wipeConfirm === "full" && "Full Wipe — this will delete ALL save data including world, characters, tribes, and mod data. This is irreversible."} +

+
+ + +
+
+ ) : ( +
+ + + +
+ )} +
+ ); +} + +// --------------------------------------------------------------------------- +// Import Saves card +// --------------------------------------------------------------------------- + +function ImportSavesCard({ server }: Props) { + const allMaps = useAllMaps(); + const [showImport, setShowImport] = useState(false); + const [importSourceId, setImportSourceId] = useState(""); + const [importing, setImporting] = useState(false); + const [importServers, setImportServers] = useState([]); + const isRunning = server.status === "running"; + + const openImportDialog = async () => { + const all = await getServers(); + setImportServers(all.filter((s) => s.id !== server.id && s.status === "stopped" && s.map_id === server.map_id)); + setImportSourceId(""); + setShowImport(true); + }; + + const handleImport = async () => { + if (!importSourceId) return; + setImporting(true); + try { + const baseDir = await getAppSetting("base_dir"); + if (!baseDir) throw new Error("Base directory not configured"); + const mapDef = allMaps.find((m) => m.id === server.map_id); + const saveFolder = mapDef ? getSaveFolder(mapDef) : server.map_id; + await tauriCmd.importServerSaves(importSourceId, server.id, baseDir, saveFolder); + setShowImport(false); + toast.success("Save data imported successfully"); + } catch (e) { + toast.error(`Import failed: ${e}`); + } finally { + setImporting(false); + } + }; + + return ( +
+
+ +

Import Saves

+
+

+ Copy the current map's save data from another stopped server into this one. Existing saves will be replaced. +

+ + + !v && setShowImport(false)}> + + + Import Save Data + + Select a stopped server to copy its {allMaps.find((m) => m.id === server.map_id)?.mapPath ?? server.map_id} save + folder into {server.name}. Only stopped servers with the same map are shown. + Existing saves will be overwritten. + + +
+ {importServers.length === 0 ? ( +

+ No other stopped servers found. Stop the source server before importing. +

+ ) : ( + + )} +
+ + + + +
+
+
+ ); +} + +// --------------------------------------------------------------------------- +// MaintenanceTab +// --------------------------------------------------------------------------- + +export function MaintenanceTab({ server }: Props) { + return ( +
+ + + + +
+ ); +} diff --git a/src/components/server/tabs/ModsTab.tsx b/src/components/server/tabs/ModsTab.tsx index 2d5535f..bfee1bc 100644 --- a/src/components/server/tabs/ModsTab.tsx +++ b/src/components/server/tabs/ModsTab.tsx @@ -1,6 +1,7 @@ "use client"; -import { useState, useEffect, useRef } from "react"; +import { useState, useEffect, useRef, useCallback } from "react"; +import { useOnMount } from "@/hooks/useOnMount"; import { Package, Plus, Trash2, ChevronUp, ChevronDown, Globe, AlertCircle, RefreshCw, ToggleLeft, ToggleRight, Info, HelpCircle, X, @@ -62,7 +63,7 @@ function CopyModsCard({ serverId, onCopied }: { serverId: string; onCopied: () = value={selectedId} onChange={(e) => setSelectedId(e.target.value)} className="w-full text-xs rounded-lg px-2 py-1.5" - style={{ background: "rgba(10,10,30,0.8)", border: "1px solid rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", border: "1px solid rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} > {servers.map((s) => ( @@ -90,9 +91,9 @@ export function ModsTab({ server }: Props) { const [addInput, setAddInput] = useState(""); const [addError, setAddError] = useState(""); - const markChanged = () => { + const markChanged = useCallback(() => { if (server.status === "running") setShowRestartNote(true); - }; + }, [server.status]); const addInputRef = useRef(null); const prevVerifyingRef = useRef(false); @@ -110,7 +111,7 @@ export function ModsTab({ server }: Props) { const stopVerifying = useAppStore((s) => s.stopVerifying); // ── Load mods from SQLite ────────────────────────────────────────────── - const loadMods = async () => { + const loadMods = useCallback(async () => { setLoading(true); try { const rows = await getServerMods(server.id); @@ -120,22 +121,24 @@ export function ModsTab({ server }: Props) { } finally { setLoading(false); } - }; + }, [server.id]); - useEffect(() => { loadMods(); }, [server.id]); // eslint-disable-line react-hooks/exhaustive-deps + useOnMount(loadMods); // Real-time update: a mod was added via the browser window - useEffect(() => { + const syncOnModAdded = useCallback(() => { if (modAddedCount > 0) { loadMods(); markChanged(); } - }, [modAddedCount]); // eslint-disable-line react-hooks/exhaustive-deps + }, [modAddedCount, loadMods, markChanged]); + useOnMount(syncOnModAdded); // Reload when the browser window is closed (safety net for any missed events) - useEffect(() => { + const syncOnBrowserClosed = useCallback(() => { if (modBrowserJustClosed) { loadMods(); setModBrowserJustClosed(false); } - }, [modBrowserJustClosed]); // eslint-disable-line react-hooks/exhaustive-deps + }, [modBrowserJustClosed, loadMods, setModBrowserJustClosed]); + useOnMount(syncOnBrowserClosed); // Clear the add input when verification finishes useEffect(() => { @@ -445,7 +448,7 @@ export function ModsTab({ server }: Props) { ) : ( <> Opens CurseForge in a separate window with a - "+ Add Mod"{" "} + "+ Add Mod"{" "} button on each mod page. )} diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index ae67bbf..df21108 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -5,7 +5,7 @@ import { useRouter } from "next/navigation"; import { Play, Square, RotateCcw, Users, Cpu, MemoryStick, Clock, Save, RefreshCw, ArrowUp, Loader2, X, BarChart2, FolderOpen, - Zap, Settings2, Terminal, Skull, CheckCircle2, ShieldCheck, + Settings2, Terminal, Skull, ChevronDown, ChevronRight, Sparkles, Ban, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { @@ -23,29 +23,32 @@ import { } from "recharts"; import { useServerStats } from "@/hooks/useServerStats"; import { useServerStatsHistory, type Timeframe } from "@/hooks/useServerStatsHistory"; -import { tauriCmd, type StartServerParams, type ArkPlayer } from "@/lib/tauri-commands"; +import { tauriCmd, type ArkPlayer } from "@/lib/tauri-commands"; import { useAppStore } from "@/store/useAppStore"; import { - updateServerStatus, getServerConfig, getServerModCount, getServerMods, + updateServerStatus, getServerConfig, getServerModCount, getLastBackupTime, getNextScheduledRestart, getHasBackupEnabled, getAppSetting, insertBackup, pruneManualBackups, setServerAutoStart, } from "@/lib/db"; -import { buildLaunchCommandPreview } from "@/lib/server-utils"; +import { buildLaunchCommandPreview, buildStartParams, restartServerGracefully, stopServerGracefully } from "@/lib/server-utils"; import { applyUpdateToServer } from "@/lib/update-utils"; +import { reinstallServer } from "@/lib/server-actions"; import { warnIfFirewallMissing } from "@/lib/firewall-utils"; import type { BackupRecord } from "@/lib/tauri-commands"; import type { ServerRow } from "@/lib/db"; -import { formatServerVersion } from "@/lib/db"; -import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; import { toast } from "sonner"; -import { ARK_MAPS, LAUNCH_PARAMETERS, NOTIFICATION_EVENTS } from "@/data/game-data"; +import { ARK_EVENTS, NOTIFICATION_EVENTS, getSaveFolder } from "@/data/game-data"; +import { useAllMaps } from "@/hooks/useAllMaps"; +import { ensureMapsCacheLoaded, findMapById } from "@/lib/maps"; import { dispatchNotification } from "@/lib/notifications"; import { useQueryClient } from "@tanstack/react-query"; import { useTauriEvent } from "@/hooks/useTauriEvent"; -import { isLinux } from "@/lib/server-utils"; +import { useOnMount } from "@/hooks/useOnMount"; interface Props { server: ServerRow; + /** Switch the parent's active tab to Config; optionally pass a section id to scroll to. */ + onNavigateToConfig?: (anchor?: string) => void; } // ── Constants ───────────────────────────────────────────────────────────────── @@ -167,7 +170,7 @@ function ChartTooltip({
m.id === server.map_id)?.displayName ?? server.map_id; + const allMaps = useAllMaps(); + const mapDisplay = allMaps.find((m) => m.id === server.map_id)?.displayName ?? server.map_id; const items = [ { label: "Started", value: currentStartMs ? fmtDate(currentStartMs) : "—" }, @@ -495,6 +499,7 @@ function ActiveConfigPanel({ launchCommand: string; onNavigateToConfig: () => void; }) { + const [cliExpanded, setCliExpanded] = useState(false); if (!config) return null; const pvp = gusVal(config, "ServerPVE") !== "True"; @@ -541,16 +546,25 @@ function ActiveConfigPanel({ ))}
- {/* Launch command */} + {/* Launch command — collapsed by default */} {launchCommand && (
-
- +
-
- {launchCommand} -
+ + {cliExpanded && ( +
+ {launchCommand} +
+ )}
)}
@@ -559,18 +573,29 @@ function ActiveConfigPanel({ // ── OverviewTab ─────────────────────────────────────────────────────────────── -export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigateToConfig?: () => void }) { +export function OverviewTab({ server, onNavigateToConfig }: Props) { const router = useRouter(); const queryClient = useQueryClient(); const stats = useServerStats(server); - const versionCache = useBuildVersionCache(); const startTime = useAppStore((s) => s.serverStartTimes[server.id]); const isServerScanPending = useAppStore((s) => s.isServerScanPending); const countdown = useAppStore((s) => s.countdowns[server.id] ?? null); + const noRetry = useAppStore((s) => !!s.noRetryServerIds[server.id]); + const setNoRetryServer = useAppStore((s) => s.setNoRetryServer); + const clearNoRetryServer = useAppStore((s) => s.clearNoRetryServer); + const enqueueStartup = useAppStore((s) => s.enqueueStartup); + const removeFromStartupQueue = useAppStore((s) => s.removeFromStartupQueue); const [modCount, setModCount] = useState(null); const [activeConfig, setActiveConfig] = useState(null); const [lastBackup, setLastBackup] = useState(null); + + // Refresh the Last Backup tile when a scheduled (hourly) backup finishes — + // without this it stays stale (showing the pre-backup time) until this tab + // remounts, since it's otherwise only fetched once on mount below. + useTauriEvent(`backup://completed/${server.id}`, () => { + getLastBackupTime(server.id).then(setLastBackup).catch(() => {}); + }); const [nextRestart, setNextRestart] = useState(null); const [backupEnabled, setBackupEnabled] = useState(null); const [actionPending, setActionPending] = useState(false); @@ -578,13 +603,11 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate const [playersLoading, setPlayersLoading] = useState(false); const [showUpdateConfirm, setShowUpdateConfirm] = useState(false); const [applyingUpdate, setApplyingUpdate] = useState(false); - const [wipeConfirm, setWipeConfirm] = useState<"map" | "players" | "full" | null>(null); - const [wiping, setWiping] = useState(false); const [autoCheckEnabled, setAutoCheckEnabled] = useState(true); const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); const [launchCommand, setLaunchCommand] = useState(""); const [wipingDinos, setWipingDinos] = useState(false); - const [validating, setValidating] = useState(false); + const activeEventId = server.active_event ?? null; // Per-tile timeframe selectors const [playersTf, setPlayersTf] = useState("Live"); @@ -594,9 +617,10 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate const hasUpdateAvailable = server.update_available === 1; const isRunning = server.status === "running"; const isStarting = server.status === "starting"; - const isTransitioning = ["starting", "stopping", "updating"].includes(server.status); + const isTransitioning = ["starting", "stopping", "updating", "update_queued"].includes(server.status); const isStartFailed = server.status === "start-failed"; - // isLinux imported from server-utils + const isUpdateQueued = server.status === "update_queued"; + const isStartupQueued = server.status === "startup_queued"; // Keep the uptime counter ticking while the server is active. const [, setTick] = useState(0); @@ -606,6 +630,14 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate return () => clearInterval(id); }, [isRunning, isStarting]); + // server is read via a ref inside the effect below so unrelated re-renders + // (e.g. status polling) don't force server's full identity into that + // effect's deps — only an actual id/install_path change should refetch. + const serverRef = useRef(server); + useEffect(() => { + serverRef.current = server; + }); + useEffect(() => { let cancelled = false; (async () => { @@ -627,7 +659,7 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate launchArgs, }); // Build launch command preview (async, non-blocking) - buildLaunchCommandPreview(server, launchArgs).then(setLaunchCommand).catch(() => {}); + buildLaunchCommandPreview(serverRef.current, launchArgs).then(setLaunchCommand).catch(() => {}); } setLastBackup(lb); setNextRestart(nr); @@ -638,53 +670,53 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate return () => { cancelled = true; }; }, [server.id, server.install_path]); - // ── Action helpers ────────────────────────────────────────────────────────── - - const buildStartParams = async (): Promise => { - const [config, mods] = await Promise.all([ - getServerConfig(server.id), - getServerMods(server.id), - ]); - const launchArgs: Record = config ? JSON.parse(config.launch_args_json) : {}; - const extraArgs = Object.entries(launchArgs).flatMap(([k, v]) => { - if (!v || v === "false" || v === "0") return []; - const param = LAUNCH_PARAMETERS.find((p) => p.key === k); - if (param?.type === "boolean") return v === "true" ? [param.flag] : []; - if (param) return v ? [`${param.flag}${v}`] : []; - return v === "true" ? [`-${k}`] : [`-${k}=${v}`]; - }); - const map = ARK_MAPS.find((m) => m.id === server.map_id); - const enabledModIds = mods.filter((m) => m.enabled === 1).map((m) => m.mod_id); - const params: StartServerParams = { - serverId: server.id, - serverName: server.name, - installPath: server.install_path, - mapPath: map?.mapPath ?? "TheIsland_WP", - port: server.port, - queryPort: server.query_port, - rconPort: server.rcon_port, - rconPassword: server.rcon_password, - extraArgs, - modIds: enabledModIds, - }; - if (isLinux) { - params.protonPath = (await getAppSetting("proton_path")) ?? undefined; - params.prefixPath = (await getAppSetting("proton_prefix_path")) ?? undefined; + const navigateToConfig = (anchor?: string) => { + if (onNavigateToConfig) { + onNavigateToConfig(anchor); + return; + } + const url = new URL(window.location.href); + url.searchParams.set("tab", "config"); + router.push(url.pathname + url.search); + if (anchor) { + setTimeout(() => document.getElementById(anchor)?.scrollIntoView({ behavior: "smooth", block: "start" }), 300); } - return params; }; + // ── Action helpers ────────────────────────────────────────────────────────── + const handleStart = async () => { setActionPending(true); + clearNoRetryServer(server.id); try { await updateServerStatus(server.id, "starting", null); queryClient.invalidateQueries({ queryKey: ["servers"] }); + + // Ensure both save symlinks/junctions are in place before launching — + // self-heals a server whose links were lost (e.g. after moving + // base_dir), same repair step the dashboard card's Start runs. + const baseDir = await getAppSetting("base_dir").catch(() => null); + if (baseDir) { + await ensureMapsCacheLoaded().catch(() => {}); + const mapPath = findMapById(server.map_id)?.mapPath ?? "TheIsland_WP"; + await tauriCmd.createSaveLink(server.install_path, server.id, baseDir).catch((e) => { + console.warn("createSaveLink failed on start:", e); + }); + await tauriCmd.createModsSavesLink(server.install_path, server.id, baseDir, mapPath).catch((e) => { + console.warn("createModsSavesLink failed on start:", e); + }); + } + await warnIfFirewallMissing(server); - const params = await buildStartParams(); + const params = await buildStartParams(server); const pid = await tauriCmd.startServer(params); await updateServerStatus(server.id, "starting", pid); } catch (e) { - const errMsg = typeof e === "string" ? e : String(e); + const raw = typeof e === "string" ? e : String(e); + const isExeMissing = raw.startsWith("exe_missing:"); + const errMsg = isExeMissing ? raw.slice("exe_missing: ".length) : raw; + if (isExeMissing) setNoRetryServer(server.id); + await updateServerStatus(server.id, "start-failed", null); toast.error(`${server.name} failed to start — ${errMsg}`); await dispatchNotification({ @@ -701,19 +733,30 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate } }; - const handleStop = async () => { + // Default entry point for the manual "Start" button — hands off to the + // staggered startup queue instead of launching directly, matching the + // dashboard card's Start button, so starting from this tab can't pile a + // second simultaneous boot on top of whatever's currently starting. + const handleQueueStart = async () => { setActionPending(true); + clearNoRetryServer(server.id); try { - await updateServerStatus(server.id, "stopping", null); + await updateServerStatus(server.id, "startup_queued", null); queryClient.invalidateQueries({ queryKey: ["servers"] }); - await tauriCmd.gracefulStopServer( - server.id, - server.rcon_port, - server.rcon_password, - server.shutdown_warn_players !== 0, - server.shutdown_warn_minutes ?? 5, - server.shutdown_message || "Server will shut down in {time}.", - ); + enqueueStartup([server.id]); + } catch (err) { + toast.error(`Failed to queue ${server.name} to start`, { description: String(err) }); + } finally { + setActionPending(false); + } + }; + + const handleStop = async () => { + setActionPending(true); + try { + await stopServerGracefully(server, { + onInvalidate: () => queryClient.invalidateQueries({ queryKey: ["servers"] }), + }); } catch (err) { toast.error(`Failed to stop ${server.name}`, { description: String(err) }); await updateServerStatus(server.id, "error", null); @@ -736,33 +779,18 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate }; const handleRestart = async () => { - if (server.restart_warn_players) { - const startParams = await buildStartParams(); - tauriCmd.startGracefulRestart({ - serverId: server.id, - warnSeconds: (server.restart_warn_minutes ?? 5) * 60, - rconPort: server.rcon_port, - rconPassword: server.rcon_password, - message: server.restart_message || "Server restarting in {time}.", - cancelMessage: server.restart_cancel_message || "Restart has been canceled.", - startParams, - }).catch((err) => toast.error(`Restart failed: ${err}`)); - return; - } - - setActionPending(true); + // Only the plain (non-warn) path is a quick stop+handoff worth a pending + // spinner — the warn path runs a countdown that can last minutes. + const isWarnRestart = !!server.restart_warn_players; + if (!isWarnRestart) setActionPending(true); try { - await updateServerStatus(server.id, "stopping", null); - queryClient.invalidateQueries({ queryKey: ["servers"] }); - const params = await buildStartParams(); - const pid = await tauriCmd.restartServer(params, true); - await updateServerStatus(server.id, "running", pid); + await restartServerGracefully(server, { + onInvalidate: () => queryClient.invalidateQueries({ queryKey: ["servers"] }), + }); } catch (err) { toast.error(`Failed to restart ${server.name}`, { description: String(err) }); - await updateServerStatus(server.id, "error", null); } finally { - queryClient.invalidateQueries({ queryKey: ["servers"] }); - setActionPending(false); + if (!isWarnRestart) setActionPending(false); } }; @@ -777,14 +805,20 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate if (!baseDir || !steamcmdPath) return; const sep = baseDir.includes("\\") ? "\\" : "/"; const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; - const startParams = restartAfterUpdate ? await buildStartParams() : null; + const startParams = restartAfterUpdate ? await buildStartParams(server) : null; + + // Show a visible transition immediately — otherwise the card sits on + // "running" with no feedback until the warning countdown finishes. + // Rust reverts this back to "running" if the countdown gets cancelled. + await updateServerStatus(server.id, "stopping", server.pid); + queryClient.invalidateQueries({ queryKey: ["servers"] }); tauriCmd.startGracefulUpdate({ serverId: server.id, serverName: server.name, warnSeconds: (server.update_warn_minutes ?? 5) * 60, rconPort: server.rcon_port, - rconPassword: server.rcon_password, + rconPassword: server.admin_password, message: server.update_message || "Server going down for update in {time}.", cancelMessage: server.update_cancel_message || "Update has been canceled.", installPath: server.install_path, @@ -806,9 +840,17 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate server.install_path, wasRunning, restartAfterUpdate, - (msg) => toast.info(msg), server.rcon_port, - server.rcon_password, + server.admin_password, + { + // This branch only runs when the warn-players countdown path above + // wasn't taken (warn disabled, or server wasn't running) — still + // always saves the world and shuts down cleanly via RCON either way. + warnPlayers: false, + warnMinutes: server.update_warn_minutes ?? 5, + warnMessage: server.update_message || "Server going down for update in {time}.", + }, + (msg) => toast.info(msg), ); } catch (err) { if (err && typeof err === "object" && "restartNeeded" in err) { @@ -828,36 +870,14 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate }; const handleReinstall = async () => { + queryClient.invalidateQueries({ queryKey: ["servers"] }); + router.push("/"); try { - const [baseDir, steamcmdPath] = await Promise.all([ - getAppSetting("base_dir"), - getAppSetting("steamcmd_path"), - ]); - if (!baseDir || !steamcmdPath) return; - const sep = baseDir.includes("\\") ? "\\" : "/"; - const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; - await updateServerStatus(server.id, "installing", null); - queryClient.invalidateQueries({ queryKey: ["servers"] }); - router.push("/"); - tauriCmd.updateServer(server.id, server.install_path, cacheDir, steamcmdPath) - .then(() => updateServerStatus(server.id, "stopped", null)) - .catch(() => updateServerStatus(server.id, "install_failed", null)) - .finally(() => queryClient.invalidateQueries({ queryKey: ["servers"] })); + await reinstallServer(server); } catch (err) { - toast.error(`Failed to start reinstall for ${server.name}`, { description: String(err) }); - } - }; - - const handleWipe = async (tier: "map" | "players" | "full") => { - setWiping(true); - try { - await tauriCmd.wipeServerSaves(server.install_path, server.save_folder_name ?? "", tier); - setWipeConfirm(null); - toast.success(`Save wipe complete (${tier})`); - } catch (e) { - toast.error(`Save wipe failed: ${e}`); + toast.error(`Reinstall failed for ${server.name}`, { description: String(err) }); } finally { - setWiping(false); + queryClient.invalidateQueries({ queryKey: ["servers"] }); } }; @@ -875,10 +895,10 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate }, [server.id]); // Fetch player list on mount/server-change if running. - useEffect(() => { + const syncPlayersIfRunning = useCallback(() => { if (server.status === "running") refreshPlayers(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [server.id]); + }, [server.status, refreshPlayers]); + useOnMount(syncPlayersIfRunning); // The per-server event emits the players array directly as payload. useTauriEvent( @@ -935,14 +955,60 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate Detecting... - ) : isStartFailed ? ( + ) : isUpdateQueued ? ( + <> + + Update queued + + + + ) : isStartupQueued ? ( <> + + Startup queued + + + + ) : isStartFailed ? ( + <> + {!noRetry && ( + + )} ) : server.status === "starting" ? ( ) : (
+ {/* ── Active Event (read-only — edit in Settings) ── */} +
+
+
+ +
+

Active Event

+

+ {activeEventId + ? (ARK_EVENTS.find((e) => e.id === activeEventId)?.displayName ?? activeEventId) + : "No event active"} +

+
+
+ +
+ {activeEventId && (() => { + const evt = ARK_EVENTS.find((e) => e.id === activeEventId); + return evt ? ( +

+ {evt.description} Mod: {evt.modId} +

+ ) : null; + })()} +
+ {/* ── Active Configuration panel ── */} { - if (onNavigateToConfig) { - onNavigateToConfig(); - } else { - const url = new URL(window.location.href); - url.searchParams.set("tab", "config"); - router.push(url.pathname + url.search); - } - }} + onNavigateToConfig={() => navigateToConfig()} /> {/* ── Network / install info ── */} @@ -1142,31 +1236,6 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate Open Install Folder -
@@ -1231,67 +1300,6 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate
)} - {/* ── Wipe Saves card ── */} - {!isRunning && ( -
-
- -

Wipe Save Data

-
-

- Permanently delete save files. This cannot be undone. Take a backup first. -

- - {wipeConfirm ? ( -
-

- {wipeConfirm === "map" && "Wipe Map Data — this will delete all world state (*.ark). Character and tribe data will be preserved."} - {wipeConfirm === "players" && "Wipe Player & Tribe Data — this will delete all character profiles and tribe records. World state will be preserved."} - {wipeConfirm === "full" && "Full Wipe — this will delete ALL save data including world, characters, tribes, and mod data. This is irreversible."} -

-
- - -
-
- ) : ( -
- - - -
- )} -
- )} - {/* ── Update confirmation dialog ── */} diff --git a/src/components/shared/CommandOutputPanel.tsx b/src/components/shared/CommandOutputPanel.tsx index 0c58647..855993a 100644 --- a/src/components/shared/CommandOutputPanel.tsx +++ b/src/components/shared/CommandOutputPanel.tsx @@ -10,9 +10,12 @@ * * Buffer lifecycle: * - Accumulates as events arrive, regardless of dialog state. - * - Cleared when the panel unmounts AND the process has completed (completed=true). - * - Also cleared on unmount when clearBufferOnUnmount=true (used by wizard "Go to Dashboard"). - * - Buffer is NOT cleared on unmount while a process is still running. + * - Cleared on unmount only when both `clearBufferOnClose` is true AND the + * process had completed (via the `completed` prop) — by default neither + * condition clears it, so callers that want cleanup must opt in. + * - Callers may also clear a channel directly via `clearOutputBuffer(channel)` + * at any point they know is safe (e.g. ServerCard does this once a + * card — and thus its association with the channel — goes away). */ import { useEffect, useRef, useState, useCallback } from "react"; @@ -51,6 +54,10 @@ export function clearOutputBuffer(channel: string): void { _buffers.delete(channel); } +export function hasOutputBuffer(channel: string): boolean { + return (_buffers.get(channel)?.length ?? 0) > 0; +} + export interface CommandOutputPanelProps { /** The Tauri event channel to subscribe to, e.g. "steamcmd://output/setup". */ eventChannel: string; @@ -87,7 +94,7 @@ export function CommandOutputPanel({ canceled = false, clearBufferOnClose = false, }: CommandOutputPanelProps) { - const [lines, setLines] = useState(() => _buffers.get(eventChannel) ?? []); + const [lines, setLines] = useState(() => [...(_buffers.get(eventChannel) ?? [])]); const [collapsed, setCollapsed] = useState(defaultCollapsed); const [copied, setCopied] = useState(false); const [autoScroll, setAutoScroll] = useState(true); @@ -98,16 +105,19 @@ export function CommandOutputPanel({ const completedRef = useRef(false); const completedProp = useRef(completed); - // Keep ref in sync for the cleanup function - completedProp.current = completed; + // Keep ref in sync for the cleanup function — synced in its own effect + // (runs after every render) rather than during render itself. + useEffect(() => { + completedProp.current = completed; + }); - // On mount: scroll to bottom if there are already lines from the buffer + // On mount (or channel change): scroll to bottom if there are already + // lines from the buffer. useEffect(() => { if (scrollRef.current && (_buffers.get(eventChannel)?.length ?? 0) > 0) { scrollRef.current.scrollTop = scrollRef.current.scrollHeight; } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); + }, [eventChannel]); // On unmount: clear buffer if process is done (or clearBufferOnClose is set) useEffect(() => { @@ -116,7 +126,6 @@ export function CommandOutputPanel({ clearOutputBuffer(eventChannel); } }; - // eslint-disable-next-line react-hooks/exhaustive-deps }, [eventChannel, clearBufferOnClose]); // Subscribe to the Tauri event channel @@ -143,12 +152,19 @@ export function CommandOutputPanel({ } }, [lines, autoScroll]); - // Elapsed time counter — resets when the event channel changes. + // Elapsed time counter — resets when the event channel changes. The + // display resets (finalElapsed/elapsed) are compared during render rather + // than set synchronously at the top of the effect below. + const [prevEventChannel, setPrevEventChannel] = useState(eventChannel); + if (eventChannel !== prevEventChannel) { + setPrevEventChannel(eventChannel); + setFinalElapsed(null); + setElapsed("0s"); + } + useEffect(() => { startTimeRef.current = new Date(); completedRef.current = false; - setFinalElapsed(null); - setElapsed("0s"); const interval = setInterval(() => { if (completedRef.current) { @@ -195,7 +211,7 @@ export function CommandOutputPanel({ {/* Header */}
diff --git a/src/components/shared/CronBuilder.tsx b/src/components/shared/CronBuilder.tsx index a6b6157..ab9a6e0 100644 --- a/src/components/shared/CronBuilder.tsx +++ b/src/components/shared/CronBuilder.tsx @@ -7,7 +7,7 @@ * input alongside a human-readable description of the expression. */ -import { useState, useEffect } from "react"; +import { useState } from "react"; import { Info } from "lucide-react"; import { Input } from "@/components/ui/input"; import { CronExpressionParser } from "cron-parser"; @@ -102,8 +102,12 @@ export function CronBuilder({ value, onChange, label }: Props) { const isCustom = selected.cron === ""; - useEffect(() => { - // Sync selection when `value` changes externally. + // Sync selection when `value` changes externally — compared during render + // rather than via an effect, since it's a synchronous derivation from the + // `value` prop with no async work of its own. + const [prevValue, setPrevValue] = useState(value); + if (value !== prevValue) { + setPrevValue(value); const preset = CRON_PRESETS.find((p) => p.cron === value && p.cron !== ""); if (preset) { setSelected(preset); @@ -111,8 +115,7 @@ export function CronBuilder({ value, onChange, label }: Props) { setSelected(CRON_PRESETS[CRON_PRESETS.length - 1]); setCustomCron(value); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [value]); + } function handlePresetChange(preset: CronPreset) { setSelected(preset); diff --git a/src/components/shared/NotificationMatrix.tsx b/src/components/shared/NotificationMatrix.tsx index d06ac44..40cd8f6 100644 --- a/src/components/shared/NotificationMatrix.tsx +++ b/src/components/shared/NotificationMatrix.tsx @@ -14,7 +14,7 @@ import { useState, useEffect, useCallback, forwardRef, useImperativeHandle } from "react"; import { toast } from "sonner"; -import { Loader2, Bell, Monitor, MessageSquare, Mail } from "lucide-react"; +import { Loader2, AppWindow, Bell, Monitor, MessageSquare, Mail } from "lucide-react"; import { getNotificationConfigs, saveGlobalChannelEvents, @@ -36,7 +36,7 @@ interface ChannelDef { } const CHANNELS: ChannelDef[] = [ - { id: "in_app", label: "In-App", Icon: Bell, description: "Toast popup inside LokiASAM" }, + { id: "in_app", label: "In-App", Icon: AppWindow, description: "Toast popup inside LokiASAM" }, { id: "bell", label: "Bell", Icon: Bell, description: "Show as unread in the bell badge and popup" }, { id: "desktop", label: "Desktop", Icon: Monitor, description: "OS system notification" }, { id: "discord", label: "Discord", Icon: MessageSquare, description: "Discord webhook" }, @@ -49,7 +49,7 @@ const ALL_EVENTS = Object.values(NOTIFICATION_EVENTS) as NotificationEventType[] const CHANNEL_DEFAULTS: Record = { in_app: ALL_EVENTS, bell: ALL_EVENTS, - desktop: ["server_started", "server_crashed", "update_available", "update_started", "update_failed", "backup_completed", "backup_failed"], + desktop: [], discord: ALL_EVENTS, email: ALL_EVENTS, }; @@ -140,8 +140,7 @@ function NotificationMatrix({ onSaved, onChange, refreshKey }, ref) { // Re-query credential status whenever the parent signals a credential change. useEffect(() => { if (refreshKey !== undefined && refreshKey > 0) loadState(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [refreshKey]); + }, [refreshKey, loadState]); useImperativeHandle(ref, () => ({ getChannelEvents: () => @@ -172,6 +171,23 @@ function NotificationMatrix({ onSaved, onChange, refreshKey }, ref) { } }, [channelEvents, onChange, onSaved]); + const handleToggleAll = useCallback((channel: ChannelId) => { + const allOn = ALL_EVENTS.every((e) => channelEvents[channel].has(e)); + const newSet = allOn ? new Set() : new Set(ALL_EVENTS); + const nextEvents = { ...channelEvents, [channel]: newSet }; + setChannelEvents(nextEvents); + + if (onChange) { + onChange(Object.fromEntries( + Object.entries(nextEvents).map(([ch, set]) => [ch, [...set]]) + )); + } else { + saveGlobalChannelEvents(channel, [...newSet]) + .then(() => onSaved?.()) + .catch((err) => toast.error("Failed to save notification settings", { description: String(err) })); + } + }, [channelEvents, onChange, onSaved]); + if (loading) { return (
@@ -197,6 +213,8 @@ function NotificationMatrix({ onSaved, onChange, refreshKey }, ref) { const disabled = (ch.id === "discord" && !discordConfigured) || (ch.id === "email" && !emailConfigured); + const allOn = ALL_EVENTS.every((e) => channelEvents[ch.id].has(e)); + const someOn = !allOn && ALL_EVENTS.some((e) => channelEvents[ch.id].has(e)); return ( {ch.label} - {disabled && ( + {disabled ? ( (not configured) + ) : ( + { if (el) el.indeterminate = someOn; }} + onChange={() => handleToggleAll(ch.id)} + className="w-3 h-3 mt-0.5" + style={{ accentColor: "var(--neon-purple)", cursor: "pointer" }} + title={allOn ? `Disable all ${ch.label} notifications` : `Enable all ${ch.label} notifications`} + /> )}
diff --git a/src/components/shared/NumberField.tsx b/src/components/shared/NumberField.tsx index 72265f7..c8b019e 100644 --- a/src/components/shared/NumberField.tsx +++ b/src/components/shared/NumberField.tsx @@ -5,7 +5,7 @@ * * The slider is clamped to [min, max] (the "safe" range). * The text input is unconstrained, letting admins override beyond safe limits. - * Colored dots with labels are shown above the track at 0 and at defaultValue. + * The "0" reference mark appears above the track; the "default" mark appears below. */ import { useState, useRef, useEffect } from "react"; @@ -72,10 +72,14 @@ export function NumberField({ value, onChange, min, max, step = 0.1, defaultValu return (
{/* Slider with reference markers */} -
- {/* Tick marks */} -
- {showZeroMark && zeroPct >= 0 && zeroPct <= 100 && ( +
+ + {/* "0" mark ABOVE the track */} + {showZeroMark && zeroPct >= 0 && zeroPct <= 100 && ( +
0
- )} - {defaultPct !== null && defaultPct >= 0 && defaultPct <= 100 && ( -
- default -
-
- )} -
+
+ )} + + + {/* "default" mark BELOW the track — clickable to snap to default */} + {defaultPct !== null && defaultPct >= 0 && defaultPct <= 100 && ( +
+ +
+ )} +
{/* Numeric input override */} @@ -116,7 +132,7 @@ export function NumberField({ value, onChange, min, max, step = 0.1, defaultValu onBlur={handleInputBlur} className="w-20 h-7 text-xs font-mono text-right rounded px-2 shrink-0" style={{ - background: "rgba(0,0,0,0.35)", + background: "var(--surface)", border: "1px solid rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)", outline: "none", diff --git a/src/components/shared/ServerScopedTabPage.tsx b/src/components/shared/ServerScopedTabPage.tsx new file mode 100644 index 0000000..fb8e07c --- /dev/null +++ b/src/components/shared/ServerScopedTabPage.tsx @@ -0,0 +1,160 @@ +"use client"; + +/** + * ServerScopedTabPage — shared page shell for the standalone Backups and Logs + * pages (also usable by any future top-level page that's just "pick a server, + * show one of its tabs"). Handles the server picker, the ?server= URL param, + * and the empty/no-servers state; the caller only supplies the page-specific + * chrome (icon/title/description) and which tab component to render. + */ + +import { useState } from "react"; +import { useSearchParams, useRouter } from "next/navigation"; +import { ChevronDown, Plus, type LucideIcon } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { useAppStore } from "@/store/useAppStore"; +import { useServers } from "@/hooks/useServers"; +import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; +import type { ServerRow } from "@/lib/db"; + +interface ServerScopedTabPageProps { + icon: LucideIcon; + title: string; + description: string; + emptyStateDescription: string; + /** Tailwind class(es) for the content wrapper — tabs differ in whether they scroll internally. */ + contentClassName: string; + TabComponent: React.ComponentType<{ server: ServerRow }>; +} + +export function ServerScopedTabPage({ + icon: Icon, + title, + description, + emptyStateDescription, + contentClassName, + TabComponent, +}: ServerScopedTabPageProps) { + const searchParams = useSearchParams(); + const router = useRouter(); + const { data: servers = [], isLoading } = useServers(); + const { setShowNewServerWizard } = useAppStore(); + + const [rawSelectedId, setSelectedId] = useState( + searchParams.get("server") ?? "" + ); + // Defaults to the first server once the list loads, without needing a + // separate effect+state just to mirror that default back into state. + const selectedId = rawSelectedId || servers[0]?.id || ""; + + const selectedServer: ServerRow | undefined = servers.find( + (s) => s.id === selectedId + ); + + const handleSelect = (id: string) => { + setSelectedId(id); + const url = new URL(window.location.href); + url.searchParams.set("server", id); + router.replace(url.pathname + url.search); + }; + + return ( +
+ {/* Page header */} +
+
+ +

+ {title} +

+
+

+ {description} +

+
+ + {/* Server selector */} +
+ + Server: + + + {isLoading ? ( +
+ ) : servers.length === 0 ? ( + + No servers configured + + ) : ( +
+ + +
+ )} + + {selectedServer && ( +
+ + + Port {selectedServer.port} + +
+ )} +
+ + {/* Tab content */} + {selectedServer ? ( +
+ +
+ ) : !isLoading && servers.length === 0 ? ( +
+
+ +
+
+

No servers yet

+

+ {emptyStateDescription} +

+
+ +
+ ) : null} +
+ ); +} diff --git a/src/components/shared/TourModal.tsx b/src/components/shared/TourModal.tsx index 58617be..ff8aa18 100644 --- a/src/components/shared/TourModal.tsx +++ b/src/components/shared/TourModal.tsx @@ -87,7 +87,7 @@ const TOUR_SLIDES = [ description: "For players outside your local network to join, your server ports need to be reachable from the internet.", imagePlaceholder: "Diagram: Internet → Router/VPN → Port Forward → LokiASAM Server", bullets: [ - "Forward three ports on your router: Game Port (UDP), Game Port+1 (UDP), and Query Port (UDP)", + "Forward two ports on your router: Game Port (UDP) and Query Port (UDP). RCON (TCP) only needs to be open if you use remote console tools.", "No router access? VPN port-forwarding services let you forward ports without touching your router — ideal for apartments, shared networks, or ISP restrictions", // TODO: Add affiliate links here for TorGuard / Mullvad / AirVPN — these let users support // LokiASAM at no extra cost while solving their port forwarding needs. diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx index a2c2d0b..b06d33a 100644 --- a/src/components/ui/dialog.tsx +++ b/src/components/ui/dialog.tsx @@ -107,7 +107,7 @@ function DialogFooter({
) { - return -} - -function SheetTrigger({ - ...props -}: React.ComponentProps) { - return -} - -function SheetClose({ - ...props -}: React.ComponentProps) { - return -} - -function SheetPortal({ - ...props -}: React.ComponentProps) { - return -} - -function SheetOverlay({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -function SheetContent({ - className, - children, - side = "right", - showCloseButton = true, - ...props -}: React.ComponentProps & { - side?: "top" | "right" | "bottom" | "left" - showCloseButton?: boolean -}) { - return ( - - - - {children} - {showCloseButton && ( - - - - )} - - - ) -} - -function SheetHeader({ className, ...props }: React.ComponentProps<"div">) { - return ( -
- ) -} - -function SheetFooter({ className, ...props }: React.ComponentProps<"div">) { - return ( -
- ) -} - -function SheetTitle({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -function SheetDescription({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -export { - Sheet, - SheetTrigger, - SheetClose, - SheetContent, - SheetHeader, - SheetFooter, - SheetTitle, - SheetDescription, -} diff --git a/src/components/ui/switch.tsx b/src/components/ui/switch.tsx index 9600e94..a5097c9 100644 --- a/src/components/ui/switch.tsx +++ b/src/components/ui/switch.tsx @@ -17,14 +17,14 @@ function Switch({ data-slot="switch" data-size={size} className={cn( - "peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50", + "peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-all outline-none after:absolute after:-inset-x-3 after:-inset-y-2 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-[size=default]:h-[18.4px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-input/80 data-disabled:cursor-not-allowed data-disabled:opacity-50", className )} {...props} > ) diff --git a/src/components/ui/table.tsx b/src/components/ui/table.tsx deleted file mode 100644 index abeaced..0000000 --- a/src/components/ui/table.tsx +++ /dev/null @@ -1,116 +0,0 @@ -"use client" - -import * as React from "react" - -import { cn } from "@/lib/utils" - -function Table({ className, ...props }: React.ComponentProps<"table">) { - return ( -
- - - ) -} - -function TableHeader({ className, ...props }: React.ComponentProps<"thead">) { - return ( - - ) -} - -function TableBody({ className, ...props }: React.ComponentProps<"tbody">) { - return ( - - ) -} - -function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) { - return ( - tr]:last:border-b-0", - className - )} - {...props} - /> - ) -} - -function TableRow({ className, ...props }: React.ComponentProps<"tr">) { - return ( - - ) -} - -function TableHead({ className, ...props }: React.ComponentProps<"th">) { - return ( -
- ) -} - -function TableCell({ className, ...props }: React.ComponentProps<"td">) { - return ( - - ) -} - -function TableCaption({ - className, - ...props -}: React.ComponentProps<"caption">) { - return ( -
- ) -} - -export { - Table, - TableHeader, - TableBody, - TableFooter, - TableHead, - TableRow, - TableCell, - TableCaption, -} diff --git a/src/components/ui/tabs.tsx b/src/components/ui/tabs.tsx deleted file mode 100644 index 05f469f..0000000 --- a/src/components/ui/tabs.tsx +++ /dev/null @@ -1,90 +0,0 @@ -"use client" - -import * as React from "react" -import { cva, type VariantProps } from "class-variance-authority" -import { Tabs as TabsPrimitive } from "radix-ui" - -import { cn } from "@/lib/utils" - -function Tabs({ - className, - orientation = "horizontal", - ...props -}: React.ComponentProps) { - return ( - - ) -} - -const tabsListVariants = cva( - "group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-horizontal/tabs:h-8 group-data-vertical/tabs:h-fit group-data-vertical/tabs:flex-col data-[variant=line]:rounded-none", - { - variants: { - variant: { - default: "bg-muted", - line: "gap-1 bg-transparent", - }, - }, - defaultVariants: { - variant: "default", - }, - } -) - -function TabsList({ - className, - variant = "default", - ...props -}: React.ComponentProps & - VariantProps) { - return ( - - ) -} - -function TabsTrigger({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -function TabsContent({ - className, - ...props -}: React.ComponentProps) { - return ( - - ) -} - -export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants } diff --git a/src/components/wizard/ServerCreationWizard.tsx b/src/components/wizard/ServerCreationWizard.tsx index c39a7ec..0beceac 100644 --- a/src/components/wizard/ServerCreationWizard.tsx +++ b/src/components/wizard/ServerCreationWizard.tsx @@ -22,10 +22,10 @@ import { Server, Network, GitBranch, Clock, Package, Download, ArrowRight, ArrowLeft, Loader2, AlertCircle, CheckCircle2, Plus, X, ChevronRight, StopCircle, RefreshCw, - Sword, Leaf, Sliders, Settings2, Code2, Globe, Lock, - ChevronDown, ChevronUp, LayoutList, ToggleLeft, ToggleRight, Terminal, + Sword, Sliders, Settings2, Code2, Globe, Lock, + ChevronDown, ChevronUp, ToggleLeft, ToggleRight, Terminal, Shield, Info, Heart, AlertTriangle, HelpCircle, Eye, EyeOff, - HardDrive, Skull, RotateCcw, Megaphone, MessageSquare, + HardDrive, Skull, RotateCcw, MessageSquare, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -34,12 +34,11 @@ import { Slider } from "@/components/ui/slider"; import { CommandOutputPanel } from "@/components/shared/CommandOutputPanel"; import { NumberField } from "@/components/shared/NumberField"; import { LokiIcon } from "@/components/shared/LokiIcon"; +import { useAllMaps } from "@/hooks/useAllMaps"; import { - getReleasedMaps, getOfficialMaps, getModMaps, getMapById, GAME_MODES, PRESET_STYLES, INI_FIELD_GROUPS, buildPresetConfig, - DEFAULT_GAME_USER_SETTINGS, DEFAULT_GAME_INI, - LAUNCH_PARAMETERS, NOTIFICATION_EVENTS, - type ArkMap, type GameModeConfig, type PresetStyle, type LaunchParameter, + LAUNCH_PARAMETERS, NOTIFICATION_EVENTS, ARK_EVENTS, + type ArkMap, type GameModeConfig, type PresetStyle, type LaunchParameter, type ArkEvent, } from "@/data/game-data"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { dispatchNotification } from "@/lib/notifications"; @@ -47,15 +46,17 @@ import { getAppSetting, setAppSetting, createServer, deleteServerRecord, saveServerConfig, createSchedule, updateScheduleConfig, getClusters, isServerNameTaken, updateServerStatus, addServerMod, getServers, getServerMods, createClusterRecord, - updateBackupBroadcastMessage, + updateBackupBroadcastMessage, getServerConfig, setServerActiveEvent, type ClusterRow, } from "@/lib/db"; import { getNextCronDate } from "@/components/shared/CronBuilder"; import { useTauriEvent } from "@/hooks/useTauriEvent"; +import { useOnMount } from "@/hooks/useOnMount"; import { tauriCmd, type PortDef, type FirewallStatus } from "@/lib/tauri-commands"; +import { getServerFirewallPorts } from "@/lib/firewall-utils"; import { useAppStore } from "@/store/useAppStore"; import { cn } from "@/lib/utils"; -import { useQueryClient } from "@tanstack/react-query"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; // --------------------------------------------------------------------------- // Wizard data model @@ -114,10 +115,33 @@ interface WizardData { serverPasswordConfirm: string; adminPassword: string; adminPasswordConfirm: string; + motdMessage: string; + motdDuration: number; + // Step 0 — Event + activeEventId: string; // Step 1 — Game Mode gameMode: "pvp" | "pve"; + // Game Mode — General (both PvP & PvE) + adminLogging: boolean; + serverCrosshair: boolean; + showDamageNumbers: boolean; + showPlayerLocation: boolean; + forceAllStructureLocking: boolean; + alwaysAllowStructurePickup: boolean; + disableStructurePlacementCollision: boolean; + // Game Mode — PvE specific flyerCarryPvE: boolean; + allowCaveBuildingPvE: boolean; + pveAllowStructuresAtSupplyDrops: boolean; + allowCrateSpawnsOnTopOfStructures: boolean; + disableStructureDecayPvE: boolean; + disableDinoDecayPvE: boolean; + // Game Mode — PvP specific pvpFriendlyFire: boolean; + preventOfflinePvP: boolean; + preventOfflinePvPInterval: number; + // Copy from server + copyFromServerId: string; // Step 2 — Style presetStyle: "official" | "casual" | "boosted" | "guided_custom" | "full_custom"; // Step 2a — Guided Custom rates @@ -133,11 +157,12 @@ interface WizardData { rconPort: number; // Cluster clusterId: string; - // Save directory - saveFolderName: string; // Automation — restart autoRestart: boolean; autoRestartCron: string; + autoRestartWarnPlayers: boolean; + autoRestartWarnMinutes: number; + autoRestartMessage: string; // Automation — backup tiers (TimeShift) serverBackupTiers: Record<"H"|"D"|"W"|"M", { enabled: boolean; keep: number }>; playerBackupTiers: Record<"H"|"D"|"W"|"M", { enabled: boolean; keep: number }>; @@ -210,9 +235,25 @@ const DEFAULT_DATA: WizardData = { serverPasswordConfirm: "", adminPassword: "", adminPasswordConfirm: "", + activeEventId: "", gameMode: "pve", - flyerCarryPvE: true, + adminLogging: true, + serverCrosshair: true, + showDamageNumbers: true, + showPlayerLocation: true, + forceAllStructureLocking: true, + alwaysAllowStructurePickup: true, + disableStructurePlacementCollision: false, + flyerCarryPvE: false, + allowCaveBuildingPvE: false, + pveAllowStructuresAtSupplyDrops: true, + allowCrateSpawnsOnTopOfStructures: true, + disableStructureDecayPvE: false, + disableDinoDecayPvE: false, pvpFriendlyFire: true, + preventOfflinePvP: false, + preventOfflinePvPInterval: 900, + copyFromServerId: "", presetStyle: "casual", guidedRates: DEFAULT_GUIDED_RATES, fullCustomGus: {}, @@ -222,9 +263,11 @@ const DEFAULT_DATA: WizardData = { queryPort: 27015, rconPort: 27020, clusterId: "", - saveFolderName: "", autoRestart: true, autoRestartCron: "0 6 * * *", + autoRestartWarnPlayers: true, + autoRestartWarnMinutes: 15, + autoRestartMessage: "Server restarting in {minutes} minutes. Progress will be saved.", serverBackupTiers: { H: { enabled: false, keep: 24 }, D: { enabled: true, keep: 7 }, @@ -248,6 +291,8 @@ const DEFAULT_DATA: WizardData = { modIds: [], lockedModIds: [], modNames: {}, + motdMessage: "", + motdDuration: 20, }; // --------------------------------------------------------------------------- @@ -260,29 +305,39 @@ interface StepDef { icon: React.ComponentType<{ className?: string; style?: React.CSSProperties }>; } -function computeSteps(data: WizardData): StepDef[] { +function computeSteps(presetStyle: WizardData["presetStyle"], copyFromServerId: WizardData["copyFromServerId"]): StepDef[] { const steps: StepDef[] = [ { id: "basic", label: "Basic Info", icon: Server }, { id: "gamemode", label: "Game Mode", icon: Sword }, - { id: "style", label: "Server Style", icon: Sliders }, ]; - if (data.presetStyle === "guided_custom") { - steps.push({ id: "guided_rates", label: "Core Rates", icon: Sliders }); - steps.push({ id: "guided_breeding", label: "Breeding", icon: Heart }); - steps.push({ id: "guided_combat", label: "Combat", icon: Sword }); - steps.push({ id: "guided_behavior", label: "Server QoL", icon: Settings2 }); - } - if (data.presetStyle === "full_custom") { - steps.push({ id: "full_ini", label: "INI Config", icon: Code2 }); + + if (!copyFromServerId) { + steps.push({ id: "style", label: "Server Style", icon: Sliders }); + if (presetStyle === "guided_custom") { + steps.push({ id: "guided_rates", label: "Core Rates", icon: Sliders }); + steps.push({ id: "guided_breeding", label: "Breeding", icon: Heart }); + steps.push({ id: "guided_combat", label: "Combat", icon: Sword }); + steps.push({ id: "guided_behavior", label: "Server QoL", icon: Settings2 }); + } + if (presetStyle === "full_custom") { + steps.push({ id: "full_ini", label: "INI Config", icon: Code2 }); + } } + steps.push( { id: "network", label: "Network", icon: Network }, - { id: "firewall", label: "Firewall", icon: Shield }, { id: "cluster", label: "Cluster", icon: GitBranch }, { id: "automation", label: "Automation", icon: Clock }, - { id: "launch", label: "Launch Args", icon: Terminal }, - { id: "mods", label: "Mods", icon: Package }, - { id: "install", label: "Install", icon: Download }, + ); + + if (!copyFromServerId) { + steps.push({ id: "launch", label: "Launch Args", icon: Terminal }); + } + + steps.push( + { id: "mods", label: "Mods", icon: Package }, + { id: "firewall", label: "Firewall", icon: Shield }, + { id: "install", label: "Install", icon: Download }, ); return steps; } @@ -328,19 +383,22 @@ function BasicInfoStep({ onChange: (patch: Partial) => void; onNameValidated: (valid: boolean) => void; }) { - const officialMaps = getOfficialMaps(); - const modMaps = getModMaps(); + const allMaps = useAllMaps(); + const officialMaps = allMaps.filter((m) => m.released && !m.isMod); + const modMaps = allMaps.filter((m) => m.released && m.isMod); const [nameError, setNameError] = useState(""); const [checkingName, setCheckingName] = useState(false); const [nameChecked, setNameChecked] = useState(false); const [mapMenuOpen, setMapMenuOpen] = useState(false); const menuRef = useRef(null); + const nameDebounce = useRef | null>(null); + const nameReqIdRef = useRef(0); const [showAdminPw, setShowAdminPw] = useState(false); const [showAdminConfirm, setShowAdminConfirm] = useState(false); const [showServerPw, setShowServerPw] = useState(false); const [showServerConfirm,setShowServerConfirm]= useState(false); - const selectedMap = getMapById(data.mapId); + const selectedMap = allMaps.find((m) => m.id === data.mapId); // Close dropdown when clicking outside useEffect(() => { @@ -360,46 +418,47 @@ function BasicInfoStep({ onNameValidated(false); return; } + // Debounce only prevents overlapping *scheduled* checks — a slow + // in-flight request for an older name could still resolve after a newer + // one. Drop the result if a newer check has started since. + const reqId = ++nameReqIdRef.current; setCheckingName(true); try { const taken = await isServerNameTaken(name.trim()); + if (reqId !== nameReqIdRef.current) return; setNameError(taken ? "A server with this name already exists." : ""); setNameChecked(true); onNameValidated(!taken); } catch { + if (reqId !== nameReqIdRef.current) return; setNameError(""); setNameChecked(true); onNameValidated(true); } finally { - setCheckingName(false); + if (reqId === nameReqIdRef.current) setCheckingName(false); } }, [onNameValidated]); const handleMapSelect = (map: ArkMap) => { const patch: Partial = { mapId: map.id }; - // Auto-update save folder name if it hasn't been manually edited - // (still empty or still equal to the old map's display name) - const prevMap = getMapById(data.mapId); - const prevDefaultName = prevMap?.displayName ?? ""; - if (!data.saveFolderName || data.saveFolderName === prevDefaultName) { - patch.saveFolderName = map.displayName; + // Start from whatever mods are currently selected, minus the previous + // map's required mod if it had one and it isn't also the new map's + // required mod — this used to only run in the "switching to a non-mod + // map" branch below, so mod-map → mod-map left the old map's mod + // installed and unlocked in the final server. + let modIds = data.modIds; + if (selectedMap?.isMod && selectedMap.requiredModId && selectedMap.requiredModId !== map.requiredModId) { + modIds = modIds.filter((id) => id !== selectedMap.requiredModId); } if (map.isMod && map.requiredModId) { // Auto-add the required mod and lock it - const newModIds = data.modIds.includes(map.requiredModId) - ? data.modIds - : [...data.modIds, map.requiredModId]; - patch.modIds = newModIds; + patch.modIds = modIds.includes(map.requiredModId) ? modIds : [...modIds, map.requiredModId]; patch.lockedModIds = [map.requiredModId]; } else { - if (prevMap?.isMod && prevMap.requiredModId) { - patch.modIds = data.modIds.filter((id) => id !== prevMap.requiredModId); - patch.lockedModIds = []; - } else { - patch.lockedModIds = []; - } + patch.modIds = modIds; + patch.lockedModIds = []; } onChange(patch); setMapMenuOpen(false); @@ -443,11 +502,21 @@ function BasicInfoStep({ { onChange({ name: e.target.value }); onNameValidated(false); setNameChecked(false); }} - onBlur={(e) => checkName(e.target.value)} + onChange={(e) => { + const val = e.target.value; + onChange({ name: val }); + onNameValidated(false); + setNameChecked(false); + if (nameDebounce.current) clearTimeout(nameDebounce.current); + nameDebounce.current = setTimeout(() => checkName(val), 600); + }} + onBlur={(e) => { + if (nameDebounce.current) clearTimeout(nameDebounce.current); + checkName(e.target.value); + }} placeholder="My ASA Server" style={{ - background: "rgba(10,10,30,0.8)", + background: "var(--surface)", borderColor: nameError ? "var(--neon-red)" : "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)", }} @@ -477,7 +546,7 @@ function BasicInfoStep({ onClick={() => setMapMenuOpen((v) => !v)} className="w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-left" style={{ - background: "rgba(10,10,30,0.8)", + background: "var(--surface)", border: "1px solid rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)", }} @@ -498,7 +567,7 @@ function BasicInfoStep({
- {/* Save Folder Name */} -
- - onChange({ saveFolderName: e.target.value })} - placeholder={selectedMap?.displayName ?? "e.g. TheIsland"} - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} - /> -

- Save files for this server will be stored in Saves/{data.saveFolderName || (selectedMap?.displayName ?? "…")}/ inside your base directory. - Use a unique name if you run two servers on the same map. + {/* Custom mod maps hint */} +

+

+ Don't see your mod map? Add it first from the{" "} + Mod Maps page (sidebar), then come back and it will appear in the list above.

+ {/* Active Event */} +
+
+ + + + + + + + Activates a seasonal event on the server. The required event mod is automatically downloaded and enabled when the server starts — you don't need to add it to the mod list manually. + + + +
+ + {data.activeEventId && (() => { + const ev = ARK_EVENTS.find((e) => e.id === data.activeEventId); + return ev ? ( +
+ +
+

{ev.description}

+

Event mod ID: {ev.modId} (auto-managed)

+
+
+ ) : null; + })()} +
+ {/* Max Players */}
@@ -566,10 +679,10 @@ function BasicInfoStep({ {/* Passwords */} {(() => { - const adminMismatch = !!data.adminPasswordConfirm && data.adminPassword !== data.adminPasswordConfirm; - const serverMismatch = !!data.serverPasswordConfirm && data.serverPassword !== data.serverPasswordConfirm; + const adminMismatch = !!data.adminPassword && data.adminPassword !== data.adminPasswordConfirm; + const serverMismatch = !!data.serverPassword && data.serverPassword !== data.serverPasswordConfirm; const fieldStyle = (hasValue: boolean, mismatch: boolean) => ({ - background: "rgba(10,10,30,0.8)", + background: "var(--surface)", borderColor: mismatch ? "var(--neon-red)" : !hasValue ? "rgba(255,0,85,0.5)" : "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)", }); @@ -663,6 +776,53 @@ function BasicInfoStep({ )}
+ + {/* Message of the Day */} +
+
+ + + + + + + Shown to players in a pop-up when they join. Leave blank to disable. Use \n for line breaks. + + +
+