diff --git a/dashboard/e2e/models-switch.spec.ts b/dashboard/e2e/models-switch.spec.ts index 602dbdd9..6e1dbd8d 100644 --- a/dashboard/e2e/models-switch.spec.ts +++ b/dashboard/e2e/models-switch.spec.ts @@ -59,7 +59,8 @@ async function setup(page: Page, opts: Opts = {}) { const calls: { method: string; path: string; body: Record }[] = []; const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); const modelCheck = () => ({ - version: "v1.3.0", checked_at: "2026-10-26T08:00:00Z", ok: !state.blocked && !state.pending, pending: state.pending, provider: "bedrock", region: "us-east-1", + // A check still running started just now (an old pending one reads as stalled). + version: "v1.3.0", checked_at: state.pending ? new Date().toISOString() : "2026-10-26T08:00:00Z", ok: !state.blocked && !state.pending, pending: state.pending, provider: "bedrock", region: "us-east-1", results: state.blocked ? [pass("claude-opus-5-5"), terms("claude-sonnet-5-5")] : MODELS.map((m) => pass(m)), }); await page.route((url) => url.pathname === "/runtime-config.js", (route) => @@ -224,9 +225,11 @@ for (const width of [1440, 390]) { test("while the release's signature is checked, the update waits and says so", async ({ page }) => { const { state } = await setup(page, { pending: true }); await page.goto("/settings/system/"); - await expect(page.getByTestId("update-checking")).toContainText("Checking v1.3.0 before it can be applied"); + await expect(page.getByTestId("update-status")).toContainText("Checking v1.3.0 before it can be applied"); + await expect(page.getByTestId("update-checking")).toContainText("Started just now"); await expect(page.getByTestId("update-needs-action")).toHaveCount(0); + await expect(page.getByTestId("update-status")).toHaveAttribute("data-state", "checking-release"); + // Nothing to press: the page follows the check and moves on once it passes. state.pending = false; - await page.getByTestId("update-checking").getByRole("button", { name: "Re-run the model check" }).click(); - await expect(page.getByTestId("update-checking")).toHaveCount(0); + await expect(page.getByTestId("update-checking")).toHaveCount(0, { timeout: 20_000 }); }); diff --git a/dashboard/e2e/selfhost.spec.ts b/dashboard/e2e/selfhost.spec.ts index af162d5f..41bd0258 100644 --- a/dashboard/e2e/selfhost.spec.ts +++ b/dashboard/e2e/selfhost.spec.ts @@ -537,7 +537,7 @@ test("System: an update still being prepared shows that, before the change set h const card = page.getByTestId("native-update"); await expect(card).toContainText("Preparing the update to v2.0.0"); await expect(page.getByTestId("update-status")).toHaveAttribute("data-state", "preparing"); - await expect(page.getByTestId("native-update-progress")).toContainText("Step 1 of 2"); + await expect(page.getByTestId("update-steps").locator('[aria-current="step"]')).toHaveAttribute("data-step", "prepare"); await expect(card).toContainText("Nothing to do yet"); await expect(page.getByTestId("native-update-summary")).toHaveCount(0); await expect(page.getByTestId("native-update-link")).toHaveCount(0); @@ -559,7 +559,7 @@ test("System: a running one-stack update says so, with nothing to do and no cons await setup(page, SELF, { signedIn: true, native: { stack: "coderhelm-prod", can_apply: true, auto_apply: true, pending: { ...PREPARED, status: "running" } } }); await page.goto("/settings/system/"); const card = page.getByTestId("native-update"); - await expect(card).toContainText("Updating to v2.0.0"); + await expect(card).toContainText("Applying v2.0.0"); await expect(page.getByTestId("native-update-summary")).toContainText("It changes 8 resources (2 to add, 5 to change, 1 to remove) in Api, Worker"); await expect(card).not.toContainText("Execute"); await expect(page.getByTestId("native-update-apply")).toHaveCount(0); diff --git a/dashboard/e2e/update-state-derive.spec.ts b/dashboard/e2e/update-state-derive.spec.ts new file mode 100644 index 00000000..eff97ff9 --- /dev/null +++ b/dashboard/e2e/update-state-derive.spec.ts @@ -0,0 +1,92 @@ +import { expect, test } from "@playwright/test"; +import { deriveUpdateState, followEvery, 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 +// one state the Version card shows. No browser: these feed it payloads, +// including the contradictory ones seen on a live install, and check that +// exactly one coherent state comes out. + +const NOW = Date.parse("2026-11-04T04:00:00Z"); +const ago = (min: number) => new Date(NOW - min * 60_000).toISOString(); + +const BASE: SystemVersion = { + self_hosted: true, + current: { version: "v0.8.32", commit: null, released_at: null, config_fingerprint: null }, + latest: { version: "v0.8.39", notes: "", breaking: false }, + update_available: true, + releases: { fetched_at: Math.floor(NOW / 1000) - 60, stale: false, reason: null, error: null, behind: null }, + running: false, + history: [], + native: { stack: "coderhelm-example", can_apply: true, auto_apply: true, pending: null }, +}; +const PERMS = { can_apply: true, confirm: "c".repeat(64), data_changes: [], permission_changes: ["Api.NewRole (AWS::IAM::Role Add: an IAM change)"], admin_changes: [] }; +const STALE_CHECK = { version: "v0.8.39", checked_at: ago(120), started_at: ago(120), ok: false, pending: true, results: [], note: "checking the release's signature before reading the models it calls" }; +const PRE: SystemPreflight = { + checked_at: ago(0), ready: false, current: "v0.8.32", latest: "v0.8.39", checks: [], + blockers: [{ key: "model_check_pending", severity: "block", detail: "Checking v0.8.39's signature before reading the models it calls.", fix: { text: "Wait a few minutes, then check again." } }], +}; + +const derive = (v: Partial, pre: SystemPreflight | null = null): UpdateState => deriveUpdateState({ ...BASE, ...v }, pre, NOW); + +test.describe("deriveUpdateState: one coherent state", () => { + test("observed: an older update waiting for its OK, a newer one prepared, and a stale Checking", () => { + const s = derive({ + native: { ...BASE.native!, pending: { version: "v0.8.37", status: "review", id: "UPDATE#a", ...PERMS } }, + history: [ + { id: "UPDATE#b", version: "v0.8.39", from_version: "v0.8.32", actor: "owner@example.org", mode: "update", status: "review", started_at: ago(10) }, + { id: "UPDATE#a", version: "v0.8.37", from_version: "v0.8.32", actor: "owner@example.org", mode: "update", status: "review", started_at: ago(60) }, + ], + model_check: STALE_CHECK, + }, PRE); + // The newest prepared update wins; the older one is never offered, and the + // stale "Checking" for a version already prepared is not shown. + expect(s.kind).toBe("preparing"); + expect(s.kind === "preparing" && s.version).toBe("v0.8.39"); + }); + + test("the same install once the updater reconciled it: ready to apply v0.8.39, with the permission list", () => { + const s = derive({ + native: { ...BASE.native!, pending: { version: "v0.8.39", status: "review", id: "UPDATE#b", execution: "AVAILABLE", ...PERMS } }, + history: [ + { id: "UPDATE#b", version: "v0.8.39", actor: "owner@example.org", status: "review", started_at: ago(10) }, + { id: "UPDATE#a", version: "v0.8.37", actor: "owner@example.org", status: "superseded", started_at: ago(60) }, + ], + model_check: { ...STALE_CHECK, pending: false, ok: true, checked_at: ago(10) }, + }); + expect(s).toMatchObject({ kind: "review", version: "v0.8.39", need: "confirm" }); + }); + + test("observed: executed in the AWS console while the entry still said review", () => { + const s = derive({ native: { ...BASE.native!, pending: { version: "v0.8.39", status: "review", id: "UPDATE#b", execution: "EXECUTE_IN_PROGRESS", ...PERMS } } }); + expect(s.kind).toBe("applying"); + }); + + test("applied in the console, reported by the updater", () => { + const s = derive({ running: true, native: { ...BASE.native!, pending: { version: "v0.8.39", status: "running", id: "UPDATE#b", applied_by: "someone in the AWS console", executed_at: ago(5) } } }); + expect(s).toMatchObject({ kind: "applying", appliedBy: "someone in the AWS console" }); + }); + + test("a model check pending for longer than its bound is stalled, not Checking", () => { + expect(derive({ model_check: STALE_CHECK }).kind).toBe("check-stalled"); + expect(derive({ model_check: { ...STALE_CHECK, started_at: ago(3), checked_at: ago(3) } }).kind).toBe("checking"); + expect(derive({ model_check: { ...STALE_CHECK, pending: false, stalled: true, note: "The release check couldn't verify v0.8.39: bad signature." } })).toMatchObject({ + kind: "check-stalled", note: "The release check couldn't verify v0.8.39: bad signature.", + }); + }); + + test("a superseded row is neither a failure nor the newest update", () => { + const s = derive({ latest: null, update_available: false, current: { ...BASE.current, version: "v0.8.39" }, history: [ + { id: "UPDATE#c", version: "v0.8.39", actor: "owner@example.org", status: "succeeded", started_at: ago(30), finished_at: ago(10) }, + { id: "UPDATE#a", version: "v0.8.37", actor: "owner@example.org", status: "superseded", started_at: ago(60) }, + ] }); + expect(s).toMatchObject({ kind: "current" }); + expect(s.kind === "current" && s.done?.version).toBe("v0.8.39"); + }); + + test("the page follows only while something is happening", () => { + expect(followEvery(derive({ native: { ...BASE.native!, pending: { version: "v0.8.39", status: "preparing", id: "UPDATE#b" } } }))).toBe(10_000); + expect(followEvery(derive({ native: { ...BASE.native!, pending: { version: "v0.8.39", status: "review", id: "UPDATE#b", ...PERMS } } }))).toBe(30_000); + expect(followEvery(derive({}))).toBeNull(); + }); +}); diff --git a/dashboard/e2e/update-states.spec.ts b/dashboard/e2e/update-states.spec.ts index fbf5c0e9..e0977052 100644 --- a/dashboard/e2e/update-states.spec.ts +++ b/dashboard/e2e/update-states.spec.ts @@ -272,7 +272,7 @@ test.describe("Version and updates: every state", () => { await page.goto("/settings/system/"); await expect(status(page)).toHaveAttribute("data-state", "preparing"); await expect(status(page)).toContainText("Preparing the update to v0.9.0"); - await expect(status(page)).toContainText("Step 1 of 2"); + await expect(status(page).getByTestId("update-steps").locator('[aria-current="step"]')).toHaveAttribute("data-step", "prepare"); await expect(page.getByTestId("release-check")).toHaveCount(0); await shoot(page, "11-preparing"); }); @@ -281,7 +281,7 @@ test.describe("Version and updates: every state", () => { await setup(page, { version: { latest: LATEST, update_available: true, running: true, native: { stack: "coderhelm-acme", can_apply: true, auto_apply: true, pending: { ...PREPARED, status: "running" } }, history: [{ id: "UPDATE#2", version: "v0.9.0", from_version: "v0.8.32", actor: "admin@acme.example", mode: "update", status: "running", started_at: ago(6) }, ...OK_HISTORY] } }); await page.goto("/settings/system/"); await expect(status(page)).toHaveAttribute("data-state", "updating"); - await expect(status(page)).toContainText("Updating to v0.9.0"); + await expect(status(page)).toContainText("Applying v0.9.0"); await expect(status(page)).toContainText("Started 6 min ago"); await expect(status(page)).toContainText("It changes 7 resources"); await expect(status(page)).not.toContainText("coderhelm-acme"); @@ -391,3 +391,213 @@ test.describe("Version and updates: every state", () => { await shoot(page, "20-updater-down"); }); }); + +// ── One truthful state, from the payloads seen on a live install ────────── +// +// The Version card shows exactly one state, from lib/update-state.ts. These +// feed the page the contradictory payloads observed live and the states the +// updater moves through, and check there is one status, saying one thing. + +const OLD = "v0.8.37"; +const NEW = "v0.8.39"; +const PERMS = { can_apply: true, confirm: "c".repeat(64), data_changes: [], permission_changes: ["Api.NewRole (AWS::IAM::Role Add: an IAM change)"], admin_changes: [] }; +const LIVE_LATEST = { ...LATEST, version: NEW }; +const STALE_PENDING_CHECK = { version: NEW, checked_at: ago(120), started_at: ago(120), ok: false, pending: true, results: [], note: "checking the release's signature before reading the models it calls" }; +const PENDING_BLOCKER = { key: "model_check_pending", severity: "block", detail: `Checking ${NEW}'s signature before reading the models it calls.`, fix: { text: "Wait a few minutes, then check again." } }; +const row = (id: string, version: string, status: string, min: number, extra: Record = {}) => ({ id, version, from_version: "v0.8.32", actor: "owner@example.org", mode: "update", status, started_at: ago(min), ...extra }); + +/** Nothing but the one status talks about the update. */ +async function oneState(page: Page) { + await expect(page.getByTestId("update-status")).toHaveCount(1); + await expect(page.getByTestId("native-update")).toHaveCount(await page.getByTestId("update-status").getByTestId("native-update").count()); + await expect(page.locator("main")).not.toContainText("Ready to update"); + await expect(page.locator("main")).not.toContainText("What stops an update"); + await expect(page.locator("main")).not.toContainText("Blocks the update"); +} + +test.describe("Version and updates: one truthful state", () => { + test("observed: an older update waiting, a newer one prepared, and a stale Checking: one state, the newer update", async ({ page }) => { + await setup(page, { + version: { + latest: LIVE_LATEST, update_available: true, + native: { stack: "coderhelm-example", can_apply: true, auto_apply: true, pending: { version: OLD, status: "review", id: "UPDATE#a", counts: { add: 1, modify: 3, remove: 0 }, ...PERMS } }, + history: [row("UPDATE#b", NEW, "review", 10), row("UPDATE#a", OLD, "review", 60), ...OK_HISTORY], + model_check: STALE_PENDING_CHECK, + }, + blockers: [PENDING_BLOCKER], + }); + await page.goto("/settings/system/"); + await oneState(page); + await expect(status(page)).toHaveAttribute("data-state", "preparing"); + await expect(status(page)).toContainText(`Preparing the update to ${NEW}`); + await expect(page.locator("main")).not.toContainText(`${OLD} needs your OK`); + await expect(page.locator("main")).not.toContainText(`Checking ${NEW}`); + await expect(page.getByRole("button", { name: "Review and apply" })).toHaveCount(0); + await shoot(page, "21-observed-contradiction"); + }); + + test("the same install once the updater reconciled it: v0.8.39 needs your OK, the permission list in the dialog", async ({ page }) => { + await setup(page, { + version: { + latest: LIVE_LATEST, update_available: true, + native: { stack: "coderhelm-example", can_apply: true, auto_apply: true, pending: { ...PREPARED, version: NEW, id: "UPDATE#b", execution: "AVAILABLE", ...PERMS } }, + history: [row("UPDATE#b", NEW, "review", 10), row("UPDATE#a", OLD, "superseded", 60, { reason: `replaced by the update to ${NEW} before it was applied; nothing was changed` }), ...OK_HISTORY], + model_check: { ...STALE_PENDING_CHECK, pending: false, ok: true, checked_at: ago(10) }, + }, + }); + await page.goto("/settings/system/"); + await oneState(page); + await expect(status(page)).toHaveAttribute("data-state", "review"); + await expect(status(page)).toContainText(`${NEW} needs your OK`); + await expect(status(page).getByTestId("update-steps").locator('[aria-current="step"]')).toContainText("waits for your OK"); + await expect(page.locator("main")).not.toContainText(OLD + " needs"); + // History keeps the older one as replaced, never as a second update waiting. + await expect(page.getByTestId("update-history").locator("li").nth(1).getByTestId("history-status")).toHaveText("Replaced"); + // Install health is its own section and never reads as an update state. + await expect(page.getByTestId("health-summary")).toHaveText("All 9 checks pass"); + await shoot(page, "22-needs-your-ok"); + await status(page).getByRole("button", { name: "Review and apply" }).click(); + await expect(page.getByTestId("native-update-permission-changes")).toContainText("Api.NewRole"); + }); + + test("observed: executed in the AWS console while the entry said review: Applying, never Review and apply", async ({ page }) => { + await setup(page, { + version: { + latest: LIVE_LATEST, update_available: true, running: true, + native: { stack: "coderhelm-example", can_apply: true, auto_apply: true, pending: { ...PREPARED, version: NEW, id: "UPDATE#b", status: "review", execution: "EXECUTE_IN_PROGRESS", ...PERMS } }, + history: [row("UPDATE#b", NEW, "review", 10), ...OK_HISTORY], + }, + }); + await page.goto("/settings/system/"); + await oneState(page); + await expect(status(page)).toHaveAttribute("data-state", "updating"); + await expect(status(page)).toContainText(`Applying ${NEW}`); + await expect(page.getByRole("button", { name: "Review and apply" })).toHaveCount(0); + await expect(page.getByTestId("native-update-apply")).toHaveCount(0); + }); + + test("applied in the AWS console, as the updater reports it: who applied it", async ({ page }) => { + await setup(page, { + version: { + latest: LIVE_LATEST, update_available: true, running: true, + native: { stack: "coderhelm-example", can_apply: true, auto_apply: true, pending: { ...PREPARED, version: NEW, id: "UPDATE#b", status: "running", applied_by: "someone in the AWS console", executed_at: ago(4) } }, + history: [row("UPDATE#b", NEW, "running", 10), ...OK_HISTORY], + }, + }); + await page.goto("/settings/system/"); + await expect(status(page)).toHaveAttribute("data-state", "updating"); + await expect(page.getByTestId("native-update-progress")).toContainText("It was applied in the AWS console."); + await shoot(page, "23-applied-in-console"); + }); + + test("checking: the step, when it started, nothing to press, and it moves on by itself", async ({ page }) => { + const m = { + version: { latest: LIVE_LATEST, update_available: true, model_check: { ...STALE_PENDING_CHECK, checked_at: ago(2), started_at: ago(2), progress: { step: "signature", started_at: ago(2), build: "IN_PROGRESS" } } } as Record, + blockers: [PENDING_BLOCKER] as unknown[], + }; + await page.clock.install({ time: new Date(NOW) }); + await setup(page, m); + await page.goto("/settings/system/"); + await oneState(page); + await expect(status(page)).toHaveAttribute("data-state", "checking-release"); + await expect(status(page)).toContainText(`Checking ${NEW} before it can be applied`); + await expect(page.getByTestId("update-checking")).toContainText("Started 2 min ago"); + await expect(status(page).getByTestId("update-steps").locator('[aria-current="step"]')).toHaveAttribute("data-step", "check"); + await expect(status(page).getByRole("button")).toHaveCount(0); + await shoot(page, "24-checking"); + // The check passes: the next poll shows the update, no reload. + m.version.model_check = { version: NEW, checked_at: ago(0), ok: true, results: [] }; + m.blockers = []; + await page.clock.fastForward(11_000); + await expect(status(page)).toHaveAttribute("data-state", "available"); + await expect(status(page).getByRole("button", { name: `Update to ${NEW}` })).toBeVisible(); + }); + + test("a check that stopped reporting: stalled with its reason and Check again, never Checking forever", async ({ page }) => { + const { calls } = await setup(page, { + version: { latest: LIVE_LATEST, update_available: true, model_check: { version: NEW, checked_at: ago(40), ok: false, pending: false, stalled: true, results: [], note: `Checking ${NEW} didn't finish: the release check build ended FAILED without reporting back. Check again to start it over.` } }, + blockers: [{ key: "model_check_stalled", severity: "block", detail: "stalled", fix: { text: "Check again to start the release check over." } }], + }); + await page.goto("/settings/system/"); + await oneState(page); + await expect(status(page)).toHaveAttribute("data-state", "check-stalled"); + await expect(status(page)).toContainText(`Checking ${NEW} didn't finish`); + await expect(page.getByTestId("update-check-stalled")).toContainText("ended FAILED without reporting back"); + await shoot(page, "25-check-stalled"); + await status(page).getByRole("button", { name: "Check again" }).click(); + await expect.poll(() => calls).toContain("/api/system/update-check"); + }); + + test("an older updater's pending check past its time bound reads as stalled", async ({ page }) => { + await setup(page, { version: { latest: LIVE_LATEST, update_available: true, model_check: STALE_PENDING_CHECK }, blockers: [PENDING_BLOCKER] }); + await page.goto("/settings/system/"); + await oneState(page); + await expect(status(page)).toHaveAttribute("data-state", "check-stalled"); + await expect(status(page)).toContainText("didn't finish within 30 minutes"); + }); + + test("preparing, then waiting for the OK, then applying, then updated: without a reload", async ({ page }) => { + const m = { + version: { + latest: LIVE_LATEST, update_available: true, + native: { stack: "coderhelm-example", can_apply: true, auto_apply: true, pending: { version: NEW, status: "preparing", id: "UPDATE#b", actor: "owner@example.org", started_at: ago(1) } }, + history: [row("UPDATE#b", NEW, "preparing", 1), ...OK_HISTORY], + } as Record, + }; + await page.clock.install({ time: new Date(NOW) }); + await setup(page, m); + await page.goto("/settings/system/"); + await expect(status(page)).toHaveAttribute("data-state", "preparing"); + await expect(page.getByTestId("native-update-progress")).toContainText("by owner@example.org"); + // The change set is ready and changes IAM: it waits for the OK. + m.version.native = { stack: "coderhelm-example", can_apply: true, auto_apply: true, pending: { ...PREPARED, version: NEW, id: "UPDATE#b", execution: "AVAILABLE", ...PERMS } }; + m.version.history = [row("UPDATE#b", NEW, "review", 2), ...OK_HISTORY]; + await page.clock.fastForward(11_000); + await expect(status(page)).toHaveAttribute("data-state", "review"); + // Executed (here or in the console): applying. + m.version.running = true; + m.version.native = { stack: "coderhelm-example", can_apply: true, auto_apply: true, pending: { ...PREPARED, version: NEW, id: "UPDATE#b", status: "running", execution: "EXECUTE_IN_PROGRESS", executed_at: ago(0) } }; + await page.clock.fastForward(31_000); + await expect(status(page)).toHaveAttribute("data-state", "updating"); + // Done: the install runs v0.8.39. + m.version.running = false; + m.version.native = { stack: "coderhelm-example", can_apply: true, auto_apply: true, pending: null }; + m.version.latest = null; + m.version.update_available = false; + m.version.current = { version: NEW, commit: null, released_at: null, config_fingerprint: null }; + m.version.history = [row("UPDATE#b", NEW, "succeeded", 20, { finished_at: ago(0) }), ...OK_HISTORY]; + await page.clock.fastForward(16_000); + await expect(status(page)).toHaveAttribute("data-state", "current"); + await expect(status(page)).toContainText(`Updated to ${NEW}`); + }); +}); + +test.describe("Uninstall: one clean card", () => { + test("dark mode: no box inside the box, the theme's border colour, and a guide link that says what it does", async ({ page }) => { + await page.emulateMedia({ colorScheme: "dark" }); + await setup(page, { version: { uninstall: { delete_data: false, changed_by: null, changed_at: null } } }); + await page.goto("/settings/system/#uninstall"); + const card = page.locator("#uninstall > div").first(); + const choice = page.getByTestId("uninstall-data"); + await expect(choice).toBeVisible(); + const cardBorder = await card.evaluate((e) => getComputedStyle(e).borderTopColor); + const box = await choice.evaluate((e) => { + const c = getComputedStyle(e); + return { left: c.borderLeftWidth, right: c.borderRightWidth, radius: c.borderTopLeftRadius, top: c.borderTopColor }; + }); + // A row of the card, split by the card's own divider: no nested border, no bright outline. + expect(box.left).toBe("0px"); + expect(box.right).toBe("0px"); + expect(box.radius).toBe("0px"); + expect(box.top).toBe(cardBorder); + expect(box.top).not.toBe("rgb(255, 255, 255)"); + const link = page.getByTestId("uninstall-link"); + await expect(link).toHaveText(/Open the uninstall guide/); + await expect(link).toHaveAttribute("target", "_blank"); + await expect(page.getByTestId("uninstall-link-note")).toHaveText("Opens the guide in a new tab. Nothing is deleted from here."); + // Turning on "delete everything" still needs the install's name typed back. + await page.getByTestId("uninstall-data-ask").click(); + await expect(page.getByTestId("uninstall-data-delete")).toBeDisabled(); + if (SHOTS) await page.locator("#uninstall").screenshot({ path: path.join(SHOTS, "26-uninstall-dark.png") }); + }); +}); diff --git a/dashboard/src/app/settings/system/page.tsx b/dashboard/src/app/settings/system/page.tsx index 07ea2c2a..6649f037 100644 --- a/dashboard/src/app/settings/system/page.tsx +++ b/dashboard/src/app/settings/system/page.tsx @@ -2,12 +2,13 @@ import { useCallback, useEffect, useState, type ReactNode } from "react"; import Link from "next/link"; -import { api, type AutoUpdateSettings, type SystemPreflight, type SystemVersion, type UpdateBlocker, type UpdateEntry } from "@/lib/api"; +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 { CheckRow } from "@/components/install-checks"; import { DomainSection } from "@/components/domain-section"; import { HybridSection } from "@/components/hybrid-section"; import { UninstallSection } from "@/components/uninstall-section"; -import { NativeUpdateCard } from "@/components/native-update"; +import { NativeUpdateCard, UpdateSteps } from "@/components/native-update"; import { ModelsSection, UpdateNeedsAction } from "@/components/models-section"; import { CodeBlock } from "@/components/code-block"; import { Code } from "@/components/settings/code"; @@ -48,6 +49,7 @@ const STATUS: Record { load(); }, [load]); - // While an update prepares or runs, follow it: the card and the history - // move along without a reload (the updater checks the stack every 5 minutes). - const following = !!data && (!!data.running || ["preparing", "running"].includes(data.native?.pending?.status ?? "")); + // The one update state, derived in one place (lib/update-state.ts). + const state: UpdateState | null = data ? deriveUpdateState(data, pre) : null; + // 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 + // preparing to waiting for the OK to applying to done without a reload. + const every = state ? followEvery(state) : null; useEffect(() => { - if (!following) return; + if (!every) return; const t = window.setInterval(() => { if (document.visibilityState === "visible") load(); - }, 30_000); + }, every); return () => window.clearInterval(t); - }, [following, load]); + }, [every, load]); const header = (
@@ -171,7 +177,7 @@ function System() { ); } - if (!data) { + if (!data || !state) { return ( {header} @@ -188,19 +194,15 @@ function System() { const latest = data.latest; const history = data.history ?? []; const canRollBack = history.some((h) => h.status === "succeeded" && h.from_version); - // A prepared or applying update is shown once, in its own card, with the - // one thing to do; it is never also listed as something blocking itself. - const pending = data.native?.pending ?? null; - const failure = failedTry(data, pre); - // What stops an update now: install checks that fail (listed under Install - // health), or an updater that didn't answer. The update itself (running, - // or its last try) and the model check have their own status, and a major - // release's notes are said in the status, so none of those repeat here. + // Install checks that fail and stop an update: marked under Install health + // (the status says "can't install yet" and points there). Nothing else on + // the page repeats the update state. 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 hold: UpdateHold = { checks: blocking.size, updater: blockers.find((b) => b.key === "updater") ?? null }; - const modelBlock = !!latest && data.model_check?.version === latest.version && !data.model_check.ok; + const busyUpdating = ["applying", "preparing", "review"].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 { @@ -247,30 +249,24 @@ function System() {
start("update")} onChanged={load} onModelChecked={(c) => { setData({ ...data, model_check: c }); loadPreflight(); + load(); }} onSkipModel={() => start("update", true)} /> - {failure && modelBlock && ( -
- { setData({ ...data, model_check: c }); loadPreflight(); }} onSkip={() => start("update", true)} /> -
- )} - {!data.running && !pending && data.current.version && } + {!busyUpdating && data.current.version && }
- {latest && !pending && } + {latest && offered && }
@@ -411,7 +407,7 @@ function System() { )}
-
@@ -430,42 +426,6 @@ function System() { /** Where release commits live: the commit a release was built from links here. */ const RELEASE_REPO_URL = "https://github.com/coderhelm/coderhelm-platform"; -/** The last try at an update that didn't land, while this install is still not on it. */ -interface FailedTry { - version: string; - status: "failed" | "rolled_back" | "not_started"; - /** The updater's reason: shown as is only when it reads as a sentence. */ - reason: string | null; - from: string | null; - startedAt: string | null; -} - -/** - * The newest update in the history, when it didn't succeed and this install - * isn't on that version (a later success, or a roll back an admin chose, - * ends it). Older updaters only say so in the readiness blocker. - */ -function failedTry(data: SystemVersion, pre: SystemPreflight | null): FailedTry | null { - if (data.running || data.native?.pending) return null; - const last = (data.history ?? []).find((h) => h.mode !== "rollback"); - const newest = (data.history ?? [])[0]; - if (last && newest === last && ["failed", "rolled_back", "not_started"].includes(last.status) && last.version !== data.current.version) { - return { - version: last.version, - status: last.status as FailedTry["status"], - reason: last.reason ?? null, - from: last.from_version ?? data.current.version, - startedAt: last.started_at ?? null, - }; - } - const b = pre?.blockers.find((x) => x.key === "failed_before"); - if (b && data.latest) { - const m = b.detail.match(/didn't succeed: (.*?)\.?$/); - return { version: data.latest.version, status: "rolled_back", reason: m?.[1] ?? null, from: data.current.version, startedAt: null }; - } - return null; -} - /** Raw AWS text (an ARN, a resource type, a handler error) belongs under Technical details. */ function isRawReason(r: string): boolean { return /arn:aws|[A-Z][A-Za-z0-9]+::[A-Z][A-Za-z0-9]+|Resource handler returned|\bstatus code\b|Exception\b|\bRequestId\b/i.test(r) || r.length > 240; @@ -476,13 +436,6 @@ function sentence(r: string): string { return `${t.charAt(0).toUpperCase()}${t.slice(1)}.`; } -/** The update in progress: its version and when it started, from the history. */ -function runningTry(data: SystemVersion): UpdateEntry | null { - const h = data.history ?? []; - const id = data.native?.pending?.id; - return (id ? h.find((e) => e.id === id) : undefined) ?? h.find((e) => e.status === "running" || e.status === "preparing") ?? null; -} - /** An indeterminate bar: an update has no reliable percentage. */ function Working({ label }: { label: string }) { return ( @@ -499,14 +452,6 @@ function windowText(s: AutoUpdateSettings | undefined): string | null { return `${day} at ${String(s.hour).padStart(2, "0")}:00 ${s.timezone.replace(/_/g, " ")}`; } -/** Why an update can't start now, from the preflight: failing install checks, or an updater that didn't answer. */ -interface UpdateHold { - /** Install checks that fail and stop an update (shown under Install health). */ - checks: number; - /** The updater in the AWS account didn't answer. */ - updater: UpdateBlocker | null; -} - function plural(n: number, one: string, many = `${one}s`) { return `${n} ${n === 1 ? one : many}`; } @@ -522,230 +467,275 @@ function StatusCard({ state, variant, title, children, actions }: { state: strin ); } -/** The newest update succeeded in the last day and is what runs: "Updated to v0.8.32". */ -function recentSuccess(data: SystemVersion): UpdateEntry | null { - const newest = (data.history ?? [])[0]; - if (!newest || newest.mode === "rollback" || newest.status !== "succeeded" || newest.version !== data.current.version) return null; - const at = newest.finished_at ?? newest.started_at; - if (!at || Date.now() - new Date(at).getTime() > 24 * 3600_000) return null; - return newest; -} - /** * The one status at the top of Version, about updates only (the install's - * own health is its own section): up to date, a release to install, one on - * its way, or the last one that didn't work, each with the one thing to do. + * own health is its own section). It renders exactly the state + * deriveUpdateState chose, nothing else: one headline, one line of detail, + * one thing to do. */ function UpdateStatus({ + state, data, - failure, - hold, - modelBlock, busy, onUpdate, onChanged, onModelChecked, onSkipModel, }: { + state: UpdateState; data: SystemVersion; - failure: FailedTry | null; - hold: UpdateHold; - /** The release's model check holds it (or is still running). */ - modelBlock: boolean; busy: "" | "update" | "rollback"; onUpdate: () => void; onChanged: () => void; - onModelChecked: (c: SystemVersion["model_check"]) => void; + onModelChecked: (c: ModelCheck | null) => void; onSkipModel: () => void; }) { const current = data.current.version; const latest = data.latest; - const pending = data.native?.pending ?? null; const on = current ?? "a development build"; const auto = windowText(data.settings); const beta = withChannel(data.settings).channel === "beta"; const healthLink = See install health; + const id = STATE_ID[state.kind]; + + switch (state.kind) { + case "applying": + if (state.pending && data.native) { + return ( +
+ +
+ ); + } + return ( + Updating to {state.version}…}> +

+ {state.startedAt ? <>Started

+ +
+ ); + + case "preparing": + case "review": + return ( +
+ +
+ ); + + case "checking": + return ( + Checking {state.version} before it can be applied}> +

+ {state.startedAt ? <>Started

+ + +
+ ); + + case "check-stalled": + return ( +
+ Checking {state.version} didn't finish} + actions={} + > +

{state.note}

+

Nothing was changed: you're on {on}. The update waits until the release is checked.

+
+
+ ); - if (pending) { - const t = runningTry(data); - return ( -
- -
- ); - } - - if (data.running) { - const t = runningTry(data); - const to = t?.version ?? latest?.version ?? "the new version"; - return ( - Updating to {to}…}> -

- {t?.started_at ? <>Started

- -
- ); - } - - if (failure) { - const plain = failure.reason && !isRawReason(failure.reason) ? sentence(failure.reason) : null; - const retry = latest?.version === failure.version; - const held = modelBlock || hold.checks > 0 || !!hold.updater; - const title = - failure.status === "not_started" - ? <>The update to {failure.version} couldn't start - : failure.status === "rolled_back" - ? <>The update to {failure.version} didn't finish - : <>The update to {failure.version} stopped partway; - return ( - - {retry && ( - - )} - {healthLink} - {failure.status === "failed" && Roll back} - - } - > -

- {failure.status === "failed" - ? <>Coderhelm may not be fully working: it reports {on}. - : <>Nothing changed: you're still on {on}, and your data is untouched.} - {failure.startedAt ? <> Tried

-

- {plain ?? "AWS stopped it with an error; its own message is under Technical details."} -

-

- {held - ? "Fix what Install health lists, then try again." - : failure.status === "failed" + case "needs-action": + return ( +

+ +
+ ); + + case "failed": { + const failure = state.failure; + const plain = failure.reason && !isRawReason(failure.reason) ? sentence(failure.reason) : null; + const retry = latest?.version === failure.version; + const title = + failure.status === "not_started" + ? <>The update to {failure.version} couldn't start + : failure.status === "rolled_back" + ? <>The update to {failure.version} didn't finish + : <>The update to {failure.version} stopped partway; + return ( + + {retry && ( + + )} + {healthLink} + {failure.status === "failed" && Roll back} + + } + > +

+ {failure.status === "failed" + ? <>Coderhelm may not be fully working: it reports {on}. + : <>Nothing changed: you're still on {on}, and your data is untouched.} + {failure.startedAt ? <> Tried

+

+ {plain ?? "AWS stopped it with an error; its own message is under Technical details."} +

+

+ {failure.status === "failed" ? "Fix what Install health lists and try again, or roll back under Update history." : "If Install health below lists a check that fails, fix it first."} - {failure.status !== "not_started" ? ` Automatic updates skip ${failure.version} until it works.` : ""} -

-
- ); - } - - if (latest && modelBlock && data.model_check) { - return ( -
- -
- ); - } - - if (latest && hold.updater) { - return ( - {latest.version} is available, but can't install from here}> -

You're on {on}. The updater in your AWS account didn't answer, so update from your machine instead:

-
-
- ); - } - - if (latest && hold.checks > 0) { - return ( - {latest.version} is available, but can't install yet} - actions={See what to fix} - > -

- You're on {on}. Fix the {hold.checks === 1 ? "install check" : `${hold.checks} install checks`} marked Stops updates below, then update. -

-
- ); - } - - if (latest) { - const majorWaits = latest.breaking && data.settings?.majors !== "auto"; - return ( - - {latest.version} is available - {latest.breaking && Major release} - {latest.prerelease && Beta} - - } - actions={ - - } - > -

- You're on {on}.{latest.published_at ? <> {latest.version} came out

- {latest.breaking && ( -

- Its notes ask you to do something before or after updating: read them below first.{auto ? " Major releases wait for you, even with automatic updates on." : ""} + {failure.status !== "not_started" ? ` Automatic updates skip ${failure.version} until it works.` : ""}

- )} - {latest.prerelease &&

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

} -
- ); - } - - const behind = data.releases?.behind; - if (behind && current) { - return ( - {behind.version} is out, but can't install yet}> -

You're on {current}. GitHub's release list doesn't show {behind.version} yet, which usually takes a few minutes. Check for updates again shortly.

-
- ); - } - - if (!current) { - return ( - -

This install was deployed from source, not a published release, so there is no version to compare with new releases.

-
- ); - } +
+ ); + } - if (data.releases?.error) { - return ( - -

GitHub didn't answer, so it isn't known whether a newer release is out. You're on {current}.

-
- ); - } + case "updater-down": + return ( + {state.version} is available, but can't install from here}> +

You're on {on}. The updater in your AWS account didn't answer, so update from your machine instead:

+
+
+ ); + + case "blocked": + return ( + {state.version} is available, but can't install yet} + actions={See what to fix} + > +

+ You're on {on}. Fix the {state.checks === 1 ? "install check" : `${state.checks} install checks`} marked Stops updates below, then update. +

+
+ ); + + case "available": { + const l = latest!; + const majorWaits = l.breaking && data.settings?.majors !== "auto"; + return ( + + {l.version} is available + {l.breaking && Major release} + {l.prerelease && Beta} + + } + actions={ + + } + > +

+ You're on {on}.{l.published_at ? <> {l.version} came out

+ {l.breaking && ( +

+ Its notes ask you to do something before or after updating: read them below first.{auto ? " Major releases wait for you, even with automatic updates on." : ""} +

+ )} + {l.prerelease &&

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

} +
+ ); + } - if (data.releases && !data.releases.fetched_at) { - return ( - -

You're on {current}. Check for updates to see whether a newer release is out.

-
- ); + case "behind": + return ( + {state.version} is out, but can't install yet}> +

You're on {current}. GitHub's release list doesn't show {state.version} yet, which usually takes a few minutes. Check for updates again shortly.

+
+ ); + + case "development": + return ( + +

This install was deployed from source, not a published release, so there is no version to compare with new releases.

+
+ ); + + case "unreachable": + return ( + +

GitHub didn't answer, so it isn't known whether a newer release is out. You're on {current}.

+
+ ); + + case "not-checked": + return ( + +

You're on {current}. Check for updates to see whether a newer release is out.

+
+ ); + + case "current": { + const done = state.done; + const channel = beta ? " on the Beta (nightly) channel" : ""; + return ( + Updated to {current} : "You're up to date"}> +

+ {done + ? <>Finished

+
+ ); + } } +} - const done = recentSuccess(data); - const channel = beta ? " on the Beta (nightly) channel" : ""; +/** Starts the release check over (a check that stalled), then the page reads the state again. */ +function CheckAgain({ onChecked }: { onChecked: (c: ModelCheck | null) => void }) { + const { toast } = useToast(); + const [busy, setBusy] = useState(false); return ( - Updated to {current} : "You're up to date"}> -

- {done - ? <>Finished

-
+ ); } diff --git a/dashboard/src/components/models-section.tsx b/dashboard/src/components/models-section.tsx index 47b3218b..029e025a 100644 --- a/dashboard/src/components/models-section.tsx +++ b/dashboard/src/components/models-section.tsx @@ -270,6 +270,20 @@ export function UpdateNeedsAction({ check, onChecked, onSkip }: { check: ModelCh ); } const failing = mc.results.filter((r) => r.status === "fail"); + if (mc.stalled || failing.length === 0) { + // The release check stopped reporting, or couldn't verify the release: + // it holds the update, with its reason, never "Checking" forever. + return ( + api.checkUpdateModels().then((r) => { setMc(r.model_check); onChecked?.(r.model_check); }).catch(() => {})}>Check again} + > +

{mc.note ?? "The release check didn't report back."}

+
+ ); + } const again = async () => { setBusy(true); try { diff --git a/dashboard/src/components/native-update.tsx b/dashboard/src/components/native-update.tsx index e9a201a4..fbd8260c 100644 --- a/dashboard/src/components/native-update.tsx +++ b/dashboard/src/components/native-update.tsx @@ -9,24 +9,73 @@ import { Modal, modalActions } from "@/components/modal"; import { useToast } from "@/components/toast"; import { primaryButton, secondaryButton } from "@/components/ui"; +/** Where an update is: the release checked, the change prepared, the change applied. */ +export type UpdateStep = "check" | "prepare" | "apply"; + +const STEPS: [UpdateStep, string][] = [ + ["check", "Check the release"], + ["prepare", "Prepare the change"], + ["apply", "Apply it"], +]; + +/** + * The three steps of an update and where it is, in words (no made-up + * percentage: AWS gives none). `waiting` names why the current step waits. + */ +export function UpdateSteps({ at, waiting }: { at: UpdateStep; waiting?: string }) { + const i = STEPS.findIndex(([k]) => k === at); + return ( +
    + {STEPS.map(([k, label], n) => { + const state = n < i ? "done" : n === i ? "current" : "todo"; + return ( +
  1. + + {label} + {state === "done" ? (done) : null} + {state === "current" && waiting ? ({waiting}) : null} +
  2. + ); + })} +
+ ); +} + /** * A native install updates as a CloudFormation stack update. The updater * prepares each release as a change set on the install's stack and applies * it through the install's deploy role. This shows it preparing and - * running, and when it waits for an admin, why: data or permission changes + * applying, and when it waits for an admin, why: data or permission changes * to confirm here (then Apply), or a change to the deploy role or a - * boundary that only an AWS admin can execute in the console. + * boundary that only an AWS admin can execute in the console. Which of + * those it is comes from the page's one update state (`phase`), never from + * the stored status alone: a change set executed in the AWS console is + * applying, whatever the entry said. */ export function NativeUpdateCard({ native, + phase, onChanged, startedAt, + startedBy, + appliedBy, from, }: { native: NativeUpdate; + phase: "preparing" | "review" | "applying"; onChanged?: () => void; - /** When this update started (its history row), for "Started 3 minutes ago". */ + /** When this update started (or was applied), for "Started 3 minutes ago". */ startedAt?: string | null; + /** Who started it, in words. */ + startedBy?: string | null; + /** Who applied it: an admin here, or someone in the AWS console. */ + appliedBy?: string | null; /** The version the install is on while it updates. */ from?: string | null; }) { @@ -37,7 +86,7 @@ export function NativeUpdateCard({ if (!p) return null; const n = p.counts ?? { add: 0, modify: 0, remove: 0 }; const total = n.add + n.modify + n.remove; - const waiting = p.status === "review"; + const waiting = phase === "review"; const canApply = waiting && !!p.can_apply && !!p.id; const data = p.data_changes ?? []; const perms = p.permission_changes ?? []; @@ -65,10 +114,11 @@ export function NativeUpdateCard({ ? `${version} needs your OK` : `${version} is ready to apply` : `${version} needs an AWS admin` - : p.status === "preparing" + : phase === "preparing" ? `Preparing the update to ${version}…` - : `Updating to ${version}…`; + : `Applying ${version}…`; const working = !waiting; + const outside = !!appliedBy && /aws console/i.test(appliedBy); return (
@@ -76,12 +126,16 @@ export function NativeUpdateCard({ {working && ( <>

- {startedAt ? <>Started

+
-
+
)} @@ -104,9 +158,10 @@ export function NativeUpdateCard({ ? "It changes the deploy role or a permissions boundary, which Coderhelm can't apply for itself. Someone with administrator rights in the AWS account opens it in the AWS console and chooses Execute." : "This install's stack doesn't have the deploy role yet, so this one update is executed in the AWS console by someone with administrator rights in the account. It adds the role; every update after it applies from here."}

- ) : p.status === "preparing" ? ( + ) : phase === "preparing" ? (

Nothing to do yet. If it would change data or permissions, it asks you here first.

) : null} + {waiting ? : null} {p.reason && !waiting ?

{p.reason}

: null}

{canApply ? ( diff --git a/dashboard/src/components/uninstall-section.tsx b/dashboard/src/components/uninstall-section.tsx index 704f4d4e..e3247f3a 100644 --- a/dashboard/src/components/uninstall-section.tsx +++ b/dashboard/src/components/uninstall-section.tsx @@ -3,6 +3,7 @@ import { useEffect, useState } from "react"; import { api, type HybridStatus, type SystemVersion, type UninstallMode } from "@/lib/api"; import { Callout } from "@/components/callout"; +import { ExternalLinkIcon } from "@/components/icons"; import { dangerButton, inputClass, secondaryButton, smallDangerButton } from "@/components/ui"; /** The uninstall page on the docs site (docs.coderhelm.com/self-host/uninstall/). */ @@ -21,7 +22,8 @@ export function uninstallLink(install: SystemVersion["install"], hybrid: HybridS /** * Keep the data, or delete everything when the stack is deleted. Nothing is * deleted here: the stack's own delete reads the choice. Turning on needs - * the install's name typed back. + * the install's name typed back. One row of the Uninstall card, not a box + * inside it. */ function DataChoice({ stage, initial }: { stage: string; initial: UninstallMode }) { const [mode, setMode] = useState(initial); @@ -44,15 +46,15 @@ function DataChoice({ stage, initial }: { stage: string; initial: UninstallMode } }; return ( -

-

When Coderhelm is uninstalled

+
+

When Coderhelm is uninstalled

{mode.delete_data ? ( Deleting the stack also deletes the tables, data bucket, sign-in users and secret, and schedules the KMS keys for deletion (AWS's 7-day minimum). {mode.changed_by ? ` Turned on by ${mode.changed_by}.` : ""} Nothing is deleted until the stack is. ) : ( -

+

Keep my data: deleting the stack removes Coderhelm, and the tables, data bucket, keys, sign-in users and secret stay.

)} @@ -62,7 +64,7 @@ function DataChoice({ stage, initial }: { stage: string; initial: UninstallMode ) : asking ? (
-