From cc4a1b7066fdac0928235f2e2b249fee5a1cc69e Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Sat, 30 May 2026 09:02:24 -0500 Subject: [PATCH 01/26] feat: enhance log file handling during server startup to ensure fresh log access --- src-tauri/src/commands/server.rs | 57 +++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 5 deletions(-) diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index f31f870..93195c9 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -491,6 +491,25 @@ async fn inner_start_server_with_state( "{}/ShooterGame/Saved/Logs/ShooterGame.log", params.install_path ); + + // Snapshot the inode/file-ID of ShooterGame.log before the server starts. + // UE rotates the log on startup (renames old → timestamped backup, creates + // fresh copy). Recording the pre-spawn inode lets the watcher below wait + // until rotation is complete before opening the file, preventing a stale + // file descriptor on the archived copy that will never receive new content. + #[cfg(unix)] + let pre_spawn_ino: Option = { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(&log_path2).ok().map(|m| m.ino()) + }; + #[cfg(windows)] + let pre_spawn_ino: Option = { + use std::os::windows::fs::MetadataExt; + std::fs::metadata(&log_path2).ok().and_then(|m| m.file_index()) + }; + #[cfg(not(any(unix, windows)))] + let pre_spawn_ino: Option = None; + let confirmed2 = Arc::clone(&confirmed_running); tauri::async_runtime::spawn(async move { use std::io::SeekFrom; @@ -530,8 +549,13 @@ async fn inner_start_server_with_state( true }; - // ── Wait for the log file to appear ────────────────────────────────── - // The server creates it within the first few seconds of startup. + // ── Wait for the log file to appear and be rotated ─────────────────── + // UE rotates ShooterGame.log on startup: it renames the old file to a + // timestamped backup and creates a fresh one. We wait until the file + // exists with a different inode than the pre-spawn snapshot, guaranteeing + // we tail the current session's log and not the archived copy. Falls back + // after 60 s for configs where UE appends rather than rotates. + let mut same_ino_polls = 0u32; let file = loop { if Instant::now() >= deadline { return; } @@ -544,13 +568,36 @@ async fn inner_start_server_with_state( if !still_tracked { return; } match tokio::fs::File::open(&log_path2).await { - Ok(f) => break f, + Ok(f) => { + // No pre-existing file — this is definitely the fresh log. + let Some(expected_ino) = pre_spawn_ino else { break f; }; + + // Check whether UE has rotated to a new inode yet. + let rotated = tokio::fs::metadata(&log_path2).await.ok().map_or(false, |m| { + #[cfg(unix)] + let changed = { use std::os::unix::fs::MetadataExt; m.ino() != expected_ino }; + #[cfg(windows)] + let changed = { use std::os::windows::fs::MetadataExt; m.file_index().map_or(false, |id| id != expected_ino) }; + #[cfg(not(any(unix, windows)))] + let changed = { let _ = m; false }; + changed + }); + + if rotated { break f; } + + // Same inode — rotation not yet complete. Fall through after + // 60 s in case UE appends instead of rotating on this config. + same_ino_polls += 1; + if same_ino_polls >= 300 { break f; } + sleep(Duration::from_millis(200)).await; + } Err(_) => sleep(Duration::from_secs(1)).await, } }; - // Seek to end so we only see lines from this server session (not a - // previous run that left the log file on disk). + // Seek past any content written before we opened the file. For a freshly + // rotated log this lands near position 0; for the 60-second fallback it + // skips stale content from a prior run. let mut file = file; let _ = file.seek(SeekFrom::End(0)).await; let mut reader = BufReader::new(file); From 7c97aa074e299e0234235d093b033faee06beb4c Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Sat, 30 May 2026 09:22:59 -0500 Subject: [PATCH 02/26] feat: enhance server startup error handling and notification system for missing executables --- src-tauri/src/commands/server.rs | 38 +++++++++++++------ src-tauri/src/lib.rs | 30 +++++++++++---- src-tauri/src/state/mod.rs | 4 ++ src/app/notifications/page.tsx | 3 +- src/components/layout/NotificationBell.tsx | 4 +- src/components/layout/NotificationManager.tsx | 7 ++-- src/components/server/ServerCard.tsx | 23 ++++++++--- src/lib/db.ts | 20 ++++++++-- src/store/useAppStore.ts | 18 +++++++++ 9 files changed, 113 insertions(+), 34 deletions(-) diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 93195c9..6be016b 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -273,9 +273,19 @@ async fn inner_start_server_with_state( cmd.env_remove("PYTHONPATH"); } - let mut child = cmd - .spawn() - .map_err(|e| format!("Failed to start server process: {e}"))?; + let mut child = match cmd.spawn() { + Ok(c) => c, + Err(e) => { + let msg = if e.kind() == std::io::ErrorKind::NotFound { + // The server executable is missing — reinstall is the only fix. + // Prefix lets the frontend detect this case and hide the Retry button. + "exe_missing: ArkAscendedServer.exe was not found. Please reinstall the server.".to_string() + } else { + format!("Failed to start server process: {e}") + }; + return Err(msg); + } + }; let pid = child.id().ok_or("Spawned process has no PID")?; @@ -296,6 +306,7 @@ async fn inner_start_server_with_state( pid, started_at: Instant::now(), install_path: params.install_path.clone(), + confirmed_running: false, }, ); } @@ -523,16 +534,19 @@ async fn inner_start_server_with_state( let deadline = Instant::now() + TIMEOUT; - // Read current PID and uptime from running_servers and emit "running". + // Mark the server as confirmed-running, read its PID/uptime, and emit "running". + // Sets confirmed_running = true so the crash monitor emits "crashed" (not + // "start-failed") if the process dies after this point. // Returns false if the server was already removed from the map. let confirm_running = |handle: &tauri::AppHandle, sid: &str| -> bool { - let pid_uptime = handle - .state::() - .running_servers - .lock() - .unwrap() - .get(sid) - .map(|rs| (rs.pid, rs.started_at.elapsed().as_secs())); + let pid_uptime = { + let state = handle.state::(); + let mut registry = state.running_servers.lock().unwrap(); + registry.get_mut(sid).map(|rs| { + rs.confirmed_running = true; + (rs.pid, rs.started_at.elapsed().as_secs()) + }) + }; let Some((game_pid, uptime)) = pid_uptime else { return false; }; @@ -797,6 +811,8 @@ pub async fn register_running_server( // will read from SQLite updated_at on the frontend instead. started_at: Instant::now(), install_path, + // A re-registered server was already running before the app restarted. + confirmed_running: true, }, ); Ok(true) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 0bd7e8e..2485f69 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -220,21 +220,35 @@ pub fn run() { .unwrap() .remove(server_id); - app_state - .running_servers - .lock() - .unwrap() - .remove(server_id); + let confirmed_running = { + let mut registry = app_state.running_servers.lock().unwrap(); + let confirmed = registry + .get(server_id) + .map_or(false, |rs| rs.confirmed_running); + registry.remove(server_id); + confirmed + }; - let status_str = - if was_intentional { "stopped" } else { "crashed" }; + let status_str = if was_intentional { + "stopped" + } else if confirmed_running { + "crashed" + } else { + "start-failed" + }; + + let error_msg = if status_str == "start-failed" { + Some("Server process exited before completing startup. Try disabling mods — if the problem persists, reinstall the server.".to_string()) + } else { + None + }; let payload = commands::server::ServerStatus { server_id: server_id.clone(), status: status_str.into(), pid: None, uptime_seconds: None, - error: None, + error: error_msg, }; let _ = handle.emit( diff --git a/src-tauri/src/state/mod.rs b/src-tauri/src/state/mod.rs index 2a5169a..fffdc7d 100644 --- a/src-tauri/src/state/mod.rs +++ b/src-tauri/src/state/mod.rs @@ -17,6 +17,10 @@ pub struct RunningServer { /// On Linux, used to locate Wine processes that were launched inside the Steam /// Runtime container (and therefore not visible in the proton PID's subtree). pub install_path: String, + /// Set to true once the log watcher sees the readiness line and emits "running". + /// The crash monitor uses this to distinguish a startup failure (false → "start-failed") + /// from a genuine runtime crash (true → "crashed"). + pub confirmed_running: bool, } /// Global application state shared across all Tauri commands via `tauri::State`. diff --git a/src/app/notifications/page.tsx b/src/app/notifications/page.tsx index f1738d9..a61f6bf 100644 --- a/src/app/notifications/page.tsx +++ b/src/app/notifications/page.tsx @@ -25,6 +25,7 @@ import { markAllNotificationsRead, deleteNotification, pruneNotificationsWithFilter, + parseDbDate, type InAppNotificationRow, } from "@/lib/db"; import { useAppStore } from "@/store/useAppStore"; @@ -106,7 +107,7 @@ function NotificationRow({ className="text-xs shrink-0" style={{ color: "var(--text-subtle)" }} > - {new Date(n.created_at).toLocaleString()} + {parseDbDate(n.created_at).toLocaleString()}

