feat(client): offer the new version when a release lands during a session

A tab kept open across a deploy ran the previous build until its next
start. The server now names its version in the realtime welcome frame,
which every open client reads again when it reconnects after the
restart a deploy brings. When that version is not the build the page
runs, a notice offers to reload. The reload goes through the same
service worker handover a launch uses: it waits for the new worker to
take over, or for a short timeout, and records the version only when
the takeover happened.

The notice reads the error boundary's texts for the same situation, so
every language has it already. It is one component for both shells,
sits above the offline pill, stays away offline and after a reload for
that version that did not bring it, and can be closed for the session.
This commit is contained in:
Maurice
2026-10-07 22:40:12 +00:00
parent ba70ad28b8
commit a094f79efa
11 changed files with 421 additions and 9 deletions
+121
View File
@@ -484,3 +484,124 @@ describe('reconcileAppVersion: the reload guard', () => {
expect(reload).not.toHaveBeenCalled()
})
})
describe('offersNewBuild: whether the notice offers a reload', () => {
it('FE-UTIL-VERSION-040: offers a version other than the one this page was built as', async () => {
const { offersNewBuild } = await loadModule()
expect(offersNewBuild(`${BUILT}-next`)).toBe(true)
expect(offersNewBuild(BUILT)).toBe(false)
expect(offersNewBuild(null)).toBe(false)
})
it('FE-UTIL-VERSION-041: not once this session reloaded for that version, since another reload shows the same build', async () => {
const { offersNewBuild } = await loadModule()
sessionStorage.setItem('trek_app_version_reload', `${BUILT}-next`)
expect(offersNewBuild(`${BUILT}-next`)).toBe(false)
expect(offersNewBuild(`${BUILT}-later`)).toBe(true)
sessionStorage.removeItem('trek_app_version_reload')
})
it('FE-UTIL-VERSION-042: not without session storage, where the reload guard and with it the reload is missing', async () => {
const { offersNewBuild } = await loadModule()
breakStorage('getItem', () => sessionStorage)
expect(offersNewBuild(`${BUILT}-next`)).toBe(false)
})
it('FE-UTIL-VERSION-043: asReleaseTag takes a release tag and nothing else', async () => {
const { asReleaseTag } = await loadModule()
expect(asReleaseTag('4.3.4-rc.1')).toBe('4.3.4-rc.1')
expect(asReleaseTag(' 4.3.4')).toBeNull()
expect(asReleaseTag(434)).toBeNull()
expect(asReleaseTag('4'.repeat(65))).toBeNull()
})
})
describe('switchToServerVersion: the reload the user asked for', () => {
afterEach(() => {
sessionStorage.removeItem('trek_app_version_reload')
vi.useRealTimers()
})
it('FE-UTIL-VERSION-050: without a worker it reloads at once, under a fresh URL', async () => {
const { switchToServerVersion } = await loadModule()
await switchToServerVersion('4.3.4')
expect(reload).toHaveBeenCalledTimes(1)
expect(plainReload).not.toHaveBeenCalled()
})
it('FE-UTIL-VERSION-051: waits for the new worker to take over, records the version, then reloads', async () => {
const { container, registration } = installWorker()
updateInstalls(registration)
const { switchToServerVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.3')
const switching = switchToServerVersion('4.3.4')
await vi.waitFor(() => expect(registration.update).toHaveBeenCalled())
expect(reload).not.toHaveBeenCalled()
container.takeOver()
await switching
expect(marker()).toBe('4.3.4')
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-UTIL-VERSION-052: an unchanged sw.js has nothing to wait for, so it reloads and leaves the marker', async () => {
const { registration } = installWorker()
const { switchToServerVersion } = await loadModule()
localStorage.setItem('trek_app_version', '4.3.3')
await switchToServerVersion('4.3.4')
expect(registration.update).toHaveBeenCalled()
expect(marker()).toBe('4.3.3')
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-UTIL-VERSION-053: an install that goes redundant still ends in the reload', async () => {
const { registration } = installWorker()
const incoming = updateInstalls(registration)
const { switchToServerVersion } = await loadModule()
const switching = switchToServerVersion('4.3.4')
await vi.waitFor(() => expect(registration.update).toHaveBeenCalled())
incoming.become('redundant')
await switching
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-UTIL-VERSION-054: a failed update or a worker that never takes over does not leave the user waiting', async () => {
const failing = installWorker()
failing.registration.update.mockRejectedValue(new Error('offline'))
let { switchToServerVersion } = await loadModule()
await switchToServerVersion('4.3.4')
expect(reload).toHaveBeenCalledTimes(1)
sessionStorage.removeItem('trek_app_version_reload')
const stuck = installWorker()
updateInstalls(stuck.registration)
;({ switchToServerVersion } = await loadModule())
vi.useFakeTimers()
const switching = switchToServerVersion('4.3.5')
await vi.advanceTimersByTimeAsync(20_000)
await switching
expect(reload).toHaveBeenCalledTimes(2)
})
it('FE-UTIL-VERSION-055: a worker the browser swapped in already answers the reload, so nothing is asked of it', async () => {
const { container, registration } = installWorker()
const { switchToServerVersion } = await loadModule()
container.controller = new FakeWorker('activated')
await switchToServerVersion('4.3.4')
expect(registration.update).not.toHaveBeenCalled()
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-UTIL-VERSION-056: a registration lookup that throws still reloads', async () => {
const { container } = installWorker()
container.getRegistration.mockRejectedValue(new Error('SecurityError'))
const { switchToServerVersion } = await loadModule()
await switchToServerVersion('4.3.4')
expect(reload).toHaveBeenCalledTimes(1)
})
})
+78 -8
View File
@@ -94,6 +94,82 @@ async function handOver(reg: ServiceWorkerRegistration, version: string, runsIt:
})
}
/**
* A version is a short release tag and nothing else. It arrives over the wire
* and is written to this device's storage, so only a value made of the
* characters a tag may contain is taken, as the match itself. Anything else is
* null, which also keeps a malformed value from being compared against the
* stored marker and starting an update on every launch.
*/
export function asReleaseTag(value: unknown): string | null {
return /^[\w.+-]{1,64}$/.exec(typeof value === 'string' ? value : '')?.[0] ?? null
}
/**
* True when the server runs `version`, this page runs another build, and a
* reload can still bring the page onto it: once this session has reloaded for
* that version, another reload would only show the same build again (a proxy
* or the server reporting a version its bundle was not built as).
*/
export function offersNewBuild(version: string | null): boolean {
if (!version || !BUNDLE_VERSION || version === BUNDLE_VERSION) return false
try {
return sessionStorage.getItem(RELOAD_KEY) !== version
} catch {
// No session storage, no reload guard, and reloadOnce does not reload.
return false
}
}
/** How long a reload the user asked for waits for the new worker to take over. */
const SWITCH_WAIT_MS = 20_000
/**
* The user asked for the build the server runs now, from the notice a release
* deployed during the session raises. The same handover as a launch, but the
* reload is theirs to ask for, so it always comes: once the new worker has
* taken over, or when there is none to wait for, or after SWITCH_WAIT_MS. The
* marker only moves on a takeover; anything else is left to the next launch,
* as there.
*/
export async function switchToServerVersion(version: string): Promise<void> {
let reg: ServiceWorkerRegistration | undefined
try {
reg = 'serviceWorker' in navigator ? await navigator.serviceWorker.getRegistration() : undefined
} catch {
reg = undefined
}
// Without a worker the reload goes to the network. A worker other than the
// one that served this page has taken over already, and answers it with the
// new build.
if (reg && currentController() === servedBy) await waitForTakeover(reg, version)
reloadOnce(version)
}
function waitForTakeover(reg: ServiceWorkerRegistration, version: string): Promise<void> {
return new Promise(resolve => {
const done = (): void => {
clearTimeout(timer)
resolve()
}
const timer = setTimeout(done, SWITCH_WAIT_MS)
navigator.serviceWorker.addEventListener('controllerchange', () => {
markApplied(version)
done()
}, { once: true })
reg.update().then(() => {
const incoming = reg.installing ?? reg.waiting
if (!incoming) {
done()
return
}
incoming.addEventListener('statechange', () => {
if (incoming.state === 'redundant') done()
})
}, done)
})
}
/**
* Compares the version the server reports with the one this device last ran
* and, when they differ, moves the app onto the new build. It never deletes a
@@ -103,14 +179,8 @@ async function handOver(reg: ServiceWorkerRegistration, version: string, runsIt:
* away the map tiles and files the user had downloaded on purpose.
*/
export async function reconcileAppVersion(reported: unknown): Promise<void> {
// A version is a short release tag and nothing else. It arrives over the
// wire and is written to this device's storage, so only a value made of
// the characters a tag may contain is taken, as the match itself. Anything
// else is ignored, which also keeps a malformed value from being compared
// against the stored marker and starting an update on every launch.
const releaseTag = /^[\w.+-]{1,64}$/.exec(typeof reported === 'string' ? reported : '')
if (!releaseTag) return
const version = releaseTag[0]
const version = asReleaseTag(reported)
if (!version) return
let storedVersion: string | null
try {