Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 4 additions & 22 deletions config/rsbuild/rsbuild.common.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {RsbuildConfig} from '@rsbuild/core';
import type {DefinePluginOptions, RspackPluginInstance, SwcJsMinimizerRspackPluginOptions} from '@rspack/core';

import {GenerateSW} from '@aaroon/workbox-rspack-plugin';
import {InjectManifest} from '@aaroon/workbox-rspack-plugin';
import {pluginSvgr} from '@rsbuild/plugin-svgr';
import {RsdoctorRspackPlugin} from '@rsdoctor/rspack-plugin';
import {rspack} from '@rspack/core';
Expand Down Expand Up @@ -521,9 +521,9 @@ const getCommonConfiguration = async ({file = '.env', platform = 'web', isDevSer
...(isDevelopment
? []
: [
new GenerateSW({
clientsClaim: true,
skipWaiting: true,
new InjectManifest({
swSrc: path.resolve(dirname, '../../web/service-worker.ts'),
swDest: 'service-worker.js',
// Cap is generous on purpose: the vendor (~6.5 MiB), main (~5.5 MiB),
// authScreens.prefetch (~10.1 MiB) chunks and the canvaskit wasm (~7.7 MiB) are
// all critical for offline boot, so we precache the lot. JS chunks are
Expand All @@ -535,24 +535,6 @@ const getCommonConfiguration = async ({file = '.env', platform = 'web', isDevSer
// worker requests the original URLs and the CDN transparently serves the Brotli copy,
// so adding the twins to the precache as well would download every chunk twice.
exclude: [/\.map$/, /^manifest.*\.js$/, /\.br$/],
// Single-page app: any unmatched navigation should serve the cached app shell.
navigateFallback: '/index.html',
// Don't fall back for asset-like or .well-known requests.
navigateFallbackDenylist: [/^\/_/, /^\/\.well-known/, /\/[^/?]+\.[^/]+$/],
runtimeCaching: [
{
// Same-origin user media (receipts, chat attachments) — cache opportunistically
// so they're viewable on offline refresh. The function below is serialized into
// the generated service worker, so it executes in the SW context where
// `sameOrigin` is the appropriate Workbox match (no need to read `self.location`).
urlPattern: ({sameOrigin, url, request}) => sameOrigin && (request.destination === 'image' || /\/(receipts|chat-attachments)\//.test(url.pathname)),
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'user-media',
expiration: {maxEntries: 200, maxAgeSeconds: 7 * 24 * 60 * 60},
},
},
],
}),
]),
// Inject <link rel="prefetch/preload" /> into HTML.
Expand Down
3 changes: 3 additions & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -951,6 +951,8 @@
"prebuild",
"prebuilds",
"precheck",
"precached",
"precaching",
"prescribers",
"presentationml",
"prestep",
Expand Down Expand Up @@ -1045,6 +1047,7 @@
"sideloaded",
"sideproject",
"simctl",
"serviceworker",
"showcerts",
"simployer",
"skia",
Expand Down
1 change: 1 addition & 0 deletions knip.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"src/HybridAppHandler.tsx",
"scripts/**/*.{js,mjs,ts}",
"web/proxy.ts",
"web/service-worker.ts",
"config/rsbuild/**/*.{js,mjs,cjs,ts}",
"config/repack/**/*.{js,mjs,ts}",
".github/scripts/**/*.ts",
Expand Down
7 changes: 6 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,12 @@
"type-fest": "4.35.0",
"typescript": "^7.0.2",
"typescript-eslint": "8.58.1",
"wait-port": "^0.2.9"
"wait-port": "^0.2.9",
"workbox-core": "7.4.0",
"workbox-expiration": "7.4.0",
"workbox-precaching": "7.4.0",
"workbox-routing": "7.4.0",
"workbox-strategies": "7.4.0"
},
"overrides": {
"typescript": "$typescript",
Expand Down
10 changes: 10 additions & 0 deletions src/libs/AppUpdateURL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/** Shared URL marker for upgrade navigations that must wait for fresh HTML. */
const APP_UPDATE_QUERY_PARAM = 'appUpdateRequired';

function getAppUpdateURL(href: string): string {
const url = new URL(href);
url.searchParams.set(APP_UPDATE_QUERY_PARAM, 'true');
return url.href;
}

export {APP_UPDATE_QUERY_PARAM, getAppUpdateURL};
7 changes: 3 additions & 4 deletions src/libs/actions/AppUpdate/updateApp/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import clearWorkboxRecoveryCaches from '@libs/clearWorkboxRecoveryCaches';
import {getAppUpdateURL} from '@libs/AppUpdateURL';

/**
* On web or mWeb, clear stale service worker and Cache Storage entries before reloading
* so the user gets the latest bundle instead of a cached version that triggers Update Required.
* The upgrade marker prevents a slow network from sending the user back to an unsupported cached shell.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export default function updateApp(isProduction: boolean) {
clearWorkboxRecoveryCaches().then(() => window.location.reload());
window.location.replace(getAppUpdateURL(window.location.href));
}
2 changes: 1 addition & 1 deletion src/libs/actions/Session/clearCache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const clearStorage: ClearCache = async () => {
// Clear the service worker's user-media cache so receipts and attachments
// from one user's session cannot be served to a subsequent user on the
// same browser (shared device / account switching). Must match the
// `cacheName` string in `config/rsbuild/rsbuild.common.ts` (GenerateSW).
// `cacheName` string in `web/service-worker.ts`.
if (typeof caches !== 'undefined') {
await caches.delete('user-media');
}
Expand Down
8 changes: 4 additions & 4 deletions src/libs/actions/UpdateRequired/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import clearWorkboxRecoveryCaches from '@libs/clearWorkboxRecoveryCaches';
import {getAppUpdateURL} from '@libs/AppUpdateURL';
import Log from '@libs/Log';

import CONST from '@src/CONST';
Expand Down Expand Up @@ -29,7 +29,7 @@ function markReloadAttempted(): boolean {

/**
* Web should always serve the latest version, so a 426 usually means the browser loaded an old bundle from its cache.
* The app version is baked into the bundle, so the request can only be retried with a new bundle: clear the caches and reload,
* The app version is baked into the bundle, so the request can only be retried with a new bundle: reload from the network,
* and show the Update Required screen if the same bundle version still gets a 426 afterwards.
*/
function alertUser() {
Expand All @@ -40,11 +40,11 @@ function alertUser() {
hasHandledUpdateRequired = true;

if (markReloadAttempted()) {
clearWorkboxRecoveryCaches().then(() => window.location.reload());
window.location.replace(getAppUpdateURL(window.location.href));
return;
}

Log.alert('[UpdateRequired] Got a 426 on web after clearing the cache and reloading', {appVersion: pkg.version});
Log.alert('[UpdateRequired] Got a 426 on web after reloading', {appVersion: pkg.version});
Onyx.set(ONYXKEYS.RAM_ONLY_UPDATE_REQUIRED, true);
}

Expand Down
14 changes: 12 additions & 2 deletions src/pages/ErrorPage/UpdateRequiredView/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import updateApp from '@userActions/AppUpdate/updateApp';

import CONST from '@src/CONST';

import React from 'react';
import React, {useState} from 'react';
import {View} from 'react-native';

function UpdateRequiredView() {
Expand All @@ -34,6 +34,15 @@ function UpdateRequiredView() {
const isReduceMotionEnabled = Accessibility.useReducedMotion();
const illustrations = useMemoizedLazyIllustrations(['UpgradeRocket']);
const {isProduction} = useEnvironment();
const [isRefreshing, setIsRefreshing] = useState(false);

const refreshPage = () => {
if (isRefreshing) {
return;
}
setIsRefreshing(true);
updateApp(isProduction);
};

return (
<View style={[styles.appBG, styles.h100, StyleUtils.getPlatformSafeAreaPadding(insets)]}>
Expand Down Expand Up @@ -69,7 +78,8 @@ function UpdateRequiredView() {
<Button
variant={CONST.BUTTON_VARIANT.SUCCESS}
size={CONST.BUTTON_SIZE.LARGE}
onPress={() => updateApp(isProduction)}
onPress={refreshPage}
isLoading={isRefreshing}
style={styles.updateRequiredViewTextContainer}
>
<Button.Text>{translate('updateRequiredView.refreshPage')}</Button.Text>
Expand Down
12 changes: 10 additions & 2 deletions src/setup/platformSetup/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {APP_UPDATE_QUERY_PARAM} from '@libs/AppUpdateURL';
import CacheAPI from '@libs/CacheAPI';
import checkForUpdates from '@libs/checkForUpdates';
import DateUtils from '@libs/DateUtils';
Expand Down Expand Up @@ -59,6 +60,13 @@ const webUpdater = (): PlatformSpecificUpdater => ({
});

export default function () {
// The worker has already handled this navigation. Later navigations should open the saved app instead of waiting for the network.
const url = new URL(window.location.href);
if (url.searchParams.has(APP_UPDATE_QUERY_PARAM)) {
url.searchParams.delete(APP_UPDATE_QUERY_PARAM);
window.history.replaceState(window.history.state, '', url.href);
}

// Initialize Cache API
CacheAPI.init();

Expand All @@ -74,10 +82,10 @@ export default function () {
// Start current date updater
DateUtils.startCurrentDateUpdater();

// Service worker is only emitted in production builds (GenerateSW is skipped in dev).
// Service worker is only emitted in production builds (InjectManifest is skipped in dev).
if (Config.IS_IN_PRODUCTION && 'serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js').catch((error) => {
navigator.serviceWorker.register('/service-worker.js', {updateViaCache: 'none'}).catch((error) => {
// Soft-fail: app must continue working even if SW registration fails (Safari Private mode, etc.).
// eslint-disable-next-line no-console
console.warn('[SW] registration failed', error);
Expand Down
54 changes: 41 additions & 13 deletions tests/unit/UpdateRequiredTest.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import {APP_UPDATE_QUERY_PARAM, getAppUpdateURL} from '@libs/AppUpdateURL';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';

Expand All @@ -7,7 +9,7 @@ import pkg from '../../package.json';
import waitForBatchedUpdates from '../utils/waitForBatchedUpdates';

// Factory mocks share these functions across the isolated module registries each test loads.
const mockClearWorkboxRecoveryCaches = jest.fn(() => Promise.resolve());
const mockClearWorkboxRecoveryCaches = jest.fn(() => new Promise<void>(() => {}));
jest.mock('@libs/clearWorkboxRecoveryCaches', () => ({
__esModule: true,
default: () => mockClearWorkboxRecoveryCaches(),
Expand Down Expand Up @@ -39,13 +41,14 @@ function loadWebUpdateRequired(): UpdateRequiredModule {
}

describe('UpdateRequired (web)', () => {
const reloadMock = jest.fn();
const replaceMock = jest.fn();
const currentURL = 'https://new.expensify.com/r/123?existing=value#details';
const originalLocation = window.location;

beforeAll(() => {
Object.defineProperty(window, 'location', {
configurable: true,
value: {reload: reloadMock},
value: {href: currentURL, replace: replaceMock},
});
});

Expand All @@ -62,17 +65,18 @@ describe('UpdateRequired (web)', () => {
sessionStorage.clear();
});

it('clears the cache and reloads on the first 426 instead of showing the Update Required screen', async () => {
// Given a web app that has not tried reloading for a 426 yet
it('reloads immediately on the first 426 without waiting for service worker cleanup', async () => {
// Given a web app that has not tried reloading and service worker cleanup that would never settle
const {alertUser} = loadWebUpdateRequired();

// When a request gets a 426
alertUser();
expect(replaceMock).toHaveBeenCalledTimes(1);
await waitForBatchedUpdates();

// Then the cache is cleared and the page reloads, because the stale bundle can only be replaced by a reload
expect(mockClearWorkboxRecoveryCaches).toHaveBeenCalledTimes(1);
expect(reloadMock).toHaveBeenCalledTimes(1);
// Then navigation can load fresh HTML immediately, preserving the worker and its offline assets
expect(mockClearWorkboxRecoveryCaches).not.toHaveBeenCalled();
expect(replaceMock).toHaveBeenCalledWith(getAppUpdateURL(currentURL));
expect(mockOnyxSet).not.toHaveBeenCalled();
});

Expand All @@ -86,7 +90,7 @@ describe('UpdateRequired (web)', () => {
await waitForBatchedUpdates();

// Then only one reload is triggered and the Update Required screen is not shown
expect(reloadMock).toHaveBeenCalledTimes(1);
expect(replaceMock).toHaveBeenCalledTimes(1);
expect(mockLogAlert).not.toHaveBeenCalled();
});

Expand All @@ -100,7 +104,7 @@ describe('UpdateRequired (web)', () => {
await waitForBatchedUpdates();

// Then it stops reloading to avoid a loop, shows the Update Required screen, and alerts because the reload didn't get a new bundle
expect(reloadMock).not.toHaveBeenCalled();
expect(replaceMock).not.toHaveBeenCalled();
expect(mockLogAlert).toHaveBeenCalledTimes(1);
expect(mockOnyxSet).toHaveBeenCalledWith(ONYXKEYS.RAM_ONLY_UPDATE_REQUIRED, true);
});
Expand Down Expand Up @@ -129,8 +133,8 @@ describe('UpdateRequired (web)', () => {
alertUser();
await waitForBatchedUpdates();

// Then it gets its own cache clear and reload instead of going straight to the Update Required screen
expect(reloadMock).toHaveBeenCalledTimes(1);
// Then it gets its own reload instead of going straight to the Update Required screen
expect(replaceMock).toHaveBeenCalledTimes(1);
expect(mockLogAlert).not.toHaveBeenCalled();
expect(sessionStorage.getItem(CONST.SESSION_STORAGE_KEYS.UPDATE_REQUIRED_RELOADED_VERSION)).toBe(pkg.version);
});
Expand All @@ -147,7 +151,31 @@ describe('UpdateRequired (web)', () => {
await waitForBatchedUpdates();

// Then it does not reload, since without a record every reload would get a 426 and reload again forever
expect(reloadMock).not.toHaveBeenCalled();
expect(replaceMock).not.toHaveBeenCalled();
expect(mockOnyxSet).toHaveBeenCalledWith(ONYXKEYS.RAM_ONLY_UPDATE_REQUIRED, true);
});

it('reloads immediately when the user presses Refresh, without clearing offline assets', () => {
// Given the web upgrade action and service worker cleanup that would never settle
const {default: updateApp} = jest.requireActual<{default: (isProduction: boolean) => void}>('../../src/libs/actions/AppUpdate/updateApp/index.ts');

// When the user presses Refresh
updateApp(true);

// Then the navigation starts without waiting for an installation or destroying the offline cache
expect(replaceMock).toHaveBeenCalledWith(getAppUpdateURL(currentURL));
expect(mockClearWorkboxRecoveryCaches).not.toHaveBeenCalled();
});

it('marks upgrade navigations without losing the route, query parameters, or fragment', () => {
// Given the user is viewing a deep link with existing parameters and a fragment
// When an upgrade reload is requested twice
const url = new URL(getAppUpdateURL(getAppUpdateURL(currentURL)));

// Then the marker is added once and the original destination is preserved
expect(url.pathname).toBe('/r/123');
expect(url.searchParams.get('existing')).toBe('value');
expect(url.hash).toBe('#details');
expect(url.searchParams.getAll(APP_UPDATE_QUERY_PARAM)).toEqual(['true']);
});
});
Loading
Loading