diff --git a/src/components/layout/NotificationBell.tsx b/src/components/layout/NotificationBell.tsx index fdd2203..352b113 100644 --- a/src/components/layout/NotificationBell.tsx +++ b/src/components/layout/NotificationBell.tsx @@ -10,7 +10,7 @@ import { PopoverTrigger, } from "@/components/ui/popover"; import { useUnreadNotificationCount, useNotificationList } from "@/hooks/useNotifications"; -import { markAllNotificationsRead } from "@/lib/db"; +import { markAllNotificationsRead, parseDbDate } from "@/lib/db"; import { useAppStore } from "@/store/useAppStore"; import { useQueryClient } from "@tanstack/react-query"; import type { InAppNotificationRow } from "@/lib/db"; @@ -69,7 +69,7 @@ function NotificationItemMini({ {n.title}

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

diff --git a/src/components/layout/NotificationManager.tsx b/src/components/layout/NotificationManager.tsx index 736ac21..03964df 100644 --- a/src/components/layout/NotificationManager.tsx +++ b/src/components/layout/NotificationManager.tsx @@ -63,15 +63,14 @@ export function NotificationManager() { severity: "error", }); } else if (status.status === "start-failed") { - const detail = status.error - ? `Server process exited immediately after launch.\n\nProcess output:\n${status.error}` - : "Server process exited immediately after launch. Verify that Proton-GE is configured correctly, the server files are intact, and all required ports are available."; + const body = status.error + ?? "Server failed to start. Verify that Proton-GE is configured correctly, the server files are intact, and all required ports are available."; await dispatchNotification({ eventType: NOTIFICATION_EVENTS.SERVER_START_FAILED, serverId: status.serverId, serverName, title: `${serverName} failed to start`, - body: detail, + body, severity: "error", }); } diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index e09fb4a..d43d184 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -97,6 +97,9 @@ export function ServerCard({ server }: Props) { const queryClient = useQueryClient(); const stats = useServerStats(server); const startTime = useAppStore((s) => s.serverStartTimes[server.id]); + const noRetry = useAppStore((s) => !!s.noRetryServerIds[server.id]); + const setNoRetryServer = useAppStore((s) => s.setNoRetryServer); + const clearNoRetryServer = useAppStore((s) => s.clearNoRetryServer); const [modCount, setModCount] = useState(null); const [lastBackup, setLastBackup] = useState(null); @@ -195,6 +198,7 @@ export function ServerCard({ server }: Props) { const handleStart = async () => { setActionPending(true); + clearNoRetryServer(server.id); try { await updateServerStatus(server.id, "starting", null); queryClient.invalidateQueries({ queryKey: ["servers"] }); @@ -207,16 +211,23 @@ export function ServerCard({ server }: Props) { await updateServerStatus(server.id, "starting", pid); queryClient.invalidateQueries({ queryKey: ["servers"] }); } catch (err) { - const errMsg = typeof err === "string" ? err : String(err); + const raw = typeof err === "string" ? err : String(err); + const isExeMissing = raw.startsWith("exe_missing:"); + const userMsg = isExeMissing + ? raw.slice("exe_missing: ".length) + : raw; + + if (isExeMissing) setNoRetryServer(server.id); + await updateServerStatus(server.id, "start-failed", null); queryClient.invalidateQueries({ queryKey: ["servers"] }); - toast.error(`${server.name} failed to start — ${errMsg}`); + toast.error(`${server.name} failed to start`, { description: userMsg }); dispatchNotification({ eventType: NOTIFICATION_EVENTS.SERVER_START_FAILED, serverId: server.id, serverName: server.name, title: `${server.name} failed to start`, - body: errMsg, + body: userMsg, severity: "error", }); } finally { @@ -478,8 +489,10 @@ export function ServerCard({ server }: Props) { {isInstallFailed ? "Install Failed" : "Start Failed"} - {/* For start-failed only: Retry Start avoids a full re-download */} - {isStartFailed && ( + {/* For start-failed only: Retry Start avoids a full re-download. + Hidden when the failure was a missing executable — retry would + immediately fail again, only reinstall can fix it. */} + {isStartFailed && !noRetry && ( + + ) : ( + + )} + + ); +} + function CloseToTraySection() { const [closeToTray, setCloseToTrayState] = useState(true); @@ -1358,6 +1446,16 @@ export default function SettingsPage() {
+ + {IS_LINUX && ( +
+ +
+ )} )} diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index d43d184..141590f 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -181,9 +181,6 @@ export function ServerCard({ server }: Props) { port: server.port, queryPort: server.query_port, rconPort: server.rcon_port, - maxPlayers: server.max_players, - serverPassword: server.server_password ?? undefined, - adminPassword: server.admin_password, extraArgs, modIds: enabledModIds, }; diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index 567c15f..4951beb 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -1,103 +1,52 @@ "use client"; import { useState, useEffect, useCallback } from "react"; -import { Save, Code, LayoutList, RefreshCw, ChevronDown, ChevronRight } from "lucide-react"; +import { + Save, Code, LayoutList, RefreshCw, ChevronDown, ChevronRight, + Settings2, X, AlertCircle, +} from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Switch } from "@/components/ui/switch"; import { tauriCmd, type ServerConfigJson } from "@/lib/tauri-commands"; -import type { ServerRow } from "@/lib/db"; +import { INI_FIELD_GROUPS, type IniFieldDef } from "@/data/game-data"; +import { getServerConfig, saveServerConfig, type ServerRow } from "@/lib/db"; interface Props { server: ServerRow; } -// --------------------------------------------------------------------------- -// Field definitions — the structured view of the most important ASA INI keys. -// Section keys must exactly match what the INI parser produces. -// --------------------------------------------------------------------------- - -interface FieldDef { - section: string; - key: string; - label: string; - type: "string" | "number" | "boolean"; - placeholder?: string; - min?: number; - max?: number; - step?: number; - file: "gus" | "game"; -} - -const FIELD_GROUPS: { title: string; fields: FieldDef[] }[] = [ - { - title: "Session", - fields: [ - { file: "gus", section: "SessionSettings", key: "SessionName", label: "Server Name", type: "string", placeholder: "My ASA Server" }, - { file: "gus", section: "ServerSettings", key: "MaxPlayers", label: "Max Players", type: "number", min: 1, max: 70 }, - { file: "gus", section: "SessionSettings", key: "ServerPassword", label: "Join Password", type: "string", placeholder: "(no password)" }, - ], - }, - { - title: "Admin & RCON", - fields: [ - { file: "gus", section: "ServerSettings", key: "ServerAdminPassword", label: "Admin Password", type: "string", placeholder: "required" }, - { file: "gus", section: "SessionSettings", key: "RCONEnabled", label: "RCON Enabled", type: "boolean" }, - { file: "gus", section: "SessionSettings", key: "RCONPort", label: "RCON Port", type: "number", min: 1024, max: 65535 }, - ], - }, - { - title: "Rates", - fields: [ - { file: "gus", section: "ServerSettings", key: "XPMultiplier", label: "XP Multiplier", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "TamingSpeedMultiplier", label: "Taming Speed", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "HarvestAmountMultiplier", label: "Harvest Amount", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "ResourcesRespawnPeriodMultiplier", label: "Resource Respawn Multiplier", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "PlayerCharacterWaterDrainMultiplier", label: "Water Drain", type: "number", min: 0.0, max: 10, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "PlayerCharacterFoodDrainMultiplier", label: "Food Drain", type: "number", min: 0.0, max: 10, step: 0.1 }, - ], - }, - { - title: "Taming & Breeding", - fields: [ - { file: "gus", section: "ServerSettings", key: "BabyMatureSpeedMultiplier", label: "Baby Mature Speed", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "EggHatchSpeedMultiplier", label: "Egg Hatch Speed", type: "number", min: 0.1, max: 100, step: 0.1 }, - { file: "gus", section: "ServerSettings", key: "BabyCuddleIntervalMultiplier", label: "Imprint Interval", type: "number", min: 0.1, max: 100, step: 0.1 }, - ], - }, - { - title: "PvP / PvE", - fields: [ - { file: "gus", section: "ServerSettings", key: "DifficultyOffset", label: "Difficulty Offset", type: "number", min: 0, max: 1, step: 0.05 }, - { file: "gus", section: "ServerSettings", key: "AllowThirdPersonPlayer", label: "Allow Third Person", type: "boolean" }, - { file: "gus", section: "ServerSettings", key: "AlwaysNotifyPlayerLeft", label: "Notify Player Left", type: "boolean" }, - { file: "gus", section: "ServerSettings", key: "AlwaysNotifyPlayerJoined", label: "Notify Player Joined", type: "boolean" }, - { file: "gus", section: "ServerSettings", key: "GlobalVoiceChat", label: "Global Voice Chat", type: "boolean" }, - { file: "gus", section: "ServerSettings", key: "ProximityChat", label: "Proximity Chat", type: "boolean" }, - ], - }, -]; +// Keys excluded from the "Full INI Editor" — handled on the server overview/setup pages. +const OVERVIEW_KEYS = new Set([ + "SessionName", "ServerPassword", "ServerAdminPassword", + "Port", "QueryPort", "RCONPort", "RCONEnabled", "MaxPlayers", +]); // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- -function getIniValue(config: ServerConfigJson, file: "gus" | "game", section: string, key: string): string { - const src = file === "gus" ? config.gameUserSettings : config.gameIni; - return src?.[section]?.[key] ?? ""; +function getIniValue( + config: ServerConfigJson, + section: "gus" | "game", + iniSection: string, + key: string +): string { + const src = section === "gus" ? config.gameUserSettings : config.gameIni; + return src?.[iniSection]?.[key] ?? ""; } function setIniValue( config: ServerConfigJson, - file: "gus" | "game", - section: string, + section: "gus" | "game", + iniSection: string, key: string, value: string, ): ServerConfigJson { - const src = file === "gus" ? { ...config.gameUserSettings } : { ...config.gameIni }; - src[section] = { ...(src[section] ?? {}), [key]: value }; - if (file === "gus") return { ...config, gameUserSettings: src }; + const src = section === "gus" ? { ...config.gameUserSettings } : { ...config.gameIni }; + src[iniSection] = { ...(src[iniSection] ?? {}), [key]: value }; + if (section === "gus") return { ...config, gameUserSettings: src }; return { ...config, gameIni: src }; } @@ -128,11 +77,15 @@ function rawTextToSections(text: string): Record> } // --------------------------------------------------------------------------- -// FieldRow +// Field row // --------------------------------------------------------------------------- -function FieldRow({ field, value, onChange }: { - field: FieldDef; +function FieldRow({ + field, + value, + onChange, +}: { + field: IniFieldDef; value: string; onChange: (val: string) => void; }) { @@ -140,36 +93,31 @@ function FieldRow({ field, value, onChange }: { const checked = value === "True" || value === "true" || value === "1"; return (
- - onChange(v ? "True" : "False")} - /> +
+ + {field.description && ( +

{field.description}

+ )} +
+ onChange(v ? "True" : "False")} />
); } return (
- +
+ + {field.description && ( +

{field.description}

+ )} +
); } // --------------------------------------------------------------------------- -// Section accordion +// Accordion group // --------------------------------------------------------------------------- -function SectionGroup({ title, fields, config, onChange }: { +function SectionGroup({ + title, + fields, + config, + onChange, + defaultOpen = true, +}: { title: string; - fields: FieldDef[]; + fields: IniFieldDef[]; config: ServerConfigJson; - onChange: (f: FieldDef, val: string) => void; + onChange: (f: IniFieldDef, val: string) => void; + defaultOpen?: boolean; }) { - const [open, setOpen] = useState(true); + const [open, setOpen] = useState(defaultOpen); return ( -
+
+
+ +
+

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

