From 2025185489314d2a0ca182049f4ed395a44fe6e0 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Mon, 16 Nov 2026 15:31:01 +0100 Subject: [PATCH] feat(web): update button in Settings (#15) Shows the installed commit, checks for new commits, starts the update after a confirmation and follows its output through the service restart. --- apps/web/src/SettingsPage.tsx | 5 +- apps/web/src/UpdatePanel.tsx | 209 +++++++++++++++++++++++++++ apps/web/src/settingsApi.ts | 6 + apps/web/src/style.css | 32 ++++ apps/web/src/tests/settings.test.tsx | 9 ++ apps/web/src/tests/update.test.tsx | 115 +++++++++++++++ 6 files changed, 373 insertions(+), 3 deletions(-) create mode 100644 apps/web/src/UpdatePanel.tsx create mode 100644 apps/web/src/tests/update.test.tsx diff --git a/apps/web/src/SettingsPage.tsx b/apps/web/src/SettingsPage.tsx index 47148ec..04a4e03 100644 --- a/apps/web/src/SettingsPage.tsx +++ b/apps/web/src/SettingsPage.tsx @@ -6,6 +6,7 @@ import type { } from "@shellbook/core"; import { settingsApi } from "./settingsApi"; import { PasswordForm } from "./PasswordForm"; +import { UpdatePanel } from "./UpdatePanel"; function duration(seconds: number): string { const days = seconds / 86400; @@ -150,10 +151,8 @@ export function SettingsPage({ ) : (

Loading…

)} -

- Update from the container with shellbook-update. -

