From e0ddce4d593c1368bc64298ae8cfa6d0c02db187 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 22 Jun 2026 10:42:40 -0500 Subject: [PATCH 01/28] feat: enhance backup functionality with alt save directory support --- src-tauri/src/commands/backup.rs | 8 +-- src-tauri/src/commands/backup_manager.rs | 34 +++++---- src-tauri/src/commands/scheduler.rs | 1 + src-tauri/src/commands/server.rs | 11 ++- src/components/server/ServerActionMenu.tsx | 4 +- src/components/server/tabs/BackupsTab.tsx | 6 +- src/components/server/tabs/OverviewTab.tsx | 81 +++++++++++++++++++--- src/lib/server-utils.ts | 11 ++- src/lib/tauri-commands.ts | 2 + 9 files changed, 118 insertions(+), 40 deletions(-) diff --git a/src-tauri/src/commands/backup.rs b/src-tauri/src/commands/backup.rs index a66f97b..80fdab5 100644 --- a/src-tauri/src/commands/backup.rs +++ b/src-tauri/src/commands/backup.rs @@ -393,7 +393,7 @@ pub async fn create_server_backup( let size = fmt_size(rec.file_size_bytes); crate::commands::notifications::dispatch_notification( &app, "backup_completed", Some(&server_id), &server_name, - "Backup Complete", &format!("Server backup completed ({size})"), "success", + "Server Backup", &format!("{server_name} — server backup complete ({size})"), "success", ).await; } result @@ -595,7 +595,7 @@ pub async fn backup_all_players( if count > 0 { crate::commands::notifications::dispatch_notification( &app, "backup_completed", Some(&server_id), &server_name, - "Backup Complete", &format!("Player backups completed ({count} players)"), "success", + "Player Backup", &format!("{server_name} — {count} player backups complete"), "success", ).await; } } @@ -702,7 +702,7 @@ pub async fn create_player_backup( let display_name = rec.player_name.as_deref().unwrap_or(&eos_id); crate::commands::notifications::dispatch_notification( &app, "backup_completed", Some(&server_id), &server_name, - "Backup Complete", &format!("Player backup for {display_name} completed ({size})"), "success", + "Player Backup", &format!("{server_name} — backup for {display_name} complete ({size})"), "success", ).await; } result @@ -1013,7 +1013,7 @@ pub async fn create_full_backup( let size = fmt_size(rec.file_size_bytes); crate::commands::notifications::dispatch_notification( &app, "backup_completed", Some(&rec.server_id), &server_name, - "Backup Complete", &format!("Full backup completed ({size})"), "success", + "Full Backup", &format!("{server_name} — full backup complete ({size})"), "success", ).await; Ok(rec) } diff --git a/src-tauri/src/commands/backup_manager.rs b/src-tauri/src/commands/backup_manager.rs index 1e7e401..8ae4a27 100644 --- a/src-tauri/src/commands/backup_manager.rs +++ b/src-tauri/src/commands/backup_manager.rs @@ -387,7 +387,10 @@ pub async fn handle_player_login(app: &AppHandle, server_id: &str, eos_id: &str, _ => return, }; - let map_path = map_id_to_path(&server.map_id); + let base_map_path = map_id_to_path(&server.map_id); + let map_path = server.save_folder_name.as_deref() + .filter(|s| !s.is_empty()) + .unwrap_or(base_map_path); // Create the archive (eos_id used as player_name for the filename). let rec = match create_player_backup_inner( @@ -590,63 +593,64 @@ pub async fn execute_tick(app: &AppHandle) { // One notification per server per tick regardless of how many backup // types ran. Titles are specific when only one type ran; generic when // both ran so the body can carry the combined detail. + let sname = &server.name; let notification: Option<(&str, &str, String, &str)> = match (&server_outcome, &player_outcome) { // Both ran — both succeeded (Some(Ok(size)), Some(Ok(count))) if *count > 0 => Some(( - "backup_completed", "Backup Complete", - format!("Server backup: {size} · {count} players backed up"), + "backup_completed", "Server & Player Backup", + format!("{sname} — server backup: {size} · {count} players"), "success", )), // Both ran — server ok, players ran but 0 profiles found (Some(Ok(size)), Some(Ok(_))) => Some(( - "backup_completed", "Server Backup Complete", - format!("Scheduled server backup completed ({size})"), + "backup_completed", "Server Backup", + format!("{sname} — server backup complete ({size})"), "success", )), // Both ran — server ok, players failed (Some(Ok(size)), Some(Err(pe))) => Some(( "backup_failed", "Backup Partially Failed", - format!("Server backup complete ({size}) · Player backup failed: {pe}"), + format!("{sname} — server backup: {size} · player backup failed: {pe}"), "error", )), // Both ran — server failed, players ok (Some(Err(se)), Some(Ok(count))) if *count > 0 => Some(( "backup_failed", "Backup Partially Failed", - format!("Server backup failed: {se} · {count} player backups complete"), + format!("{sname} — server backup failed: {se} · {count} player backups complete"), "error", )), // Both ran — server failed, 0 players (Some(Err(se)), Some(Ok(_))) => Some(( "backup_failed", "Server Backup Failed", - format!("Scheduled server backup failed: {se}"), + format!("{sname} — server backup failed: {se}"), "error", )), // Both ran — both failed (Some(Err(se)), Some(Err(pe))) => Some(( "backup_failed", "Backup Failed", - format!("Server backup failed: {se} · Player backup failed: {pe}"), + format!("{sname} — server backup failed: {se} · player backup failed: {pe}"), "error", )), // Server only (Some(Ok(size)), None) => Some(( - "backup_completed", "Server Backup Complete", - format!("Scheduled server backup completed ({size})"), + "backup_completed", "Server Backup", + format!("{sname} — server backup complete ({size})"), "success", )), (Some(Err(se)), None) => Some(( "backup_failed", "Server Backup Failed", - format!("Scheduled server backup failed: {se}"), + format!("{sname} — server backup failed: {se}"), "error", )), // Player only (None, Some(Ok(count))) if *count > 0 => Some(( - "backup_completed", "Player Backup Complete", - format!("Scheduled player backups completed ({count} players)"), + "backup_completed", "Player Backup", + format!("{sname} — {count} player backups complete"), "success", )), (None, Some(Err(pe))) => Some(( "backup_failed", "Player Backup Failed", - format!("Scheduled player backup failed: {pe}"), + format!("{sname} — player backup failed: {pe}"), "error", )), // Player only with 0 profiles, or nothing ran diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index 47cd841..b99898a 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -349,6 +349,7 @@ fn entry_to_start_params(entry: &crate::state::scheduler::ScheduleEntry) -> Star mod_ids: entry.mod_ids.clone(), proton_path: entry.proton_path.clone(), prefix_path: entry.prefix_path.clone(), + alt_save_directory_name: None, } } diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 8119f9b..388dbaa 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -116,6 +116,9 @@ pub struct StartServerParams { pub proton_path: Option, /// Linux only: WINEPREFIX path where Proton creates its fake C: drive. pub prefix_path: Option, + /// When set, appended as ?AltSaveDirectoryName= in the map query string. + /// ASA reads this from the URL and saves to SavedArks/{name} instead of SavedArks/{mapPath}. + pub alt_save_directory_name: Option, } // --------------------------------------------------------------------------- @@ -238,11 +241,16 @@ async fn inner_start_server_with_state( // Passwords, RCON, MaxPlayers, and all gameplay settings are read by the // server from GameUserSettings.ini — they must NOT be duplicated on the CLI // or they will override INI values on every restart. + let alt_save = params.alt_save_directory_name.as_deref() + .filter(|s| !s.is_empty()) + .map(|s| format!("?AltSaveDirectoryName={s}")) + .unwrap_or_default(); let query_string = format!( - "{}?listen?Port={}?QueryPort={}", + "{}?listen?Port={}?QueryPort={}{}", params.map_path, params.port, params.query_port, + alt_save, ); // Build the platform-specific Command. @@ -946,6 +954,7 @@ pub async fn scan_running_servers( mod_ids: vec![], proton_path: None, prefix_path: None, + alt_save_directory_name: None, }; registry.insert( entry.server_id.clone(), diff --git a/src/components/server/ServerActionMenu.tsx b/src/components/server/ServerActionMenu.tsx index 3808e44..360c5d7 100644 --- a/src/components/server/ServerActionMenu.tsx +++ b/src/components/server/ServerActionMenu.tsx @@ -391,7 +391,9 @@ export function ServerActionMenu({ server }: Props) { mapPath, server.map_id, backupDir, - "manual" + "manual", + "", + server.save_folder_name || undefined ); await insertBackup({ id: record.id, diff --git a/src/components/server/tabs/BackupsTab.tsx b/src/components/server/tabs/BackupsTab.tsx index 4072b7c..9c2bbdf 100644 --- a/src/components/server/tabs/BackupsTab.tsx +++ b/src/components/server/tabs/BackupsTab.tsx @@ -764,7 +764,8 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { setProgress({ active: true, percent: 0, currentFile: "", label: "Starting server backup…" }); try { const rec: BackupRecord = await tauriCmd.createServerBackup( - server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual" + server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual", + "", server.save_folder_name || undefined ); await insertBackup({ id: rec.id, server_id: rec.serverId, file_path: rec.filePath, @@ -788,7 +789,8 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { setProgress({ active: true, percent: 0, currentFile: "", label: "Starting player backups…" }); try { const records = await tauriCmd.backupAllPlayers( - server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual" + server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual", + server.save_folder_name || undefined ); if (records.length === 0) { toast.info("No player profiles found to back up."); diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index ae67bbf..06ce056 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -5,7 +5,7 @@ import { useRouter } from "next/navigation"; import { Play, Square, RotateCcw, Users, Cpu, MemoryStick, Clock, Save, RefreshCw, ArrowUp, Loader2, X, BarChart2, FolderOpen, - Zap, Settings2, Terminal, Skull, CheckCircle2, ShieldCheck, + Zap, Settings2, Terminal, Skull, CheckCircle2, ShieldCheck, ChevronDown, ChevronRight, Sparkles, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { @@ -38,7 +38,8 @@ import type { ServerRow } from "@/lib/db"; import { formatServerVersion } from "@/lib/db"; import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; import { toast } from "sonner"; -import { ARK_MAPS, LAUNCH_PARAMETERS, NOTIFICATION_EVENTS } from "@/data/game-data"; +import { ARK_MAPS, ARK_EVENTS, LAUNCH_PARAMETERS, NOTIFICATION_EVENTS } from "@/data/game-data"; +import { setServerActiveEvent } from "@/lib/db"; import { dispatchNotification } from "@/lib/notifications"; import { useQueryClient } from "@tanstack/react-query"; import { useTauriEvent } from "@/hooks/useTauriEvent"; @@ -495,6 +496,7 @@ function ActiveConfigPanel({ launchCommand: string; onNavigateToConfig: () => void; }) { + const [cliExpanded, setCliExpanded] = useState(false); if (!config) return null; const pvp = gusVal(config, "ServerPVE") !== "True"; @@ -541,16 +543,25 @@ function ActiveConfigPanel({ ))} - {/* Launch command */} + {/* Launch command — collapsed by default */} {launchCommand && (
-
- +
-
- {launchCommand} -
+ + {cliExpanded && ( +
+ {launchCommand} +
+ )}
)} @@ -585,6 +596,7 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate const [launchCommand, setLaunchCommand] = useState(""); const [wipingDinos, setWipingDinos] = useState(false); const [validating, setValidating] = useState(false); + const [activeEventId, setActiveEventId] = useState(server.active_event ?? null); // Per-tile timeframe selectors const [playersTf, setPlayersTf] = useState("Live"); @@ -1013,7 +1025,7 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate const backupDir = await getAppSetting("backup_dir"); if (!backupDir) return; 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") + tauriCmd.createServerBackup(server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual", "", server.save_folder_name || undefined) .then(async (record: BackupRecord) => { await insertBackup({ id: record.id, server_id: record.serverId, file_path: record.filePath, @@ -1099,6 +1111,55 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate + {/* ── Active Event selector ── */} +
+
+
+ +
+

Active Event

+

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

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

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

