feat(app): update the web app and PWA in place (#61995)

This commit is contained in:
Luke Parker
2026-11-05 01:05:51 -06:00
committed by GitHub
Unverified
parent 0b21b761aa
commit 4fa365faf5
8 changed files with 771 additions and 11 deletions
+79 -2
View File
@@ -10,6 +10,11 @@ import { fileURLToPath } from "node:url"
import { build } from "vite"
import { onDemandAsset, serviceWorker } from "../../vite.pwa"
// The updater the web app ships (Settings › Updates and the titlebar), built into the fixture pages.
const updaterDriver = fileURLToPath(
new URL("../../../gui-plugins/src/updater/web-driver.ts", import.meta.url),
).replaceAll("\\", "/")
type Site = {
url: string
deploy: (fault?: "failed" | "html" | "corrupt" | "mixed-html" | "blocked") => void
@@ -35,7 +40,20 @@ const fixture = test.extend<{ site: Site }, { builds: Record<string, Record<stri
"main.js": `document.querySelector("h1").textContent = "${version}";
document.querySelector("button").onclick = async () => {
document.querySelector("output").textContent = await (await import("./lazy.js")).load()
};`,
};
// ?updater runs the web app's real update driver, with its actions as buttons.
if (location.search.includes("updater")) import(${JSON.stringify(updaterDriver)}).then(({ startWebUpdater }) => {
const state = Object.assign(document.createElement("p"), { ariaLabel: "Update state" });
const announced = Object.assign(document.createElement("p"), { ariaLabel: "Update offered" });
const updater = startWebUpdater({
changed: (next) => (state.textContent = next.status),
announce: () => (announced.textContent = "yes"),
report: () => {},
});
state.textContent = updater.state().status;
const action = (name, run) => Object.assign(document.createElement("button"), { textContent: name, onclick: run });
document.body.append(state, announced, action("Check for updates", updater.check), action("Update now", updater.apply), action("Reload from server", updater.reset));
});`,
"lazy.js": `export async function load() { return (await import("./nested.js")).value }`,
"nested.js": `export const value = "${version} nested lazy loaded"`,
"public/nested/data.json": JSON.stringify({ version }),
@@ -286,7 +304,9 @@ fixture(
replacement.evaluate(() => {
// This runs in the service worker, whose global scope holds its registration.
const registration =
"registration" in self && self.registration instanceof ServiceWorkerRegistration ? self.registration : undefined
"registration" in self && self.registration instanceof ServiceWorkerRegistration
? self.registration
: undefined
return { waiting: !!registration?.waiting, active: registration?.active?.state }
}),
@@ -301,6 +321,63 @@ fixture(
},
)
fixture(
"the updater offers a new build and moves every open tab to it with one click",
async ({ page, context, site }) => {
await install(page, `${site.url}/?updater`)
await expect(page.getByLabel("Update state")).toHaveText("idle")
const second = await context.newPage()
await second.goto(`${site.url}/?updater`)
await expect(second.getByLabel("Update state")).toHaveText("idle")
site.deploy()
await page.getByRole("button", { name: "Check for updates" }).click()
await expect(page.getByLabel("Update state")).toHaveText("ready")
await expect(page.getByLabel("Update offered")).toHaveText("yes")
// Every tab hears about the download, not only the one that checked.
await expect(second.getByLabel("Update state")).toHaveText("ready")
// A tab opened while the build waits offers it at once; before, it waited for every tab to close.
const third = await context.newPage()
await third.goto(`${site.url}/?updater`)
await expect(third.getByRole("heading")).toHaveText("old")
await expect(third.getByLabel("Update state")).toHaveText("ready")
await second.getByRole("button", { name: "Update now" }).click()
for (const tab of [page, second, third]) {
await expect(tab.getByRole("heading")).toHaveText("new")
await expect(tab.getByLabel("Update state")).toHaveText("idle")
}
await page.getByRole("button", { name: "Load lazy" }).click()
await expect(page.getByRole("status")).toHaveText("new nested lazy loaded")
},
)
fixture(
"reload from server replaces a saved build that cannot update, in every open tab",
async ({ page, context, site }) => {
await install(page, `${site.url}/?updater`)
const second = await context.newPage()
await second.goto(`${site.url}/?updater`)
await expect(second.getByLabel("Update state")).toHaveText("idle")
site.deploy("failed")
await page.getByRole("button", { name: "Check for updates" }).click()
await expect(page.getByLabel("Update state")).toHaveText("error")
await page.reload()
await expect(page.getByRole("heading")).toHaveText("old")
await page.getByRole("button", { name: "Reload from server" }).click()
await expect(page.getByRole("heading")).toHaveText("new")
expect(await page.evaluate(() => navigator.serviceWorker.controller)).toBeNull()
expect(await page.evaluate(async () => (await caches.keys()).length)).toBe(0)
// The other tab's old lazy chunks went with the caches, so it reloads too instead of failing its next import.
await expect(second.getByRole("heading")).toHaveText("new")
await second.getByRole("button", { name: "Load lazy" }).click()
await expect(second.getByRole("status")).toHaveText("new nested lazy loaded")
},
)
for (const fault of ["failed", "html", "corrupt", "mixed-html"] as const) {
fixture(`retains the old complete build when a precache download is ${fault}`, async ({ page, context, site }) => {
await install(page, site.url)
@@ -6,6 +6,8 @@ export default {
"action.installRestart": "Install and restart",
"action.download": "Download OpenCode",
"action.installing": "Installing…",
"action.reload": "Reload to update",
"action.reloading": "Reloading…",
"toast.latest.title": "You're up to date",
"toast.latest.description": "You're running the latest version of OpenCode.",
"migration.title": "Move from Beta to Stable",
@@ -25,6 +27,12 @@ export default {
"dialog.ready.title": "Update Ready",
"dialog.restart": "Restart",
"dialog.later": "Later",
"web.ready.title": "Update ready",
"web.ready.message": "A new version of OpenCode is ready. Reload to use it in every open window.",
"web.reload": "Reload",
"web.reset.title": "Reload from server",
"web.reset.description": "Clear the saved copy of the app and load the server's current version",
"web.reset.action": "Reload from server",
"releaseNotes.action.getStarted": "Get started",
"releaseNotes.action.next": "Next",
"releaseNotes.action.hideFuture": "Don't show these in the future",
@@ -4,13 +4,14 @@ import { Command, SettingsPage, TitlebarItem, type SetupContext, type Plugin } f
import { onIdle } from "@opencode/plugin/gui/builtin"
import { Updater } from "@opencode/plugin/gui/updater"
import { updaterAction } from "./action"
import { webUpdates } from "./web"
import type definition from "./index"
const setup: Plugin.Setup<typeof definition> = (ctx) => {
whatsNew(ctx)
betaNotes(ctx)
if (!ctx.desktop) return
if (!ctx.desktop) return webUpdates(ctx)
const updater = ctx.main(Updater)
// Undefined until main's updater is up and has sent its state, and again while it is gone.
const state = () => updater.state()
@@ -57,7 +58,7 @@ const setup: Plugin.Setup<typeof definition> = (ctx) => {
render: () => (
<Suspense>
<Section
state={state}
action={() => updaterAction(state())}
run={() => {
const run = updaterAction(state()).run
+25 -7
View File
@@ -1,14 +1,20 @@
import { createMemo } from "solid-js"
import { Show } from "solid-js"
import { usePlugin } from "@opencode/plugin/gui"
import { updaterAction } from "./action"
import type { UpdaterState } from "@opencode/plugin/gui/updater"
import type definition from "./index"
import type en from "./i18n/en"
export default function UpdatesSection(props: { state: () => UpdaterState | undefined; run: () => void }) {
/** The one update action the row offers: its label, and whether it runs now. */
export type UpdatesAction = { readonly label: keyof typeof en; readonly run?: string }
export default function UpdatesSection(props: {
action: () => UpdatesAction
run: () => void
/** Web only: drop the saved copy of the app and load the server's build. */
reset?: () => void
}) {
const ctx = usePlugin<typeof definition>()
const ui = ctx.ui
const releaseNotes = ctx.stores.releaseNotes
const action = createMemo(() => updaterAction(props.state()))
return (
<ui.SettingsSection title={ctx.t("section.title")}>
@@ -30,10 +36,22 @@ export default function UpdatesSection(props: { state: () => UpdaterState | unde
</ui.SettingsRow>
<ui.SettingsRow id="settings-check-updates" title={ctx.t("check.title")} description={ctx.t("check.description")}>
<ui.Button disabled={!action().run} onClick={() => props.run()}>
{ctx.t(action().label)}
<ui.Button disabled={!props.action().run} onClick={() => props.run()}>
{ctx.t(props.action().label)}
</ui.Button>
</ui.SettingsRow>
<Show when={props.reset}>
{(reset) => (
<ui.SettingsRow
id="settings-reload-from-server"
title={ctx.t("web.reset.title")}
description={ctx.t("web.reset.description")}
>
<ui.Button onClick={() => reset()()}>{ctx.t("web.reset.action")}</ui.Button>
</ui.SettingsRow>
)}
</Show>
</ui.SettingsSection>
)
}
@@ -0,0 +1,187 @@
import { initialWebUpdate, transitionWebUpdate } from "./web-machine"
import type { WebUpdateEffect, WebUpdateEvent, WebUpdateState, WebWorker } from "./web-machine"
/** How often an open, visible window asks the server for a newer build. */
const CHECK_INTERVAL_MS = 10 * 60_000
/** The channel the app's windows share to reload together after a reset. */
const RESET_CHANNEL = "opencode.updater.reset"
/** How long `applying` waits for the new worker to take over before reloading anyway. */
const APPLY_TIMEOUT_MS = 10_000
type Current = { state: WebUpdateState; registration?: ServiceWorkerRegistration; disposed: boolean }
export type WebUpdateReport =
| { readonly result: "up-to-date" }
| { readonly result: "failed"; readonly message: string }
export type WebUpdaterOptions = {
/** The state changed. */
readonly changed: (state: WebUpdateState) => void
/** A newer build is ready to load. */
readonly announce: () => void
/** The user's check found nothing newer, or failed with `message` (empty when the browser gave none). */
readonly report: (report: WebUpdateReport) => void
}
/**
* Runs the web update machine against this window's service worker registration. It checks for a newer build when the
* window opens, comes back into view or reconnects, and every ten minutes while visible. Without service workers (an
* insecure origin, or development) it stays `unavailable`.
*/
export function startWebUpdater(options: WebUpdaterOptions) {
const container = "serviceWorker" in navigator ? navigator.serviceWorker : undefined
// The app's windows share one saved copy, so a reset in one tells the others to reload.
const channel = container && "BroadcastChannel" in window ? new BroadcastChannel(RESET_CHANNEL) : undefined
const current: Current = { state: initialWebUpdate, disposed: false }
const queue: WebUpdateEvent[] = []
const cleanup: (() => void)[] = []
// An event dispatched while another applies (a listener that fires synchronously) waits its turn.
const dispatch = (event: WebUpdateEvent) => {
if (current.disposed) return
queue.push(event)
if (queue.length > 1) return
for (const next of queue) apply(next)
queue.length = 0
}
const apply = (event: WebUpdateEvent) => {
const step = transitionWebUpdate(current.state, event)
if (step.state !== current.state) {
current.state = step.state
options.changed(step.state)
}
step.effects.forEach(perform)
}
const perform = (effect: WebUpdateEffect) => {
if (effect.type === "announce") return options.announce()
if (effect.type === "report") return options.report(effect)
if (effect.type === "reload") return location.reload()
if (effect.type === "reset") return void reset(channel)
const registration = current.registration
if (!registration) return
if (effect.type === "update") {
const attempt = effect.attempt
return void registration.update().then(
() => dispatch({ type: "check.settled", attempt, worker: newest(registration) }),
// The browser rejects with a TypeError or DOMException, both Errors.
(error: Error) => dispatch({ type: "check.failed", attempt, message: error.message }),
)
}
// Workbox's generated worker skips waiting when it receives this message.
registration.waiting?.postMessage({ type: "SKIP_WAITING" })
const timer = setTimeout(() => dispatch({ type: "apply.timeout" }), APPLY_TIMEOUT_MS)
cleanup.push(() => clearTimeout(timer))
}
const check = (manual: boolean) => dispatch({ type: "check.requested", manual, at: Date.now() })
const listen = (target: EventTarget, type: string, listener: () => void) => {
target.addEventListener(type, listener)
cleanup.push(() => target.removeEventListener(type, listener))
}
const track = (worker: ServiceWorker | null) => {
if (!worker) return
listen(worker, "statechange", () => {
if (worker.state === "installed") dispatch({ type: "worker.installed" })
if (worker.state === "redundant") dispatch({ type: "worker.redundant" })
})
}
if (container) {
// A page the worker did not serve (a first visit) already runs the newest build; only a served page follows a
// takeover.
const controlled = !!container.controller
listen(container, "controllerchange", () => {
if (controlled) dispatch({ type: "controller.changed" })
})
void container.ready.then((registration) => {
if (current.disposed) return
current.registration = registration
listen(registration, "updatefound", () => {
dispatch({ type: "worker.installing" })
track(registration.installing)
})
track(registration.installing)
dispatch({ type: "registered", worker: newest(registration) })
check(false)
})
listen(document, "visibilitychange", () => {
if (document.visibilityState === "visible") check(false)
})
listen(window, "online", () => check(false))
const interval = setInterval(() => {
if (document.visibilityState === "visible") check(false)
}, CHECK_INTERVAL_MS)
cleanup.push(() => clearInterval(interval))
}
if (channel) {
// Only reset posts here, and a channel never hears its own messages.
listen(channel, "message", () => dispatch({ type: "reset.elsewhere" }))
cleanup.push(() => channel.close())
}
return {
state: () => current.state,
/** Asks the server for a newer build now and reports what it found. */
check: () => check(true),
/** Moves every window to the downloaded build. */
apply: () => dispatch({ type: "apply.requested" }),
/** Drops the saved copy of the app and loads the server's current build. */
reset: () => dispatch({ type: "reset.requested" }),
dispose: () => {
current.disposed = true
cleanup.splice(0).forEach((run) => run())
},
}
}
function newest(registration: ServiceWorkerRegistration): WebWorker {
if (registration.waiting) return "waiting"
if (registration.installing) return "installing"
return "none"
}
// Every window of this origin loses the saved app. The others reload only once it is gone, so they load the server's
// build instead of the old files a lazy import would now miss.
async function reset(channel: BroadcastChannel | undefined) {
const registrations = await navigator.serviceWorker.getRegistrations().catch(() => [])
const names = "caches" in window ? await caches.keys().catch(() => []) : []
await Promise.allSettled([
...registrations.map((registration) => registration.unregister()),
...names.map((name) => caches.delete(name)),
])
channel?.postMessage("reset")
location.reload()
}
@@ -0,0 +1,164 @@
import { describe, expect, test } from "bun:test"
import {
AUTO_CHECK_SPACING_MS,
initialWebUpdate,
transitionWebUpdate,
type WebUpdateEffect,
type WebUpdateEvent,
type WebUpdateState,
} from "./web-machine"
// Replays events the way the driver sends them and collects every effect in order.
function replay(events: readonly WebUpdateEvent[]) {
const effects: WebUpdateEffect[] = []
const state = events.reduce((current, event) => {
const step = transitionWebUpdate(current, event)
effects.push(...step.effects)
return step.state
}, initialWebUpdate)
return { state, effects }
}
const auto = (at: number): WebUpdateEvent => ({ type: "check.requested", manual: false, at })
const manual = (at: number): WebUpdateEvent => ({ type: "check.requested", manual: true, at })
type Report = {
readonly name: string
readonly settle: WebUpdateEvent
readonly status: WebUpdateState["status"]
readonly effects: WebUpdateEffect[]
}
const reports: readonly Report[] = [
{
name: "nothing newer",
settle: { type: "check.settled", attempt: 1, worker: "none" },
status: "up-to-date",
effects: [{ type: "report", result: "up-to-date" }],
},
{
name: "a failed check",
settle: { type: "check.failed", attempt: 1, message: "offline" },
status: "error",
effects: [{ type: "report", result: "failed", message: "offline" }],
},
]
describe("web update machine", () => {
test("a build already waiting when the app opens is offered at once", () => {
// Before, it waited until every window closed, which an installed app rarely does.
const result = replay([{ type: "registered", worker: "waiting" }])
expect(result.state.status).toBe("ready")
expect(result.effects).toEqual([{ type: "announce" }])
})
test("a build that downloads in the background is offered once it is installed", () => {
const result = replay([
{ type: "registered", worker: "none" },
auto(0),
{ type: "worker.installing" },
{ type: "check.settled", attempt: 1, worker: "installing" },
{ type: "worker.installed" },
])
expect(result.state.status).toBe("ready")
expect(result.effects).toEqual([{ type: "update", attempt: 1 }, { type: "announce" }])
})
test("automatic checks close together ask the server once, and the user's check always runs", () => {
const result = replay([
{ type: "registered", worker: "none" },
auto(0),
{ type: "check.settled", attempt: 1, worker: "none" },
auto(AUTO_CHECK_SPACING_MS - 1),
manual(AUTO_CHECK_SPACING_MS - 1),
{ type: "check.settled", attempt: 2, worker: "none" },
auto(2 * AUTO_CHECK_SPACING_MS),
])
expect(result.effects.filter((effect) => effect.type === "update")).toEqual([
{ type: "update", attempt: 1 },
{ type: "update", attempt: 2 },
{ type: "update", attempt: 3 },
])
})
test.each(reports)("the user's check reports $name; an automatic one stays quiet", (row) => {
const asked = replay([{ type: "registered", worker: "none" }, manual(0), row.settle])
const quiet = replay([{ type: "registered", worker: "none" }, auto(0), row.settle])
expect(asked.state.status).toBe(row.status)
expect(asked.effects.slice(1)).toEqual(row.effects)
expect(quiet.state.status).toBe("idle")
expect(quiet.effects.slice(1)).toEqual([])
})
test("a result for an older check is ignored", () => {
const result = replay([
{ type: "registered", worker: "none" },
manual(0),
{ type: "check.settled", attempt: 1, worker: "none" },
manual(1),
{ type: "check.failed", attempt: 1, message: "late" },
])
expect(result.state).toMatchObject({ status: "checking", attempt: 2 })
})
test("a download the browser rejects keeps the current build and tells only a user who asked", () => {
const steps = (first: WebUpdateEvent) => [
{ type: "registered", worker: "none" } as const,
first,
{ type: "worker.installing" } as const,
{ type: "worker.redundant" } as const,
]
expect(replay(steps(manual(0))).effects.at(-1)).toEqual({ type: "report", result: "failed", message: "" })
expect(replay(steps(auto(0))).state.status).toBe("idle")
})
test("reloading asks the waiting build to take over, then reloads when it does or after a timeout", () => {
const ready = [{ type: "registered", worker: "waiting" }, { type: "apply.requested" }] as const
const applying = replay(ready)
const taken = replay([...ready, { type: "controller.changed" }])
const timedOut = replay([...ready, { type: "apply.timeout" }])
expect(applying.state.status).toBe("applying")
expect(applying.effects.at(-1)).toEqual({ type: "skip-waiting" })
expect(taken.effects.at(-1)).toEqual({ type: "reload" })
expect(timedOut.effects.at(-1)).toEqual({ type: "reload" })
})
test.each(["controller.changed", "reset.elsewhere"] as const)(
"another window's %s reloads this one, whose old files are gone",
(type) => {
const result = replay([{ type: "registered", worker: "waiting" }, { type }])
expect(result).toEqual({ state: { status: "reloading" }, effects: [{ type: "announce" }, { type: "reload" }] })
},
)
test("a reset reloads once from any state and nothing runs after it", () => {
const result = replay([
{ type: "registered", worker: "waiting" },
{ type: "reset.requested" },
{ type: "controller.changed" },
manual(0),
{ type: "apply.requested" },
])
expect(result.state).toEqual({ status: "reloading" })
expect(result.effects).toEqual([{ type: "announce" }, { type: "reset" }])
})
test("only the reload action runs while a build is ready; checking again offers it again", () => {
const result = replay([{ type: "registered", worker: "waiting" }, auto(0), manual(0)])
expect(result.effects).toEqual([{ type: "announce" }, { type: "announce" }])
})
})
@@ -0,0 +1,202 @@
/**
* The web app's update lifecycle. The server's service worker precaches the app, so a new build installs in the
* background and then waits until every window closes, which an installed app (PWA) rarely does. This machine finds
* that build, offers it, and moves every window to it on request.
*/
/** Where a registration's newest worker is. */
export type WebWorker = "none" | "installing" | "waiting"
type Meta = {
/** The last check attempt issued; a result for any other attempt is stale. */
readonly issued: number
/** When the last check started, in epoch milliseconds, to space out automatic checks. */
readonly checkedAt: number | undefined
}
/**
* - `unavailable`: no service worker serves this page (development, or an insecure origin), so a reload is current.
* - `idle`: nothing newer is known.
* - `checking`: asking the server for a newer build; `manual` when the user asked.
* - `up-to-date`: the user's last check found nothing newer.
* - `downloading`: a newer build is downloading.
* - `ready`: a newer build is downloaded and waits for a reload.
* - `applying`: the newer build was asked to take over; every window reloads once it does.
* - `reloading`: this window is reloading into the newer build (or a reset).
* - `error`: the user's last check or download failed.
*/
export type WebUpdateState =
| { readonly status: "unavailable" }
| (Meta & { readonly status: "idle" })
| (Meta & { readonly status: "checking"; readonly attempt: number; readonly manual: boolean })
| (Meta & { readonly status: "up-to-date" })
| (Meta & { readonly status: "downloading"; readonly manual: boolean })
| (Meta & { readonly status: "ready" })
| (Meta & { readonly status: "applying" })
| { readonly status: "reloading" }
| (Meta & { readonly status: "error"; readonly message: string })
export type WebUpdateEvent =
| { readonly type: "registered"; readonly worker: WebWorker }
| { readonly type: "check.requested"; readonly manual: boolean; readonly at: number }
| { readonly type: "check.settled"; readonly attempt: number; readonly worker: WebWorker }
| { readonly type: "check.failed"; readonly attempt: number; readonly message: string }
| { readonly type: "worker.installing" }
| { readonly type: "worker.installed" }
| { readonly type: "worker.redundant" }
| { readonly type: "apply.requested" }
| { readonly type: "apply.timeout" }
| { readonly type: "reset.requested" }
/** Another window dropped the saved app, including the files this window still loads. */
| { readonly type: "reset.elsewhere" }
| { readonly type: "controller.changed" }
export type WebUpdateEffect =
/** Ask the server for a newer service worker. */
| { readonly type: "update"; readonly attempt: number }
/** Tell the waiting worker to take over now. */
| { readonly type: "skip-waiting" }
| { readonly type: "reload" }
/** Unregister the worker, delete its caches, tell every other window to reload, then reload from the server. */
| { readonly type: "reset" }
/** A newer build is ready: offer the reload. */
| { readonly type: "announce" }
/** Answer the user's check: nothing newer, or it failed with `message`. */
| { readonly type: "report"; readonly result: "up-to-date" }
| { readonly type: "report"; readonly result: "failed"; readonly message: string }
export type WebUpdateTransition = { readonly state: WebUpdateState; readonly effects: readonly WebUpdateEffect[] }
/** Automatic checks (focus, network, timer) closer together than this ask once. A user's check always runs. */
export const AUTO_CHECK_SPACING_MS = 60_000
export const initialWebUpdate: WebUpdateState = { status: "unavailable" }
export function transitionWebUpdate(state: WebUpdateState, event: WebUpdateEvent): WebUpdateTransition {
if (state.status === "reloading") return unchanged(state)
// Another window applied the update or dropped the saved app, or this one applied it: the old build's files are
// gone, so reload.
if (event.type === "controller.changed" || event.type === "reset.elsewhere")
return { state: { status: "reloading" }, effects: [{ type: "reload" }] }
if (event.type === "reset.requested") return { state: { status: "reloading" }, effects: [{ type: "reset" }] }
if (state.status === "unavailable") {
if (event.type !== "registered") return unchanged(state)
return found({ issued: 0, checkedAt: undefined }, event.worker, false)
}
const meta: Meta = { issued: state.issued, checkedAt: state.checkedAt }
switch (event.type) {
case "check.requested":
return checkRequested(state, event)
case "check.settled":
if (state.status !== "checking" || event.attempt !== state.attempt) return unchanged(state)
return found(meta, event.worker, state.manual)
case "check.failed":
if (state.status !== "checking" || event.attempt !== state.attempt) return unchanged(state)
// An automatic check fails whenever the device is offline; only the user's own check says so.
if (!state.manual) return unchanged({ ...meta, status: "idle" })
return {
state: { ...meta, status: "error", message: event.message },
effects: [{ type: "report", result: "failed", message: event.message }],
}
case "worker.installing":
if (state.status === "downloading" || state.status === "ready" || state.status === "applying")
return unchanged(state)
return unchanged({ ...meta, status: "downloading", manual: state.status === "checking" && state.manual })
case "worker.installed":
if (state.status === "ready" || state.status === "applying") return unchanged(state)
return { state: { ...meta, status: "ready" }, effects: [{ type: "announce" }] }
case "worker.redundant":
// The download failed and the browser kept the current build.
if (state.status !== "downloading") return unchanged(state)
if (!state.manual) return unchanged({ ...meta, status: "idle" })
return {
state: { ...meta, status: "error", message: "" },
effects: [{ type: "report", result: "failed", message: "" }],
}
case "apply.requested":
if (state.status !== "ready") return unchanged(state)
return { state: { ...meta, status: "applying" }, effects: [{ type: "skip-waiting" }] }
case "apply.timeout":
// The new worker took over without telling this window; a reload still lands on it.
if (state.status !== "applying") return unchanged(state)
return { state: { status: "reloading" }, effects: [{ type: "reload" }] }
case "registered":
return unchanged(state)
}
}
/** The one action the settings row and the titlebar offer for a state. */
export function webUpdateAction(state: WebUpdateState) {
switch (state.status) {
case "checking":
return { label: "action.checking" as const }
case "downloading":
return { label: "action.downloading" as const }
case "ready":
return { label: "action.reload" as const, run: "apply" as const }
case "applying":
case "reloading":
return { label: "action.reloading" as const }
case "unavailable":
return { label: "action.checkNow" as const }
default:
return { label: "action.checkNow" as const, run: "check" as const }
}
}
/** Whether the titlebar shows the update button: a newer build is ready, or the window is moving to it. */
export function webUpdatePending(state: WebUpdateState) {
return state.status === "ready" || state.status === "applying" || state.status === "reloading"
}
function checkRequested(
state: Exclude<WebUpdateState, { status: "unavailable" | "reloading" }>,
event: Extract<WebUpdateEvent, { type: "check.requested" }>,
): WebUpdateTransition {
if (state.status === "checking" || state.status === "downloading")
return unchanged(event.manual && !state.manual ? { ...state, manual: true } : state)
// The newer build is already here: offer it again.
if (state.status === "ready") return event.manual ? unchanged(state, [{ type: "announce" }]) : unchanged(state)
if (state.status === "applying") return unchanged(state)
if (!event.manual && state.checkedAt !== undefined && event.at - state.checkedAt < AUTO_CHECK_SPACING_MS)
return unchanged(state)
const attempt = state.issued + 1
return {
state: { issued: attempt, checkedAt: event.at, status: "checking", attempt, manual: event.manual },
effects: [{ type: "update", attempt }],
}
}
function found(meta: Meta, worker: WebWorker, manual: boolean): WebUpdateTransition {
if (worker === "waiting") return { state: { ...meta, status: "ready" }, effects: [{ type: "announce" }] }
if (worker === "installing") return unchanged({ ...meta, status: "downloading", manual })
if (!manual) return unchanged({ ...meta, status: "idle" })
return { state: { ...meta, status: "up-to-date" }, effects: [{ type: "report", result: "up-to-date" }] }
}
function unchanged(state: WebUpdateState, effects: readonly WebUpdateEffect[] = []): WebUpdateTransition {
return { state, effects }
}
+103
View File
@@ -0,0 +1,103 @@
import { Icon } from "@opencode/ui/icon"
import { showToast, toaster } from "@opencode/ui/toast"
import { createSignal, lazy, onCleanup, Suspense } from "solid-js"
import { Command, createKeyed, SettingsPage, TitlebarItem, type SetupContext } from "@opencode/plugin/gui"
import { onIdle } from "@opencode/plugin/gui/builtin"
import { startWebUpdater } from "./web-driver"
import { initialWebUpdate, webUpdateAction, webUpdatePending, type WebUpdateState } from "./web-machine"
import type definition from "./index"
type Offer = { toast?: number }
/**
* Updates for the web app and installed web app (PWA): finds the server's newer build, offers it in a toast, the
* titlebar and Settings › Updates, and moves every open window to it. Settings also offers a full reload from the
* server for a saved copy that will not update.
*/
export function webUpdates(ctx: SetupContext<typeof definition>) {
const [state, setState] = createSignal<WebUpdateState>(initialWebUpdate)
// The one "update ready" toast on screen, replaced when it is offered again.
const offer: Offer = {}
const updater = startWebUpdater({
changed: setState,
announce: () => {
if (offer.toast !== undefined) toaster.dismiss(offer.toast)
offer.toast = showToast({
title: ctx.t("web.ready.title"),
description: ctx.t("web.ready.message"),
persistent: true,
actions: [
{ label: ctx.t("web.reload"), variant: "primary", onClick: () => updater.apply() },
{ label: ctx.t("dialog.later"), variant: "secondary", onClick: "dismiss" },
],
})
},
report: (report) => {
if (report.result === "up-to-date")
return void showToast({
variant: "success",
icon: () => <Icon name="circle-check" />,
title: ctx.t("toast.latest.title"),
description: ctx.t("toast.latest.description", { version: ctx.app.version }),
})
showToast({ title: ctx.t("common.requestFailed"), description: report.message || undefined })
},
})
onCleanup(updater.dispose)
const run = () => {
const next = webUpdateAction(state()).run
if (next === "apply") return updater.apply()
if (next === "check") updater.check()
}
const Section = lazy(() => import("./section"))
onCleanup(onIdle(() => void Section.preload()))
// Without a service worker (development, an insecure origin) a reload is already the newest build: offer nothing.
createKeyed(
() => state().status !== "unavailable",
() => {
ctx.add(TitlebarItem, () => {
const current = state()
if (!webUpdatePending(current)) return
return {
id: "update",
label: ctx.t("status.label"),
title: ctx.t(webUpdateAction(current).label),
busy: current.status !== "ready",
run,
}
})
ctx.add(SettingsPage, {
id: "updates",
page: "general",
get title() {
return ctx.t("section.title")
},
get entries() {
return [
{ id: "settings-release-notes", title: ctx.t("releaseNotes.title") },
{ id: "settings-check-updates", title: ctx.t("check.title") },
{ id: "settings-reload-from-server", title: ctx.t("web.reset.title") },
]
},
render: () => (
<Suspense>
<Section action={() => webUpdateAction(state())} run={run} reset={() => updater.reset()} />
</Suspense>
),
})
ctx.add(Command, (): Command => ({ id: "check", title: ctx.t("menu.check"), hidden: true, run: updater.check }))
},
)
}