Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(standalone): support multiple tabs via leader election
Elian Doran1e6722268a6d
diff --git a/apps/standalone/e2e/multi_tab.spec.ts b/apps/standalone/e2e/multi_tab.spec.tsnew file mode 100644index 0000000000..4a43af9e84--- /dev/null+++ b/apps/standalone/e2e/multi_tab.spec.ts@@ -0,0 +1,99 @@+import test, { expect } from "@playwright/test";++import App from "../../../packages/trilium-e2e/src/support/app";++/**+ * Multi-tab behaviour, which is specific to standalone.+ *+ * The database lives in the browser on the OPFS SAHPool VFS, whose sync access+ * handles are exclusive to one dedicated worker per origin. Every tab used to+ * spawn its own worker: the second one could not open the database at all,+ * silently fell back to an empty in-memory one, and — because the service worker+ * routed API traffic to an arbitrary window — could drag the first tab onto that+ * empty database too.+ *+ * Now a Web Lock elects a single leader tab; it alone runs a worker, and the+ * others proxy through the service worker. See leader_election.ts.+ */+test("a second tab opens the same database rather than an empty one", async ({ context }) => {+ const firstTab = new App(await context.newPage(), context);+ await firstTab.goto();+ await expect(firstTab.noteTree).toContainText("Trilium Integration Test");++ const secondTab = new App(await context.newPage(), context);+ await secondTab.goto();++ // The regression: a second tab used to come up on a blank in-memory+ // database, so the fixture's notes would be missing here.+ await expect(secondTab.noteTree).toContainText("Trilium Integration Test");++ // ...and the first tab must not have been dragged onto that empty database.+ await expect(firstTab.noteTree).toContainText("Trilium Integration Test");+});++test("both tabs stay usable side by side", async ({ context }) => {+ const firstTab = new App(await context.newPage(), context);+ await firstTab.goto();+ await expect(firstTab.noteTree).toContainText("Trilium Integration Test");++ const secondTab = new App(await context.newPage(), context);+ await secondTab.goto();+ await expect(secondTab.noteTree).toContainText("Trilium Integration Test");++ // The follower's API calls are proxied to the leader's worker, so ordinary+ // navigation has to keep working in both.+ await firstTab.goToNoteInNewTab("Empty text");+ await expect(firstTab.currentNoteSplitTitle).toHaveValue(/Empty text/);++ await secondTab.goToNoteInNewTab("Empty text");+ await expect(secondTab.currentNoteSplitTitle).toHaveValue(/Empty text/);+});++test("a write from the follower reaches the leader's tree", async ({ context }) => {+ const leaderTab = new App(await context.newPage(), context);+ await leaderTab.goto();+ await expect(leaderTab.noteTree).toContainText("Trilium Integration Test");++ const followerTab = new App(await context.newPage(), context);+ await followerTab.goto();+ await expect(followerTab.noteTree).toContainText("Trilium Integration Test");++ // Write from the *follower*, which has no worker of its own: the request has+ // to travel through the service worker to the leader's worker to succeed.+ const renamed = "Renamed by the follower tab";+ const status = await followerTab.page.evaluate(async (title) => {+ const response = await fetch("/api/notes/root/title", {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ title })+ });+ return response.status;+ }, renamed);+ expect(status).toBe(200);++ // The resulting entity change is broadcast from the leader's worker and+ // relayed to every tab over the BroadcastChannel in local-bridge.ts, so both+ // trees converge without a reload.+ await expect(leaderTab.noteTree).toContainText(renamed, { timeout: 20_000 });+ await expect(followerTab.noteTree).toContainText(renamed, { timeout: 20_000 });+});++test("closing the leader promotes the surviving tab", async ({ context }) => {+ const leaderTab = new App(await context.newPage(), context);+ await leaderTab.goto();+ await expect(leaderTab.noteTree).toContainText("Trilium Integration Test");++ const followerTab = new App(await context.newPage(), context);+ await followerTab.goto();+ await expect(followerTab.noteTree).toContainText("Trilium Integration Test");++ // The first tab holds the database lock. Closing it releases the lock, and+ // the browser hands it to the tab that was queued behind — no heartbeat or+ // timeout involved.+ await leaderTab.page.close();++ // The survivor must be able to serve its own requests now, which it can only+ // do by having been promoted and started a worker of its own.+ await followerTab.goToNoteInNewTab("Empty text");+ await expect(followerTab.currentNoteSplitTitle).toHaveValue(/Empty text/, { timeout: 20_000 });+});diff --git a/apps/standalone/playwright.config.ts b/apps/standalone/playwright.config.tsindex c93c99df9d..7b52a78851 100644--- a/apps/standalone/playwright.config.ts+++ b/apps/standalone/playwright.config.ts@@ -6,6 +6,9 @@ const baseURL = process.env["BASE_URL"] || `http://127.0.0.1:${port}`;export default createBaseConfig({appDir: __dirname,projectName: "standalone",+ // Multi-tab behaviour is standalone-specific — the server already serves+ // several browser clients from one backend — so those tests live here.+ localTestDir: "e2e",workers: 1,webServer: !process.env.TRILIUM_DOCKER ? {command: `pnpm build && pnpm vite preview --host 127.0.0.1 --port ${port}`,diff --git a/apps/standalone/src/leader_election.spec.ts b/apps/standalone/src/leader_election.spec.tsnew file mode 100644index 0000000000..6bce8beddb--- /dev/null+++ b/apps/standalone/src/leader_election.spec.ts@@ -0,0 +1,93 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { claimLeadership, isLeader, resetLeadershipForTesting } from "./leader_election.js";++type LockCallback = () => Promise<unknown>;++interface NavLocks {+ locks?: { request: ReturnType<typeof vi.fn> } | undefined;+}++function installLocks(request: ReturnType<typeof vi.fn>) {+ Object.defineProperty(navigator, "locks", { value: { request }, configurable: true });+}++beforeEach(() => {+ resetLeadershipForTesting();+});++afterEach(() => {+ delete (navigator as unknown as NavLocks).locks;+ vi.restoreAllMocks();+});++describe("claimLeadership", () => {+ it("takes an exclusive lock and elects this tab once granted", async () => {+ let granted: LockCallback | undefined;+ const request = vi.fn((_name: string, _opts: unknown, callback: LockCallback) => {+ granted = callback;+ return new Promise(() => {});+ });+ installLocks(request);+ const onElected = vi.fn();++ claimLeadership(onElected);++ // The lock must be exclusive — a shared one would let every tab through+ // and they would all try to open the same OPFS database.+ expect(request).toHaveBeenCalledWith(+ "trilium-standalone-db",+ { mode: "exclusive" },+ expect.any(Function)+ );++ // Not the leader until the browser actually grants the lock.+ expect(isLeader()).toBe(false);+ expect(onElected).not.toHaveBeenCalled();++ granted?.();+ expect(isLeader()).toBe(true);+ expect(onElected).toHaveBeenCalledTimes(1);+ });++ it("holds the lock indefinitely so no other tab is promoted while alive", async () => {+ let granted: LockCallback | undefined;+ installLocks(vi.fn((_n: string, _o: unknown, callback: LockCallback) => {+ granted = callback;+ return new Promise(() => {});+ }));++ claimLeadership(() => {});+ const held = granted?.();++ // Releasing early would let a second tab start a worker against the same+ // database, which is exactly the failure this prevents.+ const settled = await Promise.race([+ held?.then(() => "settled"),+ Promise.resolve("still-held")+ ]);+ expect(settled).toBe("still-held");+ });++ it("assumes leadership when Web Locks is unavailable", () => {+ // Some embedded WebViews lack the API. Those are single-window Capacitor+ // apps, so this tab is trivially the only possible owner.+ Object.defineProperty(navigator, "locks", { value: undefined, configurable: true });+ const onElected = vi.fn();+ vi.spyOn(console, "info").mockImplementation(() => {});++ claimLeadership(onElected);++ expect(isLeader()).toBe(true);+ expect(onElected).toHaveBeenCalledTimes(1);+ });++ it("reports a follower as not the leader", () => {+ // A queued request never invokes the callback until promotion.+ installLocks(vi.fn(() => new Promise(() => {})));++ claimLeadership(vi.fn());++ expect(isLeader()).toBe(false);+ });+});diff --git a/apps/standalone/src/leader_election.ts b/apps/standalone/src/leader_election.tsnew file mode 100644index 0000000000..b09239c8bc--- /dev/null+++ b/apps/standalone/src/leader_election.ts@@ -0,0 +1,56 @@+/**+ * Elects the one tab that owns the database.+ *+ * The database lives on the OPFS SAHPool VFS, which takes *exclusive* sync+ * access handles over its pool files — only one worker on the origin can hold+ * them. Worse, `createSyncAccessHandle` is exposed solely in a dedicated worker+ * (not in a SharedWorker, and a SharedWorker cannot spawn a nested worker to do+ * it either), so the owner has to be a dedicated worker belonging to some page.+ *+ * A Web Lock picks that page. The winner holds the lock for as long as it lives+ * and is the only tab that starts a worker; the others proxy their API calls to+ * it through the service worker. When the leader's tab closes, the browser+ * releases the lock automatically and a waiting tab is promoted — no heartbeat+ * or timeout to get wrong.+ */+const DB_LOCK_NAME = "trilium-standalone-db";++let leader = false;++/** True when this tab owns the database worker. */+export function isLeader(): boolean {+ return leader;+}++/**+ * Ask to own the database. `onElected` runs once this tab holds the lock, which+ * is immediately for the first tab and only on promotion for later ones.+ */+export function claimLeadership(onElected: () => void): void {+ // Web Locks is missing in some embedded WebViews. Those are single-window+ // Capacitor apps, so this tab is trivially the only possible owner.+ if (!navigator.locks?.request) {+ console.info("[Leader] Web Locks unavailable — assuming sole tab");+ promote(onElected);+ return;+ }++ void navigator.locks.request(DB_LOCK_NAME, { mode: "exclusive" }, () => {+ promote(onElected);++ // Never resolves: holding the lock for the lifetime of the tab is what+ // keeps other tabs from opening a second worker. The browser releases it+ // when the tab goes away.+ return new Promise<never>(() => {});+ });+}++function promote(onElected: () => void): void {+ leader = true;+ onElected();+}++/** Reset module state. Test-only. */+export function resetLeadershipForTesting(): void {+ leader = false;+}diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.tsindex 73ab64c095..e085911500 100644--- a/apps/standalone/src/lightweight/browser_routes.ts+++ b/apps/standalone/src/lightweight/browser_routes.ts@@ -8,6 +8,7 @@ import { entity_changes, getContext, getPlatform, getSharedBootstrapItems, getSqimport packageJson from '../../package.json' with { type: 'json' };import { type BrowserRequest, BrowserRouter } from './browser_router';+import { dbLock } from './db_lock';/** Minimal response object used by apiResultHandler to capture the processed result. */interface ResultHandlerResponse {@@ -62,14 +63,14 @@ function setContextFromHeaders(req: BrowserRequest) {*/function wrapHandler(handler: (req: any) => unknown, transactional: boolean) {return (req: BrowserRequest) => {- return getContext().init(() => {+ return dbLock.runShared(() => getContext().init(() => {setContextFromHeaders(req);const expressLikeReq = toExpressLikeReq(req);if (transactional) {return getSql().transactional(() => handler(expressLikeReq));}return handler(expressLikeReq);- });+ }));};}@@ -94,7 +95,7 @@ function createApiRoute(router: BrowserRouter, transactional: boolean) {function createRoute(router: BrowserRouter) {return (method: HttpMethod, path: string, _middleware: any[], handler: (req: any, res: any) => unknown, resultHandler?: ((req: any, res: any, result: unknown) => unknown) | null) => {router.register(method, path, (req: BrowserRequest) => {- return getContext().init(() => {+ return dbLock.runShared(() => getContext().init(() => {setContextFromHeaders(req);const expressLikeReq = toExpressLikeReq(req);const mockRes = createMockExpressResponse();@@ -119,7 +120,7 @@ function createRoute(router: BrowserRouter) {}return result;- });+ }));});};}@@ -133,7 +134,9 @@ function createRoute(router: BrowserRouter) {function createAsyncRoute(router: BrowserRouter) {return (method: HttpMethod, path: string, _middleware: any[], handler: (req: any, res: any) => Promise<unknown>, resultHandler?: ((req: any, res: any, result: unknown) => unknown) | null) => {router.register(method, path, (req: BrowserRequest) => {- return getContext().init(async () => {+ // Exclusive: this transaction stays open across awaits, so no other+ // route may touch the connection until it commits. See db_lock.ts.+ return dbLock.runExclusive(() => getContext().init(async () => {setContextFromHeaders(req);const expressLikeReq = toExpressLikeReq(req);const mockRes = createMockExpressResponse();@@ -158,7 +161,7 @@ function createAsyncRoute(router: BrowserRouter) {}return result;- });+ }) as Promise<unknown>);});};}diff --git a/apps/standalone/src/lightweight/db_lock.spec.ts b/apps/standalone/src/lightweight/db_lock.spec.tsnew file mode 100644index 0000000000..656a2acfe6--- /dev/null+++ b/apps/standalone/src/lightweight/db_lock.spec.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from "vitest";++import { DbLock } from "./db_lock.js";++/** A promise plus the handle to settle it, so tests control interleaving exactly. */+function deferred<T = void>() {+ let resolve: (value: T) => void = () => {};+ let reject: (reason?: unknown) => void = () => {};+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++describe("DbLock exclusive access", () => {+ it("runs exclusive sections one at a time", async () => {+ const lock = new DbLock();+ const order: string[] = [];+ const first = deferred();++ const a = lock.runExclusive(async () => {+ order.push("a:start");+ await first.promise;+ order.push("a:end");+ return "a";+ });++ // b must not begin until a has committed, or its BEGIN IMMEDIATE would+ // land inside a's still-open transaction.+ const b = lock.runExclusive(async () => {+ order.push("b:start");+ return "b";+ });++ await Promise.resolve();+ expect(order).toEqual(["a:start"]);++ first.resolve();+ expect(await Promise.all([a, b])).toEqual(["a", "b"]);+ expect(order).toEqual(["a:start", "a:end", "b:start"]);+ });++ it("releases the lock when an exclusive section throws", async () => {+ const lock = new DbLock();++ await expect(lock.runExclusive(async () => {+ throw new Error("import failed");+ })).rejects.toThrow("import failed");++ // A failed import must not wedge the worker for every later request.+ expect(lock.isLocked).toBe(false);+ await expect(lock.runExclusive(async () => "recovered")).resolves.toBe("recovered");+ });++ it("reports isLocked only while a holder is active", async () => {+ const lock = new DbLock();+ expect(lock.isLocked).toBe(false);++ const gate = deferred();+ const running = lock.runExclusive(async () => { await gate.promise; });+ await Promise.resolve();+ expect(lock.isLocked).toBe(true);++ gate.resolve();+ await running;+ expect(lock.isLocked).toBe(false);+ });+});++describe("DbLock shared access", () => {+ it("runs synchronously and returns the value directly when unlocked", () => {+ const lock = new DbLock();++ // The common path must stay synchronous — a promise here would make+ // every ordinary route asynchronous for no reason.+ const result = lock.runShared(() => "immediate");+ expect(result).toBe("immediate");+ });++ it("defers shared work until an exclusive holder finishes", async () => {+ const lock = new DbLock();+ const order: string[] = [];+ const gate = deferred();++ const exclusive = lock.runExclusive(async () => {+ order.push("exclusive:start");+ await gate.promise;+ order.push("exclusive:end");+ });++ await Promise.resolve();+ const shared = lock.runShared(() => {+ order.push("shared");+ return "shared-result";+ });++ // While an import holds the connection, a plain request must wait rather+ // than being folded into the import's transaction as a SAVEPOINT.+ expect(shared).toBeInstanceOf(Promise);+ expect(order).toEqual(["exclusive:start"]);++ gate.resolve();+ await exclusive;+ await expect(shared).resolves.toBe("shared-result");+ expect(order).toEqual(["exclusive:start", "exclusive:end", "shared"]);+ });++ it("lets shared work proceed after a failed exclusive section", async () => {+ const lock = new DbLock();+ const gate = deferred();++ const exclusive = lock.runExclusive(async () => {+ await gate.promise;+ throw new Error("rolled back");+ });++ await Promise.resolve();+ const shared = lock.runShared(() => "after-failure");++ gate.resolve();+ await expect(exclusive).rejects.toThrow("rolled back");+ await expect(shared).resolves.toBe("after-failure");+ });+});diff --git a/apps/standalone/src/lightweight/db_lock.ts b/apps/standalone/src/lightweight/db_lock.tsnew file mode 100644index 0000000000..2aca94eee7--- /dev/null+++ b/apps/standalone/src/lightweight/db_lock.ts@@ -0,0 +1,74 @@+/**+ * Serialises route handlers against the worker's single SQLite connection.+ *+ * Most routes run inside the *synchronous* `getSql().transactional()`, which is+ * atomic on its own: single-threaded JS cannot interleave another request into+ * the middle of it. Those need no coordination.+ *+ * The exception is `createAsyncRoute` (imports and friends), which holds a+ * transaction open across `await` points via `transactionalAsync`. While such a+ * transaction is open:+ *+ * - a second async route would issue `BEGIN IMMEDIATE` inside the open+ * transaction, which SQLite rejects; and+ * - a synchronous route would be folded into it as a SAVEPOINT (see the nesting+ * branch in `sql_provider.ts`), so an unrelated request's writes would be+ * rolled back if the import later failed.+ *+ * Both hazards predate multi-tab support — one tab already issues concurrent+ * requests — but a second tab makes them far likelier, so the worker now gates+ * on this lock. Shared (synchronous) work keeps a zero-overhead fast path and+ * only becomes asynchronous while an exclusive holder is actually active.+ */+export class DbLock {+ private exclusive: Promise<void> | null = null;++ /** True while an async-transaction holder is active. */+ get isLocked(): boolean {+ return this.exclusive !== null;+ }++ /**+ * Run `fn` with exclusive access to the connection. Other exclusive work and+ * any shared work queue behind it.+ */+ async runExclusive<T>(fn: () => Promise<T>): Promise<T> {+ while (this.exclusive) {+ await this.exclusive;+ }++ let release: () => void = () => {};+ this.exclusive = new Promise<void>((resolve) => {+ release = resolve;+ });++ try {+ return await fn();+ } finally {+ this.exclusive = null;+ release();+ }+ }++ /**+ * Run `fn`, first waiting for any exclusive holder to finish.+ *+ * Returns `fn`'s value directly when the lock is free so the common path+ * stays synchronous; returns a promise only when it has to wait.+ */+ runShared<T>(fn: () => T): T | Promise<T> {+ if (!this.exclusive) {+ return fn();+ }++ return (async () => {+ while (this.exclusive) {+ await this.exclusive;+ }+ return fn();+ })();+ }+}++/** The worker owns exactly one SQLite connection, so one lock covers it. */+export const dbLock = new DbLock();diff --git a/apps/standalone/src/local-bridge.spec.ts b/apps/standalone/src/local-bridge.spec.tsindex 746c0e39f6..73ce794f68 100644--- a/apps/standalone/src/local-bridge.spec.ts+++ b/apps/standalone/src/local-bridge.spec.ts@@ -2,7 +2,14 @@ import { afterEach, describe, expect, it, vi } from "vitest";// A controllable stand-in for the bundled local-server-worker. vi.hoisted lets the// (hoisted) vi.mock factory share the instance registry with the test body.-const { workerInstances } = vi.hoisted(() => ({ workerInstances: [] as MockWorker[] }));+const { workerInstances, leadership } = vi.hoisted(() => ({+ workerInstances: [] as MockWorker[],+ // Most of this suite exercises the leader, which is the tab that owns the+ // worker. Followers take a different path — see the leadership describe.+ leadership: { isLeader: true }+}));++vi.mock("./leader_election.js", () => ({ isLeader: () => leadership.isLeader }));class MockWorker {postMessage = vi.fn();@@ -25,6 +32,7 @@ let swHandler: ((event: unknown) => unknown) | undefined;async function freshBridge(withServiceWorker = true): Promise<LocalBridge> {vi.resetModules();workerInstances.length = 0;+ leadership.isLeader = true;swHandler = undefined;if (withServiceWorker) {Object.defineProperty(navigator, "serviceWorker", {@@ -412,4 +420,115 @@ describe("restoreBackup", () => {expect(() => worker.onmessage?.({ data: { type: "RESTORE_PROGRESS", id: "other", progress: {} } })).not.toThrow();});++ it("refuses in a follower rather than opening a second database", async () => {+ const bridge = await freshBridge();+ leadership.isLeader = false;++ await expect(bridge.restoreBackup({ backup: new File([ "bytes" ], "backup.db") }))+ .rejects.toThrow(/tab that owns the database/);+ expect(workerInstances).toHaveLength(0);+ });+});++describe("leadership", () => {+ it("a follower refuses to serve and never starts a worker", async () => {+ const bridge = await freshBridge();+ bridge.attachServiceWorkerBridge();+ leadership.isLeader = false;++ const port = { postMessage: vi.fn() };+ await swHandler?.({+ data: { type: "LOCAL_FETCH", id: "9", request: { method: "GET", url: "/api/x", headers: {} } },+ ports: [port]+ });++ // Starting a worker here would open a second database against the same+ // OPFS pool — the exact failure leadership exists to prevent.+ expect(workerInstances).toHaveLength(0);+ expect(port.postMessage).toHaveBeenCalledWith({ type: "NOT_LEADER", id: "9" });+ });++ it("answers the service worker's leader probe", async () => {+ const bridge = await freshBridge();+ bridge.attachServiceWorkerBridge();++ const leaderPort = { postMessage: vi.fn() };+ await swHandler?.({ data: { type: "WHO_IS_LEADER" }, ports: [leaderPort] });+ expect(leaderPort.postMessage).toHaveBeenCalledWith({ type: "LEADER_REPLY", isLeader: true });++ leadership.isLeader = false;+ const followerPort = { postMessage: vi.fn() };+ await swHandler?.({ data: { type: "WHO_IS_LEADER" }, ports: [followerPort] });+ expect(followerPort.postMessage).toHaveBeenCalledWith({ type: "LEADER_REPLY", isLeader: false });+ });++ it("announceLeadership tells the controlling service worker", async () => {+ const bridge = await freshBridge();+ const controller = { postMessage: vi.fn() };+ Object.defineProperty(navigator, "serviceWorker", {+ value: { addEventListener: vi.fn(), controller },+ configurable: true+ });++ bridge.announceLeadership();+ expect(controller.postMessage).toHaveBeenCalledWith({ type: "LEADER_ANNOUNCE" });+ });++ it("survives announcing with no controlling service worker", async () => {+ const bridge = await freshBridge(false);+ expect(() => bridge.announceLeadership()).not.toThrow();+ });+});++describe("cross-tab ws relay", () => {+ it("relays the worker's ws messages to the other tabs", async () => {+ const posted: unknown[] = [];+ class MockBroadcastChannel {+ onmessage: ((e: { data: unknown }) => void) | null = null;+ postMessage = vi.fn((m: unknown) => { posted.push(m); });+ close = vi.fn();+ }+ vi.stubGlobal("BroadcastChannel", MockBroadcastChannel);++ const bridge = await freshBridge();+ bridge.startLocalServerWorker();+ lastWorker().onmessage?.({ data: { type: "WS_MESSAGE", message: { kind: "entity-change" } } });++ // Only the leader has a worker, so without this relay a follower would+ // never learn the entity changed.+ expect(posted).toEqual([{ kind: "entity-change" }]);+ vi.unstubAllGlobals();+ });++ it("dispatches a relayed message into this tab", async () => {+ const channels: MockBroadcastChannel[] = [];+ class MockBroadcastChannel {+ onmessage: ((e: { data: unknown }) => void) | null = null;+ postMessage = vi.fn();+ close = vi.fn();+ constructor() { channels.push(this); }+ }+ vi.stubGlobal("BroadcastChannel", MockBroadcastChannel);++ const bridge = await freshBridge();+ bridge.attachServiceWorkerBridge();+ const dispatchSpy = vi.spyOn(window, "dispatchEvent");++ channels.at(-1)?.onmessage?.({ data: { kind: "from-leader" } });++ const event = dispatchSpy.mock.calls.at(-1)?.[0] as CustomEvent;+ expect(event.type).toBe("trilium:ws-message");+ expect(event.detail).toEqual({ kind: "from-leader" });+ vi.unstubAllGlobals();+ });++ it("works when BroadcastChannel is unavailable", async () => {+ vi.stubGlobal("BroadcastChannel", undefined);+ const bridge = await freshBridge();+ bridge.startLocalServerWorker();++ expect(() => lastWorker().onmessage?.({ data: { type: "WS_MESSAGE", message: { kind: "x" } } })).not.toThrow();+ vi.unstubAllGlobals();+ });});diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.tsindex 56cde72555..8ccc38ca14 100644--- a/apps/standalone/src/local-bridge.ts+++ b/apps/standalone/src/local-bridge.ts@@ -1,5 +1,6 @@import type { StandaloneRestoreProgress, StandaloneRestoreResult } from "@triliumnext/commons";+import { isLeader } from "./leader_election.js";import LocalServerWorker from "./local-server-worker?worker";let localWorker: Worker | null = null;const pending = new Map();@@ -10,6 +11,44 @@ const restores = new Map<string, {onProgress?: (progress: StandaloneRestoreProgress) => void;}>();+/**+ * Carries the worker's WebSocket-style messages from the leader tab to the+ * others. Only the leader has a worker, so without this relay a follower would+ * never learn that an entity changed and its froca cache would go stale.+ *+ * A BroadcastChannel never echoes to the sender, so the leader posting here does+ * not re-deliver to itself — it dispatches its own copy directly.+ */+const WS_RELAY_CHANNEL = "trilium-ws-relay";+let wsRelay: BroadcastChannel | null = null;++function getWsRelay(): BroadcastChannel | null {+ if (typeof BroadcastChannel === "undefined") {+ return null;+ }+ if (!wsRelay) {+ wsRelay = new BroadcastChannel(WS_RELAY_CHANNEL);+ wsRelay.onmessage = (event) => dispatchWsMessage(event.data);+ }+ return wsRelay;+}++function dispatchWsMessage(message: unknown): void {+ window.dispatchEvent(new CustomEvent("trilium:ws-message", { detail: message }));+}++/**+ * Tell the service worker that this tab owns the database, so it routes every+ * tab's API traffic here. The service worker is evicted when idle and loses+ * this, so it also probes for the leader on demand — see sw.ts.+ */+export function announceLeadership(): void {+ // Start listening for relayed messages even as leader: if this tab is ever+ // demoted the channel is already live.+ getWsRelay();+ navigator.serviceWorker?.controller?.postMessage({ type: "LEADER_ANNOUNCE" });+}+const LOCAL_API_PREFIXES = ["/bootstrap", "/api/", "/sync/", "/search/"];/**@@ -20,19 +59,31 @@ const LOCAL_API_PREFIXES = ["/bootstrap", "/api/", "/sync/", "/search/"];* serialises bodies whole and gives up after thirty seconds, neither of which a database survives.** Progress is relayed from the worker to `onProgress`, which stays on this side of the boundary.+ *+ * Only the leader tab can do this: it is the one holding the database, and the+ * restore bypasses the request path that would otherwise proxy a follower's+ * call through to it. Starting a worker here in a follower would open a second+ * database against the same OPFS pool — the failure leadership exists to+ * prevent — so a follower is refused outright instead.*/export function restoreBackup(opts: {backup: File;passphrase?: string;onProgress?: (progress: StandaloneRestoreProgress) => void;}): Promise<StandaloneRestoreResult> {- startLocalServerWorker();+ if (!isLeader()) {+ return Promise.reject(new Error(+ "A backup can only be restored from the tab that owns the database. "+ + "Close the other Trilium tabs and try again."+ ));+ }+ const worker = startLocalServerWorker();const id = Math.random().toString(36).slice(2);return new Promise((resolve, reject) => {restores.set(id, { resolve, reject, onProgress: opts.onProgress });- localWorker!.postMessage({+ worker.postMessage({type: "RESTORE_BACKUP",id,backup: opts.backup,@@ -169,9 +220,10 @@ export function startLocalServerWorker() {// Handle WebSocket-like messages from the worker (for frontend updates)if (msg?.type === "WS_MESSAGE" && msg.message) {// Dispatch a custom event that ws.ts listens to in standalone mode- window.dispatchEvent(new CustomEvent("trilium:ws-message", {- detail: msg.message- }));+ dispatchWsMessage(msg.message);+ // Only this tab has a worker, so pass the update on to the others —+ // that is what makes one tab's edit show up in the rest.+ getWsRelay()?.postMessage(msg.message);return;}@@ -216,13 +268,32 @@ export function attachServiceWorkerBridge() {return;}+ // Followers need the relay too, so they receive the leader's entity changes.+ getWsRelay();+navigator.serviceWorker.addEventListener("message", async (event) => {const msg = event.data;++ // The service worker lost track of the leader and is probing for it.+ if (msg?.type === "WHO_IS_LEADER") {+ const replyPort = event.ports && event.ports[0];+ replyPort?.postMessage({ type: "LEADER_REPLY", isLeader: isLeader() });+ return;+ }+if (!msg || msg.type !== "LOCAL_FETCH") return;const port = event.ports && event.ports[0];if (!port) return;+ // Never start a worker just because a request arrived: only the leader+ // may own one. If the service worker guessed wrong, say so and let it+ // find the real leader rather than opening a second, broken database.+ if (!isLeader()) {+ port.postMessage({ type: "NOT_LEADER", id: msg.id });+ return;+ }+try {startLocalServerWorker();diff --git a/apps/standalone/src/main.spec.ts b/apps/standalone/src/main.spec.tsindex 72d4f3b250..a945b3460e 100644--- a/apps/standalone/src/main.spec.ts+++ b/apps/standalone/src/main.spec.ts@@ -5,14 +5,27 @@ const mocks = vi.hoisted(() => ({attachServiceWorkerBridge: vi.fn(),registerNativeHttpHandler: vi.fn(),restoreBackup: vi.fn(),+ announceLeadership: vi.fn(),capacitorHttpHandler: vi.fn()}));+// Whether this tab wins the database lock. Only the leader may start a worker;+// a second worker cannot open the OPFS database at all.+const leadership = vi.hoisted(() => ({ elected: true }));+vi.mock("./local-bridge.js", () => ({startLocalServerWorker: mocks.startLocalServerWorker,attachServiceWorkerBridge: mocks.attachServiceWorkerBridge,registerNativeHttpHandler: mocks.registerNativeHttpHandler,- restoreBackup: mocks.restoreBackup+ restoreBackup: mocks.restoreBackup,+ announceLeadership: mocks.announceLeadership+}));+vi.mock("./leader_election.js", () => ({+ claimLeadership: (onElected: () => void) => {+ if (leadership.elected) {+ onElected();+ }+ }}));vi.mock("./services/capacitor_http_handler.js", () => ({ capacitorHttpHandler: mocks.capacitorHttpHandler }));// Avoid pulling the entire client bundle when loadScripts() runs.@@ -34,6 +47,7 @@ let reloadSpy: ReturnType<typeof vi.fn>;beforeEach(() => {Object.values(mocks).forEach((m) => m.mockReset());+ leadership.elected = true;document.body.innerHTML = "";delete (window as unknown as WindowWithCapacitor).Capacitor;reloadSpy = vi.fn();@@ -63,6 +77,26 @@ describe("bootstrap", () => {expect(document.body.innerHTML).toBe("");});+ it("announces leadership once elected", async () => {+ setServiceWorker({ controller: {}, register: vi.fn(), ready: Promise.resolve() });+ await runBootstrap();+ // The service worker has to know which tab owns the worker so it can+ // route every tab's API traffic there.+ await vi.waitFor(() => expect(mocks.announceLeadership).toHaveBeenCalled());+ });++ it("a follower tab starts no worker but still bridges the SW", async () => {+ leadership.elected = false;+ setServiceWorker({ controller: {}, register: vi.fn(), ready: Promise.resolve() });+ await runBootstrap();+ await vi.waitFor(() => expect(mocks.attachServiceWorkerBridge).toHaveBeenCalled());++ // Starting a worker here would open a second database against the same+ // exclusive OPFS handles and silently fall back to an empty in-memory one.+ expect(mocks.startLocalServerWorker).not.toHaveBeenCalled();+ expect(mocks.announceLeadership).not.toHaveBeenCalled();+ });+it("registers the native HTTP handler under Capacitor", async () => {(window as unknown as WindowWithCapacitor).Capacitor = {};setServiceWorker({ controller: {}, register: vi.fn(), ready: Promise.resolve() });diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.tsindex 892624921a..5923bc8c4b 100644--- a/apps/standalone/src/main.ts+++ b/apps/standalone/src/main.ts@@ -1,5 +1,6 @@import { installIosInterceptors } from "./ios-interceptors.js";-import { attachServiceWorkerBridge, registerNativeHttpHandler, restoreBackup, startLocalServerWorker } from "./local-bridge.js";+import { claimLeadership } from "./leader_election.js";+import { announceLeadership, attachServiceWorkerBridge, registerNativeHttpHandler, restoreBackup, startLocalServerWorker } from "./local-bridge.js";async function waitForServiceWorkerControl(): Promise<void> {if (!("serviceWorker" in navigator) || !navigator.serviceWorker) {@@ -56,8 +57,15 @@ async function bootstrap() {registerNativeHttpHandler(capacitorHttpHandler);}- // 1) Start local worker ASAP (so /bootstrap is fast)- startLocalServerWorker();+ // 1) Start the local worker ASAP (so /bootstrap is fast) — but only in+ // the tab that wins the database lock. A second worker cannot open the+ // OPFS database at all; before this gate it silently fell back to an+ // empty in-memory one. Other tabs reach this worker through the service+ // worker instead. See leader_election.ts.+ claimLeadership(() => {+ startLocalServerWorker();+ announceLeadership();+ });// iOS Capacitor loads on the capacitor:// scheme, where WebKit rejects// service worker registration. Fall back to in-page request interceptorsdiff --git a/apps/standalone/src/sw.spec.ts b/apps/standalone/src/sw.spec.tsindex b29da63141..351c457bec 100644--- a/apps/standalone/src/sw.spec.ts+++ b/apps/standalone/src/sw.spec.ts@@ -157,8 +157,22 @@ describe("fetch routing", () => {});describe("forwardToClientLocalServer", () => {- function mainClient() {- return { url: `${origin}/`, postMessage: vi.fn() };+ /**+ * A main app window. Real tabs answer the service worker's WHO_IS_LEADER+ * probe, so the stand-in does too — otherwise every lookup would sit out the+ * probe timeout before falling back.+ */+ function mainClient(id = "c1", leader = true) {+ const client = {+ id,+ url: `${origin}/`,+ postMessage: vi.fn((msg: { type?: string }) => {+ if (msg?.type === "WHO_IS_LEADER") {+ channels.at(-1)?.port1.onmessage?.({ data: { type: "LEADER_REPLY", isLeader: leader } } as unknown);+ }+ })+ };+ return client;}async function dispatchLocal(handlers: Record<string, EventHandler>, method = "POST") {@@ -176,7 +190,7 @@ describe("forwardToClientLocalServer", () => {const handlers = await loadSw();const event = await dispatchLocal(handlers);- await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalled());+ await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));const channel = channels.at(-1);channel?.port1.onmessage?.({ data: { type: "LOCAL_FETCH_RESPONSE", id: "uuid-1", response: { status: 201, headers: { "content-type": "application/json" }, body: new TextEncoder().encode("ok").buffer } } } as unknown);@@ -213,7 +227,7 @@ describe("forwardToClientLocalServer", () => {(self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [client]) };const handlers = await loadSw();const event = await dispatchLocal(handlers, "GET");- await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalled());+ await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));// No status, no headers, no body → status falls back to 200, headers stay empty.channels.at(-1)?.port1.onmessage?.({ data: { type: "LOCAL_FETCH_RESPONSE", id: "uuid-1", response: {} } } as unknown);const res = await awaitResponse(event);@@ -225,7 +239,7 @@ describe("forwardToClientLocalServer", () => {(self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [client]) };const handlers = await loadSw();const event = await dispatchLocal(handlers, "GET");- await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalled());+ await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));channels.at(-1)?.port1.onmessage?.({ data: { type: "WRONG", id: "uuid-1" } } as unknown);await event._response;expect(fetch).toHaveBeenCalled();@@ -236,7 +250,7 @@ describe("forwardToClientLocalServer", () => {(self as unknown as SwGlobals).clients = { claim: vi.fn(), matchAll: vi.fn(async () => [client]) };const handlers = await loadSw();const event = await dispatchLocal(handlers, "GET");- await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalled());+ await vi.waitFor(() => expect(client.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));channels.at(-1)?.port1.onmessageerror?.();await expect(event._response).rejects.toThrow("Local server message error");});@@ -253,4 +267,65 @@ describe("forwardToClientLocalServer", () => {await rejection;vi.useRealTimers();});++ it("routes to the tab that announced itself as leader", async () => {+ const follower = mainClient("c-follower", false);+ const leader = mainClient("c-leader", true);+ // Leader deliberately last: picking the first window (the old behaviour)+ // would send every tab's traffic to a tab with no worker.+ (self as unknown as SwGlobals).clients = {+ claim: vi.fn(),+ matchAll: vi.fn(async () => [follower, leader])+ };+ const handlers = await loadSw();+ handlers.message({ data: { type: "LEADER_ANNOUNCE" }, source: { id: "c-leader" } });++ const event = await dispatchLocal(handlers, "GET");+ await vi.waitFor(() => expect(leader.postMessage).toHaveBeenCalled());+ // Announced leader is used directly, with no probe round.+ expect(follower.postMessage).not.toHaveBeenCalled();++ channels.at(-1)?.port1.onmessage?.({ data: { type: "LOCAL_FETCH_RESPONSE", id: "uuid-1", response: { status: 200, headers: {}, body: null } } } as unknown);+ expect((await awaitResponse(event)).status).toBe(200);+ });++ it("probes for the leader when it has not been told who it is", async () => {+ const follower = mainClient("c-follower", false);+ const leader = mainClient("c-leader", true);+ (self as unknown as SwGlobals).clients = {+ claim: vi.fn(),+ matchAll: vi.fn(async () => [follower, leader])+ };+ const handlers = await loadSw();++ const event = await dispatchLocal(handlers, "GET");+ // Both are asked; only the leader claims it, and the request goes there.+ await vi.waitFor(() => expect(follower.postMessage).toHaveBeenCalledWith({ type: "WHO_IS_LEADER" }, expect.anything()));+ await vi.waitFor(() => expect(leader.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));++ channels.at(-1)?.port1.onmessage?.({ data: { type: "LOCAL_FETCH_RESPONSE", id: "uuid-1", response: { status: 200, headers: {}, body: null } } } as unknown);+ expect((await awaitResponse(event)).status).toBe(200);+ });++ it("re-resolves the leader when a tab replies NOT_LEADER", async () => {+ // Stale cached leader: the tab was demoted since it announced.+ const stale = mainClient("c-stale", false);+ const leader = mainClient("c-leader", true);+ (self as unknown as SwGlobals).clients = {+ claim: vi.fn(),+ matchAll: vi.fn(async () => [stale, leader])+ };+ const handlers = await loadSw();+ handlers.message({ data: { type: "LEADER_ANNOUNCE" }, source: { id: "c-stale" } });++ const event = await dispatchLocal(handlers, "GET");+ await vi.waitFor(() => expect(stale.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));++ // The demoted tab refuses rather than opening a second database.+ channels.at(-1)?.port1.onmessage?.({ data: { type: "NOT_LEADER", id: "uuid-1" } } as unknown);++ await vi.waitFor(() => expect(leader.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "LOCAL_FETCH" }), expect.anything()));+ channels.at(-1)?.port1.onmessage?.({ data: { type: "LOCAL_FETCH_RESPONSE", id: "uuid-1", response: { status: 200, headers: {}, body: null } } } as unknown);+ expect((await awaitResponse(event)).status).toBe(200);+ });});diff --git a/apps/standalone/src/sw.ts b/apps/standalone/src/sw.tsindex f2ebfb9b61..62e44ffc1f 100644--- a/apps/standalone/src/sw.ts+++ b/apps/standalone/src/sw.ts@@ -92,23 +92,65 @@ async function networkFirst(request) {/* v8 ignore stop */}+// Only one tab owns the database (it holds the Web Lock and is the only one with+// a worker), so every tab's API traffic has to reach that specific tab. This is+// a cache: the service worker is evicted when idle and loses it, so a miss falls+// back to probing the open tabs.+let leaderClientId = null;++self.addEventListener("message", (event) => {+ if (event.data?.type === "LEADER_ANNOUNCE" && event.source) {+ leaderClientId = event.source.id;+ }+});++function isMainAppWindow(client) {+ const url = new URL(client.url);+ // Main app is at root or index.html, not in /pdfjs/ or other iframe paths,+ // which have no local bridge of their own.+ return !url.pathname.startsWith("/pdfjs/");+}++/**+ * Ask each candidate tab whether it is the leader. Used when the cached id is+ * missing or stale; the answer is cached again for subsequent requests.+ */+async function findLeader(candidates) {+ for (const candidate of candidates) {+ const channel = new MessageChannel();+ const replied = new Promise((resolve) => {+ const timeout = setTimeout(() => resolve(null), 1_000);+ channel.port1.onmessage = (event) => {+ clearTimeout(timeout);+ resolve(event.data);+ };+ });++ candidate.postMessage({ type: "WHO_IS_LEADER" }, [channel.port2]);+ const answer = await replied;+ if (answer?.isLeader) {+ leaderClientId = candidate.id;+ return candidate;+ }+ }+ return null;+}+async function forwardToClientLocalServer(request, _clientId) {- // Find the main app window to handle the request- // We must route to the main app (which has the local bridge), not iframes like PDF.js viewer// @ts-expect-error - self.clients is valid in service worker contextconst all = await self.clients.matchAll({ type: "window", includeUncontrolled: true });+ const candidates = all.filter(isMainAppWindow);- // Find the main app window - it's the one NOT serving pdfjs or other embedded content- // The main app has the local bridge handler for LOCAL_FETCH messages- let client = all.find((c: { url: string }) => {- const url = new URL(c.url);- // Main app is at root or index.html, not in /pdfjs/ or other iframe paths- return !url.pathname.startsWith("/pdfjs/");- }) || null;+ let client = candidates.find((c) => c.id === leaderClientId) || null;+ if (!client) {+ client = await findLeader(candidates);+ }- // If no main app window found, fall back to any available client+ // No leader answered (e.g. the old one is closing and the next has not been+ // promoted yet). Fall back to the first app window rather than dropping the+ // request; if it is not the leader it replies NOT_LEADER and we retry below.if (!client) {- client = all[0] || null;+ client = candidates[0] || all[0] || null;}// If no page is available, fall back to network@@ -154,6 +196,15 @@ async function forwardToClientLocalServer(request, _clientId) {const localResp = await responsePromise;+ // We picked a follower. It refused to open a second database; re-resolve the+ // leader and try once more.+ if (localResp?.type === "NOT_LEADER") {+ leaderClientId = null;+ const leader = await findLeader(candidates.filter((c) => c.id !== client.id));+ if (!leader) return fetch(request);+ return forwardToClientLocalServer(request, _clientId);+ }+if (!localResp || localResp.type !== "LOCAL_FETCH_RESPONSE" || localResp.id !== id) {// Protocol mismatch; fall backreturn fetch(request);