fix(offline): the PWA starts offline again and the download does what it says

Four separate defects sat behind "offline mode is broken".

The app shell. On the first online launch after a version bump, App.tsx
deleted EVERY Cache Storage bucket and unregistered EVERY service worker,
then reloaded. That is exactly wrong for a Workbox autoUpdate build, which
swaps its precache atomically on install and never leaves an empty one.
Between the purge and the completion of a fresh 22 MB precache the origin
had no shell at all; anyone who closed the app or lost signal inside that
window could no longer start the PWA offline. It also threw away the map
tiles and documents the user had downloaded on purpose. It now asks the
worker to fetch the new build and reloads once it has taken over. The
version marker also moves inside the guarded path, because it was written
after the purge and outside its try: a throwing setItem left the caches
gone, the marker unwritten and the reload unreached, repeating on every
launch.

The reported version is validated before it reaches this device's storage and
before it is compared against the stored marker, so a value that is not a
release tag can neither be persisted nor start an update on every launch.

The session. loadUser's offline branch kept the persisted session but
never called onAuthSuccess, the only caller of setAuthed(true), and the
mutation queue's flush, syncAll and prepareForOffline are all gated on it.
A session that launched without network could therefore never sync again
for the rest of its life, even after the signal returned: the offline
settings buttons spun and returned instantly having done nothing, and
queued edits never uploaded. It also left reads pointed at the anonymous
database instead of the user's own.

The date rule. A trip is only cached when it has not ended, and one that
ended over a week ago is actively evicted. The per-trip switch was an
opt-out list, so ticking a finished trip changed nothing at all. For
anyone whose trips are all in the past, "Download for offline use" stored
none of them, reported success, and the cache stayed at zero. Switching a
trip on now pins it, which overrides both the skip and the eviction, and
the switch shows the honest position rather than promising storage that
never happens.

What the screen says. A sync that never started (already running, offline,
signed out) was indistinguishable from one that stored everything: the
progress bar painted full and a green "Ready for offline use" appeared over
a run of nothing. Both syncs now report why they stopped and the screen
says so. A rejected Dexie read no longer renders as "No trips cached yet",
and the clear button stays reachable when the database holds data that no
bookkeeping row points at. A run that rejects outright says so too: the trip
list it starts from is a plain fetch, so a network blip took the whole thing
down and left the last progress frame on screen looking like a finished
download. The 401-with-HTML branch in the API client now
confirms a reachable proxy before tearing the worker down, since several of
TREK's own routes answer 401 with a text/html body.

Both settings shells move onto one shared hook rather than growing the same
logic twice, and the tile prefetch caps its depth when the browser refused
persistent storage. Opaque tiles are billed at about 7 MB each, and an
origin that is not exempt from eviction loses its whole bucket, precached
shell included, which Workbox then never refills because sw.js has not
changed.

