From 592537cfeabdce760ec0fd09af1c2df3deae716c Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 8 Jun 2026 07:38:18 -0500 Subject: [PATCH 01/15] feat: enhance sidebar navigation and logs management - Refactor Sidebar component to separate top and bottom navigation items. - Add new navigation links for Logs and Backups in the Sidebar. - Implement a NavLink component for cleaner code and better reusability. - Update LogsTab component to support multiple views: Live, Archive, Crashes, and Chat. - Introduce new interfaces for archived logs, crash reports, and chat logs in tauri-commands. - Add functionality to list, read, and delete archived logs and crash reports. - Implement cleanup functionality for old logs and display log statistics. --- src-tauri/src/commands/logs.rs | 581 ++++++++++++++++++--- src-tauri/src/commands/rcon.rs | 10 +- src-tauri/src/commands/server.rs | 55 +- src-tauri/src/events/mod.rs | 4 +- src-tauri/src/lib.rs | 14 +- src-tauri/src/state/log_manager.rs | 323 ++++++++++++ src-tauri/src/state/log_watcher.rs | 43 -- src-tauri/src/state/mod.rs | 2 +- src/app/backups/page.tsx | 62 +++ src/app/logs/page.tsx | 123 +++++ src/components/layout/Sidebar.tsx | 122 ++--- src/components/server/tabs/LogsTab.tsx | 683 +++++++++++++++++++++---- src/lib/tauri-commands.ts | 69 +++ 13 files changed, 1740 insertions(+), 351 deletions(-) create mode 100644 src-tauri/src/state/log_manager.rs delete mode 100644 src-tauri/src/state/log_watcher.rs create mode 100644 src/app/backups/page.tsx create mode 100644 src/app/logs/page.tsx diff --git a/src-tauri/src/commands/logs.rs b/src-tauri/src/commands/logs.rs index 37948da..922bdcf 100644 --- a/src-tauri/src/commands/logs.rs +++ b/src-tauri/src/commands/logs.rs @@ -1,114 +1,541 @@ -use std::io::SeekFrom; -use std::sync::{atomic::Ordering, Arc}; -use tauri::{Emitter, State}; -use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader}; - -use crate::{events, state::log_watcher::LogWatcherState}; - -/// Begin tailing `log_path` for `server_id`. -/// A background tokio task polls the file every 200 ms, seeking to the current -/// end on start so only new lines are emitted. Each new line fires the event -/// `log://line/{server_id}` with a `LogLine` payload. -/// -/// Calling this again for the same `server_id` replaces the previous watcher. +use serde::{Deserialize, Serialize}; +use tauri::State; + +use crate::state::log_manager::LogManagerState; + +// --------------------------------------------------------------------------- +// Public types (mirrored on the frontend) +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ArchivedLogInfo { + pub filename: String, + pub size_bytes: u64, + /// ISO timestamp derived from the filename (YYYY-MM-DD_HH-MM-SS). + pub timestamp: String, + pub full_path: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CrashInfo { + pub folder_name: String, + pub timestamp: String, + pub has_call_stack: bool, + pub files: Vec, + pub full_path: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CrashFile { + pub name: String, + pub content: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CrashReport { + pub folder_name: String, + pub files: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChatLogInfo { + pub filename: String, + pub date: String, + pub size_bytes: u64, + pub full_path: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LogStats { + pub shootergame_archive_count: u32, + pub shootergame_total_bytes: u64, + pub chat_log_count: u32, + pub chat_total_bytes: u64, + pub crash_count: u32, + pub storage_root: String, +} + +// --------------------------------------------------------------------------- +// Watch commands +// --------------------------------------------------------------------------- + +/// Start tailing ShooterGame.log for `server_id`. +/// Emits `log://backfill/{server_id}` with existing content then +/// `log://line/{server_id}` for each new line. #[tauri::command] pub async fn watch_server_log( app: tauri::AppHandle, server_id: String, log_path: String, - state: State<'_, LogWatcherState>, + state: State<'_, LogManagerState>, ) -> Result<(), String> { - let stop_flag = state.start(&server_id).await; - let event_name = format!("{}/{server_id}", events::LOG_LINE); - - tauri::async_runtime::spawn(async move { - tail_log(app, event_name, log_path, stop_flag).await; - }); - + state.start_watcher(&server_id, log_path, app).await; Ok(()) } -/// Stop the log watcher for `server_id` (no-op if not watching). +/// Stop the log watcher for `server_id`. #[tauri::command] pub async fn stop_log_watch( server_id: String, - state: State<'_, LogWatcherState>, + state: State<'_, LogManagerState>, ) -> Result<(), String> { - state.stop(&server_id).await; + state.stop_watcher(&server_id).await; Ok(()) } -#[derive(Clone, serde::Serialize)] -pub struct LogLine { - pub line: String, - pub level: String, +// --------------------------------------------------------------------------- +// Archive commands +// --------------------------------------------------------------------------- + +/// List all archived ShooterGame log files for a server, newest first. +#[tauri::command] +pub async fn list_archived_logs( + app: tauri::AppHandle, + server_id: String, +) -> Result, String> { + let dir = match LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("shootergame")) + { + Some(d) => d, + None => return Ok(vec![]), + }; + + if !dir.exists() { + return Ok(vec![]); + } + + let mut entries: Vec = Vec::new(); + let mut read_dir = tokio::fs::read_dir(&dir) + .await + .map_err(|e| format!("Failed to read log archive dir: {e}"))?; + + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let name = entry.file_name().to_string_lossy().to_string(); + if !name.ends_with(".log") { + continue; + } + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + let timestamp = extract_timestamp_from_filename(&name); + entries.push(ArchivedLogInfo { + filename: name, + size_bytes: meta.len(), + timestamp, + full_path: entry.path().to_string_lossy().to_string(), + }); + } + + // Sort newest first by filename (ISO timestamp sorts lexicographically). + entries.sort_by(|a, b| b.filename.cmp(&a.filename)); + Ok(entries) } -/// Classify an ASA log line into a rough severity level. -fn classify_level(line: &str) -> &'static str { - let lower = line.to_ascii_lowercase(); - if lower.contains("error") || lower.contains("fatal") || lower.contains("critical") { - "error" - } else if lower.contains("warning") || lower.contains("warn") { - "warning" - } else { - "info" +/// Read lines from an archived log file, with pagination. +/// `offset` is line index (0-based); `limit` is max lines to return. +/// Pass limit=0 to get all lines. +#[tauri::command] +pub async fn read_archived_log( + app: tauri::AppHandle, + server_id: String, + filename: String, + offset: usize, + limit: usize, +) -> Result, String> { + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("shootergame")) + .ok_or("Log storage not configured")?; + + // Validate filename — no path traversal + if filename.contains('/') || filename.contains('\\') || filename.contains("..") { + return Err("Invalid filename".to_string()); } + + let path = dir.join(&filename); + let content = tokio::fs::read_to_string(&path) + .await + .map_err(|e| format!("Failed to read log: {e}"))?; + + let lines: Vec = content + .lines() + .skip(offset) + .take(if limit == 0 { usize::MAX } else { limit }) + .map(|l| l.to_string()) + .collect(); + + Ok(lines) } -async fn tail_log( +/// Delete an archived log file. +#[tauri::command] +pub async fn delete_archived_log( app: tauri::AppHandle, - event_name: String, - log_path: String, - stop_flag: Arc, -) { - use tokio::fs::File; - - // Wait for the log file to exist (server may not have started yet). - let mut file = { - let mut attempts = 0u32; - loop { - if stop_flag.load(Ordering::Relaxed) { - return; - } - match File::open(&log_path).await { - Ok(f) => break f, - Err(_) => { - attempts += 1; - if attempts >= 60 { - return; - } - tokio::time::sleep(std::time::Duration::from_secs(1)).await; + server_id: String, + filename: String, +) -> Result<(), String> { + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("shootergame")) + .ok_or("Log storage not configured")?; + + if filename.contains('/') || filename.contains('\\') || filename.contains("..") { + return Err("Invalid filename".to_string()); + } + + tokio::fs::remove_file(dir.join(&filename)) + .await + .map_err(|e| format!("Failed to delete log: {e}")) +} + +// --------------------------------------------------------------------------- +// Crash commands +// --------------------------------------------------------------------------- + +/// List crash reports from the server's Saved/Crashes directory. +#[tauri::command] +pub async fn list_crashes( + install_path: String, +) -> Result, String> { + let crashes_dir = format!("{}/ShooterGame/Saved/Crashes", install_path); + let path = std::path::Path::new(&crashes_dir); + + if !path.exists() { + return Ok(vec![]); + } + + let mut crashes: Vec = Vec::new(); + let mut read_dir = tokio::fs::read_dir(&path) + .await + .map_err(|e| format!("Failed to read crashes dir: {e}"))?; + + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + if !meta.is_dir() { + continue; + } + + let folder_name = entry.file_name().to_string_lossy().to_string(); + let full_path = entry.path().to_string_lossy().to_string(); + + // Collect file names in the crash folder. + let mut files: Vec = Vec::new(); + let mut has_call_stack = false; + + if let Ok(mut inner) = tokio::fs::read_dir(entry.path()).await { + while let Ok(Some(f)) = inner.next_entry().await { + let fname = f.file_name().to_string_lossy().to_string(); + let fl = fname.to_lowercase(); + if fl.contains("callstack") || fl.contains("stack") { + has_call_stack = true; } + files.push(fname); } } + files.sort(); + + let timestamp = folder_name_to_timestamp(&folder_name); + + crashes.push(CrashInfo { + folder_name, + timestamp, + has_call_stack, + files, + full_path, + }); + } + + // Newest first. + crashes.sort_by(|a, b| b.folder_name.cmp(&a.folder_name)); + Ok(crashes) +} + +/// Read all readable (non-binary) files from a crash folder. +#[tauri::command] +pub async fn read_crash_report( + install_path: String, + folder_name: String, +) -> Result { + if folder_name.contains('/') || folder_name.contains('\\') || folder_name.contains("..") { + return Err("Invalid folder name".to_string()); + } + + let crashes_dir = format!("{}/ShooterGame/Saved/Crashes", install_path); + let folder_path = std::path::Path::new(&crashes_dir).join(&folder_name); + + if !folder_path.exists() { + return Err("Crash folder not found".to_string()); + } + + let mut files: Vec = Vec::new(); + let mut read_dir = tokio::fs::read_dir(&folder_path) + .await + .map_err(|e| format!("Failed to read crash folder: {e}"))?; + + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let name = entry.file_name().to_string_lossy().to_string(); + let lower = name.to_lowercase(); + + // Skip binary files (.dmp, .png, .jpg). + if lower.ends_with(".dmp") + || lower.ends_with(".png") + || lower.ends_with(".jpg") + || lower.ends_with(".bin") + { + continue; + } + + let content = tokio::fs::read_to_string(entry.path()) + .await + .unwrap_or_else(|_| "[binary or unreadable file]".to_string()); + + files.push(CrashFile { name, content }); + } + + files.sort_by(|a, b| a.name.cmp(&b.name)); + + Ok(CrashReport { folder_name, files }) +} + +// --------------------------------------------------------------------------- +// Chat log commands +// --------------------------------------------------------------------------- + +/// List all chat log files for a server, newest first. +#[tauri::command] +pub async fn list_chat_logs( + app: tauri::AppHandle, + server_id: String, +) -> Result, String> { + let dir = match LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("chat")) + { + Some(d) => d, + None => return Ok(vec![]), + }; + + if !dir.exists() { + return Ok(vec![]); + } + + let mut entries: Vec = Vec::new(); + let mut read_dir = tokio::fs::read_dir(&dir) + .await + .map_err(|e| format!("Failed to read chat log dir: {e}"))?; + + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let name = entry.file_name().to_string_lossy().to_string(); + if !name.ends_with(".log") { + continue; + } + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + // filename: chat_YYYY-MM-DD.log → date: YYYY-MM-DD + let date = name + .strip_prefix("chat_") + .and_then(|s| s.strip_suffix(".log")) + .unwrap_or(&name) + .to_string(); + entries.push(ChatLogInfo { + filename: name, + date, + size_bytes: meta.len(), + full_path: entry.path().to_string_lossy().to_string(), + }); + } + + entries.sort_by(|a, b| b.filename.cmp(&a.filename)); + Ok(entries) +} + +/// Read lines from a chat log file. +#[tauri::command] +pub async fn read_chat_log( + app: tauri::AppHandle, + server_id: String, + filename: String, + offset: usize, + limit: usize, +) -> Result, String> { + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("chat")) + .ok_or("Log storage not configured")?; + + if filename.contains('/') || filename.contains('\\') || filename.contains("..") { + return Err("Invalid filename".to_string()); + } + + let path = dir.join(&filename); + let content = tokio::fs::read_to_string(&path) + .await + .map_err(|e| format!("Failed to read chat log: {e}"))?; + + let lines: Vec = content + .lines() + .skip(offset) + .take(if limit == 0 { usize::MAX } else { limit }) + .map(|l| l.to_string()) + .collect(); + + Ok(lines) +} + +// --------------------------------------------------------------------------- +// Cleanup + stats +// --------------------------------------------------------------------------- + +/// Delete all archived ShooterGame logs older than `older_than_days` days. +/// Returns the number of files deleted. +#[tauri::command] +pub async fn cleanup_logs( + app: tauri::AppHandle, + server_id: String, + older_than_days: u32, +) -> Result { + let dir = match LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("shootergame")) + { + Some(d) => d, + None => return Ok(0), }; - // Seek to end so we only tail new content from this point. - let _ = file.seek(SeekFrom::End(0)).await; + if !dir.exists() { + return Ok(0); + } + + let cutoff_secs = { + use std::time::{SystemTime, UNIX_EPOCH}; + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + .saturating_sub(older_than_days as u64 * 86_400) + }; - let mut reader = BufReader::new(file); - let mut line_buf = String::new(); + let mut deleted = 0u32; + let mut read_dir = tokio::fs::read_dir(&dir) + .await + .map_err(|e| format!("Failed to read log dir: {e}"))?; - loop { - if stop_flag.load(Ordering::Relaxed) { - break; + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let name = entry.file_name().to_string_lossy().to_string(); + if !name.ends_with(".log") { + continue; } + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + let modified_secs = meta + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_secs()) + .unwrap_or(0); - match reader.read_line(&mut line_buf).await { - Ok(0) => { - // No new data — sleep before next poll. - tokio::time::sleep(std::time::Duration::from_millis(200)).await; + if modified_secs < cutoff_secs { + if tokio::fs::remove_file(entry.path()).await.is_ok() { + deleted += 1; } - Ok(_) => { - let trimmed = line_buf.trim_end_matches(['\n', '\r']).to_string(); - if !trimmed.is_empty() { - let level = classify_level(&trimmed).to_string(); - let _ = app.emit(&event_name, LogLine { line: trimmed, level }); + } + } + + Ok(deleted) +} + +/// Get log storage statistics for a server. +#[tauri::command] +pub async fn get_log_stats( + app: tauri::AppHandle, + server_id: String, +) -> Result { + let root = LogManagerState::server_logs_dir(&app, &server_id); + let storage_root = root + .as_ref() + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default(); + + let sg_dir = root.as_ref().map(|d| d.join("shootergame")); + let chat_dir = root.as_ref().map(|d| d.join("chat")); + let crash_dir = root.as_ref().map(|d| { + // crashes live in the install dir, but we reference them from here + d.clone() + }); + let _ = crash_dir; // placeholder until we store crashes centrally + + let (sg_count, sg_bytes) = count_dir(sg_dir.as_deref()).await; + let (chat_count, chat_bytes) = count_dir(chat_dir.as_deref()).await; + + Ok(LogStats { + shootergame_archive_count: sg_count, + shootergame_total_bytes: sg_bytes, + chat_log_count: chat_count, + chat_total_bytes: chat_bytes, + crash_count: 0, // populated by list_crashes on demand + storage_root, + }) +} + +/// Return the path to the central logs storage root (for display in UI). +#[tauri::command] +pub fn get_log_storage_root(app: tauri::AppHandle) -> String { + LogManagerState::logs_root(&app) + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default() +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +async fn count_dir(dir: Option<&std::path::Path>) -> (u32, u64) { + let dir = match dir { + Some(d) if d.exists() => d, + _ => return (0, 0), + }; + let mut count = 0u32; + let mut bytes = 0u64; + if let Ok(mut rd) = tokio::fs::read_dir(dir).await { + while let Ok(Some(entry)) = rd.next_entry().await { + if let Ok(meta) = entry.metadata().await { + if meta.is_file() { + count += 1; + bytes += meta.len(); } - line_buf.clear(); } - Err(_) => break, } } + (count, bytes) +} + +/// Extract the timestamp string from a filename like `ShooterGame_2026-06-08_14-30-00.log`. +fn extract_timestamp_from_filename(name: &str) -> String { + // ShooterGame_YYYY-MM-DD_HH-MM-SS.log + name.trim_start_matches("ShooterGame_") + .trim_end_matches(".log") + .replace('_', " ") + .replace('-', if name.contains("_") { "-" } else { "-" }) + .to_string() +} + +/// Convert a UE5 crash folder name (e.g. `UE5-ShooterGame-Win64-2026.06.08-14.30.00`) to a readable string. +fn folder_name_to_timestamp(folder: &str) -> String { + // Try to extract any date-like portion. + // Common patterns: 2026.06.08-14.30.00 or 2026-06-08_14-30-00 + for part in folder.split('-') { + if part.len() >= 4 && part.chars().next().map_or(false, |c| c.is_ascii_digit()) { + return part.replace('.', "-"); + } + } + folder.to_string() } diff --git a/src-tauri/src/commands/rcon.rs b/src-tauri/src/commands/rcon.rs index bf35821..dc0087a 100644 --- a/src-tauri/src/commands/rcon.rs +++ b/src-tauri/src/commands/rcon.rs @@ -4,9 +4,12 @@ use tauri::{Emitter, Manager, State}; use tokio::sync::{mpsc, oneshot}; use tokio::time::{timeout, Duration, interval, MissedTickBehavior}; -use crate::state::rcon_pool::{ - bin_subdir, CachedPlayer, RconCmd, RconConn, RconLogLine, RconPool, - RCON_AUTH, RCON_AUTH_RESPONSE, RCON_EXECCOMMAND, parse_player_list, +use crate::state::{ + log_manager::LogManagerState, + rcon_pool::{ + bin_subdir, CachedPlayer, RconCmd, RconConn, RconLogLine, RconPool, + RCON_AUTH, RCON_AUTH_RESPONSE, RCON_EXECCOMMAND, parse_player_list, + }, }; // Re-export CachedPlayer as ArkPlayer for backwards-compat with existing frontend calls. @@ -245,6 +248,7 @@ async fn run_rcon_manager( // Drop SERVER: prefix lines — these are echoes of admin // broadcasts (e.g. ServerChat) that the user already saw. if line.starts_with("SERVER: ") { continue; } + LogManagerState::append_chat_line(&app, &server_id, line).await; emit_log(&app, &server_id, RconLogLine { timestamp_ms: now_ms(), text: line.to_string(), diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 16a51c0..9c2088a 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -1,4 +1,4 @@ -use crate::{events, state::{AppState, rcon_pool::RconPool}}; +use crate::{events, state::{AppState, log_manager::LogManagerState, rcon_pool::RconPool}}; use serde::{Deserialize, Serialize}; use std::sync::{ atomic::{AtomicBool, Ordering}, @@ -319,52 +319,13 @@ async fn inner_start_server_with_state( cmd.env_remove("PYTHONPATH"); } - // 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 - }; + // Archive any existing ShooterGame.log to central LokiASAM log storage before + // launching so the fresh session always starts from byte 0. + let did_rotate = LogManagerState::archive_shootergame_log( + app_handle, + ¶ms.server_id, + ¶ms.install_path, + ).await; let mut child = match cmd.spawn() { Ok(c) => c, diff --git a/src-tauri/src/events/mod.rs b/src-tauri/src/events/mod.rs index 895d24d..4b648a9 100644 --- a/src-tauri/src/events/mod.rs +++ b/src-tauri/src/events/mod.rs @@ -8,8 +8,10 @@ pub const SERVER_STATUS: &str = "server://status"; pub const SERVER_ANY_CHANGE: &str = "server://any-change"; /// SteamCMD stdout/stderr lines streamed during install / update / validate. pub const STEAMCMD_OUTPUT: &str = "steamcmd://output"; -/// ASA server log lines streamed from the ShooterGame.log file watcher. +/// ASA server log lines streamed from the ShooterGame.log file watcher (new lines only). pub const LOG_LINE: &str = "log://line"; +/// Batch of existing log lines sent once when the watcher first opens a file (backfill). +pub const LOG_BACKFILL: &str = "log://backfill"; /// Backup progress update. pub const BACKUP_PROGRESS: &str = "backup://progress"; /// ASA update check result (or update-applied notification). diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 05b6592..aedbc72 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -157,7 +157,7 @@ pub fn run() { app.manage(state::AppState::new()); app.manage(state::rcon_pool::RconPool::new()); - app.manage(state::log_watcher::LogWatcherState::new()); + app.manage(state::log_manager::LogManagerState::new()); app.manage(state::scheduler::SchedulerState::new()); app.manage(state::stats_recorder::StatsRecorderState::new()); @@ -433,9 +433,19 @@ pub fn run() { commands::rcon::rcon_disable_chat_poll, commands::rcon::rcon_read_ban_list, commands::rcon::rcon_read_whitelist, - // Log watcher + // Log watcher + archive + crash + chat commands::logs::watch_server_log, commands::logs::stop_log_watch, + commands::logs::list_archived_logs, + commands::logs::read_archived_log, + commands::logs::delete_archived_log, + commands::logs::list_crashes, + commands::logs::read_crash_report, + commands::logs::list_chat_logs, + commands::logs::read_chat_log, + commands::logs::cleanup_logs, + commands::logs::get_log_stats, + commands::logs::get_log_storage_root, // Config / INI commands::config::read_server_config, commands::config::write_server_config, diff --git a/src-tauri/src/state/log_manager.rs b/src-tauri/src/state/log_manager.rs new file mode 100644 index 0000000..4a45660 --- /dev/null +++ b/src-tauri/src/state/log_manager.rs @@ -0,0 +1,323 @@ +use std::collections::HashMap; +use std::io::SeekFrom; +use std::path::PathBuf; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; +use tauri::{Emitter, Manager}; +use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader}; +use tokio::sync::Mutex; + +use crate::events; + +/// Manages all server log file watchers. +/// Replaces the old LogWatcherState — adds backfill of existing content on start. +pub struct LogManagerState { + pub watchers: Mutex>>, +} + +impl LogManagerState { + pub fn new() -> Self { + Self { + watchers: Mutex::new(HashMap::new()), + } + } + + /// Start tailing `log_path` for `server_id`. + /// + /// 1. Reads all existing content from the beginning, emitting a single + /// `log://backfill/{server_id}` event with Vec. + /// 2. Tails new lines from EOF, emitting `log://line/{server_id}` per line. + /// + /// Calling again for the same `server_id` cancels the previous watcher. + pub async fn start_watcher( + &self, + server_id: &str, + log_path: String, + app: tauri::AppHandle, + ) -> Arc { + let stop_flag = Arc::new(AtomicBool::new(false)); + if let Some(old) = self + .watchers + .lock() + .await + .insert(server_id.to_string(), stop_flag.clone()) + { + old.store(true, Ordering::Relaxed); + } + + let server_id = server_id.to_string(); + let flag = stop_flag.clone(); + tauri::async_runtime::spawn(async move { + tail_log_with_backfill(app, server_id, log_path, flag).await; + }); + + stop_flag + } + + pub async fn stop_watcher(&self, server_id: &str) { + if let Some(flag) = self.watchers.lock().await.remove(server_id) { + flag.store(true, Ordering::Relaxed); + } + } + + /// Resolve the central logs root: `{base_dir}/lokiasam/logs/`. + /// Returns None if bootstrap.json is missing (setup not complete). + pub fn logs_root(app: &tauri::AppHandle) -> Option { + let config_dir = app.path().app_config_dir().ok()?; + let bootstrap_path = config_dir.join("bootstrap.json"); + let text = std::fs::read_to_string(&bootstrap_path).ok()?; + let value: serde_json::Value = serde_json::from_str(&text).ok()?; + let base_dir = value.get("baseDir")?.as_str()?; + Some(PathBuf::from(base_dir).join("lokiasam").join("logs")) + } + + /// Resolve per-server log directory: `{logs_root}/{server_id}/`. + pub fn server_logs_dir(app: &tauri::AppHandle, server_id: &str) -> Option { + Some(Self::logs_root(app)?.join(server_id)) + } + + /// Archive the current ShooterGame.log for `server_id` to central storage. + /// Called by `inner_start_server` before the server process is spawned. + /// Returns true if the log was archived or didn't exist; false on error. + pub async fn archive_shootergame_log( + app: &tauri::AppHandle, + server_id: &str, + install_path: &str, + ) -> bool { + let current_log = format!( + "{}/ShooterGame/Saved/Logs/ShooterGame.log", + install_path + ); + + if tokio::fs::metadata(¤t_log).await.is_err() { + return true; // no log to archive — fresh install + } + + let Some(dest_dir) = Self::server_logs_dir(app, server_id) + .map(|d| d.join("shootergame")) else { + // Bootstrap not set up yet; fall back to deleting the old log so + // the new session always starts from byte 0. + return tokio::fs::remove_file(¤t_log).await.is_ok(); + }; + + if tokio::fs::create_dir_all(&dest_dir).await.is_err() { + return tokio::fs::remove_file(¤t_log).await.is_ok(); + } + + let timestamp = current_timestamp_str(); + let archive_name = format!("ShooterGame_{timestamp}.log"); + let dest = dest_dir.join(&archive_name); + + if tokio::fs::rename(¤t_log, &dest).await.is_ok() { + true + } else { + // rename across filesystems fails — copy then delete + if tokio::fs::copy(¤t_log, &dest).await.is_ok() { + let _ = tokio::fs::remove_file(¤t_log).await; + true + } else { + tokio::fs::remove_file(¤t_log).await.is_ok() + } + } + } + + /// Append a chat line to today's chat log file. + /// Called by the RCON manager when a GetChat line is received. + pub async fn append_chat_line(app: &tauri::AppHandle, server_id: &str, line: &str) { + let Some(dir) = Self::server_logs_dir(app, server_id) + .map(|d| d.join("chat")) else { return }; + + if tokio::fs::create_dir_all(&dir).await.is_err() { + return; + } + + let date = current_date_str(); + let path = dir.join(format!("chat_{date}.log")); + let ts = current_time_str(); + let entry = format!("[{ts}] {line}\n"); + use tokio::io::AsyncWriteExt; + if let Ok(mut f) = tokio::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .await + { + let _ = f.write_all(entry.as_bytes()).await; + } + } +} + +// --------------------------------------------------------------------------- +// Tail task +// --------------------------------------------------------------------------- + +#[derive(Clone, serde::Serialize)] +pub struct LogLine { + pub line: String, + pub level: String, +} + +fn classify_level(line: &str) -> &'static str { + let lower = line.to_ascii_lowercase(); + if lower.contains("error") || lower.contains("fatal") || lower.contains("critical") { + "error" + } else if lower.contains("warning") || lower.contains("warn") { + "warning" + } else { + "info" + } +} + +async fn tail_log_with_backfill( + app: tauri::AppHandle, + server_id: String, + log_path: String, + stop_flag: Arc, +) { + use tokio::fs::File; + + // Wait up to 60 s for the log file to appear (server may still be starting). + let mut file = { + let mut attempts = 0u32; + loop { + if stop_flag.load(Ordering::Relaxed) { + return; + } + match File::open(&log_path).await { + Ok(f) => break f, + Err(_) => { + attempts += 1; + if attempts >= 60 { + return; + } + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + } + } + } + }; + + // ── Backfill: read all existing content from start ─────────────────────── + let backfill_event = format!("{}/{server_id}", events::LOG_BACKFILL); + let mut backfill: Vec = Vec::new(); + let mut buf = String::new(); + let mut reader = BufReader::new(&mut file); + loop { + buf.clear(); + match reader.read_line(&mut buf).await { + Ok(0) => break, + Ok(_) => { + let trimmed = buf.trim_end_matches(['\n', '\r']).to_string(); + if !trimmed.is_empty() { + let level = classify_level(&trimmed).to_string(); + backfill.push(LogLine { line: trimmed, level }); + } + } + Err(_) => break, + } + } + if !backfill.is_empty() { + let _ = app.emit(&backfill_event, &backfill); + } + + // Seek to current EOF so we only tail truly new content. + let _ = file.seek(SeekFrom::End(0)).await; + + // ── Tail: stream new lines as they arrive ──────────────────────────────── + let line_event = format!("{}/{server_id}", events::LOG_LINE); + let mut reader = BufReader::new(file); + let mut line_buf = String::new(); + + loop { + if stop_flag.load(Ordering::Relaxed) { + break; + } + match reader.read_line(&mut line_buf).await { + Ok(0) => { + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + } + Ok(_) => { + let trimmed = line_buf.trim_end_matches(['\n', '\r']).to_string(); + if !trimmed.is_empty() { + let level = classify_level(&trimmed).to_string(); + let _ = app.emit(&line_event, LogLine { line: trimmed, level }); + } + line_buf.clear(); + } + Err(_) => break, + } + } +} + +// --------------------------------------------------------------------------- +// Time helpers (no external crate, manual calculation) +// --------------------------------------------------------------------------- + +fn current_timestamp_str() -> String { + use std::time::{SystemTime, UNIX_EPOCH}; + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let (y, mo, d, h, min, s) = epoch_to_ymdhms(secs); + format!("{y:04}-{mo:02}-{d:02}_{h:02}-{min:02}-{s:02}") +} + +pub fn current_date_str() -> String { + use std::time::{SystemTime, UNIX_EPOCH}; + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let (y, mo, d, _, _, _) = epoch_to_ymdhms(secs); + format!("{y:04}-{mo:02}-{d:02}") +} + +fn current_time_str() -> String { + use std::time::{SystemTime, UNIX_EPOCH}; + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let (_, _, _, h, min, s) = epoch_to_ymdhms(secs); + format!("{h:02}:{min:02}:{s:02}") +} + +pub fn epoch_to_ymdhms(now_secs: u64) -> (u64, u64, u64, u64, u64, u64) { + 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, + ) +} diff --git a/src-tauri/src/state/log_watcher.rs b/src-tauri/src/state/log_watcher.rs deleted file mode 100644 index c193f33..0000000 --- a/src-tauri/src/state/log_watcher.rs +++ /dev/null @@ -1,43 +0,0 @@ -use std::collections::HashMap; -use std::sync::{ - atomic::{AtomicBool, Ordering}, - Arc, -}; -use tokio::sync::Mutex; - -/// Tracks active log-tail tasks keyed by server UUID. -/// Each value is a shared flag; setting it to `true` signals the background -/// task to stop polling the file. -pub struct LogWatcherState { - pub tokens: Mutex>>, -} - -impl LogWatcherState { - pub fn new() -> Self { - Self { - tokens: Mutex::new(HashMap::new()), - } - } - - /// Create a fresh stop-flag for `server_id`, cancelling the previous one - /// if it existed. Returns the new flag for the spawned task to poll. - pub async fn start(&self, server_id: &str) -> Arc { - let flag = Arc::new(AtomicBool::new(false)); - if let Some(old) = self - .tokens - .lock() - .await - .insert(server_id.to_string(), flag.clone()) - { - old.store(true, Ordering::Relaxed); - } - flag - } - - /// Signal the watcher for `server_id` to stop and remove it from the map. - pub async fn stop(&self, server_id: &str) { - if let Some(flag) = self.tokens.lock().await.remove(server_id) { - flag.store(true, Ordering::Relaxed); - } - } -} diff --git a/src-tauri/src/state/mod.rs b/src-tauri/src/state/mod.rs index 854d1f4..40b5398 100644 --- a/src-tauri/src/state/mod.rs +++ b/src-tauri/src/state/mod.rs @@ -1,4 +1,4 @@ -pub mod log_watcher; +pub mod log_manager; pub mod rcon_pool; pub mod scheduler; pub mod stats_recorder; diff --git a/src/app/backups/page.tsx b/src/app/backups/page.tsx new file mode 100644 index 0000000..5549fb7 --- /dev/null +++ b/src/app/backups/page.tsx @@ -0,0 +1,62 @@ +"use client"; + +import { Archive, Hammer } from "lucide-react"; + +export default function BackupsPage() { + return ( +
+ {/* ── Page header ── */} +
+ +

