Skip to content

Build your personal knowledge base with Trilium Notes

docs: record that the tab owning the worker answers its own API calls

Elian Doran4412cd5240a9
diff --git a/.claude/skills/developing-capacitor-mobile/SKILL.md b/.claude/skills/developing-capacitor-mobile/SKILL.md
index 1e3a37ed89..721d4ea504 100644
--- a/.claude/skills/developing-capacitor-mobile/SKILL.md
+++ b/.claude/skills/developing-capacitor-mobile/SKILL.md
@@ -28,7 +28,11 @@ apps/client/src/services/utils.ts # isMobileApp() — running inside th
## Inbound: how the client's API calls reach the in-app worker
-The client's `/api`, `/sync`, `/bootstrap`, `/search` requests (`LOCAL_API_PREFIXES` in `local-bridge.ts`) must be answered by the worker. The two platforms do it differently because their WebViews resolve `*Scheme: "https"` differently:
+The client's `/api`, `/sync`, `/bootstrap`, `/search` requests (`LOCAL_API_PREFIXES` in `local-bridge.ts`) must be answered by the worker.
+
+**Most of them never leave the page.** The shell is a single WebView, so its one tab always wins the database lock, and a tab that owns the worker publishes `localFetch` on `window.standaloneApi`; the client's `ajax()` and `setupGlob()`'s `/bootstrap` call it directly rather than issuing a request (see the standalone skill, "Request flow" step 3). That covers everything routed through `apps/client/src/services/server.ts`, on both platforms alike.
+
+What still leaves the page — engine-initiated loads (`<img src="api/images/…">`, `@font-face`, themes), `upload()`/`chunked_upload.ts`, the LLM stream — is where the platforms diverge, because their WebViews resolve `*Scheme: "https"` differently:
- **Android** — `androidScheme: "https"` works, the app runs at `https://localhost`, a real secure origin, so the **service worker** (`sw.ts`) intercepts those requests and forwards them to the worker — the same path as the web build.
- **iOS** — the app runs at **`capacitor://localhost`**, and WebKit refuses to register a service worker on a non-HTTP(S) origin. `main.ts` therefore installs **in-page interceptors** (`installIosInterceptors()`, gated on `location.protocol === "capacitor:"`), one per way a request can leave the page: `window.fetch`, `XMLHttpRequest` (jQuery `$.ajax` never touches fetch), `<img src="api/images/…">` (the image loader issues its own requests) and CSS-initiated loads (`@font-face url()` in injected styles, custom themes via `<link href="api/…">`). Each rewrites a local-API request into `localFetch()`.
diff --git a/.claude/skills/developing-standalone/SKILL.md b/.claude/skills/developing-standalone/SKILL.md
index 8890db7641..afe9b19ab4 100644
--- a/.claude/skills/developing-standalone/SKILL.md
+++ b/.claude/skills/developing-standalone/SKILL.md
@@ -13,7 +13,7 @@ description: Use when working on Trilium's standalone in-browser build (`apps/st
apps/standalone/
src/index.html, main.ts # page bootstrap: SW registration, leadership claim, worker start, standaloneApi
src/desktop.ts # re-exports apps/client/src/desktop — the client entry
- src/sw.ts # service worker: caches assets, forwards local API requests to the leader tab
+ src/sw.ts # service worker: caches assets, forwards follower tabs' API requests to the leader
src/leader_election.ts # Web Lock decides which tab owns the database worker
src/local-bridge.ts # page ⇄ worker protocol (LOCAL_REQUEST/RESPONSE, WS_MESSAGE, HTTP_REQUEST, backup/restore)
src/local-server-worker.ts # the worker: opens SQLite, initializeCore(), routes requests
@@ -30,10 +30,11 @@ apps/standalone/
## Request flow
-1. **`main.ts`** requires a service worker (secure context: HTTPS or localhost — otherwise it throws a message explaining that), registers `./sw.js` with scope `/`, reloads once if the SW installed but doesn't control the page yet, and exposes `window.standaloneApi` (`restore.importBackup`, `backup.downloadDatabase`) — the client's escape hatch for things carrying a whole file, the twin of desktop's `window.electronApi`.
+1. **`main.ts`** requires a service worker (secure context: HTTPS or localhost — otherwise it throws a message explaining that), registers `./sw.js` with scope `/`, reloads once if the SW installed but doesn't control the page yet, and exposes `window.standaloneApi` (`restore.importBackup`, `backup.downloadDatabase`) — the client's escape hatch for things carrying a whole file, the twin of desktop's `window.electronApi`. The leader also publishes `localFetch` there (step 3).
2. **Leader election** (`leader_election.ts`): the OPFS SAHPool VFS takes *exclusive* sync-access handles, and `createSyncAccessHandle` exists only in a dedicated worker, so exactly one tab per origin can own the database. A **Web Lock** (`trilium-standalone-db`, held for the tab's lifetime) picks it; only the winner calls `startLocalServerWorker()`; when it closes the browser releases the lock and a waiting tab is promoted. Where Web Locks are missing (some WebViews) the tab assumes it is alone.
-3. **Service worker** (`sw.ts`): cache-first for hashed assets, network-first otherwise; requests under `LOCAL_API_PREFIXES` (`/bootstrap`, `/api/`, `/sync/`, `/search/`, from `local-bridge.ts`) are forwarded with `LOCAL_FETCH` to the **leader** client, found via a cached id, `WHO_IS_LEADER` / `LEADER_REPLY` probing, and one retry on `NOT_LEADER` (leadership can flip while a request is in flight). Backup downloads stream over a `MessageChannel` from the leader. It must **let `/_trilium_native_http/` fall through** (Android native proxy) and has a defensive guard for `capacitor://`.
-4. **The worker** (`local-server-worker.ts`): waits for the previous worker's OPFS access handles to be released (`waitForSahPoolRelease` — a reload races the browser's asynchronous release, and `installOpfsSAHPoolVfs()` reacts to an acquisition failure by *deleting the pool directory*, so the pool must be acquirable before it runs — a wait that reaches its deadline ends the boot instead of installing anyway), then installs the SAHPool VFS **once** — failure is a fatal startup error painted by `error-overlay.ts`, never an in-memory fallback (`TRILIUM_INTEGRATION_TEST=memory` builds seed a fixture into the pool, so writes survive reloads within a test). It then calls `initializeCore({...})` with the `lightweight/*` providers, registers `createConfiguredRouter()` (`BrowserRouter` mimicking Express, path params + query strings), then answers `LOCAL_REQUEST` messages. `DbLock` (`lightweight/db_lock.ts`) serialises `createAsyncRoute` handlers (imports) that hold a transaction across `await`s against the single connection — synchronous routes keep a zero-overhead path. `WS_MESSAGE` replaces the WebSocket in both directions. Anything that escapes after startup is reported as `WORKER_ERROR` for one background task; before startup it means the app never came up and `error-overlay.ts` paints it (the async worker init is invisible to `main.ts`'s try/catch).
+3. **The leader answers its own API calls.** Winning the lock also publishes `localFetch` (`local-bridge.ts`) on `window.standaloneApi`, and the client prefers it over its XHR transport — in `ajax()` (`apps/client/src/services/server.ts`) and in `setupGlob()`'s `/bootstrap` (`apps/client/src/index.ts`). Without it the leader's own request leaves as an XHR, is intercepted by the service worker, and is posted back into the page it started in, to reach a worker that page owns. `localAjax()` matches the XHR path's contract — headers, JSON body, CSRF refresh-and-retry-once, the `silent*` suppressions, `raw`, and a timeout of `opts.timeoutMs ?? DEFAULT_TIMEOUT`. **Build with `VITE_DISABLE_LOCAL_FETCH=true` to take the service worker's route instead**, which is what compares the two transports. Follower tabs leave `localFetch` unset; so do `upload()`, `chunked_upload.ts` and the LLM stream, which carry `FormData` or want the body as it arrives.
+4. **Service worker** (`sw.ts`): cache-first for hashed assets, network-first otherwise; requests under `LOCAL_API_PREFIXES` (`/bootstrap`, `/api/`, `/sync/`, `/search/`, from `local-bridge.ts`) are forwarded with `LOCAL_FETCH` to the **leader** client, found via a cached id, `WHO_IS_LEADER` / `LEADER_REPLY` probing, and one retry on `NOT_LEADER` (leadership can flip while a request is in flight). Since step 3 this carries follower tabs, engine-initiated loads (`<img src="api/images/…">`, fonts, themes) and the call sites that reach past `server.ts`, rather than the whole API surface. Backup downloads stream over a `MessageChannel` from the leader. It must **let `/_trilium_native_http/` fall through** (Android native proxy) and has a defensive guard for `capacitor://`.
+5. **The worker** (`local-server-worker.ts`): waits for the previous worker's OPFS access handles to be released (`waitForSahPoolRelease` — a reload races the browser's asynchronous release, and `installOpfsSAHPoolVfs()` reacts to an acquisition failure by *deleting the pool directory*, so the pool must be acquirable before it runs — a wait that reaches its deadline ends the boot instead of installing anyway), then installs the SAHPool VFS **once** — failure is a fatal startup error painted by `error-overlay.ts`, never an in-memory fallback (`TRILIUM_INTEGRATION_TEST=memory` builds seed a fixture into the pool, so writes survive reloads within a test). It then calls `initializeCore({...})` with the `lightweight/*` providers, registers `createConfiguredRouter()` (`BrowserRouter` mimicking Express, path params + query strings), then answers `LOCAL_REQUEST` messages. `DbLock` (`lightweight/db_lock.ts`) serialises `createAsyncRoute` handlers (imports) that hold a transaction across `await`s against the single connection — synchronous routes keep a zero-overhead path. `WS_MESSAGE` replaces the WebSocket in both directions. Anything that escapes after startup is reported as `WORKER_ERROR` for one background task; before startup it means the app never came up and `error-overlay.ts` paints it (the async worker init is invisible to `main.ts`'s try/catch).
## The provider set (`src/lightweight/`)
diff --git a/CLAUDE.md b/CLAUDE.md
index b4940aef1c..20f52b228b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -139,10 +139,10 @@ Shared components live in `apps/client/src/widgets/react/` — **always** reuse
`apps/desktop` runs server + client in one Electron process; the renderer loads over the `trilium-app://` custom protocol and talks to main only through the preload bridge (`window.electronApi`, typed by `packages/commons/src/lib/electron_api_interface.ts`). The main process bundles to **ESM with code splitting** (`dist/main.mjs` + lazy `chunks/`, via `buildBackend(..., { format: "esm" })`); the preload and `image_worker.cjs` stay CJS. `nodeIntegration` is off, `contextIsolation` is on, `@electron/remote` is gone — never `require("electron")` in client code. Adding an API means interface + `preload.ts` + an `ipcMain` handler in the owning service + a spec. Load the **`developing-electron-desktop` skill** for the recipe, the security model, running/launch errors and testing.
### Standalone (in-browser) app
-`apps/standalone` runs the client on the page and `@triliumnext/core` — plain JS — in a dedicated Web Worker over `@sqlite.org/sqlite-wasm` persisted in OPFS; a Web Lock elects the one tab that owns the database and the service worker forwards other tabs' API calls to it. Every core provider has a browser twin in `apps/standalone/src/lightweight/` — **a new provider or Node import in core breaks this build first.** Load the **`developing-standalone` skill** before touching `sw.ts`, `main.ts`, `local-server-worker.ts`, `lightweight/*` or `vite.config.mts`.
+`apps/standalone` runs the client on the page and `@triliumnext/core` — plain JS — in a dedicated Web Worker over `@sqlite.org/sqlite-wasm` persisted in OPFS; a Web Lock elects the one tab that owns the database, which answers its own API calls straight from the worker (`standaloneApi.localFetch`); the service worker forwards other tabs' calls to it and covers what the page still requests. Every core provider has a browser twin in `apps/standalone/src/lightweight/` — **a new provider or Node import in core breaks this build first.** Load the **`developing-standalone` skill** before touching `sw.ts`, `main.ts`, `local-server-worker.ts`, `lightweight/*` or `vite.config.mts`.
### Mobile (Capacitor) app
-`apps/mobile` wraps the standalone WASM build in a Capacitor WebView — no network backend. Android runs at `https://localhost` and routes API calls through the service worker; iOS runs at `capacitor://localhost`, where no service worker can register, so `apps/standalone/src/ios-interceptors.ts` stands in. **`iosScheme: "https"` is a no-op and must not be re-added, and the iOS interceptor path is not dead code.** Load the **`developing-capacitor-mobile` skill** before touching `apps/mobile`, `ios-interceptors.ts`, `capacitor_http_handler.ts` or the `capacitor:` branches of `sw.ts`/`main.ts`.
+`apps/mobile` wraps the standalone WASM build in a Capacitor WebView — no network backend. Its one tab always owns the worker, so the client answers most API calls in-page; what still leaves it (images, fonts, uploads) goes through the service worker on Android, at `https://localhost`, and through `apps/standalone/src/ios-interceptors.ts` on iOS, at `capacitor://localhost`, where no service worker can register. **`iosScheme: "https"` is a no-op and must not be re-added, and the iOS interceptor path is not dead code.** Load the **`developing-capacitor-mobile` skill** before touching `apps/mobile`, `ios-interceptors.ts`, `capacitor_http_handler.ts` or the `capacitor:` branches of `sw.ts`/`main.ts`.
### Database
diff --git a/apps/mobile/README.md b/apps/mobile/README.md
index 5e77dabbcb..f26765b01e 100644
--- a/apps/mobile/README.md
+++ b/apps/mobile/README.md
@@ -30,7 +30,9 @@ pnpm --filter @triliumnext/mobile open:android # open Android Studio
## How web requests reach the local server (Android vs iOS)
-There is **no network backend** — the whole server runs in-process as WASM in a web worker. How the client's API/sync calls (`/api`, `/sync`, `/bootstrap`, `/search`) reach that worker differs by platform, because the two WebViews resolve `*Scheme: "https"` differently:
+There is **no network backend** — the whole server runs in-process as WASM in a web worker. The app is a single WebView, so its one tab always wins the database lock, and a tab that owns the worker calls it directly: `window.standaloneApi.localFetch`, which the client's `ajax()` ([`apps/client/src/services/server.ts`](../client/src/services/server.ts)) prefers over issuing a request at all. Most of the client's API/sync calls (`/api`, `/sync`, `/bootstrap`, `/search`) therefore never leave the page, on either platform.
+
+What still leaves it — images and fonts the engine loads, uploads, the LLM stream — reaches the worker differently per platform, because the two WebViews resolve `*Scheme: "https"` differently:
- **Android** — `androidScheme: "https"` works: the app loads at `https://localhost` (a real secure origin), so the **service worker** ([`apps/standalone/src/sw.ts`](../standalone/src/sw.ts)) intercepts those requests and forwards them to the worker.
- **iOS** — the app loads at **`capacitor://localhost`** and uses **fetch / XHR / image interceptors** ([`apps/standalone/src/main.ts`](../standalone/src/main.ts), gated on `location.protocol === "capacitor:"`) instead, because a service worker cannot register on `capacitor://` (`navigator.serviceWorker.register()` throws — the scheme is not HTTP/HTTPS).
diff --git a/packages/commons/src/lib/standalone_api_interface.ts b/packages/commons/src/lib/standalone_api_interface.ts
index a10209f5ee..03f1892ddf 100644
--- a/packages/commons/src/lib/standalone_api_interface.ts
+++ b/packages/commons/src/lib/standalone_api_interface.ts
@@ -2,13 +2,16 @@
* What the standalone build exposes to the client as `window.standaloneApi`.
*
* Standalone runs the whole stack in the browser: the database lives in a worker's private
- * filesystem, and the client talks to it over an intercepted `fetch`. That path serialises every
- * request body twice on its way through, and gives up after thirty seconds, which is fine for the
- * JSON everything else exchanges and impossible for a database.
+ * filesystem, and a tab that does not own that worker reaches it over an intercepted `fetch`. That
+ * path serialises every request body twice on its way through, and gives up after thirty seconds,
+ * which is fine for the JSON everything else exchanges and impossible for a database.
*
* So the few things that carry a file get their own way through, the same way the desktop's
* `window.electronApi` does. A `File` handed across is a reference to bytes the browser already has;
* nothing is copied, nothing is uploaded, and the worker reads it as a stream.
+ *
+ * `localFetch` sits here for a different reason: it carries no file, and offers the tab that owns
+ * the worker the ordinary request path without the trip through the service worker.
*/
/** How far a restore has got, reported as it goes. */