diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts index 1304f03b5..73e8f9dfb 100644 --- a/client/src/native/nativeApp.test.ts +++ b/client/src/native/nativeApp.test.ts @@ -154,14 +154,14 @@ describe('startNativeApp', () => { startNativeApp(); expect(keepOfflineShellFresh).not.toHaveBeenCalled(); vi.advanceTimersByTime(15_000); - expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toBe(false); + expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toEqual({ nativeStore: false }); }); it('refreshes it on Android too, into the store of the app', () => { vi.mocked(isNativeAndroid).mockReturnValue(true); startNativeApp(); vi.advanceTimersByTime(15_000); - expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toBe(true); + expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toEqual({ nativeStore: true }); }); it('skips the refresh while offline', () => { diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts index 3d62f1a5b..d53626082 100644 --- a/client/src/native/nativeApp.ts +++ b/client/src/native/nativeApp.ts @@ -96,11 +96,11 @@ export function startNativeApp(): void { if (isEffectivelyOffline()) return; // Not refreshed this time is no harm: the next launch tries again. An app // older than the offline copy has no such method, which is no failure. - keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language, isNativeAndroid()).catch( - (err: unknown) => { - if (!isUnimplemented(err)) reportNativeFailure(err); - } - ); + keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language, { + nativeStore: isNativeAndroid(), + }).catch((err: unknown) => { + if (!isUnimplemented(err)) reportNativeFailure(err); + }); }, OFFLINE_SHELL_DELAY_MS); } diff --git a/client/src/native/offlineShell.test.ts b/client/src/native/offlineShell.test.ts index 821fa1f3d..713784b06 100644 --- a/client/src/native/offlineShell.test.ts +++ b/client/src/native/offlineShell.test.ts @@ -38,7 +38,7 @@ describe('manifestFiles', () => { }); describe('keepOfflineShellFresh', () => { - it('refreshes the stored start page and fetches every file of the build', async () => { + it('tries every asset even when one fails and does not replace the stored start page', async () => { const fetched: string[] = []; const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input); @@ -53,7 +53,7 @@ describe('keepOfflineShellFresh', () => { await keepOfflineShellFresh(fetchImpl); - expect(TrekShell.refreshOfflineCopy).toHaveBeenCalled(); + expect(TrekShell.refreshOfflineCopy).not.toHaveBeenCalled(); expect(fetched.sort()).toEqual([ '/assets/AtlasPage-99887766.js', '/assets/index-a1b2c3d4.js', @@ -63,10 +63,11 @@ describe('keepOfflineShellFresh', () => { ]); }); - it('stops after the start page when the build has no manifest', async () => { + it('keeps the previous start page when the build has no manifest', async () => { const fetchImpl = vi.fn(async () => new Response('', { status: 404 })) as unknown as typeof fetch; await keepOfflineShellFresh(fetchImpl); expect(fetchImpl).toHaveBeenCalledTimes(1); + expect(TrekShell.refreshOfflineCopy).not.toHaveBeenCalled(); }); it('fetches at low priority, only the own language, and once per build', async () => { @@ -114,6 +115,31 @@ describe('keepOfflineShellFresh', () => { expect(fetchImpl).toHaveBeenCalledWith('/assets/AtlasPage-99887766.js', { priority: 'low' }); }); + it('rechecks the marked iOS shell on demand and keeps the previous start page if an asset is missing', async () => { + const chunk = '/assets/AtlasPage-99887766.js'; + let chunkAvailable = true; + const fetchImpl = vi.fn(async (input: RequestInfo | URL) => { + if (String(input) === '/asset-manifest.json') return new Response(JSON.stringify(manifest)); + if (String(input) === chunk && !chunkAvailable) return new Response(null, { status: 503 }); + return new Response('asset'); + }); + + expect(await keepOfflineShellFresh(fetchImpl)).toBe(true); + expect(await keepOfflineShellFresh(fetchImpl)).toBe(true); + expect(fetchImpl.mock.calls.filter(([url]) => url === chunk)).toHaveLength(1); + vi.mocked(TrekShell.refreshOfflineCopy).mockClear(); + chunkAvailable = false; + + expect(await keepOfflineShellFresh(fetchImpl, 'en', { verifyAssets: true })).toBe(false); + expect(fetchImpl.mock.calls.filter(([url]) => url === chunk)).toHaveLength(2); + expect(TrekShell.refreshOfflineCopy).not.toHaveBeenCalled(); + + chunkAvailable = true; + expect(await keepOfflineShellFresh(fetchImpl)).toBe(true); + expect(fetchImpl.mock.calls.filter(([url]) => url === chunk)).toHaveLength(3); + expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledOnce(); + }); + 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) => { @@ -121,7 +147,7 @@ describe('keepOfflineShellFresh', () => { throw new Error('the native side fetches the files'); }) as unknown as typeof fetch; - await keepOfflineShellFresh(fetchImpl, 'en', true); + await keepOfflineShellFresh(fetchImpl, 'en', { nativeStore: true }); expect(fetchImpl).toHaveBeenCalledTimes(1); expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledTimes(1); @@ -142,7 +168,7 @@ describe('keepOfflineShellFresh', () => { const fetchImpl = vi.fn(async () => new Response(JSON.stringify(manifest))) as unknown as typeof fetch; try { - await keepOfflineShellFresh(fetchImpl, 'en', true); + await keepOfflineShellFresh(fetchImpl, 'en', { nativeStore: true }); } finally { document.head.innerHTML = ''; } @@ -158,8 +184,8 @@ describe('keepOfflineShellFresh', () => { vi.mocked(TrekShell.refreshOfflineCopy).mockResolvedValue({ saved: true, complete: false }); const fetchImpl = vi.fn(async () => new Response(JSON.stringify(manifest))) as unknown as typeof fetch; - await keepOfflineShellFresh(fetchImpl, 'en', true); - await keepOfflineShellFresh(fetchImpl, 'en', true); + await keepOfflineShellFresh(fetchImpl, 'en', { nativeStore: true }); + await keepOfflineShellFresh(fetchImpl, 'en', { nativeStore: true }); expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledTimes(2); }); diff --git a/client/src/native/offlineShell.ts b/client/src/native/offlineShell.ts index 42ccaf94d..de8bc7ef6 100644 --- a/client/src/native/offlineShell.ts +++ b/client/src/native/offlineShell.ts @@ -94,9 +94,10 @@ function warmedBuild(): string | null { } } -function rememberWarmed(build: string): void { +function recordWarmedBuild(build: string | null): void { try { - window.localStorage.setItem(WARMED_KEY, build); + if (build === null) window.localStorage.removeItem(WARMED_KEY); + else window.localStorage.setItem(WARMED_KEY, build); } catch { // Not remembered: the next launch walks the files again, from the cache. } @@ -105,9 +106,8 @@ function rememberWarmed(build: string): void { export async function keepOfflineShellFresh( fetchImpl: typeof fetch = fetch, language?: string, - nativeStore = false + { nativeStore = false, verifyAssets = false }: { nativeStore?: boolean; verifyAssets?: boolean } = {} ): Promise { - const startPage = nativeStore ? null : await TrekShell.refreshOfflineCopy(); const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' }); if (!response.ok) return false; const files = manifestFiles(await response.json(), language); @@ -117,15 +117,28 @@ export async function keepOfflineShellFresh( 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); + if (complete) recordWarmedBuild(build); return complete === true; } - if (warmedBuild() === build) return startPage?.saved === true; - const complete = await warmCache(files, async (path) => { - const asset = await fetchImpl(path, { priority: 'low' } as RequestInit); + const marked = warmedBuild() === build; + if (marked && !verifyAssets) return (await TrekShell.refreshOfflineCopy()).saved; + + // WebKit can evict an asset independently of localStorage. An explicit + // download visits every file again, reusing cached responses and filling misses. + const assets = verifyAssets ? [...new Set([...files, ...pageScripts()])] : files; + const request = { priority: 'low', ...(verifyAssets ? { cache: 'force-cache' } : {}) } as RequestInit; + const complete = await warmCache(assets, async (path) => { + const asset = await fetchImpl(path, request); 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; + if (!complete) { + if (marked) recordWarmedBuild(null); + return false; + } + + // Keep the previous start page until all assets of the current build are available. + const { saved } = await TrekShell.refreshOfflineCopy(); + if (saved) recordWarmedBuild(build); + return saved; } diff --git a/client/src/sync/tripSyncManager.prepare.test.ts b/client/src/sync/tripSyncManager.prepare.test.ts index a2a1e0588..87b28a02b 100644 --- a/client/src/sync/tripSyncManager.prepare.test.ts +++ b/client/src/sync/tripSyncManager.prepare.test.ts @@ -8,7 +8,7 @@ import { server } from '../../tests/helpers/msw/server' import { tripSyncManager, type PrepareProgress } from './tripSyncManager' import { prefetchTilesForTrip } from './tilePrefetcher' import { setAuthed } from './authGate' -import { setCacheTiles, setTripOfflineEnabled, _resetOfflinePrefs } from './offlinePrefs' +import { isTripPinned, setCacheTiles, setTripOfflineEnabled, _resetOfflinePrefs } from './offlinePrefs' import { prefetchPlacesForTrip } from './placePrefetcher' import { offlineDb, clearAll, upsertTrip } from '../db/offlineDb' import { buildTrip, buildDay, buildPlace, buildTripFile } from '../../tests/helpers/factories' @@ -173,11 +173,22 @@ describe('tripSyncManager.prepareForOffline — full run', () => { expect(await download).toEqual({ status: 'done', trips: 1 }) expect(await offlineDb.trips.get(611)).toBeDefined() + const meta = await offlineDb.syncMeta.get(611) + expect(meta?.lastSyncedAt).toBeGreaterThan(0) + expect(isTripPinned(611)).toBe(true) 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' })) + expect(await offlineDb.syncMeta.get(611)).toEqual(meta) + expect(isTripPinned(611)).toBe(true) + + const newTrip = buildTrip({ id: 612, end_date: dateOffset(-2) }) + serveTrips([newTrip], { 612: bundleFor(newTrip) }) + await expect(tripSyncManager.prepareForOffline(progress, newTrip)).rejects.toThrow('The offline app could not be cached') + expect(await offlineDb.syncMeta.get(612)).toBeUndefined() + expect(isTripPinned(612)).toBe(false) }) it('FE-SYNC-PREP-006: forces the tile prefetch so an already-cached bbox is refreshed', async () => { diff --git a/client/src/sync/tripSyncManager.ts b/client/src/sync/tripSyncManager.ts index 1386fa17f..6e2f3ecaf 100644 --- a/client/src/sync/tripSyncManager.ts +++ b/client/src/sync/tripSyncManager.ts @@ -405,6 +405,9 @@ export const tripSyncManager = { if (skipped) return skipped _syncing = true try { + // A trip must not gain a sync timestamp or a pin if its iOS UI is unavailable. + await prepareOfflineUi() + if (!isAuthed()) return { status: 'skipped', reason: 'signed-out' } const candidates = await offlineTripCandidates(selectedTrip) const total = candidates.length const prepared: Trip[] = [] @@ -461,7 +464,6 @@ 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 } @@ -479,7 +481,7 @@ 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) + const ready = await keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language, { verifyAssets: true }) if (!ready) throw new Error('The offline app could not be cached') }