From 7779274308f3d73eff25797097cbb4e10f8d83ac Mon Sep 17 00:00:00 2001 From: Precious Okwu Date: Thu, 26 Nov 2026 07:19:48 +0100 Subject: [PATCH] UI: show universal Restarting overlay and shared spinner across all restarts --- crates/kiri-win/src/update.rs | 1 + crates/kiri-win/src/wslconfig.rs | 8 +- crates/kiri/src/ui/index.html | 148 ++++++++++++++++++++++++------- crates/kiri/src/ui/mod.rs | 27 +++--- tests/ui/restartnow.js | 130 +++++++++++++++++++++++++-- 5 files changed, 264 insertions(+), 50 deletions(-) diff --git a/crates/kiri-win/src/update.rs b/crates/kiri-win/src/update.rs index c188c07..0cb3aea 100644 --- a/crates/kiri-win/src/update.rs +++ b/crates/kiri-win/src/update.rs @@ -726,6 +726,7 @@ fn restart_and_report() { } Err(e) => { crate::serve::log(&format!("engine: did not restart ({e})")); + emit(json!({"type": "enginerestarted", "error": e.to_string()}).to_string()); emit(notice("error", &trf("Could not restart the engine: {error}", &[("error", &e)]))); if let Some(v) = engine_version() && newer(CURRENT, &v) diff --git a/crates/kiri-win/src/wslconfig.rs b/crates/kiri-win/src/wslconfig.rs index 466d338..ab5a7a9 100644 --- a/crates/kiri-win/src/wslconfig.rs +++ b/crates/kiri-win/src/wslconfig.rs @@ -334,17 +334,23 @@ pub fn resources(body: Option) { /// Restart to apply: WSL stops and Kiri's engine starts again. pub fn restart() { std::thread::spawn(|| { + emit(json!({"type": "state", "state": "stopping"}).to_string()); let mut cmd = crate::win::tool("wsl.exe"); std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); - let r = cmd.arg("--shutdown").status().and_then(|s| if s.success() { Ok(()) } else { Err(io::Error::other("wsl --shutdown failed")) }).and_then(|()| crate::engine::ensure_daemon()); + let r = cmd.arg("--shutdown").status().and_then(|s| if s.success() { Ok(()) } else { Err(io::Error::other("wsl --shutdown failed")) }).and_then(|()| { + emit(json!({"type": "state", "state": "booting"}).to_string()); + crate::engine::ensure_daemon() + }); if r.is_ok() { let _ = apply_wsl_integration(None, true); } + emit(json!({"type": "vmrestarted", "ok": r.is_ok()}).to_string()); emit(match r { Ok(()) => notice("ok", &tr("WSL restarted with the new resources")), Err(e) => notice("error", &trf("Could not restart WSL: {error}", &[("error", &e)])), }); emit(event().to_string()); + crate::engine::send(crate::engine::Cmd::Refresh); }); } diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index a85c083..c0c677f 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -160,7 +160,7 @@ body.rail .vm .dot { width: 6px; height: 6px; position: relative; box-shadow: no body.rail[data-vm=running] .vm .dot::after { content: ""; position: absolute; inset: 0; border-radius: 50%; background: var(--moss); --ring: 2.8; animation: var(--beat); pointer-events: none; } .mark .speed { fill: currentColor; opacity: .35; transition: opacity .3s; } [data-vm=running] .mark .speed { opacity: .9; } -[data-vm=booting] .mark .speed { animation: zoom .25s infinite alternate; } +[data-vm=booting] .mark .speed, [data-vm=restarting] .mark .speed { animation: zoom .25s infinite alternate; } [data-vm=stopped] .mark .eyes, [data-vm=asleep] .mark .eyes { transform: scaleY(.25); transform-origin: 46px 29px; } .navlabel { font-size: var(--fs); font-weight: 600; color: var(--faint); padding: 10px 8px 4px; text-transform: uppercase; letter-spacing: .06em; } @@ -180,7 +180,7 @@ nav .count { margin-inline-start: auto; font-size: var(--fs); color: var(--faint .vm-head { display: flex; align-items: center; gap: 7px; font-weight: 600; } .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--faint); flex: none; } [data-vm=running] .dot { background: var(--moss); box-shadow: 0 0 0 3px color-mix(in srgb, var(--moss) 25%, transparent); } -[data-vm=booting] .dot, [data-vm=waking] .dot, [data-vm=stopping] .dot { background: var(--sun); animation: pulse .8s infinite alternate; } +[data-vm=booting] .dot, [data-vm=waking] .dot, [data-vm=stopping] .dot, [data-vm=restarting] .dot { background: var(--sun); animation: pulse .8s infinite alternate; } [data-vm=asleep] .dot { background: transparent; box-shadow: inset 0 0 0 2px var(--moss); } .vm-sub { color: var(--faint); font-size: var(--fs-small); margin-top: -6px; } #vm-state { margin-inline-start: auto; font-weight: 500; color: var(--muted); font-size: var(--fs); } @@ -868,7 +868,7 @@ tr[data-rowopen] .sel, .sel { cursor: text; -webkit-user-select: text; user-sele .statusbar .k8s { width: 13px; height: 13px; fill: #326CE5; flex: none; } .statusbar .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--faint); } .statusbar .dot.running { background: var(--moss); } -.statusbar .dot.booting, .statusbar .dot.stopping { background: var(--sun); } +.statusbar .dot.booting, .statusbar .dot.stopping, .statusbar .dot.restarting { background: var(--sun); } .statusbar .dot.asleep { background: transparent; box-shadow: inset 0 0 0 1.5px var(--moss); } .statusbar .sep { color: var(--faint); } /* Kiri Dev, after the version: solid amber with near-black text, the same in either theme. */ @@ -1234,7 +1234,7 @@ tr.row:hover td.actions .acts-row { background: linear-gradient(var(--fwd), tran #onb .st.no, #onb .st.restart { background: rgba(255, 194, 61, .15); color: var(--sun-text); } #onb .st.bad { background: rgba(220, 53, 69, .16); color: var(--red-text); } #onb .st.off { background: var(--raised); color: var(--faint); } -#onb .st.wait { border: 2px solid var(--line); border-top-color: var(--blue); animation: onbspin .8s linear infinite; } +#onb .st.wait { border: 2px solid color-mix(in srgb, var(--sun) 20%, var(--line)); border-top-color: var(--sun); border-right-color: color-mix(in srgb, var(--sun) 65%, transparent); animation: onbspin .8s linear infinite; } @keyframes onbspin { to { transform: rotate(360deg); } } #onb .btn svg.i { width: 13px; height: 13px; } #onb .onb-ft { display: flex; align-items: center; gap: 8px; margin-top: 14px; } @@ -1249,6 +1249,26 @@ tr.row:hover td.actions .acts-row { background: linear-gradient(var(--fwd), tran #onb .onb-rs p { color: var(--muted); font-size: var(--fs-small); margin: 2px 0 8px; } #onb .onb-rs .a { display: flex; gap: 6px; } .scrim { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); display: grid; place-items: center; z-index: 8; } +/* Universal Restarting overlay & shared restarting spinner (.rspin). */ +.rspin { --sz: 40px; position: relative; width: var(--sz); height: var(--sz); display: inline-grid; place-items: center; flex: none; } +.rspin::before { content: ""; position: absolute; inset: 0; border-radius: 50%; border: 2.5px solid color-mix(in srgb, var(--sun) 20%, var(--line)); border-top-color: var(--sun); border-right-color: color-mix(in srgb, var(--sun) 65%, transparent); animation: spin .85s cubic-bezier(.42, .15, .58, .85) infinite; } +.rspin.sm { --sz: 16px; } +.rspin.sm::before { border-width: 2px; } +.rspin.md { --sz: 28px; } +.rspin.md::before { border-width: 2.2px; } +.rspin .kdot { width: 16px; height: 17px; animation: bob 1.5s ease-in-out infinite; } +.rspin.md .kdot { width: 12px; height: 13px; } +.rspin.plain .kdot { display: none; } +.rscrim { position: fixed; inset: 0; z-index: 25; background: rgba(8, 12, 16, .58); -webkit-backdrop-filter: blur(3px); backdrop-filter: blur(3px); display: grid; place-items: center; animation: sh-fade .16s ease-out; } +@media (prefers-color-scheme: light) { :root:not([data-theme="dark"]) .rscrim { background: rgba(15, 20, 25, .36); } } +:root[data-theme="light"] .rscrim { background: rgba(15, 20, 25, .36); } +.rdlg { width: min(360px, calc(100% - 32px)); background: var(--panel); border: 1px solid color-mix(in srgb, var(--sun) 32%, var(--line)); border-radius: 14px; padding: 24px 22px 20px; display: grid; justify-items: center; text-align: center; gap: 8px; box-shadow: 0 24px 60px rgba(0, 0, 0, .48); animation: sh-rise .2s ease-out; } +.rdlg h3 { font-size: var(--fs-head); font-weight: 700; letter-spacing: -.01em; margin-top: 4px; } +.rdlg .rwhat { color: var(--muted); font-size: var(--fs); max-width: 300px; line-height: 1.45; overflow-wrap: anywhere; } +.rdlg .rstep { margin-top: 4px; display: inline-flex; align-items: center; gap: 7px; padding: 4px 11px; border-radius: 999px; background: var(--raised); border: 1px solid var(--line); font-size: var(--fs-small); color: var(--muted); font-variant-numeric: tabular-nums; max-width: 100%; } +.rdlg .rstep i { width: 6px; height: 6px; border-radius: 50%; background: var(--sun); flex: none; animation: pulse .75s infinite alternate; } +.rdlg .rbar { width: 100%; height: 4px; border-radius: 99px; background: var(--raised); overflow: hidden; margin-top: 6px; } +.rdlg .rbar span { display: block; height: 100%; background: var(--sun); border-radius: 99px; transition: width .35s ease; } /* The language step's dialog takes its height from this box, not the window's: Text size zooms the page, and 100vh would be the unzoomed window. */ .scrim.langstep { z-index: 40; grid-template: minmax(0, 1fr) / minmax(0, 1fr); } @@ -2610,6 +2630,7 @@ tr.usb-more > td { padding: 0; background: var(--panel); }
+ @@ -2815,15 +2836,15 @@ const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "& const ui = { acting: new Map(), gacting: new Map(), running: new Set(), launched: new Map(), runWatch: new Map(), need: null, probed: new Map(), probing: new Set(), why: new Map(), startErr: {}, fixed: null, openTab: null, listening: new Map(), starting: new Map(), scans: new Map(), scanf: { sev: "", fix: false, own: false }, view: "containers", vm: "stopped", containers: [], images: [], volumes: [], volSizes: {}, volSizesLoading: false, volSizesAt: 0, volSizesKey: "", volSizesInFlight: 0, networks: [], sort: { images: { key: "pulled", desc: true } }, filter: "", suffix: "kiri.localhost", collapsed: new Set(), res: null, resDraft: {}, storage: null, stErr: "", stReclaiming: false, stReclaimed: null, stPruning: false, stPruned: null, bset: null, bsetDraft: null, vmnet: null, shellPath: null, shellPathBusy: false, proxy: null, pxDraft: {}, rports: null, rpDraft: {}, rpAt: 0, regcfg: null, regBase: null, regDraft: { insecure: [], mirrors: [] }, regAdd: { insecure: "", mirrors: "" }, dockersock: null, sockTaking: false, ctxSwitching: false, imp: { sources: null, source: null, inv: null, picked: { images: new Set(), volumes: new Set(), containers: new Set() }, steps: {}, running: false, summary: "" }, - upd: null, engineStale: null, staleHidden: false, + upd: null, engineStale: null, staleHidden: false, restarting: null, // The Builds view: the list, the picked build and its detail, and how its steps show. bl: { items: null, error: "", sel: null, d: null, steps: "all", internal: false, open: new Set(), confirm: null, tab: "steps", layers: null, plat: null } }; function resetPicks() { ui.imp.picked = { images: new Set(), volumes: new Set(), containers: new Set() }; ui.imp.steps = {}; ui.imp.summary = ""; } // Asleep is ready: the VM sleeps after a minute with nothing running and the next // request wakes it in milliseconds, so it reads as Ready with Stop, never as stopped // with Start. Start is for an engine someone stopped (Stop, `kiri stop`). -const vmLabels = { stopped: "Off", booting: "Starting…", running: "Running", stopping: "Stopping…" }; -/* i18n */ void [tr("Off"), tr("Starting…"), tr("Running"), tr("Stopping…")]; +const vmLabels = { stopped: "Off", booting: "Starting…", running: "Running", stopping: "Stopping…", restarting: "Restarting…" }; +/* i18n */ void [tr("Off"), tr("Starting…"), tr("Running"), tr("Stopping…"), tr("Restarting…")]; /* i18n */ void [tr("Mac"), tr("PC"), tr("computer"), tr("Linux VM"), tr("Engine")]; function size(b) { @@ -3967,6 +3988,40 @@ const KIRI_MARK = ``; +const rspin = (cls = "") => ``; +function drawRestartOverlay() { + const el = $("rscrim"), r = ui.restarting; + if (!el) return; + if (!r) { el.hidden = true; el.innerHTML = ""; return; } + el.hidden = false; + setHTML(el, `
${rspin()}

${tr("Restarting…")}

${r.what ? `

${r.what}

` : ""}${r.step ? `${esc(r.step)}` : ""}${r.pct != null ? `
` : ""}
`); +} +function startRestartOverlay(kind, what, step, pct = null) { + ui.restarting = { kind, what: what || "", step: step || tr("Restarting…"), pct }; + drawRestartOverlay(); + paintEngine(); + renderStatus(); + if (ui.view === "settings" && prefs.tab === "resources") render(); +} +function setRestartStep(step, pct = ui.restarting?.pct ?? null) { + if (!ui.restarting) return; + ui.restarting.step = step; + ui.restarting.pct = pct; + drawRestartOverlay(); +} +function stopRestartOverlay() { + if (!ui.restarting) return; + ui.restarting = null; + drawRestartOverlay(); + paintEngine(); + renderStatus(); + if (ui.view === "settings") render(); +} +function restartVm() { + const note = esc(ui.res?.restart_note || tr("Restarting stops the running containers; start them again afterwards.")); + startRestartOverlay("vm", note, tr("Stopping containers…")); + send("restartvm"); +} const localChip = (url) => ``; /* First open: two small pictures of the same app, by port and by name. */ @@ -4013,6 +4068,7 @@ const ONB_MAC = [ tr("The engine runs from the app for now"), tr("Show log"), tr("Continue anyway"), tr("One step didn't work. Everything else is ready."), tr("Some steps didn't work. Everything else is ready.")]; const onbIcon = (name) => ``; function onboarding(e) { + if (ui.restarting?.kind === "onb") stopRestartOverlay(); ui.onb = { ...e, busy: null }; let el = $("onb"); if (!el) { @@ -4064,17 +4120,19 @@ function onbClick(ev) { o.error = ""; send("onbskip", { name: b.dataset.onbskip, value: !b.dataset.undo }); } else if (b.dataset.onbfix) { + if (b.dataset.onbfix === "running" && o.checks?.running === "bad") startRestartOverlay("onb", "", tr("Restarting engine…")); o.busy = b.dataset.onbfix; o.error = ""; drawOnb(); send("onbfix", { name: b.dataset.onbfix }); } else if (b.dataset.onb === "open") { + if (ui.restarting?.kind === "onb") stopRestartOverlay(); $("onb")?.remove(); ui.onb = null; send("onbopen"); } else if (b.dataset.onb === "log") send("diagfolder"); else if (b.dataset.onb === "logout") send("onblogout"); - else if (b.dataset.onb === "restart") send("onbrestart"); + else if (b.dataset.onb === "restart") { startRestartOverlay("onb", "", tr("Restarting…")); send("onbrestart"); } } /* The first start: which language, before anything else: langStep @@ -4636,13 +4694,14 @@ function vmNetRow() { const v = ui.vmnet; if (!v || v.supported === false) return ""; const nat = v.shared_nat !== false; + const pending = v.awake && v.running_shared_nat != null && v.running_shared_nat !== nat; const desc = nat ? tr("macOS NAT: fastest. Switch to Host relay if Cloudflare WARP or a corporate firewall blocks container HTTPS. Applies on VM restart.") : tr("Host relay: connections leave from Kiri on macOS instead of Virtualization.framework NAT. Applies on VM restart."); const envNote = v.env ? ` ${tr("KIRI_SHARED_NAT is set in the environment and takes precedence.")}` : ""; return `
${tr("Outbound VM traffic")} ${desc}${envNote} -
`; +
${pending ? `` : ""}
`; } function networkPane() { @@ -4703,8 +4762,8 @@ function enginePane() { const { shown } = engineShown(), off = shown === "stopped"; const d = off ? tr("Off: press Start engine to run containers. It stays off after a restart until you start it.") : shown === "running" ? tr("Running: it rests by itself when nothing runs and wakes when you use it.") - : shown === "booting" ? tr("Starting…") : shown === "stopping" ? tr("Stopping…") : ""; - const busy = shown === "booting" || shown === "stopping"; + : shown === "booting" ? tr("Starting…") : shown === "stopping" ? tr("Stopping…") : shown === "restarting" ? tr("Restarting…") : ""; + const busy = shown === "booting" || shown === "stopping" || shown === "restarting"; const btn = off ? `` : ``; return `

${tr(VM)}

${vmLabels[shown] != null ? tr(vmLabels[shown]) : "—"}${d}${btn}
`; @@ -4893,7 +4952,7 @@ function storagePane() { const m = s.moving; const pct = m && m.total > 0 ? Math.min(100, Math.round((m.done / m.total) * 100)) : null; const progressBox = moving && m ? `
-
${stPhaseText(m.phase)}
+
${rspin("sm plain")}${stPhaseText(m.phase)}

${tr("Moving Kiri's data to {path}.", { path: `${esc(m.to || "")}` })}

${pct != null ? `

${size(m.done)} / ${size(m.total)} (${pct}%)

` : ""}

${tr("Running containers pause while Kiri copies its data and start again once it's done.")}

@@ -4961,6 +5020,7 @@ function storageConfirm(c) { if (ev.target.closest("[data-stgo]")) { const fresh = scrim.querySelector('input[name="st-mode"]:checked')?.value === "fresh"; ui.stErr = ""; + startRestartOverlay("storage", c.reset ? tr("Kiri will switch to this folder and restart the engine.") : tr("Moving Kiri's data to {path}.", { path: `${esc(c.path)}` }), tr("Stopping containers…")); if (c.reset) send("storagereset"); else send("storagemove", { path: c.path, value: { fresh } }); close(); @@ -7266,7 +7326,7 @@ function renderStatus() { const k8s = ui.containers.find((c) => c.Names?.[0] === "/kiri-k8s" && c.State === "running"); const k8sVersion = k8s ? (k8s.Image.split(":")[1] || "").replace(/-k3s\d+$/, "") : ""; const { shown: vshown } = engineShown(); - const vmText = { running: tr("{vm} running", { vm: tr(VM) }), stopped: tr("{vm} off", { vm: tr(VM) }), booting: tr("Starting…"), stopping: tr("Stopping…") }[vshown] || vshown; + const vmText = { running: tr("{vm} running", { vm: tr(VM) }), stopped: tr("{vm} off", { vm: tr(VM) }), booting: tr("Starting…"), stopping: tr("Stopping…"), restarting: tr("Restarting…") }[vshown] || vshown; const mem = ui.mem ? tr("{used} of {total}", { used: memText(ui.mem.used), total: `${Math.round(ui.mem.ceiling / 1024)} GB` }) : ""; const parts = [ `${KDOT}Kiri ${esc(ui.status?.version || "")}${ui.status?.dev ? `DEV` : ""}`, @@ -7333,7 +7393,7 @@ function aboutUpdate(version) { } else if (u?.phase === "ready") { row = `${tr("Kiri {version} is downloaded", { version: esc(u.version) })}${btn(tr("Restart to update"), 'data-upd="restart"', "primary")}`; } else if (u?.phase === "available") { - const whatsNew = u.notes.trim() || NOTES_URL.test(u.notesUrl) ? `` : ""; + const whatsNew = (u.notes || "").trim() || NOTES_URL.test(u.notesUrl) ? `` : ""; row = `${tr("Version {version}", { version: v })}${tr("{version} available", { version: esc(u.version) })}${btn(u.error ? tr("Try again") : tr("Download"), 'data-upd="download"', "primary")}${whatsNew}`; } else if (s?.state === "available") { row = `${tr("Version {version}", { version: v })}${tr("{version} available", { version: esc(s.latest) })}${btn(tr("Show"), "data-updcheck", "primary")}`; @@ -7346,7 +7406,7 @@ function aboutUpdate(version) { } else if (s?.state === "error") { row = `${tr("Version {version}", { version: v })}${tr("Couldn't check: {error}", { error: esc(s.error || "") })}${check}`; } else row = `${tr("Version {version}", { version: v })}${check}`; - const notes = u?.phase === "available" && u.notes.trim() ? `
${tr("What's new in {version}", { version: esc(u.version) })}${notesHtml(u.notes)}
` : ""; + const notes = u?.phase === "available" && (u.notes || "").trim() ? `
${tr("What's new in {version}", { version: esc(u.version) })}${notesHtml(u.notes)}
` : ""; const fixed = s?.state === "test" || s?.state === "dev"; const auto = prefs.updateAuto !== false; return `
${row}
${notes}${fixed ? "" : `
${tr("Check for updates automatically")}${auto ? tr("On: Kiri checks each time it opens. It never updates without asking.") : tr("Off: Kiri checks only when you click Check now.")} @@ -7362,8 +7422,8 @@ function renderUpdate() {
${UPD_ICON[ic]}

${esc(title)}

${sub}
${close ? `` : ""}
${body}
`; if (u && !u.hidden && u.phase === "available") { - const whatsNew = u.notes.trim() || NOTES_URL.test(u.notesUrl) ? ` · ` : ""; - const sub = `${tr("You have {version}", { version: esc(u.current) })}${whatsNew}${u.error ? `
${tr("Couldn't download it: {error}", { error: esc(u.error) })}
` : ""}`; + const whatsNew = (u.notes || "").trim() || NOTES_URL.test(u.notesUrl) ? ` · ` : ""; + const sub = `${tr("You have {version}", { version: esc(u.current || "") })}${whatsNew}${u.error ? `
${tr("Couldn't download it: {error}", { error: esc(u.error) })}
` : ""}`; el.innerHTML = card("up", tr("Kiri {version} is available", { version: u.version }), sub, "hide", `
${btn(u.error ? tr("Try again") : tr("Download"), 'data-upd="download"', "primary")} ${u.snoozing ? `${btn(tr("Tomorrow"), 'data-upd="snooze1"')}${btn(tr("In a week"), 'data-upd="snooze7"')}` : btn(tr("Snooze ▾"), 'data-upd="snooze" aria-haspopup="true"')} @@ -7388,9 +7448,9 @@ function updateAction(a) { case "snooze1": snooze(1); break; case "snooze7": snooze(7); break; case "skip": setPref("updateSkip", u.version); ui.upd = null; break; - case "notes": if (u.notes.trim()) openNotes(); else send("updatenotes", { name: u.notesUrl }); break; - case "restart": send("updaterestart"); break; - case "engine": send("restartengine"); ui.engineStale = null; break; + case "notes": if ((u?.notes || "").trim()) openNotes(); else send("updatenotes", { name: u?.notesUrl || "" }); break; + case "restart": startRestartOverlay("update", tr("Finish updating to Kiri {version}", { version: esc(u?.version || "") }), tr("Restarting…")); send("updaterestart"); break; + case "engine": startRestartOverlay("engine", tr("Finish updating to Kiri {version}", { version: esc(ui.status?.version || "") }), tr("Restarting engine…")); send("restartengine"); ui.engineStale = null; break; case "enginelater": ui.staleHidden = true; break; case "showengine": ui.staleHidden = false; break; } @@ -7553,6 +7613,10 @@ function render() { } function setVm(state, error) { + if (ui.restarting && ["vm", "engine", "reclaim"].includes(ui.restarting.kind)) { + if (state === "stopping") setRestartStep(tr("Stopping containers…")); + else if (state === "booting") setRestartStep(tr("Starting…")); + } if (ui.vm !== state) { const was = ui.vm; ui.vm = state; @@ -7576,6 +7640,7 @@ function setVm(state, error) { VM rests to save memory and the next docker command wakes it, so it reads Running, and waking does too. Off is only Stop (or no engine at all). */ function engineShown() { + if (ui.restarting && ui.restarting.kind !== "k8s") return { look: "restarting", on: false, shown: "restarting" }; const look = ui.vmLook || ui.vm; const shown = ui.vm === "stopped" ? "stopped" : ui.vm === "stopping" ? "stopping" @@ -7595,7 +7660,7 @@ function paintEngine() { const { shown } = engineShown(); document.body.dataset.vm = shown; const label = tr(vmLabels[shown] ?? shown); - /* i18n */ void [tr("Off"), tr("Starting…"), tr("Running"), tr("Stopping…")]; + /* i18n */ void [tr("Off"), tr("Starting…"), tr("Running"), tr("Stopping…"), tr("Restarting…")]; $("vm-state").textContent = label; const sub = $("vm-sub"); sub.textContent = ""; sub.hidden = true; @@ -7605,9 +7670,9 @@ function paintEngine() { /* When it last turned into a Stop button: see the press guard below. */ const act = shown === "running" ? "stop" : "start"; if (b.dataset.act !== act) { b.dataset.act = act; b.dataset.flipped = String(Date.now()); } - b.textContent = shown === "running" ? tr("Stop") : shown === "booting" ? tr("Starting…") : shown === "stopping" ? tr("Stopping…") : tr("Start"); - b.classList.toggle("primary", shown !== "running"); - b.disabled = shown === "booting" || shown === "stopping"; + b.textContent = shown === "running" ? tr("Stop") : shown === "booting" ? tr("Starting…") : shown === "stopping" ? tr("Stopping…") : shown === "restarting" ? tr("Restarting…") : tr("Start"); + b.classList.toggle("primary", shown !== "running" && shown !== "restarting"); + b.disabled = shown === "booting" || shown === "stopping" || shown === "restarting"; headTitles(); } /* The name or state says itself on hover only when it is cut. */ @@ -7739,7 +7804,7 @@ function toast(kind, text, op, open, act, why) { // Resources saved while the VM runs: restart it now to use them. if (!error && act === "restartvm") { el.querySelector(".txt").insertAdjacentHTML("beforeend", `
`); - el.querySelector("[data-trestart]").addEventListener("click", () => { el.remove(); send("restartvm"); }); + el.querySelector("[data-trestart]").addEventListener("click", () => { el.remove(); restartVm(); }); } $("toasts").append(el); retire(el, ms); @@ -8513,7 +8578,7 @@ function drawReport() { ${done ? `
${tr("Report ID")}${esc(rp.id)}
` : ""} ${rp.error ? `

${send_ ? tr("Couldn't send it: {error}", { error: esc(rp.error) }) : tr("Couldn't save it: {error}", { error: esc(rp.error) })}

` : ""}
${done ? `` - : ` `}
`; + : ` `}
`; } /* The card after a crash, in the update card's place (an update offer goes @@ -8683,6 +8748,7 @@ window.kiri = { if (e.kind === "search" && [...ui.pulls.values()].some((p) => p.kind === "notfound")) pullsChanged(); break; case "notice": + if (ui.restarting && (ui.restarting.kind === "vm" || (e.kind === "error" && ["storage", "engine", "update", "reclaim"].includes(ui.restarting.kind)))) stopRestartOverlay(); // Each pod a batch deletes says so; the batch's own toast already has. if (e.kind === "ok" && /^Deleting pod /.test(e.text) && ui.batches.some((b) => b.view === "pods" && b.phase === "going")) break; if (e.kind === "ok" && e.image && e.open) { ui.launched.set(e.image, e.open); runHold(e.image, e.text, e.open, e.ms); break; } @@ -8712,7 +8778,8 @@ window.kiri = { case "textsize": if (htHasFocus()) htStep(e.step); else stepTextSize(e.step); break; case "term": htOn(e); break; case "closekey": htCloseKey(); break; - case "enginerestarted": engineToast(e); break; + case "vmrestarted": if (ui.restarting?.kind === "vm") stopRestartOverlay(); break; + case "enginerestarted": if (ui.restarting?.kind === "engine") stopRestartOverlay(); if (!e.error) engineToast(e); break; case "view": if (empty[e.view] || e.view === "settings") show(e.view); break; case "prefs": { const was = prefs.lang; Object.assign(prefs, e.prefs || {}); prefsIn = true; if (prefs.lang !== was) relang(); applyPrefs(); render(); paintEngine(); renderStatus(); break; } case "starprompt": starCard(tr("Kiri started your container.")); break; @@ -8752,10 +8819,10 @@ window.kiri = { if (ui.upd.phase !== "downloading") Object.assign(ui.upd, { phase: "downloading", t0: Date.now(), g0: e.got }); Object.assign(ui.upd, { got: e.got, total: e.total }); renderUpdate(); break; case "updatestate": ui.updState = { ...e, checking: false }; if (ui.view === "settings" && prefs.tab === "about") render(); break; - case "updateready": if (ui.upd?.phase === "ready" && ui.upd.version === e.version && ui.upd.hidden) break; ui.upd = { ...(ui.upd || {}), phase: "ready", version: e.version, hidden: false, error: "" }; renderUpdate(); break; + case "updateready": if (ui.upd?.phase === "ready" && ui.upd.version === e.version && ui.upd.hidden) break; ui.upd = { notes: "", notesUrl: "", ...(ui.upd || {}), phase: "ready", version: e.version, hidden: false, error: "" }; renderUpdate(); break; case "updatecancelled": if (ui.upd) Object.assign(ui.upd, { phase: "available", hidden: true }); renderUpdate(); break; - case "updateerror": if (ui.upd) Object.assign(ui.upd, { phase: "available", hidden: false, error: e.error }); else toast("error", e.error); renderUpdate(); break; - case "enginestale": ui.engineStale = e.version; ui.staleHidden = false; renderUpdate(); break; + case "updateerror": if (ui.restarting?.kind === "update") stopRestartOverlay(); if (ui.upd) Object.assign(ui.upd, { phase: "available", hidden: false, error: e.error }); else toast("error", e.error); renderUpdate(); break; + case "enginestale": if (e.version && ui.restarting?.kind === "engine") stopRestartOverlay(); ui.engineStale = e.version; ui.staleHidden = false; renderUpdate(); break; case "tools": toolsBar(e); break; case "share": case "shares": case "shareaccount": case "sharelogin": case "shareusage": case "sharetunnels": case "sharetraffic": shEvent(e); break; case "builds": { @@ -8822,13 +8889,20 @@ window.kiri = { case "storage": { const wasUnavail = ui.storage?.state === "unavailable"; ui.storage = e; - if (e.state === "moving") ui.stErr = ""; + if (e.state === "moving") { + ui.stErr = ""; + const m = e.moving, pct = m && m.total > 0 ? Math.min(100, Math.round((m.done / m.total) * 100)) : null; + startRestartOverlay("storage", m?.to ? tr("Moving Kiri's data to {path}.", { path: `${esc(m.to)}` }) : tr("Kiri will switch to this folder and restart the engine."), stPhaseText(m?.phase), pct); + } else if (ui.restarting?.kind === "storage") { + stopRestartOverlay(); + } if (e.reclaimable > 0) ui.stReclaimed = null; if (ui.view === "settings" || e.state === "unavailable" || wasUnavail) render(); break; } case "storagereclaimed": ui.stReclaiming = false; + if (ui.restarting?.kind === "reclaim") stopRestartOverlay(); if (e.error) { toast("error", tr("Couldn't reclaim disk space: {error}", { error: e.error })); } else { @@ -8851,6 +8925,7 @@ window.kiri = { if (ui.view === "settings") render(); break; case "storagecheck": + if (ui.restarting?.kind === "storage") stopRestartOverlay(); if (e.error) { ui.stErr = e.error; if (ui.view === "settings") render(); else toast("error", e.error); } else { ui.stErr = ""; storageConfirm(e); } break; @@ -8957,7 +9032,7 @@ $("content").addEventListener("click", (ev) => { else if (t("[data-stpick]")) { ui.stErr = ""; send("storagepick"); } else if (t("[data-streclaim]")) { if (WIN) { - confirmRemove(tr("Compact WSL disk?"), tr("Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.", { vhdx: 'ext4.vhdx' }), tr("Compact disk"), () => { ui.stReclaiming = true; ui.stReclaimed = null; send("storagereclaim"); render(); }, "primary"); + confirmRemove(tr("Compact WSL disk?"), tr("Compacting {vhdx} returns unused space to Windows and briefly restarts Kiri's engine and running containers.", { vhdx: 'ext4.vhdx' }), tr("Compact disk"), () => { ui.stReclaiming = true; ui.stReclaimed = null; startRestartOverlay("reclaim", tr("Compacting {vhdx} and restarting the engine…", { vhdx: 'ext4.vhdx' }), tr("Restarting engine…")); send("storagereclaim"); render(); }, "primary"); } else { ui.stReclaiming = true; ui.stReclaimed = null; send("storagereclaim"); render(); } @@ -8967,7 +9042,7 @@ $("content").addEventListener("click", (ev) => { } else if (t("[data-streset]")) { if (ui.storage?.state === "unavailable") { - confirmRemove(tr("Reset storage location to default?"), tr("Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted."), tr("Reset to default"), () => send("storagereset"), "primary"); + confirmRemove(tr("Reset storage location to default?"), tr("Kiri will switch back to its default folder and restart the engine. Data on the disconnected drive isn't deleted."), tr("Reset to default"), () => { startRestartOverlay("storage", tr("Kiri will switch to this folder and restart the engine."), tr("Restarting engine…")); send("storagereset"); }, "primary"); } else { ui.stErr = ""; send("storagecheck", { path: "", value: { reset: true } }); @@ -9044,7 +9119,7 @@ $("content").addEventListener("click", (ev) => { if (cur && !!cur.on !== on) { cur.on = on; send("setresources", { value: { wsl_distro: name, on } }); render(); } } else if ((el = t("[data-vmpower]"))) { el.disabled = true; powerEngine(el.dataset.vmpower); } - else if ((el = t("[data-restartvm]"))) { el.disabled = true; el.textContent = tr("Restarting…"); send("restartvm"); } + else if ((el = t("[data-restartvm]"))) { el.disabled = true; el.textContent = tr("Restarting…"); restartVm(); } else if ((el = t("[data-detail]"))) openDetail(el.dataset.detail); else if (t("[data-ctrcompose]")) show("compose"); else if ((el = t("[data-img]"))) openImage(el.dataset.img); @@ -9250,9 +9325,11 @@ function k8sOn(e) { case "k8sop": if (e.state === "progress") { k8s.opLine = e.line.endsWith("…") || e.line.endsWith(".") || e.line.endsWith(")") ? e.line : `${e.line}…`; + if (ui.restarting?.kind === "k8s") setRestartStep(k8s.opLine); if (k8sShown()) { const el = $("k8s-step"); if (el) el.textContent = k8s.opLine; else render(); } break; } + if (ui.restarting?.kind === "k8s") stopRestartOverlay(); k8s.op = ""; k8s.opLine = ""; k8s.opAt = 0; k8s.sanDraft = null; k8s.portDraft = null; k8s.argsDraft = null; if (e.port) k8s.port = e.port; if (e.want_port) k8s.wantPort = e.want_port; @@ -9279,6 +9356,9 @@ function k8sOn(e) { function k8sDo(op, value) { if (k8s.op) return; Object.assign(k8s, { op, opAt: Date.now(), opLine: op === "start" ? tr("Starting Kubernetes…") : tr(OP_WORDS[op]) }); + if (op === "set" && (k8sNode()?.State === "running" || k8s.state === "running")) { + startRestartOverlay("k8s", esc(tr("Kiri's Kubernetes cluster")), tr("Restarting…")); + } send("k8s", { action: op, value }); k8sSide(); render(); diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rs index bd38f78..55ba204 100644 --- a/crates/kiri/src/ui/mod.rs +++ b/crates/kiri/src/ui/mod.rs @@ -999,20 +999,18 @@ fn builder_settings(save: Option) { #[cfg(target_os = "macos")] fn vm_net(save: Option) { - if let Some(body) = save { - if let Some(enabled) = body["shared_nat"].as_bool() { - match crate::vm_cli::set_shared_nat(enabled) { - Ok(()) => emit(notice("ok", &tr("Outbound VM traffic setting saved. Restart the VM to apply."))), - Err(e) => emit(notice("error", &trf("Could not save VM networking setting: {error}", &[("error", &e)]))), - } - } - } + let saved = save.and_then(|body| body["shared_nat"].as_bool().map(crate::vm_cli::set_shared_nat)); let configured = crate::daemon::engine::vm_shared_nat_config(); let env_override = crate::daemon::engine::shared_nat_env(); let effective = env_override.or(configured).unwrap_or(true); let info = client::get_background("/info").ok(); let awake = info.as_ref().is_some_and(|i| i["KiriVmAwake"] == true); let running_shared_nat = awake.then(|| info.as_ref().and_then(|i| i["KiriVmUplink"]["mode"].as_str()).is_none_or(|m| m != "host-egress")); + match saved { + Some(Ok(())) => emit(serde_json::json!({"type": "notice", "kind": "ok", "text": tr("Outbound VM traffic setting saved. Restart the VM to apply."), "act": if awake { "restartvm" } else { "" }}).to_string()), + Some(Err(e)) => emit(notice("error", &trf("Could not save VM networking setting: {error}", &[("error", &e)]))), + None => {} + } emit( serde_json::json!({ "type": "vmnet", @@ -1178,6 +1176,7 @@ fn restart_engine_now() { } Err(e) => { diag::error!("the engine did not restart", error = e); + emit(serde_json::json!({"type": "enginerestarted", "error": e.to_string()}).to_string()); emit(notice("error", &trf("Could not restart the engine: {error}", &[("error", &e)]))); if let Some(v) = client::request("GET", "/version", None).ok().filter(|r| r.ok()).and_then(|r| client::kiri_version(&r.json()).map(str::to_owned)) && update::newer(env!("CARGO_PKG_VERSION"), &v) @@ -2706,14 +2705,22 @@ fn handle(text: &str, tx: &Sender, autostart: bool, view: Option<&str>) { Ok(()) } "restartvm" => { - std::thread::spawn(|| { + let tx = tx.clone(); + std::thread::spawn(move || { let _op = diag::enter_op(diag::new_op("restartvm")); - let result = expect_ok(client::request("POST", "/kiri/sleep", None)).and_then(|()| expect_ok(client::request("POST", "/kiri/wake", None))); + emit(state("stopping", None)); + let result = expect_ok(client::request("POST", "/kiri/sleep", None)).and_then(|()| { + emit(state("booting", None)); + expect_ok(client::request("POST", "/kiri/wake", None)) + }); + emit(serde_json::json!({"type": "vmrestarted", "ok": result.is_ok()}).to_string()); match result { Ok(()) => emit(notice("ok", &tr("The Linux VM restarted with the new resources"))), Err(e) => emit(notice("error", &trf("Could not restart the VM: {error}", &[("error", &e)]))), } resources(None); + vm_net(None); + let _ = tx.send(Cmd::Refresh); }); Ok(()) } diff --git a/tests/ui/restartnow.js b/tests/ui/restartnow.js index f22688e..d4cbd88 100644 --- a/tests/ui/restartnow.js +++ b/tests/ui/restartnow.js @@ -1,16 +1,136 @@ -// Resources saved while the VM runs: the toast's Restart now restarts it. +// Every restart trigger opens the universal Restarting… overlay (#rscrim) with +// the shared .rspin spinner, syncs the VM card and status bar, and clears when +// the restart completes or fails. const R = []; const t = (name, fn) => { try { fn(); R.push("PASS " + name); } catch (e) { R.push("FAIL " + name + ": " + e.message); } }; -kiri.on({ type: "notice", kind: "ok", text: "Saved. The VM uses these from its next start", act: "restartvm" }); -t("the toast has Restart now", () => { +const eq = (a, b, m) => { if (JSON.stringify(a) !== JSON.stringify(b)) throw new Error(m + ": got " + JSON.stringify(a) + " want " + JSON.stringify(b)); }; + +kiri.on({ type: "status", version: "0.2.3", dev: false, share: true, app: "Kiri", ours: "kiri", context: "kiri" }); +kiri.on({ type: "state", state: "running" }); + +t("toast Restart now opens universal Restarting overlay with .rspin and syncs VM card + status bar", () => { + kiri.on({ type: "notice", kind: "ok", text: "Saved. The VM uses these from its next start", act: "restartvm" }); const b = document.querySelector("#toasts [data-trestart]"); if (!b) throw new Error("no link"); b.click(); if (!sent.some((m) => m.type === "restartvm")) throw new Error("sent " + sent.map((m) => m.type).join(",")); if (document.querySelector("#toasts [data-trestart]")) throw new Error("toast stayed"); + const scrim = document.getElementById("rscrim"); + if (!scrim || scrim.hidden) throw new Error("Restarting overlay did not open"); + if (!scrim.querySelector(".rspin")) throw new Error("missing .rspin spinner"); + eq(scrim.querySelector("h3")?.textContent.trim(), "Restarting…", "overlay heading"); + eq(document.body.dataset.vm, "restarting", "body data-vm"); + eq(document.getElementById("vm-state")?.textContent.trim(), "Restarting…", "sidebar VM state"); + if (!document.querySelector("#statusbar .dot.restarting")) throw new Error("status bar missing restarting dot"); + + // Live step updates as VM stops and starts + kiri.on({ type: "state", state: "booting" }); + eq(scrim.querySelector(".rstep span")?.textContent.trim(), "Starting…", "step updated on booting"); + + // Completion clears overlay and restores running state + kiri.on({ type: "state", state: "running" }); + kiri.on({ type: "vmrestarted", ok: true }); + if (!scrim.hidden) throw new Error("overlay stayed after vmrestarted"); + eq(document.body.dataset.vm, "running", "restored to running"); }); -kiri.on({ type: "notice", kind: "ok", text: "Saved. The VM uses these from its next start", act: "" }); -t("no link while the VM is asleep", () => { + +t("no Restart now link while the VM is asleep", () => { + kiri.on({ type: "notice", kind: "ok", text: "Saved. The VM uses these from its next start", act: "" }); if (document.querySelector("#toasts [data-trestart]")) throw new Error("link shown"); }); + +t("Resources Restart VM to apply and Network Restart VM to apply open Restarting overlay", () => { + kiri.on({ + type: "resources", cpus: 4, memory_mib: 11264, disk_gb: 160, + running_cpus: 2, running_memory_mib: 12288, running_disk_gb: 160, + awake: true, max_cpus: 12, max_memory_mib: 32768, min_disk_gb: 64, max_disk_gb: 1024, overridden: false, + }); + prefs.tab = "resources"; + show("settings"); + const resBtn = document.getElementById("res-restart"); + if (!resBtn) throw new Error("missing #res-restart"); + sent.length = 0; + resBtn.click(); + if (!sent.some((m) => m.type === "restartvm")) throw new Error("did not send restartvm"); + if (document.getElementById("rscrim").hidden) throw new Error("overlay not shown for #res-restart"); + kiri.on({ type: "vmrestarted", ok: true }); + if (!document.getElementById("rscrim").hidden) throw new Error("overlay did not close"); + + prefs.tab = "network"; + show("settings"); + kiri.on({ type: "proxy", settings: { mode: "system", containers: false }, effective: { http: null, https: null, no_proxy: [], pac: false } }); + kiri.on({ type: "vmnet", supported: true, shared_nat: false, env: false, awake: true, running_shared_nat: true }); + const netRestart = document.querySelector(".settings .pane [data-restartvm]"); + if (!netRestart) throw new Error("missing Restart VM to apply in Network when pending"); + netRestart.click(); + if (document.getElementById("rscrim").hidden) throw new Error("overlay not shown from Network restart"); + kiri.on({ type: "vmrestarted", ok: false }); + if (!document.getElementById("rscrim").hidden) throw new Error("overlay did not close on failed vmrestarted"); +}); + +t("Update Restart now and Stale engine Restart engine open Restarting overlay", () => { + kiri.on({ type: "updateready", version: "0.2.4" }); + const updBtn = document.querySelector('#updcard [data-upd="restart"]'); + if (!updBtn) throw new Error("missing update restart button"); + updBtn.click(); + if (document.getElementById("rscrim").hidden || !document.querySelector("#rscrim .rspin")) throw new Error("overlay missing on updaterestart"); + kiri.on({ type: "updateerror", error: "staged bundle missing" }); + if (!document.getElementById("rscrim").hidden) throw new Error("overlay stayed after updateerror"); + + ui.upd = null; + kiri.on({ type: "enginestale", version: "0.2.2" }); + const engBtn = document.querySelector('#updcard [data-upd="engine"]'); + if (!engBtn) throw new Error("missing stale engine restart button"); + engBtn.click(); + if (document.getElementById("rscrim").hidden || !document.querySelector("#rscrim .rspin")) throw new Error("overlay missing on restartengine"); + kiri.on({ type: "enginerestarted", version: "0.2.3", ms: 420 }); + if (!document.getElementById("rscrim").hidden) throw new Error("overlay stayed after enginerestarted"); +}); + +t("Storage move shows Restarting overlay with progress bar and .rspin in pane", () => { + prefs.tab = "storage"; + show("settings"); + kiri.on({ + type: "storage", + path: "/Users/me/Library/Application Support/Kiri", + default: "/Users/me/Library/Application Support/Kiri", + custom: false, env: false, state: "moving", + used: null, free: 120_000_000_000, fs: "apfs", + moving: { to: "/Volumes/SSD/kiri", phase: "restarting", done: 3_000_000_000, total: 4_000_000_000 }, + error: null, old: null, + }); + const scrim = document.getElementById("rscrim"); + if (scrim.hidden || !scrim.querySelector(".rspin")) throw new Error("storage moving did not show Restarting overlay"); + eq(scrim.querySelector(".rstep span")?.textContent.trim(), "Restarting engine…", "storage phase step"); + eq(scrim.querySelector(".rbar span")?.style.width, "75%", "storage progress bar"); + if (!document.querySelector(".settings .st-box .rspin")) throw new Error("storage pane box missing .rspin"); + + kiri.on({ + type: "storage", + path: "/Volumes/SSD/kiri", + default: "/Users/me/Library/Application Support/Kiri", + custom: true, env: false, state: "ok", + used: 4_000_000_000, free: 300_000_000_000, fs: "apfs", + moving: null, error: null, old: null, + }); + if (!scrim.hidden) throw new Error("storage overlay stayed after state=ok"); +}); + +t("Kubernetes set while running opens Restarting overlay and streams progress", () => { + ui.containers = [{ Id: "k8s1", Names: ["/kiri-k8s"], Image: "rancher/k3s:v1.37.1-k3s1", State: "running", Ports: [], Labels: { "dev.kiri.k8s": "1" } }]; + kiri.on({ + type: "k8s", state: "running", ready: true, context: "kiri", port: 6443, want_port: 6443, + config: { lan: false, tls_san: [] }, pods: [], services: [], + }); + prefs.tab = "kubernetes"; + show("settings"); + document.querySelector('[data-k8slan="1"]').click(); + const scrim = document.getElementById("rscrim"); + if (scrim.hidden || !scrim.querySelector(".rspin")) throw new Error("k8s restart did not open Restarting overlay"); + kiri.on({ type: "k8sop", op: "set", state: "progress", line: "Waiting for the API server" }); + eq(scrim.querySelector(".rstep span")?.textContent.trim(), "Waiting for the API server…", "k8s progress line"); + kiri.on({ type: "k8sop", op: "set", state: "done", context: "kiri", port: 6443, want_port: 6443 }); + if (!scrim.hidden) throw new Error("k8s overlay stayed after k8sop done"); +}); + report(R);