diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts index af625ed08..1304f03b5 100644 --- a/client/src/native/nativeApp.test.ts +++ b/client/src/native/nativeApp.test.ts @@ -52,7 +52,7 @@ beforeEach(() => { vi.mocked(isNativeIos).mockReturnValue(false); vi.mocked(isNativeAndroid).mockReturnValue(false); vi.mocked(isEffectivelyOffline).mockReturnValue(false); - vi.mocked(keepOfflineShellFresh).mockResolvedValue(); + vi.mocked(keepOfflineShellFresh).mockResolvedValue(true); vi.mocked(hasNativeFeature).mockReturnValue(false); document.documentElement.classList.remove('dark'); document.documentElement.removeAttribute('data-native-app'); diff --git a/client/src/native/offlineShell.test.ts b/client/src/native/offlineShell.test.ts index 548a0dfaf..821fa1f3d 100644 --- a/client/src/native/offlineShell.test.ts +++ b/client/src/native/offlineShell.test.ts @@ -100,6 +100,20 @@ describe('keepOfflineShellFresh', () => { expect(fetched).toContain('/assets/fr-bbbb2222.js'); }); + it('retries the iOS warm-up when a route chunk returned an HTTP error', async () => { + const fetchImpl = vi.fn(async (input: RequestInfo | URL) => { + if (String(input) === '/asset-manifest.json') return new Response(JSON.stringify(manifest)); + if (String(input) === '/assets/AtlasPage-99887766.js') return new Response(null, { status: 503 }); + return new Response('asset'); + }); + + await keepOfflineShellFresh(fetchImpl); + expect(fetchImpl).toHaveBeenCalledWith('/assets/AtlasPage-99887766.js', { priority: 'low' }); + fetchImpl.mockClear(); + await keepOfflineShellFresh(fetchImpl); + expect(fetchImpl).toHaveBeenCalledWith('/assets/AtlasPage-99887766.js', { priority: 'low' }); + }); + it('on Android hands the list to the native store instead of fetching it here', async () => { vi.mocked(TrekShell.refreshOfflineCopy).mockResolvedValue({ saved: true, complete: true }); const fetchImpl = vi.fn(async (input: RequestInfo | URL) => { diff --git a/client/src/native/offlineShell.ts b/client/src/native/offlineShell.ts index 0b2915e1c..42ccaf94d 100644 --- a/client/src/native/offlineShell.ts +++ b/client/src/native/offlineShell.ts @@ -22,7 +22,8 @@ const MANIFEST_URL = '/asset-manifest.json'; */ const CONCURRENCY = 2; /** The build whose files are all in the cache; a launch on the same build skips the walk. */ -const WARMED_KEY = 'trek.offlineShellBuild'; +// Older iOS builds counted an HTTP error page as a cached asset. Warm those builds once more. +const WARMED_KEY = 'trek.offlineShellBuild.v2'; const LOCALE_KEY = /\/i18n\/([^/]+)\/index\.[cm]?js$/; interface ManifestChunk { @@ -105,22 +106,26 @@ export async function keepOfflineShellFresh( fetchImpl: typeof fetch = fetch, language?: string, nativeStore = false -): Promise { - if (!nativeStore) await TrekShell.refreshOfflineCopy(); +): Promise { + const startPage = nativeStore ? null : await TrekShell.refreshOfflineCopy(); const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' }); - if (!response.ok) return; + if (!response.ok) return false; const files = manifestFiles(await response.json(), language); + if (!files.length) return false; // The build and the language together: a new language needs its own chunk. const build = `${[...files].sort((a, b) => a.localeCompare(b)).find((f) => /index-[^/]+\.js$/.test(f)) ?? files.length}:${language ?? 'en'}`; if (nativeStore) { // The native side fetches only what its store lacks, and keeps the start page fresh each time. const { complete } = await TrekShell.refreshOfflineCopy({ files: [...new Set([...files, ...pageScripts()])] }); if (complete) rememberWarmed(build); - return; + return complete === true; } - if (warmedBuild() === build) return; - const complete = await warmCache(files, (path) => - fetchImpl(path, { priority: 'low' } as RequestInit).then((r) => r.blob()) - ); + if (warmedBuild() === build) return startPage?.saved === true; + const complete = await warmCache(files, async (path) => { + const asset = await fetchImpl(path, { priority: 'low' } as RequestInit); + if (!asset.ok) throw new Error(`Could not cache ${path}: HTTP ${asset.status}`); + await asset.blob(); + }); if (complete) rememberWarmed(build); + return complete && startPage?.saved === true; } diff --git a/client/src/sync/tripSyncManager.prepare.test.ts b/client/src/sync/tripSyncManager.prepare.test.ts index eb003bbc0..a2a1e0588 100644 --- a/client/src/sync/tripSyncManager.prepare.test.ts +++ b/client/src/sync/tripSyncManager.prepare.test.ts @@ -12,8 +12,16 @@ import { setCacheTiles, setTripOfflineEnabled, _resetOfflinePrefs } from './offl import { prefetchPlacesForTrip } from './placePrefetcher' import { offlineDb, clearAll, upsertTrip } from '../db/offlineDb' import { buildTrip, buildDay, buildPlace, buildTripFile } from '../../tests/helpers/factories' +import { keepOfflineShellFresh } from '../native/offlineShell' +import { isNativeIos } from '../native/platform' import type { Trip, TripFile } from '../types' +vi.mock('../native/platform', async (importOriginal) => ({ + ...(await importOriginal()), + isNativeIos: vi.fn(() => false), +})) +vi.mock('../native/offlineShell', () => ({ keepOfflineShellFresh: vi.fn() })) + vi.mock('./tilePrefetcher', () => ({ prefetchTilesForTrip: vi.fn(async () => {}), })) @@ -77,6 +85,8 @@ beforeEach(async () => { }) afterEach(() => { + vi.mocked(isNativeIos).mockReset() + vi.mocked(keepOfflineShellFresh).mockReset() vi.restoreAllMocks() vi.unstubAllGlobals() _resetOfflinePrefs() @@ -142,6 +152,34 @@ describe('tripSyncManager.prepareForOffline — full run', () => { expect(await offlineDb.tripMembers.where('tripId').equals(602).count()).toBe(1) }) + it('waits for the iOS UI copy before reporting an offline download as ready', async () => { + vi.mocked(isNativeIos).mockReturnValue(true) + let publishCopy: (() => void) | undefined + vi.mocked(keepOfflineShellFresh).mockImplementation(() => new Promise(resolve => { + publishCopy = () => resolve(true) + })) + const trip = buildTrip({ id: 611, end_date: dateOffset(4) }) + serveTrips([trip], { 611: bundleFor(trip) }) + const progress = vi.fn() + const download = tripSyncManager.prepareForOffline(progress, trip) + + try { + await vi.waitFor(() => expect(keepOfflineShellFresh).toHaveBeenCalledOnce()) + expect(progress).not.toHaveBeenCalledWith(expect.objectContaining({ phase: 'done' })) + } finally { + publishCopy?.() + await download + } + + expect(await download).toEqual({ status: 'done', trips: 1 }) + expect(await offlineDb.trips.get(611)).toBeDefined() + + vi.mocked(keepOfflineShellFresh).mockResolvedValue(false) + progress.mockClear() + await expect(tripSyncManager.prepareForOffline(progress, trip)).rejects.toThrow('The offline app could not be cached') + expect(progress).not.toHaveBeenCalledWith(expect.objectContaining({ phase: 'done' })) + }) + it('FE-SYNC-PREP-006: forces the tile prefetch so an already-cached bbox is refreshed', async () => { const trip = buildTrip({ id: 603, end_date: dateOffset(4) }) serveTrips([trip], { 603: bundleFor(trip) }) diff --git a/client/src/sync/tripSyncManager.ts b/client/src/sync/tripSyncManager.ts index 86cf6c589..1386fa17f 100644 --- a/client/src/sync/tripSyncManager.ts +++ b/client/src/sync/tripSyncManager.ts @@ -33,6 +33,8 @@ import { prefetchTilesForTrip } from './tilePrefetcher' import { isAuthed } from './authGate' import { isEffectivelyOffline } from './networkMode' import { getOfflinePrefs, isTripOfflineEnabled, isTripPinned, setTripOfflineEnabled, setTripPinned } from './offlinePrefs' +import { keepOfflineShellFresh } from '../native/offlineShell' +import { isNativeIos } from '../native/platform' import { useSettingsStore } from '../store/settingsStore' import { useAddonStore } from '../store/addonStore' import { useTripAddonsStore } from '../store/tripAddonsStore' @@ -459,6 +461,7 @@ export const tripSyncManager = { } } + await prepareOfflineUi() if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' } onProgress?.({ phase: 'done', current: prepared.length, total: prepared.length }) return { status: 'done', trips: prepared.length } @@ -473,6 +476,13 @@ export const tripSyncManager = { }, } +async function prepareOfflineUi(): Promise { + // The trip bundle is unusable on iOS if WebKit cannot load the planner itself. + if (!isAuthed() || !isNativeIos()) return + const ready = await keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language) + if (!ready) throw new Error('The offline app could not be cached') +} + async function offlineTripCandidates(selectedTrip?: Trip) { if (selectedTrip) return [selectedTrip] const [{ trips }, archived] = await Promise.all([tripsApi.list() as Promise<{ trips: Trip[] }>, archivedTrips()])