diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e7c9ab4..30a1b35 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -66,41 +66,63 @@ jobs: releaseBody: | ## LokiASAM ${{ github.ref_name }} — Public Beta - LokiASAM is a desktop application for managing Ark Survival Ascended dedicated servers on Linux and Windows. It provides a full GUI for every aspect of running one or more ASA servers without needing to touch config files or the command line. + LokiASAM is a desktop application for managing Ark Survival Ascended dedicated servers on Linux and Windows. - ### Bug fixes in v0.10.1 + ### What's new in v0.11.0 - - **Linux: server stats and uptime not tracked** — the Steam Runtime container detaches Wine from the Proton PID the app was watching, causing CPU/RAM usage and uptime to show as zero for running servers. Fixed by scanning process command lines for the server's install path to locate the correct Wine process inside the container. + **Server stats history** + CPU and RAM usage are now recorded to a local database in the background. The Overview tab shows live charts of resource usage over time so you can see how your server behaves across a session, not just at a single moment. - ### Features + **Server status on startup** + The app now scans running OS processes on launch to determine which servers are actually running, rather than relying on stored state. If a server crashed or was stopped while the app was closed, the status will be correct immediately on next open. - - **Server management** — create, start, stop, restart, and monitor multiple servers from a single dashboard. Live CPU/RAM stats and player counts update automatically. - - **Server configuration** — edit `GameUserSettings.ini` and `Game.ini` through an organized section editor, or drop into the raw text view for full control. - - **RCON console** — built-in terminal with command history, preset commands, and broadcast support. - - **Live log viewer** — tail server logs in real time with text filtering and auto-scroll. - - **Mods** — browse CurseForge directly inside the app, add mods by ID, reorder, toggle, and install via SteamCMD with one click. - - **Backups** — create, restore, and delete server backups; configurable retention with scheduled automatic backups. - - **Automation** — schedule backups, updates, restarts, and broadcasts on a cron schedule with optional RCON warnings before restarts. - - **Clusters** — group servers into clusters with shared player data directories. - - **Notifications** — configurable desktop, Discord webhook, and email alerts with per-event channel control. - - **ASA server updates** — shared SteamCMD cache keeps downloads fast when managing multiple servers; update cache and apply to servers independently. - - **Auto-update** — the app checks for new LokiASAM releases and can download and install them without leaving the app. - - **Setup wizard** — guided first-run experience that installs SteamCMD and Proton (Linux) automatically. + **Launch parameters** + You can now configure per-server launch arguments through the UI — both in the setup wizard and the server config tab — without editing config files manually. + + **Graceful shutdown settings** + Servers now have configurable graceful shutdown behaviour, letting you control how the shutdown sequence is handled per server. + + **Per-server update automation** + Update automation is now configured per server rather than globally, with in-app notifications when updates are available for the server's installed version. + + **New game settings** + - PvP friendly fire toggle added + - Cryo sickness handling option added + + ### Improvements + + - **RCON** — improved tab layout, scrolling behaviour, and reliability. IO errors and timeouts are now distinguished and reported separately. Player list updates are handled via events. + - **Log handling** — ShooterGame.log is now rotated on server startup so the log viewer always starts from a clean slate for that session. + - **UI controls** — toggle switches replaced with icon buttons for better clarity. Numeric settings now use a combined number field and slider control. + - **Setup wizard** — improved visual effects and theme handling. + + ### Bug fixes + + - **Linux/Arch/CachyOS: blank screen on launch** — modern distros with newer GPU drivers could get a blank white window due to a WebKit DMA-BUF renderer incompatibility. Fixed. + - **Linux/KDE: title bar buttons stop working** — minimising and restoring the window on KDE could leave the decoration buttons unresponsive. Fixed. + - **Startup: Steam error output** — noisy Steam deprecation warnings are no longer surfaced as server errors in the log. + - **Startup: missing executable** — clearer error notification when the server binary can't be found at launch. ### Installation - **Linux:** Download the `.AppImage` from the assets below, make it executable, and run it. + **Linux:** Download your preferred package from the assets below. + + | Format | Auto-updates | Notes | + |--------|-------------|-------| + | `.AppImage` | Yes | Updates in-place, no admin rights needed | + | `.deb` | Yes | Installs via `dpkg`, prompts for your password | + | `.rpm` | Yes | Installs via `rpm`, prompts for your password | + ```bash - chmod +x LokiASAM_0.10.1_amd64.AppImage - ./LokiASAM_0.10.1_amd64.AppImage + chmod +x LokiASAM_0.11.0_amd64.AppImage + ./LokiASAM_0.11.0_amd64.AppImage ``` - > The AppImage receives automatic update notifications. The `.deb` package does not. - **Windows:** Download and run `LokiASAM_0.10.1_x64-setup.exe` from the assets below. + **Windows:** Download and run `LokiASAM_0.11.0_x64-setup.exe` 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. - - Linux requires a working Proton-GE installation for server processes. The setup wizard will guide you through this. + - Linux requires a working Proton-GE installation. The setup wizard will guide you through this. releaseDraft: false prerelease: false updaterJsonKeepUniversal: false diff --git a/next.config.ts b/next.config.ts index 7686e78..663904f 100644 --- a/next.config.ts +++ b/next.config.ts @@ -8,6 +8,12 @@ const nextConfig: NextConfig = { images: { unoptimized: true }, // Add trailing slashes so Tauri's file protocol resolves paths correctly. trailingSlash: true, + experimental: { + // Prevents the dev server from loading entire packages into memory when only + // specific exports are used. Fixes OOM crashes from lucide-react (thousands of + // icons), framer-motion, and radix-ui bloating the module cache in dev mode. + optimizePackageImports: ["lucide-react", "framer-motion", "radix-ui", "recharts"], + }, }; export default nextConfig; diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 3831a6d..d03cb9d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -30,6 +30,18 @@ dependencies = [ "version_check", ] +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.4" @@ -1318,6 +1330,18 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.4.1" @@ -1881,7 +1905,16 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" dependencies = [ - "ahash", + "ahash 0.7.8", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash 0.8.12", ] [[package]] @@ -1901,6 +1934,15 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown 0.14.5", +] + [[package]] name = "hashlink" version = "0.10.0" @@ -2620,7 +2662,7 @@ dependencies = [ [[package]] name = "lokiasam" -version = "0.10.0" +version = "0.11.0" dependencies = [ "configparser", "flate2", @@ -2628,6 +2670,7 @@ dependencies = [ "log", "procfs", "reqwest 0.12.28", + "rusqlite", "serde", "serde_json", "sysinfo", @@ -4056,6 +4099,20 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags 2.11.1", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink 0.9.1", + "libsqlite3-sys", + "smallvec", +] + [[package]] name = "rust_decimal" version = "1.42.0" @@ -4734,7 +4791,7 @@ dependencies = [ "futures-io", "futures-util", "hashbrown 0.15.5", - "hashlink", + "hashlink 0.10.0", "indexmap 2.14.0", "log", "memchr", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 3a3306d..d5e3ada 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lokiasam" -version = "0.10.0" +version = "0.11.0" description = "Loki Ark Survival Ascended Server Manager" authors = ["Loki"] license = "GPL-3.0-or-later" @@ -64,6 +64,10 @@ url = { version = "2" } # Logging log = "0.4" +# Direct SQLite access for the background stats recorder (separate from tauri-plugin-sql). +# "bundled" links SQLite statically so no system library is required. +rusqlite = { version = "0.32", features = ["bundled"] } + # Linux /proc reader — process discovery, PSS memory, thread detection # Replaces hand-rolled /proc string parsing with a tested, maintained library. [target.'cfg(target_os = "linux")'.dependencies] diff --git a/src-tauri/src/commands/config.rs b/src-tauri/src/commands/config.rs index d857bb1..63cfc7c 100644 --- a/src-tauri/src/commands/config.rs +++ b/src-tauri/src/commands/config.rs @@ -13,22 +13,18 @@ pub struct ServerConfigJson { pub launch_args: Value, } -/// Returns the platform-specific path to the server INI config directory. +/// Returns the path to the server INI config directory. /// -/// ASA uses different subdirectories on each platform: -/// - Windows: ShooterGame/Saved/Config/WindowsServer/ -/// - Linux: ShooterGame/Saved/Config/LinuxServer/ +/// ASA ships only a Windows dedicated server binary. On Linux the binary is +/// run through Proton/Wine, which maps the working directory to the real +/// filesystem via the Z:\ drive. The server binary therefore always writes +/// and reads config from the WindowsServer subfolder regardless of the host OS. fn config_dir(install_path: &Path) -> PathBuf { - #[cfg(target_os = "windows")] - let platform = "WindowsServer"; - #[cfg(not(target_os = "windows"))] - let platform = "LinuxServer"; - install_path .join("ShooterGame") .join("Saved") .join("Config") - .join(platform) + .join("WindowsServer") } /// Parse an INI file at `path` into a JSON object of section → { key → value }. diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index d037845..50d9bcd 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -8,6 +8,7 @@ pub mod proton; pub mod rcon; pub mod scheduler; pub mod server; +pub mod stats; pub mod steamcmd; pub mod system; pub mod utils; diff --git a/src-tauri/src/commands/rcon.rs b/src-tauri/src/commands/rcon.rs index e219cf9..bf35821 100644 --- a/src-tauri/src/commands/rcon.rs +++ b/src-tauri/src/commands/rcon.rs @@ -1,22 +1,355 @@ -use std::sync::Arc; +use std::collections::VecDeque; use serde::{Deserialize, Serialize}; -use tauri::State; -use tokio::sync::Mutex; -use tokio::time::{timeout, Duration}; +use tauri::{Emitter, Manager, State}; +use tokio::sync::{mpsc, oneshot}; +use tokio::time::{timeout, Duration, interval, MissedTickBehavior}; -use crate::state::rcon_pool::{RconConn, RconPool, RCON_AUTH, RCON_AUTH_RESPONSE, RCON_EXECCOMMAND}; +use crate::state::rcon_pool::{ + bin_subdir, CachedPlayer, RconCmd, RconConn, RconLogLine, RconPool, + RCON_AUTH, RCON_AUTH_RESPONSE, RCON_EXECCOMMAND, parse_player_list, +}; -#[derive(Debug, Serialize, Deserialize, Clone)] +// Re-export CachedPlayer as ArkPlayer for backwards-compat with existing frontend calls. +pub type ArkPlayer = CachedPlayer; + +// --------------------------------------------------------------------------- +// Internal helpers +// --------------------------------------------------------------------------- + +fn now_ms() -> u64 { + RconPool::now_ms() +} + +/// Emit one log line to the log buffer and fire the Tauri event. +async fn emit_log(app: &tauri::AppHandle, server_id: &str, line: RconLogLine) { + let pool = app.state::(); + pool.push_log(server_id, line.clone()).await; + let _ = app.emit(&format!("rcon://log/{server_id}"), &line); +} + +/// Payload for `rcon://status/{id}` and `rcon://status-any` events. +#[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ArkPlayer { - pub name: String, - pub steam_id: String, +pub struct RconStatusPayload { + pub server_id: String, + /// "connecting" | "connected" | "disconnected" + pub status: String, + pub host: Option, + pub port: Option, + pub error: Option, +} + +/// Emit connection status to both the per-server channel and the broadcast channel. +fn emit_status(app: &tauri::AppHandle, payload: RconStatusPayload) { + let _ = app.emit(&format!("rcon://status/{}", payload.server_id), &payload); + let _ = app.emit("rcon://status-any", &payload); +} + +/// Distinguishes a dead TCP connection from a command that simply got no response. +/// Only `Io` errors should terminate the manager task; `Timeout` is often normal +/// (e.g. GetChat when the chat buffer is empty). +#[derive(Debug)] +enum ExecError { + /// The TCP stream returned an error — connection is definitely dead. + Io(String), + /// No matching response packet arrived within the timeout window. + /// The TCP stream itself may still be alive. + Timeout, +} + +impl std::fmt::Display for ExecError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ExecError::Io(e) => write!(f, "{e}"), + ExecError::Timeout => write!(f, "RCON command timed out — no response from server"), + } + } +} + +/// Send one RCON command and collect the full response. +/// `first_timeout_ms` controls how long to wait for the very first packet; +/// subsequent packets always use a 200 ms drain window. +/// +/// Returns `Err(ExecError::Io)` on TCP errors (connection dead). +/// Returns `Err(ExecError::Timeout)` when no matching packet arrived in time +/// (the TCP stream may still be alive — callers decide whether to break). +async fn exec_cmd( + conn: &mut RconConn, + command: &str, + first_timeout_ms: u64, +) -> Result { + let cmd_id = conn.next_id; + conn.next_id += 1; + conn.send_packet(cmd_id, RCON_EXECCOMMAND, command).await + .map_err(ExecError::Io)?; + + let mut response = String::new(); + let mut received_any = false; + + loop { + let wait = if received_any { + Duration::from_millis(200) + } else { + Duration::from_millis(first_timeout_ms) + }; + + match timeout(wait, conn.recv_packet()).await { + Ok(Ok((id, _, body))) if id == cmd_id => { + received_any = true; + response.push_str(&body); + } + Ok(Ok(_)) => {} + Ok(Err(e)) => return Err(ExecError::Io(e)), + Err(_) => { + if !received_any { + return Err(ExecError::Timeout); + } + break; + } + } + } + Ok(response) } -/// Connect to the server's RCON port and authenticate. -/// Stores the live TcpStream in the global RconPool for subsequent commands. +// --------------------------------------------------------------------------- +// Per-server RCON manager task +// --------------------------------------------------------------------------- + +/// Owns the TCP connection for one server. Runs a select! loop that: +/// • Processes commands from the mpsc channel (user commands, player refresh) +/// • Polls listplayers every 30 s +/// • Polls GetChat every 5 s (only when chat_poll_active) +/// +/// All RCON I/O is serialized — nothing competes for the connection. +/// On any fatal I/O error the task exits, emits rcon://status disconnected, +/// and removes itself from the pool so the frontend can reconnect. +async fn run_rcon_manager( + server_id: String, + conn_id: u64, + mut conn: RconConn, + mut rx: mpsc::Receiver, + app: tauri::AppHandle, + _host: String, + _port: u16, +) { + let mut player_tick = interval(Duration::from_secs(30)); + player_tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + player_tick.tick().await; // discard the immediate first tick + + let mut chat_tick = interval(Duration::from_secs(5)); + chat_tick.set_missed_tick_behavior(MissedTickBehavior::Skip); + chat_tick.tick().await; // discard the immediate first tick + + loop { + tokio::select! { + // ── Incoming command from frontend ──────────────────────────── + cmd = rx.recv() => { + match cmd { + None | Some(RconCmd::Disconnect) => break, + + Some(RconCmd::Execute { command, suppress_cmd, suppress_resp, response_tx }) => { + if !suppress_cmd { + emit_log(&app, &server_id, RconLogLine { + timestamp_ms: now_ms(), + text: format!("> {command}"), + kind: "command".into(), + }).await; + } + + match exec_cmd(&mut conn, &command, 15_000).await { + Ok(raw) => { + if !suppress_resp { + for line in raw.trim().lines() { + let t = line.trim(); + if t.is_empty() { continue; } + if t.to_lowercase() == "server received, but no response!!" { continue; } + emit_log(&app, &server_id, RconLogLine { + timestamp_ms: now_ms(), + text: t.to_string(), + kind: "response".into(), + }).await; + } + } + let _ = response_tx.send(Ok(raw)); + } + Err(e) => { + emit_log(&app, &server_id, RconLogLine { + timestamp_ms: now_ms(), + text: format!("Error: {e}"), + kind: "error".into(), + }).await; + let _ = response_tx.send(Err(e.to_string())); + if matches!(e, ExecError::Io(_)) { + break; // TCP dead + } + // Timeout: log + surface to caller but keep the manager alive. + } + } + } + + Some(RconCmd::GetPlayers { response_tx }) => { + match exec_cmd(&mut conn, "listplayers", 5_000).await { + Ok(raw) => { + let players = parse_player_list(&raw); + { + let pool = app.state::(); + pool.player_cache.lock().await + .insert(server_id.clone(), players.clone()); + } + let _ = app.emit(&format!("rcon://players/{server_id}"), &players); + let _ = response_tx.send(Ok(players)); + } + Err(e) => { + let _ = response_tx.send(Err(e.to_string())); + if matches!(e, ExecError::Io(_)) { + break; // TCP dead + } + // Timeout: caller gets an error but keep the manager alive. + } + } + } + } + } + + // ── Periodic player list poll (every 30 s) ──────────────────── + _ = player_tick.tick() => { + match exec_cmd(&mut conn, "listplayers", 5_000).await { + Ok(raw) => { + let players = parse_player_list(&raw); + { + let pool = app.state::(); + pool.player_cache.lock().await + .insert(server_id.clone(), players.clone()); + } + let _ = app.emit(&format!("rcon://players/{server_id}"), &players); + } + Err(ExecError::Io(_)) => break, // TCP dead + Err(ExecError::Timeout) => {} // server slow; skip this poll cycle + } + } + + // ── Periodic chat poll (every 5 s, only when tab is open) ───── + _ = chat_tick.tick() => { + let active = app.state::() + .chat_poll_active.lock().await + .contains(&server_id); + + if !active { continue; } + + match exec_cmd(&mut conn, "GetChat", 3_000).await { + Ok(raw) => { + for line in raw.lines().map(|l| l.trim()).filter(|l| !l.is_empty()) { + let tl = line.to_lowercase(); + // Drop no-response noise. + if tl == "server received, but no response!!" { continue; } + // Drop SERVER: prefix lines — these are echoes of admin + // broadcasts (e.g. ServerChat) that the user already saw. + if line.starts_with("SERVER: ") { continue; } + emit_log(&app, &server_id, RconLogLine { + timestamp_ms: now_ms(), + text: line.to_string(), + kind: "chat".into(), + }).await; + } + } + Err(ExecError::Io(_)) => break, // TCP dead + // Timeout means the chat buffer was empty (ASA sent no packet or + // responded with a non-matching ID). This is normal — just continue. + Err(ExecError::Timeout) => {} + } + } + } + } + + // ── Cleanup ─────────────────────────────────────────────────────────────── + // Only emit events and clean up the pool if we are still the current + // connection for this server. If a newer rcon_connect call has already + // taken over (its conn_id replaced ours in the pool), exit silently — the + // newer manager task will handle its own lifecycle. Without this check, + // the stale task's cleanup would drop the newer task's tx, instantly + // killing it and creating the disconnect/reconnect loop. + { + let pool = app.state::(); + let mut guard = pool.cmd_channels.lock().await; + let is_superseded = guard + .get(&server_id) + .map(|(_, id)| *id != conn_id) + .unwrap_or(false); + if is_superseded { + return; + } + guard.remove(&server_id); + } + + emit_log(&app, &server_id, RconLogLine { + timestamp_ms: now_ms(), + text: "RCON connection closed.".into(), + kind: "system".into(), + }).await; + + emit_status(&app, RconStatusPayload { + server_id, + status: "disconnected".into(), + host: None, + port: None, + error: None, + }); +} + +// --------------------------------------------------------------------------- +// One-shot transient connection (graceful shutdown etc.) +// --------------------------------------------------------------------------- + +/// Open a fresh authenticated connection, run one command, return the response. +/// Used for fire-and-forget operations that must not block the pool connection. +pub async fn transient_rcon_command(port: u16, password: &str, command: &str) -> Result { + use tokio::net::TcpStream; + + let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port)); + let stream = timeout(Duration::from_secs(5), TcpStream::connect(addr)) + .await + .map_err(|_| "RCON connect 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 }; + + conn.send_packet(1, RCON_AUTH, password).await?; + for _ in 0..3 { + match timeout(Duration::from_secs(5), conn.recv_packet()).await { + Ok(Ok((_, t, _))) if t == RCON_AUTH_RESPONSE => break, + Ok(Err(e)) => return Err(e), + Err(_) => return Err("RCON auth timed out".into()), + _ => {} + } + } + + conn.send_packet(2, RCON_EXECCOMMAND, command).await?; + + let mut response = String::new(); + let mut got_any = false; + loop { + let wait = if got_any { Duration::from_millis(300) } else { Duration::from_secs(15) }; + match timeout(wait, conn.recv_packet()).await { + Ok(Ok((id, _, body))) if id == 2 => { + got_any = true; + response.push_str(&body); + } + Ok(Ok(_)) => {} + Ok(Err(_)) | Err(_) => break, + } + } + Ok(response) +} + +// --------------------------------------------------------------------------- +// Tauri commands +// --------------------------------------------------------------------------- + +/// Connect to the server's RCON port, authenticate, and spawn the manager task. +/// If a live connection already exists this is a no-op. #[tauri::command] pub async fn rcon_connect( + app: tauri::AppHandle, server_id: String, host: String, port: u16, @@ -25,6 +358,24 @@ pub async fn rcon_connect( ) -> Result<(), String> { use tokio::net::TcpStream; + // Already connected and task is alive — nothing to do. + { + let guard = pool.cmd_channels.lock().await; + if let Some((tx, _)) = guard.get(&server_id) { + if !tx.is_closed() { + return Ok(()); + } + } + } + + emit_status(&app, RconStatusPayload { + server_id: server_id.clone(), + status: "connecting".into(), + host: Some(host.clone()), + port: Some(port), + error: None, + }); + let stream = timeout( Duration::from_secs(5), TcpStream::connect(format!("{host}:{port}")), @@ -34,22 +385,16 @@ pub async fn rcon_connect( .map_err(|e| format!("RCON connect failed: {e}"))?; let _ = stream.set_nodelay(true); + let mut conn = RconConn { stream, next_id: 1 }; - let mut conn = RconConn { - stream, - next_id: 1, - }; - - // Send AUTH packet — do this before inserting into the pool let auth_id = conn.next_id; conn.next_id += 1; conn.send_packet(auth_id, RCON_AUTH, &password).await?; - // Read response packets. Some servers send an empty RESPONSE_VALUE first, - // then the AUTH_RESPONSE; others skip the empty packet. let mut authenticated = false; for _ in 0..3 { - let result = timeout(Duration::from_secs(5), conn.recv_packet()).await + 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 { @@ -67,113 +412,211 @@ pub async fn rcon_connect( return Err("RCON authentication failed — unexpected response sequence".into()); } - pool.connections - .lock() - .await - .insert(server_id, Arc::new(Mutex::new(conn))); + 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; + } + }); + Ok(()) } -/// Send an RCON command and return the server's response string. -/// -/// The pool lock is held only long enough to clone the per-connection Arc. -/// All I/O is done while holding only the individual connection lock, so a -/// slow or hanging command never blocks other servers or disconnect calls. +/// Send an RCON command through the manager task queue. #[tauri::command] pub async fn rcon_send( server_id: String, command: String, pool: State<'_, RconPool>, ) -> Result { - // Grab a clone of the Arc without holding the pool lock during I/O - let conn_arc = { - let guard = pool.connections.lock().await; - guard - .get(&server_id) - .ok_or_else(|| "Not connected to RCON for this server".to_string())? - .clone() - }; - - let mut conn = conn_arc.lock().await; + let tx = pool.cmd_channels.lock().await + .get(&server_id) + .map(|(tx, _)| tx.clone()) + .ok_or_else(|| "Not connected to RCON for this server".to_string())?; - let cmd_id = conn.next_id; - conn.next_id += 1; - conn.send_packet(cmd_id, RCON_EXECCOMMAND, &command).await?; - - // Timeout-based multi-packet reading: - // - Wait up to 15s for the first response packet (commands like saveworld can be slow) - // - After receiving any packet, switch to a 200ms continuation window - // - If no packet arrives within the window, the response is complete - // - This avoids the "ping trick" which ASA ignores - let mut response = String::new(); - let mut received_any = false; - - loop { - let wait = if received_any { - Duration::from_millis(200) - } else { - Duration::from_secs(15) - }; + // ServerChat* responses are an echo of the sent message — suppress them. + let suppress_resp = command.to_lowercase().starts_with("serverchat"); - match timeout(wait, conn.recv_packet()).await { - Ok(Ok((resp_id, _resp_type, body))) => { - received_any = true; - if resp_id == cmd_id { - response.push_str(&body); - } - } - Ok(Err(e)) => return Err(e), - Err(_) => { - if !received_any { - return Err("RCON command timed out — no response from server".into()); - } - break; - } - } - } + let (response_tx, response_rx) = oneshot::channel(); + tx.send(RconCmd::Execute { + command, + suppress_cmd: false, + suppress_resp, + response_tx, + }) + .await + .map_err(|_| "RCON manager task has stopped".to_string())?; - Ok(response) + response_rx.await + .map_err(|_| "RCON response channel dropped".to_string())? } -/// Disconnect RCON for this server and remove the connection from the pool. -/// Removing the Arc here will drop the TcpStream once the connection lock is free. +/// Signal the manager task to close the connection and remove it from the pool. #[tauri::command] pub async fn rcon_disconnect( server_id: String, pool: State<'_, RconPool>, ) -> Result<(), String> { - pool.connections.lock().await.remove(&server_id); + if let Some((tx, _)) = pool.cmd_channels.lock().await.remove(&server_id) { + let _ = tx.send(RconCmd::Disconnect).await; + } Ok(()) } -/// Send RCON `listplayers` and parse the result into a typed player list. -/// -/// ASA response format (one player per line): -/// `0. PlayerName, SteamID 76561198XXXXXXXXX` +/// Returns true only if a manager task is actively running for this server. +/// Uses channel liveness — a dead connection is detected even if the key exists. +#[tauri::command] +pub async fn rcon_is_connected( + server_id: String, + pool: State<'_, RconPool>, +) -> Result { + Ok(pool.cmd_channels.lock().await + .get(&server_id) + .map(|(tx, _)| !tx.is_closed()) + .unwrap_or(false)) +} + +/// Request an immediate listplayers refresh through the manager queue. #[tauri::command] pub async fn rcon_get_players( + _app: tauri::AppHandle, server_id: String, pool: State<'_, RconPool>, ) -> Result, String> { - let raw = rcon_send(server_id, "listplayers".into(), pool).await?; - - let players = raw - .lines() - .filter_map(|line| { - let line = line.trim(); - if line.is_empty() || line.starts_with("No Players") { - return None; - } - let after_dot = line.find(". ").map(|i| &line[i + 2..])?; - if let Some(comma) = after_dot.rfind(", SteamID ") { - let name = after_dot[..comma].trim().to_string(); - let steam_id = after_dot[comma + 10..].trim().to_string(); - Some(ArkPlayer { name, steam_id }) - } else { - None - } - }) - .collect(); + let tx = pool.cmd_channels.lock().await + .get(&server_id) + .map(|(tx, _)| tx.clone()) + .ok_or_else(|| "Not connected to RCON for this server".to_string())?; + + let (response_tx, response_rx) = oneshot::channel(); + tx.send(RconCmd::GetPlayers { response_tx }) + .await + .map_err(|_| "RCON manager task has stopped".to_string())?; + + response_rx.await + .map_err(|_| "RCON response channel dropped".to_string())? +} + +/// Return the cached player list without sending a command. +/// +/// Returns `None` when no RCON connection has been established this session +/// (distinguishes "no data yet" from "0 players online"). +#[tauri::command] +pub async fn rcon_get_cached_players( + server_id: String, + pool: State<'_, RconPool>, +) -> Result>, String> { + Ok(pool.player_cache.lock().await.get(&server_id).cloned()) +} + +/// Return the current in-memory console log for this server (up to 500 lines). +#[tauri::command] +pub async fn rcon_get_log( + server_id: String, + pool: State<'_, RconPool>, +) -> Result, String> { + Ok(pool.log_buffer.lock().await + .get(&server_id) + .map(|d| d.iter().cloned().collect()) + .unwrap_or_default()) +} + +/// Clear the in-memory log buffer for this server. +#[tauri::command] +pub async fn rcon_clear_log( + server_id: String, + pool: State<'_, RconPool>, +) -> Result<(), String> { + pool.log_buffer.lock().await.insert(server_id, VecDeque::new()); + Ok(()) +} + +/// Enable GetChat polling for this server (called when RCON tab opens). +#[tauri::command] +pub async fn rcon_enable_chat_poll( + server_id: String, + pool: State<'_, RconPool>, +) -> Result<(), String> { + pool.chat_poll_active.lock().await.insert(server_id); + Ok(()) +} + +/// Disable GetChat polling for this server (called when RCON tab closes). +#[tauri::command] +pub async fn rcon_disable_chat_poll( + server_id: String, + pool: State<'_, RconPool>, +) -> Result<(), String> { + pool.chat_poll_active.lock().await.remove(&server_id); + Ok(()) +} + +/// Read the server's BanList.txt and return a list of EOS IDs. +#[tauri::command] +pub async fn rcon_read_ban_list(install_path: String) -> Result, String> { + let path = std::path::PathBuf::from(&install_path) + .join(bin_subdir()) + .join("BanList.txt"); + + if !path.exists() { + return Ok(vec![]); + } + + let content = tokio::fs::read_to_string(&path) + .await + .map_err(|e| format!("Failed to read BanList.txt: {e}"))?; + + Ok(content.lines() + .map(|l| l.trim().to_string()) + .filter(|l| !l.is_empty()) + .collect()) +} + +/// Read the server's PlayersJoinNoCheckList.txt and return a list of EOS IDs. +#[tauri::command] +pub async fn rcon_read_whitelist(install_path: String) -> Result, String> { + let path = std::path::PathBuf::from(&install_path) + .join(bin_subdir()) + .join("PlayersJoinNoCheckList.txt"); + + if !path.exists() { + return Ok(vec![]); + } + + let content = tokio::fs::read_to_string(&path) + .await + .map_err(|e| format!("Failed to read PlayersJoinNoCheckList.txt: {e}"))?; - Ok(players) + Ok(content.lines() + .map(|l| l.trim().to_string()) + .filter(|l| !l.is_empty()) + .collect()) } diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index 1b2711d..e3a9c7a 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -126,8 +126,8 @@ async fn fire_broadcast(app: &AppHandle, entry: &crate::state::scheduler::Schedu .as_str() .unwrap_or("Server broadcast.") .to_string(); - transient_rcon_send(entry.rcon_port, &entry.admin_password, &format!("Broadcast {message}")).await; - let _ = app; // no app events needed for broadcast + transient_rcon_send(entry.rcon_port, &entry.rcon_password, &format!("ServerChat {message}")).await; + let _ = app; // no app events needed for chat Ok(()) } @@ -167,44 +167,82 @@ async fn fire_restart(app: &AppHandle, entry: &crate::state::scheduler::Schedule .unwrap_or("Server restarting in {minutes} minutes.") .to_string(); let msg = template.replace("{minutes}", &warning_minutes.to_string()); - transient_rcon_send(entry.rcon_port, &entry.admin_password, &format!("Broadcast {msg}")).await; + transient_rcon_send(entry.rcon_port, &entry.rcon_password, &format!("ServerChat {msg}")).await; sleep(Duration::from_secs(warning_minutes * 60)).await; } - let _ = inner_stop_server(app, &entry.server_id, true); + // Clean shutdown via RCON: save then exit. + transient_rcon_send(entry.rcon_port, &entry.rcon_password, "saveworld").await; + sleep(Duration::from_secs(2)).await; + transient_rcon_send(entry.rcon_port, &entry.rcon_password, "doexit").await; - // Wait up to 15 s for the process to exit. - for _ in 0..30 { + // Wait up to 30 s for the process to exit gracefully. + for _ in 0..60 { sleep(Duration::from_millis(500)).await; - let running = { + let still_running = { let state = app.state::(); let r = state.running_servers.lock().unwrap().contains_key(&entry.server_id); r }; - if !running { - break; - } + if !still_running { break; } } + // Force-kill if still alive. + let _ = inner_stop_server(app, &entry.server_id, false); + let params = entry_to_start_params(entry); inner_start_server(app.clone(), params).await.map(|_| ()) } +/// 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. +async fn fire_global_update_check( + app: &AppHandle, + entry: &crate::state::scheduler::ScheduleEntry, +) -> Result<(), String> { + let sep = if entry.base_dir.contains('\\') { '\\' } else { '/' }; + let cache_dir = format!("{}{sep}lokiasam{sep}cache{sep}asa-server", entry.base_dir); + + 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, + &cache_dir, + false, + "steamcmd://output/global-update-check", + None, + ) + .await?; + + let new_build = crate::commands::steamcmd::get_cache_build_id(&cache_dir) + .unwrap_or_else(|| old_build.clone()); + + let _ = app.emit( + crate::events::ASA_UPDATE_CHECK, + serde_json::json!({ + "updateAvailable": new_build != old_build, + "cachedBuildId": old_build, + "latestBuildId": new_build, + }), + ); + + Ok(()) +} + async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleEntry) -> Result<(), String> { let cfg: serde_json::Value = serde_json::from_str(&entry.config_json).unwrap_or_default(); - let mode = cfg["mode"].as_str().unwrap_or("check_and_apply"); let sep = if entry.base_dir.contains('\\') { '\\' } else { '/' }; let cache_dir = format!("{}{sep}lokiasam{sep}cache{sep}asa-server", entry.base_dir); - // ── Check-only mode: query Steam API, emit result, do nothing else ──────── - if mode == "check_only" { - let result = crate::commands::steamcmd::check_asa_update(cache_dir).await?; - let _ = app.emit(crate::events::ASA_UPDATE_CHECK, result); - return Ok(()); - } - // ── Check & Apply mode ──────────────────────────────────────────────────── let is_running = { let state = app.state::(); @@ -225,7 +263,7 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE if let Ok(Ok(stream)) = tokio::time::timeout(Duration::from_secs(3), TcpStream::connect(addr)).await { let _ = stream.set_nodelay(true); let mut conn = RconConn { stream, next_id: 1 }; - if conn.send_packet(1, RCON_AUTH, &entry.admin_password).await.is_ok() { + if conn.send_packet(1, RCON_AUTH, &entry.rcon_password).await.is_ok() { for _ in 0..3 { match tokio::time::timeout(Duration::from_secs(3), conn.recv_packet()).await { Ok(Ok((_, t, _))) if t == RCON_AUTH_RESPONSE => break, @@ -260,21 +298,28 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE .unwrap_or("Server updating in {minutes} minutes.") .to_string(); let msg = template.replace("{minutes}", &warning_minutes.to_string()); - transient_rcon_send(entry.rcon_port, &entry.admin_password, &format!("Broadcast {msg}")).await; + transient_rcon_send(entry.rcon_port, &entry.rcon_password, &format!("ServerChat {msg}")).await; sleep(Duration::from_secs(warning_minutes * 60)).await; } if is_running { - let _ = inner_stop_server(app, &entry.server_id, true); - for _ in 0..30 { + // Clean shutdown via RCON: save then exit. + transient_rcon_send(entry.rcon_port, &entry.rcon_password, "saveworld").await; + sleep(Duration::from_secs(2)).await; + transient_rcon_send(entry.rcon_port, &entry.rcon_password, "doexit").await; + + for _ in 0..60 { sleep(Duration::from_millis(500)).await; - let running = { + let still_running = { let state = app.state::(); let r = state.running_servers.lock().unwrap().contains_key(&entry.server_id); r }; - if !running { break; } + if !still_running { break; } } + + // Force-kill if still alive. + let _ = inner_stop_server(app, &entry.server_id, false); } // Update shared cache via SteamCMD. @@ -320,9 +365,6 @@ fn entry_to_start_params(entry: &crate::state::scheduler::ScheduleEntry) -> Star port: entry.port, query_port: entry.query_port, rcon_port: entry.rcon_port, - max_players: entry.max_players, - server_password: entry.server_password.clone(), - admin_password: entry.admin_password.clone(), extra_args: entry.extra_args.clone(), mod_ids: entry.mod_ids.clone(), proton_path: entry.proton_path.clone(), @@ -374,6 +416,10 @@ pub fn tick_scheduler(app: &AppHandle) { Ok(_) => (true, None, None), Err(e) => (false, Some(e), None), }, + "global_update_check" => match fire_global_update_check(&app, &entry).await { + Ok(_) => (true, None, None), + Err(e) => (false, Some(e), None), + }, _ => (false, Some(format!("Unknown schedule type: {schedule_type}")), None), }; diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index f31f870..16a51c0 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -1,4 +1,4 @@ -use crate::{events, state::AppState}; +use crate::{events, state::{AppState, rcon_pool::RconPool}}; use serde::{Deserialize, Serialize}; use std::sync::{ atomic::{AtomicBool, Ordering}, @@ -47,9 +47,47 @@ fn strip_ansi(s: &str) -> String { out } +/// Remove Steam/Wine/Proton diagnostic noise from stderr before surfacing it +/// as a start-failed error. These lines are emitted unconditionally by the +/// runtime and contain no actionable information for the user. +fn filter_steam_noise(s: &str) -> String { + let noisy_prefixes = [ + "ProtonFixes", + "wineserver:", + "WARNING: radv", + "WARNING: ANV", + "wine: ", + "wine64: ", + "fsync:", + "esync:", + ]; + let noisy_contains = ["minidumps folder is set to", "NTSync up and running"]; + let lines: Vec<&str> = s + .lines() + .filter(|line| { + let l = line.trim(); + if l.is_empty() { + return false; + } + if noisy_prefixes.iter().any(|p| l.starts_with(p)) { + return false; + } + if noisy_contains.iter().any(|p| l.contains(p)) { + return false; + } + true + }) + .collect(); + lines.join("\n") +} + /// Full parameter set for starting an ASA dedicated server. /// The frontend reads all values from SQLite and passes them here — Rust does /// no DB access of its own. +/// +/// Server name, passwords, rates, RCON, and MaxPlayers all live in +/// GameUserSettings.ini — they are NOT passed on the command line. +/// Only map path, ports, mods, and CLI-only flags are handled here. #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct StartServerParams { @@ -58,23 +96,20 @@ pub struct StartServerParams { pub install_path: String, /// ASA map identifier, e.g. "TheIsland_WP". pub map_path: String, + /// Game UDP port that clients connect to (CLI only, must be ?Port=). pub port: u16, + /// Steam query UDP port (CLI only, must be ?QueryPort=). pub query_port: u16, + /// 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, - pub max_players: u32, - /// Optional join password shown to connecting players. - pub server_password: Option, - pub admin_password: String, - /// Additional command-line flags, e.g. ["-NoBattlEye", "-servergamelog"]. + /// Additional CLI-only flags, e.g. ["-NoBattlEye", "-ForceRespawnDinos"]. pub extra_args: Vec, - /// CurseForge mod IDs to load. Passed as `-mods=id1,id2,...` — the server - /// downloads and applies them on startup automatically. + /// CurseForge mod IDs to load. Passed as `-mods=id1,id2,...`. pub mod_ids: Vec, - /// Linux only: path to the Proton-GE installation directory (must contain `proton` script). - /// Typically {base_dir}/proton/GE-ProtonX-Y/ + /// Linux only: path to the Proton-GE installation directory. pub proton_path: Option, /// Linux only: WINEPREFIX path where Proton creates its fake C: drive. - /// Stored at {base_dir}/proton/prefix/ so everything Proton-related is co-located. pub prefix_path: Option, } @@ -148,6 +183,22 @@ fn pid_alive(pid: u32) -> bool { // Commands // --------------------------------------------------------------------------- +/// Try an A2S_INFO Source Query on localhost. Returns true if any UDP response +/// arrives within 3 seconds. Used by the readiness fallback to get a second +/// opinion when the log watcher times out without seeing READY_MSG. +async fn try_source_query_local(port: u16) -> bool { + use tokio::net::UdpSocket; + use tokio::time::{timeout, Duration}; + let Ok(sock) = UdpSocket::bind("0.0.0.0:0").await else { return false }; + if sock.connect(format!("127.0.0.1:{port}")).await.is_err() { return false; } + let req: &[u8] = b"\xFF\xFF\xFF\xFF\x54Source Engine Query\x00"; + if sock.send(req).await.is_err() { return false; } + let mut buf = [0u8; 64]; + timeout(Duration::from_secs(3), sock.recv(&mut buf)) + .await + .is_ok_and(|r| r.is_ok()) +} + /// Internal: start a server without requiring Tauri State injection. /// Called by both the `start_server` command and the Rust scheduler. pub async fn inner_start_server( @@ -179,20 +230,15 @@ async fn inner_start_server_with_state( params: StartServerParams, ) -> Result { // Build the ?-delimited query string that follows the map name. - let mut query_string = format!( - "{}?listen?Port={}?QueryPort={}?RCONEnabled=True?RCONPort={}?MaxPlayers={}?ServerAdminPassword={}", + // Passwords, RCON, MaxPlayers, and all gameplay settings are read by the + // server from GameUserSettings.ini — they must NOT be duplicated on the CLI + // or they will override INI values on every restart. + let query_string = format!( + "{}?listen?Port={}?QueryPort={}", params.map_path, params.port, params.query_port, - params.rcon_port, - params.max_players, - params.admin_password, ); - if let Some(pw) = ¶ms.server_password { - if !pw.is_empty() { - query_string.push_str(&format!("?ServerPassword={}", pw)); - } - } // Build the platform-specific Command. // Windows: run the Win64 exe directly. @@ -273,9 +319,66 @@ async fn inner_start_server_with_state( cmd.env_remove("PYTHONPATH"); } - let mut child = cmd - .spawn() - .map_err(|e| format!("Failed to start server process: {e}"))?; + // Rotate any existing ShooterGame.log before launching. We own log rotation + // from here on — archiving the old file ourselves so the fresh log starts at + // byte 0 and the readiness watcher below never has to deal with inodes. + let current_log_path = format!( + "{}/ShooterGame/Saved/Logs/ShooterGame.log", + params.install_path + ); + let did_rotate: bool = if tokio::fs::metadata(¤t_log_path).await.is_ok() { + use std::time::{SystemTime, UNIX_EPOCH}; + let now_secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let (year, month, day, hh, mm, ss) = { + let secs_per_day = 86_400u64; + let days = now_secs / secs_per_day; + let day_secs = now_secs % secs_per_day; + let mut d = days; + let mut y = 1970u64; + loop { + let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0); + let days_in_year = if leap { 366 } else { 365 }; + if d < days_in_year { break; } + d -= days_in_year; + y += 1; + } + let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0); + let days_in_month = [31u64, if leap { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + let mut mo = 0usize; + while mo < 12 && d >= days_in_month[mo] { d -= days_in_month[mo]; mo += 1; } + (y, (mo + 1) as u64, d + 1, day_secs / 3600, (day_secs % 3600) / 60, day_secs % 60) + }; + let archive_path = format!( + "{}/ShooterGame/Saved/Logs/ShooterGame_{year:04}-{month:02}-{day:02}_{hh:02}-{mm:02}-{ss:02}.log", + params.install_path + ); + // Rename preferred; fall back to delete so we always start with a clean slate. + if tokio::fs::rename(¤t_log_path, &archive_path).await.is_ok() { + true + } else { + tokio::fs::remove_file(¤t_log_path).await.is_ok() + } + } else { + // No pre-existing log — fresh install or first ever start. + true + }; + + let mut child = match cmd.spawn() { + Ok(c) => c, + Err(e) => { + let msg = if e.kind() == std::io::ErrorKind::NotFound { + // The server executable is missing — reinstall is the only fix. + // Prefix lets the frontend detect this case and hide the Retry button. + "exe_missing: ArkAscendedServer.exe was not found. Please reinstall the server.".to_string() + } else { + format!("Failed to start server process: {e}") + }; + return Err(msg); + } + }; let pid = child.id().ok_or("Spawned process has no PID")?; @@ -296,6 +399,7 @@ async fn inner_start_server_with_state( pid, started_at: Instant::now(), install_path: params.install_path.clone(), + confirmed_running: false, }, ); } @@ -367,12 +471,12 @@ async fn inner_start_server_with_state( // On Linux with the Steam Runtime, Proton (a Python script) hands the // Wine process off to the container daemon and exits — this is NORMAL. // The game continues under a different PID. Before declaring a start - // failure, scan /proc for up to 30 s to see if the game process appears. - // If it does, update the tracked PID and let the log-watcher task handle - // the "running" transition. + // failure, scan /proc for up to 10 s (20 × 500 ms) to see if the game + // process appears. If it does, update the tracked PID and let the + // log-watcher task handle the "running" transition. #[cfg(target_os = "linux")] { - for i in 0..30u32 { + for i in 0..20u32 { if let Some(game_pid) = super::utils::find_game_process_pid(&install_path_watcher) { @@ -386,8 +490,8 @@ async fn inner_start_server_with_state( // The log-watcher task will emit "running" when the ready line appears. return; } - if i < 29 { - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + if i < 19 { + tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; } } } @@ -395,10 +499,11 @@ async fn inner_start_server_with_state( // ── Genuine start failure ───────────────────────────────────────────── app_state.running_servers.lock().unwrap().remove(&sid); let cleaned = strip_ansi(raw_stderr.trim()); - let trimmed = if cleaned.len() > 800 { - format!("\u{2026}{}", &cleaned[cleaned.len() - 800..]) + let filtered = filter_steam_noise(&cleaned); + let trimmed = if filtered.len() > 800 { + format!("\u{2026}{}", &filtered[filtered.len() - 800..]) } else { - cleaned + filtered }; emit_status(&handle_clone, &ServerStatus { server_id: sid, @@ -485,16 +590,18 @@ async fn inner_start_server_with_state( // Falls back to emitting "running" after 15 minutes if the message is // never seen (e.g. log location changed, log disabled) so the server // doesn't stay in "starting" forever. - let sid2 = params.server_id.clone(); - let handle2 = app_handle.clone(); - let log_path2 = format!( + let sid2 = params.server_id.clone(); + let handle2 = app_handle.clone(); + let query_port2 = params.query_port; + let log_path2 = format!( "{}/ShooterGame/Saved/Logs/ShooterGame.log", params.install_path ); + let confirmed2 = Arc::clone(&confirmed_running); tauri::async_runtime::spawn(async move { use std::io::SeekFrom; - use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader}; + use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, BufReader}; use tokio::time::{sleep, Duration, Instant}; // The exact log line ARK SA writes when the server is fully loaded. @@ -504,16 +611,19 @@ async fn inner_start_server_with_state( let deadline = Instant::now() + TIMEOUT; - // Read current PID and uptime from running_servers and emit "running". + // Mark the server as confirmed-running, read its PID/uptime, and emit "running". + // Sets confirmed_running = true so the crash monitor emits "crashed" (not + // "start-failed") if the process dies after this point. // Returns false if the server was already removed from the map. let confirm_running = |handle: &tauri::AppHandle, sid: &str| -> bool { - let pid_uptime = handle - .state::() - .running_servers - .lock() - .unwrap() - .get(sid) - .map(|rs| (rs.pid, rs.started_at.elapsed().as_secs())); + let pid_uptime = { + let state = handle.state::(); + let mut registry = state.running_servers.lock().unwrap(); + registry.get_mut(sid).map(|rs| { + rs.confirmed_running = true; + (rs.pid, rs.started_at.elapsed().as_secs()) + }) + }; let Some((game_pid, uptime)) = pid_uptime else { return false; }; @@ -530,8 +640,12 @@ async fn inner_start_server_with_state( true }; - // ── Wait for the log file to appear ────────────────────────────────── - // The server creates it within the first few seconds of startup. + // ── Wait for the fresh log file to appear ──────────────────────────── + // We rotated any pre-existing ShooterGame.log before spawning, so the + // first file to appear at this path belongs to the current session. + // Read from byte 0 — no need for inode detection or seek-to-end. + // If rotation failed (permissions, locked file), did_rotate is false + // and we seek to end to skip stale content from the previous session. let file = loop { if Instant::now() >= deadline { return; } @@ -549,10 +663,12 @@ async fn inner_start_server_with_state( } }; - // Seek to end so we only see lines from this server session (not a - // previous run that left the log file on disk). let mut file = file; - let _ = file.seek(SeekFrom::End(0)).await; + if !did_rotate { + // Rotation failed — old file is still in place. Seek past stale + // content so we don't false-positive on a READY_MSG from a prior run. + let _ = file.seek(SeekFrom::End(0)).await; + } let mut reader = BufReader::new(file); let mut buf = String::new(); @@ -584,17 +700,59 @@ async fn inner_start_server_with_state( } } - // ── 20-minute fallback ──────────────────────────────────────────────── + // ── 20-minute fallback — verify before promoting ────────────────────── + // The tail loop timed out without seeing READY_MSG. Before blindly + // promoting to "running", make two verification attempts: + // + // 1. Re-scan the tail of the current log file from scratch. This catches + // the TOCTOU race where we spent 20 min tailing the pre-rotation + // archived copy — the live file will have READY_MSG even though we + // never saw it in the tailed stream. + // + // 2. Source Query (A2S_INFO) on localhost. An independent signal that + // the server is advertising to Steam. May not respond from loopback + // on all Linux/Proton configurations, but worth a few attempts. + // + // If both checks fail we still promote as a last resort: the server has + // been running 20+ minutes without crashing, so it is almost certainly + // up. Leaving it in "starting" forever is worse than a false positive. let still_tracked = handle2 .state::() .running_servers .lock() .unwrap() .contains_key(&sid2); - if still_tracked { + if !still_tracked { return; } + + // 1. Re-scan the tail of the log file (last 512 KB) for READY_MSG. + let log_confirmed = 'scan: { + let Ok(mut lf) = tokio::fs::File::open(&log_path2).await else { break 'scan false }; + const TAIL: u64 = 512 * 1024; + let size = lf.metadata().await.map(|m| m.len()).unwrap_or(0); + let _ = lf.seek(SeekFrom::Start(size.saturating_sub(TAIL))).await; + let mut snippet = String::new(); + let _ = lf.read_to_string(&mut snippet).await; + snippet.contains(READY_MSG) + }; + if log_confirmed { confirmed2.store(true, Ordering::Relaxed); confirm_running(&handle2, &sid2); + return; } + + // 2. Try Source Query on localhost (3 attempts, 5 s apart). + for _ in 0..3u8 { + if try_source_query_local(query_port2).await { + confirmed2.store(true, Ordering::Relaxed); + confirm_running(&handle2, &sid2); + return; + } + sleep(Duration::from_secs(5)).await; + } + + // 3. Last resort — promote regardless. + confirmed2.store(true, Ordering::Relaxed); + confirm_running(&handle2, &sid2); }); Ok(pid) @@ -727,35 +885,131 @@ pub async fn get_server_status( } } -/// Register a server PID from a previous app session in the running_servers map -/// so the crash-monitor 30 s polling loop can watch it. +/// Scan for running ASA server processes on app startup. /// -/// Returns `true` if the process is alive, `false` if it has already exited -/// (i.e., it crashed while the app was closed — the frontend should mark it -/// "crashed" in SQLite). +/// For each entry, scans the OS for a matching game process by install path. +/// Servers that are found are registered in the running map and get a dedicated +/// watcher task that fires a crash event within ~5 s of the process dying. +/// Returns the live PID for each server found, or null if not running. +/// This replaces stored-PID reconciliation — the OS is the source of truth. #[tauri::command] -pub async fn register_running_server( +pub async fn scan_running_servers( + app_handle: tauri::AppHandle, state: tauri::State<'_, AppState>, - server_id: String, - pid: u32, - install_path: String, -) -> Result { - if pid_alive(pid) { - let mut registry = state.running_servers.lock().unwrap(); - registry.insert( - server_id, - crate::state::RunningServer { - pid, - // started_at is approximate for re-registered servers; uptime - // will read from SQLite updated_at on the frontend instead. - started_at: Instant::now(), - install_path, - }, - ); - Ok(true) - } else { - Ok(false) + servers: Vec, +) -> Result, String> { + let mut results = Vec::new(); + + for entry in servers { + let pid = find_server_process(&entry.install_path); + + if let Some(pid) = pid { + { + let mut registry = state.running_servers.lock().unwrap(); + registry.insert( + entry.server_id.clone(), + crate::state::RunningServer { + pid, + started_at: Instant::now(), + install_path: entry.install_path, + confirmed_running: true, + }, + ); + } + + let handle = app_handle.clone(); + let sid = entry.server_id.clone(); + tauri::async_runtime::spawn(async move { + loop { + tokio::time::sleep(std::time::Duration::from_secs(5)).await; + + let app_state = handle.state::(); + + // stop_server removes the entry — if it's gone, exit cleanly. + if !app_state.running_servers.lock().unwrap().contains_key(&sid) { + break; + } + + if !pid_alive(pid) { + let was_intentional = app_state + .stopping_servers + .lock() + .unwrap() + .remove(&sid); + + app_state.running_servers.lock().unwrap().remove(&sid); + + 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; + } + } + }); + } + + results.push(ScanResult { server_id: entry.server_id, pid }); } + + Ok(results) +} + +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ScanEntry { + pub server_id: String, + pub install_path: String, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ScanResult { + pub server_id: String, + pub pid: Option, +} + +/// Find a running ASA server process by install path. +/// Linux: procfs cmdline scan finds the Wine game process even when re-parented. +/// Windows: sysinfo exe-path scan finds ArkAscendedServer.exe directly. +#[cfg(target_os = "linux")] +fn find_server_process(install_path: &str) -> Option { + super::utils::find_game_process_pid(install_path) +} + +#[cfg(target_os = "windows")] +fn find_server_process(install_path: &str) -> Option { + use sysinfo::{ProcessesToUpdate, System}; + + if install_path.is_empty() { + return None; + } + + let mut sys = System::new(); + sys.refresh_processes(ProcessesToUpdate::All, false); + + let base = install_path.trim_end_matches('\\').trim_end_matches('/').to_lowercase(); + + for (pid, proc) in sys.processes() { + let exe = proc + .exe() + .map(|p| p.to_string_lossy().to_lowercase()) + .unwrap_or_default(); + if exe.starts_with(&base) && exe.contains("arkascendedserver") { + return Some(pid.as_u32()); + } + } + None } /// Delete a server from disk (optionally) and clean up in-memory state. @@ -828,3 +1082,132 @@ pub async fn clone_server( Ok(()) } + +// --------------------------------------------------------------------------- +// Graceful shutdown +// --------------------------------------------------------------------------- + +/// Gracefully stop a running server with optional player countdown warnings. +/// +/// Flow: +/// 1. Emit "stopping" status +/// 2. If warn_players AND players are online: send countdown chat messages +/// 3. SaveWorld (wait for acknowledgment) +/// 4. DoExit +/// 5. Wait up to 30 s for process to exit, then force-kill +/// 6. Emit "stopped" status +#[tauri::command] +pub async fn graceful_stop_server( + app_handle: tauri::AppHandle, + server_id: String, + rcon_port: u16, + rcon_password: String, + warn_players: bool, + warn_minutes: u64, + warn_message: String, +) -> Result<(), String> { + use crate::commands::rcon::transient_rcon_command; + use tokio::time::{sleep, Duration}; + + let state = app_handle.state::(); + let pool = app_handle.state::(); + + let (pid, install_path) = { + let registry = state.running_servers.lock().unwrap(); + registry + .get(&server_id) + .map(|rs| (rs.pid, rs.install_path.clone())) + .ok_or_else(|| format!("Server {server_id} is not running"))? + }; + + state.stopping_servers.lock().unwrap().insert(server_id.clone()); + + emit_status(&app_handle, &ServerStatus { + server_id: server_id.clone(), + status: "stopping".into(), + pid: Some(pid), + uptime_seconds: None, + error: None, + }); + + // Helper: returns true if at least one player is connected right now. + let has_players = |resp: &str| -> bool { + !resp.trim().is_empty() && !resp.to_lowercase().contains("no players") + }; + + // Optional player countdown — re-checks player count before each message + // so we skip straight to save+exit the moment the server empties. + if warn_players && warn_minutes > 0 { + let initial_check = transient_rcon_command(rcon_port, &rcon_password, "listplayers").await.unwrap_or_default(); + + if has_players(&initial_check) { + let total_secs = warn_minutes * 60; + let mut elapsed: u64 = 0; + + let initial_msg = warn_message.replace( + "{time}", + &format!("{warn_minutes} minute{}", if warn_minutes == 1 { "" } else { "s" }), + ); + let _ = transient_rcon_command(rcon_port, &rcon_password, &format!("ServerChat {initial_msg}")).await; + + 'countdown: while elapsed < total_secs { + let remaining = total_secs - elapsed; + let interval_secs: u64 = if remaining <= 5 { 1 } else if remaining <= 30 { 5 } else { 60 }; + + sleep(Duration::from_secs(interval_secs)).await; + elapsed += interval_secs; + + // If server is now empty, skip the rest of the countdown. + let check = transient_rcon_command(rcon_port, &rcon_password, "listplayers").await.unwrap_or_default(); + if !has_players(&check) { + break 'countdown; + } + + let still_remaining = total_secs.saturating_sub(elapsed); + if still_remaining == 0 { break; } + + let time_str = if still_remaining >= 60 { + let m = still_remaining / 60; + format!("{m} minute{}", if m == 1 { "" } else { "s" }) + } else { + format!("{still_remaining} second{}", if still_remaining == 1 { "" } else { "s" }) + }; + + let msg = warn_message.replace("{time}", &time_str); + let _ = transient_rcon_command(rcon_port, &rcon_password, &format!("ServerChat {msg}")).await; + } + } + } + + // 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; + + // 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; + } + + // Clean up state + 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.chat_poll_active.lock().await.remove(&server_id); + pool.player_cache.lock().await.remove(&server_id); + + emit_status(&app_handle, &ServerStatus { + server_id, + status: "stopped".into(), + pid: None, + uptime_seconds: None, + error: None, + }); + + Ok(()) +} diff --git a/src-tauri/src/commands/stats.rs b/src-tauri/src/commands/stats.rs new file mode 100644 index 0000000..81081b5 --- /dev/null +++ b/src-tauri/src/commands/stats.rs @@ -0,0 +1,21 @@ +use crate::state::stats_recorder::StatsRecorderState; + +/// Called by the frontend once the JS-side `initDb(dbPath)` has run all migrations. +/// Opens a separate rusqlite connection for the background recorder task and +/// immediately runs the first rollup (pruning old raw samples and old daily rows). +#[tauri::command] +pub async fn init_stats_recorder( + db_path: String, + recorder: tauri::State<'_, StatsRecorderState>, +) -> Result<(), String> { + recorder.init(&db_path)?; + + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64; + + recorder.run_rollup(now_ms); + + Ok(()) +} diff --git a/src-tauri/src/commands/steamcmd.rs b/src-tauri/src/commands/steamcmd.rs index aad48d3..623f5fa 100644 --- a/src-tauri/src/commands/steamcmd.rs +++ b/src-tauri/src/commands/steamcmd.rs @@ -14,6 +14,13 @@ const ACF_REL_PATH: &str = "steamapps/appmanifest_2430930.acf"; // ACF / INI helpers // --------------------------------------------------------------------------- +/// Read the build ID from the shared cache directory's appmanifest ACF. +/// Returns None if the cache has never been downloaded. +pub fn get_cache_build_id(cache_dir: &str) -> Option { + let acf_path = Path::new(cache_dir).join(ACF_REL_PATH); + read_acf_build_id(&acf_path) +} + /// Extract the "buildid" value from a SteamCMD appmanifest ACF file. /// Returns None if the file is missing or the key is not found. pub fn read_acf_build_id(acf_path: &Path) -> Option { @@ -108,6 +115,7 @@ struct SteamUpToDateCheck { #[derive(serde::Deserialize)] struct SteamCheckResponse { success: bool, + #[serde(default)] up_to_date: bool, #[serde(default)] required_version: Option, @@ -575,9 +583,14 @@ pub async fn check_asa_update(cache_dir: String) -> Result Result { *cursor += 1; // consume the null byte Ok(s) } + +// --------------------------------------------------------------------------- +// AppImage desktop integration (Linux only) +// +// Writes a .desktop file and icon to the user's XDG local directories so the +// app appears in application menus and launchers. Nothing is written +// automatically — the user triggers this explicitly from the setup wizard or +// settings page. Uninstall removes only the files we created; it does not +// touch the AppImage itself or the user's base/config directories. +// --------------------------------------------------------------------------- + +const APP_INTEGRATION_ID: &str = "xyz.lokisoft.lokiasam"; +const APP_ICON_PNG: &[u8] = include_bytes!("../../icons/icon.png"); + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AppImageIntegrationStatus { + /// True when the process is running as a packaged AppImage. + pub is_appimage: bool, + /// True when our .desktop file already exists in ~/.local/share/applications/. + pub is_installed: bool, +} + +/// Check whether LokiASAM is running as an AppImage and whether it is already +/// registered in the user's application menu. +#[tauri::command] +pub fn check_appimage_integration() -> AppImageIntegrationStatus { + let is_appimage = std::env::var("APPIMAGE").is_ok(); + let is_installed = std::env::var("HOME").map_or(false, |home| { + std::path::Path::new(&format!( + "{home}/.local/share/applications/{APP_INTEGRATION_ID}.desktop" + )) + .exists() + }); + AppImageIntegrationStatus { is_appimage, is_installed } +} + +/// Install LokiASAM into the user's application menu by writing a .desktop +/// file and icon to ~/.local/share/. Only available when running as an AppImage. +#[tauri::command] +pub fn install_appimage_integration() -> Result<(), String> { + let appimage_path = std::env::var("APPIMAGE") + .map_err(|_| "Not running as an AppImage.".to_string())?; + let home = std::env::var("HOME") + .map_err(|_| "HOME environment variable not set.".to_string())?; + + // ── Icons ───────────────────────────────────────────────────────────────── + for size in ["512x512", "256x256", "128x128"] { + let dir = format!("{home}/.local/share/icons/hicolor/{size}/apps"); + std::fs::create_dir_all(&dir) + .map_err(|e| format!("Failed to create icon directory: {e}"))?; + std::fs::write( + format!("{dir}/{APP_INTEGRATION_ID}.png"), + APP_ICON_PNG, + ) + .map_err(|e| format!("Failed to write icon: {e}"))?; + } + + // ── Desktop file ────────────────────────────────────────────────────────── + let desktop_dir = format!("{home}/.local/share/applications"); + std::fs::create_dir_all(&desktop_dir) + .map_err(|e| format!("Failed to create applications directory: {e}"))?; + + let desktop_content = format!( + "[Desktop Entry]\n\ + Name=LokiASAM\n\ + Comment=ARK Survival Ascended Dedicated Server Manager\n\ + Exec={appimage_path} %U\n\ + Icon={APP_INTEGRATION_ID}\n\ + Type=Application\n\ + Categories=Game;Utility;\n\ + StartupWMClass={APP_INTEGRATION_ID}\n\ + Terminal=false\n" + ); + std::fs::write( + format!("{desktop_dir}/{APP_INTEGRATION_ID}.desktop"), + desktop_content, + ) + .map_err(|e| format!("Failed to write desktop file: {e}"))?; + + // ── Rebuild caches ──────────────────────────────────────────────────────── + let icon_theme_dir = format!("{home}/.local/share/icons/hicolor"); + let _ = std::process::Command::new("update-desktop-database").arg(&desktop_dir).status(); + let _ = std::process::Command::new("gtk-update-icon-cache").args(["-f", "-t", &icon_theme_dir]).status(); + let _ = std::process::Command::new("kbuildsycoca6").arg("--incremental").status(); + let _ = std::process::Command::new("kbuildsycoca5").arg("--incremental").status(); + + Ok(()) +} + +/// Remove the .desktop file and icons that were installed by +/// `install_appimage_integration`. Does not touch the AppImage itself. +#[tauri::command] +pub fn uninstall_appimage_integration() -> Result<(), String> { + let home = std::env::var("HOME") + .map_err(|_| "HOME environment variable not set.".to_string())?; + + let desktop_path = format!( + "{home}/.local/share/applications/{APP_INTEGRATION_ID}.desktop" + ); + if std::path::Path::new(&desktop_path).exists() { + std::fs::remove_file(&desktop_path) + .map_err(|e| format!("Failed to remove desktop file: {e}"))?; + } + + for size in ["512x512", "256x256", "128x128"] { + let icon_path = format!( + "{home}/.local/share/icons/hicolor/{size}/apps/{APP_INTEGRATION_ID}.png" + ); + let _ = std::fs::remove_file(&icon_path); // ignore — may not exist for all sizes + } + + // ── Rebuild caches ──────────────────────────────────────────────────────── + let desktop_dir = format!("{home}/.local/share/applications"); + let icon_theme_dir = format!("{home}/.local/share/icons/hicolor"); + let _ = std::process::Command::new("update-desktop-database").arg(&desktop_dir).status(); + let _ = std::process::Command::new("gtk-update-icon-cache").args(["-f", "-t", &icon_theme_dir]).status(); + let _ = std::process::Command::new("kbuildsycoca6").arg("--incremental").status(); + let _ = std::process::Command::new("kbuildsycoca5").arg("--incremental").status(); + + Ok(()) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 0bd7e8e..05b6592 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -2,6 +2,36 @@ mod commands; mod events; mod state; +// Suppress the "libayatana-appindicator is deprecated" stderr warning that the +// library emits unconditionally when the tray icon is initialized on Linux. +// The warning is informational only (Tauri still works correctly); we silence +// it by registering a no-op GLib log handler for that specific domain before +// the tray is created. +#[cfg(target_os = "linux")] +#[link(name = "glib-2.0")] +extern "C" { + fn g_log_set_handler( + log_domain: *const std::ffi::c_char, + log_levels: u32, + log_func: unsafe extern "C" fn( + *const std::ffi::c_char, + u32, + *const std::ffi::c_char, + *mut std::ffi::c_void, + ), + user_data: *mut std::ffi::c_void, + ) -> u32; +} + +#[cfg(target_os = "linux")] +unsafe extern "C" fn noop_log( + _domain: *const std::ffi::c_char, + _level: u32, + _message: *const std::ffi::c_char, + _user_data: *mut std::ffi::c_void, +) { +} + use tauri::{ image::Image, menu::{Menu, MenuItem}, @@ -20,24 +50,36 @@ fn show_main_window(app: &tauri::AppHandle) { if let Some(w) = app.get_webview_window("main") { let is_min = w.is_minimized().unwrap_or(false); if is_min { - let _ = w.unminimize(); + // Wayland XDG Shell has no unminimize operation; maximize overrides it. + let _ = w.maximize(); } let _ = w.show(); - // set_focus() alone is blocked by focus-stealing prevention on X11 and - // most Wayland compositors (Cinnamon, GNOME, KDE, etc.). - // Workaround: briefly set always-on-top so the WM is forced to raise and - // present the window, then immediately restore normal z-order. - // The 50 ms pre-delay gives the WM time to finish processing unminimize/show - // before we try to raise. The 50 ms post-delay keeps the window pinned - // long enough for focus to land before we clear the flag. let w2 = w.clone(); tauri::async_runtime::spawn(async move { - tokio::time::sleep(std::time::Duration::from_millis(50)).await; - let _ = w2.set_always_on_top(true); + // KDE/KWin leaves decoration buttons non-interactive after a hide→show + // cycle. Cycling through maximize state forces KWin to re-initialize + // button input regions. Only needed on KDE — other DEs handle remap fine. + #[cfg(target_os = "linux")] + let on_kde = std::env::var("XDG_CURRENT_DESKTOP") + .map(|v| v.to_uppercase().contains("KDE")) + .unwrap_or(false); + #[cfg(not(target_os = "linux"))] + let on_kde = false; + + if on_kde { + let already_max = w2.is_maximized().unwrap_or(false); + if already_max { + let _ = w2.unmaximize(); + tokio::time::sleep(std::time::Duration::from_millis(16)).await; + let _ = w2.maximize(); + } else { + let _ = w2.maximize(); + tokio::time::sleep(std::time::Duration::from_millis(16)).await; + let _ = w2.unmaximize(); + } + } let _ = w2.set_focus(); - tokio::time::sleep(std::time::Duration::from_millis(50)).await; - let _ = w2.set_always_on_top(false); }); } if let Some(tray_state) = app.try_state::() { @@ -77,8 +119,26 @@ fn hide_main_window(app: &tauri::AppHandle) { } } + #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { + #[cfg(target_os = "linux")] + unsafe { + // G_LOG_LEVEL_WARNING = 1 << 4 + g_log_set_handler( + b"libayatana-appindicator\0".as_ptr() as *const std::ffi::c_char, + 1u32 << 4, + noop_log, + std::ptr::null_mut(), + ); + } + + // Disable WebKit's DMA-BUF renderer before the WebView is created. + // The DMA-BUF path breaks on modern Linux distributions (Arch, CachyOS, etc.) + // with newer mesa/kernel versions, producing a blank white window. Falling back + // to the SHM renderer has no visible effect for a desktop management UI. + #[cfg(target_os = "linux")] + std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1"); tauri::Builder::default() // ── Single-instance guard ────────────────────────────────────────── @@ -99,6 +159,7 @@ pub fn run() { app.manage(state::rcon_pool::RconPool::new()); app.manage(state::log_watcher::LogWatcherState::new()); app.manage(state::scheduler::SchedulerState::new()); + app.manage(state::stats_recorder::StatsRecorderState::new()); // ── System tray ─────────────────────────────────────────────── // Window starts visible, so "Bring to Front" is the correct initial label. @@ -171,99 +232,163 @@ pub fn run() { } }); - // ── Crash-monitor background task ────────────────────────────── - // Polls every 30 s for any PID in `running_servers` that has exited - // unexpectedly. This catches servers started in a previous app session - // that were re-registered via `register_running_server`, as well as - // any watcher-task gaps. For servers started in the current session - // the per-server watcher task in `start_server` provides instant - // detection; this loop acts as a safety net. - let handle = app.handle().clone(); + // ── Scheduler background task ────────────────────────────────── + let scheduler_handle = app.handle().clone(); tauri::async_runtime::spawn(async move { let mut interval = tokio::time::interval(std::time::Duration::from_secs(30)); - // Skip the immediate first tick so we don't race with startup - // reconciliation on the frontend. interval.tick().await; + loop { + interval.tick().await; + commands::scheduler::tick_scheduler(&scheduler_handle); + } + }); + + // ── Stats recorder background task ───────────────────────────── + // Polls all running servers every 5 s. On every poll: + // - Emits "stats://live" so the frontend live buffer stays current. + // - Writes a raw sample to server_stats_history every 12th poll (60 s). + // - Opens / closes server_uptime_sessions when servers start / stop. + // Waits until the frontend calls init_stats_recorder (which opens the + // rusqlite connection) before doing any DB work. + let stats_handle = app.handle().clone(); + tauri::async_runtime::spawn(async move { + use std::collections::{HashMap, HashSet}; + + let mut poll_counters: HashMap = HashMap::new(); + let mut prev_active: HashSet = HashSet::new(); + let mut open_sessions: HashMap = HashMap::new(); + let mut rollup_done = false; + let mut last_rollup = tokio::time::Instant::now(); + + let mut interval = + tokio::time::interval(std::time::Duration::from_secs(5)); + interval.set_missed_tick_behavior( + tokio::time::MissedTickBehavior::Skip, + ); + interval.tick().await; // consume the immediate first tick loop { interval.tick().await; - let app_state = handle.state::(); + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as i64; + + let recorder = stats_handle + .state::(); + + if !recorder.is_ready() { + continue; + } + + // Initial rollup on first ready tick; then every 24 h. + if !rollup_done { + rollup_done = true; + last_rollup = tokio::time::Instant::now(); + recorder.run_rollup(now_ms); + } else if last_rollup.elapsed() + >= std::time::Duration::from_secs(24 * 60 * 60) + { + last_rollup = tokio::time::Instant::now(); + recorder.run_rollup(now_ms); + } - // Snapshot current entries to avoid holding the lock - // across the sysinfo calls. - let entries: Vec<(String, u32)> = { - let registry = app_state.running_servers.lock().unwrap(); - registry - .iter() - .map(|(id, rs)| (id.clone(), rs.pid)) + // Snapshot running servers. + let app_state = stats_handle.state::(); + let servers: Vec<(String, u32, String)> = { + let lock = app_state.running_servers.lock().unwrap(); + lock.iter() + .map(|(id, rs)| { + (id.clone(), rs.pid, rs.install_path.clone()) + }) .collect() }; + let active_now: HashSet = + servers.iter().map(|(id, _, _)| id.clone()).collect(); - if entries.is_empty() { - continue; + // Open uptime sessions for newly-started servers. + for id in active_now.difference(&prev_active) { + let session_id = uuid::Uuid::new_v4().to_string(); + open_sessions.insert(id.clone(), session_id.clone()); + recorder.open_uptime_session(id, &session_id, now_ms); + } + // Close uptime sessions for servers that stopped. + for id in prev_active.difference(&active_now) { + if let Some(sid) = open_sessions.remove(id) { + recorder.close_uptime_session(&sid, now_ms); + } + poll_counters.remove(id); } + prev_active = active_now; + + // Sample all active servers concurrently so the 200 ms + // CPU-delta sleeps inside get_process_stats overlap. + let rcon_pool = + stats_handle.state::(); + let mut tasks = tokio::task::JoinSet::new(); + + 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 + .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); - use sysinfo::{Pid, ProcessesToUpdate, System}; - let mut sys = System::new(); - - for (server_id, pid) in &entries { - let spid = Pid::from_u32(*pid); - sys.refresh_processes(ProcessesToUpdate::Some(&[spid]), false); - let alive = sys.process(spid).is_some(); - - if !alive { - let was_intentional = app_state - .stopping_servers - .lock() - .unwrap() - .remove(server_id); - - app_state - .running_servers - .lock() - .unwrap() - .remove(server_id); - - let status_str = - if was_intentional { "stopped" } else { "crashed" }; - - let payload = commands::server::ServerStatus { - server_id: server_id.clone(), - status: status_str.into(), - pid: None, - uptime_seconds: None, - error: None, - }; - - let _ = handle.emit( - &events::server_event( - events::SERVER_STATUS, - server_id, - ), - payload.clone(), + let _ = stats_handle.emit( + "stats://live", + serde_json::json!({ + "serverId": server_id, + "ts": now_ms, + "cpu": cpu, + "mem": mem, + "players": players, + }), + ); + + // Write raw sample every 12th poll (~60 s). + let count = + poll_counters.entry(server_id.clone()).or_insert(0); + *count += 1; + if *count % 12 == 0 { + recorder.insert_stat_sample( + &server_id, + now_ms, + cpu, + mem, + players, ); - let _ = handle.emit(events::SERVER_ANY_CHANGE, payload); } } } }); - // ── Scheduler background task ────────────────────────────────── - // Checks every 30 s for due entries. This runs unconditionally — JS - // timers are throttled when the window is hidden to tray; this loop is not. - let scheduler_handle = app.handle().clone(); - tauri::async_runtime::spawn(async move { - let mut interval = - tokio::time::interval(std::time::Duration::from_secs(30)); - interval.tick().await; // skip the immediate first tick - - loop { - interval.tick().await; - commands::scheduler::tick_scheduler(&scheduler_handle); - } - }); + // RCON chat and player polling are now handled inside per-server + // manager tasks spawned by rcon_connect. No background tasks needed here. Ok(()) }) @@ -279,8 +404,9 @@ pub fn run() { commands::server::start_server, commands::server::stop_server, commands::server::restart_server, + commands::server::graceful_stop_server, commands::server::get_server_status, - commands::server::register_running_server, + commands::server::scan_running_servers, commands::server::clone_server, commands::server::delete_server, // SteamCMD / installation @@ -298,7 +424,15 @@ pub fn run() { commands::rcon::rcon_connect, commands::rcon::rcon_send, commands::rcon::rcon_disconnect, + commands::rcon::rcon_is_connected, commands::rcon::rcon_get_players, + commands::rcon::rcon_get_cached_players, + commands::rcon::rcon_get_log, + commands::rcon::rcon_clear_log, + commands::rcon::rcon_enable_chat_poll, + commands::rcon::rcon_disable_chat_poll, + commands::rcon::rcon_read_ban_list, + commands::rcon::rcon_read_whitelist, // Log watcher commands::logs::watch_server_log, commands::logs::stop_log_watch, @@ -317,7 +451,12 @@ pub fn run() { commands::mods::close_mod_browser, commands::mods::start_mod_verification, commands::mods::close_mod_verify, + // Stats recorder + commands::stats::init_stats_recorder, // System stats + commands::system::check_appimage_integration, + commands::system::install_appimage_integration, + commands::system::uninstall_appimage_integration, commands::system::check_dir, commands::system::check_file_exists, commands::system::delete_directory, diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 23c39a0..ed7d9d2 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -2,5 +2,5 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] fn main() { - lokiasam_lib::run(); + lokiasam_lib::run(); } diff --git a/src-tauri/src/state/mod.rs b/src-tauri/src/state/mod.rs index 2a5169a..854d1f4 100644 --- a/src-tauri/src/state/mod.rs +++ b/src-tauri/src/state/mod.rs @@ -1,6 +1,7 @@ pub mod log_watcher; pub mod rcon_pool; pub mod scheduler; +pub mod stats_recorder; use std::collections::{HashMap, HashSet}; use std::sync::{atomic::AtomicBool, Arc, Mutex}; @@ -17,6 +18,10 @@ pub struct RunningServer { /// On Linux, used to locate Wine processes that were launched inside the Steam /// Runtime container (and therefore not visible in the proton PID's subtree). pub install_path: String, + /// Set to true once the log watcher sees the readiness line and emits "running". + /// The crash monitor uses this to distinguish a startup failure (false → "start-failed") + /// from a genuine runtime crash (true → "crashed"). + pub confirmed_running: bool, } /// Global application state shared across all Tauri commands via `tauri::State`. diff --git a/src-tauri/src/state/rcon_pool.rs b/src-tauri/src/state/rcon_pool.rs index 73950cd..7955d99 100644 --- a/src-tauri/src/state/rcon_pool.rs +++ b/src-tauri/src/state/rcon_pool.rs @@ -1,10 +1,10 @@ -use std::collections::HashMap; -use std::sync::Arc; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::atomic::{AtomicU64, Ordering}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; -use tokio::sync::Mutex; +use tokio::sync::{mpsc, oneshot, Mutex}; -/// Packet type constants for Source RCON protocol. +/// Packet type constants for the Source RCON protocol. pub const RCON_AUTH: i32 = 3; pub const RCON_AUTH_RESPONSE: i32 = 2; pub const RCON_EXECCOMMAND: i32 = 2; @@ -71,16 +71,120 @@ impl RconConn { } } -/// Global pool of live RCON connections, keyed by server UUID. -/// Each connection has its own Mutex so the pool lock is never held during I/O. +/// One line in the RCON console log buffer. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RconLogLine { + pub timestamp_ms: u64, + pub text: String, + /// "command" | "response" | "chat" | "system" | "error" + pub kind: String, +} + +/// A cached player entry from listplayers output. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CachedPlayer { + pub name: String, + pub player_id: String, +} + +/// Command sent to a server's RCON manager task through its mpsc channel. +pub enum RconCmd { + /// Execute an arbitrary RCON command and return the raw response. + Execute { + command: String, + /// When true, the "> command" log line is suppressed. + suppress_cmd: bool, + /// When true, response lines are not logged to the console. + suppress_resp: bool, + response_tx: oneshot::Sender>, + }, + /// Run listplayers, update the player cache, emit rcon://players/{id}. + GetPlayers { + response_tx: oneshot::Sender, String>>, + }, + /// Gracefully shut down the manager task and close the connection. + Disconnect, +} + +/// Global pool of RCON manager state, keyed by server UUID. pub struct RconPool { - pub connections: Mutex>>>, + /// mpsc sender + connection ID for each server's manager task. + /// The ID lets a stale manager task detect that a newer connection has + /// taken over, so it exits silently instead of clobbering the pool. + pub cmd_channels: Mutex, u64)>>, + /// Rolling console log buffer per server, capped at 500 lines. + pub log_buffer: Mutex>>, + /// Server IDs that have an active GetChat poll subscriber (RCON tab open). + pub chat_poll_active: Mutex>, + /// Last-known player list per server. A missing key means no data yet + /// (never connected this session); an empty Vec means 0 players online. + pub player_cache: Mutex>>, + /// Monotonically increasing counter — each rcon_connect call gets a unique ID. + next_conn_id: AtomicU64, } impl RconPool { pub fn new() -> Self { Self { - connections: Mutex::new(HashMap::new()), + cmd_channels: Mutex::new(HashMap::new()), + log_buffer: Mutex::new(HashMap::new()), + chat_poll_active: Mutex::new(HashSet::new()), + player_cache: Mutex::new(HashMap::new()), + next_conn_id: AtomicU64::new(1), } } + + /// Allocate the next connection ID (used by rcon_connect). + pub fn alloc_conn_id(&self) -> u64 { + self.next_conn_id.fetch_add(1, Ordering::Relaxed) + } + + pub fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64 + } + + /// Append a log line to the buffer for `server_id` (cap 500 lines). + pub async fn push_log(&self, server_id: &str, line: RconLogLine) { + let mut buf = self.log_buffer.lock().await; + let deque = buf.entry(server_id.to_string()).or_default(); + if deque.len() >= 500 { + deque.pop_front(); + } + deque.push_back(line); + } +} + +/// Returns the platform binary subdirectory within a server install path. +/// On Linux we always run the Win64 dedicated server binary via Wine/Proton. +pub fn bin_subdir() -> &'static str { + "ShooterGame/Binaries/Win64" +} + +/// Parse the raw `listplayers` response into a typed player list. +/// +/// ASA response format (one player per line): +/// `0. PlayerName, EOS_ID` +pub fn parse_player_list(raw: &str) -> Vec { + raw.lines() + .filter_map(|line| { + let line = line.trim(); + if line.is_empty() || line.to_lowercase().starts_with("no players") { + return None; + } + let after_dot = line.find(". ").map(|i| &line[i + 2..])?; + if let Some(comma) = after_dot.rfind(", ") { + let name = after_dot[..comma].trim().to_string(); + let player_id = after_dot[comma + 2..].trim().to_string(); + if !player_id.is_empty() { + return Some(CachedPlayer { name, player_id }); + } + } + None + }) + .collect() } diff --git a/src-tauri/src/state/scheduler.rs b/src-tauri/src/state/scheduler.rs index 5788666..84a37ee 100644 --- a/src-tauri/src/state/scheduler.rs +++ b/src-tauri/src/state/scheduler.rs @@ -3,6 +3,9 @@ use std::sync::Mutex; /// One schedule entry with all data needed to fire the action — no DB access required. /// The frontend builds this from SQLite and sends it via `sync_schedules`. +/// +/// Server passwords, MaxPlayers, and gameplay settings are NOT included here — +/// they are in GameUserSettings.ini and read by the server process directly. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ScheduleEntry { @@ -19,9 +22,6 @@ pub struct ScheduleEntry { pub rcon_port: u16, /// RCON/admin password — used for in-game broadcast warnings before restart/update. pub rcon_password: String, - pub max_players: u32, - pub server_password: Option, - pub admin_password: String, pub extra_args: Vec, pub mod_ids: Vec, /// Linux only: path to Proton-GE directory. diff --git a/src-tauri/src/state/stats_recorder.rs b/src-tauri/src/state/stats_recorder.rs new file mode 100644 index 0000000..430538f --- /dev/null +++ b/src-tauri/src/state/stats_recorder.rs @@ -0,0 +1,120 @@ +use std::sync::Mutex; + +/// Holds a direct rusqlite connection used exclusively by the background stats recorder task. +/// The connection is opened once `init_stats_recorder` is called from the frontend +/// (after the JS-side `initDb` has already run migrations on the same file). +/// +/// All public methods lock the connection internally and silently swallow errors so +/// that a DB hiccup never disrupts the main stats polling loop. +pub struct StatsRecorderState { + conn: Mutex>, +} + +// rusqlite::Connection is Send but not Sync. Wrapping in Mutex> provides +// the Sync bound that Tauri's managed-state system requires. +// Safety: access is always serialised through the Mutex. +unsafe impl Sync for StatsRecorderState {} + +impl StatsRecorderState { + pub fn new() -> Self { + Self { + conn: Mutex::new(None), + } + } + + /// Open (or re-open) a connection to the SQLite file at `db_path`. + /// Must be called after the frontend has already applied all migrations. + pub fn init(&self, db_path: &str) -> Result<(), String> { + let conn = rusqlite::Connection::open(db_path) + .map_err(|e| format!("StatsRecorder: failed to open DB: {e}"))?; + // Match the WAL + synchronous settings the frontend uses. + conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;") + .map_err(|e| format!("StatsRecorder: PRAGMA failed: {e}"))?; + *self.conn.lock().unwrap() = Some(conn); + Ok(()) + } + + pub fn is_ready(&self) -> bool { + self.conn.lock().unwrap().is_some() + } + + pub fn insert_stat_sample( + &self, + server_id: &str, + sampled_at: i64, + cpu_pct: Option, + mem_mb: Option, + players: Option, + ) { + let guard = self.conn.lock().unwrap(); + if let Some(c) = guard.as_ref() { + let _ = c.execute( + "INSERT INTO server_stats_history \ + (server_id, sampled_at, cpu_pct, mem_mb, players) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + rusqlite::params![server_id, sampled_at, cpu_pct, mem_mb, players], + ); + } + } + + pub fn open_uptime_session(&self, server_id: &str, session_id: &str, started_at: i64) { + let guard = self.conn.lock().unwrap(); + if let Some(c) = guard.as_ref() { + let _ = c.execute( + "INSERT OR IGNORE INTO server_uptime_sessions \ + (id, server_id, started_at) VALUES (?1, ?2, ?3)", + rusqlite::params![session_id, server_id, started_at], + ); + } + } + + pub fn close_uptime_session(&self, session_id: &str, ended_at: i64) { + let guard = self.conn.lock().unwrap(); + if let Some(c) = guard.as_ref() { + let _ = c.execute( + "UPDATE server_uptime_sessions \ + SET ended_at = ?1 \ + WHERE id = ?2 AND ended_at IS NULL", + rusqlite::params![ended_at, session_id], + ); + } + } + + /// Roll up raw samples older than 30 days into daily aggregates, + /// then delete daily rows older than 1 year. + pub fn run_rollup(&self, now_ms: i64) { + let guard = self.conn.lock().unwrap(); + if let Some(c) = guard.as_ref() { + let cutoff_30d: i64 = now_ms - 30 * 24 * 60 * 60_000; + let cutoff_1y: i64 = now_ms - 365 * 24 * 60 * 60_000; + let day_ms: i64 = 86_400_000; + + // Aggregate raw rows into daily buckets (INSERT OR REPLACE merges with existing). + let _ = c.execute( + "INSERT OR REPLACE INTO server_stats_daily \ + (server_id, day_ts, avg_cpu, max_cpu, avg_mem, max_mem, avg_players, max_players) \ + SELECT server_id, \ + (sampled_at / ?1) * ?1 AS day_ts, \ + AVG(cpu_pct), MAX(cpu_pct), \ + AVG(mem_mb), MAX(mem_mb), \ + AVG(players), MAX(players) \ + FROM server_stats_history \ + WHERE sampled_at < ?2 \ + GROUP BY server_id, day_ts", + rusqlite::params![day_ms, cutoff_30d], + ); + + // Remove the raw rows that were just rolled up. + let _ = c.execute( + "DELETE FROM server_stats_history WHERE sampled_at < ?1", + rusqlite::params![cutoff_30d], + ); + + // Prune daily rows beyond 1 year. + let _ = c.execute( + "DELETE FROM server_stats_daily WHERE day_ts < ?1", + rusqlite::params![cutoff_1y], + ); + } + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 5d3c758..f4e6874 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.10.1", + "version": "0.11.0", "identifier": "xyz.lokisoft.lokiasam", "build": { "frontendDist": "../out", diff --git a/src/app/globals.css b/src/app/globals.css index 5bfa275..409bbf6 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -37,7 +37,7 @@ Overridden at runtime by applyThemeAccent() to match the chosen accent. */ --color-primary: #bf00ff; --color-primary-foreground: #050510; - --color-input: rgba(191, 0, 255, 0.2); + --color-input: rgba(var(--neon-purple-rgb), 0.2); --color-ring: #bf00ff; --color-muted: rgba(10, 10, 30, 0.75); --color-muted-foreground: #5858a0; @@ -61,6 +61,9 @@ --surface-elevated: rgba(15, 15, 40, 0.9); --terminal-bg: #000008; + /* Accent RGB components — updated by applyThemeAccent() so all rgba() uses track the active color */ + --neon-purple-rgb: 191, 0, 255; + /* Borders — purple is the primary accent */ --border: rgba(191, 0, 255, 0.15); --border-hover: rgba(191, 0, 255, 0.4); @@ -114,11 +117,11 @@ body { color: var(--text-primary); font-family: var(--font-geist-sans), system-ui, -apple-system, sans-serif; min-height: 100vh; - /* Subtle scanline/grid background texture — purple tint for primary theme */ + /* Subtle scanline/grid background texture — tracks the active accent color */ background-image: - radial-gradient(ellipse 80% 50% at 50% -20%, rgba(191,0,255,0.06) 0%, transparent 60%), - linear-gradient(rgba(191,0,255,0.015) 1px, transparent 1px), - linear-gradient(90deg, rgba(191,0,255,0.015) 1px, transparent 1px); + radial-gradient(ellipse 80% 50% at 50% -20%, rgba(var(--neon-purple-rgb),0.06) 0%, transparent 60%), + linear-gradient(rgba(var(--neon-purple-rgb),0.015) 1px, transparent 1px), + linear-gradient(90deg, rgba(var(--neon-purple-rgb),0.015) 1px, transparent 1px); background-size: 100% 100%, 40px 40px, 40px 40px; } @@ -144,7 +147,7 @@ body { } .glass-card:hover { - border-color: rgba(191, 0, 255, 0.3); + border-color: rgba(var(--neon-purple-rgb), 0.3); } /* --------------------------------------------------------------------------- @@ -156,7 +159,7 @@ body { .glow-red { box-shadow: var(--glow-red); } .text-glow-cyan { text-shadow: 0 0 10px rgba(0,255,255,0.8); } -.text-glow-purple { text-shadow: 0 0 10px rgba(191,0,255,0.8); } +.text-glow-purple { text-shadow: 0 0 10px rgba(var(--neon-purple-rgb),0.8); } .text-glow-green { text-shadow: 0 0 10px rgba(0,255,136,0.8); } .text-glow-red { text-shadow: 0 0 10px rgba(255,0,85,0.8); } @@ -194,8 +197,8 @@ body { } @keyframes pulse-border-purple { - 0%, 100% { box-shadow: 0 0 12px rgba(191,0,255,0.3); } - 50% { box-shadow: 0 0 24px rgba(191,0,255,0.6); } + 0%, 100% { box-shadow: 0 0 12px rgba(var(--neon-purple-rgb),0.3); } + 50% { box-shadow: 0 0 24px rgba(var(--neon-purple-rgb),0.6); } } @keyframes pulse-border-cyan { @@ -217,8 +220,8 @@ body { --------------------------------------------------------------------------- */ ::-webkit-scrollbar { width: 6px; height: 6px; } ::-webkit-scrollbar-track { background: rgba(0,0,0,0.3); } -::-webkit-scrollbar-thumb { background: rgba(191,0,255,0.2); border-radius: 3px; } -::-webkit-scrollbar-thumb:hover { background: rgba(191,0,255,0.4); } +::-webkit-scrollbar-thumb { background: rgba(var(--neon-purple-rgb),0.2); border-radius: 3px; } +::-webkit-scrollbar-thumb:hover { background: rgba(var(--neon-purple-rgb),0.4); } /* --------------------------------------------------------------------------- Neon button base styles (used in conjunction with ShadCN Button variants) @@ -230,7 +233,7 @@ body { transition: box-shadow 150ms ease, background 150ms ease; } .btn-neon-purple:hover { - background: rgba(191,0,255,0.08); + background: rgba(var(--neon-purple-rgb),0.08); box-shadow: var(--glow-purple); } diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 1fa78fa..2f298f1 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,17 +1,7 @@ import type { Metadata } from "next"; import { Geist, Geist_Mono } from "next/font/google"; import "./globals.css"; -import { Providers } from "@/components/layout/Providers"; -import { Sidebar } from "@/components/layout/Sidebar"; -import { TopBar } from "@/components/layout/TopBar"; -import { SetupGuard } from "@/components/layout/SetupGuard"; -import { DisableContextMenu } from "@/components/layout/DisableContextMenu"; -import { ModBrowserEventHandler } from "@/components/layout/ModBrowserEventHandler"; -import { SchedulerManager } from "@/components/layout/SchedulerManager"; -import { NotificationManager } from "@/components/layout/NotificationManager"; -import { UpdateManager } from "@/components/layout/UpdateManager"; -import { CloseWarningManager } from "@/components/layout/CloseWarningManager"; -import { Toaster } from "sonner"; +import { AppShell } from "@/components/layout/AppShell"; const geistSans = Geist({ variable: "--font-geist-sans", @@ -32,49 +22,14 @@ export const metadata: Metadata = { export default function RootLayout({ children, -}: Readonly<{ - children: React.ReactNode; -}>) { +}: Readonly<{ children: React.ReactNode }>) { return ( - - - {/* - SetupGuard checks SQLite on mount. While checking it shows a loading - spinner. If setup is not complete it renders the SetupWizard overlay - on top of everything. Once setup completes it clears the overlay. - */} - - - - - - - -
- -
- -
- {children} -
-
-
-
-
+ {children} ); diff --git a/src/app/notifications/page.tsx b/src/app/notifications/page.tsx index f1738d9..a61f6bf 100644 --- a/src/app/notifications/page.tsx +++ b/src/app/notifications/page.tsx @@ -25,6 +25,7 @@ import { markAllNotificationsRead, deleteNotification, pruneNotificationsWithFilter, + parseDbDate, type InAppNotificationRow, } from "@/lib/db"; import { useAppStore } from "@/store/useAppStore"; @@ -106,7 +107,7 @@ function NotificationRow({ className="text-xs shrink-0" style={{ color: "var(--text-subtle)" }} > - {new Date(n.created_at).toLocaleString()} + {parseDbDate(n.created_at).toLocaleString()}

diff --git a/src/app/page.tsx b/src/app/page.tsx index 5696fe5..4087af6 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -8,8 +8,11 @@ import { StatCard } from "@/components/shared/StatCard"; import { ServerCard } from "@/components/server/ServerCard"; import { ImportServerWizard } from "@/components/server/ImportServerWizard"; import { useServers } from "@/hooks/useServers"; -import { getTransitioningServers, updateServerStatus, getAppSetting, setAppSetting } from "@/lib/db"; +import { getAppSetting, setAppSetting } from "@/lib/db"; import { tauriCmd, type UpdateCheckResult } from "@/lib/tauri-commands"; +import { runPerServerUpdateCheck } from "@/lib/update-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"; @@ -21,7 +24,6 @@ import { toast } from "sonner"; function UpdateStatusChip() { const [checking, setChecking] = useState(false); - const [updating, setUpdating] = useState(false); const [updateAvailable, setUpdateAvailable] = useState(false); const [cachedBuild, setCachedBuild] = useState(""); const [latestBuild, setLatestBuild] = useState(""); @@ -58,62 +60,63 @@ function UpdateStatusChip() { await setAppSetting("asa_latest_build_id", r.latestBuildId); await setAppSetting("asa_last_checked", now); load(); + // Always run per-server check — a server may be behind the cache even + // if the cache itself is current (e.g. server was never updated). + await runPerServerUpdateCheck(); } }); const handleCheck = async () => { setChecking(true); try { - const cacheDir = await getAppSetting("base_dir"); - if (!cacheDir) { toast.error("Base directory not configured."); return; } - const sep = cacheDir.includes("\\") ? "\\" : "/"; - const dir = `${cacheDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; - const result = await tauriCmd.checkAsaUpdate(dir); - const now = new Date().toISOString(); - await setAppSetting("asa_update_available", String(result.updateAvailable)); - await setAppSetting("asa_cached_build_id", result.cachedBuildId); - await setAppSetting("asa_latest_build_id", result.latestBuildId); - await setAppSetting("asa_last_checked", now); - load(); - if (result.updateAvailable) { - toast.info(`Update available: build ${result.latestBuildId}`); - } else { - toast.success("Server is up to date."); - } - } catch (e) { - toast.error(`Update check failed: ${e}`); - } finally { - setChecking(false); - } - }; - - const handleUpdateCache = async () => { - setUpdating(true); - try { - const [cacheBase, steamcmdPath] = await Promise.all([ + const [baseDir, steamcmdPath] = await Promise.all([ getAppSetting("base_dir"), getAppSetting("steamcmd_path"), ]); - if (!cacheBase || !steamcmdPath) { - toast.error("Base directory or SteamCMD path not configured."); + if (!baseDir || !steamcmdPath) { + toast.error("Base directory or SteamCMD not configured."); return; } - const sep = cacheBase.includes("\\") ? "\\" : "/"; - const cacheDir = `${cacheBase.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; - const newBuild = await tauriCmd.updateCache("global", cacheDir, steamcmdPath); - await setAppSetting("asa_cached_build_id", newBuild); - await setAppSetting("asa_update_available", "false"); - await setAppSetting("asa_last_checked", new Date().toISOString()); + 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(); + 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), + ]); + await runPerServerUpdateCheck(); load(); - toast.success(`Cache updated to build ${newBuild}. Apply to individual servers via their Overview tab.`); + if (cacheUpdated) { + await dispatchNotification({ + eventType: NOTIFICATION_EVENTS.UPDATE_AVAILABLE, + serverId: null, + serverName: "ASA Cache", + title: "Cache Updated", + body: `Cache updated to build ${newBuild}. Outdated servers have been flagged.`, + severity: "info", + }); + } else { + toast.success(`Cache is up to date (build ${newBuild}).`); + } } catch (e) { - toast.error(`Cache update failed: ${e}`); + await dispatchNotification({ + eventType: NOTIFICATION_EVENTS.UPDATE_FAILED, + serverId: null, + serverName: "ASA Cache", + title: "Cache Update Failed", + body: `Failed to update cache: ${e}`, + severity: "error", + }); } finally { - setUpdating(false); + setChecking(false); } }; - const busy = checking || updating; + const busy = checking; const neverChecked = !lastChecked; return ( @@ -145,25 +148,6 @@ function UpdateStatusChip() { ) : null} - {updateAvailable && ( - - )} - ); } -// --------------------------------------------------------------------------- -// Startup reconciliation -// --------------------------------------------------------------------------- - -/** - * On mount, reconcile servers that were left in a transitioning state - * ('running' or 'starting') from a previous app session. - * - * For each server, the stored PID is checked against live OS processes: - * - alive PID → re-register in the Rust crash-monitor map; status unchanged - * - dead PID, was "running" → "crashed" (was running, died while app was closed) - * - dead PID, was "starting" → "stopped" (never confirmed running; clean slate) - */ -function useStartupReconciliation() { - const queryClient = useQueryClient(); - - useEffect(() => { - (async () => { - try { - const transitioning = await getTransitioningServers(); - if (!transitioning.length) return; - - await Promise.all( - transitioning.map(async (s) => { - if (!s.pid) return; - try { - const alive = await tauriCmd.registerRunningServer(s.id, s.pid, s.install_path); - if (!alive) { - const deadStatus = s.status === "running" ? "crashed" : "stopped"; - await updateServerStatus(s.id, deadStatus, null); - } - } catch { - // Tauri not available (dev browser preview) — skip. - } - }) - ); - - queryClient.invalidateQueries({ queryKey: ["servers"] }); - } catch { - // Non-fatal. - } - })(); - }, []); // eslint-disable-line react-hooks/exhaustive-deps -} - export default function DashboardPage() { - useStartupReconciliation(); const { data: servers = [], isLoading } = useServers(); const { setShowNewServerWizard } = useAppStore(); diff --git a/src/app/servers/detail/page.tsx b/src/app/servers/detail/page.tsx index 1147703..4ca5642 100644 --- a/src/app/servers/detail/page.tsx +++ b/src/app/servers/detail/page.tsx @@ -125,9 +125,12 @@ 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 ── */} -
+
); } diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index 03a66d6..fe28e11 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -5,21 +5,26 @@ import { Folder, Terminal, Info, FolderOpen, CheckCircle2, AlertCircle, Loader2, Save, RefreshCw, ArrowUp, Bell, MessageSquare, Mail, Monitor, Send, Download, - Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, + Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, } 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 { Separator } from "@/components/ui/separator"; -import { Switch } from "@/components/ui/switch"; +import { + Dialog, DialogContent, DialogDescription, + DialogFooter, DialogHeader, DialogTitle, +} from "@/components/ui/dialog"; import { CommandOutputPanel } from "@/components/shared/CommandOutputPanel"; import { NotificationMatrix } from "@/components/shared/NotificationMatrix"; import { getAppSetting, setAppSetting, saveNotificationConfig, getNotificationConfigs, + getServers, type NotificationConfigRow, } from "@/lib/db"; +import { runPerServerUpdateCheck, applyUpdateToServer } from "@/lib/update-utils"; import { check } from "@tauri-apps/plugin-updater"; import { getVersion } from "@tauri-apps/api/app"; import { tauriCmd, type DirCheckResult, type ProtonUpdateInfo, type MigrateProgress } from "@/lib/tauri-commands"; @@ -228,7 +233,16 @@ function BaseDirMigrationSection() {

Create backup before moving

Backs up the lokiasam config/DB folder inside the current base dir.

- +
@@ -602,24 +616,22 @@ const AUTO_CHECK_OPTIONS = [ function ServerUpdatesSection() { const [checking, setChecking] = useState(false); - const [updateAvailable, setUpdate] = useState(false); const [cachedBuild, setCached] = useState(""); - const [latestBuild, setLatest] = useState(""); const [lastChecked, setLastChecked] = useState(""); const [autoCheckHours, setAutoCheck] = useState("0"); 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 load = useCallback(async () => { - const [avail, cached, latest, checked, hours, baseDir] = await Promise.all([ - getAppSetting("asa_update_available"), + const [cached, checked, hours, baseDir] = await Promise.all([ getAppSetting("asa_cached_build_id"), - getAppSetting("asa_latest_build_id"), getAppSetting("asa_last_checked"), getAppSetting("asa_auto_check_hours"), getAppSetting("base_dir"), ]); - setUpdate(avail === "true"); setCached(cached ?? ""); setLatest(latest ?? ""); - setLastChecked(checked ?? ""); setAutoCheck(hours ?? "0"); + setCached(cached ?? ""); setLastChecked(checked ?? ""); setAutoCheck(hours ?? "0"); if (baseDir) { const sep = baseDir.includes("\\") ? "\\" : "/"; const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; @@ -635,31 +647,65 @@ function ServerUpdatesSection() { const handleCheck = async () => { setChecking(true); try { - const baseDir = await getAppSetting("base_dir"); + 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`; - const result = await tauriCmd.checkAsaUpdate(cacheDir); + + // Read build ID before update so we can detect whether something changed. + const oldBuild = await getAppSetting("asa_cached_build_id") ?? ""; + + // 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(); - await setAppSetting("asa_update_available", String(result.updateAvailable)); - await setAppSetting("asa_cached_build_id", result.cachedBuildId); - await setAppSetting("asa_latest_build_id", result.latestBuildId); - await setAppSetting("asa_last_checked", now); + 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), + ]); + + // Run per-server check now that the cache build ID is current. + await runPerServerUpdateCheck(); + + const servers = await getServers(); + const outdated = servers.filter((s) => s.update_available === 1); + await setAppSetting("asa_update_available", String(outdated.length > 0)); load(); - if (result.updateAvailable) { - toast.info(`Update available — build ${result.latestBuildId} (cache is at ${result.cachedBuildId}).`); + + if (cacheUpdated) { + await dispatchNotification({ + eventType: NOTIFICATION_EVENTS.UPDATE_AVAILABLE, + serverId: null, + serverName: "ASA Cache", + title: "Cache Updated", + body: `Cache updated to build ${newBuild}${oldBuild ? ` (was ${oldBuild})` : ""}. Outdated servers have been flagged.`, + severity: "info", + }); } else { - toast.success("ASA server cache is up to date."); + // "Already up to date" is purely informational — toast only, no bell. + 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 }); + setShowApplyAll(true); } } catch (e) { - const msg = `Update check failed: ${e}`; - toast.error(msg); - dispatchNotification({ - eventType: NOTIFICATION_EVENTS.UPDATE_AVAILABLE, + await dispatchNotification({ + eventType: NOTIFICATION_EVENTS.UPDATE_FAILED, serverId: null, serverName: "ASA Cache", - title: "ASA Update Check Failed", - body: msg, + title: "Cache Update Failed", + body: `Failed to update cache: ${e}`, severity: "error", }); } finally { @@ -667,6 +713,57 @@ function ServerUpdatesSection() { } }; + const handleApplyAll = async () => { + setShowApplyAll(false); + 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", + undefined, + ); + } 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", + }); + } catch (e) { + await dispatchNotification({ + eventType: NOTIFICATION_EVENTS.UPDATE_FAILED, + serverId: null, + serverName: "ASA Cache", + title: "Apply All Failed", + body: `Failed to apply updates: ${e}`, + severity: "error", + }); + } finally { + setApplyingAll(false); + } + }; + const handleAutoCheckChange = async (value: string) => { setAutoCheck(value); await setAppSetting("asa_auto_check_hours", value); @@ -675,32 +772,17 @@ function ServerUpdatesSection() { return (

- Compares the locally cached build ID against the latest build on Steam. Does not run SteamCMD or alter any files — apply updates per-server from the server Overview tab or via an Auto-Update schedule. + Runs SteamCMD to update the shared server cache. If a new version is available it will be downloaded automatically. Servers are then compared against the updated cache and marked for update if behind.

Cache Build {cachedBuild || "—"}
- {updateAvailable && latestBuild && ( - <> -
→
-
- Steam Build - {latestBuild} -
- - )}
Last Checked {lastChecked ? new Date(lastChecked).toLocaleString() : "Never"}
- {updateAvailable && ( - - Update Available - - )}
+ + {/* ── Apply to all servers dialog ── */} + + + + Apply Update to All Servers? + + {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. + )} + + + + + + + +
); } @@ -964,7 +1074,7 @@ function ProtonGeUpdateSection() { {looksExternal && !isManaged && (
- +

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

@@ -1246,6 +1356,102 @@ function GlobalChannelCard({ channelId: _channelId, icon: Icon, label, desc, fie // Close-to-tray section // --------------------------------------------------------------------------- +// --------------------------------------------------------------------------- +// AppImage integration (Linux AppImage only) +// --------------------------------------------------------------------------- + +function AppImageIntegrationSection() { + const [status, setStatus] = useState<{ isAppimage: boolean; isInstalled: boolean } | null>(null); + const [working, setWorking] = useState(false); + + const refresh = useCallback(() => { + tauriCmd.checkAppimageIntegration().then(setStatus).catch(() => {}); + }, []); + + useEffect(() => { refresh(); }, [refresh]); + + if (!status?.isAppimage) return null; + + const handleInstall = async () => { + setWorking(true); + try { + await tauriCmd.installAppimageIntegration(); + refresh(); + toast.success("LokiASAM added to your application menu.", { + description: "If it doesn't appear right away, log out and back in.", + duration: 6000, + }); + } catch (e) { + toast.error("Installation failed", { description: String(e) }); + } finally { + setWorking(false); + } + }; + + const handleUninstall = async () => { + setWorking(true); + try { + await tauriCmd.uninstallAppimageIntegration(); + refresh(); + toast.success("Removed from application menu."); + } catch (e) { + toast.error("Removal failed", { description: String(e) }); + } finally { + setWorking(false); + } + }; + + 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 + + +
+

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

+
+ ) : ( + + )} +
+ ); +} + function CloseToTraySection() { const [closeToTray, setCloseToTrayState] = useState(true); @@ -1358,6 +1564,16 @@ export default function SettingsPage() {
+ + {IS_LINUX && ( +
+ +
+ )}
)} diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx new file mode 100644 index 0000000..8597f6b --- /dev/null +++ b/src/components/layout/AppShell.tsx @@ -0,0 +1,52 @@ +"use client"; + +import { Providers } from "@/components/layout/Providers"; +import { Sidebar } from "@/components/layout/Sidebar"; +import { TopBar } from "@/components/layout/TopBar"; +import { SetupGuard } from "@/components/layout/SetupGuard"; +import { DisableContextMenu } from "@/components/layout/DisableContextMenu"; +import { ModBrowserEventHandler } from "@/components/layout/ModBrowserEventHandler"; +import { SchedulerManager } from "@/components/layout/SchedulerManager"; +import { NotificationManager } from "@/components/layout/NotificationManager"; +import { UpdateManager } from "@/components/layout/UpdateManager"; +import { CloseWarningManager } from "@/components/layout/CloseWarningManager"; +import { RconManager } from "@/components/layout/RconManager"; +import { StartupReconciliationManager } from "@/components/layout/StartupReconciliationManager"; +import { ServerStatsRecorderProvider } from "@/providers/ServerStatsRecorderProvider"; +import { Toaster } from "sonner"; + +const toasterOptions = { + style: { + background: "rgba(10,10,30,0.95)", + border: "1px solid rgba(191,0,255,0.25)", + color: "var(--text-primary)", + }, +}; + +export function AppShell({ children }: { children: React.ReactNode }) { + return ( + + + + + + + + + + + + +
+ +
+ +
+ {children} +
+
+
+
+
+ ); +} diff --git a/src/components/layout/NotificationBell.tsx b/src/components/layout/NotificationBell.tsx index fdd2203..352b113 100644 --- a/src/components/layout/NotificationBell.tsx +++ b/src/components/layout/NotificationBell.tsx @@ -10,7 +10,7 @@ import { PopoverTrigger, } from "@/components/ui/popover"; import { useUnreadNotificationCount, useNotificationList } from "@/hooks/useNotifications"; -import { markAllNotificationsRead } from "@/lib/db"; +import { markAllNotificationsRead, parseDbDate } from "@/lib/db"; import { useAppStore } from "@/store/useAppStore"; import { useQueryClient } from "@tanstack/react-query"; import type { InAppNotificationRow } from "@/lib/db"; @@ -69,7 +69,7 @@ function NotificationItemMini({ {n.title}

- {formatRelative(new Date(n.created_at))} + {formatRelative(parseDbDate(n.created_at))}

diff --git a/src/components/layout/NotificationManager.tsx b/src/components/layout/NotificationManager.tsx index 736ac21..03964df 100644 --- a/src/components/layout/NotificationManager.tsx +++ b/src/components/layout/NotificationManager.tsx @@ -63,15 +63,14 @@ export function NotificationManager() { severity: "error", }); } else if (status.status === "start-failed") { - const detail = status.error - ? `Server process exited immediately after launch.\n\nProcess output:\n${status.error}` - : "Server process exited immediately after launch. Verify that Proton-GE is configured correctly, the server files are intact, and all required ports are available."; + const body = status.error + ?? "Server failed to start. Verify that Proton-GE is configured correctly, the server files are intact, and all required ports are available."; await dispatchNotification({ eventType: NOTIFICATION_EVENTS.SERVER_START_FAILED, serverId: status.serverId, serverName, title: `${serverName} failed to start`, - body: detail, + body, severity: "error", }); } diff --git a/src/components/layout/RconManager.tsx b/src/components/layout/RconManager.tsx new file mode 100644 index 0000000..c25aee5 --- /dev/null +++ b/src/components/layout/RconManager.tsx @@ -0,0 +1,88 @@ +"use client"; + +/** + * RconManager — global side-effect component that maintains RCON connections. + * + * Strategy: + * 1. On mount: attempt to connect all currently-running servers. + * 2. server://any-change → immediately connect when a server becomes "running". + * 3. rcon://status-any → immediately reconnect when the Rust manager task + * reports a disconnection for a server that is still running. + * 4. 60 s safety-net interval: catches any edge case where events were missed. + * + * The Rust manager task owns all polling (listplayers every 30 s, GetChat + * every 5 s). This component only handles connection lifecycle. + */ + +import { useEffect } from "react"; +import { getServers } from "@/lib/db"; +import { tauriCmd, type ServerStatus, type RconStatusPayload } from "@/lib/tauri-commands"; +import { useTauriEvent } from "@/hooks/useTauriEvent"; + +const SAFETY_NET_MS = 60_000; + +async function connectServer(serverId: string, host: string, rconPort: number, rconPassword: string) { + try { + await tauriCmd.rconConnect(serverId, host, rconPort, rconPassword); + } catch { + // Server RCON not ready yet — the safety-net interval or next status event + // will retry automatically. + } +} + +export function RconManager() { + // ── Initial connect for all running servers on mount ────────────────────── + useEffect(() => { + getServers().then((servers) => { + for (const s of servers) { + if (s.status === "running") { + connectServer(s.id, "127.0.0.1", s.rcon_port, s.rcon_password); + } + } + }).catch(() => null); + }, []); + + // ── React immediately when a server becomes "running" ───────────────────── + useTauriEvent("server://any-change", (payload) => { + if (payload.status === "running") { + // Fetch the server row to get rcon_port and rcon_password. + getServers().then((servers) => { + const s = servers.find((srv) => srv.id === payload.serverId); + if (s) connectServer(s.id, "127.0.0.1", s.rcon_port, s.rcon_password); + }).catch(() => null); + } + + // Clean up the pool entry when the server stops. + if (["stopped", "crashed", "start-failed"].includes(payload.status)) { + tauriCmd.rconDisconnect(payload.serverId).catch(() => null); + } + }); + + // ── Reconnect when the Rust manager reports a disconnection ─────────────── + useTauriEvent("rcon://status-any", (payload) => { + if (payload.status !== "disconnected") return; + getServers().then((servers) => { + const s = servers.find((srv) => srv.id === payload.serverId); + if (s && s.status === "running") { + connectServer(s.id, "127.0.0.1", s.rcon_port, s.rcon_password); + } + }).catch(() => null); + }); + + // ── 60 s safety-net: reconnect any running server that lost its connection ─ + useEffect(() => { + const id = setInterval(async () => { + const servers = await getServers().catch(() => []); + for (const s of servers) { + if (s.status !== "running") continue; + const connected = await tauriCmd.rconIsConnected(s.id).catch(() => false); + if (!connected) { + connectServer(s.id, "127.0.0.1", s.rcon_port, s.rcon_password); + } + } + }, SAFETY_NET_MS); + return () => clearInterval(id); + }, []); + + return null; +} diff --git a/src/components/layout/SchedulerManager.tsx b/src/components/layout/SchedulerManager.tsx index 0e3ee48..08808fe 100644 --- a/src/components/layout/SchedulerManager.tsx +++ b/src/components/layout/SchedulerManager.tsx @@ -10,7 +10,7 @@ import { useEffect } from "react"; import { toast } from "sonner"; import { useTauriEvent } from "@/hooks/useTauriEvent"; -import { insertBackup, updateScheduleRun, getScheduleById } from "@/lib/db"; +import { insertBackup, updateScheduleRun, getScheduleById, setAppSetting } from "@/lib/db"; import { getNextCronDate } from "@/components/shared/CronBuilder"; import { syncSchedulesToRust } from "@/lib/scheduler-sync"; import type { SchedulerFiredPayload } from "@/lib/tauri-commands"; @@ -24,6 +24,20 @@ export function SchedulerManager() { useTauriEvent("scheduler://fired", async (payload) => { const { scheduleId, serverName, scheduleType, success, error, backupRecord } = payload; + // ── Global cache update check — synthetic entry, not in the schedules table ── + if (scheduleType === "global_update_check") { + // Update asa_last_checked so syncSchedulesToRust computes the correct + // next_run_ms when it re-syncs below. + await setAppSetting("asa_last_checked", new Date().toISOString()); + // The asa://update-check event (emitted by the Rust handler) drives the + // per-server badge update and "update available" settings — no toast here. + if (!success) { + toast.error(`Auto update check failed: ${error ?? "unknown error"}`); + } + syncSchedulesToRust(); + return; + } + // Persist backup record to SQLite when a backup schedule fired. if (scheduleType === "backup" && backupRecord && success) { try { @@ -42,8 +56,6 @@ export function SchedulerManager() { } // Update last_run / next_run in SQLite so the UI shows correct times. - // Fetch the schedule to get the cron expression and compute the real next_run - // up-front — avoids a null flash in the UI between update and re-sync. const lastRun = new Date().toISOString(); try { const row = await getScheduleById(scheduleId); @@ -57,9 +69,9 @@ export function SchedulerManager() { // Show a toast notification. if (success) { const labels: Record = { - backup: "Scheduled backup completed", - restart: "Scheduled restart completed", - update: "Scheduled update completed", + backup: "Scheduled backup completed", + restart: "Scheduled restart completed", + update: "Scheduled update completed", broadcast: "Scheduled broadcast sent", }; toast.success(`[${serverName}] ${labels[scheduleType] ?? "Schedule fired"}.`); diff --git a/src/components/layout/SetupGuard.tsx b/src/components/layout/SetupGuard.tsx index 71f426e..6b7169d 100644 --- a/src/components/layout/SetupGuard.tsx +++ b/src/components/layout/SetupGuard.tsx @@ -60,6 +60,8 @@ export function SetupGuard({ children }: SetupGuardProps) { const dbPath = bootstrap.baseDir.replace(/[/\\]$/, "") + sep + "lokiasam" + sep + "lokiasam.db"; await initDb(dbPath); + // Open a separate Rust-side connection for the background stats recorder. + tauriCmd.initStatsRecorder(dbPath).catch(() => null); const [value, accent, closeToTraySetting] = await Promise.all([ getAppSetting("setup_complete"), diff --git a/src/components/layout/StartupReconciliationManager.tsx b/src/components/layout/StartupReconciliationManager.tsx new file mode 100644 index 0000000..9f49e7e --- /dev/null +++ b/src/components/layout/StartupReconciliationManager.tsx @@ -0,0 +1,57 @@ +"use client"; + +import { useEffect } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { useAppStore } from "@/store/useAppStore"; +import { getServers, updateServerStatus } from "@/lib/db"; +import { tauriCmd } from "@/lib/tauri-commands"; + +export function StartupReconciliationManager() { + const queryClient = useQueryClient(); + const { setIsServerScanPending } = useAppStore(); + + useEffect(() => { + setIsServerScanPending(true); + (async () => { + try { + const servers = await getServers(); + + if (!servers.length) return; + + const entries = servers.map((s) => ({ serverId: s.id, installPath: s.install_path })); + + let results: Array<{ serverId: string; pid: number | null }>; + try { + results = await tauriCmd.scanRunningServers(entries); + } catch { + return; + } + + await Promise.all( + results.map(async (r) => { + const current = servers.find((s) => s.id === r.serverId); + if (!current) return; + + if (r.pid != null) { + if (current.status !== "running" || current.pid !== r.pid) { + await updateServerStatus(r.serverId, "running", r.pid); + } + } else { + if (current.status !== "stopped") { + await updateServerStatus(r.serverId, "stopped", null); + } + } + }) + ); + + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } catch { + // Non-fatal. + } finally { + setIsServerScanPending(false); + } + })(); + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + return null; +} diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index e09fb4a..c5d92b1 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -2,6 +2,7 @@ import { useState, useEffect } from "react"; import Link from "next/link"; +import { useRouter } from "next/navigation"; import { Play, Square, @@ -19,6 +20,7 @@ import { XCircle, Terminal, Loader2, + X, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; @@ -44,7 +46,8 @@ import { getNextScheduledRestart, getAppSetting, } from "@/lib/db"; -import { ARK_MAPS, NOTIFICATION_EVENTS } from "@/data/game-data"; +import { applyUpdateToServer } from "@/lib/update-utils"; +import { ARK_MAPS, LAUNCH_PARAMETERS, NOTIFICATION_EVENTS } from "@/data/game-data"; import { dispatchNotification } from "@/lib/notifications"; import { useQueryClient } from "@tanstack/react-query"; import { useAppStore } from "@/store/useAppStore"; @@ -94,16 +97,25 @@ function formatFutureTime(iso: string | null): string { // ── Main component ─────────────────────────────────────────────────────────── export function ServerCard({ server }: Props) { + const router = useRouter(); const queryClient = useQueryClient(); const stats = useServerStats(server); const startTime = useAppStore((s) => s.serverStartTimes[server.id]); + const noRetry = useAppStore((s) => !!s.noRetryServerIds[server.id]); + const setNoRetryServer = useAppStore((s) => s.setNoRetryServer); + const clearNoRetryServer = useAppStore((s) => s.clearNoRetryServer); + const isServerScanPending = useAppStore((s) => s.isServerScanPending); const [modCount, setModCount] = useState(null); const [lastBackup, setLastBackup] = useState(null); const [nextRestart, setNextRestart] = useState(null); const [actionPending, setActionPending] = useState(false); - const [hasUpdateAvailable, setHasUpdateAvailable] = useState(false); const [showProgress, setShowProgress] = useState(false); + const [showUpdateConfirm, setShowUpdateConfirm] = useState(false); + const [autoCheckEnabled, setAutoCheckEnabled] = useState(true); + + // Derive update badge directly from the DB column (set by runPerServerUpdateCheck). + const hasUpdateAvailable = server.update_available === 1; // Force a re-render every 30 s so the uptime counter advances visually. const [, setTick] = useState(0); @@ -126,29 +138,25 @@ export function ServerCard({ server }: Props) { const isStartFailed = server.status === "start-failed"; const isReinstallable = isInstallFailed || isStartFailed; - // Load secondary card data (mod count, backup, schedule, update badge). + // Load secondary card data (mod count, backup, schedule, auto-check state). useEffect(() => { let cancelled = false; (async () => { - const [mc, lb, nr, cachedBuild, serverBuild] = await Promise.all([ + const [mc, lb, nr, autoHours] = await Promise.all([ getServerModCount(server.id), getLastBackupTime(server.id), getNextScheduledRestart(server.id), - getAppSetting("asa_cached_build_id"), - tauriCmd.getInstalledBuildId(server.install_path).catch(() => null), + getAppSetting("asa_auto_check_hours"), ]); if (!cancelled) { setModCount(mc); setLastBackup(lb); setNextRestart(nr); - // Show badge when the cache has a newer build than what's installed. - if (cachedBuild && serverBuild && cachedBuild !== "0" && serverBuild !== "0") { - setHasUpdateAvailable(parseInt(cachedBuild) > parseInt(serverBuild)); - } + setAutoCheckEnabled((autoHours ?? "0") !== "0"); } })(); return () => { cancelled = true; }; - }, [server.id, server.install_path]); + }, [server.id]); // ── Actions ────────────────────────────────────────────────────────────── @@ -164,9 +172,13 @@ export function ServerCard({ server }: Props) { ? JSON.parse(config.launch_args_json) : {}; - const extraArgs = Object.entries(launchArgs) - .filter(([, v]) => v === "true" || v === "1") - .map(([k]) => `-${k}`); + 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); @@ -178,9 +190,6 @@ export function ServerCard({ server }: Props) { port: server.port, queryPort: server.query_port, rconPort: server.rcon_port, - maxPlayers: server.max_players, - serverPassword: server.server_password ?? undefined, - adminPassword: server.admin_password, extraArgs, modIds: enabledModIds, }; @@ -195,6 +204,7 @@ export function ServerCard({ server }: Props) { const handleStart = async () => { setActionPending(true); + clearNoRetryServer(server.id); try { await updateServerStatus(server.id, "starting", null); queryClient.invalidateQueries({ queryKey: ["servers"] }); @@ -207,16 +217,23 @@ export function ServerCard({ server }: Props) { await updateServerStatus(server.id, "starting", pid); queryClient.invalidateQueries({ queryKey: ["servers"] }); } catch (err) { - const errMsg = typeof err === "string" ? err : String(err); + const raw = typeof err === "string" ? err : String(err); + const isExeMissing = raw.startsWith("exe_missing:"); + const userMsg = isExeMissing + ? raw.slice("exe_missing: ".length) + : raw; + + if (isExeMissing) setNoRetryServer(server.id); + await updateServerStatus(server.id, "start-failed", null); queryClient.invalidateQueries({ queryKey: ["servers"] }); - toast.error(`${server.name} failed to start — ${errMsg}`); + toast.error(`${server.name} failed to start`, { description: userMsg }); dispatchNotification({ eventType: NOTIFICATION_EVENTS.SERVER_START_FAILED, serverId: server.id, serverName: server.name, title: `${server.name} failed to start`, - body: errMsg, + body: userMsg, severity: "error", }); } finally { @@ -229,8 +246,14 @@ export function ServerCard({ server }: Props) { try { await updateServerStatus(server.id, "stopping", server.pid); queryClient.invalidateQueries({ queryKey: ["servers"] }); - await tauriCmd.stopServer(server.id, true); - // Actual "stopped" status comes via the server://any-change event from Rust. + 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}.", + ); } catch (err) { toast.error(`Failed to stop ${server.name}`, { description: String(err) }); } finally { @@ -238,6 +261,17 @@ export function ServerCard({ server }: Props) { } }; + const handleForceStop = async () => { + setActionPending(true); + try { + await tauriCmd.stopServer(server.id, false); + } catch (err) { + toast.error(`Force stop failed: ${err}`); + } finally { + setActionPending(false); + } + }; + const handleRestart = async () => { setActionPending(true); try { @@ -258,6 +292,36 @@ export function ServerCard({ server }: Props) { } }; + const handleApplyUpdate = async () => { + setShowUpdateConfirm(false); + setActionPending(true); + try { + const wasRunning = isRunning; + try { + await applyUpdateToServer( + server.id, + server.name, + server.install_path, + wasRunning, + (msg) => toast.info(msg), + ); + } catch (err) { + if (err && typeof err === "object" && "restartNeeded" in err) { + await handleStart(); + return; + } + throw err; + } + queryClient.invalidateQueries({ queryKey: ["servers"] }); + toast.success(`${server.name} updated successfully.`); + } catch (e) { + toast.error(`Update failed: ${e}`); + } finally { + setActionPending(false); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + }; + const handleReinstall = async () => { try { const [baseDir, steamcmdPath] = await Promise.all([ @@ -310,7 +374,7 @@ export function ServerCard({ server }: Props) { return (
{ + if (!(e.target as HTMLElement).closest('button, a, [role="menuitem"], [data-radix-collection-item]')) { + router.push(`/servers/detail?id=${server.id}`); + } + }} > {/* ── Header row ── */}
@@ -330,7 +399,7 @@ export function ServerCard({ server }: Props) { > {server.name} - + {hasUpdateAvailable && ( {isInstallFailed ? "Install Failed" : "Start Failed"}
- {/* For start-failed only: Retry Start avoids a full re-download */} - {isStartFailed && ( + {/* For start-failed only: Retry Start avoids a full re-download. + Hidden when the failure was a missing executable — retry would + immediately fail again, only reinstall can fix it. */} + {isStartFailed && !noRetry && ( ) : ( <> - {/* Start / Stop toggle */} - {isRunning || isTransitioning ? ( + {/* Start / Stop / Force Stop */} + {server.status === "stopping" ? ( + ) : server.status === "starting" ? ( + + ) : isRunning ? ( + ) : ( )} - {/* Restart */} - + {/* Restart — only shown when fully running */} + {isRunning && ( + + )} + + {/* Update — shown only when update is available */} + {hasUpdateAvailable && ( + + )} )} - {/* Open Detail — hidden while installing/updating/failed */} - {!isActiveInstall && !isReinstallable && ( + {/* Right side: optional note + always-visible detail arrow */} +
+ {hasUpdateAvailable && !autoCheckEnabled && ( + + Enable auto checks in Settings + + )} - )} +
+ {/* ── Update confirmation dialog ── */} + + + + Apply Server Update? + + {isRunning + ? `${server.name} is currently running. It will be stopped, updated, and restarted automatically.` + : `${server.name} will be updated from the shared cache.`} + + + + + + + + + {/* ── View Progress modal ── */} = { running: { label: "Running", color: "var(--neon-green)", pulse: true }, starting: { label: "Starting", color: "var(--neon-cyan)", pulse: true }, - stopping: { label: "Stopping", color: "var(--neon-purple)", pulse: true }, + stopping: { label: "Shutting Down", color: "#ff6400", pulse: true }, updating: { label: "Updating", color: "var(--neon-cyan)", pulse: true }, stopped: { label: "Stopped", color: "var(--text-muted)", pulse: false }, error: { label: "Error", color: "var(--neon-red)", pulse: false }, @@ -29,6 +30,7 @@ const STATUS_MAP: Record = { installing: { label: "Installing", color: "var(--neon-purple)", pulse: true }, install_failed: { label: "Install Failed", color: "var(--neon-red)", pulse: false }, "start-failed": { label: "Start Failed", color: "var(--neon-red)", pulse: false }, + detecting: { label: "Detecting...", color: "var(--text-muted)", pulse: true }, }; interface Props { diff --git a/src/components/server/rcon/RconConsole.tsx b/src/components/server/rcon/RconConsole.tsx new file mode 100644 index 0000000..4ddbfa8 --- /dev/null +++ b/src/components/server/rcon/RconConsole.tsx @@ -0,0 +1,590 @@ +"use client"; + +import { useState, useRef, useEffect, useCallback } from "react"; +import { + Terminal, Send, RefreshCw, Trash2, Copy, AlertCircle, + Users, ShieldX, Shield, ChevronDown, ChevronUp, Clock, +} from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { tauriCmd, type RconLogLine, type ArkPlayer, type RconStatusPayload } from "@/lib/tauri-commands"; +import { useTauriEvent } from "@/hooks/useTauriEvent"; +import type { ServerRow } from "@/lib/db"; + +interface Props { + server: ServerRow; +} + +// ── Time of day presets ─────────────────────────────────────────────────────── +const TIME_PRESETS = [ + { label: "Morning", time: "06:00:00" }, + { label: "Noon", time: "12:00:00" }, + { label: "Evening", time: "18:00:00" }, + { label: "Midnight", time: "00:00:00" }, +] as const; + +// ServerChat is the only working global message command on ASA. +const SEND_CMD = "ServerChat"; + +// ── Line color ──────────────────────────────────────────────────────────────── +function lineColor(kind: RconLogLine["kind"]): string { + switch (kind) { + case "command": return "var(--neon-cyan)"; + case "response": return "var(--text-primary)"; + case "chat": return "#ffd700"; + case "error": return "var(--neon-red)"; + case "system": return "var(--text-muted)"; + } +} + +function fmtTs(ms: number): string { + const d = new Date(ms); + return [d.getHours(), d.getMinutes(), d.getSeconds()] + .map((n) => String(n).padStart(2, "0")) + .join(":"); +} + +// ── Player context-menu actions ─────────────────────────────────────────────── +interface PlayerAction { + label: string; + cmd: (p: ArkPlayer) => string; + danger?: boolean; +} + +const PLAYER_ACTIONS: PlayerAction[] = [ + { label: "Kick", cmd: (p) => `kickplayer ${p.playerId}`, danger: true }, + { label: "Ban", cmd: (p) => `banplayer ${p.playerId}`, danger: true }, + { label: "Whitelist", cmd: (p) => `allowplayertojoinnocheck ${p.playerId}` }, + { label: "Make Tribe Admin", cmd: (p) => `maketribeadmin ${p.playerId}` }, + { label: "Make Tribe Founder", cmd: (p) => `maketribefounders ${p.playerId}` }, + { label: "Remove Tribe Admin", cmd: (p) => `removetribeadmin ${p.playerId}`, danger: true }, +]; + +// ── Component ───────────────────────────────────────────────────────────────── +export function RconConsole({ server }: Props) { + const [connected, setConnected] = useState(false); + const [connecting, setConnecting] = useState(false); + const [error, setError] = useState(null); + const [lines, setLines] = useState([]); + const [cmdInput, setCmdInput] = useState(""); + const [msgInput, setMsgInput] = useState(""); + const [sending, setSending] = useState(false); + const [cmdHistory, setCmdHistory] = useState([]); + const [historyIdx, setHistoryIdx] = useState(-1); + const [players, setPlayers] = useState([]); + const [banList, setBanList] = useState([]); + const [whitelist, setWhitelist] = useState([]); + const [banOpen, setBanOpen] = useState(true); + const [wlOpen, setWlOpen] = useState(false); + const [showTimeMenu, setShowTimeMenu] = useState(false); + const [selectedPlayer, setSelectedPlayer] = useState(null); + const [playerMenuPos, setPlayerMenuPos] = useState({ x: 0, y: 0 }); + + const logRef = useRef(null); + const cmdInputRef = useRef(null); + const timeMenuRef = useRef(null); + const playerMenuRef = useRef(null); + + // ── Auto-scroll log ──────────────────────────────────────────────────────── + useEffect(() => { + const el = logRef.current; + if (el) el.scrollTop = el.scrollHeight; + }, [lines]); + + // ── Close floating menus on outside click ───────────────────────────────── + useEffect(() => { + const handler = (e: MouseEvent) => { + if (timeMenuRef.current && !timeMenuRef.current.contains(e.target as Node)) { + setShowTimeMenu(false); + } + if (playerMenuRef.current && !playerMenuRef.current.contains(e.target as Node)) { + setSelectedPlayer(null); + } + }; + document.addEventListener("mousedown", handler); + return () => document.removeEventListener("mousedown", handler); + }, []); + + // ── Subscribe to backend log events ─────────────────────────────────────── + useTauriEvent(`rcon://log/${server.id}`, (line) => { + setLines((prev) => [...prev.slice(-499), line]); + }); + + // ── Subscribe to player list updates ────────────────────────────────────── + useTauriEvent(`rcon://players/${server.id}`, (list) => { + setPlayers(list); + }); + + // ── Drive connected/disconnected state from Rust manager events ──────────── + // This is the authoritative source of truth — no more inferring connection + // state from command errors. + useTauriEvent(`rcon://status/${server.id}`, (payload) => { + if (payload.status === "connected") { + setConnected(true); + setError(null); + } else if (payload.status === "connecting") { + setConnecting(true); + } else if (payload.status === "disconnected") { + setConnected(false); + setConnecting(false); + if (payload.error) setError(payload.error); + } + }); + + // ── Load initial log buffer on mount ────────────────────────────────────── + useEffect(() => { + tauriCmd.rconGetLog(server.id).then((buf) => { + if (buf.length > 0) setLines(buf); + }).catch(() => null); + }, [server.id]); + + // ── Enable chat poll on mount, disable on unmount ───────────────────────── + useEffect(() => { + tauriCmd.rconEnableChatPoll(server.id).catch(() => null); + return () => { tauriCmd.rconDisableChatPoll(server.id).catch(() => null); }; + }, [server.id]); + + // ── Load players, ban list, whitelist ──────────────────────────────────── + const refreshPlayers = useCallback(async () => { + if (!connected) return; + try { + const list = await tauriCmd.rconGetPlayers(server.id); + setPlayers(list); + } catch { /* connection may have dropped */ } + }, [connected, server.id]); + + const refreshLists = useCallback(async () => { + try { + const [bans, wl] = await Promise.all([ + tauriCmd.rconReadBanList(server.install_path), + tauriCmd.rconReadWhitelist(server.install_path), + ]); + setBanList(bans); + setWhitelist(wl); + } catch { /* ignore */ } + }, [server.install_path]); + + // ── Manual reconnect (user presses "Reconnect" button) ─────────────────── + // RconManager handles auto-connect; this is only needed for the manual button. + const connect = useCallback(async () => { + setConnecting(true); + setError(null); + try { + await tauriCmd.rconConnect(server.id, "127.0.0.1", server.rcon_port, server.rcon_password); + // State update comes via rcon://status/{id} event — no need to set here. + } catch (e) { + setError(String(e)); + setConnecting(false); + } + }, [server.id, server.rcon_port, server.rcon_password]); + + // Sync initial connected state from Rust on mount (covers the case where + // RconManager already connected before this tab was opened). + useEffect(() => { + if (server.status !== "running") { + setLines([{ + timestampMs: Date.now(), + text: "Server is not running — start the server to use RCON.", + kind: "system", + }]); + return; + } + tauriCmd.rconIsConnected(server.id).then((live) => { + setConnected(live); + if (!live) setError(null); + }).catch(() => null); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // Seed player list from cache (no RCON command) and load file-based lists once connected. + // Subsequent updates come from rcon://players/{id} events via RconManager's 30 s tick. + useEffect(() => { + if (!connected) return; + tauriCmd.rconGetCachedPlayers(server.id).then((p) => { if (p !== null) setPlayers(p); }).catch(() => null); + refreshLists(); + }, [connected]); // eslint-disable-line react-hooks/exhaustive-deps + + // ── Send a raw RCON command ─────────────────────────────────────────────── + const sendCommand = useCallback(async (cmd: string) => { + if (!cmd.trim() || !connected || sending) return; + const trimmed = cmd.trim(); + setCmdHistory((h) => [trimmed, ...h.slice(0, 49)]); + setHistoryIdx(-1); + setCmdInput(""); + setSending(true); + try { + await tauriCmd.rconSend(server.id, trimmed); + } catch { + // Connection state update comes via rcon://status/{id} event from Rust. + } finally { + setSending(false); + cmdInputRef.current?.focus(); + } + }, [connected, sending, server.id]); + + const handleCmdKeyDown = (e: React.KeyboardEvent) => { + if (e.key === "Enter") { + sendCommand(cmdInput); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + const next = Math.min(historyIdx + 1, cmdHistory.length - 1); + setHistoryIdx(next); + setCmdInput(cmdHistory[next] ?? ""); + } else if (e.key === "ArrowDown") { + e.preventDefault(); + const next = Math.max(historyIdx - 1, -1); + setHistoryIdx(next); + setCmdInput(next === -1 ? "" : cmdHistory[next] ?? ""); + } + }; + + // ── Send global chat / broadcast ────────────────────────────────────────── + const sendMessage = useCallback(async () => { + if (!msgInput.trim() || !connected || sending) return; + await sendCommand(`${SEND_CMD} ${msgInput.trim()}`); + setMsgInput(""); + }, [msgInput, connected, sending, sendCommand]); + + // ── Player context menu ─────────────────────────────────────────────────── + const openPlayerMenu = (e: React.MouseEvent, player: ArkPlayer) => { + e.preventDefault(); + setPlayerMenuPos({ x: e.clientX, y: e.clientY }); + setSelectedPlayer(player); + }; + + const handlePlayerAction = async (action: PlayerAction) => { + if (!selectedPlayer) return; + const cmd = action.cmd(selectedPlayer); + setSelectedPlayer(null); + await sendCommand(cmd); + if (action.label === "Ban" || action.label === "Whitelist") { + setTimeout(refreshLists, 500); + } + }; + + const copyLog = () => { + const text = lines.map((l) => `[${fmtTs(l.timestampMs)}] ${l.text}`).join("\n"); + navigator.clipboard.writeText(text).catch(() => null); + }; + + // ── Status labels ───────────────────────────────────────────────────────── + const statusColor = connected + ? "var(--neon-green)" + : error ? "var(--neon-red)" + : connecting ? "var(--neon-cyan)" + : "var(--text-muted)"; + + const statusLabel = connected + ? `Connected — 127.0.0.1:${server.rcon_port}` + : connecting ? "Connecting…" + : error ? "Disconnected" + : server.status !== "running" ? "Server not running" + : "Disconnected"; + + // ── Accordion helpers ───────────────────────────────────────────────────── + const toggleBan = () => { setBanOpen((v) => !v); if (!banOpen) setWlOpen(false); }; + const toggleWl = () => { setWlOpen((v) => !v); if (!wlOpen) setBanOpen(false); }; + + const unban = async (id: string) => { + await sendCommand(`unbanplayer ${id}`); + setTimeout(refreshLists, 500); + }; + + const unwhitelist = async (id: string) => { + await sendCommand(`disallowplayertojoinnocheck ${id}`); + setTimeout(refreshLists, 500); + }; + + // ── Layout ──────────────────────────────────────────────────────────────── + return ( +
+ + {/* ── Status bar ── */} +
+
+
+ {statusLabel} +
+
+ {!connected && !connecting && server.status === "running" && ( + + )} + + +
+
+ + {/* ── Error banner ── */} + {error && !connected && ( +
+ + {error} +
+ )} + + {/* ── Main two-column body ── */} +
+ + {/* LEFT — player management */} +
+ + {/* Online players */} +
+
+ + + Online ({players.length}) + + +
+
+ {players.length === 0 ? ( +

No players online

+ ) : ( + players.map((p) => ( + + )) + )} +
+
+ + {/* Banned Players accordion */} +
+ + {banOpen && ( +
+ {banList.length === 0 ? ( +

No banned players

+ ) : banList.map((id) => ( +
+ {id} + +
+ ))} +
+ )} +
+ + {/* Whitelist accordion */} +
+ + {wlOpen && ( +
+ {whitelist.length === 0 ? ( +

Whitelist is empty

+ ) : whitelist.map((id) => ( +
+ {id} + +
+ ))} +
+ )} +
+
+ + {/* RIGHT — console + controls */} +
+ + {/* Terminal — fills remaining height, scrolls internally */} +
+ {lines.map((l, i) => ( +
+ {fmtTs(l.timestampMs)} + {l.text} +
+ ))} + {sending && ( +
+ + Waiting… +
+ )} +
+ + {/* Quick actions row */} + {connected && ( +
+ + + + {/* SetTimeOfDay dropdown */} +
+ + {showTimeMenu && ( +
+ {TIME_PRESETS.map((p) => ( + + ))} +
+ )} +
+
+ )} + + {/* Global chat input */} + {connected && ( +
+ + Global Chat + + setMsgInput(e.target.value)} + onKeyDown={(e) => e.key === "Enter" && sendMessage()} + disabled={!connected || sending} + style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(191,0,255,0.25)", color: "var(--text-primary)" }} + /> + +
+ )} + + {/* Raw command input */} +
+ > + { setCmdInput(e.target.value); setHistoryIdx(-1); }} + onKeyDown={handleCmdKeyDown} + disabled={!connected || sending} + style={{ background: "#000010", borderColor: connected ? "rgba(0,255,255,0.3)" : "rgba(255,255,255,0.1)", color: "var(--text-primary)" }} + /> + +
+
+
+ + {/* ── Player context menu (floating) ── */} + {selectedPlayer && ( +
+
+

{selectedPlayer.name}

+

{selectedPlayer.playerId}

+
+ {PLAYER_ACTIONS.map((action) => ( + + ))} +
+ )} +
+ ); +} diff --git a/src/components/server/tabs/AutomationTab.tsx b/src/components/server/tabs/AutomationTab.tsx index 1941a73..c284ddd 100644 --- a/src/components/server/tabs/AutomationTab.tsx +++ b/src/components/server/tabs/AutomationTab.tsx @@ -13,19 +13,22 @@ import { CalendarClock, HardDrive, RefreshCw, RotateCcw, Megaphone, Info, CheckCircle2, Loader2, Plus, Trash2, ToggleLeft, ToggleRight, AlertTriangle, Bell, Mail, MessageSquare, Monitor, ChevronDown, ChevronUp, Send, + ArrowUp, Clock, Zap, } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; -import { Switch } from "@/components/ui/switch"; import { Label } from "@/components/ui/label"; import { CronBuilder, getNextCronDate, CRON_PRESETS } from "@/components/shared/CronBuilder"; import { getServerSchedules, createSchedule, deleteScheduleRecord, updateScheduleEnabled, updateScheduleConfig, + setServerUpdateAutomation, getServerNotificationConfigs, saveNotificationConfig, type ScheduleRow, type CreateScheduleInput, type NotificationConfigRow, + type UpdateAutomation, } from "@/lib/db"; +import { getAppSetting } from "@/lib/db"; import { tauriCmd } from "@/lib/tauri-commands"; import { syncSchedulesToRust } from "@/lib/scheduler-sync"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; @@ -35,7 +38,7 @@ import type { ServerRow } from "@/lib/db"; // Types // --------------------------------------------------------------------------- -type ScheduleType = "backup" | "update" | "restart" | "broadcast"; +type ScheduleType = "backup" | "restart" | "broadcast"; interface BackupConfig { // no extra options @@ -47,15 +50,6 @@ interface RestartConfig { message: string; } -interface UpdateConfig { - mode: "check_only" | "check_and_apply"; - restartAfterUpdate: boolean; - broadcastWarning: boolean; - warningMinutes: number; - message: string; - skipIfPlayersOnline: boolean; -} - interface BroadcastConfig { message: string; } @@ -66,21 +60,12 @@ interface BroadcastConfig { const DEFAULT_CRON: Record = { backup: CRON_PRESETS[3].cron, // Every 6h - update: "0 3 * * *", // Daily at 3 AM restart: "0 6 * * *", // Daily at 6 AM broadcast: CRON_PRESETS[0].cron, // Every hour }; const DEFAULT_CONFIG: Record = { backup: {} as BackupConfig, - update: { - mode: "check_and_apply", - restartAfterUpdate: true, - broadcastWarning: true, - warningMinutes: 15, - message: "Server updating in {minutes} minutes. Progress will be saved.", - skipIfPlayersOnline: false, - } as UpdateConfig, restart: { broadcastWarning: true, warningMinutes: 15, message: "Server restarting in {minutes} minutes. Progress will be saved." } as RestartConfig, broadcast: { message: "Welcome to the server! Type /help for commands." } as BroadcastConfig, }; @@ -139,7 +124,7 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing const nextDate = getNextCronDate(cron); const nextRun = existing?.next_run ?? (nextDate ? nextDate.toISOString() : null); - function patchConfig(patch: Partial) { + function patchConfig(patch: Partial) { setConfig((c) => ({ ...c, ...patch })); } @@ -221,7 +206,7 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing } } - const c = config as RestartConfig & UpdateConfig & BroadcastConfig; + const c = config as RestartConfig & BroadcastConfig; return (
- {/* Update-specific options */} - {type === "update" && ( -
- {/* Mode toggle */} -
- -
- {(["check_only", "check_and_apply"] as const).map((m) => ( - - ))} -
-

- {(c.mode ?? "check_and_apply") === "check_only" - ? "Only check if an update is available. An Update Available badge will appear — apply manually." - : "Check for an update and apply it automatically. The shared cache is updated, then synced to this server."} -

-
- - {/* Check & Apply options */} - {(c.mode ?? "check_and_apply") === "check_and_apply" && ( -
- - - - {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(191,0,255,0.2)", color: "var(--text-primary)" }} - /> -
-
- - patchConfig({ message: e.target.value })} - placeholder="Server updating in {minutes} minutes." - className="h-7 text-xs" - style={{ background: "rgba(0,0,0,0.4)", border: "1px solid rgba(191,0,255,0.2)", color: "var(--text-primary)" }} - /> -
-
- )} -
- )} -
- )} - {/* Restart-specific options */} {type === "restart" && (
@@ -392,7 +282,7 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing className="w-3.5 h-3.5 accent-purple-500" /> - Broadcast warning in-game before restart + Send in-game chat warning before restart {c.broadcastWarning && ( @@ -412,7 +302,7 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing />
- + patchConfig({ message: e.target.value })} @@ -432,7 +322,7 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing {type === "broadcast" && (
- + patchConfig({ message: e.target.value })} @@ -509,12 +399,6 @@ const CARD_DEFS: { title: "Auto-Backup", description: "Automatically zip and archive the server's save directory on a schedule.", }, - { - type: "update", - icon: RefreshCw, - title: "Auto-Update", - description: "Check for and install server updates via SteamCMD on a schedule.", - }, { type: "restart", icon: RotateCcw, @@ -524,11 +408,188 @@ const CARD_DEFS: { { type: "broadcast", icon: Megaphone, - title: "Scheduled Broadcast", - description: "Send a recurring in-game message to all online players via RCON.", + title: "Scheduled Chat Message", + description: "Send a recurring global chat message to all online players via RCON.", }, ]; +// --------------------------------------------------------------------------- +// UpdateAutomationCard — per-server update automation settings +// --------------------------------------------------------------------------- + +const DEFAULT_UPDATE_AUTOMATION: UpdateAutomation = { + mode: "off", + update_time: "03:00", + restart_after_update: true, + only_if_running: true, +}; + +function UpdateAutomationCard({ server }: { server: ServerRow }) { + const [automation, setAutomation] = useState(DEFAULT_UPDATE_AUTOMATION); + const [autoCheckEnabled, setAutoCheckEnabled] = useState(true); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(false); + + useEffect(() => { + (async () => { + const hours = await getAppSetting("asa_auto_check_hours"); + setAutoCheckEnabled((hours ?? "0") !== "0"); + try { + const raw = server.update_automation_json; + if (raw && raw !== "{}") { + setAutomation({ ...DEFAULT_UPDATE_AUTOMATION, ...JSON.parse(raw) }); + } + } catch { + // malformed JSON — use defaults + } + })(); + }, [server.id, server.update_automation_json]); + + const handleSave = async (patch: Partial) => { + const next = { ...automation, ...patch }; + setAutomation(next); + setSaving(true); + try { + await setServerUpdateAutomation(server.id, next); + setSaved(true); + setTimeout(() => setSaved(false), 2000); + } catch (e) { + toast.error(`Failed to save update automation: ${e}`); + } finally { + setSaving(false); + } + }; + + const isActive = automation.mode !== "off"; + + return ( +
+ {/* Header */} +
+
+ +
+
+
+

Auto-Update

+ {isActive && ( + + Active + + )} + {saving && } + {saved && } +
+

+ Automatically apply cached server updates when available. +

+
+
+ + {/* Auto-check required warning */} + {!autoCheckEnabled && ( +
+ + Auto update checks are disabled in Settings. Enable a check interval there for automation to work. +
+ )} + + {/* Mode selector */} +
+ +
+ {([ + { value: "off", label: "Disabled", icon: null }, + { value: "immediately", label: "When Found", icon: Zap }, + { value: "at_time", label: "Daily at Time", icon: Clock }, + ] as const).map(({ value, label, icon: Icon }) => ( + + ))} +
+ + {/* At-time picker */} + {automation.mode === "at_time" && ( +
+ + handleSave({ update_time: e.target.value })} + className="h-7 rounded px-2 text-xs font-mono" + style={{ background: "rgba(0,0,0,0.35)", border: "1px solid rgba(255,165,0,0.3)", color: "var(--text-primary)", outline: "none" }} + /> +
+ )} + + {/* Framework note for non-off modes */} + {automation.mode !== "off" && ( +
+ + + 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. + +
+ )} +
+ + {/* Restart options — only shown when a mode is active */} + {automation.mode !== "off" && ( +
+ + {automation.restart_after_update && ( + + )} +
+ )} +
+ ); +} + export function AutomationTab({ server }: Props) { const [schedules, setSchedules] = useState([]); const [loading, setLoading] = useState(true); @@ -597,6 +658,10 @@ export function AutomationTab({ server }: Props) {
) : (
+ {/* Update automation — uses new per-server settings instead of schedule rows */} + + + {/* Backup, restart, broadcast — cron-based schedule cards */} {CARD_DEFS.map((def) => ( {expanded ? "Hide" : "Configure"} - +
diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index 567c15f..89b3ba8 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -1,103 +1,53 @@ "use client"; import { useState, useEffect, useCallback } from "react"; -import { Save, Code, LayoutList, RefreshCw, ChevronDown, ChevronRight } from "lucide-react"; +import { + Save, Code, LayoutList, RefreshCw, ChevronDown, ChevronRight, + Settings2, X, AlertCircle, ToggleLeft, ToggleRight, Terminal, +} from "lucide-react"; 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 { tauriCmd, type ServerConfigJson } from "@/lib/tauri-commands"; -import type { ServerRow } from "@/lib/db"; +import { INI_FIELD_GROUPS, LAUNCH_PARAMETERS, type IniFieldDef, type LaunchParameter } from "@/data/game-data"; +import { getServerConfig, saveServerConfig, updateServerShutdownSettings, type ServerRow } from "@/lib/db"; +import { toast } from "sonner"; +import { NumberField } from "@/components/shared/NumberField"; interface Props { server: ServerRow; } -// --------------------------------------------------------------------------- -// Field definitions — the structured view of the most important ASA INI keys. -// Section keys must exactly match what the INI parser produces. -// --------------------------------------------------------------------------- - -interface FieldDef { - section: string; - key: string; - label: string; - type: "string" | "number" | "boolean"; - placeholder?: string; - min?: number; - max?: number; - step?: number; - file: "gus" | "game"; -} - -const FIELD_GROUPS: { title: string; fields: FieldDef[] }[] = [ - { - title: "Session", - fields: [ - { file: "gus", section: "SessionSettings", key: "SessionName", label: "Server Name", type: "string", placeholder: "My ASA Server" }, - { file: "gus", section: "ServerSettings", key: "MaxPlayers", label: "Max Players", type: "number", min: 1, max: 70 }, - { file: "gus", section: "SessionSettings", key: "ServerPassword", label: "Join Password", type: "string", placeholder: "(no password)" }, - ], - }, - { - title: "Admin & RCON", - fields: [ - { file: "gus", section: "ServerSettings", key: "ServerAdminPassword", label: "Admin Password", type: "string", placeholder: "required" }, - { file: "gus", section: "SessionSettings", key: "RCONEnabled", label: "RCON Enabled", type: "boolean" }, - { file: "gus", section: "SessionSettings", key: "RCONPort", label: "RCON Port", type: "number", min: 1024, max: 65535 }, - ], - }, - { - title: "Rates", - fields: [ - { file: "gus", section: "ServerSettings", key: "XPMultiplier", label: "XP Multiplier", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "TamingSpeedMultiplier", label: "Taming Speed", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "HarvestAmountMultiplier", label: "Harvest Amount", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "ResourcesRespawnPeriodMultiplier", label: "Resource Respawn Multiplier", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "PlayerCharacterWaterDrainMultiplier", label: "Water Drain", type: "number", min: 0.0, max: 10, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "PlayerCharacterFoodDrainMultiplier", label: "Food Drain", type: "number", min: 0.0, max: 10, step: 0.1 }, - ], - }, - { - title: "Taming & Breeding", - fields: [ - { file: "gus", section: "ServerSettings", key: "BabyMatureSpeedMultiplier", label: "Baby Mature Speed", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "EggHatchSpeedMultiplier", label: "Egg Hatch Speed", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "BabyCuddleIntervalMultiplier", label: "Imprint Interval", type: "number", min: 0.1, max: 100, step: 0.1 }, - ], - }, - { - title: "PvP / PvE", - fields: [ - { file: "gus", section: "ServerSettings", key: "DifficultyOffset", label: "Difficulty Offset", type: "number", min: 0, max: 1, step: 0.05 }, - { file: "gus", section: "ServerSettings", key: "AllowThirdPersonPlayer", label: "Allow Third Person", type: "boolean" }, - { file: "gus", section: "ServerSettings", key: "AlwaysNotifyPlayerLeft", label: "Notify Player Left", type: "boolean" }, - { file: "gus", section: "ServerSettings", key: "AlwaysNotifyPlayerJoined", label: "Notify Player Joined", type: "boolean" }, - { file: "gus", section: "ServerSettings", key: "GlobalVoiceChat", label: "Global Voice Chat", type: "boolean" }, - { file: "gus", section: "ServerSettings", key: "ProximityChat", label: "Proximity Chat", type: "boolean" }, - ], - }, -]; +// 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 // --------------------------------------------------------------------------- -function getIniValue(config: ServerConfigJson, file: "gus" | "game", section: string, key: string): string { - const src = file === "gus" ? config.gameUserSettings : config.gameIni; - return src?.[section]?.[key] ?? ""; +function getIniValue( + config: ServerConfigJson, + section: "gus" | "game", + iniSection: string, + key: string +): string { + const src = section === "gus" ? config.gameUserSettings : config.gameIni; + return src?.[iniSection]?.[key] ?? ""; } function setIniValue( config: ServerConfigJson, - file: "gus" | "game", - section: string, + section: "gus" | "game", + iniSection: string, key: string, value: string, ): ServerConfigJson { - const src = file === "gus" ? { ...config.gameUserSettings } : { ...config.gameIni }; - src[section] = { ...(src[section] ?? {}), [key]: value }; - if (file === "gus") return { ...config, gameUserSettings: src }; + const src = section === "gus" ? { ...config.gameUserSettings } : { ...config.gameIni }; + src[iniSection] = { ...(src[iniSection] ?? {}), [key]: value }; + if (section === "gus") return { ...config, gameUserSettings: src }; return { ...config, gameIni: src }; } @@ -128,11 +78,15 @@ function rawTextToSections(text: string): Record> } // --------------------------------------------------------------------------- -// FieldRow +// Field row // --------------------------------------------------------------------------- -function FieldRow({ field, value, onChange }: { - field: FieldDef; +function FieldRow({ + field, + value, + onChange, +}: { + field: IniFieldDef; value: string; onChange: (val: string) => void; }) { @@ -140,19 +94,49 @@ function FieldRow({ field, value, onChange }: { const checked = value === "True" || value === "true" || value === "1"; return (
-
+ +
+ ); + } + + if (field.type === "number" && field.min !== undefined && field.max !== undefined) { + const numVal = parseFloat(value) || 0; + return ( +
+
+ +
+ {field.description && ( +

{field.description}

+ )} + onChange(String(v))} + min={field.min} + max={field.max} + step={field.step} + defaultValue={field.defaultValue} />
); @@ -160,71 +144,161 @@ function FieldRow({ field, value, onChange }: { return (
- +
+ + {field.description && ( +

{field.description}

+ )} +
onChange(e.target.value)} placeholder={field.placeholder} - min={field.min} - max={field.max} - step={field.step} className="h-8 text-sm max-w-xs" - style={{ - background: "rgba(0,0,0,0.3)", - borderColor: "rgba(191,0,255,0.2)", - color: "var(--text-primary)", - }} + style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(191,0,255,0.2)", color: "var(--text-primary)" }} />
); } // --------------------------------------------------------------------------- -// Section accordion +// Launch parameter row // --------------------------------------------------------------------------- -function SectionGroup({ title, fields, config, onChange }: { - title: string; - fields: FieldDef[]; +function LaunchParamRow({ + param, + value, + onChange, +}: { + param: LaunchParameter; + value: string; + onChange: (val: string) => void; +}) { + if (param.type === "boolean") { + const on = value === "true" || value === "1"; + return ( +
+
+ {param.flag} + {param.description && ( +

{param.description}

+ )} +
+ +
+ ); + } + + return ( +
+ {param.flag} + {param.description && ( +

{param.description}

+ )} + onChange(e.target.value)} + className="h-8 text-xs font-mono" + style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(191,0,255,0.2)", color: "var(--text-primary)" }} + /> +
+ ); +} + +function LaunchParamGroup({ + config, + onChange, +}: { config: ServerConfigJson; - onChange: (f: FieldDef, val: string) => void; + onChange: (key: string, val: string) => void; }) { - const [open, setOpen] = useState(true); + const [open, setOpen] = useState(false); + const args = (config.launchArgs ?? {}) as Record; return ( -
+
+ {open && ( +
+ {LAUNCH_PARAMETERS.filter((p) => p.category !== "cluster").map((p) => ( + onChange(p.key, val)} + /> + ))} +
+ )} +
+ ); +} + +// --------------------------------------------------------------------------- +// Accordion group +// --------------------------------------------------------------------------- + +function SectionGroup({ + title, + fields, + config, + onChange, + defaultOpen = true, +}: { + title: string; + fields: IniFieldDef[]; + config: ServerConfigJson; + onChange: (f: IniFieldDef, val: string) => void; + defaultOpen?: boolean; +}) { + const [open, setOpen] = useState(defaultOpen); + + return ( +
+ {open && (
{fields.map((f) => ( onChange(f, val)} /> ))} @@ -234,10 +308,218 @@ function SectionGroup({ title, fields, config, onChange }: { ); } +// --------------------------------------------------------------------------- +// 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(["rates", "breeding"])); + + 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. +

+
+ + {/* Scrollable body */} +
+ {INI_FIELD_GROUPS.map((group) => { + const visibleFields = group.fields.filter( + (f) => f.section === "gus" && !OVERVIEW_KEYS.has(f.key) + ); + if (visibleFields.length === 0) return null; + const open = expandedGroups.has(group.id); + return ( +
+ + {open && ( +
+ {visibleFields.map((f) => ( + handleChange(f, val)} + /> + ))} +
+ )} +
+ ); + })} +
+ + {/* Footer */} +
+ + +
+
+
+ ); +} + +// --------------------------------------------------------------------------- +// Quick-edit groups shown in the structured tab (subset of all groups) +// --------------------------------------------------------------------------- + +const QUICK_EDIT_GROUP_IDS = ["session", "admin", "rates", "breeding"]; + // --------------------------------------------------------------------------- // Main ConfigTab // --------------------------------------------------------------------------- +// --------------------------------------------------------------------------- +// Shutdown Settings Card +// --------------------------------------------------------------------------- + +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}." + ); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(false); + + const handleSave = async () => { + setSaving(true); + try { + await updateServerShutdownSettings(server.id, warnPlayers, warnMinutes, message); + setSaved(true); + setTimeout(() => setSaved(false), 2000); + } catch (e) { + toast.error(`Failed to save shutdown settings: ${e}`); + } finally { + setSaving(false); + } + }; + + return ( +
+
+ +

Graceful Shutdown

+
+ + + +
+
+ + setWarnMinutes(parseInt(e.target.value, 10) || 5)} + className="h-7 w-24 text-xs" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(191,0,255,0.2)", color: "var(--text-primary)" }} + /> +
+
+ + setMessage(e.target.value)} + placeholder="Server will shut down in {time}." + className="h-7 text-xs" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(191,0,255,0.2)", color: "var(--text-primary)" }} + /> +
+
+ + +
+ ); +} + export function ConfigTab({ server }: Props) { const [config, setConfig] = useState(null); const [rawGus, setRawGus] = useState(""); @@ -245,12 +527,45 @@ export function ConfigTab({ server }: Props) { const [rawMode, setRawMode] = useState(false); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); + const [readingIni, setReadingIni] = useState(false); const [savedFlash, setSavedFlash] = useState(false); const [error, setError] = useState(null); + const [showFullModal, setShowFullModal] = useState(false); - const loadConfig = useCallback(async () => { + // Load from DB on mount — reflects what we last saved, not what the server may have overwritten + const loadFromDb = useCallback(async () => { setLoading(true); setError(null); + try { + const row = await getServerConfig(server.id); + if (row) { + const gus = JSON.parse(row.game_user_settings_json || "{}"); + const game = JSON.parse(row.game_ini_json || "{}"); + const launchArgs = JSON.parse(row.launch_args_json || "{}"); + const cfg: ServerConfigJson = { gameUserSettings: gus, gameIni: game, launchArgs }; + setConfig(cfg); + setRawGus(configToRawText(gus)); + setRawGame(configToRawText(game)); + } else { + // No saved config yet — show empty + const empty: ServerConfigJson = { gameUserSettings: {}, gameIni: {}, launchArgs: {} }; + setConfig(empty); + setRawGus(""); + setRawGame(""); + } + } catch (e) { + setError(String(e)); + } finally { + setLoading(false); + } + }, [server.id]); + + useEffect(() => { loadFromDb(); }, [loadFromDb]); + + // Explicitly read from the INI files on disk — overwrites UI state with what the server has on disk + const readFromIni = useCallback(async () => { + setReadingIni(true); + setError(null); try { const cfg = await tauriCmd.readServerConfig(server.install_path); setConfig(cfg); @@ -259,32 +574,47 @@ export function ConfigTab({ server }: Props) { } catch (e) { setError(String(e)); } finally { - setLoading(false); + setReadingIni(false); } }, [server.install_path]); - useEffect(() => { loadConfig(); }, [loadConfig]); - - const handleFieldChange = (field: FieldDef, value: string) => { + const handleFieldChange = (field: IniFieldDef, value: string) => { if (!config) return; - setConfig(setIniValue(config, field.file, field.section, field.key, value)); + setConfig(setIniValue(config, field.section, field.iniSection, field.key, value)); }; - const handleSave = async () => { + const handleLaunchArgChange = (key: string, val: string) => { if (!config) return; + setConfig({ ...config, launchArgs: { ...(config.launchArgs as Record ?? {}), [key]: val } }); + }; + + // Save to disk AND update DB so our settings survive server restarts + const handleSave = async (cfg?: ServerConfigJson) => { + const toWrite = cfg ?? config; + if (!toWrite) return; setSaving(true); setError(null); try { - let toSave = config; - if (rawMode) { + let toSave = toWrite; + if (rawMode && !cfg) { toSave = { - ...config, + ...toWrite, gameUserSettings: rawTextToSections(rawGus), gameIni: rawTextToSections(rawGame), }; setConfig(toSave); + } else if (cfg) { + setConfig(cfg); } + // 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 ?? {}), + ); setSavedFlash(true); setTimeout(() => setSavedFlash(false), 2000); } catch (e) { @@ -313,46 +643,55 @@ export function ConfigTab({ server }: Props) { return (
- - Reading INI files… - + Loading saved config…
); } + // Quick-edit: only show a curated subset of groups + const quickGroups = INI_FIELD_GROUPS.filter((g) => QUICK_EDIT_GROUP_IDS.includes(g.id)); + return (
- {/* ── Toolbar ── */} + {/* Toolbar */}
- - + {!rawMode && ( + + )}
-
{error && ( -
+
{error}
)} - {/* ── Structured editor ── */} + {/* Structured editor — quick groups */} {!rawMode && config && (
- {FIELD_GROUPS.map((g) => ( + {quickGroups.map((g, idx) => ( ))} + +

+ Click Full INI Editor in the toolbar to access all server settings. +

)} - {/* ── Raw INI editor ── */} + {/* Raw INI editor */} {rawMode && (
-

- GameUserSettings.ini -

+

GameUserSettings.ini