+ Backups +

+
+ + {/* ── Coming soon ── */} +
+
+ +
+ +
+

+ Coming Soon +

+

+ Scheduled and on-demand backups for your ARK server save data are in active + development. This will include per-server backup schedules, restore points, + and retention policies. +

+
+ +
+ + Next up after the logging system +
+
+
+ ); +} diff --git a/src/app/logs/page.tsx b/src/app/logs/page.tsx new file mode 100644 index 0000000..13f8e74 --- /dev/null +++ b/src/app/logs/page.tsx @@ -0,0 +1,123 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { useSearchParams, useRouter } from "next/navigation"; +import { ScrollText, ChevronDown } from "lucide-react"; +import { useServers } from "@/hooks/useServers"; +import { LogsTab } from "@/components/server/tabs/LogsTab"; +import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; +import type { ServerRow } from "@/lib/db"; + +export default function LogsPage() { + const searchParams = useSearchParams(); + const router = useRouter(); + const { data: servers = [], isLoading } = useServers(); + + const [selectedId, setSelectedId] = useState( + searchParams.get("server") ?? "" + ); + + // Default to first server once loaded if none selected + useEffect(() => { + if (!selectedId && servers.length > 0) { + setSelectedId(servers[0].id); + } + }, [servers, selectedId]); + + const selectedServer: ServerRow | undefined = servers.find( + (s) => s.id === selectedId + ); + + const handleSelect = (id: string) => { + setSelectedId(id); + const url = new URL(window.location.href); + url.searchParams.set("server", id); + router.replace(url.pathname + url.search); + }; + + return ( +
+ {/* ── Page header ── */} +
+ +

+ Logs +

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

+ No servers yet +

+

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

+
+ ) : null} +
+ ); +} diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx index c38d77d..f81f1b2 100644 --- a/src/components/layout/Sidebar.tsx +++ b/src/components/layout/Sidebar.tsx @@ -5,13 +5,14 @@ import { usePathname } from "next/navigation"; import { LayoutDashboard, Network, + ScrollText, + Archive, Bell, Settings, } from "lucide-react"; import { cn } from "@/lib/utils"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { LokiIcon } from "@/components/shared/LokiIcon"; -import { useServers } from "@/hooks/useServers"; interface NavItem { href: string; @@ -20,22 +21,49 @@ interface NavItem { exact?: boolean; } -const NAV_ITEMS: NavItem[] = [ - { href: "/", icon: LayoutDashboard, label: "Dashboard", exact: true }, - { href: "/clusters", icon: Network, label: "Clusters" }, - { href: "/notifications", icon: Bell, label: "Notifications" }, - { href: "/settings", icon: Settings, label: "Settings" }, +const TOP_NAV: NavItem[] = [ + { href: "/", icon: LayoutDashboard, label: "Dashboard", exact: true }, + { href: "/clusters", icon: Network, label: "Clusters" }, + { href: "/logs", icon: ScrollText, label: "Logs" }, + { href: "/backups", icon: Archive, label: "Backups" }, ]; +const BOTTOM_NAV: NavItem[] = [ + { href: "/notifications", icon: Bell, label: "Notifications" }, + { href: "/settings", icon: Settings, label: "Settings" }, +]; + +function NavLink({ item, pathname }: { item: NavItem; pathname: string }) { + const active = item.exact ? pathname === item.href : pathname.startsWith(item.href); + return ( + + + + + + + + {item.label} + + + ); +} + export function Sidebar() { const pathname = usePathname(); - const { data: servers = [] } = useServers(); - const runningCount = servers.filter((s) => s.status === "running").length; - - function isActive(item: NavItem): boolean { - if (item.exact) return pathname === item.href; - return pathname.startsWith(item.href); - } return (
-
- {NAV_ITEMS.map((item) => { - const active = isActive(item); - return ( - - - - - - - - {item.label} - - - ); - })} + {/* Top nav items */} +
+ {TOP_NAV.map((item) => ( + + ))}
- {/* Running server count badge */} -
- - -
-
0 ? "var(--neon-green)" : "var(--text-subtle)", - boxShadow: runningCount > 0 ? "var(--glow-green)" : "none", - }} - /> - {runningCount > 0 && ( - - {runningCount > 9 ? "9+" : runningCount} - - )} -
- - - {runningCount > 0 ? `${runningCount} server${runningCount !== 1 ? "s" : ""} running` : "No servers running"} - - + {/* Spacer */} +
+ + {/* Bottom nav items (Notifications + Settings pinned to bottom) */} +
+ {BOTTOM_NAV.map((item) => ( + + ))}
); diff --git a/src/components/server/tabs/LogsTab.tsx b/src/components/server/tabs/LogsTab.tsx index 41baf76..24b18ac 100644 --- a/src/components/server/tabs/LogsTab.tsx +++ b/src/components/server/tabs/LogsTab.tsx @@ -2,13 +2,17 @@ import { useState, useRef, useEffect, useCallback } from "react"; import { - Eye, EyeOff, Copy, Trash2, Search, X, ChevronDown, + Copy, Trash2, Search, X, ChevronDown, FileText, FolderOpen, + MessageSquare, AlertTriangle, RefreshCw, Archive, ChevronRight, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { tauriCmd } from "@/lib/tauri-commands"; import { useTauriEvent } from "@/hooks/useTauriEvent"; import type { ServerRow } from "@/lib/db"; +import type { + ArchivedLogInfo, CrashInfo, CrashReport, ChatLogInfo, +} from "@/lib/tauri-commands"; interface Props { server: ServerRow; @@ -21,6 +25,7 @@ interface LogLine { } type LevelFilter = "all" | "warning" | "error"; +type LogView = "live" | "archive" | "crashes" | "chat"; let _id = 0; @@ -40,28 +45,48 @@ function levelBg(level: LogLine["level"]): string { } } -/** Derive the ASA ShooterGame.log path from the server install path. */ function logPath(installPath: string): string { - // Works on both Linux and Windows because path.join isn't available here. - // installPath already ends without a slash in practice. const sep = installPath.includes("\\") ? "\\" : "/"; return `${installPath}${sep}ShooterGame${sep}Saved${sep}Logs${sep}ShooterGame.log`; } -export function LogsTab({ server }: Props) { - const [watching, setWatching] = useState(false); +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +} + +// --------------------------------------------------------------------------- +// Live log panel +// --------------------------------------------------------------------------- + +function LivePanel({ server }: { server: ServerRow }) { const [lines, setLines] = useState([]); const [filter, setFilter] = useState("all"); const [search, setSearch] = useState(""); const [autoScroll, setAutoScroll] = useState(true); - + const [ready, setReady] = useState(false); const logRef = useRef(null); - const eventName = `log://line/${server.id}`; - // Tauri event subscription — fires whenever Rust emits a new log line - useTauriEvent<{ line: string; level: string }>(eventName, (payload) => { + const backfillEvent = `log://backfill/${server.id}`; + const lineEvent = `log://line/${server.id}`; + + // Receive batch of existing lines (backfill on watcher start) + useTauriEvent<{ line: string; level: string }[]>(backfillEvent, (payload) => { + const newLines = payload.map((item) => ({ + id: ++_id, + line: item.line, + level: (item.level as LogLine["level"]) ?? "info", + })); + setLines(newLines.slice(-4000)); + setReady(true); + }); + + // Receive individual new lines while tailing + useTauriEvent<{ line: string; level: string }>(lineEvent, (payload) => { + setReady(true); setLines((prev) => [ - ...prev.slice(-999), + ...prev.slice(-3999), { id: ++_id, line: payload.line, @@ -70,6 +95,16 @@ export function LogsTab({ server }: Props) { ]); }); + // Auto-start watcher on mount + useEffect(() => { + const path = logPath(server.install_path); + tauriCmd.watchServerLog(server.id, path).catch(() => null); + return () => { + tauriCmd.stopLogWatch(server.id).catch(() => null); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [server.id, server.install_path]); + // Auto-scroll useEffect(() => { if (autoScroll && logRef.current) { @@ -77,46 +112,6 @@ export function LogsTab({ server }: Props) { } }, [lines, autoScroll]); - const startWatching = useCallback(async () => { - const path = logPath(server.install_path); - try { - await tauriCmd.watchServerLog(server.id, path); - setWatching(true); - setLines((prev) => [ - ...prev, - { id: ++_id, line: `── Watching: ${path} ──`, level: "info" }, - ]); - } catch (e) { - setLines((prev) => [ - ...prev, - { id: ++_id, line: `Failed to start watcher: ${e}`, level: "error" }, - ]); - } - }, [server.id, server.install_path]); - - const stopWatching = useCallback(async () => { - await tauriCmd.stopLogWatch(server.id).catch(() => null); - setWatching(false); - setLines((prev) => [ - ...prev, - { id: ++_id, line: "── Log watch stopped ──", level: "info" }, - ]); - }, [server.id]); - - // Stop the watcher when the component unmounts - useEffect(() => { - return () => { - if (watching) { - tauriCmd.stopLogWatch(server.id).catch(() => null); - } - }; - }, [watching, server.id]); - - const copyLog = () => { - const text = visibleLines.map((l) => l.line).join("\n"); - navigator.clipboard.writeText(text).catch(() => null); - }; - const visibleLines = lines.filter((l) => { if (filter === "warning" && l.level === "info") return false; if (filter === "error" && l.level !== "error") return false; @@ -124,29 +119,33 @@ export function LogsTab({ server }: Props) { return true; }); + const copyLog = () => { + const text = visibleLines.map((l) => l.line).join("\n"); + navigator.clipboard.writeText(text).catch(() => null); + }; + return ( -
- {/* ── Toolbar ── */} +
+ {/* Toolbar */}
- {watching ? "Live" : "Idle"} + {ready ? "Live" : "Connecting…"}
- {/* Level filter */} {(["all", "warning", "error"] as LevelFilter[]).map((lvl) => ( ))} - - {!watching ? ( - - ) : ( - - )} - -
- {/* ── Search ── */} + {/* Search */}
- + setSearch(e.target.value)} className="pl-9 h-8 text-sm" - 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)" }} /> {search && ( - )}
- {/* ── Log output ── */} + {/* Log output */}
{visibleLines.length === 0 ? (
- +

- {watching - ? "Waiting for new log lines…" - : "Click \"Watch Log\" to start tailing ShooterGame.log"} + {ready ? "No lines match the current filter" : "Waiting for ShooterGame.log…"}

) : ( visibleLines.map((l) => ( -
- - {l.line} - +
+ {l.line}
)) )} @@ -264,3 +226,506 @@ export function LogsTab({ server }: Props) {
); } + +// --------------------------------------------------------------------------- +// Archive panel +// --------------------------------------------------------------------------- + +function ArchivePanel({ server }: { server: ServerRow }) { + const [archives, setArchives] = useState([]); + const [loading, setLoading] = useState(true); + const [selected, setSelected] = useState(null); + const [lines, setLines] = useState([]); + const [loadingFile, setLoadingFile] = useState(false); + const [search, setSearch] = useState(""); + const [cleanupDays, setCleanupDays] = useState(30); + const [cleanupPending, setCleanupPending] = useState(false); + + const load = useCallback(async () => { + setLoading(true); + try { + const list = await tauriCmd.listArchivedLogs(server.id); + setArchives(list); + } catch { /* ignore */ } + finally { setLoading(false); } + }, [server.id]); + + useEffect(() => { load(); }, [load]); + + const openFile = useCallback(async (info: ArchivedLogInfo) => { + setSelected(info); + setLoadingFile(true); + setLines([]); + try { + const content = await tauriCmd.readArchivedLog(server.id, info.filename, 0, 0); + setLines(content); + } catch { setLines(["[Failed to read file]"]); } + finally { setLoadingFile(false); } + }, [server.id]); + + const deleteFile = useCallback(async (info: ArchivedLogInfo) => { + await tauriCmd.deleteArchivedLog(server.id, info.filename).catch(() => null); + if (selected?.filename === info.filename) { + setSelected(null); + setLines([]); + } + load(); + }, [server.id, selected, load]); + + const doCleanup = useCallback(async () => { + setCleanupPending(true); + await tauriCmd.cleanupLogs(server.id, cleanupDays).catch(() => null); + setCleanupPending(false); + if (selected) { setSelected(null); setLines([]); } + load(); + }, [server.id, cleanupDays, selected, load]); + + const visibleLines = search + ? lines.filter((l) => l.toLowerCase().includes(search.toLowerCase())) + : lines; + + if (selected) { + return ( +
+
+ + {selected.filename} + ({formatBytes(selected.sizeBytes)}) +
+
+ + setSearch(e.target.value)} + className="pl-7 h-7 text-xs w-36" + style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(191,0,255,0.2)", color: "var(--text-primary)" }} + /> +
+ +
+
+
+ {loadingFile ? ( +
+ +
+ ) : visibleLines.length === 0 ? ( +

No lines match

+ ) : ( + visibleLines.map((l, i) => ( +
+ {l} +
+ )) + )} +
+

+ {search ? `${visibleLines.length} of ${lines.length} lines` : `${lines.length} lines`} +

+
+ ); + } + + return ( +
+
+ + {archives.length} archived session{archives.length !== 1 ? "s" : ""} + + +
+ Delete older than + + +
+
+ + {loading ? ( +
+ +
+ ) : archives.length === 0 ? ( +
+ +

No archived logs yet

+

Archives are created automatically each time the server starts

+
+ ) : ( +
+ {archives.map((a) => ( +
openFile(a)} + > + +
+

{a.filename}

+

{a.timestamp} · {formatBytes(a.sizeBytes)}

+
+ +
+ ))} +
+ )} +
+ ); +} + +// --------------------------------------------------------------------------- +// Crashes panel +// --------------------------------------------------------------------------- + +function CrashesPanel({ server }: { server: ServerRow }) { + const [crashes, setCrashes] = useState([]); + const [loading, setLoading] = useState(true); + const [selected, setSelected] = useState(null); + const [report, setReport] = useState(null); + const [loadingReport, setLoadingReport] = useState(false); + const [activeFile, setActiveFile] = useState(null); + + const load = useCallback(async () => { + setLoading(true); + try { + const list = await tauriCmd.listCrashes(server.install_path); + setCrashes(list); + } catch { /* ignore */ } + finally { setLoading(false); } + }, [server.install_path]); + + useEffect(() => { load(); }, [load]); + + const openCrash = useCallback(async (crash: CrashInfo) => { + setSelected(crash); + setReport(null); + setActiveFile(null); + setLoadingReport(true); + try { + const r = await tauriCmd.readCrashReport(server.install_path, crash.folderName); + setReport(r); + if (r.files.length > 0) setActiveFile(r.files[0].name); + } catch { /* ignore */ } + finally { setLoadingReport(false); } + }, [server.install_path]); + + if (selected) { + const fileContent = report?.files.find((f) => f.name === activeFile)?.content ?? ""; + return ( +
+
+ + {selected.folderName} +
+ {loadingReport ? ( +
+ +
+ ) : report ? ( +
+ {/* File tabs */} +
+ {report.files.map((f) => ( + + ))} +
+
+ {fileContent} +
+
+ ) : ( +

Failed to load crash report

+ )} +
+ ); + } + + return ( +
+
+ + {crashes.length} crash report{crashes.length !== 1 ? "s" : ""} + + +
+ + {loading ? ( +
+ +
+ ) : crashes.length === 0 ? ( +
+ +

No crash reports found

+
+ ) : ( +
+ {crashes.map((c) => ( +
openCrash(c)} + > + +
+

{c.folderName}

+

+ {c.timestamp} + {c.hasCallStack && · has call stack} + · {c.files.length} file{c.files.length !== 1 ? "s" : ""} +

+
+ +
+ ))} +
+ )} +
+ ); +} + +// --------------------------------------------------------------------------- +// Chat panel +// --------------------------------------------------------------------------- + +function ChatPanel({ server }: { server: ServerRow }) { + const [chatLogs, setChatLogs] = useState([]); + const [loading, setLoading] = useState(true); + const [selected, setSelected] = useState(null); + const [lines, setLines] = useState([]); + const [loadingFile, setLoadingFile] = useState(false); + const [search, setSearch] = useState(""); + + const load = useCallback(async () => { + setLoading(true); + try { + const list = await tauriCmd.listChatLogs(server.id); + setChatLogs(list); + } catch { /* ignore */ } + finally { setLoading(false); } + }, [server.id]); + + useEffect(() => { load(); }, [load]); + + const openFile = useCallback(async (info: ChatLogInfo) => { + setSelected(info); + setLoadingFile(true); + setLines([]); + try { + const content = await tauriCmd.readChatLog(server.id, info.filename, 0, 0); + setLines(content); + } catch { setLines(["[Failed to read file]"]); } + finally { setLoadingFile(false); } + }, [server.id]); + + // Auto-open today's log if available + useEffect(() => { + if (chatLogs.length > 0 && !selected) { + openFile(chatLogs[0]); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [chatLogs]); + + const visibleLines = search + ? lines.filter((l) => l.toLowerCase().includes(search.toLowerCase())) + : lines; + + return ( +
+ {/* Day selector */} +
+ {loading ? ( + + ) : chatLogs.length === 0 ? ( +

No chat logs yet — chat is captured when RCON is connected

+ ) : ( + chatLogs.map((cl) => ( + + )) + )} + +
+ + {selected && ( + <> +
+ + setSearch(e.target.value)} + className="pl-9 h-8 text-sm" + style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(191,0,255,0.2)", color: "var(--text-primary)" }} + /> + {search && ( + + )} +
+ +
+ {loadingFile ? ( +
+ +
+ ) : visibleLines.length === 0 ? ( +
+ +

+ {search ? "No lines match" : "No chat messages recorded yet"} +

+
+ ) : ( + visibleLines.map((l, i) => ( +
+ {l} +
+ )) + )} +
+ +

+ {search ? `${visibleLines.length} of ${lines.length} messages` : `${lines.length} messages`} +

+ + )} +
+ ); +} + +// --------------------------------------------------------------------------- +// Main LogsTab +// --------------------------------------------------------------------------- + +const VIEW_TABS: { value: LogView; label: string; icon: React.ComponentType<{ className?: string; style?: React.CSSProperties }> }[] = [ + { value: "live", label: "Live", icon: FileText }, + { value: "archive", label: "Archive", icon: Archive }, + { value: "crashes", label: "Crashes", icon: AlertTriangle }, + { value: "chat", label: "Chat", icon: MessageSquare }, +]; + +export function LogsTab({ server }: Props) { + const [view, setView] = useState("live"); + + return ( +
+ {/* Sub-tab bar */} +
+ {VIEW_TABS.map(({ value, label, icon: Icon }) => { + const active = view === value; + return ( + + ); + })} +
+ +
+
+ + {/* Active panel */} + {view === "live" && } + {view === "archive" && } + {view === "crashes" && } + {view === "chat" && } +
+ ); +} diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index 2a9e136..23a3062 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -104,6 +104,47 @@ export interface RconLogLine { kind: "command" | "response" | "chat" | "system" | "error"; } +export interface ArchivedLogInfo { + filename: string; + sizeBytes: number; + timestamp: string; + fullPath: string; +} + +export interface CrashInfo { + folderName: string; + timestamp: string; + hasCallStack: boolean; + files: string[]; + fullPath: string; +} + +export interface CrashFile { + name: string; + content: string; +} + +export interface CrashReport { + folderName: string; + files: CrashFile[]; +} + +export interface ChatLogInfo { + filename: string; + date: string; + sizeBytes: number; + fullPath: string; +} + +export interface LogStats { + shootergameArchiveCount: number; + shootergameTotalBytes: number; + chatLogCount: number; + chatTotalBytes: number; + crashCount: number; + storageRoot: string; +} + /** Emitted on rcon://status/{id} and rcon://status-any when connection state changes. */ export interface RconStatusPayload { serverId: string; @@ -361,6 +402,34 @@ export const tauriCmd = { invoke("watch_server_log", { serverId, logPath }), stopLogWatch: (serverId: string) => invoke("stop_log_watch", { serverId }), + // Log archive + listArchivedLogs: (serverId: string) => + invoke("list_archived_logs", { serverId }), + readArchivedLog: (serverId: string, filename: string, offset: number, limit: number) => + invoke("read_archived_log", { serverId, filename, offset, limit }), + deleteArchivedLog: (serverId: string, filename: string) => + invoke("delete_archived_log", { serverId, filename }), + + // Crash reports + listCrashes: (installPath: string) => + invoke("list_crashes", { installPath }), + readCrashReport: (installPath: string, folderName: string) => + invoke("read_crash_report", { installPath, folderName }), + + // Chat logs + listChatLogs: (serverId: string) => + invoke("list_chat_logs", { serverId }), + readChatLog: (serverId: string, filename: string, offset: number, limit: number) => + invoke("read_chat_log", { serverId, filename, offset, limit }), + + // Log maintenance + cleanupLogs: (serverId: string, olderThanDays: number) => + invoke("cleanup_logs", { serverId, olderThanDays }), + getLogStats: (serverId: string) => + invoke("get_log_stats", { serverId }), + getLogStorageRoot: () => + invoke("get_log_storage_root"), + // Config / INI /** Read GameUserSettings.ini and Game.ini from the server's install path. */ readServerConfig: (installPath: string) => From 1da17657396e1144953ca74ba3df33113c77cbd3 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 8 Jun 2026 08:15:08 -0500 Subject: [PATCH 02/15] feat: add server name to StartServerParams and enhance OverviewTab with install folder access - Added serverName to StartServerParams for better logging context. - Updated OverviewTab to include a button for opening the server's install folder. - Enhanced network info section with server UUID display. --- src-tauri/src/commands/logs.rs | 159 ++++- src-tauri/src/commands/scheduler.rs | 1 + src-tauri/src/commands/server.rs | 4 +- src-tauri/src/commands/system.rs | 2 +- src-tauri/src/lib.rs | 10 +- src-tauri/src/state/log_manager.rs | 138 ++++- src/app/logs/page.tsx | 17 +- src/app/servers/detail/page.tsx | 18 +- src/components/server/ServerCard.tsx | 1 + src/components/server/tabs/LogsTab.tsx | 684 +++++++++++---------- src/components/server/tabs/OverviewTab.tsx | 25 +- src/lib/tauri-commands.ts | 27 +- 12 files changed, 668 insertions(+), 418 deletions(-) diff --git a/src-tauri/src/commands/logs.rs b/src-tauri/src/commands/logs.rs index 922bdcf..17d61e1 100644 --- a/src-tauri/src/commands/logs.rs +++ b/src-tauri/src/commands/logs.rs @@ -197,20 +197,25 @@ pub async fn delete_archived_log( // Crash commands // --------------------------------------------------------------------------- -/// List crash reports from the server's Saved/Crashes directory. +/// List crash reports from the server's central crash storage. #[tauri::command] pub async fn list_crashes( - install_path: String, + app: tauri::AppHandle, + server_id: String, ) -> Result, String> { - let crashes_dir = format!("{}/ShooterGame/Saved/Crashes", install_path); - let path = std::path::Path::new(&crashes_dir); + let dir = match LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("crashes")) + { + Some(d) => d, + None => return Ok(vec![]), + }; - if !path.exists() { + if !dir.exists() { return Ok(vec![]); } let mut crashes: Vec = Vec::new(); - let mut read_dir = tokio::fs::read_dir(&path) + let mut read_dir = tokio::fs::read_dir(&dir) .await .map_err(|e| format!("Failed to read crashes dir: {e}"))?; @@ -226,7 +231,6 @@ pub async fn list_crashes( let folder_name = entry.file_name().to_string_lossy().to_string(); let full_path = entry.path().to_string_lossy().to_string(); - // Collect file names in the crash folder. let mut files: Vec = Vec::new(); let mut has_call_stack = false; @@ -243,34 +247,29 @@ pub async fn list_crashes( files.sort(); let timestamp = folder_name_to_timestamp(&folder_name); - - crashes.push(CrashInfo { - folder_name, - timestamp, - has_call_stack, - files, - full_path, - }); + crashes.push(CrashInfo { folder_name, timestamp, has_call_stack, files, full_path }); } - // Newest first. crashes.sort_by(|a, b| b.folder_name.cmp(&a.folder_name)); Ok(crashes) } -/// Read all readable (non-binary) files from a crash folder. +/// Read all readable (non-binary) files from a crash folder in central storage. #[tauri::command] pub async fn read_crash_report( - install_path: String, + app: tauri::AppHandle, + server_id: String, folder_name: String, ) -> Result { if folder_name.contains('/') || folder_name.contains('\\') || folder_name.contains("..") { return Err("Invalid folder name".to_string()); } - let crashes_dir = format!("{}/ShooterGame/Saved/Crashes", install_path); - let folder_path = std::path::Path::new(&crashes_dir).join(&folder_name); + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("crashes")) + .ok_or("Log storage not configured")?; + let folder_path = dir.join(&folder_name); if !folder_path.exists() { return Err("Crash folder not found".to_string()); } @@ -283,28 +282,128 @@ pub async fn read_crash_report( while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { let name = entry.file_name().to_string_lossy().to_string(); let lower = name.to_lowercase(); - - // Skip binary files (.dmp, .png, .jpg). - if lower.ends_with(".dmp") - || lower.ends_with(".png") - || lower.ends_with(".jpg") - || lower.ends_with(".bin") - { + if lower.ends_with(".dmp") || lower.ends_with(".png") || lower.ends_with(".jpg") || lower.ends_with(".bin") { continue; } - let content = tokio::fs::read_to_string(entry.path()) .await .unwrap_or_else(|_| "[binary or unreadable file]".to_string()); - files.push(CrashFile { name, content }); } files.sort_by(|a, b| a.name.cmp(&b.name)); - Ok(CrashReport { folder_name, files }) } +/// Delete a crash report folder from central storage. +#[tauri::command] +pub async fn delete_crash_report( + app: tauri::AppHandle, + server_id: String, + folder_name: String, +) -> Result<(), String> { + if folder_name.contains('/') || folder_name.contains('\\') || folder_name.contains("..") { + return Err("Invalid folder name".to_string()); + } + + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("crashes")) + .ok_or("Log storage not configured")?; + + tokio::fs::remove_dir_all(dir.join(&folder_name)) + .await + .map_err(|e| format!("Failed to delete crash report: {e}")) +} + +// --------------------------------------------------------------------------- +// Other log commands (secondary engine logs collected at server start) +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OtherLogInfo { + pub filename: String, + pub size_bytes: u64, + pub timestamp: String, + pub full_path: String, +} + +/// List secondary log files collected to central storage (non-ShooterGame logs). +#[tauri::command] +pub async fn list_other_logs( + app: tauri::AppHandle, + server_id: String, +) -> Result, String> { + let dir = match LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("other")) + { + Some(d) => d, + None => return Ok(vec![]), + }; + + if !dir.exists() { + return Ok(vec![]); + } + + let mut entries: Vec = Vec::new(); + let mut read_dir = tokio::fs::read_dir(&dir) + .await + .map_err(|e| format!("Failed to read other logs dir: {e}"))?; + + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let name = entry.file_name().to_string_lossy().to_string(); + if !name.ends_with(".log") { + continue; + } + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + let timestamp = extract_timestamp_from_filename(&name); + entries.push(OtherLogInfo { + filename: name, + size_bytes: meta.len(), + timestamp, + full_path: entry.path().to_string_lossy().to_string(), + }); + } + + entries.sort_by(|a, b| b.filename.cmp(&a.filename)); + Ok(entries) +} + +/// Read lines from an other log file. +#[tauri::command] +pub async fn read_other_log( + app: tauri::AppHandle, + server_id: String, + filename: String, + offset: usize, + limit: usize, +) -> Result, String> { + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("other")) + .ok_or("Log storage not configured")?; + + if filename.contains('/') || filename.contains('\\') || filename.contains("..") { + return Err("Invalid filename".to_string()); + } + + let path = dir.join(&filename); + let content = tokio::fs::read_to_string(&path) + .await + .map_err(|e| format!("Failed to read log: {e}"))?; + + let lines: Vec = content + .lines() + .skip(offset) + .take(if limit == 0 { usize::MAX } else { limit }) + .map(|l| l.to_string()) + .collect(); + + Ok(lines) +} + // --------------------------------------------------------------------------- // Chat log commands // --------------------------------------------------------------------------- diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index e3a9c7a..35272bc 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -360,6 +360,7 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE fn entry_to_start_params(entry: &crate::state::scheduler::ScheduleEntry) -> StartServerParams { StartServerParams { server_id: entry.server_id.clone(), + server_name: entry.server_name.clone(), install_path: entry.install_path.clone(), map_path: entry.map_path.clone(), port: entry.port, diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 9c2088a..9b1018e 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -92,6 +92,8 @@ fn filter_steam_noise(s: &str) -> String { #[serde(rename_all = "camelCase")] pub struct StartServerParams { pub server_id: String, + /// Human-readable server name — used only for log archiving context. + pub server_name: String, /// Absolute path to the server install directory. pub install_path: String, /// ASA map identifier, e.g. "TheIsland_WP". @@ -321,7 +323,7 @@ async fn inner_start_server_with_state( // Archive any existing ShooterGame.log to central LokiASAM log storage before // launching so the fresh session always starts from byte 0. - let did_rotate = LogManagerState::archive_shootergame_log( + let did_rotate = LogManagerState::archive_all_server_logs( app_handle, ¶ms.server_id, ¶ms.install_path, diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs index 47aa5a7..a10e6b0 100644 --- a/src-tauri/src/commands/system.rs +++ b/src-tauri/src/commands/system.rs @@ -444,7 +444,7 @@ pub fn get_platform() -> String { pub async fn open_folder(path: String) -> Result<(), String> { let p = std::path::Path::new(&path); if !p.exists() { - return Err(format!("Path does not exist: {path}")); + std::fs::create_dir_all(p).map_err(|e| format!("Could not create directory: {e}"))?; } #[cfg(target_os = "linux")] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index aedbc72..e52191f 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -133,13 +133,6 @@ pub fn run() { ); } - // 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 ────────────────────────────────────────── // If a second instance is launched, focus the existing window and exit. @@ -441,6 +434,9 @@ pub fn run() { commands::logs::delete_archived_log, commands::logs::list_crashes, commands::logs::read_crash_report, + commands::logs::delete_crash_report, + commands::logs::list_other_logs, + commands::logs::read_other_log, commands::logs::list_chat_logs, commands::logs::read_chat_log, commands::logs::cleanup_logs, diff --git a/src-tauri/src/state/log_manager.rs b/src-tauri/src/state/log_manager.rs index 4a45660..88a5e16 100644 --- a/src-tauri/src/state/log_manager.rs +++ b/src-tauri/src/state/log_manager.rs @@ -78,49 +78,95 @@ impl LogManagerState { Some(Self::logs_root(app)?.join(server_id)) } - /// Archive the current ShooterGame.log for `server_id` to central storage. - /// Called by `inner_start_server` before the server process is spawned. - /// Returns true if the log was archived or didn't exist; false on error. - pub async fn archive_shootergame_log( + /// Archive ALL log and crash data from the server install directory to central + /// storage before each server launch. Handles: + /// - ShooterGame.log → {server_id}/shootergame/ShooterGame_{ts}.log + /// - Other *.log files in Saved/Logs/ → {server_id}/other/{name}_{ts}.log + /// - Crash folders in Saved/Crashes/ → {server_id}/crashes/{folder}/ + /// + /// Returns true if the main log was cleanly handled (or absent). + pub async fn archive_all_server_logs( app: &tauri::AppHandle, server_id: &str, install_path: &str, ) -> bool { + let timestamp = current_timestamp_str(); + let server_dir = Self::server_logs_dir(app, server_id); + + // ── ShooterGame.log ────────────────────────────────────────────────── let current_log = format!( "{}/ShooterGame/Saved/Logs/ShooterGame.log", install_path ); - - if tokio::fs::metadata(¤t_log).await.is_err() { - return true; // no log to archive — fresh install - } - - let Some(dest_dir) = Self::server_logs_dir(app, server_id) - .map(|d| d.join("shootergame")) else { - // Bootstrap not set up yet; fall back to deleting the old log so - // the new session always starts from byte 0. - return tokio::fs::remove_file(¤t_log).await.is_ok(); + let main_ok = if tokio::fs::metadata(¤t_log).await.is_ok() { + let ok = if let Some(dest_dir) = server_dir.as_ref().map(|d| d.join("shootergame")) { + let _ = tokio::fs::create_dir_all(&dest_dir).await; + let dest = dest_dir.join(format!("ShooterGame_{timestamp}.log")); + move_file(¤t_log, &dest).await + } else { + false + }; + if !ok { + // Fall back to delete so the new session starts at byte 0. + tokio::fs::remove_file(¤t_log).await.is_ok() + } else { + true + } + } else { + true // no prior log — fresh install }; - if tokio::fs::create_dir_all(&dest_dir).await.is_err() { - return tokio::fs::remove_file(¤t_log).await.is_ok(); + // ── Other *.log files in Saved/Logs/ ──────────────────────────────── + let logs_src_dir = format!("{}/ShooterGame/Saved/Logs", install_path); + if let Ok(mut rd) = tokio::fs::read_dir(&logs_src_dir).await { + if let Some(other_dir) = server_dir.as_ref().map(|d| d.join("other")) { + let _ = tokio::fs::create_dir_all(&other_dir).await; + while let Ok(Some(entry)) = rd.next_entry().await { + let name = entry.file_name().to_string_lossy().to_string(); + // Skip ShooterGame.log (handled above) and our own archives. + if name == "ShooterGame.log" || name.starts_with("ShooterGame_") { + continue; + } + if !name.ends_with(".log") { + continue; + } + let stem = name.trim_end_matches(".log"); + let dest = other_dir.join(format!("{stem}_{timestamp}.log")); + let src = entry.path().to_string_lossy().to_string(); + let _ = move_file(&src, &dest).await; + } + } } - let timestamp = current_timestamp_str(); - let archive_name = format!("ShooterGame_{timestamp}.log"); - let dest = dest_dir.join(&archive_name); - - if tokio::fs::rename(¤t_log, &dest).await.is_ok() { - true - } else { - // rename across filesystems fails — copy then delete - if tokio::fs::copy(¤t_log, &dest).await.is_ok() { - let _ = tokio::fs::remove_file(¤t_log).await; - true - } else { - tokio::fs::remove_file(¤t_log).await.is_ok() + // ── Crash folders in Saved/Crashes/ ───────────────────────────────── + let crashes_src = format!("{}/ShooterGame/Saved/Crashes", install_path); + if let Ok(mut rd) = tokio::fs::read_dir(&crashes_src).await { + if let Some(crashes_dir) = server_dir.as_ref().map(|d| d.join("crashes")) { + let _ = tokio::fs::create_dir_all(&crashes_dir).await; + while let Ok(Some(entry)) = rd.next_entry().await { + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + if !meta.is_dir() { + continue; + } + let folder_name = entry.file_name().to_string_lossy().to_string(); + let dest = crashes_dir.join(&folder_name); + // If destination already exists (same crash already moved), skip. + if dest.exists() { + continue; + } + let src = entry.path().to_string_lossy().to_string(); + // Try rename first, then recursive copy+delete. + if tokio::fs::rename(&src, &dest).await.is_err() { + copy_dir_and_remove(&src, &dest).await; + } + } } } + + main_ok } /// Append a chat line to today's chat log file. @@ -149,6 +195,40 @@ impl LogManagerState { } } +// --------------------------------------------------------------------------- +// File/directory helpers +// --------------------------------------------------------------------------- + +/// Move a file: try rename first (fast, same filesystem); fall back to copy+delete. +async fn move_file(src: &str, dest: &std::path::Path) -> bool { + if tokio::fs::rename(src, dest).await.is_ok() { + return true; + } + if tokio::fs::copy(src, dest).await.is_ok() { + let _ = tokio::fs::remove_file(src).await; + true + } else { + false + } +} + +/// Recursively copy a directory then remove the source. +async fn copy_dir_and_remove(src: &str, dest: &std::path::Path) { + let src_path = std::path::Path::new(src); + if let Err(_) = tokio::fs::create_dir_all(dest).await { + return; + } + let mut rd = match tokio::fs::read_dir(src_path).await { + Ok(r) => r, + Err(_) => return, + }; + while let Ok(Some(entry)) = rd.next_entry().await { + let dest_file = dest.join(entry.file_name()); + let _ = tokio::fs::copy(entry.path(), &dest_file).await; + } + let _ = tokio::fs::remove_dir_all(src_path).await; +} + // --------------------------------------------------------------------------- // Tail task // --------------------------------------------------------------------------- diff --git a/src/app/logs/page.tsx b/src/app/logs/page.tsx index 13f8e74..d3d7029 100644 --- a/src/app/logs/page.tsx +++ b/src/app/logs/page.tsx @@ -17,7 +17,6 @@ export default function LogsPage() { searchParams.get("server") ?? "" ); - // Default to first server once loaded if none selected useEffect(() => { if (!selectedId && servers.length > 0) { setSelectedId(servers[0].id); @@ -36,9 +35,9 @@ export default function LogsPage() { }; return ( -
+
{/* ── Page header ── */} -
+
- {/* ── Server selector (sticky) ── */} + {/* ── Server selector ── */}
@@ -101,12 +100,14 @@ export default function LogsPage() { )}
- {/* ── Log viewer ── */} + {/* ── Log viewer — fills remaining height ── */} {selectedServer ? ( - +
+ +
) : !isLoading && servers.length === 0 ? (
diff --git a/src/app/servers/detail/page.tsx b/src/app/servers/detail/page.tsx index 4ca5642..ee73ac0 100644 --- a/src/app/servers/detail/page.tsx +++ b/src/app/servers/detail/page.tsx @@ -128,7 +128,7 @@ export default function ServerDetailPage() { // 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 ── */}
+ ))} + + ); +} + +// --------------------------------------------------------------------------- +// Scroll-to-bottom banner +// --------------------------------------------------------------------------- + +function ScrollBanner({ onClick }: { onClick: () => void }) { + return ( +
+ + Live tail paused — click to scroll to bottom +
+ ); +} + // --------------------------------------------------------------------------- // Live log panel // --------------------------------------------------------------------------- @@ -64,15 +137,11 @@ function LivePanel({ server }: { server: ServerRow }) { const [lines, setLines] = useState([]); const [filter, setFilter] = useState("all"); const [search, setSearch] = useState(""); - const [autoScroll, setAutoScroll] = useState(true); const [ready, setReady] = useState(false); + const [scrolledUp, setScrolledUp] = useState(false); const logRef = useRef(null); - const backfillEvent = `log://backfill/${server.id}`; - const lineEvent = `log://line/${server.id}`; - - // Receive batch of existing lines (backfill on watcher start) - useTauriEvent<{ line: string; level: string }[]>(backfillEvent, (payload) => { + useTauriEvent<{ line: string; level: string }[]>(`log://backfill/${server.id}`, (payload) => { const newLines = payload.map((item) => ({ id: ++_id, line: item.line, @@ -82,105 +151,90 @@ function LivePanel({ server }: { server: ServerRow }) { setReady(true); }); - // Receive individual new lines while tailing - useTauriEvent<{ line: string; level: string }>(lineEvent, (payload) => { + useTauriEvent<{ line: string; level: string }>(`log://line/${server.id}`, (payload) => { setReady(true); setLines((prev) => [ ...prev.slice(-3999), - { - id: ++_id, - line: payload.line, - level: (payload.level as LogLine["level"]) ?? "info", - }, + { id: ++_id, line: payload.line, level: (payload.level as LogLine["level"]) ?? "info" }, ]); }); // Auto-start watcher on mount useEffect(() => { - const path = logPath(server.install_path); - tauriCmd.watchServerLog(server.id, path).catch(() => null); - return () => { - tauriCmd.stopLogWatch(server.id).catch(() => null); - }; + tauriCmd.watchServerLog(server.id, logPath(server.install_path)).catch(() => null); + return () => { tauriCmd.stopLogWatch(server.id).catch(() => null); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [server.id, server.install_path]); - // Auto-scroll + // Auto-scroll when not scrolled up useEffect(() => { - if (autoScroll && logRef.current) { + if (!scrolledUp && logRef.current) { logRef.current.scrollTop = logRef.current.scrollHeight; } - }, [lines, autoScroll]); + }, [lines, scrolledUp]); + + const handleScroll = useCallback(() => { + const el = logRef.current; + if (!el) return; + const atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 50; + setScrolledUp(!atBottom); + }, []); + + const scrollToBottom = useCallback(() => { + if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; + setScrolledUp(false); + }, []); const visibleLines = lines.filter((l) => { - if (filter === "warning" && l.level === "info") return false; - if (filter === "error" && l.level !== "error") return false; + if (!matchesFilter(l.level, filter)) return false; if (search && !l.line.toLowerCase().includes(search.toLowerCase())) return false; return true; }); - const copyLog = () => { - const text = visibleLines.map((l) => l.line).join("\n"); - navigator.clipboard.writeText(text).catch(() => null); - }; + const openLogsFolder = useCallback(async () => { + const root = await tauriCmd.getLogStorageRoot().catch(() => ""); + if (root) tauriCmd.openFolder(`${root}/${server.id}`).catch(() => null); + }, [server.id]); return ( -
+
{/* Toolbar */}
- + {ready ? "Live" : "Connecting…"}
-
- {(["all", "warning", "error"] as LevelFilter[]).map((lvl) => ( - - ))} - - - +
{/* Search */} -
+
- {/* Log output */} -
- {visibleLines.length === 0 ? ( -
- -

- {ready ? "No lines match the current filter" : "Waiting for ShooterGame.log…"} -

-
- ) : ( - visibleLines.map((l) => ( -
- {l.line} + {/* Log output — fills remaining height */} +
+
+ {visibleLines.length === 0 ? ( +
+ +

+ {ready ? "No lines match the current filter" : "Waiting for ShooterGame.log…"} +

- )) - )} + ) : ( + visibleLines.map((l) => ( +
+ {l.line} +
+ )) + )} +
+ {scrolledUp && }
-

