diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2a98b98..97eb4f0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -66,43 +66,45 @@ jobs: releaseBody: | ## LokiASAM ${{ github.ref_name }} — Public Beta - LokiASAM is a desktop application for managing Ark Survival Ascended dedicated servers on Linux and Windows. + LokiASAM is a desktop application for managing ARK: Survival Ascended dedicated servers on Linux and Windows. - ### What's new in v0.12.0 + ### What's new in ${{ github.ref_name }} - **Firewall management** - LokiASAM can now detect your system firewall (UFW, firewalld, iptables on Linux; Windows Defender Firewall on Windows) and open the required ports for each server with a single elevation prompt. A dedicated Firewall step in the server creation wizard checks port status and offers to fix missing rules before you ever try to start. A non-blocking warning notification is shown at startup if a rule is missing. You can also check and repair rules for all servers at any time from Settings → Tools → Firewall Rules. When deleting a server, you're offered the option to clean up firewall rules for ports that no longer have any server behind them. + **Server Creation Wizard — major overhaul** + The Guided Custom section has been reworked from a single slider page into four dedicated steps: **Core Rates**, **Breeding**, **Combat**, and **Server QoL**. Each step covers the relevant settings with sliders, toggles, and contextual help. The Breeding page includes a live warning when food consumption is set higher than mature speed — a common misconfiguration that causes baby dinos to starve before they fully mature. - **Amazon Root CA certificate install** - Servers with mods can fail to start with a CurseForge API TLS error when the Amazon Root CA 1 certificate is missing from the Wine/Windows cert store. The setup wizard now includes a certificate install step that fixes this automatically. The same action is available under Settings → Tools → Amazon Root CA for reinstallation at any time. + **Preset config fixes** + The Official, Casual, and Boosted presets now correctly apply all `GameUserSettings.ini` and `Game.ini` values per game mode, matching the documented target settings for each style. - **CurseForge API auto-retry** - When a server exits immediately after logging the CurseForge "serverUnreachable" error, LokiASAM now automatically retries the launch up to three times before declaring start-failed. This handles the common case where the CurseForge API is briefly rate-limiting or slow at startup. If all three attempts fail, a detailed notification explains the cause and suggests next steps. + **Full Customize INI — tooltip descriptions** + Every field in the Full Customize INI section now has a `?` icon that shows a description tooltip on hover, making it easier to understand what each setting does without leaving the wizard. - **Expanded backup system** - Backups now support three types: full server backups, player save backups (per player EOS ID), and INI config backups. Player backups can be restored individually. The backup tab and scheduler have been updated to reflect the new options. + **INI field defaults** + Fields that are not explicitly set by the selected preset now show their documented game default value instead of `0`. - **Logs page** - A dedicated Logs page is now accessible from the sidebar. It provides four views: Live (tail of the current ShooterGame.log), Archive (past session logs), Crashes (crash dump files), and Chat (chat log history). Logs are automatically archived when a server stops or crashes so previous sessions are always accessible. Old logs are cleaned up automatically based on retention settings. + **Map list correction** + Genesis Part 1 has been removed from the available map list — it is not yet released for ARK: Survival Ascended. - **Auto-start on launch** - Each server now has an auto-start toggle. Servers marked for auto-start will be queued and started sequentially when the app launches, one at a time to avoid overloading the host. + **Slider improvements** + The default value marker on all sliders has been relabelled from `def` to `default` and its alignment has been corrected to match the actual thumb position at all values. - **Quick Start Guide** - A `?` button in the sidebar opens the Quick Start Guide from anywhere in the app. The guide now includes a slide covering port forwarding and VPN services for players connecting from outside your home network. Clicking "Quick Start Guide" on the setup wizard completion screen takes you directly to the dashboard with the guide already open. + **Password visibility toggles** + All password inputs now have an eye icon to reveal or hide the entered text — admin password, server password, their confirm fields, and the SMTP password in the setup wizard. - **Updated application icons** - New icon set with improved clarity at all sizes. Linux builds include adaptive launcher icons. + **Live chat log** + The chat panel now updates in real time via Tauri events. No manual refresh is needed. - ### Improvements + **Cleaner server restart** + Server restarts now use RCON `saveworld` followed by `doexit` for a clean, save-first shutdown instead of a raw process signal. - - **Setup wizard** — auto-update settings are now configured during first-time setup. The wizard completion screen includes a Quick Start Guide button that opens the tour on the dashboard. - - **Server creation wizard** — added a Firewall step and a port forwarding info card in the Network step. - - **Logs tab** — the per-server Logs tab now loads the last session's log on open, even when the server is stopped. Logs are archived automatically on server state changes. - - **Mods tab** — added a note reminding users that a server restart is required for mod changes to take effect. - - **Sidebar** — Logs and Backups are now top-level navigation items. Tooltip backgrounds and contrast improved across all nav items. - - **Theme** — updated built-in theme presets and accent colours for improved consistency. - - **Settings** — Tools section now includes rows for certificate install/reinstall and firewall rule check/repair. + **Notification system improvements** + Notification matrix state management has been reworked and event wiring fixed. Auto-update notification options have been reworked. + + **Setup wizard additions** + Directory wipe functionality added. Build version is now tracked and displayed in the wizard footer. + + **Backup & scheduling fixes** + Backup scheduling accuracy improved. Schedule filtering logic corrected. ### Installation @@ -114,12 +116,9 @@ jobs: | `.deb` | Yes | Installs via `dpkg`, prompts for your password | | `.rpm` | Yes | Installs via `rpm`, prompts for your password | - ```bash - chmod +x LokiASAM_0.12.0_amd64.AppImage - ./LokiASAM_0.12.0_amd64.AppImage - ``` + > **Arch / CachyOS / Manjaro:** AppImage does not work reliably on rolling-release distros. Build from source using `./install.sh` instead — see the [README](https://github.com/LokiRothbrook/LokiASAM#arch-linux--cachyos--manjaro) for instructions. - **Windows:** Download and run `LokiASAM_0.12.0_x64-setup.exe` from the assets below. + **Windows:** Download and run the `_x64-setup.exe` installer from the assets below. ### Notes - This is a public beta — bugs are expected. Please report them on the [Issues](https://github.com/LokiRothbrook/LokiASAM/issues) page. diff --git a/.gitignore b/.gitignore index 1d7cb62..4122460 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,9 @@ yarn-error.log* *.tsbuildinfo next-env.d.ts +# planning docs (local only) +/doc/ + # makepkg build artifacts packaging/arch/src/ packaging/arch/pkg/ diff --git a/package.json b/package.json index 55ce545..b66b462 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lokiasam", - "version": "0.13.1", + "version": "0.14.0", "private": true, "scripts": { "dev": "next dev", diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index 6b4d398..3bc6015 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -1,6 +1,6 @@ # Maintainer: Arron Ohnemus pkgname=lokiasam -pkgver=0.13.1 +pkgver=0.14.0 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 f5cf127..582b9b7 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2727,7 +2727,7 @@ dependencies = [ [[package]] name = "lokiasam" -version = "0.13.1" +version = "0.14.0" dependencies = [ "configparser", "flate2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 50e8098..d7a496e 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lokiasam" -version = "0.13.1" +version = "0.14.0" description = "Loki Ark Survival Ascended Server Manager" authors = ["Loki"] license = "GPL-3.0-or-later" diff --git a/src-tauri/src/commands/backup_manager.rs b/src-tauri/src/commands/backup_manager.rs index 69b2656..64824d5 100644 --- a/src-tauri/src/commands/backup_manager.rs +++ b/src-tauri/src/commands/backup_manager.rs @@ -513,7 +513,7 @@ pub async fn execute_tick(app: &AppHandle) { } // ── Server backup ────────────────────────────────────────────────── - if server_active { + let server_outcome: Option> = if server_active { if let Some(cfg) = server_cfg { match create_server_backup_inner( app, @@ -530,33 +530,22 @@ pub async fn execute_tick(app: &AppHandle) { ).await { Ok(rec) => { handle_backup_record(&conn, &rec, &cfg, "server", None); - let size = fmt_size(rec.file_size_bytes); - crate::commands::notifications::dispatch_notification( - app, "backup_completed", Some(&server.id), &server.name, - "Backup Complete", &format!("Scheduled server backup completed ({size})"), "success", - ).await; - let _ = app.emit( - &format!("backup://completed/{}", server.id), - serde_json::json!({ "serverId": server.id }), - ); + Some(Ok(fmt_size(rec.file_size_bytes))) } Err(e) => { eprintln!("[backup_manager] Server backup failed for {}: {e}", server.name); - crate::commands::notifications::dispatch_notification( - app, "backup_failed", Some(&server.id), &server.name, - "Backup Failed", &format!("Scheduled server backup failed: {e}"), "error", - ).await; - let _ = app.emit( - &format!("backup://completed/{}", server.id), - serde_json::json!({ "serverId": server.id, "error": e }), - ); + Some(Err(e)) } } + } else { + None } - } + } else { + None + }; // ── Player backup ────────────────────────────────────────────────── - if player_active { + let player_outcome: Option> = if player_active { if let Some(cfg) = player_cfg { match backup_all_players_inner( app, @@ -574,22 +563,100 @@ pub async fn execute_tick(app: &AppHandle) { let eos_id = rec.player_eosid.as_deref(); handle_backup_record(&conn, rec, &cfg, "player", eos_id); } - if count > 0 { - crate::commands::notifications::dispatch_notification( - app, "backup_completed", Some(&server.id), &server.name, - "Backup Complete", &format!("Scheduled player backups completed ({count} players)"), "success", - ).await; - } + Some(Ok(count)) } Err(e) => { eprintln!("[backup_manager] Player backup failed for {}: {e}", server.name); - crate::commands::notifications::dispatch_notification( - app, "backup_failed", Some(&server.id), &server.name, - "Backup Failed", &format!("Scheduled player backup failed: {e}"), "error", - ).await; + Some(Err(e)) } } + } else { + None } + } else { + None + }; + + // ── Consolidated notification ────────────────────────────────────── + // 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 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"), + "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})"), + "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}"), + "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"), + "error", + )), + // Both ran — server failed, 0 players + (Some(Err(se)), Some(Ok(_))) => Some(( + "backup_failed", "Server Backup Failed", + format!("Scheduled 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}"), + "error", + )), + // Server only + (Some(Ok(size)), None) => Some(( + "backup_completed", "Server Backup Complete", + format!("Scheduled server backup completed ({size})"), + "success", + )), + (Some(Err(se)), None) => Some(( + "backup_failed", "Server Backup Failed", + format!("Scheduled 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)"), + "success", + )), + (None, Some(Err(pe))) => Some(( + "backup_failed", "Player Backup Failed", + format!("Scheduled player backup failed: {pe}"), + "error", + )), + // Player only with 0 profiles, or nothing ran + _ => None, + }; + + if let Some((event_type, title, body, severity)) = notification { + crate::commands::notifications::dispatch_notification( + app, event_type, Some(&server.id), &server.name, + title, &body, severity, + ).await; + } + + // Single UI-refresh event whenever any backup was attempted for this server. + if server_outcome.is_some() || player_outcome.is_some() { + let _ = app.emit( + &format!("backup://completed/{}", server.id), + serde_json::json!({ "serverId": server.id }), + ); } } } diff --git a/src-tauri/src/commands/build_version.rs b/src-tauri/src/commands/build_version.rs new file mode 100644 index 0000000..819f8a8 --- /dev/null +++ b/src-tauri/src/commands/build_version.rs @@ -0,0 +1,310 @@ +// build_version.rs — ASA build ID → human-readable game version (e.g. "49.23") +// +// Two sources, in priority order: +// "internet" – Steam News API title parse, fetched once per build_id right +// after SteamCMD downloads it (so the latest news matches the +// latest build). +// "server" – A2S_INFO Source Query against localhost once the server +// confirms running. Always overwrites "internet". + +use crate::{db, state::AppState}; +use tauri::Manager; + +// ── Version sources ─────────────────────────────────────────────────────────── + +const OFFICIAL_SERVER_LIST_URL: &str = + "https://cdn2.arkdedicated.com/servers/asa/officialserverlist.json"; + +const PATCH_NOTES_URL: &str = + "https://survivetheark.com/index.php?/forums/topic/708761-asa-pc-patch-notes-client"; + +/// Fetch the current ASA version from the official Wildcard server list. +/// This is the same JSON the game client uses for the server browser, so it +/// reflects the live version exactly. Returns e.g. "88.23". +async fn fetch_version_from_official_list() -> Option { + #[derive(serde::Deserialize)] + struct Entry { + #[serde(rename = "BuildId")] + build_id: u32, + #[serde(rename = "MinorBuildId")] + minor_build_id: u32, + } + + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(15)) + .user_agent("LokiASAM/1.0") + .build() + .ok()?; + + let entries: Vec = client + .get(OFFICIAL_SERVER_LIST_URL) + .send() + .await + .ok()? + .json() + .await + .ok()?; + + let first = entries.into_iter().next()?; + Some(format!("{}.{}", first.build_id, first.minor_build_id)) +} + +/// Extract "88.3" from text like "v88.3 - Major version for Servers…" +/// Requires at least a 2-digit major so single-digit noise is skipped. +fn extract_version_from_patch_notes(text: &str) -> Option { + let s = text.as_bytes(); + let mut i = 0; + while i < s.len() { + // Require explicit 'v' / 'V' prefix so bare numbers are ignored + if (s[i] != b'v' && s[i] != b'V') || i + 1 >= s.len() || !s[i + 1].is_ascii_digit() { + i += 1; + continue; + } + let num_start = i + 1; + let mut j = num_start; + while j < s.len() && s[j].is_ascii_digit() { j += 1; } + let major_len = j - num_start; + if major_len < 2 || j >= s.len() || s[j] != b'.' { + i += 1; + continue; + } + j += 1; // skip dot + let minor_start = j; + while j < s.len() && s[j].is_ascii_digit() { j += 1; } + if j == minor_start { + i += 1; + continue; + } + // Return "MAJOR.MINOR" (drop any trailing .patch suffix) + return Some(text[num_start..j].to_string()); + } + None +} + +/// Fetch the most recent ASA version string from the survivetheark.com patch +/// notes thread. The forum meta description always leads with the newest entry +/// so we only need to parse those first few hundred characters. +async fn fetch_version_from_patch_notes() -> Option { + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(15)) + .user_agent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \ + (KHTML, like Gecko) Chrome/125.0 Safari/537.36") + .build() + .ok()?; + + let html = client.get(PATCH_NOTES_URL).send().await.ok()?.text().await.ok()?; + + // The forum renders the first ~300 chars of post body as the meta description, + // which always starts with the most recently prepended version entry. + let meta_start = html.find(" Option { + use tokio::net::UdpSocket; + use tokio::time::{timeout, Duration}; + + let sock = UdpSocket::bind("0.0.0.0:0").await.ok()?; + sock.connect(format!("127.0.0.1:{port}")).await.ok()?; + + let base_req: &[u8] = b"\xFF\xFF\xFF\xFF\x54Source Engine Query\x00"; + let mut req = base_req.to_vec(); + + sock.send(&req).await.ok()?; + + let mut buf = [0u8; 1400]; + + // Up to two rounds: initial send + one challenge re-send + for _ in 0..2u8 { + let n = timeout(Duration::from_secs(5), sock.recv(&mut buf)) + .await + .ok()?.ok()?; + + if n < 5 || buf[0..4] != [0xFF, 0xFF, 0xFF, 0xFF] { + return None; + } + + match buf[4] { + 0x41 => { + // Challenge response — resend query with 4-byte challenge appended + if n < 9 { + return None; + } + let mut new_req = base_req.to_vec(); + new_req.extend_from_slice(&buf[5..9]); + req = new_req; + sock.send(&req).await.ok()?; + } + 0x49 => { + // A2S_INFO response — parse for version string + return parse_a2s_version(&buf[5..n]); + } + _ => return None, + } + } + None +} + +/// Parse an A2S_INFO response body (after the 0xFF×4 0x49 header) for the +/// version string. Layout: protocol(1), name, map, folder, game (null-term +/// 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 { + 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 + } + + // Skip: app_id(2) + players(1) + max_players(1) + bots(1) + + // server_type(1) + environment(1) + visibility(1) + vac(1) = 9 bytes + pos += 9; + + if pos >= data.len() { + 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()?; + if version.is_empty() { + return None; + } + + // Normalise to "MAJOR.MINOR" (e.g. "49.23.0" → "49.23") + let parts: Vec<&str> = version.split('.').collect(); + if parts.len() >= 2 { + Some(format!("{}.{}", parts[0], parts[1])) + } else { + Some(version.to_string()) + } +} + +// ── Public helpers called by steamcmd.rs and server.rs ─────────────────────── + +/// After SteamCMD downloads a new build: store the build_id against the server +/// row and fetch the internet version if this build_id isn't cached yet. +/// Runs the internet fetch in a background task (fire and forget). +pub fn record_install(app: &tauri::AppHandle, server_id: &str, build_id: &str) { + let Some(db_path) = app.state::().get_db_path() else { return }; + if let Ok(conn) = db::open(&db_path) { + let _ = db::set_server_installed_build(&conn, server_id, build_id); + } + maybe_fetch_internet(app, build_id); +} + +/// Trigger an internet version fetch for a build_id unless already +/// server-confirmed. Spawns a background task — does not block. +/// Re-fetches on every call when source is "internet" so a failed parse +/// (game_version = null) is retried on each update check. +pub fn maybe_fetch_internet(app: &tauri::AppHandle, build_id: &str) { + let Some(db_path) = app.state::().get_db_path() else { return }; + + // Skip only if server-confirmed — internet entries may lack a version and + // should be retried until we get one (or the server query overwrites them) + if let Ok(conn) = db::open(&db_path) { + if let Some((_, src)) = db::get_build_game_version(&conn, build_id) { + if src == "server" { + return; + } + } + } else { + return; + } + + let build_id = build_id.to_string(); + tauri::async_runtime::spawn(async move { + // Try the official Wildcard server list first (real-time, structured JSON). + // Fall back to the survivetheark.com forum post if that fails. + let version = match fetch_version_from_official_list().await { + Some(v) => Some(v), + None => fetch_version_from_patch_notes().await, + }; + if let Ok(conn) = db::open(&db_path) { + let _ = db::upsert_build_game_version( + &conn, + &build_id, + version.as_deref(), + "internet", + ); + } + }); +} + +/// After a server confirms running: try A2S to get the server-confirmed version +/// and store it (overwrites "internet" source). Fire and forget. +pub fn maybe_capture_server_version(app: &tauri::AppHandle, server_id: &str, query_port: u16) { + let Some(db_path) = app.state::().get_db_path() else { return }; + + // Read the installed_build_id for this server + let build_id = { + let Ok(conn) = db::open(&db_path) else { return }; + match conn.query_row( + "SELECT installed_build_id FROM servers WHERE id = ?1", + [server_id], + |row| row.get::<_, Option>(0), + ) { + Ok(Some(b)) => b, + _ => return, + } + }; + + // Skip if already server-confirmed + { + let Ok(conn) = db::open(&db_path) else { return }; + if let Some((_, src)) = db::get_build_game_version(&conn, &build_id) { + if src == "server" { + return; + } + } + } + + tauri::async_runtime::spawn(async move { + if let Some(version) = source_query_version(query_port).await { + if let Ok(conn) = db::open(&db_path) { + let _ = db::upsert_build_game_version( + &conn, + &build_id, + Some(&version), + "server", + ); + } + } + }); +} + +// ── Tauri command ───────────────────────────────────────────────────────────── + +/// Manually trigger an internet version fetch for a build_id. Returns the +/// game_version if now available, or None if the fetch failed / build unknown. +#[tauri::command] +pub async fn fetch_build_version( + build_id: String, + state: tauri::State<'_, AppState>, +) -> Result, String> { + let db_path = state.get_db_path().ok_or("DB path not set")?; + + // Always re-fetch (user triggered) — official list first, forum scrape fallback + let version = match fetch_version_from_official_list().await { + Some(v) => Some(v), + None => fetch_version_from_patch_notes().await, + }; + let conn = db::open(&db_path)?; + db::upsert_build_game_version(&conn, &build_id, version.as_deref(), "internet")?; + Ok(version) +} diff --git a/src-tauri/src/commands/certs.rs b/src-tauri/src/commands/certs.rs index eb19ce1..18d06a0 100644 --- a/src-tauri/src/commands/certs.rs +++ b/src-tauri/src/commands/certs.rs @@ -103,33 +103,48 @@ 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 wine_bin = format!("{proton_path}/files/bin/wine64"); - let wine_pfx = format!("{prefix_path}/pfx"); - let marker = PathBuf::from(prefix_path).join(CERT_MARKER_FILENAME); - - // Initialise the Wine prefix if it has not been set up yet. wineboot -u - // creates the fake C: drive, registry hives, etc. without blocking on - // Mono/Gecko downloads. This can take up to ~30 s on first run. + let proton_script = format!("{proton_path}/proton"); + let wine_bin = format!("{proton_path}/files/bin/wine64"); + let wine_pfx = format!("{prefix_path}/pfx"); + let marker = PathBuf::from(prefix_path).join(CERT_MARKER_FILENAME); + + // Initialise the Wine prefix if it has not been set up yet. + // Use the Proton run script (same mechanism as server start) rather than + // wine64 directly — Proton-GE's wine64 is compiled for the Steam Linux + // Runtime and may fail outside it. `proton run` handles environment setup. + // Setting STEAM_COMPAT_CLIENT_INSTALL_PATH to a dummy value prevents + // Proton from trying to use the Steam Runtime daemon when Steam is installed. let system_reg = format!("{wine_pfx}/system.reg"); if !tokio::fs::try_exists(&system_reg).await.unwrap_or(false) { - let status = Command::new(&wine_bin) - .args(["wineboot", "-u"]) - .env("WINEPREFIX", &wine_pfx) + // Create parent directories so Proton can create the pfx inside. + tokio::fs::create_dir_all(&wine_pfx) + .await + .map_err(|e| format!("Failed to create prefix directory: {e}"))?; + + let status = Command::new(&proton_script) + .arg("run") + .arg("C:\\windows\\system32\\wineboot.exe") + .env("STEAM_COMPAT_DATA_PATH", prefix_path) + .env("STEAM_COMPAT_CLIENT_INSTALL_PATH", "/") .env("WINEDLLOVERRIDES", "mscoree,mshtml=") .env("WINEDEBUG", "-all") + .env("PROTON_LOG", "0") .status() .await - .map_err(|e| format!("Failed to run wineboot: {e}"))?; + .map_err(|e| format!("Failed to run proton wineboot: {e}"))?; - if !status.success() { + // Proton may exit non-zero even on success (wineboot is a short-lived + // process). Check that the prefix was actually created instead. + if !tokio::fs::try_exists(&system_reg).await.unwrap_or(false) { return Err(format!( - "wineboot exited with code {}", + "Wine prefix initialisation failed (proton exited {}); try starting a server once first.", status.code().unwrap_or(-1) )); } } // Install the certificate into Wine's CurrentUser\Root store. + // At this point the prefix exists, so wine64 can run standalone. let status = Command::new(&wine_bin) .args(["certutil", "-addstore", "Root", cert_path]) .env("WINEPREFIX", &wine_pfx) diff --git a/src-tauri/src/commands/logs.rs b/src-tauri/src/commands/logs.rs index 17d61e1..34d56a7 100644 --- a/src-tauri/src/commands/logs.rs +++ b/src-tauri/src/commands/logs.rs @@ -50,17 +50,6 @@ pub struct ChatLogInfo { pub full_path: String, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct LogStats { - pub shootergame_archive_count: u32, - pub shootergame_total_bytes: u64, - pub chat_log_count: u32, - pub chat_total_bytes: u64, - pub crash_count: u32, - pub storage_root: String, -} - // --------------------------------------------------------------------------- // Watch commands // --------------------------------------------------------------------------- @@ -552,39 +541,6 @@ pub async fn cleanup_logs( Ok(deleted) } -/// Get log storage statistics for a server. -#[tauri::command] -pub async fn get_log_stats( - app: tauri::AppHandle, - server_id: String, -) -> Result { - let root = LogManagerState::server_logs_dir(&app, &server_id); - let storage_root = root - .as_ref() - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_default(); - - let sg_dir = root.as_ref().map(|d| d.join("shootergame")); - let chat_dir = root.as_ref().map(|d| d.join("chat")); - let crash_dir = root.as_ref().map(|d| { - // crashes live in the install dir, but we reference them from here - d.clone() - }); - let _ = crash_dir; // placeholder until we store crashes centrally - - let (sg_count, sg_bytes) = count_dir(sg_dir.as_deref()).await; - let (chat_count, chat_bytes) = count_dir(chat_dir.as_deref()).await; - - Ok(LogStats { - shootergame_archive_count: sg_count, - shootergame_total_bytes: sg_bytes, - chat_log_count: chat_count, - chat_total_bytes: chat_bytes, - crash_count: 0, // populated by list_crashes on demand - storage_root, - }) -} - /// Return the path to the central logs storage root (for display in UI). #[tauri::command] pub fn get_log_storage_root(app: tauri::AppHandle) -> String { @@ -594,29 +550,6 @@ pub fn get_log_storage_root(app: tauri::AppHandle) -> String { } // --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -async fn count_dir(dir: Option<&std::path::Path>) -> (u32, u64) { - let dir = match dir { - Some(d) if d.exists() => d, - _ => return (0, 0), - }; - let mut count = 0u32; - let mut bytes = 0u64; - if let Ok(mut rd) = tokio::fs::read_dir(dir).await { - while let Ok(Some(entry)) = rd.next_entry().await { - if let Ok(meta) = entry.metadata().await { - if meta.is_file() { - count += 1; - bytes += meta.len(); - } - } - } - } - (count, bytes) -} - /// Extract the timestamp string from a filename like `ShooterGame_2026-06-08_14-30-00.log`. fn extract_timestamp_from_filename(name: &str) -> String { // ShooterGame_YYYY-MM-DD_HH-MM-SS.log diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index e265a43..38045a3 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -1,5 +1,6 @@ pub mod backup; pub mod backup_manager; +pub mod build_version; pub mod countdown; pub mod certs; pub mod firewall; diff --git a/src-tauri/src/commands/rcon.rs b/src-tauri/src/commands/rcon.rs index e4b0e1c..8df43b2 100644 --- a/src-tauri/src/commands/rcon.rs +++ b/src-tauri/src/commands/rcon.rs @@ -393,78 +393,94 @@ pub async fn rcon_connect( error: None, }); - let stream = timeout( - Duration::from_secs(5), - TcpStream::connect(format!("{host}:{port}")), - ) - .await - .map_err(|_| "RCON connection timed out".to_string())? - .map_err(|e| format!("RCON connect failed: {e}"))?; - - let _ = stream.set_nodelay(true); - let mut conn = RconConn { stream, next_id: 1 }; - - let auth_id = conn.next_id; - conn.next_id += 1; - conn.send_packet(auth_id, RCON_AUTH, &password).await?; + // Run the full connect+auth sequence in an inner block so every failure + // path falls through to a single "disconnected" emit below. + let result: Result<(), String> = async { + let stream = timeout( + Duration::from_secs(5), + TcpStream::connect(format!("{host}:{port}")), + ) + .await + .map_err(|_| "RCON connection timed out".to_string())? + .map_err(|e| format!("RCON connect failed: {e}"))?; - let mut authenticated = false; - for _ in 0..3 { - let result = timeout(Duration::from_secs(5), conn.recv_packet()) - .await - .map_err(|_| "RCON auth timed out — no response from server".to_string())?; - let (resp_id, resp_type, _body) = result?; - if resp_type == RCON_AUTH_RESPONSE { - if resp_id == -1 { - return Err("RCON authentication failed — wrong password".into()); - } - if resp_id == auth_id { - authenticated = true; - break; + let _ = stream.set_nodelay(true); + let mut conn = RconConn { stream, next_id: 1 }; + + let auth_id = conn.next_id; + conn.next_id += 1; + conn.send_packet(auth_id, RCON_AUTH, &password).await?; + + let mut authenticated = false; + for _ in 0..3 { + let result = timeout(Duration::from_secs(5), conn.recv_packet()) + .await + .map_err(|_| "RCON auth timed out — no response from server".to_string())?; + let (resp_id, resp_type, _body) = result?; + if resp_type == RCON_AUTH_RESPONSE { + if resp_id == -1 { + return Err("RCON authentication failed — wrong password".into()); + } + if resp_id == auth_id { + authenticated = true; + break; + } } } - } - if !authenticated { - return Err("RCON authentication failed — unexpected response sequence".into()); - } - - let conn_id = pool.alloc_conn_id(); - let (tx, rx) = mpsc::channel::(32); - pool.cmd_channels.lock().await.insert(server_id.clone(), (tx.clone(), conn_id)); - - // Spawn the manager task — it owns the connection from here on. - let app_clone = app.clone(); - let sid = server_id.clone(); - let h = host.clone(); - tauri::async_runtime::spawn(async move { - run_rcon_manager(sid, conn_id, conn, rx, app_clone, h, port).await; - }); - - emit_log(&app, &server_id, RconLogLine { - timestamp_ms: now_ms(), - text: format!("Connected to RCON at {host}:{port}"), - kind: "system".into(), - }).await; - - emit_status(&app, RconStatusPayload { - server_id: server_id.clone(), - status: "connected".into(), - host: Some(host), - port: Some(port), - error: None, - }); - - // Seed the player cache asynchronously — the event will update the frontend. - let tx_seed = tx.clone(); - tauri::async_runtime::spawn(async move { - let (resp_tx, resp_rx) = oneshot::channel(); - if tx_seed.send(RconCmd::GetPlayers { response_tx: resp_tx }).await.is_ok() { - let _ = resp_rx.await; + if !authenticated { + return Err("RCON authentication failed — unexpected response sequence".into()); } - }); - Ok(()) + let conn_id = pool.alloc_conn_id(); + let (tx, rx) = mpsc::channel::(32); + pool.cmd_channels.lock().await.insert(server_id.clone(), (tx.clone(), conn_id)); + + // Spawn the manager task — it owns the connection from here on. + let app_clone = app.clone(); + let sid = server_id.clone(); + let h = host.clone(); + tauri::async_runtime::spawn(async move { + run_rcon_manager(sid, conn_id, conn, rx, app_clone, h, port).await; + }); + + emit_log(&app, &server_id, RconLogLine { + timestamp_ms: now_ms(), + text: format!("Connected to RCON at {host}:{port}"), + kind: "system".into(), + }).await; + + emit_status(&app, RconStatusPayload { + server_id: server_id.clone(), + status: "connected".into(), + host: Some(host.clone()), + port: Some(port), + error: None, + }); + + // Seed the player cache asynchronously — the event will update the frontend. + let tx_seed = tx.clone(); + tauri::async_runtime::spawn(async move { + let (resp_tx, resp_rx) = oneshot::channel(); + if tx_seed.send(RconCmd::GetPlayers { response_tx: resp_tx }).await.is_ok() { + let _ = resp_rx.await; + } + }); + + Ok(()) + }.await; + + if let Err(ref e) = result { + emit_status(&app, RconStatusPayload { + server_id, + status: "disconnected".into(), + host: Some(host), + port: Some(port), + error: Some(e.clone()), + }); + } + + result } /// Send an RCON command through the manager task queue. diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index b6e175d..691bc96 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -1,9 +1,8 @@ use crate::state::{scheduler::SchedulerState, AppState}; -use serde::{Deserialize, Serialize}; +use serde::Serialize; use std::time::{SystemTime, UNIX_EPOCH}; use tauri::{AppHandle, Emitter, Manager}; use tokio::time::{sleep, Duration}; -use uuid::Uuid; use super::server::{inner_start_server, inner_stop_server, StartServerParams}; @@ -11,15 +10,6 @@ use super::server::{inner_start_server, inner_stop_server, StartServerParams}; // Types // --------------------------------------------------------------------------- -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ScheduleConfig { - pub server_id: String, - pub schedule_type: String, - pub cron_expression: String, - pub config_json: String, -} - /// Emitted as the payload of `scheduler://fired` so the frontend can update /// SQLite (last_run / next_run) and requeue the entry via sync_schedules. #[derive(Debug, Serialize, Clone)] @@ -39,25 +29,6 @@ pub struct SchedulerFiredPayload { // Tauri commands // --------------------------------------------------------------------------- -/// Generate and return a UUID for a new schedule. -/// All schedule persistence is handled by the frontend via SQLite (db.ts). -#[tauri::command] -pub async fn create_schedule(_config: ScheduleConfig) -> Result { - Ok(Uuid::new_v4().to_string()) -} - -/// No-op — the frontend removes the schedule record from SQLite, then calls sync_schedules. -#[tauri::command] -pub async fn delete_schedule(_schedule_id: String) -> Result<(), String> { - Ok(()) -} - -/// No-op — the frontend updates the enabled flag in SQLite, then calls sync_schedules. -#[tauri::command] -pub async fn toggle_schedule(_schedule_id: String, _enabled: bool) -> Result<(), String> { - Ok(()) -} - /// Atomically replace all active schedule entries. /// /// Called by the frontend whenever schedules are created, updated, toggled, or deleted, @@ -226,6 +197,11 @@ async fn fire_global_update_check( let new_build = crate::commands::steamcmd::get_cache_build_id(&cache_dir) .unwrap_or_else(|| old_build.clone()); + // Trigger internet version fetch for a newly-downloaded build + if new_build != "0" { + crate::commands::build_version::maybe_fetch_internet(app, &new_build); + } + let _ = app.emit( crate::events::ASA_UPDATE_CHECK, serde_json::json!({ @@ -331,6 +307,13 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE .map_err(|e| format!("Sync task panicked: {e}"))? .map_err(|e| format!("Failed to sync server files: {e}"))?; + // Record updated build ID and trigger internet version fetch + let acf = std::path::Path::new(&entry.install_path) + .join(crate::commands::steamcmd::ACF_REL_PATH); + if let Some(build_id) = crate::commands::steamcmd::read_acf_build_id(&acf) { + crate::commands::build_version::record_install(app, &entry.server_id, &build_id); + } + let _ = app.emit(crate::events::ASA_UPDATE_CHECK, serde_json::json!({ "updateApplied": true, "serverId": entry.server_id, @@ -354,6 +337,7 @@ fn entry_to_start_params(entry: &crate::state::scheduler::ScheduleEntry) -> Star 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(), diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 619f0aa..7ab8a70 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -105,6 +105,9 @@ pub struct StartServerParams { /// RCON TCP port — NOT passed on CLI; used internally for readiness polling. /// The actual value is read by the server from GameUserSettings.ini [ServerSettings]. pub rcon_port: u16, + /// RCON password — NOT passed on CLI; used internally for graceful shutdown + /// (saveworld/doexit) and readiness polling. + pub rcon_password: String, /// Additional CLI-only flags, e.g. ["-NoBattlEye", "-ForceRespawnDinos"]. pub extra_args: Vec, /// CurseForge mod IDs to load. Passed as `-mods=id1,id2,...`. @@ -686,6 +689,9 @@ async fn inner_start_server_with_state( if buf.contains(READY_MSG) { confirmed2.store(true, Ordering::Relaxed); confirm_running(&handle2, &sid2); + crate::commands::build_version::maybe_capture_server_version( + &handle2, &sid2, query_port2, + ); return; } if buf.contains("Error querying server mods: ApiError: Failed (serverUnreachable)") { @@ -734,6 +740,9 @@ async fn inner_start_server_with_state( if log_confirmed { confirmed2.store(true, Ordering::Relaxed); confirm_running(&handle2, &sid2); + crate::commands::build_version::maybe_capture_server_version( + &handle2, &sid2, query_port2, + ); return; } @@ -742,6 +751,9 @@ async fn inner_start_server_with_state( if try_source_query_local(query_port2).await { confirmed2.store(true, Ordering::Relaxed); confirm_running(&handle2, &sid2); + crate::commands::build_version::maybe_capture_server_version( + &handle2, &sid2, query_port2, + ); return; } sleep(Duration::from_secs(5)).await; @@ -750,6 +762,9 @@ async fn inner_start_server_with_state( // 3. Last resort — promote regardless. confirmed2.store(true, Ordering::Relaxed); confirm_running(&handle2, &sid2); + crate::commands::build_version::maybe_capture_server_version( + &handle2, &sid2, query_port2, + ); }); Ok(pid) @@ -811,17 +826,25 @@ pub async fn inner_restart_server( state.stopping_servers.lock().unwrap().insert(params.server_id.clone()); } - kill_process_tree(pid, graceful, &install_path); - - // Wait up to 15 s for the process to exit. - for _ in 0..30 { - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - if !pid_alive(pid) { - break; + 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; } } + } else { + kill_process_tree(pid, false, &install_path); + tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; } - // Ensure it's gone regardless. + // Force-kill anything still alive after the graceful window. if pid_alive(pid) { kill_process_tree(pid, false, &install_path); tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; diff --git a/src-tauri/src/commands/steamcmd.rs b/src-tauri/src/commands/steamcmd.rs index 623f5fa..a39683c 100644 --- a/src-tauri/src/commands/steamcmd.rs +++ b/src-tauri/src/commands/steamcmd.rs @@ -8,7 +8,7 @@ use super::utils::{build_steamcmd_cmd, copy_dir_recursive, emit_line, stream_pro const ASA_SERVER_APP_ID: &str = "2430930"; /// Relative path to the appmanifest ACF inside a Steam install directory. -const ACF_REL_PATH: &str = "steamapps/appmanifest_2430930.acf"; +pub const ACF_REL_PATH: &str = "steamapps/appmanifest_2430930.acf"; // --------------------------------------------------------------------------- // ACF / INI helpers @@ -496,6 +496,13 @@ pub async fn install_server( .map_err(|e| format!("Failed to copy server files: {e}"))?; emit_line(&app_handle, &channel, "stdout", "Server installation complete.")?; + + // Record installed build ID and trigger internet version fetch + let acf = 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); + } + Ok(()) }.await; @@ -540,6 +547,13 @@ pub async fn update_server( .map_err(|e| format!("Failed to sync server files: {e}"))?; emit_line(&app_handle, &channel, "stdout", "Server update complete.")?; + + // Record installed build ID and trigger internet version fetch + let acf = 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); + } + Ok(()) }.await; @@ -659,6 +673,12 @@ pub async fn update_cache( 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}."))?; + + // 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); + } + Ok(build_id) } @@ -685,6 +705,12 @@ pub async fn apply_cache_to_server( .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); + } + emit_line(&app_handle, &channel, "stdout", "Server update applied.")?; Ok(()) } diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs index cb5c11d..7058029 100644 --- a/src-tauri/src/commands/system.rs +++ b/src-tauri/src/commands/system.rs @@ -120,6 +120,12 @@ pub struct DirCheckResult { pub writable: bool, pub free_bytes: u64, pub error: Option, + /// Target path does not exist yet and will be created on install. + pub is_new: bool, + /// A LokiASAM database was found inside the target path (existing install). + pub has_lokiasam: bool, + /// Target path exists but contains no files or subdirectories. + pub is_empty: bool, } // --------------------------------------------------------------------------- @@ -135,6 +141,9 @@ pub struct DirCheckResult { pub async fn check_dir(path: String) -> Result { let p = Path::new(&path); + // Whether the target path itself exists (vs. needing to be created). + let is_new = !p.exists(); + // Find the deepest existing ancestor (may be p itself). let check_against = { let mut cursor = p; @@ -149,6 +158,9 @@ pub async fn check_dir(path: String) -> Result { writable: false, free_bytes: 0, error: Some("Cannot find any existing parent directory.".into()), + is_new: true, + has_lokiasam: false, + is_empty: false, }); } } @@ -168,6 +180,9 @@ pub async fn check_dir(path: String) -> Result { "Location is not writable (check permissions on {}).", check_against.display() )), + is_new, + has_lokiasam: false, + is_empty: false, }); } @@ -182,10 +197,23 @@ pub async fn check_dir(path: String) -> Result { .unwrap_or(0) }; + // Check for an existing LokiASAM install and whether the dir is empty. + let (has_lokiasam, is_empty) = if !is_new { + let db_path = p.join("lokiasam").join("lokiasam.db"); + let has_db = db_path.exists(); + let empty = p.read_dir().map(|mut d| d.next().is_none()).unwrap_or(false); + (has_db, empty) + } else { + (false, false) + }; + Ok(DirCheckResult { writable: true, free_bytes, error: None, + is_new, + has_lokiasam, + is_empty, }) } @@ -197,6 +225,44 @@ pub async fn check_file_exists(path: String) -> Result { Ok(Path::new(&path).exists()) } +/// Wipe LokiASAM data from a directory. +/// +/// * `full_wipe = false` — deletes only the `lokiasam/` subdirectory (database, +/// config, logs). Server game files are left intact. +/// * `full_wipe = true` — deletes ALL contents inside `path` (but not `path` +/// itself, so it remains as an empty directory ready for a clean install). +#[tauri::command] +pub async fn wipe_lokiasam_dir(path: String, full_wipe: bool) -> Result<(), String> { + let p = Path::new(&path); + if !p.exists() { + return Ok(()); + } + + if full_wipe { + // Delete every entry inside the directory but keep the directory itself. + let entries = std::fs::read_dir(p) + .map_err(|e| format!("Failed to read directory: {e}"))?; + for entry in entries.flatten() { + let ep = entry.path(); + if ep.is_dir() { + std::fs::remove_dir_all(&ep) + .map_err(|e| format!("Failed to remove {}: {e}", ep.display()))?; + } else { + std::fs::remove_file(&ep) + .map_err(|e| format!("Failed to remove {}: {e}", ep.display()))?; + } + } + } else { + let loki_dir = p.join("lokiasam"); + if loki_dir.exists() { + std::fs::remove_dir_all(&loki_dir) + .map_err(|e| format!("Failed to remove lokiasam directory: {e}"))?; + } + } + + 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, diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index 4a8574b..5326458 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -398,3 +398,60 @@ pub fn log_notification(conn: &Connection, n: &NotifInsert) -> Result<(), String .map_err(|e| format!("log_notification failed: {e}"))?; Ok(()) } + +// --------------------------------------------------------------------------- +// build_version_cache +// --------------------------------------------------------------------------- + +/// Returns the cached (game_version, source) for a build_id, if present. +pub fn get_build_game_version(conn: &Connection, build_id: &str) -> Option<(Option, String)> { + conn.query_row( + "SELECT game_version, source FROM build_version_cache WHERE build_id = ?1", + [build_id], + |row| Ok((row.get::<_, Option>(0)?, row.get::<_, String>(1)?)), + ) + .ok() +} + +/// Upsert a (build_id → game_version) entry. "server" source always wins; +/// never downgrades an existing "server" entry to "internet". +pub fn upsert_build_game_version( + conn: &Connection, + build_id: &str, + version: Option<&str>, + source: &str, +) -> Result<(), String> { + // Don't overwrite a server-confirmed entry with an internet one. + if source != "server" { + let existing: Option = conn.query_row( + "SELECT source FROM build_version_cache WHERE build_id = ?1", + [build_id], + |row| row.get(0), + ).ok(); + if existing.as_deref() == Some("server") { + return Ok(()); + } + } + + conn.execute( + "INSERT INTO build_version_cache (build_id, game_version, source, fetched_at) \ + VALUES (?1, ?2, ?3, strftime('%s','now')) \ + ON CONFLICT(build_id) DO UPDATE SET \ + game_version = excluded.game_version, \ + source = excluded.source, \ + fetched_at = excluded.fetched_at", + rusqlite::params![build_id, version, source], + ) + .map_err(|e| format!("upsert_build_game_version failed: {e}"))?; + Ok(()) +} + +/// Update the installed_build_id column for a specific server. +pub fn set_server_installed_build(conn: &Connection, server_id: &str, build_id: &str) -> Result<(), String> { + conn.execute( + "UPDATE servers SET installed_build_id = ?1 WHERE id = ?2", + [build_id, server_id], + ) + .map_err(|e| format!("set_server_installed_build failed: {e}"))?; + Ok(()) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c9f119e..969804d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -255,7 +255,14 @@ pub fn run() { loop { crate::commands::backup_manager::execute_tick(&backup_tick_handle).await; - tokio::time::sleep(tokio::time::Duration::from_secs(3600)).await; + // Re-anchor to the next wall-clock hour boundary after each + // tick so backup execution time does not cause cumulative drift. + let now_secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let secs_until_next_hour = 3600 - (now_secs % 3600); + tokio::time::sleep(tokio::time::Duration::from_secs(secs_until_next_hour)).await; } }); @@ -450,6 +457,8 @@ pub fn run() { commands::steamcmd::update_cache, commands::steamcmd::apply_cache_to_server, commands::steamcmd::detect_server_install, + // Build version cache + commands::build_version::fetch_build_version, // RCON commands::rcon::rcon_connect, commands::rcon::rcon_send, @@ -475,7 +484,6 @@ pub fn run() { commands::logs::list_chat_logs, commands::logs::read_chat_log, commands::logs::cleanup_logs, - commands::logs::get_log_stats, commands::logs::get_log_storage_root, // Config / INI commands::config::read_server_config, @@ -513,6 +521,7 @@ pub fn run() { commands::system::get_install_method, 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, @@ -541,9 +550,6 @@ pub fn run() { commands::cluster::add_server_to_cluster, commands::cluster::remove_server_from_cluster, // Scheduler - commands::scheduler::create_schedule, - commands::scheduler::delete_schedule, - commands::scheduler::toggle_schedule, commands::scheduler::sync_schedules, ]) .run(tauri::generate_context!()) diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index a8ea526..a8e6689 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.13.1", + "version": "0.14.0", "identifier": "xyz.lokisoft.lokiasam", "build": { "frontendDist": "../out", diff --git a/src/app/backups/page.tsx b/src/app/backups/page.tsx index aa4975d..2be893d 100644 --- a/src/app/backups/page.tsx +++ b/src/app/backups/page.tsx @@ -35,7 +35,7 @@ export default function BackupsPage() { }; return ( -
+
{/* Page header */}
+
) : !isLoading && servers.length === 0 ? ( diff --git a/src/app/clusters/detail/page.tsx b/src/app/clusters/detail/page.tsx index 71a624a..02cb1c9 100644 --- a/src/app/clusters/detail/page.tsx +++ b/src/app/clusters/detail/page.tsx @@ -31,11 +31,13 @@ import { getServers, setServerCluster, getAppSetting, + formatServerVersion, type ClusterRow, type ServerRow, } from "@/lib/db"; import { ARK_MAPS } from "@/data/game-data"; import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; +import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; // --------------------------------------------------------------------------- // Add Server Dialog @@ -151,6 +153,7 @@ interface MemberRowProps { function MemberRow({ server, onRemove }: MemberRowProps) { const router = useRouter(); const map = ARK_MAPS.find((m) => m.id === server.map_id); + const versionCache = useBuildVersionCache(); return (

{map?.displayName ?? server.map_id} · :{server.port} + {server.installed_build_id && ( + <> · {formatServerVersion(server.installed_build_id, versionCache)} + )}

diff --git a/src/app/clusters/page.tsx b/src/app/clusters/page.tsx index ffc81f9..18293b6 100644 --- a/src/app/clusters/page.tsx +++ b/src/app/clusters/page.tsx @@ -313,9 +313,9 @@ export default function ClustersPage() { }, [queryClient]); return ( -
+
{/* Header */} -
+
@@ -343,6 +343,7 @@ export default function ClustersPage() {
+
{/* Cluster Grid */} {isLoading ? (
@@ -396,6 +397,7 @@ export default function ClustersPage() { onClose={() => setDeleteTarget(null)} onDeleted={refresh} /> +
); } diff --git a/src/app/notifications/page.tsx b/src/app/notifications/page.tsx index b17fe8a..85f7032 100644 --- a/src/app/notifications/page.tsx +++ b/src/app/notifications/page.tsx @@ -220,9 +220,9 @@ function NotificationsContent() { }, [refetch, severityFilter, eventTypeFilter]); return ( -
+
{/* Header */} -
+
@@ -244,7 +244,7 @@ function NotificationsContent() { variant="ghost" size="sm" className="text-xs gap-1.5" - style={{ color: "var(--text-muted)", border: "1px solid var(--border)" }} + style={{ color: "var(--neon-red, #f87171)", border: "1px solid rgba(255,0,85,0.3)" }} > Delete… @@ -285,7 +285,7 @@ function NotificationsContent() { {/* Filters */}
@@ -329,6 +329,7 @@ function NotificationsContent() {
{/* List */} +
{filtered.length === 0 ? (
)} +
); } diff --git a/src/app/page.tsx b/src/app/page.tsx index eafc485..4d3bb49 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -2,7 +2,7 @@ import { useEffect, useState, useCallback, useRef } from "react"; import { - Plus, Server, Activity, PowerOff, Power, RefreshCw, Upload, + Plus, Server, Activity, RefreshCw, Upload, ArrowUp, Loader2, CheckCircle2, AlertTriangle, LayoutDashboard, } from "lucide-react"; import { Button } from "@/components/ui/button"; @@ -19,7 +19,7 @@ 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 { runPerServerUpdateCheck, applyUpdateToServer, type ServerUpdateInfo } from "@/lib/update-utils"; +import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToServer, type ServerUpdateInfo } from "@/lib/update-utils"; import { buildStartParams } from "@/lib/server-utils"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; @@ -27,6 +27,9 @@ 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"; +import { getVersion } from "@tauri-apps/api/app"; // --------------------------------------------------------------------------- // UpdateStatusChip — Check for Updates button + post-check dialogs @@ -80,24 +83,12 @@ function UpdateStatusChip({ servers = [], onUpdateAllClick, onUpdatesFound }: Up const handleCheck = async () => { setChecking(true); try { - const [baseDir, steamcmdPath] = await Promise.all([ - getAppSetting("base_dir"), - getAppSetting("steamcmd_path"), - ]); - if (!baseDir || !steamcmdPath) { + const oldBuild = await getAppSetting("asa_cached_build_id") ?? ""; + const newBuild = await runAsaCacheUpdate(); + if (!newBuild) { toast.error("Base directory or SteamCMD not configured."); return; } - const sep = baseDir.includes("\\") ? "\\" : "/"; - const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; - const oldBuild = await getAppSetting("asa_cached_build_id") ?? ""; - const newBuild = await tauriCmd.updateCache("check", cacheDir, steamcmdPath); - const now = new Date().toISOString(); - await Promise.all([ - setAppSetting("asa_cached_build_id", newBuild), - setAppSetting("asa_latest_build_id", newBuild), - setAppSetting("asa_last_checked", now), - ]); // Manual check: silent mode suppresses per-server toasts; we show dialog. const summary = await runPerServerUpdateCheck(true); queryClient.invalidateQueries({ queryKey: ["servers"] }); @@ -185,6 +176,7 @@ function UpdatesFoundDialog({ open, onOpenChange, updates, onUpdateAll }: Update const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); const anyRunning = updates.some((s) => s.status === "running"); const anyStarting = updates.some((s) => s.status === "starting"); + const versionCache = useBuildVersionCache(); return ( @@ -210,8 +202,8 @@ function UpdatesFoundDialog({ open, onOpenChange, updates, onUpdateAll }: Update
{s.name} {s.installedBuild !== "unknown" && ( - - {s.installedBuild} → {s.cachedBuild} + + {formatServerVersion(s.installedBuild, versionCache)} → {formatServerVersion(s.cachedBuild, versionCache)} )}
@@ -302,6 +294,7 @@ interface UpdateAllDialogProps { function UpdateAllDialog({ open, onOpenChange, updates, anyStarting, onConfirm }: UpdateAllDialogProps) { const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); const anyRunning = updates.some((s) => s.status === "running"); + const versionCache = useBuildVersionCache(); return ( @@ -326,8 +319,8 @@ function UpdateAllDialog({ open, onOpenChange, updates, anyStarting, onConfirm }
{s.name} {s.installedBuild !== "unknown" && ( - - {s.installedBuild} → {s.cachedBuild} + + {formatServerVersion(s.installedBuild, versionCache)} → {formatServerVersion(s.cachedBuild, versionCache)} )}
@@ -409,15 +402,18 @@ export default function DashboardPage() { const { data: servers = [], isLoading } = useServers(); const { setShowNewServerWizard, enqueueStartup } = useAppStore(); const [showImport, setShowImport] = useState(false); + const [appVersion, setAppVersion] = useState(""); + + useEffect(() => { + getVersion().then(setAppVersion).catch(() => {}); + }, []); const [showUpdateAllDialog, setShowUpdateAllDialog] = useState(false); const [showUpdatesFoundDialog, setShowUpdatesFoundDialog] = useState(false); const [pendingUpdates, setPendingUpdates] = useState([]); const [updatingAll, setUpdatingAll] = useState(false); const queryClient = useQueryClient(); - const total = servers.length; - const running = servers.filter((s) => s.status === "running").length; - const stopped = total - running; + const total = servers.length; // Build the ServerUpdateInfo list from the live servers data. const serversWithUpdates: ServerUpdateInfo[] = servers @@ -496,9 +492,9 @@ export default function DashboardPage() { }, [servers, updatingAll, queryClient, enqueueStartup]); return ( -
+
{/* ── Page header ── */} -
+
@@ -514,14 +510,16 @@ export default function DashboardPage() {

- setShowUpdateAllDialog(true)} - onUpdatesFound={(updates) => { - setPendingUpdates(updates); - setShowUpdatesFoundDialog(true); - }} - /> + {servers.length > 0 && ( + setShowUpdateAllDialog(true)} + onUpdatesFound={(updates) => { + setPendingUpdates(updates); + setShowUpdatesFoundDialog(true); + }} + /> + )}
- {/* ── Global stats bar ── */} - {total > 0 && ( +
+ {/* ── Needs Attention warning — only shown when servers are in a bad state ── */} + {total > 0 && servers.some((s) => s.status === "crashed" || s.status === "error") && (
- - - 0 ? "var(--text-muted)" : "var(--neon-green)"} /> - {servers.some((s) => s.status === "crashed" || s.status === "error") && ( - s.status === "crashed" || s.status === "error").length} - icon={Activity} - color="var(--neon-red)" - /> - )} + s.status === "crashed" || s.status === "error").length} + icon={Activity} + color="var(--neon-red)" + />
)} @@ -642,6 +634,14 @@ export default function DashboardPage() { updates={pendingUpdates} onUpdateAll={runUpdateAll} /> +
+ + {/* Branding footer */} +
+

+ LokiASAM{appVersion ? ` v${appVersion}` : ""} · lokisoft.xyz +

+
); } diff --git a/src/app/servers/detail/page.tsx b/src/app/servers/detail/page.tsx index c8885d3..7c23c6a 100644 --- a/src/app/servers/detail/page.tsx +++ b/src/app/servers/detail/page.tsx @@ -17,13 +17,14 @@ 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 } from "@/lib/db"; +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 { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; const TABS = [ { value: "overview", label: "Overview", icon: LayoutDashboard }, @@ -55,6 +56,7 @@ export default function ServerDetailPage() { const [loading, setLoading] = useState(true); const [notFound, setNotFound] = useState(false); const [activeTab, setActiveTab] = useState(tabParam); + const versionCache = useBuildVersionCache(); // ── Load server row ────────────────────────────────────────────────────── const reload = async () => { @@ -125,10 +127,7 @@ export default function ServerDetailPage() { const mapDisplay = ARK_MAPS.find((m) => m.id === server.map_id)?.displayName ?? server.map_id; return ( - // When the RCON tab is active the root div fills main's content area exactly - // so the log scrolls internally without creating a page-level scrollbar. - // Other tabs keep normal flow (gap-6, no height constraint). -
+
{/* ── Header ── */}

- {mapDisplay} · Port {server.port} · RCON {server.rcon_port} · ID{" "} - {server.id.slice(0, 8)} + {mapDisplay} · Port {server.port} · RCON {server.rcon_port} + {server.installed_build_id && ( + <> + {" "}·{" "} + {formatServerVersion(server.installed_build_id, versionCache)} + + )} + {" "}· ID {server.id.slice(0, 8)}

@@ -192,13 +197,13 @@ export default function ServerDetailPage() { {/* ── Tab content ── */} {(activeTab === "rcon" || activeTab === "logs" || activeTab === "mods") ? ( -
+
{activeTab === "rcon" && } {activeTab === "logs" && } {activeTab === "mods" && }
) : ( -
+
{activeTab === "overview" && } {activeTab === "config" && } {activeTab === "backups" && } diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index 9fb93c8..83c15dc 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from "react"; import { - Folder, Terminal, Info, Archive, + 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, @@ -24,10 +24,11 @@ import { NotificationMatrix } from "@/components/shared/NotificationMatrix"; import { getAppSetting, setAppSetting, saveNotificationConfig, getNotificationConfigs, - getServers, + getServers, formatServerVersion, type NotificationConfigRow, } from "@/lib/db"; -import { runPerServerUpdateCheck, applyUpdateToServer } from "@/lib/update-utils"; +import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; +import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToServer } from "@/lib/update-utils"; import { check } from "@tauri-apps/plugin-updater"; import { getVersion } from "@tauri-apps/api/app"; import { tempDir } from "@tauri-apps/api/path"; @@ -358,7 +359,7 @@ function PathField({ if (!path.trim() || !validateDir) return; setChecking(true); setDirResult(null); try { setDirResult(await tauriCmd.checkDir(path)); } - catch { setDirResult({ writable: false, freeBytes: 0, error: "Could not check directory." }); } + catch { setDirResult({ writable: false, freeBytes: 0, error: "Could not check directory.", isNew: false, hasLokiasam: false, isEmpty: false }); } finally { setChecking(false); } }, [validateDir]); @@ -611,18 +612,66 @@ function ThemesSection() { // About section // --------------------------------------------------------------------------- +function AboutRow({ label, value }: { label: string; value: string }) { + return ( +
+ {label}: + {value} +
+ ); +} + +function AboutSectionLabel({ children }: { children: React.ReactNode }) { + return ( +
+ + {children} + +
+
+ ); +} + function AboutSection() { - const [paths, setPaths] = useState({ baseDir: "", dbPath: "", cachePath: "" }); - const [appVersion, setAppVersion] = useState("…"); + const [appVersion, setAppVersion] = useState("…"); + const [asaBuild, setAsaBuild] = useState("—"); + const [protonVersion, setProtonVer] = useState("—"); + const [paths, setPaths] = useState({ + baseDir: "—", backupDir: "—", steamcmd: "—", + dbPath: "—", cachePath: "—", logRoot: "—", + }); + const [copied, setCopied] = useState(false); + const versionCache = useBuildVersionCache(); useEffect(() => { getVersion().then(setAppVersion).catch(() => setAppVersion("0.10.0")); (async () => { - const baseDir = (await getAppSetting("base_dir")) ?? ""; - if (!baseDir) return; - const sep = baseDir.includes("\\") ? "\\" : "/"; - const base = baseDir.replace(/[/\\]$/, ""); - setPaths({ baseDir, dbPath: `${base}${sep}lokiasam${sep}lokiasam.db`, cachePath: `${base}${sep}lokiasam${sep}cache${sep}asa-server` }); + const [baseDir, backupDir, steamcmd, asaCached, protonPath, logRoot] = await Promise.all([ + getAppSetting("base_dir"), + getAppSetting("backup_dir"), + getAppSetting("steamcmd_path"), + getAppSetting("asa_cached_build_id"), + IS_LINUX ? getAppSetting("proton_path") : Promise.resolve(null), + tauriCmd.getLogStorageRoot().catch(() => ""), + ]); + + setAsaBuild(asaCached || "—"); + + if (protonPath) { + const ver = protonPath.replace(/[/\\]$/, "").split(/[/\\]/).pop() ?? ""; + setProtonVer(ver || "—"); + } + + const sep = (baseDir ?? "").includes("\\") ? "\\" : "/"; + const base = (baseDir ?? "").replace(/[/\\]$/, ""); + setPaths({ + 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 || "—", + }); })(); }, []); @@ -630,25 +679,76 @@ function AboutSection() { ? "~/.config/xyz.lokisoft.lokiasam/bootstrap.json" : "%APPDATA%\\xyz.lokisoft.lokiasam\\bootstrap.json"; - const rows = [ - { label: "Version", value: appVersion }, - { label: "Base Directory", value: paths.baseDir || "—" }, - { label: "Database", value: paths.dbPath || "—" }, - { label: "Server Cache", value: paths.cachePath || "—" }, - { label: "Bootstrap", value: bootstrapHint }, + // Resolve the human-readable ASA version from the cache build ID + const asaVersionDisplay = asaBuild !== "—" + ? formatServerVersion(asaBuild, versionCache) + : "—"; + + const versionRows = [ + { label: "LokiASAM", value: `v${appVersion}` }, + { label: "ASA Server Cache", value: asaVersionDisplay }, + ...(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 handleCopy = () => { + const text = [ + "Versions:", + ...versionRows.map((r) => ` ${r.label}: ${r.value}`), + "", + "Directories:", + ...pathRows.map((r) => ` ${r.label}: ${r.value}`), + ].join("\n"); + navigator.clipboard.writeText(text).catch(() => null); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }; + return ( -
- {rows.map(({ label, value }, i) => ( -
- {i > 0 && } -
- {label} - {value} -
+
+ {/* Header */} +
+ +
+

About

+

Application version and data paths.

+
+ +
+ + {/* Content */} +
+ Versions +
+ {versionRows.map((r) => )} +
+ + Directories +
+ {pathRows.map((r) => )}
- ))} +
); } @@ -658,18 +758,16 @@ function AboutSection() { // --------------------------------------------------------------------------- const AUTO_CHECK_OPTIONS = [ - { value: "0", label: "Disabled" }, - { value: "1", label: "Every hour" }, - { value: "6", label: "Every 6 hours" }, - { value: "12", label: "Every 12 hours" }, - { value: "24", label: "Daily" }, + { value: "disabled", label: "Disabled" }, + { value: "startup", label: "On startup" }, + { value: "startup_hourly", label: "On startup + hourly" }, ]; function ServerUpdatesSection() { const [checking, setChecking] = useState(false); const [cachedBuild, setCached] = useState(""); const [lastChecked, setLastChecked] = useState(""); - const [autoCheckHours, setAutoCheck] = useState("0"); + 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 }); @@ -682,7 +780,7 @@ function ServerUpdatesSection() { getAppSetting("asa_auto_check_hours"), getAppSetting("base_dir"), ]); - setCached(cached ?? ""); setLastChecked(checked ?? ""); setAutoCheck(hours ?? "0"); + setCached(cached ?? ""); setLastChecked(checked ?? ""); setAutoCheck(hours ?? "disabled"); if (baseDir) { const sep = baseDir.includes("\\") ? "\\" : "/"; const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; @@ -698,30 +796,11 @@ function ServerUpdatesSection() { const handleCheck = async () => { setChecking(true); try { - const [baseDir, steamcmdPath] = await Promise.all([ - getAppSetting("base_dir"), - getAppSetting("steamcmd_path"), - ]); - if (!baseDir) { toast.error("Base directory not configured."); return; } - if (!steamcmdPath) { toast.error("SteamCMD path not configured. Set it up in Settings."); return; } - - const sep = baseDir.includes("\\") ? "\\" : "/"; - const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; - - // Read build ID before update so we can detect whether something changed. const oldBuild = await getAppSetting("asa_cached_build_id") ?? ""; + const newBuild = await runAsaCacheUpdate(); + if (!newBuild) { toast.error("Base directory or SteamCMD not configured."); return; } - // Run SteamCMD. If already current this is fast; if an update exists it downloads. - const newBuild = await tauriCmd.updateCache("check", cacheDir, steamcmdPath); - - const now = new Date().toISOString(); - const cacheUpdated = !!newBuild && newBuild !== oldBuild; - - await Promise.all([ - setAppSetting("asa_cached_build_id", newBuild), - setAppSetting("asa_latest_build_id", newBuild), - setAppSetting("asa_last_checked", now), - ]); + const cacheUpdated = newBuild !== oldBuild; // Run per-server check now that the cache build ID is current. await runPerServerUpdateCheck(); @@ -901,9 +980,9 @@ function ServerUpdatesSection() { // --------------------------------------------------------------------------- const APP_UPDATE_MODE_OPTIONS = [ - { value: "startup", label: "On startup only" }, - { value: "periodic", label: "Every hour" }, { value: "off", label: "Disabled" }, + { value: "startup", label: "On startup" }, + { value: "periodic", label: "On startup + hourly" }, ]; function AppUpdateSection() { @@ -955,6 +1034,12 @@ function AppUpdateSection() {

Automatic update checks for LokiASAM itself. When an update is found, a notification appears with a Download & Install button.

+ +
@@ -970,12 +1055,6 @@ function AppUpdateSection() { ))}
- -
); } @@ -1265,17 +1344,17 @@ function ProtonGeUpdateSection() { const [updateInfo, setUpdateInfo] = useState(null); const [downloading, setDownloading] = useState(false); const [downloadDone, setDownloadDone] = useState(false); - const [autoCheck, setAutoCheck] = useState(false); + const [checkMode, setCheckMode] = useState("startup_hourly"); useEffect(() => { Promise.all([ getAppSetting("proton_path"), getAppSetting("proton_ge_managed"), - getAppSetting("proton_ge_auto_check"), - ]).then(([p, managed, auto]) => { + getAppSetting("proton_ge_check_mode"), + ]).then(([p, managed, mode]) => { setProtonPath(p ?? ""); setIsManaged(managed === "true"); - setAutoCheck(auto === "true"); + setCheckMode(mode ?? "startup_hourly"); }); }, []); @@ -1314,9 +1393,9 @@ function ProtonGeUpdateSection() { toast.success("LokiASAM will now manage Proton-GE updates."); }; - const handleAutoCheckToggle = async (checked: boolean) => { - setAutoCheck(checked); - await setAppSetting("proton_ge_auto_check", checked ? "true" : "false"); + const handleCheckModeChange = async (value: string) => { + setCheckMode(value); + await setAppSetting("proton_ge_check_mode", value); }; // Determine if the current path is inside the managed location @@ -1389,7 +1468,7 @@ function ProtonGeUpdateSection() { {/* Action buttons */}
@@ -1414,15 +1493,28 @@ function ProtonGeUpdateSection() { )}
- {/* Auto-check toggle */} -
-
-

Daily Auto-Check

-

- Automatically check GitHub for new GE-Proton releases once per day. -

+ {/* Auto-check mode */} +
+ +

+ Automatically check GitHub for new GE-Proton releases. +

+
+ {[ + { value: "disabled", label: "Disabled" }, + { value: "startup", label: "On startup" }, + { value: "startup_hourly", label: "On startup + hourly" }, + ].map((opt) => ( + + ))}
-
{/* Download output */} @@ -1457,7 +1549,7 @@ const GLOBAL_CHANNEL_DEFS = [ }, ]; -function GlobalNotificationsSection() { +function GlobalNotificationsSection({ onCredentialSaved }: { onCredentialSaved?: () => void }) { const [configs, setConfigs] = useState([]); const [saving, setSaving] = useState(null); @@ -1488,6 +1580,7 @@ function GlobalNotificationsSection() { }); await loadConfigs(); toast.success("Notification config saved."); + onCredentialSaved?.(); } catch (e) { toast.error(`Failed to save: ${e}`); } finally { setSaving(null); } } @@ -1833,29 +1926,43 @@ type TabId = typeof TABS[number]["id"]; export default function SettingsPage() { const [activeTab, setActiveTab] = useState("general"); + const [matrixRefreshKey, setMatrixRefreshKey] = useState(0); return ( -
-
+
+

Settings

Global application configuration.

{/* Tab bar */} -
- {TABS.map((tab) => ( - - ))} +
+ {TABS.map((tab) => { + const active = activeTab === tab.id; + return ( + + ); + })}
+
{/* General tab */} {activeTab === "general" && (
@@ -1939,22 +2046,23 @@ export default function SettingsPage() { {activeTab === "notifications" && (
- + setMatrixRefreshKey((k) => k + 1)} />
- +
)} {/* About tab */} {activeTab === "about" && ( -
-
+
+
-
+
)} +
); } diff --git a/src/components/layout/DisableContextMenu.tsx b/src/components/layout/DisableContextMenu.tsx index 34098e8..01f1af8 100644 --- a/src/components/layout/DisableContextMenu.tsx +++ b/src/components/layout/DisableContextMenu.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect, useState, useCallback } from "react"; +import { useEffect, useState, useCallback, useRef } from "react"; import { writeText, readText } from "@tauri-apps/plugin-clipboard-manager"; interface MenuState { @@ -16,12 +16,19 @@ interface MenuState { export function DisableContextMenu() { const [menu, setMenu] = useState(null); + // Saved on right-click mousedown so contextmenu can read it even if WebkitGTK + // clears the DOM selection before the contextmenu event fires. + const pendingSelectionRef = useRef(""); + // Ref to the overlay div — used in handleMouseDown to skip close() for inside-overlay + // clicks without stopPropagation (which breaks the pointer event chain in WebkitGTK). + const overlayRef = useRef(null); const handleContextMenu = useCallback((e: MouseEvent) => { e.preventDefault(); - // Capture selection NOW — a subsequent mousedown/click will clear it. - const selectedText = window.getSelection()?.toString() ?? ""; + // Use selection captured at mousedown time (WebkitGTK may clear it before contextmenu fires). + const selectedText = pendingSelectionRef.current || (window.getSelection()?.toString() ?? ""); + pendingSelectionRef.current = ""; const canCopy = selectedText.length > 0; const target = e.target as HTMLElement; @@ -30,7 +37,10 @@ export function DisableContextMenu() { target instanceof HTMLTextAreaElement || target.isContentEditable; - if (!canCopy && !canPaste) return; + if (!canCopy && !canPaste) { + setMenu(null); + return; + } // Capture cursor position so paste inserts at the right spot. let selStart = 0; @@ -55,6 +65,19 @@ export function DisableContextMenu() { const close = useCallback(() => setMenu(null), []); + const handleMouseDown = useCallback((e: MouseEvent) => { + // Never close the menu when clicking inside the overlay — use contains() instead of + // stopPropagation so the full event chain reaches WebkitGTK and pointer events work. + if (overlayRef.current?.contains(e.target as Node)) return; + + if (e.button === 2) { + pendingSelectionRef.current = window.getSelection()?.toString() ?? ""; + } else { + pendingSelectionRef.current = ""; + } + setMenu(null); + }, []); + const handleCopy = useCallback(() => { const text = menu?.selectedText ?? ""; setMenu(null); @@ -71,34 +94,36 @@ export function DisableContextMenu() { setMenu(null); if (!target) return; - // rAF: let the menu overlay disappear so the target can regain focus first. - requestAnimationFrame(() => { - target.focus(); - // Use the Tauri clipboard plugin — reads from the real OS clipboard. - readText() - .then((text) => { - if (text) insertAt(target, text, selStart, selEnd); - }) - .catch(() => {}); - }); + // Use the Tauri plugin — navigator.clipboard.readText() requires a user-gesture + // context that WebkitGTK considers expired by the time our async handler runs. + // The Tauri plugin makes a direct Rust call that bypasses this restriction. + readText() + .then((text) => { + if (text) { + target.focus(); + insertAt(target, text, selStart, selEnd); + } + }) + .catch(() => {}); }, [menu]); useEffect(() => { document.addEventListener("contextmenu", handleContextMenu); - document.addEventListener("mousedown", close); + document.addEventListener("mousedown", handleMouseDown); document.addEventListener("keydown", close); return () => { document.removeEventListener("contextmenu", handleContextMenu); - document.removeEventListener("mousedown", close); + document.removeEventListener("mousedown", handleMouseDown); document.removeEventListener("keydown", close); }; - }, [handleContextMenu, close]); + }, [handleContextMenu, handleMouseDown, close]); if (!menu) return null; return (
e.stopPropagation()} > {menu.canCopy && ( @@ -175,7 +199,9 @@ function ContextMenuItem({
))} + + {asaCacheUpdateInProgress && ( +
+ + + Checking ASA updates… + +
+ )}
diff --git a/src/components/layout/UpdateManager.tsx b/src/components/layout/UpdateManager.tsx index 24fba89..51db3bf 100644 --- a/src/components/layout/UpdateManager.tsx +++ b/src/components/layout/UpdateManager.tsx @@ -5,11 +5,35 @@ import { check } from "@tauri-apps/plugin-updater"; import { invoke } from "@tauri-apps/api/core"; import { toast } from "sonner"; import { getAppSetting } from "@/lib/db"; +import { tauriCmd } from "@/lib/tauri-commands"; const ONE_HOUR_MS = 60 * 60 * 1000; export function UpdateManager() { - const checkingRef = useRef(false); + const checkingRef = useRef(false); + const protonCheckRef = useRef(false); + const isLinux = typeof navigator !== "undefined" && !navigator.userAgent.includes("Windows"); + + async function checkForProtonUpdate() { + if (protonCheckRef.current) return; + protonCheckRef.current = true; + try { + const protonPath = await getAppSetting("proton_path"); + if (!protonPath) return; + const info = await tauriCmd.checkProtonGeUpdate(protonPath); + if (!info.updateAvailable) return; + toast.info(`Proton-GE ${info.latestVersion} is available`, { + id: `proton-update-${info.latestVersion}`, + description: `Current: ${info.currentVersion || "unknown"}. Update in Settings → Updates → Proton-GE.`, + duration: Infinity, + cancel: { label: "Dismiss", onClick: () => {} }, + }); + } catch { + // Silently ignore — background check should never surface errors + } finally { + protonCheckRef.current = false; + } + } async function checkForUpdate() { if (checkingRef.current) return; @@ -71,22 +95,35 @@ export function UpdateManager() { } useEffect(() => { - let intervalId: ReturnType | null = null; + let appIntervalId: ReturnType | null = null; + let protonIntervalId: ReturnType | null = null; (async () => { - const mode = await getAppSetting("app_update_check_mode"); - // Default to 'startup' if the key has never been set - if (mode === "off") return; + const [mode, protonMode] = await Promise.all([ + getAppSetting("app_update_check_mode"), + isLinux ? getAppSetting("proton_ge_check_mode") : Promise.resolve(null), + ]); - checkForUpdate(); + // LokiASAM app updates + if (mode !== "off") { + checkForUpdate(); + if (mode === "periodic") { + appIntervalId = setInterval(checkForUpdate, ONE_HOUR_MS); + } + } - if (mode === "periodic") { - intervalId = setInterval(checkForUpdate, ONE_HOUR_MS); + // Proton-GE updates (Linux only) + if (isLinux && protonMode && protonMode !== "disabled") { + checkForProtonUpdate(); + if (protonMode === "startup_hourly") { + protonIntervalId = setInterval(checkForProtonUpdate, ONE_HOUR_MS); + } } })(); return () => { - if (intervalId) clearInterval(intervalId); + if (appIntervalId) clearInterval(appIntervalId); + if (protonIntervalId) clearInterval(protonIntervalId); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index 6ed53ea..ad0356a 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -60,6 +60,8 @@ import { useQueryClient } from "@tanstack/react-query"; import { useAppStore } from "@/store/useAppStore"; import { toast } from "sonner"; import type { ServerRow } from "@/lib/db"; +import { formatServerVersion } from "@/lib/db"; +import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; interface Props { server: ServerRow; @@ -114,6 +116,7 @@ export function ServerCard({ server }: Props) { const router = useRouter(); const queryClient = useQueryClient(); const stats = useServerStats(server); + const versionCache = useBuildVersionCache(); const startTime = useAppStore((s) => s.serverStartTimes[server.id]); const noRetry = useAppStore((s) => !!s.noRetryServerIds[server.id]); const setNoRetryServer = useAppStore((s) => s.setNoRetryServer); @@ -202,7 +205,7 @@ export function ServerCard({ server }: Props) { setLastBackup(lb); setNextRestart(nr); setBackupEnabled(be); - setAutoCheckEnabled((autoHours ?? "0") !== "0"); + setAutoCheckEnabled((autoHours ?? "disabled") !== "disabled"); } })(); return () => { cancelled = true; }; @@ -241,6 +244,7 @@ export function ServerCard({ server }: Props) { port: server.port, queryPort: server.query_port, rconPort: server.rcon_port, + rconPassword: server.rcon_password, extraArgs, modIds: enabledModIds, }; @@ -504,15 +508,6 @@ export function ServerCard({ server }: Props) { : `Updating in ${formatCountdown(countdown.remainingSecs)}` : undefined} /> - {hasUpdateAvailable && ( - - - Update - - )}
{mapDisplay} · :{server.port} + {server.installed_build_id && ( + <> + · + {formatServerVersion(server.installed_build_id, versionCache)} + + )}
diff --git a/src/components/server/tabs/AutomationTab.tsx b/src/components/server/tabs/AutomationTab.tsx index 25c77e1..1274e7a 100644 --- a/src/components/server/tabs/AutomationTab.tsx +++ b/src/components/server/tabs/AutomationTab.tsx @@ -20,7 +20,6 @@ import { type UpdateAutomation, } from "@/lib/db"; import { getAppSetting, setAppSetting } from "@/lib/db"; -import { tauriCmd } from "@/lib/tauri-commands"; import { syncSchedulesToRust } from "@/lib/scheduler-sync"; import type { ServerRow } from "@/lib/db"; @@ -350,7 +349,7 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing ? JSON.stringify({ message: addMsg }) : JSON.stringify(config); const nextIso = getNextCronDate(cron)?.toISOString() ?? new Date().toISOString(); - const newId = await tauriCmd.createSchedule({ serverId, scheduleType: type, cronExpression: cron, configJson }); + const newId = crypto.randomUUID(); const input: CreateScheduleInput = { id: newId, serverId, scheduleType: type, cronExpression: cron, enabled: true, configJson }; await createSchedule(input); await updateScheduleConfig(newId, cron, configJson, nextIso); @@ -366,7 +365,6 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing } async function handleDelete(id: string) { - await tauriCmd.deleteSchedule(id); await deleteScheduleRecord(id); onRefresh(); syncSchedulesToRust(); @@ -374,7 +372,6 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing async function handleToggle(row: ScheduleRow) { const newVal = !(row.enabled === 1); - await tauriCmd.toggleSchedule(row.id, newVal); await updateScheduleEnabled(row.id, newVal); onRefresh(); syncSchedulesToRust(); @@ -615,7 +612,6 @@ function BackupTypeSection({ // Delete any extra rows left over from the old per-tier format for (const row of allExisting.slice(1)) { - await tauriCmd.deleteSchedule(row.id); await deleteScheduleRecord(row.id); } @@ -623,7 +619,7 @@ function BackupTypeSection({ await updateScheduleConfig(primary.id, cron, configJson, nextIso); if (anyEnabled !== (primary.enabled === 1)) await updateScheduleEnabled(primary.id, anyEnabled); } else if (anyEnabled) { - const newId = await tauriCmd.createSchedule({ serverId, scheduleType, cronExpression: cron, configJson }); + const newId = crypto.randomUUID(); await createSchedule({ id: newId, serverId, scheduleType, cronExpression: cron, enabled: true, configJson }); await updateScheduleConfig(newId, cron, configJson, nextIso); } @@ -721,7 +717,7 @@ function FullBackupScheduleSection({ serverId, schedules, onRefresh }: { await updateScheduleConfig(existing.id, cron, configJson, nextIso); if (enabled !== (existing.enabled === 1)) await updateScheduleEnabled(existing.id, enabled); } else if (enabled) { - const newId = await tauriCmd.createSchedule({ serverId, scheduleType: "backup_full", cronExpression: cron, configJson }); + const newId = crypto.randomUUID(); await createSchedule({ id: newId, serverId, scheduleType: "backup_full", cronExpression: cron, enabled: true, configJson }); await updateScheduleConfig(newId, cron, configJson, nextIso); } @@ -1154,7 +1150,7 @@ export function AutomationTab({ server }: Props) { } return ( -
+
diff --git a/src/components/server/tabs/BackupsTab.tsx b/src/components/server/tabs/BackupsTab.tsx index cd8b60f..4072b7c 100644 --- a/src/components/server/tabs/BackupsTab.tsx +++ b/src/components/server/tabs/BackupsTab.tsx @@ -1018,7 +1018,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { const editScheduleBtn = onNavigateToAutomation ? handleEditSchedule : undefined; return ( -
+
{/* Progress overlay */} {progress.active && (
> // Field row // --------------------------------------------------------------------------- +function FieldLabel({ field }: { field: IniFieldDef }) { + return ( + + {field.label} + {field.key} + {field.description && ( + + + + + + {field.description} + + + )} + + ); +} + function FieldRow({ field, value, @@ -93,16 +126,8 @@ function FieldRow({ if (field.type === "boolean") { const checked = value === "True" || value === "true" || value === "1"; return ( -
-
- - {field.description && ( -

{field.description}

- )} -
+
+
-
+

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) => { - const visibleFields = group.fields.filter( - (f) => f.section === "gus" && !OVERVIEW_KEYS.has(f.key) - ); + 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 = expandedGroups.has(group.id); + const open = q ? true : expandedGroups.has(group.id); return (
+
+
+
+ +