+ ); } diff --git a/apps/web/src/UpdatePanel.tsx b/apps/web/src/UpdatePanel.tsx new file mode 100644 index 0000000..74d537a --- /dev/null +++ b/apps/web/src/UpdatePanel.tsx @@ -0,0 +1,209 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import type { UpdateCheckResponse, UpdateStatusResponse } from "@shellbook/core"; +import { settingsApi } from "./settingsApi"; +import { Dialog } from "./ui"; + +type UpdateApi = Pick; + +/** How long a requested update may take to show up in systemd before we say so. */ +const START_TIMEOUT_MS = 30_000; +/** systemd timestamps have second resolution; allow for that and small clock steps. */ +const START_SLACK_MS = 5_000; + +type Watch = + | { phase: "starting" | "running" | "restarting"; since: number } + | { phase: "done" | "failed" | "stalled" }; + +const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString() : ""); + +/** + * Settings card that starts ShellBook's own update. The server only requests it; systemd + * runs the updater as root and restarts the service, so this card keeps polling through + * the restart and then offers a reload for the new web app. + */ +export function UpdatePanel({ api = settingsApi, pollMs = 2000 }: { api?: UpdateApi; pollMs?: number }) { + const [status, setStatus] = useState(); + const [check, setCheck] = useState(); + const [watch, setWatch] = useState(); + const [confirming, setConfirming] = useState(false); + const [error, setError] = useState(""); + const logRef = useRef(null); + + // Initial load; an update already running (e.g. after a reload) is followed as well. + useEffect(() => { + let active = true; + api.updateStatus().then( + (next) => { + if (!active) return; + setStatus(next); + if (next.state === "running") setWatch({ phase: "running", since: Date.parse(next.startedAt ?? "") || Date.now() }); + }, + () => active && setStatus("error"), + ); + return () => { + active = false; + }; + }, [api]); + + const following = watch && (watch.phase === "starting" || watch.phase === "running" || watch.phase === "restarting"); + const since = watch && "since" in watch ? watch.since : 0; + const poll = useCallback(async () => { + let next: UpdateStatusResponse; + try { + next = await api.updateStatus(); + } catch { + // The update restarts ShellBook; the API is gone for a moment. + setWatch((current) => (current && "since" in current ? { ...current, phase: "restarting" } : current)); + return; + } + setStatus(next); + const started = next.startedAt !== null && Date.parse(next.startedAt) >= since - START_SLACK_MS; + if (next.state === "running") setWatch({ phase: "running", since }); + else if (!started) + setWatch(Date.now() - since > START_TIMEOUT_MS ? { phase: "stalled" } : { phase: "starting", since }); + else setWatch({ phase: next.state === "succeeded" ? "done" : "failed" }); + }, [api, since]); + useEffect(() => { + if (!following) return; + const timer = setInterval(() => void poll(), pollMs); + return () => clearInterval(timer); + }, [following, poll, pollMs]); + + // Keep the newest log lines in view while an update runs. + const log = status && status !== "error" ? status.log : ""; + useEffect(() => { + if (following && logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; + }, [log, following]); + + const start = async () => { + setConfirming(false); + setError(""); + try { + const { requestedAt } = await api.startUpdate(); + setWatch({ phase: "starting", since: Date.parse(requestedAt) }); + } catch { + setError("Unable to start the update. It may already be running; reload this page."); + } + }; + + if (status === undefined) + return ( +
+

Updates

+

Loading…

+
+ ); + if (status === "error") + return ( +
+

Updates

+

Unable to load the update status.

+
+ ); + + return ( +
+

Updates

+
+
Installed
+
{status.current ? {status.current} : "unknown (not a git checkout)"}
+ {status.available && status.startedAt && !following && ( + <> +
Last update
+
+ {status.state === "failed" ? "failed" : status.state === "succeeded" ? "succeeded" : status.state},{" "} + {when(status.finishedAt ?? status.startedAt)} +
+ + )} +
+ {!status.available ? ( +

+ Updating from the web UI is not set up on this installation. Run shellbook-update as root in the + container (from the Proxmox host: pct exec <ctid> -- shellbook-update); that run also + adds the button here. +

+ ) : ( + <> + {watch && ( +

+ {watch.phase === "starting" && "Starting the update…"} + {watch.phase === "running" && "Updating… This takes a few minutes; ShellBook restarts at the end."} + {watch.phase === "restarting" && "ShellBook is restarting…"} + {watch.phase === "done" && ( + <> + Update finished{status.current ? ` (${status.current})` : ""}. Reload to use the new version. + + + )} + {watch.phase === "failed" && "The update failed. The log below shows why."} + {watch.phase === "stalled" && + "The update did not start. Check systemctl status shellbook-update.path in the container."} +

+ )} + {error &&

{error}

} + {check === "error" &&

Unable to reach the repository.

} + {check && check !== "checking" && check !== "error" && ( + check.pinned ? ( +

This installation is pinned to a fixed version and is not updated from the branch.

+ ) : check.changes.length === 0 ? ( +

Up to date{check.latest ? ` (${check.latest})` : ""}.

+ ) : ( +
+

+ {check.changes.length === 1 ? "1 new change" : `${check.changes.length} new changes`} ( + {check.current} → {check.latest}): +

+
    + {check.changes.map((change) => ( +
  • + {change.commit} {change.subject} +
  • + ))} +
+
+ ) + )} +
+ + +
+ {status.log && (following || watch?.phase === "failed" || watch?.phase === "done" || !watch) && ( +
+ {following ? "Update output" : "Output of the last update"} +
+                {status.log}
+              
+
+ )} + + )} + {confirming && ( + setConfirming(false)}> +

+ Downloads the installer from the repository, pulls the newest version, rebuilds and restarts ShellBook. Running + steps are interrupted by the restart; terminal sessions keep running. +

+
+ + +
+
+ )} +
+ ); +} diff --git a/apps/web/src/settingsApi.ts b/apps/web/src/settingsApi.ts index 21ec87c..ec3bb07 100644 --- a/apps/web/src/settingsApi.ts +++ b/apps/web/src/settingsApi.ts @@ -5,6 +5,9 @@ import type { SessionSettingsResponse, ClaudeStatusResponse, SystemInfoResponse, + UpdateCheckResponse, + UpdateStartResponse, + UpdateStatusResponse, } from "@shellbook/core"; import { HttpError } from "./api"; async function request(path: string, body?: unknown): Promise { @@ -29,4 +32,7 @@ export const settingsApi = { session: () => request("/settings/session"), claude: () => request("/settings/claude"), system: () => request("/settings/system"), + updateStatus: () => request("/settings/update"), + checkUpdate: () => request("/settings/update/check", {}), + startUpdate: () => request("/settings/update", {}), }; diff --git a/apps/web/src/style.css b/apps/web/src/style.css index 9d0fae9..0bf63c7 100644 --- a/apps/web/src/style.css +++ b/apps/web/src/style.css @@ -971,6 +971,38 @@ pre.script { color: var(--danger); } +.update-panel .changes { + margin: 0 0 12px; + padding-left: 18px; + max-height: 240px; + overflow: auto; +} +.update-panel .changes code { + color: var(--muted); +} +.update-panel details { + margin-top: 12px; +} +.update-panel summary { + cursor: pointer; + color: var(--muted); +} +pre.update-log { + background: var(--code); + margin: 8px 0 0; + padding: 12px 14px; + max-height: 320px; + overflow: auto; + border-radius: 6px; + font: + 12.5px/1.6 "Cascadia Code", + Consolas, + monospace; + white-space: pre-wrap; + overflow-wrap: anywhere; + user-select: text; +} + /* Sign-in */ .login { max-width: 360px; diff --git a/apps/web/src/tests/settings.test.tsx b/apps/web/src/tests/settings.test.tsx index c1ebf73..7daaa25 100644 --- a/apps/web/src/tests/settings.test.tsx +++ b/apps/web/src/tests/settings.test.tsx @@ -67,10 +67,19 @@ it("renders system/session/Claude information and opens the terminal", async () version: "Claude 1", loginAppearsPresent: true, }); + vi.spyOn(settingsApi, "updateStatus").mockResolvedValue({ + available: true, + state: "idle", + current: "abc1234", + startedAt: null, + finishedAt: null, + log: "", + }); const revoke = vi.spyOn(settingsApi, "revoke").mockResolvedValue(); const open = vi.fn(); render(); expect(await screen.findByText("/workspace")).toBeInTheDocument(); + expect(await screen.findByRole("button", { name: "Update now" })).toBeInTheDocument(); expect(screen.getByText(/86400 seconds/)).toBeInTheDocument(); expect(screen.getByText("Available: Claude 1")).toBeInTheDocument(); fireEvent.click(screen.getByText("Open terminal to log in")); diff --git a/apps/web/src/tests/update.test.tsx b/apps/web/src/tests/update.test.tsx new file mode 100644 index 0000000..e6bca68 --- /dev/null +++ b/apps/web/src/tests/update.test.tsx @@ -0,0 +1,115 @@ +import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { expect, it, vi } from "vitest"; +import type { UpdateStatusResponse } from "@shellbook/core"; +import { UpdatePanel } from "../UpdatePanel"; + +const idle: UpdateStatusResponse = { + available: true, + state: "idle", + current: "abc1234", + startedAt: null, + finishedAt: null, + log: "", +}; + +function fakeApi(statuses: (UpdateStatusResponse | Error)[]) { + let index = 0; + return { + // Returns the statuses in order and then keeps returning the last one. + updateStatus: vi.fn(async () => { + const next = statuses[Math.min(index++, statuses.length - 1)]!; + if (next instanceof Error) throw next; + return next; + }), + checkUpdate: vi.fn(), + startUpdate: vi.fn(), + }; +} + +it("explains the manual update when the trigger is not installed", async () => { + const api = fakeApi([{ ...idle, available: false }]); + render(); + expect(await screen.findByText("abc1234")).toBeInTheDocument(); + expect(screen.getByText(/not set up on this installation/)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Update now" })).toBeNull(); +}); + +it("lists the commits an update would bring, or says it is up to date", async () => { + const api = fakeApi([idle]); + api.checkUpdate + .mockResolvedValueOnce({ + current: "abc1234", + latest: "def5678", + pinned: false, + changes: [ + { commit: "def5678", subject: "feat(web): newer" }, + { commit: "bbb0000", subject: "fix: older" }, + ], + }) + .mockResolvedValueOnce({ current: "def5678", latest: "def5678", pinned: false, changes: [] }) + .mockResolvedValueOnce({ current: "abc1234", latest: null, pinned: true, changes: [] }) + .mockRejectedValueOnce(new Error("502")); + render(); + const check = await screen.findByRole("button", { name: "Check for updates" }); + fireEvent.click(check); + expect(await screen.findByText(/2 new changes/)).toBeInTheDocument(); + expect(screen.getByText("feat(web): newer")).toBeInTheDocument(); + fireEvent.click(check); + expect(await screen.findByText("Up to date (def5678).")).toBeInTheDocument(); + fireEvent.click(check); + expect(await screen.findByText(/pinned to a fixed version/)).toBeInTheDocument(); + fireEvent.click(check); + expect(await screen.findByText("Unable to reach the repository.")).toBeInTheDocument(); +}); + +it("asks first, then follows the update through the restart and offers a reload", async () => { + const requestedAt = new Date().toISOString(); + const startedAt = new Date(Date.parse(requestedAt) + 1000).toISOString(); + const api = fakeApi([ + idle, + { ...idle, state: "running", startedAt, log: "Pulling…\nBuilding…" }, + new Error("502"), + { ...idle, state: "succeeded", current: "def5678", startedAt, finishedAt: startedAt, log: "Done" }, + ]); + api.startUpdate.mockResolvedValue({ requestedAt }); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Update now" })); + // Nothing starts before the confirmation. + const dialog = screen.getByRole("dialog", { name: "Update ShellBook?" }); + expect(api.startUpdate).not.toHaveBeenCalled(); + fireEvent.click(within(dialog).getByRole("button", { name: "Update now" })); + await waitFor(() => expect(api.startUpdate).toHaveBeenCalledOnce()); + expect(await screen.findByText(/Building…/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Update now" })).toBeDisabled(); + await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Update finished (def5678)")); + expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument(); + // The restart in between was shown instead of an error. + expect(screen.queryByText(/Unable to load/)).toBeNull(); +}); + +it("does not mistake the previous run for the requested one", async () => { + const requestedAt = new Date().toISOString(); + const old = new Date(Date.parse(requestedAt) - 3_600_000).toISOString(); + const api = fakeApi([{ ...idle, state: "succeeded", startedAt: old, finishedAt: old, log: "old run" }]); + api.startUpdate.mockResolvedValue({ requestedAt }); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Update now" })); + fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update now" })); + await waitFor(() => expect(api.updateStatus.mock.calls.length).toBeGreaterThan(3)); + expect(screen.getByRole("status")).toHaveTextContent("Starting the update…"); +}); + +it("shows a failed update with its log", async () => { + const requestedAt = new Date().toISOString(); + const api = fakeApi([ + idle, + { ...idle, state: "failed", startedAt: requestedAt, finishedAt: requestedAt, log: "pnpm: build failed" }, + ]); + api.startUpdate.mockResolvedValue({ requestedAt }); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Update now" })); + fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update now" })); + await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("The update failed")); + expect(screen.getByText("pnpm: build failed")).toBeVisible(); + expect(screen.getByRole("button", { name: "Update now" })).toBeEnabled(); +});