- Showing {visibleLines.length} of {lines.length} lines +

+ {visibleLines.length} of {lines.length} lines {search ? ` matching "${search}"` : ""} - {filter !== "all" ? ` (${filter}+)` : ""} + {filter !== "all" ? ` · ${filter} only` : ""}

); } // --------------------------------------------------------------------------- -// Archive panel +// Archive panel (ShooterGame archives + other logs) // --------------------------------------------------------------------------- function ArchivePanel({ server }: { server: ServerRow }) { const [archives, setArchives] = useState([]); + const [otherLogs, setOtherLogs] = useState([]); const [loading, setLoading] = useState(true); - const [selected, setSelected] = useState(null); + const [selected, setSelected] = useState<{ filename: string; type: "shootergame" | "other" } | null>(null); const [lines, setLines] = useState([]); const [loadingFile, setLoadingFile] = useState(false); const [search, setSearch] = useState(""); + const [filter, setFilter] = useState("all"); const [cleanupDays, setCleanupDays] = useState(30); const [cleanupPending, setCleanupPending] = useState(false); const load = useCallback(async () => { setLoading(true); try { - const list = await tauriCmd.listArchivedLogs(server.id); - setArchives(list); + const [sg, other] = await Promise.all([ + tauriCmd.listArchivedLogs(server.id), + tauriCmd.listOtherLogs(server.id), + ]); + setArchives(sg); + setOtherLogs(other); } catch { /* ignore */ } finally { setLoading(false); } }, [server.id]); useEffect(() => { load(); }, [load]); - const openFile = useCallback(async (info: ArchivedLogInfo) => { - setSelected(info); + const openFile = useCallback(async (filename: string, type: "shootergame" | "other") => { + setSelected({ filename, type }); setLoadingFile(true); setLines([]); try { - const content = await tauriCmd.readArchivedLog(server.id, info.filename, 0, 0); + const content = type === "shootergame" + ? await tauriCmd.readArchivedLog(server.id, filename, 0, 0) + : await tauriCmd.readOtherLog(server.id, filename, 0, 0); setLines(content); } catch { setLines(["[Failed to read file]"]); } finally { setLoadingFile(false); } }, [server.id]); - const deleteFile = useCallback(async (info: ArchivedLogInfo) => { - await tauriCmd.deleteArchivedLog(server.id, info.filename).catch(() => null); - if (selected?.filename === info.filename) { - setSelected(null); - setLines([]); - } + const deleteFile = useCallback(async (filename: string, type: "shootergame" | "other") => { + if (type === "shootergame") await tauriCmd.deleteArchivedLog(server.id, filename).catch(() => null); + // other logs don't have a delete command yet — leave them (or add one later) + if (selected?.filename === filename) { setSelected(null); setLines([]); } load(); }, [server.id, selected, load]); @@ -276,135 +340,143 @@ function ArchivePanel({ server }: { server: ServerRow }) { setCleanupPending(true); await tauriCmd.cleanupLogs(server.id, cleanupDays).catch(() => null); setCleanupPending(false); - if (selected) { setSelected(null); setLines([]); } + setSelected(null); setLines([]); load(); - }, [server.id, cleanupDays, selected, load]); + }, [server.id, cleanupDays, load]); - const visibleLines = search - ? lines.filter((l) => l.toLowerCase().includes(search.toLowerCase())) - : lines; + const openLogsFolder = useCallback(async () => { + const root = await tauriCmd.getLogStorageRoot().catch(() => ""); + if (root) tauriCmd.openFolder(`${root}/${server.id}`).catch(() => null); + }, [server.id]); + + // Apply level filter to archive lines + const visibleLines = lines.filter((l) => { + const level = classifyLine(l); + if (!matchesFilter(level, filter)) return false; + if (search && !l.toLowerCase().includes(search.toLowerCase())) return false; + return true; + }); if (selected) { return ( -
-
- - {selected.filename} - ({formatBytes(selected.sizeBytes)}) -
-
- - setSearch(e.target.value)} - className="pl-7 h-7 text-xs w-36" - style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(191,0,255,0.2)", color: "var(--text-primary)" }} - /> -
-
-
- {loadingFile ? ( -
- -
- ) : visibleLines.length === 0 ? ( -

No lines match

- ) : ( - visibleLines.map((l, i) => ( -
- {l} -
- )) - )} +
+ + setSearch(e.target.value)} className="pl-9 h-8 text-sm" style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(191,0,255,0.2)", color: "var(--text-primary)" }} /> + {search && }
-

- {search ? `${visibleLines.length} of ${lines.length} lines` : `${lines.length} lines`} +

+
+ {loadingFile ? ( +
+ ) : visibleLines.length === 0 ? ( +

No lines match

+ ) : ( + visibleLines.map((l, i) => { + const level = classifyLine(l); + return ( +
+ {l} +
+ ); + }) + )} +
+
+