Closes #2228
This commit is contained in:
Maurice
2026-09-04 12:16:00 +02:00
parent 6d54ac629e
commit 55f14c6a70
42 changed files with 1101 additions and 390 deletions
+31 -1
View File
@@ -12,6 +12,11 @@
* world map"). See tripSyncManager / clearTileCache.
* disabledTripIds — trips the user explicitly excluded from offline storage.
* Everything else that is date-eligible is cached.
* pinnedTripIds : trips the user explicitly asked for that the date rule
* would otherwise skip or evict (a finished trip). Without
* this there was no way to say yes: the list was opt-out
* only, so ticking a past trip changed nothing and the
* download quietly stored none of them (#2228).
* conflictStrategy — what to do when an offline edit collides with a newer
* server change: 'ask' surfaces a per-conflict picker,
* 'mine'/'server' resolve automatically.
@@ -22,6 +27,7 @@ export type ConflictStrategy = 'ask' | 'mine' | 'server'
export interface OfflinePrefs {
cacheTiles: boolean
disabledTripIds: number[]
pinnedTripIds: number[]
conflictStrategy: ConflictStrategy
}
@@ -30,6 +36,7 @@ const STORAGE_KEY = 'trek_offline_prefs'
const DEFAULTS: OfflinePrefs = {
cacheTiles: true,
disabledTripIds: [],
pinnedTripIds: [],
conflictStrategy: 'ask',
}
@@ -44,6 +51,7 @@ function read(): OfflinePrefs {
return {
cacheTiles: typeof parsed.cacheTiles === 'boolean' ? parsed.cacheTiles : DEFAULTS.cacheTiles,
disabledTripIds: Array.isArray(parsed.disabledTripIds) ? parsed.disabledTripIds.filter(n => typeof n === 'number') : [],
pinnedTripIds: Array.isArray(parsed.pinnedTripIds) ? parsed.pinnedTripIds.filter(n => typeof n === 'number') : [],
conflictStrategy: parsed.conflictStrategy === 'mine' || parsed.conflictStrategy === 'server' ? parsed.conflictStrategy : 'ask',
}
} catch {
@@ -59,7 +67,7 @@ function write(next: OfflinePrefs): void {
/** Current snapshot (a copy — callers must not mutate it in place). */
export function getOfflinePrefs(): OfflinePrefs {
return { ..._prefs, disabledTripIds: [..._prefs.disabledTripIds] }
return { ..._prefs, disabledTripIds: [..._prefs.disabledTripIds], pinnedTripIds: [..._prefs.pinnedTripIds] }
}
export function setCacheTiles(on: boolean): void {
@@ -77,6 +85,14 @@ export function isTripOfflineEnabled(tripId: number): boolean {
return !_prefs.disabledTripIds.includes(tripId)
}
/**
* True when the user explicitly asked to keep this trip, overriding the date
* rule that otherwise skips and evicts finished trips (tripSyncManager).
*/
export function isTripPinned(tripId: number): boolean {
return _prefs.pinnedTripIds.includes(tripId)
}
/** Turn offline storage for a single trip on or off. */
export function setTripOfflineEnabled(tripId: number, on: boolean): void {
const has = _prefs.disabledTripIds.includes(tripId)
@@ -88,6 +104,20 @@ export function setTripOfflineEnabled(tripId: number, on: boolean): void {
write({ ..._prefs, disabledTripIds })
}
/**
* Pin a trip the date rule would not keep on its own, or release it again.
* Turning a trip off releases the pin too, so "off then on" cannot leave a
* finished trip silently pinned.
*/
export function setTripPinned(tripId: number, on: boolean): void {
const has = _prefs.pinnedTripIds.includes(tripId)
if (on === has) return
const pinnedTripIds = on
? [..._prefs.pinnedTripIds, tripId]
: _prefs.pinnedTripIds.filter(id => id !== tripId)
write({ ..._prefs, pinnedTripIds })
}
/** Subscribe to preference changes. Returns an unsubscribe function. */
export function onOfflinePrefsChange(fn: () => void): () => void {
listeners.add(fn)
+38 -3
View File
@@ -6,13 +6,48 @@
*
* Best-effort and idempotent: returns whether persistence is (now) granted.
*/
/**
* Last known answer, so callers that have to size a download against it do not
* each re-ask. `null` until the request at app init has resolved.
*
* The answer matters: a browser that refuses persistence evicts this origin's
* WHOLE bucket under pressure (the Workbox precache with it), and since sw.js
* is byte-identical between releases, Workbox never re-installs and never
* refills what was evicted. The PWA then cannot start offline at all, and
* reinstalling does not help because it does not clear or restore site data
* (#2228).
*/
let _persisted: boolean | null = null
export async function requestPersistentStorage(): Promise<boolean> {
try {
if (typeof navigator === 'undefined' || !navigator.storage?.persist) return false
if (typeof navigator === 'undefined' || !navigator.storage?.persist) {
_persisted = false
return false
}
// Already persisted? Avoid re-prompting where the API distinguishes.
if (navigator.storage.persisted && (await navigator.storage.persisted())) return true
return await navigator.storage.persist()
if (navigator.storage.persisted && (await navigator.storage.persisted())) {
_persisted = true
return true
}
_persisted = await navigator.storage.persist()
return _persisted
} catch {
_persisted = false
return false
}
}
/**
* Whether this origin's storage is exempt from eviction. Treats "not asked yet"
* as not granted, so a caller sizing a download errs on the small side.
*/
export function isStoragePersisted(): boolean {
return _persisted === true
}
/** Test helper: forget the cached answer. */
export function _resetPersistentStorage(): void {
_persisted = null
}
+18 -1
View File
@@ -26,6 +26,7 @@
import type { Place } from '../types'
import { offlineDb, upsertSyncMeta } from '../db/offlineDb'
import { isAuthed } from './authGate'
import { isStoragePersisted } from './persistentStorage'
import { isVectorStyle, normalizeTileUrl, resolveTileUrl, withTileApiKey } from '../utils/tileUrl'
import { OFM_POSITRON } from '../constants/mapDefaults'
import { clearVectorCache, prefetchVectorForPlaces } from './glPrefetcher'
@@ -54,6 +55,13 @@ export const MAX_TILES = Math.floor((180 * 1024) / AVG_TILE_KB) // = 12288
*/
export const TILE_CONCURRENCY = 6
/**
* Deepest zoom prefetched when the browser refused persistent storage. Keeps the
* padded quota cost of one trip in the low hundreds of megabytes rather than the
* tens of gigabytes a full z16 run bills (#2228).
*/
export const UNPERSISTED_MAX_ZOOM = 12
/** Name of the Workbox runtime cache holding map tiles (see vite.config.js). */
const TILE_CACHE = 'map-tiles'
@@ -430,7 +438,16 @@ export async function prefetchTilesForTrip(
// tile providers that don't send CORS headers. To stop the browser evicting
// these tiles under the inflated quota, we request persistent storage at app
// init instead (sync/persistentStorage.ts).
const fetched = await prefetchTiles(bbox, template, 0, 16, cartoKey)
//
// When that request was refused, the padding stops being an accounting detail:
// a full run bills this origin tens of gigabytes it is not exempt from, and
// the browser answers by evicting the whole bucket, including the precached
// app shell, which then never comes back on its own. So cap the depth instead.
// The shallow zooms are the ones the trip map actually opens at and cost a few
// dozen tiles (#2180); the deep ones are the volume, and they are what the
// user loses rather than the ability to start the app at all (#2228).
const maxZoom = isStoragePersisted() ? 16 : UNPERSISTED_MAX_ZOOM
const fetched = await prefetchTiles(bbox, template, 0, maxZoom, cartoKey)
// Update syncMeta with bbox and tile count
const meta = await offlineDb.syncMeta.get(tripId)
@@ -77,18 +77,18 @@ afterEach(() => {
})
describe('tripSyncManager.prepareForOffline — guards', () => {
it('FE-SYNC-PREP-001: returns 0 and hits no endpoint when logged out', async () => {
it('FE-SYNC-PREP-001: reports why it stopped and hits no endpoint when logged out', async () => {
setAuthed(false)
let called = false
server.use(http.get('/api/trips', () => { called = true; return HttpResponse.json({ trips: [] }) }))
expect(await tripSyncManager.prepareForOffline()).toBe(0)
expect(await tripSyncManager.prepareForOffline()).toEqual({ status: 'skipped', reason: 'signed-out' })
expect(called).toBe(false)
})
it('FE-SYNC-PREP-002: returns 0 when the browser is offline', async () => {
it('FE-SYNC-PREP-002: reports that it stopped because the browser is offline', async () => {
setOnline(false)
expect(await tripSyncManager.prepareForOffline()).toBe(0)
expect(await tripSyncManager.prepareForOffline()).toEqual({ status: 'skipped', reason: 'offline' })
})
it('FE-SYNC-PREP-003: a second concurrent run is refused by the syncing flag', async () => {
@@ -99,7 +99,11 @@ describe('tripSyncManager.prepareForOffline — guards', () => {
tripSyncManager.prepareForOffline(),
tripSyncManager.prepareForOffline(),
])
expect([first, second].sort()).toEqual([0, 1])
// The loser says so rather than reporting a successful run of nothing: the
// settings screen paints that answer instead of a finished progress bar
// (#2228).
expect(first).toEqual({ status: 'done', trips: 1 })
expect(second).toEqual({ status: 'skipped', reason: 'busy' })
})
})
@@ -112,7 +116,7 @@ describe('tripSyncManager.prepareForOffline — full run', () => {
const progress: PrepareProgress[] = []
const count = await tripSyncManager.prepareForOffline(p => progress.push(p))
expect(count).toBe(1)
expect(count).toEqual({ status: 'done', trips: 1 })
expect(progress.map(p => p.phase)).toEqual(['trips', 'files', 'tiles', 'done'])
expect(progress[0]).toMatchObject({ current: 1, total: 1, label: 'Munich' })
expect(progress[3]).toMatchObject({ phase: 'done', current: 1, total: 1 })
@@ -174,7 +178,7 @@ describe('tripSyncManager.prepareForOffline — full run', () => {
http.get('/api/categories', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
)
expect(await tripSyncManager.prepareForOffline()).toBe(1)
expect(await tripSyncManager.prepareForOffline()).toEqual({ status: 'done', trips: 1 })
expect(await offlineDb.tags.count()).toBe(0)
})
@@ -183,7 +187,7 @@ describe('tripSyncManager.prepareForOffline — full run', () => {
const broken = buildTrip({ id: 608, end_date: dateOffset(4) })
serveTrips([broken, good], { 607: bundleFor(good) })
expect(await tripSyncManager.prepareForOffline()).toBe(2)
expect(await tripSyncManager.prepareForOffline()).toEqual({ status: 'done', trips: 2 })
expect(await offlineDb.trips.get(607)).toBeDefined()
expect(await offlineDb.trips.get(608)).toBeUndefined()
expect(console.error).toHaveBeenCalled()
@@ -196,7 +200,7 @@ describe('tripSyncManager.prepareForOffline — full run', () => {
setTripOfflineEnabled(610, false)
serveTrips([kept, excluded], { 609: bundleFor(kept), 610: bundleFor(excluded) })
expect(await tripSyncManager.prepareForOffline()).toBe(1)
expect(await tripSyncManager.prepareForOffline()).toEqual({ status: 'done', trips: 1 })
expect(await offlineDb.trips.get(609)).toBeDefined()
expect(await offlineDb.trips.get(610)).toBeUndefined()
})
+44 -13
View File
@@ -31,7 +31,7 @@ import {
} from '../db/offlineDb'
import { prefetchTilesForTrip } from './tilePrefetcher'
import { isAuthed } from './authGate'
import { getOfflinePrefs, isTripOfflineEnabled } from './offlinePrefs'
import { getOfflinePrefs, isTripOfflineEnabled, isTripPinned } from './offlinePrefs'
import { useSettingsStore } from '../store/settingsStore'
import type { Trip, Day, Place, PackingItem, TodoItem, BudgetItem, Reservation, TripFile, Accommodation, TripMember } from '../types'
@@ -74,13 +74,24 @@ function whenIdle(fn: () => void | Promise<void>): void {
else setTimeout(run, 2_000)
}
function shouldCache(trip: Trip): boolean {
/**
* Would the date rule keep this trip on its own? Exported so the offline
* settings screen can show the honest state of a trip's switch: a finished trip
* is not stored unless the user pins it, and a switch that reads "on" while
* nothing is stored is what made "Download for offline use" look broken (#2228).
*/
export function isDateEligible(trip: Trip): boolean {
if (!trip.end_date) return true // no end date → cache forever
return trip.end_date >= todayStr() // ongoing or future
}
function shouldCache(trip: Trip): boolean {
return isTripPinned(trip.id) || isDateEligible(trip)
}
function isStale(trip: Trip): boolean {
if (!trip.end_date) return false
if (isTripPinned(trip.id)) return false // the user asked for it, keep it
const cutoff = new Date()
cutoff.setDate(cutoff.getDate() - 7)
return trip.end_date < ymd(cutoff)
@@ -185,14 +196,32 @@ async function reconcileTrips(trips: Trip[]): Promise<Trip[]> {
return trips.filter(t => shouldCache(t) && isTripOfflineEnabled(t.id))
}
/**
* Why a sync did nothing. The settings screen shows these: a run that never
* started used to be indistinguishable from a run that stored everything, so
* "Download for offline use" reported success while the cache stayed at zero
* and the user had no way to tell (#2228).
*/
export type SyncOutcome =
| { status: 'done'; trips: number }
| { status: 'skipped'; reason: 'busy' | 'offline' | 'signed-out' }
function skipReason(): SyncOutcome | null {
if (_syncing) return { status: 'skipped', reason: 'busy' }
if (!navigator.onLine) return { status: 'skipped', reason: 'offline' }
if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' }
return null
}
export const tripSyncManager = {
/**
* Sync all cache-eligible trips.
* Evicts stale and user-disabled trips. Caches file blobs + map tiles in the
* background. No-ops when offline.
*/
async syncAll(): Promise<void> {
if (_syncing || !navigator.onLine || !isAuthed()) return
async syncAll(): Promise<SyncOutcome> {
const skipped = skipReason()
if (skipped) return skipped
_syncing = true
try {
const { trips } = await tripsApi.list() as { trips: Trip[] }
@@ -201,7 +230,7 @@ export const tripSyncManager = {
for (const trip of toSync) {
// The gate is re-read per trip: a logout halfway through must not keep
// writing the old account's rows into the (now anonymous) offline DB.
if (!isAuthed()) return
if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' }
try {
await syncTrip(trip.id)
} catch (err) {
@@ -220,7 +249,7 @@ export const tripSyncManager = {
const tileUrl = useSettingsStore.getState().settings.map_tile_url || undefined
const cartoKey = useSettingsStore.getState().settings.carto_api_key || undefined
for (const trip of toSync) {
if (!isAuthed()) return
if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' }
const files = await offlineDb.tripFiles.where('trip_id').equals(trip.id).toArray()
cacheFilesForTrip(trip.id, files).catch(console.error)
}
@@ -238,6 +267,7 @@ export const tripSyncManager = {
}
})
}
return { status: 'done', trips: toSync.length }
} finally {
_syncing = false
}
@@ -250,10 +280,11 @@ export const tripSyncManager = {
* front instead of deferring them to idle time, reports progress, and forces
* the tile prefetch to run even for a bbox we believe is already cached.
*
* Returns the number of trips prepared.
* Returns how many trips were prepared, or why the run never started.
*/
async prepareForOffline(onProgress?: (p: PrepareProgress) => void): Promise<number> {
if (_syncing || !navigator.onLine || !isAuthed()) return 0
async prepareForOffline(onProgress?: (p: PrepareProgress) => void): Promise<SyncOutcome> {
const skipped = skipReason()
if (skipped) return skipped
_syncing = true
try {
const { trips } = await tripsApi.list() as { trips: Trip[] }
@@ -263,7 +294,7 @@ export const tripSyncManager = {
// 1) Trip bundles (structured data).
let i = 0
for (const trip of toSync) {
if (!isAuthed()) return 0
if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' }
onProgress?.({ phase: 'trips', current: ++i, total, label: trip.title })
try {
await syncTrip(trip.id)
@@ -281,7 +312,7 @@ export const tripSyncManager = {
// 2) File blobs — awaited so "prepared" really means downloaded.
i = 0
for (const trip of toSync) {
if (!isAuthed()) return 0
if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' }
onProgress?.({ phase: 'files', current: ++i, total, label: trip.title })
const files = await offlineDb.tripFiles.where('trip_id').equals(trip.id).toArray()
await cacheFilesForTrip(trip.id, files).catch(console.error)
@@ -293,7 +324,7 @@ export const tripSyncManager = {
const cartoKey = useSettingsStore.getState().settings.carto_api_key || undefined
i = 0
for (const trip of toSync) {
if (!isAuthed()) return 0
if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' }
onProgress?.({ phase: 'tiles', current: ++i, total, label: trip.title })
const places = await offlineDb.places.where('trip_id').equals(trip.id).toArray()
await prefetchTilesForTrip(trip.id, places, tileUrl, true, cartoKey).catch(console.error)
@@ -301,7 +332,7 @@ export const tripSyncManager = {
}
onProgress?.({ phase: 'done', current: total, total })
return total
return { status: 'done', trips: total }
} finally {
_syncing = false
}