fix(desktop): keep staged updates fresh with silent re-checks (#42707)

This commit is contained in:
Luke Parker
2026-08-15 14:22:24 +10:00
committed by GitHub
Unverified
parent 41f70bfbb1
commit 7301c5e798
8 changed files with 208 additions and 197 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ export type UpdaterState =
| { status: "disabled" }
| { status: "idle" }
| { status: "checking" }
| { status: "downloading"; version: string; percent?: number }
| { status: "downloading"; version: string }
| { status: "ready"; version: string }
| { status: "up-to-date" }
| { status: "installing"; version: string }
+3 -4
View File
@@ -24,8 +24,7 @@ import {
isOldLayoutEligible,
} from "./onboarding"
import { getDefaultServerUrl, preferAppEnv, setDefaultServerUrl } from "./server"
import { setupAutoUpdater, showUpdaterDialog } from "./updater"
import { registerUpdaterIpc } from "./updater-ipc"
import { registerUpdaterIpc, setupAutoUpdater, showUpdaterDialog } from "./updater"
import { safeWebContentsURL } from "./window-state"
import {
getLastFocusedWindow,
@@ -242,7 +241,7 @@ const main = Effect.gen(function* () {
const win = getLastFocusedWindow()
if (win) sendMenuCommand(win, id)
},
checkForUpdates: () => void showUpdaterDialog(updater, true),
checkForUpdates: () => void showUpdaterDialog(updater),
relaunch,
}
registerIpcHandlers({
@@ -267,7 +266,7 @@ const main = Effect.gen(function* () {
setDisplayBackend: async () => undefined,
checkAppExists: (appName) => checkAppExists(appName),
resolveAppPath: async (appName) => resolveAppPath(appName),
showUpdater: () => showUpdaterDialog(updater, true),
showUpdater: () => showUpdaterDialog(updater),
setBackgroundColor: (color) => setBackgroundColor(color),
exportDebugLogs: () => exportDebugLogs(),
recordFatalRendererError: (error) => writeLog("renderer", "fatal renderer error", { ...error }, "error"),
@@ -1,26 +1,35 @@
import { describe, expect, test } from "bun:test"
import { createUpdaterController, type UpdaterPlatform, type UpdaterReadyRecord } from "./updater-controller"
import { createUpdaterController, type UpdaterReadyRecord } from "./updater-controller"
function setup(input?: { currentVersion?: string; ready?: UpdaterReadyRecord }) {
// Drives the controller the way the app does: start or check, observe the states
// the renderer sees, then install like a button click. `calls` records the platform
// operations in order; installs record the staged version they would apply.
function setup(input?: {
currentVersion?: string
ready?: UpdaterReadyRecord
latest?: () => string
stage?: () => Promise<void>
install?: () => Promise<never>
}) {
const calls: string[] = []
const platform: UpdaterPlatform = {
async checkForUpdate() {
calls.push("check")
return "2.0.0"
},
async stageUpdate() {
calls.push("download")
},
installAndRestart() {
calls.push("install")
return new Promise<never>(() => {})
},
}
const states: string[] = []
let ready = input?.ready
const controller = createUpdaterController({
enabled: true,
currentVersion: input?.currentVersion ?? "1.0.0",
platform,
platform: {
async checkForUpdate() {
calls.push("check")
return input?.latest?.() ?? "2.0.0"
},
async stageUpdate() {
calls.push("download")
await input?.stage?.()
},
installAndRestart() {
calls.push(`install:${ready?.version}`)
return input?.install?.() ?? new Promise<never>(() => {})
},
},
lifecycle: {
async prepareToRestart() {
calls.push("prepare")
@@ -36,21 +45,29 @@ function setup(input?: { currentVersion?: string; ready?: UpdaterReadyRecord })
},
},
})
return { controller, calls, getReady: () => ready }
controller.subscribe((state) => states.push(state.status))
return { controller, calls, states, getReady: () => ready }
}
describe("updater controller", () => {
test("checks, downloads, persists, and publishes one authoritative ready state", async () => {
test("stages an update found at launch and shows it as ready", async () => {
const app = setup()
const states: ReturnType<typeof app.controller.getState>[] = []
app.controller.subscribe((state) => states.push(state))
await app.controller.start()
expect(app.calls).toEqual(["check", "download"])
expect(app.getReady()).toEqual({ version: "2.0.0" })
expect(states.map((state) => state.status)).toEqual(["idle", "checking", "downloading", "ready"])
expect(app.states).toEqual(["idle", "checking", "downloading", "ready"])
expect(app.controller.getState()).toEqual({ status: "ready", version: "2.0.0" })
expect(app.getReady()).toEqual({ version: "2.0.0" })
})
test("reports up to date and clears the record once the update is installed", async () => {
const app = setup({ currentVersion: "2.0.0", ready: { version: "2.0.0" } })
await app.controller.start()
expect(app.states).toEqual(["idle", "checking", "up-to-date"])
expect(app.calls).toEqual(["check"])
expect(app.getReady()).toBeUndefined()
})
test("revalidates a persisted target through the updater cache on launch", async () => {
@@ -62,16 +79,7 @@ describe("updater controller", () => {
expect(app.controller.getState()).toEqual({ status: "ready", version: "2.0.0" })
})
test("clears a target already installed before checking", async () => {
const app = setup({ currentVersion: "2.0.0", ready: { version: "2.0.0" } })
await app.controller.start()
expect(app.getReady()).toBeUndefined()
expect(app.calls).toEqual(["check"])
})
test("coalesces concurrent checks", async () => {
test("concurrent checks share one platform check", async () => {
const app = setup()
await Promise.all([app.controller.check(), app.controller.check(), app.controller.check()])
@@ -79,81 +87,109 @@ describe("updater controller", () => {
expect(app.calls).toEqual(["check", "download"])
})
test("starts installing synchronously and coalesces restart requests", async () => {
test("clicking install twice stops the servers once and installs once", async () => {
const app = setup()
await app.controller.start()
const first = app.controller.install()
const second = app.controller.install()
void app.controller.install()
void app.controller.install()
expect(first).toBe(second)
await Promise.resolve()
expect(app.calls).toEqual(["check", "download", "prepare", "install"])
expect(app.calls).toEqual(["check", "download", "prepare", "install:2.0.0"])
expect(app.controller.getState()).toEqual({ status: "installing", version: "2.0.0" })
})
test("does not check for updates while installation is in progress", async () => {
test("ignores checks while an installation is in progress", async () => {
const app = setup()
await app.controller.start()
void app.controller.install()
await app.controller.check()
expect(app.calls).toEqual(["check", "download", "prepare", "install"])
expect(app.calls).toEqual(["check", "download", "prepare", "install:2.0.0"])
})
test("later checks stay silent while ready and pick up newer versions", async () => {
let latest = "2.0.0"
const app = setup({ latest: () => latest })
await app.controller.start()
await app.controller.check()
// Nothing new was published: the install button never hid.
expect(app.states).toEqual(["idle", "checking", "downloading", "ready"])
latest = "3.0.0"
await app.controller.check()
expect(app.states).toEqual(["idle", "checking", "downloading", "ready", "ready"])
expect(app.controller.getState()).toEqual({ status: "ready", version: "3.0.0" })
expect(app.getReady()).toEqual({ version: "3.0.0" })
})
test("keeps the staged update installable when a silent re-check fails", async () => {
let offline = false
const app = setup({
latest: () => {
if (offline) throw new Error("offline")
return "2.0.0"
},
})
await app.controller.start()
offline = true
await app.controller.check()
expect(app.states).toEqual(["idle", "checking", "downloading", "ready"])
expect(app.controller.getState()).toEqual({ status: "ready", version: "2.0.0" })
expect(app.getReady()).toEqual({ version: "2.0.0" })
})
test("install during a silent refresh waits for the download, then installs the newer version", async () => {
let latest = "2.0.0"
let slowStage = false
let releaseStage = () => {}
const app = setup({
latest: () => latest,
stage: () => {
if (!slowStage) return Promise.resolve()
return new Promise<void>((resolve) => {
releaseStage = resolve
})
},
})
await app.controller.start()
latest = "3.0.0"
slowStage = true
const refresh = app.controller.check()
await new Promise((resolve) => setTimeout(resolve, 0))
void app.controller.install()
expect(app.controller.getState()).toEqual({ status: "installing", version: "2.0.0" })
releaseStage()
await refresh
expect(app.controller.getState()).toEqual({ status: "installing", version: "3.0.0" })
await new Promise((resolve) => setTimeout(resolve, 0))
expect(app.calls).toEqual(["check", "download", "check", "download", "prepare", "install:3.0.0"])
})
test("returns to ready after a failed installation and allows a retry", async () => {
let attempts = 0
const app = setup({
install() {
attempts++
if (attempts === 1) return Promise.reject(new Error("install failed"))
return new Promise<never>(() => {})
},
})
await app.controller.start()
await expect(app.controller.install()).rejects.toThrow("install failed")
expect(app.controller.getState()).toEqual({ status: "ready", version: "2.0.0" })
void app.controller.install()
await Promise.resolve()
expect(attempts).toBe(2)
expect(app.controller.getState()).toEqual({ status: "installing", version: "2.0.0" })
})
test("returns to ready when installation fails", async () => {
const app = setup()
await app.controller.start()
const error = new Error("install failed")
const failed = createUpdaterController({
enabled: true,
currentVersion: "1.0.0",
platform: {
checkForUpdate: async () => "2.0.0",
stageUpdate: async () => {},
installAndRestart: () => Promise.reject(error),
},
lifecycle: { prepareToRestart: async () => {} },
persistence: { get: () => undefined, set() {}, clear() {} },
})
await failed.start()
await expect(failed.install()).rejects.toThrow("install failed")
expect(failed.getState()).toEqual({ status: "ready", version: "2.0.0" })
})
test("allows a state subscriber to retry after installation fails", async () => {
let attempts = 0
let sawInstalling = false
let retry: Promise<void> | undefined
const failed = createUpdaterController({
enabled: true,
currentVersion: "1.0.0",
platform: {
checkForUpdate: async () => "2.0.0",
stageUpdate: async () => {},
installAndRestart() {
attempts++
if (attempts === 1) return Promise.reject(new Error("install failed"))
return new Promise<never>(() => {})
},
},
lifecycle: { prepareToRestart: async () => {} },
persistence: { get: () => undefined, set() {}, clear() {} },
})
failed.subscribe((state) => {
if (state.status === "installing") sawInstalling = true
if (!sawInstalling || state.status !== "ready" || retry) return
retry = failed.install()
})
await failed.start()
await expect(failed.install()).rejects.toThrow("install failed")
expect(retry).toBeDefined()
expect(attempts).toBe(2)
expect(failed.getState()).toEqual({ status: "installing", version: "2.0.0" })
})
})
+45 -32
View File
@@ -21,14 +21,13 @@ type UpdaterPersistence = {
}
export function createUpdaterController(input: {
enabled: boolean
currentVersion: string
platform?: UpdaterPlatform
lifecycle: UpdaterLifecycle
persistence: UpdaterPersistence
log?: (message: string, data?: object) => void
}) {
let state: UpdaterState = input.enabled ? { status: "idle" } : { status: "disabled" }
let state: UpdaterState = input.platform ? { status: "idle" } : { status: "disabled" }
let pending: Promise<UpdaterState> | undefined
let installing: Promise<void> | undefined
const listeners = new Set<(state: UpdaterState) => void>()
@@ -41,13 +40,21 @@ export function createUpdaterController(input: {
}
const check = () => {
if (!input.enabled) return Promise.resolve(state)
const platform = input.platform
if (!platform) return Promise.resolve(state)
if (state.status === "ready" || state.status === "installing") return Promise.resolve(state)
if (state.status === "installing") return Promise.resolve(state)
if (pending) return pending
pending = (async () => {
pending = (state.status === "ready" ? refreshStaged(platform, state.version) : findAndStage(platform)).finally(
() => {
pending = undefined
},
)
return pending
}
const findAndStage = (platform: UpdaterPlatform) =>
(async () => {
transition({ status: "checking" })
const version = await platform.checkForUpdate()
if (!version || version === input.currentVersion) {
@@ -59,41 +66,47 @@ export function createUpdaterController(input: {
await platform.stageUpdate()
await input.persistence.set({ version })
return transition({ status: "ready", version })
})()
.catch((error) =>
transition({ status: "error", message: error instanceof Error ? error.message : String(error) }),
)
.finally(() => {
pending = undefined
})().catch((error) =>
transition({ status: "error", message: error instanceof Error ? error.message : String(error) }),
)
// A staged update stays visible and installable throughout: the refresh makes no
// transitions until a newer version is staged, and a failure keeps the current one.
const refreshStaged = (platform: UpdaterPlatform, staged: string) =>
(async () => {
const version = await platform.checkForUpdate()
if (!version || version === staged || version === input.currentVersion) return state
await platform.stageUpdate()
await input.persistence.set({ version })
// An install may have started while this stage was in flight; keep its status
// and show the newer version instead of flickering back to ready.
return transition({ status: installing ? "installing" : "ready", version })
})().catch((error) => {
input.log?.("updater refresh failed, keeping staged update", {
staged,
message: error instanceof Error ? error.message : String(error),
})
return pending
}
return state
})
const install = () => {
if (installing) return installing
if (state.status !== "ready") return Promise.reject(new Error("Update is not ready to install"))
const platform = input.platform
if (!platform || state.status !== "ready") return Promise.reject(new Error("Update is not ready to install"))
const version = startInstalling(state.version)
installing = restartWithUpdate(version)
return installing
}
const startInstalling = (version: string) => {
transition({ status: "installing", version })
return version
}
const restartWithUpdate = (version: string) =>
prepareAndRestart().catch((error) => {
transition({ status: "installing", version: state.version })
installing = (async () => {
// A click during a silent refresh waits for the newer download, then installs it.
if (pending) await pending
await input.lifecycle.prepareToRestart()
await platform.installAndRestart()
})().catch((error) => {
installing = undefined
transition({ status: "ready", version })
if (state.status === "installing") transition({ status: "ready", version: state.version })
throw error
})
const prepareAndRestart = async () => {
if (!input.platform) throw new Error("Updater is disabled")
await input.lifecycle.prepareToRestart()
await input.platform.installAndRestart()
return installing
}
return {
-23
View File
@@ -1,23 +0,0 @@
import { app, ipcMain } from "electron"
import type { UpdaterController } from "./updater-controller"
import { createUpdaterSubscriptions } from "./updater-subscriptions"
export function registerUpdaterIpc(controller: UpdaterController) {
const subscriptions = createUpdaterSubscriptions()
app.once("will-quit", subscriptions.clear)
ipcMain.handle("updater-subscribe", (event) => {
const id = event.sender.id
subscriptions.set(
id,
controller.subscribe((state) => {
if (event.sender.isDestroyed()) return subscriptions.delete(id)
event.sender.send("updater-state", state)
}),
)
event.sender.once("destroyed", () => subscriptions.delete(id))
})
ipcMain.handle("updater-unsubscribe", (event) => subscriptions.delete(event.sender.id))
ipcMain.handle("updater-check", () => controller.check())
ipcMain.handle("updater-install", () => controller.install())
}
@@ -1,16 +0,0 @@
import { describe, expect, test } from "bun:test"
import { createUpdaterSubscriptions } from "./updater-subscriptions"
describe("updater subscriptions", () => {
test("replaces the previous renderer subscription on reload", () => {
const subscriptions = createUpdaterSubscriptions()
const disposed: string[] = []
subscriptions.set(1, () => disposed.push("first"))
subscriptions.set(1, () => disposed.push("second"))
expect(disposed).toEqual(["first"])
subscriptions.delete(1)
expect(disposed).toEqual(["first", "second"])
})
})
@@ -1,20 +0,0 @@
export function createUpdaterSubscriptions() {
const subscriptions = new Map<number, () => void>()
const remove = (id: number) => {
subscriptions.get(id)?.()
subscriptions.delete(id)
}
return {
set(id: number, unsubscribe: () => void) {
remove(id)
subscriptions.set(id, unsubscribe)
},
delete: remove,
clear() {
subscriptions.forEach((unsubscribe) => unsubscribe())
subscriptions.clear()
},
}
}
+28 -6
View File
@@ -1,6 +1,6 @@
import { app, dialog } from "electron"
import { app, dialog, ipcMain } from "electron"
import { UPDATER_ENABLED } from "./constants"
import { createUpdaterController, type UpdaterReadyRecord } from "./updater-controller"
import { createUpdaterController, type UpdaterController, type UpdaterReadyRecord } from "./updater-controller"
import { getLogger } from "./logging"
import { getStore } from "./store"
import { nativeT } from "./native-translations"
@@ -12,7 +12,6 @@ export function setupAutoUpdater(prepareToRestart: () => Promise<void>) {
const logger = getLogger()
const store = getStore("opencode.updater")
return createUpdaterController({
enabled: UPDATER_ENABLED,
currentVersion: app.getVersion(),
platform: UPDATER_ENABLED ? createUpdaterPlatform(logger) : undefined,
lifecycle: { prepareToRestart },
@@ -29,10 +28,34 @@ export function setupAutoUpdater(prepareToRestart: () => Promise<void>) {
})
}
export async function showUpdaterDialog(controller: ReturnType<typeof setupAutoUpdater>, alertOnFail: boolean) {
export function registerUpdaterIpc(controller: UpdaterController) {
const subscriptions = new Map<number, () => void>()
const unsubscribe = (id: number) => {
subscriptions.get(id)?.()
subscriptions.delete(id)
}
app.once("will-quit", () => subscriptions.forEach((dispose) => dispose()))
ipcMain.handle("updater-subscribe", (event) => {
const id = event.sender.id
subscriptions.get(id)?.() // a reloaded renderer replaces its previous subscription
subscriptions.set(
id,
controller.subscribe((state) => {
if (event.sender.isDestroyed()) return unsubscribe(id)
event.sender.send("updater-state", state)
}),
)
event.sender.once("destroyed", () => unsubscribe(id))
})
ipcMain.handle("updater-unsubscribe", (event) => unsubscribe(event.sender.id))
ipcMain.handle("updater-check", () => controller.check())
ipcMain.handle("updater-install", () => controller.install())
}
export async function showUpdaterDialog(controller: UpdaterController) {
const state = await controller.check()
if (state.status === "error") {
if (!alertOnFail) return
await dialog.showMessageBox({
type: "error",
message: nativeT("desktop.updater.dialog.checkFailed.message"),
@@ -41,7 +64,6 @@ export async function showUpdaterDialog(controller: ReturnType<typeof setupAutoU
return
}
if (state.status === "up-to-date") {
if (!alertOnFail) return
await dialog.showMessageBox({
type: "info",
message: nativeT("desktop.updater.dialog.upToDate.message"),