+ {search || filter !== "all" ? `${visibleLines.length} of ${lines.length} lines` : `${lines.length} lines`}

); } + const totalFiles = archives.length + otherLogs.length; + return ( -
-
+
+
- {archives.length} archived session{archives.length !== 1 ? "s" : ""} + {totalFiles} file{totalFiles !== 1 ? "s" : ""} +
Delete older than - setCleanupDays(Number(e.target.value))} className="h-7 text-xs rounded px-2" style={{ background: "rgba(0,0,0,0.4)", border: "1px solid rgba(191,0,255,0.2)", color: "var(--text-primary)" }}> {[7, 14, 30, 60, 90].map((d) => )} -
- {loading ? ( -
- -
- ) : archives.length === 0 ? ( -
- -

No archived logs yet

-

Archives are created automatically each time the server starts

-
- ) : ( -
- {archives.map((a) => ( -
openFile(a)} - > - -
-

{a.filename}

-

{a.timestamp} · {formatBytes(a.sizeBytes)}

+
+ {loading ? ( +
+ ) : totalFiles === 0 ? ( +
+ +

No archived logs yet

+

Archives are created each time the server starts

+
+ ) : ( + <> + {/* ShooterGame archives */} + {archives.length > 0 && ( +
+

ShooterGame Sessions

+ {archives.map((a) => ( +
openFile(a.filename, "shootergame")}> + +
+

{a.filename}

+

{a.timestamp} · {formatBytes(a.sizeBytes)}

+
+ +
+ ))}
- -
- ))} -
- )} + )} + + {/* Other logs */} + {otherLogs.length > 0 && ( +
+

Other Server Logs

+ {otherLogs.map((o) => ( +
openFile(o.filename, "other")}> + +
+

{o.filename}

+

{o.timestamp} · {formatBytes(o.sizeBytes)}

+
+
+ ))} +
+ )} + + )} +
); } @@ -424,11 +496,11 @@ function CrashesPanel({ server }: { server: ServerRow }) { const load = useCallback(async () => { setLoading(true); try { - const list = await tauriCmd.listCrashes(server.install_path); + const list = await tauriCmd.listCrashes(server.id); setCrashes(list); } catch { /* ignore */ } finally { setLoading(false); } - }, [server.install_path]); + }, [server.id]); useEffect(() => { load(); }, [load]); @@ -438,50 +510,51 @@ function CrashesPanel({ server }: { server: ServerRow }) { setActiveFile(null); setLoadingReport(true); try { - const r = await tauriCmd.readCrashReport(server.install_path, crash.folderName); + const r = await tauriCmd.readCrashReport(server.id, crash.folderName); setReport(r); if (r.files.length > 0) setActiveFile(r.files[0].name); } catch { /* ignore */ } finally { setLoadingReport(false); } - }, [server.install_path]); + }, [server.id]); + + const deleteCrash = useCallback(async (crash: CrashInfo) => { + await tauriCmd.deleteCrashReport(server.id, crash.folderName).catch(() => null); + if (selected?.folderName === crash.folderName) { setSelected(null); setReport(null); } + load(); + }, [server.id, selected, load]); + + const openCrashFolder = useCallback(async () => { + const root = await tauriCmd.getLogStorageRoot().catch(() => ""); + if (root) tauriCmd.openFolder(`${root}/${server.id}/crashes`).catch(() => null); + }, [server.id]); if (selected) { const fileContent = report?.files.find((f) => f.name === activeFile)?.content ?? ""; return ( -
-
+
+
- {selected.folderName} + {selected.folderName} +
{loadingReport ? ( -
+
) : report ? ( -
- {/* File tabs */} -
+
+
{report.files.map((f) => ( - ))}
-
+
{fileContent}
@@ -493,48 +566,49 @@ function CrashesPanel({ server }: { server: ServerRow }) { } return ( -
-
+
+
{crashes.length} crash report{crashes.length !== 1 ? "s" : ""} +
- {loading ? ( -
- -
- ) : crashes.length === 0 ? ( -
- -

No crash reports found

-
- ) : ( -
- {crashes.map((c) => ( -
openCrash(c)} - > - -
-

{c.folderName}

-

- {c.timestamp} - {c.hasCallStack && · has call stack} - · {c.files.length} file{c.files.length !== 1 ? "s" : ""} -

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

No crash reports found

+
+ ) : ( +
+ {crashes.map((c) => ( +
openCrash(c)}> + +
+

{c.folderName}

+

+ {c.timestamp} + {c.hasCallStack && · has call stack} + · {c.files.length} file{c.files.length !== 1 ? "s" : ""} +

+
+ +
- -
- ))} -
- )} + ))} +
+ )} +
); } @@ -573,11 +647,8 @@ function ChatPanel({ server }: { server: ServerRow }) { finally { setLoadingFile(false); } }, [server.id]); - // Auto-open today's log if available useEffect(() => { - if (chatLogs.length > 0 && !selected) { - openFile(chatLogs[0]); - } + if (chatLogs.length > 0 && !selected) openFile(chatLogs[0]); // eslint-disable-next-line react-hooks/exhaustive-deps }, [chatLogs]); @@ -586,25 +657,15 @@ function ChatPanel({ server }: { server: ServerRow }) { : lines; return ( -
- {/* Day selector */} -
+
+
{loading ? ( ) : chatLogs.length === 0 ? ( -

No chat logs yet — chat is captured when RCON is connected

+

No chat logs yet — captured when RCON is connected

) : ( chatLogs.map((cl) => ( - @@ -617,47 +678,30 @@ function ChatPanel({ server }: { server: ServerRow }) { {selected && ( <> -
+
- setSearch(e.target.value)} - className="pl-9 h-8 text-sm" - style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(191,0,255,0.2)", color: "var(--text-primary)" }} - /> - {search && ( - - )} + setSearch(e.target.value)} className="pl-9 h-8 text-sm" style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(191,0,255,0.2)", color: "var(--text-primary)" }} /> + {search && }
- -
- {loadingFile ? ( -
- -
- ) : visibleLines.length === 0 ? ( -
- -

- {search ? "No lines match" : "No chat messages recorded yet"} -

-
- ) : ( - visibleLines.map((l, i) => ( -
- {l} +
+
+ {loadingFile ? ( +
+ ) : visibleLines.length === 0 ? ( +
+ +

{search ? "No lines match" : "No chat messages recorded yet"}

- )) - )} + ) : ( + visibleLines.map((l, i) => ( +
+ {l} +
+ )) + )} +
- -

+

{search ? `${visibleLines.length} of ${lines.length} messages` : `${lines.length} messages`}

@@ -681,10 +725,10 @@ export function LogsTab({ server }: Props) { const [view, setView] = useState("live"); return ( -
+
{/* Sub-tab bar */}
{VIEW_TABS.map(({ value, label, icon: Icon }) => { @@ -707,25 +751,15 @@ export function LogsTab({ server }: Props) { ); })} -
- -
- {/* Active panel */} - {view === "live" && } - {view === "archive" && } - {view === "crashes" && } - {view === "chat" && } + {/* Active panel — fills remaining height */} +
+ {view === "live" && } + {view === "archive" && } + {view === "crashes" && } + {view === "chat" && } +
); } diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index 1654550..9c192d9 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -4,7 +4,7 @@ import React, { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { Play, Square, RotateCcw, Users, Cpu, MemoryStick, Clock, - Save, RefreshCw, ArrowUp, Loader2, X, BarChart2, + Save, RefreshCw, ArrowUp, Loader2, X, BarChart2, FolderOpen, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { @@ -475,6 +475,7 @@ export function OverviewTab({ server }: Props) { const enabledModIds = mods.filter((m) => m.enabled === 1).map((m) => m.mod_id); const params: StartServerParams = { serverId: server.id, + serverName: server.name, installPath: server.install_path, mapPath: map?.mapPath ?? "TheIsland_WP", port: server.port, @@ -809,7 +810,7 @@ export function OverviewTab({ server }: Props) {
- {/* ── Network info ── */} + {/* ── Network / install info ── */}

Network

@@ -825,6 +826,26 @@ export function OverviewTab({ server }: Props) {
))}
+ +
+
+
Server UUID
+
{server.id}
+
+ +
{/* ── Player list ── */} diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index 23a3062..c5e3bbf 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -50,6 +50,8 @@ export interface ServerStatus { */ export interface StartServerParams { serverId: string; + /** Human-readable server name — used for log context only. */ + serverName: string; installPath: string; /** ASA map identifier, e.g. "TheIsland_WP". */ mapPath: string; @@ -129,6 +131,13 @@ export interface CrashReport { files: CrashFile[]; } +export interface OtherLogInfo { + filename: string; + sizeBytes: number; + timestamp: string; + fullPath: string; +} + export interface ChatLogInfo { filename: string; date: string; @@ -410,11 +419,19 @@ export const tauriCmd = { deleteArchivedLog: (serverId: string, filename: string) => invoke("delete_archived_log", { serverId, filename }), - // Crash reports - listCrashes: (installPath: string) => - invoke("list_crashes", { installPath }), - readCrashReport: (installPath: string, folderName: string) => - invoke("read_crash_report", { installPath, folderName }), + // Crash reports (stored in central LokiASAM logs folder) + listCrashes: (serverId: string) => + invoke("list_crashes", { serverId }), + readCrashReport: (serverId: string, folderName: string) => + invoke("read_crash_report", { serverId, folderName }), + deleteCrashReport: (serverId: string, folderName: string) => + invoke("delete_crash_report", { serverId, folderName }), + + // Other server logs (secondary engine logs collected at startup) + listOtherLogs: (serverId: string) => + invoke("list_other_logs", { serverId }), + readOtherLog: (serverId: string, filename: string, offset: number, limit: number) => + invoke("read_other_log", { serverId, filename, offset, limit }), // Chat logs listChatLogs: (serverId: string) => From e01baed88609bf39296dd5455b86efa03bd50a23 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 8 Jun 2026 08:46:08 -0500 Subject: [PATCH 03/15] feat: enhance log management by implementing last session log loading and archiving on server state changes --- src-tauri/src/commands/server.rs | 45 +++++++------ src/components/server/tabs/LogsTab.tsx | 88 ++++++++++++++++++++------ 2 files changed, 93 insertions(+), 40 deletions(-) diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 9b1018e..4d3f5f8 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -321,14 +321,6 @@ async fn inner_start_server_with_state( cmd.env_remove("PYTHONPATH"); } - // Archive any existing ShooterGame.log to central LokiASAM log storage before - // launching so the fresh session always starts from byte 0. - let did_rotate = LogManagerState::archive_all_server_logs( - app_handle, - ¶ms.server_id, - ¶ms.install_path, - ).await; - let mut child = match cmd.spawn() { Ok(c) => c, Err(e) => { @@ -413,6 +405,7 @@ async fn inner_start_server_with_state( // ── Intentional stop ───────────────────────────────────────────────── if was_intentional { app_state.running_servers.lock().unwrap().remove(&sid); + LogManagerState::archive_all_server_logs(&handle_clone, &sid, &install_path_watcher).await; emit_status(&handle_clone, &ServerStatus { server_id: sid, status: "stopped".into(), pid: None, uptime_seconds: None, error: None, @@ -423,6 +416,7 @@ async fn inner_start_server_with_state( // ── Runtime crash (was confirmed running) ──────────────────────────── if confirmed_clone.load(Ordering::Relaxed) { app_state.running_servers.lock().unwrap().remove(&sid); + LogManagerState::archive_all_server_logs(&handle_clone, &sid, &install_path_watcher).await; emit_status(&handle_clone, &ServerStatus { server_id: sid, status: "crashed".into(), pid: None, uptime_seconds: None, error: None, @@ -461,6 +455,7 @@ async fn inner_start_server_with_state( // ── Genuine start failure ───────────────────────────────────────────── app_state.running_servers.lock().unwrap().remove(&sid); + LogManagerState::archive_all_server_logs(&handle_clone, &sid, &install_path_watcher).await; let cleaned = strip_ansi(raw_stderr.trim()); let filtered = filter_steam_noise(&cleaned); let trimmed = if filtered.len() > 800 { @@ -604,11 +599,8 @@ async fn inner_start_server_with_state( }; // ── 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. + // Rotation happens on stop/crash/startup, so by the time the server + // starts there is no pre-existing ShooterGame.log. Read from byte 0. let file = loop { if Instant::now() >= deadline { return; } @@ -626,12 +618,6 @@ async fn inner_start_server_with_state( } }; - let mut file = file; - 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(); @@ -862,11 +848,14 @@ pub async fn scan_running_servers( servers: Vec, ) -> Result, String> { let mut results = Vec::new(); + let mut to_rotate: Vec<(String, String)> = Vec::new(); for entry in servers { let pid = find_server_process(&entry.install_path); if let Some(pid) = pid { + // Keep a copy of install_path for the watcher closure before it's moved. + let install_path_watcher = entry.install_path.clone(); { let mut registry = state.running_servers.lock().unwrap(); registry.insert( @@ -902,6 +891,10 @@ pub async fn scan_running_servers( app_state.running_servers.lock().unwrap().remove(&sid); + // Rotate logs before announcing the status change so the + // frontend can display the archived last-session log immediately. + LogManagerState::archive_all_server_logs(&handle, &sid, &install_path_watcher).await; + let status = if was_intentional { "stopped" } else { "crashed" }; let payload = ServerStatus { server_id: sid.clone(), @@ -920,11 +913,20 @@ pub async fn scan_running_servers( } } }); + } else { + // Not running — schedule for startup rotation. + to_rotate.push((entry.server_id.clone(), entry.install_path.clone())); } results.push(ScanResult { server_id: entry.server_id, pid }); } + // Rotate all stopped servers before returning so the scan-complete signal + // only reaches the frontend after logs are already in central storage. + for (server_id, install_path) in to_rotate { + LogManagerState::archive_all_server_logs(&app_handle, &server_id, &install_path).await; + } + Ok(results) } @@ -1164,6 +1166,11 @@ pub async fn graceful_stop_server( pool.chat_poll_active.lock().await.remove(&server_id); pool.player_cache.lock().await.remove(&server_id); + // Rotate logs now that the process is confirmed dead. Covers servers that + // were found running at startup (watched by the scan watcher which exits + // cleanly when running_servers is cleared above, bypassing its rotation). + LogManagerState::archive_all_server_logs(&app_handle, &server_id, &install_path).await; + emit_status(&app_handle, &ServerStatus { server_id, status: "stopped".into(), diff --git a/src/components/server/tabs/LogsTab.tsx b/src/components/server/tabs/LogsTab.tsx index d1c9c25..2af0cf8 100644 --- a/src/components/server/tabs/LogsTab.tsx +++ b/src/components/server/tabs/LogsTab.tsx @@ -134,13 +134,34 @@ function ScrollBanner({ onClick }: { onClick: () => void }) { // --------------------------------------------------------------------------- function LivePanel({ server }: { server: ServerRow }) { + const isActive = server.status === "running" || server.status === "starting"; + const [lines, setLines] = useState([]); const [filter, setFilter] = useState("all"); const [search, setSearch] = useState(""); const [ready, setReady] = useState(false); const [scrolledUp, setScrolledUp] = useState(false); + const [lastSessionFilename, setLastSessionFilename] = useState(null); const logRef = useRef(null); + const loadLastSession = useCallback(async () => { + try { + const archives = await tauriCmd.listArchivedLogs(server.id); + if (archives.length === 0) { + setLastSessionFilename(null); + setLines([]); + return; + } + const latest = archives[archives.length - 1]; + setLastSessionFilename(latest.filename); + const content = await tauriCmd.readArchivedLog(server.id, latest.filename, 0, 0); + setLines(content.map((line) => ({ id: ++_id, line, level: classifyLine(line) }))); + } catch { + setLastSessionFilename(null); + setLines([]); + } + }, [server.id]); + useTauriEvent<{ line: string; level: string }[]>(`log://backfill/${server.id}`, (payload) => { const newLines = payload.map((item) => ({ id: ++_id, @@ -159,14 +180,22 @@ function LivePanel({ server }: { server: ServerRow }) { ]); }); - // Auto-start watcher on mount + // Manage watcher vs last-session display based on whether the server is active. useEffect(() => { - tauriCmd.watchServerLog(server.id, logPath(server.install_path)).catch(() => null); - return () => { tauriCmd.stopLogWatch(server.id).catch(() => null); }; + if (isActive) { + setLastSessionFilename(null); + setLines([]); + setReady(false); + tauriCmd.watchServerLog(server.id, logPath(server.install_path)).catch(() => null); + return () => { tauriCmd.stopLogWatch(server.id).catch(() => null); }; + } else { + tauriCmd.stopLogWatch(server.id).catch(() => null); + loadLastSession(); + } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [server.id, server.install_path]); + }, [server.id, isActive]); - // Auto-scroll when not scrolled up + // Auto-scroll on new live lines and when last-session content is first loaded. useEffect(() => { if (!scrolledUp && logRef.current) { logRef.current.scrollTop = logRef.current.scrollHeight; @@ -196,25 +225,36 @@ function LivePanel({ server }: { server: ServerRow }) { if (root) tauriCmd.openFolder(`${root}/${server.id}`).catch(() => null); }, [server.id]); + // Derive toolbar appearance from server state + const toolbarBorder = isActive + ? (ready ? "rgba(0,255,136,0.3)" : "rgba(191,0,255,0.15)") + : "rgba(255,170,68,0.2)"; + const dotStyle = isActive + ? (ready + ? { background: "var(--neon-green)", boxShadow: "0 0 6px var(--neon-green)", animation: "pulse 2s infinite" } + : { background: "var(--text-muted)" as string }) + : { background: "#ffaa44" }; + const statusLabel = isActive + ? (ready ? "Live" : (server.status === "starting" ? "Starting…" : "Connecting…")) + : (lastSessionFilename ? "Last Session" : "No Previous Sessions"); + return (
{/* Toolbar */}
-
-
- - {ready ? "Live" : "Connecting…"} +
+
+ + {statusLabel} + {!isActive && lastSessionFilename && ( + + · {lastSessionFilename} + + )}
@@ -224,9 +264,11 @@ function LivePanel({ server }: { server: ServerRow }) { - + {isActive && ( + + )} @@ -262,7 +304,11 @@ function LivePanel({ server }: { server: ServerRow }) {

- {ready ? "No lines match the current filter" : "Waiting for ShooterGame.log…"} + {isActive + ? "Waiting for ShooterGame.log…" + : lastSessionFilename + ? "No lines match the current filter" + : "No previous session logs found"}

) : ( From 74ae5a27ffe1bf50c8977070d9b0988490c52ed7 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 9 Jun 2026 06:52:28 -0500 Subject: [PATCH 04/15] feat: enhance server management with auto-start and update features - Added new server status values: "update_queued" and "startup_queued". - Updated ServerStatusBadge to reflect new statuses with appropriate labels and colors. - Introduced auto-start toggle in OverviewTab for server settings, allowing servers to start automatically on app launch. - Implemented database migration to add auto_start flag for servers. - Created utility functions for server start/stop operations to streamline code reuse. - Enhanced update handling to include an option for restarting servers after updates. - Updated notification system to provide consolidated updates on server statuses. - Added state management for startup queue to handle sequential server startups. --- src/app/page.tsx | 509 ++++++++++++++---- src/app/settings/page.tsx | 69 ++- src/components/layout/AppShell.tsx | 4 + src/components/layout/StartupQueueManager.tsx | 101 ++++ .../layout/StartupReconciliationManager.tsx | 21 +- .../layout/StartupRecoveryManager.tsx | 183 +++++++ src/components/server/ServerCard.tsx | 337 ++++++------ src/components/server/ServerStatusBadge.tsx | 6 +- src/components/server/tabs/OverviewTab.tsx | 223 +++++--- src/lib/db.ts | 49 +- src/lib/server-utils.ts | 55 ++ src/lib/update-utils.ts | 123 +++-- src/store/useAppStore.ts | 38 ++ 13 files changed, 1333 insertions(+), 385 deletions(-) create mode 100644 src/components/layout/StartupQueueManager.tsx create mode 100644 src/components/layout/StartupRecoveryManager.tsx create mode 100644 src/lib/server-utils.ts diff --git a/src/app/page.tsx b/src/app/page.tsx index 4087af6..468cfd1 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,16 +1,26 @@ "use client"; -import { useEffect, useState, useCallback } from "react"; -import { Plus, Server, Activity, PowerOff, Power, RefreshCw, Upload, ArrowUp, CheckCircle2, Loader2 } from "lucide-react"; +import { useEffect, useState, useCallback, useRef } from "react"; +import { + Plus, Server, Activity, PowerOff, Power, RefreshCw, Upload, + ArrowUp, Loader2, CheckCircle2, AlertTriangle, +} from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; +import { Switch } from "@/components/ui/switch"; +import { Label } from "@/components/ui/label"; +import { + Dialog, DialogContent, DialogDescription, + DialogFooter, DialogHeader, DialogTitle, +} from "@/components/ui/dialog"; import { StatCard } from "@/components/shared/StatCard"; import { ServerCard } from "@/components/server/ServerCard"; import { ImportServerWizard } from "@/components/server/ImportServerWizard"; import { useServers } from "@/hooks/useServers"; -import { getAppSetting, setAppSetting } from "@/lib/db"; +import { getAppSetting, setAppSetting, updateServerStatus } from "@/lib/db"; import { tauriCmd, type UpdateCheckResult } from "@/lib/tauri-commands"; -import { runPerServerUpdateCheck } from "@/lib/update-utils"; +import { runPerServerUpdateCheck, applyUpdateToServer, type ServerUpdateInfo } from "@/lib/update-utils"; +import { buildStartParams } from "@/lib/server-utils"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; import { useQueryClient } from "@tanstack/react-query"; @@ -19,32 +29,33 @@ import { useTauriEvent } from "@/hooks/useTauriEvent"; import { toast } from "sonner"; // --------------------------------------------------------------------------- -// Update status chip +// UpdateStatusChip — Check for Updates button + post-check dialogs // --------------------------------------------------------------------------- -function UpdateStatusChip() { - const [checking, setChecking] = useState(false); - const [updateAvailable, setUpdateAvailable] = useState(false); - const [cachedBuild, setCachedBuild] = useState(""); +interface UpdateStatusChipProps { + servers: ReturnType["data"]; + onUpdateAllClick: () => void; + onUpdatesFound: (updates: ServerUpdateInfo[]) => void; +} + +function UpdateStatusChip({ servers = [], onUpdateAllClick, onUpdatesFound }: UpdateStatusChipProps) { + const queryClient = useQueryClient(); + const [checking, setChecking] = useState(false); const [latestBuild, setLatestBuild] = useState(""); - const [lastChecked, setLastChecked] = useState(""); + const [cachedBuild, setCachedBuild] = useState(""); const load = useCallback(async () => { - const [avail, cached, latest, checked] = await Promise.all([ - getAppSetting("asa_update_available"), + const [cached, latest] = await Promise.all([ getAppSetting("asa_cached_build_id"), getAppSetting("asa_latest_build_id"), - getAppSetting("asa_last_checked"), ]); - setUpdateAvailable(avail === "true"); setCachedBuild(cached ?? ""); setLatestBuild(latest ?? ""); - setLastChecked(checked ?? ""); }, []); useEffect(() => { load(); }, [load]); - // Listen for background check results fired from the Rust scheduler. + // Background check result — refresh state + run per-server check (with toasts). useTauriEvent("asa://update-check", async (payload) => { if ("updateApplied" in payload && payload.updateApplied) { await setAppSetting("asa_update_available", "false"); @@ -60,9 +71,9 @@ 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(); + // Background check: toasts fire per-server, no dialog. + await runPerServerUpdateCheck(false); + queryClient.invalidateQueries({ queryKey: ["servers"] }); } }); @@ -77,81 +88,75 @@ function UpdateStatusChip() { toast.error("Base directory or SteamCMD not configured."); return; } - const sep = baseDir.includes("\\") ? "\\" : "/"; + 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; + const now = new Date().toISOString(); await Promise.all([ setAppSetting("asa_cached_build_id", newBuild), setAppSetting("asa_latest_build_id", newBuild), setAppSetting("asa_last_checked", now), ]); - await runPerServerUpdateCheck(); + // Manual check: silent mode suppresses per-server toasts; we show dialog. + const summary = await runPerServerUpdateCheck(true); + queryClient.invalidateQueries({ queryKey: ["servers"] }); load(); - if (cacheUpdated) { + + if (summary.allWithUpdates.length > 0) { + // Show the updates-found dialog to the user. + onUpdatesFound(summary.allWithUpdates); + } else { + toast.success("All servers are up to date."); + } + + // Only notify Discord/email if the cache actually changed. + if (newBuild && newBuild !== oldBuild) { 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.`, + body: `Cache updated to build ${newBuild}. Check for server updates.`, severity: "info", }); - } else { - toast.success(`Cache is up to date (build ${newBuild}).`); } } catch (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", - }); + toast.error("Update check failed", { description: String(e) }); } finally { setChecking(false); } }; - const busy = checking; - const neverChecked = !lastChecked; + const serversWithUpdates = (servers ?? []).filter((s) => s.update_available === 1); + const anyStarting = (servers ?? []).some( + (s) => s.update_available === 1 && s.status === "starting" + ); return (
- {updateAvailable ? ( -
0 && ( +
- ) : !neverChecked ? ( -
- - Up to date -
- ) : null} + Update All ({serversWithUpdates.length}) + + )}
); } -export default function DashboardPage() { +// --------------------------------------------------------------------------- +// UpdatesFoundDialog — shown after manual "Check for Updates" finds results +// --------------------------------------------------------------------------- + +interface UpdatesFoundDialogProps { + open: boolean; + onOpenChange: (v: boolean) => void; + updates: ServerUpdateInfo[]; + onUpdateAll: (restartAfterUpdate: boolean) => void; +} + +function UpdatesFoundDialog({ open, onOpenChange, updates, onUpdateAll }: UpdatesFoundDialogProps) { + const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); + const anyRunning = updates.some((s) => s.status === "running"); + const anyStarting = updates.some((s) => s.status === "starting"); + + return ( + + + + + + {updates.length === 1 ? "Update Available" : `${updates.length} Updates Available`} + + + The following servers have updates ready to apply from the shared cache. + + + + {/* Server list */} +
+ {updates.map((s) => ( +
+
+ {s.name} + {s.installedBuild !== "unknown" && ( + + {s.installedBuild} → {s.cachedBuild} + + )} +
+ + {s.status} + +
+ ))} +
+ + {/* Warnings */} + {anyRunning && ( +
+ + Running servers will be stopped to apply the update. +
+ )} + {anyStarting && ( +
+ + One or more servers are currently starting. Their startup will be cancelled to apply the update. +
+ )} + + {/* Restart toggle */} + {(anyRunning || anyStarting) && ( +
+ + +
+ )} + + + + + +
+
+ ); +} + +// --------------------------------------------------------------------------- +// UpdateAllDialog — confirmation before applying updates from the header button +// --------------------------------------------------------------------------- + +interface UpdateAllDialogProps { + open: boolean; + onOpenChange: (v: boolean) => void; + updates: ServerUpdateInfo[]; + anyStarting: boolean; + onConfirm: (restartAfterUpdate: boolean) => void; +} + +function UpdateAllDialog({ open, onOpenChange, updates, anyStarting, onConfirm }: UpdateAllDialogProps) { + const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); + const anyRunning = updates.some((s) => s.status === "running"); + + return ( + + + + + + Update All Servers + + + Updates will be applied sequentially from the shared cache. + + +
+ {updates.map((s) => ( +
+
+ {s.name} + {s.installedBuild !== "unknown" && ( + + {s.installedBuild} → {s.cachedBuild} + + )} +
+ + {s.status} + +
+ ))} +
+ + {anyRunning && ( +
+ + Running servers will be stopped to apply the update. +
+ )} + {anyStarting && ( +
+ + One or more servers are currently starting. Their startup will be cancelled to apply the update. +
+ )} + + {(anyRunning || anyStarting) && ( +
+ + +
+ )} + + + + + +
+
+ ); +} + +// --------------------------------------------------------------------------- +// DashboardPage +// --------------------------------------------------------------------------- + +export default function DashboardPage() { const { data: servers = [], isLoading } = useServers(); - const { setShowNewServerWizard } = useAppStore(); - const [showImport, setShowImport] = useState(false); + const { setShowNewServerWizard, enqueueStartup } = useAppStore(); + const [showImport, setShowImport] = useState(false); + const [showUpdateAllDialog, setShowUpdateAllDialog] = useState(false); + const [showUpdatesFoundDialog, setShowUpdatesFoundDialog] = useState(false); + const [pendingUpdates, setPendingUpdates] = useState([]); + const [updatingAll, setUpdatingAll] = useState(false); const queryClient = useQueryClient(); const total = servers.length; const running = servers.filter((s) => s.status === "running").length; const stopped = total - running; + // Build the ServerUpdateInfo list from the live servers data. + const serversWithUpdates: ServerUpdateInfo[] = servers + .filter((s) => s.update_available === 1) + .map((s) => ({ + id: s.id, + name: s.name, + status: s.status, + installedBuild: "—", + cachedBuild: "—", + })); + + const anyUpdatesStarting = serversWithUpdates.some((s) => s.status === "starting"); + + // ── Update All handler ──────────────────────────────────────────────────── + + const runUpdateAll = useCallback(async (restartAfterUpdate: boolean) => { + if (updatingAll) return; + setUpdatingAll(true); + + const targets = servers.filter((s) => s.update_available === 1); + if (targets.length === 0) { setUpdatingAll(false); return; } + + try { + // First: mark all targets with their initial status. + // Active server = first in list → "updating" + // Rest → "update_queued" + const [first, ...rest] = targets; + + if (rest.length > 0) { + await Promise.all( + rest.map((s) => updateServerStatus(s.id, "update_queued", null)) + ); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + + // Process sequentially + for (const server of targets) { + await updateServerStatus(server.id, "updating", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + + const wasRunning = server.status === "running" || server.status === "starting"; + + try { + await applyUpdateToServer( + server.id, + server.name, + server.install_path, + wasRunning, + restartAfterUpdate, + (msg) => toast.info(msg, { id: `update-${server.id}` }), + ); + } catch (err) { + if (err && typeof err === "object" && "restartNeeded" in err) { + // Queue this server for startup after update + await updateServerStatus(server.id, "startup_queued", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + const serverData = servers.find((s) => s.id === server.id); + if (serverData) enqueueStartup([serverData.id]); + continue; + } + toast.error(`Failed to update ${server.name}`, { description: String(err) }); + await updateServerStatus(server.id, "stopped", null).catch(() => {}); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + + await updateServerStatus(server.id, "stopped", null).catch(() => {}); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + + toast.success(`Updated ${targets.length} server${targets.length === 1 ? "" : "s"} successfully.`); + } finally { + setUpdatingAll(false); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + }, [servers, updatingAll, queryClient, enqueueStartup]); + return (
{/* ── Page header ── */} @@ -192,7 +511,14 @@ export default function DashboardPage() {

- + setShowUpdateAllDialog(true)} + onUpdatesFound={(updates) => { + setPendingUpdates(updates); + setShowUpdatesFoundDialog(true); + }} + />
)} @@ -313,6 +619,23 @@ export default function DashboardPage() { }} /> )} + + {/* ── Update All confirmation dialog (from header button) ── */} + + + {/* ── Updates found dialog (after manual Check for Updates) ── */} +
); } diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index fe28e11..156841a 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -5,13 +5,16 @@ import { Folder, Terminal, Info, FolderOpen, CheckCircle2, AlertCircle, Loader2, Save, RefreshCw, ArrowUp, Bell, MessageSquare, Mail, Monitor, Send, Download, - Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, + Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, Power, } 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 { + Select, SelectContent, SelectItem, SelectTrigger, SelectValue, +} from "@/components/ui/select"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, @@ -726,7 +729,7 @@ function ServerUpdatesSection() { server.name, server.install_path, server.status === "running", - undefined, + false, ); } catch (err) { // restartNeeded signal — server updated successfully, restart handled inside. @@ -1483,6 +1486,64 @@ function CloseToTraySection() { ); } +// --------------------------------------------------------------------------- +// Startup section +// --------------------------------------------------------------------------- + +type AutoRestartPref = "ask" | "auto" | "never"; + +function StartupSection() { + const [pref, setPref] = useState("ask"); + + useEffect(() => { + getAppSetting("auto_restart_downed").then((v) => { + if (v === "auto" || v === "never") setPref(v); + else setPref("ask"); + }); + }, []); + + const handleChange = async (v: AutoRestartPref) => { + setPref(v); + await setAppSetting("auto_restart_downed", v); + }; + + return ( +
+
+
+ +

+ When the app starts and detects servers that were running during the previous session but + are now offline, LokiASAM can prompt you to restart them, restart them automatically, + or do nothing. +

+ {pref === "never" && ( +

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

+ )} +
+ +
+
+ ); +} + // --------------------------------------------------------------------------- // Tab navigation // --------------------------------------------------------------------------- @@ -1565,6 +1626,10 @@ export default function SettingsPage() { +
+ +
+ {IS_LINUX && (
+ +
diff --git a/src/components/layout/StartupQueueManager.tsx b/src/components/layout/StartupQueueManager.tsx new file mode 100644 index 0000000..d89eb4e --- /dev/null +++ b/src/components/layout/StartupQueueManager.tsx @@ -0,0 +1,101 @@ +"use client"; + +/** + * StartupQueueManager — processes the startup queue sequentially. + * + * Watches the server list and the Zustand startupQueue. When no server is + * currently in the "starting" state and the queue is non-empty, it pops the + * next server and starts it. This ensures servers are started one at a time + * to avoid overloading the host machine. + * + * Queue entries have status = "startup_queued" in the DB so the badge shows. + * When a server is manually started by the user it bypasses this queue entirely. + */ + +import { useEffect, useRef } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { useServers } from "@/hooks/useServers"; +import { useAppStore } from "@/store/useAppStore"; +import { getServer, updateServerStatus } from "@/lib/db"; +import { tauriCmd } from "@/lib/tauri-commands"; +import { buildStartParams } from "@/lib/server-utils"; +import { dispatchNotification } from "@/lib/notifications"; +import { NOTIFICATION_EVENTS } from "@/data/game-data"; +import { toast } from "sonner"; + +export function StartupQueueManager() { + const queryClient = useQueryClient(); + const { data: servers = [] } = useServers(); + const startupQueue = useAppStore((s) => s.startupQueue); + const dequeueNextStartup = useAppStore((s) => s.dequeueNextStartup); + const setNoRetryServer = useAppStore((s) => s.setNoRetryServer); + const startingRef = useRef(false); + + useEffect(() => { + // Guard: don't start another server while one is already starting, + // or if the queue is empty. + const anyStarting = servers.some((s) => s.status === "starting"); + if (anyStarting || startupQueue.length === 0 || startingRef.current) return; + + const nextId = startupQueue[0]; + + // Quick cache check: if the server has been fully deleted, skip immediately. + if (servers.length > 0 && !servers.find((s) => s.id === nextId)) { + dequeueNextStartup(); + return; + } + + startingRef.current = true; + dequeueNextStartup(); + + (async () => { + try { + // Read authoritative status from DB — the TanStack cache may still be + // stale when enqueueStartup fires immediately after a DB write, causing + // the cache-based status check to see "stopped" and silently skip the server. + const server = await getServer(nextId); + + if (!server || server.status !== "startup_queued") { + // Server was cancelled or doesn't exist — skip without error. + return; + } + + await updateServerStatus(server.id, "starting", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + + const params = await buildStartParams(server); + const pid = await tauriCmd.startServer(params); + + await updateServerStatus(server.id, "starting", pid); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } catch (err) { + const raw = typeof err === "string" ? err : String(err); + const isExeMissing = raw.startsWith("exe_missing:"); + const userMsg = isExeMissing ? raw.slice("exe_missing: ".length) : raw; + + // Re-read name for the error notification since we may not have `server` in scope. + const serverName = servers.find((s) => s.id === nextId)?.name ?? nextId; + + if (isExeMissing) setNoRetryServer(nextId); + + await updateServerStatus(nextId, "start-failed", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + + toast.error(`${serverName} failed to start`, { description: userMsg }); + dispatchNotification({ + eventType: NOTIFICATION_EVENTS.SERVER_START_FAILED, + serverId: nextId, + serverName, + title: `${serverName} failed to start`, + body: userMsg, + severity: "error", + }); + } finally { + startingRef.current = false; + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + })(); + }, [servers, startupQueue, dequeueNextStartup, queryClient, setNoRetryServer]); + + return null; +} diff --git a/src/components/layout/StartupReconciliationManager.tsx b/src/components/layout/StartupReconciliationManager.tsx index 9f49e7e..78a9e0e 100644 --- a/src/components/layout/StartupReconciliationManager.tsx +++ b/src/components/layout/StartupReconciliationManager.tsx @@ -8,14 +8,23 @@ import { tauriCmd } from "@/lib/tauri-commands"; export function StartupReconciliationManager() { const queryClient = useQueryClient(); - const { setIsServerScanPending } = useAppStore(); + const { setIsServerScanPending, setPreScanStatuses } = useAppStore(); useEffect(() => { - setIsServerScanPending(true); (async () => { + // Always capture pre-scan statuses and mark the scan complete, even on error. + // StartupRecoveryManager waits for preScanStatuses to be set before it runs. + let servers: Awaited> = []; try { - const servers = await getServers(); + servers = await getServers(); + } catch { + // DB unavailable — proceed with empty snapshot + } + + setPreScanStatuses(Object.fromEntries(servers.map((s) => [s.id, s.status]))); + setIsServerScanPending(true); + try { if (!servers.length) return; const entries = servers.map((s) => ({ serverId: s.id, installPath: s.install_path })); @@ -27,6 +36,10 @@ export function StartupReconciliationManager() { return; } + // States that StartupRecoveryManager handles after the scan — skip them here + // so they aren't wiped by the reconciliation. + const QUEUE_STATES = new Set(["startup_queued", "update_queued"]); + await Promise.all( results.map(async (r) => { const current = servers.find((s) => s.id === r.serverId); @@ -37,7 +50,7 @@ export function StartupReconciliationManager() { await updateServerStatus(r.serverId, "running", r.pid); } } else { - if (current.status !== "stopped") { + if (current.status !== "stopped" && !QUEUE_STATES.has(current.status)) { await updateServerStatus(r.serverId, "stopped", null); } } diff --git a/src/components/layout/StartupRecoveryManager.tsx b/src/components/layout/StartupRecoveryManager.tsx new file mode 100644 index 0000000..5ba0a46 --- /dev/null +++ b/src/components/layout/StartupRecoveryManager.tsx @@ -0,0 +1,183 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { ToggleLeft, ToggleRight } from "lucide-react"; +import { useAppStore } from "@/store/useAppStore"; +import { + getServers, getAppSetting, setAppSetting, updateServerStatus, + type ServerRow, +} from "@/lib/db"; +import { applyUpdateToServer } from "@/lib/update-utils"; +import { + Dialog, DialogContent, DialogDescription, + DialogFooter, DialogHeader, DialogTitle, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; + +export function StartupRecoveryManager() { + const queryClient = useQueryClient(); + const isServerScanPending = useAppStore((s) => s.isServerScanPending); + const preScanStatuses = useAppStore((s) => s.preScanStatuses); + const { enqueueStartup } = useAppStore(); + + const hasRunRef = useRef(false); + const [downedServers, setDownedServers] = useState([]); + const [showDownedDialog, setShowDownedDialog] = useState(false); + const [rememberChoice, setRememberChoice] = useState(false); + + useEffect(() => { + // Wait until reconciliation finishes and pre-scan data is available + if (isServerScanPending || hasRunRef.current || !preScanStatuses) return; + hasRunRef.current = true; + + (async () => { + const servers = await getServers(); + + // --- 1. Re-queue startup_queued servers -------------------------------- + const startupQueued = servers.filter((s) => s.status === "startup_queued"); + if (startupQueued.length > 0) { + enqueueStartup(startupQueued.map((s) => s.id)); + } + + // --- 2. Resume update_queued servers sequentially ---------------------- + const updateQueued = servers.filter((s) => s.status === "update_queued"); + if (updateQueued.length > 0) { + const count = updateQueued.length; + toast.info( + count === 1 + ? `Resuming update for ${updateQueued[0].name}…` + : `Resuming update queue for ${count} servers…`, + ); + (async () => { + for (const server of updateQueued) { + try { + await updateServerStatus(server.id, "updating", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + await applyUpdateToServer(server.id, server.name, server.install_path, false, false); + } catch { + // applyUpdateToServer already dispatches a failure notification + } + await updateServerStatus(server.id, "stopped", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + })(); + } + + // --- 3. Queue auto_start servers that are stopped ---------------------- + const autoStartStopped = servers.filter( + (s) => s.auto_start === 1 && s.status === "stopped", + ); + if (autoStartStopped.length > 0) { + for (const s of autoStartStopped) { + await updateServerStatus(s.id, "startup_queued", null); + } + enqueueStartup(autoStartStopped.map((s) => s.id)); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + + // --- 4. Detect downed servers (were running/starting, now stopped, no auto_start) --- + const RUNNING_STATES = new Set(["running", "starting"]); + const downed = servers.filter( + (s) => + RUNNING_STATES.has(preScanStatuses[s.id] ?? "") && + s.status === "stopped" && + s.auto_start === 0, + ); + + if (downed.length === 0) return; + + const pref = (await getAppSetting("auto_restart_downed")) ?? "ask"; + + if (pref === "auto") { + await enqueueDownedServers(downed, enqueueStartup, queryClient); + } else if (pref === "ask") { + setDownedServers(downed); + setShowDownedDialog(true); + } + // pref === "never" → do nothing + })(); + }, [isServerScanPending, preScanStatuses]); // eslint-disable-line react-hooks/exhaustive-deps + + const handleLeaveOffline = async () => { + setShowDownedDialog(false); + if (rememberChoice) await setAppSetting("auto_restart_downed", "never"); + }; + + const handleRestartNow = async () => { + setShowDownedDialog(false); + if (rememberChoice) await setAppSetting("auto_restart_downed", "auto"); + await enqueueDownedServers(downedServers, enqueueStartup, queryClient); + }; + + return ( + + + + Servers Went Offline + + The following server{downedServers.length > 1 ? "s were" : " was"} running in your last + session but went offline while the app was closed. + + + +
    + {downedServers.map((s) => ( +
  • + {s.name} +
  • + ))} +
+ +
+

Remember my choice

+ +
+ + + + + +
+
+ ); +} + +async function enqueueDownedServers( + servers: ServerRow[], + enqueueStartup: (ids: string[]) => void, + queryClient: ReturnType, +) { + for (const s of servers) { + await updateServerStatus(s.id, "startup_queued", null); + } + enqueueStartup(servers.map((s) => s.id)); + queryClient.invalidateQueries({ queryKey: ["servers"] }); +} diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index 6df0307..e4ae2de 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -21,6 +21,7 @@ import { Terminal, Loader2, X, + Ban, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; @@ -32,6 +33,8 @@ import { DialogTitle, DialogFooter, } from "@/components/ui/dialog"; +import { Switch } from "@/components/ui/switch"; +import { Label } from "@/components/ui/label"; import { CommandOutputPanel, clearOutputBuffer } from "@/components/shared/CommandOutputPanel"; import { ServerStatusBadge } from "./ServerStatusBadge"; import { ServerActionMenu } from "./ServerActionMenu"; @@ -45,6 +48,7 @@ import { getLastBackupTime, getNextScheduledRestart, getAppSetting, + resetServersFromStatus, } from "@/lib/db"; import { applyUpdateToServer } from "@/lib/update-utils"; import { ARK_MAPS, LAUNCH_PARAMETERS, NOTIFICATION_EVENTS } from "@/data/game-data"; @@ -113,11 +117,13 @@ export function ServerCard({ server }: Props) { const [showProgress, setShowProgress] = useState(false); const [showUpdateConfirm, setShowUpdateConfirm] = useState(false); const [autoCheckEnabled, setAutoCheckEnabled] = useState(true); + const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); + const removeFromStartupQueue = useAppStore((s) => s.removeFromStartupQueue); - // Derive update badge directly from the DB column (set by runPerServerUpdateCheck). - const hasUpdateAvailable = server.update_available === 1; + const hasUpdateAvailable = server.update_available === 1; + const isUpdateQueued = server.status === "update_queued"; + const isStartupQueued = server.status === "startup_queued"; - // Force a re-render every 30 s so the uptime counter advances visually. const [, setTick] = useState(0); useEffect(() => { const active = server.status === "running" || server.status === "starting"; @@ -129,13 +135,14 @@ export function ServerCard({ server }: Props) { const mapDisplay = ARK_MAPS.find((m) => m.id === server.map_id)?.displayName ?? server.map_id; - const isRunning = server.status === "running"; - const isTransitioning = ["starting", "stopping", "updating"].includes(server.status); - const isInstalling = server.status === "installing"; - const isUpdating = server.status === "updating"; + const isRunning = server.status === "running"; + const isStarting = server.status === "starting"; + const isTransitioning = ["starting", "stopping", "updating", "update_queued"].includes(server.status); + const isInstalling = server.status === "installing"; + const isUpdating = server.status === "updating"; const isActiveInstall = isInstalling || isUpdating; const isInstallFailed = server.status === "install_failed"; - const isStartFailed = server.status === "start-failed"; + const isStartFailed = server.status === "start-failed"; const isReinstallable = isInstallFailed || isStartFailed; // Load secondary card data (mod count, backup, schedule, auto-check state). @@ -304,6 +311,7 @@ export function ServerCard({ server }: Props) { server.name, server.install_path, wasRunning, + restartAfterUpdate, (msg) => toast.info(msg), ); } catch (err) { @@ -512,179 +520,166 @@ export function ServerCard({ server }: Props) { )} {/* ── Action buttons ── */} -
- {isActiveInstall ? ( - /* Installing/Updating — Cancel and View Progress */ - <> - - - - ) : isReinstallable ? ( - /* Install/Start failed */ - <> -
- - {isInstallFailed ? "Install Failed" : "Start Failed"} -
- {/* 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 && ( + {/* Two non-wrapping groups: left (status-dependent) + right (nav arrow). + This prevents the arrow from shifting when left-side buttons change. */} +
+ + {/* Left: all status-dependent actions */} +
+ {isActiveInstall ? ( + <> - )} - - - ) : isServerScanPending ? ( - - ) : ( - <> - {/* Start / Stop / Force Stop */} - {server.status === "stopping" ? ( - - ) : server.status === "starting" ? ( - ) : isRunning ? ( + + ) : isUpdateQueued ? ( + <> + + Update queued + - ) : ( + + ) : isStartupQueued ? ( + <> + + Startup queued + - )} - - {/* Restart — only shown when fully running */} - {isRunning && ( + + ) : isReinstallable ? ( + <> +
+ + {isInstallFailed ? "Install Failed" : "Start Failed"} +
+ {isStartFailed && !noRetry && ( + + )} - )} + + ) : isServerScanPending ? ( + + ) : ( + <> + {/* Primary status button — always flex-1 so width is consistent */} + {server.status === "stopping" ? ( + + ) : isStarting ? ( + + ) : isRunning ? ( + + ) : ( + + )} - {/* Update — shown only when update is available */} - {hasUpdateAvailable && ( - - )} - - )} - - {/* Right side: optional note + always-visible detail arrow */} -
- {hasUpdateAvailable && !autoCheckEnabled && ( - - Enable auto checks in Settings - + {isRunning && ( + + )} + + {hasUpdateAvailable && ( + + )} + )} -
+ + {/* Right: detail arrow — never moves */} +
{/* ── Update confirmation dialog ── */} @@ -694,10 +689,27 @@ export function ServerCard({ server }: Props) { Apply Server Update? {isRunning - ? `${server.name} is currently running. It will be stopped, updated, and restarted automatically.` + ? `${server.name} is currently running and will be stopped to apply the update.` : `${server.name} will be updated from the shared cache.`} + + {isRunning && ( +
+ + +
+ )} + diff --git a/src/components/server/ServerStatusBadge.tsx b/src/components/server/ServerStatusBadge.tsx index 11831f0..9966578 100644 --- a/src/components/server/ServerStatusBadge.tsx +++ b/src/components/server/ServerStatusBadge.tsx @@ -6,6 +6,8 @@ export type ServerStatusValue = | "running" | "stopping" | "updating" + | "update_queued" + | "startup_queued" | "error" | "crashed" | "installing" @@ -23,7 +25,9 @@ const STATUS_MAP: Record = { running: { label: "Running", color: "var(--neon-green)", pulse: true }, starting: { label: "Starting", color: "var(--neon-cyan)", pulse: true }, stopping: { label: "Shutting Down", color: "#ff6400", pulse: true }, - updating: { label: "Updating", color: "var(--neon-cyan)", pulse: true }, + updating: { label: "Updating", color: "#ffa500", pulse: true }, + update_queued: { label: "Update Queued", color: "#ffa500", pulse: false }, + startup_queued: { label: "Startup Queued", color: "var(--neon-cyan)", pulse: false }, stopped: { label: "Stopped", color: "var(--text-muted)", pulse: false }, error: { label: "Error", color: "var(--neon-red)", pulse: false }, crashed: { label: "Crashed", color: "var(--neon-red)", pulse: false }, diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index 9c192d9..6639719 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -5,6 +5,7 @@ import { useRouter } from "next/navigation"; import { Play, Square, RotateCcw, Users, Cpu, MemoryStick, Clock, Save, RefreshCw, ArrowUp, Loader2, X, BarChart2, FolderOpen, + Zap, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { @@ -14,6 +15,8 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; +import { Switch } from "@/components/ui/switch"; +import { Label } from "@/components/ui/label"; import { ResponsiveContainer, ComposedChart, Area, Line, XAxis, YAxis, CartesianGrid, Tooltip, @@ -25,6 +28,7 @@ import { useAppStore } from "@/store/useAppStore"; import { updateServerStatus, getServerConfig, getServerModCount, getServerMods, getLastBackupTime, getNextScheduledRestart, getAppSetting, insertBackup, + setServerAutoStart, } from "@/lib/db"; import { applyUpdateToServer } from "@/lib/update-utils"; import type { BackupRecord } from "@/lib/tauri-commands"; @@ -300,12 +304,14 @@ function ServerSummaryPanel({ modCount, lastBackup, nextRestart, + onAutoStartChange, }: { server: ServerRow; startTime: number | undefined; modCount: number | null; lastBackup: string | null; nextRestart: string | null; + onAutoStartChange: (v: boolean) => void; }) { const isRunning = server.status === "running" || server.status === "starting"; const currentStartMs = startTime ?? (isRunning ? new Date(server.updated_at).getTime() : null); @@ -327,13 +333,35 @@ function ServerSummaryPanel({ ]; return ( -
- {items.map(({ label, value }) => ( -
-
{label}
-
{value}
+
+
+ {items.map(({ label, value }) => ( +
+
{label}
+
{value}
+
+ ))} +
+ + {/* Auto-start toggle */} +
+ +
+ +

+ Start this server automatically when the app opens +

- ))} +
); } @@ -416,6 +444,7 @@ export function OverviewTab({ server }: Props) { const [showUpdateConfirm, setShowUpdateConfirm] = useState(false); const [applyingUpdate, setApplyingUpdate] = useState(false); const [autoCheckEnabled, setAutoCheckEnabled] = useState(true); + const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); // Per-tile timeframe selectors const [playersTf, setPlayersTf] = useState("Live"); @@ -579,6 +608,7 @@ export function OverviewTab({ server }: Props) { server.name, server.install_path, wasRunning, + restartAfterUpdate, (msg) => toast.info(msg), ); } catch (err) { @@ -638,76 +668,81 @@ export function OverviewTab({ server }: Props) {
{/* ── Quick actions ── */} + {/* Structured as two non-wrapping groups so the right-side buttons + never shift position when the primary status button changes label. */}
- + Actions - {isServerScanPending ? ( - - ) : isStartFailed ? ( - + {/* Left group — status-dependent buttons */} +
+ {isServerScanPending ? ( + + ) : isStartFailed ? ( + <> + + + + ) : server.status === "stopping" ? ( + ) : server.status === "starting" ? ( - - ) : server.status === "stopping" ? ( - - ) : server.status === "starting" ? ( - - ) : isRunning ? ( - - ) : ( - - )} + ) : isRunning ? ( + + ) : ( + + )} - {isRunning && !isServerScanPending && ( - - )} + {isRunning && !isServerScanPending && ( + + )} +
- {hasUpdateAvailable && ( - <> + {/* Right group — persistent buttons that never move */} +
+ {hasUpdateAvailable && ( - {!autoCheckEnabled && ( - - Enable auto checks in Settings - - )} - - )} + )} - + +
{/* ── Chart tiles (2-column) ── */} @@ -770,6 +800,10 @@ export function OverviewTab({ server }: Props) { modCount={modCount} lastBackup={lastBackup} nextRestart={nextRestart} + onAutoStartChange={async (v) => { + await setServerAutoStart(server.id, v); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + }} /> @@ -886,10 +920,27 @@ export function OverviewTab({ server }: Props) { Apply Server Update? {isRunning - ? `${server.name} is currently running. It will be stopped, updated, and restarted automatically.` + ? `${server.name} is currently running and will be stopped to apply the update.` : `${server.name} will be updated from the shared cache.`} + + {isRunning && ( +
+ + +
+ )} + + )} +
+
+ ); +} + // --------------------------------------------------------------------------- // Icon-based toggle (matches the wizard's ToggleRow style) // --------------------------------------------------------------------------- @@ -1596,6 +1642,8 @@ export default function SettingsPage() { hint="Where scheduled and manual backup zips are stored." validateDir /> + +
0 ? cfg.keep : defaultKeep; + } catch { return defaultKeep; } +} + +/** Add a tier flag to a comma-separated tiers string without duplicating. */ +function addTier(existing: string, tier: Tier): string { + const flags = existing ? existing.split(",").filter(Boolean) : []; + if (!flags.includes(tier)) flags.push(tier); + return flags.sort().join(","); +} + +/** Remove a tier flag from a comma-separated tiers string. */ +function removeTier(existing: string, tier: Tier): string { + return (existing ? existing.split(",").filter(Boolean) : []) + .filter((f) => f !== tier) + .join(","); +} + +/** + * TimeShift retention prune. + * + * For the given tier, if the count exceeds `keepCount`, strip the tier flag + * from the oldest excess backups. If a backup then has no tier flags at all, + * delete the file and DB record. + */ +async function pruneByTier( + serverId: string, + backupType: string, + tier: Tier, + keepCount: number, +): Promise { + const backups = await getServerBackupsByType(serverId, backupType); + // Only backups that carry this tier flag, oldest first. + const withTier = backups + .filter((b) => b.tiers.split(",").includes(tier)) + .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()); + + if (withTier.length <= keepCount) return; + + const excess = withTier.slice(0, withTier.length - keepCount); + for (const b of excess) { + const newTiers = removeTier(b.tiers, tier); + if (!newTiers) { + // No tier flags remain — physically delete. + try { await tauriCmd.deleteBackup(b.file_path); } catch { /* best-effort */ } + await deleteBackupRecord(b.id); + } else { + await updateBackupTiers(b.id, newTiers); + } + } +} + +/** + * Try to promote an existing backup to a higher tier instead of creating a new + * archive. Promotion succeeds if there is a backup of the given type whose + * creation timestamp falls within `windowMs` of now. + * + * Returns the promoted backup (with updated tiers) or null if none found. + */ +async function tryPromote( + serverId: string, + backupType: string, + tier: Tier, + windowMs: number, +): Promise { + const backups = await getServerBackupsByType(serverId, backupType); + // Most-recent backup that was created recently enough. + const candidate = backups + .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()) + .find((b) => Date.now() - new Date(b.created_at).getTime() <= windowMs); + + if (!candidate) return null; + + const newTiers = addTier(candidate.tiers, tier); + await updateBackupTiers(candidate.id, newTiers); + return { ...candidate, tiers: newTiers }; +} + +// Promotion window per tier — how recent must an existing backup be to count? +const PROMOTE_WINDOW: Record = { + H: 0, // never promote — always create new hourly + D: 6 * 3600_000, // promote if there's a backup within 6h + W: 24 * 3600_000, // promote if there's a backup within 24h + M: 48 * 3600_000, // promote if there's a backup within 48h +}; + +// --------------------------------------------------------------------------- +// Component +// --------------------------------------------------------------------------- + export function SchedulerManager() { - // Hydrate the Rust scheduler once the component mounts (DB is ready by this point). useEffect(() => { syncSchedulesToRust(); }, []); + // Update player_name_map whenever RCON refreshes the player list. + useTauriEvent<{ serverId?: string; players?: { name: string; playerId: string }[] }>( + "rcon://players-any", + async (payload) => { + if (!payload.serverId || !payload.players?.length) return; + await upsertPlayerNames( + payload.serverId, + payload.players.map((p) => ({ eosId: p.playerId, name: p.name })), + ).catch(() => {}); + } + ); + useTauriEvent("scheduler://fired", async (payload) => { const { scheduleId, serverName, scheduleType, success, error, backupRecord } = payload; - // ── Global cache update check — synthetic entry, not in the schedules table ── + // ── Global update check ───────────────────────────────────────────────── 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"}`); - } + 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) { + // ── Backup schedule types ─────────────────────────────────────────────── + const isBackup = scheduleType === "backup_server" + || scheduleType === "backup_player" + || scheduleType === "backup_full"; + + if (isBackup && success && backupRecord) { + const row = await getScheduleById(scheduleId); + const configJson = row?.config_json ?? "{}"; + const tier = parseTier(configJson); + const keep = parseKeep(configJson, 5); + const bType = backupRecord.backupType; + + // Determine final tiers for the new backup. + let tiers = tier; + + // For D/W/M: if we can promote an existing backup, don't need the one + // Rust just created (it was a "new backup" case, not promotion). + // The Rust always creates a new file; we just tag it accordingly. + if (tier !== "H") { + const window = PROMOTE_WINDOW[tier]; + const promoted = await tryPromote(payload.serverId, bType, tier, window); + if (promoted) { + // A recent backup was promoted — delete the redundant new file Rust created. + try { await tauriCmd.deleteBackup(backupRecord.filePath); } catch { /* ok */ } + // Prune and re-sync without inserting the new record. + await pruneByTier(payload.serverId, bType, tier, keep); + const lastRun = new Date().toISOString(); + const nextDate = row ? getNextCronDate(row.cron_expression) : null; + await updateScheduleRun(scheduleId, lastRun, nextDate?.toISOString() ?? null); + syncSchedulesToRust(); + toast.success(`[${serverName}] ${tier}-tier backup promoted.`); + return; + } + // No recent backup to promote — keep the new file Rust created. + tiers = tier; + } + try { await insertBackup({ id: backupRecord.id, @@ -49,37 +209,45 @@ export function SchedulerManager() { map_id: backupRecord.mapId, triggered_by: backupRecord.triggeredBy, created_at: backupRecord.createdAt, + backup_type: bType, + tiers, + player_eosid: backupRecord.playerEosid ?? null, + player_name: backupRecord.playerName ?? null, }); } catch { - // Non-fatal — backup file was created, just the DB record failed. + // Non-fatal — backup file exists even if DB insert failed. } + + await pruneByTier(payload.serverId, bType, tier, keep); } - // Update last_run / next_run in SQLite so the UI shows correct times. + // ── Update last_run / next_run ────────────────────────────────────────── const lastRun = new Date().toISOString(); try { const row = await getScheduleById(scheduleId); const nextDate = row ? getNextCronDate(row.cron_expression) : null; - const nextRun = nextDate?.toISOString() ?? null; - await updateScheduleRun(scheduleId, lastRun, nextRun); - } catch { - // Non-fatal. - } + await updateScheduleRun(scheduleId, lastRun, nextDate?.toISOString() ?? null); + } catch { /* non-fatal */ } - // Show a toast notification. if (success) { - const labels: Record = { - backup: "Scheduled backup completed", - restart: "Scheduled restart completed", - update: "Scheduled update completed", - broadcast: "Scheduled broadcast sent", - }; - toast.success(`[${serverName}] ${labels[scheduleType] ?? "Schedule fired"}.`); + // Skipped-because-server-stopped: success=true but no backupRecord. + // Don't toast — this is expected behaviour, not an event worth surfacing. + const wasSkipped = isBackup && !backupRecord; + if (!wasSkipped) { + const labels: Record = { + backup_server: "Server backup completed", + backup_player: "Player backups completed", + backup_full: "Full backup completed", + restart: "Scheduled restart completed", + update: "Scheduled update completed", + broadcast: "Scheduled broadcast sent", + }; + toast.success(`[${serverName}] ${labels[scheduleType] ?? "Schedule fired"}.`); + } } else { toast.error(`[${serverName}] Scheduled ${scheduleType} failed: ${error ?? "unknown error"}`); } - // Re-sync so Rust gets the updated next_run_ms from the DB. syncSchedulesToRust(); }); diff --git a/src/components/server/ServerActionMenu.tsx b/src/components/server/ServerActionMenu.tsx index 90f7df4..d98838e 100644 --- a/src/components/server/ServerActionMenu.tsx +++ b/src/components/server/ServerActionMenu.tsx @@ -22,6 +22,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { toast } from "sonner"; import { tauriCmd } from "@/lib/tauri-commands"; +import { ARK_MAPS } from "@/data/game-data"; import { deleteServerRecord, createServer, @@ -331,12 +332,14 @@ export function ServerActionMenu({ server }: Props) { const backupDir = await getAppSetting("backup_dir"); if (!backupDir) { toast.error("Backup directory not configured. Check Settings."); return; } - const record: BackupRecord = await tauriCmd.createBackup( + const mapPath = ARK_MAPS.find((m) => m.id === server.map_id)?.mapPath ?? "TheIsland_WP"; + const record: BackupRecord = await tauriCmd.createServerBackup( server.id, server.name, server.install_path, - backupDir, + mapPath, server.map_id, + backupDir, "manual" ); await insertBackup({ @@ -347,6 +350,10 @@ export function ServerActionMenu({ server }: Props) { map_id: record.mapId, triggered_by: record.triggeredBy, created_at: record.createdAt, + backup_type: "server", + tiers: "", + player_eosid: null, + player_name: null, }); toast.success(`Backup of "${server.name}" completed.`); } catch (err) { diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index e4ae2de..44e5bb5 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -1,6 +1,7 @@ "use client"; import { useState, useEffect } from "react"; +import { useTauriEvent } from "@/hooks/useTauriEvent"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { @@ -118,8 +119,16 @@ export function ServerCard({ server }: Props) { const [showUpdateConfirm, setShowUpdateConfirm] = useState(false); const [autoCheckEnabled, setAutoCheckEnabled] = useState(true); const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); + const [backupProgress, setBackupProgress] = useState<{ active: boolean; percent: number; label: string }>({ + active: false, percent: 0, label: "", + }); const removeFromStartupQueue = useAppStore((s) => s.removeFromStartupQueue); + useTauriEvent<{ percent: number; currentFile: string; label: string }>( + `backup://progress/${server.id}`, + (p) => setBackupProgress({ active: p.percent < 100, percent: p.percent, label: p.label }) + ); + const hasUpdateAvailable = server.update_available === 1; const isUpdateQueued = server.status === "update_queued"; const isStartupQueued = server.status === "startup_queued"; @@ -501,12 +510,27 @@ export function ServerCard({ server }: Props) {
- Backup + {backupProgress.active ? backupProgress.label || "Backing up…" : "Backup"} - {formatRelativeTime(lastBackup)} + {backupProgress.active + ? `${backupProgress.percent.toFixed(0)}%` + : formatRelativeTime(lastBackup) + }
+ {backupProgress.active && ( +
+
+
+ )}
{/* Next restart */} diff --git a/src/components/server/tabs/AutomationTab.tsx b/src/components/server/tabs/AutomationTab.tsx index c284ddd..4d9fbe2 100644 --- a/src/components/server/tabs/AutomationTab.tsx +++ b/src/components/server/tabs/AutomationTab.tsx @@ -38,11 +38,7 @@ import type { ServerRow } from "@/lib/db"; // Types // --------------------------------------------------------------------------- -type ScheduleType = "backup" | "restart" | "broadcast"; - -interface BackupConfig { - // no extra options -} +type ScheduleType = "restart" | "broadcast"; interface RestartConfig { broadcastWarning: boolean; @@ -59,13 +55,11 @@ interface BroadcastConfig { // --------------------------------------------------------------------------- const DEFAULT_CRON: Record = { - backup: CRON_PRESETS[3].cron, // Every 6h restart: "0 6 * * *", // Daily at 6 AM broadcast: CRON_PRESETS[0].cron, // Every hour }; const DEFAULT_CONFIG: Record = { - backup: {} as BackupConfig, 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, }; @@ -379,6 +373,326 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing ); } +// --------------------------------------------------------------------------- +// Backup schedule section — TimeShift tiers per backup type +// --------------------------------------------------------------------------- + +type BackupTier = "H" | "D" | "W" | "M"; +type BackupScheduleType = "backup_server" | "backup_player" | "backup_full"; + +// Fixed cron expressions per tier (not exposed in UI — schedule timing is implicit) +const TIER_FIXED_CRON: Record = { + M: "0 4 1 * *", // monthly — 1st at 4am + W: "0 3 * * 0", // weekly — Sunday 3am + D: "0 2 * * *", // daily — 2am + H: "0 */6 * * *", // hourly — every 6h +}; + +const TIER_DEFAULT_KEEP: Record = { + M: 3, W: 4, D: 7, H: 24, +}; + +const TIER_LABEL: Record = { + M: "monthly", W: "weekly", D: "daily", H: "hourly", +}; + +function findTierSchedule( + schedules: ScheduleRow[], + type: BackupScheduleType, + tier: BackupTier, +): ScheduleRow | null { + return schedules.find((s) => { + if (s.schedule_type !== type) return false; + try { return (JSON.parse(s.config_json ?? "{}").tier ?? "H") === tier; } + catch { return false; } + }) ?? null; +} + +function findFullSchedule(schedules: ScheduleRow[]): ScheduleRow | null { + return schedules.find((s) => s.schedule_type === "backup_full") ?? null; +} + +// --------------------------------------------------------------------------- +// BackupTypeSection — simple keep-count + toggle rows per tier +// --------------------------------------------------------------------------- + +const TIER_ORDER: BackupTier[] = ["M", "W", "D", "H"]; + +type TierState = { keep: number; enabled: boolean }; + +function BackupTypeSection({ + title, scheduleType, serverId, schedules, onRefresh, accentColor, +}: { + title: string; + scheduleType: BackupScheduleType; + serverId: string; + schedules: ScheduleRow[]; + onRefresh: () => void; + accentColor: string; +}) { + const buildState = (): Record => { + const s = {} as Record; + for (const tier of TIER_ORDER) { + const row = findTierSchedule(schedules, scheduleType, tier); + const cfg = row?.config_json ? (() => { try { return JSON.parse(row.config_json); } catch { return {}; } })() : {}; + s[tier] = { keep: cfg.keep ?? TIER_DEFAULT_KEEP[tier], enabled: row ? row.enabled === 1 : false }; + } + return s; + }; + + const [tiers, setTiers] = useState>(buildState); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(false); + + useEffect(() => { setTiers(buildState()); }, [schedules.length, serverId, scheduleType]); + + const patch = (tier: BackupTier, delta: Partial) => + setTiers((s) => ({ ...s, [tier]: { ...s[tier], ...delta } })); + + async function handleSave() { + setSaving(true); + try { + for (const tier of TIER_ORDER) { + const { keep, enabled } = tiers[tier]; + const existing = findTierSchedule(schedules, scheduleType, tier); + const configJson = JSON.stringify({ tier, keep }); + const cron = TIER_FIXED_CRON[tier]; + const nextIso = getNextCronDate(cron)?.toISOString() ?? new Date().toISOString(); + + if (existing) { + await updateScheduleConfig(existing.id, cron, configJson, nextIso); + if (enabled !== (existing.enabled === 1)) await updateScheduleEnabled(existing.id, enabled); + } else if (enabled) { + const newId = await tauriCmd.createSchedule({ serverId, scheduleType, cronExpression: cron, configJson }); + await createSchedule({ id: newId, serverId, scheduleType, cronExpression: cron, enabled: true, configJson }); + await updateScheduleConfig(newId, cron, configJson, nextIso); + } + } + setSaved(true); + setTimeout(() => setSaved(false), 2000); + onRefresh(); + syncSchedulesToRust(); + } catch (e) { + toast.error(`Failed to save ${title}: ${e}`); + } finally { + setSaving(false); + } + } + + return ( +
+

{title}

+ {TIER_ORDER.map((tier) => ( +
+ patch(tier, { keep: Math.max(1, parseInt(e.target.value, 10) || 1) })} + className="w-16 h-8 text-sm text-center shrink-0" + style={{ + background: "rgba(0,0,0,0.4)", + border: `1px solid ${tiers[tier].enabled ? `${accentColor}35` : "rgba(191,0,255,0.15)"}`, + color: "var(--text-primary)", + }} + /> + + {TIER_LABEL[tier]} backups to keep + + +
+ ))} + +
+ ); +} + +// --------------------------------------------------------------------------- +// FullBackupScheduleSection — single keep-count + toggle +// --------------------------------------------------------------------------- + +function FullBackupScheduleSection({ + serverId, schedules, onRefresh, +}: { + serverId: string; + schedules: ScheduleRow[]; + onRefresh: () => void; +}) { + const existing = findFullSchedule(schedules); + const cfg = existing?.config_json ? (() => { try { return JSON.parse(existing.config_json); } catch { return {}; } })() : {}; + + const [keep, setKeep] = useState(cfg.keep ?? 3); + const [enabled, setEnabled] = useState(existing ? existing.enabled === 1 : false); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(false); + + useEffect(() => { + const row = findFullSchedule(schedules); + const c = row?.config_json ? (() => { try { return JSON.parse(row.config_json); } catch { return {}; } })() : {}; + setKeep(c.keep ?? 3); + setEnabled(row ? row.enabled === 1 : false); + }, [schedules.length, serverId]); + + async function handleSave() { + setSaving(true); + try { + const configJson = JSON.stringify({ keep }); + const cron = "0 3 1 * *"; + const nextIso = getNextCronDate(cron)?.toISOString() ?? new Date().toISOString(); + + if (existing) { + await updateScheduleConfig(existing.id, cron, configJson, nextIso); + if (enabled !== (existing.enabled === 1)) await updateScheduleEnabled(existing.id, enabled); + } else if (enabled) { + const newId = await tauriCmd.createSchedule({ serverId, scheduleType: "backup_full", cronExpression: cron, configJson }); + await createSchedule({ id: newId, serverId, scheduleType: "backup_full", cronExpression: cron, enabled: true, configJson }); + await updateScheduleConfig(newId, cron, configJson, nextIso); + } + + setSaved(true); + setTimeout(() => setSaved(false), 2000); + onRefresh(); + syncSchedulesToRust(); + } catch (e) { + toast.error(`Failed to save full backup schedule: ${e}`); + } finally { + setSaving(false); + } + } + + return ( +
+

Full Backups

+
+ setKeep(Math.max(1, parseInt(e.target.value, 10) || 1))} + className="w-16 h-8 text-sm text-center shrink-0" + style={{ + background: "rgba(0,0,0,0.4)", + border: `1px solid ${enabled ? "rgba(255,165,0,0.35)" : "rgba(255,165,0,0.15)"}`, + color: "var(--text-primary)", + }} + /> + + full backups to keep + + +
+

+ Zips the entire install folder — runs monthly on the 1st at 3am. +

+ +
+ ); +} + +// --------------------------------------------------------------------------- +// BackupScheduleSection — groups all three backup type sections +// --------------------------------------------------------------------------- + +function BackupScheduleSection({ + serverId, schedules, onRefresh, +}: { + serverId: string; + schedules: ScheduleRow[]; + onRefresh: () => void; +}) { + return ( +
+ {/* Header */} +
+
+ +
+
+

Backup Schedules

+

+ TimeShift — each tier keeps its own independent set of backups +

+
+
+ +
+ +
+ +
+ +
+
+ ); +} + // --------------------------------------------------------------------------- // AutomationTab // --------------------------------------------------------------------------- @@ -393,12 +707,6 @@ const CARD_DEFS: { title: string; description: string; }[] = [ - { - type: "backup", - icon: HardDrive, - title: "Auto-Backup", - description: "Automatically zip and archive the server's save directory on a schedule.", - }, { type: "restart", icon: RotateCcw, @@ -661,7 +969,10 @@ export function AutomationTab({ server }: Props) { {/* Update automation — uses new per-server settings instead of schedule rows */} - {/* Backup, restart, broadcast — cron-based schedule cards */} + {/* Backup schedules — TimeShift tiers (server, player, full) */} + + + {/* Restart, broadcast — cron-based schedule cards */} {CARD_DEFS.map((def) => ( {/* Collapsible header */}
-

