From d2f0f330e2cdc91676aed1115b22439415892d48 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 15 Jun 2026 12:20:13 -0500 Subject: [PATCH 01/19] feat: fix wizard notifications, rework auto-update options, and harden ASA cache/cert flows - Fix wizard notification settings not persisting: matrix state is now saved to notification_configs on wizard completion (not lost to failed DB writes); Discord/SMTP credentials saved as notification_configs entries so settings page reads them correctly - Replace numeric auto-update intervals with semantic modes (disabled/startup/startup_hourly) for ASA cache, LokiASAM app, and Proton-GE; standardise 3-button selector layout across all wizard cards - Add Proton-GE background update check to UpdateManager with startup/hourly modes controlled by proton_ge_check_mode setting - Guard ASA cache auto-check and dashboard update button behind servers.length > 0 so nothing runs before a server is created - Show spinning indicator in TopBar while ASA cache update is in progress - Fix mod API cert installation on Linux: initialise Wine prefix via proton run instead of bare wine64 so it works before any server starts --- src-tauri/src/commands/certs.rs | 41 +++++-- src/app/page.tsx | 38 +++--- src/app/settings/page.tsx | 86 ++++++------- src/components/layout/TopBar.tsx | 13 +- src/components/layout/UpdateManager.tsx | 55 +++++++-- src/components/server/ServerCard.tsx | 2 +- src/components/server/tabs/OverviewTab.tsx | 2 +- src/components/shared/NotificationMatrix.tsx | 19 ++- src/components/wizard/SetupWizard.tsx | 121 +++++++++++++------ src/lib/db.ts | 2 +- src/lib/scheduler-sync.ts | 39 ++++-- src/lib/update-utils.ts | 35 +++++- src/store/useAppStore.ts | 7 ++ src/store/useSetupStore.ts | 34 +----- 14 files changed, 315 insertions(+), 179 deletions(-) diff --git a/src-tauri/src/commands/certs.rs b/src-tauri/src/commands/certs.rs index eb19ce1..18d06a0 100644 --- a/src-tauri/src/commands/certs.rs +++ b/src-tauri/src/commands/certs.rs @@ -103,33 +103,48 @@ async fn install_windows(cert_path: &str) -> Result<(), String> { #[cfg(target_os = "linux")] async fn install_linux(cert_path: &str, proton_path: &str, prefix_path: &str) -> Result<(), String> { - let wine_bin = format!("{proton_path}/files/bin/wine64"); - let wine_pfx = format!("{prefix_path}/pfx"); - let marker = PathBuf::from(prefix_path).join(CERT_MARKER_FILENAME); - - // Initialise the Wine prefix if it has not been set up yet. wineboot -u - // creates the fake C: drive, registry hives, etc. without blocking on - // Mono/Gecko downloads. This can take up to ~30 s on first run. + let proton_script = format!("{proton_path}/proton"); + let wine_bin = format!("{proton_path}/files/bin/wine64"); + let wine_pfx = format!("{prefix_path}/pfx"); + let marker = PathBuf::from(prefix_path).join(CERT_MARKER_FILENAME); + + // Initialise the Wine prefix if it has not been set up yet. + // Use the Proton run script (same mechanism as server start) rather than + // wine64 directly — Proton-GE's wine64 is compiled for the Steam Linux + // Runtime and may fail outside it. `proton run` handles environment setup. + // Setting STEAM_COMPAT_CLIENT_INSTALL_PATH to a dummy value prevents + // Proton from trying to use the Steam Runtime daemon when Steam is installed. let system_reg = format!("{wine_pfx}/system.reg"); if !tokio::fs::try_exists(&system_reg).await.unwrap_or(false) { - let status = Command::new(&wine_bin) - .args(["wineboot", "-u"]) - .env("WINEPREFIX", &wine_pfx) + // Create parent directories so Proton can create the pfx inside. + tokio::fs::create_dir_all(&wine_pfx) + .await + .map_err(|e| format!("Failed to create prefix directory: {e}"))?; + + let status = Command::new(&proton_script) + .arg("run") + .arg("C:\\windows\\system32\\wineboot.exe") + .env("STEAM_COMPAT_DATA_PATH", prefix_path) + .env("STEAM_COMPAT_CLIENT_INSTALL_PATH", "/") .env("WINEDLLOVERRIDES", "mscoree,mshtml=") .env("WINEDEBUG", "-all") + .env("PROTON_LOG", "0") .status() .await - .map_err(|e| format!("Failed to run wineboot: {e}"))?; + .map_err(|e| format!("Failed to run proton wineboot: {e}"))?; - if !status.success() { + // Proton may exit non-zero even on success (wineboot is a short-lived + // process). Check that the prefix was actually created instead. + if !tokio::fs::try_exists(&system_reg).await.unwrap_or(false) { return Err(format!( - "wineboot exited with code {}", + "Wine prefix initialisation failed (proton exited {}); try starting a server once first.", status.code().unwrap_or(-1) )); } } // Install the certificate into Wine's CurrentUser\Root store. + // At this point the prefix exists, so wine64 can run standalone. let status = Command::new(&wine_bin) .args(["certutil", "-addstore", "Root", cert_path]) .env("WINEPREFIX", &wine_pfx) diff --git a/src/app/page.tsx b/src/app/page.tsx index eafc485..de44b2c 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -19,7 +19,7 @@ import { ImportServerWizard } from "@/components/server/ImportServerWizard"; import { useServers } from "@/hooks/useServers"; import { getAppSetting, setAppSetting, updateServerStatus } from "@/lib/db"; import { tauriCmd, type UpdateCheckResult } from "@/lib/tauri-commands"; -import { runPerServerUpdateCheck, applyUpdateToServer, type ServerUpdateInfo } from "@/lib/update-utils"; +import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToServer, type ServerUpdateInfo } from "@/lib/update-utils"; import { buildStartParams } from "@/lib/server-utils"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; @@ -80,24 +80,12 @@ function UpdateStatusChip({ servers = [], onUpdateAllClick, onUpdatesFound }: Up const handleCheck = async () => { setChecking(true); try { - const [baseDir, steamcmdPath] = await Promise.all([ - getAppSetting("base_dir"), - getAppSetting("steamcmd_path"), - ]); - if (!baseDir || !steamcmdPath) { + const oldBuild = await getAppSetting("asa_cached_build_id") ?? ""; + const newBuild = await runAsaCacheUpdate(); + if (!newBuild) { toast.error("Base directory or SteamCMD not configured."); return; } - const sep = baseDir.includes("\\") ? "\\" : "/"; - const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; - const oldBuild = await getAppSetting("asa_cached_build_id") ?? ""; - const newBuild = await tauriCmd.updateCache("check", cacheDir, steamcmdPath); - const now = new Date().toISOString(); - await Promise.all([ - setAppSetting("asa_cached_build_id", newBuild), - setAppSetting("asa_latest_build_id", newBuild), - setAppSetting("asa_last_checked", now), - ]); // Manual check: silent mode suppresses per-server toasts; we show dialog. const summary = await runPerServerUpdateCheck(true); queryClient.invalidateQueries({ queryKey: ["servers"] }); @@ -514,14 +502,16 @@ export default function DashboardPage() {

- setShowUpdateAllDialog(true)} - onUpdatesFound={(updates) => { - setPendingUpdates(updates); - setShowUpdatesFoundDialog(true); - }} - /> + {servers.length > 0 && ( + setShowUpdateAllDialog(true)} + onUpdatesFound={(updates) => { + setPendingUpdates(updates); + setShowUpdatesFoundDialog(true); + }} + /> + )}
- {/* Auto-check toggle */} -
-
-

Daily Auto-Check

-

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

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

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

