Standalone browser runtime
The standalone browser runtime runs Trilium in a browser page while keeping its database and core services on the user's device. It combines durable browser storage with a local worker and a request bridge, then adapts that model for web, Android, and iOS hosts. For the wider client model, see platform clients, desktop shell and IPC, and deployment targets and operations.
Runtime model
The runtime separates the page, the local server worker, and the platform request path. The page renders the client, the local server worker owns the database and shared services, and a service worker or native request bridge makes local routes available to the client. The package uses SQLite WASM as its browser database engine and provides development, production preview, unit test, and end-to-end test entry points through apps/…/package.json.
flowchart LR
UI[Browser page] --> Route[Service worker or native request bridge]
Route --> Bridge[Local bridge]
Bridge --> Worker[Local server worker]
Worker --> DB[(Browser database)]
Worker --> Remote[Configured sync and API targets]
Application startup
Application startup first establishes the platform's local request path. The HTML shell keeps the PWA and mobile metadata, a no-script message, and an inline startup splash available before the application module loads. The splash reports weighted startup phases and adapts to dark mode, reduced motion, and print output before it disappears when the shared client is ready. apps/…/main.ts then lets one tab claim database leadership, starts the local worker only in that tab, and loads the shared client after the service worker controls the page. On mobile shells with a native request channel, the runtime installs the native bridge instead and removes stale service workers from older builds. Bootstrap also asks the browser for persistent origin storage, but a refusal is reported as best effort and does not by itself stop startup.
The standalone platform provider gives the shared core a browser-safe platform view. It marks the runtime as standalone rather than Electron, detects the host OS for matching client behavior, and maps supported URL flags such as safe mode and a start note into the worker's environment view. The browser owns the database storage, so this provider exposes no file path. Shared database work uses the runtime's database lock so platform callbacks do not compete with imports or other held connections.
The local worker initializes the shared core against browser-specific services. It opens the persistent browser database, reads the separate security settings, starts local sync and scheduled work, and exposes the broad route surface that the client expects from a server. It loads runtime services after its error handlers are active, so a heavy browser dependency cannot fail before the page can receive a startup error. It also registers the standalone LLM skill reader, which serves the skill sheets bundled into the application because the browser runtime has no server resource directory. A startup failure is shown as a blocking error because the page cannot provide a useful local session without this worker. After startup, an escaped error is reported as a background failure so one failed task does not end an active session.
The standalone build also uses generated in-app help artifacts. The help provider inlines the help tree and loads rendered page content and related assets from the build's server-assets/help area during worker startup. If the content load fails, help navigation remains available but page bodies are absent.
Fatal failures can occur after the page's first bootstrap try block has ended. The framework-free error overlay writes the failure into the document, removes the startup splash, shows useful detail, and offers a reload action. Its layout uses the active theme and device safe-area insets, so the failure remains readable in a mobile shell. The first reported failure wins so one worker fault does not cover the original cause with a second message. If a startup module fails to load, the runtime tries one reload; a session marker prevents a repeated failure from creating a reload loop. If session storage is not available, it shows the error instead of retrying.
References: apps/…/index.html• L3-11 apps/…/index.html• L12-117 apps/…/index.html• L120-155 apps/…/main.ts• L21-29 apps/…/main.ts• L71-147 apps/…/main.ts• L149-200 apps/…/platform_provider.ts• L6-57 apps/…/local-bridge.ts• L473-628 apps/…/local-server-worker.ts• L1-68 apps/…/local-server-worker.ts• L169-229 apps/…/local-server-worker.ts• L243-435 apps/…/local-server-worker.ts• L672-733 apps/…/local-server-worker.spec.ts• L17-40 apps/…/error-overlay.ts• L22-114 apps/…/error-overlay.spec.ts• L19-135 apps/…/in_app_help_provider.ts• L1-61 apps/…/llm_skills.ts• L1-35 apps/…/package.json• L1-14 apps/…/package.json• L16-23
Local service boundary
The local service boundary turns browser messages into request and response objects for the shared core. The browser router keeps the server-like route contract by matching methods and Express-style paths, decoding path values, reading query and body data, and shaping JSON, text, binary, and error responses. It also accepts wildcard paths for custom routes and can defer reading a posted File until an import route asks for its contents.
This boundary lets the client use familiar paths such as /bootstrap, /api/, /sync/, /search/, and /custom/ without a separate local HTTP server. Shared core routes keep their normal result and transaction rules, while standalone-only routes cover browser needs such as local bootstrap, streamed chat control, database checks, shared-note pages, and custom request handlers. The router accepts file uploads and byte-range responses so browser-managed media and import flows use the same route contract as server clients. Requests that need one long transaction wait for exclusive access to the worker's single database connection. Other requests share the connection when no such transaction is active. Operations that replace or reopen the database run outside a normal transaction so the connection can change safely. Route wrappers create the request context inside that lock; the router itself does not create a context that could outlive the lock.
The route boundary also preserves the different completion and response forms that browser features need. It waits for asynchronous work, passes raw media and HTML responses without JSON conversion, and keeps upload files available in the form expected by import and file routes. A raw byte view is narrowed to its own range before it leaves the worker, so a media seek does not return the backing file. The route checks cover these contracts together with setup responses, detached-window bootstrap, and compatibility routes.
Published notes use the same local service boundary. A /share request is rendered from the local database and returns the share theme's page response. The standalone share provider binds that rendering to the active browser database connection and to templates bundled into the application because the browser runtime has no server file system. Note-specific templates are not executed because standalone does not enable backend scripting. The share theme's own files remain static build assets, so the runtime can render a shared note without a server while still loading its styles, scripts, fonts, and icons.
Custom request handlers and resource providers use the /custom/ path. Resource providers can return stored content without running code. Request handlers can run only when backend scripting is enabled, and their response is complete before the local worker answers. This keeps browser behavior finite even when a handler performs asynchronous work.
References: apps/…/local-bridge.ts• L59-61 apps/…/browser_router.ts• L71-124 apps/…/browser_router.ts• L157-200 apps/…/browser_router.ts• L206-345 apps/…/browser_router.ts• L347-381 apps/…/browser_routes.ts• L67-170 apps/…/browser_routes.ts• L319-392 apps/…/browser_routes.ts• L478-527 apps/…/share_provider.ts• L12-64 apps/…/db_lock.ts• L1-21 apps/…/browser_router.spec.ts• L39-69 apps/…/browser_router.spec.ts• L151-195 apps/…/browser_router.spec.ts• L208-365 apps/…/browser_routes.spec.ts• L21-192 apps/…/browser_routes.spec.ts• L259-367
Browser storage
Browser storage gives the standalone runtime a local database that survives page reloads and browser restarts. The runtime uses the Origin Private File System (OPFS), a private file area owned by the page's origin, through SQLite's browser storage layer. The preferred storage pool supports the write and access pattern needed by the local database.
Persistent database
The database is the shared source of truth for notes, settings, sync state, and other local application data. apps/…/sql_provider.ts opens the named database in the OPFS pool and supports the database operations expected by the shared core. The active database name is kept as browser state so a restore can replace the database without exposing a normal file path.
The normal standalone startup requires persistent OPFS access. The provider has an in-memory mode for special use such as controlled integration runs, but the application does not silently switch to it when persistent storage is unavailable. This prevents the runtime from opening an empty session whose data disappears when the page closes. The platform provider therefore reports no ordinary file path to the rest of the application.
After a reload, startup waits for access handles held by the previous worker to close before it installs the storage pool. This protects the database from a partial pool operation that could remove active data instead of waiting for the old context to release it.
References: apps/…/sql_provider.ts• L293-332 apps/…/sql_provider.ts• L348-395 apps/…/sql_provider.ts• L437-464 apps/…/sql_provider.ts• L690-777 apps/…/local-server-worker.ts• L249-305 apps/…/sql_provider.spec.ts• L344-446 apps/…/sql_provider.spec.ts• L552-664
Browser cryptography
Browser cryptography keeps protected notes and related integrity checks compatible with the server and desktop clients. The standalone provider supplies synchronous hashes, HMAC, AES-128-CBC, constant-time comparison, secure random values, and asynchronous scrypt using browser-safe primitives. It treats binary input as bytes so encrypted or protected binary content has the same digest and decryption result on every client.
Base64 conversion uses native typed-array methods when the host provides them. Older mobile WebViews use a streaming fallback that avoids a large intermediate string, and pooled decoding can write sync data directly into a supplied buffer. The provider's parity checks compare these results with Node's crypto behavior across text, binary, encryption, key derivation, and large payloads.
References: apps/…/crypto_provider.ts• L1-24 apps/…/crypto_provider.ts• L26-125 apps/…/crypto_provider.ts• L142-184 apps/…/crypto_provider.ts• L199-252 apps/…/crypto_provider.spec.ts• L34-155 apps/…/crypto_provider.spec.ts• L249-477
Security capability settings
Standalone security settings control whether backend scripting and the SQL console can run in the local instance. They live outside the database, which prevents a database write from granting either capability, and they default to off when the setting store cannot be trusted.
The page must obtain a browser confirmation before it asks the worker to change a setting. The worker owns the setting file and applies a successful change on the next start, so the current core session cannot silently gain a new capability. Only the leader can make the change because only its worker owns the setting store.
References: apps/…/security_settings.ts• L5-18 apps/…/security_settings.ts• L56-95 apps/…/security_settings.ts• L121-191 apps/…/security_gate.ts• L5-25 apps/…/security_gate.ts• L45-76 apps/…/local-bridge.ts• L103-149 apps/…/local-server-worker.ts• L585-624 apps/…/local-server-worker.spec.ts• L43-69
Setup and database replacement
Setup state uses a small marker in the same browser storage area as the database. The marker is read before the database opens, so a restart can enter the setup flow without opening the old database first. Backup restore replaces the local database only from the tab that owns it, then returns the worker to normal application mode.
Restore streams a selected database or backup container into a second pool entry. It checks the file type, passphrase, schema, and required options before changing the pointer that names the live database. The old entry remains live until that final swap succeeds, and a failed swap restores the old pointer. This lets the setup flow report whether the file is incomplete, protected, invalid, or unable to open without discarding the current notes.
Backup download follows the reverse path. The local worker reads the live database through its pages and wraps every output in one backup-container format. A passphrase adds encryption; without one, the container is still protected by its recorded digest. The service worker streams the result to the browser's download manager. This avoids staging a second full database in page storage and keeps the passphrase out of the download URL. The stream detects writes during the read and rejects a mixed snapshot instead of producing a backup with uncertain contents. Its exact size is known before transfer, so the browser can show a reliable progress bar. Restore progress and the final result return through the page bridge so the setup screen can show each stage.
On Capacitor, the page consumes the same backup stream and saves a complete file before opening the system share sheet. A dismissed share sheet does not undo the saved backup, and a failed partial write does not replace the previous backup.
References: apps/…/local-server-worker.ts• L472-579 apps/…/local-server-worker.ts• L627-670 apps/…/local-bridge.ts• L63-100 apps/…/local-bridge.ts• L193-370 apps/…/backup-stream.ts• L49-149 apps/…/backup-download.ts• L12-33 apps/…/backup-download.ts• L93-209 apps/…/database_restore.ts• L18-31 apps/…/database_restore.ts• L57-139 apps/…/database_restore.ts• L149-190 apps/…/database_restore.ts• L231-305 apps/…/backup-download.spec.ts• L115-225 apps/…/backup-stream.spec.ts• L50-120 apps/…/database_restore.spec.ts• L243-332 apps/…/capacitor_download.ts• L85-107 apps/…/capacitor_download.ts• L149-198
Local exports
Standalone exports turn local note data into HTML, Markdown, or a share-theme archive without relying on a server file system. HTML exports also include the editor's content, admonition, aside, and multi-column styles so exported notes keep their document layout. Share-theme exports use the standalone share provider and load the theme files, built-in icon fonts, translations, and optional Mermaid client files that the standalone build serves, so an exported archive can render away from the application.
The share-theme export uses the build manifest as its asset contract. It requires a production share-theme manifest, includes only translation catalogues that the build serves, and fails when a required theme asset is missing. Development builds can omit built Mermaid files, so the export keeps the diagram as source content instead of failing on an optional asset that does not exist. This makes the export useful in development without allowing an incomplete share archive in a production build.
The browser ZIP provider reads uploaded archives from bytes or a Blob. It reads the central directory and then fetches entry ranges only when their contents are requested. It can create an archive in memory for browser downloads, but it does not provide a file stream backed by a local filesystem. It bounds inflated entry size and rejects corrupt, encrypted, and unsupported archives. Legacy archive names can use a detected common encoding, while names that declare UTF-8 keep that declaration even when the same archive contains legacy names. ZIP64 metadata remains supported by the shared archive reader.
References: apps/…/zip_export_provider_factory.ts• L13-46 apps/…/zip_export_provider_factory.ts• L49-61 apps/…/zip_export_provider_factory.ts• L63-115 apps/…/share_provider.ts• L12-64 apps/…/zip_provider.ts• L14-57 apps/…/zip_provider.ts• L60-125 apps/…/zip_provider.ts• L127-207 apps/…/zip_export_provider_factory.spec.ts• L35-132 apps/…/zip_provider.spec.ts• L77-169 apps/…/zip_provider.spec.ts• L171-346 apps/…/zip_provider.spec.ts• L348-409 apps/…/vite.config.mts• L25-43 apps/…/vite.config.mts• L191-212
Image handling
The standalone image provider accepts image data without changing its bytes. It uses the shared image inspector to identify supported formats, reports unknown data as a generic file, and declines compression and preview resizing because this browser runtime has no image decoder for those operations. The client can still store and display an image that is already suitable for use, while unsupported optimization is reported as a platform limit rather than as a failed upload.
References: apps/…/image_provider.ts• L1-64 apps/…/image_provider.spec.ts• L20-106
Local diagnostics
The standalone log service stores dated log files in the same origin-private storage model as the local application. It writes the active file through a synchronous access handle, keeps a bounded in-memory buffer while another worker still holds the file, and retries in the background so a worker replacement does not lose the first useful failure details.
The service keeps a seven-day log window and reads the current file for the in-app log view. If the file remains unavailable, the runtime reports that state with the buffered entries instead of blocking the application or silently discarding its diagnostics.
References: apps/…/log_provider.ts• L4-27 apps/…/log_provider.ts• L42-109 apps/…/log_provider.ts• L134-192 apps/…/log_provider.ts• L195-229 apps/…/log_provider.spec.ts• L238-337
Tab coordination
Tab coordination prevents two browser contexts from opening the same local database at the same time. A browser Web Lock selects one leader tab. The leader owns the local server worker and database connection. Other tabs remain usable by sending local requests through the service worker to that leader.
Leadership ownership
apps/…/leader_election.ts holds one exclusive lock for the lifetime of the leader tab. When that tab closes, the browser releases the lock and promotes a waiting tab. This avoids a heartbeat-based decision that could leave two tabs believing that they own the database.
The service worker keeps a best-effort leader client ID. When that value is missing or stale, it asks open application tabs which one is the leader. If a guessed tab refuses a request, the service worker clears the cached choice and keeps resolving leadership until the promotion window ends. Body-bearing requests remain retryable because the service worker reads their body from a clone rather than consuming the original request.
The page starts the local worker only after it wins leadership. A follower never starts a second worker in response to a request, a restore, a backup download, or a security change. It returns a leader signal or a refusal so the service worker can find the owner without risking a second database connection.
References: apps/…/main.ts• L106-121 apps/…/local-bridge.ts• L77-87 apps/…/local-bridge.ts• L125-149 apps/…/local-bridge.ts• L652-706 apps/…/leader_election.ts• L1-15 apps/…/leader_election.ts• L25-50 apps/…/sw.ts• L119-185 apps/…/sw.ts• L228-310 apps/…/main.spec.ts• L95-137 apps/…/local-bridge.spec.ts• L865-940
Cross-tab state updates
Local writes made by a follower still reach the leader's database through the request bridge. After a write, the leader emits a WebSocket-style entity change message. The page dispatches its own update and relays the same message through a BroadcastChannel, a browser channel for messages between same-origin tabs. This keeps note trees and other client caches aligned without a reload.
The same rule applies to a detached extra window. It shares the database with the main window but does not own the saved tab set, so it can show the same data without overwriting the main window's navigation state. Security changes and database replacement remain limited to the leader window.
References: apps/…/local-bridge.ts• L20-56 apps/…/local-bridge.ts• L588-595 apps/…/browser_routes.ts• L53-64 apps/…/browser_routes.ts• L394-419 apps/…/multi_tab.spec.ts• L52-79 apps/…/extra_window.spec.ts• L5-15
Request and sync paths
The runtime separates local application requests from outbound requests to a configured remote service. Local paths stay inside the browser and reach the local worker. Remote sync and fetch work use browser fetch on the web, or a native HTTP path when a mobile host must bypass browser network limits.
Local request routing
The service worker intercepts the local API path groups and shared-note paths before normal page navigation and asset handling. It forwards request bodies and headers to the selected leader through a message port, then turns the worker response back into a browser Response. If no page can serve the local request, if the message protocol fails, or if the selected page is no longer the leader, it returns a clear local error instead of sending an API request to a static host. A stale-leader request can wait while another tab takes the Web Lock, but it stops when the leadership wait window ends.
The local bridge also handles operations that do not fit a normal request body. Restore sends a File directly to the worker. Backup download uses a streamed message channel with backpressure, so a large database does not need to be held in full in page memory. The page sends periodic no-op fetches while the stream is active so browser service-worker idle rules do not stop a long download.
References: apps/…/local-bridge.ts• L59-73 apps/…/local-bridge.ts• L389-433 apps/…/local-bridge.ts• L652-727 apps/…/sw.ts• L22-30 apps/…/sw.ts• L228-310 apps/…/sw.ts• L313-397 apps/…/sw.ts• L400-433
Remote request transport
The normal browser transport uses page fetch with browser-managed credentials for same-origin API requests. It validates configured URLs and remains subject to the browser's same-origin and CORS rules for third-party resources. API timeouts cover both response headers and body reads, so a stalled sync body reports a useful phase. Resource reads use a short timeout and a response-size cap, while API calls retain the response form needed by sync and other streamed work. This is the expected path for the web build.
In a Capacitor host, the worker can send an HTTP request to the page through a message bridge. The page then uses the native HTTP plugin. This path carries remote resource and image responses across the bridge, while configured API calls continue through page fetch so streamed responses remain incremental. When a native API response is already parsed as JSON, it crosses as structured data instead of making the worker parse another full string. Requests with binary results use a separate byte response path, and resource responses are checked against their decoded size limit before base64 decoding.
The native path can read cross-origin resources that a WebView cannot expose because of CORS. The browser path reports these CORS limits to the caller instead of treating an unreadable response as an empty resource. Both paths reject unsupported URLs before sending a request and enforce the response size limit available to their transport.
References: apps/…/local-bridge.ts• L435-471 apps/…/main.ts• L91-104 apps/…/request_provider.ts• L4-9 apps/…/request_provider.ts• L12-97 apps/…/request_provider.ts• L125-158 apps/…/bridged_request_provider.ts• L4-10 apps/…/bridged_request_provider.ts• L36-129 apps/…/bridged_request_provider.ts• L178-235 apps/…/capacitor_http_handler.ts• L38-44 apps/…/capacitor_http_handler.ts• L92-190 apps/…/bridged_request_provider.spec.ts• L172-347 apps/…/capacitor_http_handler.spec.ts• L108-227
Platform interception
Platform interception preserves the local request contract when the host cannot provide a normal service-worker path. The web and Android builds use service-worker routing on HTTP(S) origins when no native request channel is present. Mobile shells can instead use a native request bridge that receives requests from the WebView and returns local worker responses in chunks.
Web and Android handling
On a normal HTTP(S) origin, the service worker handles local API paths and shared-note pages and leaves unrelated remote requests to the browser. It supports network-first behavior for page navigations and cache-first behavior for static GET assets. The current source runs with cache bypass enabled for development, so local changes appear at once.
Android Capacitor uses an HTTPS WebView origin. Its native proxy can answer selected same-origin proxy URLs without passing the full response through the plugin message envelope. The service worker leaves those proxy URLs untouched so the WebView's native interception layer can receive them. The proxy is used only when its availability probe succeeds; POST and binary requests stay on the native plugin path.
The build keeps the service-worker URL stable while content chunks use build-specific names. It also publishes the SQLite WebAssembly files and share-theme assets under the names the worker and share export expect. Help assets and PDF.js files are available through matching development and production paths. Together these rules let a page move to a new build without mixing old and new chunks or losing the worker's runtime assets. Capacitor downloads use a separate page-to-device path because a WebView does not provide the browser download manager used by the web build.
References: apps/…/main.ts• L91-140 apps/…/sw.ts• L1-21 apps/…/sw.ts• L400-459 apps/…/capacitor_http_handler.ts• L38-82 apps/…/capacitor_http_handler.ts• L101-134 apps/…/capacitor_http_handler.spec.ts• L108-227 apps/…/vite.config.mts• L91-123 apps/…/vite.config.mts• L125-193 apps/…/vite.config.mts• L196-267 apps/…/vite.config.mts• L448-475
Mobile request bridge
The mobile request bridge lets Android and iOS native WebView hooks serve local API and shared-note requests when a service worker cannot control the page. The native side forwards GET and HEAD requests from any WebView loader, including images, stylesheets, fonts, frames, and media. The page answers through localFetch() and sends the result back as a response header followed by bounded binary or base64 chunks.
Requests with bodies remain on the page request path because the native interception hook does not provide their body. A native redirect becomes a small page navigation because the native response APIs do not carry a normal 3xx response. If no native channel is available, startup uses the service-worker bridge instead.
References: apps/…/native-request-bridge.ts• L1-39 apps/…/native-request-bridge.ts• L41-105 apps/…/native-request-bridge.ts• L107-151 apps/…/main.ts• L123-140 apps/…/main.spec.ts• L194-281 apps/…/native-request-bridge.spec.ts• L59-157
Capacitor file handling
Capacitor file handling saves downloads and backups inside the mobile app before it calls the system share sheet. Ordinary downloads use short-lived cache files, while backups use durable document storage and replace the old file only after the new file is complete.
The page consumes response or backup bytes in chunks. It uses a native binary sink when the shell provides one and a base64 plugin path otherwise, while keeping the write order and cleanup rules the same. This gives web, Android, and iOS a common save result even though their host download behavior differs.
References: apps/…/capacitor_download.ts• L13-51 apps/…/capacitor_download.ts• L66-107 apps/…/capacitor_download.ts• L149-198 apps/…/capacitor_download.ts• L267-342 apps/…/local-bridge.ts• L265-302 apps/…/capacitor_download.spec.ts• L365-497
Change checklist
When these files or sections are changed, remember to consider these:
- The local path list must stay aligned across local-bridge.ts, sw.ts, and native-request-bridge.ts. A new local route or share path can silently use the remote network path on one platform.
- The browser route registration must keep the shared route contract aligned with the request prefixes. A route that is registered but not intercepted can leave the client with a local-looking URL that goes to the network.
- Shared route wrappers, transaction choice, request context, raw response handling, upload parsing, wildcard paths, and method coverage must stay aligned. A change can preserve a route name while breaking async work, media ranges, imports, custom handlers, or HEAD requests.
- Share route paths, share templates, static share assets, and share-export asset lookup form one contract. A new share page or asset must work both as a live
/sharepage and inside a share-theme export. - Message types for local requests, leader probes, backup streams, native requests, and worker responses form one contract across the page, service worker, native shell, and local worker. Change all sides together.
- Database ownership changes must update both Web Lock promotion and service-worker leader discovery. Otherwise a follower can receive a request but cannot safely serve it.
- Entity-change delivery must preserve both the leader tab's local event and the
BroadcastChannelrelay. Losing either path leaves one class of tab with stale client state. - Native HTTP changes must keep the Android proxy limits separate from the plugin path. POST bodies and binary responses cannot use the streaming proxy contract. Structured JSON responses must remain distinct from base64 binary responses.
- Security setting changes must preserve the browser confirmation, leader-only bridge, locked worker file, and next-start application rule. Opening the write on the public worker message path or in the database removes the safety boundary.
- Setup marker and active database replacement must keep their read, replace, and reopen steps in the same worker lifecycle. A stale marker or old connection can send the client to setup with the wrong database.
- Restore staging, validation, pointer replacement, rollback, and pool cleanup form one database replacement contract. A change that moves the pointer before validation can make a bad or incomplete file live.
- Backup reads must keep their live-database consistency check and cancellation path. A change during the stream must fail the backup instead of producing a mixed snapshot.
- Backup container sizing, encryption state, digest handling, and restore format detection must remain aligned. An output that is readable as a download but not by the restore path breaks the only local recovery loop.
- Capacitor save targets and temporary-file rename rules must stay distinct for ordinary downloads and user backups. Pruning or replacing the wrong target can remove a file that the share sheet still uses or damage the last good backup.
- Service-worker entry naming, SQLite runtime asset names, and copied help, PDF.js, and share-theme assets must remain stable across the build and startup code. A changed name can leave an installed worker or share export unable to load its runtime files.
- Persistent OPFS startup must keep its release wait before pool installation. Removing that order can turn a normal reload into data loss.
- Browser route response rules must keep raw byte ranges, HTML fragments, multipart uploads, and HEAD responses distinct from JSON results. A change in result formatting can break media seeking, uploads, previews, or custom handlers without changing the route names.
- A custom request handler must remain behind the scripting capability check, while a resource provider must remain readable when scripting is off. Mixing the two paths changes the local security boundary.
- Standalone platform flags must keep their URL-to-environment mapping and host OS mapping aligned with startup and worker code. An unrecognized or renamed flag can silently disable safe mode or change the requested start note, while a platform mismatch can show the wrong client shortcuts.
- Platform callbacks that need the database must continue to use the shared database lock. Running them outside that boundary can commit derived data while an import still owns the connection.
- Log-file replacement must preserve the bounded pending buffer, generation check, and background retry. Otherwise a new worker can close or adopt the wrong handle and lose startup diagnostics.
- Share-export asset names must stay aligned between the export provider, the build's copied theme files, and the Mermaid manifest. A path change can produce archives that download successfully but cannot render.
- Image format detection must stay aligned with the shared image inspector. A change in the accepted format result can make stored image metadata differ between standalone and other clients.
- Standalone image operations must keep their unsupported-platform result explicit. Enabling compression or preview resizing requires a decoder and changes storage, preview, and user-facing outcome contracts.
- The HTML shell's startup splash, module entry point, and error overlay must keep one lifecycle. A changed element ID or startup phase can leave a failed launch hidden behind the splash or show progress that never completes.
- Module-load failure detection and its session reload marker must stay aligned with browser error text and the overlay lifecycle. A broad match can hide real startup errors behind reloads, while a missing engine variant can leave a transient chunk failure on a blank page.
- The standalone worker entry must keep runtime dependencies dynamically loaded after its error handlers. A static value import can move SQLite or core startup before failure reporting and break mobile WASM loading.
- The standalone package's SQLite WASM dependency and build entry points must remain compatible with the browser storage and worker assets. A package or script change can make local development, preview, or production startup use a different runtime path.
- Generated help metadata, rendered help content, copied help assets, and
StandaloneInAppHelpProvidermust remain aligned. A stale build artifact can remove help content or leave its tree pointing at unavailable pages even when the main client starts normally. - Bundled LLM skill names and the shared skill catalog must remain aligned. A renamed or omitted raw skill file can leave an in-app assistant without the instructions it needs even though the main worker starts normally.
- Browser and native request providers must preserve the split between streamed API calls and whole-response resource calls. Moving a streamed API call through the whole-response bridge can change user-visible latency and memory use. Native resource size checks must happen before base64 decoding, while structured JSON API responses must avoid an unnecessary second parse.
- URL validation, CORS reporting, request timeouts, and response-size caps must remain consistent with the browser and native request contracts. Changing one transport can make remote resource reads unsafe or fail differently by platform.
- Native request framing must stay aligned between the WebView hooks and native-request-bridge.ts. A changed chunk size, frame id, or end marker can turn a valid local response into a broken image, stylesheet, or media load.
- Native request interception and page
localFetch()must keep their method boundary. Sending a body-bearing request to the native interceptor can lose the body before the local route sees it. - ZIP entry-name detection must keep declared UTF-8 names separate from unflagged legacy names. Applying a detected legacy encoding to all entries can make an export archive fail to find its metadata.
- Browser ZIP reads must keep random-access Blob handling, central-directory-first reads, ZIP64 support, entry-size limits, and rejection of encrypted or unsupported entries. Relaxing one guard can cause high memory use or incomplete imports.
- Browser ZIP output is an in-memory archive and does not provide a filesystem stream. A change that assumes backpressure or a local path can make browser downloads fail or consume more memory than expected.
- Browser cryptography must preserve byte-level parity with Node for hashes, HMAC, scrypt, AES padding, and base64. A text conversion or fallback change can make protected notes fail integrity checks or exceed mobile WebView memory.
- The native base64 fast path and the older-WebView fallback must remain behaviorally equal. A change to pooled decode must preserve output length and ignore padding and whitespace without allocating a second full blob.
- The worker-shaped test environment must keep browser module resolution and the worker global boundary. Running core tests in a page-like environment can hide dependencies that fail in the production worker.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A web or Android page is not a secure HTTP(S) context and has no usable service worker or native request channel | The standalone page cannot establish its normal local request path | Bootstrap checks service-worker support and directs the user to HTTPS or localhost; mobile shells use the native bridge when present |
| OPFS is unavailable or its access cannot be acquired | The persistent notes database cannot open and the application does not start with an empty temporary database | Startup waits for old handles, then reports a blocking error when the persistent pool still cannot open |
| A request reaches a follower tab | Opening a second database is unsafe, so the request cannot be served there | The follower returns NOT_LEADER; the service worker re-resolves leadership |
| A leader closes during a request | The request can wait or return 503 while another tab waits for promotion | Web Lock release promotes a waiting tab and service-worker discovery retries until its bounded wait ends |
| A stale leader receives a body-bearing request | Leadership recovery can fail because the request body was already consumed | The service worker reads the body from a clone and reuses it while it retries within the bounded wait |
| A security setting file cannot be locked or read | Backend scripting and the SQL console stay disabled rather than using an untrusted value | The worker grants no capability unless it owns the file lock and can read valid boolean settings |
| A page script asks to enable a security capability without a user action | The request does not reach the setting file | The page uses the captured browser confirmation and requires transient user activation; repeated declined grants are limited |
| The live database changes during a backup stream | The backup is rejected instead of containing a mix of old and new database pages | The stream checks its database fingerprint before each batch and at the end |
| A backup stream is cancelled or its receiver disappears | The worker can otherwise keep reading pages with no destination | Pull timeouts, explicit cancellation, and stream cleanup close the port and cancel the unread source |
| A backup file is incomplete, encrypted without a passphrase, or fails database validation | Restore leaves the current database live and reports an actionable failure | Restore reads the format before import, validates a staged candidate, and changes the live pointer only after checks pass |
| A shared-note request has no open application tab | The share page cannot be rendered because no local worker owns the database | The service worker returns a clear 503 response that tells the user to open Trilium |
| A share-theme file is missing from the build | Published pages or share-theme exports can be unstyled or incomplete | The build copies the theme assets and the export provider fails when an expected asset cannot be fetched |
| A share-theme export has no valid production manifest | The archive cannot determine the required theme asset set | The export requires the built manifest and reports that a production build is needed |
| A mobile WebView has no native request channel and cannot use a service worker | Local API, image, stylesheet, and media requests have no local responder | Startup falls back to the service worker when possible and shows a startup error when neither path exists |
| A native request carries a body that the WebView hook did not expose | The local route receives no body or cannot perform the requested upload | Body-bearing requests use the page localFetch() path rather than native interception |
| A native response uses an unsupported redirect or malformed bridge message | The WebView resource or navigation fails instead of reaching the local route | The bridge converts redirects to a safe navigation page and sends explicit error and end messages |
| Capacitor has no native HTTP plugin, or its proxy is not available | Remote sync or resource fetches fail from the mobile runtime | The bridge probes the Android proxy and falls back to the native plugin transport |
| A browser remote request is blocked by CORS or exceeds its timeout or response-size limit | A sync or resource read fails instead of returning a partial or unreadable result | The browser provider validates the URL, reports CORS as an error, aborts slow requests during headers or body reads, and caps resource reads |
| A native resource response exceeds its size limit | The whole response has already crossed the bridge and is refused before decoding | The bridged provider checks decoded size before base64 decoding and returns a size error |
| A native API response is sent as an already-parsed object but the worker treats it as text | A large sync result pays an avoidable parse and memory cost or fails because no body string exists | The bridged provider accepts structured response data before falling back to text parsing |
| A Capacitor save fails after writing only part of a file | The previous backup remains available and the partial file is removed | The page writes a part file and renames it only after the stream completes |
| An uncaught worker error occurs before startup completes | The page cannot use the local session and must show a blocking startup error | The worker reports a WORKER_ERROR and the page renders the standalone error overlay |
| An uncaught worker error occurs after startup completes | A background task fails, but ending the active session would be more harmful than keeping it open | The worker reports an unhandled-error message and continues serving the session |
| JavaScript is disabled or the module entry point cannot run | The application cannot start, but the page still needs to explain why or show the last startup state | The HTML shell provides a no-script message and keeps the startup UI inline before external code loads |
| A startup module fails to load because a chunk or connection is temporarily unavailable | The page may remain on its splash or show a startup error even though a retry could work | The overlay recognizes the supported browser module-load errors and reloads once; sessionStorage stops repeated reloads within one minute |
| A browser route returns a byte view as its full backing buffer | A media range request can return unrelated bytes or the full file | Raw response formatting sends only the view's own byte range |
| A browser route needs request context but the route wrapper does not hold the database lock | A concurrent request can replace the context while an async handler is still running | Shared route wrappers open context inside the exclusive or shared dbLock scope; the router does not open one outside it |
| A custom handler returns after an await or does not send a response | The request can be sent before the handler's result exists, or it can hang without a useful answer | The custom route awaits the handler and returns a 500 response when no response was sent |
| Another worker holds the active log file during startup | The app can lose early log entries or show no useful reason for a startup failure | The log service buffers a bounded set of entries and retries the file open with an invalidated-handle check |
| A share export cannot fetch a required theme asset | The archive is incomplete and its published page can fail to render | The export rejects the operation and the build copies the theme files to the paths used by the exporter |
| Standalone receives an image format that the shared inspector does not know | The image is stored as generic data and cannot receive a known image type | The provider delegates format detection to the shared inspector and uses a generic fallback for unknown data |
| A caller asks standalone to compress or resize an image preview | The image stays unchanged and the caller must handle an unsupported optimization result | The provider returns unsupported-platform instead of pretending that the operation changed the image |
| Generated help metadata is stale or help content is unavailable | Help navigation can remain visible while page bodies or linked assets fail | The provider uses the generated tree as a build contract, loads content during worker startup, and logs content-load failures |
| A bundled LLM skill sheet is missing or has the wrong name | An in-app assistant can lack a skill description or API guide even when the worker is healthy | The build inlines the known skill set and the standalone reader returns only matching catalog names |
| A browser request needs third-party CORS access but uses the page transport | The remote response is blocked even when the target server is healthy | The browser provider reports the CORS failure; Capacitor uses the native bridge for resource requests that need it |
| A ZIP archive is corrupt, encrypted, uses an unsupported compression method, or declares an entry above the browser limit | Import stops instead of silently producing incomplete note data or exhausting browser memory | The browser ZIP provider validates the central directory, reads entries by range, checks declared size before inflation, and rejects unsupported entry data |
| A ZIP archive mixes legacy unflagged names with a name that declares UTF-8, and the declared name is decoded with the legacy encoding | An export entry can be renamed and the importer can fail to find its metadata | The provider always decodes UTF-8-flagged names as UTF-8 and applies detected encoding only to ambiguous names |
| A ZIP source is supplied as a filesystem path or a file stream is requested | Browser import or export fails because the runtime has no local filesystem | The provider accepts bytes or Blob ranges and reports path and file-stream operations as unsupported |
| Browser crypto receives binary data through a lossy text conversion | Protected binary notes can fail their integrity check or decrypt incorrectly on standalone or mobile | The provider hashes and authenticates byte input directly and checks parity with Node crypto |
| An older WebView decodes a large base64 sync blob through an intermediate binary string | The WebView can exceed its heap and fail the sync operation | The provider uses native typed-array base64 methods when available and a streaming or pooled fallback on older hosts |
| A worker entry imports a heavy runtime value before its error handlers run | A WASM or core load error can appear as a blank page or break mobile startup before the worker can report it | The worker keeps runtime imports dynamic and tests that only type-only imports are static |
Key files
| File | Why to read it |
|---|---|
| apps/…/index.html | Shows the document shell, PWA and mobile metadata, no-script fallback, and startup splash that bridge the page to the runtime lifecycle |
| apps/…/main.ts | Shows the platform split and the order of worker, leadership, service-worker or native-bridge, storage request, and client startup |
| apps/…/error-overlay.ts | Shows how fatal startup and worker failures reach the user before the client is running |
| apps/…/local-server-worker.ts | Shows how the local core service starts, opens browser storage, serves routes, handles backup and security operations, and separates startup errors from background errors |
| apps/…/local-bridge.ts | Shows the message boundary between the page, service worker, native request path, and local worker |
| apps/…/sw.ts | Shows local-first request routing, leader discovery, shared-note forwarding, and streamed downloads |
| apps/…/leader_election.ts | Defines the one-owner rule for the browser database |
| apps/…/platform_provider.ts | Shows the standalone platform identity, host OS mapping, launch flags, database lock boundary, and no-path storage contract |
| apps/…/browser_routes.ts | Shows how shared core routes, shared-note pages, custom handlers, and raw browser responses become a local browser API |
| apps/…/browser_routes.spec.ts | Shows the route contract for transactions, async work, uploads, byte ranges, bootstrap, and custom handlers |
| apps/…/browser_router.ts | Shows how browser requests, wildcard paths, lazy uploads, and shared-core results keep the server-like API shape |
| apps/…/browser_router.spec.ts | Shows the browser route contract for query and body parsing, raw byte ranges, response errors, and request context isolation |
| apps/…/share_provider.ts | Shows how standalone share rendering uses the local database connection and bundled templates |
| apps/…/zip_export_provider_factory.ts | Shows how browser exports select HTML, Markdown, or share-theme output and assemble build assets for the archive |
| apps/…/zip_provider.ts | Shows how browser imports and exports read bytes or blobs without a filesystem and protect the browser from unsupported or oversized entries |
| apps/…/zip_provider.spec.ts | Shows the archive contract for Blob ranges, ZIP64, filename encodings, malformed data, and entry limits |
| apps/…/crypto_provider.ts | Shows the browser-safe crypto contract shared with protected-note and sync flows |
| apps/…/crypto_provider.spec.ts | Shows byte-level parity with Node crypto and memory-safe base64 behavior on older WebViews |
| apps/…/image_provider.ts | Shows the standalone image contract for format detection, unchanged storage, and unsupported optimization |
| apps/…/log_provider.ts | Shows how standalone diagnostics survive temporary OPFS file locks and worker replacement |
| apps/…/sql_provider.ts | Explains the persistent browser database and the OPFS release boundary |
| apps/…/database_restore.ts | Explains staged backup validation, live-database pointer replacement, rollback, and erase behavior |
| apps/…/security_settings.ts | Defines the separate, locked settings used for backend scripting and the SQL console |
| apps/…/security_gate.ts | Defines the user-confirmation boundary for changing standalone security capabilities |
| apps/…/backup-stream.ts | Defines the consistent live-database read used by backup output |
| apps/…/backup-download.ts | Defines the pull-driven backup stream and its encrypted container output |
| apps/…/request_provider.ts | Shows the browser transport for same-origin APIs, timeout phases, and CORS-limited remote resources |
| apps/…/bridged_request_provider.ts | Shows the native message transport for remote resources, size limits, and structured responses in Capacitor hosts |
| apps/…/native-request-bridge.ts | Shows how Android and iOS WebView interception reaches the local worker and returns bounded response chunks |
| apps/…/capacitor_http_handler.ts | Shows the native transport split used by Capacitor hosts |
| apps/…/capacitor_download.ts | Shows how Capacitor writes complete files and shares them across native hosts |
| apps/…/llm_skills.ts | Shows how worker-bundled skill sheets make LLM guidance available without a server file system |
| apps/…/test_environment_worker.ts | Shows how core tests use a worker-shaped global scope and browser module conditions |
| apps/…/test_setup.ts | Shows how standalone-flavored tests initialize core with browser providers and a fixture database |
apps/standalone/vite.config.mts | Shows how the build publishes worker, SQLite, help, Mermaid, PDF.js, and share-theme assets and prevents mixed-build browser caches |
| apps/…/share.spec.ts | Shows the user-visible contract for local shared-note pages and protected shares |
| apps/…/package.json | Defines the standalone app identity, SQLite WebAssembly dependency, and local build, development, test, and preview entry points |