Skip to content

Build your personal knowledge base with Trilium Notes

fix(mobile): remove the service worker an older Android build left behind (closes #12170)

Elian Doran5ee394196336
diff --git a/.claude/skills/developing-capacitor-mobile/SKILL.md b/.claude/skills/developing-capacitor-mobile/SKILL.md
index 97a7def36c..0fe910294c 100644
--- a/.claude/skills/developing-capacitor-mobile/SKILL.md
+++ b/.claude/skills/developing-capacitor-mobile/SKILL.md
@@ -52,7 +52,7 @@ Consequences that keep tripping people up:
- **Android WebView applies a request's `Range` to the intercepted stream itself.** Chromium's `AndroidStreamReaderURLLoader` treats the `InputStream` as the whole resource and skips `first_byte_position` bytes before reading, while keeping our status and headers. The worker has already cut the `206` slice, so `LocalRequestBroker` reads the start from its `Content-Range` and `ChunkStream.skip()` passes over that many bytes without reading. Without it every range past byte 0 lands in the wrong place or runs off the end (`ERR_REQUEST_RANGE_NOT_SATISFIABLE`), which breaks seeking and any MP4 whose `moov` index sits at the end. Keep `available()` at 0: that is what makes Chromium skip its own bounds check.
- **Standalone caps `bytes=N-` media responses at 8 MiB** (`maxOpenRangeLength` in `serveContentWithRanges()`, set by `openPartialInt()` when `getPlatform().isStandalone`), because each response is buffered whole on the page and copied through the bridge. The element asks for the next range on its own; ranges with an explicit end are served as asked.
- **Three prefix lists must agree**: `isLocalApiRequest()` in `local-bridge.ts`, `LocalRequestBroker.isLocalPath()` in Java and `isLocalApiPath()` in Swift, including the `/share` rule.
-- **A service worker registered by an older Android build still controls the page.** Its fetches never reach `shouldInterceptRequest`, and with no `attachServiceWorkerBridge()` nothing answers them. Clearing the app's data or reinstalling removes it.
+- **A service worker registered by an older Android build still controls the page.** Its fetches never reach `shouldInterceptRequest`, and with no `attachServiceWorkerBridge()` nothing answers them — a custom theme silently stops applying (#12170), images hang. `removeStaleServiceWorkers()` in `main.ts` unregisters it once the native bridge is installed and reloads if it was controlling. Never advise clearing the app's data: that deletes the OPFS database.
- `sw.ts` has a defensive `self.location.protocol === "capacitor:"` guard and must **let `/_trilium_native_http/` requests fall through** to the WebView (see below); keep both when editing its fetch handler.
## Outbound: how the worker syncs with a remote server
diff --git a/apps/standalone/src/main.spec.ts b/apps/standalone/src/main.spec.ts
index b3b00c8096..ca04f672f9 100644
--- a/apps/standalone/src/main.spec.ts
+++ b/apps/standalone/src/main.spec.ts
@@ -49,6 +49,7 @@ interface ServiceWorkerLike {
controller: unknown;
register: ReturnType<typeof vi.fn>;
ready: Promise<unknown>;
+ getRegistrations?: ReturnType<typeof vi.fn>;
}
interface WindowWithCapacitor {
@@ -205,6 +206,56 @@ describe("bootstrap", () => {
expect(document.body.innerHTML).toBe("");
});
+ it("removes a service worker an older shell build registered, reloading if it controls the page", async () => {
+ const win = window as unknown as WindowWithCapacitor;
+ win.Capacitor = {};
+ mocks.installNativeRequestBridge.mockReturnValue(true);
+
+ // An update installed over a build that answered through the SW: it still controls the
+ // page, and its fetches never reach the native bridge.
+ const controlling = { unregister: vi.fn().mockResolvedValue(true) };
+ setServiceWorker({
+ controller: {}, register: vi.fn(), ready: Promise.resolve(),
+ getRegistrations: vi.fn().mockResolvedValue([ controlling ])
+ });
+ await runBootstrap();
+ await vi.waitFor(() => expect(reloadSpy).toHaveBeenCalledTimes(1));
+ expect(controlling.unregister).toHaveBeenCalled();
+ expect(document.body.innerHTML).toBe("");
+
+ // A registration that controls nothing yet goes too, without a reload.
+ reloadSpy.mockClear();
+ const idle = { unregister: vi.fn().mockResolvedValue(true) };
+ setServiceWorker({
+ controller: null, register: vi.fn(), ready: Promise.resolve(),
+ getRegistrations: vi.fn().mockResolvedValue([ idle ])
+ });
+ await runBootstrap();
+ await vi.waitFor(() => expect(idle.unregister).toHaveBeenCalled());
+ expect(reloadSpy).not.toHaveBeenCalled();
+
+ // A failed unregister must not reload, or the page would reload forever.
+ const stuck = { unregister: vi.fn().mockResolvedValue(false) };
+ setServiceWorker({
+ controller: {}, register: vi.fn(), ready: Promise.resolve(),
+ getRegistrations: vi.fn().mockResolvedValue([ stuck ])
+ });
+ await runBootstrap();
+ await vi.waitFor(() => expect(stuck.unregister).toHaveBeenCalled());
+ expect(reloadSpy).not.toHaveBeenCalled();
+
+ // Where the registrations cannot be listed (WebKit on capacitor://), startup carries on.
+ setServiceWorker({
+ controller: null, register: vi.fn(), ready: Promise.resolve(),
+ getRegistrations: vi.fn().mockRejectedValue(new Error("SecurityError"))
+ });
+ await runBootstrap();
+ await vi.waitFor(() => expect(console.warn).toHaveBeenCalledWith(
+ "[Bootstrap] Could not remove a stale service worker:", expect.any(Error)));
+ expect(reloadSpy).not.toHaveBeenCalled();
+ expect(document.body.innerHTML).toBe("");
+ });
+
it("falls back to the SW when the shell has no native request bridge, and never asks on the web", async () => {
setServiceWorker({ controller: {}, register: vi.fn(), ready: Promise.resolve() });
await runBootstrap();
diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.ts
index 2750dd45b2..6ff8f691d6 100644
--- a/apps/standalone/src/main.ts
+++ b/apps/standalone/src/main.ts
@@ -132,7 +132,9 @@ async function bootstrap() {
// Android WebView without message listeners, the service worker does.
const answeredNatively = "Capacitor" in window
&& (await import("./native-request-bridge.js")).installNativeRequestBridge();
- if (!answeredNatively) {
+ if (answeredNatively) {
+ await removeStaleServiceWorkers();
+ } else {
attachServiceWorkerBridge();
await waitForServiceWorkerControl();
}
@@ -151,6 +153,32 @@ async function bootstrap() {
}
}
+/**
+ * Unregisters the service worker an older Android build installed. While it controls the page,
+ * engine-initiated requests (stylesheets, images, fonts) go to it instead of the native request
+ * bridge, and nothing answers them, so a controlled page reloads once the worker is gone.
+ */
+async function removeStaleServiceWorkers() {
+ try {
+ const registrations = await navigator.serviceWorker?.getRegistrations() ?? [];
+ let removed = false;
+ for (const registration of registrations) {
+ removed = await registration.unregister() || removed;
+ }
+
+ if (removed && navigator.serviceWorker?.controller) {
+ console.log("[Bootstrap] Removed a stale service worker - reloading page");
+ window.location.reload();
+ throw new Error("Reloading without the stale service worker");
+ }
+ } catch (err) {
+ if (err instanceof Error && err.message.startsWith("Reloading")) {
+ throw err;
+ }
+ console.warn("[Bootstrap] Could not remove a stale service worker:", err);
+ }
+}
+
/**
* Asks the browser to keep the storage the database lives in. Without the grant that storage is
* best-effort: WebKit drops it after about a week without a visit and Chromium evicts it under