- This will{serverRunning ? " stop the server, " : " "}replace all save files with the backup from{" "} - {formatDate(backup.created_at)} - {serverRunning ? ", then restart the server" : ""}.{" "} + This will{serverRunning ? " stop the server, " : " "}restore the backup from{" "} + {formatHumanDate(backup.created_at)} + {serverRunning ? ", then allow you to restart manually" : ""}.{" "} This cannot be undone.

- -

- {backup.file_path} -

-
- + +
+
+
+ ); +} + +// --------------------------------------------------------------------------- +// Full backup warning dialog +// --------------------------------------------------------------------------- + +function FullBackupWarningDialog({ + estimatedSize, onConfirm, onNeverShow, onCancel, +}: { + estimatedSize: number; + onConfirm: () => void; + onNeverShow: () => void; + onCancel: () => void; +}) { + return ( +
+
+
+
- Cancel + +
+

+ Full Backup Warning +

+
+

+ A full backup copies the entire server installation (~ + {formatBytes(estimatedSize)} + ). This can take several minutes and use significant disk space. +

+
+

Recommendations:

+
    +
  • Keep 2–3 full backups maximum
  • +
  • Run weekly or monthly at most
  • +
  • Ensure at least {formatBytes(estimatedSize * 3)} free on backup drive
  • +