+
+ {[ + { value: "disabled", label: "Disabled" }, + { value: "startup", label: "On startup" }, + { value: "startup_hourly", label: "On startup + hourly" }, + ].map((opt) => ( + + ))}
-
{/* Download output */} diff --git a/src/components/layout/TopBar.tsx b/src/components/layout/TopBar.tsx index 93f56eb..1179644 100644 --- a/src/components/layout/TopBar.tsx +++ b/src/components/layout/TopBar.tsx @@ -1,11 +1,13 @@ "use client"; import { NotificationBell } from "@/components/layout/NotificationBell"; -import { Server, Activity, Users } from "lucide-react"; +import { Server, Activity, Users, RefreshCw } from "lucide-react"; import { useServers } from "@/hooks/useServers"; +import { useAppStore } from "@/store/useAppStore"; export function TopBar() { const { data: servers = [] } = useServers(); + const asaCacheUpdateInProgress = useAppStore((s) => s.asaCacheUpdateInProgress); const total = servers.length; const running = servers.filter((s) => s.status === "running").length; @@ -38,6 +40,15 @@ export function TopBar() {
))} + + {asaCacheUpdateInProgress && ( +
+ + + Checking ASA updates… + +
+ )}
diff --git a/src/components/layout/UpdateManager.tsx b/src/components/layout/UpdateManager.tsx index 24fba89..51db3bf 100644 --- a/src/components/layout/UpdateManager.tsx +++ b/src/components/layout/UpdateManager.tsx @@ -5,11 +5,35 @@ import { check } from "@tauri-apps/plugin-updater"; import { invoke } from "@tauri-apps/api/core"; import { toast } from "sonner"; import { getAppSetting } from "@/lib/db"; +import { tauriCmd } from "@/lib/tauri-commands"; const ONE_HOUR_MS = 60 * 60 * 1000; export function UpdateManager() { - const checkingRef = useRef(false); + const checkingRef = useRef(false); + const protonCheckRef = useRef(false); + const isLinux = typeof navigator !== "undefined" && !navigator.userAgent.includes("Windows"); + + async function checkForProtonUpdate() { + if (protonCheckRef.current) return; + protonCheckRef.current = true; + try { + const protonPath = await getAppSetting("proton_path"); + if (!protonPath) return; + const info = await tauriCmd.checkProtonGeUpdate(protonPath); + if (!info.updateAvailable) return; + toast.info(`Proton-GE ${info.latestVersion} is available`, { + id: `proton-update-${info.latestVersion}`, + description: `Current: ${info.currentVersion || "unknown"}. Update in Settings → Updates → Proton-GE.`, + duration: Infinity, + cancel: { label: "Dismiss", onClick: () => {} }, + }); + } catch { + // Silently ignore — background check should never surface errors + } finally { + protonCheckRef.current = false; + } + } async function checkForUpdate() { if (checkingRef.current) return; @@ -71,22 +95,35 @@ export function UpdateManager() { } useEffect(() => { - let intervalId: ReturnType | null = null; + let appIntervalId: ReturnType | null = null; + let protonIntervalId: ReturnType | null = null; (async () => { - const mode = await getAppSetting("app_update_check_mode"); - // Default to 'startup' if the key has never been set - if (mode === "off") return; + const [mode, protonMode] = await Promise.all([ + getAppSetting("app_update_check_mode"), + isLinux ? getAppSetting("proton_ge_check_mode") : Promise.resolve(null), + ]); - checkForUpdate(); + // LokiASAM app updates + if (mode !== "off") { + checkForUpdate(); + if (mode === "periodic") { + appIntervalId = setInterval(checkForUpdate, ONE_HOUR_MS); + } + } - if (mode === "periodic") { - intervalId = setInterval(checkForUpdate, ONE_HOUR_MS); + // Proton-GE updates (Linux only) + if (isLinux && protonMode && protonMode !== "disabled") { + checkForProtonUpdate(); + if (protonMode === "startup_hourly") { + protonIntervalId = setInterval(checkForProtonUpdate, ONE_HOUR_MS); + } } })(); return () => { - if (intervalId) clearInterval(intervalId); + if (appIntervalId) clearInterval(appIntervalId); + if (protonIntervalId) clearInterval(protonIntervalId); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index 6ed53ea..634f8cf 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -202,7 +202,7 @@ export function ServerCard({ server }: Props) { setLastBackup(lb); setNextRestart(nr); setBackupEnabled(be); - setAutoCheckEnabled((autoHours ?? "0") !== "0"); + setAutoCheckEnabled((autoHours ?? "disabled") !== "disabled"); } })(); return () => { cancelled = true; }; diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index 351594b..be93091 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -516,7 +516,7 @@ export function OverviewTab({ server }: Props) { setLastBackup(lb); setNextRestart(nr); setBackupEnabled(be); - setAutoCheckEnabled((autoHours ?? "0") !== "0"); + setAutoCheckEnabled((autoHours ?? "disabled") !== "disabled"); } })(); return () => { cancelled = true; }; diff --git a/src/components/shared/NotificationMatrix.tsx b/src/components/shared/NotificationMatrix.tsx index d83ecbd..8c66684 100644 --- a/src/components/shared/NotificationMatrix.tsx +++ b/src/components/shared/NotificationMatrix.tsx @@ -12,7 +12,7 @@ * Discord and SMTP columns are disabled if credentials are not yet configured. */ -import { useState, useEffect, useCallback } from "react"; +import { useState, useEffect, useCallback, forwardRef, useImperativeHandle } from "react"; import { toast } from "sonner"; import { Loader2, Bell, Monitor, MessageSquare, Mail } from "lucide-react"; import { @@ -58,11 +58,16 @@ const CHANNEL_DEFAULTS: Record = { // Component // --------------------------------------------------------------------------- +export interface NotificationMatrixHandle { + getChannelEvents: () => Record; +} + interface NotificationMatrixProps { onSaved?: () => void; } -export function NotificationMatrix({ onSaved }: NotificationMatrixProps) { +export const NotificationMatrix = forwardRef( +function NotificationMatrix({ onSaved }, ref) { const [channelEvents, setChannelEvents] = useState>>({ in_app: new Set(CHANNEL_DEFAULTS.in_app), bell: new Set(CHANNEL_DEFAULTS.bell), @@ -122,6 +127,13 @@ export function NotificationMatrix({ onSaved }: NotificationMatrixProps) { useEffect(() => { loadState(); }, [loadState]); + useImperativeHandle(ref, () => ({ + getChannelEvents: () => + Object.fromEntries( + Object.entries(channelEvents).map(([ch, set]) => [ch, [...set]]) + ), + }), [channelEvents]); + const handleToggle = useCallback(async (channel: ChannelId, event: NotificationEventType) => { const next = new Set(channelEvents[channel]); if (next.has(event)) { @@ -225,4 +237,5 @@ export function NotificationMatrix({ onSaved }: NotificationMatrixProps) {
); -} +}); +NotificationMatrix.displayName = "NotificationMatrix"; diff --git a/src/components/wizard/SetupWizard.tsx b/src/components/wizard/SetupWizard.tsx index 7cfdd3e..65afc59 100644 --- a/src/components/wizard/SetupWizard.tsx +++ b/src/components/wizard/SetupWizard.tsx @@ -37,8 +37,8 @@ import { useSetupStore } from "@/store/useSetupStore"; import { useAppStore } from "@/store/useAppStore"; import { tauriCmd, type DirCheckResult, type ProtonEntry } from "@/lib/tauri-commands"; import { applyTheme, ACCENT_OPTIONS, THEME_PRESETS, type ThemeAccent, type ThemePreset } from "@/lib/theme"; -import { setAppSetting, initDb } from "@/lib/db"; -import { NotificationMatrix } from "@/components/shared/NotificationMatrix"; +import { setAppSetting, initDb, saveNotificationConfig, saveGlobalChannelEvents } from "@/lib/db"; +import { NotificationMatrix, type NotificationMatrixHandle } from "@/components/shared/NotificationMatrix"; import { open } from "@tauri-apps/plugin-dialog"; import { homeDir, tempDir } from "@tauri-apps/api/path"; import { getVersion } from "@tauri-apps/api/app"; @@ -162,8 +162,8 @@ function WelcomeStep() {
{[ - { label: "Server Management", desc: "Start, stop & monitor" }, - { label: "Auto Scheduling", desc: "Backups & restarts" }, + { label: "Server Management", desc: "Start, Stop & Monitor" }, + { label: "Auto Scheduling", desc: "Backups & Restarts" }, { label: "Mod Browser", desc: "CurseForge integration" }, ].map((feat) => (

- This is where your ASA server files will be installed. Choose a drive with at least 20 GB of free space. + This is where your ASA server files will be installed. Choose a drive with at least 40 GB of free space.

@@ -1602,7 +1602,7 @@ function CertStep() { ); } -function NotificationsStep() { +function NotificationsStep({ matrixRef }: { matrixRef: React.RefObject }) { const { discordWebhook, setDiscordWebhook, smtpHost, setSmtpHost, @@ -1792,7 +1792,7 @@ function NotificationsStep() { Choose which events trigger each channel. Configure credentials above to unlock Discord and SMTP columns.

- + ); @@ -1876,7 +1876,7 @@ function TrayStep() { >

Desktop notifications: - OS desktop notifications (the pop-up alerts from your system) only appear when LokiASAM is minimized to the system tray. While the window is open or the app is fully closed, notifications are shown as in-app toasts instead. + OS desktop notifications (the pop-up alerts from your system) may only appear when LokiASAM is minimized to the system tray. This is dependent on your desktop environment and its notification settings, not LokiASAM itself.

@@ -1892,21 +1892,25 @@ function AutoUpdateStep() { const { asaAutoCheckHours, setAsaAutoCheckHours, appUpdateCheckMode, setAppUpdateCheckMode, - protonAutoCheckEnabled, setProtonAutoCheckEnabled, + protonCheckMode, setProtonCheckMode, } = useSetupStore(); const asaIntervals = [ - { value: "0", label: "Disabled" }, - { value: "1", label: "Hourly" }, - { value: "6", label: "Every 6h" }, - { value: "12", label: "Every 12h" }, - { value: "24", label: "Daily" }, + { value: "disabled", label: "Disabled" }, + { value: "startup", label: "On Startup" }, + { value: "startup_hourly", label: "On Startup + Hourly" }, ]; const appModes = [ - { value: "startup", label: "On Startup" }, - { value: "periodic", label: "Every Hour" }, { value: "off", label: "Disabled" }, + { value: "startup", label: "On Startup" }, + { value: "periodic", label: "On Startup + Hourly" }, + ]; + + const protonModes = [ + { value: "disabled", label: "Disabled" }, + { value: "startup", label: "On Startup" }, + { value: "startup_hourly", label: "On Startup + Hourly" }, ]; return ( @@ -1929,12 +1933,12 @@ function AutoUpdateStep() { Checks Steam for new ARK server builds and flags any servers that need updating. Updates are never applied automatically — you stay in control.

-
+
{asaIntervals.map(({ value, label }) => ( + ))} +
)} @@ -2214,7 +2234,7 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { discordWebhook, smtpHost, smtpPort, smtpUsername, smtpPassword, smtpUseTls, smtpFrom, smtpTo, closeToTray, - asaAutoCheckHours, appUpdateCheckMode, protonAutoCheckEnabled, + asaAutoCheckHours, appUpdateCheckMode, protonCheckMode, isLoading, importMode, importValid, importDir, } = useSetupStore(); @@ -2223,6 +2243,7 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { const [saveError, setSaveError] = useState(""); const [appVersion, setAppVersion] = useState("..."); const scrollAreaRef = useRef(null); + const matrixRef = useRef(null); useEffect(() => { getVersion().then(setAppVersion).catch(() => setAppVersion("")); @@ -2326,26 +2347,46 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { const prefix = baseDir.replace(/[/\\]$/, "") + sep + "lokiasam" + sep + "proton" + sep + "prefix"; await setAppSetting("proton_prefix_path", prefix); } - if (discordWebhook) await setAppSetting("discord_webhook", discordWebhook); + // Save Discord webhook as a notification_configs entry if provided + if (discordWebhook) { + await saveNotificationConfig({ + id: crypto.randomUUID(), serverId: null, channel: "discord", + enabled: true, + configJson: JSON.stringify({ webhookUrl: discordWebhook }), + eventsJson: "[]", + }); + } - // SMTP (only if host is set) + // Save SMTP config as a notification_configs entry if host is set if (smtpHost) { - await setAppSetting("smtp_host", smtpHost); - await setAppSetting("smtp_port", smtpPort); - await setAppSetting("smtp_username", smtpUsername); - await setAppSetting("smtp_password", smtpPassword); - await setAppSetting("smtp_use_tls", String(smtpUseTls)); - await setAppSetting("smtp_from", smtpFrom); - await setAppSetting("smtp_to", smtpTo); + await saveNotificationConfig({ + id: crypto.randomUUID(), serverId: null, channel: "email", + enabled: true, + configJson: JSON.stringify({ + host: smtpHost, port: smtpPort, + username: smtpUsername, password: smtpPassword, + fromAddress: smtpFrom, toAddress: smtpTo, + useTls: smtpUseTls, + }), + eventsJson: "[]", + }); + } + + // Save notification matrix channel event preferences + const channelEvents = matrixRef.current?.getChannelEvents(); + if (channelEvents) { + for (const [channel, events] of Object.entries(channelEvents)) { + await saveGlobalChannelEvents(channel, events); + } } // Tray preference await setAppSetting("close_to_tray", String(closeToTray)); // Auto-update preferences - await setAppSetting("asa_auto_check_hours", asaAutoCheckHours); - await setAppSetting("app_update_check_mode", appUpdateCheckMode); - if (IS_LINUX) await setAppSetting("proton_ge_auto_check", String(protonAutoCheckEnabled)); + await setAppSetting("asa_auto_check_hours", asaAutoCheckHours); + await setAppSetting("app_update_check_mode", appUpdateCheckMode); + if (IS_LINUX) await setAppSetting("proton_ge_check_mode", protonCheckMode); // Theme await setAppSetting("theme_preset", themePreset); @@ -2383,7 +2424,7 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { , , , - , + , , , , @@ -2395,7 +2436,7 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { , , , - , + , , , , diff --git a/src/lib/db.ts b/src/lib/db.ts index beb9451..29b5627 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -194,7 +194,7 @@ async function runMigrations(db: Database): Promise { ('asa_last_checked', ''), ('asa_cached_build_id', ''), ('asa_latest_build_id', ''), - ('asa_auto_check_hours', '1'), + ('asa_auto_check_hours', 'startup'), ('app_update_check_mode', 'startup'), ('auto_restart_downed', 'ask'), ('full_backup_warning_dismissed', 'false')`); diff --git a/src/lib/scheduler-sync.ts b/src/lib/scheduler-sync.ts index b540654..3e99aee 100644 --- a/src/lib/scheduler-sync.ts +++ b/src/lib/scheduler-sync.ts @@ -120,23 +120,42 @@ export async function syncSchedulesToRust(): Promise { } // ── Global auto-update-check entry ───────────────────────────────────── - // This is a synthetic entry (not in the schedules table) that fires the - // shared cache update on the interval configured in Settings. - const [autoCheckHours, lastChecked] = await Promise.all([ + // Fires the shared cache update on startup and/or hourly, depending on + // the asa_auto_check_hours setting: + // "startup" — fire once ~30 s after launch + // "startup_hourly" — fire ~30 s after launch, then repeat every hour + // "disabled" / "0" — no scheduled check + const [autoCheckMode, lastChecked] = await Promise.all([ getAppSetting("asa_auto_check_hours"), getAppSetting("asa_last_checked"), ]); - const hours = parseInt(autoCheckHours ?? "0"); - if (hours > 0 && steamcmdPath && baseDir) { - const intervalMs = hours * 3_600_000; + const mode = autoCheckMode ?? "disabled"; + const isStartupHourly = mode === "startup_hourly"; + const isStartup = mode === "startup" || isStartupHourly; + // Legacy numeric values ("1","6","12","24") treated as startup_hourly. + const legacyHours = parseInt(mode); + const isLegacy = !isNaN(legacyHours) && legacyHours > 0; + + if ((isStartup || isLegacy) && steamcmdPath && baseDir && servers.length > 0) { + const intervalMs = isStartupHourly || isLegacy ? 3_600_000 : 0; let nextRunMs: number; if (!lastChecked) { - // Never checked — wait 5 minutes after startup to let things settle. - nextRunMs = Date.now() + 5 * 60_000; - } else { + // Never checked — fire 30 s after startup. + nextRunMs = Date.now() + 30_000; + } else if (isStartupHourly || isLegacy) { const scheduled = new Date(lastChecked).getTime() + intervalMs; // If overdue, give a 30-second startup buffer before firing. nextRunMs = scheduled < Date.now() ? Date.now() + 30_000 : scheduled; + } else { + // "startup" mode — only fire if we've never checked (handled above). + // If already checked today, skip. + const sinceLastCheck = Date.now() - new Date(lastChecked).getTime(); + if (sinceLastCheck < 24 * 3_600_000) { + // Checked within the last 24 h; don't fire again on this session. + await tauriCmd.syncSchedules(entries); + return; + } + nextRunMs = Date.now() + 30_000; } entries.push({ @@ -159,7 +178,7 @@ export async function syncSchedulesToRust(): Promise { backupDir: "", scheduleType: "global_update_check", enabled: true, - configJson: "{}", + configJson: JSON.stringify({ intervalMs }), nextRunMs, }); } diff --git a/src/lib/update-utils.ts b/src/lib/update-utils.ts index 9849929..991f427 100644 --- a/src/lib/update-utils.ts +++ b/src/lib/update-utils.ts @@ -6,10 +6,11 @@ * update_available column in the DB and optionally fires notifications. */ -import { getServers, getAppSetting, setServerUpdateAvailable } from "@/lib/db"; +import { getServers, getAppSetting, setServerUpdateAvailable, setAppSetting } from "@/lib/db"; import { tauriCmd } from "@/lib/tauri-commands"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; +import { useAppStore } from "@/store/useAppStore"; // ── Types ───────────────────────────────────────────────────────────────────── @@ -28,6 +29,38 @@ export interface UpdateCheckSummary { allWithUpdates: ServerUpdateInfo[]; } +// ── ASA cache update (shared across dashboard, settings, scheduler) ─────────── + +/** + * Run a full ASA cache update/check via SteamCMD. Sets the global + * `asaCacheUpdateInProgress` flag in Zustand so the TopBar spinner shows. + * + * Returns the new build ID string, or null on error. + */ +export async function runAsaCacheUpdate(): Promise { + const { setAsaCacheUpdateInProgress } = useAppStore.getState(); + setAsaCacheUpdateInProgress(true); + try { + const [baseDir, steamcmdPath] = await Promise.all([ + getAppSetting("base_dir"), + getAppSetting("steamcmd_path"), + ]); + if (!baseDir || !steamcmdPath) return null; + const sep = baseDir.includes("\\") ? "\\" : "/"; + const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; + const newBuild = await tauriCmd.updateCache("check", cacheDir, steamcmdPath); + const now = new Date().toISOString(); + await Promise.all([ + setAppSetting("asa_cached_build_id", newBuild), + setAppSetting("asa_latest_build_id", newBuild), + setAppSetting("asa_last_checked", now), + ]); + return newBuild; + } finally { + setAsaCacheUpdateInProgress(false); + } +} + // ── Per-server update check ─────────────────────────────────────────────────── /** diff --git a/src/store/useAppStore.ts b/src/store/useAppStore.ts index c18b42b..a968390 100644 --- a/src/store/useAppStore.ts +++ b/src/store/useAppStore.ts @@ -117,6 +117,10 @@ interface AppState { /** Active countdown info keyed by server ID. Null means no countdown running. */ countdowns: Record; setCountdown: (serverId: string, entry: { action: 'restart' | 'update'; remainingSecs: number; totalSecs: number } | null) => void; + + /** True while an ASA cache update/check is running (shows spinner in TopBar). */ + asaCacheUpdateInProgress: boolean; + setAsaCacheUpdateInProgress: (v: boolean) => void; } export const useAppStore = create((set) => ({ @@ -205,4 +209,7 @@ export const useAppStore = create((set) => ({ countdowns: {}, setCountdown: (serverId, entry) => set((s) => ({ countdowns: { ...s.countdowns, [serverId]: entry } })), + + asaCacheUpdateInProgress: false, + setAsaCacheUpdateInProgress: (v) => set({ asaCacheUpdateInProgress: v }), })); diff --git a/src/store/useSetupStore.ts b/src/store/useSetupStore.ts index c90fc21..1c1972b 100644 --- a/src/store/useSetupStore.ts +++ b/src/store/useSetupStore.ts @@ -54,20 +54,13 @@ interface SetupState { smtpFrom: string; smtpTo: string; - // Notifications step — toggles - desktopNotificationsEnabled: boolean; - notifyServerStart: boolean; - notifyServerCrash: boolean; - notifyServerStop: boolean; - notifyUpdateAvailable: boolean; - // Tray step closeToTray: boolean; // Auto-update step - asaAutoCheckHours: string; // "0"|"1"|"6"|"12"|"24" + asaAutoCheckHours: string; // "disabled"|"startup"|"startup_hourly" appUpdateCheckMode: string; // "startup"|"periodic"|"off" - protonAutoCheckEnabled: boolean; + protonCheckMode: string; // "disabled"|"startup"|"startup_hourly" // Theme step themePreset: string; @@ -104,15 +97,10 @@ interface SetupState { setSmtpUseTls: (v: boolean) => void; setSmtpFrom: (v: string) => void; setSmtpTo: (v: string) => void; - setDesktopNotificationsEnabled: (v: boolean) => void; - setNotifyServerStart: (v: boolean) => void; - setNotifyServerCrash: (v: boolean) => void; - setNotifyServerStop: (v: boolean) => void; - setNotifyUpdateAvailable: (v: boolean) => void; setCloseToTray: (v: boolean) => void; setAsaAutoCheckHours: (v: string) => void; setAppUpdateCheckMode: (v: string) => void; - setProtonAutoCheckEnabled: (v: boolean) => void; + setProtonCheckMode: (v: string) => void; setThemePreset: (v: string) => void; setThemeAccent: (v: string) => void; setLoading: (loading: boolean, message?: string) => void; @@ -144,15 +132,10 @@ const initialState = { smtpUseTls: true, smtpFrom: "", smtpTo: "", - desktopNotificationsEnabled: true, - notifyServerStart: true, - notifyServerCrash: true, - notifyServerStop: false, - notifyUpdateAvailable: true, closeToTray: true, - asaAutoCheckHours: "1", + asaAutoCheckHours: "startup", appUpdateCheckMode: "startup", - protonAutoCheckEnabled: true, + protonCheckMode: "startup_hourly", themePreset: "storm", themeAccent: "blue", isLoading: false, @@ -188,15 +171,10 @@ export const useSetupStore = create((set, get) => ({ setSmtpUseTls: (smtpUseTls) => set({ smtpUseTls }), setSmtpFrom: (smtpFrom) => set({ smtpFrom }), setSmtpTo: (smtpTo) => set({ smtpTo }), - setDesktopNotificationsEnabled: (desktopNotificationsEnabled) => set({ desktopNotificationsEnabled }), - setNotifyServerStart: (notifyServerStart) => set({ notifyServerStart }), - setNotifyServerCrash: (notifyServerCrash) => set({ notifyServerCrash }), - setNotifyServerStop: (notifyServerStop) => set({ notifyServerStop }), - setNotifyUpdateAvailable: (notifyUpdateAvailable) => set({ notifyUpdateAvailable }), setCloseToTray: (closeToTray) => set({ closeToTray }), setAsaAutoCheckHours: (asaAutoCheckHours) => set({ asaAutoCheckHours }), setAppUpdateCheckMode: (appUpdateCheckMode) => set({ appUpdateCheckMode }), - setProtonAutoCheckEnabled: (protonAutoCheckEnabled) => set({ protonAutoCheckEnabled }), + setProtonCheckMode: (protonCheckMode) => set({ protonCheckMode }), setThemePreset: (themePreset) => set({ themePreset }), setThemeAccent: (themeAccent) => set({ themeAccent }), setLoading: (isLoading, message = "") => From 3139b2c9b958bcdcc81caac570b3813fa9637111 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 15 Jun 2026 14:58:24 -0500 Subject: [PATCH 02/19] feat: enhance context menu functionality with improved selection handling and overlay management --- src/components/layout/DisableContextMenu.tsx | 66 ++++++++++++++------ 1 file changed, 46 insertions(+), 20 deletions(-) diff --git a/src/components/layout/DisableContextMenu.tsx b/src/components/layout/DisableContextMenu.tsx index 34098e8..01f1af8 100644 --- a/src/components/layout/DisableContextMenu.tsx +++ b/src/components/layout/DisableContextMenu.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect, useState, useCallback } from "react"; +import { useEffect, useState, useCallback, useRef } from "react"; import { writeText, readText } from "@tauri-apps/plugin-clipboard-manager"; interface MenuState { @@ -16,12 +16,19 @@ interface MenuState { export function DisableContextMenu() { const [menu, setMenu] = useState(null); + // Saved on right-click mousedown so contextmenu can read it even if WebkitGTK + // clears the DOM selection before the contextmenu event fires. + const pendingSelectionRef = useRef(""); + // Ref to the overlay div — used in handleMouseDown to skip close() for inside-overlay + // clicks without stopPropagation (which breaks the pointer event chain in WebkitGTK). + const overlayRef = useRef(null); const handleContextMenu = useCallback((e: MouseEvent) => { e.preventDefault(); - // Capture selection NOW — a subsequent mousedown/click will clear it. - const selectedText = window.getSelection()?.toString() ?? ""; + // Use selection captured at mousedown time (WebkitGTK may clear it before contextmenu fires). + const selectedText = pendingSelectionRef.current || (window.getSelection()?.toString() ?? ""); + pendingSelectionRef.current = ""; const canCopy = selectedText.length > 0; const target = e.target as HTMLElement; @@ -30,7 +37,10 @@ export function DisableContextMenu() { target instanceof HTMLTextAreaElement || target.isContentEditable; - if (!canCopy && !canPaste) return; + if (!canCopy && !canPaste) { + setMenu(null); + return; + } // Capture cursor position so paste inserts at the right spot. let selStart = 0; @@ -55,6 +65,19 @@ export function DisableContextMenu() { const close = useCallback(() => setMenu(null), []); + const handleMouseDown = useCallback((e: MouseEvent) => { + // Never close the menu when clicking inside the overlay — use contains() instead of + // stopPropagation so the full event chain reaches WebkitGTK and pointer events work. + if (overlayRef.current?.contains(e.target as Node)) return; + + if (e.button === 2) { + pendingSelectionRef.current = window.getSelection()?.toString() ?? ""; + } else { + pendingSelectionRef.current = ""; + } + setMenu(null); + }, []); + const handleCopy = useCallback(() => { const text = menu?.selectedText ?? ""; setMenu(null); @@ -71,34 +94,36 @@ export function DisableContextMenu() { setMenu(null); if (!target) return; - // rAF: let the menu overlay disappear so the target can regain focus first. - requestAnimationFrame(() => { - target.focus(); - // Use the Tauri clipboard plugin — reads from the real OS clipboard. - readText() - .then((text) => { - if (text) insertAt(target, text, selStart, selEnd); - }) - .catch(() => {}); - }); + // Use the Tauri plugin — navigator.clipboard.readText() requires a user-gesture + // context that WebkitGTK considers expired by the time our async handler runs. + // The Tauri plugin makes a direct Rust call that bypasses this restriction. + readText() + .then((text) => { + if (text) { + target.focus(); + insertAt(target, text, selStart, selEnd); + } + }) + .catch(() => {}); }, [menu]); useEffect(() => { document.addEventListener("contextmenu", handleContextMenu); - document.addEventListener("mousedown", close); + document.addEventListener("mousedown", handleMouseDown); document.addEventListener("keydown", close); return () => { document.removeEventListener("contextmenu", handleContextMenu); - document.removeEventListener("mousedown", close); + document.removeEventListener("mousedown", handleMouseDown); document.removeEventListener("keydown", close); }; - }, [handleContextMenu, close]); + }, [handleContextMenu, handleMouseDown, close]); if (!menu) return null; return (
e.stopPropagation()} > {menu.canCopy && ( @@ -175,7 +199,9 @@ function ContextMenuItem({
); @@ -2243,7 +2244,10 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { const [saveError, setSaveError] = useState(""); const [appVersion, setAppVersion] = useState("..."); const scrollAreaRef = useRef(null); - const matrixRef = useRef(null); + // Stores the wizard's notification matrix state as the user toggles checkboxes. + // Kept in a ref (not state) so navigating away from the notifications step + // doesn't lose the values when the step component unmounts and clears its ref. + const matrixEventsRef = useRef | null>(null); useEffect(() => { getVersion().then(setAppVersion).catch(() => setAppVersion("")); @@ -2353,7 +2357,7 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { id: crypto.randomUUID(), serverId: null, channel: "discord", enabled: true, configJson: JSON.stringify({ webhookUrl: discordWebhook }), - eventsJson: "[]", + eventsJson: JSON.stringify(Object.values(NOTIFICATION_EVENTS)), }); } @@ -2368,14 +2372,16 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { fromAddress: smtpFrom, toAddress: smtpTo, useTls: smtpUseTls, }), - eventsJson: "[]", + eventsJson: JSON.stringify(Object.values(NOTIFICATION_EVENTS)), }); } - // Save notification matrix channel event preferences - const channelEvents = matrixRef.current?.getChannelEvents(); - if (channelEvents) { - for (const [channel, events] of Object.entries(channelEvents)) { + // Save notification matrix channel event preferences. + // matrixEventsRef is populated by the onChange callback in NotificationsStep; + // if the user never touched the matrix it stays null and we skip + // (channels will fall back to their default all-events-on behaviour). + if (matrixEventsRef.current) { + for (const [channel, events] of Object.entries(matrixEventsRef.current)) { await saveGlobalChannelEvents(channel, events); } } @@ -2424,7 +2430,7 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { , , , - , + { matrixEventsRef.current = e; }} />, , , , @@ -2436,7 +2442,7 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { , , , - , + { matrixEventsRef.current = e; }} />, , , , From ebac1cfbc6188e7010b4b0980f730e72765e180c Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Mon, 15 Jun 2026 21:44:22 -0500 Subject: [PATCH 04/19] fix: use RCON saveworld/doexit for server restarts instead of SIGTERM MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The restart button was killing the server process with SIGTERM rather than sending the graceful shutdown sequence through RCON. This caused the server to close instantly on restart while the stop button took the expected ~1 minute because it already went through graceful_stop_server. Restart now sends saveworld → 2s delay → doexit via RCON and waits up to 30 seconds for a clean exit before force-killing, matching the behaviour of the stop button. Added rcon_password to StartServerParams (Rust struct and TS interface) so inner_restart_server has everything it needs without requiring a separate tauri command. --- src-tauri/src/commands/scheduler.rs | 1 + src-tauri/src/commands/server.rs | 27 +++++++++++++++------- src/components/server/ServerCard.tsx | 1 + src/components/server/tabs/OverviewTab.tsx | 1 + src/lib/server-utils.ts | 17 +++++++------- src/lib/tauri-commands.ts | 2 ++ 6 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index b6e175d..f8823f2 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -354,6 +354,7 @@ fn entry_to_start_params(entry: &crate::state::scheduler::ScheduleEntry) -> Star port: entry.port, query_port: entry.query_port, rcon_port: entry.rcon_port, + rcon_password: entry.rcon_password.clone(), extra_args: entry.extra_args.clone(), mod_ids: entry.mod_ids.clone(), proton_path: entry.proton_path.clone(), diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 619f0aa..13de218 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -105,6 +105,9 @@ pub struct StartServerParams { /// RCON TCP port — NOT passed on CLI; used internally for readiness polling. /// The actual value is read by the server from GameUserSettings.ini [ServerSettings]. pub rcon_port: u16, + /// RCON password — NOT passed on CLI; used internally for graceful shutdown + /// (saveworld/doexit) and readiness polling. + pub rcon_password: String, /// Additional CLI-only flags, e.g. ["-NoBattlEye", "-ForceRespawnDinos"]. pub extra_args: Vec, /// CurseForge mod IDs to load. Passed as `-mods=id1,id2,...`. @@ -811,17 +814,25 @@ pub async fn inner_restart_server( state.stopping_servers.lock().unwrap().insert(params.server_id.clone()); } - kill_process_tree(pid, graceful, &install_path); - - // Wait up to 15 s for the process to exit. - for _ in 0..30 { - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - if !pid_alive(pid) { - break; + if graceful { + // Graceful path: ask the server to save and exit via RCON so it + // flushes world data cleanly (same as the Stop button does). + use crate::commands::rcon::transient_rcon_command; + let _ = transient_rcon_command(params.rcon_port, ¶ms.rcon_password, "saveworld").await; + tokio::time::sleep(tokio::time::Duration::from_secs(2)).await; + let _ = transient_rcon_command(params.rcon_port, ¶ms.rcon_password, "doexit").await; + + // Wait up to 30 s for the server to exit cleanly. + for _ in 0..60 { + tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; + if !pid_alive(pid) { break; } } + } else { + kill_process_tree(pid, false, &install_path); + tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; } - // Ensure it's gone regardless. + // Force-kill anything still alive after the graceful window. if pid_alive(pid) { kill_process_tree(pid, false, &install_path); tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index 634f8cf..51007bc 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -241,6 +241,7 @@ export function ServerCard({ server }: Props) { port: server.port, queryPort: server.query_port, rconPort: server.rcon_port, + rconPassword: server.rcon_password, extraArgs, modIds: enabledModIds, }; diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index be93091..14c3ee7 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -547,6 +547,7 @@ export function OverviewTab({ server }: Props) { port: server.port, queryPort: server.query_port, rconPort: server.rcon_port, + rconPassword: server.rcon_password, extraArgs, modIds: enabledModIds, }; diff --git a/src/lib/server-utils.ts b/src/lib/server-utils.ts index db32ab0..466531b 100644 --- a/src/lib/server-utils.ts +++ b/src/lib/server-utils.ts @@ -35,15 +35,16 @@ export async function buildStartParams(server: ServerRow): Promise 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, + 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, + modIds: enabledModIds, }; if (isLinux) { diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index df87a6f..f72db2e 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -78,6 +78,8 @@ export interface StartServerParams { queryPort: number; /** NOT passed on CLI — used internally by Rust for RCON readiness polling. */ rconPort: number; + /** NOT passed on CLI — used internally by Rust for graceful shutdown (saveworld/doexit). */ + rconPassword: string; /** Additional CLI-only flags like ["-NoBattlEye", "-ForceRespawnDinos"]. */ extraArgs: string[]; /** CurseForge mod IDs to pass as -mods=id1,id2,... on startup. */ From f9ac30c94300bd033673e2ef152a4987bda1453b Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 16 Jun 2026 01:55:50 -0500 Subject: [PATCH 05/19] feat: implement live chat log updates in ChatPanel using Tauri events --- src-tauri/src/commands/rcon.rs | 148 ++++++++++++++----------- src/components/server/tabs/LogsTab.tsx | 16 ++- 2 files changed, 97 insertions(+), 67 deletions(-) diff --git a/src-tauri/src/commands/rcon.rs b/src-tauri/src/commands/rcon.rs index e4b0e1c..8df43b2 100644 --- a/src-tauri/src/commands/rcon.rs +++ b/src-tauri/src/commands/rcon.rs @@ -393,78 +393,94 @@ pub async fn rcon_connect( error: None, }); - let stream = timeout( - Duration::from_secs(5), - TcpStream::connect(format!("{host}:{port}")), - ) - .await - .map_err(|_| "RCON connection timed out".to_string())? - .map_err(|e| format!("RCON connect failed: {e}"))?; - - let _ = stream.set_nodelay(true); - let mut conn = RconConn { stream, next_id: 1 }; - - let auth_id = conn.next_id; - conn.next_id += 1; - conn.send_packet(auth_id, RCON_AUTH, &password).await?; + // Run the full connect+auth sequence in an inner block so every failure + // path falls through to a single "disconnected" emit below. + let result: Result<(), String> = async { + let stream = timeout( + Duration::from_secs(5), + TcpStream::connect(format!("{host}:{port}")), + ) + .await + .map_err(|_| "RCON connection timed out".to_string())? + .map_err(|e| format!("RCON connect failed: {e}"))?; - let mut authenticated = false; - for _ in 0..3 { - let result = timeout(Duration::from_secs(5), conn.recv_packet()) - .await - .map_err(|_| "RCON auth timed out — no response from server".to_string())?; - let (resp_id, resp_type, _body) = result?; - if resp_type == RCON_AUTH_RESPONSE { - if resp_id == -1 { - return Err("RCON authentication failed — wrong password".into()); - } - if resp_id == auth_id { - authenticated = true; - break; + let _ = stream.set_nodelay(true); + let mut conn = RconConn { stream, next_id: 1 }; + + let auth_id = conn.next_id; + conn.next_id += 1; + conn.send_packet(auth_id, RCON_AUTH, &password).await?; + + let mut authenticated = false; + for _ in 0..3 { + let result = timeout(Duration::from_secs(5), conn.recv_packet()) + .await + .map_err(|_| "RCON auth timed out — no response from server".to_string())?; + let (resp_id, resp_type, _body) = result?; + if resp_type == RCON_AUTH_RESPONSE { + if resp_id == -1 { + return Err("RCON authentication failed — wrong password".into()); + } + if resp_id == auth_id { + authenticated = true; + break; + } } } - } - if !authenticated { - return Err("RCON authentication failed — unexpected response sequence".into()); - } - - let conn_id = pool.alloc_conn_id(); - let (tx, rx) = mpsc::channel::(32); - pool.cmd_channels.lock().await.insert(server_id.clone(), (tx.clone(), conn_id)); - - // Spawn the manager task — it owns the connection from here on. - let app_clone = app.clone(); - let sid = server_id.clone(); - let h = host.clone(); - tauri::async_runtime::spawn(async move { - run_rcon_manager(sid, conn_id, conn, rx, app_clone, h, port).await; - }); - - emit_log(&app, &server_id, RconLogLine { - timestamp_ms: now_ms(), - text: format!("Connected to RCON at {host}:{port}"), - kind: "system".into(), - }).await; - - emit_status(&app, RconStatusPayload { - server_id: server_id.clone(), - status: "connected".into(), - host: Some(host), - port: Some(port), - error: None, - }); - - // Seed the player cache asynchronously — the event will update the frontend. - let tx_seed = tx.clone(); - tauri::async_runtime::spawn(async move { - let (resp_tx, resp_rx) = oneshot::channel(); - if tx_seed.send(RconCmd::GetPlayers { response_tx: resp_tx }).await.is_ok() { - let _ = resp_rx.await; + if !authenticated { + return Err("RCON authentication failed — unexpected response sequence".into()); } - }); - Ok(()) + let conn_id = pool.alloc_conn_id(); + let (tx, rx) = mpsc::channel::(32); + pool.cmd_channels.lock().await.insert(server_id.clone(), (tx.clone(), conn_id)); + + // Spawn the manager task — it owns the connection from here on. + let app_clone = app.clone(); + let sid = server_id.clone(); + let h = host.clone(); + tauri::async_runtime::spawn(async move { + run_rcon_manager(sid, conn_id, conn, rx, app_clone, h, port).await; + }); + + emit_log(&app, &server_id, RconLogLine { + timestamp_ms: now_ms(), + text: format!("Connected to RCON at {host}:{port}"), + kind: "system".into(), + }).await; + + emit_status(&app, RconStatusPayload { + server_id: server_id.clone(), + status: "connected".into(), + host: Some(host.clone()), + port: Some(port), + error: None, + }); + + // Seed the player cache asynchronously — the event will update the frontend. + let tx_seed = tx.clone(); + tauri::async_runtime::spawn(async move { + let (resp_tx, resp_rx) = oneshot::channel(); + if tx_seed.send(RconCmd::GetPlayers { response_tx: resp_tx }).await.is_ok() { + let _ = resp_rx.await; + } + }); + + Ok(()) + }.await; + + if let Err(ref e) = result { + emit_status(&app, RconStatusPayload { + server_id, + status: "disconnected".into(), + host: Some(host), + port: Some(port), + error: Some(e.clone()), + }); + } + + result } /// Send an RCON command through the manager task queue. diff --git a/src/components/server/tabs/LogsTab.tsx b/src/components/server/tabs/LogsTab.tsx index 8a6419d..110a12d 100644 --- a/src/components/server/tabs/LogsTab.tsx +++ b/src/components/server/tabs/LogsTab.tsx @@ -10,8 +10,9 @@ import { Input } from "@/components/ui/input"; import { tauriCmd } from "@/lib/tauri-commands"; import type { ServerRow } from "@/lib/db"; import type { - ArchivedLogInfo, CrashInfo, CrashReport, ChatLogInfo, OtherLogInfo, + ArchivedLogInfo, CrashInfo, CrashReport, ChatLogInfo, OtherLogInfo, RconLogLine, } from "@/lib/tauri-commands"; +import { useTauriEvent } from "@/hooks/useTauriEvent"; import { getKnownPlayers, getPlayerKnownIps, getPlayerConnectionHistory, getPossibleAlts, type PlayerConnectionRow, @@ -734,6 +735,19 @@ function ChatPanel({ server }: { server: ServerRow }) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [chatLogs]); + // Live-append incoming chat lines so the panel updates without manual refresh. + const todayFilename = `chat_${new Date().toISOString().slice(0, 10)}.log`; + useTauriEvent(`rcon://log/${server.id}`, (line) => { + if (line.kind !== "chat") return; + if (selected?.filename === todayFilename) { + // Append to the currently-visible file content. + setLines((prev) => [...prev, line.text]); + } else if (!chatLogs.some((cl) => cl.filename === todayFilename)) { + // Today's file just appeared for the first time — refresh the list so it shows. + load(); + } + }); + const visibleLines = search ? lines.filter((l) => l.toLowerCase().includes(search.toLowerCase())) : lines; From e32495ba15776226d98402548a79a3495aec023f Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 16 Jun 2026 02:01:24 -0500 Subject: [PATCH 06/19] feat: improve backup scheduling accuracy and enhance UI layout in BackupsTab --- src-tauri/src/commands/backup_manager.rs | 127 +++++++++++++++++----- src-tauri/src/lib.rs | 9 +- src/components/server/tabs/BackupsTab.tsx | 2 +- 3 files changed, 106 insertions(+), 32 deletions(-) diff --git a/src-tauri/src/commands/backup_manager.rs b/src-tauri/src/commands/backup_manager.rs index 69b2656..64824d5 100644 --- a/src-tauri/src/commands/backup_manager.rs +++ b/src-tauri/src/commands/backup_manager.rs @@ -513,7 +513,7 @@ pub async fn execute_tick(app: &AppHandle) { } // ── Server backup ────────────────────────────────────────────────── - if server_active { + let server_outcome: Option> = if server_active { if let Some(cfg) = server_cfg { match create_server_backup_inner( app, @@ -530,33 +530,22 @@ pub async fn execute_tick(app: &AppHandle) { ).await { Ok(rec) => { handle_backup_record(&conn, &rec, &cfg, "server", None); - let size = fmt_size(rec.file_size_bytes); - crate::commands::notifications::dispatch_notification( - app, "backup_completed", Some(&server.id), &server.name, - "Backup Complete", &format!("Scheduled server backup completed ({size})"), "success", - ).await; - let _ = app.emit( - &format!("backup://completed/{}", server.id), - serde_json::json!({ "serverId": server.id }), - ); + Some(Ok(fmt_size(rec.file_size_bytes))) } Err(e) => { eprintln!("[backup_manager] Server backup failed for {}: {e}", server.name); - crate::commands::notifications::dispatch_notification( - app, "backup_failed", Some(&server.id), &server.name, - "Backup Failed", &format!("Scheduled server backup failed: {e}"), "error", - ).await; - let _ = app.emit( - &format!("backup://completed/{}", server.id), - serde_json::json!({ "serverId": server.id, "error": e }), - ); + Some(Err(e)) } } + } else { + None } - } + } else { + None + }; // ── Player backup ────────────────────────────────────────────────── - if player_active { + let player_outcome: Option> = if player_active { if let Some(cfg) = player_cfg { match backup_all_players_inner( app, @@ -574,22 +563,100 @@ pub async fn execute_tick(app: &AppHandle) { let eos_id = rec.player_eosid.as_deref(); handle_backup_record(&conn, rec, &cfg, "player", eos_id); } - if count > 0 { - crate::commands::notifications::dispatch_notification( - app, "backup_completed", Some(&server.id), &server.name, - "Backup Complete", &format!("Scheduled player backups completed ({count} players)"), "success", - ).await; - } + Some(Ok(count)) } Err(e) => { eprintln!("[backup_manager] Player backup failed for {}: {e}", server.name); - crate::commands::notifications::dispatch_notification( - app, "backup_failed", Some(&server.id), &server.name, - "Backup Failed", &format!("Scheduled player backup failed: {e}"), "error", - ).await; + Some(Err(e)) } } + } else { + None } + } else { + None + }; + + // ── Consolidated notification ────────────────────────────────────── + // One notification per server per tick regardless of how many backup + // types ran. Titles are specific when only one type ran; generic when + // both ran so the body can carry the combined detail. + let notification: Option<(&str, &str, String, &str)> = match (&server_outcome, &player_outcome) { + // Both ran — both succeeded + (Some(Ok(size)), Some(Ok(count))) if *count > 0 => Some(( + "backup_completed", "Backup Complete", + format!("Server backup: {size} · {count} players backed up"), + "success", + )), + // Both ran — server ok, players ran but 0 profiles found + (Some(Ok(size)), Some(Ok(_))) => Some(( + "backup_completed", "Server Backup Complete", + format!("Scheduled server backup completed ({size})"), + "success", + )), + // Both ran — server ok, players failed + (Some(Ok(size)), Some(Err(pe))) => Some(( + "backup_failed", "Backup Partially Failed", + format!("Server backup complete ({size}) · Player backup failed: {pe}"), + "error", + )), + // Both ran — server failed, players ok + (Some(Err(se)), Some(Ok(count))) if *count > 0 => Some(( + "backup_failed", "Backup Partially Failed", + format!("Server backup failed: {se} · {count} player backups complete"), + "error", + )), + // Both ran — server failed, 0 players + (Some(Err(se)), Some(Ok(_))) => Some(( + "backup_failed", "Server Backup Failed", + format!("Scheduled server backup failed: {se}"), + "error", + )), + // Both ran — both failed + (Some(Err(se)), Some(Err(pe))) => Some(( + "backup_failed", "Backup Failed", + format!("Server backup failed: {se} · Player backup failed: {pe}"), + "error", + )), + // Server only + (Some(Ok(size)), None) => Some(( + "backup_completed", "Server Backup Complete", + format!("Scheduled server backup completed ({size})"), + "success", + )), + (Some(Err(se)), None) => Some(( + "backup_failed", "Server Backup Failed", + format!("Scheduled server backup failed: {se}"), + "error", + )), + // Player only + (None, Some(Ok(count))) if *count > 0 => Some(( + "backup_completed", "Player Backup Complete", + format!("Scheduled player backups completed ({count} players)"), + "success", + )), + (None, Some(Err(pe))) => Some(( + "backup_failed", "Player Backup Failed", + format!("Scheduled player backup failed: {pe}"), + "error", + )), + // Player only with 0 profiles, or nothing ran + _ => None, + }; + + if let Some((event_type, title, body, severity)) = notification { + crate::commands::notifications::dispatch_notification( + app, event_type, Some(&server.id), &server.name, + title, &body, severity, + ).await; + } + + // Single UI-refresh event whenever any backup was attempted for this server. + if server_outcome.is_some() || player_outcome.is_some() { + let _ = app.emit( + &format!("backup://completed/{}", server.id), + serde_json::json!({ "serverId": server.id }), + ); } } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index c9f119e..ad1abf9 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -255,7 +255,14 @@ pub fn run() { loop { crate::commands::backup_manager::execute_tick(&backup_tick_handle).await; - tokio::time::sleep(tokio::time::Duration::from_secs(3600)).await; + // Re-anchor to the next wall-clock hour boundary after each + // tick so backup execution time does not cause cumulative drift. + let now_secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let secs_until_next_hour = 3600 - (now_secs % 3600); + tokio::time::sleep(tokio::time::Duration::from_secs(secs_until_next_hour)).await; } }); diff --git a/src/components/server/tabs/BackupsTab.tsx b/src/components/server/tabs/BackupsTab.tsx index cd8b60f..af75b72 100644 --- a/src/components/server/tabs/BackupsTab.tsx +++ b/src/components/server/tabs/BackupsTab.tsx @@ -1018,7 +1018,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { const editScheduleBtn = onNavigateToAutomation ? handleEditSchedule : undefined; return ( -
+
{/* Progress overlay */} {progress.active && (
Date: Tue, 16 Jun 2026 02:09:55 -0500 Subject: [PATCH 07/19] feat: enhance server statistics display in TopBar and remove update notification from ServerCard --- src/app/page.tsx | 29 ++++++++---------------- src/components/layout/TopBar.tsx | 34 ++++++++++++++++++++++++---- src/components/server/ServerCard.tsx | 9 -------- 3 files changed, 40 insertions(+), 32 deletions(-) diff --git a/src/app/page.tsx b/src/app/page.tsx index de44b2c..d53f286 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -2,7 +2,7 @@ import { useEffect, useState, useCallback, useRef } from "react"; import { - Plus, Server, Activity, PowerOff, Power, RefreshCw, Upload, + Plus, Server, Activity, RefreshCw, Upload, ArrowUp, Loader2, CheckCircle2, AlertTriangle, LayoutDashboard, } from "lucide-react"; import { Button } from "@/components/ui/button"; @@ -403,9 +403,7 @@ export default function DashboardPage() { const [updatingAll, setUpdatingAll] = useState(false); const queryClient = useQueryClient(); - const total = servers.length; - const running = servers.filter((s) => s.status === "running").length; - const stopped = total - running; + const total = servers.length; // Build the ServerUpdateInfo list from the live servers data. const serversWithUpdates: ServerUpdateInfo[] = servers @@ -533,22 +531,15 @@ export default function DashboardPage() {
- {/* ── Global stats bar ── */} - {total > 0 && ( + {/* ── Needs Attention warning — only shown when servers are in a bad state ── */} + {total > 0 && servers.some((s) => s.status === "crashed" || s.status === "error") && (
- - - 0 ? "var(--text-muted)" : "var(--neon-green)"} /> - {servers.some((s) => s.status === "crashed" || s.status === "error") && ( - s.status === "crashed" || s.status === "error").length} - icon={Activity} - color="var(--neon-red)" - /> - )} + s.status === "crashed" || s.status === "error").length} + icon={Activity} + color="var(--neon-red)" + />
)} diff --git a/src/components/layout/TopBar.tsx b/src/components/layout/TopBar.tsx index 1179644..7b7fd3c 100644 --- a/src/components/layout/TopBar.tsx +++ b/src/components/layout/TopBar.tsx @@ -1,21 +1,47 @@ "use client"; import { NotificationBell } from "@/components/layout/NotificationBell"; -import { Server, Activity, Users, RefreshCw } from "lucide-react"; +import { Server, Activity, Users, RefreshCw, Cpu, MemoryStick } from "lucide-react"; import { useServers } from "@/hooks/useServers"; import { useAppStore } from "@/store/useAppStore"; export function TopBar() { const { data: servers = [] } = useServers(); const asaCacheUpdateInProgress = useAppStore((s) => s.asaCacheUpdateInProgress); + const statsLiveBuffers = useAppStore((s) => s.statsLiveBuffers); const total = servers.length; const running = servers.filter((s) => s.status === "running").length; + // Aggregate CPU, RAM, and players from the live buffer across all active servers. + let totalPlayers: number | null = null; + let totalCpu: number | null = null; + let totalRamMb: number | null = null; + + const activeStatuses = new Set(["running", "starting"]); + for (const server of servers) { + if (!activeStatuses.has(server.status)) continue; + const buf = statsLiveBuffers[server.id]; + if (!buf || buf.length === 0) continue; + const latest = buf[buf.length - 1]; + if (latest.players !== null) totalPlayers = (totalPlayers ?? 0) + latest.players; + if (latest.cpu !== null) totalCpu = (totalCpu ?? 0) + latest.cpu; + if (latest.mem !== null) totalRamMb = (totalRamMb ?? 0) + latest.mem; + } + + const cpuDisplay = totalCpu !== null ? `${totalCpu.toFixed(1)}%` : "—"; + const ramDisplay = totalRamMb !== null + ? totalRamMb >= 1024 + ? `${(totalRamMb / 1024).toFixed(1)} GB` + : `${Math.round(totalRamMb)} MB` + : "—"; + const stats = [ - { icon: Server, label: "Servers", value: total, color: "var(--text-muted)" }, - { icon: Activity, label: "Running", value: running, color: running > 0 ? "var(--neon-green)" : "var(--text-muted)" }, - { icon: Users, label: "Players", value: "—", color: "var(--text-muted)" }, + { icon: Server, label: "Servers", value: total, color: "var(--text-muted)" }, + { icon: Activity, label: "Running", value: running, color: running > 0 ? "var(--neon-green)" : "var(--text-muted)" }, + { icon: Users, label: "Players", value: totalPlayers !== null ? totalPlayers : "—", color: totalPlayers !== null && totalPlayers > 0 ? "var(--neon-cyan)" : "var(--text-muted)" }, + { icon: Cpu, label: "CPU", value: cpuDisplay, color: totalCpu !== null ? "var(--neon-purple)" : "var(--text-muted)" }, + { icon: MemoryStick, label: "RAM", value: ramDisplay, color: totalRamMb !== null ? "var(--neon-purple)" : "var(--text-muted)" }, ]; return ( diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index 51007bc..68838a5 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -505,15 +505,6 @@ export function ServerCard({ server }: Props) { : `Updating in ${formatCountdown(countdown.remainingSecs)}` : undefined} /> - {hasUpdateAvailable && ( - - - Update - - )}
Date: Tue, 16 Jun 2026 11:03:35 -0500 Subject: [PATCH 08/19] fix: update schedule filtering logic to include only enabled schedules --- src/lib/scheduler-sync.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/scheduler-sync.ts b/src/lib/scheduler-sync.ts index 3e99aee..3bb3ace 100644 --- a/src/lib/scheduler-sync.ts +++ b/src/lib/scheduler-sync.ts @@ -48,7 +48,7 @@ export async function syncSchedulesToRust(): Promise { for (const server of servers) { const schedules = await getServerSchedules(server.id); - const enabled = schedules.filter((s) => s.enabled === 1 && s.next_run); + const enabled = schedules.filter((s) => s.enabled === 1); if (enabled.length === 0) continue; const [config, mods] = await Promise.all([ From f9aac441f5e241332d7ded0412514089423f0dce Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 16 Jun 2026 11:08:25 -0500 Subject: [PATCH 09/19] refactor: remove unused log statistics and schedule commands from backend --- src-tauri/src/commands/logs.rs | 67 -------------------- src-tauri/src/commands/scheduler.rs | 31 +-------- src-tauri/src/lib.rs | 4 -- src/components/server/tabs/AutomationTab.tsx | 10 +-- src/lib/db.ts | 11 ---- src/lib/tauri-commands.ts | 22 ------- 6 files changed, 4 insertions(+), 141 deletions(-) diff --git a/src-tauri/src/commands/logs.rs b/src-tauri/src/commands/logs.rs index 17d61e1..34d56a7 100644 --- a/src-tauri/src/commands/logs.rs +++ b/src-tauri/src/commands/logs.rs @@ -50,17 +50,6 @@ pub struct ChatLogInfo { pub full_path: String, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct LogStats { - pub shootergame_archive_count: u32, - pub shootergame_total_bytes: u64, - pub chat_log_count: u32, - pub chat_total_bytes: u64, - pub crash_count: u32, - pub storage_root: String, -} - // --------------------------------------------------------------------------- // Watch commands // --------------------------------------------------------------------------- @@ -552,39 +541,6 @@ pub async fn cleanup_logs( Ok(deleted) } -/// Get log storage statistics for a server. -#[tauri::command] -pub async fn get_log_stats( - app: tauri::AppHandle, - server_id: String, -) -> Result { - let root = LogManagerState::server_logs_dir(&app, &server_id); - let storage_root = root - .as_ref() - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_default(); - - let sg_dir = root.as_ref().map(|d| d.join("shootergame")); - let chat_dir = root.as_ref().map(|d| d.join("chat")); - let crash_dir = root.as_ref().map(|d| { - // crashes live in the install dir, but we reference them from here - d.clone() - }); - let _ = crash_dir; // placeholder until we store crashes centrally - - let (sg_count, sg_bytes) = count_dir(sg_dir.as_deref()).await; - let (chat_count, chat_bytes) = count_dir(chat_dir.as_deref()).await; - - Ok(LogStats { - shootergame_archive_count: sg_count, - shootergame_total_bytes: sg_bytes, - chat_log_count: chat_count, - chat_total_bytes: chat_bytes, - crash_count: 0, // populated by list_crashes on demand - storage_root, - }) -} - /// Return the path to the central logs storage root (for display in UI). #[tauri::command] pub fn get_log_storage_root(app: tauri::AppHandle) -> String { @@ -594,29 +550,6 @@ pub fn get_log_storage_root(app: tauri::AppHandle) -> String { } // --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -async fn count_dir(dir: Option<&std::path::Path>) -> (u32, u64) { - let dir = match dir { - Some(d) if d.exists() => d, - _ => return (0, 0), - }; - let mut count = 0u32; - let mut bytes = 0u64; - if let Ok(mut rd) = tokio::fs::read_dir(dir).await { - while let Ok(Some(entry)) = rd.next_entry().await { - if let Ok(meta) = entry.metadata().await { - if meta.is_file() { - count += 1; - bytes += meta.len(); - } - } - } - } - (count, bytes) -} - /// Extract the timestamp string from a filename like `ShooterGame_2026-06-08_14-30-00.log`. fn extract_timestamp_from_filename(name: &str) -> String { // ShooterGame_YYYY-MM-DD_HH-MM-SS.log diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index f8823f2..60387f7 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -1,9 +1,8 @@ use crate::state::{scheduler::SchedulerState, AppState}; -use serde::{Deserialize, Serialize}; +use serde::Serialize; use std::time::{SystemTime, UNIX_EPOCH}; use tauri::{AppHandle, Emitter, Manager}; use tokio::time::{sleep, Duration}; -use uuid::Uuid; use super::server::{inner_start_server, inner_stop_server, StartServerParams}; @@ -11,15 +10,6 @@ use super::server::{inner_start_server, inner_stop_server, StartServerParams}; // Types // --------------------------------------------------------------------------- -#[derive(Debug, Serialize, Deserialize, Clone)] -#[serde(rename_all = "camelCase")] -pub struct ScheduleConfig { - pub server_id: String, - pub schedule_type: String, - pub cron_expression: String, - pub config_json: String, -} - /// Emitted as the payload of `scheduler://fired` so the frontend can update /// SQLite (last_run / next_run) and requeue the entry via sync_schedules. #[derive(Debug, Serialize, Clone)] @@ -39,25 +29,6 @@ pub struct SchedulerFiredPayload { // Tauri commands // --------------------------------------------------------------------------- -/// Generate and return a UUID for a new schedule. -/// All schedule persistence is handled by the frontend via SQLite (db.ts). -#[tauri::command] -pub async fn create_schedule(_config: ScheduleConfig) -> Result { - Ok(Uuid::new_v4().to_string()) -} - -/// No-op — the frontend removes the schedule record from SQLite, then calls sync_schedules. -#[tauri::command] -pub async fn delete_schedule(_schedule_id: String) -> Result<(), String> { - Ok(()) -} - -/// No-op — the frontend updates the enabled flag in SQLite, then calls sync_schedules. -#[tauri::command] -pub async fn toggle_schedule(_schedule_id: String, _enabled: bool) -> Result<(), String> { - Ok(()) -} - /// Atomically replace all active schedule entries. /// /// Called by the frontend whenever schedules are created, updated, toggled, or deleted, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index ad1abf9..5addd65 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -482,7 +482,6 @@ pub fn run() { commands::logs::list_chat_logs, commands::logs::read_chat_log, commands::logs::cleanup_logs, - commands::logs::get_log_stats, commands::logs::get_log_storage_root, // Config / INI commands::config::read_server_config, @@ -548,9 +547,6 @@ pub fn run() { commands::cluster::add_server_to_cluster, commands::cluster::remove_server_from_cluster, // Scheduler - commands::scheduler::create_schedule, - commands::scheduler::delete_schedule, - commands::scheduler::toggle_schedule, commands::scheduler::sync_schedules, ]) .run(tauri::generate_context!()) diff --git a/src/components/server/tabs/AutomationTab.tsx b/src/components/server/tabs/AutomationTab.tsx index 25c77e1..7c9a2ec 100644 --- a/src/components/server/tabs/AutomationTab.tsx +++ b/src/components/server/tabs/AutomationTab.tsx @@ -20,7 +20,6 @@ import { type UpdateAutomation, } from "@/lib/db"; import { getAppSetting, setAppSetting } from "@/lib/db"; -import { tauriCmd } from "@/lib/tauri-commands"; import { syncSchedulesToRust } from "@/lib/scheduler-sync"; import type { ServerRow } from "@/lib/db"; @@ -350,7 +349,7 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing ? JSON.stringify({ message: addMsg }) : JSON.stringify(config); const nextIso = getNextCronDate(cron)?.toISOString() ?? new Date().toISOString(); - const newId = await tauriCmd.createSchedule({ serverId, scheduleType: type, cronExpression: cron, configJson }); + const newId = crypto.randomUUID(); const input: CreateScheduleInput = { id: newId, serverId, scheduleType: type, cronExpression: cron, enabled: true, configJson }; await createSchedule(input); await updateScheduleConfig(newId, cron, configJson, nextIso); @@ -366,7 +365,6 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing } async function handleDelete(id: string) { - await tauriCmd.deleteSchedule(id); await deleteScheduleRecord(id); onRefresh(); syncSchedulesToRust(); @@ -374,7 +372,6 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing async function handleToggle(row: ScheduleRow) { const newVal = !(row.enabled === 1); - await tauriCmd.toggleSchedule(row.id, newVal); await updateScheduleEnabled(row.id, newVal); onRefresh(); syncSchedulesToRust(); @@ -615,7 +612,6 @@ function BackupTypeSection({ // Delete any extra rows left over from the old per-tier format for (const row of allExisting.slice(1)) { - await tauriCmd.deleteSchedule(row.id); await deleteScheduleRecord(row.id); } @@ -623,7 +619,7 @@ function BackupTypeSection({ await updateScheduleConfig(primary.id, cron, configJson, nextIso); if (anyEnabled !== (primary.enabled === 1)) await updateScheduleEnabled(primary.id, anyEnabled); } else if (anyEnabled) { - const newId = await tauriCmd.createSchedule({ serverId, scheduleType, cronExpression: cron, configJson }); + const newId = crypto.randomUUID(); await createSchedule({ id: newId, serverId, scheduleType, cronExpression: cron, enabled: true, configJson }); await updateScheduleConfig(newId, cron, configJson, nextIso); } @@ -721,7 +717,7 @@ function FullBackupScheduleSection({ serverId, schedules, onRefresh }: { await updateScheduleConfig(existing.id, cron, configJson, nextIso); if (enabled !== (existing.enabled === 1)) await updateScheduleEnabled(existing.id, enabled); } else if (enabled) { - const newId = await tauriCmd.createSchedule({ serverId, scheduleType: "backup_full", cronExpression: cron, configJson }); + const newId = crypto.randomUUID(); await createSchedule({ id: newId, serverId, scheduleType: "backup_full", cronExpression: cron, enabled: true, configJson }); await updateScheduleConfig(newId, cron, configJson, nextIso); } diff --git a/src/lib/db.ts b/src/lib/db.ts index 29b5627..9e864cc 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -163,15 +163,6 @@ async function runMigrations(db: Database): Promise { updated_at DATETIME DEFAULT CURRENT_TIMESTAMP )`); - // Reserved for future file-integrity tracking — not yet used by any query. - await db.execute(`CREATE TABLE IF NOT EXISTS file_cache ( - cache_key TEXT PRIMARY KEY, - file_path TEXT NOT NULL, - size_bytes INTEGER NOT NULL DEFAULT 0, - sha256_hash TEXT, - last_updated DATETIME DEFAULT CURRENT_TIMESTAMP - )`); - // Indexes await db.execute("CREATE INDEX IF NOT EXISTS idx_server_mods_server_id ON server_mods(server_id)"); await db.execute("CREATE INDEX IF NOT EXISTS idx_schedules_server_id ON schedules(server_id)"); @@ -186,8 +177,6 @@ async function runMigrations(db: Database): Promise { ('base_dir', ''), ('backup_dir', ''), ('steamcmd_path', ''), - ('steamcmd_mode', 'auto'), - ('app_version', '0.1.0'), ('theme_preset', 'storm'), ('theme_accent', 'blue'), ('asa_update_available', 'false'), diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index f72db2e..55ae188 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -166,15 +166,6 @@ export interface ChatLogInfo { fullPath: string; } -export interface LogStats { - shootergameArchiveCount: number; - shootergameTotalBytes: number; - chatLogCount: number; - chatTotalBytes: number; - crashCount: number; - storageRoot: string; -} - /** Emitted on rcon://status/{id} and rcon://status-any when connection state changes. */ export interface RconStatusPayload { serverId: string; @@ -275,13 +266,6 @@ export interface MigrateProgress { percent: number; } -export interface ScheduleConfig { - serverId: string; - scheduleType: string; - cronExpression: string; - configJson: string; -} - /** One fully-hydrated schedule entry sent to Rust via sync_schedules. */ export interface ScheduleEntry { scheduleId: string; @@ -506,8 +490,6 @@ export const tauriCmd = { // Log maintenance cleanupLogs: (serverId: string, olderThanDays: number) => invoke("cleanup_logs", { serverId, olderThanDays }), - getLogStats: (serverId: string) => - invoke("get_log_stats", { serverId }), getLogStorageRoot: () => invoke("get_log_storage_root"), @@ -698,10 +680,6 @@ export const tauriCmd = { invoke("remove_server_from_cluster", { serverId }), // Scheduler - createSchedule: (config: ScheduleConfig) => invoke("create_schedule", { config }), - deleteSchedule: (scheduleId: string) => invoke("delete_schedule", { scheduleId }), - toggleSchedule: (scheduleId: string, enabled: boolean) => - invoke("toggle_schedule", { scheduleId, enabled }), /** Atomically replace all active schedule entries in the Rust scheduler. */ syncSchedules: (entries: ScheduleEntry[]) => invoke("sync_schedules", { entries }), From 2207cac172f3792df0728643e2cad46643779560 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 16 Jun 2026 11:58:08 -0500 Subject: [PATCH 10/19] style: enhance padding in various components for improved layout --- src/app/backups/page.tsx | 4 ++-- src/app/servers/detail/page.tsx | 9 +++------ src/components/server/tabs/AutomationTab.tsx | 2 +- src/components/server/tabs/BackupsTab.tsx | 2 +- src/components/server/tabs/ConfigTab.tsx | 2 +- src/components/server/tabs/LogsTab.tsx | 4 ++-- src/components/server/tabs/OverviewTab.tsx | 2 +- 7 files changed, 11 insertions(+), 14 deletions(-) diff --git a/src/app/backups/page.tsx b/src/app/backups/page.tsx index aa4975d..2be893d 100644 --- a/src/app/backups/page.tsx +++ b/src/app/backups/page.tsx @@ -35,7 +35,7 @@ export default function BackupsPage() { }; return ( -
+
{/* Page header */}
+
) : !isLoading && servers.length === 0 ? ( diff --git a/src/app/servers/detail/page.tsx b/src/app/servers/detail/page.tsx index c8885d3..934168b 100644 --- a/src/app/servers/detail/page.tsx +++ b/src/app/servers/detail/page.tsx @@ -125,10 +125,7 @@ export default function ServerDetailPage() { const mapDisplay = ARK_MAPS.find((m) => m.id === server.map_id)?.displayName ?? server.map_id; return ( - // When the RCON tab is active the root div fills main's content area exactly - // so the log scrolls internally without creating a page-level scrollbar. - // Other tabs keep normal flow (gap-6, no height constraint). -
+
{/* ── Header ── */}
-
+
{loading ? (
) : crashes.length === 0 ? ( diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index 14c3ee7..bb623fd 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -760,7 +760,7 @@ export function OverviewTab({ server }: Props) { // ── Render ────────────────────────────────────────────────────────────────── return ( -
+
{/* ── Quick actions ── */} {/* Structured as two non-wrapping groups so the right-side buttons From bd803e23bcebf134ac9bdc0d9a25dc24ddb8d3e8 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 16 Jun 2026 12:35:18 -0500 Subject: [PATCH 11/19] style: enhance layout and overflow handling in various components --- src/app/clusters/page.tsx | 6 +- src/app/notifications/page.tsx | 10 +- src/app/page.tsx | 6 +- src/app/settings/page.tsx | 188 ++++++++++++++++++++++++--------- 4 files changed, 154 insertions(+), 56 deletions(-) diff --git a/src/app/clusters/page.tsx b/src/app/clusters/page.tsx index ffc81f9..18293b6 100644 --- a/src/app/clusters/page.tsx +++ b/src/app/clusters/page.tsx @@ -313,9 +313,9 @@ export default function ClustersPage() { }, [queryClient]); return ( -
+
{/* Header */} -
+
@@ -343,6 +343,7 @@ export default function ClustersPage() {
+
{/* Cluster Grid */} {isLoading ? (
@@ -396,6 +397,7 @@ export default function ClustersPage() { onClose={() => setDeleteTarget(null)} onDeleted={refresh} /> +
); } diff --git a/src/app/notifications/page.tsx b/src/app/notifications/page.tsx index b17fe8a..85f7032 100644 --- a/src/app/notifications/page.tsx +++ b/src/app/notifications/page.tsx @@ -220,9 +220,9 @@ function NotificationsContent() { }, [refetch, severityFilter, eventTypeFilter]); return ( -
+
{/* Header */} -
+
@@ -244,7 +244,7 @@ function NotificationsContent() { variant="ghost" size="sm" className="text-xs gap-1.5" - style={{ color: "var(--text-muted)", border: "1px solid var(--border)" }} + style={{ color: "var(--neon-red, #f87171)", border: "1px solid rgba(255,0,85,0.3)" }} > Delete… @@ -285,7 +285,7 @@ function NotificationsContent() { {/* Filters */}
@@ -329,6 +329,7 @@ function NotificationsContent() {
{/* List */} +
{filtered.length === 0 ? (
)} +
); } diff --git a/src/app/page.tsx b/src/app/page.tsx index d53f286..fedb1bc 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -482,9 +482,9 @@ export default function DashboardPage() { }, [servers, updatingAll, queryClient, enqueueStartup]); return ( -
+
{/* ── Page header ── */} -
+
@@ -531,6 +531,7 @@ export default function DashboardPage() {
+
{/* ── Needs Attention warning — only shown when servers are in a bad state ── */} {total > 0 && servers.some((s) => s.status === "crashed" || s.status === "error") && (
@@ -623,6 +624,7 @@ export default function DashboardPage() { updates={pendingUpdates} onUpdateAll={runUpdateAll} /> +
); } diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index f8fbfb1..ce87389 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from "react"; import { - Folder, Terminal, Info, Archive, + Folder, Terminal, Info, Archive, Copy, FolderOpen, CheckCircle2, AlertCircle, Loader2, Save, RefreshCw, ArrowUp, Bell, MessageSquare, Mail, Monitor, Send, Download, Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, Power, ShieldCheck, @@ -611,18 +611,54 @@ function ThemesSection() { // About section // --------------------------------------------------------------------------- +function AboutRow({ label, value }: { label: string; value: string }) { + return ( +
+ {label}: + {value} +
+ ); +} + function AboutSection() { - const [paths, setPaths] = useState({ baseDir: "", dbPath: "", cachePath: "" }); - const [appVersion, setAppVersion] = useState("…"); + const [appVersion, setAppVersion] = useState("…"); + const [asaBuild, setAsaBuild] = useState("—"); + const [protonVersion, setProtonVer] = useState("—"); + const [paths, setPaths] = useState({ + baseDir: "—", backupDir: "—", steamcmd: "—", + dbPath: "—", cachePath: "—", logRoot: "—", + }); + const [copied, setCopied] = useState(false); useEffect(() => { getVersion().then(setAppVersion).catch(() => setAppVersion("0.10.0")); (async () => { - const baseDir = (await getAppSetting("base_dir")) ?? ""; - if (!baseDir) return; - const sep = baseDir.includes("\\") ? "\\" : "/"; - const base = baseDir.replace(/[/\\]$/, ""); - setPaths({ baseDir, dbPath: `${base}${sep}lokiasam${sep}lokiasam.db`, cachePath: `${base}${sep}lokiasam${sep}cache${sep}asa-server` }); + const [baseDir, backupDir, steamcmd, asaCached, protonPath, logRoot] = await Promise.all([ + getAppSetting("base_dir"), + getAppSetting("backup_dir"), + getAppSetting("steamcmd_path"), + getAppSetting("asa_cached_build_id"), + IS_LINUX ? getAppSetting("proton_path") : Promise.resolve(null), + tauriCmd.getLogStorageRoot().catch(() => ""), + ]); + + setAsaBuild(asaCached || "—"); + + if (protonPath) { + const ver = protonPath.replace(/[/\\]$/, "").split(/[/\\]/).pop() ?? ""; + setProtonVer(ver || "—"); + } + + const sep = (baseDir ?? "").includes("\\") ? "\\" : "/"; + const base = (baseDir ?? "").replace(/[/\\]$/, ""); + setPaths({ + baseDir: baseDir || "—", + backupDir: backupDir || "—", + steamcmd: steamcmd || "—", + dbPath: base ? `${base}${sep}lokiasam${sep}lokiasam.db` : "—", + cachePath: base ? `${base}${sep}lokiasam${sep}cache${sep}asa-server` : "—", + logRoot: logRoot || "—", + }); })(); }, []); @@ -630,25 +666,67 @@ function AboutSection() { ? "~/.config/xyz.lokisoft.lokiasam/bootstrap.json" : "%APPDATA%\\xyz.lokisoft.lokiasam\\bootstrap.json"; - const rows = [ - { label: "Version", value: appVersion }, - { label: "Base Directory", value: paths.baseDir || "—" }, - { label: "Database", value: paths.dbPath || "—" }, - { label: "Server Cache", value: paths.cachePath || "—" }, - { label: "Bootstrap", value: bootstrapHint }, + const appRows = [ + { label: "Version", value: appVersion }, + { label: "ASA Cache Build", value: asaBuild }, + ...(IS_LINUX ? [{ label: "Proton-GE", value: protonVersion }] : []), + ]; + + const pathRows = [ + { label: "Base Directory", value: paths.baseDir }, + { label: "Backup Directory", value: paths.backupDir }, + { label: "SteamCMD", value: paths.steamcmd }, + { label: "Database", value: paths.dbPath }, + { label: "Server Cache", value: paths.cachePath }, + { label: "Log Storage", value: paths.logRoot }, + { label: "Bootstrap", value: bootstrapHint }, ]; + const handleCopy = () => { + const text = [ + ...appRows.map((r) => `${r.label}: ${r.value}`), + "", + ...pathRows.map((r) => `${r.label}: ${r.value}`), + ].join("\n"); + navigator.clipboard.writeText(text).catch(() => null); + setCopied(true); + setTimeout(() => setCopied(false), 2000); + }; + return ( -
- {rows.map(({ label, value }, i) => ( -
- {i > 0 && } -
- {label} - {value} -
+
+ {/* Header */} +
+ +
+

About

+

Application version and data paths.

+
+ +
+ + {/* Content */} +
+
+ {appRows.map((r) => )} +
+ +
+ {pathRows.map((r) => )}
- ))} +
); } @@ -880,9 +958,9 @@ function ServerUpdatesSection() { // --------------------------------------------------------------------------- const APP_UPDATE_MODE_OPTIONS = [ + { value: "off", label: "Disabled" }, { value: "startup", label: "On startup" }, { value: "periodic", label: "On startup + hourly" }, - { value: "off", label: "Disabled" }, ]; function AppUpdateSection() { @@ -934,6 +1012,12 @@ function AppUpdateSection() {

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

+ +
@@ -949,12 +1033,6 @@ function AppUpdateSection() { ))}
- -
); } @@ -1368,7 +1446,7 @@ function ProtonGeUpdateSection() { {/* Action buttons */}
@@ -1829,27 +1907,40 @@ export default function SettingsPage() { const [matrixRefreshKey, setMatrixRefreshKey] = useState(0); return ( -
-
+
+

Settings

Global application configuration.

{/* Tab bar */} -
- {TABS.map((tab) => ( - - ))} +
+ {TABS.map((tab) => { + const active = activeTab === tab.id; + return ( + + ); + })}
+
{/* General tab */} {activeTab === "general" && (
@@ -1943,12 +2034,13 @@ export default function SettingsPage() { {/* About tab */} {activeTab === "about" && ( -
-
+
+
-
+
)} +
); } From d0e9503b9bbbca6b85aa51f36940e81cffffd3f8 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 16 Jun 2026 15:54:55 -0500 Subject: [PATCH 12/19] feat: add build version tracking and fetching functionality - Implemented `build_version.rs` to handle fetching and caching game versions from the Steam News API and server queries. - Added database functions for managing build version cache and installed build IDs. - Updated server commands to record installed build IDs and trigger version fetches after installations and updates. - Introduced a React hook `useBuildVersionCache` to manage version cache state in the frontend. - Enhanced UI components to display human-readable game versions based on installed build IDs. --- src-tauri/src/commands/build_version.rs | 310 +++++++++++++++++++++ src-tauri/src/commands/mod.rs | 1 + src-tauri/src/commands/scheduler.rs | 12 + src-tauri/src/commands/server.rs | 12 + src-tauri/src/commands/steamcmd.rs | 28 +- src-tauri/src/db.rs | 57 ++++ src-tauri/src/lib.rs | 2 + src/app/clusters/detail/page.tsx | 6 + src/app/page.tsx | 12 +- src/app/servers/detail/page.tsx | 14 +- src/app/settings/page.tsx | 40 ++- src/components/server/ServerCard.tsx | 9 + src/components/server/tabs/OverviewTab.tsx | 11 + src/hooks/useBuildVersionCache.ts | 22 ++ src/lib/db.ts | 68 +++++ src/lib/tauri-commands.ts | 4 + src/lib/update-utils.ts | 8 +- 17 files changed, 598 insertions(+), 18 deletions(-) create mode 100644 src-tauri/src/commands/build_version.rs create mode 100644 src/hooks/useBuildVersionCache.ts diff --git a/src-tauri/src/commands/build_version.rs b/src-tauri/src/commands/build_version.rs new file mode 100644 index 0000000..819f8a8 --- /dev/null +++ b/src-tauri/src/commands/build_version.rs @@ -0,0 +1,310 @@ +// build_version.rs — ASA build ID → human-readable game version (e.g. "49.23") +// +// Two sources, in priority order: +// "internet" – Steam News API title parse, fetched once per build_id right +// after SteamCMD downloads it (so the latest news matches the +// latest build). +// "server" – A2S_INFO Source Query against localhost once the server +// confirms running. Always overwrites "internet". + +use crate::{db, state::AppState}; +use tauri::Manager; + +// ── Version sources ─────────────────────────────────────────────────────────── + +const OFFICIAL_SERVER_LIST_URL: &str = + "https://cdn2.arkdedicated.com/servers/asa/officialserverlist.json"; + +const PATCH_NOTES_URL: &str = + "https://survivetheark.com/index.php?/forums/topic/708761-asa-pc-patch-notes-client"; + +/// Fetch the current ASA version from the official Wildcard server list. +/// This is the same JSON the game client uses for the server browser, so it +/// reflects the live version exactly. Returns e.g. "88.23". +async fn fetch_version_from_official_list() -> Option { + #[derive(serde::Deserialize)] + struct Entry { + #[serde(rename = "BuildId")] + build_id: u32, + #[serde(rename = "MinorBuildId")] + minor_build_id: u32, + } + + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(15)) + .user_agent("LokiASAM/1.0") + .build() + .ok()?; + + let entries: Vec = client + .get(OFFICIAL_SERVER_LIST_URL) + .send() + .await + .ok()? + .json() + .await + .ok()?; + + let first = entries.into_iter().next()?; + Some(format!("{}.{}", first.build_id, first.minor_build_id)) +} + +/// Extract "88.3" from text like "v88.3 - Major version for Servers…" +/// Requires at least a 2-digit major so single-digit noise is skipped. +fn extract_version_from_patch_notes(text: &str) -> Option { + let s = text.as_bytes(); + let mut i = 0; + while i < s.len() { + // Require explicit 'v' / 'V' prefix so bare numbers are ignored + if (s[i] != b'v' && s[i] != b'V') || i + 1 >= s.len() || !s[i + 1].is_ascii_digit() { + i += 1; + continue; + } + let num_start = i + 1; + let mut j = num_start; + while j < s.len() && s[j].is_ascii_digit() { j += 1; } + let major_len = j - num_start; + if major_len < 2 || j >= s.len() || s[j] != b'.' { + i += 1; + continue; + } + j += 1; // skip dot + let minor_start = j; + while j < s.len() && s[j].is_ascii_digit() { j += 1; } + if j == minor_start { + i += 1; + continue; + } + // Return "MAJOR.MINOR" (drop any trailing .patch suffix) + return Some(text[num_start..j].to_string()); + } + None +} + +/// Fetch the most recent ASA version string from the survivetheark.com patch +/// notes thread. The forum meta description always leads with the newest entry +/// so we only need to parse those first few hundred characters. +async fn fetch_version_from_patch_notes() -> Option { + let client = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(15)) + .user_agent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \ + (KHTML, like Gecko) Chrome/125.0 Safari/537.36") + .build() + .ok()?; + + let html = client.get(PATCH_NOTES_URL).send().await.ok()?.text().await.ok()?; + + // The forum renders the first ~300 chars of post body as the meta description, + // which always starts with the most recently prepended version entry. + let meta_start = html.find(" Option { + use tokio::net::UdpSocket; + use tokio::time::{timeout, Duration}; + + let sock = UdpSocket::bind("0.0.0.0:0").await.ok()?; + sock.connect(format!("127.0.0.1:{port}")).await.ok()?; + + let base_req: &[u8] = b"\xFF\xFF\xFF\xFF\x54Source Engine Query\x00"; + let mut req = base_req.to_vec(); + + sock.send(&req).await.ok()?; + + let mut buf = [0u8; 1400]; + + // Up to two rounds: initial send + one challenge re-send + for _ in 0..2u8 { + let n = timeout(Duration::from_secs(5), sock.recv(&mut buf)) + .await + .ok()?.ok()?; + + if n < 5 || buf[0..4] != [0xFF, 0xFF, 0xFF, 0xFF] { + return None; + } + + match buf[4] { + 0x41 => { + // Challenge response — resend query with 4-byte challenge appended + if n < 9 { + return None; + } + let mut new_req = base_req.to_vec(); + new_req.extend_from_slice(&buf[5..9]); + req = new_req; + sock.send(&req).await.ok()?; + } + 0x49 => { + // A2S_INFO response — parse for version string + return parse_a2s_version(&buf[5..n]); + } + _ => return None, + } + } + None +} + +/// Parse an A2S_INFO response body (after the 0xFF×4 0x49 header) for the +/// version string. Layout: protocol(1), name, map, folder, game (null-term +/// strings), app_id(2), players(1), max_players(1), bots(1), server_type(1), +/// environment(1), visibility(1), vac(1), version (null-term string). +fn parse_a2s_version(data: &[u8]) -> Option { + let mut pos = 1; // skip protocol byte + + // Skip four null-terminated strings: name, map, folder, game + for _ in 0..4 { + while pos < data.len() && data[pos] != 0 { + pos += 1; + } + pos += 1; // consume null terminator + } + + // Skip: app_id(2) + players(1) + max_players(1) + bots(1) + + // server_type(1) + environment(1) + visibility(1) + vac(1) = 9 bytes + pos += 9; + + if pos >= data.len() { + return None; + } + + // Version string (null-terminated) + let start = pos; + while pos < data.len() && data[pos] != 0 { + pos += 1; + } + let version = std::str::from_utf8(&data[start..pos]).ok()?; + if version.is_empty() { + return None; + } + + // Normalise to "MAJOR.MINOR" (e.g. "49.23.0" → "49.23") + let parts: Vec<&str> = version.split('.').collect(); + if parts.len() >= 2 { + Some(format!("{}.{}", parts[0], parts[1])) + } else { + Some(version.to_string()) + } +} + +// ── Public helpers called by steamcmd.rs and server.rs ─────────────────────── + +/// After SteamCMD downloads a new build: store the build_id against the server +/// row and fetch the internet version if this build_id isn't cached yet. +/// Runs the internet fetch in a background task (fire and forget). +pub fn record_install(app: &tauri::AppHandle, server_id: &str, build_id: &str) { + let Some(db_path) = app.state::().get_db_path() else { return }; + if let Ok(conn) = db::open(&db_path) { + let _ = db::set_server_installed_build(&conn, server_id, build_id); + } + maybe_fetch_internet(app, build_id); +} + +/// Trigger an internet version fetch for a build_id unless already +/// server-confirmed. Spawns a background task — does not block. +/// Re-fetches on every call when source is "internet" so a failed parse +/// (game_version = null) is retried on each update check. +pub fn maybe_fetch_internet(app: &tauri::AppHandle, build_id: &str) { + let Some(db_path) = app.state::().get_db_path() else { return }; + + // Skip only if server-confirmed — internet entries may lack a version and + // should be retried until we get one (or the server query overwrites them) + if let Ok(conn) = db::open(&db_path) { + if let Some((_, src)) = db::get_build_game_version(&conn, build_id) { + if src == "server" { + return; + } + } + } else { + return; + } + + let build_id = build_id.to_string(); + tauri::async_runtime::spawn(async move { + // Try the official Wildcard server list first (real-time, structured JSON). + // Fall back to the survivetheark.com forum post if that fails. + let version = match fetch_version_from_official_list().await { + Some(v) => Some(v), + None => fetch_version_from_patch_notes().await, + }; + if let Ok(conn) = db::open(&db_path) { + let _ = db::upsert_build_game_version( + &conn, + &build_id, + version.as_deref(), + "internet", + ); + } + }); +} + +/// After a server confirms running: try A2S to get the server-confirmed version +/// and store it (overwrites "internet" source). Fire and forget. +pub fn maybe_capture_server_version(app: &tauri::AppHandle, server_id: &str, query_port: u16) { + let Some(db_path) = app.state::().get_db_path() else { return }; + + // Read the installed_build_id for this server + let build_id = { + let Ok(conn) = db::open(&db_path) else { return }; + match conn.query_row( + "SELECT installed_build_id FROM servers WHERE id = ?1", + [server_id], + |row| row.get::<_, Option>(0), + ) { + Ok(Some(b)) => b, + _ => return, + } + }; + + // Skip if already server-confirmed + { + let Ok(conn) = db::open(&db_path) else { return }; + if let Some((_, src)) = db::get_build_game_version(&conn, &build_id) { + if src == "server" { + return; + } + } + } + + tauri::async_runtime::spawn(async move { + if let Some(version) = source_query_version(query_port).await { + if let Ok(conn) = db::open(&db_path) { + let _ = db::upsert_build_game_version( + &conn, + &build_id, + Some(&version), + "server", + ); + } + } + }); +} + +// ── Tauri command ───────────────────────────────────────────────────────────── + +/// Manually trigger an internet version fetch for a build_id. Returns the +/// game_version if now available, or None if the fetch failed / build unknown. +#[tauri::command] +pub async fn fetch_build_version( + build_id: String, + state: tauri::State<'_, AppState>, +) -> Result, String> { + let db_path = state.get_db_path().ok_or("DB path not set")?; + + // Always re-fetch (user triggered) — official list first, forum scrape fallback + let version = match fetch_version_from_official_list().await { + Some(v) => Some(v), + None => fetch_version_from_patch_notes().await, + }; + let conn = db::open(&db_path)?; + db::upsert_build_game_version(&conn, &build_id, version.as_deref(), "internet")?; + Ok(version) +} diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index e265a43..38045a3 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -1,5 +1,6 @@ pub mod backup; pub mod backup_manager; +pub mod build_version; pub mod countdown; pub mod certs; pub mod firewall; diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index 60387f7..691bc96 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -197,6 +197,11 @@ async fn fire_global_update_check( let new_build = crate::commands::steamcmd::get_cache_build_id(&cache_dir) .unwrap_or_else(|| old_build.clone()); + // Trigger internet version fetch for a newly-downloaded build + if new_build != "0" { + crate::commands::build_version::maybe_fetch_internet(app, &new_build); + } + let _ = app.emit( crate::events::ASA_UPDATE_CHECK, serde_json::json!({ @@ -302,6 +307,13 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE .map_err(|e| format!("Sync task panicked: {e}"))? .map_err(|e| format!("Failed to sync server files: {e}"))?; + // Record updated build ID and trigger internet version fetch + let acf = std::path::Path::new(&entry.install_path) + .join(crate::commands::steamcmd::ACF_REL_PATH); + if let Some(build_id) = crate::commands::steamcmd::read_acf_build_id(&acf) { + crate::commands::build_version::record_install(app, &entry.server_id, &build_id); + } + let _ = app.emit(crate::events::ASA_UPDATE_CHECK, serde_json::json!({ "updateApplied": true, "serverId": entry.server_id, diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 13de218..7ab8a70 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -689,6 +689,9 @@ async fn inner_start_server_with_state( if buf.contains(READY_MSG) { confirmed2.store(true, Ordering::Relaxed); confirm_running(&handle2, &sid2); + crate::commands::build_version::maybe_capture_server_version( + &handle2, &sid2, query_port2, + ); return; } if buf.contains("Error querying server mods: ApiError: Failed (serverUnreachable)") { @@ -737,6 +740,9 @@ async fn inner_start_server_with_state( if log_confirmed { confirmed2.store(true, Ordering::Relaxed); confirm_running(&handle2, &sid2); + crate::commands::build_version::maybe_capture_server_version( + &handle2, &sid2, query_port2, + ); return; } @@ -745,6 +751,9 @@ async fn inner_start_server_with_state( if try_source_query_local(query_port2).await { confirmed2.store(true, Ordering::Relaxed); confirm_running(&handle2, &sid2); + crate::commands::build_version::maybe_capture_server_version( + &handle2, &sid2, query_port2, + ); return; } sleep(Duration::from_secs(5)).await; @@ -753,6 +762,9 @@ async fn inner_start_server_with_state( // 3. Last resort — promote regardless. confirmed2.store(true, Ordering::Relaxed); confirm_running(&handle2, &sid2); + crate::commands::build_version::maybe_capture_server_version( + &handle2, &sid2, query_port2, + ); }); Ok(pid) diff --git a/src-tauri/src/commands/steamcmd.rs b/src-tauri/src/commands/steamcmd.rs index 623f5fa..a39683c 100644 --- a/src-tauri/src/commands/steamcmd.rs +++ b/src-tauri/src/commands/steamcmd.rs @@ -8,7 +8,7 @@ use super::utils::{build_steamcmd_cmd, copy_dir_recursive, emit_line, stream_pro const ASA_SERVER_APP_ID: &str = "2430930"; /// Relative path to the appmanifest ACF inside a Steam install directory. -const ACF_REL_PATH: &str = "steamapps/appmanifest_2430930.acf"; +pub const ACF_REL_PATH: &str = "steamapps/appmanifest_2430930.acf"; // --------------------------------------------------------------------------- // ACF / INI helpers @@ -496,6 +496,13 @@ pub async fn install_server( .map_err(|e| format!("Failed to copy server files: {e}"))?; emit_line(&app_handle, &channel, "stdout", "Server installation complete.")?; + + // Record installed build ID and trigger internet version fetch + let acf = Path::new(&install_path).join(ACF_REL_PATH); + if let Some(build_id) = read_acf_build_id(&acf) { + crate::commands::build_version::record_install(&app_handle, &server_id, &build_id); + } + Ok(()) }.await; @@ -540,6 +547,13 @@ pub async fn update_server( .map_err(|e| format!("Failed to sync server files: {e}"))?; emit_line(&app_handle, &channel, "stdout", "Server update complete.")?; + + // Record installed build ID and trigger internet version fetch + let acf = Path::new(&install_path).join(ACF_REL_PATH); + if let Some(build_id) = read_acf_build_id(&acf) { + crate::commands::build_version::record_install(&app_handle, &server_id, &build_id); + } + Ok(()) }.await; @@ -659,6 +673,12 @@ pub async fn update_cache( let build_id = read_acf_build_id(&acf_path).unwrap_or_else(|| "0".to_string()); emit_line(&app_handle, &channel, "stdout", &format!("Cache updated to build {build_id}."))?; + + // Trigger internet version fetch for this build in the background + if build_id != "0" { + crate::commands::build_version::maybe_fetch_internet(&app_handle, &build_id); + } + Ok(build_id) } @@ -685,6 +705,12 @@ pub async fn apply_cache_to_server( .map_err(|e| format!("Sync task panicked: {e}"))? .map_err(|e| format!("Failed to sync server files: {e}"))?; + // Record updated build ID for version tracking + let acf = std::path::Path::new(&install_path).join(ACF_REL_PATH); + if let Some(build_id) = read_acf_build_id(&acf) { + crate::commands::build_version::record_install(&app_handle, &server_id, &build_id); + } + emit_line(&app_handle, &channel, "stdout", "Server update applied.")?; Ok(()) } diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index 4a8574b..5326458 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -398,3 +398,60 @@ pub fn log_notification(conn: &Connection, n: &NotifInsert) -> Result<(), String .map_err(|e| format!("log_notification failed: {e}"))?; Ok(()) } + +// --------------------------------------------------------------------------- +// build_version_cache +// --------------------------------------------------------------------------- + +/// Returns the cached (game_version, source) for a build_id, if present. +pub fn get_build_game_version(conn: &Connection, build_id: &str) -> Option<(Option, String)> { + conn.query_row( + "SELECT game_version, source FROM build_version_cache WHERE build_id = ?1", + [build_id], + |row| Ok((row.get::<_, Option>(0)?, row.get::<_, String>(1)?)), + ) + .ok() +} + +/// Upsert a (build_id → game_version) entry. "server" source always wins; +/// never downgrades an existing "server" entry to "internet". +pub fn upsert_build_game_version( + conn: &Connection, + build_id: &str, + version: Option<&str>, + source: &str, +) -> Result<(), String> { + // Don't overwrite a server-confirmed entry with an internet one. + if source != "server" { + let existing: Option = conn.query_row( + "SELECT source FROM build_version_cache WHERE build_id = ?1", + [build_id], + |row| row.get(0), + ).ok(); + if existing.as_deref() == Some("server") { + return Ok(()); + } + } + + conn.execute( + "INSERT INTO build_version_cache (build_id, game_version, source, fetched_at) \ + VALUES (?1, ?2, ?3, strftime('%s','now')) \ + ON CONFLICT(build_id) DO UPDATE SET \ + game_version = excluded.game_version, \ + source = excluded.source, \ + fetched_at = excluded.fetched_at", + rusqlite::params![build_id, version, source], + ) + .map_err(|e| format!("upsert_build_game_version failed: {e}"))?; + Ok(()) +} + +/// Update the installed_build_id column for a specific server. +pub fn set_server_installed_build(conn: &Connection, server_id: &str, build_id: &str) -> Result<(), String> { + conn.execute( + "UPDATE servers SET installed_build_id = ?1 WHERE id = ?2", + [build_id, server_id], + ) + .map_err(|e| format!("set_server_installed_build failed: {e}"))?; + Ok(()) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5addd65..dd2b322 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -457,6 +457,8 @@ pub fn run() { commands::steamcmd::update_cache, commands::steamcmd::apply_cache_to_server, commands::steamcmd::detect_server_install, + // Build version cache + commands::build_version::fetch_build_version, // RCON commands::rcon::rcon_connect, commands::rcon::rcon_send, diff --git a/src/app/clusters/detail/page.tsx b/src/app/clusters/detail/page.tsx index 71a624a..02cb1c9 100644 --- a/src/app/clusters/detail/page.tsx +++ b/src/app/clusters/detail/page.tsx @@ -31,11 +31,13 @@ import { getServers, setServerCluster, getAppSetting, + formatServerVersion, type ClusterRow, type ServerRow, } from "@/lib/db"; import { ARK_MAPS } from "@/data/game-data"; import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; +import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; // --------------------------------------------------------------------------- // Add Server Dialog @@ -151,6 +153,7 @@ interface MemberRowProps { function MemberRow({ server, onRemove }: MemberRowProps) { const router = useRouter(); const map = ARK_MAPS.find((m) => m.id === server.map_id); + const versionCache = useBuildVersionCache(); return (

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

diff --git a/src/app/page.tsx b/src/app/page.tsx index fedb1bc..d54c646 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -27,6 +27,8 @@ import { useQueryClient } from "@tanstack/react-query"; import { useAppStore } from "@/store/useAppStore"; import { useTauriEvent } from "@/hooks/useTauriEvent"; import { toast } from "sonner"; +import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; +import { formatServerVersion } from "@/lib/db"; // --------------------------------------------------------------------------- // UpdateStatusChip — Check for Updates button + post-check dialogs @@ -173,6 +175,7 @@ function UpdatesFoundDialog({ open, onOpenChange, updates, onUpdateAll }: Update const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); const anyRunning = updates.some((s) => s.status === "running"); const anyStarting = updates.some((s) => s.status === "starting"); + const versionCache = useBuildVersionCache(); return ( @@ -198,8 +201,8 @@ function UpdatesFoundDialog({ open, onOpenChange, updates, onUpdateAll }: Update
{s.name} {s.installedBuild !== "unknown" && ( - - {s.installedBuild} → {s.cachedBuild} + + {formatServerVersion(s.installedBuild, versionCache)} → {formatServerVersion(s.cachedBuild, versionCache)} )}
@@ -290,6 +293,7 @@ interface UpdateAllDialogProps { function UpdateAllDialog({ open, onOpenChange, updates, anyStarting, onConfirm }: UpdateAllDialogProps) { const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); const anyRunning = updates.some((s) => s.status === "running"); + const versionCache = useBuildVersionCache(); return ( @@ -314,8 +318,8 @@ function UpdateAllDialog({ open, onOpenChange, updates, anyStarting, onConfirm }
{s.name} {s.installedBuild !== "unknown" && ( - - {s.installedBuild} → {s.cachedBuild} + + {formatServerVersion(s.installedBuild, versionCache)} → {formatServerVersion(s.cachedBuild, versionCache)} )}
diff --git a/src/app/servers/detail/page.tsx b/src/app/servers/detail/page.tsx index 934168b..7c23c6a 100644 --- a/src/app/servers/detail/page.tsx +++ b/src/app/servers/detail/page.tsx @@ -17,13 +17,14 @@ import { LogsTab } from "@/components/server/tabs/LogsTab"; import { ModsTab } from "@/components/server/tabs/ModsTab"; import { BackupsTab } from "@/components/server/tabs/BackupsTab"; import { AutomationTab } from "@/components/server/tabs/AutomationTab"; -import { getServer } from "@/lib/db"; +import { getServer, formatServerVersion } from "@/lib/db"; import { ARK_MAPS } from "@/data/game-data"; import { useTauriEvent } from "@/hooks/useTauriEvent"; import { useQueryClient } from "@tanstack/react-query"; import { updateServerStatus } from "@/lib/db"; import type { ServerRow } from "@/lib/db"; import type { ServerStatus } from "@/lib/tauri-commands"; +import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; const TABS = [ { value: "overview", label: "Overview", icon: LayoutDashboard }, @@ -55,6 +56,7 @@ export default function ServerDetailPage() { const [loading, setLoading] = useState(true); const [notFound, setNotFound] = useState(false); const [activeTab, setActiveTab] = useState(tabParam); + const versionCache = useBuildVersionCache(); // ── Load server row ────────────────────────────────────────────────────── const reload = async () => { @@ -150,8 +152,14 @@ export default function ServerDetailPage() {

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

diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index ce87389..787edea 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -24,9 +24,10 @@ import { NotificationMatrix } from "@/components/shared/NotificationMatrix"; import { getAppSetting, setAppSetting, saveNotificationConfig, getNotificationConfigs, - getServers, + getServers, formatServerVersion, type NotificationConfigRow, } from "@/lib/db"; +import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; import { runAsaCacheUpdate, runPerServerUpdateCheck, applyUpdateToServer } from "@/lib/update-utils"; import { check } from "@tauri-apps/plugin-updater"; import { getVersion } from "@tauri-apps/api/app"; @@ -620,6 +621,17 @@ function AboutRow({ label, value }: { label: string; value: string }) { ); } +function AboutSectionLabel({ children }: { children: React.ReactNode }) { + return ( +
+ + {children} + +
+
+ ); +} + function AboutSection() { const [appVersion, setAppVersion] = useState("…"); const [asaBuild, setAsaBuild] = useState("—"); @@ -629,6 +641,7 @@ function AboutSection() { dbPath: "—", cachePath: "—", logRoot: "—", }); const [copied, setCopied] = useState(false); + const versionCache = useBuildVersionCache(); useEffect(() => { getVersion().then(setAppVersion).catch(() => setAppVersion("0.10.0")); @@ -666,9 +679,14 @@ function AboutSection() { ? "~/.config/xyz.lokisoft.lokiasam/bootstrap.json" : "%APPDATA%\\xyz.lokisoft.lokiasam\\bootstrap.json"; - const appRows = [ - { label: "Version", value: appVersion }, - { label: "ASA Cache Build", value: asaBuild }, + // Resolve the human-readable ASA version from the cache build ID + const asaVersionDisplay = asaBuild !== "—" + ? formatServerVersion(asaBuild, versionCache) + : "—"; + + const versionRows = [ + { label: "LokiASAM", value: `v${appVersion}` }, + { label: "ASA Server Cache", value: asaVersionDisplay }, ...(IS_LINUX ? [{ label: "Proton-GE", value: protonVersion }] : []), ]; @@ -684,9 +702,11 @@ function AboutSection() { const handleCopy = () => { const text = [ - ...appRows.map((r) => `${r.label}: ${r.value}`), + "Versions:", + ...versionRows.map((r) => ` ${r.label}: ${r.value}`), "", - ...pathRows.map((r) => `${r.label}: ${r.value}`), + "Directories:", + ...pathRows.map((r) => ` ${r.label}: ${r.value}`), ].join("\n"); navigator.clipboard.writeText(text).catch(() => null); setCopied(true); @@ -718,11 +738,13 @@ function AboutSection() {
{/* Content */} -
+
+ Versions
- {appRows.map((r) => )} + {versionRows.map((r) => )}
- + + Directories
{pathRows.map((r) => )}
diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index 68838a5..ad0356a 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -60,6 +60,8 @@ import { useQueryClient } from "@tanstack/react-query"; import { useAppStore } from "@/store/useAppStore"; import { toast } from "sonner"; import type { ServerRow } from "@/lib/db"; +import { formatServerVersion } from "@/lib/db"; +import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; interface Props { server: ServerRow; @@ -114,6 +116,7 @@ export function ServerCard({ server }: Props) { const router = useRouter(); const queryClient = useQueryClient(); const stats = useServerStats(server); + const versionCache = useBuildVersionCache(); const startTime = useAppStore((s) => s.serverStartTimes[server.id]); const noRetry = useAppStore((s) => !!s.noRetryServerIds[server.id]); const setNoRetryServer = useAppStore((s) => s.setNoRetryServer); @@ -514,6 +517,12 @@ export function ServerCard({ server }: Props) { {mapDisplay} · :{server.port} + {server.installed_build_id && ( + <> + · + {formatServerVersion(server.installed_build_id, versionCache)} + + )}
diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index bb623fd..8238b95 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -34,6 +34,8 @@ import { applyUpdateToServer } from "@/lib/update-utils"; import { warnIfFirewallMissing } from "@/lib/firewall-utils"; import type { BackupRecord } from "@/lib/tauri-commands"; 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 { dispatchNotification } from "@/lib/notifications"; @@ -465,6 +467,7 @@ export function OverviewTab({ server }: Props) { const router = useRouter(); const queryClient = useQueryClient(); const stats = useServerStats(server); + const versionCache = useBuildVersionCache(); const startTime = useAppStore((s) => s.serverStartTimes[server.id]); const isServerScanPending = useAppStore((s) => s.isServerScanPending); const countdown = useAppStore((s) => s.countdowns[server.id] ?? null); @@ -988,6 +991,14 @@ export function OverviewTab({ server }: Props) {
+ {server.installed_build_id && ( +
+
Installed Version
+
+ {formatServerVersion(server.installed_build_id, versionCache)} +
+
+ )}
Server UUID
{server.id}
diff --git a/src/hooks/useBuildVersionCache.ts b/src/hooks/useBuildVersionCache.ts new file mode 100644 index 0000000..869af4d --- /dev/null +++ b/src/hooks/useBuildVersionCache.ts @@ -0,0 +1,22 @@ +import { useState, useEffect, useCallback } from "react"; +import { getBuildVersionCache, type BuildVersionRow } from "@/lib/db"; + +// Refresh the cache when a server status event fires (server may have confirmed +// its version via A2S after starting) or on a slow background interval. +const REFRESH_MS = 30_000; + +export function useBuildVersionCache(): Map { + const [cache, setCache] = useState>(new Map()); + + const refresh = useCallback(() => { + getBuildVersionCache().then(setCache).catch(() => null); + }, []); + + useEffect(() => { + refresh(); + const id = setInterval(refresh, REFRESH_MS); + return () => clearInterval(id); + }, [refresh]); + + return cache; +} diff --git a/src/lib/db.ts b/src/lib/db.ts index 9e864cc..80ada78 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -462,6 +462,23 @@ async function runMigrations(db: Database): Promise { ); } } + + // ── Migration 015: build version cache + per-server installed_build_id ───── + // build_version_cache: maps Steam build IDs to human-readable version strings + // (e.g. "49.23"). Populated lazily: "internet" source comes from the Steam + // News API right after a cache update; "server" source from A2S_INFO when + // the server actually starts. "server" always wins over "internet". + // installed_build_id: the build ID currently installed at this server's path, + // populated by Rust on install/update. + await db.execute(`CREATE TABLE IF NOT EXISTS build_version_cache ( + build_id TEXT PRIMARY KEY, + game_version TEXT, + source TEXT NOT NULL DEFAULT 'internet', + fetched_at INTEGER NOT NULL DEFAULT 0 + )`); + try { + await db.execute("ALTER TABLE servers ADD COLUMN installed_build_id TEXT"); + } catch { /* already exists */ } } // --------------------------------------------------------------------------- @@ -498,10 +515,17 @@ export interface ServerRow { update_message: string; // template with {time} placeholder 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 created_at: string; updated_at: string; } +export interface BuildVersionRow { + build_id: string; + game_version: string | null; + source: string; // "internet" | "server" +} + export interface UpdateAutomation { mode: "off" | "immediately" | "at_time"; update_time: string; // "HH:MM" used when mode === "at_time" @@ -827,6 +851,14 @@ export async function setServerUpdateAvailable( ); } +export async function setServerInstalledBuild(id: string, buildId: string): Promise { + const db = await getDb(); + await db.execute( + "UPDATE servers SET installed_build_id = ? WHERE id = ?", + [buildId, id] + ); +} + /** Read/write per-server update automation settings. */ export async function setServerUpdateAutomation( id: string, @@ -1940,3 +1972,39 @@ export async function removeFirewallRule(port: number, protocol: string): Promis [port, protocol] ); } + +// --------------------------------------------------------------------------- +// build_version_cache +// --------------------------------------------------------------------------- + +export async function getBuildVersionCache(): Promise> { + const db = await getDb(); + const rows = await db.select( + "SELECT build_id, game_version, source FROM build_version_cache" + ); + return new Map(rows.map((r) => [r.build_id, r])); +} + +export async function getBuildVersion(buildId: string): Promise { + const db = await getDb(); + const rows = await db.select( + "SELECT build_id, game_version, source FROM build_version_cache WHERE build_id = ?", + [buildId] + ); + return rows[0] ?? null; +} + +/** Format a build ID + optional version into a display string. + * Known version: "V49.23 (23691984)" + * Unknown: "Build 23691984" + * No build ID: "—" + */ +export function formatServerVersion( + installedBuildId: string | null | undefined, + versionCache: Map +): string { + if (!installedBuildId) return "—"; + const entry = versionCache.get(installedBuildId); + if (entry?.game_version) return `V${entry.game_version} (${installedBuildId})`; + return `Build ${installedBuildId}`; +} diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index 55ae188..8bebe9b 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -395,6 +395,10 @@ export const tauriCmd = { /** Inspect an existing folder: checks for the server exe and parses INI files. */ detectServerInstall: (installPath: string) => invoke("detect_server_install", { installPath }), + /** Fetch game version for a build ID from the Steam News API and store it. + * Returns the version string (e.g. "49.23") or null if unavailable. */ + fetchBuildVersion: (buildId: string) => + invoke("fetch_build_version", { buildId }), // RCON — connection rconConnect: (serverId: string, host: string, port: number, password: string) => diff --git a/src/lib/update-utils.ts b/src/lib/update-utils.ts index 991f427..4552607 100644 --- a/src/lib/update-utils.ts +++ b/src/lib/update-utils.ts @@ -6,7 +6,7 @@ * update_available column in the DB and optionally fires notifications. */ -import { getServers, getAppSetting, setServerUpdateAvailable, setAppSetting } from "@/lib/db"; +import { getServers, getAppSetting, setServerUpdateAvailable, setServerInstalledBuild, setAppSetting } from "@/lib/db"; import { tauriCmd } from "@/lib/tauri-commands"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; @@ -89,6 +89,12 @@ export async function runPerServerUpdateCheck(silent = false): Promise null); + } + await setServerUpdateAvailable(server.id, isOutdated); if (isOutdated) { From 679f43a72910c2b96bc828e6e3db34e40d4541d8 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 16 Jun 2026 18:07:47 -0500 Subject: [PATCH 13/19] style: improve overflow handling and layout adjustments in SetupWizard component --- src/components/wizard/SetupWizard.tsx | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/components/wizard/SetupWizard.tsx b/src/components/wizard/SetupWizard.tsx index 3cbcda1..44b2bff 100644 --- a/src/components/wizard/SetupWizard.tsx +++ b/src/components/wizard/SetupWizard.tsx @@ -2450,7 +2450,7 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { return (
{/* Background texture */} @@ -2492,17 +2492,15 @@ export function SetupWizard({ onComplete }: SetupWizardProps) {
{/* Main content card */} -
+
From 5addd6e1a721a606ca35e743808be3ef745d1c0d Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 16 Jun 2026 19:16:16 -0500 Subject: [PATCH 14/19] feat: implement directory wipe functionality and enhance DirCheckResult structure --- src-tauri/src/commands/system.rs | 66 ++++++++ src-tauri/src/lib.rs | 1 + src/app/page.tsx | 13 ++ src/app/settings/page.tsx | 2 +- src/components/wizard/SetupWizard.tsx | 215 +++++++++++++++++++++++++- src/lib/tauri-commands.ts | 7 + 6 files changed, 298 insertions(+), 6 deletions(-) diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs index cb5c11d..7058029 100644 --- a/src-tauri/src/commands/system.rs +++ b/src-tauri/src/commands/system.rs @@ -120,6 +120,12 @@ pub struct DirCheckResult { pub writable: bool, pub free_bytes: u64, pub error: Option, + /// Target path does not exist yet and will be created on install. + pub is_new: bool, + /// A LokiASAM database was found inside the target path (existing install). + pub has_lokiasam: bool, + /// Target path exists but contains no files or subdirectories. + pub is_empty: bool, } // --------------------------------------------------------------------------- @@ -135,6 +141,9 @@ pub struct DirCheckResult { pub async fn check_dir(path: String) -> Result { let p = Path::new(&path); + // Whether the target path itself exists (vs. needing to be created). + let is_new = !p.exists(); + // Find the deepest existing ancestor (may be p itself). let check_against = { let mut cursor = p; @@ -149,6 +158,9 @@ pub async fn check_dir(path: String) -> Result { writable: false, free_bytes: 0, error: Some("Cannot find any existing parent directory.".into()), + is_new: true, + has_lokiasam: false, + is_empty: false, }); } } @@ -168,6 +180,9 @@ pub async fn check_dir(path: String) -> Result { "Location is not writable (check permissions on {}).", check_against.display() )), + is_new, + has_lokiasam: false, + is_empty: false, }); } @@ -182,10 +197,23 @@ pub async fn check_dir(path: String) -> Result { .unwrap_or(0) }; + // Check for an existing LokiASAM install and whether the dir is empty. + let (has_lokiasam, is_empty) = if !is_new { + let db_path = p.join("lokiasam").join("lokiasam.db"); + let has_db = db_path.exists(); + let empty = p.read_dir().map(|mut d| d.next().is_none()).unwrap_or(false); + (has_db, empty) + } else { + (false, false) + }; + Ok(DirCheckResult { writable: true, free_bytes, error: None, + is_new, + has_lokiasam, + is_empty, }) } @@ -197,6 +225,44 @@ pub async fn check_file_exists(path: String) -> Result { Ok(Path::new(&path).exists()) } +/// Wipe LokiASAM data from a directory. +/// +/// * `full_wipe = false` — deletes only the `lokiasam/` subdirectory (database, +/// config, logs). Server game files are left intact. +/// * `full_wipe = true` — deletes ALL contents inside `path` (but not `path` +/// itself, so it remains as an empty directory ready for a clean install). +#[tauri::command] +pub async fn wipe_lokiasam_dir(path: String, full_wipe: bool) -> Result<(), String> { + let p = Path::new(&path); + if !p.exists() { + return Ok(()); + } + + if full_wipe { + // Delete every entry inside the directory but keep the directory itself. + let entries = std::fs::read_dir(p) + .map_err(|e| format!("Failed to read directory: {e}"))?; + for entry in entries.flatten() { + let ep = entry.path(); + if ep.is_dir() { + std::fs::remove_dir_all(&ep) + .map_err(|e| format!("Failed to remove {}: {e}", ep.display()))?; + } else { + std::fs::remove_file(&ep) + .map_err(|e| format!("Failed to remove {}: {e}", ep.display()))?; + } + } + } else { + let loki_dir = p.join("lokiasam"); + if loki_dir.exists() { + std::fs::remove_dir_all(&loki_dir) + .map_err(|e| format!("Failed to remove lokiasam directory: {e}"))?; + } + } + + Ok(()) +} + /// Return CPU % and RSS memory (MB) for a server process and ALL its descendants. /// /// On Linux the tracked PID is the Proton launcher. When Steam is installed, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index dd2b322..969804d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -521,6 +521,7 @@ pub fn run() { commands::system::get_install_method, commands::system::check_dir, commands::system::check_file_exists, + commands::system::wipe_lokiasam_dir, commands::system::delete_directory, commands::system::move_base_dir, commands::system::abort_operation, diff --git a/src/app/page.tsx b/src/app/page.tsx index d54c646..4d3bb49 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -29,6 +29,7 @@ import { useTauriEvent } from "@/hooks/useTauriEvent"; import { toast } from "sonner"; import { useBuildVersionCache } from "@/hooks/useBuildVersionCache"; import { formatServerVersion } from "@/lib/db"; +import { getVersion } from "@tauri-apps/api/app"; // --------------------------------------------------------------------------- // UpdateStatusChip — Check for Updates button + post-check dialogs @@ -401,6 +402,11 @@ export default function DashboardPage() { const { data: servers = [], isLoading } = useServers(); const { setShowNewServerWizard, enqueueStartup } = useAppStore(); const [showImport, setShowImport] = useState(false); + const [appVersion, setAppVersion] = useState(""); + + useEffect(() => { + getVersion().then(setAppVersion).catch(() => {}); + }, []); const [showUpdateAllDialog, setShowUpdateAllDialog] = useState(false); const [showUpdatesFoundDialog, setShowUpdatesFoundDialog] = useState(false); const [pendingUpdates, setPendingUpdates] = useState([]); @@ -629,6 +635,13 @@ export default function DashboardPage() { onUpdateAll={runUpdateAll} />
+ + {/* Branding footer */} +
+

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

+
); } diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index 787edea..83c15dc 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -359,7 +359,7 @@ function PathField({ if (!path.trim() || !validateDir) return; setChecking(true); setDirResult(null); try { setDirResult(await tauriCmd.checkDir(path)); } - catch { setDirResult({ writable: false, freeBytes: 0, error: "Could not check directory." }); } + catch { setDirResult({ writable: false, freeBytes: 0, error: "Could not check directory.", isNew: false, hasLokiasam: false, isEmpty: false }); } finally { setChecking(false); } }, [validateDir]); diff --git a/src/components/wizard/SetupWizard.tsx b/src/components/wizard/SetupWizard.tsx index 44b2bff..0ba05e5 100644 --- a/src/components/wizard/SetupWizard.tsx +++ b/src/components/wizard/SetupWizard.tsx @@ -25,13 +25,16 @@ 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, + X, BookOpen, ShieldCheck, Trash2, TriangleAlert, } from "lucide-react"; import { toast } from "sonner"; import { LokiIcon } from "@/components/shared/LokiIcon"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { + Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, +} from "@/components/ui/dialog"; import { CommandOutputPanel } from "@/components/shared/CommandOutputPanel"; import { useSetupStore } from "@/store/useSetupStore"; import { useAppStore } from "@/store/useAppStore"; @@ -128,6 +131,155 @@ function DirValidationRow({ result }: { result: DirCheckResult }) { ); } +// --------------------------------------------------------------------------- +// WipeLokiAsamDialog +// --------------------------------------------------------------------------- + +interface WipeLokiAsamDialogProps { + open: boolean; + path: string; + onClose: () => void; + onWiped: () => void; +} + +function WipeLokiAsamDialog({ open, path, onClose, onWiped }: WipeLokiAsamDialogProps) { + const [fullWipe, setFullWipe] = useState(false); + const [confirmOpen, setConfirmOpen] = useState(false); + const [wiping, setWiping] = useState(false); + + // When the outer dialog closes, reset state. + useEffect(() => { + if (!open) { setFullWipe(false); setConfirmOpen(false); setWiping(false); } + }, [open]); + + const handleFullWipeToggle = () => { + if (!fullWipe) { + // Require the secondary confirmation before checking the box. + setConfirmOpen(true); + } else { + setFullWipe(false); + } + }; + + const handleConfirmFullWipe = () => { + setConfirmOpen(false); + setFullWipe(true); + }; + + const handleWipe = async () => { + setWiping(true); + try { + await tauriCmd.wipeLokiAsamDir(path, fullWipe); + toast.success(fullWipe ? "Directory wiped — ready for a clean install." : "LokiASAM data removed — ready for a clean install."); + onWiped(); + onClose(); + } catch (e) { + toast.error("Failed to delete files", { description: String(e) }); + } finally { + setWiping(false); + } + }; + + return ( + <> + {/* Main delete dialog */} + { if (!v) onClose(); }}> + + + + Delete LokiASAM Data + + + +
+

+ This will remove the existing LokiASAM installation from {path}. +

+ + {/* Base case — always deleted */} +
+

Will be deleted

+

The lokiasam/ subfolder — database, config, and logs. Server game files are kept.

+
+ + {/* Full wipe toggle */} + +
+ + + + + +
+
+ + {/* Nested confirmation for full wipe */} + { if (!v) setConfirmOpen(false); }}> + + + + Complete Data Loss Warning + + + +
+

+ This will permanently delete everything inside: +

+

+ {path} +

+

+ All old LokiASAM data, server configurations, downloaded game files, and backups will be gone permanently. This cannot be undone. +

+
+ + + + + +
+
+ + ); +} + // --------------------------------------------------------------------------- // Sub-components per step // --------------------------------------------------------------------------- @@ -241,7 +393,7 @@ function ThemeStep() { }} >
-
+
{preset.label} {selected && Active} @@ -474,6 +626,7 @@ function BaseDirStep() { } = useSetupStore(); const [dirResult, setDirResult] = useState(null); const [checking, setChecking] = useState(false); + const [wipeOpen, setWipeOpen] = useState(false); const [importChecking, setImportChecking] = useState(false); const [importError, setImportError] = useState(""); const [importInfo, setImportInfo] = useState<{ @@ -490,7 +643,7 @@ function BaseDirStep() { setDirResult(result); setBaseDirWritable(result.writable); } catch { - const fallback: DirCheckResult = { writable: false, freeBytes: 0, error: "Could not check directory." }; + const fallback: DirCheckResult = { writable: false, freeBytes: 0, error: "Could not check directory.", isNew: false, hasLokiasam: false, isEmpty: false }; setDirResult(fallback); setBaseDirWritable(false); } finally { @@ -651,9 +804,61 @@ function BaseDirStep() { )} {dirResult && }
+ + {/* ── LokiASAM already installed here ── */} + {dirResult?.hasLokiasam && ( +
+
+ +
+

LokiASAM is already installed here

+

+ Continuing will overwrite your database — all server configurations, schedules, and settings will be permanently lost. +

+
+
+
+ + +
+
+ )} + + {/* ── Directory has other content (not LokiASAM) ── */} + {dirResult?.writable && !dirResult.hasLokiasam && !dirResult.isNew && !dirResult.isEmpty && ( +
+ +

+ This directory is not empty. Server files will be installed alongside existing content. +

+
+ )} )} + {/* Wipe dialog */} + setWipeOpen(false)} + onWiped={() => validateDir(baseDir)} + /> + {/* ── Import Previous Install ── */} {importMode && ( <> @@ -742,7 +947,7 @@ function BackupDirStep() { setDirResult(result); setBackupDirWritable(result.writable); } catch { - const fallback: DirCheckResult = { writable: false, freeBytes: 0, error: "Could not check directory." }; + const fallback: DirCheckResult = { writable: false, freeBytes: 0, error: "Could not check directory.", isNew: false, hasLokiasam: false, isEmpty: false }; setDirResult(fallback); setBackupDirWritable(false); } finally { @@ -1840,7 +2045,7 @@ function TrayStep() { >
{closeToTray === value && ( diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index 8bebe9b..992316f 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -258,6 +258,12 @@ export interface DirCheckResult { writable: boolean; freeBytes: number; error: string | null; + /** Target path does not exist yet and will be created on install. */ + isNew: boolean; + /** A LokiASAM database was found inside the target path (existing install). */ + hasLokiasam: boolean; + /** Target path exists but contains no files or subdirectories. */ + isEmpty: boolean; } export interface MigrateProgress { @@ -620,6 +626,7 @@ export const tauriCmd = { */ checkDir: (path: string) => invoke("check_dir", { path }), checkFileExists: (path: string) => invoke("check_file_exists", { path }), + wipeLokiAsamDir: (path: string, fullWipe: boolean) => invoke("wipe_lokiasam_dir", { path, fullWipe }), /** Recursively delete a directory. Idempotent — returns Ok if path doesn't exist. */ deleteDirectory: (path: string) => invoke("delete_directory", { path }), /** From 5b14bf1217a54f6e0882811a4698b92c8c0af9f8 Mon Sep 17 00:00:00 2001 From: Arron Ohnemus Date: Tue, 16 Jun 2026 19:31:53 -0500 Subject: [PATCH 15/19] style: adjust padding and margin for improved layout in SetupWizard component --- src/components/wizard/SetupWizard.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/wizard/SetupWizard.tsx b/src/components/wizard/SetupWizard.tsx index 0ba05e5..701a62d 100644 --- a/src/components/wizard/SetupWizard.tsx +++ b/src/components/wizard/SetupWizard.tsx @@ -2709,7 +2709,7 @@ export function SetupWizard({ onComplete }: SetupWizardProps) { }} >
-
+
Date: Mon, 22 Jun 2026 01:25:24 -0500 Subject: [PATCH 16/19] feat: Add extended server settings for gameplay customization - Introduced new settings for server configurations including: - Show Damage Numbers - Disable Weather Fog - Flying Stamina Recovery - Max Tamed Dinos (Server and Per Tribe) - NPC Network Stasis Range adjustments - Various breeding, player, and dino settings - XP multipliers and PvP/PvE settings - Tribe and decay settings - Structure pickup and transfer options - Cryopod nerf settings - Chat and admin configurations - Message of the Day settings - Ragnarok and Lost Colony specific settings --- .gitignore | 3 + .../layout/ModBrowserEventHandler.tsx | 7 + src/components/server/tabs/ConfigTab.tsx | 734 ++++++++++++++++-- src/components/server/tabs/OverviewTab.tsx | 151 +++- .../wizard/ServerCreationWizard.tsx | 50 +- src/components/wizard/SetupWizard.tsx | 95 ++- src/data/game-data.ts | 283 +++++++ 7 files changed, 1218 insertions(+), 105 deletions(-) diff --git a/.gitignore b/.gitignore index 1d7cb62..4122460 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,9 @@ yarn-error.log* *.tsbuildinfo next-env.d.ts +# planning docs (local only) +/doc/ + # makepkg build artifacts packaging/arch/src/ packaging/arch/pkg/ diff --git a/src/components/layout/ModBrowserEventHandler.tsx b/src/components/layout/ModBrowserEventHandler.tsx index 913ac20..e182c25 100644 --- a/src/components/layout/ModBrowserEventHandler.tsx +++ b/src/components/layout/ModBrowserEventHandler.tsx @@ -42,6 +42,13 @@ export function ModBrowserEventHandler() { source?: string; }; + // Wizard uses a fake "wizard-temp" server ID since no DB record exists yet. + // The wizard's ModsStep listens for this event directly and updates its own state. + if (data.serverId === "wizard-temp") { + incrementModAddedCount(); + return; + } + // For browser-sourced adds, only save if it matches the open browser session. if (data.source !== "verify" && modBrowserParams) { if (data.serverId !== modBrowserParams.serverId) return; diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index 57aca43..6f7440e 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -4,15 +4,29 @@ 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, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; import { tauriCmd, type ServerConfigJson } from "@/lib/tauri-commands"; -import { INI_FIELD_GROUPS, LAUNCH_PARAMETERS, type IniFieldDef, type LaunchParameter } from "@/data/game-data"; +import { + INI_FIELD_GROUPS, LAUNCH_PARAMETERS, GAME_MODES, PRESET_STYLES, + buildPresetConfig, + type IniFieldDef, type LaunchParameter, +} from "@/data/game-data"; import { getServerConfig, saveServerConfig, updateServerShutdownSettings, updateServerRestartSettings, updateServerUpdateSettings, getAppSetting, type ServerRow } from "@/lib/db"; import { toast } from "sonner"; import { NumberField } from "@/components/shared/NumberField"; +import { open as openFilePicker } from "@tauri-apps/plugin-dialog"; +import { readTextFile } from "@tauri-apps/plugin-fs"; interface Props { server: ServerRow; @@ -81,6 +95,25 @@ function rawTextToSections(text: string): Record> // Field row // --------------------------------------------------------------------------- +function FieldLabel({ field }: { field: IniFieldDef }) { + return ( + + {field.label} + {field.key} + {field.description && ( + + + + + + {field.description} + + + )} + + ); +} + function FieldRow({ field, value, @@ -93,16 +126,8 @@ function FieldRow({ if (field.type === "boolean") { const checked = value === "True" || value === "true" || value === "1"; return ( -
-
- - {field.description && ( -

{field.description}

- )} -
+
+
-
+

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

+ {/* Search */} +
+ + setSearch(e.target.value)} + placeholder="Search settings…" + className="h-8 pl-8 text-xs" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + /> +
{/* Scrollable body */}
{INI_FIELD_GROUPS.map((group) => { - const visibleFields = group.fields.filter( - (f) => f.section === "gus" && !OVERVIEW_KEYS.has(f.key) - ); + let visibleFields = group.fields.filter((f) => !OVERVIEW_KEYS.has(f.key)); + if (q) { + visibleFields = visibleFields.filter( + (f) => + f.label.toLowerCase().includes(q) || + f.key.toLowerCase().includes(q) || + (f.description?.toLowerCase().includes(q) ?? false), + ); + } if (visibleFields.length === 0) return null; - const open = expandedGroups.has(group.id); + const open = q ? true : expandedGroups.has(group.id); return (
+
+
+
+ +