+
+ + {/* Scrollable body */} +
+ {INI_FIELD_GROUPS.map((group) => { + const visibleFields = group.fields.filter( + (f) => f.section === "gus" && !OVERVIEW_KEYS.has(f.key) + ); + if (visibleFields.length === 0) return null; + const open = expandedGroups.has(group.id); + return ( +
+ + {open && ( +
+ {visibleFields.map((f) => ( + handleChange(f, val)} + /> + ))} +
+ )} +
+ ); + })} +
+ + {/* Footer */} +
+ + +
+
+ + ); +} + +// --------------------------------------------------------------------------- +// Quick-edit groups shown in the structured tab (subset of all groups) +// --------------------------------------------------------------------------- + +const QUICK_EDIT_GROUP_IDS = ["session", "admin", "rates", "breeding"]; + // --------------------------------------------------------------------------- // Main ConfigTab // --------------------------------------------------------------------------- @@ -245,12 +310,44 @@ export function ConfigTab({ server }: Props) { const [rawMode, setRawMode] = useState(false); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); + const [readingIni, setReadingIni] = useState(false); const [savedFlash, setSavedFlash] = useState(false); const [error, setError] = useState(null); + const [showFullModal, setShowFullModal] = useState(false); - const loadConfig = useCallback(async () => { + // Load from DB on mount — reflects what we last saved, not what the server may have overwritten + const loadFromDb = useCallback(async () => { setLoading(true); setError(null); + try { + const row = await getServerConfig(server.id); + if (row) { + const gus = JSON.parse(row.game_user_settings_json || "{}"); + const game = JSON.parse(row.game_ini_json || "{}"); + const cfg: ServerConfigJson = { gameUserSettings: gus, gameIni: game, launchArgs: {} }; + setConfig(cfg); + setRawGus(configToRawText(gus)); + setRawGame(configToRawText(game)); + } else { + // No saved config yet — show empty + const empty: ServerConfigJson = { gameUserSettings: {}, gameIni: {}, launchArgs: {} }; + setConfig(empty); + setRawGus(""); + setRawGame(""); + } + } catch (e) { + setError(String(e)); + } finally { + setLoading(false); + } + }, [server.id]); + + useEffect(() => { loadFromDb(); }, [loadFromDb]); + + // Explicitly read from the INI files on disk — overwrites UI state with what the server has on disk + const readFromIni = useCallback(async () => { + setReadingIni(true); + setError(null); try { const cfg = await tauriCmd.readServerConfig(server.install_path); setConfig(cfg); @@ -259,32 +356,42 @@ export function ConfigTab({ server }: Props) { } catch (e) { setError(String(e)); } finally { - setLoading(false); + setReadingIni(false); } }, [server.install_path]); - useEffect(() => { loadConfig(); }, [loadConfig]); - - const handleFieldChange = (field: FieldDef, value: string) => { + const handleFieldChange = (field: IniFieldDef, value: string) => { if (!config) return; - setConfig(setIniValue(config, field.file, field.section, field.key, value)); + setConfig(setIniValue(config, field.section, field.iniSection, field.key, value)); }; - const handleSave = async () => { - if (!config) return; + // Save to disk AND update DB so our settings survive server restarts + const handleSave = async (cfg?: ServerConfigJson) => { + const toWrite = cfg ?? config; + if (!toWrite) return; setSaving(true); setError(null); try { - let toSave = config; - if (rawMode) { + let toSave = toWrite; + if (rawMode && !cfg) { toSave = { - ...config, + ...toWrite, gameUserSettings: rawTextToSections(rawGus), gameIni: rawTextToSections(rawGame), }; setConfig(toSave); + } else if (cfg) { + setConfig(cfg); } + // Write to disk await tauriCmd.writeServerConfig(server.install_path, toSave); + // Persist to DB so Config tab loads our version next time, not the server's overwrite + await saveServerConfig( + server.id, + JSON.stringify(toSave.gameUserSettings), + JSON.stringify(toSave.gameIni), + JSON.stringify(toSave.launchArgs ?? {}), + ); setSavedFlash(true); setTimeout(() => setSavedFlash(false), 2000); } catch (e) { @@ -313,46 +420,55 @@ export function ConfigTab({ server }: Props) { return (
- - Reading INI files… - + Loading saved config…
); } + // Quick-edit: only show a curated subset of groups + const quickGroups = INI_FIELD_GROUPS.filter((g) => QUICK_EDIT_GROUP_IDS.includes(g.id)); + return (
- {/* ── Toolbar ── */} + {/* Toolbar */}
- - + {!rawMode && ( + + )}
-
{error && ( -
+
{error}
)} - {/* ── Structured editor ── */} + {/* Structured editor — quick groups */} {!rawMode && config && (
- {FIELD_GROUPS.map((g) => ( + {quickGroups.map((g, idx) => ( ))} +

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

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

- GameUserSettings.ini -

+

GameUserSettings.ini