From 4f5522a7e66ec8f8264545596599dba229780d59 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 6 Nov 2026 11:52:49 -0500 Subject: [PATCH 1/2] Settings, System: one press of Update does the whole job Pressing Update while the release check ran showed a red error toast, a version read from before a press brought the Update button back, a double click could send two requests, and a newer release could take over the card as a second Update button while one ran. Now a press shows progress at once and can't be repeated; a press recorded while the check runs shows Checking with who pressed it; a read older than the press shows Starting until the updater shows the update; a newer release is only mentioned while one runs and offered once it ends. Error toasts are kept for real failures and say what to do; 409 states show in the card. Polling no longer drops unsaved settings, an old release list no longer reads as up to date, and the update sections come first on the page. --- dashboard/e2e/selfhost.spec.ts | 13 +- dashboard/e2e/update-press.spec.ts | 308 +++++++++++++++++++++ dashboard/e2e/update-state-derive.spec.ts | 57 +++- dashboard/src/app/settings/system/page.tsx | 195 +++++++++---- dashboard/src/components/native-update.tsx | 28 +- dashboard/src/lib/api.ts | 43 ++- dashboard/src/lib/update-state.ts | 99 ++++++- 7 files changed, 672 insertions(+), 71 deletions(-) create mode 100644 dashboard/e2e/update-press.spec.ts diff --git a/dashboard/e2e/selfhost.spec.ts b/dashboard/e2e/selfhost.spec.ts index 41bd0258..638e99ff 100644 --- a/dashboard/e2e/selfhost.spec.ts +++ b/dashboard/e2e/selfhost.spec.ts @@ -298,11 +298,6 @@ for (const [name, viewport] of [["desktop", { width: 1280, height: 800 }], ["pho await expect(page.getByTestId("update-history")).toContainText("health check failed after deploying v1.1.5"); await expect(page.getByTestId("update-history")).toContainText("auto-update window"); - await page.getByRole("button", { name: "Update to v2.0.0" }).click(); - await expect.poll(() => systemCalls.map((c) => c.path)).toContain("/api/system/update"); - // No version: the updater reads GitHub first and installs the newest release at that moment. - expect(systemCalls.find((c) => c.path === "/api/system/update")!.body).toEqual({}); - await page.getByRole("switch", { name: "Install updates automatically" }).click(); await pickOption(page.getByRole("combobox", { name: "Day" }), "sat"); await pickOption(page.getByRole("combobox", { name: "Hour" }), "22"); @@ -312,6 +307,14 @@ for (const [name, viewport] of [["desktop", { width: 1280, height: 800 }], ["pho await page.getByRole("button", { name: "Roll back to the previous version" }).click(); await expect.poll(() => systemCalls.map((c) => c.path)).toContain("/api/system/rollback"); + await page.getByRole("button", { name: "Update to v2.0.0" }).click(); + await expect.poll(() => systemCalls.map((c) => c.path)).toContain("/api/system/update"); + // No version: the updater reads GitHub first and installs the newest release at that moment. + expect(systemCalls.find((c) => c.path === "/api/system/update")!.body).toEqual({}); + // Pressed: the card shows it starting at once, and the button isn't offered again. + await expect(status).toHaveAttribute("data-state", "starting"); + await expect(page.getByRole("button", { name: /^Update to/ })).toHaveCount(0); + const width = await page.evaluate(() => document.documentElement.scrollWidth); expect(width).toBeLessThanOrEqual(viewport.width); await expect(page.getByTestId("install-version").first()).toHaveCount(name === "desktop" ? 1 : await page.getByTestId("install-version").count()); diff --git a/dashboard/e2e/update-press.spec.ts b/dashboard/e2e/update-press.spec.ts new file mode 100644 index 00000000..610dd81f --- /dev/null +++ b/dashboard/e2e/update-press.spec.ts @@ -0,0 +1,308 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; + +// Settings, System: one press of Update does the whole job. The button shows +// progress at once and can't be pressed twice; pressing it while the +// release check runs is recorded, never an error; while an update runs a +// newer release is only mentioned, never a second Update button; error +// toasts are kept for real failures and say what to do. + +const NOW = Date.now(); +const ago = (min: number) => new Date(NOW - min * 60_000).toISOString(); +const unix = (min: number) => Math.floor((NOW - min * 60_000) / 1000); +const pass = (key: string, label: string) => ({ key, group: "Install", label, status: "pass", detail: `${label}: fine.` }); +const CHECKS = [pass("url", "Web address answers"), pass("github_app", "GitHub accepts the app's keys"), pass("email_identity", "Email sender verified"), pass("model", "Claude answers a test call")]; +const NOTES = "## What changed\n\n- Faster reviews on large pull requests (#812)\n- Jira links keep their labels (#815)"; +const rel = (v: string, extra: Record = {}) => ({ version: v, notes: NOTES, published_at: "2026-11-05T16:00:00Z", url: `https://example.org/releases/${v}`, breaking: false, ...extra }); +const SETTINGS = { auto: false, channel: "stable", day: "sun", hour: 3, timezone: "UTC", majors: "ask", digest: "weekly" }; +const OK_HISTORY = [{ id: "UPDATE#1", version: "v0.8.45", from_version: "v0.8.44", actor: "auto", mode: "update", status: "succeeded", started_at: "2026-11-02T03:00:00Z", finished_at: "2026-11-02T03:14:00Z" }]; +const CS_LINK = "https://us-east-1.console.aws.amazon.com/cloudformation/home#/stacks/changesets/changes?stackId=x&changeSetId=y"; +const PENDING = (v: string, min = 1) => ({ version: v, checked_at: ago(min), started_at: ago(min), ok: false, pending: true, results: [], progress: { step: "signature", started_at: ago(min), build: "IN_PROGRESS" } }); + +type V = Record; +interface World { + v: V; + update?: (body: V, w: World) => { status: number; body: unknown }; + rollback?: (w: World) => { status: number; body: unknown }; + apply?: (w: World) => { status: number; body: unknown }; + save?: (body: V, w: World) => { status: number; body: unknown }; + uninstall?: (body: V) => { status: number; body: unknown }; + check?: (w: World) => { status: number; body: unknown }; +} + + +async function setup(page: Page, w: World) { + const calls: string[] = []; + const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route((url) => url.pathname === "/runtime-config.js", (route) => + route.fulfill({ contentType: "text/javascript", body: `window.__CODERHELM_CONFIG__ = ${JSON.stringify({ apiUrl: "", streamUrl: "", selfHosted: true, version: "v0.8.45" })};` }), + ); + await page.route((url) => !["localhost", "127.0.0.1"].includes(url.hostname), (route) => route.abort()); + await page.route((url) => ["localhost", "127.0.0.1"].includes(url.hostname) && /^\/(api|auth)\//.test(url.pathname), async (route) => { + const p = new URL(route.request().url()).pathname; + const method = route.request().method(); + calls.push(`${method} ${p}`); + if (p === "/api/me") return json(route, { user_id: "u_1", team_id: "t_1", github_login: null, email: "admin@acme.example", avatar_url: "", role: "owner", auth_provider: "email", mfa_enabled: true, platform_admin: true }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "acme", status: "active", current: true }] }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/system/version" || p === "/api/system/releases/check") { + return json(route, { + self_hosted: true, + current: { version: "v0.8.45", commit: "0123456789abcdef0123456789abcdef01234567", released_at: "2026-11-01T00:00:00Z", config_fingerprint: "0a3bb7ad772e" }, + latest: null, update_available: false, running: false, settings: SETTINGS, history: OK_HISTORY, + releases: { fetched_at: unix(2), stale: false, reason: null, error: null, behind: null }, + install: { stage: "acme", region: "us-east-1" }, + native: { stack: "coderhelm-acme", can_apply: true, auto_apply: true, pending: null }, + uninstall: { delete_data: false, changed_by: null, changed_at: null }, + ...w.v, + }); + } + if (p === "/api/system/preflight") return json(route, { checked_at: ago(0.2), ready: true, current: "v0.8.45", latest: null, blockers: [], checks: CHECKS }); + if (p === "/api/system/update" && w.update) { + await new Promise((r) => setTimeout(r, 600)); + const r = w.update(route.request().postDataJSON() as V, w); + return json(route, r.body, r.status); + } + if (p === "/api/system/update/apply" && w.apply) { const r = w.apply(w); return json(route, r.body, r.status); } + if (p === "/api/system/rollback" && w.rollback) { const r = w.rollback(w); return json(route, r.body, r.status); } + if (p === "/api/system/update-check" && w.check) { const r = w.check(w); return json(route, r.body, r.status); } + if (p === "/api/system/auto-update" && w.save) { const r = w.save(route.request().postDataJSON() as V, w); return json(route, r.body, r.status); } + if (p === "/api/system/uninstall-mode" && w.uninstall) { const r = w.uninstall(route.request().postDataJSON() as V); return json(route, r.body, r.status); } + if (p === "/api/system/hybrid" || p === "/api/hybrid") return json(route, { registered: false }); + if (p === "/api/system/models") return json(route, { provider: "bedrock", inference_prefix: "us.", model_ids: {}, source: "deploy", updated_at: null, updated_by: null, deploy_default: { provider: "bedrock", inference_prefix: "us." }, region: "us-east-1", models: ["claude-opus-5-5", "claude-sonnet-5-5"], bedrock_ids: { "claude-opus-5-5": "us.anthropic.claude-opus-5-5", "claude-sonnet-5-5": "us.anthropic.claude-sonnet-5-5" }, prefixes: ["us.", "eu.", ""] }); + if (p === "/api/system/domain") return json(route, { available: true, status: "aws", code: "aws", domain: { state: "none" }, check: null }); + return json(route, {}); + }); + return calls; +} + + +const status = (page: Page) => page.getByTestId("update-status"); +const toasts = (page: Page) => page.getByTestId("toast"); +const updateButtons = (page: Page) => page.getByRole("button", { name: /^Update to / }); +const PREPARING = (v: string) => ({ + native: { stack: "coderhelm-acme", can_apply: true, auto_apply: true, pending: { status: "preparing", version: v, id: "UPDATE#2", actor: "admin@acme.example", started_at: ago(0) } }, + history: [{ id: "UPDATE#2", version: v, from_version: "v0.8.45", actor: "admin@acme.example", mode: "update", status: "preparing", started_at: ago(0) }, ...OK_HISTORY], +}); +const posts = (calls: string[], p: string) => calls.filter((c) => c === `POST ${p}`).length; + +test.describe("Update: one press does the whole job", () => { + test("pressed while the release check runs: Checking, who pressed, no toast, nothing more to press", async ({ page }) => { + const w: World = { + v: { latest: rel("v0.8.46"), update_available: true }, + update: (_b, w) => { + const request = { version: "v0.8.46", actor: "admin@acme.example", requested_at: ago(0), status: "waiting", waiting_for: "the release check" }; + w.v = { ...w.v, model_check: PENDING("v0.8.46", 0), update_request: request }; + return { status: 200, body: { ok: true, state: "checking", version: "v0.8.46", model_check: PENDING("v0.8.46", 0), request } }; + }, + }; + const calls = await setup(page, w); + await page.goto("/settings/system/"); + const button = page.getByRole("button", { name: "Update to v0.8.46" }); + await button.click(); + // Progress shows at once, and the button can't be pressed again meanwhile. + await expect(status(page).getByRole("button", { name: "Starting…" })).toBeDisabled(); + await expect(status(page)).toHaveAttribute("data-state", "checking-release"); + await expect(status(page)).toContainText("Checking v0.8.46 before it can be applied"); + await expect(page.getByTestId("update-requested")).toContainText("admin@acme.example pressed Update"); + await expect(page.getByTestId("update-requested")).toContainText("it starts by itself once the check passes"); + await expect(updateButtons(page)).toHaveCount(0); + await page.waitForTimeout(800); + await expect(toasts(page)).toHaveCount(0); + expect(posts(calls, "/api/system/update")).toBe(1); + // The check passes and the updater starts it: the card moves on by itself. + w.v = { ...w.v, model_check: { version: "v0.8.46", checked_at: ago(0), ok: true, results: [] }, update_request: { version: "v0.8.46", status: "started", id: "UPDATE#2" }, ...PREPARING("v0.8.46") }; + await expect(status(page)).toHaveAttribute("data-state", "preparing", { timeout: 20_000 }); + expect(posts(calls, "/api/system/update")).toBe(1); + }); + + test("a double click sends one request and the button never comes back while it starts", async ({ page }) => { + const w: World = { + v: { latest: rel("v0.8.46"), update_available: true, model_check: { version: "v0.8.46", checked_at: ago(5), ok: true, results: [] } }, + update: (_b, w) => { + w.v = { ...w.v, ...PREPARING("v0.8.46") }; + return { status: 200, body: { id: "UPDATE#2", version: "v0.8.46", status: "preparing", state: "started" } }; + }, + }; + const calls = await setup(page, w); + await page.goto("/settings/system/"); + await page.getByRole("button", { name: "Update to v0.8.46" }).dblclick(); + await expect(status(page)).toHaveAttribute("data-state", "preparing"); + await expect(updateButtons(page)).toHaveCount(0); + expect(posts(calls, "/api/system/update")).toBe(1); + await expect(toasts(page)).toHaveCount(0); + }); + + test("a read from before the press never brings the Update button back: Starting until the updater shows it", async ({ page }) => { + let pressed = false; + let reads = 0; + const w: World = { + v: { latest: rel("v0.8.46"), update_available: true, model_check: { version: "v0.8.46", checked_at: ago(5), ok: true, results: [] } }, + update: () => { pressed = true; return { status: 200, body: { id: "UPDATE#2", version: "v0.8.46", status: "preparing", state: "started" } }; }, + }; + const calls = await setup(page, w); + await page.route((url) => url.pathname === "/api/system/version", async (route) => { + if (pressed && ++reads > 2) w.v = { ...w.v, ...PREPARING("v0.8.46") }; + return route.fallback(); + }); + await page.goto("/settings/system/"); + await page.getByRole("button", { name: "Update to v0.8.46" }).click(); + await expect(status(page)).toHaveAttribute("data-state", "starting"); + await expect(status(page)).toContainText("Starting the update to v0.8.46"); + await expect(status(page)).toContainText("there's nothing more to press"); + await expect(updateButtons(page)).toHaveCount(0); + await expect(status(page)).toHaveAttribute("data-state", "preparing", { timeout: 20_000 }); + expect(posts(calls, "/api/system/update")).toBe(1); + }); + + test("a newer release out while one prepares: mentioned quietly, never a second Update button", async ({ page }) => { + await setup(page, { v: { latest: rel("v0.8.47"), update_available: true, ...PREPARING("v0.8.46") } }); + await page.goto("/settings/system/"); + await expect(status(page)).toHaveAttribute("data-state", "preparing"); + await expect(status(page)).toContainText("Preparing the update to v0.8.46"); + await expect(page.getByTestId("update-next")).toHaveText("v0.8.47 is out too; it's next after this one."); + await expect(updateButtons(page)).toHaveCount(0); + await expect(page.getByTestId("release-notes")).toHaveCount(0); + }); + + test("a newer release out while the pressed one is checked: still Checking the pressed one, the newer one mentioned", async ({ page }) => { + await setup(page, { + v: { + latest: rel("v0.8.47"), update_available: true, model_check: PENDING("v0.8.46", 2), + update_request: { version: "v0.8.46", actor: "admin@acme.example", requested_at: ago(2), status: "waiting", waiting_for: "the release check" }, + }, + }); + await page.goto("/settings/system/"); + await expect(status(page)).toHaveAttribute("data-state", "checking-release"); + await expect(status(page)).toContainText("Checking v0.8.46"); + await expect(page.getByTestId("update-next")).toContainText("v0.8.47 is out too"); + await expect(updateButtons(page)).toHaveCount(0); + }); + + test("once the update finished, the newer release is offered once", async ({ page }) => { + await setup(page, { v: { current: { version: "v0.8.46", commit: null, released_at: null, config_fingerprint: null }, latest: rel("v0.8.47"), update_available: true, history: [{ id: "UPDATE#2", version: "v0.8.46", from_version: "v0.8.45", actor: "admin@acme.example", mode: "update", status: "succeeded", started_at: ago(20), finished_at: ago(1) }, ...OK_HISTORY] } }); + await page.goto("/settings/system/"); + await expect(status(page)).toHaveAttribute("data-state", "available"); + await expect(updateButtons(page)).toHaveCount(1); + await expect(page.getByTestId("update-next")).toHaveCount(0); + }); + + test("a press that ended says why in the card", async ({ page }) => { + await setup(page, { v: { latest: rel("v0.8.46"), update_available: true, update_request: { version: "v0.8.46", actor: "admin@acme.example", requested_at: ago(30), status: "ended", reason: "the update to v0.8.45 is still running; this one can start once it finishes", ended_at: ago(25) } } }); + await page.goto("/settings/system/"); + await expect(page.getByTestId("update-ended")).toContainText("didn't apply it: the update to v0.8.45 is still running"); + }); +}); + +test.describe("Update: error toasts only for real failures", () => { + test("a real 500: a toast that says what went wrong and what to do, and Update works again", async ({ page }) => { + let n = 0; + const w: World = { + v: { latest: rel("v0.8.46"), update_available: true }, + update: (_b, w) => { + n += 1; + if (n === 1) return { status: 500, body: {} }; + w.v = { ...w.v, ...PREPARING("v0.8.46") }; + return { status: 200, body: { id: "UPDATE#2", version: "v0.8.46", status: "preparing", state: "started" } }; + }, + }; + await setup(page, w); + await page.goto("/settings/system/"); + await page.getByRole("button", { name: "Update to v0.8.46" }).click(); + await expect(toasts(page)).toHaveText(["Couldn't start the update: the server didn't answer (error 500). Nothing changed; try again in a minute."]); + await expect(status(page)).toHaveAttribute("data-state", "available"); + await page.getByRole("button", { name: "Update to v0.8.46" }).click(); + await expect(status(page)).toHaveAttribute("data-state", "preparing"); + }); + + test("a model the release calls refused: the card shows it with the fix, no toast", async ({ page }) => { + const mc = { version: "v0.8.46", checked_at: ago(1), ok: false, provider: "bedrock", results: [{ model: "claude-sonnet-5-5", id: "us.anthropic.claude-sonnet-5-5", status: "fail", code: "terms", detail: "The terms for this model haven't been accepted in this AWS account.", fix: "Accept the terms in the Bedrock console.", required: true }] }; + await setup(page, { + v: { latest: rel("v0.8.46"), update_available: true }, + update: (_b, w) => { w.v = { ...w.v, model_check: mc }; return { status: 409, body: { error: "Update to v0.8.46 needs your action: The terms for this model haven't been accepted in this AWS account.", model_check: mc } }; }, + }); + await page.goto("/settings/system/"); + await page.getByRole("button", { name: "Update to v0.8.46" }).click(); + await expect(status(page)).toHaveAttribute("data-state", "needs-action"); + await page.waitForTimeout(800); + await expect(toasts(page)).toHaveCount(0); + }); + + test("a refusal with its reason: the toast names it", async ({ page }) => { + await setup(page, { v: { latest: rel("v0.8.46"), update_available: true }, update: () => ({ status: 400, body: { error: "the update to v0.8.45 is still running; this one can start once it finishes" } }) }); + await page.goto("/settings/system/"); + await page.getByRole("button", { name: "Update to v0.8.46" }).click(); + await expect(toasts(page)).toHaveText(["Couldn't start the update: the update to v0.8.45 is still running; this one can start once it finishes."]); + }); + + test("Apply after it was applied in the AWS console: the card shows it applying, no toast", async ({ page }) => { + const prepared = { version: "v0.8.46", status: "review", counts: { add: 2, modify: 5, remove: 0 }, parts: ["Api"], link: CS_LINK, id: "UPDATE#2", can_apply: true, data_changes: [], permission_changes: [], admin_changes: [] }; + const calls = await setup(page, { + v: { latest: rel("v0.8.46"), update_available: true, native: { stack: "coderhelm-acme", can_apply: true, auto_apply: true, pending: prepared } }, + apply: (w) => { + w.v = { ...w.v, running: true, native: { stack: "coderhelm-acme", can_apply: true, auto_apply: true, pending: { ...prepared, status: "running", execution: "EXECUTE_IN_PROGRESS", applied_by: "someone in the AWS console", executed_at: ago(1) } } }; + return { status: 400, body: { error: "no prepared update is waiting for you (reload the page)" } }; + }, + }); + await page.goto("/settings/system/"); + await page.getByRole("button", { name: "Apply v0.8.46" }).dblclick(); + await expect(status(page)).toHaveAttribute("data-state", "updating"); + await expect(page.getByTestId("native-update-progress")).toContainText("It was applied in the AWS console."); + await expect(toasts(page)).toHaveCount(0); + expect(posts(calls, "/api/system/update/apply")).toBe(1); + }); + + test("settings saves: a refusal and a 502 each say what to do; polling never drops an unsaved change", async ({ page }) => { + let n = 0; + await setup(page, { + v: { latest: rel("v0.8.46"), update_available: true, ...PREPARING("v0.8.46") }, + save: (b) => { n += 1; if (n === 1) return { status: 400, body: { error: "timezone: an IANA name such as Europe/Berlin" } }; if (n === 2) return { status: 502, body: {} }; return { status: 200, body: { settings: b } }; }, + }); + await page.clock.install({ time: new Date(NOW) }); + await page.goto("/settings/system/"); + await page.getByTestId("channel-beta").click(); + // The page reads the version route every 10 seconds while it prepares. + await page.clock.fastForward(21_000); + await expect(page.getByTestId("channel-beta").getByRole("radio")).toBeChecked(); + await page.getByRole("button", { name: "Save changes" }).click(); + await expect(toasts(page).last()).toHaveText("Couldn't save the update settings: timezone: an IANA name such as Europe/Berlin."); + await page.getByRole("button", { name: "Save changes" }).click(); + await expect(toasts(page).last()).toHaveText("Couldn't save the update settings: the server didn't answer (error 502). Nothing changed; try again in a minute."); + await expect(page.getByTestId("channel-beta").getByRole("radio")).toBeChecked(); + await page.getByRole("button", { name: "Save changes" }).click(); + await expect(toasts(page).last()).toHaveText("Update settings saved"); + }); +}); + +test.describe("Version and updates: the page", () => { + test("an old release list never says up to date, and Check for updates is the action", async ({ page }) => { + await setup(page, { v: { releases: { fetched_at: unix(60 * 80), stale: true, reason: null, error: null, behind: null } } }); + await page.goto("/settings/system/"); + await expect(status(page)).toHaveAttribute("data-state", "stale"); + await expect(status(page)).toContainText("Not checked for updates lately"); + await expect(page.locator("#version")).not.toContainText("up to date"); + }); + + test("update sections come first: Version, Automatic updates, Update history, then the install", async ({ page }) => { + await setup(page, { v: {} }); + await page.goto("/settings/system/"); + await expect(status(page)).toBeVisible(); + const ids = await page.locator("main section[id], main [id]").evaluateAll((els) => els.map((e) => e.id).filter((i) => ["version", "auto", "history", "health", "models", "domain", "hybrid", "uninstall"].includes(i))); + expect(ids).toEqual(["version", "auto", "history", "health", "models", "domain", "hybrid", "uninstall"]); + }); + + test("nothing to roll back to: a line that says so, no dead button", async ({ page }) => { + await setup(page, { v: { history: [] } }); + await page.goto("/settings/system/"); + await expect(page.getByTestId("rollback")).toHaveCount(0); + await expect(page.getByTestId("rollback-note")).toContainText("Nothing to roll back to yet"); + }); + + test("the version route doesn't answer: what happened and Try again", async ({ page }) => { + await setup(page, { v: {} }); + await page.route((url) => url.pathname === "/api/system/version", (route) => route.fulfill({ status: 502, contentType: "application/json", body: "{}" })); + await page.goto("/settings/system/"); + await expect(page.getByText("Couldn't load this install's version")).toBeVisible(); + await expect(page.getByText("The server didn't answer.")).toBeVisible(); + await expect(page.getByRole("button", { name: "Try again" })).toBeVisible(); + }); +}); diff --git a/dashboard/e2e/update-state-derive.spec.ts b/dashboard/e2e/update-state-derive.spec.ts index eff97ff9..6b518a87 100644 --- a/dashboard/e2e/update-state-derive.spec.ts +++ b/dashboard/e2e/update-state-derive.spec.ts @@ -1,5 +1,5 @@ import { expect, test } from "@playwright/test"; -import { deriveUpdateState, followEvery, type UpdateState } from "../src/lib/update-state"; +import { deriveUpdateState, failureText, followEvery, nextAfter, withPress, type UpdateState } from "../src/lib/update-state"; import type { SystemPreflight, SystemVersion } from "../src/lib/api"; // The one function that maps the version route (and the preflight) to the @@ -90,3 +90,58 @@ test.describe("deriveUpdateState: one coherent state", () => { expect(followEvery(derive({}))).toBeNull(); }); }); + +test.describe("an Update press: one state, never a second button", () => { + const waiting = { version: "v0.8.39", actor: "owner@example.org", requested_at: ago(2), status: "waiting" as const, waiting_for: "the release check" }; + const pending = { ...STALE_CHECK, checked_at: ago(2), started_at: ago(2) }; + + test("a press waiting for the check is Checking, with who pressed", () => { + const s = derive({ model_check: pending, update_request: waiting }); + expect(s.kind).toBe("checking"); + if (s.kind === "checking") expect(s.request?.actor).toBe("owner@example.org"); + }); + + test("a newer release listed while the pressed one is checked: still Checking the pressed one, the newer one next", () => { + const data = { ...BASE, latest: { version: "v0.8.40", notes: "", breaking: false }, model_check: pending, update_request: waiting }; + const s = deriveUpdateState(data, null, NOW); + expect(s.kind === "checking" && s.version).toBe("v0.8.39"); + expect(nextAfter(s, data)).toBe("v0.8.40"); + }); + + test("the check passed but the updater hasn't started it yet: still Checking, not an Update button", () => { + expect(derive({ model_check: { version: "v0.8.39", checked_at: ago(0), ok: true, results: [] }, update_request: waiting }).kind).toBe("checking"); + }); + + test("a press that ended: the offer, with the reason", () => { + const s = derive({ update_request: { ...waiting, status: "ended", reason: "a model was refused", ended_at: ago(1) } }); + expect(s.kind).toBe("available"); + if (s.kind === "available") expect(s.ended?.reason).toBe("a model was refused"); + }); + + test("just pressed and the version route still reads as before: Starting, until it moves or the hold runs out", () => { + const before = derive({}); + expect(before.kind).toBe("available"); + const press = { version: "v0.8.39", at: NOW }; + expect(withPress(before, press, NOW).kind).toBe("starting"); + expect(followEvery(withPress(before, press, NOW))).toBe(3_000); + expect(withPress(before, press, NOW + 120_000).kind).toBe("available"); + const preparing = derive({ native: { ...BASE.native!, pending: { version: "v0.8.39", status: "preparing", id: "UPDATE#b" } } }); + expect(withPress(preparing, press, NOW).kind).toBe("preparing"); + }); + + test("no newer release mentioned for the version in progress itself, or when nothing runs", () => { + const data = { ...BASE, native: { ...BASE.native!, pending: { version: "v0.8.39", status: "preparing", id: "UPDATE#b" } } }; + expect(nextAfter(deriveUpdateState(data, null, NOW), data)).toBeNull(); + expect(nextAfter(derive({}), BASE)).toBeNull(); + }); + + test("an old release list is not up to date", () => { + expect(derive({ latest: null, update_available: false, releases: { fetched_at: Math.floor(NOW / 1000) - 4 * 86400, stale: true, reason: null, error: null, behind: null } }).kind).toBe("stale"); + }); + + test("error toasts say what went wrong and what to do", () => { + expect(failureText("start the update", "", 502)).toBe("Couldn't start the update: the server didn't answer (error 502). Nothing changed; try again in a minute."); + expect(failureText("start the update", "Forbidden", 403)).toContain("only install admins"); + expect(failureText("start the roll back", "an update is already running.", 400)).toBe("Couldn't start the roll back: an update is already running."); + }); +}); diff --git a/dashboard/src/app/settings/system/page.tsx b/dashboard/src/app/settings/system/page.tsx index b0f00340..45a44420 100644 --- a/dashboard/src/app/settings/system/page.tsx +++ b/dashboard/src/app/settings/system/page.tsx @@ -1,9 +1,9 @@ "use client"; -import { useCallback, useEffect, useState, type ReactNode } from "react"; +import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; import Link from "next/link"; -import { api, type AutoUpdateSettings, type ModelCheck, type SystemPreflight, type SystemVersion, type UpdateEntry } from "@/lib/api"; -import { deriveUpdateState, followEvery, STATE_ID, type FailedTry, type UpdateState } from "@/lib/update-state"; +import { api, errorStatus, type AutoUpdateSettings, type ModelCheck, type SystemPreflight, type SystemVersion, type UpdateEntry } from "@/lib/api"; +import { deriveUpdateState, failureText, followEvery, isStateAnswer, nextAfter, STATE_ID, STARTING_HOLD_MS, withPress, type FailedTry, type UpdateState } from "@/lib/update-state"; import { CheckRow } from "@/components/install-checks"; import { DomainSection } from "@/components/domain-section"; import { HybridSection } from "@/components/hybrid-section"; @@ -137,24 +137,54 @@ function System() { loadPreflight(); }, [loadPreflight]); const form = useDirtyForm(DEFAULTS, { disabled: !data }); + // An Update press the version route may not show yet: until it does, the + // card says Starting and never offers the button again. + const [press, setPress] = useState<{ version: string | null; at: number } | null>(null); + // One action at a time, whatever the clicks: a double click sends one request. + const acting = useRef(false); + // Only the newest read of the version route is shown: a slow poll that + // started before a press never replaces what the press led to. + const reads = useRef(0); const load = useCallback(async () => { + const mine = ++reads.current; try { const v = await api.getSystemVersion(); + if (mine !== reads.current) return; setData(v); setError(false); - form.reset(withChannel(v.settings)); + // The saved settings, without dropping what someone is changing: the + // page reads the version route again every few seconds while an update runs. + if (!dirtyRef.current) form.reset(withChannel(v.settings)); } catch { - setError(true); + if (mine !== reads.current) return; + // A failed poll keeps what is on screen; only a page with nothing yet shows the error. + setError((had) => had || !dataRef.current); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + const dataRef = useRef(null); + dataRef.current = data; + const dirtyRef = useRef(false); + dirtyRef.current = form.dirty; useEffect(() => { load(); }, [load]); - // The one update state, derived in one place (lib/update-state.ts). - const state: UpdateState | null = data ? deriveUpdateState(data, pre) : null; + // The one update state, derived in one place (lib/update-state.ts), with a + // press the version route doesn't show yet laid over it. + const derived: UpdateState | null = data ? deriveUpdateState(data, pre) : null; + const state: UpdateState | null = derived ? withPress(derived, press) : null; + useEffect(() => { + if (!press) return; + // The updater's answer is on screen (or the hold ran out): the press is done. + if (state && state.kind !== "starting") { + setPress(null); + return; + } + const t = window.setTimeout(() => setPress(null), Math.max(0, press.at + STARTING_HOLD_MS - Date.now())); + return () => window.clearTimeout(t); + }, [press, state]); // While something is happening (the release check, preparing, waiting for // an OK that can also be given in the AWS console, applying), follow it: // the version route reads CloudFormation each time, so the card moves from @@ -170,7 +200,7 @@ function System() { const header = (
- +
); @@ -178,7 +208,8 @@ function System() { return ( {header} - + +

The server didn't answer. Nothing changed on the install; try again in a minute.

@@ -207,47 +238,60 @@ function System() { const blockers = (pre?.blockers ?? []).filter((b) => b.severity === "block"); const checkKeys = new Set((pre?.checks ?? []).map((c) => c.key)); const blocking = new Set(blockers.filter((b) => checkKeys.has(b.key)).map((b) => b.key)); - const busyUpdating = ["applying", "preparing", "review"].includes(state.kind); + const busyUpdating = ["applying", "preparing", "review", "starting", "checking"].includes(state.kind); const failure = state.kind === "failed" ? state.failure : null; const offered = !!latest && ["available", "blocked", "updater-down", "needs-action", "checking", "check-stalled", "failed"].includes(state.kind); const save = async () => { try { const r = await api.setAutoUpdate(form.values); - form.reset({ ...DEFAULTS, ...r.settings }); + form.reset(withChannel({ ...DEFAULTS, ...r.settings })); toast("Update settings saved"); } catch (e) { - toast(e instanceof Error ? e.message : "Could not save", "error"); + // Your changes stay on the page: Save again once it answers. + toast(failureText("save the update settings", e instanceof Error ? e.message : null, errorStatus(e)), "error"); } }; const start = async (kind: "update" | "rollback", skipCheck = false) => { + if (acting.current) return; + acting.current = true; setBusy(kind); + // Any read already on its way is from before this press. + reads.current += 1; try { if (kind === "update") { // No version: the updater reads GitHub first and installs the newest // release at this moment. Skipping a model check names the release // whose check the admin read. const r = await api.updateNow(skipCheck ? data.model_check?.version : undefined, skipCheck); - if (!r.ok) { - // A model the release calls was refused: show which, with its fix. - if (r.model_check) setData({ ...data, model_check: r.model_check }); - toast(r.error, "error"); + if (r.ok) { + // Started, or recorded while the release check runs (it starts by + // itself once the check passes): either way the card shows it. + setPress({ version: r.version ?? null, at: Date.now() }); + if (r.state === "checking") { + setData((d) => (d ? { ...d, model_check: r.model_check ?? d.model_check, update_request: r.request ?? d.update_request } : d)); + } + } else if (r.model_check || r.waiting || isStateAnswer(r.httpStatus)) { + // The release check holds it (a model it calls was refused, or the + // release isn't ready): the card shows which, with the fix. + if (r.model_check) setData((d) => (d ? { ...d, model_check: r.model_check } : d)); loadPreflight(); - return; + } else { + toast(failureText("start the update", r.error, r.httpStatus), "error"); } - toast(data.native ? `Preparing ${r.version}, then it applies. This takes 10 to 20 minutes.` : `Updating to ${r.version}. This takes 10 to 20 minutes.`); } else { - const e = await api.rollbackInstall(); - toast(`Rolling back to ${e.version}.`); + await api.rollbackInstall(); } - await load(); } catch (e) { - toast(e instanceof Error ? e.message : "Could not start", "error"); + toast(failureText(kind === "update" ? "start the update" : "start the roll back", e instanceof Error ? e.message : null, errorStatus(e)), "error"); } finally { + await load(); + acting.current = false; setBusy(""); } }; + const next = nextAfter(state, data); return ( @@ -267,6 +311,7 @@ function System() { load(); }} onSkipModel={() => start("update", true)} + next={next} /> {!busyUpdating && data.current.version && } @@ -276,22 +321,6 @@ function System() { {latest && offered && } - - - - - - - - - - - - - - - - )} -
- +
+ {canRollBack ? ( + + ) : null} +

+ {!canRollBack + ? "Nothing to roll back to yet: once an update finishes here, you can go back to the version before it." + : busyUpdating + ? "You can roll back once the update in progress finishes." + : "Goes back to the version before the last update. Your data stays as it is."} +

+ + + + + + + + + + + + + + + + @@ -504,6 +558,7 @@ function UpdateStatus({ onChanged, onModelChecked, onSkipModel, + next, }: { state: UpdateState; data: SystemVersion; @@ -512,6 +567,8 @@ function UpdateStatus({ onChanged: () => void; onModelChecked: (c: ModelCheck | null) => void; onSkipModel: () => void; + /** A release newer than the update in progress: mentioned, never a second button. */ + next: string | null; }) { const current = data.current.version; const latest = data.latest; @@ -520,13 +577,14 @@ function UpdateStatus({ const beta = withChannel(data.settings).channel === "beta"; const healthLink = See install health; const id = STATE_ID[state.kind]; + const nextLine = next ?

{next} is out too; it's next after this one.

: null; switch (state.kind) { case "applying": if (state.pending && data.native) { return (
- +
); } @@ -537,6 +595,7 @@ function UpdateStatus({ This takes 10 to 20 minutes. Coderhelm keeps running {on} until it finishes, and this page updates by itself.

+ {nextLine} ); @@ -551,21 +610,47 @@ function UpdateStatus({ startedAt={state.kind === "preparing" ? state.startedAt : undefined} startedBy={state.kind === "preparing" ? state.startedBy : undefined} from={current} + next={nextLine} />
); - case "checking": + case "starting": + return ( + Starting the update to {state.version}…}> +

+ The updater has your request. This card moves on by itself in a few seconds; there's nothing more to press. +

+ + +
+ ); + + case "checking": { + const req = state.request; + const by = req?.actor && req.actor !== "AWS CLI" ? req.actor : null; + const waits = req?.waiting_for && req.waiting_for !== "the release check" ? req.waiting_for : null; return ( Checking {state.version} before it can be applied}>

{state.startedAt ? <>Started

+ {req ? ( +

+ {by ? <>{by} pressed Update : <>Update was pressed} + {req.requested_at ? <>

+ ) : ( +

Then you can update, or it installs by itself in your maintenance window if automatic updates are on.

+ )} + {nextLine}
); + } case "check-stalled": return ( @@ -687,6 +772,11 @@ function UpdateStatus({

)} {l.prerelease &&

A nightly beta: it reaches Stable after a day with no reported problem. You get these because the channel is Beta (nightly).

} + {state.ended?.reason ? ( +

+ The last press of Update{state.ended.requested_at ? <> (

+ ) : null} ); } @@ -712,6 +802,15 @@ function UpdateStatus({ ); + case "stale": + return ( + +

+ You're on {current}. The list of releases was last read {state.fetchedAt ?

+
+ ); + case "not-checked": return ( @@ -751,7 +850,7 @@ function CheckAgain({ onChecked }: { onChecked: (c: ModelCheck | null) => void } try { onChecked((await api.checkUpdateModels()).model_check); } catch (e) { - toast(e instanceof Error ? e.message : "Could not start the check", "error"); + toast(failureText("start the check again", e instanceof Error ? e.message : null, errorStatus(e)), "error"); } finally { setBusy(false); } @@ -783,12 +882,12 @@ function ReleaseCheck({ data, onChecked }: { data: SystemVersion; onChecked: (v: try { onChecked(await api.checkReleases()); } catch (e) { - toast(e instanceof Error ? e.message : "Could not check for updates", "error"); + toast(failureText("check for updates", e instanceof Error ? e.message : null, errorStatus(e)), "error"); } finally { setChecking(false); } }; - const primary = !!r && (!r.fetched_at || !!r.error || !!r.behind) && !data.latest; + const primary = !!r && (!r.fetched_at || !!r.error || !!r.behind || r.stale) && !data.latest; return (
@@ -1067,7 +1073,7 @@ function InstallHealth({ pre, state, blocking, onRecheck }: { pre: SystemPreflig )} {pre && failing.length + warning.length > 0 && ( -