add updating dialog

This commit is contained in:
Eduard Gert
2026-05-20 16:20:40 +02:00
parent 42534b24c5
commit a7b26e3c0d
16 changed files with 408 additions and 451 deletions
@@ -4,14 +4,13 @@ import {
useContext,
useEffect,
useMemo,
useRef,
useState,
type ReactNode,
} from "react";
import { Events } from "@wailsio/runtime";
import { Update as UpdateSvc } from "@bindings/services";
import { Update as UpdateSvc, WindowManager } from "@bindings/services";
import type { State as UpdateState } from "@bindings/updater/models.js";
import { UpdateAvailableBanner } from "@/modules/auto-update/UpdateAvailableBanner";
import { UpdatingOverlay } from "@/modules/auto-update/UpdatingOverlay";
type ClientVersionContextValue = {
updateAvailable: boolean;
@@ -20,42 +19,22 @@ type ClientVersionContextValue = {
installing: boolean;
triggerUpdate: () => void;
updating: boolean;
updateError: string | null;
dismissUpdateError: () => void;
};
// Dev toggles — flip to preview UI states without triggering real flows.
const FORCE_UPDATE_AVAILABLE = false;
const FORCE_UPDATING = false;
const FORCE_ENFORCED = true;
const FORCE_VERSION = "0.65.0";
// Hide all "update available" UI (header trigger, settings badge, banner)
// regardless of what the daemon reports.
const HIDE_UPDATE_AVAILABLE = false;
// FORCE_ERROR options:
// null → no error (loading state)
// "timeout" → "Update timed out" state
// "cancel" → "Update canceled" state
// "fail" → generic "Update failed" state (uses FORCE_ERROR_MSG)
type ForceError = "timeout" | "cancel" | "fail" | null;
const FORCE_ERROR = null as ForceError;
const FORCE_ERROR_MSG = "installer exited with code 1";
const forcedErrorMessage = (): string | null => {
switch (FORCE_ERROR) {
case "timeout":
return "update timed out after 15m";
case "cancel":
return "update canceled by user";
case "fail":
return FORCE_ERROR_MSG;
default:
return null;
}
};
const EVENT_UPDATE_STATE = "netbird:update:state";
// Dev tab in Settings emits this with { updateAvailable, enforced, version }.
// Lives only in-memory in the main window for the session — losing it when
// Settings closes is acceptable per the dev-toggle scope (no daemon write,
// no persistence). See SettingsDevelopment.tsx.
const EVENT_DEV_OVERRIDES = "netbird:dev:overrides";
type DevOverrides = {
updateAvailable: boolean;
enforced: boolean;
version: string;
};
const emptyState: UpdateState = {
available: false,
version: "",
@@ -76,11 +55,8 @@ export const useClientVersion = () => {
export const ClientVersionProvider = ({ children }: { children: ReactNode }) => {
const [state, setState] = useState<UpdateState>(emptyState);
const [updating, setUpdating] = useState(false);
const [updateError, setUpdateError] = useState<string | null>(null);
const [devOverride, setDevOverride] = useState<DevOverrides | null>(null);
// Pull the current state once on mount so a banner / overlay that
// re-renders later in the session still has the right baseline, then
// subscribe to the push channel for live updates.
useEffect(() => {
let cancelled = false;
UpdateSvc.GetState()
@@ -100,40 +76,53 @@ export const ClientVersionProvider = ({ children }: { children: ReactNode }) =>
};
}, []);
// Merge the live state with dev overrides. The overrides win so designers
// can preview any branch without involving the daemon.
useEffect(() => {
const off = Events.On(EVENT_DEV_OVERRIDES, (ev: { data: DevOverrides }) => {
if (ev?.data) setDevOverride(ev.data);
});
return () => {
off?.();
};
}, []);
// Dev override only kicks in when it explicitly forces updateAvailable on.
// Otherwise daemon truth wins.
const effective = useMemo<UpdateState>(() => {
if (HIDE_UPDATE_AVAILABLE) return emptyState;
if (FORCE_UPDATE_AVAILABLE || FORCE_UPDATING) {
if (devOverride && devOverride.updateAvailable) {
return {
available: true,
version: FORCE_VERSION,
enforced: FORCE_ENFORCED,
installing: FORCE_UPDATING,
version: devOverride.version || "0.65.0",
enforced: devOverride.enforced,
installing: state.installing,
};
}
return state;
}, [state]);
}, [state, devOverride]);
// Force-install branch: daemon's progress_window:show flipped installing
// to true while the UI was idle. Open the install window so the user
// sees the progress UI without having to click anything.
const prevInstallingRef = useRef(false);
useEffect(() => {
if (effective.installing && !prevInstallingRef.current) {
WindowManager.OpenInstallProgress(effective.version || "").catch(console.error);
}
prevInstallingRef.current = effective.installing;
}, [effective.installing, effective.version]);
// Enforced user-driven branch: kick Trigger() in the background, then
// hand off to the install window. The window owns the polling loop and
// the final Quit() — this provider just fires the trigger.
const triggerUpdate = useCallback(() => {
setUpdateError(null);
setUpdating(true);
WindowManager.OpenInstallProgress(effective.version || "").catch(console.error);
UpdateSvc.Trigger()
.then((result) => {
if (!result?.success) {
setUpdateError(result?.errorMsg || "Update failed");
setUpdating(false);
}
.catch(() => {
// The daemon may already be down (force-install branch raced
// us). The install window's polling loop handles it.
})
.catch((e: unknown) => {
setUpdateError(String(e));
setUpdating(false);
});
}, []);
const dismissUpdateError = useCallback(() => setUpdateError(null), []);
const showOverlay = updating || effective.installing || updateError || FORCE_ERROR;
.finally(() => setUpdating(false));
}, [effective.version]);
const value = useMemo<ClientVersionContextValue>(
() => ({
@@ -143,23 +132,13 @@ export const ClientVersionProvider = ({ children }: { children: ReactNode }) =>
installing: effective.installing,
triggerUpdate,
updating,
updateError,
dismissUpdateError,
}),
[effective, triggerUpdate, updating, updateError, dismissUpdateError],
[effective, triggerUpdate, updating],
);
return (
<ClientVersionContext.Provider value={value}>
{children}
<UpdateAvailableBanner />
{showOverlay && (
<UpdatingOverlay
version={effective.version || null}
error={updateError ?? forcedErrorMessage()}
onDismiss={dismissUpdateError}
/>
)}
</ClientVersionContext.Provider>
);
};
@@ -0,0 +1,182 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useSearchParams } from "react-router-dom";
import { Loader2, XCircle } from "lucide-react";
import { Update as UpdateSvc, WindowManager } from "@bindings/services";
import { Button } from "@/components/Button";
import { ConfirmDialog } from "@/components/ConfirmDialog";
import { DialogActions } from "@/components/DialogActions";
import { DialogDescription } from "@/components/DialogDescription";
import { DialogHeading } from "@/components/DialogHeading";
import { SquareIcon } from "@/components/SquareIcon";
import { useAutoSizeWindow } from "@/lib/useAutoSizeWindow";
const TIMEOUT_MS = 15 * 60 * 1000;
const POLL_INTERVAL_MS = 2000;
// Sustained gRPC failure during install is taken as success — the daemon
// gets restarted by the installer mid-flight, mirroring the legacy Fyne
// UI's branch in client/ui/update.go.
const DAEMON_DOWN_GRACE_MS = 5000;
const WINDOW_WIDTH = 360;
type Phase =
| { kind: "running" }
| { kind: "timeout" }
| { kind: "canceled" }
| { kind: "failed"; message: string };
export default function InstallProgressDialog() {
const { t } = useTranslation();
const [params] = useSearchParams();
const version = params.get("version") ?? "";
const [phase, setPhase] = useState<Phase>({ kind: "running" });
const phaseRef = useRef(phase);
phaseRef.current = phase;
const contentRef = useAutoSizeWindow<HTMLDivElement>(WINDOW_WIDTH);
useEffect(() => {
let cancelled = false;
const start = Date.now();
let firstUnreachableAt: number | null = null;
const timer = setInterval(async () => {
if (cancelled) return;
if (phaseRef.current.kind !== "running") return;
if (Date.now() - start > TIMEOUT_MS) {
clearInterval(timer);
setPhase({ kind: "timeout" });
return;
}
try {
const r = await UpdateSvc.GetInstallerResult();
firstUnreachableAt = null;
if (r.success) {
clearInterval(timer);
UpdateSvc.Quit();
return;
}
if (r.errorMsg) {
clearInterval(timer);
setPhase(mapInstallError(r.errorMsg));
}
} catch {
const now = Date.now();
if (firstUnreachableAt === null) {
firstUnreachableAt = now;
} else if (now - firstUnreachableAt >= DAEMON_DOWN_GRACE_MS) {
clearInterval(timer);
UpdateSvc.Quit();
}
}
}, POLL_INTERVAL_MS);
return () => {
cancelled = true;
clearInterval(timer);
};
}, []);
const isError = phase.kind !== "running";
const errorInfo = isError ? classifyPhase(phase, version, t) : null;
return (
<ConfirmDialog ref={contentRef}>
{isError ? (
<SquareIcon
icon={XCircle}
className={"mt-4 bg-red-500 [&_svg]:text-white"}
/>
) : (
<SquareIcon icon={Loader2} className={"mt-4 [&_svg]:animate-spin"} />
)}
<div className={"flex flex-col items-center gap-2"}>
<DialogHeading className={"text-balance"}>
{isError
? errorInfo!.title
: version
? t("update.overlay.updatingVersion", { version })
: t("update.overlay.updating")}
</DialogHeading>
<DialogDescription>
{isError ? (
<>
{errorInfo!.description}
{errorInfo!.message && (
<>
<br />
<span className={"first-letter:uppercase"}>
{errorInfo!.message}
</span>
</>
)}
</>
) : (
t("update.overlay.description")
)}
</DialogDescription>
</div>
{isError && (
<DialogActions>
<Button
variant={"secondary"}
size={"md"}
className={"w-full"}
onClick={() =>
WindowManager.CloseInstallProgress().catch(console.error)
}
>
{t("common.close")}
</Button>
</DialogActions>
)}
</ConfirmDialog>
);
}
function mapInstallError(msg: string): Phase {
const m = msg.trim().toLowerCase();
if (m === "") return { kind: "failed", message: "unknown update error" };
if (m.includes("deadline exceeded") || m.includes("timeout") || m.includes("timed out")) {
return { kind: "timeout" };
}
if (m.includes("canceled") || m.includes("cancelled") || m.includes("cancel")) {
return { kind: "canceled" };
}
return { kind: "failed", message: msg };
}
type Variant = { title: string; description: string; message?: string };
function classifyPhase(
phase: Phase,
version: string,
t: (key: string, options?: Record<string, unknown>) => string,
): Variant {
const target = version
? t("update.overlay.error.targetVersion", { version })
: t("update.overlay.error.targetFallback");
switch (phase.kind) {
case "timeout":
return {
title: t("update.overlay.error.timeoutTitle"),
description: t("update.overlay.error.timeoutDescription", { target }),
};
case "canceled":
return {
title: t("update.overlay.error.canceledTitle"),
description: t("update.overlay.error.canceledDescription", { target }),
};
case "failed":
return {
title: t("update.overlay.error.failTitle"),
description: t("update.overlay.error.failDescription", { target }),
message: phase.message || t("update.overlay.error.unknownMessage"),
};
default:
return { title: "", description: "" };
}
}
@@ -25,10 +25,13 @@ export function UpdateVersionCard() {
const { updateVersion, enforced, triggerUpdate } = useClientVersion();
if (updateVersion) {
const titleKey = enforced
? "update.card.versionAvailableInstall"
: "update.card.versionAvailableDownload";
return (
<Card>
<div>
<Title>{t("update.card.versionAvailable", { version: updateVersion })}</Title>
<Title>{t(titleKey, { version: updateVersion })}</Title>
<Link
url={`https://github.com/netbirdio/netbird/releases/tag/v${updateVersion}`}
>
@@ -1,118 +0,0 @@
import { useTranslation } from "react-i18next";
import { Loader2, XCircle } from "lucide-react";
import { Button } from "@/components/Button";
type Props = {
version: string | null;
error: string | null;
onDismiss: () => void;
};
type Variant = {
title: string;
description: string;
message?: string;
};
function classifyError(
msg: string,
version: string | null,
t: (key: string, options?: Record<string, unknown>) => string,
): Variant {
const lower = msg.toLowerCase();
const target = version
? t("update.overlay.error.targetVersion", { version })
: t("update.overlay.error.targetFallback");
if (lower.includes("timeout") || lower.includes("timed out")) {
return {
title: t("update.overlay.error.timeoutTitle"),
description: t("update.overlay.error.timeoutDescription", { target }),
};
}
if (lower.includes("cancel")) {
return {
title: t("update.overlay.error.canceledTitle"),
description: t("update.overlay.error.canceledDescription", { target }),
};
}
return {
title: t("update.overlay.error.failTitle"),
description: t("update.overlay.error.failDescription", { target }),
message: msg || t("update.overlay.error.unknownMessage"),
};
}
export const UpdatingOverlay = ({ version, error, onDismiss }: Props) => {
const { t } = useTranslation();
const isError = Boolean(error);
const errorInfo = error ? classifyError(error, version, t) : null;
return (
<div
className={
"fixed inset-0 z-[100] flex items-center justify-center bg-nb-gray-950/85 backdrop-blur-sm cursor-default select-none wails-draggable"
}
onPointerDown={(e) => {
if (isError) return;
e.preventDefault();
e.stopPropagation();
}}
onKeyDown={(e) => {
if (isError) return;
e.preventDefault();
e.stopPropagation();
}}
>
<div className={"flex flex-col items-center gap-5 px-8 max-w-lg text-center"}>
{isError ? (
<div
className={"h-9 w-9 rounded-md flex items-center justify-center bg-red-500"}
>
<XCircle className={"text-white"} size={18} />
</div>
) : (
<div
className={"h-9 w-9 rounded-md flex items-center justify-center bg-nb-gray-100"}
>
<Loader2 className={"animate-spin text-nb-gray-950"} size={16} />
</div>
)}
<div className={"flex flex-col items-center gap-1"}>
<p className={"text-base font-medium text-nb-gray-50"}>
{isError
? errorInfo!.title
: version
? t("update.overlay.updatingVersion", { version })
: t("update.overlay.updating")}
</p>
<p className={"text-sm text-nb-gray-300"}>
{isError ? (
<>
{errorInfo!.description}
{errorInfo!.message && (
<>
<br />
<span className={"first-letter:uppercase"}>
{errorInfo!.message}
</span>
</>
)}
</>
) : (
t("update.overlay.description")
)}
</p>
</div>
{isError && (
<div className={"wails-no-draggable"}>
<Button variant={"secondary"} size={"xs"} onClick={onDismiss}>
{t("common.close")}
</Button>
</div>
)}
</div>
</div>
);
};
@@ -1,30 +1,84 @@
import { useEffect, useState } from "react";
import { Events } from "@wailsio/runtime";
import { Button } from "@/components/Button";
import FancyToggleSwitch from "@/components/FancyToggleSwitch";
import { WindowManager } from "@bindings/services";
import { SectionGroup } from "@/modules/settings/SettingsSection.tsx";
// Cross-window dev override: ClientVersionContext in the main window
// listens for this and replaces daemon-reported update state with the
// toggle values. Resets when the Settings window closes (no persistence
// by design).
const EVENT_DEV_OVERRIDES = "netbird:dev:overrides";
const PREVIEW_VERSION = "0.65.0";
export function SettingsDevelopment() {
const [updateAvailable, setUpdateAvailable] = useState(false);
const [enforced, setEnforced] = useState(false);
useEffect(() => {
void Events.Emit(EVENT_DEV_OVERRIDES, {
updateAvailable,
enforced,
version: PREVIEW_VERSION,
});
}, [updateAvailable, enforced]);
return (
<SectionGroup title={"Session windows"}>
<div className={"flex flex-col gap-2 items-start"}>
<Button
variant={"secondary"}
onClick={() =>
WindowManager.OpenSessionExpired().catch(console.error)
<>
<SectionGroup title={"Auto-update"}>
<FancyToggleSwitch
value={updateAvailable}
onChange={setUpdateAvailable}
label={"Is update available"}
helpText={
"Force the UI to think a new version is available. Reflects in the About card and the header badge."
}
>
Open Session expired
</Button>
<Button
variant={"secondary"}
onClick={() =>
WindowManager.OpenSessionAboutToExpire(336).catch(
console.error,
)
/>
<FancyToggleSwitch
value={enforced}
onChange={setEnforced}
label={"Auto update enabled"}
helpText={
"Force the UI to think management has auto-update enabled. Switches the About card to “Install now”."
}
>
Open About to expire (5:36)
</Button>
</div>
</SectionGroup>
/>
<div className={"flex flex-col gap-2 items-start pt-2"}>
<Button
variant={"secondary"}
onClick={() =>
WindowManager.OpenInstallProgress(PREVIEW_VERSION).catch(
console.error,
)
}
>
Show updating dialog
</Button>
</div>
</SectionGroup>
<SectionGroup title={"Session windows"}>
<div className={"flex flex-col gap-2 items-start"}>
<Button
variant={"secondary"}
onClick={() =>
WindowManager.OpenSessionExpired().catch(console.error)
}
>
Open Session expired
</Button>
<Button
variant={"secondary"}
onClick={() =>
WindowManager.OpenSessionAboutToExpire(336).catch(
console.error,
)
}
>
Open About to expire (5:36)
</Button>
</div>
</SectionGroup>
</>
);
}
@@ -1,7 +1,7 @@
import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Dialogs } from "@wailsio/runtime";
import { LogOut, PlusCircle, Trash2, UserCircle } from "lucide-react";
import { CircleMinus, PlusCircle, Trash2, UserCircle } from "lucide-react";
import type { Profile } from "@bindings/services/models.js";
import { Badge } from "@/components/Badge";
import { Button } from "@/components/Button";
@@ -251,7 +251,7 @@ const RowActions = ({ canDeregister, canDelete, onDeregister, onDelete }: RowAct
<div className={"inline-flex items-center gap-1"}>
<ActionIconButton
label={t("profile.selector.deregister")}
icon={LogOut}
icon={CircleMinus}
onClick={onDeregister}
hidden={!canDeregister}
/>
@@ -268,7 +268,7 @@ const RowActions = ({ canDeregister, canDelete, onDeregister, onDelete }: RowAct
type ActionIconButtonProps = {
label: string;
icon: typeof LogOut;
icon: typeof CircleMinus;
onClick: () => void;
variant?: "default" | "danger";
/** When true the button still occupies space (preserves row layout)