+
+
+ + + +
+
+
+ ); +} + +// --------------------------------------------------------------------------- +// BackupRowCard — single backup entry +// --------------------------------------------------------------------------- + +function BackupRowCard({ + backup, onRestore, onDelete, restoreDisabled, +}: { + backup: BackupRow; + onRestore: (b: BackupRow) => void; + onDelete: (b: BackupRow) => void; + restoreDisabled: boolean; +}) { + const tiers = backup.tiers ? backup.tiers.split(",").filter(Boolean) : []; + const fname = backup.file_path.split(/[\\/]/).pop() ?? backup.file_path; + const displayName = backup.backup_type === "player" && backup.player_name + ? backup.player_name + : null; + + return ( +
+
+ {/* Tier tags + date */} +
+ {tiers.map((t) => )} + + {formatHumanDate(backup.created_at)} + +
+ {/* Size or player name */} +
+ {displayName && ( + + {displayName} + + )} + {backup.file_size_bytes > 0 && ( + + {formatBytes(backup.file_size_bytes)} + + )} +
+
+
+ + +
+
+ ); +} + +// --------------------------------------------------------------------------- +// SectionHeader — title + [Edit Schedules] + [Backup Now] button row +// --------------------------------------------------------------------------- + +function SectionHeader({ + icon: Icon, title, color, count, onEditSchedules, onManualBackup, isBusy, manualLabel, +}: { + icon: React.ElementType; + title: string; + color: string; + count: number; + onEditSchedules?: () => void; + onManualBackup: () => void; + isBusy: boolean; + manualLabel?: string; +}) { + return ( +
+
+ +
+ + {title} + + {count > 0 && ( + + {count} + + )} +
+ {onEditSchedules && ( + - +
+
+ ); +} + +// --------------------------------------------------------------------------- +// BackupSectionPanel — always-open scrollable panel with 6-entry visible area +// --------------------------------------------------------------------------- + +function BackupSectionPanel({ + icon: Icon, title, color, backups, loading, onRestore, onDelete, onManualBackup, + onEditSchedules, restoreDisabled, children, +}: { + icon: React.ElementType; + title: string; + color: string; + backups: BackupRow[]; + loading: boolean; + onRestore: (b: BackupRow) => void; + onDelete: (b: BackupRow) => void; + onManualBackup: () => void; + onEditSchedules?: () => void; + restoreDisabled: boolean; + children?: React.ReactNode; +}) { + return ( +
+ +
+
+ {children} + {loading ? ( +
+ ) : backups.length === 0 ? ( +

+ No backups yet +

+ ) : backups.map((b) => ( + + ))} +
+
+
+ ); +} + +// --------------------------------------------------------------------------- +// PlayerBackupSection — grouped by player, always open +// --------------------------------------------------------------------------- + +function PlayerBackupSection({ + serverId, playerBackups, loading, onRestore, onDelete, restoreDisabled, + onEditSchedules, onManualBackup, +}: { + serverId: string; + playerBackups: BackupRow[]; + loading: boolean; + onRestore: (b: BackupRow) => void; + onDelete: (b: BackupRow) => void; + restoreDisabled: boolean; + onEditSchedules?: () => void; + onManualBackup: () => void; +}) { + const [knownPlayers, setKnownPlayers] = useState<{ eosId: string; playerName: string }[]>([]); + + useEffect(() => { + getKnownPlayers(serverId).then(setKnownPlayers).catch(() => {}); + }, [serverId, playerBackups.length]); + + const byPlayer: Record = {}; + for (const b of playerBackups) { + const id = b.player_eosid ?? "unknown"; + (byPlayer[id] ??= []).push(b); + } + + const playerIds = Object.keys(byPlayer).filter((id) => (byPlayer[id]?.length ?? 0) > 0); + + const nameFor = (eosId: string): string => + knownPlayers.find((p) => p.eosId === eosId)?.playerName + ?? playerBackups.find((b) => b.player_eosid === eosId)?.player_name + ?? eosId; + + return ( +
+ +
+
+ {loading ? ( +
+ ) : playerIds.length === 0 ? ( +

+ No player backups yet +

+ ) : ( +
+ {playerIds.map((eosId) => { + const pBackups = (byPlayer[eosId] ?? []).sort( + (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime() + ); + return ( +
+

+ {nameFor(eosId)} +

+
+ {pBackups.map((b) => ( + + ))} +
+
+ ); + })} +
+ )} +
+
+
+ ); +} + +// --------------------------------------------------------------------------- +// IniBackupSection — always open, scrollable INI snapshots +// --------------------------------------------------------------------------- + +function IniBackupSection({ + serverId, backupDir, installPath, isBusy, onBusyChange, onEditSchedules, +}: { + serverId: string; + backupDir: string; + installPath: string; + isBusy: boolean; + onBusyChange: (b: boolean) => void; + onEditSchedules?: () => void; +}) { + const [snapshots, setSnapshots] = useState([]); + const [loading, setLoading] = useState(true); + + const load = useCallback(async () => { + setLoading(true); + try { + setSnapshots(await tauriCmd.listIniBackups(serverId, backupDir)); + } catch { /* ok */ } finally { + setLoading(false); + } + }, [serverId, backupDir]); + + useEffect(() => { if (backupDir) load(); }, [load, backupDir]); + + async function handleRestore(timestamp: string) { + onBusyChange(true); + try { + await tauriCmd.restoreIniBackup(`${backupDir}/${serverId}/ini/${timestamp}`, installPath, platform()); + toast.success(`Config restored from ${timestamp}.`); + } catch (e) { + toast.error(`INI restore failed: ${e}`); + } finally { + onBusyChange(false); + } + } + + async function handleDelete(timestamp: string) { + try { + await tauriCmd.deleteBackup(`${backupDir}/${serverId}/ini/${timestamp}`); + setSnapshots((s) => s.filter((x) => x !== timestamp)); + toast.success("Config snapshot deleted."); + } catch (e) { + toast.error(`Delete failed: ${e}`); + } + } + + return ( +
+
+
+ +
+
+ + Config (INI) Backups + + + auto-saved on config change + +
+ {onEditSchedules && ( + + )} +
+
+
+ {loading ? ( +
+ ) : snapshots.length === 0 ? ( +

+ No snapshots yet — save the config to create one +

+ ) : snapshots.map((snap) => ( +
+ +
+

+ {snap} +

+
+
+ + +
+
+ ))}
@@ -127,95 +569,83 @@ function RestoreConfirmDialog({ } // --------------------------------------------------------------------------- -// BackupsTab +// BackupsTab — main component // --------------------------------------------------------------------------- interface Props { server: ServerRow; + onNavigateToAutomation?: () => void; } -interface ProgressState { - active: boolean; - percent: number; - currentFile: string; - label: string; -} +export function BackupsTab({ server, onNavigateToAutomation }: Props) { + const mapPath = ARK_MAPS.find((m) => m.id === server.map_id)?.mapPath ?? "TheIsland_WP"; -const RETENTION_COUNT_KEY = (id: string) => `backup_retention_count_${id}`; -const RETENTION_DAYS_KEY = (id: string) => `backup_retention_days_${id}`; - -export function BackupsTab({ server }: Props) { - const [backups, setBackups] = useState(null); + const [serverBackups, setServerBackups] = useState([]); + const [playerBackups, setPlayerBackups] = useState([]); + const [fullBackups, setFullBackups] = useState([]); const [loading, setLoading] = useState(true); - const [progress, setProgress] = useState({ active: false, percent: 0, currentFile: "", label: "" }); - const [restoreTarget, setRestoreTarget] = useState(null); - const [retentionCount, setRetentionCount] = useState("10"); - const [retentionDays, setRetentionDays] = useState("30"); - const [retentionSaved, setRetentionSaved] = useState(false); - - // Load backups + retention settings on mount - const loadBackups = useCallback(async () => { + + const [progress, setProgress] = useState({ + active: false, percent: 0, currentFile: "", label: "", + }); + const [restoreTarget, setRestoreTarget] = useState(null); + const [showFullWarning, setShowFullWarning] = useState(false); + const [fullEstimate, setFullEstimate] = useState(0); + const [backupDir, setBackupDir] = useState(""); + + const loadAll = useCallback(async () => { setLoading(true); try { - const [rows, rCount, rDays] = await Promise.all([ - getServerBackups(server.id), - getAppSetting(RETENTION_COUNT_KEY(server.id)), - getAppSetting(RETENTION_DAYS_KEY(server.id)), + const [srv, plr, ful, bdir] = await Promise.all([ + getServerBackupsByType(server.id, "server"), + getServerBackupsByType(server.id, "player"), + getServerBackupsByType(server.id, "full"), + getAppSetting("backup_dir"), ]); - setBackups(rows); - if (rCount) setRetentionCount(rCount); - if (rDays) setRetentionDays(rDays); + setServerBackups(srv); + setPlayerBackups(plr); + setFullBackups(ful); + setBackupDir(bdir ?? ""); } catch (e) { toast.error(`Failed to load backups: ${e}`); } finally { setLoading(false); } - // eslint-disable-next-line react-hooks/exhaustive-deps }, [server.id]); - // Kick off initial load - useState(() => { loadBackups(); }); + useEffect(() => { loadAll(); }, [loadAll]); - // Listen for backup progress events - useTauriEvent<{ percent: number; currentFile: string }>( + useTauriEvent<{ percent: number; currentFile: string; label: string }>( `backup://progress/${server.id}`, (payload) => { - setProgress((p) => ({ ...p, percent: payload.percent, currentFile: payload.currentFile })); + setProgress((p) => ({ + ...p, + active: payload.percent < 100, + percent: payload.percent, + currentFile: payload.currentFile, + label: payload.label, + })); + if (payload.percent >= 100) setTimeout(loadAll, 500); } ); - // ── Create backup ────────────────────────────────────────────────────────── - - async function handleCreateBackup() { - const backupDir = await getAppSetting("backup_dir"); - if (!backupDir) { - toast.error("Backup directory not configured. Check Settings → Paths."); - return; - } + // ── Manual backup helpers ──────────────────────────────────────────────── - setProgress({ active: true, percent: 0, currentFile: "", label: "Creating backup…" }); + async function handleServerBackup() { + if (!backupDir) { toast.error("Backup directory not configured."); return; } + setProgress({ active: true, percent: 0, currentFile: "", label: "Starting server backup…" }); try { - const record: BackupRecord = await tauriCmd.createBackup( - server.id, - server.name, - server.install_path, - backupDir, - server.map_id, - "manual" + const rec: BackupRecord = await tauriCmd.createServerBackup( + server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual" ); await insertBackup({ - id: record.id, - server_id: record.serverId, - file_path: record.filePath, - file_size_bytes: record.fileSizeBytes, - map_id: record.mapId, - triggered_by: record.triggeredBy, - created_at: record.createdAt, + id: rec.id, server_id: rec.serverId, file_path: rec.filePath, + file_size_bytes: rec.fileSizeBytes, map_id: rec.mapId, + triggered_by: rec.triggeredBy, created_at: rec.createdAt, + backup_type: "server", tiers: "", player_eosid: null, player_name: null, }); - toast.success("Backup created successfully."); - await loadBackups(); - // Auto-prune after manual backup - await pruneOldBackups(); + toast.success("Server backup created."); + await loadAll(); } catch (e) { toast.error(`Backup failed: ${e}`); } finally { @@ -223,48 +653,61 @@ export function BackupsTab({ server }: Props) { } } - // ── Delete backup ────────────────────────────────────────────────────────── + async function handleFullBackupClick() { + if (!backupDir) { toast.error("Backup directory not configured."); return; } + const dismissed = await getAppSetting("full_backup_warning_dismissed"); + if (dismissed === "true") { + await runFullBackup(); + } else { + const size = await tauriCmd.estimateDirSize(server.install_path).catch(() => 0); + setFullEstimate(size); + setShowFullWarning(true); + } + } - async function handleDelete(backup: BackupRow) { + async function runFullBackup() { + setShowFullWarning(false); + setProgress({ active: true, percent: 0, currentFile: "", label: "Starting full backup…" }); try { - await tauriCmd.deleteBackup(backup.file_path); - await deleteBackupRecord(backup.id); - setBackups((prev) => prev?.filter((b) => b.id !== backup.id) ?? null); - toast.success("Backup deleted."); + const rec: BackupRecord = await tauriCmd.createFullBackup( + server.id, server.name, server.install_path, server.map_id, backupDir, "manual" + ); + await insertBackup({ + id: rec.id, server_id: rec.serverId, file_path: rec.filePath, + file_size_bytes: rec.fileSizeBytes, map_id: rec.mapId, + triggered_by: rec.triggeredBy, created_at: rec.createdAt, + backup_type: "full", tiers: "", player_eosid: null, player_name: null, + }); + toast.success("Full backup created."); + await loadAll(); } catch (e) { - toast.error(`Delete failed: ${e}`); + toast.error(`Full backup failed: ${e}`); + } finally { + setProgress((p) => ({ ...p, active: false })); } } - // ── Restore backup ───────────────────────────────────────────────────────── + // ── Restore ──────────────────────────────────────────────────────────────── async function handleRestoreConfirmed() { if (!restoreTarget) return; const target = restoreTarget; setRestoreTarget(null); - - const fresh = await getServer(server.id); - const isRunning = fresh?.status === "running"; - - setProgress({ active: true, percent: 0, currentFile: "", label: "Restoring backup…" }); + setProgress({ active: true, percent: 0, currentFile: "", label: "Restoring…" }); try { - if (isRunning) { - setProgress((p) => ({ ...p, label: "Stopping server…", currentFile: "" })); + if (server.status === "running") { + setProgress((p) => ({ ...p, label: "Stopping server…" })); await tauriCmd.stopServer(server.id, true); - // Brief pause to let process exit await new Promise((r) => setTimeout(r, 2000)); } - - setProgress((p) => ({ ...p, label: "Restoring save files…" })); - await tauriCmd.restoreBackup(server.id, target.file_path, server.install_path); - - if (isRunning) { - setProgress((p) => ({ ...p, label: "Restarting server…", percent: 100, currentFile: "" })); - // Restart needs full params — not available here, so notify user instead. - toast.success("Restore complete. Start the server manually to apply the restored save."); - } else { - toast.success("Backup restored successfully."); + if (target.backup_type === "server") { + await tauriCmd.restoreServerBackup(server.id, target.file_path, server.install_path); + } else if (target.backup_type === "player") { + await tauriCmd.restorePlayerBackup(server.id, target.file_path, server.install_path, mapPath); + } else if (target.backup_type === "full") { + await tauriCmd.restoreFullBackup(server.id, target.file_path, server.install_path); } + toast.success("Restore complete. Start the server manually to apply."); } catch (e) { toast.error(`Restore failed: ${e}`); } finally { @@ -272,54 +715,29 @@ export function BackupsTab({ server }: Props) { } } - // ── Retention prune ──────────────────────────────────────────────────────── - - async function pruneOldBackups() { - const allBackups = await getServerBackups(server.id); - const maxCount = parseInt(retentionCount, 10) || 10; - const maxDays = parseInt(retentionDays, 10) || 30; - const cutoff = Date.now() - maxDays * 86_400_000; - - let toDelete = [...allBackups]; - toDelete.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()); - - // Remove backups older than maxDays - const byAge = toDelete.filter((b) => new Date(b.created_at).getTime() < cutoff); - // Also remove oldest beyond maxCount (excluding byAge already) - const remaining = toDelete.filter((b) => !byAge.includes(b)); - const byCount = remaining.length > maxCount ? remaining.slice(0, remaining.length - maxCount) : []; - - const victims = [...new Set([...byAge, ...byCount])]; - for (const v of victims) { - try { - await tauriCmd.deleteBackup(v.file_path); - await deleteBackupRecord(v.id); - } catch {/* best-effort */} - } - if (victims.length > 0) { - toast.info(`Auto-pruned ${victims.length} old backup${victims.length > 1 ? "s" : ""}.`); - await loadBackups(); - } - } + // ── Delete ───────────────────────────────────────────────────────────────── - async function handleSaveRetention() { - await setAppSetting(RETENTION_COUNT_KEY(server.id), retentionCount); - await setAppSetting(RETENTION_DAYS_KEY(server.id), retentionDays); - setRetentionSaved(true); - setTimeout(() => setRetentionSaved(false), 2000); + async function handleDelete(backup: BackupRow) { + try { + await tauriCmd.deleteBackup(backup.file_path); + await deleteBackupRecord(backup.id); + await loadAll(); + toast.success("Backup deleted."); + } catch (e) { + toast.error(`Delete failed: ${e}`); + } } // ── Render ───────────────────────────────────────────────────────────────── + const isBusy = progress.active; + return (
- {/* Progress overlay */} {progress.active && ( -
+
@@ -329,7 +747,6 @@ export function BackupsTab({ server }: Props) { {progress.percent.toFixed(0)}%
- {/* Progress bar */}
)} - {/* Header row */} + {/* Header */}
-

- Backups -

- {backups && ( - - {backups.length} - - )} -
-
- - +

Backups

+
- {/* Backup list */} - {loading ? ( -
- {[1, 2, 3].map((n) => ( -
- ))} -
- ) : !backups || backups.length === 0 ? ( -
- -
-

No backups yet

-

- Click “Create Backup” to make your first save backup. -

-
-
- ) : ( -
- {backups.map((backup) => ( -
- -
-

- {backup.file_path.split(/[\\/]/).pop() ?? backup.file_path} -

-
- - {formatDate(backup.created_at)} - - - {formatBytes(backup.file_size_bytes)} - - {triggerBadge(backup.triggered_by)} -
-
-
- - -
-
- ))} -
+ {/* INI backups */} + {backupDir && ( + setProgress((p) => ({ ...p, active: b }))} + onEditSchedules={onNavigateToAutomation} + /> )} - {/* Retention settings */} -
-

- Retention Policy -

-
-
- - setRetentionCount(e.target.value)} - className="h-8 w-24 text-sm" - style={{ - background: "rgba(0,0,0,0.4)", - border: "1px solid rgba(191,0,255,0.2)", - color: "var(--text-primary)", - }} - /> -
-
- - setRetentionDays(e.target.value)} - className="h-8 w-24 text-sm" - style={{ - background: "rgba(0,0,0,0.4)", - border: "1px solid rgba(191,0,255,0.2)", - color: "var(--text-primary)", - }} - /> -
- -
-

- Old backups are pruned automatically after each new backup is created. -

-
+ {/* Server backups */} + + + {/* Player backups */} + toast.info("Player backups are triggered automatically by the scheduler.")} + onEditSchedules={onNavigateToAutomation} + restoreDisabled={isBusy} + /> + + {/* Full backups */} + - {/* Restore confirm dialog */} {restoreTarget && ( setRestoreTarget(null)} /> )} + + {showFullWarning && ( + { + await setAppSetting("full_backup_warning_dismissed", "true"); + await runFullBackup(); + }} + onCancel={() => setShowFullWarning(false)} + /> + )}
); } diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index 89b3ba8..468560a 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -10,7 +10,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { tauriCmd, type ServerConfigJson } from "@/lib/tauri-commands"; import { INI_FIELD_GROUPS, LAUNCH_PARAMETERS, type IniFieldDef, type LaunchParameter } from "@/data/game-data"; -import { getServerConfig, saveServerConfig, updateServerShutdownSettings, type ServerRow } from "@/lib/db"; +import { getServerConfig, saveServerConfig, updateServerShutdownSettings, getAppSetting, type ServerRow } from "@/lib/db"; import { toast } from "sonner"; import { NumberField } from "@/components/shared/NumberField"; @@ -617,6 +617,14 @@ export function ConfigTab({ server }: Props) { ); setSavedFlash(true); setTimeout(() => setSavedFlash(false), 2000); + + // Snapshot INI files into the backup system (best-effort, non-blocking) + const backupDir = await getAppSetting("backup_dir").catch(() => null); + const plat = typeof navigator !== "undefined" && !navigator.userAgent.includes("Windows") + ? "LinuxServer" : "WindowsServer"; + if (backupDir) { + tauriCmd.createIniBackup(server.id, server.install_path, backupDir, plat).catch(() => {}); + } } catch (e) { setError(String(e)); } finally { diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index 6639719..1c01541 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -762,12 +762,14 @@ export function OverviewTab({ server }: Props) { onClick={async () => { const backupDir = await getAppSetting("backup_dir"); if (!backupDir) return; - tauriCmd.createBackup(server.id, server.name, server.install_path, backupDir, server.map_id, "manual") + const mapPath = ARK_MAPS.find((m) => m.id === server.map_id)?.mapPath ?? "TheIsland_WP"; + tauriCmd.createServerBackup(server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual") .then(async (record: BackupRecord) => { await insertBackup({ id: record.id, server_id: record.serverId, file_path: record.filePath, file_size_bytes: record.fileSizeBytes, map_id: record.mapId, triggered_by: record.triggeredBy, created_at: record.createdAt, + backup_type: "server", tiers: "", player_eosid: null, player_name: null, }); }) .catch(() => null); diff --git a/src/lib/db.ts b/src/lib/db.ts index 4742dbc..4d0dab9 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -120,7 +120,19 @@ async function runMigrations(db: Database): Promise { file_size_bytes INTEGER NOT NULL DEFAULT 0, map_id TEXT NOT NULL, triggered_by TEXT NOT NULL, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + backup_type TEXT NOT NULL DEFAULT 'server', + tiers TEXT NOT NULL DEFAULT '', + player_eosid TEXT, + player_name TEXT + )`); + + await db.execute(`CREATE TABLE IF NOT EXISTS player_name_map ( + server_id TEXT NOT NULL, + eos_id TEXT NOT NULL, + player_name TEXT NOT NULL, + last_seen TEXT NOT NULL, + PRIMARY KEY (server_id, eos_id) )`); await db.execute(`CREATE TABLE IF NOT EXISTS notification_configs ( @@ -181,7 +193,8 @@ async function runMigrations(db: Database): Promise { ('asa_cached_build_id', ''), ('asa_latest_build_id', ''), ('asa_auto_check_hours', '1'), - ('auto_restart_downed', 'ask')`); + ('auto_restart_downed', 'ask'), + ('full_backup_warning_dismissed', 'false')`); // ── Migration 002: add settings_json to clusters if missing (old DBs) ── try { @@ -283,6 +296,22 @@ async function runMigrations(db: Database): Promise { await db.execute( "CREATE INDEX IF NOT EXISTS idx_uptime_sessions_server ON server_uptime_sessions(server_id, started_at)" ); + + // ── Migration 008: backup system v2 ────────────────────────────────────── + try { await db.execute("ALTER TABLE backups ADD COLUMN backup_type TEXT NOT NULL DEFAULT 'server'"); } catch { /* exists */ } + try { await db.execute("ALTER TABLE backups ADD COLUMN tiers TEXT NOT NULL DEFAULT ''"); } catch { /* exists */ } + try { await db.execute("ALTER TABLE backups ADD COLUMN player_eosid TEXT"); } catch { /* exists */ } + try { await db.execute("ALTER TABLE backups ADD COLUMN player_name TEXT"); } catch { /* exists */ } + await db.execute(`CREATE TABLE IF NOT EXISTS player_name_map ( + server_id TEXT NOT NULL, + eos_id TEXT NOT NULL, + player_name TEXT NOT NULL, + last_seen TEXT NOT NULL, + PRIMARY KEY (server_id, eos_id) + )`); + // Rename old generic "backup" schedule rows to the new typed name. + await db.execute("UPDATE schedules SET schedule_type = 'backup_server' WHERE schedule_type = 'backup'"); + try { await db.execute("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('full_backup_warning_dismissed', 'false')"); } catch { /* exists */ } } // --------------------------------------------------------------------------- @@ -829,16 +858,25 @@ export interface BackupRow { file_path: string; file_size_bytes: number; map_id: string; + /** manual | schedule | pre_update | pre_restart | config_save */ triggered_by: string; created_at: string; + /** server | player | full | ini */ + backup_type: string; + /** Comma-separated tier flags: H, D, W, M — or empty for manual/full */ + tiers: string; + player_eosid: string | null; + player_name: string | null; } -/** Insert a backup record returned by the Rust create_backup command. */ +/** Insert a backup record. */ export async function insertBackup(record: BackupRow): Promise { const db = await getDb(); await db.execute( - `INSERT INTO backups (id, server_id, file_path, file_size_bytes, map_id, triggered_by, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`, + `INSERT INTO backups + (id, server_id, file_path, file_size_bytes, map_id, triggered_by, created_at, + backup_type, tiers, player_eosid, player_name) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ record.id, record.server_id, @@ -847,6 +885,10 @@ export async function insertBackup(record: BackupRow): Promise { record.map_id, record.triggered_by, record.created_at, + record.backup_type ?? 'server', + record.tiers ?? '', + record.player_eosid ?? null, + record.player_name ?? null, ] ); } @@ -860,12 +902,108 @@ export async function getServerBackups(serverId: string): Promise { ); } +/** Fetch backups for a server filtered by type, newest first. */ +export async function getServerBackupsByType( + serverId: string, + backupType: string +): Promise { + const db = await getDb(); + return db.select( + "SELECT * FROM backups WHERE server_id = ? AND backup_type = ? ORDER BY created_at DESC", + [serverId, backupType] + ); +} + +/** Fetch all backups across every server, newest first (used by global /backups page). */ +export async function getAllBackups(): Promise { + const db = await getDb(); + return db.select( + "SELECT * FROM backups ORDER BY created_at DESC" + ); +} + +/** Fetch all player backups for a specific EOS ID on a server. */ +export async function getPlayerBackups( + serverId: string, + eosId: string +): Promise { + const db = await getDb(); + return db.select( + "SELECT * FROM backups WHERE server_id = ? AND player_eosid = ? ORDER BY created_at DESC", + [serverId, eosId] + ); +} + +/** Update the tier flags on an existing backup (for TimeShift promotion). */ +export async function updateBackupTiers(backupId: string, tiers: string): Promise { + const db = await getDb(); + await db.execute("UPDATE backups SET tiers = ? WHERE id = ?", [tiers, backupId]); +} + /** Remove a backup record from the database (after the file has been deleted). */ export async function deleteBackupRecord(backupId: string): Promise { const db = await getDb(); await db.execute("DELETE FROM backups WHERE id = ?", [backupId]); } +// --------------------------------------------------------------------------- +// Player name map +// --------------------------------------------------------------------------- + +/** Insert or update an EOS ID → player name mapping. */ +export async function upsertPlayerName( + serverId: string, + eosId: string, + playerName: string +): Promise { + const db = await getDb(); + await db.execute( + `INSERT INTO player_name_map (server_id, eos_id, player_name, last_seen) + VALUES (?, ?, ?, ?) + ON CONFLICT(server_id, eos_id) DO UPDATE SET player_name = excluded.player_name, last_seen = excluded.last_seen`, + [serverId, eosId, playerName, new Date().toISOString()] + ); +} + +/** Bulk upsert multiple players from a listplayers result. */ +export async function upsertPlayerNames( + serverId: string, + players: { eosId: string; name: string }[] +): Promise { + const db = await getDb(); + const now = new Date().toISOString(); + for (const p of players) { + await db.execute( + `INSERT INTO player_name_map (server_id, eos_id, player_name, last_seen) + VALUES (?, ?, ?, ?) + ON CONFLICT(server_id, eos_id) DO UPDATE SET player_name = excluded.player_name, last_seen = excluded.last_seen`, + [serverId, p.eosId, p.name, now] + ); + } +} + +/** Return an eosId → playerName map for a server. */ +export async function getPlayerNameMap(serverId: string): Promise> { + const db = await getDb(); + const rows = await db.select<{ eos_id: string; player_name: string }[]>( + "SELECT eos_id, player_name FROM player_name_map WHERE server_id = ?", + [serverId] + ); + return Object.fromEntries(rows.map((r) => [r.eos_id, r.player_name])); +} + +/** Return all known players for a server (for the player backup browser). */ +export async function getKnownPlayers( + serverId: string +): Promise<{ eosId: string; playerName: string; lastSeen: string }[]> { + const db = await getDb(); + const rows = await db.select<{ eos_id: string; player_name: string; last_seen: string }[]>( + "SELECT eos_id, player_name, last_seen FROM player_name_map WHERE server_id = ? ORDER BY last_seen DESC", + [serverId] + ); + return rows.map((r) => ({ eosId: r.eos_id, playerName: r.player_name, lastSeen: r.last_seen })); +} + // --------------------------------------------------------------------------- // Schedule mutations // --------------------------------------------------------------------------- diff --git a/src/lib/scheduler-sync.ts b/src/lib/scheduler-sync.ts index b29d2ac..b64e752 100644 --- a/src/lib/scheduler-sync.ts +++ b/src/lib/scheduler-sync.ts @@ -72,6 +72,8 @@ export async function syncSchedulesToRust(): Promise { const map = ARK_MAPS.find((m) => m.id === server.map_id); const mapPath = map?.mapPath ?? "TheIsland_WP"; + // Exclude backup schedule types that don't use the standard cron approach. + // backup_server / backup_player / backup_full are included normally below. for (const schedule of enabled) { // Compute next_run_ms from either the stored ISO date or fresh from cron. let nextRunMs: number; diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index c5e3bbf..a1e5b52 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -184,6 +184,19 @@ export interface BackupRecord { mapId: string; triggeredBy: string; createdAt: string; + /** server | player | full | ini */ + backupType: string; + /** Comma-separated tier flags assigned by frontend: H, D, W, M */ + tiers: string; + playerEosid: string | null; + playerName: string | null; +} + +export interface IniBackupRecord { + id: string; + serverId: string; + folderPath: string; + createdAt: string; } /** Result of comparing the shared cache against the Steam UpToDateCheck API. */ @@ -459,28 +472,58 @@ export const tauriCmd = { invoke("import_ini_files", { gusPath, gameIniPath }), // Backups - /** - * Zip the server's ShooterGame/Saved directory into backup_dir. - * Emits backup://progress/{serverId} events. Returns a BackupRecord to - * persist in SQLite via db.insertBackup(). - */ - createBackup: ( - serverId: string, - serverName: string, - installPath: string, - backupDir: string, - mapId: string, - triggeredBy: string, - ) => invoke("create_backup", { serverId, serverName, installPath, backupDir, mapId, triggeredBy }), - /** - * Extract backup zip over ShooterGame/Saved. The frontend must stop the - * server before calling this and restart it after. - */ - restoreBackup: (serverId: string, backupFilePath: string, installPath: string) => - invoke("restore_backup", { serverId, backupFilePath, installPath }), - /** Delete the zip file from disk. Frontend removes the SQLite record via db.deleteBackupRecord(). */ + /** Server backup: SaveWorld → cleanup ARK files → 7z SavedArks+SaveGames. */ + createServerBackup: ( + serverId: string, serverName: string, installPath: string, mapPath: string, + mapId: string, backupDir: string, triggeredBy: string, + ) => invoke("create_server_backup", { serverId, serverName, installPath, mapPath, mapId, backupDir, triggeredBy }), + + /** Player backup: 7z a single .arkprofile file. */ + createPlayerBackup: ( + serverId: string, serverName: string, installPath: string, mapPath: string, + mapId: string, backupDir: string, eosId: string, playerName: string, triggeredBy: string, + ) => invoke("create_player_backup", { serverId, serverName, installPath, mapPath, mapId, backupDir, eosId, playerName, triggeredBy }), + + /** INI backup: copy loose INI files into a rotating timestamped folder. */ + createIniBackup: (serverId: string, installPath: string, backupDir: string, platform: string) => + invoke("create_ini_backup", { serverId, installPath, backupDir, platform }), + + /** Full backup: 7z the entire install_path directory. */ + createFullBackup: ( + serverId: string, serverName: string, installPath: string, mapId: string, + backupDir: string, triggeredBy: string, + ) => invoke("create_full_backup", { serverId, serverName, installPath, mapId, backupDir, triggeredBy }), + + /** List timestamped INI snapshot folder names for a server, newest first. */ + listIniBackups: (serverId: string, backupDir: string) => + invoke("list_ini_backups", { serverId, backupDir }), + + /** Restore a server backup: extract 7z over SavedArks+SaveGames. */ + restoreServerBackup: (serverId: string, backupFilePath: string, installPath: string) => + invoke("restore_server_backup", { serverId, backupFilePath, installPath }), + + /** Restore a player backup: extract 7z into SavedArks/{mapPath}. */ + restorePlayerBackup: (serverId: string, backupFilePath: string, installPath: string, mapPath: string) => + invoke("restore_player_backup", { serverId, backupFilePath, installPath, mapPath }), + + /** Restore an INI backup: copy loose INI files back to Config/{platform}. */ + restoreIniBackup: (backupFolderPath: string, installPath: string, platform: string) => + invoke("restore_ini_backup", { backupFolderPath, installPath, platform }), + + /** Restore a full backup: extract 7z over the entire install_path. */ + restoreFullBackup: (serverId: string, backupFilePath: string, installPath: string) => + invoke("restore_full_backup", { serverId, backupFilePath, installPath }), + + /** Delete a backup archive or INI folder from disk. */ deleteBackup: (filePath: string) => invoke("delete_backup", { filePath }), + /** Delete ARK's own timestamped .ark backups and .profilebak files. */ + cleanupArkOwnBackups: (installPath: string, mapPath: string) => + invoke("cleanup_ark_own_backups", { installPath, mapPath }), + + /** Estimate total uncompressed size of a directory in bytes. */ + estimateDirSize: (dirPath: string) => invoke("estimate_dir_size", { dirPath }), + // Mods /** * Download all listed mods via SteamCMD, cache them, and copy to the server. From edce62279f68e062d3603dcdbb5e2aaab767d641 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 9 Jun 2026 11:17:26 -0500 Subject: [PATCH 06/15] refactor: update backup section headers and button labels for clarity - Renamed manual backup button label to "Backup X Now" for consistency. - Updated button styles for manual backup and edit schedule actions. - Adjusted props to pass new backupLabel for better readability. - Enhanced navigation for editing schedules to improve user experience. --- src/components/server/tabs/AutomationTab.tsx | 1134 ++++++++---------- src/components/server/tabs/BackupsTab.tsx | 66 +- 2 files changed, 550 insertions(+), 650 deletions(-) diff --git a/src/components/server/tabs/AutomationTab.tsx b/src/components/server/tabs/AutomationTab.tsx index 4d9fbe2..8d73fff 100644 --- a/src/components/server/tabs/AutomationTab.tsx +++ b/src/components/server/tabs/AutomationTab.tsx @@ -1,13 +1,5 @@ "use client"; -/** - * AutomationTab — manage per-server cron schedules (backup, update, restart, broadcast). - * - * Schedule data lives in SQLite. Firing is handled by the Tokio background task in lib.rs - * via the Rust SchedulerState (immune to JS timer throttling when minimized to tray). - * Schedules only fire while the LokiASAM app is running. - */ - import { useState, useCallback, useEffect } from "react"; import { CalendarClock, HardDrive, RefreshCw, RotateCcw, Megaphone, @@ -19,7 +11,7 @@ import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; -import { CronBuilder, getNextCronDate, CRON_PRESETS } from "@/components/shared/CronBuilder"; +import { getNextCronDate } from "@/components/shared/CronBuilder"; import { getServerSchedules, createSchedule, deleteScheduleRecord, updateScheduleEnabled, updateScheduleConfig, @@ -39,6 +31,7 @@ import type { ServerRow } from "@/lib/db"; // --------------------------------------------------------------------------- type ScheduleType = "restart" | "broadcast"; +type AddMode = "minutes" | "hours" | "daily"; interface RestartConfig { broadcastWarning: boolean; @@ -46,23 +39,57 @@ interface RestartConfig { message: string; } -interface BroadcastConfig { - message: string; -} - // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- -const DEFAULT_CRON: Record = { - restart: "0 6 * * *", // Daily at 6 AM - broadcast: CRON_PRESETS[0].cron, // Every hour -}; +function parseCfg(json: string | null | undefined): Record { + try { return JSON.parse(json ?? "{}"); } catch { return {}; } +} -const DEFAULT_CONFIG: Record = { - 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, -}; +function buildCronFromMode(mode: AddMode, val: number | string): string { + if (mode === "minutes") return `*/${Math.max(1, Math.min(59, val as number))} * * * *`; + if (mode === "hours") return `0 */${Math.max(1, Math.min(23, val as number))} * * *`; + const [h, m] = String(val).split(":").map(Number); + return `${isNaN(m) ? 0 : m} ${isNaN(h) ? 6 : h} * * *`; +} + +function describeSchedule(cron: string): string { + const parts = cron.trim().split(/\s+/); + if (parts.length !== 5) return cron; + const [min, hour, dom, mon, dow] = parts; + const minMatch = min.match(/^\*\/(\d+)$/); + if (minMatch && hour === "*" && dom === "*" && mon === "*" && dow === "*") { + const n = minMatch[1]; + return `Every ${n} minute${n === "1" ? "" : "s"}`; + } + const hourMatch = hour.match(/^\*\/(\d+)$/); + if (hourMatch && min === "0" && dom === "*" && mon === "*" && dow === "*") { + const n = hourMatch[1]; + return `Every ${n} hour${n === "1" ? "" : "s"}`; + } + const minNum = parseInt(min), hourNum = parseInt(hour); + if (!isNaN(minNum) && !isNaN(hourNum) && dom === "*" && mon === "*" && dow === "*") { + const d = new Date(); d.setHours(hourNum, minNum, 0); + return `Daily at ${d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}`; + } + return cron; +} + +function cronToMode(cron: string): { mode: AddMode; num: number; time: string } { + const parts = cron.trim().split(/\s+/); + if (parts.length !== 5) return { mode: "daily", num: 6, time: "06:00" }; + const [min, hour] = parts; + const minMatch = min.match(/^\*\/(\d+)$/); + if (minMatch && hour === "*") return { mode: "minutes", num: parseInt(minMatch[1]) || 30, time: "06:00" }; + const hourMatch = hour.match(/^\*\/(\d+)$/); + if (hourMatch && min === "0") return { mode: "hours", num: parseInt(hourMatch[1]) || 6, time: "06:00" }; + const h = parseInt(hour ?? "6"), m = parseInt(min ?? "0"); + return { + mode: "daily", num: 6, + time: `${String(isNaN(h) ? 6 : h).padStart(2, "0")}:${String(isNaN(m) ? 0 : m).padStart(2, "0")}`, + }; +} function formatNextRun(iso: string | null): string { if (!iso) return "—"; @@ -78,21 +105,188 @@ function formatNextRun(iso: string | null): string { return `in ${Math.floor(h / 24)}d`; } -function formatLastRun(iso: string | null): string { - if (!iso) return "Never"; - const d = new Date(iso); - if (isNaN(d.getTime())) return "—"; - const diff = Date.now() - d.getTime(); - const mins = Math.floor(diff / 60_000); - if (mins < 1) return "just now"; - if (mins < 60) return `${mins}m ago`; - const h = Math.floor(mins / 60); - if (h < 24) return `${h}h ago`; - return `${Math.floor(h / 24)}d ago`; +// --------------------------------------------------------------------------- +// AddScheduleRow — shared picker for add and inline edit +// --------------------------------------------------------------------------- + +interface AddScheduleRowProps { + mode: AddMode; setMode: (m: AddMode) => void; + num: number; setNum: (n: number) => void; + time: string; setTime: (t: string) => void; + showMessage: boolean; message: string; setMessage: (m: string) => void; + onConfirm: () => void; + onCancel?: () => void; + confirmLabel?: string; + busy: boolean; +} + +function AddScheduleRow({ + mode, setMode, num, setNum, time, setTime, + showMessage, message, setMessage, + onConfirm, onCancel, confirmLabel = "Add", busy, +}: AddScheduleRowProps) { + return ( +
+
+ + + {(mode === "minutes" || mode === "hours") && ( + setNum(Math.max(1, parseInt(e.target.value) || 1))} + className="w-20 h-8 text-xs text-center" + style={{ background: "rgba(0,0,0,0.4)", border: "1px solid rgba(191,0,255,0.2)", color: "var(--text-primary)" }} + /> + )} + {mode === "daily" && ( + setTime(e.target.value)} + className="h-8 rounded px-2 text-xs font-mono" + style={{ background: "rgba(0,0,0,0.35)", border: "1px solid rgba(191,0,255,0.25)", color: "var(--text-primary)", outline: "none" }} + /> + )} + +
+ {onCancel && ( + + )} + +
+
+ + {showMessage && ( + setMessage(e.target.value)} + placeholder="Message to send in global chat" + className="h-8 text-sm" + style={{ background: "rgba(0,0,0,0.4)", border: "1px solid rgba(191,0,255,0.2)", color: "var(--text-primary)" }} + /> + )} +
+ ); } // --------------------------------------------------------------------------- -// ScheduleCard — one card per schedule type +// ScheduleListRow — one schedule entry with inline edit +// --------------------------------------------------------------------------- + +function ScheduleListRow({ row, type, onDelete, onToggle, onSave }: { + row: ScheduleRow; + type: ScheduleType; + onDelete: () => Promise; + onToggle: () => Promise; + onSave: (cron: string, configJson: string) => Promise; +}) { + const parsed = cronToMode(row.cron_expression); + const [editing, setEditing] = useState(false); + const [mode, setMode] = useState(parsed.mode); + const [num, setNum] = useState(parsed.num); + const [time, setTime] = useState(parsed.time); + const [msg, setMsg] = useState((parseCfg(row.config_json).message as string) ?? ""); + const [saving, setSaving] = useState(false); + const [deleting, setDeleting] = useState(false); + + async function handleSave() { + setSaving(true); + try { + const cron = buildCronFromMode(mode, mode === "daily" ? time : num); + const cfg = parseCfg(row.config_json); + const configJson = type === "broadcast" + ? JSON.stringify({ ...cfg, message: msg }) + : row.config_json ?? "{}"; + await onSave(cron, configJson); + setEditing(false); + } catch (e) { + toast.error(`Save failed: ${e}`); + } finally { + setSaving(false); + } + } + + async function handleDelete() { + setDeleting(true); + try { await onDelete(); } + finally { setDeleting(false); } + } + + if (editing) { + return ( +
+ setEditing(false)} + confirmLabel="Save" busy={saving} + /> +
+ ); + } + + return ( +
+
+

+ {describeSchedule(row.cron_expression)} +

+ {type === "broadcast" && msg && ( +

{msg}

+ )} + {row.next_run && ( +

+ Next: {formatNextRun(row.next_run)} +

+ )} +
+ + + +
+ ); +} + +// --------------------------------------------------------------------------- +// ScheduleCard — list-based restart / broadcast schedule manager // --------------------------------------------------------------------------- interface CardProps { @@ -101,273 +295,204 @@ interface CardProps { icon: React.ElementType; title: string; description: string; - existing: ScheduleRow | null; + existing: ScheduleRow[]; onRefresh: () => void; } -function ScheduleCard({ serverId, type, icon: Icon, title, description, existing, onRefresh }: CardProps) { - const [cron, setCron] = useState(existing?.cron_expression ?? DEFAULT_CRON[type]); - const [enabled, setEnabled] = useState(existing ? existing.enabled === 1 : false); - const [config, setConfig] = useState( - existing?.config_json ? JSON.parse(existing.config_json) : DEFAULT_CONFIG[type] - ); - const [saving, setSaving] = useState(false); - const [saved, setSaved] = useState(false); - const [deleting, setDeleting] = useState(false); - - const nextDate = getNextCronDate(cron); - const nextRun = existing?.next_run ?? (nextDate ? nextDate.toISOString() : null); +const DEFAULT_RESTART_CFG: RestartConfig = { + broadcastWarning: true, + warningMinutes: 15, + message: "Server restarting in {minutes} minutes. Progress will be saved.", +}; - function patchConfig(patch: Partial) { +function ScheduleCard({ serverId, type, icon: Icon, title, description, existing, onRefresh }: CardProps) { + const [config, setConfig] = useState(() => ({ + ...DEFAULT_RESTART_CFG, + ...(parseCfg(existing[0]?.config_json) as Partial), + })); + const [savingConfig, setSavingConfig] = useState(false); + const [savedConfig, setSavedConfig] = useState(false); + + const [addMode, setAddMode] = useState("daily"); + const [addNum, setAddNum] = useState(6); + const [addTime, setAddTime] = useState("06:00"); + const [addMsg, setAddMsg] = useState(""); + const [adding, setAdding] = useState(false); + + const hasSchedules = existing.length > 0; + + function patchConfig(patch: Partial) { setConfig((c) => ({ ...c, ...patch })); } - async function handleSave() { - if (!cron) return; - setSaving(true); + async function handleSaveConfig() { + setSavingConfig(true); try { - const configJson = JSON.stringify(config); - const nextDate = getNextCronDate(cron); - const nextIso = nextDate?.toISOString() ?? new Date().toISOString(); - - if (existing) { - // Update existing schedule - await updateScheduleConfig(existing.id, cron, configJson, nextIso); - if (enabled !== (existing.enabled === 1)) { - await updateScheduleEnabled(existing.id, enabled); - } - } else { - // Create new schedule — get UUID from Rust, then persist to SQLite - const newId = await tauriCmd.createSchedule({ - serverId, - scheduleType: type, - cronExpression: cron, - configJson, - }); - const input: CreateScheduleInput = { - id: newId, - serverId, - scheduleType: type, - cronExpression: cron, - enabled, - configJson, - }; - await createSchedule(input); - // Update next_run after insert - await updateScheduleConfig(newId, cron, configJson, nextIso); + for (const row of existing) { + const merged = { ...parseCfg(row.config_json), ...config }; + const nextIso = getNextCronDate(row.cron_expression)?.toISOString() ?? new Date().toISOString(); + await updateScheduleConfig(row.id, row.cron_expression, JSON.stringify(merged), nextIso); } - - setSaved(true); - setTimeout(() => setSaved(false), 2000); + setSavedConfig(true); + setTimeout(() => setSavedConfig(false), 2000); onRefresh(); syncSchedulesToRust(); } catch (e) { - toast.error(`Failed to save schedule: ${e}`); + toast.error(`Failed to save config: ${e}`); } finally { - setSaving(false); + setSavingConfig(false); } } - async function handleDelete() { - if (!existing) return; - setDeleting(true); + async function handleAdd() { + setAdding(true); try { - await tauriCmd.deleteSchedule(existing.id); - await deleteScheduleRecord(existing.id); + const cron = buildCronFromMode(addMode, addMode === "daily" ? addTime : addNum); + const configJson = type === "broadcast" + ? JSON.stringify({ message: addMsg }) + : JSON.stringify(config); + const nextIso = getNextCronDate(cron)?.toISOString() ?? new Date().toISOString(); + const newId = await tauriCmd.createSchedule({ serverId, scheduleType: type, cronExpression: cron, configJson }); + const input: CreateScheduleInput = { id: newId, serverId, scheduleType: type, cronExpression: cron, enabled: true, configJson }; + await createSchedule(input); + await updateScheduleConfig(newId, cron, configJson, nextIso); + if (type === "broadcast") setAddMsg(""); + toast.success("Schedule added."); onRefresh(); syncSchedulesToRust(); - toast.success(`${title} schedule removed.`); } catch (e) { - toast.error(`Failed to delete: ${e}`); + toast.error(`Failed to add schedule: ${e}`); } finally { - setDeleting(false); + setAdding(false); } } - async function handleToggle() { - const newVal = !enabled; - setEnabled(newVal); - if (existing) { - try { - await tauriCmd.toggleSchedule(existing.id, newVal); - await updateScheduleEnabled(existing.id, newVal); - onRefresh(); - syncSchedulesToRust(); - } catch (e) { - toast.error(`Toggle failed: ${e}`); - setEnabled(!newVal); - } - } + async function handleDelete(id: string) { + await tauriCmd.deleteSchedule(id); + await deleteScheduleRecord(id); + onRefresh(); + syncSchedulesToRust(); } - const c = config as RestartConfig & BroadcastConfig; + async function handleToggle(row: ScheduleRow) { + const newVal = !(row.enabled === 1); + await tauriCmd.toggleSchedule(row.id, newVal); + await updateScheduleEnabled(row.id, newVal); + onRefresh(); + syncSchedulesToRust(); + } + + async function handleSaveRow(row: ScheduleRow, cron: string, configJson: string) { + const nextIso = getNextCronDate(cron)?.toISOString() ?? new Date().toISOString(); + await updateScheduleConfig(row.id, cron, configJson, nextIso); + onRefresh(); + syncSchedulesToRust(); + } + + const c = config; return (
{/* Header */}
- +