+ ) : null; + })()} +
+ {/* ── Active Configuration panel ── */} m.id === server.map_id); const enabledModIds = mods.filter((m) => m.enabled === 1).map((m) => m.mod_id); @@ -71,6 +67,7 @@ export async function buildStartParams(server: ServerRow): Promise 0 ? `-mods=${enabledModIds.join(",")}` : ""; const portArgs = `-port=${server.port} -queryport=${server.query_port} -RCONPort=${server.rcon_port} -MaxPlayers=${server.max_players}`; + const altSave = server.save_folder_name ? `?AltSaveDirectoryName=${server.save_folder_name}` : ""; const parts = [ - `${exe} ${mapPath}`, - portArgs, + `${exe} ${mapPath}?listen?Port=${server.port}?QueryPort=${server.query_port}${altSave}`, + "-server -log", ...extraArgs, modsArg, ].filter(Boolean); diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index 8abf441..93f4b1f 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -88,6 +88,8 @@ export interface StartServerParams { protonPath?: string; /** Linux only: path to the Steam compatibility prefix (WINEPREFIX). */ prefixPath?: string; + /** When set, appended as ?AltSaveDirectoryName= in the map query string so ASA saves to SavedArks/{name}. */ + altSaveDirectoryName?: string; } export interface ProtonEntry { From b394ab55edf665ff11789273fb6d2a0968fd1e02 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 22 Jun 2026 11:55:59 -0500 Subject: [PATCH 02/28] feat: add dialog for adding mod settings and enhance custom mod sections editor --- src/components/server/tabs/ConfigTab.tsx | 431 ++++++++++++++++------- 1 file changed, 299 insertions(+), 132 deletions(-) diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index c787133..2d4d770 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -4,7 +4,7 @@ import { useState, useEffect, useCallback } from "react"; import { Save, Code, LayoutList, RefreshCw, ChevronDown, ChevronRight, Settings2, X, AlertCircle, ToggleLeft, ToggleRight, Terminal, - HelpCircle, Upload, Search, FileText, Clipboard, Wand2, + HelpCircle, Upload, Search, FileText, Clipboard, Wand2, Clock, Package, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -16,6 +16,20 @@ import { DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, +} from "@/components/ui/dialog"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; import { tauriCmd, type ServerConfigJson } from "@/lib/tauri-commands"; import { INI_FIELD_GROUPS, LAUNCH_PARAMETERS, GAME_MODES, PRESET_STYLES, @@ -143,7 +157,8 @@ function FieldRow({ } if (field.type === "number" && field.min !== undefined && field.max !== undefined) { - const numVal = parseFloat(value) || 0; + const parsed = parseFloat(value); + const numVal = isNaN(parsed) ? (field.defaultValue as number ?? 0) : parsed; return (
@@ -545,10 +560,140 @@ function PasteIniModal({ // --------------------------------------------------------------------------- type CustomSection = { - sectionName: string; // The [SectionName] key in Game.ini + sectionName: string; rows: { key: string; value: string }[]; }; +type SettingType = "string" | "boolean" | "integer" | "float"; + +function inferType(value: string): SettingType { + if (value === "True" || value === "False") return "boolean"; + if (/^-?\d+$/.test(value)) return "integer"; + if (/^-?\d*\.\d+$/.test(value)) return "float"; + return "string"; +} + +function defaultForType(t: SettingType): string { + if (t === "boolean") return "False"; + if (t === "integer") return "0"; + if (t === "float") return "0.0"; + return ""; +} + +// --------------------------------------------------------------------------- +// Dialog for adding a new setting to a mod section +// --------------------------------------------------------------------------- + +function AddSettingDialog({ + open, + onClose, + onAdd, +}: { + open: boolean; + onClose: () => void; + onAdd: (key: string, value: string) => void; +}) { + const [name, setName] = useState(""); + const [type, setType] = useState("string"); + + const handleAdd = () => { + const k = name.trim(); + if (!k) return; + onAdd(k, defaultForType(type)); + setName(""); + setType("string"); + onClose(); + }; + + return ( + { if (!v) onClose(); }}> + + + Add Setting + +
+
+ + setName(e.target.value)} + onKeyDown={(e) => { if (e.key === "Enter") handleAdd(); }} + placeholder="e.g. MaxDinos" + autoFocus + className="h-8 text-xs font-mono" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + /> +
+
+ + +
+

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

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

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

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

No settings yet — click "Add Setting" below.

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

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

- + ); } @@ -1425,8 +1569,7 @@ export function ConfigTab({ server }: Props) { const [config, setConfig] = useState(null); const [rawGus, setRawGus] = useState(""); const [rawGame, setRawGame] = useState(""); - const [rawMode, setRawMode] = useState(false); - const [advancedMode, setAdvancedMode] = useState(false); + const [activeTab, setActiveTab] = useState<"automation" | "structured" | "mods" | "advanced" | "raw">("structured"); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [readingIni, setReadingIni] = useState(false); @@ -1588,7 +1731,7 @@ export function ConfigTab({ server }: Props) { setError(null); try { let toSave = toWrite; - if (rawMode && !cfg) { + if (activeTab === "raw" && !cfg) { toSave = { ...toWrite, gameUserSettings: rawTextToSections(rawGus), @@ -1628,15 +1771,13 @@ export function ConfigTab({ server }: Props) { setRawGus(configToRawText(config.gameUserSettings as Record>)); setRawGame(configToRawText(config.gameIni as Record>)); } - setRawMode(true); + setActiveTab("raw"); }; - const switchToStructured = () => { + const switchFromRaw = () => { const gus = rawTextToSections(rawGus); const game = rawTextToSections(rawGame); if (config) setConfig({ ...config, gameUserSettings: gus, gameIni: game }); - setRawMode(false); - setAdvancedMode(false); }; if (loading) { @@ -1660,18 +1801,36 @@ export function ConfigTab({ server }: Props) { {/* Tab selectors */}
+ +
)} - {/* ── Structured view — ALL INI groups ──────────────────────────────── */} - {!rawMode && config && ( + {/* ── Automation tab ────────────────────────────────────────────────── */} + {activeTab === "automation" && ( +
+ + + + +
+ )} + + {/* ── Structured view — all INI field groups ────────────────────────── */} + {activeTab === "structured" && config && (
{INI_FIELD_GROUPS.map((g, idx) => ( ))} - >} - onChange={(updated) => { - setConfig({ ...config, gameIni: updated }); - setIsDirty(true); - }} - />
)} + {/* ── Mod Settings tab ─────────────────────────────────────────────── */} + {activeTab === "mods" && config && ( + >} + onChange={(updated) => { + setConfig({ ...config, gameIni: updated }); + setIsDirty(true); + }} + /> + )} + + {/* ── Advanced tab ──────────────────────────────────────────────────── */} + {activeTab === "advanced" && config && ( + { setConfig({ ...config, ...patch }); setIsDirty(true); }} /> + )} + {/* ── Raw INI editor ────────────────────────────────────────────────── */} - {rawMode && ( + {activeTab === "raw" && (

GameUserSettings.ini

@@ -1809,17 +1987,6 @@ export function ConfigTab({ server }: Props) {
)} - {/* ── Advanced tab ──────────────────────────────────────────────────── */} - {advancedMode && config && ( - { setConfig({ ...config, ...patch }); setIsDirty(true); }} /> - )} - - {/* ── Server behaviour cards (always visible) ───────────────────────── */} - - - - - {/* Paste INI modal */} {showPasteModal && ( Date: Mon, 22 Jun 2026 11:56:54 -0500 Subject: [PATCH 03/28] feat: implement reusable PortField component for network step in server creation wizard --- .../wizard/ServerCreationWizard.tsx | 80 ++++++++++--------- 1 file changed, 44 insertions(+), 36 deletions(-) diff --git a/src/components/wizard/ServerCreationWizard.tsx b/src/components/wizard/ServerCreationWizard.tsx index c39a7ec..c452c0f 100644 --- a/src/components/wizard/ServerCreationWizard.tsx +++ b/src/components/wizard/ServerCreationWizard.tsx @@ -1267,6 +1267,47 @@ function FullIniStep({ data, onChange }: { data: WizardData; onChange: (patch: P // Network Step // --------------------------------------------------------------------------- +function PortField({ + label, fieldKey, value, status, conflict, description, onChange, onBlur, +}: { + label: string; + fieldKey: "port" | "queryPort" | "rconPort"; + value: number; + status: boolean | null | undefined; + conflict: string | undefined; + description: string; + onChange: (fieldKey: "port" | "queryPort" | "rconPort", val: number) => void; + onBlur: (fieldKey: string, val: number) => void; +}) { + return ( +
+
+ + {status === true && !conflict && Available} + {status === false && In use on this machine!} +
+ onChange(fieldKey, Number(e.target.value))} + onBlur={() => onBlur(fieldKey, value)} + className="font-mono" + style={{ + background: "rgba(10,10,30,0.8)", + borderColor: conflict ? "rgba(255,140,0,0.6)" : status === false ? "var(--neon-red)" : status === true ? "rgba(0,255,136,0.4)" : "rgba(var(--neon-purple-rgb),0.3)", + color: "var(--text-primary)", + }} + /> + {conflict && ( +

+ + Shared with {conflict} — both servers cannot run at the same time. +

+ )} +

{description}

+
+ ); +} + function NetworkStep({ data, onChange }: { data: WizardData; onChange: (patch: Partial) => void }) { const [portStatus, setPortStatus] = useState>({}); const [checking, setChecking] = useState(false); @@ -1341,47 +1382,14 @@ function NetworkStep({ data, onChange }: { data: WizardData; onChange: (patch: P updateConflicts(next.port, next.queryPort, next.rconPort); }; - const PortField = ({ label, fieldKey, description }: { label: string; fieldKey: "port" | "queryPort" | "rconPort"; description: string }) => { - const val = data[fieldKey] as number; - const status = portStatus[fieldKey]; - const conflict = conflicts[fieldKey]; - return ( -
-
- - {status === true && !conflict && Available} - {status === false && In use on this machine!} -
- handlePortChange(fieldKey, Number(e.target.value))} - onBlur={() => checkPort(fieldKey, val)} - className="font-mono" - style={{ - background: "rgba(10,10,30,0.8)", - borderColor: conflict ? "rgba(255,140,0,0.6)" : status === false ? "var(--neon-red)" : status === true ? "rgba(0,255,136,0.4)" : "rgba(var(--neon-purple-rgb),0.3)", - color: "var(--text-primary)", - }} - /> - {conflict && ( -

- - Shared with {conflict} — both servers cannot run at the same time. -

- )} -

{description}

-
- ); - }; - return (

Ports have been auto-suggested based on your existing servers. Each server needs a unique set of three ports.

- - - + + + {checking && (

Checking port availability… From ea305848be037768960cc4288bed68fcdbbb2cb9 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 22 Jun 2026 14:39:18 -0500 Subject: [PATCH 04/28] feat: add server disk usage retrieval and enhance delete server functionality --- src-tauri/src/commands/server.rs | 88 +++++++++++ src-tauri/src/lib.rs | 1 + src/components/server/ServerActionMenu.tsx | 165 ++++++++++++++------- src/lib/tauri-commands.ts | 18 ++- 4 files changed, 217 insertions(+), 55 deletions(-) diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 388dbaa..2bf22b8 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -1076,16 +1076,78 @@ fn find_server_process(install_path: &str) -> Option { None } +/// Return the total on-disk size (in bytes) of a server's backup, log, and save data. +/// Values are 0 if the directories don't exist. +#[tauri::command] +pub async fn get_server_disk_usage( + app: tauri::AppHandle, + server_id: String, + backup_dir: String, + base_dir: String, + save_folder_name: String, +) -> Result { + fn dir_size(path: &std::path::Path) -> u64 { + if !path.exists() { return 0; } + // Follow symlinks for the top-level dir but not recursively, to handle + // the SavedArks symlink case where the real data is under base_dir/Saves/. + let mut total = 0u64; + if let Ok(walker) = std::fs::read_dir(path) { + for entry in walker.flatten() { + let p = entry.path(); + if p.is_dir() { + total += dir_size(&p); + } else if let Ok(meta) = p.metadata() { + total += meta.len(); + } + } + } + total + } + + let backup_bytes = if !backup_dir.is_empty() { + let p = std::path::PathBuf::from(&backup_dir).join(&server_id); + dir_size(&p) + } else { + 0 + }; + + let log_bytes = { + use crate::state::log_manager::LogManagerState; + let p = LogManagerState::server_logs_dir(&app, &server_id); + p.map(|d| dir_size(&d)).unwrap_or(0) + }; + + let save_bytes = if !base_dir.is_empty() && !save_folder_name.is_empty() { + let p = std::path::PathBuf::from(&base_dir).join("Saves").join(&save_folder_name); + dir_size(&p) + } else { + 0 + }; + + Ok(serde_json::json!({ + "backupBytes": backup_bytes, + "logBytes": log_bytes, + "saveBytes": save_bytes, + })) +} + /// Delete a server from disk (optionally) and clean up in-memory state. /// /// Database record deletion is handled by the frontend via `db.deleteServerRecord()`. /// This command only removes the install directory when `delete_files` is true. #[tauri::command] pub async fn delete_server( + app: tauri::AppHandle, state: tauri::State<'_, AppState>, server_id: String, install_path: String, + backup_dir: String, + base_dir: String, + save_folder_name: String, delete_files: bool, + delete_backups: bool, + delete_logs: bool, + delete_saves: bool, ) -> Result<(), String> { // If the server is running, force-stop it first. let pid = { @@ -1110,6 +1172,32 @@ pub async fn delete_server( .map_err(|e| format!("Failed to delete server files at {install_path}: {e}"))?; } + if delete_backups && !backup_dir.is_empty() { + let p = std::path::PathBuf::from(&backup_dir).join(&server_id); + if p.exists() { + std::fs::remove_dir_all(&p) + .map_err(|e| format!("Failed to delete backup data: {e}"))?; + } + } + + if delete_logs { + use crate::state::log_manager::LogManagerState; + if let Some(p) = LogManagerState::server_logs_dir(&app, &server_id) { + if p.exists() { + std::fs::remove_dir_all(&p) + .map_err(|e| format!("Failed to delete log data: {e}"))?; + } + } + } + + if delete_saves && !base_dir.is_empty() && !save_folder_name.is_empty() { + let p = std::path::PathBuf::from(&base_dir).join("Saves").join(&save_folder_name); + if p.exists() { + std::fs::remove_dir_all(&p) + .map_err(|e| format!("Failed to delete save data: {e}"))?; + } + } + Ok(()) } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 80fe524..93b5fd3 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -488,6 +488,7 @@ pub fn run() { commands::server::scan_running_servers, commands::server::clone_server, commands::server::delete_server, + commands::server::get_server_disk_usage, commands::server::force_server_start_failed, // Certificates commands::certs::download_amazon_root_ca, diff --git a/src/components/server/ServerActionMenu.tsx b/src/components/server/ServerActionMenu.tsx index 360c5d7..730a743 100644 --- a/src/components/server/ServerActionMenu.tsx +++ b/src/components/server/ServerActionMenu.tsx @@ -54,6 +54,40 @@ interface Props { // Delete dialog // --------------------------------------------------------------------------- +function formatBytes(bytes: number): string { + if (bytes === 0) return "0 B"; + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + +interface DiskUsage { backupBytes: number; logBytes: number; saveBytes: number; } + +function DeleteToggleRow({ + label, sublabel, enabled, onToggle, color = "var(--neon-red)", +}: { + label: string; sublabel: string; enabled: boolean; + onToggle: () => void; color?: string; +}) { + return ( +

+
+

{label}

+

{sublabel}

+
+ +
+ ); +} + function DeleteDialog({ server, open, @@ -64,16 +98,37 @@ function DeleteDialog({ onClose: () => void; }) { const queryClient = useQueryClient(); - const [deleteFiles, setDeleteFiles] = useState(false); - const [removeRules, setRemoveRules] = useState(false); - const [deleting, setDeleting] = useState(false); + const [deleteFiles, setDeleteFiles] = useState(false); + const [deleteBackups, setDeleteBackups] = useState(false); + const [deleteLogs, setDeleteLogs] = useState(false); + const [deleteSaves, setDeleteSaves] = useState(false); + const [removeRules, setRemoveRules] = useState(false); + const [deleting, setDeleting] = useState(false); const [exclusivePorts, setExclusivePorts] = useState([]); + const [diskUsage, setDiskUsage] = useState(null); + const [backupDir, setBackupDir] = useState(""); + const [baseDir, setBaseDir] = useState(""); - // Compute exclusive ports when the dialog opens useEffect(() => { if (!open) return; - getServers().then((all) => { + // Reset toggles each time the dialog opens + setDeleteFiles(false); setDeleteBackups(false); + setDeleteLogs(false); setDeleteSaves(false); + setRemoveRules(false); setDiskUsage(null); + + Promise.all([ + getServers(), + getAppSetting("backup_dir"), + getAppSetting("base_dir"), + ]).then(([all, bkDir, bsDir]) => { setExclusivePorts(computeExclusivePorts(server, all)); + const bd = bkDir ?? ""; + const bsd = bsDir ?? ""; + setBackupDir(bd); + setBaseDir(bsd); + return tauriCmd.getServerDiskUsage(server.id, bd, bsd, server.save_folder_name ?? ""); + }).then((usage) => { + setDiskUsage(usage); }).catch(() => {}); // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]); @@ -84,7 +139,17 @@ function DeleteDialog({ if (removeRules && exclusivePorts.length > 0) { await tauriCmd.removeFirewallRules(exclusivePorts).catch(() => {}); } - await tauriCmd.deleteServer(server.id, server.install_path, deleteFiles); + await tauriCmd.deleteServer( + server.id, + server.install_path, + backupDir, + baseDir, + server.save_folder_name ?? "", + deleteFiles, + deleteBackups, + deleteLogs, + deleteSaves, + ); await deleteServerRecord(server.id); queryClient.invalidateQueries({ queryKey: ["servers"] }); onClose(); @@ -99,6 +164,8 @@ function DeleteDialog({ .map((p) => `${p.port}/${p.protocol.toUpperCase()}`) .join(", "); + const hasSaveFolder = !!(server.save_folder_name); + return ( !v && onClose()}> e.stopPropagation()}> @@ -107,51 +174,49 @@ function DeleteDialog({ Delete “{server.name}”? - This will remove the server from LokiASAM. Backup archives are never deleted. + This will remove the server from LokiASAM. Choose what to clean up from disk below — everything is off by default. -
-
-
-

Also delete server files on disk

-

{server.install_path}

-
- -
- +
+ setDeleteFiles((v) => !v)} + color="var(--neon-red)" + /> + 0 ? ` (${formatBytes(diskUsage.backupBytes)})` : diskUsage ? " (none)" : ""}`} + sublabel={backupDir ? `${backupDir}/${server.id}/` : "Backup directory not configured"} + enabled={deleteBackups} + onToggle={() => setDeleteBackups((v) => !v)} + color="var(--neon-red)" + /> + 0 ? ` (${formatBytes(diskUsage.logBytes)})` : diskUsage ? " (none)" : ""}`} + sublabel="Archived logs and crash folders stored by LokiASAM" + enabled={deleteLogs} + onToggle={() => setDeleteLogs((v) => !v)} + color="var(--neon-red)" + /> + {hasSaveFolder && ( + 0 ? ` (${formatBytes(diskUsage.saveBytes)})` : diskUsage ? " (none)" : ""}`} + sublabel={baseDir ? `${baseDir}/Saves/${server.save_folder_name}/` : "Saves directory"} + enabled={deleteSaves} + onToggle={() => setDeleteSaves((v) => !v)} + color="var(--neon-red)" + /> + )} {exclusivePorts.length > 0 && ( -
-
-

Also remove firewall rules for ports {exclusivePortList}

-

Only ports not used by any other server will be removed

-
- -
+ setRemoveRules((v) => !v)} + color="rgba(255,165,0,1)" + /> )}
@@ -160,11 +225,7 @@ function DeleteDialog({ diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index 93f4b1f..9451df0 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -339,9 +339,21 @@ export const tauriCmd = { */ cloneServer: (sourceInstallPath: string, destInstallPath: string) => invoke("clone_server", { sourceInstallPath, destInstallPath }), - /** Delete server files from disk. DB record deletion is done separately via db.ts. */ - deleteServer: (serverId: string, installPath: string, deleteFiles: boolean) => - invoke("delete_server", { serverId, installPath, deleteFiles }), + /** Delete server files and optional data from disk. DB record deletion is done separately via db.ts. */ + deleteServer: ( + serverId: string, + installPath: string, + backupDir: string, + baseDir: string, + saveFolderName: string, + deleteFiles: boolean, + deleteBackups: boolean, + deleteLogs: boolean, + deleteSaves: boolean, + ) => invoke("delete_server", { serverId, installPath, backupDir, baseDir, saveFolderName, deleteFiles, deleteBackups, deleteLogs, deleteSaves }), + /** Return on-disk byte counts for a server's backups, logs, and save data. */ + getServerDiskUsage: (serverId: string, backupDir: string, baseDir: string, saveFolderName: string) => + invoke<{ backupBytes: number; logBytes: number; saveBytes: number }>("get_server_disk_usage", { serverId, backupDir, baseDir, saveFolderName }), // SteamCMD / installation /** Download and extract SteamCMD to targetDir. Streams to steamcmd://output/setup. */ From 7b6c5f6b47eeaca6ef248839df6f28bf835701cc Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 22 Jun 2026 17:39:00 -0500 Subject: [PATCH 05/28] feat: add get_dir_size command to calculate directory size - Implemented `get_dir_size` command in `server.rs` to return the total on-disk size of a directory. - Integrated the new command into the Tauri command set in `lib.rs`. - Updated the `DeleteDialog` component to display the size of the cluster directory and allow users to choose whether to delete it. - Modified the `deleteCluster` command to accept a parameter for deleting files. - Enhanced the firewall management logic to ensure all relevant ports are accounted for when adding/removing firewall rules. - Refactored server start parameters handling to streamline the process and ensure correct parameters are passed. - Updated various components to reflect changes in server management and firewall handling. --- src-tauri/src/commands/cluster.rs | 14 +- src-tauri/src/commands/firewall.rs | 309 ++++++++---------- src-tauri/src/commands/server.rs | 19 ++ src-tauri/src/lib.rs | 1 + src/app/clusters/page.tsx | 70 +++- src/app/settings/page.tsx | 9 +- src/components/server/ServerActionMenu.tsx | 39 ++- src/components/server/ServerCard.tsx | 57 +--- src/components/server/tabs/OverviewTab.tsx | 51 +-- src/components/shared/TourModal.tsx | 2 +- .../wizard/ServerCreationWizard.tsx | 42 ++- src/lib/firewall-utils.ts | 9 +- src/lib/tauri-commands.ts | 4 +- 13 files changed, 318 insertions(+), 308 deletions(-) diff --git a/src-tauri/src/commands/cluster.rs b/src-tauri/src/commands/cluster.rs index a8db29e..f513231 100644 --- a/src-tauri/src/commands/cluster.rs +++ b/src-tauri/src/commands/cluster.rs @@ -34,11 +34,17 @@ pub async fn create_cluster( Ok(id) } -/// No-op — the cluster directory is intentionally not deleted automatically. -/// The frontend removes the SQLite record and can prompt the user to delete -/// the directory manually if desired. +/// Delete the cluster directory from disk when `delete_files` is true. +/// The frontend removes the SQLite record and clears cluster_id on member servers. #[tauri::command] -pub async fn delete_cluster(_cluster_id: String) -> Result<(), String> { +pub async fn delete_cluster(cluster_dir: String, delete_files: bool) -> Result<(), String> { + if delete_files && !cluster_dir.is_empty() { + let p = std::path::Path::new(&cluster_dir); + if p.exists() { + std::fs::remove_dir_all(p) + .map_err(|e| format!("Failed to delete cluster directory: {e}"))?; + } + } Ok(()) } diff --git a/src-tauri/src/commands/firewall.rs b/src-tauri/src/commands/firewall.rs index e54a55d..69182ee 100644 --- a/src-tauri/src/commands/firewall.rs +++ b/src-tauri/src/commands/firewall.rs @@ -179,7 +179,7 @@ mod linux_impl { // ── UFW ───────────────────────────────────────────────────────────────── const UFW_PROFILE_PATH: &str = "/etc/ufw/applications.d/lokiasam"; - const UFW_APP_NAME: &str = "LokiASAM"; + const UFW_APP_NAME: &str = "lokiasam"; /// Parse the ports line from the lokiasam ufw profile. /// Returns a set of "port/proto" strings like {"7777/udp", "27020/tcp"}. @@ -211,8 +211,11 @@ mod linux_impl { } /// Build the ports= line for the ufw profile from a list of PortDef. + /// Each port is its own `|`-separated segment (e.g. `27020/tcp|7777/udp|27015/udp`). + /// Comma-grouping (`7777,27015/udp`) is avoided because some UFW versions silently + /// drop segments that follow a comma-grouped entry when mixed protocols are present. + /// TCP entries come first to match the convention used by other application profiles. fn build_ufw_ports_line(ports: &[PortDef]) -> String { - // Group by protocol let mut udp: Vec = ports.iter().filter(|p| p.protocol == "udp").map(|p| p.port).collect(); let mut tcp: Vec = ports.iter().filter(|p| p.protocol == "tcp").map(|p| p.port).collect(); udp.sort_unstable(); @@ -220,15 +223,9 @@ mod linux_impl { tcp.sort_unstable(); tcp.dedup(); - let mut segments = Vec::new(); - if !udp.is_empty() { - let ports_str = udp.iter().map(|p| p.to_string()).collect::>().join(","); - segments.push(format!("{ports_str}/udp")); - } - if !tcp.is_empty() { - let ports_str = tcp.iter().map(|p| p.to_string()).collect::>().join(","); - segments.push(format!("{ports_str}/tcp")); - } + let mut segments: Vec = Vec::new(); + for p in &udp { segments.push(format!("{p}/udp")); } + for p in &tcp { segments.push(format!("{p}/tcp")); } segments.join("|") } @@ -256,120 +253,46 @@ mod linux_impl { FirewallStatus { firewall_type: "ufw".into(), active: true, ports: statuses } } - pub async fn add_ufw(new_ports: &[PortDef], existing_covered: &std::collections::HashSet) -> Result<(), String> { - // Read current profile ports, merge with new ones - let current = parse_ufw_profile(); - let mut all_ports: Vec = Vec::new(); - - // Keep existing covered ports that are already in the profile - for entry in ¤t { - if let Some(slash) = entry.rfind('/') { - if let Ok(p) = entry[..slash].parse::() { - let proto = entry[slash + 1..].to_string(); - all_ports.push(PortDef { port: p, protocol: proto }); - } - } - } - // Add new ports (dedup handled by build) - for p in new_ports { - let key = format!("{}/{}", p.port, p.protocol); - if !existing_covered.contains(&key) { - all_ports.push(p.clone()); - } - } - // Also include uncovered ones from the original new_ports list - for p in new_ports { - if !all_ports.iter().any(|e| e.port == p.port && e.protocol == p.protocol) { - all_ports.push(p.clone()); + /// Set the UFW application profile to exactly `desired_ports` and apply it. + /// Writes a fresh profile (TCP entries first, one port per `|` segment) then does + /// delete → re-allow so UFW picks up the new profile cleanly. + /// If `desired_ports` is empty, deletes the rule and the profile file entirely. + pub async fn apply_ufw_state(desired_ports: &[PortDef]) -> Result<(), String> { + if desired_ports.is_empty() { + let cmd = format!("ufw delete allow '{UFW_APP_NAME}' ; rm -f '{UFW_PROFILE_PATH}'"); + let status = Command::new("pkexec") + .args(["sh", "-c", &cmd]) + .status() + .await + .map_err(|e| format!("pkexec ufw delete failed: {e}"))?; + if !status.success() { + return Err(format!("pkexec ufw delete exited {}", status.code().unwrap_or(-1))); } + return Ok(()); } - let profile_content = build_ufw_profile(&all_ports); - - // Write profile with pkexec tee - let mut child = Command::new("pkexec") - .args(["tee", UFW_PROFILE_PATH]) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::null()) - .spawn() - .map_err(|e| format!("Failed to spawn pkexec tee: {e}"))?; - - if let Some(mut stdin) = child.stdin.take() { - use tokio::io::AsyncWriteExt; - stdin.write_all(profile_content.as_bytes()).await - .map_err(|e| format!("Failed to write profile: {e}"))?; - } - - let output = child.wait_with_output().await - .map_err(|e| format!("pkexec tee failed: {e}"))?; - - if !output.status.success() { - return Err(format!("pkexec tee exited {}", output.status.code().unwrap_or(-1))); - } - - // Activate the rule - let allow_status = Command::new("pkexec") - .args(["ufw", "allow", UFW_APP_NAME]) + let tmp_path = std::env::temp_dir().join("lokiasam_ufw_profile"); + std::fs::write(&tmp_path, build_ufw_profile(desired_ports)) + .map_err(|e| format!("Failed to write UFW temp profile: {e}"))?; + + let tmp_str = tmp_path.to_string_lossy(); + // Copy profile first (`&&` ensures allow only runs if cp succeeded), then + // delete the old rule (`;` so allow still runs even if no rule existed yet), + // then re-allow from the updated profile. + let cmd = format!( + "cp '{tmp_str}' '{UFW_PROFILE_PATH}' && ufw delete allow '{UFW_APP_NAME}' ; ufw allow '{UFW_APP_NAME}'" + ); + let status = Command::new("pkexec") + .args(["sh", "-c", &cmd]) .status() .await - .map_err(|e| format!("Failed to run pkexec ufw allow: {e}"))?; + .map_err(|e| format!("pkexec ufw apply failed: {e}"))?; - if !allow_status.success() { - return Err(format!("pkexec ufw allow exited {}", allow_status.code().unwrap_or(-1))); - } - Ok(()) - } + let _ = std::fs::remove_file(&tmp_path); - pub async fn remove_ufw(ports_to_remove: &[PortDef]) -> Result<(), String> { - let current = parse_ufw_profile(); - let remove_set: std::collections::HashSet = ports_to_remove - .iter().map(|p| format!("{}/{}", p.port, p.protocol)).collect(); - - let remaining: Vec = current.iter() - .filter(|k| !remove_set.contains(*k)) - .filter_map(|entry| { - let slash = entry.rfind('/')?; - let p = entry[..slash].parse::().ok()?; - Some(PortDef { port: p, protocol: entry[slash + 1..].to_string() }) - }) - .collect(); - - let profile_content = if remaining.is_empty() { - // Delete the profile and the rule - let _ = Command::new("pkexec") - .args(["ufw", "delete", "allow", UFW_APP_NAME]) - .status().await; - let _ = Command::new("pkexec") - .args(["rm", "-f", UFW_PROFILE_PATH]) - .status().await; - return Ok(()); - } else { - build_ufw_profile(&remaining) - }; - - // Rewrite profile - let mut child = Command::new("pkexec") - .args(["tee", UFW_PROFILE_PATH]) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::null()) - .spawn() - .map_err(|e| format!("Failed to spawn pkexec tee: {e}"))?; - - if let Some(mut stdin) = child.stdin.take() { - use tokio::io::AsyncWriteExt; - stdin.write_all(profile_content.as_bytes()).await - .map_err(|e| format!("Failed to write profile: {e}"))?; - } - let out = child.wait_with_output().await - .map_err(|e| format!("pkexec tee failed: {e}"))?; - if !out.status.success() { - return Err(format!("pkexec tee exited {}", out.status.code().unwrap_or(-1))); + if !status.success() { + return Err(format!("pkexec ufw apply exited {}", status.code().unwrap_or(-1))); } - - // Re-apply - let _ = Command::new("pkexec") - .args(["ufw", "allow", UFW_APP_NAME]) - .status().await; Ok(()) } @@ -391,66 +314,119 @@ mod linux_impl { } pub async fn add_firewalld(ports: &[PortDef]) -> Result<(), String> { + // Check which ports aren't already open (no elevation needed for --query-port) + let mut to_add = Vec::new(); for p in ports { let arg = format!("{}/{}", p.port, p.protocol); let already = Command::new("firewall-cmd") .args(["--query-port", &arg]) .status().await .map(|s| s.success()).unwrap_or(false); - if already { continue; } - - let s = Command::new("pkexec") - .args(["firewall-cmd", "--permanent", &format!("--add-port={arg}")]) - .status().await - .map_err(|e| format!("pkexec firewall-cmd failed: {e}"))?; - if !s.success() { - return Err(format!("firewall-cmd --add-port exited {}", s.code().unwrap_or(-1))); - } + if !already { to_add.push(arg); } + } + if to_add.is_empty() { return Ok(()); } + + // Batch all --add-port flags + --reload into a single pkexec sh call + let add_flags = to_add.iter().map(|a| format!("--add-port={a}")).collect::>().join(" "); + let cmd = format!("firewall-cmd --permanent {add_flags} && firewall-cmd --reload"); + let s = Command::new("pkexec") + .args(["sh", "-c", &cmd]) + .status().await + .map_err(|e| format!("pkexec firewall-cmd failed: {e}"))?; + if !s.success() { + return Err(format!("firewall-cmd add/reload exited {}", s.code().unwrap_or(-1))); } - // Reload once after all ports added - let _ = Command::new("pkexec") - .args(["firewall-cmd", "--reload"]) - .status().await; Ok(()) } - pub async fn remove_firewalld(ports: &[PortDef]) -> Result<(), String> { - for p in ports { - let arg = format!("{}/{}", p.port, p.protocol); - let _ = Command::new("pkexec") - .args(["firewall-cmd", "--permanent", &format!("--remove-port={arg}")]) - .status().await; + /// Remove firewall rules for ports NOT in `remaining_ports`. + /// Queries `firewall-cmd --list-ports` (no elevation) to find what is currently + /// open, then removes only the excess — never touches ports still in use. + pub async fn remove_firewalld(remaining_ports: &[PortDef]) -> Result<(), String> { + let remaining_set: std::collections::HashSet = remaining_ports + .iter().map(|p| format!("{}/{}", p.port, p.protocol)).collect(); + + // Query current open ports without elevation + let text = match Command::new("firewall-cmd").args(["--list-ports"]).output().await { + Ok(o) => String::from_utf8_lossy(&o.stdout).into_owned(), + Err(_) => return Ok(()), // can't query current state — skip rather than error + }; + + let to_remove: Vec = text + .split_whitespace() + .filter(|s| !remaining_set.contains(*s)) + .map(|s| s.to_string()) + .collect(); + + if to_remove.is_empty() { return Ok(()); } + + let remove_flags = to_remove.iter() + .map(|s| format!("--remove-port={s}")) + .collect::>().join(" "); + let cmd = format!("firewall-cmd --permanent {remove_flags} && firewall-cmd --reload"); + let status = Command::new("pkexec") + .args(["sh", "-c", &cmd]) + .status() + .await + .map_err(|e| format!("pkexec firewall-cmd remove failed: {e}"))?; + if !status.success() { + return Err(format!("firewall-cmd remove/reload exited {}", status.code().unwrap_or(-1))); } - let _ = Command::new("pkexec") - .args(["firewall-cmd", "--reload"]) - .status().await; Ok(()) } // ── iptables (DB-backed fallback) ──────────────────────────────────────── pub async fn add_iptables(ports: &[PortDef]) -> Result<(), String> { - for p in ports { - let proto = &p.protocol; - let port_str = p.port.to_string(); - let s = Command::new("pkexec") - .args(["iptables", "-A", "INPUT", "-p", proto, "--dport", &port_str, "-j", "ACCEPT"]) - .status().await - .map_err(|e| format!("pkexec iptables failed: {e}"))?; - if !s.success() { - return Err(format!("iptables -A exited {} for port {}", s.code().unwrap_or(-1), p.port)); - } + if ports.is_empty() { return Ok(()); } + let cmds = ports.iter() + .map(|p| format!("iptables -A INPUT -p {} --dport {} -j ACCEPT", p.protocol, p.port)) + .collect::>().join(" && "); + let s = Command::new("pkexec") + .args(["sh", "-c", &cmds]) + .status().await + .map_err(|e| format!("pkexec iptables failed: {e}"))?; + if !s.success() { + return Err(format!("iptables add exited {}", s.code().unwrap_or(-1))); } Ok(()) } - pub async fn remove_iptables(ports: &[PortDef]) -> Result<(), String> { - for p in ports { - let proto = &p.protocol; - let port_str = p.port.to_string(); - let _ = Command::new("pkexec") - .args(["iptables", "-D", "INPUT", "-p", proto, "--dport", &port_str, "-j", "ACCEPT"]) - .status().await; + /// Remove iptables rules for ports NOT in `remaining_ports`. + /// Parses `iptables -S INPUT` (no elevation) to find current ACCEPT rules, + /// then removes only the ones that are no longer needed. + pub async fn remove_iptables(remaining_ports: &[PortDef]) -> Result<(), String> { + let remaining_set: std::collections::HashSet = remaining_ports + .iter().map(|p| format!("{}/{}", p.protocol, p.port)).collect(); + + let text = match Command::new("iptables").args(["-S", "INPUT"]).output().await { + Ok(o) => String::from_utf8_lossy(&o.stdout).into_owned(), + Err(_) => return Ok(()), // can't query current state — skip rather than error + }; + + // Match lines like: -A INPUT -p udp --dport 7777 -j ACCEPT + let mut to_remove: Vec = Vec::new(); + for line in text.lines() { + if !line.contains("-j ACCEPT") { continue; } + let proto = ["udp", "tcp"].iter().find(|&&pr| line.contains(&format!("-p {pr} "))); + let dport = line.split("--dport ").nth(1).and_then(|s| s.split_whitespace().next()); + if let (Some(proto), Some(port)) = (proto, dport) { + if !remaining_set.contains(&format!("{proto}/{port}")) { + to_remove.push(format!("iptables -D INPUT -p {proto} --dport {port} -j ACCEPT")); + } + } + } + + if to_remove.is_empty() { return Ok(()); } + // Use ; so a missing rule doesn't abort removal of the remaining ones + let cmds = to_remove.join(" ; "); + let status = Command::new("pkexec") + .args(["sh", "-c", &cmds]) + .status() + .await + .map_err(|e| format!("pkexec iptables remove failed: {e}"))?; + if !status.success() { + return Err(format!("iptables remove exited {}", status.code().unwrap_or(-1))); } Ok(()) } @@ -502,7 +478,10 @@ pub async fn check_firewall_ports(ports: Vec) -> Result, _proton_path: Option) -> Result<(), String> { #[cfg(target_os = "windows")] @@ -514,13 +493,10 @@ pub async fn add_firewall_rules(ports: Vec, _proton_path: Option { - let current = parse_ufw_profile(); - add_ufw(&ports, ¤t).await - } + FirewallKind::Ufw => apply_ufw_state(&ports).await, FirewallKind::Firewalld => add_firewalld(&ports).await, FirewallKind::Iptables => add_iptables(&ports).await, - FirewallKind::None => Ok(()), // nothing to do + FirewallKind::None => Ok(()), } } @@ -530,11 +506,16 @@ pub async fn add_firewall_rules(ports: Vec, _proton_path: Option) -> Result<(), String> { #[cfg(target_os = "windows")] { + // On Windows, remove_rules takes ports-to-remove, so we can't use the + // remaining-ports model directly. For now keep existing per-rule deletion. windows_impl::remove_rules(&ports).await } @@ -542,7 +523,7 @@ pub async fn remove_firewall_rules(ports: Vec) -> Result<(), String> { { use linux_impl::*; match detect().await { - FirewallKind::Ufw => remove_ufw(&ports).await, + FirewallKind::Ufw => apply_ufw_state(&ports).await, FirewallKind::Firewalld => remove_firewalld(&ports).await, FirewallKind::Iptables => remove_iptables(&ports).await, FirewallKind::None => Ok(()), diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 2bf22b8..c535c23 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -1076,6 +1076,25 @@ fn find_server_process(install_path: &str) -> Option { None } +/// Return the total on-disk size (in bytes) of an arbitrary directory tree. +/// Returns 0 if the path doesn't exist. +#[tauri::command] +pub async fn get_dir_size(path: String) -> u64 { + fn walk(p: &std::path::Path) -> u64 { + if !p.exists() { return 0; } + let mut total = 0u64; + if let Ok(rd) = std::fs::read_dir(p) { + for entry in rd.flatten() { + let ep = entry.path(); + if ep.is_dir() { total += walk(&ep); } + else if let Ok(m) = ep.metadata() { total += m.len(); } + } + } + total + } + walk(std::path::Path::new(&path)) +} + /// Return the total on-disk size (in bytes) of a server's backup, log, and save data. /// Values are 0 if the directories don't exist. #[tauri::command] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 93b5fd3..187ac3f 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -489,6 +489,7 @@ pub fn run() { commands::server::clone_server, commands::server::delete_server, commands::server::get_server_disk_usage, + commands::server::get_dir_size, commands::server::force_server_start_failed, // Certificates commands::certs::download_amazon_root_ca, diff --git a/src/app/clusters/page.tsx b/src/app/clusters/page.tsx index 18293b6..c8475d7 100644 --- a/src/app/clusters/page.tsx +++ b/src/app/clusters/page.tsx @@ -1,10 +1,10 @@ "use client"; -import { useState, useCallback } from "react"; +import { useState, useCallback, useEffect } from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useRouter } from "next/navigation"; import { - Network, Plus, Trash2, ChevronRight, Server, Folder, + Network, Plus, Trash2, ChevronRight, Server, Folder, ToggleLeft, ToggleRight, } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; @@ -144,19 +144,45 @@ interface DeleteDialogProps { onDeleted: () => void; } +function formatBytes(bytes: number): string { + if (bytes === 0) return "empty"; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; + return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`; +} + function DeleteDialog({ cluster, onClose, onDeleted }: DeleteDialogProps) { - const [busy, setBusy] = useState(false); + const [busy, setBusy] = useState(false); + const [deleteFiles, setDeleteFiles] = useState(true); + const [clusterDir, setClusterDir] = useState(""); + const [dirBytes, setDirBytes] = useState(null); + + useEffect(() => { + if (!cluster) return; + setDeleteFiles(true); + setDirBytes(null); + + // Resolve actual cluster directory + getAppSetting("base_dir").then((baseDir) => { + const dir = cluster.cluster_dir_override?.trim() + ? cluster.cluster_dir_override + : `${(baseDir ?? "").replace(/[/\\]$/, "")}/clusters/${cluster.id}`; + setClusterDir(dir); + + return tauriCmd.getDirSize(dir).then((bytes) => setDirBytes(bytes)).catch(() => setDirBytes(-1)); + }).catch(() => {}); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [cluster?.id]); async function handleDelete() { if (!cluster) return; setBusy(true); try { - // Clear cluster_id on all member servers first const members = await getServersInCluster(cluster.id); for (const s of members) { await setServerCluster(s.id, null); } - await tauriCmd.deleteCluster(cluster.id); + await tauriCmd.deleteCluster(clusterDir, deleteFiles); await deleteClusterRecord(cluster.id); toast.success(`Cluster "${cluster.name}" deleted.`); onDeleted(); @@ -182,15 +208,33 @@ function DeleteDialog({ cluster, onClose, onDeleted }: DeleteDialogProps) { Confirm cluster deletion. -

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

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

- + +
+
+

+ Delete cluster directory{dirBytes !== null && dirBytes >= 0 ? ` (${formatBytes(dirBytes)})` : dirBytes === null ? " (scanning…)" : ""} +

+

{clusterDir || "…"}

+
+ +
+ + diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index fdeb751..3989d77 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -1231,13 +1231,14 @@ function FirewallRepairRow() { const handleFix = async () => { if (!fwStatus) return; - const missingPorts: PortDef[] = fwStatus.ports - .filter((p) => !p.covered) - .map((p) => ({ port: p.port, protocol: p.protocol as "tcp" | "udp" })); setIsFixing(true); try { + // Pass the complete desired port set so the backend can rebuild from scratch, + // removing any stale entries from previously deleted servers. + const allPorts: PortDef[] = fwStatus.ports + .map((p) => ({ port: p.port, protocol: p.protocol as "tcp" | "udp" })); const protonPath = IS_LINUX ? (await getAppSetting("proton_path")) ?? undefined : undefined; - await tauriCmd.addFirewallRules(missingPorts, protonPath); + await tauriCmd.addFirewallRules(allPorts, protonPath); toast.success("Firewall rules added."); await runCheck(); } catch (e) { diff --git a/src/components/server/ServerActionMenu.tsx b/src/components/server/ServerActionMenu.tsx index 730a743..f503d0e 100644 --- a/src/components/server/ServerActionMenu.tsx +++ b/src/components/server/ServerActionMenu.tsx @@ -42,7 +42,7 @@ import { import { useQueryClient } from "@tanstack/react-query"; import type { ServerRow } from "@/lib/db"; import type { BackupRecord } from "@/lib/tauri-commands"; -import { getExclusivePorts as computeExclusivePorts } from "@/lib/firewall-utils"; +import { getExclusivePorts as computeExclusivePorts, getServerFirewallPorts } from "@/lib/firewall-utils"; import type { PortDef } from "@/lib/tauri-commands"; const uuidv4 = () => crypto.randomUUID(); @@ -98,23 +98,24 @@ function DeleteDialog({ onClose: () => void; }) { const queryClient = useQueryClient(); - const [deleteFiles, setDeleteFiles] = useState(false); - const [deleteBackups, setDeleteBackups] = useState(false); - const [deleteLogs, setDeleteLogs] = useState(false); - const [deleteSaves, setDeleteSaves] = useState(false); - const [removeRules, setRemoveRules] = useState(false); + const [deleteFiles, setDeleteFiles] = useState(true); + const [deleteBackups, setDeleteBackups] = useState(true); + const [deleteLogs, setDeleteLogs] = useState(true); + const [deleteSaves, setDeleteSaves] = useState(true); + const [removeRules, setRemoveRules] = useState(true); const [deleting, setDeleting] = useState(false); const [exclusivePorts, setExclusivePorts] = useState([]); + const [remainingPorts, setRemainingPorts] = useState([]); const [diskUsage, setDiskUsage] = useState(null); const [backupDir, setBackupDir] = useState(""); const [baseDir, setBaseDir] = useState(""); useEffect(() => { if (!open) return; - // Reset toggles each time the dialog opens - setDeleteFiles(false); setDeleteBackups(false); - setDeleteLogs(false); setDeleteSaves(false); - setRemoveRules(false); setDiskUsage(null); + // Reset toggles each time the dialog opens (all ON by default) + setDeleteFiles(true); setDeleteBackups(true); + setDeleteLogs(true); setDeleteSaves(true); + setRemoveRules(true); setDiskUsage(null); Promise.all([ getServers(), @@ -122,6 +123,18 @@ function DeleteDialog({ getAppSetting("base_dir"), ]).then(([all, bkDir, bsDir]) => { setExclusivePorts(computeExclusivePorts(server, all)); + + // Remaining ports = every port from servers OTHER than this one. + // This is the complete desired state passed to the firewall backend after deletion. + const otherServers = all.filter((s) => s.id !== server.id); + const remainingMap = new Map(); + for (const s of otherServers) { + for (const p of getServerFirewallPorts(s)) { + remainingMap.set(`${p.port}/${p.protocol}`, p); + } + } + setRemainingPorts([...remainingMap.values()]); + const bd = bkDir ?? ""; const bsd = bsDir ?? ""; setBackupDir(bd); @@ -137,7 +150,11 @@ function DeleteDialog({ setDeleting(true); try { if (removeRules && exclusivePorts.length > 0) { - await tauriCmd.removeFirewallRules(exclusivePorts).catch(() => {}); + // Pass remaining ports (complete desired state after deletion) so the + // backend can rebuild from scratch rather than trying to diff a stale profile. + await tauriCmd.removeFirewallRules(remainingPorts).catch((e) => { + toast.warning(`Firewall rules could not be removed: ${e}`); + }); } await tauriCmd.deleteServer( server.id, diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index ad0356a..7536d57 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -40,7 +40,7 @@ import { CommandOutputPanel, clearOutputBuffer } from "@/components/shared/Comma import { ServerStatusBadge } from "./ServerStatusBadge"; import { ServerActionMenu } from "./ServerActionMenu"; import { useServerStats } from "@/hooks/useServerStats"; -import { tauriCmd, type StartServerParams } from "@/lib/tauri-commands"; +import { tauriCmd } from "@/lib/tauri-commands"; import { updateServerStatus, getServerConfig, @@ -54,7 +54,8 @@ import { } from "@/lib/db"; import { applyUpdateToServer } from "@/lib/update-utils"; import { warnIfFirewallMissing } from "@/lib/firewall-utils"; -import { ARK_MAPS, LAUNCH_PARAMETERS, NOTIFICATION_EVENTS } from "@/data/game-data"; +import { ARK_MAPS, NOTIFICATION_EVENTS } from "@/data/game-data"; +import { buildStartParams, isLinux } from "@/lib/server-utils"; import { dispatchNotification } from "@/lib/notifications"; import { useQueryClient } from "@tanstack/react-query"; import { useAppStore } from "@/store/useAppStore"; @@ -213,50 +214,6 @@ export function ServerCard({ server }: Props) { // ── Actions ────────────────────────────────────────────────────────────── - const isLinux = - typeof navigator !== "undefined" && !navigator.userAgent.includes("Windows"); - - const buildStartParams = async (): Promise => { - const [config, mods] = await Promise.all([ - getServerConfig(server.id), - getServerMods(server.id), - ]); - const launchArgs: Record = config - ? JSON.parse(config.launch_args_json) - : {}; - - const extraArgs = Object.entries(launchArgs).flatMap(([k, v]) => { - if (!v || v === "false" || v === "0") return []; - const param = LAUNCH_PARAMETERS.find((p) => p.key === k); - if (param?.type === "boolean") return v === "true" ? [param.flag] : []; - if (param) return v ? [`${param.flag}${v}`] : []; - return v === "true" ? [`-${k}`] : [`-${k}=${v}`]; - }); - - const map = ARK_MAPS.find((m) => m.id === server.map_id); - const enabledModIds = mods.filter((m) => m.enabled === 1).map((m) => m.mod_id); - - const params: StartServerParams = { - serverId: server.id, - serverName: server.name, - installPath: server.install_path, - mapPath: map?.mapPath ?? "TheIsland_WP", - port: server.port, - queryPort: server.query_port, - rconPort: server.rcon_port, - rconPassword: server.rcon_password, - extraArgs, - modIds: enabledModIds, - }; - - if (isLinux) { - params.protonPath = (await getAppSetting("proton_path")) ?? undefined; - params.prefixPath = (await getAppSetting("proton_prefix_path")) ?? undefined; - } - - return params; - }; - const handleStart = async () => { setActionPending(true); clearNoRetryServer(server.id); @@ -265,7 +222,7 @@ export function ServerCard({ server }: Props) { queryClient.invalidateQueries({ queryKey: ["servers"] }); await warnIfFirewallMissing(server); - const params = await buildStartParams(); + const params = await buildStartParams(server); const pid = await tauriCmd.startServer(params); // Stay "starting" — Rust backend emits server://status/{id} with "running" @@ -330,7 +287,7 @@ export function ServerCard({ server }: Props) { const handleRestart = async () => { if (server.restart_warn_players) { - const startParams = await buildStartParams(); + const startParams = await buildStartParams(server); tauriCmd.startGracefulRestart({ serverId: server.id, warnSeconds: (server.restart_warn_minutes ?? 5) * 60, @@ -348,7 +305,7 @@ export function ServerCard({ server }: Props) { await updateServerStatus(server.id, "stopping", server.pid); queryClient.invalidateQueries({ queryKey: ["servers"] }); - const params = await buildStartParams(); + const params = await buildStartParams(server); const newPid = await tauriCmd.restartServer(params, true); await updateServerStatus(server.id, "running", newPid); @@ -373,7 +330,7 @@ export function ServerCard({ server }: Props) { if (!baseDir || !steamcmdPath) return; const sep = baseDir.includes("\\") ? "\\" : "/"; const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; - const startParams = restartAfterUpdate ? await buildStartParams() : null; + const startParams = restartAfterUpdate ? await buildStartParams(server) : null; tauriCmd.startGracefulUpdate({ serverId: server.id, diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index 06ce056..bcc1810 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -23,14 +23,14 @@ import { } from "recharts"; import { useServerStats } from "@/hooks/useServerStats"; import { useServerStatsHistory, type Timeframe } from "@/hooks/useServerStatsHistory"; -import { tauriCmd, type StartServerParams, type ArkPlayer } from "@/lib/tauri-commands"; +import { tauriCmd, type ArkPlayer } from "@/lib/tauri-commands"; import { useAppStore } from "@/store/useAppStore"; import { - updateServerStatus, getServerConfig, getServerModCount, getServerMods, + updateServerStatus, getServerConfig, getServerModCount, getLastBackupTime, getNextScheduledRestart, getHasBackupEnabled, getAppSetting, insertBackup, pruneManualBackups, setServerAutoStart, } from "@/lib/db"; -import { buildLaunchCommandPreview } from "@/lib/server-utils"; +import { buildLaunchCommandPreview, buildStartParams, isLinux } from "@/lib/server-utils"; import { applyUpdateToServer } from "@/lib/update-utils"; import { warnIfFirewallMissing } from "@/lib/firewall-utils"; import type { BackupRecord } from "@/lib/tauri-commands"; @@ -38,12 +38,11 @@ import type { ServerRow } from "@/lib/db"; import { formatServerVersion } from "@/lib/db"; import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; import { toast } from "sonner"; -import { ARK_MAPS, ARK_EVENTS, LAUNCH_PARAMETERS, NOTIFICATION_EVENTS } from "@/data/game-data"; +import { ARK_MAPS, ARK_EVENTS, NOTIFICATION_EVENTS } from "@/data/game-data"; import { setServerActiveEvent } from "@/lib/db"; import { dispatchNotification } from "@/lib/notifications"; import { useQueryClient } from "@tanstack/react-query"; import { useTauriEvent } from "@/hooks/useTauriEvent"; -import { isLinux } from "@/lib/server-utils"; interface Props { server: ServerRow; @@ -652,47 +651,13 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate // ── Action helpers ────────────────────────────────────────────────────────── - const buildStartParams = async (): Promise => { - const [config, mods] = await Promise.all([ - getServerConfig(server.id), - getServerMods(server.id), - ]); - const launchArgs: Record = config ? JSON.parse(config.launch_args_json) : {}; - const extraArgs = Object.entries(launchArgs).flatMap(([k, v]) => { - if (!v || v === "false" || v === "0") return []; - const param = LAUNCH_PARAMETERS.find((p) => p.key === k); - if (param?.type === "boolean") return v === "true" ? [param.flag] : []; - if (param) return v ? [`${param.flag}${v}`] : []; - return v === "true" ? [`-${k}`] : [`-${k}=${v}`]; - }); - const map = ARK_MAPS.find((m) => m.id === server.map_id); - const enabledModIds = mods.filter((m) => m.enabled === 1).map((m) => m.mod_id); - const params: StartServerParams = { - serverId: server.id, - serverName: server.name, - installPath: server.install_path, - mapPath: map?.mapPath ?? "TheIsland_WP", - port: server.port, - queryPort: server.query_port, - rconPort: server.rcon_port, - rconPassword: server.rcon_password, - extraArgs, - modIds: enabledModIds, - }; - if (isLinux) { - params.protonPath = (await getAppSetting("proton_path")) ?? undefined; - params.prefixPath = (await getAppSetting("proton_prefix_path")) ?? undefined; - } - return params; - }; - const handleStart = async () => { setActionPending(true); try { await updateServerStatus(server.id, "starting", null); queryClient.invalidateQueries({ queryKey: ["servers"] }); await warnIfFirewallMissing(server); - const params = await buildStartParams(); + const params = await buildStartParams(server); const pid = await tauriCmd.startServer(params); await updateServerStatus(server.id, "starting", pid); } catch (e) { @@ -749,7 +714,7 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate const handleRestart = async () => { if (server.restart_warn_players) { - const startParams = await buildStartParams(); + const startParams = await buildStartParams(server); tauriCmd.startGracefulRestart({ serverId: server.id, warnSeconds: (server.restart_warn_minutes ?? 5) * 60, @@ -766,7 +731,7 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate try { await updateServerStatus(server.id, "stopping", null); queryClient.invalidateQueries({ queryKey: ["servers"] }); - const params = await buildStartParams(); + const params = await buildStartParams(server); const pid = await tauriCmd.restartServer(params, true); await updateServerStatus(server.id, "running", pid); } catch (err) { @@ -789,7 +754,7 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate if (!baseDir || !steamcmdPath) return; const sep = baseDir.includes("\\") ? "\\" : "/"; const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; - const startParams = restartAfterUpdate ? await buildStartParams() : null; + const startParams = restartAfterUpdate ? await buildStartParams(server) : null; tauriCmd.startGracefulUpdate({ serverId: server.id, diff --git a/src/components/shared/TourModal.tsx b/src/components/shared/TourModal.tsx index 58617be..ff8aa18 100644 --- a/src/components/shared/TourModal.tsx +++ b/src/components/shared/TourModal.tsx @@ -87,7 +87,7 @@ const TOUR_SLIDES = [ description: "For players outside your local network to join, your server ports need to be reachable from the internet.", imagePlaceholder: "Diagram: Internet → Router/VPN → Port Forward → LokiASAM Server", bullets: [ - "Forward three ports on your router: Game Port (UDP), Game Port+1 (UDP), and Query Port (UDP)", + "Forward two ports on your router: Game Port (UDP) and Query Port (UDP). RCON (TCP) only needs to be open if you use remote console tools.", "No router access? VPN port-forwarding services let you forward ports without touching your router — ideal for apartments, shared networks, or ISP restrictions", // TODO: Add affiliate links here for TorGuard / Mullvad / AirVPN — these let users support // LokiASAM at no extra cost while solving their port forwarding needs. diff --git a/src/components/wizard/ServerCreationWizard.tsx b/src/components/wizard/ServerCreationWizard.tsx index c452c0f..edcfe68 100644 --- a/src/components/wizard/ServerCreationWizard.tsx +++ b/src/components/wizard/ServerCreationWizard.tsx @@ -53,6 +53,7 @@ import { import { getNextCronDate } from "@/components/shared/CronBuilder"; import { useTauriEvent } from "@/hooks/useTauriEvent"; import { tauriCmd, type PortDef, type FirewallStatus } from "@/lib/tauri-commands"; +import { getServerFirewallPorts } from "@/lib/firewall-utils"; import { useAppStore } from "@/store/useAppStore"; import { cn } from "@/lib/utils"; import { useQueryClient } from "@tanstack/react-query"; @@ -1326,12 +1327,12 @@ function NetworkStep({ data, onChange }: { data: WizardData; onChange: (patch: P usedPorts.set(s.rcon_port, s.name); } - // Find next available game port (ARK uses game_port and game_port+1 internally, so step by 2) + // Find next available game port (step by 1 — ASA does not use port+1) const maxGame = Math.max(...servers.map((s) => s.port)); const maxQuery = Math.max(...servers.map((s) => s.query_port)); const maxRcon = Math.max(...servers.map((s) => s.rcon_port)); - const suggestGame = maxGame + 2; + const suggestGame = maxGame + 1; const suggestQuery = maxQuery + 1; const suggestRcon = maxRcon + 1; @@ -1342,8 +1343,12 @@ function NetworkStep({ data, onChange }: { data: WizardData; onChange: (patch: P onChange({ port: suggestGame, queryPort: suggestQuery, rconPort: suggestRcon }); } - // Check current values for conflicts - updateConflicts(data.port, data.queryPort, data.rconPort, usedPorts); + // Check conflicts against the ports that will actually be displayed — + // if we just auto-incremented, use the suggested values, not the stale closure values. + const checkGame = isDefault ? suggestGame : data.port; + const checkQuery = isDefault ? suggestQuery : data.queryPort; + const checkRcon = isDefault ? suggestRcon : data.rconPort; + updateConflicts(checkGame, checkQuery, checkRcon, usedPorts); }).catch(() => {}); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); @@ -1387,7 +1392,7 @@ function NetworkStep({ data, onChange }: { data: WizardData; onChange: (patch: P

Ports have been auto-suggested based on your existing servers. Each server needs a unique set of three ports.

- + {checking && ( @@ -1439,10 +1444,9 @@ function FirewallStep({ data }: { data: WizardData }) { const [errorMsg, setErrorMsg] = useState(""); const ports: PortDef[] = [ - { port: data.port, protocol: "udp" }, - { port: data.port + 1, protocol: "udp" }, - { port: data.queryPort, protocol: "udp" }, - { port: data.rconPort, protocol: "tcp" }, + { port: data.port, protocol: "udp" }, + { port: data.queryPort, protocol: "udp" }, + { port: data.rconPort, protocol: "tcp" }, ]; useEffect(() => { @@ -1460,8 +1464,23 @@ function FirewallStep({ data }: { data: WizardData }) { if (missing.length === 0) { setPhase("done"); return; } setPhase("adding"); try { + // Build the complete desired port set: all existing servers + this new server. + // The new server isn't in the DB yet, so we add its ports explicitly. + const existingServers = await getServers(); + const allPortsMap = new Map(); + for (const srv of existingServers) { + for (const p of getServerFirewallPorts(srv)) { + allPortsMap.set(`${p.port}/${p.protocol}`, p); + } + } + for (const p of ports) { + allPortsMap.set(`${p.port}/${p.protocol}`, p); + } const protonPath = (await getAppSetting("proton_path")) ?? undefined; - await tauriCmd.addFirewallRules(missing.map((p) => ({ port: p.port, protocol: p.protocol as "tcp" | "udp" })), protonPath); + await tauriCmd.addFirewallRules([...allPortsMap.values()], protonPath); + // Re-check so the port list shows real green checkmarks instead of staying stale. + const updated = await tauriCmd.checkFirewallPorts(ports); + setStatus(updated); setPhase("done"); } catch (e) { setErrorMsg(String(e)); @@ -1510,8 +1529,7 @@ function FirewallStep({ data }: { data: WizardData }) { style={{ background: "rgba(var(--neon-purple-rgb),0.05)", border: "1px solid rgba(var(--neon-purple-rgb),0.12)" }}> {p.port}/{p.protocol.toUpperCase()} - {p.port === data.port + 1 ? " (Steam P2P)" : ""} - + {p.covered ? : } diff --git a/src/lib/firewall-utils.ts b/src/lib/firewall-utils.ts index 4867fb2..a07735d 100644 --- a/src/lib/firewall-utils.ts +++ b/src/lib/firewall-utils.ts @@ -3,13 +3,12 @@ import { type ServerRow } from "@/lib/db"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; -/** Returns the 4-port set required for an ARK SA server. */ +/** Returns the 3-port set required for an ARK SA server. */ export function getServerFirewallPorts(server: ServerRow): PortDef[] { return [ - { port: server.port, protocol: "udp" }, - { port: server.port + 1, protocol: "udp" }, // Steam P2P peer port - { port: server.query_port, protocol: "udp" }, - { port: server.rcon_port, protocol: "tcp" }, + { port: server.port, protocol: "udp" }, + { port: server.query_port, protocol: "udp" }, + { port: server.rcon_port, protocol: "tcp" }, ]; } diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index 9451df0..2b8be66 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -354,6 +354,8 @@ export const tauriCmd = { /** Return on-disk byte counts for a server's backups, logs, and save data. */ getServerDiskUsage: (serverId: string, backupDir: string, baseDir: string, saveFolderName: string) => invoke<{ backupBytes: number; logBytes: number; saveBytes: number }>("get_server_disk_usage", { serverId, backupDir, baseDir, saveFolderName }), + /** Return the total size in bytes of any directory path. Returns 0 if path doesn't exist. */ + getDirSize: (path: string) => invoke("get_dir_size", { path }), // SteamCMD / installation /** Download and extract SteamCMD to targetDir. Streams to steamcmd://output/setup. */ @@ -707,7 +709,7 @@ export const tauriCmd = { // Clusters createCluster: (name: string, baseDir: string, clusterDirOverride?: string) => invoke("create_cluster", { name, baseDir, clusterDirOverride }), - deleteCluster: (clusterId: string) => invoke("delete_cluster", { clusterId }), + deleteCluster: (clusterDir: string, deleteFiles: boolean) => invoke("delete_cluster", { clusterDir, deleteFiles }), addServerToCluster: (serverId: string, clusterId: string) => invoke("add_server_to_cluster", { serverId, clusterId }), removeServerFromCluster: (serverId: string) => From 5564a06b77362e6eedff70e8147bc66d0ee6053e Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 22 Jun 2026 20:26:08 -0500 Subject: [PATCH 06/28] feat: add Mod Maps section to sidebar and implement save import functionality - Added a new "Mod Maps" entry in the sidebar navigation. - Updated ServerActionMenu to remove legacy save folder name handling. - Enhanced ServerCard to create save links after server updates. - Modified BackupsTab to utilize base directory for backups and removed save folder name dependency. - Updated OverviewTab to support importing save data from other stopped servers. - Introduced a new dialog for importing saves, allowing users to select a source server. - Created useAllMaps hook to merge built-in and custom maps for better map management. - Implemented database migrations for custom mod maps and updated related database functions. - Refactored server utility functions to remove legacy save folder name handling. --- src-tauri/src/commands/backup.rs | 169 ++++++++----- src-tauri/src/commands/backup_manager.rs | 13 +- src-tauri/src/commands/scheduler.rs | 1 - src-tauri/src/commands/server.rs | 21 +- src-tauri/src/db.rs | 15 +- src-tauri/src/lib.rs | 1 + src/app/mod-maps/page.tsx | 235 ++++++++++++++++++ src/components/layout/Sidebar.tsx | 2 + src/components/server/ServerActionMenu.tsx | 21 +- src/components/server/ServerCard.tsx | 3 + src/components/server/tabs/BackupsTab.tsx | 10 +- src/components/server/tabs/OverviewTab.tsx | 107 +++++++- .../wizard/ServerCreationWizard.tsx | 63 ++--- src/hooks/useAllMaps.ts | 36 +++ src/lib/db.ts | 48 +++- src/lib/server-utils.ts | 1 - src/lib/tauri-commands.ts | 37 ++- 17 files changed, 606 insertions(+), 177 deletions(-) create mode 100644 src/app/mod-maps/page.tsx create mode 100644 src/hooks/useAllMaps.ts diff --git a/src-tauri/src/commands/backup.rs b/src-tauri/src/commands/backup.rs index 80fdab5..d0ed68e 100644 --- a/src-tauri/src/commands/backup.rs +++ b/src-tauri/src/commands/backup.rs @@ -347,12 +347,13 @@ pub async fn cleanup_ark_own_backups( // Server backup (SavedArks + SaveGames → .7z) // --------------------------------------------------------------------------- -/// Inner implementation for server backup — callable from both the Tauri command -/// and the Rust backup_manager tick handler (which cannot use State<'_> wrappers). +/// Inner implementation callable from both the Tauri command and the Rust +/// backup_manager tick handler (which cannot use State<'_> wrappers). /// -/// `skip_world_save`: pass `true` when the caller has already issued SaveWorld -/// (e.g. the scheduler tick that consolidates the save across backup types). -/// Pass `false` for manual/UI-triggered backups so they save on their own. +/// `skip_world_save`: pass `true` when the caller has already issued SaveWorld. +/// `base_dir`: when non-empty, resolves the canonical save path +/// `{base_dir}/Saves/{server_id}/SavedArks/{map_path}` instead of following +/// the SavedArks symlink inside the install directory. pub async fn create_server_backup_inner( app: &AppHandle, server_id: &str, @@ -365,8 +366,9 @@ pub async fn create_server_backup_inner( tier: &str, pool: &RconPool, skip_world_save: bool, + base_dir: &str, ) -> Result { - create_server_backup_impl(app, server_id, server_name, install_path, map_path, map_id, backup_dir, triggered_by, tier, pool, skip_world_save).await + create_server_backup_impl(app, server_id, server_name, install_path, map_path, map_id, backup_dir, triggered_by, tier, pool, skip_world_save, base_dir).await } /// Tauri command: exposed to the frontend for manual/UI-triggered backups. @@ -381,14 +383,10 @@ pub async fn create_server_backup( backup_dir: String, triggered_by: String, tier: String, - save_folder_name: Option, + base_dir: String, pool: State<'_, RconPool>, ) -> Result { - // Use save_folder_name as the save dir when set (new symlink-based layout) - let effective_map_path = save_folder_name - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| map_path.clone()); - let result = create_server_backup_inner(&app, &server_id, &server_name, &install_path, &effective_map_path, &map_id, &backup_dir, &triggered_by, &tier, &pool, false).await; + let result = create_server_backup_inner(&app, &server_id, &server_name, &install_path, &map_path, &map_id, &backup_dir, &triggered_by, &tier, &pool, false, &base_dir).await; if let Ok(ref rec) = result { let size = fmt_size(rec.file_size_bytes); crate::commands::notifications::dispatch_notification( @@ -411,6 +409,7 @@ async fn create_server_backup_impl( tier: &str, pool: &RconPool, skip_world_save: bool, + base_dir: &str, ) -> Result { const MAX_ATTEMPTS: u32 = 3; const RETRY_DELAY_SECS: u64 = 15; @@ -427,8 +426,12 @@ async fn create_server_backup_impl( sleep(Duration::from_secs(POST_SAVE_WAIT_SECS)).await; } - let saved_arks = PathBuf::from(&install_path) - .join("ShooterGame").join("Saved").join("SavedArks").join(&map_path); + // Use canonical path when base_dir is known, otherwise fall back to following the symlink. + let saved_arks = if !base_dir.is_empty() { + PathBuf::from(base_dir).join("Saves").join(server_id).join("SavedArks").join(map_path) + } else { + PathBuf::from(&install_path).join("ShooterGame").join("Saved").join("SavedArks").join(map_path) + }; let save_games = PathBuf::from(&install_path) .join("ShooterGame").join("Saved").join("SaveGames"); let saved_root = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); @@ -584,12 +587,8 @@ pub async fn backup_all_players( map_id: String, backup_dir: String, triggered_by: String, - save_folder_name: Option, ) -> Result, String> { - let effective_map_path = save_folder_name - .filter(|s| !s.is_empty()) - .unwrap_or_else(|| map_path.clone()); - let result = backup_all_players_inner(&app, &server_id, &server_name, &install_path, &effective_map_path, &map_id, &backup_dir, &triggered_by).await; + let result = backup_all_players_inner(&app, &server_id, &server_name, &install_path, &map_path, &map_id, &backup_dir, &triggered_by).await; if let Ok(ref recs) = result { let count = recs.len(); if count > 0 { @@ -776,53 +775,55 @@ pub async fn create_ini_backup( }) } -/// Create the save directory link used with -SaveDirectoryOverride. +/// Create the save directory link for a server. /// /// Creates: -/// `{base_dir}/Saves/{save_folder_name}/` ← the real save location -/// `{install_path}/ShooterGame/Saved/SavedArks/{save_folder_name}` ← the link target +/// `{base_dir}/Saves/{server_id}/SavedArks/` ← the real save location +/// `{install_path}/ShooterGame/Saved/SavedArks` → symlink ← replaces the whole SavedArks dir /// -/// On Linux: a symlink pointing to the base_dir/Saves/ subdirectory. -/// On Windows: an NTFS junction point (no admin rights required for junctions on local filesystems). +/// On Linux: a symlink. On Windows: an NTFS junction (no admin rights required). /// -/// If the link already exists and already points to the correct target, returns success without changes. +/// If `SavedArks` already exists as a regular directory (first-run or leftover from a +/// previous install), it is removed so the symlink/junction can be placed at that path. +/// If the link already points to the correct target, returns success without changes. #[tauri::command] pub async fn create_save_link( install_path: String, - save_folder_name: String, + server_id: String, base_dir: String, ) -> Result<(), String> { - if save_folder_name.is_empty() { - return Err("save_folder_name must not be empty".to_string()); + if server_id.is_empty() { + return Err("server_id must not be empty".to_string()); } - // The real save storage directory - let save_target = PathBuf::from(&base_dir).join("Saves").join(&save_folder_name); + // The canonical save storage directory (real data lives here) + let save_target = PathBuf::from(&base_dir).join("Saves").join(&server_id).join("SavedArks"); fs::create_dir_all(&save_target).map_err(|e| format!("Failed to create save target dir: {e}"))?; - // The path where the server expects saves (must be the link) - let saved_arks = PathBuf::from(&install_path) - .join("ShooterGame").join("Saved").join("SavedArks"); - fs::create_dir_all(&saved_arks).map_err(|e| format!("Failed to create SavedArks dir: {e}"))?; - - let link_path = saved_arks.join(&save_folder_name); + // The path inside the server install where SavedArks should be (will become the link) + let saved_dir = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); + fs::create_dir_all(&saved_dir).map_err(|e| format!("Failed to create Saved dir: {e}"))?; + let link_path = saved_dir.join("SavedArks"); - // If already correctly linked, do nothing + // If something already exists at link_path, check it and remove if wrong if link_path.exists() || link_path.is_symlink() { - #[cfg(target_os = "linux")] - { - if let Ok(existing) = std::fs::read_link(&link_path) { - if existing == save_target { - return Ok(()); - } + if let Ok(existing) = std::fs::read_link(&link_path) { + if existing == save_target { + return Ok(()); } - // Wrong target or broken link — remove and recreate - let _ = fs::remove_file(&link_path); } - #[cfg(target_os = "windows")] - { - // Junction already exists — leave it; user can manage via OS if needed - return Ok(()); + // Wrong target, broken link, or plain directory — remove so we can recreate. + // On Windows, junctions must be removed with remove_dir (not remove_dir_all, + // which would follow the junction and delete the actual save data). + if link_path.is_symlink() { + #[cfg(target_os = "windows")] + { let _ = fs::remove_dir(&link_path); } + #[cfg(not(target_os = "windows"))] + { let _ = fs::remove_file(&link_path); } + } else if link_path.is_dir() { + let _ = fs::remove_dir_all(&link_path); + } else { + let _ = fs::remove_file(&link_path); } } @@ -847,23 +848,19 @@ pub async fn create_save_link( /// - `"players"` — delete `.arkprofile` and `.arktribe` files only (resets characters/tribes). /// - `"full"` — delete all save files (world + characters + tribe + mod saves). /// -/// The save directory is `{install_path}/ShooterGame/Saved/SavedArks/{save_folder_name}/` -/// when save_folder_name is non-empty, otherwise `{install_path}/ShooterGame/Saved/SavedArks/`. +/// `SavedArks` is a symlink to the canonical save directory, so all tiers operate +/// on the real data transparently. `map_path` is the map folder name (e.g. `TheIsland_WP`). /// /// The server MUST NOT be running when this is called (enforced on the frontend). #[tauri::command] pub async fn wipe_server_saves( install_path: String, - save_folder_name: String, + map_path: String, tier: String, ) -> Result<(), String> { - let saves_root = if save_folder_name.is_empty() { - PathBuf::from(&install_path).join("ShooterGame").join("Saved").join("SavedArks") - } else { - PathBuf::from(&install_path) - .join("ShooterGame").join("Saved").join("SavedArks") - .join(&save_folder_name) - }; + let saves_root = PathBuf::from(&install_path) + .join("ShooterGame").join("Saved").join("SavedArks") + .join(&map_path); if !saves_root.exists() { return Ok(()); @@ -914,6 +911,60 @@ pub async fn wipe_server_saves( Ok(()) } +/// Copy the save data for a specific map from one server to another. +/// +/// Source: `{base_dir}/Saves/{source_server_id}/SavedArks/{map_path}/` +/// Target: `{base_dir}/Saves/{target_server_id}/SavedArks/{map_path}/` +/// +/// The target map subfolder is cleared before the copy so the result is an +/// exact mirror of the source. Both servers must be stopped before calling this. +#[tauri::command] +pub async fn import_server_saves( + source_server_id: String, + target_server_id: String, + base_dir: String, + map_path: String, +) -> Result<(), String> { + if source_server_id == target_server_id { + return Err("Source and target server must be different".to_string()); + } + + let source = PathBuf::from(&base_dir) + .join("Saves").join(&source_server_id).join("SavedArks").join(&map_path); + let target = PathBuf::from(&base_dir) + .join("Saves").join(&target_server_id).join("SavedArks").join(&map_path); + + if !source.exists() { + return Err(format!("Source save directory does not exist: {}", source.display())); + } + + // Clear the target map subfolder first + if target.exists() { + fs::remove_dir_all(&target).map_err(|e| format!("Failed to clear target save dir: {e}"))?; + } + fs::create_dir_all(&target).map_err(|e| format!("Failed to create target save dir: {e}"))?; + + // Recursively copy everything from source into target + fn copy_dir(src: &Path, dst: &Path) -> Result<(), String> { + for entry in fs::read_dir(src).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + let dst_path = dst.join(entry.file_name()); + let src_path = entry.path(); + if src_path.is_dir() { + fs::create_dir_all(&dst_path).map_err(|e| e.to_string())?; + copy_dir(&src_path, &dst_path)?; + } else { + fs::copy(&src_path, &dst_path) + .map_err(|e| format!("Failed to copy {:?}: {e}", src_path))?; + } + } + Ok(()) + } + + copy_dir(&source, &target)?; + Ok(()) +} + /// List timestamped INI snapshot folders for a server (newest first). #[tauri::command] pub async fn list_ini_backups( diff --git a/src-tauri/src/commands/backup_manager.rs b/src-tauri/src/commands/backup_manager.rs index 8ae4a27..f602180 100644 --- a/src-tauri/src/commands/backup_manager.rs +++ b/src-tauri/src/commands/backup_manager.rs @@ -387,10 +387,7 @@ pub async fn handle_player_login(app: &AppHandle, server_id: &str, eos_id: &str, _ => return, }; - let base_map_path = map_id_to_path(&server.map_id); - let map_path = server.save_folder_name.as_deref() - .filter(|s| !s.is_empty()) - .unwrap_or(base_map_path); + let map_path = map_id_to_path(&server.map_id); // Create the archive (eos_id used as player_name for the filename). let rec = match create_player_backup_inner( @@ -482,6 +479,8 @@ pub async fn execute_tick(app: &AppHandle) { } }; + let base_dir = db::get_app_setting(&conn, "base_dir").unwrap_or_default(); + let servers = db::get_servers(&conn); let pool = app.state::(); @@ -491,10 +490,7 @@ pub async fn execute_tick(app: &AppHandle) { } let schedules = db::get_server_schedules(&conn, &server.id); - let base_map_path = map_id_to_path(&server.map_id); - let map_path = server.save_folder_name.as_deref() - .filter(|s| !s.is_empty()) - .unwrap_or(base_map_path); + let map_path = map_id_to_path(&server.map_id); // Parse both schedule configs up front so we can decide whether a // world save is needed before starting either backup. @@ -539,6 +535,7 @@ pub async fn execute_tick(app: &AppHandle) { "", // tier assigned after tier computation &pool, true, // world save already done above + &base_dir, ).await { Ok(rec) => { handle_backup_record(&conn, &rec, &cfg, "server", None); diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index b99898a..47cd841 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -349,7 +349,6 @@ fn entry_to_start_params(entry: &crate::state::scheduler::ScheduleEntry) -> Star mod_ids: entry.mod_ids.clone(), proton_path: entry.proton_path.clone(), prefix_path: entry.prefix_path.clone(), - alt_save_directory_name: None, } } diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index c535c23..6b40d31 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -116,9 +116,6 @@ pub struct StartServerParams { pub proton_path: Option, /// Linux only: WINEPREFIX path where Proton creates its fake C: drive. pub prefix_path: Option, - /// When set, appended as ?AltSaveDirectoryName= in the map query string. - /// ASA reads this from the URL and saves to SavedArks/{name} instead of SavedArks/{mapPath}. - pub alt_save_directory_name: Option, } // --------------------------------------------------------------------------- @@ -241,16 +238,11 @@ async fn inner_start_server_with_state( // Passwords, RCON, MaxPlayers, and all gameplay settings are read by the // server from GameUserSettings.ini — they must NOT be duplicated on the CLI // or they will override INI values on every restart. - let alt_save = params.alt_save_directory_name.as_deref() - .filter(|s| !s.is_empty()) - .map(|s| format!("?AltSaveDirectoryName={s}")) - .unwrap_or_default(); let query_string = format!( - "{}?listen?Port={}?QueryPort={}{}", + "{}?listen?Port={}?QueryPort={}", params.map_path, params.port, params.query_port, - alt_save, ); // Build the platform-specific Command. @@ -954,7 +946,6 @@ pub async fn scan_running_servers( mod_ids: vec![], proton_path: None, prefix_path: None, - alt_save_directory_name: None, }; registry.insert( entry.server_id.clone(), @@ -1103,7 +1094,6 @@ pub async fn get_server_disk_usage( server_id: String, backup_dir: String, base_dir: String, - save_folder_name: String, ) -> Result { fn dir_size(path: &std::path::Path) -> u64 { if !path.exists() { return 0; } @@ -1136,8 +1126,8 @@ pub async fn get_server_disk_usage( p.map(|d| dir_size(&d)).unwrap_or(0) }; - let save_bytes = if !base_dir.is_empty() && !save_folder_name.is_empty() { - let p = std::path::PathBuf::from(&base_dir).join("Saves").join(&save_folder_name); + let save_bytes = if !base_dir.is_empty() { + let p = std::path::PathBuf::from(&base_dir).join("Saves").join(&server_id).join("SavedArks"); dir_size(&p) } else { 0 @@ -1162,7 +1152,6 @@ pub async fn delete_server( install_path: String, backup_dir: String, base_dir: String, - save_folder_name: String, delete_files: bool, delete_backups: bool, delete_logs: bool, @@ -1209,8 +1198,8 @@ pub async fn delete_server( } } - if delete_saves && !base_dir.is_empty() && !save_folder_name.is_empty() { - let p = std::path::PathBuf::from(&base_dir).join("Saves").join(&save_folder_name); + if delete_saves && !base_dir.is_empty() { + let p = std::path::PathBuf::from(&base_dir).join("Saves").join(&server_id); if p.exists() { std::fs::remove_dir_all(&p) .map_err(|e| format!("Failed to delete save data: {e}"))?; diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index 2cdfe1a..fb73bc1 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -78,14 +78,13 @@ pub struct ServerRow { pub name: String, pub map_id: String, pub install_path: String, - pub save_folder_name: Option, pub backup_broadcast_message: Option, pub memory_limit_gb: Option, } pub fn get_server(conn: &Connection, server_id: &str) -> Option { conn.query_row( - "SELECT id, name, map_id, install_path, save_folder_name, backup_broadcast_message, memory_limit_gb FROM servers WHERE id = ?1", + "SELECT id, name, map_id, install_path, backup_broadcast_message, memory_limit_gb FROM servers WHERE id = ?1", [server_id], |row| { Ok(ServerRow { @@ -93,9 +92,8 @@ pub fn get_server(conn: &Connection, server_id: &str) -> Option { name: row.get(1)?, map_id: row.get(2)?, install_path: row.get(3)?, - save_folder_name: row.get(4)?, - backup_broadcast_message: row.get(5)?, - memory_limit_gb: row.get(6)?, + backup_broadcast_message: row.get(4)?, + memory_limit_gb: row.get(5)?, }) }, ) @@ -104,7 +102,7 @@ pub fn get_server(conn: &Connection, server_id: &str) -> Option { pub fn get_servers(conn: &Connection) -> Vec { let mut stmt = match conn.prepare( - "SELECT id, name, map_id, install_path, save_folder_name, backup_broadcast_message, memory_limit_gb FROM servers", + "SELECT id, name, map_id, install_path, backup_broadcast_message, memory_limit_gb FROM servers", ) { Ok(s) => s, Err(e) => { @@ -118,9 +116,8 @@ pub fn get_servers(conn: &Connection) -> Vec { name: row.get(1)?, map_id: row.get(2)?, install_path: row.get(3)?, - save_folder_name: row.get(4)?, - backup_broadcast_message: row.get(5)?, - memory_limit_gb: row.get(6)?, + backup_broadcast_message: row.get(4)?, + memory_limit_gb: row.get(5)?, }) }) .map(|rows| rows.filter_map(|r| r.ok()).collect()) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 187ac3f..c27b7e8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -550,6 +550,7 @@ pub fn run() { commands::backup::create_ini_backup, commands::backup::create_save_link, commands::backup::wipe_server_saves, + commands::backup::import_server_saves, commands::backup::create_full_backup, commands::backup::list_ini_backups, commands::backup::restore_server_backup, diff --git a/src/app/mod-maps/page.tsx b/src/app/mod-maps/page.tsx new file mode 100644 index 0000000..a64ecf2 --- /dev/null +++ b/src/app/mod-maps/page.tsx @@ -0,0 +1,235 @@ +"use client"; + +import { useState, useEffect, useCallback } from "react"; +import { Map, Plus, Trash2, Loader2 } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { toast } from "sonner"; +import { getCustomMaps, insertCustomMap, deleteCustomMap, type CustomMapRow } from "@/lib/db"; +import { ARK_MAPS } from "@/data/game-data"; + +export default function ModMapsPage() { + const [customMaps, setCustomMaps] = useState([]); + const [loading, setLoading] = useState(true); + const [showAdd, setShowAdd] = useState(false); + const [displayName, setDisplayName] = useState(""); + const [modId, setModId] = useState(""); + const [mapPath, setMapPath] = useState(""); + const [saving, setSaving] = useState(false); + + const load = useCallback(async () => { + setLoading(true); + try { + setCustomMaps(await getCustomMaps()); + } catch (e) { + toast.error(`Failed to load custom maps: ${e}`); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { load(); }, [load]); + + const handleAdd = async () => { + const name = displayName.trim(); + const id = modId.trim(); + const path = mapPath.trim(); + if (!name || !id || !path) { toast.error("All fields are required."); return; } + if (!/^\d+$/.test(id)) { toast.error("Mod ID must be numeric."); return; } + setSaving(true); + try { + await insertCustomMap(crypto.randomUUID(), name, id, path); + setDisplayName(""); setModId(""); setMapPath(""); + setShowAdd(false); + await load(); + toast.success(`Custom map "${name}" added.`); + } catch (e) { + toast.error(`Failed to add map: ${e}`); + } finally { + setSaving(false); + } + }; + + const handleDelete = async (map: CustomMapRow) => { + try { + await deleteCustomMap(map.id); + await load(); + toast.success(`"${map.display_name}" removed.`); + } catch (e) { + toast.error(`Failed to delete map: ${e}`); + } + }; + + return ( +
+ {/* Header */} +
+
+ +
+

Mod Maps

+

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

+
+
+ +
+ + {/* Add form */} + {showAdd && ( +
+

New Custom Map

+
+
+ + setDisplayName(e.target.value)} + placeholder="e.g. Fjordur Reborn" + style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + /> +
+
+ + setModId(e.target.value)} + placeholder="e.g. 965379" + style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + /> +
+
+ + setMapPath(e.target.value)} + placeholder="e.g. MyMap_WP" + style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + /> +

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

+
+
+
+ + +
+
+ )} + + {/* Official maps reference */} +
+

+ Official Maps (read-only reference) +

+
+ {ARK_MAPS.filter((m) => m.isOfficial && m.released).map((m, i, arr) => ( +
+ {m.displayName} + {m.mapPath} +
+ ))} +
+
+ + {/* Built-in mod maps reference */} + {ARK_MAPS.filter((m) => m.isMod && m.released).length > 0 && ( +
+

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

+
+ {ARK_MAPS.filter((m) => m.isMod && m.released).map((m, i, arr) => ( +
+
+ {m.displayName} + {m.requiredModId && ( + mod {m.requiredModId} + )} +
+ {m.mapPath} +
+ ))} +
+
+ )} + + {/* Custom maps */} +
+

+ Your Custom Maps +

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

No custom maps added yet.

+

+ Use the Add Map button above to register a community mod map. +

+
+ ) : ( +
+ {customMaps.map((m, i) => ( +
+
+

{m.display_name}

+

+ mod {m.mod_id} · {m.map_path} +

+
+ +
+ ))} +
+ )} +
+
+ ); +} diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx index c574fd5..6ffce7b 100644 --- a/src/components/layout/Sidebar.tsx +++ b/src/components/layout/Sidebar.tsx @@ -10,6 +10,7 @@ import { Network, ScrollText, Archive, + Map, Bell, Settings, HelpCircle, @@ -30,6 +31,7 @@ const TOP_NAV: NavItem[] = [ { href: "/clusters", icon: Network, label: "Clusters" }, { href: "/logs", icon: ScrollText, label: "Logs" }, { href: "/backups", icon: Archive, label: "Backups" }, + { href: "/mod-maps", icon: Map, label: "Mod Maps" }, ]; const BOTTOM_NAV: NavItem[] = [ diff --git a/src/components/server/ServerActionMenu.tsx b/src/components/server/ServerActionMenu.tsx index f503d0e..2621061 100644 --- a/src/components/server/ServerActionMenu.tsx +++ b/src/components/server/ServerActionMenu.tsx @@ -139,7 +139,7 @@ function DeleteDialog({ const bsd = bsDir ?? ""; setBackupDir(bd); setBaseDir(bsd); - return tauriCmd.getServerDiskUsage(server.id, bd, bsd, server.save_folder_name ?? ""); + return tauriCmd.getServerDiskUsage(server.id, bd, bsd); }).then((usage) => { setDiskUsage(usage); }).catch(() => {}); @@ -161,7 +161,6 @@ function DeleteDialog({ server.install_path, backupDir, baseDir, - server.save_folder_name ?? "", deleteFiles, deleteBackups, deleteLogs, @@ -181,8 +180,6 @@ function DeleteDialog({ .map((p) => `${p.port}/${p.protocol.toUpperCase()}`) .join(", "); - const hasSaveFolder = !!(server.save_folder_name); - return ( !v && onClose()}> e.stopPropagation()}> @@ -217,15 +214,13 @@ function DeleteDialog({ onToggle={() => setDeleteLogs((v) => !v)} color="var(--neon-red)" /> - {hasSaveFolder && ( - 0 ? ` (${formatBytes(diskUsage.saveBytes)})` : diskUsage ? " (none)" : ""}`} - sublabel={baseDir ? `${baseDir}/Saves/${server.save_folder_name}/` : "Saves directory"} - enabled={deleteSaves} - onToggle={() => setDeleteSaves((v) => !v)} - color="var(--neon-red)" - /> - )} + 0 ? ` (${formatBytes(diskUsage.saveBytes)})` : diskUsage ? " (none)" : ""}`} + sublabel={baseDir ? `${baseDir}/Saves/${server.id}/` : "Saves directory"} + enabled={deleteSaves} + onToggle={() => setDeleteSaves((v) => !v)} + color="var(--neon-red)" + /> {exclusivePorts.length > 0 && ( { + console.warn("createSaveLink failed after reinstall:", e); + }); await updateServerStatus(server.id, "stopped", null); dispatchNotification({ eventType: NOTIFICATION_EVENTS.SERVER_INSTALL_COMPLETE, diff --git a/src/components/server/tabs/BackupsTab.tsx b/src/components/server/tabs/BackupsTab.tsx index 9c2bbdf..4402cf3 100644 --- a/src/components/server/tabs/BackupsTab.tsx +++ b/src/components/server/tabs/BackupsTab.tsx @@ -715,22 +715,25 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { const [showFullWarning, setShowFullWarning] = useState(false); const [fullEstimate, setFullEstimate] = useState(0); const [backupDir, setBackupDir] = useState(""); + const [baseDir, setBaseDir] = useState(""); const [syncPending, setSyncPending] = useState<{ toImport: BackupRecord[] } | null>(null); const [syncing, setSyncing] = useState(false); const loadAll = useCallback(async () => { setLoading(true); try { - const [srv, plr, ful, bdir] = await Promise.all([ + const [srv, plr, ful, bdir, bsdir] = await Promise.all([ getServerBackupsByType(server.id, "server"), getServerBackupsByType(server.id, "player"), getServerBackupsByType(server.id, "full"), getAppSetting("backup_dir"), + getAppSetting("base_dir"), ]); setServerBackups(srv); setPlayerBackups(plr); setFullBackups(ful); setBackupDir(bdir ?? ""); + setBaseDir(bsdir ?? ""); } catch (e) { toast.error(`Failed to load backups: ${e}`); } finally { @@ -765,7 +768,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { try { const rec: BackupRecord = await tauriCmd.createServerBackup( server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual", - "", server.save_folder_name || undefined + "", baseDir ); await insertBackup({ id: rec.id, server_id: rec.serverId, file_path: rec.filePath, @@ -789,8 +792,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { setProgress({ active: true, percent: 0, currentFile: "", label: "Starting player backups…" }); try { const records = await tauriCmd.backupAllPlayers( - server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual", - server.save_folder_name || undefined + server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual" ); if (records.length === 0) { toast.info("No player profiles found to back up."); diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index bcc1810..95f0de1 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -28,7 +28,7 @@ import { useAppStore } from "@/store/useAppStore"; import { updateServerStatus, getServerConfig, getServerModCount, getLastBackupTime, getNextScheduledRestart, getHasBackupEnabled, getAppSetting, insertBackup, - pruneManualBackups, setServerAutoStart, + pruneManualBackups, setServerAutoStart, getServers, } from "@/lib/db"; import { buildLaunchCommandPreview, buildStartParams, isLinux } from "@/lib/server-utils"; import { applyUpdateToServer } from "@/lib/update-utils"; @@ -38,7 +38,7 @@ import type { ServerRow } from "@/lib/db"; import { formatServerVersion } from "@/lib/db"; import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; import { toast } from "sonner"; -import { ARK_MAPS, ARK_EVENTS, NOTIFICATION_EVENTS } from "@/data/game-data"; +import { ARK_MAPS, ARK_EVENTS, NOTIFICATION_EVENTS, getMapById } from "@/data/game-data"; import { setServerActiveEvent } from "@/lib/db"; import { dispatchNotification } from "@/lib/notifications"; import { useQueryClient } from "@tanstack/react-query"; @@ -590,6 +590,10 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate const [applyingUpdate, setApplyingUpdate] = useState(false); const [wipeConfirm, setWipeConfirm] = useState<"map" | "players" | "full" | null>(null); const [wiping, setWiping] = useState(false); + const [showImport, setShowImport] = useState(false); + const [importSourceId, setImportSourceId] = useState(""); + const [importing, setImporting] = useState(false); + const [importServers, setImportServers] = useState([]); const [autoCheckEnabled, setAutoCheckEnabled] = useState(true); const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); const [launchCommand, setLaunchCommand] = useState(""); @@ -817,6 +821,9 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate queryClient.invalidateQueries({ queryKey: ["servers"] }); router.push("/"); tauriCmd.updateServer(server.id, server.install_path, cacheDir, steamcmdPath) + .then(() => tauriCmd.createSaveLink(server.install_path, server.id, baseDir).catch((e) => { + console.warn("createSaveLink failed after reinstall:", e); + })) .then(() => updateServerStatus(server.id, "stopped", null)) .catch(() => updateServerStatus(server.id, "install_failed", null)) .finally(() => queryClient.invalidateQueries({ queryKey: ["servers"] })); @@ -827,8 +834,9 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate const handleWipe = async (tier: "map" | "players" | "full") => { setWiping(true); + const mapPath = getMapById(server.map_id)?.mapPath ?? server.map_id; try { - await tauriCmd.wipeServerSaves(server.install_path, server.save_folder_name ?? "", tier); + await tauriCmd.wipeServerSaves(server.install_path, mapPath, tier); setWipeConfirm(null); toast.success(`Save wipe complete (${tier})`); } catch (e) { @@ -838,6 +846,30 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate } }; + const openImportDialog = async () => { + const all = await getServers(); + setImportServers(all.filter((s) => s.id !== server.id && s.status === "stopped")); + setImportSourceId(""); + setShowImport(true); + }; + + const handleImport = async () => { + if (!importSourceId) return; + setImporting(true); + try { + const baseDir = await getAppSetting("base_dir"); + if (!baseDir) throw new Error("Base directory not configured"); + const mapPath = getMapById(server.map_id)?.mapPath ?? server.map_id; + await tauriCmd.importServerSaves(importSourceId, server.id, baseDir, mapPath); + setShowImport(false); + toast.success("Save data imported successfully"); + } catch (e) { + toast.error(`Import failed: ${e}`); + } finally { + setImporting(false); + } + }; + const refreshPlayers = useCallback(async () => { setPlayersLoading(true); try { @@ -987,10 +1019,10 @@ export function OverviewTab({ server, onNavigateToConfig }: Props & { onNavigate
)} + {/* ── Import Saves card ── */} + {!isRunning && ( +
+
+ +

Import Saves

+
+

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

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

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

+ ) : ( + + )} +
+ + + + +
+
+ {/* ── Update confirmation dialog ── */} diff --git a/src/components/wizard/ServerCreationWizard.tsx b/src/components/wizard/ServerCreationWizard.tsx index edcfe68..fdbab10 100644 --- a/src/components/wizard/ServerCreationWizard.tsx +++ b/src/components/wizard/ServerCreationWizard.tsx @@ -34,6 +34,7 @@ import { Slider } from "@/components/ui/slider"; import { CommandOutputPanel } from "@/components/shared/CommandOutputPanel"; import { NumberField } from "@/components/shared/NumberField"; import { LokiIcon } from "@/components/shared/LokiIcon"; +import { useAllMaps } from "@/hooks/useAllMaps"; import { getReleasedMaps, getOfficialMaps, getModMaps, getMapById, GAME_MODES, PRESET_STYLES, INI_FIELD_GROUPS, buildPresetConfig, @@ -134,8 +135,6 @@ interface WizardData { rconPort: number; // Cluster clusterId: string; - // Save directory - saveFolderName: string; // Automation — restart autoRestart: boolean; autoRestartCron: string; @@ -223,7 +222,6 @@ const DEFAULT_DATA: WizardData = { queryPort: 27015, rconPort: 27020, clusterId: "", - saveFolderName: "", autoRestart: true, autoRestartCron: "0 6 * * *", serverBackupTiers: { @@ -329,8 +327,9 @@ function BasicInfoStep({ onChange: (patch: Partial) => void; onNameValidated: (valid: boolean) => void; }) { - const officialMaps = getOfficialMaps(); - const modMaps = getModMaps(); + const allMaps = useAllMaps(); + const officialMaps = allMaps.filter((m) => m.released && !m.isMod); + const modMaps = allMaps.filter((m) => m.released && m.isMod); const [nameError, setNameError] = useState(""); const [checkingName, setCheckingName] = useState(false); const [nameChecked, setNameChecked] = useState(false); @@ -341,7 +340,7 @@ function BasicInfoStep({ const [showServerPw, setShowServerPw] = useState(false); const [showServerConfirm,setShowServerConfirm]= useState(false); - const selectedMap = getMapById(data.mapId); + const selectedMap = allMaps.find((m) => m.id === data.mapId); // Close dropdown when clicking outside useEffect(() => { @@ -379,14 +378,6 @@ function BasicInfoStep({ const handleMapSelect = (map: ArkMap) => { const patch: Partial = { mapId: map.id }; - // Auto-update save folder name if it hasn't been manually edited - // (still empty or still equal to the old map's display name) - const prevMap = getMapById(data.mapId); - const prevDefaultName = prevMap?.displayName ?? ""; - if (!data.saveFolderName || data.saveFolderName === prevDefaultName) { - patch.saveFolderName = map.displayName; - } - if (map.isMod && map.requiredModId) { // Auto-add the required mod and lock it const newModIds = data.modIds.includes(map.requiredModId) @@ -395,8 +386,8 @@ function BasicInfoStep({ patch.modIds = newModIds; patch.lockedModIds = [map.requiredModId]; } else { - if (prevMap?.isMod && prevMap.requiredModId) { - patch.modIds = data.modIds.filter((id) => id !== prevMap.requiredModId); + if (selectedMap?.isMod && selectedMap.requiredModId) { + patch.modIds = data.modIds.filter((id) => id !== selectedMap.requiredModId); patch.lockedModIds = []; } else { patch.lockedModIds = []; @@ -541,18 +532,14 @@ function BasicInfoStep({ )}
- {/* Save Folder Name */} -
- - onChange({ saveFolderName: e.target.value })} - placeholder={selectedMap?.displayName ?? "e.g. TheIsland"} - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} - /> -

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

+

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

@@ -2118,6 +2105,7 @@ function AutomationStep({ data, onChange }: { data: WizardData; onChange: (patch // --------------------------------------------------------------------------- function ModsStep({ data, onChange }: { data: WizardData; onChange: (patch: Partial) => void }) { + const allMaps = useAllMaps(); const [input, setInput] = useState(""); const [existingServers, setExistingServers] = useState([]); const [copyFromId, setCopyFromId] = useState(""); @@ -2188,7 +2176,7 @@ function ModsStep({ data, onChange }: { data: WizardData; onChange: (patch: Part onChange({ modIds: data.modIds.filter((m) => m !== id) }); }; - const selectedMap = getMapById(data.mapId); + const selectedMap = allMaps.find((m) => m.id === data.mapId); return (
@@ -2331,6 +2319,7 @@ function InstallStep({ onStatusChange: (status: string) => void; onCleanupReady: (fn: () => Promise) => void; }) { + const allMaps = useAllMaps(); const queryClient = useQueryClient(); const [status, setStatus] = useState<"idle" | "installing" | "done" | "error">("idle"); const [canceled, setCanceled] = useState(false); @@ -2341,7 +2330,6 @@ function InstallStep({ const steamcmdPathRef = useRef(""); const cacheDirRef = useRef(""); const baseDirRef = useRef(""); - const saveFolderNameRef = useRef(""); const terminalRef = useRef(null); const sentinelRef = useRef(null); const backgroundRef = useRef(false); @@ -2360,7 +2348,7 @@ function InstallStep({ return () => ro.disconnect(); }, [scrollToBottom]); - const selectedMap = getMapById(data.mapId); + const selectedMap = allMaps.find((m) => m.id === data.mapId); const presetLabel = (() => { const modeLabel = data.gameMode === "pvp" ? "PvP" : "PvE"; const styleLabel = PRESET_STYLES.find((s) => s.id === data.presetStyle)?.displayName ?? data.presetStyle; @@ -2373,7 +2361,6 @@ function InstallStep({ { label: "Mode / Style", value: presetLabel }, { label: "Max Players", value: String(data.maxPlayers) }, { label: "Ports", value: `${data.port} / ${data.queryPort} / ${data.rconPort}` }, - { label: "Save Folder", value: data.saveFolderName || getMapById(data.mapId)?.displayName || data.mapId }, { label: "Auto-Restart", value: data.autoRestart ? humanCron(data.autoRestartCron) : "Disabled" }, { label: "Server Backups", value: WIZ_TIER_ORDER.some((t) => data.serverBackupTiers[t].enabled) ? WIZ_TIER_ORDER.filter((t) => data.serverBackupTiers[t].enabled).map((t) => WIZ_TIER_LABEL[t]).join(", ") : "Disabled" }, { label: "Player Backups", value: WIZ_TIER_ORDER.some((t) => data.playerBackupTiers[t].enabled) ? WIZ_TIER_ORDER.filter((t) => data.playerBackupTiers[t].enabled).map((t) => WIZ_TIER_LABEL[t]).join(", ") : "Disabled" }, @@ -2734,12 +2721,7 @@ function InstallStep({ ? data.presetStyle : `${data.gameMode}_${data.presetStyle}`; - // Resolve the effective save folder name (fall back to map display name) - const effectiveSaveFolderName = data.saveFolderName.trim() - || getMapById(data.mapId)?.displayName - || data.mapId; baseDirRef.current = baseDir; - saveFolderNameRef.current = effectiveSaveFolderName; await createServer({ id: serverId, @@ -2755,7 +2737,6 @@ function InstallStep({ adminPassword: data.adminPassword, clusterId: data.clusterId || undefined, presetId, - saveFolderName: effectiveSaveFolderName, }); await updateServerStatus(serverId, "installing", null); await saveServerConfig(serverId, "{}", "{}", "{}"); @@ -2864,9 +2845,9 @@ function InstallStep({ await saveServerConfig(serverId, JSON.stringify(gusJson), JSON.stringify(gameIniJson), JSON.stringify(data.launchArgs)); await updateServerStatus(serverId, "stopped", null); - // Create symlink/junction so -SaveDirectoryOverride writes to the managed Saves folder - if (saveFolderNameRef.current && baseDirRef.current) { - await tauriCmd.createSaveLink(installPath, saveFolderNameRef.current, baseDirRef.current).catch((e) => { + // Create SavedArks symlink/junction pointing to managed Saves/{serverId}/SavedArks/ + if (baseDirRef.current) { + await tauriCmd.createSaveLink(installPath, serverId, baseDirRef.current).catch((e) => { console.warn("createSaveLink failed (non-fatal):", e); }); } diff --git a/src/hooks/useAllMaps.ts b/src/hooks/useAllMaps.ts new file mode 100644 index 0000000..b810514 --- /dev/null +++ b/src/hooks/useAllMaps.ts @@ -0,0 +1,36 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { ARK_MAPS, type ArkMap } from "@/data/game-data"; +import { getCustomMaps } from "@/lib/db"; + +/** + * Returns all selectable maps: built-in ARK_MAPS merged with user-defined + * custom maps from the custom_maps table. Custom maps are appended after + * the built-in mod maps section so the ordering stays stable. + */ +export function useAllMaps(): ArkMap[] { + const [allMaps, setAllMaps] = useState(ARK_MAPS); + + useEffect(() => { + getCustomMaps() + .then((rows) => { + const custom: ArkMap[] = rows.map((r) => ({ + id: `custom_${r.id}`, + displayName: r.display_name, + mapPath: r.map_path, + isOfficial: false, + dlcRequired: false, + released: true, + isMod: true, + requiredModId: r.mod_id, + })); + setAllMaps([...ARK_MAPS, ...custom]); + }) + .catch(() => { + // Custom maps unavailable — fall back to built-in list silently + }); + }, []); + + return allMaps; +} diff --git a/src/lib/db.ts b/src/lib/db.ts index cb23c83..05e1195 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -493,6 +493,15 @@ async function runMigrations(db: Database): Promise { // ── Migration 018: memory limit restart + backup broadcast message ───────── try { await db.execute("ALTER TABLE servers ADD COLUMN memory_limit_gb REAL"); } catch { /* exists */ } try { await db.execute("ALTER TABLE servers ADD COLUMN backup_broadcast_message TEXT NOT NULL DEFAULT 'Server backup in progress — lag may occur.'"); } catch { /* exists */ } + + // ── Migration 019: user-defined custom mod maps ────────────────────────── + await db.execute(`CREATE TABLE IF NOT EXISTS custom_maps ( + id TEXT PRIMARY KEY, + display_name TEXT NOT NULL, + mod_id TEXT NOT NULL, + map_path TEXT NOT NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP + )`); } // --------------------------------------------------------------------------- @@ -530,7 +539,7 @@ export interface ServerRow { update_cancel_message: string; auto_start: number; // 0 | 1 — always start on app launch installed_build_id: string | null; // populated by Rust on install/update - save_folder_name: string; // subfolder name for -SaveDirectoryOverride; empty = no override + save_folder_name: string; // legacy column — no longer used; kept for schema compatibility active_event: string | null; // ARK event id (e.g. "FearEvolved"); null = no active event memory_limit_gb: number | null; // restart server if RAM exceeds this; null = disabled backup_broadcast_message: string; // RCON broadcast sent before each scheduled backup @@ -2077,3 +2086,40 @@ export function formatServerVersion( if (entry?.game_version) return `V${entry.game_version} (${installedBuildId})`; return `Build ${installedBuildId}`; } + +// --------------------------------------------------------------------------- +// custom_maps +// --------------------------------------------------------------------------- + +export interface CustomMapRow { + id: string; + display_name: string; + mod_id: string; + map_path: string; + created_at: string; +} + +export async function getCustomMaps(): Promise { + const db = await getDb(); + return db.select( + "SELECT id, display_name, mod_id, map_path, created_at FROM custom_maps ORDER BY created_at ASC" + ); +} + +export async function insertCustomMap( + id: string, + displayName: string, + modId: string, + mapPath: string, +): Promise { + const db = await getDb(); + await db.execute( + "INSERT INTO custom_maps (id, display_name, mod_id, map_path) VALUES (?, ?, ?, ?)", + [id, displayName, modId, mapPath], + ); +} + +export async function deleteCustomMap(id: string): Promise { + const db = await getDb(); + await db.execute("DELETE FROM custom_maps WHERE id = ?", [id]); +} diff --git a/src/lib/server-utils.ts b/src/lib/server-utils.ts index d44edde..89a6aae 100644 --- a/src/lib/server-utils.ts +++ b/src/lib/server-utils.ts @@ -67,7 +67,6 @@ export async function buildStartParams(server: ServerRow): Promise invoke("delete_server", { serverId, installPath, backupDir, baseDir, saveFolderName, deleteFiles, deleteBackups, deleteLogs, deleteSaves }), + ) => invoke("delete_server", { serverId, installPath, backupDir, baseDir, deleteFiles, deleteBackups, deleteLogs, deleteSaves }), /** Return on-disk byte counts for a server's backups, logs, and save data. */ - getServerDiskUsage: (serverId: string, backupDir: string, baseDir: string, saveFolderName: string) => - invoke<{ backupBytes: number; logBytes: number; saveBytes: number }>("get_server_disk_usage", { serverId, backupDir, baseDir, saveFolderName }), + getServerDiskUsage: (serverId: string, backupDir: string, baseDir: string) => + invoke<{ backupBytes: number; logBytes: number; saveBytes: number }>("get_server_disk_usage", { serverId, backupDir, baseDir }), /** Return the total size in bytes of any directory path. Returns 0 if path doesn't exist. */ getDirSize: (path: string) => invoke("get_dir_size", { path }), @@ -534,8 +531,8 @@ export const tauriCmd = { /** Server backup: SaveWorld → cleanup ARK files → 7z SavedArks+SaveGames. */ createServerBackup: ( serverId: string, serverName: string, installPath: string, mapPath: string, - mapId: string, backupDir: string, triggeredBy: string, tier = "", saveFolderName?: string, - ) => invoke("create_server_backup", { serverId, serverName, installPath, mapPath, mapId, backupDir, triggeredBy, tier, saveFolderName: saveFolderName ?? null }), + mapId: string, backupDir: string, triggeredBy: string, tier = "", baseDir = "", + ) => invoke("create_server_backup", { serverId, serverName, installPath, mapPath, mapId, backupDir, triggeredBy, tier, baseDir }), /** Player backup: 7z a single .arkprofile file. */ createPlayerBackup: ( @@ -546,21 +543,23 @@ export const tauriCmd = { /** Back up every .arkprofile in SavedArks/{mapPath}/ in one call. */ backupAllPlayers: ( serverId: string, serverName: string, installPath: string, mapPath: string, - mapId: string, backupDir: string, triggeredBy: string, saveFolderName?: string, - ) => invoke("backup_all_players", { serverId, serverName, installPath, mapPath, mapId, backupDir, triggeredBy, saveFolderName: saveFolderName ?? null }), + mapId: string, backupDir: string, triggeredBy: string, + ) => invoke("backup_all_players", { serverId, serverName, installPath, mapPath, mapId, backupDir, triggeredBy }), /** INI backup: copy loose INI files into a rotating timestamped folder. */ createIniBackup: (serverId: string, installPath: string, backupDir: string) => invoke("create_ini_backup", { serverId, installPath, backupDir }), - /** Wipe server save files. tier: "map" | "players" | "full". Server must be stopped. */ - wipeServerSaves: (installPath: string, saveFolderName: string, tier: "map" | "players" | "full") => - invoke("wipe_server_saves", { installPath, saveFolderName, tier }), - /** Create a symlink (Linux) or NTFS junction point (Windows) from - * {installPath}/ShooterGame/Saved/SavedArks/{saveFolderName} - * → {baseDir}/Saves/{saveFolderName}/ - * so -SaveDirectoryOverride writes saves to the managed Saves folder. */ - createSaveLink: (installPath: string, saveFolderName: string, baseDir: string) => - invoke("create_save_link", { installPath, saveFolderName, baseDir }), + /** Wipe server save files. tier: "map" | "players" | "full". Server must be stopped. + * mapPath is the map folder name (e.g. TheIsland_WP). */ + wipeServerSaves: (installPath: string, mapPath: string, tier: "map" | "players" | "full") => + invoke("wipe_server_saves", { installPath, mapPath, tier }), + /** Create a symlink (Linux) or NTFS junction (Windows) so that + * {installPath}/ShooterGame/Saved/SavedArks → {baseDir}/Saves/{serverId}/SavedArks */ + createSaveLink: (installPath: string, serverId: string, baseDir: string) => + invoke("create_save_link", { installPath, serverId, baseDir }), + /** Copy the current map's save subfolder from one server to another. Both servers must be stopped. */ + importServerSaves: (sourceServerId: string, targetServerId: string, baseDir: string, mapPath: string) => + invoke("import_server_saves", { sourceServerId, targetServerId, baseDir, mapPath }), /** Full backup: 7z the entire install_path directory. */ createFullBackup: ( From d0fae15bbe6b39564ca294b9edc6a12363ccb130 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 23 Jun 2026 04:57:50 -0500 Subject: [PATCH 07/28] feat: implement per-map SaveGames management with symlinks and map selector - Add create_mods_saves_link command to create platform-specific links for mod saves - Refactor backup compression to support alternative root paths for multi-source backups - Store mod SaveGames in backups under Mods/{map_path}/ structure - Rewrite restore_server_backup to handle canonical locations and recreate symlinks - Add map selector UI to Config tab for changing maps without reinstalling - Update server's map_id in database when map changes - Call create_mods_saves_link on server install, update, wizard completion, and map change --- src-tauri/src/commands/backup.rs | 257 ++++++++++++++++-- src/app/mod-maps/page.tsx | 21 -- src/components/server/ServerCard.tsx | 8 + src/components/server/tabs/BackupsTab.tsx | 2 +- src/components/server/tabs/ConfigTab.tsx | 60 +++- src/components/server/tabs/OverviewTab.tsx | 7 + .../wizard/ServerCreationWizard.tsx | 6 + src/lib/db.ts | 8 + src/lib/tauri-commands.ts | 10 +- 9 files changed, 336 insertions(+), 43 deletions(-) diff --git a/src-tauri/src/commands/backup.rs b/src-tauri/src/commands/backup.rs index d0ed68e..4be05ba 100644 --- a/src-tauri/src/commands/backup.rs +++ b/src-tauri/src/commands/backup.rs @@ -235,6 +235,7 @@ pub async fn rcon_broadcast(pool: &RconPool, server_id: &str, message: &str) { /// Write `files` into a 7z archive at `dest_path`. /// `root` is stripped from each file path to produce the archive entry name. +/// `alt_root` is an alternative root tried if primary root fails (used for mixed-source backups). /// Emits progress events keyed on `server_id`. /// Returns Ok(skipped_count) on success. A non-zero skipped_count means some /// files disappeared between enumeration and compression — the caller should @@ -247,22 +248,65 @@ fn compress_to_7z( dest_path: &Path, label: &str, ) -> Result { - let total = files.len().max(1) as f32; + compress_to_7z_with_alt_root(app, server_id, files, root, None, dest_path, label) +} + +fn compress_to_7z_with_alt_root( + app: &AppHandle, + server_id: &str, + files: &[PathBuf], + root: &Path, + alt_root: Option<&Path>, + dest_path: &Path, + label: &str, +) -> Result { + compress_to_7z_with_entries( + app, + server_id, + &files.iter().map(|f| (f.clone(), None)).collect::>(), + root, + alt_root, + dest_path, + label, + ) +} + +/// Compress files with explicit entry names for archive structure. +/// `entries` is a vec of (file_path, optional_custom_entry_name). +/// If custom entry name is None, it's calculated by stripping the root paths. +fn compress_to_7z_with_entries( + app: &AppHandle, + server_id: &str, + entries: &[(PathBuf, Option)], + root: &Path, + alt_root: Option<&Path>, + dest_path: &Path, + label: &str, +) -> Result { + let total = entries.len().max(1) as f32; let mut writer = SevenZWriter::create(dest_path).map_err(|e| e.to_string())?; let mut skipped = 0usize; - for (idx, file_path) in files.iter().enumerate() { - let rel = file_path - .strip_prefix(root) - .map_err(|e| e.to_string())?; - let entry_name = rel.to_string_lossy().replace('\\', "/"); + for (idx, (file_path, custom_entry)) in entries.iter().enumerate() { + let entry_name = if let Some(custom) = custom_entry { + custom.clone() + } else { + let rel = file_path + .strip_prefix(root) + .or_else(|_| { + alt_root.ok_or(()).and_then(|alt| file_path.strip_prefix(alt).map_err(|_| ())) + }) + .map_err(|_| format!( + "File {} doesn't match root {} or alt root {:?}", + file_path.display(), root.display(), alt_root.map(|r| r.display()) + ))?; + rel.to_string_lossy().replace('\\', "/") + }; let pct = (idx as f32 / total * 99.0).min(99.0); emit_progress(app, server_id, pct, &entry_name, label); - // Skip files that disappeared between enumeration and compression (ASA - // uses delete+rename atomic writes, which creates a brief window where - // the file doesn't exist). Count skips so callers can retry. + // Skip files that disappeared between enumeration and compression let file = match File::open(file_path) { Ok(f) => f, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { @@ -273,7 +317,7 @@ fn compress_to_7z( }; let metadata = file.metadata().map_err(|e| e.to_string())?; let mut entry = SevenZArchiveEntry::new(); - entry.name = entry_name.clone(); + entry.name = entry_name; entry.size = metadata.len(); entry.is_directory = false; writer @@ -434,7 +478,21 @@ async fn create_server_backup_impl( }; let save_games = PathBuf::from(&install_path) .join("ShooterGame").join("Saved").join("SaveGames"); - let saved_root = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); + + // When base_dir is used, files come from two roots: canonical saves and install_path SaveGames. + // Calculate the primary root based on whether base_dir is used. + let saved_root = if !base_dir.is_empty() { + PathBuf::from(base_dir).join("Saves").join(server_id) + } else { + PathBuf::from(&install_path).join("ShooterGame").join("Saved") + }; + + // The alternate root is always install_path/ShooterGame/Saved for SaveGames compatibility. + let alt_root = if !base_dir.is_empty() { + Some(PathBuf::from(&install_path).join("ShooterGame").join("Saved")) + } else { + None + }; let out_dir = PathBuf::from(&backup_dir).join(&server_id).join("server"); fs::create_dir_all(&out_dir).map_err(|e| e.to_string())?; @@ -466,17 +524,35 @@ async fn create_server_backup_impl( return Err("No save files found to back up".to_string()); } + // Build entries with custom names for SaveGames files to include map path + let mut entries: Vec<(PathBuf, Option)> = Vec::new(); + for file_path in all_files { + let custom_name = if file_path.starts_with(&save_games) { + // For SaveGames files, prepend Mods/{map_path}/SaveGames/ + let rel_path = file_path.strip_prefix(&save_games) + .ok() + .and_then(|p| p.to_str()) + .unwrap_or(""); + let rel_clean = rel_path.trim_start_matches(|c| c == '/' || c == '\\'); + Some(format!("Mods/{}/SaveGames/{}", map_path, rel_clean.replace('\\', "/"))) + } else { + // For SavedArks files, let compress_to_7z_with_entries handle it + None + }; + entries.push((file_path, custom_name)); + } + let (ts_file, ts_iso) = now_timestamp(); let archive_name = format!("{safe_name}-{ts_file}{suffix}.7z"); let archive_path = out_dir.join(&archive_name); let app_c = app.clone(); let sid = server_id.to_string(); - let files = all_files; let root = saved_root.clone(); + let alt = alt_root.clone(); let dest = archive_path.clone(); let compress_result = tokio::task::spawn_blocking(move || { - compress_to_7z(&app_c, &sid, &files, &root, &dest, "Creating server backup…") + compress_to_7z_with_entries(&app_c, &sid, &entries, &root, alt.as_deref(), &dest, "Creating server backup…") }) .await .map_err(|e| format!("Backup task panicked: {e}"))?; @@ -842,6 +918,76 @@ pub async fn create_save_link( Ok(()) } +/// Create the mods saves directory link for a server (per-map SaveGames). +/// +/// Creates: +/// `{base_dir}/Saves/{server_id}/Mods/{map_path}/SaveGames/` ← the real mod save location +/// `{install_path}/ShooterGame/Saved/SaveGames` → symlink/junction ← points to current map's mod data +/// +/// On Linux: a symlink. On Windows: an NTFS junction (no admin rights required). +/// +/// This is called when the server starts or when the map changes to ensure the +/// SaveGames symlink points to the current map's mod save data. +#[tauri::command] +pub async fn create_mods_saves_link( + install_path: String, + server_id: String, + base_dir: String, + map_path: String, +) -> Result<(), String> { + if server_id.is_empty() || map_path.is_empty() { + return Err("server_id and map_path must not be empty".to_string()); + } + + // The canonical mod save storage directory for this map (real data lives here) + let mods_target = PathBuf::from(&base_dir) + .join("Saves") + .join(&server_id) + .join("Mods") + .join(&map_path) + .join("SaveGames"); + fs::create_dir_all(&mods_target).map_err(|e| format!("Failed to create mods target dir: {e}"))?; + + // The path inside the server install where SaveGames should be (will become the link) + let saved_dir = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); + fs::create_dir_all(&saved_dir).map_err(|e| format!("Failed to create Saved dir: {e}"))?; + let link_path = saved_dir.join("SaveGames"); + + // If something already exists at link_path, check it and remove if it points to wrong target + if link_path.exists() || link_path.is_symlink() { + if let Ok(existing) = std::fs::read_link(&link_path) { + if existing == mods_target { + return Ok(()); + } + } + // Wrong target, broken link, or plain directory — remove so we can recreate. + if link_path.is_symlink() { + #[cfg(target_os = "windows")] + { let _ = fs::remove_dir(&link_path); } + #[cfg(not(target_os = "windows"))] + { let _ = fs::remove_file(&link_path); } + } else if link_path.is_dir() { + let _ = fs::remove_dir_all(&link_path); + } else { + let _ = fs::remove_file(&link_path); + } + } + + #[cfg(target_os = "linux")] + { + std::os::unix::fs::symlink(&mods_target, &link_path) + .map_err(|e| format!("Failed to create symlink: {e}"))?; + } + + #[cfg(target_os = "windows")] + { + junction::create(&mods_target, &link_path) + .map_err(|e| format!("Failed to create junction point: {e}"))?; + } + + Ok(()) +} + /// Wipe server save files at one of three tiers: /// /// - `"map"` — delete world `.ark` files only (clears map state, preserves characters). @@ -1073,16 +1219,95 @@ pub async fn create_full_backup( // Restore // --------------------------------------------------------------------------- -/// Restore a Server backup: extract 7z over SavedArks/{mapPath} and SaveGames. +/// Restore a Server backup: extract 7z to correct canonical locations and recreate symlinks. +/// Archive structure: +/// SavedArks/{map_path}/... → restored to {install_path}/ShooterGame/Saved/SavedArks/{map_path}/ +/// Mods/{map_path}/SaveGames/... → restored to {base_dir}/Saves/{server_id}/Mods/{map_path}/SaveGames/ #[tauri::command] pub async fn restore_server_backup( app: AppHandle, server_id: String, backup_file_path: String, install_path: String, + base_dir: String, + map_path: String, ) -> Result<(), String> { - let saved_root = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); - extract_7z_with_progress(&app, &server_id, &backup_file_path, &saved_root, "Restoring server backup…").await + use std::fs; + + // Validate inputs + if server_id.is_empty() || map_path.is_empty() { + return Err("server_id and map_path must not be empty".to_string()); + } + + // Step 1: Clear existing save locations + emit_progress(&app, &server_id, 10.0, "", "Clearing existing saves…"); + let saved_arks_path = PathBuf::from(&base_dir).join("Saves").join(&server_id).join("SavedArks").join(&map_path); + if saved_arks_path.exists() { + fs::remove_dir_all(&saved_arks_path).map_err(|e| format!("Failed to clear SavedArks: {e}"))?; + } + + let mods_saves_path = PathBuf::from(&base_dir).join("Saves").join(&server_id).join("Mods").join(&map_path).join("SaveGames"); + if mods_saves_path.exists() { + fs::remove_dir_all(&mods_saves_path).map_err(|e| format!("Failed to clear SaveGames: {e}"))?; + } + + // Step 2: Extract backup to temp directory + emit_progress(&app, &server_id, 20.0, "", "Extracting backup…"); + let temp_dir = std::env::temp_dir().join(format!("lokiasam-restore-{}", server_id)); + if temp_dir.exists() { + fs::remove_dir_all(&temp_dir).ok(); + } + fs::create_dir_all(&temp_dir).map_err(|e| e.to_string())?; + + sevenz_rust::decompress_file(&backup_file_path, &temp_dir) + .map_err(|e| e.to_string())?; + + // Step 3: Move extracted files to correct locations + emit_progress(&app, &server_id, 50.0, "", "Moving files to correct locations…"); + + // Process SavedArks files + let temp_saved_arks = temp_dir.join("SavedArks").join(&map_path); + if temp_saved_arks.exists() { + fs::create_dir_all(&saved_arks_path).map_err(|e| e.to_string())?; + copy_dir_recursive(&temp_saved_arks, &saved_arks_path).map_err(|e| e.to_string())?; + } + + // Process Mods/SaveGames files + let temp_mods = temp_dir.join("Mods").join(&map_path).join("SaveGames"); + if temp_mods.exists() { + fs::create_dir_all(&mods_saves_path).map_err(|e| e.to_string())?; + copy_dir_recursive(&temp_mods, &mods_saves_path).map_err(|e| e.to_string())?; + } + + // Step 4: Recreate symlinks + emit_progress(&app, &server_id, 80.0, "", "Recreating symlinks…"); + create_save_link(install_path.clone(), server_id.clone(), base_dir.clone()).await?; + create_mods_saves_link(install_path, server_id.clone(), base_dir, map_path).await?; + + // Step 5: Cleanup temp directory + emit_progress(&app, &server_id, 95.0, "", "Cleaning up…"); + let _ = fs::remove_dir_all(&temp_dir); + + emit_progress(&app, &server_id, 100.0, "", "Restore complete"); + Ok(()) +} + +fn copy_dir_recursive(src: &Path, dst: &Path) -> std::io::Result<()> { + use std::fs; + fs::create_dir_all(dst)?; + for entry in fs::read_dir(src)? { + let entry = entry?; + let path = entry.path(); + let file_name = entry.file_name(); + let dest_path = dst.join(&file_name); + + if path.is_dir() { + copy_dir_recursive(&path, &dest_path)?; + } else { + fs::copy(&path, &dest_path)?; + } + } + Ok(()) } /// Restore a Player backup: extract 7z into SavedArks/{mapPath}. diff --git a/src/app/mod-maps/page.tsx b/src/app/mod-maps/page.tsx index a64ecf2..8559ebd 100644 --- a/src/app/mod-maps/page.tsx +++ b/src/app/mod-maps/page.tsx @@ -135,27 +135,6 @@ export default function ModMapsPage() {
)} - {/* Official maps reference */} -
-

- Official Maps (read-only reference) -

-
- {ARK_MAPS.filter((m) => m.isOfficial && m.released).map((m, i, arr) => ( -
- {m.displayName} - {m.mapPath} -
- ))} -
-
- {/* Built-in mod maps reference */} {ARK_MAPS.filter((m) => m.isMod && m.released).length > 0 && (
diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index 849a4d4..7172bc5 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -396,9 +396,17 @@ export function ServerCard({ server }: Props) { try { await tauriCmd.updateServer(server.id, server.install_path, cacheDir, steamcmdPath); + + // Import ARK_MAPS for map path lookup + const { ARK_MAPS } = await import("@/data/game-data"); + const mapPath = ARK_MAPS.find((m) => m.id === server.map_id)?.mapPath ?? "TheIsland_WP"; + await tauriCmd.createSaveLink(server.install_path, server.id, baseDir).catch((e) => { console.warn("createSaveLink failed after reinstall:", e); }); + await tauriCmd.createModsSavesLink(server.install_path, server.id, baseDir, mapPath).catch((e) => { + console.warn("createModsSavesLink failed after update:", e); + }); await updateServerStatus(server.id, "stopped", null); dispatchNotification({ eventType: NOTIFICATION_EVENTS.SERVER_INSTALL_COMPLETE, diff --git a/src/components/server/tabs/BackupsTab.tsx b/src/components/server/tabs/BackupsTab.tsx index 4402cf3..41cb65a 100644 --- a/src/components/server/tabs/BackupsTab.tsx +++ b/src/components/server/tabs/BackupsTab.tsx @@ -872,7 +872,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { await new Promise((r) => setTimeout(r, 2000)); } if (target.backup_type === "server") { - await tauriCmd.restoreServerBackup(server.id, target.file_path, server.install_path); + await tauriCmd.restoreServerBackup(server.id, target.file_path, server.install_path, baseDir, mapPath); } else if (target.backup_type === "player") { await tauriCmd.restorePlayerBackup(server.id, target.file_path, server.install_path, mapPath); } else if (target.backup_type === "full") { diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index 2d4d770..17fc3e0 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -33,10 +33,10 @@ import { import { tauriCmd, type ServerConfigJson } from "@/lib/tauri-commands"; import { INI_FIELD_GROUPS, LAUNCH_PARAMETERS, GAME_MODES, PRESET_STYLES, - buildPresetConfig, ARK_EVENTS, + buildPresetConfig, ARK_EVENTS, ARK_MAPS, type IniFieldDef, type LaunchParameter, } from "@/data/game-data"; -import { getServerConfig, saveServerConfig, updateServerShutdownSettings, updateServerRestartSettings, updateServerUpdateSettings, getAppSetting, setServerActiveEvent, getServers, copyServerConfig, updateServerMemoryLimit, type ServerRow } from "@/lib/db"; +import { getServerConfig, saveServerConfig, updateServerShutdownSettings, updateServerRestartSettings, updateServerUpdateSettings, getAppSetting, setServerActiveEvent, getServers, copyServerConfig, updateServerMemoryLimit, updateServerMap, type ServerRow } from "@/lib/db"; import { toast } from "sonner"; import { NumberField } from "@/components/shared/NumberField"; import { open as openFilePicker } from "@tauri-apps/plugin-dialog"; @@ -1774,6 +1774,32 @@ export function ConfigTab({ server }: Props) { setActiveTab("raw"); }; + const handleMapChange = async (newMapId: string) => { + if (server.status !== "stopped") { + toast.error("Server must be stopped to change maps"); + return; + } + try { + const baseDir = await getAppSetting("base_dir"); + if (!baseDir) { + toast.error("Base directory not configured"); + return; + } + const newMapData = ARK_MAPS.find((m) => m.id === newMapId); + if (!newMapData) { + toast.error("Map not found"); + return; + } + // Update the SaveGames symlink for the new map + await tauriCmd.createModsSavesLink(server.install_path, server.id, baseDir, newMapData.mapPath); + // Update the database + await updateServerMap(server.id, newMapId); + toast.success(`Map changed to ${newMapData.displayName}`); + } catch (e) { + toast.error(`Failed to change map: ${e}`); + } + }; + const switchFromRaw = () => { const gus = rawTextToSections(rawGus); const game = rawTextToSections(rawGame); @@ -1929,6 +1955,36 @@ export function ConfigTab({ server }: Props) { {/* ── Structured view — all INI field groups ────────────────────────── */} {activeTab === "structured" && config && (
+ {/* Map Selector */} +
+
+
+

Server Map

+

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

+
+ {server.status !== "stopped" && ( +
+ Stop to change +
+ )} +
+ +
+ + {/* INI Field Groups */} {INI_FIELD_GROUPS.map((g, idx) => ( m.id === server.map_id)?.mapPath ?? "TheIsland_WP"; + tauriCmd.updateServer(server.id, server.install_path, cacheDir, steamcmdPath) .then(() => tauriCmd.createSaveLink(server.install_path, server.id, baseDir).catch((e) => { console.warn("createSaveLink failed after reinstall:", e); })) + .then(() => tauriCmd.createModsSavesLink(server.install_path, server.id, baseDir, mapPath).catch((e) => { + console.warn("createModsSavesLink failed after reinstall:", e); + })) .then(() => updateServerStatus(server.id, "stopped", null)) .catch(() => updateServerStatus(server.id, "install_failed", null)) .finally(() => queryClient.invalidateQueries({ queryKey: ["servers"] })); diff --git a/src/components/wizard/ServerCreationWizard.tsx b/src/components/wizard/ServerCreationWizard.tsx index fdbab10..9824b4d 100644 --- a/src/components/wizard/ServerCreationWizard.tsx +++ b/src/components/wizard/ServerCreationWizard.tsx @@ -2847,9 +2847,15 @@ function InstallStep({ // Create SavedArks symlink/junction pointing to managed Saves/{serverId}/SavedArks/ if (baseDirRef.current) { + const { ARK_MAPS } = await import("@/data/game-data"); + const mapPath = ARK_MAPS.find((m) => m.id === data.mapId)?.mapPath ?? "TheIsland_WP"; + await tauriCmd.createSaveLink(installPath, serverId, baseDirRef.current).catch((e) => { console.warn("createSaveLink failed (non-fatal):", e); }); + await tauriCmd.createModsSavesLink(installPath, serverId, baseDirRef.current, mapPath).catch((e) => { + console.warn("createModsSavesLink failed (non-fatal):", e); + }); } queryClientRef.current.invalidateQueries({ queryKey: ["servers"] }); diff --git a/src/lib/db.ts b/src/lib/db.ts index 05e1195..38783da 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -893,6 +893,14 @@ export async function updateBackupBroadcastMessage(id: string, message: string): ); } +export async function updateServerMap(id: string, mapId: string): Promise { + const db = await getDb(); + await db.execute( + "UPDATE servers SET map_id = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", + [mapId, id] + ); +} + /** Set the update_available flag for a single server. */ export async function setServerUpdateAvailable( id: string, diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index f94e456..ce46005 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -557,6 +557,10 @@ export const tauriCmd = { * {installPath}/ShooterGame/Saved/SavedArks → {baseDir}/Saves/{serverId}/SavedArks */ createSaveLink: (installPath: string, serverId: string, baseDir: string) => invoke("create_save_link", { installPath, serverId, baseDir }), + /** Create a symlink (Linux) or NTFS junction (Windows) for mod saves so that + * {installPath}/ShooterGame/Saved/SaveGames → {baseDir}/Saves/{serverId}/Mods/{mapPath}/SaveGames */ + createModsSavesLink: (installPath: string, serverId: string, baseDir: string, mapPath: string) => + invoke("create_mods_saves_link", { installPath, serverId, baseDir, mapPath }), /** Copy the current map's save subfolder from one server to another. Both servers must be stopped. */ importServerSaves: (sourceServerId: string, targetServerId: string, baseDir: string, mapPath: string) => invoke("import_server_saves", { sourceServerId, targetServerId, baseDir, mapPath }), @@ -571,9 +575,9 @@ export const tauriCmd = { 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 server backup: extract 7z to canonical locations and recreate symlinks. */ + restoreServerBackup: (serverId: string, backupFilePath: string, installPath: string, baseDir: string, mapPath: string) => + invoke("restore_server_backup", { serverId, backupFilePath, installPath, baseDir, mapPath }), /** Restore a player backup: extract 7z into SavedArks/{mapPath}. */ restorePlayerBackup: (serverId: string, backupFilePath: string, installPath: string, mapPath: string) => From a391840cc454d9f74d9731be8b73187b1f5d6f64 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 23 Jun 2026 11:46:38 -0500 Subject: [PATCH 08/28] feat: improve import wizard with path remapping, cert/firewall steps, and UX fixes Add remap_import_paths command to rewrite all DB paths (app_settings, servers, backups) when importing from a different base directory. Extend ImportVerifyPanel with Amazon mod cert installation and firewall port checking/opening. Add fallback path detection for SteamCMD and Proton-GE when stored paths don't match the import location. Fix SteamCMD/Proton tab switching to only lock during active download, preserve manually-added Proton entries across rescans, add debounced validation to BackupDirStep, and self-heal both save symlinks on server start --- src-tauri/src/commands/system.rs | 63 +++ src-tauri/src/lib.rs | 2 + src/components/server/ServerCard.tsx | 12 + src/components/wizard/SetupWizard.tsx | 715 +++++++++++++++++++++++--- src/lib/tauri-commands.ts | 2 + src/store/useSetupStore.ts | 2 +- 6 files changed, 726 insertions(+), 70 deletions(-) diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs index 7058029..576bc22 100644 --- a/src-tauri/src/commands/system.rs +++ b/src-tauri/src/commands/system.rs @@ -981,3 +981,66 @@ pub fn uninstall_appimage_integration() -> Result<(), String> { Ok(()) } + +/// Remap all paths in the database from old_base_dir to new_base_dir during import. +/// Updates: app_settings (base_dir, backup_dir, steamcmd_path, proton_path, proton_prefix_path), +/// servers (install_path), and backups (file_path). +#[tauri::command] +pub async fn remap_import_paths( + db_path: String, + old_base_dir: String, + new_base_dir: String, +) -> Result<(), String> { + use rusqlite::Connection; + + // Normalize paths (remove trailing slashes) + let old_base = old_base_dir.trim_end_matches('/').trim_end_matches('\\'); + let new_base = new_base_dir.trim_end_matches('/').trim_end_matches('\\'); + + let conn = Connection::open(&db_path) + .map_err(|e| format!("Failed to open database '{}': {}", db_path, e))?; + + // Update app_settings paths + let settings_to_update = vec![ + "base_dir", + "backup_dir", + "steamcmd_path", + "proton_path", + "proton_prefix_path", + ]; + + for setting_key in settings_to_update { + let old_value: Option = conn.query_row( + "SELECT value FROM app_settings WHERE key = ?1", + [setting_key], + |row| row.get(0), + ).ok(); + + if let Some(val) = old_value { + if val.contains(old_base) { + let new_value = val.replace(old_base, new_base); + conn.execute( + "UPDATE app_settings SET value = ?1, updated_at = CURRENT_TIMESTAMP WHERE key = ?2", + rusqlite::params![new_value, setting_key], + ) + .map_err(|e| format!("Failed to update app_settings '{}': {}", setting_key, e))?; + } + } + } + + // Update servers.install_path using simple REPLACE + conn.execute( + "UPDATE servers SET install_path = REPLACE(install_path, ?1, ?2)", + rusqlite::params![old_base, new_base], + ) + .map_err(|e| format!("Failed to update server install_path: {}", e))?; + + // Update backups.file_path using simple REPLACE + conn.execute( + "UPDATE backups SET file_path = REPLACE(file_path, ?1, ?2)", + rusqlite::params![old_base, new_base], + ) + .map_err(|e| format!("Failed to update backup file_path: {}", e))?; + + Ok(()) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c27b7e8..52ca9f8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -549,6 +549,7 @@ pub fn run() { commands::backup::backup_all_players, commands::backup::create_ini_backup, commands::backup::create_save_link, + commands::backup::create_mods_saves_link, commands::backup::wipe_server_saves, commands::backup::import_server_saves, commands::backup::create_full_backup, @@ -592,6 +593,7 @@ pub fn run() { commands::system::read_bootstrap, commands::system::write_bootstrap, commands::system::open_folder, + commands::system::remap_import_paths, // Proton-GE (Linux) commands::proton::scan_for_proton, commands::proton::validate_proton_path, diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index 7172bc5..f0a514f 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -221,6 +221,18 @@ export function ServerCard({ server }: Props) { await updateServerStatus(server.id, "starting", null); queryClient.invalidateQueries({ queryKey: ["servers"] }); + // Ensure both save symlinks/junctions are in place before launching + const baseDir = await getAppSetting("base_dir").catch(() => null); + if (baseDir) { + const mapPath = ARK_MAPS.find((m) => m.id === server.map_id)?.mapPath ?? "TheIsland_WP"; + await tauriCmd.createSaveLink(server.install_path, server.id, baseDir).catch((e) => { + console.warn("createSaveLink failed on start:", e); + }); + await tauriCmd.createModsSavesLink(server.install_path, server.id, baseDir, mapPath).catch((e) => { + console.warn("createModsSavesLink failed on start:", e); + }); + } + await warnIfFirewallMissing(server); const params = await buildStartParams(server); const pid = await tauriCmd.startServer(params); diff --git a/src/components/wizard/SetupWizard.tsx b/src/components/wizard/SetupWizard.tsx index 2c565fc..88ad778 100644 --- a/src/components/wizard/SetupWizard.tsx +++ b/src/components/wizard/SetupWizard.tsx @@ -25,7 +25,7 @@ import { FolderOpen, HardDrive, Terminal, Bell, CheckCircle2, ArrowRight, ArrowLeft, Loader2, AlertCircle, HardDrive as DiskIcon, Cpu, RefreshCw, Download, MonitorDown, ToggleLeft, ToggleRight, Layers, Send, StopCircle, Palette, - X, BookOpen, ShieldCheck, Trash2, TriangleAlert, Eye, EyeOff, + X, BookOpen, ShieldCheck, Trash2, TriangleAlert, Eye, EyeOff, Shield, } from "lucide-react"; import { toast } from "sonner"; import { LokiIcon } from "@/components/shared/LokiIcon"; @@ -38,7 +38,8 @@ import { import { CommandOutputPanel } from "@/components/shared/CommandOutputPanel"; import { useSetupStore } from "@/store/useSetupStore"; import { useAppStore } from "@/store/useAppStore"; -import { tauriCmd, type DirCheckResult, type ProtonEntry } from "@/lib/tauri-commands"; +import { tauriCmd, type DirCheckResult, type ProtonEntry, type FirewallStatus, type PortDef } from "@/lib/tauri-commands"; +import { getServerFirewallPorts } from "@/lib/firewall-utils"; import { applyTheme, ACCENT_OPTIONS, THEME_PRESETS, type ThemeAccent, type ThemePreset } from "@/lib/theme"; import { setAppSetting, initDb, saveNotificationConfig, saveGlobalChannelEvents } from "@/lib/db"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; @@ -468,15 +469,41 @@ function ImportVerifyPanel({ info, importDir, }: { - info: { servers: number; steamcmd: string; proton?: string; steamcmdMissing?: boolean; protonMissing?: boolean }; + info: { + servers: number; + steamcmd: string; + proton?: string; + protonPrefix?: string; + steamcmdMissing?: boolean; + protonMissing?: boolean; + allServersPorts?: Array<{ + serverId: string; + serverName: string; + gamePort: number; + queryPort: number; + rconPort: number; + }>; + }; importDir: string; }) { - const { setSteamcmdPath, setSteamcmdValidated, setProtonPath, setProtonValidated } = useSetupStore(); + const { setSteamcmdPath, setSteamcmdValidated, setProtonPath, setProtonValidated, protonPath } = useSetupStore(); const [installingSteamcmd, setInstallingSteamcmd] = useState(false); const [steamcmdDone, setSteamcmdDone] = useState(false); const [installingProton, setInstallingProton] = useState(false); const [protonDone, setProtonDone] = useState(false); + // Mod Certs + const [certPhase, setCertPhase] = useState<"idle" | "downloading" | "installing" | "done" | "error">("idle"); + const [certError, setCertError] = useState(""); + const [certSkipped, setCertSkipped] = useState(false); + + // Firewall + const [fwPhase, setFwPhase] = useState<"idle" | "checking" | "ready" | "opening" | "done" | "error">("idle"); + const [fwStatus, setFwStatus] = useState(null); + const [fwError, setFwError] = useState(""); + const [fwSkipped, setFwSkipped] = useState(false); + const [showFwDialog, setShowFwDialog] = useState(false); + const handleInstallSteamcmd = async () => { const sep = importDir.includes("\\") ? "\\" : "/"; const targetDir = importDir.replace(/[/\\]$/, "") + sep + "lokiasam" + sep + "steamcmd"; @@ -528,6 +555,146 @@ function ImportVerifyPanel({ } catch {/* */} }; + const handleInstallCerts = async () => { + setCertError(""); + try { + const tmp = await tempDir(); + setCertPhase("downloading"); + const certPath = await tauriCmd.downloadAmazonRootCa(tmp); + + setCertPhase("installing"); + if (IS_LINUX && !protonPath && !info.proton) { + throw new Error("Proton-GE path not found. Please ensure Proton-GE is validated first."); + } + // Use protonPath from setup store if user just selected proton, otherwise use info.proton + const resolvedProtonPath = protonPath || info.proton; + const proton = IS_LINUX && resolvedProtonPath ? resolvedProtonPath : undefined; + const prefix = IS_LINUX && info.protonPrefix ? info.protonPrefix : undefined; + await tauriCmd.installAmazonRootCa(certPath, proton, prefix); + setCertPhase("done"); + } catch (e) { + if (!String(e).includes("Aborted")) { + setCertError(String(e)); + setCertPhase("error"); + } + } + }; + + const handleSkipCerts = () => { + setCertSkipped(true); + }; + + const handleCheckFirewall = async () => { + setFwError(""); + setFwPhase("checking"); + try { + if (!info.allServersPorts || info.allServersPorts.length === 0) { + setFwStatus({ firewallType: "none", active: false, ports: [] }); + setFwPhase("done"); + return; + } + + const allPorts: PortDef[] = []; + const seen = new Set(); + for (const srv of info.allServersPorts) { + for (const p of [ + { port: srv.gamePort, protocol: "udp" as const }, + { port: srv.queryPort, protocol: "udp" as const }, + { port: srv.rconPort, protocol: "tcp" as const }, + ]) { + const key = `${p.port}/${p.protocol}`; + if (!seen.has(key)) { + seen.add(key); + allPorts.push(p); + } + } + } + + if (allPorts.length === 0) { + setFwStatus({ firewallType: "none", active: false, ports: [] }); + setFwPhase("done"); + return; + } + + const result = await tauriCmd.checkFirewallPorts(allPorts); + setFwStatus(result); + const allCovered = !result.active || result.ports.every((p) => p.covered); + setFwPhase(allCovered ? "done" : "ready"); + } catch (e) { + setFwError(String(e)); + setFwPhase("error"); + } + }; + + const handleOpenFirewallPorts = async () => { + if (!fwStatus) return; + setFwPhase("opening"); + try { + const allPorts = fwStatus.ports.map((p) => ({ + port: p.port, + protocol: p.protocol as "tcp" | "udp", + })); + const proton = IS_LINUX && protonDone ? protonPath : undefined; + await tauriCmd.addFirewallRules(allPorts, proton); + + const updated = await tauriCmd.checkFirewallPorts(allPorts); + setFwStatus(updated); + setFwPhase("done"); + setShowFwDialog(false); + } catch (e) { + setFwError(String(e)); + setFwPhase("error"); + } + }; + + const handleSkipFirewall = () => { + setFwSkipped(true); + }; + + // Auto-check firewall when servers data loads (doesn't require Proton-GE for checking) + useEffect(() => { + if ( + fwPhase === "idle" && + info.allServersPorts && + info.allServersPorts.length > 0 + ) { + handleCheckFirewall(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [info.allServersPorts]); + + // Auto-validate found tools + useEffect(() => { + if (info && !info.steamcmdMissing && !steamcmdDone) { + setSteamcmdDone(true); + } + if (info && !IS_LINUX && !info.steamcmdMissing && !protonDone) { + setProtonDone(true); + } + if (info && IS_LINUX && !info.protonMissing && !protonDone) { + setProtonDone(true); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [info?.steamcmdMissing, info?.protonMissing]); + + // Check if cert is already installed + useEffect(() => { + (async () => { + try { + if (!IS_LINUX || !info.proton || !info.protonPrefix) return; + const proton = info.proton; + const prefix = info.protonPrefix; + const installed = await tauriCmd.checkAmazonRootCaInstalled(proton, prefix); + if (installed) { + setCertPhase("done"); + } + } catch { + // If check fails, leave as idle so user can manually install + } + })(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [protonDone, info?.proton, info?.protonPrefix]); + const allGood = !info.steamcmdMissing || steamcmdDone; const protonAllGood = !info.protonMissing || protonDone; @@ -611,9 +778,262 @@ function ImportVerifyPanel({

) : null} + {/* Mod Certs row */} +
+
+

Amazon Mod API Cert

+ {certPhase === "done" && } + {(certPhase === "downloading" || certPhase === "installing") && ( + + )} +
+ + {certPhase === "idle" && !certSkipped && ( +
+
+ +
+

+ {!allGood || !protonAllGood ? "SteamCMD and Proton-GE must be ready first." : "Install later in Settings if needed."} +

+
+ )} + + {(certPhase === "downloading" || certPhase === "installing") && ( +

+ {certPhase === "downloading" ? "Downloading…" : "Installing…"} +

+ )} + + {certPhase === "done" && ( +

✓ Installed

+ )} + + {certPhase === "error" && ( +
+

Installation failed

+

{certError}

+ +
+ )} + + {certSkipped && certPhase !== "done" && ( +

+ Skipped — can be installed later in Settings. +

+ )} +
+ + {/* Firewall row */} +
+
+

Firewall Ports

+ {fwPhase === "done" && } + {(fwPhase === "checking" || fwPhase === "opening") && ( + + )} +
+ + {fwPhase === "checking" && ( +

Checking firewall…

+ )} + + {fwStatus && !fwStatus.active && (fwPhase === "done" || fwPhase === "ready") && ( +

✓ No active firewall detected.

+ )} + + {fwStatus && fwStatus.active && (fwPhase === "ready" || fwPhase === "done") && ( +
+

+ {fwPhase === "done" + ? "✓ All ports covered." + : `${fwStatus.ports.filter((p) => !p.covered).length} port(s) need opening.`} +

+ {fwPhase === "ready" && fwStatus.ports.filter((p) => !p.covered).length > 0 && ( + + )} + {fwPhase === "ready" && fwStatus.ports.filter((p) => !p.covered).length === 0 && ( + + )} +
+ )} + + {fwPhase === "error" && ( +
+

Check failed

+

{fwError}

+ +
+ )} + + {fwSkipped && fwPhase !== "done" && ( +

+ Skipped — configure firewall manually if needed. +

+ )} + +
+ + {/* Firewall Dialog */} + + + + + + Open Firewall Ports + + + +
+ {info.allServersPorts?.map((srv) => { + const srvPortDefs = [ + { port: srv.gamePort, protocol: "udp" as const, label: "Game Port" }, + { port: srv.queryPort, protocol: "udp" as const, label: "Query Port" }, + { port: srv.rconPort, protocol: "tcp" as const, label: "RCON Port" }, + ]; + + const srvStatus = srvPortDefs + .map((pd) => ({ + ...pd, + status: fwStatus?.ports.find( + (p) => p.port === pd.port && p.protocol === pd.protocol + ), + })) + .filter((x) => x.status); + + if (srvStatus.length === 0) return null; + + return ( +
+

+ {srv.serverName} +

+
+ {srvStatus.map((pd) => ( +
+ {pd.status?.covered ? ( + + ) : ( + + )} + + {pd.port}/{pd.protocol.toUpperCase()} + + + ({pd.label}) + +
+ ))} +
+
+ ); + })} +
+ + + + + +
+
+ {allGood && protonAllGood && (

- ✓ Click "Import & Finish" below to continue. + ✓ SteamCMD and {IS_LINUX ? "Proton-GE are " : "is "} ready. Mod certs and firewall are optional. Click "Import & Finish" below to continue.

)}
@@ -635,8 +1055,19 @@ function BaseDirStep() { const validateDebounceRef = useRef | null>(null); const [importError, setImportError] = useState(""); const [importInfo, setImportInfo] = useState<{ - servers: number; steamcmd: string; proton?: string; - steamcmdMissing?: boolean; protonMissing?: boolean; + servers: number; + steamcmd: string; + proton?: string; + protonPrefix?: string; + steamcmdMissing?: boolean; + protonMissing?: boolean; + allServersPorts?: Array<{ + serverId: string; + serverName: string; + gamePort: number; + queryPort: number; + rconPort: number; + }>; } | null>(null); const validateDir = useCallback(async (path: string) => { @@ -728,16 +1159,71 @@ function BaseDirStep() { getSetting("steamcmd_path"), getSetting("proton_path"), ]); - const [steamcmdExists, protonExists] = await Promise.all([ - steamcmdPath ? tauriCmd.checkFileExists(steamcmdPath) : Promise.resolve(false), - protonPath ? tauriCmd.checkFileExists(protonPath) : Promise.resolve(false), - ]); + + // Check if stored paths exist; if not, check fallback locations in the importing folder + let resolvedSteamcmdPath = steamcmdPath; + let resolvedProtonPath = protonPath; + let steamcmdExists = steamcmdPath ? await tauriCmd.checkFileExists(steamcmdPath) : false; + let protonExists = protonPath ? await tauriCmd.checkFileExists(protonPath) : false; + + // If steamcmd not found at stored location, check fallback + if (!steamcmdExists) { + const isWindows = typeof window !== "undefined" && navigator.userAgent.includes("Windows"); + const fallbackSteamcmd = importDir.replace(/[/\\]$/, "") + sep + "lokiasam" + sep + "steamcmd" + sep + (isWindows ? "steamcmd.exe" : "steamcmd.sh"); + if (await tauriCmd.checkFileExists(fallbackSteamcmd)) { + resolvedSteamcmdPath = fallbackSteamcmd; + steamcmdExists = true; + } + } + + // If proton not found at stored location, check fallback directory (only on Linux) + if (!protonExists && typeof window !== "undefined" && !navigator.userAgent.includes("Windows")) { + const fallbackDir = importDir.replace(/[/\\]$/, "") + sep + "lokiasam" + sep + "proton"; + if (await tauriCmd.checkFileExists(fallbackDir)) { + // Look specifically inside lokiasam/proton/ for GE-Proton* subdirectories + // and verify each has a valid proton executable + try { + const found = await tauriCmd.scanForProton(importDir); + // Filter to only those inside the fallback directory + const localProtons = found.filter(p => p.path.startsWith(fallbackDir)); + if (localProtons.length > 0) { + // Validate the first found Proton to ensure it's complete (has proton executable) + const isValid = await tauriCmd.validateProtonPath(localProtons[0].path); + if (isValid) { + resolvedProtonPath = localProtons[0].path; + protonExists = true; + } + } + } catch { + // If scanning fails, proton stays not found + } + } + } + + // During import: ALWAYS compute prefix from importDir, ignore stored protonPrefixPath + // Proton can be external, but prefix is always local to this installation + let resolvedPrefix: string | undefined; + if (typeof window !== "undefined" && !navigator.userAgent.includes("Windows")) { + resolvedPrefix = importDir.replace(/[/\\]$/, "") + sep + "lokiasam" + sep + "proton" + sep + "prefix"; + } + + // Build all servers' port data for firewall checking + const allServersPorts = servers.map((srv) => ({ + serverId: srv.id, + serverName: srv.name, + gamePort: srv.port, + queryPort: srv.query_port, + rconPort: srv.rcon_port, + })); + setImportInfo({ servers: servers.length, - steamcmd: steamcmdPath ?? "(not set)", - proton: protonPath ?? undefined, - steamcmdMissing: !steamcmdPath || !steamcmdExists, - protonMissing: typeof window !== "undefined" && !navigator.userAgent.includes("Windows") && (!protonPath || !protonExists), + steamcmd: resolvedSteamcmdPath ?? "(not set)", + proton: resolvedProtonPath ?? undefined, + protonPrefix: resolvedPrefix ?? undefined, + steamcmdMissing: !resolvedSteamcmdPath || !steamcmdExists, + protonMissing: typeof window !== "undefined" && !navigator.userAgent.includes("Windows") && (!resolvedProtonPath || !protonExists), + allServersPorts, }); setImportValid(true); } catch (e) { @@ -845,7 +1331,7 @@ function BaseDirStep() {
- ))} + ].map(({ mode, label, desc }) => { + // Lock tabs only in auto mode (downloading or validated). Manual mode is always switchable. + const isTabLocked = (isLoading || steamcmdValidated) && steamcmdMode === "auto"; + return ( + + ); + })}
{steamcmdMode === "auto" && ( @@ -1317,16 +1825,23 @@ function ProtonGEStep() { const [protonPhase, setProtonPhase] = useState<"downloading" | "extracting">("downloading"); const [attempt, setAttempt] = useState(0); const [canceled, setCanceled] = useState(false); + const [manuallyAddedPaths, setManuallyAddedPaths] = useState>(new Set()); + const detectedListRef = useRef(null); const scan = useCallback(async () => { setScanning(true); try { const results = await tauriCmd.scanForProton(baseDir); - setFound(results); + // Preserve manually added paths during rescan + const preserved = results.filter(e => !manuallyAddedPaths.has(e.path)); + const manual = Array.from(manuallyAddedPaths) + .map(path => found.find(e => e.path === path)) + .filter((e): e is ProtonEntry => e !== undefined); + setFound([...preserved, ...manual]); } catch { /* ignore */ } finally { setScanning(false); } - }, [baseDir]); + }, [baseDir, manuallyAddedPaths, found]); useEffect(() => { if (protonMode === "existing") scan(); @@ -1335,20 +1850,26 @@ function ProtonGEStep() { const handleSelectDetected = async (entry: ProtonEntry) => { if (validating) return; setError(""); - setProtonValidated(false); setProtonPath(""); setValidating(entry.path); try { const ok = await tauriCmd.validateProtonPath(entry.path); if (ok) { setProtonPath(entry.path); - setProtonValidated(true); setProtonVersion(entry.version); + setProtonValidated(true); + // Auto-scroll to show the selected item + setTimeout(() => { + const selected = detectedListRef.current?.querySelector('[data-selected="true"]'); + selected?.scrollIntoView({ behavior: "smooth", block: "nearest" }); + }, 50); } else { setError(`${entry.version} does not appear to be a valid Proton-GE installation.`); + setProtonValidated(false); } } catch (e) { setError(String(e)); + setProtonValidated(false); } finally { setValidating(null); } @@ -1382,6 +1903,7 @@ function ProtonGEStep() { setCanceled(true); } else { setError(msg); + setProtonValidated(false); } } finally { setLoading(false); @@ -1393,7 +1915,6 @@ function ProtonGEStep() { const handleManualValidate = async () => { if (!manualPath.trim()) { setError("Enter the path to your Proton-GE directory."); return; } setError(""); - setProtonValidated(false); setProtonPath(""); const path = manualPath.trim(); const versionName = path.split("/").pop() || path; @@ -1402,13 +1923,22 @@ function ProtonGEStep() { if (ok) { const newEntry: ProtonEntry = { path, version: versionName }; setFound(prev => [...prev.filter(e => e.path !== path), newEntry]); + setManuallyAddedPaths(prev => new Set([...prev, path])); setProtonPath(path); - setProtonValidated(true); setProtonVersion(versionName); + setProtonValidated(true); + // Auto-scroll to the newly added entry + setTimeout(() => { + detectedListRef.current?.scrollTo({ top: detectedListRef.current.scrollHeight, behavior: "smooth" }); + }, 100); } else { setError("Validation failed — check the path contains a `proton` script and `files/bin/wine64`."); + setProtonValidated(false); } - } catch (e) { setError(String(e)); } + } catch (e) { + setError(String(e)); + setProtonValidated(false); + } }; const pickDir = async () => { @@ -1438,24 +1968,36 @@ function ProtonGEStep() { {([ { mode: "managed" as const, label: "Managed by LokiASAM", desc: `Download & update automatically into ${managedTarget}` }, { mode: "existing" as const, label: "Use existing installation", desc: "Point to a Proton-GE you already have" }, - ]).map(({ mode, label, desc }) => ( - - ))} + ]).map(({ mode, label, desc }) => { + // Only lock tabs in managed mode when downloading/validated. Existing mode is always switchable. + const isTabLocked = (isLoading || protonValidated) && protonMode === "managed"; + return ( + + ); + })}
{protonMode === "managed" && ( @@ -1534,13 +2076,14 @@ function ProtonGEStep() { No Proton-GE installations detected. Enter a path manually below or switch to Managed mode.

) : ( -
+
{found.map((entry) => { const isValidating = validating === entry.path; - const isSelected = protonValidated && protonPath === entry.path; + const isSelected = protonPath === entry.path; return (
) : null}
diff --git a/src/app/clusters/detail/page.tsx b/src/app/clusters/detail/page.tsx index 02cb1c9..cd7b553 100644 --- a/src/app/clusters/detail/page.tsx +++ b/src/app/clusters/detail/page.tsx @@ -1,6 +1,6 @@ "use client"; -import { Suspense, useState, useCallback } from "react"; +import { Suspense, useState, useCallback, useEffect } from "react"; import { useSearchParams, useRouter } from "next/navigation"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { @@ -38,6 +38,7 @@ import { import { ARK_MAPS } from "@/data/game-data"; import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; // --------------------------------------------------------------------------- // Add Server Dialog @@ -121,17 +122,21 @@ function AddServerDialog({ cluster, open, onClose, onAdded }: AddServerDialogPro )} - @@ -233,9 +238,14 @@ function ClusterDetailContent() { queryClient.invalidateQueries({ queryKey: ["servers"] }); }, [queryClient, id]); - const baseDir = cluster?.cluster_dir_override - ? null - : null; // shown as note + const [baseDir, setBaseDir] = useState(""); + useEffect(() => { + getAppSetting("base_dir").then((v) => setBaseDir(v ?? "")); + }, []); + + const resolvedClusterDir = cluster + ? (cluster.cluster_dir_override?.trim() || `${baseDir}/clusters/${cluster.id}`) + : ""; async function handleRemove(server: ServerRow) { setRemoving(true); @@ -289,37 +299,48 @@ function ClusterDetailContent() { return (
{/* Header */} -
- -
-
+
+
-
-

+ +
+
- {cluster.name} -

-

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

+ +
+
+

+ {cluster.name} +

+

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

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

+

Cluster Settings

-

Cluster ID

+

Cluster ID

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

Cluster Directory

-

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

+

Cluster Directory

+
+

+ {resolvedClusterDir || "…"} +

+ + + + + Open cluster folder + +

@@ -373,27 +416,11 @@ function ClusterDetailContent() {

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

- Member Servers -

- -
+

+ Servers in Cluster +

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

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

diff --git a/src/app/clusters/page.tsx b/src/app/clusters/page.tsx index c8475d7..cada5d3 100644 --- a/src/app/clusters/page.tsx +++ b/src/app/clusters/page.tsx @@ -84,7 +84,7 @@ function NewClusterDialog({ open, onClose, onCreated }: NewClusterDialogProps) {
- + setName(e.target.value)} @@ -94,7 +94,7 @@ function NewClusterDialog({ open, onClose, onCreated }: NewClusterDialogProps) { />
-
- @@ -235,17 +233,21 @@ function DeleteDialog({ cluster, onClose, onDeleted }: DeleteDialogProps) {
- @@ -269,7 +271,7 @@ function ClusterCard({ cluster, onDelete }: ClusterCardProps) { return (
router.push(`/clusters/detail?id=${cluster.id}`)} style={{ border: "1px solid var(--border)", @@ -306,7 +308,7 @@ function ClusterCard({ cluster, onDelete }: ClusterCardProps) { e.stopPropagation(); onDelete(cluster); }} - style={{ color: "var(--text-muted)" }} + style={{ color: "var(--neon-red)" }} > @@ -359,7 +361,7 @@ export default function ClustersPage() { return (
{/* Header */} -
+
@@ -375,14 +377,12 @@ export default function ClustersPage() {

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

- No clusters yet -

-

+

No clusters yet

+

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

) : ( diff --git a/src/app/globals.css b/src/app/globals.css index 93fd26f..29b52d0 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -40,7 +40,7 @@ --color-input: rgba(var(--neon-purple-rgb), 0.2); --color-ring: var(--neon-purple); --color-muted: rgba(20, 20, 52, 0.85); - --color-muted-foreground: #5858a0; + --color-muted-foreground: rgba(var(--neon-purple-rgb), 0.45); /* Fonts */ --font-sans: var(--font-geist-sans); @@ -76,8 +76,8 @@ --neon-orange: #ff8800; /* Text — defaults match storm preset */ - --foreground: #e0e0ff; - --text-primary: #e0e0ff; + --foreground: #dfe4f2; + --text-primary: #dfe4f2; --text-muted: #606880; --text-subtle: #464e64; @@ -93,12 +93,12 @@ --glass-blur: 12px; /* Popover / dropdown surface */ - --popover: #12161e; - --popover-foreground: #e0e0ff; + --popover: rgba(18, 20, 32, 0.97); + --popover-foreground: #dfe4f2; /* Accent — subtle highlight for menu item hover/focus */ --accent: rgba(64, 128, 255, 0.15); - --accent-foreground: #e0e0ff; + --accent-foreground: #dfe4f2; } /* --------------------------------------------------------------------------- diff --git a/src/app/logs/page.tsx b/src/app/logs/page.tsx index 4aea937..eed4e9c 100644 --- a/src/app/logs/page.tsx +++ b/src/app/logs/page.tsx @@ -2,7 +2,9 @@ import { useState, useEffect } from "react"; import { useSearchParams, useRouter } from "next/navigation"; -import { ScrollText, ChevronDown } from "lucide-react"; +import { ScrollText, ChevronDown, Plus } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { useAppStore } from "@/store/useAppStore"; import { useServers } from "@/hooks/useServers"; import { LogsTab } from "@/components/server/tabs/LogsTab"; import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; @@ -12,6 +14,7 @@ export default function LogsPage() { const searchParams = useSearchParams(); const router = useRouter(); const { data: servers = [], isLoading } = useServers(); + const { setShowNewServerWizard } = useAppStore(); const [selectedId, setSelectedId] = useState( searchParams.get("server") ?? "" @@ -37,17 +40,22 @@ export default function LogsPage() { return (
{/* ── Page header ── */} -
- -

- Logs -

+
+
+ +

+ Logs +

+
+

+ Browse server logs, crash reports, and chat history. +

{/* ── Server selector ── */} @@ -106,17 +114,27 @@ export default function LogsPage() {
) : !isLoading && servers.length === 0 ? ( -
- -

- No servers yet -

-

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

+
+
+ +
+
+

No servers yet

+

+ Create a server to start viewing logs. +

+
+
) : null}
diff --git a/src/app/mod-maps/page.tsx b/src/app/mod-maps/page.tsx index 8559ebd..e26a5e8 100644 --- a/src/app/mod-maps/page.tsx +++ b/src/app/mod-maps/page.tsx @@ -62,24 +62,27 @@ export default function ModMapsPage() { }; return ( -
+
{/* Header */} -
-
- -
-

Mod Maps

-

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

+
+
+
+ +

+ Mod Maps +

+

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

@@ -98,7 +101,7 @@ export default function ModMapsPage() { value={displayName} onChange={(e) => setDisplayName(e.target.value)} placeholder="e.g. Fjordur Reborn" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} />
@@ -107,7 +110,7 @@ export default function ModMapsPage() { value={modId} onChange={(e) => setModId(e.target.value)} placeholder="e.g. 965379" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} />
@@ -116,7 +119,7 @@ export default function ModMapsPage() { value={mapPath} onChange={(e) => setMapPath(e.target.value)} placeholder="e.g. MyMap_WP" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} />

The exact map path string passed at server launch (e.g. TheIsland_WP). @@ -124,7 +127,7 @@ export default function ModMapsPage() {

- +
) : (
diff --git a/src/app/notifications/page.tsx b/src/app/notifications/page.tsx index 85f7032..7fed6e2 100644 --- a/src/app/notifications/page.tsx +++ b/src/app/notifications/page.tsx @@ -222,7 +222,7 @@ function NotificationsContent() { return (
{/* Header */} -
+
@@ -241,12 +241,11 @@ function NotificationsContent() { @@ -331,16 +330,18 @@ function NotificationsContent() { {/* List */}
{filtered.length === 0 ? ( -
- +
+
+ +
-

+

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

-

+

+

{notifications.length === 0 ? "Events like server starts, stops, crashes, and backups will appear here." : "Try adjusting your filters."} diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index 3989d77..6893dd1 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -5,7 +5,7 @@ import { Folder, Terminal, Info, Archive, Copy, FolderOpen, CheckCircle2, AlertCircle, Loader2, Save, RefreshCw, ArrowUp, Bell, MessageSquare, Mail, Monitor, Send, Download, - Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, Power, ShieldCheck, + Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, Power, ShieldCheck, Settings, } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; @@ -239,7 +239,7 @@ function BaseDirMigrationSection() { Root folder for all server installs. To relocate, enter a new path and click Verify & Move.

@@ -1914,11 +1914,11 @@ function StartupSection() { @@ -1509,7 +1509,7 @@ function AdvancedConfigTab({ onChange={(e) => setArg("_customCli", e.target.value)} placeholder="-SomeFlag -AnotherFlag=value" className="font-mono text-xs" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(255,165,0,0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(255,165,0,0.3)", color: "var(--text-primary)" }} />
@@ -1528,7 +1528,7 @@ function AdvancedConfigTab({ min={1} step={0.5} className="w-32 text-xs" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(255,165,0,0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(255,165,0,0.3)", color: "var(--text-primary)" }} /> GB
))} @@ -1971,7 +1971,7 @@ export function ConfigTab({ server }: Props) { )}
- + diff --git a/src/components/shared/CommandOutputPanel.tsx b/src/components/shared/CommandOutputPanel.tsx index 0c58647..c07c348 100644 --- a/src/components/shared/CommandOutputPanel.tsx +++ b/src/components/shared/CommandOutputPanel.tsx @@ -195,7 +195,7 @@ export function CommandOutputPanel({ {/* Header */}
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx index a2c2d0b..b06d33a 100644 --- a/src/components/ui/dialog.tsx +++ b/src/components/ui/dialog.tsx @@ -107,7 +107,7 @@ function DialogFooter({
checkName(e.target.value)} placeholder="My ASA Server" style={{ - background: "rgba(10,10,30,0.8)", + background: "var(--surface)", borderColor: nameError ? "var(--neon-red)" : "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)", }} @@ -469,7 +469,7 @@ function BasicInfoStep({ onClick={() => setMapMenuOpen((v) => !v)} className="w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-left" style={{ - background: "rgba(10,10,30,0.8)", + background: "var(--surface)", border: "1px solid rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)", }} @@ -557,7 +557,7 @@ function BasicInfoStep({ const adminMismatch = !!data.adminPasswordConfirm && data.adminPassword !== data.adminPasswordConfirm; const serverMismatch = !!data.serverPasswordConfirm && data.serverPassword !== data.serverPasswordConfirm; const fieldStyle = (hasValue: boolean, mismatch: boolean) => ({ - background: "rgba(10,10,30,0.8)", + background: "var(--surface)", borderColor: mismatch ? "var(--neon-red)" : !hasValue ? "rgba(255,0,85,0.5)" : "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)", }); @@ -677,7 +677,7 @@ function GameModeStep({ data, onChange }: { data: WizardData; onChange: (patch: onClick={() => onChange({ gameMode: mode.id })} className="rounded-xl p-5 text-left transition-all flex flex-col gap-3" style={{ - background: active ? "rgba(var(--neon-purple-rgb),0.1)" : "rgba(10,10,30,0.5)", + background: active ? "rgba(var(--neon-purple-rgb),0.1)" : "var(--surface)", border: `1px solid ${active ? "rgba(var(--neon-purple-rgb),0.5)" : "rgba(var(--neon-purple-rgb),0.12)"}`, boxShadow: active ? "0 0 24px rgba(var(--neon-purple-rgb),0.1)" : "none", }} @@ -779,7 +779,7 @@ function StyleStep({ data, onChange }: { data: WizardData; onChange: (patch: Par onClick={() => onChange({ presetStyle: style.id as WizardData["presetStyle"] })} className="w-full rounded-lg p-4 text-left transition-all" style={{ - background: active ? "rgba(var(--neon-purple-rgb),0.1)" : "rgba(10,10,30,0.5)", + background: active ? "rgba(var(--neon-purple-rgb),0.1)" : "var(--surface)", border: `1px solid ${active ? "rgba(var(--neon-purple-rgb),0.5)" : "rgba(var(--neon-purple-rgb),0.12)"}`, boxShadow: active ? "0 0 16px rgba(var(--neon-purple-rgb),0.1)" : "none", }} @@ -1231,7 +1231,7 @@ function FullIniStep({ data, onChange }: { data: WizardData; onChange: (patch: P onChange={(e) => setValue(field.iniSection, field.key, e.target.value)} className="h-7 text-xs font-mono" style={{ - background: "rgba(10,10,30,0.8)", + background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)", }} @@ -1280,7 +1280,7 @@ function PortField({ onBlur={() => onBlur(fieldKey, value)} className="font-mono" style={{ - background: "rgba(10,10,30,0.8)", + background: "var(--surface)", borderColor: conflict ? "rgba(255,140,0,0.6)" : status === false ? "var(--neon-red)" : status === true ? "rgba(0,255,136,0.4)" : "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)", }} @@ -1663,7 +1663,7 @@ function ClusterStep({ data, onChange }: { data: WizardData; onChange: (patch: P onClick={() => handleSelectCluster(cluster.id)} className="w-full rounded-lg p-3 text-left transition-all" style={{ - background: data.clusterId === cluster.id ? "rgba(var(--neon-purple-rgb),0.1)" : "rgba(10,10,30,0.5)", + background: data.clusterId === cluster.id ? "rgba(var(--neon-purple-rgb),0.1)" : "var(--surface)", border: `1px solid ${data.clusterId === cluster.id ? "rgba(var(--neon-purple-rgb),0.5)" : "rgba(var(--neon-purple-rgb),0.15)"}`, }} > @@ -1681,7 +1681,7 @@ function ClusterStep({ data, onChange }: { data: WizardData; onChange: (patch: P onKeyDown={(e) => e.key === "Enter" && handleCreateCluster()} placeholder="Cluster name" className="text-sm" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} />
); @@ -2028,7 +2028,7 @@ function AutomationStep({ data, onChange }: { data: WizardData; onChange: (patch onChange={(e) => onChange({ backupBroadcastMessage: e.target.value })} placeholder="Backup in progress — lag may occur." className="text-xs" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} />
@@ -2214,7 +2214,7 @@ function ModsStep({ data, onChange }: { data: WizardData; onChange: (patch: Part value={copyFromId} onChange={(e) => setCopyFromId(e.target.value)} className="flex-1 text-xs rounded-lg px-2 py-1.5" - style={{ background: "rgba(10,10,30,0.8)", border: "1px solid rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", border: "1px solid rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} > {existingServers.map((s) => )} @@ -2244,7 +2244,7 @@ function ModsStep({ data, onChange }: { data: WizardData; onChange: (patch: Part onKeyDown={(e) => e.key === "Enter" && addMod()} placeholder="CurseForge mod ID (e.g. 928793)" className="font-mono text-sm" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} />
@@ -2541,7 +2549,7 @@ function NotificationsStep({ onMatrixChange }: { onMatrixChange: (events: Record setSmtpUsername(e.target.value)} placeholder="user@example.com" className="font-mono text-xs" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} />
@@ -2549,7 +2557,7 @@ function NotificationsStep({ onMatrixChange }: { onMatrixChange: (events: Record
setSmtpPassword(e.target.value)} placeholder="••••••••" className="font-mono text-xs pr-8" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} />
setSmtpTo(e.target.value)} placeholder="admin@example.com" className="font-mono text-xs" - style={{ background: "rgba(10,10,30,0.8)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} />
@@ -2581,10 +2589,13 @@ function NotificationsStep({ onMatrixChange }: { onMatrixChange: (events: Record {/* Notification event matrix */}
-

Notification Events

+

+ Notification Events + (optional) +

Choose which events trigger each channel. Configure credentials above to unlock Discord and SMTP columns.

@@ -2633,7 +2644,7 @@ function TrayStep() { onClick={() => setCloseToTray(value)} className="w-full text-left rounded-lg p-4 transition-all" style={{ - background: closeToTray === value ? "rgba(var(--neon-purple-rgb),0.1)" : "rgba(10,10,30,0.5)", + background: closeToTray === value ? "rgba(var(--neon-purple-rgb),0.1)" : "var(--surface)", border: `1px solid ${closeToTray === value ? "rgba(var(--neon-purple-rgb),0.5)" : "rgba(var(--neon-purple-rgb),0.15)"}`, boxShadow: closeToTray === value ? "0 0 16px rgba(var(--neon-purple-rgb),0.12)" : "none", }} @@ -2754,7 +2765,7 @@ function AutoUpdateStep() { {/* ASA Server Updates */}
+ style={{ background: "var(--surface)", border: "1px solid rgba(var(--neon-purple-rgb),0.12)" }}>

ASA Server Updates

@@ -2768,7 +2779,7 @@ function AutoUpdateStep() { onClick={() => setAsaAutoCheckHours(value)} className="flex-1 py-1.5 rounded-lg text-xs font-medium transition-all" style={{ - background: asaAutoCheckHours === value ? "rgba(var(--neon-purple-rgb),0.15)" : "rgba(10,10,30,0.5)", + background: asaAutoCheckHours === value ? "rgba(var(--neon-purple-rgb),0.15)" : "var(--surface-elevated)", border: `1px solid ${asaAutoCheckHours === value ? "rgba(var(--neon-purple-rgb),0.5)" : "rgba(var(--neon-purple-rgb),0.15)"}`, color: asaAutoCheckHours === value ? "var(--neon-purple)" : "var(--text-muted)", }} @@ -2784,7 +2795,7 @@ function AutoUpdateStep() { {/* LokiASAM App Updates */}

+ style={{ background: "var(--surface)", border: "1px solid rgba(var(--neon-purple-rgb),0.12)" }}>

LokiASAM App Updates

@@ -2798,7 +2809,7 @@ function AutoUpdateStep() { onClick={() => setAppUpdateCheckMode(value)} className="flex-1 py-1.5 rounded-lg text-xs font-medium transition-all" style={{ - background: appUpdateCheckMode === value ? "rgba(var(--neon-purple-rgb),0.15)" : "rgba(10,10,30,0.5)", + background: appUpdateCheckMode === value ? "rgba(var(--neon-purple-rgb),0.15)" : "var(--surface-elevated)", border: `1px solid ${appUpdateCheckMode === value ? "rgba(var(--neon-purple-rgb),0.5)" : "rgba(var(--neon-purple-rgb),0.15)"}`, color: appUpdateCheckMode === value ? "var(--neon-purple)" : "var(--text-muted)", }} @@ -2812,7 +2823,7 @@ function AutoUpdateStep() { {/* Proton-GE (Linux only) */} {IS_LINUX && (

+ style={{ background: "var(--surface)", border: "1px solid rgba(var(--neon-purple-rgb),0.12)" }}>

Proton-GE Updates

@@ -2826,7 +2837,7 @@ function AutoUpdateStep() { onClick={() => setProtonCheckMode(value)} className="flex-1 py-1.5 rounded-lg text-xs font-medium transition-all" style={{ - background: protonCheckMode === value ? "rgba(var(--neon-purple-rgb),0.15)" : "rgba(10,10,30,0.5)", + background: protonCheckMode === value ? "rgba(var(--neon-purple-rgb),0.15)" : "var(--surface-elevated)", border: `1px solid ${protonCheckMode === value ? "rgba(var(--neon-purple-rgb),0.5)" : "rgba(var(--neon-purple-rgb),0.15)"}`, color: protonCheckMode === value ? "var(--neon-purple)" : "var(--text-muted)", }} @@ -2977,7 +2988,7 @@ function CompleteStep({ onComplete }: { onComplete: () => void }) {

{label} {value || "—"} diff --git a/src/lib/theme.ts b/src/lib/theme.ts index bf71270..f9bb3a2 100644 --- a/src/lib/theme.ts +++ b/src/lib/theme.ts @@ -43,6 +43,8 @@ interface PresetTokens { surface: string; surfaceEl: string; glassBg: string; + popoverBg: string; + foreground: string; textMuted: string; textSubtle: string; defaultAccent: ThemeAccent; @@ -55,6 +57,8 @@ export const THEME_PRESETS: Record = { surface: "rgba(20, 20, 52, 0.85)", surfaceEl: "rgba(28, 28, 68, 0.92)", glassBg: "rgba(18, 18, 50, 0.72)", + popoverBg: "rgba(16, 16, 44, 0.97)", + foreground: "#e8e4ff", textMuted: "#5858a0", textSubtle: "#3a3a70", defaultAccent: "purple", @@ -65,6 +69,8 @@ export const THEME_PRESETS: Record = { surface: "rgba(5, 12, 25, 0.75)", surfaceEl: "rgba(8, 16, 35, 0.9)", glassBg: "rgba(5, 12, 30, 0.6)", + popoverBg: "rgba(10, 16, 30, 0.97)", + foreground: "#dce4f6", textMuted: "#384060", textSubtle: "#263040", defaultAccent: "blue", @@ -75,6 +81,8 @@ export const THEME_PRESETS: Record = { surface: "rgba(8, 18, 8, 0.75)", surfaceEl: "rgba(10, 24, 10, 0.9)", glassBg: "rgba(8, 18, 8, 0.6)", + popoverBg: "rgba(12, 20, 12, 0.97)", + foreground: "#d8eedc", textMuted: "#3a5040", textSubtle: "#283530", defaultAccent: "green", @@ -85,6 +93,8 @@ export const THEME_PRESETS: Record = { surface: "rgba(18, 22, 35, 0.8)", surfaceEl: "rgba(24, 28, 44, 0.9)", glassBg: "rgba(18, 22, 38, 0.65)", + popoverBg: "rgba(18, 20, 32, 0.97)", + foreground: "#dfe4f2", textMuted: "#606880", textSubtle: "#464e64", defaultAccent: "blue", @@ -122,6 +132,11 @@ export function applyThemePreset(preset: string): void { root.style.setProperty("--surface", p.surface); root.style.setProperty("--surface-elevated", p.surfaceEl); root.style.setProperty("--glass-bg", p.glassBg); + root.style.setProperty("--popover", p.popoverBg); + root.style.setProperty("--foreground", p.foreground); + root.style.setProperty("--text-primary", p.foreground); + root.style.setProperty("--popover-foreground",p.foreground); + root.style.setProperty("--accent-foreground", p.foreground); root.style.setProperty("--text-muted", p.textMuted); root.style.setProperty("--text-subtle", p.textSubtle); root.dataset.preset = preset; From 5d31ab97a9ac600968f4eb880e4909e25924b4c8 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 23 Jun 2026 16:48:55 -0500 Subject: [PATCH 10/28] feat: improve ASA cache install UX with progress persistence, close guard, and nav fixes - Register abort flag in update_cache Rust command so running ops are trackable via get_running_ops; enables close guard and nav reconnect - Add get_running_ops command; extend CloseWarningManager to check both server installs and tool ops on close/tray-quit, showing a combined abort dialog - Persist ASA cache install progress when navigating away and back; polling only runs in reconnect mode to avoid racing runCacheOp's own state management - Pre-download button on Updates tab navigates to General tab and auto-scrolls to the cache row, auto-starting the install - Disable and relabel the ASA update button while any cache op is running, mirroring the TopBar spinner label - Replace boolean asaCacheUpdateInProgress store flag with asaCacheOpLabel (string | null) so TopBar shows the correct op name (Installing / Reinstalling / Verifying vs. Checking ASA updates) - Reset tab scroll position to top on tab switch; skip reset when the pre-download navigation triggers its own scrollIntoView - Fix CommandOutputPanel duplicate key error on remount caused by mutating the shared buffer array before setLines reads prev --- src-tauri/src/commands/steamcmd.rs | 39 +- src-tauri/src/commands/system.rs | 8 + src-tauri/src/lib.rs | 1 + src/app/settings/page.tsx | 836 +++++++++++++++--- src/components/layout/CloseWarningManager.tsx | 139 ++- src/components/layout/DisableContextMenu.tsx | 2 +- src/components/layout/TopBar.tsx | 6 +- src/components/shared/CommandOutputPanel.tsx | 2 +- src/components/shared/NotificationMatrix.tsx | 37 +- src/components/wizard/SetupWizard.tsx | 238 +++-- src/lib/tauri-commands.ts | 2 + src/lib/update-utils.ts | 13 +- src/store/useAppStore.ts | 7 +- 13 files changed, 1062 insertions(+), 268 deletions(-) diff --git a/src-tauri/src/commands/steamcmd.rs b/src-tauri/src/commands/steamcmd.rs index a39683c..07e68c3 100644 --- a/src-tauri/src/commands/steamcmd.rs +++ b/src-tauri/src/commands/steamcmd.rs @@ -658,28 +658,43 @@ pub async fn update_cache( server_id: String, cache_dir: String, steamcmd_path: String, + state: tauri::State<'_, crate::state::AppState>, app_handle: tauri::AppHandle, ) -> Result { let channel = format!("{}/{}", events::STEAMCMD_OUTPUT, server_id); + let abort = state.register_abort(&server_id); - emit_line(&app_handle, &channel, "stdout", "Updating server cache from Steam…")?; - tokio::fs::create_dir_all(&cache_dir) - .await - .map_err(|e| format!("Failed to create cache directory: {e}"))?; + let result: Result = async { + emit_line(&app_handle, &channel, "stdout", "Updating server cache from Steam…")?; + tokio::fs::create_dir_all(&cache_dir) + .await + .map_err(|e| format!("Failed to create cache directory: {e}"))?; - steamcmd_app_update(&app_handle, &steamcmd_path, &cache_dir, false, &channel, None).await?; + steamcmd_app_update( + &app_handle, + &steamcmd_path, + &cache_dir, + false, + &channel, + Some(std::sync::Arc::clone(&abort)), + ) + .await?; - let acf_path = Path::new(&cache_dir).join(ACF_REL_PATH); - let build_id = read_acf_build_id(&acf_path).unwrap_or_else(|| "0".to_string()); + let acf_path = Path::new(&cache_dir).join(ACF_REL_PATH); + let build_id = read_acf_build_id(&acf_path).unwrap_or_else(|| "0".to_string()); + + emit_line(&app_handle, &channel, "stdout", &format!("Cache updated to build {build_id}."))?; - emit_line(&app_handle, &channel, "stdout", &format!("Cache updated to build {build_id}."))?; + if build_id != "0" { + crate::commands::build_version::maybe_fetch_internet(&app_handle, &build_id); + } - // Trigger internet version fetch for this build in the background - if build_id != "0" { - crate::commands::build_version::maybe_fetch_internet(&app_handle, &build_id); + Ok(build_id) } + .await; - Ok(build_id) + state.clear_abort(&server_id); + result } /// Copy the shared cache to a specific server directory without re-running SteamCMD. diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs index 576bc22..6cded33 100644 --- a/src-tauri/src/commands/system.rs +++ b/src-tauri/src/commands/system.rs @@ -873,6 +873,14 @@ pub fn get_install_method() -> &'static str { "binary" } +/// Returns the IDs of all currently active background operations. +/// An operation is active from `register_abort` until `clear_abort` is called. +#[tauri::command] +pub fn get_running_ops(state: tauri::State<'_, crate::state::AppState>) -> Vec { + state.abort_flags.lock().unwrap().keys().cloned().collect() +} + + #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AppImageIntegrationStatus { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 52ca9f8..5f1c561 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -577,6 +577,7 @@ pub fn run() { commands::system::install_appimage_integration, commands::system::uninstall_appimage_integration, commands::system::get_install_method, + commands::system::get_running_ops, commands::system::check_dir, commands::system::check_file_exists, commands::system::wipe_lokiasam_dir, diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index 6893dd1..a624b0a 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -1,11 +1,11 @@ "use client"; -import { useState, useEffect, useCallback } from "react"; +import { useState, useEffect, useCallback, useRef } from "react"; import { Folder, Terminal, Info, Archive, Copy, FolderOpen, CheckCircle2, AlertCircle, Loader2, Save, RefreshCw, ArrowUp, Bell, MessageSquare, Mail, Monitor, Send, Download, - Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, Power, ShieldCheck, Settings, + Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, Power, ShieldCheck, Settings, TriangleAlert, } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; @@ -32,6 +32,7 @@ import { useAutostart } from "@/hooks/useAutostart"; import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToServer } from "@/lib/update-utils"; import { check } from "@tauri-apps/plugin-updater"; import { getVersion } from "@tauri-apps/api/app"; +import { invoke } from "@tauri-apps/api/core"; import { tempDir } from "@tauri-apps/api/path"; import { tauriCmd, type DirCheckResult, type ProtonUpdateInfo, type MigrateProgress, type PortDef, type FirewallStatus } from "@/lib/tauri-commands"; import { getServerFirewallPorts } from "@/lib/firewall-utils"; @@ -44,6 +45,7 @@ import { import { open } from "@tauri-apps/plugin-dialog"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; +import { useAppStore } from "@/store/useAppStore"; // --------------------------------------------------------------------------- // Helpers @@ -428,17 +430,27 @@ interface ToolPathFieldProps { validateFn: (path: string) => Promise; validLabel?: string; invalidLabel?: string; + /** When provided and validation fails, show a dialog offering to install + * rather than a toast. The callback receives the typed path as targetDir + * and should return the final installed path to save. */ + onInstallOffer?: (targetDir: string) => Promise; + installOfferTitle?: string; + installOfferBody?: string; } function ToolPathField({ label, settingKey, placeholder, hint, pickDirectory = false, validateFn, validLabel = "Valid", invalidLabel = "Validation failed — check the path.", + onInstallOffer, installOfferTitle = "Not Found", installOfferBody, }: ToolPathFieldProps) { const [value, setValue] = useState(""); const [original, setOriginal] = useState(""); const [verifying, setVerifying] = useState(false); const [valid, setValid] = useState(null); + const [showInstallDialog, setShowInstallDialog] = useState(false); + const [installing, setInstalling] = useState(false); + const [installError, setInstallError] = useState(null); useEffect(() => { getAppSetting(settingKey).then((v) => { const val = v ?? ""; setValue(val); setOriginal(val); }); @@ -461,17 +473,44 @@ function ToolPathField({ await setAppSetting(settingKey, value.trim()); setOriginal(value.trim()); toast.success(`${label} saved.`); + } else if (onInstallOffer) { + setInstallError(null); + setShowInstallDialog(true); } else { toast.error(invalidLabel); } } catch (e) { - setValid(false); - toast.error(`Verification failed: ${e}`); + if (onInstallOffer) { + setInstallError(null); + setShowInstallDialog(true); + } else { + setValid(false); + toast.error(`Verification failed: ${e}`); + } } finally { setVerifying(false); } }; + const handleInstall = async () => { + if (!onInstallOffer) return; + setInstalling(true); + setInstallError(null); + try { + const newPath = await onInstallOffer(value.trim()); + await setAppSetting(settingKey, newPath); + setValue(newPath); + setOriginal(newPath); + setValid(true); + setShowInstallDialog(false); + toast.success(`${label} installed successfully.`); + } catch (e) { + setInstallError(String(e)); + } finally { + setInstalling(false); + } + }; + const dirty = value !== original; return ( @@ -499,7 +538,47 @@ function ToolPathField({
{valid === true &&

{validLabel}

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

{invalidLabel}

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

{invalidLabel}

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

{installError}

+ )} + + + + +
+
+ )}
); } @@ -764,7 +843,8 @@ const AUTO_CHECK_OPTIONS = [ { value: "startup_hourly", label: "On startup + hourly" }, ]; -function ServerUpdatesSection() { +function ServerUpdatesSection({ onPreDownload }: { onPreDownload?: () => void }) { + const asaCacheOpLabel = useAppStore((s) => s.asaCacheOpLabel); const [checking, setChecking] = useState(false); const [cachedBuild, setCached] = useState(""); const [lastChecked, setLastChecked] = useState(""); @@ -916,14 +996,26 @@ function ServerUpdatesSection() {
- - {hasCacheInstalled === false && ( + {!cachedBuild && !asaCacheOpLabel && ( - No server cache installed yet — install a server first. + No server files cached yet — this will download them via SteamCMD. )}
@@ -987,11 +1079,18 @@ const APP_UPDATE_MODE_OPTIONS = [ ]; function AppUpdateSection() { - const [mode, setMode] = useState("startup"); - const [checking, setCheck] = useState(false); + const [mode, setMode] = useState("startup"); + const [checking, setChecking] = useState(false); + const [currentVersion, setCurrentVersion] = useState(""); + const [installMethod, setInstallMethod] = useState("binary"); + const [updateResult, setUpdateResult] = useState<{ version: string; body?: string | null; available: boolean } | null>(null); + const [installing, setInstalling] = useState(false); + const [installDone, setInstallDone] = useState(false); useEffect(() => { getAppSetting("app_update_check_mode").then((v) => setMode(v ?? "startup")); + getVersion().then(setCurrentVersion).catch(() => {}); + invoke("get_install_method").then(setInstallMethod).catch(() => {}); }, []); const handleModeChange = async (value: string) => { @@ -1000,34 +1099,37 @@ function AppUpdateSection() { }; const handleCheckNow = async () => { - setCheck(true); + setChecking(true); + setUpdateResult(null); try { const update = await check(); if (!update) { + setUpdateResult({ version: currentVersion, available: false }); toast.success("LokiASAM is up to date."); } else { - const toastId = `app-update-${update.version}`; - const firstLine = (update.body ?? "").split("\n").find((l) => l.trim()) ?? ""; - const description = firstLine.length > 120 ? firstLine.slice(0, 120) + "…" : firstLine || "A new version is ready to install."; - toast.info(`LokiASAM ${update.version} is available`, { - id: toastId, description, duration: Infinity, - action: { - label: "Download & Install", - onClick: async () => { - toast.dismiss(toastId); - const loadingId = toast.loading("Downloading update…"); - try { - await update.downloadAndInstall(); - toast.dismiss(loadingId); - toast.success("Update installed. Restart LokiASAM to apply it.", { duration: Infinity }); - } catch (e) { toast.dismiss(loadingId); toast.error(`Update failed: ${e}`); } - }, - }, - cancel: { label: "Later", onClick: () => {} }, - }); + setUpdateResult({ version: update.version, body: update.body, available: true }); + toast.info(`LokiASAM ${update.version} is available.`); } } catch (e) { toast.error(`Update check failed: ${e}`); } - finally { setCheck(false); } + finally { setChecking(false); } + }; + + const handleInstall = async () => { + setChecking(true); + try { + const update = await check(); + if (!update) { toast.info("No update available."); return; } + setInstalling(true); + const loadingId = toast.loading("Downloading update…"); + try { + await update.downloadAndInstall(); + toast.dismiss(loadingId); + toast.success("Update installed. Restart LokiASAM to apply it.", { duration: Infinity }); + setInstallDone(true); + } catch (e) { toast.dismiss(loadingId); toast.error(`Update failed: ${e}`); } + finally { setInstalling(false); } + } catch (e) { toast.error(`Update check failed: ${e}`); } + finally { setChecking(false); } }; return ( @@ -1035,11 +1137,55 @@ function AppUpdateSection() {

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

- + +
+ + + {updateResult?.available && installMethod !== "pkgbuild" && ( + + )} +
+ + {updateResult && ( +
+ {currentVersion && ( +
+ Current: + {currentVersion} + → + {updateResult.version} +
+ )} + {updateResult.available ? ( + installMethod === "pkgbuild" ? ( +

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

+ ) : ( +

A newer version is available.

+ ) + ) : ( +

You are on the latest version.

+ )} +
+ )} +
@@ -1060,6 +1206,187 @@ function AppUpdateSection() { ); } +// --------------------------------------------------------------------------- +// ASA Server Cache row — Install / Reinstall / Verify the shared server cache +// --------------------------------------------------------------------------- + +// Persists the active operation type across navigation (component remounts) +let _asaCacheActiveOp: "install" | "reinstall" | "verify" = "install"; + +const CACHE_OP_LABELS: Record = { + install: "Installing ASA cache…", + reinstall: "Reinstalling ASA cache…", + verify: "Verifying ASA cache…", +}; + +function AsaServerCacheRow({ autoStart = false, onAutoStartConsumed }: { autoStart?: boolean; onAutoStartConsumed?: () => void }) { + const [cachedBuild, setCachedBuild] = useState(""); + const [baseDir, setBaseDir] = useState(""); + const [phase, setPhase] = useState<"idle" | "running" | "done" | "error">("idle"); + const [operation, setOperation] = useState<"install" | "reinstall" | "verify">("install"); + const [autoStartPending, setAutoStartPending] = useState(false); + // True only when we reconnected to an op that was already running (navigation case). + // When runCacheOp starts the op directly, it manages phase itself — no polling needed. + const reconnectedRef = useRef(false); + const containerRef = useRef(null); + + const getCacheDir = useCallback((dir: string) => { + if (!dir) return ""; + const sep = dir.includes("\\") ? "\\" : "/"; + return `${dir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; + }, []); + + const runCacheOp = useCallback(async (op: "install" | "reinstall" | "verify") => { + if (!baseDir) { toast.error("Base directory not configured."); return; } + reconnectedRef.current = false; // Direct mode: runCacheOp manages phase + _asaCacheActiveOp = op; + setOperation(op); + setPhase("running"); + try { + if (op === "reinstall") { + await tauriCmd.deleteDirectory(getCacheDir(baseDir)).catch(() => {}); + await setAppSetting("asa_cached_build_id", ""); + } + const newBuild = await runAsaCacheUpdate(CACHE_OP_LABELS[op]); + if (newBuild) { + setCachedBuild(newBuild); + setPhase("done"); + const label = op === "reinstall" ? "reinstalled" : op === "install" ? "installed" : "verified"; + toast.success(`Server cache ${label} (build ${newBuild}).`); + } else { + setPhase("error"); + } + } catch (e) { + if (!String(e).includes("Aborted")) toast.error(`Cache ${op} failed: ${e}`); + setPhase("error"); + } + }, [baseDir, getCacheDir]); + + const load = useCallback(async () => { + const [build, dir] = await Promise.all([ + getAppSetting("asa_cached_build_id"), + getAppSetting("base_dir"), + ]); + setCachedBuild(build ?? ""); + setBaseDir(dir ?? ""); + return dir ?? ""; + }, []); + + // On mount: check if a cache operation is already running in the background + // (e.g. user navigated away and came back). Restore running state if so. + useEffect(() => { + if (autoStart) { + onAutoStartConsumed?.(); + setAutoStartPending(true); + } + load().then((dir) => { + if (autoStart && dir) return; // autoStartPending will drive the start via the effect below + tauriCmd.getRunningOps().then((ops) => { + if (ops.includes("check")) { + reconnectedRef.current = true; + setOperation(_asaCacheActiveOp); + setPhase("running"); + } + }).catch(() => {}); + }); + }, [load]); // eslint-disable-line react-hooks/exhaustive-deps + + // After an auto-start navigation: once baseDir is loaded, scroll into view and start install. + useEffect(() => { + if (!autoStartPending || !baseDir) return; + setAutoStartPending(false); + containerRef.current?.scrollIntoView({ behavior: "smooth", block: "start" }); + runCacheOp("install"); + }, [autoStartPending, baseDir, runCacheOp]); + + // Poll for completion — only when we reconnected to a background op. + // When runCacheOp started the op directly, it awaits the result itself. + useEffect(() => { + if (phase !== "running" || !reconnectedRef.current) return; + const interval = setInterval(async () => { + try { + const ops = await tauriCmd.getRunningOps(); + if (!ops.includes("check")) { + clearInterval(interval); + reconnectedRef.current = false; + // Brief delay so the JS side of runAsaCacheUpdate() can finish saving + // asa_cached_build_id before we read it. + await new Promise((r) => setTimeout(r, 400)); + const build = await getAppSetting("asa_cached_build_id"); + setCachedBuild(build ?? ""); + setPhase(build ? "done" : "error"); + } + } catch { /* ignore poll errors */ } + }, 2000); + return () => clearInterval(interval); + }, [phase]); + + const hasCache = !!cachedBuild; + const busy = phase === "running"; + + return ( +
+
+
+

+ ARK: Survival Ascended Server +

+

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

+

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

+
+
+ {busy && ( + + )} + {hasCache && ( + + )} + +
+
+ {(busy || phase === "done") && ( + + )} +
+ ); +} + // --------------------------------------------------------------------------- // SteamCMD reinstall row (shown inline under the SteamCMD path field) // --------------------------------------------------------------------------- @@ -1069,14 +1396,16 @@ function SteamcmdReinstallRow() { const [done, setDone] = useState(false); const handleReinstall = async () => { - const baseDir = await getAppSetting("base_dir"); - if (!baseDir) { toast.error("Base directory not configured."); return; } - const sep = baseDir.includes("\\") ? "\\" : "/"; - const targetDir = `${baseDir.replace(/[/\\]$/, "")}${sep}steamcmd`; + const currentPath = await getAppSetting("steamcmd_path"); + if (!currentPath) { toast.error("SteamCMD path not configured."); return; } + // Reinstall to the same directory the current executable lives in + const targetDir = currentPath.replace(/[/\\][^/\\]+$/, ""); setReinstalling(true); setDone(false); try { await tauriCmd.installSteamcmd(targetDir); - const newPath = targetDir + (navigator.userAgent.includes("Windows") ? "\\steamcmd.exe" : "/steamcmd.sh"); + const sep = targetDir.includes("\\") ? "\\" : "/"; + const exe = navigator.userAgent.includes("Windows") ? "steamcmd.exe" : "steamcmd.sh"; + const newPath = `${targetDir}${sep}${exe}`; await setAppSetting("steamcmd_path", newPath); setDone(true); toast.success("SteamCMD reinstalled successfully."); @@ -1112,13 +1441,171 @@ function SteamcmdReinstallRow() { ); } +// --------------------------------------------------------------------------- +// Proton-GE install/reinstall row (managed installs only, Linux only) +// --------------------------------------------------------------------------- + +function ProtonGeInstallRow() { + const [protonPath, setProtonPath] = useState(""); + const [isManaged, setIsManaged] = useState(false); + const [phase, setPhase] = useState<"idle" | "running" | "done" | "error">("idle"); + const [isReinstall, setIsReinstall] = useState(false); + const [showManagedConfirm, setShowManagedConfirm] = useState(false); + + useEffect(() => { + Promise.all([ + getAppSetting("proton_path"), + getAppSetting("proton_ge_managed"), + ]).then(([p, managed]) => { + setProtonPath(p ?? ""); + setIsManaged(managed === "true"); + }); + }, []); + + const handleConfirmManaged = async () => { + await setAppSetting("proton_ge_managed", "true"); + setIsManaged(true); + setShowManagedConfirm(false); + toast.success("LokiASAM will now manage Proton-GE updates."); + }; + + const hasInstall = !!protonPath; + const busy = phase === "running"; + + const handleRun = async (reinstall: boolean) => { + const baseDir = await getAppSetting("base_dir"); + if (!baseDir) { toast.error("Base directory not configured."); return; } + const sep = baseDir.includes("\\") ? "\\" : "/"; + // Reinstall: go back to the same parent directory we deleted from. + // Fresh install: fall back to the managed default location. + const targetDir = protonPath + ? protonPath.replace(/[/\\][^/\\]+$/, "") + : `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}proton`; + setIsReinstall(reinstall); + setPhase("running"); + try { + if (reinstall && protonPath) { + await tauriCmd.deleteDirectory(protonPath).catch(() => {}); + } + const newPath = await tauriCmd.downloadProtonGe(targetDir); + await setAppSetting("proton_path", newPath); + setProtonPath(newPath); + setPhase("done"); + toast.success(`Proton-GE ${reinstall ? "reinstalled" : "installed"} successfully.`); + } catch (e) { + if (!String(e).includes("Aborted")) toast.error(`Proton-GE ${reinstall ? "reinstall" : "install"} failed: ${e}`); + setPhase("error"); + } + }; + + if (!isManaged) { + return ( +
+
+ +

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

+
+
+ +
+ { if (!v) setShowManagedConfirm(false); }}> + + + + Allow LokiASAM to Manage Proton-GE? + + + + Switching to managed mode gives LokiASAM full control over your Proton-GE installation — it may download new versions and replace the current one. + + + If this Proton-GE was installed by Steam, Lutris, or another tool, LokiASAM may overwrite it and break other applications that depend on it. + + + For the safest experience, let LokiASAM download and install its own dedicated copy of Proton-GE instead. + + + + + + + + + +
+ ); + } + + return ( +
+
+

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

+
+ {busy && ( + + )} + +
+
+ {(busy || phase === "done") && ( + + )} +
+ ); +} + // --------------------------------------------------------------------------- // Amazon Root CA certificate install row // --------------------------------------------------------------------------- function CertInstallRow() { - const [phase, setPhase] = useState<"idle" | "downloading" | "installing" | "done" | "error">("idle"); - const [error, setError] = useState(""); + const [phase, setPhase] = useState<"idle" | "downloading" | "installing" | "done" | "error">("idle"); + const [error, setError] = useState(""); + const [isInstalled, setIsInstalled] = useState(false); + + useEffect(() => { + (async () => { + const protonPath = IS_LINUX ? (await getAppSetting("proton_path")) ?? undefined : undefined; + const prefixPath = IS_LINUX ? (await getAppSetting("proton_prefix_path")) ?? undefined : undefined; + const installed = await tauriCmd.checkAmazonRootCaInstalled(protonPath, prefixPath).catch(() => false); + setIsInstalled(installed); + })(); + }, []); const handleInstall = async () => { setError(""); @@ -1140,6 +1627,7 @@ function CertInstallRow() { : undefined); await tauriCmd.installAmazonRootCa(certPath, protonPath, resolvedPrefix); setPhase("done"); + setIsInstalled(true); toast.success("Amazon Root CA 1 installed successfully."); } catch (e) { setError(String(e)); @@ -1181,7 +1669,7 @@ function CertInstallRow() { ? (phase === "downloading" ? "Downloading…" : "Installing…") : phase === "done" ? "Installed" - : "Install / Reinstall"} + : isInstalled ? "Reinstall Certs" : "Install Certs"}
{phase === "error" && ( @@ -1279,7 +1767,7 @@ function FirewallRepairRow() { : allGood ? : } - {phase === "checking" ? "Checking…" : allGood ? "All Good" : "Check & Repair"} + {phase === "checking" ? "Checking…" : allGood ? "All Good" : "Check & Repair Firewall"}
@@ -1340,13 +1828,14 @@ function FirewallRepairRow() { // --------------------------------------------------------------------------- function ProtonGeUpdateSection() { - const [protonPath, setProtonPath] = useState(""); - const [isManaged, setIsManaged] = useState(false); - const [checking, setChecking] = useState(false); - const [updateInfo, setUpdateInfo] = useState(null); - const [downloading, setDownloading] = useState(false); - const [downloadDone, setDownloadDone] = useState(false); - const [checkMode, setCheckMode] = useState("startup_hourly"); + const [protonPath, setProtonPath] = useState(""); + const [isManaged, setIsManaged] = useState(false); + const [checking, setChecking] = useState(false); + const [updateInfo, setUpdateInfo] = useState(null); + const [downloading, setDownloading] = useState(false); + const [downloadDone, setDownloadDone] = useState(false); + const [checkMode, setCheckMode] = useState("disabled"); + const [showManagedConfirm, setShowManagedConfirm] = useState(false); useEffect(() => { Promise.all([ @@ -1356,7 +1845,7 @@ function ProtonGeUpdateSection() { ]).then(([p, managed, mode]) => { setProtonPath(p ?? ""); setIsManaged(managed === "true"); - setCheckMode(mode ?? "startup_hourly"); + setCheckMode(mode ?? "disabled"); }); }, []); @@ -1366,15 +1855,18 @@ function ProtonGeUpdateSection() { try { const info = await tauriCmd.checkProtonGeUpdate(protonPath); setUpdateInfo(info); + if (info.updateAvailable) { + toast.info(`Proton-GE ${info.latestVersion} is available.`); + } else { + toast.success("Proton-GE is up to date."); + } } catch (e) { toast.error(`Failed to check for updates: ${e}`); } finally { setChecking(false); } }; const handleDownload = async () => { - const baseDir = await getAppSetting("base_dir"); - if (!baseDir) { toast.error("Base directory not configured."); return; } - const sep = baseDir.includes("\\") ? "\\" : "/"; - const targetDir = `${baseDir.replace(/[/\\]$/, "")}${sep}proton`; + if (!protonPath) { toast.error("Proton-GE path not configured."); return; } + const targetDir = protonPath.replace(/[/\\][^/\\]+$/, ""); setDownloading(true); setDownloadDone(false); try { const newPath = await tauriCmd.downloadProtonGe(targetDir); @@ -1389,9 +1881,10 @@ function ProtonGeUpdateSection() { finally { setDownloading(false); } }; - const handleTakeOwnership = async () => { + const handleConfirmManaged = async () => { await setAppSetting("proton_ge_managed", "true"); setIsManaged(true); + setShowManagedConfirm(false); toast.success("LokiASAM will now manage Proton-GE updates."); }; @@ -1424,18 +1917,25 @@ function ProtonGeUpdateSection() {
)} - {/* External path notice */} - {looksExternal && !isManaged && ( -
-
- + {/* Unmanaged notice — shown whenever isManaged is false */} + {!isManaged && ( +
+
+

- This Proton-GE path is outside LokiASAM's managed directory. Automatic updates are suppressed. + Proton-GE is in unmanaged mode — LokiASAM will not check for or update it. + {looksExternal && " The current path is outside LokiASAM's managed directory."}

-
)} @@ -1469,10 +1969,10 @@ function ProtonGeUpdateSection() { {/* Action buttons */}
- {(updateInfo?.updateAvailable || (!protonPath && updateInfo)) && (isManaged || !looksExternal) && ( @@ -1496,7 +1996,7 @@ function ProtonGeUpdateSection() {
{/* Auto-check mode */} -
+

Automatically check GitHub for new GE-Proton releases. @@ -1519,6 +2019,41 @@ function ProtonGeUpdateSection() {

+ {/* Managed confirmation dialog */} + { if (!v) setShowManagedConfirm(false); }}> + + + + Allow LokiASAM to Manage Proton-GE? + + + + Switching to managed mode gives LokiASAM full control over your Proton-GE installation — it may download new versions and replace the current one. + + + If this Proton-GE was installed by Steam, Lutris, or another tool, LokiASAM may overwrite it and break other applications that depend on it. + + + For the safest experience, let LokiASAM download and install its own dedicated copy of Proton-GE instead. + + + + + + + + + + {/* Download output */} {(downloading || downloadDone) && ( @@ -1770,53 +2305,59 @@ function AppImageIntegrationSection() { }; return ( -
-

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

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

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

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

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

+
+ ) : ( -
-

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

-
- ) : ( - - )} -
+ )} +
+ ); } @@ -1897,16 +2438,16 @@ function StartupSection() {

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

{pref === "never" && (

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

)} @@ -1949,6 +2490,21 @@ type TabId = typeof TABS[number]["id"]; export default function SettingsPage() { const [activeTab, setActiveTab] = useState("general"); const [matrixRefreshKey, setMatrixRefreshKey] = useState(0); + const [autoStartCache, setAutoStartCache] = useState(false); + const scrollContainerRef = useRef(null); + const skipScrollToTopRef = useRef(false); + + // Reset scroll position on tab change, unless the tab switch came from the + // pre-download button (which scrolls to the cache row instead). + useEffect(() => { + if (skipScrollToTopRef.current) { + skipScrollToTopRef.current = false; + return; + } + if (scrollContainerRef.current) { + scrollContainerRef.current.scrollTop = 0; + } + }, [activeTab]); return (
@@ -1971,7 +2527,7 @@ export default function SettingsPage() {
-
+
{/* General tab */} {activeTab === "general" && (
@@ -2001,11 +2557,23 @@ export default function SettingsPage() {
+ setAutoStartCache(false)} /> + tauriCmd.validateSteamcmd(p)} - validLabel="SteamCMD is valid" invalidLabel="SteamCMD not found at this path — check the path." + validLabel="SteamCMD is valid" + onInstallOffer={async (typedPath) => { + const isExe = /[/\\](steamcmd\.sh|steamcmd\.exe)$/i.test(typedPath); + const targetDir = isExe ? typedPath.replace(/[/\\][^/\\]+$/, "") : typedPath; + await tauriCmd.installSteamcmd(targetDir); + const sep = targetDir.includes("\\") ? "\\" : "/"; + const exe = navigator.userAgent.includes("Windows") ? "steamcmd.exe" : "steamcmd.sh"; + return `${targetDir}${sep}${exe}`; + }} + installOfferTitle="SteamCMD Not Found" + installOfferBody="No SteamCMD executable was found at this path. Would you like to install it here?" /> {IS_LINUX && ( @@ -2016,8 +2584,16 @@ export default function SettingsPage() { placeholder="/path/to/GE-Proton9-x" hint="Proton-GE installation used to run the Windows ASA server binary on Linux." pickDirectory validateFn={(p) => tauriCmd.validateProtonPath(p)} - validLabel="Proton-GE is valid" invalidLabel="Not a valid Proton-GE directory — check the path." + validLabel="Proton-GE is valid" + onInstallOffer={async (targetDir) => { + const newPath = await tauriCmd.downloadProtonGe(targetDir); + await setAppSetting("proton_ge_managed", "true"); + return newPath; + }} + installOfferTitle="Proton-GE Not Found" + installOfferBody="No Proton-GE installation was found at this path. Would you like to install it here?" /> + )} @@ -2034,19 +2610,11 @@ export default function SettingsPage() {
-
+
- {IS_LINUX && ( -
- -
- )} + {IS_LINUX && }
)} @@ -2054,7 +2622,7 @@ export default function SettingsPage() { {activeTab === "updates" && (
- + { skipScrollToTopRef.current = true; setAutoStartCache(true); setActiveTab("general"); }} />
diff --git a/src/components/layout/CloseWarningManager.tsx b/src/components/layout/CloseWarningManager.tsx index ec79982..a879dbf 100644 --- a/src/components/layout/CloseWarningManager.tsx +++ b/src/components/layout/CloseWarningManager.tsx @@ -10,14 +10,27 @@ import { DialogTitle, DialogFooter, } from "@/components/ui/dialog"; +import { TriangleAlert } from "lucide-react"; import { getServers, getAppSetting } from "@/lib/db"; import { tauriCmd } from "@/lib/tauri-commands"; +const TOOL_OP_LABELS: Record = { + check: "ASA Server Cache install", + steamcmd_install: "SteamCMD install", + proton_download: "Proton-GE install", +}; + +function toolOpLabel(key: string): string { + return TOOL_OP_LABELS[key] ?? key; +} + export function CloseWarningManager() { - const [showWarning, setShowWarning] = useState(false); + const [showWarning, setShowWarning] = useState(false); const [installingCount, setInstallingCount] = useState(0); - const installingIds = useRef([]); - const allowClose = useRef(false); + const [toolOps, setToolOps] = useState([]); + const [aborting, setAborting] = useState(false); + const installingIds = useRef([]); + const allowClose = useRef(false); const checkActiveInstalls = async (): Promise<{ count: number; ids: string[] }> => { const servers = await getServers().catch(() => []); @@ -27,6 +40,25 @@ export function CloseWarningManager() { return { count: active.length, ids: active.map((s) => s.id) }; }; + const checkAndWarn = async (): Promise => { + const [{ count, ids }, runningOps] = await Promise.all([ + checkActiveInstalls(), + tauriCmd.getRunningOps().catch(() => [] as string[]), + ]); + + const ops = runningOps.filter((k) => !k.startsWith("server_")); + + if (count > 0 || ops.length > 0) { + installingIds.current = ids; + setInstallingCount(count); + setToolOps(ops); + setAborting(false); + setShowWarning(true); + return true; + } + return false; + }; + useEffect(() => { if (typeof window === "undefined") return; @@ -50,33 +82,22 @@ export function CloseWarningManager() { ]); // If close-to-tray is active, the Rust handler already hid the window. - // Nothing more to do here — silently swallow the close event. + // Background tool operations can safely keep running — nothing to warn about. if (closeToTray !== "false" && setupDone === "true") return; - // close_to_tray is off (or setup not done): check for active installs. - const { count, ids } = await checkActiveInstalls(); - if (count > 0) { - installingIds.current = ids; - setInstallingCount(count); - setShowWarning(true); - return; + // close_to_tray is off → app will actually exit. Warn if anything is running. + const warned = await checkAndWarn(); + if (!warned) { + await tauriCmd.forceQuit(); } - - // No active installs, close_to_tray is off → exit the app. - await tauriCmd.forceQuit(); }) .then((fn) => { unlistenClose = fn; }); }); import("@tauri-apps/api/event").then(({ listen }) => { listen("tray-quit-requested", async () => { - const { count, ids } = await checkActiveInstalls(); - if (count > 0) { - installingIds.current = ids; - setInstallingCount(count); - setShowWarning(true); - } else { - // No active installs — exit immediately + const warned = await checkAndWarn(); + if (!warned) { await tauriCmd.forceQuit(); } }).then((fn) => { unlistenTrayQuit = fn; }); @@ -88,10 +109,12 @@ export function CloseWarningManager() { }; }, []); - const handleCancelAndExit = async () => { - for (const id of installingIds.current) { - await tauriCmd.abortOperation(`server_${id}`).catch(() => {}); - } + const handleAbortAndClose = async () => { + setAborting(true); + await Promise.allSettled([ + ...installingIds.current.map((id) => tauriCmd.abortOperation(`server_${id}`)), + ...toolOps.map((op) => tauriCmd.abortOperation(op)), + ]); setShowWarning(false); allowClose.current = true; await tauriCmd.forceQuit(); @@ -101,34 +124,60 @@ export function CloseWarningManager() { setShowWarning(false); }; + const hasServerInstalls = installingCount > 0; + const hasToolOps = toolOps.length > 0; + return ( - { if (!open) setShowWarning(false); }}> - + { if (!open && !aborting) setShowWarning(false); }}> + - Install in Progress - - A server installation is running. Choose to cancel it and exit, or keep the app running. + + + Operation{hasServerInstalls && hasToolOps ? "s" : installingCount + toolOps.length > 1 ? "s" : ""} In Progress + + + + Closing the app will abort the following and may leave files in an incomplete state: + +
    + {hasServerInstalls && ( +
  • + {installingCount === 1 + ? "1 server install / update" + : `${installingCount} server installs / updates`} +
  • + )} + {toolOps.map((op) => ( +
  • + {toolOpLabel(op)} +
  • + ))} +
-

- {installingCount === 1 - ? "A server install is currently running in the background." - : `${installingCount} server installs are currently running in the background.`}{" "} - Closing the app will cancel {installingCount === 1 ? "it" : "them"}. -

- -
diff --git a/src/components/layout/DisableContextMenu.tsx b/src/components/layout/DisableContextMenu.tsx index 01f1af8..da6e14d 100644 --- a/src/components/layout/DisableContextMenu.tsx +++ b/src/components/layout/DisableContextMenu.tsx @@ -127,7 +127,7 @@ export function DisableContextMenu() { style={{ top: menu.y, left: menu.x, - background: "rgba(8,8,25,0.96)", + background: "var(--popover)", border: "1px solid rgba(var(--neon-purple-rgb),0.35)", backdropFilter: "blur(16px)", boxShadow: "0 4px 20px rgba(0,0,0,0.6), 0 0 10px rgba(var(--neon-purple-rgb),0.08)", diff --git a/src/components/layout/TopBar.tsx b/src/components/layout/TopBar.tsx index 7b7fd3c..79c1e38 100644 --- a/src/components/layout/TopBar.tsx +++ b/src/components/layout/TopBar.tsx @@ -7,7 +7,7 @@ import { useAppStore } from "@/store/useAppStore"; export function TopBar() { const { data: servers = [] } = useServers(); - const asaCacheUpdateInProgress = useAppStore((s) => s.asaCacheUpdateInProgress); + const asaCacheOpLabel = useAppStore((s) => s.asaCacheOpLabel); const statsLiveBuffers = useAppStore((s) => s.statsLiveBuffers); const total = servers.length; @@ -67,11 +67,11 @@ export function TopBar() {
))} - {asaCacheUpdateInProgress && ( + {asaCacheOpLabel && (
- Checking ASA updates… + {asaCacheOpLabel}
)} diff --git a/src/components/shared/CommandOutputPanel.tsx b/src/components/shared/CommandOutputPanel.tsx index c07c348..5988945 100644 --- a/src/components/shared/CommandOutputPanel.tsx +++ b/src/components/shared/CommandOutputPanel.tsx @@ -87,7 +87,7 @@ export function CommandOutputPanel({ canceled = false, clearBufferOnClose = false, }: CommandOutputPanelProps) { - const [lines, setLines] = useState(() => _buffers.get(eventChannel) ?? []); + const [lines, setLines] = useState(() => [...(_buffers.get(eventChannel) ?? [])]); const [collapsed, setCollapsed] = useState(defaultCollapsed); const [copied, setCopied] = useState(false); const [autoScroll, setAutoScroll] = useState(true); diff --git a/src/components/shared/NotificationMatrix.tsx b/src/components/shared/NotificationMatrix.tsx index d06ac44..d1ab10b 100644 --- a/src/components/shared/NotificationMatrix.tsx +++ b/src/components/shared/NotificationMatrix.tsx @@ -14,7 +14,7 @@ import { useState, useEffect, useCallback, forwardRef, useImperativeHandle } from "react"; import { toast } from "sonner"; -import { Loader2, Bell, Monitor, MessageSquare, Mail } from "lucide-react"; +import { Loader2, AppWindow, Bell, Monitor, MessageSquare, Mail } from "lucide-react"; import { getNotificationConfigs, saveGlobalChannelEvents, @@ -36,7 +36,7 @@ interface ChannelDef { } const CHANNELS: ChannelDef[] = [ - { id: "in_app", label: "In-App", Icon: Bell, description: "Toast popup inside LokiASAM" }, + { id: "in_app", label: "In-App", Icon: AppWindow, description: "Toast popup inside LokiASAM" }, { id: "bell", label: "Bell", Icon: Bell, description: "Show as unread in the bell badge and popup" }, { id: "desktop", label: "Desktop", Icon: Monitor, description: "OS system notification" }, { id: "discord", label: "Discord", Icon: MessageSquare, description: "Discord webhook" }, @@ -49,7 +49,7 @@ const ALL_EVENTS = Object.values(NOTIFICATION_EVENTS) as NotificationEventType[] const CHANNEL_DEFAULTS: Record = { in_app: ALL_EVENTS, bell: ALL_EVENTS, - desktop: ["server_started", "server_crashed", "update_available", "update_started", "update_failed", "backup_completed", "backup_failed"], + desktop: [], discord: ALL_EVENTS, email: ALL_EVENTS, }; @@ -172,6 +172,23 @@ function NotificationMatrix({ onSaved, onChange, refreshKey }, ref) { } }, [channelEvents, onChange, onSaved]); + const handleToggleAll = useCallback((channel: ChannelId) => { + const allOn = ALL_EVENTS.every((e) => channelEvents[channel].has(e)); + const newSet = allOn ? new Set() : new Set(ALL_EVENTS); + const nextEvents = { ...channelEvents, [channel]: newSet }; + setChannelEvents(nextEvents); + + if (onChange) { + onChange(Object.fromEntries( + Object.entries(nextEvents).map(([ch, set]) => [ch, [...set]]) + )); + } else { + saveGlobalChannelEvents(channel, [...newSet]) + .then(() => onSaved?.()) + .catch((err) => toast.error("Failed to save notification settings", { description: String(err) })); + } + }, [channelEvents, onChange, onSaved]); + if (loading) { return (
@@ -197,6 +214,8 @@ function NotificationMatrix({ onSaved, onChange, refreshKey }, ref) { const disabled = (ch.id === "discord" && !discordConfigured) || (ch.id === "email" && !emailConfigured); + const allOn = ALL_EVENTS.every((e) => channelEvents[ch.id].has(e)); + const someOn = !allOn && ALL_EVENTS.some((e) => channelEvents[ch.id].has(e)); return ( {ch.label} - {disabled && ( + {disabled ? ( (not configured) + ) : ( + { if (el) el.indeterminate = someOn; }} + onChange={() => handleToggleAll(ch.id)} + className="w-3 h-3 mt-0.5" + style={{ accentColor: "var(--neon-purple)", cursor: "pointer" }} + title={allOn ? `Disable all ${ch.label} notifications` : `Enable all ${ch.label} notifications`} + /> )}
diff --git a/src/components/wizard/SetupWizard.tsx b/src/components/wizard/SetupWizard.tsx index 1b19155..ef1cdef 100644 --- a/src/components/wizard/SetupWizard.tsx +++ b/src/components/wizard/SetupWizard.tsx @@ -33,7 +33,7 @@ import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { - Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, + Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter, } from "@/components/ui/dialog"; import { CommandOutputPanel } from "@/components/shared/CommandOutputPanel"; import { useSetupStore } from "@/store/useSetupStore"; @@ -720,8 +720,8 @@ function ImportVerifyPanel({ Install Now {installingSteamcmd && ( - )} @@ -1702,7 +1702,7 @@ function SteamCmdStep() { boxShadow: steamcmdMode === mode ? "0 0 16px rgba(var(--neon-purple-rgb),0.15)" : "none", }} > -

+

{label}

{desc}

@@ -1734,8 +1734,8 @@ function SteamCmdStep() { {isLoading && outputChannel !== null && ( )} @@ -1834,6 +1834,7 @@ function ProtonGEStep() { const [attempt, setAttempt] = useState(0); const [canceled, setCanceled] = useState(false); const [manuallyAddedPaths, setManuallyAddedPaths] = useState>(new Set()); + const [showManagedConfirm, setShowManagedConfirm] = useState(false); const detectedListRef = useRef(null); const scan = useCallback(async () => { @@ -1984,11 +1985,16 @@ function ProtonGEStep() { key={mode} onClick={() => { if (!isTabLocked) { - setProtonMode(mode); - setProtonPath(""); - setProtonValidated(false); - setError(""); - setShowDownload(false); + if (mode === "managed" && protonMode === "existing") { + // Warn before handing control to LokiASAM + setShowManagedConfirm(true); + } else { + setProtonMode(mode); + setProtonPath(""); + setProtonValidated(false); + setError(""); + setShowDownload(false); + } } }} disabled={isTabLocked} @@ -1999,7 +2005,7 @@ function ProtonGEStep() { boxShadow: protonMode === mode ? "0 0 16px rgba(var(--neon-purple-rgb),0.15)" : "none", }} > -

+

{label}

{desc}

@@ -2033,8 +2039,8 @@ function ProtonGEStep() { {isLoading && showDownload && ( )} @@ -2163,6 +2169,49 @@ function ProtonGEStep() { {error}

)} + + {/* Managed-mode risk confirmation */} + { if (!v) setShowManagedConfirm(false); }}> + + + + Switch to Managed Mode? + + + + LokiASAM will take full control of downloading and updating Proton-GE into its own managed directory. + + + If your current Proton-GE installation is managed by Steam, Lutris, or another tool, LokiASAM may overwrite or conflict with it. + + + Only switch to managed if this is a standalone Proton-GE install you want LokiASAM to fully control. + + + + + + + + +
); } @@ -2377,19 +2426,6 @@ function CertStep() { {phase === "error" ? "Retry Installation" : "Install Certificate"} - {!certSkipped && ( - - )}
)}
@@ -2729,8 +2765,23 @@ function AutoUpdateStep() { asaAutoCheckHours, setAsaAutoCheckHours, appUpdateCheckMode, setAppUpdateCheckMode, protonCheckMode, setProtonCheckMode, + protonMode, setProtonMode, + setStep, } = useSetupStore(); + const [showManagedConfirm, setShowManagedConfirm] = useState(false); + + // Keep proton check mode in sync with the managed/unmanaged choice + useEffect(() => { + if (!IS_LINUX) return; + if (protonMode === "existing") { + setProtonCheckMode("disabled"); + } else if (protonMode === "managed" && protonCheckMode === "disabled") { + setProtonCheckMode("startup"); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [protonMode]); + const asaIntervals = [ { value: "disabled", label: "Disabled" }, { value: "startup", label: "On Startup" }, @@ -2830,22 +2881,84 @@ function AutoUpdateStep() { Check GitHub for new GE-Proton releases. A notification appears when a new version is available.

-
- {protonModes.map(({ value, label }) => ( - - ))} -
+ + Allow LokiASAM to Manage This Proton Install + + + { if (!v) setShowManagedConfirm(false); }}> + + + + Allow LokiASAM to Manage Proton-GE? + + + + Switching to managed mode gives LokiASAM full control over your Proton-GE installation — it may download new versions and replace the current one. + + + If this Proton-GE was installed by Steam, Lutris, or another tool, LokiASAM may overwrite it and break other applications that depend on it. + + + For the safest experience, go back and let LokiASAM download and install its own dedicated copy of Proton-GE instead. + + + + + + + + + + +
+ ) : ( +
+ {protonModes.map(({ value, label }) => ( + + ))} +
+ )}
)} @@ -3067,7 +3180,7 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { steamcmdPath, steamcmdValidated, themePreset, themeAccent, protonPath, protonValidated, protonMode, - certInstalled, certSkipped, + certInstalled, certSkipped, setCertSkipped, setBaseDir, setBackupDir, setSteamcmdPath, setSteamcmdValidated, setProtonPath, setProtonValidated, discordWebhook, @@ -3116,10 +3229,10 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { case 2: return baseDirWritable; case 3: return backupDirWritable; case 4: return steamcmdValidated; - // step 5: Proton-GE (Linux) | Cert (Windows) - case 5: return IS_LINUX ? protonValidated : (certInstalled || certSkipped); - // step 6: Cert (Linux) | Notifications (Windows) - case 6: return IS_LINUX ? (certInstalled || certSkipped) : true; + // step 5: Proton-GE (Linux) | Cert (Windows) — cert always advances (Next becomes Skip) + case 5: return IS_LINUX ? protonValidated : true; + // step 6: Cert (Linux) | Notifications (Windows) — cert always advances + case 6: return true; case 7: return true; // notifications (Linux) / tray (Windows) case 8: return true; // tray (Linux) / updates (Windows) case 9: return true; // updates (Linux) @@ -3279,6 +3392,11 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { setSaving(false); } } else { + // Leaving the cert step without installing — mark as skipped + const certStepIdx = IS_LINUX ? 6 : 5; + if (step === certStepIdx && !certInstalled) { + setCertSkipped(true); + } setDirection(1); nextStep(); } @@ -3406,11 +3524,11 @@ export function SetupWizard({ onComplete }: SetupWizardProps) {
) : ( @@ -3423,19 +3541,18 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { {/* Hide the default Next button when import mode is showing its own button */} {!(step === 2 && importMode && importValid) && (
- {/* Add form */} - {showAdd && ( -
-

New Custom Map

-
+ {/* Add / Edit dialog */} + { if (!open) closeDialog(); }}> + + + + {editTarget ? "Edit Custom Map" : "New Custom Map"} + + +
setDisplayName(e.target.value)} placeholder="e.g. Fjordur Reborn" + disabled={saving} style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} />
@@ -108,8 +142,10 @@ export default function ModMapsPage() { setModId(e.target.value)} + onChange={(e) => setModId(e.target.value.replace(/\D/g, ""))} placeholder="e.g. 965379" + inputMode="numeric" + disabled={saving} style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} />
@@ -119,6 +155,7 @@ export default function ModMapsPage() { value={mapPath} onChange={(e) => setMapPath(e.target.value)} placeholder="e.g. MyMap_WP" + disabled={saving} style={{ background: "var(--surface)", borderColor: "rgba(var(--neon-purple-rgb),0.3)", color: "var(--text-primary)" }} />

@@ -126,49 +163,63 @@ export default function ModMapsPage() {

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

+

Built-in Mod Maps (read-only reference)

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

+

Your Custom Maps

{loading ? ( @@ -198,30 +249,48 @@ export default function ModMapsPage() {
) : (
- {customMaps.map((m, i) => ( -
-
-

{m.display_name}

-

- mod {m.mod_id} · {m.map_path} -

-
- -
- ))} + + + + + + + + + + {customMaps.map((m, i) => ( + + + + + + + ))} + +
Display NameMap Launch ParameterCurseForge Mod ID +
{m.display_name}{m.map_path}{m.mod_id} +
+ + +
+
)}
diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index a624b0a..8064d6b 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -1,6 +1,7 @@ "use client"; import { useState, useEffect, useCallback, useRef } from "react"; +import { useSearchParams } from "next/navigation"; import { Folder, Terminal, Info, Archive, Copy, FolderOpen, CheckCircle2, AlertCircle, Loader2, @@ -19,7 +20,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; -import { CommandOutputPanel } from "@/components/shared/CommandOutputPanel"; +import { CommandOutputPanel, hasOutputBuffer } from "@/components/shared/CommandOutputPanel"; import { NotificationMatrix } from "@/components/shared/NotificationMatrix"; import { getAppSetting, setAppSetting, @@ -716,9 +717,12 @@ function AboutSection() { const [appVersion, setAppVersion] = useState("…"); const [asaBuild, setAsaBuild] = useState("—"); const [protonVersion, setProtonVer] = useState("—"); - const [paths, setPaths] = useState({ + const [protonPath, setProtonPath] = useState("—"); + const [configured, setConfigured] = useState({ baseDir: "—", backupDir: "—", steamcmd: "—", - dbPath: "—", cachePath: "—", logRoot: "—", + }); + const [managed, setManaged] = useState({ + dbPath: "—", cachePath: "—", savesRoot: "—", clustersRoot: "—", logRoot: "—", }); const [copied, setCopied] = useState(false); const versionCache = useBuildVersionCache(); @@ -726,7 +730,7 @@ function AboutSection() { useEffect(() => { getVersion().then(setAppVersion).catch(() => setAppVersion("0.10.0")); (async () => { - const [baseDir, backupDir, steamcmd, asaCached, protonPath, logRoot] = await Promise.all([ + const [baseDir, backupDir, steamcmd, asaCached, protonRaw, logRoot] = await Promise.all([ getAppSetting("base_dir"), getAppSetting("backup_dir"), getAppSetting("steamcmd_path"), @@ -737,20 +741,25 @@ function AboutSection() { setAsaBuild(asaCached || "—"); - if (protonPath) { - const ver = protonPath.replace(/[/\\]$/, "").split(/[/\\]/).pop() ?? ""; + if (protonRaw) { + const ver = protonRaw.replace(/[/\\]$/, "").split(/[/\\]/).pop() ?? ""; setProtonVer(ver || "—"); + setProtonPath(protonRaw); } const sep = (baseDir ?? "").includes("\\") ? "\\" : "/"; const base = (baseDir ?? "").replace(/[/\\]$/, ""); - setPaths({ + setConfigured({ baseDir: baseDir || "—", backupDir: backupDir || "—", steamcmd: steamcmd || "—", - dbPath: base ? `${base}${sep}lokiasam${sep}lokiasam.db` : "—", - cachePath: base ? `${base}${sep}lokiasam${sep}cache${sep}asa-server` : "—", - logRoot: logRoot || "—", + }); + setManaged({ + dbPath: base ? `${base}${sep}lokiasam${sep}lokiasam.db` : "—", + cachePath: base ? `${base}${sep}lokiasam${sep}cache${sep}asa-server` : "—", + savesRoot: base ? `${base}${sep}saves` : "—", + clustersRoot: base ? `${base}${sep}clusters` : "—", + logRoot: logRoot || "—", }); })(); }, []); @@ -770,14 +779,20 @@ function AboutSection() { ...(IS_LINUX ? [{ label: "Proton-GE", value: protonVersion }] : []), ]; - const pathRows = [ - { label: "Base Directory", value: paths.baseDir }, - { label: "Backup Directory", value: paths.backupDir }, - { label: "SteamCMD", value: paths.steamcmd }, - { label: "Database", value: paths.dbPath }, - { label: "Server Cache", value: paths.cachePath }, - { label: "Log Storage", value: paths.logRoot }, - { label: "Bootstrap", value: bootstrapHint }, + const configuredRows = [ + { label: "Base Directory", value: configured.baseDir }, + { label: "Backup Directory", value: configured.backupDir }, + { label: "SteamCMD", value: configured.steamcmd }, + ...(IS_LINUX ? [{ label: "Proton-GE", value: protonPath }] : []), + ]; + + const managedRows = [ + { label: "Database", value: managed.dbPath }, + { label: "Server Cache", value: managed.cachePath }, + { label: "Saves", value: managed.savesRoot }, + { label: "Clusters", value: managed.clustersRoot }, + { label: "Log Storage", value: managed.logRoot }, + { label: "Bootstrap", value: bootstrapHint }, ]; const handleCopy = () => { @@ -785,8 +800,11 @@ function AboutSection() { "Versions:", ...versionRows.map((r) => ` ${r.label}: ${r.value}`), "", - "Directories:", - ...pathRows.map((r) => ` ${r.label}: ${r.value}`), + "Configured Directories:", + ...configuredRows.map((r) => ` ${r.label}: ${r.value}`), + "", + "Managed Directories:", + ...managedRows.map((r) => ` ${r.label}: ${r.value}`), ].join("\n"); navigator.clipboard.writeText(text).catch(() => null); setCopied(true); @@ -824,9 +842,14 @@ function AboutSection() { {versionRows.map((r) => )}
- Directories + Configured Directories
- {pathRows.map((r) => )} + {configuredRows.map((r) => )} +
+ + Managed Directories +
+ {managedRows.map((r) => )}
@@ -1445,7 +1468,14 @@ function SteamcmdReinstallRow() { // Proton-GE install/reinstall row (managed installs only, Linux only) // --------------------------------------------------------------------------- +const PROTON_CHANNEL = "proton://output/download"; + function ProtonGeInstallRow() { + const protonOpLabel = useAppStore((s) => s.protonOpLabel); + const protonOpDone = useAppStore((s) => s.protonOpDone); + const setProtonOpLabel = useAppStore((s) => s.setProtonOpLabel); + const setProtonOpDone = useAppStore((s) => s.setProtonOpDone); + const [protonPath, setProtonPath] = useState(""); const [isManaged, setIsManaged] = useState(false); const [phase, setPhase] = useState<"idle" | "running" | "done" | "error">("idle"); @@ -1462,6 +1492,13 @@ function ProtonGeInstallRow() { }); }, []); + // Restore phase from Zustand on mount so nav-away/back shows the right state. + useEffect(() => { + if (protonOpLabel !== null) setPhase("running"); + else if (protonOpDone) setPhase("done"); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + const handleConfirmManaged = async () => { await setAppSetting("proton_ge_managed", "true"); setIsManaged(true); @@ -1483,6 +1520,8 @@ function ProtonGeInstallRow() { : `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}proton`; setIsReinstall(reinstall); setPhase("running"); + setProtonOpLabel(reinstall ? "Reinstalling Proton-GE…" : "Installing Proton-GE…"); + setProtonOpDone(false); try { if (reinstall && protonPath) { await tauriCmd.deleteDirectory(protonPath).catch(() => {}); @@ -1491,10 +1530,14 @@ function ProtonGeInstallRow() { await setAppSetting("proton_path", newPath); setProtonPath(newPath); setPhase("done"); + setProtonOpLabel(null); + setProtonOpDone(true); toast.success(`Proton-GE ${reinstall ? "reinstalled" : "installed"} successfully.`); } catch (e) { if (!String(e).includes("Aborted")) toast.error(`Proton-GE ${reinstall ? "reinstall" : "install"} failed: ${e}`); setPhase("error"); + setProtonOpLabel(null); + setProtonOpDone(false); } }; @@ -1582,8 +1625,8 @@ function ProtonGeInstallRow() { - {(busy || phase === "done") && ( - + {(phase === "running" || phase === "done" || hasOutputBuffer(PROTON_CHANNEL)) && ( + )} ); @@ -1827,7 +1870,12 @@ function FirewallRepairRow() { // Proton-GE Update section (Linux only) // --------------------------------------------------------------------------- -function ProtonGeUpdateSection() { +function ProtonGeUpdateSection({ autoStart }: { autoStart?: boolean }) { + const protonOpLabel = useAppStore((s) => s.protonOpLabel); + const protonOpDone = useAppStore((s) => s.protonOpDone); + const setProtonOpLabel = useAppStore((s) => s.setProtonOpLabel); + const setProtonOpDone = useAppStore((s) => s.setProtonOpDone); + const [protonPath, setProtonPath] = useState(""); const [isManaged, setIsManaged] = useState(false); const [checking, setChecking] = useState(false); @@ -1836,6 +1884,8 @@ function ProtonGeUpdateSection() { const [downloadDone, setDownloadDone] = useState(false); const [checkMode, setCheckMode] = useState("disabled"); const [showManagedConfirm, setShowManagedConfirm] = useState(false); + const autoStartedRef = useRef(false); + const sectionRef = useRef(null); useEffect(() => { Promise.all([ @@ -1849,6 +1899,23 @@ function ProtonGeUpdateSection() { }); }, []); + // Restore in-progress / done state from Zustand on mount (nav-away/back). + useEffect(() => { + if (protonOpLabel !== null) setDownloading(true); + else if (protonOpDone) setDownloadDone(true); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // Scroll this section into view when navigated here from the update toast. + useEffect(() => { + if (!autoStart) return; + const frame = requestAnimationFrame(() => { + sectionRef.current?.scrollIntoView({ behavior: "smooth", block: "start" }); + }); + return () => cancelAnimationFrame(frame); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + const handleCheckUpdate = async () => { setChecking(true); setUpdateInfo(null); @@ -1868,6 +1935,8 @@ function ProtonGeUpdateSection() { if (!protonPath) { toast.error("Proton-GE path not configured."); return; } const targetDir = protonPath.replace(/[/\\][^/\\]+$/, ""); setDownloading(true); setDownloadDone(false); + setProtonOpLabel("Updating Proton-GE…"); + setProtonOpDone(false); try { const newPath = await tauriCmd.downloadProtonGe(targetDir); await setAppSetting("proton_path", newPath); @@ -1876,8 +1945,14 @@ function ProtonGeUpdateSection() { setIsManaged(true); setDownloadDone(true); setUpdateInfo(null); + setProtonOpLabel(null); + setProtonOpDone(true); toast.success("Proton-GE updated successfully."); - } catch (e) { toast.error(`Proton-GE update failed: ${e}`); } + } catch (e) { + setProtonOpLabel(null); + setProtonOpDone(false); + if (!String(e).includes("Aborted")) toast.error(`Proton-GE update failed: ${e}`); + } finally { setDownloading(false); } }; @@ -1893,6 +1968,14 @@ function ProtonGeUpdateSection() { await setAppSetting("proton_ge_check_mode", value); }; + // When navigated here via the update toast, auto-start the download once settings are loaded. + // eslint-disable-next-line react-hooks/exhaustive-deps + useEffect(() => { + if (!autoStart || autoStartedRef.current || !protonPath || !isManaged) return; + autoStartedRef.current = true; + handleDownload(); + }, [autoStart, protonPath, isManaged]); + // Determine if the current path is inside the managed location const managedPattern = /[/\\]proton[/\\]GE-Proton/; const looksExternal = protonPath && !managedPattern.test(protonPath); @@ -1901,7 +1984,7 @@ function ProtonGeUpdateSection() { : ""; return ( -
+
{/* Current version row */} {currentVersion && (
@@ -1969,14 +2052,14 @@ function ProtonGeUpdateSection() { {/* Action buttons */}
- {(updateInfo?.updateAvailable || (!protonPath && updateInfo)) && (isManaged || !looksExternal) && ( -
); @@ -2488,7 +2571,13 @@ type TabId = typeof TABS[number]["id"]; // --------------------------------------------------------------------------- export default function SettingsPage() { - const [activeTab, setActiveTab] = useState("general"); + const searchParams = useSearchParams(); + const tabParam = searchParams.get("tab") as TabId | null; + const autoUpdateProton = searchParams.get("autoUpdateProton") === "1"; + + const [activeTab, setActiveTab] = useState( + tabParam && TABS.some((t) => t.id === tabParam) ? tabParam : "general" + ); const [matrixRefreshKey, setMatrixRefreshKey] = useState(0); const [autoStartCache, setAutoStartCache] = useState(false); const scrollContainerRef = useRef(null); @@ -2629,7 +2718,7 @@ export default function SettingsPage() { {IS_LINUX && (
- +
)}
diff --git a/src/components/layout/TopBar.tsx b/src/components/layout/TopBar.tsx index 79c1e38..bd123fb 100644 --- a/src/components/layout/TopBar.tsx +++ b/src/components/layout/TopBar.tsx @@ -8,6 +8,7 @@ import { useAppStore } from "@/store/useAppStore"; export function TopBar() { const { data: servers = [] } = useServers(); const asaCacheOpLabel = useAppStore((s) => s.asaCacheOpLabel); + const protonOpLabel = useAppStore((s) => s.protonOpLabel); const statsLiveBuffers = useAppStore((s) => s.statsLiveBuffers); const total = servers.length; @@ -75,6 +76,14 @@ export function TopBar() {
)} + {protonOpLabel && ( +
+ + + {protonOpLabel} + +
+ )}
diff --git a/src/components/layout/UpdateManager.tsx b/src/components/layout/UpdateManager.tsx index 51db3bf..708b815 100644 --- a/src/components/layout/UpdateManager.tsx +++ b/src/components/layout/UpdateManager.tsx @@ -1,6 +1,7 @@ "use client"; import { useEffect, useRef } from "react"; +import { useRouter } from "next/navigation"; import { check } from "@tauri-apps/plugin-updater"; import { invoke } from "@tauri-apps/api/core"; import { toast } from "sonner"; @@ -10,6 +11,7 @@ import { tauriCmd } from "@/lib/tauri-commands"; const ONE_HOUR_MS = 60 * 60 * 1000; export function UpdateManager() { + const router = useRouter(); const checkingRef = useRef(false); const protonCheckRef = useRef(false); const isLinux = typeof navigator !== "undefined" && !navigator.userAgent.includes("Windows"); @@ -22,10 +24,28 @@ export function UpdateManager() { if (!protonPath) return; const info = await tauriCmd.checkProtonGeUpdate(protonPath); if (!info.updateAvailable) return; + const toastId = `proton-update-${info.latestVersion}`; toast.info(`Proton-GE ${info.latestVersion} is available`, { - id: `proton-update-${info.latestVersion}`, - description: `Current: ${info.currentVersion || "unknown"}. Update in Settings → Updates → Proton-GE.`, + id: toastId, + description: `Current: ${info.currentVersion || "unknown"}.`, duration: Infinity, + action: { + label: "Update", + onClick: () => { + toast.dismiss(toastId); + router.push("/settings?tab=updates&autoUpdateProton=1"); + }, + }, + actionButtonStyle: { + background: "rgba(var(--neon-purple-rgb),0.15)", + border: "1px solid rgba(var(--neon-purple-rgb),0.4)", + color: "var(--neon-purple)", + }, + cancelButtonStyle: { + background: "transparent", + border: "1px solid rgba(var(--neon-purple-rgb),0.2)", + color: "var(--text-muted)", + }, cancel: { label: "Dismiss", onClick: () => {} }, }); } catch { diff --git a/src/components/server/ServerActionMenu.tsx b/src/components/server/ServerActionMenu.tsx index 2621061..c1c521c 100644 --- a/src/components/server/ServerActionMenu.tsx +++ b/src/components/server/ServerActionMenu.tsx @@ -216,7 +216,7 @@ function DeleteDialog({ /> 0 ? ` (${formatBytes(diskUsage.saveBytes)})` : diskUsage ? " (none)" : ""}`} - sublabel={baseDir ? `${baseDir}/Saves/${server.id}/` : "Saves directory"} + sublabel={baseDir ? `${baseDir}/saves/${server.id}/` : "Saves directory"} enabled={deleteSaves} onToggle={() => setDeleteSaves((v) => !v)} color="var(--neon-red)" diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index 493f6fe..b0b3b8d 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -168,7 +168,7 @@ function FieldRow({ min={field.min} max={field.max} step={field.step} - defaultValue={field.defaultValue} + defaultValue={typeof field.defaultValue === "number" ? field.defaultValue : undefined} />
); diff --git a/src/components/shared/CommandOutputPanel.tsx b/src/components/shared/CommandOutputPanel.tsx index 5988945..99213f6 100644 --- a/src/components/shared/CommandOutputPanel.tsx +++ b/src/components/shared/CommandOutputPanel.tsx @@ -51,6 +51,10 @@ export function clearOutputBuffer(channel: string): void { _buffers.delete(channel); } +export function hasOutputBuffer(channel: string): boolean { + return (_buffers.get(channel)?.length ?? 0) > 0; +} + export interface CommandOutputPanelProps { /** The Tauri event channel to subscribe to, e.g. "steamcmd://output/setup". */ eventChannel: string; diff --git a/src/components/shared/NumberField.tsx b/src/components/shared/NumberField.tsx index 72265f7..c8b019e 100644 --- a/src/components/shared/NumberField.tsx +++ b/src/components/shared/NumberField.tsx @@ -5,7 +5,7 @@ * * The slider is clamped to [min, max] (the "safe" range). * The text input is unconstrained, letting admins override beyond safe limits. - * Colored dots with labels are shown above the track at 0 and at defaultValue. + * The "0" reference mark appears above the track; the "default" mark appears below. */ import { useState, useRef, useEffect } from "react"; @@ -72,10 +72,14 @@ export function NumberField({ value, onChange, min, max, step = 0.1, defaultValu return (
{/* Slider with reference markers */} -
- {/* Tick marks */} -
- {showZeroMark && zeroPct >= 0 && zeroPct <= 100 && ( +
+ + {/* "0" mark ABOVE the track */} + {showZeroMark && zeroPct >= 0 && zeroPct <= 100 && ( +
0
- )} - {defaultPct !== null && defaultPct >= 0 && defaultPct <= 100 && ( -
- default -
-
- )} -
+
+ )} + + + {/* "default" mark BELOW the track — clickable to snap to default */} + {defaultPct !== null && defaultPct >= 0 && defaultPct <= 100 && ( +
+ +
+ )} +
{/* Numeric input override */} @@ -116,7 +132,7 @@ export function NumberField({ value, onChange, min, max, step = 0.1, defaultValu onBlur={handleInputBlur} className="w-20 h-7 text-xs font-mono text-right rounded px-2 shrink-0" style={{ - background: "rgba(0,0,0,0.35)", + background: "var(--surface)", border: "1px solid rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)", outline: "none", diff --git a/src/components/wizard/ServerCreationWizard.tsx b/src/components/wizard/ServerCreationWizard.tsx index d137947..e5d50a2 100644 --- a/src/components/wizard/ServerCreationWizard.tsx +++ b/src/components/wizard/ServerCreationWizard.tsx @@ -39,8 +39,8 @@ import { getReleasedMaps, getOfficialMaps, getModMaps, getMapById, GAME_MODES, PRESET_STYLES, INI_FIELD_GROUPS, buildPresetConfig, DEFAULT_GAME_USER_SETTINGS, DEFAULT_GAME_INI, - LAUNCH_PARAMETERS, NOTIFICATION_EVENTS, - type ArkMap, type GameModeConfig, type PresetStyle, type LaunchParameter, + LAUNCH_PARAMETERS, NOTIFICATION_EVENTS, ARK_EVENTS, + type ArkMap, type GameModeConfig, type PresetStyle, type LaunchParameter, type ArkEvent, } from "@/data/game-data"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; import { dispatchNotification } from "@/lib/notifications"; @@ -48,8 +48,8 @@ import { getAppSetting, setAppSetting, createServer, deleteServerRecord, saveServerConfig, createSchedule, updateScheduleConfig, getClusters, isServerNameTaken, updateServerStatus, addServerMod, getServers, getServerMods, createClusterRecord, - updateBackupBroadcastMessage, - type ClusterRow, + updateBackupBroadcastMessage, getServerConfig, setServerActiveEvent, + type ClusterRow, type ServerRow, } from "@/lib/db"; import { getNextCronDate } from "@/components/shared/CronBuilder"; import { useTauriEvent } from "@/hooks/useTauriEvent"; @@ -116,10 +116,33 @@ interface WizardData { serverPasswordConfirm: string; adminPassword: string; adminPasswordConfirm: string; + motdMessage: string; + motdDuration: number; + // Step 0 — Event + activeEventId: string; // Step 1 — Game Mode gameMode: "pvp" | "pve"; + // Game Mode — General (both PvP & PvE) + adminLogging: boolean; + serverCrosshair: boolean; + showDamageNumbers: boolean; + showPlayerLocation: boolean; + forceAllStructureLocking: boolean; + alwaysAllowStructurePickup: boolean; + disableStructurePlacementCollision: boolean; + // Game Mode — PvE specific flyerCarryPvE: boolean; + allowCaveBuildingPvE: boolean; + pveAllowStructuresAtSupplyDrops: boolean; + allowCrateSpawnsOnTopOfStructures: boolean; + disableStructureDecayPvE: boolean; + disableDinoDecayPvE: boolean; + // Game Mode — PvP specific pvpFriendlyFire: boolean; + preventOfflinePvP: boolean; + preventOfflinePvPInterval: number; + // Copy from server + copyFromServerId: string; // Step 2 — Style presetStyle: "official" | "casual" | "boosted" | "guided_custom" | "full_custom"; // Step 2a — Guided Custom rates @@ -138,6 +161,9 @@ interface WizardData { // Automation — restart autoRestart: boolean; autoRestartCron: string; + autoRestartWarnPlayers: boolean; + autoRestartWarnMinutes: number; + autoRestartMessage: string; // Automation — backup tiers (TimeShift) serverBackupTiers: Record<"H"|"D"|"W"|"M", { enabled: boolean; keep: number }>; playerBackupTiers: Record<"H"|"D"|"W"|"M", { enabled: boolean; keep: number }>; @@ -210,9 +236,25 @@ const DEFAULT_DATA: WizardData = { serverPasswordConfirm: "", adminPassword: "", adminPasswordConfirm: "", + activeEventId: "", gameMode: "pve", - flyerCarryPvE: true, + adminLogging: true, + serverCrosshair: true, + showDamageNumbers: true, + showPlayerLocation: true, + forceAllStructureLocking: true, + alwaysAllowStructurePickup: true, + disableStructurePlacementCollision: false, + flyerCarryPvE: false, + allowCaveBuildingPvE: false, + pveAllowStructuresAtSupplyDrops: true, + allowCrateSpawnsOnTopOfStructures: true, + disableStructureDecayPvE: false, + disableDinoDecayPvE: false, pvpFriendlyFire: true, + preventOfflinePvP: false, + preventOfflinePvPInterval: 900, + copyFromServerId: "", presetStyle: "casual", guidedRates: DEFAULT_GUIDED_RATES, fullCustomGus: {}, @@ -224,6 +266,9 @@ const DEFAULT_DATA: WizardData = { clusterId: "", autoRestart: true, autoRestartCron: "0 6 * * *", + autoRestartWarnPlayers: true, + autoRestartWarnMinutes: 15, + autoRestartMessage: "Server restarting in {minutes} minutes. Progress will be saved.", serverBackupTiers: { H: { enabled: false, keep: 24 }, D: { enabled: true, keep: 7 }, @@ -247,6 +292,8 @@ const DEFAULT_DATA: WizardData = { modIds: [], lockedModIds: [], modNames: {}, + motdMessage: "", + motdDuration: 20, }; // --------------------------------------------------------------------------- @@ -263,25 +310,35 @@ function computeSteps(data: WizardData): StepDef[] { const steps: StepDef[] = [ { id: "basic", label: "Basic Info", icon: Server }, { id: "gamemode", label: "Game Mode", icon: Sword }, - { id: "style", label: "Server Style", icon: Sliders }, ]; - if (data.presetStyle === "guided_custom") { - steps.push({ id: "guided_rates", label: "Core Rates", icon: Sliders }); - steps.push({ id: "guided_breeding", label: "Breeding", icon: Heart }); - steps.push({ id: "guided_combat", label: "Combat", icon: Sword }); - steps.push({ id: "guided_behavior", label: "Server QoL", icon: Settings2 }); - } - if (data.presetStyle === "full_custom") { - steps.push({ id: "full_ini", label: "INI Config", icon: Code2 }); + + if (!data.copyFromServerId) { + steps.push({ id: "style", label: "Server Style", icon: Sliders }); + if (data.presetStyle === "guided_custom") { + steps.push({ id: "guided_rates", label: "Core Rates", icon: Sliders }); + steps.push({ id: "guided_breeding", label: "Breeding", icon: Heart }); + steps.push({ id: "guided_combat", label: "Combat", icon: Sword }); + steps.push({ id: "guided_behavior", label: "Server QoL", icon: Settings2 }); + } + if (data.presetStyle === "full_custom") { + steps.push({ id: "full_ini", label: "INI Config", icon: Code2 }); + } } + steps.push( { id: "network", label: "Network", icon: Network }, - { id: "firewall", label: "Firewall", icon: Shield }, { id: "cluster", label: "Cluster", icon: GitBranch }, { id: "automation", label: "Automation", icon: Clock }, - { id: "launch", label: "Launch Args", icon: Terminal }, - { id: "mods", label: "Mods", icon: Package }, - { id: "install", label: "Install", icon: Download }, + ); + + if (!data.copyFromServerId) { + steps.push({ id: "launch", label: "Launch Args", icon: Terminal }); + } + + steps.push( + { id: "mods", label: "Mods", icon: Package }, + { id: "firewall", label: "Firewall", icon: Shield }, + { id: "install", label: "Install", icon: Download }, ); return steps; } @@ -335,6 +392,7 @@ function BasicInfoStep({ const [nameChecked, setNameChecked] = useState(false); const [mapMenuOpen, setMapMenuOpen] = useState(false); const menuRef = useRef(null); + const nameDebounce = useRef | null>(null); const [showAdminPw, setShowAdminPw] = useState(false); const [showAdminConfirm, setShowAdminConfirm] = useState(false); const [showServerPw, setShowServerPw] = useState(false); @@ -435,8 +493,18 @@ function BasicInfoStep({ { onChange({ name: e.target.value }); onNameValidated(false); setNameChecked(false); }} - onBlur={(e) => checkName(e.target.value)} + onChange={(e) => { + const val = e.target.value; + onChange({ name: val }); + onNameValidated(false); + setNameChecked(false); + if (nameDebounce.current) clearTimeout(nameDebounce.current); + nameDebounce.current = setTimeout(() => checkName(val), 600); + }} + onBlur={(e) => { + if (nameDebounce.current) clearTimeout(nameDebounce.current); + checkName(e.target.value); + }} placeholder="My ASA Server" style={{ background: "var(--surface)", @@ -490,7 +558,7 @@ function BasicInfoStep({
+ {/* Active Event */} +
+
+ + + + + + + + Activates a seasonal event on the server. The required event mod is automatically downloaded and enabled when the server starts — you don't need to add it to the mod list manually. + + + +
+ + {data.activeEventId && (() => { + const ev = ARK_EVENTS.find((e) => e.id === data.activeEventId); + return ev ? ( +
+ +
+

{ev.description}

+

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

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