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.
This commit is contained in:
@@ -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({
|
||||
) : (
|
||||
<p className="muted">Loading…</p>
|
||||
)}
|
||||
<p className="muted">
|
||||
Update from the container with <code>shellbook-update</code>.
|
||||
</p>
|
||||
</section>
|
||||
<UpdatePanel />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<typeof settingsApi, "updateStatus" | "checkUpdate" | "startUpdate">;
|
||||
|
||||
/** 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<UpdateStatusResponse | "error">();
|
||||
const [check, setCheck] = useState<UpdateCheckResponse | "checking" | "error">();
|
||||
const [watch, setWatch] = useState<Watch>();
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const logRef = useRef<HTMLPreElement>(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 (
|
||||
<section className="card">
|
||||
<h2>Updates</h2>
|
||||
<p className="muted">Loading…</p>
|
||||
</section>
|
||||
);
|
||||
if (status === "error")
|
||||
return (
|
||||
<section className="card">
|
||||
<h2>Updates</h2>
|
||||
<p className="error">Unable to load the update status.</p>
|
||||
</section>
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="card update-panel" aria-label="Updates">
|
||||
<h2>Updates</h2>
|
||||
<dl className="facts">
|
||||
<dt>Installed</dt>
|
||||
<dd>{status.current ? <code>{status.current}</code> : "unknown (not a git checkout)"}</dd>
|
||||
{status.available && status.startedAt && !following && (
|
||||
<>
|
||||
<dt>Last update</dt>
|
||||
<dd>
|
||||
{status.state === "failed" ? "failed" : status.state === "succeeded" ? "succeeded" : status.state},{" "}
|
||||
{when(status.finishedAt ?? status.startedAt)}
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
{!status.available ? (
|
||||
<p className="muted">
|
||||
Updating from the web UI is not set up on this installation. Run <code>shellbook-update</code> as root in the
|
||||
container (from the Proxmox host: <code>pct exec <ctid> -- shellbook-update</code>); that run also
|
||||
adds the button here.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
{watch && (
|
||||
<p role="status" className={`banner${watch.phase === "failed" || watch.phase === "stalled" ? " error" : ""}`}>
|
||||
{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.
|
||||
<button className="primary" onClick={() => location.reload()}>
|
||||
Reload
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{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."}
|
||||
</p>
|
||||
)}
|
||||
{error && <p className="banner error">{error}</p>}
|
||||
{check === "error" && <p className="error">Unable to reach the repository.</p>}
|
||||
{check && check !== "checking" && check !== "error" && (
|
||||
check.pinned ? (
|
||||
<p className="muted">This installation is pinned to a fixed version and is not updated from the branch.</p>
|
||||
) : check.changes.length === 0 ? (
|
||||
<p className="ok">Up to date{check.latest ? ` (${check.latest})` : ""}.</p>
|
||||
) : (
|
||||
<div>
|
||||
<p>
|
||||
{check.changes.length === 1 ? "1 new change" : `${check.changes.length} new changes`} (
|
||||
<code>{check.current}</code> → <code>{check.latest}</code>):
|
||||
</p>
|
||||
<ul className="changes">
|
||||
{check.changes.map((change) => (
|
||||
<li key={change.commit}>
|
||||
<code>{change.commit}</code> {change.subject}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
<div className="actions">
|
||||
<button
|
||||
disabled={following || check === "checking"}
|
||||
onClick={() => {
|
||||
setCheck("checking");
|
||||
api.checkUpdate().then(setCheck, () => setCheck("error"));
|
||||
}}
|
||||
>
|
||||
{check === "checking" ? "Checking…" : "Check for updates"}
|
||||
</button>
|
||||
<button className="primary" disabled={following} onClick={() => setConfirming(true)}>
|
||||
Update now
|
||||
</button>
|
||||
</div>
|
||||
{status.log && (following || watch?.phase === "failed" || watch?.phase === "done" || !watch) && (
|
||||
<details open={following || watch?.phase === "failed"}>
|
||||
<summary>{following ? "Update output" : "Output of the last update"}</summary>
|
||||
<pre ref={logRef} className="update-log">
|
||||
{status.log}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{confirming && (
|
||||
<Dialog title="Update ShellBook?" onClose={() => setConfirming(false)}>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<div className="dialog-actions">
|
||||
<button onClick={() => setConfirming(false)}>Cancel</button>
|
||||
<button className="primary" onClick={() => void start()}>
|
||||
Update now
|
||||
</button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import type {
|
||||
SessionSettingsResponse,
|
||||
ClaudeStatusResponse,
|
||||
SystemInfoResponse,
|
||||
UpdateCheckResponse,
|
||||
UpdateStartResponse,
|
||||
UpdateStatusResponse,
|
||||
} from "@shellbook/core";
|
||||
import { HttpError } from "./api";
|
||||
async function request<T>(path: string, body?: unknown): Promise<T> {
|
||||
@@ -29,4 +32,7 @@ export const settingsApi = {
|
||||
session: () => request<SessionSettingsResponse>("/settings/session"),
|
||||
claude: () => request<ClaudeStatusResponse>("/settings/claude"),
|
||||
system: () => request<SystemInfoResponse>("/settings/system"),
|
||||
updateStatus: () => request<UpdateStatusResponse>("/settings/update"),
|
||||
checkUpdate: () => request<UpdateCheckResponse>("/settings/update/check", {}),
|
||||
startUpdate: () => request<UpdateStartResponse>("/settings/update", {}),
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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(<SettingsPage openTerminal={open} />);
|
||||
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"));
|
||||
|
||||
@@ -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(<UpdatePanel api={api} />);
|
||||
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(<UpdatePanel api={api} />);
|
||||
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(<UpdatePanel api={api} pollMs={5} />);
|
||||
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(<UpdatePanel api={api} pollMs={5} />);
|
||||
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(<UpdatePanel api={api} pollMs={5} />);
|
||||
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();
|
||||
});
|
||||
Reference in New Issue
Block a user