From 2c0bb2bac3802d09963cfe42143769d6139348d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Thu, 1 Oct 2026 14:05:56 +0500 Subject: [PATCH] Settings: a running server update survives leaving the tab The update's busy flag, progress and result were local to the Settings card, so switching tabs and coming back showed 'Update now' again while the update was still running (and the server rightly answered 'another action is still in progress'). They now live in the shared server-update store: the card re-attaches to the running update with its progress, and shows how it ended. Co-Authored-By: Claude Sonnet 5.5 --- src/dev/mock.ts | 2 +- src/lib/serverUpdate.ts | 32 +++++++++++++++++++------- src/screens/SettingsHome.tsx | 44 +++++++++++++++++------------------- 3 files changed, 46 insertions(+), 32 deletions(-) diff --git a/src/dev/mock.ts b/src/dev/mock.ts index 8a78d53..8cead1c 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -32,7 +32,7 @@ export {}; if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]}; if(cmd==="add_companions"){const base=(window as any).__bots??85;(window as any).__target=base+args.count;return {spawned:"queued",created:null,baseline:base};} if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261001.8":"0.260930.5",to_version:"0.261001.8",items:[],conflicts:[],migrations:5,download_bytes:6000000}; - if(cmd==="apply_update"){await new Promise((r: any)=>setTimeout(r,1500));(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261001.8"},migrations:null};} + if(cmd==="apply_update"){const w=window as any;for(let i=1;i<=8;i++){await new Promise((r: any)=>setTimeout(r,700));(w.__handlers?.["update-progress"]??[]).forEach((h: any)=>h({event:"update-progress",id:1,payload:{step:i<4?"Downloading the update":i<7?"Applying the update":"Finishing",percent:i*12}}));}(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261001.8"},migrations:null};} if(cmd==="get_population"){if(!running) return null;let b=(window as any).__bots??85;const t=(window as any).__target??0;if(t>b){b=Math.min(t,b+25);(window as any).__bots=b;}return {online_total:b,bots_online:Math.max(0,b-7),players_online:0,bots_total:b};} if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null; if(cmd==="run_diagnostics") return {problems:2,checks:[{id:"files",title:"Server files",level:"ok",detail:"All expected server parts were found."},{id:"world",title:"World server",level:"warn",detail:"Not running."},{id:"disk",title:"Free disk space",level:"warn",detail:"Only 3 GB free; backups and updates need room."},{id:"exposure",title:"Private services",level:"ok",detail:"Database and server console are not reachable from the network."}]}; diff --git a/src/lib/serverUpdate.ts b/src/lib/serverUpdate.ts index 7def550..49727ff 100644 --- a/src/lib/serverUpdate.ts +++ b/src/lib/serverUpdate.ts @@ -1,6 +1,6 @@ import { useSyncExternalStore } from "react"; import { listen } from "@tauri-apps/api/event"; -import { api, asUiError, type UpdatePreview } from "@/lib/api"; +import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api"; /** * Server update status for the main screen and the navigation: checked when the app starts and every five minutes, @@ -14,9 +14,13 @@ export interface ServerUpdateState { step: string | null; percent: number; error: string | null; + /** The full error of the last update attempt, for the Settings card. */ + uiError: UiError | null; + /** How the last update ended; kept here so the Settings card can show it after the user left and came back. */ + result: { committed: string } | { pending: UpdateTxn } | null; } -const EMPTY: ServerUpdateState = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null }; +const EMPTY: ServerUpdateState = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null, uiError: null, result: null }; const states = new Map(); const listeners = new Set<() => void>(); export const CHECK_EVERY_MS = 5 * 60 * 1000; @@ -49,11 +53,21 @@ export function startServerUpdatePolling(id: string): () => void { return () => clearInterval(t); } -/** Apply the pending update when no file needs a decision. Resolves true on success. */ -export async function applyServerUpdate(id: string): Promise { +export function clearServerUpdateResult(id: string) { + set(id, { result: null, uiError: null }); +} + +/** + * Apply an update. Without options this is the main-screen button: the pending update, only when no file needs a + * decision. With options (the Settings card) the owner has already chosen what to do with each changed file and may + * point at another package source. The state lives here, not in a screen, so leaving the Settings tab and coming back + * shows the update still running (and its progress) instead of an "Update now" button the server would refuse. + */ +export async function applyServerUpdate(id: string, opts?: { choices: Record; source?: string }): Promise { const p = get(id).preview; - if (!p || p.conflicts.length > 0 || get(id).applying) return false; - set(id, { applying: true, step: null, percent: 0, error: null }); + if (get(id).applying) return false; + if (!opts && (!p || p.conflicts.length > 0)) return false; + set(id, { applying: true, step: null, percent: 0, error: null, uiError: null, result: null }); let un: (() => void) | undefined; try { un = await listen<{ step: string; percent: number }>("update-progress", (e) => set(id, { step: e.payload.step, percent: e.payload.percent })); @@ -61,10 +75,12 @@ export async function applyServerUpdate(id: string): Promise { /* progress is optional */ } try { - await api.applyUpdate(id, {}); + const out = await api.applyUpdate(id, opts?.choices ?? {}, opts?.source); + set(id, { result: out.txn.state === "committed" ? { committed: out.txn.to_version ?? "" } : { pending: out.txn } }); return true; } catch (e) { - set(id, { error: asUiError(e).human.code }); + const ui = asUiError(e); + set(id, { error: ui.human.code, uiError: ui }); return false; } finally { un?.(); diff --git a/src/screens/SettingsHome.tsx b/src/screens/SettingsHome.tsx index cb2104d..bbd50ed 100644 --- a/src/screens/SettingsHome.tsx +++ b/src/screens/SettingsHome.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from "react"; -import { listen } from "@tauri-apps/api/event"; import { open } from "@tauri-apps/plugin-dialog"; import { ChevronDown, ChevronRight, Loader2 } from "lucide-react"; +import { applyServerUpdate, clearServerUpdateResult, useServerUpdate } from "@/lib/serverUpdate"; import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; @@ -17,29 +17,39 @@ function mb(bytes: number) { export function SettingsHome({ serverId }: { serverId: string }) { const { t } = useI18n(); + const upd = useServerUpdate(serverId); const human = useHuman(); const [preview, setPreview] = useState(null); const [pending, setPending] = useState(null); - const [busy, setBusy] = useState<"check" | "update" | "rollback" | null>(null); - const [progress, setProgress] = useState<{ step: string; percent: number } | null>(null); - const [error, setError] = useState(null); - const [done, setDone] = useState(null); + const [localBusy, setBusy] = useState<"check" | "rollback" | null>(null); + // an update keeps running in the background when this tab is left, so its state is the shared one + const busy = upd.applying ? "update" : localBusy; + const progress = upd.applying ? { step: upd.step ?? "Starting", percent: upd.percent } : null; + const [localError, setError] = useState(null); + const error = localError ?? upd.uiError; + const [localDone, setDone] = useState(null); + const done = upd.result && "committed" in upd.result ? t("upd.updatedTo", { v: upd.result.committed }) : localDone; const [choices, setChoices] = useState>({}); const [advanced, setAdvanced] = useState(false); const [source, setSource] = useState(""); useEffect(() => { void api.pendingUpdate(serverId).then(setPending).catch(() => {}); - const un = listen<{ step: string; percent: number }>("update-progress", (e) => setProgress(e.payload)); - return () => { - void un.then((f) => f()); - }; }, [serverId]); + // the update finished (possibly while another tab was open): drop the stale preview, show what is left to decide + useEffect(() => { + if (!upd.result) return; + setPreview(null); + if ("pending" in upd.result) setPending(upd.result.pending); + else void api.pendingUpdate(serverId).then(setPending).catch(() => {}); + }, [upd.result, serverId]); + async function check() { setBusy("check"); setError(null); setDone(null); + clearServerUpdateResult(serverId); setPreview(null); try { const p = await api.checkUpdate(serverId, source.trim() || undefined); @@ -53,21 +63,9 @@ export function SettingsHome({ serverId }: { serverId: string }) { } async function update() { - setBusy("update"); setError(null); - setProgress({ step: "Starting", percent: 0 }); - try { - const out = await api.applyUpdate(serverId, choices, source.trim() || undefined); - setPreview(null); - if (out.txn.state === "committed") setDone(t("upd.updatedTo", { v: out.txn.to_version ?? "" })); - else setPending(out.txn); - } catch (e) { - setError(asUiError(e)); - } finally { - setBusy(null); - setProgress(null); - void api.pendingUpdate(serverId).then(setPending).catch(() => {}); - } + setDone(null); + await applyServerUpdate(serverId, { choices, source: source.trim() || undefined }); } async function rollback(txn: UpdateTxn) {