{title}

- {existing && ( - - {enabled ? "Active" : "Paused"} + {hasSchedules && ( + + {existing.length} schedule{existing.length !== 1 ? "s" : ""} )}

{description}

-
- {/* Last / next run */} - {existing && ( -
- Last run: {formatLastRun(existing.last_run)} - Next run: {formatNextRun(existing.next_run)} -
- )} - - {/* Cron picker */} - - - {/* Restart-specific options */} + {/* Restart shared config */} {type === "restart" && ( -
+
{c.broadcastWarning && (
- - Warning minutes + 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)", - }} - /> + style={{ background: "rgba(0,0,0,0.4)", border: "1px solid rgba(191,0,255,0.2)", color: "var(--text-primary)" }} />
- - + Message ({"{minutes}"} = countdown) + + patchConfig({ message: e.target.value })} placeholder="Server restarting in {minutes} minutes." className="h-7 text-xs" - style={{ - background: "rgba(0,0,0,0.4)", - border: "1px solid rgba(191,0,255,0.2)", - color: "var(--text-primary)", - }} - /> + style={{ background: "rgba(0,0,0,0.4)", border: "1px solid rgba(191,0,255,0.2)", color: "var(--text-primary)" }} />
)} +
)} - {type === "broadcast" && ( -
- - patchConfig({ message: e.target.value })} - placeholder="Welcome to the server!" - className="h-8 text-sm" - style={{ - background: "rgba(0,0,0,0.4)", - border: "1px solid rgba(191,0,255,0.2)", - color: "var(--text-primary)", - }} - /> + {/* Existing schedule list */} + {hasSchedules && ( +
+

Active Schedules

+ {existing.map((row) => ( + handleDelete(row.id)} + onToggle={() => handleToggle(row)} + onSave={(cron, configJson) => handleSaveRow(row, cron, configJson)} + /> + ))}
)} - {/* Save / delete row */} -
- - - {existing && ( - - )} + {/* Add new schedule */} +
+

Add Schedule

+
); @@ -380,27 +505,19 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing type BackupTier = "H" | "D" | "W" | "M"; type BackupScheduleType = "backup_server" | "backup_player" | "backup_full"; -// Fixed cron expressions per tier (not exposed in UI — schedule timing is implicit) const TIER_FIXED_CRON: Record = { - M: "0 4 1 * *", // monthly — 1st at 4am - W: "0 3 * * 0", // weekly — Sunday 3am - D: "0 2 * * *", // daily — 2am - H: "0 */6 * * *", // hourly — every 6h -}; - -const TIER_DEFAULT_KEEP: Record = { - M: 3, W: 4, D: 7, H: 24, + M: "0 4 1 * *", + W: "0 3 * * 0", + D: "0 2 * * *", + H: "0 */6 * * *", }; -const TIER_LABEL: Record = { - M: "monthly", W: "weekly", D: "daily", H: "hourly", -}; +const TIER_DEFAULT_KEEP: Record = { M: 3, W: 4, D: 7, H: 24 }; +const TIER_LABEL: Record = { M: "monthly", W: "weekly", D: "daily", H: "hourly" }; +const TIER_ORDER: BackupTier[] = ["M", "W", "D", "H"]; +type TierState = { keep: number; enabled: boolean }; -function findTierSchedule( - schedules: ScheduleRow[], - type: BackupScheduleType, - tier: BackupTier, -): ScheduleRow | null { +function findTierSchedule(schedules: ScheduleRow[], type: BackupScheduleType, tier: BackupTier): ScheduleRow | null { return schedules.find((s) => { if (s.schedule_type !== type) return false; try { return (JSON.parse(s.config_json ?? "{}").tier ?? "H") === tier; } @@ -413,29 +530,25 @@ function findFullSchedule(schedules: ScheduleRow[]): ScheduleRow | null { } // --------------------------------------------------------------------------- -// BackupTypeSection — simple keep-count + toggle rows per tier +// BackupTypeSection — keep-count + toggle rows per tier (hex accent required) // --------------------------------------------------------------------------- -const TIER_ORDER: BackupTier[] = ["M", "W", "D", "H"]; - -type TierState = { keep: number; enabled: boolean }; - function BackupTypeSection({ - title, scheduleType, serverId, schedules, onRefresh, accentColor, + title, scheduleType, serverId, schedules, onRefresh, accentHex, }: { title: string; scheduleType: BackupScheduleType; serverId: string; schedules: ScheduleRow[]; onRefresh: () => void; - accentColor: string; + accentHex: string; }) { const buildState = (): Record => { const s = {} as Record; for (const tier of TIER_ORDER) { const row = findTierSchedule(schedules, scheduleType, tier); - const cfg = row?.config_json ? (() => { try { return JSON.parse(row.config_json); } catch { return {}; } })() : {}; - s[tier] = { keep: cfg.keep ?? TIER_DEFAULT_KEEP[tier], enabled: row ? row.enabled === 1 : false }; + const cfg = row?.config_json ? parseCfg(row.config_json) : {}; + s[tier] = { keep: (cfg.keep as number) ?? TIER_DEFAULT_KEEP[tier], enabled: row ? row.enabled === 1 : false }; } return s; }; @@ -458,7 +571,6 @@ function BackupTypeSection({ const configJson = JSON.stringify({ tier, keep }); const cron = TIER_FIXED_CRON[tier]; const nextIso = getNextCronDate(cron)?.toISOString() ?? new Date().toISOString(); - if (existing) { await updateScheduleConfig(existing.id, cron, configJson, nextIso); if (enabled !== (existing.enabled === 1)) await updateScheduleEnabled(existing.id, enabled); @@ -481,14 +593,14 @@ function BackupTypeSection({ return (
-

{title}

+

{title}

{TIER_ORDER.map((tier) => (
{TIER_LABEL[tier]} backups to keep -
))} - ))}
- {/* 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" }} - /> + 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. + 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 && ( )} @@ -898,38 +919,42 @@ function UpdateAutomationCard({ server }: { server: ServerRow }) { ); } +// --------------------------------------------------------------------------- +// CARD_DEFS +// --------------------------------------------------------------------------- + +const CARD_DEFS: { type: ScheduleType; icon: React.ElementType; title: string; description: string }[] = [ + { type: "restart", icon: RotateCcw, title: "Auto-Restart", description: "Gracefully restart the server on a schedule with optional in-game warnings." }, + { type: "broadcast", icon: Megaphone, title: "Scheduled Chat Message", description: "Send a recurring global chat message to all online players via RCON." }, +]; + +// --------------------------------------------------------------------------- +// AutomationTab +// --------------------------------------------------------------------------- + +interface Props { server: ServerRow } + export function AutomationTab({ server }: Props) { const [schedules, setSchedules] = useState([]); - const [loading, setLoading] = useState(true); + const [loading, setLoading] = useState(true); const loadSchedules = useCallback(async () => { setLoading(true); - try { - setSchedules(await getServerSchedules(server.id)); - } catch (e) { - toast.error(`Failed to load schedules: ${e}`); - } finally { - setLoading(false); - } + try { setSchedules(await getServerSchedules(server.id)); } + catch (e) { toast.error(`Failed to load schedules: ${e}`); } + finally { setLoading(false); } }, [server.id]); useEffect(() => { loadSchedules(); }, [loadSchedules]); - function scheduleFor(type: ScheduleType): ScheduleRow | null { - return schedules.find((s) => s.schedule_type === type) ?? null; + function schedulesFor(type: ScheduleType): ScheduleRow[] { + return schedules.filter((s) => s.schedule_type === type); } return (
- {/* App-running notice */} -
+
Schedules only fire while LokiASAM is running. @@ -937,22 +962,14 @@ export function AutomationTab({ server }: Props) {
- {/* Header */}
-

- Automation -

+

Automation

-
@@ -966,13 +983,8 @@ export function AutomationTab({ server }: Props) {
) : (
- {/* Update automation — uses new per-server settings instead of schedule rows */} - - {/* Backup schedules — TimeShift tiers (server, player, full) */} - - {/* Restart, broadcast — cron-based schedule cards */} {CARD_DEFS.map((def) => ( ))}
)} - {/* Notification Config */}
); } // --------------------------------------------------------------------------- -// NotificationConfigSection — per-server channel configuration +// NotificationConfigSection // --------------------------------------------------------------------------- const CHANNEL_DEFS = [ + { id: "desktop", label: "Desktop Notifications", icon: Monitor, desc: "OS-level toast notifications via the system tray.", fields: [] }, { - id: "desktop", - label: "Desktop Notifications", - icon: Monitor, - desc: "OS-level toast notifications via the system tray.", - fields: [], - }, - { - id: "discord", - label: "Discord Webhook", - icon: MessageSquare, - desc: "POST an embed to a Discord channel webhook URL.", - fields: [ - { key: "webhookUrl", label: "Webhook URL", placeholder: "https://discord.com/api/webhooks/…", type: "url" }, - ], + id: "discord", label: "Discord Webhook", icon: MessageSquare, + desc: "POST an embed to a Discord channel webhook URL.", + fields: [{ key: "webhookUrl", label: "Webhook URL", placeholder: "https://discord.com/api/webhooks/…", type: "url" }], }, { - id: "email", - label: "Email / SMTP", - icon: Mail, - desc: "Send email alerts via your SMTP server.", + id: "email", label: "Email / SMTP", icon: Mail, + desc: "Send email alerts via your SMTP server.", fields: [ { key: "host", label: "SMTP Host", placeholder: "smtp.example.com", type: "text" }, { key: "port", label: "Port", placeholder: "587", type: "number" }, @@ -1031,7 +1030,7 @@ const CHANNEL_DEFS = [ }, ]; -const EVENT_OPTIONS: { value: string; label: string }[] = [ +const EVENT_OPTIONS = [ { value: NOTIFICATION_EVENTS.SERVER_STARTED, label: "Server Started" }, { value: NOTIFICATION_EVENTS.SERVER_STOPPED, label: "Server Stopped" }, { value: NOTIFICATION_EVENTS.SERVER_CRASHED, label: "Server Crashed" }, @@ -1041,63 +1040,33 @@ const EVENT_OPTIONS: { value: string; label: string }[] = [ { value: NOTIFICATION_EVENTS.SERVER_UPDATED, label: "Server Updated" }, ]; -interface NotificationConfigSectionProps { - serverId: string; -} - -function NotificationConfigSection({ serverId }: NotificationConfigSectionProps) { +function NotificationConfigSection({ serverId }: { serverId: string }) { const [open, setOpen] = useState(false); const [configs, setConfigs] = useState([]); const [saving, setSaving] = useState(null); const loadConfigs = useCallback(async () => { - try { - const rows = await getServerNotificationConfigs(serverId); - setConfigs(rows); - } catch (err) { - toast.error("Failed to load notification configs", { description: String(err) }); - } + try { setConfigs(await getServerNotificationConfigs(serverId)); } + catch (err) { toast.error("Failed to load notification configs", { description: String(err) }); } }, [serverId]); - useEffect(() => { - if (open) loadConfigs(); - }, [open, loadConfigs]); + useEffect(() => { if (open) loadConfigs(); }, [open, loadConfigs]); - function getConfig(channelId: string): NotificationConfigRow | undefined { - return configs.find((c) => c.channel === channelId); - } + function getConfig(channelId: string) { return configs.find((c) => c.channel === channelId); } async function handleToggle(channelId: string, enabled: boolean) { const existing = getConfig(channelId); const id = existing?.id ?? crypto.randomUUID(); - await saveNotificationConfig({ - id, - serverId, - channel: channelId, - enabled, - configJson: existing?.config_json ?? "{}", - eventsJson: existing?.events_json ?? "[]", - }); + await saveNotificationConfig({ id, serverId, channel: channelId, enabled, configJson: existing?.config_json ?? "{}", eventsJson: existing?.events_json ?? "[]" }); await loadConfigs(); } - async function handleSaveConfig( - channelId: string, - configJson: string, - eventsJson: string - ) { + async function handleSaveConfig(channelId: string, configJson: string, eventsJson: string) { setSaving(channelId); try { const existing = getConfig(channelId); const id = existing?.id ?? crypto.randomUUID(); - await saveNotificationConfig({ - id, - serverId, - channel: channelId, - enabled: existing?.enabled === 1, - configJson, - eventsJson, - }); + await saveNotificationConfig({ id, serverId, channel: channelId, enabled: existing?.enabled === 1, configJson, eventsJson }); await loadConfigs(); toast.success("Notification config saved."); } catch (e) { @@ -1116,26 +1085,12 @@ function NotificationConfigSection({ serverId }: NotificationConfigSectionProps) } else if (channelId === "discord") { const url = cfg.webhookUrl as string | undefined; if (!url) { toast.error("Enter a webhook URL first."); return; } - await tauriCmd.sendDiscordNotification(url, { - title: "LokiASAM Test", - description: "Discord notifications are working.", - color: 0x00ff88, - serverName: "Test", - eventType: "test", - }); + await tauriCmd.sendDiscordNotification(url, { title: "LokiASAM Test", description: "Discord notifications are working.", color: 0x00ff88, serverName: "Test", eventType: "test" }); } else if (channelId === "email") { const to = cfg.toAddress as string | undefined; if (!to) { toast.error("Enter a To address first."); return; } await tauriCmd.sendEmailNotification( - { - host: (cfg.host as string) ?? "", - port: Number(cfg.port ?? 587), - username: (cfg.username as string) ?? "", - password: (cfg.password as string) ?? "", - fromAddress: (cfg.fromAddress as string) ?? "noreply@lokiasam", - toAddress: to, - useTls: Boolean(cfg.useTls ?? false), - }, + { host: (cfg.host as string) ?? "", port: Number(cfg.port ?? 587), username: (cfg.username as string) ?? "", password: (cfg.password as string) ?? "", fromAddress: (cfg.fromAddress as string) ?? "noreply@lokiasam", toAddress: to, useTls: Boolean(cfg.useTls ?? false) }, { subject: "LokiASAM Test", body: "Email notifications are working." } ); } @@ -1146,26 +1101,15 @@ function NotificationConfigSection({ serverId }: NotificationConfigSectionProps) } return ( -
- {/* Collapsible header */} - {open && ( @@ -1175,24 +1119,12 @@ function NotificationConfigSection({ serverId }: NotificationConfigSectionProps) const enabled = row?.enabled === 1; const cfg = JSON.parse(row?.config_json ?? "{}") as Record; const events: string[] = JSON.parse(row?.events_json ?? "[]"); - const Icon = ch.icon; - return ( - handleToggle(ch.id, v)} onSave={(cfgJson, evJson) => handleSaveConfig(ch.id, cfgJson, evJson)} - onTest={() => handleTest(ch.id)} - /> + onTest={() => handleTest(ch.id)} /> ); })}
@@ -1202,40 +1134,31 @@ function NotificationConfigSection({ serverId }: NotificationConfigSectionProps) } // --------------------------------------------------------------------------- -// ChannelCard — individual notification channel config +// ChannelCard // --------------------------------------------------------------------------- interface ChannelCardProps { channelId: string; icon: React.ComponentType<{ className?: string; style?: React.CSSProperties }>; - label: string; - desc: string; + label: string; desc: string; fields: { key: string; label: string; placeholder: string; type: string }[]; - enabled: boolean; - cfg: Record; - events: string[]; + enabled: boolean; cfg: Record; events: string[]; saving: boolean; onToggle: (v: boolean) => void; onSave: (cfgJson: string, evJson: string) => void; onTest: () => void; } -function ChannelCard({ - channelId, icon: Icon, label, desc, fields, - enabled, cfg, events, saving, - onToggle, onSave, onTest, -}: ChannelCardProps) { - const [localCfg, setLocalCfg] = useState>(cfg); +function ChannelCard({ channelId, icon: Icon, label, desc, fields, enabled, cfg, events, saving, onToggle, onSave, onTest }: ChannelCardProps) { + const [localCfg, setLocalCfg] = useState>(cfg); const [localEvents, setLocalEvents] = useState(events); - const [expanded, setExpanded] = useState(false); + const [expanded, setExpanded] = useState(false); useEffect(() => { setLocalCfg(cfg); }, [JSON.stringify(cfg)]); useEffect(() => { setLocalEvents(events); }, [JSON.stringify(events)]); function toggleEvent(ev: string) { - setLocalEvents((prev) => - prev.includes(ev) ? prev.filter((e) => e !== ev) : [...prev, ev] - ); + setLocalEvents((prev) => prev.includes(ev) ? prev.filter((e) => e !== ev) : [...prev, ev]); } return ( @@ -1248,101 +1171,60 @@ function ChannelCard({
{enabled && ( - )} - -
{expanded && (
- {/* Config fields */} {fields.length > 0 && (
{fields.map((f) => (
- - - setLocalCfg((prev) => ({ ...prev, [f.key]: e.target.value })) - } - placeholder={f.placeholder} - className="h-7 text-xs" - style={{ background: "var(--surface)", borderColor: "var(--border)" }} - /> + + setLocalCfg((prev) => ({ ...prev, [f.key]: e.target.value }))} + placeholder={f.placeholder} className="h-7 text-xs" + style={{ background: "var(--surface)", borderColor: "var(--border)" }} />
))}
)} - - {/* Event filters */}

