import { useEffect, useState } from "react"; import { open } from "@tauri-apps/plugin-dialog"; import { ChevronDown, ChevronRight, Loader2, RefreshCw, Server } from "lucide-react"; import { applyServerUpdate, clearServerUpdateResult, refreshServerUpdateState, useServerUpdate } from "@/lib/serverUpdate"; import { isUpdateCurrent } from "@/lib/serverUpdateStatus"; import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { useStartAfterUpdate } from "@/lib/updatePrefs"; import { hasKey, useHuman, useI18n, type Key } from "@/i18n"; function mb(bytes: number) { return bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`; } export function ServerUpdateCard({ serverId, onHistory, onAttention }: { serverId: string; onHistory: (from?: string | null, to?: string) => void; onAttention: (value: boolean) => void }) { const { t } = useI18n(); const upd = useServerUpdate(serverId); const human = useHuman(); const [preview, setPreview] = useState(upd.preview); const [pending, setPending] = useState(null); const [pendingChecked, setPendingChecked] = useState(false); const [pendingStateError, setPendingStateError] = useState(null); const [localBusy, setBusy] = useState<"check" | "rollback" | "retry" | 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 = pendingStateError ?? 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>(() => Object.fromEntries((upd.preview?.conflicts ?? []).map(c => [c, "keep" as const]))); const [advanced, setAdvanced] = useState(false); const [source, setSource] = useState(""); const [startAfter, setStartAfter] = useStartAfterUpdate("server", serverId); useEffect(() => { let active = true; setPendingChecked(false); setPending(null); setPendingStateError(null); void api.pendingUpdate(serverId).then((txn) => { if (active) { setPending(txn); setPendingChecked(true); } }).catch((e) => { if (active) setPendingStateError(asUiError(e)); }); return () => { active = false; }; }, [serverId]); // Every finished attempt refreshes the disk state, including failures in the background. useEffect(() => { if (!upd.stateRevision) return; setPreview(null); setPendingChecked(!upd.stateError); setPendingStateError(upd.stateError); if (!upd.stateError) setPending(upd.result && "pending" in upd.result ? upd.result.pending : null); }, [upd.stateRevision, serverId]); useEffect(() => { onAttention(!!pending || !!pendingStateError); }, [pending, pendingStateError, onAttention]); async function refreshPending() { setPendingChecked(false); try { const txn = await refreshServerUpdateState(serverId); setPending(txn); setPendingStateError(null); setPendingChecked(true); return txn; } catch (e) { setPendingStateError(asUiError(e)); throw e; } } async function check() { setBusy("check"); setError(null); setDone(null); clearServerUpdateResult(serverId); setPreview(null); try { const txn = await refreshPending(); if (txn) return; const p = await api.checkUpdate(serverId, source.trim() || undefined); setPreview(p); setChoices(Object.fromEntries(p.conflicts.map((c) => [c, "keep" as const]))); } catch (e) { setError(asUiError(e)); } finally { setBusy(null); } } async function update() { if (!pendingChecked || pendingStateError || pending) return; setError(null); setDone(null); await applyServerUpdate(serverId, { choices, source: source.trim() || undefined }); } async function rollback(txn: UpdateTxn) { if (!window.confirm(t("upd.confirmBack"))) return; setBusy("rollback"); setError(null); try { await api.rollbackUpdate(serverId, txn.id); setPending(null); setDone(t("upd.wentBack")); } catch (e) { setError(asUiError(e)); } finally { try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ } setBusy(null); } } async function retryValidation(txn: UpdateTxn) { setBusy("retry"); setError(null); try { const result = await api.retryUpdateValidation(serverId, txn.id); if (result.state === "committed") { setPending(null); setPreview(null); setDone(t("upd.updatedTo", { v: result.to_version })); clearServerUpdateResult(serverId); } else setPending(result); } catch (e) { setError(asUiError(e)); } finally { try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ } setBusy(null); } } async function browse() { const p = await open({ directory: true, multiple: false, title: t("upd.dialogTitle") }); if (typeof p === "string") setSource(p); } return (
{pending && (

{pending.state === "needs-decision" ? t("upd.pendingBad") : t("upd.pendingUnfinished")}

{pending.message ?? t("upd.safeBack")}

{pending.state === "needs-decision" && ( )}

{t("upd.backNote")}

)}

{t("history.server")}

{preview?.from_version ? t("settings.version", { v: preview.from_version }) : "…"}

{advanced && (
setSource(e.target.value)} placeholder={t("upd.folderHint")} className="selectable flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" />
)} {done && pendingChecked && !pendingStateError &&

{done}

} {error && (

{error.human.code === "unknown" ? error.technical : human(error.human).message}

)} {preview?.database_check_error && (

{t("upd.dbUnchecked", { why: preview.database_check_error })}

)} {preview && isUpdateCurrent(preview) && (

{t("upd.current", { v: preview.to_version })}

)} {preview && !isUpdateCurrent(preview) && (

{preview.from_version ? t("upd.availableFrom", { to: preview.to_version, from: preview.from_version }) : t("upd.available", { to: preview.to_version })}

{preview.latest_version &&

{t("upd.intermediate", { to: preview.to_version, latest: preview.latest_version })}

}

{!preview.database_check_error && (preview.pending_migrations ?? preview.migrations) > 0 ? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.pending_migrations ?? preview.migrations }) : t("upd.summary", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length })}

i.action === "conflict")}>{t("history.files")}
    {preview.items.filter((i) => i.action !== "skip").map((i) => (
  • {i.path} {t(`upd.act.${i.action}` as Key)}
    {i.action === "conflict" && (
    {t("upd.conflict")} {t("upd.conflict")} {(["keep", "replace"] as const).map((c) => ( ))}
    )}
  • ))}

{t("upd.stopNote")}

)} {busy === "update" && progress && (
{hasKey(`ustep.${progress.step}`) ? t(`ustep.${progress.step}` as Key) : progress.step} {progress.percent}%
)}
); }