- Trigger on events{" "} - (all if none selected) + Trigger on events (all if none selected)

{EVENT_OPTIONS.map((ev) => { const active = localEvents.includes(ev.value); return ( - ); })}
- -
diff --git a/src/components/server/tabs/BackupsTab.tsx b/src/components/server/tabs/BackupsTab.tsx index 8c2f4a9..cdd9fe4 100644 --- a/src/components/server/tabs/BackupsTab.tsx +++ b/src/components/server/tabs/BackupsTab.tsx @@ -258,11 +258,11 @@ function BackupRowCard({ } // --------------------------------------------------------------------------- -// SectionHeader — title + [Edit Schedules] + [Backup Now] button row +// SectionHeader — title + [Backup X Now] (orange) + [Edit Schedule] (cyan) // --------------------------------------------------------------------------- function SectionHeader({ - icon: Icon, title, color, count, onEditSchedules, onManualBackup, isBusy, manualLabel, + icon: Icon, title, color, count, onEditSchedules, onManualBackup, isBusy, backupLabel, }: { icon: React.ElementType; title: string; @@ -271,7 +271,7 @@ function SectionHeader({ onEditSchedules?: () => void; onManualBackup: () => void; isBusy: boolean; - manualLabel?: string; + backupLabel: string; }) { return (
{count > 0 && ( - + {count} )}
+ {onEditSchedules && ( - )} -
); @@ -322,7 +327,7 @@ function SectionHeader({ function BackupSectionPanel({ icon: Icon, title, color, backups, loading, onRestore, onDelete, onManualBackup, - onEditSchedules, restoreDisabled, children, + onEditSchedules, restoreDisabled, backupLabel, children, }: { icon: React.ElementType; title: string; @@ -334,6 +339,7 @@ function BackupSectionPanel({ onManualBackup: () => void; onEditSchedules?: () => void; restoreDisabled: boolean; + backupLabel: string; children?: React.ReactNode; }) { return ( @@ -344,6 +350,7 @@ function BackupSectionPanel({ onEditSchedules={onEditSchedules} onManualBackup={onManualBackup} isBusy={restoreDisabled} + backupLabel={backupLabel} />
@@ -410,7 +417,7 @@ function PlayerBackupSection({ onEditSchedules={onEditSchedules} onManualBackup={onManualBackup} isBusy={restoreDisabled} - manualLabel="Backup All Players" + backupLabel="Backup Players Now" />
@@ -521,10 +528,10 @@ function IniBackupSection({
{onEditSchedules && ( - )}
@@ -728,9 +735,18 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { } } + // ── Navigation helper — switch to automation tab then scroll to backup section + function handleEditSchedule() { + onNavigateToAutomation?.(); + setTimeout(() => { + document.getElementById("backup-schedules-section")?.scrollIntoView({ behavior: "smooth", block: "start" }); + }, 150); + } + // ── Render ───────────────────────────────────────────────────────────────── const isBusy = progress.active; + const editScheduleBtn = onNavigateToAutomation ? handleEditSchedule : undefined; return (
@@ -786,7 +802,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { installPath={server.install_path} isBusy={isBusy} onBusyChange={(b) => setProgress((p) => ({ ...p, active: b }))} - onEditSchedules={onNavigateToAutomation} + onEditSchedules={editScheduleBtn} /> )} @@ -796,8 +812,9 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { backups={serverBackups} loading={loading} onRestore={setRestoreTarget} onDelete={handleDelete} onManualBackup={handleServerBackup} - onEditSchedules={onNavigateToAutomation} + onEditSchedules={editScheduleBtn} restoreDisabled={isBusy} + backupLabel="Backup Server Now" /> {/* Player backups */} @@ -806,7 +823,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { playerBackups={playerBackups} loading={loading} onRestore={setRestoreTarget} onDelete={handleDelete} onManualBackup={() => toast.info("Player backups are triggered automatically by the scheduler.")} - onEditSchedules={onNavigateToAutomation} + onEditSchedules={editScheduleBtn} restoreDisabled={isBusy} /> @@ -816,8 +833,9 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { backups={fullBackups} loading={loading} onRestore={setRestoreTarget} onDelete={handleDelete} onManualBackup={handleFullBackupClick} - onEditSchedules={onNavigateToAutomation} + onEditSchedules={editScheduleBtn} restoreDisabled={isBusy} + backupLabel="Backup Full Now" /> {restoreTarget && ( From e0a2d9486b7b47014085ff44616d21a9f7794a72 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 9 Jun 2026 13:10:13 -0500 Subject: [PATCH 07/15] Refactor color styles in SetupWizard component to use CSS variables for neon theme consistency; update theme preset colors for improved aesthetics. --- src/app/backups/page.tsx | 8 +- src/app/clusters/detail/page.tsx | 6 +- src/app/clusters/page.tsx | 19 +- src/app/globals.css | 10 +- src/app/logs/page.tsx | 10 +- src/app/notifications/page.tsx | 19 +- src/app/page.tsx | 36 +- src/app/servers/detail/page.tsx | 6 +- src/app/settings/page.tsx | 42 +-- src/components/layout/AppShell.tsx | 2 +- src/components/layout/DisableContextMenu.tsx | 8 +- src/components/layout/Sidebar.tsx | 8 +- .../layout/StartupRecoveryManager.tsx | 2 +- src/components/layout/TopBar.tsx | 4 +- src/components/server/ImportServerWizard.tsx | 12 +- src/components/server/ServerActionMenu.tsx | 2 +- src/components/server/ServerCard.tsx | 22 +- src/components/server/rcon/RconConsole.tsx | 26 +- src/components/server/tabs/AutomationTab.tsx | 326 +++--------------- src/components/server/tabs/BackupsTab.tsx | 36 +- src/components/server/tabs/ConfigTab.tsx | 48 +-- src/components/server/tabs/LogsTab.tsx | 32 +- src/components/server/tabs/ModsTab.tsx | 24 +- src/components/server/tabs/OverviewTab.tsx | 32 +- src/components/shared/CommandOutputPanel.tsx | 8 +- src/components/shared/CronBuilder.tsx | 10 +- src/components/shared/NumberField.tsx | 6 +- src/components/ui/slider.tsx | 2 +- .../wizard/ServerCreationWizard.tsx | 114 +++--- src/components/wizard/SetupWizard.tsx | 150 ++++---- src/lib/theme.ts | 6 +- 31 files changed, 412 insertions(+), 624 deletions(-) diff --git a/src/app/backups/page.tsx b/src/app/backups/page.tsx index 1bdd967..aa4975d 100644 --- a/src/app/backups/page.tsx +++ b/src/app/backups/page.tsx @@ -44,7 +44,7 @@ export default function BackupsPage() { />

Backups

@@ -53,7 +53,7 @@ export default function BackupsPage() { {/* Server selector */}
Server: @@ -73,7 +73,7 @@ export default function BackupsPage() { className="w-full h-9 pl-3 pr-8 text-sm rounded-lg appearance-none cursor-pointer" style={{ background: "rgba(0,0,0,0.4)", - border: "1px solid rgba(191,0,255,0.25)", + border: "1px solid rgba(var(--neon-purple-rgb),0.25)", color: "var(--text-primary)", }} > @@ -108,7 +108,7 @@ export default function BackupsPage() { ) : !isLoading && servers.length === 0 ? (

diff --git a/src/app/clusters/detail/page.tsx b/src/app/clusters/detail/page.tsx index 09b312f..71a624a 100644 --- a/src/app/clusters/detail/page.tsx +++ b/src/app/clusters/detail/page.tsx @@ -296,8 +296,8 @@ function ClusterDetailContent() {

@@ -333,7 +333,7 @@ function ClusterDetailContent() { style={{ background: "rgba(0,0,0,0.3)", color: "var(--neon-cyan)", - border: "1px solid rgba(0,255,255,0.15)", + border: "1px solid rgba(var(--neon-purple-rgb),0.15)", }} > {cluster.id} diff --git a/src/app/clusters/page.tsx b/src/app/clusters/page.tsx index f4b5903..ffc81f9 100644 --- a/src/app/clusters/page.tsx +++ b/src/app/clusters/page.tsx @@ -237,8 +237,8 @@ function ClusterCard({ cluster, onDelete }: ClusterCardProps) {
@@ -317,12 +317,15 @@ export default function ClustersPage() { {/* Header */}
-

- Clusters -

+
+ +

+ Clusters +

+

Group servers for cross-ARK travel and shared data.

diff --git a/src/app/globals.css b/src/app/globals.css index 409bbf6..1acbe18 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -39,7 +39,7 @@ --color-primary-foreground: #050510; --color-input: rgba(var(--neon-purple-rgb), 0.2); --color-ring: #bf00ff; - --color-muted: rgba(10, 10, 30, 0.75); + --color-muted: rgba(20, 20, 52, 0.85); --color-muted-foreground: #5858a0; /* Fonts */ @@ -57,8 +57,8 @@ :root { /* Backgrounds */ --background: #050510; - --surface: rgba(10, 10, 30, 0.75); - --surface-elevated: rgba(15, 15, 40, 0.9); + --surface: rgba(20, 20, 52, 0.85); + --surface-elevated: rgba(28, 28, 68, 0.92); --terminal-bg: #000008; /* Accent RGB components — updated by applyThemeAccent() so all rgba() uses track the active color */ @@ -88,12 +88,12 @@ --glow-red: 0 0 8px rgba(255,0,85,0.6), 0 0 24px rgba(255,0,85,0.2); /* Card glass — purple-tinted borders */ - --glass-bg: rgba(10, 10, 35, 0.6); + --glass-bg: rgba(18, 18, 50, 0.72); --glass-border: rgba(191, 0, 255, 0.12); --glass-blur: 12px; /* Popover / dropdown surface */ - --popover: #0c0c20; + --popover: #101028; --popover-foreground: #e0e0ff; /* Accent — subtle purple highlight for menu item hover/focus */ diff --git a/src/app/logs/page.tsx b/src/app/logs/page.tsx index d3d7029..4aea937 100644 --- a/src/app/logs/page.tsx +++ b/src/app/logs/page.tsx @@ -40,11 +40,11 @@ export default function LogsPage() {

Logs

@@ -53,7 +53,7 @@ export default function LogsPage() { {/* ── Server selector ── */}
Server: @@ -73,7 +73,7 @@ export default function LogsPage() { className="w-full h-9 pl-3 pr-8 text-sm rounded-lg appearance-none cursor-pointer" style={{ background: "rgba(0,0,0,0.4)", - border: "1px solid rgba(0,255,255,0.25)", + border: "1px solid rgba(var(--neon-purple-rgb),0.25)", color: "var(--text-primary)", }} > @@ -108,7 +108,7 @@ export default function LogsPage() { ) : !isLoading && servers.length === 0 ? (

diff --git a/src/app/notifications/page.tsx b/src/app/notifications/page.tsx index a61f6bf..b17fe8a 100644 --- a/src/app/notifications/page.tsx +++ b/src/app/notifications/page.tsx @@ -89,9 +89,9 @@ function NotificationRow({ style={{ borderColor: "var(--border)", background: highlighted - ? "rgba(191,0,255,0.12)" + ? "rgba(var(--neon-purple-rgb),0.12)" : "transparent", - outline: highlighted ? "1px solid rgba(191,0,255,0.4)" : "none", + outline: highlighted ? "1px solid rgba(var(--neon-purple-rgb),0.4)" : "none", }} > @@ -224,12 +224,15 @@ function NotificationsContent() { {/* Header */}

-

- Notifications -

+
+ +

+ Notifications +

+

Event log for all managed servers.

diff --git a/src/app/page.tsx b/src/app/page.tsx index 468cfd1..a7fc8b5 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -3,7 +3,7 @@ import { useEffect, useState, useCallback, useRef } from "react"; import { Plus, Server, Activity, PowerOff, Power, RefreshCw, Upload, - ArrowUp, Loader2, CheckCircle2, AlertTriangle, + ArrowUp, Loader2, CheckCircle2, AlertTriangle, LayoutDashboard, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; @@ -159,7 +159,7 @@ function UpdateStatusChip({ servers = [], onUpdateAllClick, onUpdatesFound }: Up disabled={checking} onClick={handleCheck} className="h-7 gap-1.5 text-xs" - style={{ borderColor: "rgba(191,0,255,0.3)", color: "var(--text-muted)" }} + style={{ borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--neon-purple)" }} > {checking ? @@ -271,7 +271,7 @@ function UpdatesFoundDialog({ open, onOpenChange, updates, onUpdateAll }: Update diff --git a/src/app/servers/detail/page.tsx b/src/app/servers/detail/page.tsx index ee73ac0..1958397 100644 --- a/src/app/servers/detail/page.tsx +++ b/src/app/servers/detail/page.tsx @@ -164,7 +164,7 @@ export default function ServerDetailPage() { className="flex gap-1 p-1 rounded-xl flex-wrap shrink-0" style={{ background: "rgba(0,0,0,0.4)", - border: "1px solid rgba(191,0,255,0.15)", + border: "1px solid rgba(var(--neon-purple-rgb),0.15)", }} > {TABS.map(({ value, label, icon: Icon }) => { @@ -177,8 +177,8 @@ export default function ServerDetailPage() { className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-lg transition-all cursor-pointer" style={{ color: active ? "var(--neon-purple)" : "var(--text-muted)", - background: active ? "rgba(191,0,255,0.12)" : "transparent", - border: active ? "1px solid rgba(191,0,255,0.3)" : "1px solid transparent", + background: active ? "rgba(var(--neon-purple-rgb),0.12)" : "transparent", + border: active ? "1px solid rgba(var(--neon-purple-rgb),0.3)" : "1px solid transparent", fontWeight: active ? 600 : 400, textShadow: active ? "var(--glow-purple)" : "none", }} diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index 3f0b170..d31b276 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -315,7 +315,7 @@ function BaseDirMigrationSection() { )} @@ -392,7 +392,7 @@ function PathField({ @@ -853,7 +853,7 @@ function ServerUpdatesSection() { {AUTO_CHECK_OPTIONS.map((opt) => (
@@ -1018,8 +1018,8 @@ function SteamcmdReinstallRow() { )} @@ -1173,8 +1173,8 @@ function ProtonGeUpdateSection() { {(updateInfo?.updateAvailable || (!protonPath && updateInfo)) && (isManaged || !looksExternal) && ( @@ -584,7 +584,7 @@ export function ServerCard({ server }: Props) { queryClient.invalidateQueries({ queryKey: ["servers"] }); }} className="gap-1.5 ml-auto" - style={{ color: "var(--text-muted)", borderColor: "rgba(191,0,255,0.2)" }} + style={{ color: "var(--text-muted)", borderColor: "rgba(var(--neon-purple-rgb),0.2)" }} > Cancel @@ -602,7 +602,7 @@ export function ServerCard({ server }: Props) { queryClient.invalidateQueries({ queryKey: ["servers"] }); }} className="gap-1.5 ml-auto" - style={{ color: "var(--text-muted)", borderColor: "rgba(191,0,255,0.2)" }} + style={{ color: "var(--text-muted)", borderColor: "rgba(var(--neon-purple-rgb),0.2)" }} > Cancel @@ -623,7 +623,7 @@ export function ServerCard({ server }: Props) { )} @@ -668,7 +668,7 @@ export function ServerCard({ server }: Props) { {isRunning && ( @@ -698,7 +698,7 @@ export function ServerCard({ server }: Props) { diff --git a/src/components/server/rcon/RconConsole.tsx b/src/components/server/rcon/RconConsole.tsx index 4ddbfa8..7cd8ff9 100644 --- a/src/components/server/rcon/RconConsole.tsx +++ b/src/components/server/rcon/RconConsole.tsx @@ -302,7 +302,7 @@ export function RconConsole({ server }: Props) { {/* ── Status bar ── */}
{/* Online players */} -
-
+
+
Online ({players.length}) @@ -455,7 +455,7 @@ export function RconConsole({ server }: Props) {
{lines.map((l, i) => (
@@ -475,12 +475,12 @@ export function RconConsole({ server }: Props) { {connected && (
@@ -488,7 +488,7 @@ export function RconConsole({ server }: Props) { {/* SetTimeOfDay dropdown */}
{showTimeMenu && (
+ style={{ background: "rgba(5,5,16,0.98)", border: "1px solid rgba(var(--neon-purple-rgb),0.2)", minWidth: "110px" }}> {TIME_PRESETS.map((p) => ( @@ -629,8 +627,8 @@ function BackupTypeSection({ @@ -718,8 +716,8 @@ function FullBackupScheduleSection({ serverId, schedules, onRefresh }: {
)} {automation.mode !== "off" && (
+ style={{ background: "rgba(var(--neon-purple-rgb),0.04)", border: "1px solid rgba(var(--neon-purple-rgb),0.12)", color: "var(--text-muted)" }}> Automated triggers are coming in a future update once proper RCON shutdown is implemented. @@ -898,18 +896,20 @@ function UpdateAutomationCard({ server }: { server: ServerRow }) {
{automation.mode !== "off" && ( -
+
{automation.restart_after_update && ( )} @@ -954,7 +954,7 @@ export function AutomationTab({ server }: Props) { return (
+ style={{ background: "rgba(var(--neon-purple-rgb),0.04)", border: "1px solid rgba(var(--neon-purple-rgb),0.15)", color: "var(--text-muted)" }}> Schedules only fire while LokiASAM is running. @@ -978,7 +978,7 @@ export function AutomationTab({ server }: Props) {
{[1, 2, 3, 4].map((n) => (
+ style={{ border: "1px solid rgba(var(--neon-purple-rgb),0.1)" }} /> ))}
) : ( @@ -1000,235 +1000,7 @@ export function AutomationTab({ server }: Props) {
)} -
); } -// --------------------------------------------------------------------------- -// NotificationConfigSection -// --------------------------------------------------------------------------- - -const CHANNEL_DEFS = [ - { id: "desktop", label: "Desktop Notifications", icon: Monitor, desc: "OS-level toast notifications via the system tray.", fields: [] }, - { - id: "discord", label: "Discord Webhook", icon: MessageSquare, - desc: "POST an embed to a Discord channel webhook URL.", - fields: [{ key: "webhookUrl", label: "Webhook URL", placeholder: "https://discord.com/api/webhooks/…", type: "url" }], - }, - { - id: "email", label: "Email / SMTP", icon: Mail, - desc: "Send email alerts via your SMTP server.", - fields: [ - { key: "host", label: "SMTP Host", placeholder: "smtp.example.com", type: "text" }, - { key: "port", label: "Port", placeholder: "587", type: "number" }, - { key: "username", label: "Username", placeholder: "user@example.com", type: "text" }, - { key: "password", label: "Password", placeholder: "••••••••", type: "password" }, - { key: "fromAddress", label: "From", placeholder: "noreply@example.com", type: "email" }, - { key: "toAddress", label: "To", placeholder: "admin@example.com", type: "email" }, - ], - }, -]; - -const EVENT_OPTIONS = [ - { value: NOTIFICATION_EVENTS.SERVER_STARTED, label: "Server Started" }, - { value: NOTIFICATION_EVENTS.SERVER_STOPPED, label: "Server Stopped" }, - { value: NOTIFICATION_EVENTS.SERVER_CRASHED, label: "Server Crashed" }, - { value: NOTIFICATION_EVENTS.SERVER_START_FAILED, label: "Server Failed to Start" }, - { value: NOTIFICATION_EVENTS.BACKUP_COMPLETED, label: "Backup Completed" }, - { value: NOTIFICATION_EVENTS.BACKUP_FAILED, label: "Backup Failed" }, - { value: NOTIFICATION_EVENTS.SERVER_UPDATED, label: "Server Updated" }, -]; - -function NotificationConfigSection({ serverId }: { serverId: string }) { - const [open, setOpen] = useState(false); - const [configs, setConfigs] = useState([]); - const [saving, setSaving] = useState(null); - - const loadConfigs = useCallback(async () => { - try { setConfigs(await getServerNotificationConfigs(serverId)); } - catch (err) { toast.error("Failed to load notification configs", { description: String(err) }); } - }, [serverId]); - - useEffect(() => { if (open) loadConfigs(); }, [open, loadConfigs]); - - function getConfig(channelId: string) { return configs.find((c) => c.channel === channelId); } - - async function handleToggle(channelId: string, enabled: boolean) { - const existing = getConfig(channelId); - const id = existing?.id ?? crypto.randomUUID(); - await saveNotificationConfig({ id, serverId, channel: channelId, enabled, configJson: existing?.config_json ?? "{}", eventsJson: existing?.events_json ?? "[]" }); - await loadConfigs(); - } - - async function handleSaveConfig(channelId: string, configJson: string, eventsJson: string) { - setSaving(channelId); - try { - const existing = getConfig(channelId); - const id = existing?.id ?? crypto.randomUUID(); - await saveNotificationConfig({ id, serverId, channel: channelId, enabled: existing?.enabled === 1, configJson, eventsJson }); - await loadConfigs(); - toast.success("Notification config saved."); - } catch (e) { - toast.error(`Failed to save config: ${e}`); - } finally { - setSaving(null); - } - } - - async function handleTest(channelId: string) { - const config = getConfig(channelId); - const cfg = JSON.parse(config?.config_json ?? "{}") as Record; - try { - if (channelId === "desktop") { - await tauriCmd.sendOsNotification("LokiASAM Test", "Desktop notifications are working."); - } else if (channelId === "discord") { - const url = cfg.webhookUrl as string | undefined; - if (!url) { toast.error("Enter a webhook URL first."); return; } - await tauriCmd.sendDiscordNotification(url, { title: "LokiASAM Test", description: "Discord notifications are working.", color: 0x00ff88, serverName: "Test", eventType: "test" }); - } else if (channelId === "email") { - const to = cfg.toAddress as string | undefined; - if (!to) { toast.error("Enter a To address first."); return; } - await tauriCmd.sendEmailNotification( - { host: (cfg.host as string) ?? "", port: Number(cfg.port ?? 587), username: (cfg.username as string) ?? "", password: (cfg.password as string) ?? "", fromAddress: (cfg.fromAddress as string) ?? "noreply@lokiasam", toAddress: to, useTls: Boolean(cfg.useTls ?? false) }, - { subject: "LokiASAM Test", body: "Email notifications are working." } - ); - } - toast.success("Test notification sent."); - } catch (e) { - toast.error(`Test failed: ${e}`); - } - } - - return ( -
- - - {open && ( -
- {CHANNEL_DEFS.map((ch) => { - const row = getConfig(ch.id); - const enabled = row?.enabled === 1; - const cfg = JSON.parse(row?.config_json ?? "{}") as Record; - const events: string[] = JSON.parse(row?.events_json ?? "[]"); - return ( - handleToggle(ch.id, v)} - onSave={(cfgJson, evJson) => handleSaveConfig(ch.id, cfgJson, evJson)} - onTest={() => handleTest(ch.id)} /> - ); - })} -
- )} -
- ); -} - -// --------------------------------------------------------------------------- -// ChannelCard -// --------------------------------------------------------------------------- - -interface ChannelCardProps { - channelId: string; - icon: React.ComponentType<{ className?: string; style?: React.CSSProperties }>; - label: string; desc: string; - fields: { key: string; label: string; placeholder: string; type: string }[]; - enabled: boolean; cfg: Record; events: string[]; - saving: boolean; - onToggle: (v: boolean) => void; - onSave: (cfgJson: string, evJson: string) => void; - onTest: () => void; -} - -function ChannelCard({ channelId, icon: Icon, label, desc, fields, enabled, cfg, events, saving, onToggle, onSave, onTest }: ChannelCardProps) { - const [localCfg, setLocalCfg] = useState>(cfg); - const [localEvents, setLocalEvents] = useState(events); - const [expanded, setExpanded] = useState(false); - - useEffect(() => { setLocalCfg(cfg); }, [JSON.stringify(cfg)]); - useEffect(() => { setLocalEvents(events); }, [JSON.stringify(events)]); - - function toggleEvent(ev: string) { - setLocalEvents((prev) => prev.includes(ev) ? prev.filter((e) => e !== ev) : [...prev, ev]); - } - - return ( -
-
- -
-

{label}

-

{desc}

-
-
- {enabled && ( - - )} - - -
-
- - {expanded && ( -
- {fields.length > 0 && ( -
- {fields.map((f) => ( -
- - setLocalCfg((prev) => ({ ...prev, [f.key]: e.target.value }))} - placeholder={f.placeholder} className="h-7 text-xs" - style={{ background: "var(--surface)", borderColor: "var(--border)" }} /> -
- ))} -
- )} -
-

- Trigger on events (all if none selected) -

-
- {EVENT_OPTIONS.map((ev) => { - const active = localEvents.includes(ev.value); - return ( - - ); - })} -
-
- -
- )} -
- ); -} diff --git a/src/components/server/tabs/BackupsTab.tsx b/src/components/server/tabs/BackupsTab.tsx index cdd9fe4..d7a3458 100644 --- a/src/components/server/tabs/BackupsTab.tsx +++ b/src/components/server/tabs/BackupsTab.tsx @@ -103,7 +103,7 @@ function RestoreConfirmDialog({
{/* Tier tags + date */} @@ -277,13 +277,13 @@ function SectionHeader({
@@ -291,7 +291,7 @@ function SectionHeader({ {title} {count > 0 && ( - + {count} )} @@ -299,9 +299,9 @@ function SectionHeader({ @@ -309,9 +309,9 @@ function SectionHeader({ @@ -343,7 +343,7 @@ function BackupSectionPanel({ children?: React.ReactNode; }) { return ( -
+
+
+
+ style={{ background: "rgba(var(--neon-purple-rgb),0.1)", border: "1px solid rgba(var(--neon-purple-rgb),0.35)", color: "var(--neon-purple)" }}> Edit Schedule )} @@ -753,7 +753,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { {/* Progress overlay */} {progress.active && (
+ style={{ border: "1px solid rgba(var(--neon-purple-rgb),0.3)" }}>
diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index 468560a..c97f850 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -159,7 +159,7 @@ function FieldRow({ onChange={(e) => onChange(e.target.value)} placeholder={field.placeholder} 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(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} />
); @@ -214,7 +214,7 @@ function LaunchParamRow({ placeholder={String(param.defaultValue) || "(empty = disabled)"} onChange={(e) => 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)" }} + style={{ background: "rgba(0,0,0,0.3)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} />
); @@ -231,13 +231,13 @@ function LaunchParamGroup({ const args = (config.launchArgs ?? {}) as Record; return ( -
+
-
+

Server name, passwords, and ports are managed on the overview page and are excluded here. @@ -377,13 +377,13 @@ function FullIniModal({ if (visibleFields.length === 0) return null; const open = expandedGroups.has(group.id); return ( -

+
{/* Footer */} -
+
@@ -460,7 +460,7 @@ function ShutdownSettingsCard({ server }: { server: ServerRow }) { return (
@@ -487,7 +487,7 @@ function ShutdownSettingsCard({ server }: { server: ServerRow }) { value={warnMinutes} onChange={(e) => 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)" }} + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} />
@@ -499,7 +499,7 @@ function ShutdownSettingsCard({ server }: { server: ServerRow }) { onChange={(e) => 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)" }} + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} />
@@ -509,8 +509,8 @@ function ShutdownSettingsCard({ server }: { server: ServerRow }) { onClick={handleSave} disabled={saving} style={{ - background: saved ? "rgba(0,255,136,0.15)" : "rgba(191,0,255,0.15)", - border: saved ? "1px solid rgba(0,255,136,0.4)" : "1px solid rgba(191,0,255,0.4)", + background: saved ? "rgba(0,255,136,0.15)" : "rgba(var(--neon-purple-rgb),0.15)", + border: saved ? "1px solid rgba(0,255,136,0.4)" : "1px solid rgba(var(--neon-purple-rgb),0.4)", color: saved ? "var(--neon-green)" : "var(--neon-purple)", }} > @@ -676,7 +676,7 @@ export function ConfigTab({ server }: Props) { variant="ghost" onClick={() => setShowFullModal(true)} disabled={!config} - style={{ color: "var(--neon-purple)", borderColor: "rgba(191,0,255,0.3)" }} + style={{ color: "var(--neon-purple)", borderColor: "rgba(var(--neon-purple-rgb),0.3)" }} > Full INI Editor @@ -738,22 +738,22 @@ export function ConfigTab({ server }: Props) { {rawMode && (
-

GameUserSettings.ini

+

GameUserSettings.ini