Skip to content

Build your personal knowledge base with Trilium Notes

docs(claude): Electron desktop and Capacitor mobile skills

Elian Doran4342e71662b0
diff --git a/.claude/skills/developing-capacitor-mobile/SKILL.md b/.claude/skills/developing-capacitor-mobile/SKILL.md
new file mode 100644
index 0000000000..57733933c4
--- /dev/null
+++ b/.claude/skills/developing-capacitor-mobile/SKILL.md
@@ -0,0 +1,85 @@
+---
+name: developing-capacitor-mobile
+description: Use when working on the Trilium mobile app (`apps/mobile`, Capacitor for Android/iOS) or on the standalone code paths that only run inside it — request routing on `capacitor://` vs `https://localhost`, the iOS fetch/XHR/image/stylesheet interceptors, the Android native streaming HTTP proxy (`TriliumWebViewClient`), the `NativeHttpHandler` sync transport, `MainActivity`/`ViewController` WebView tweaks (edge-to-edge, keyboard), `isMobileApp()` gating in the client, or the mobile CI/nightly builds. Also load it when reviewing a diff that touches these files, so working iOS-only code is not flagged as dead.
+---
+
+# Developing the Capacitor mobile app
+
+`apps/mobile` is a **Capacitor shell around the standalone build**: it ships no web assets of its own — `webDir` in `capacitor.config.json` is `../standalone/dist`, and the entire Trilium server runs **in-process as WASM in a web worker** (`apps/standalone`). There is no network backend inside the app; "the server" is `apps/standalone/src/local-server-worker.ts`. Most mobile work therefore lands in `apps/standalone/src/`, with the native projects (`apps/mobile/android/`, `apps/mobile/ios/`) touched only for WebView behaviour.
+
+Key files:
+
+```
+apps/mobile/capacitor.config.json # appId org.triliumnotes.trilium, androidScheme https, hostname localhost, plugins
+apps/mobile/android/app/src/main/java/org/triliumnotes/trilium/
+ MainActivity.java # installs TriliumWebViewClient, edge-to-edge + insets, system bar appearance
+ TriliumWebViewClient.java # streaming same-origin HTTP proxy for the sync worker (Android only)
+apps/mobile/ios/App/App/ViewController.swift # keyboard handling: pins outer scroll, drives --tn-keyboard-gap
+apps/standalone/src/main.ts # boot: registers native HTTP handler if `Capacitor` in window; iOS interceptors
+apps/standalone/src/ios-interceptors.ts # fetch / XHR / <img> / stylesheet interceptors, iOS only
+apps/standalone/src/services/capacitor_http_handler.ts # NativeHttpHandler: Android proxy probe + CapacitorHttp fallback
+apps/standalone/src/local-bridge.ts # LOCAL_API_PREFIXES, localFetch(), registerNativeHttpHandler()
+apps/standalone/src/sw.ts # service worker routing (Android + web); guards for capacitor:// and the native proxy
+apps/client/src/services/utils.ts # isMobileApp() — running inside the native wrapper
+.github/workflows/mobile.yml, .github/actions/build-mobile # APK + iOS simulator builds, nightly signing
+```
+
+## Inbound: how the client's API calls reach the in-app worker
+
+The client's `/api`, `/sync`, `/bootstrap`, `/search` requests (`LOCAL_API_PREFIXES` in `local-bridge.ts`) must be answered by the worker. The two platforms do it differently because their WebViews resolve `*Scheme: "https"` differently:
+
+- **Android** — `androidScheme: "https"` works, the app runs at `https://localhost`, a real secure origin, so the **service worker** (`sw.ts`) intercepts those requests and forwards them to the worker — the same path as the web build.
+- **iOS** — the app runs at **`capacitor://localhost`**, and WebKit refuses to register a service worker on a non-HTTP(S) origin. `main.ts` therefore installs **in-page interceptors** (`installIosInterceptors()`, gated on `location.protocol === "capacitor:"`), one per way a request can leave the page: `window.fetch`, `XMLHttpRequest` (jQuery `$.ajax` never touches fetch), `<img src="api/images/…">` (the image loader issues its own requests) and CSS-initiated loads (`@font-face url()` in injected styles, custom themes via `<link href="api/…">`). Each rewrites a local-API request into `localFetch()`.
+
+Consequences that keep tripping people up:
+
+- **`iosScheme: "https"` is a no-op — do not re-add it.** Capacitor rejects it: `CAPInstanceDescriptor.normalize()` checks `WKWebView.handlesURLScheme(scheme) == false`, and WKWebView reserves `http`/`https`, so the scheme resets to `capacitor`. The config line only implies an https origin that never exists on iOS.
+- **Do not delete the iOS interceptor path as "dead code"**, and do not gate anything on "there is always a service worker". A reviewer assuming `iosScheme: https` ⇒ https origin will wrongly flag it.
+- A **new way for the page to issue a request** (a new element type loading `api/…`, a `new Worker` fetching, `EventSource`, `sendBeacon`) needs a fourth/fifth interceptor in `ios-interceptors.ts`, or it will silently 404 on iOS while working everywhere else. Test it in `ios-interceptors.spec.ts`.
+- `sw.ts` has a defensive `self.location.protocol === "capacitor:"` guard and must **let `/_trilium_native_http/` requests fall through** to the WebView (see below); keep both when editing its fetch handler.
+- Image blob URLs created by the interceptor are revoked (`5332cee3fb`); if you add another `URL.createObjectURL`, revoke it.
+
+## Outbound: how the worker syncs with a remote server
+
+A fetch from the app origin to a sync server is cross-origin, so CORS and cookie rules apply and large bodies cost bridge copies; instead `local-bridge.ts` exposes `registerNativeHttpHandler()`: when a handler is registered (only inside Capacitor — `main.ts` checks `"Capacitor" in window`), the worker's `BridgedRequestProvider` posts `HTTP_REQUEST` messages to the page and the handler does the real HTTP call. `capacitor_http_handler.ts` is that handler:
+
+- **Android** — probes `GET /_trilium_native_http/ping` once; if `TriliumWebViewClient` answers with the `x-trilium-native-http` marker, GET/HEAD requests go through the **streaming same-origin proxy** (`/_trilium_native_http/fetch?url=…`, request headers tunnelled as `x-trilium-h-<name>`, upstream `Set-Cookie` re-exposed as `x-trilium-set-cookie`, proxy failures → 502 + `x-trilium-proxy-error`). Answered from `WebViewClient.shouldInterceptRequest`, so the body streams into the page with no bridge envelope, no full-body Java string, no base64 — the plugin transport measured ~60 % of a core and ~2 MB/s during an initial sync. A failed probe is retried after 15 s because an old service worker can still own fetches right after an update.
+- **Everything else** (POSTs, binary responses, and all of iOS) uses the stock **`CapacitorHttp` plugin**, reached via the global `window.Capacitor.Plugins` — **not** `import "@capacitor/core"`, since bare specifiers don't resolve in the browser's native module loader.
+- Responses hand **parsed JSON through `data`** and only non-JSON through `body`; the handler must not `JSON.stringify` — the extra string copy OOM-ed the iOS worker on large blobs. Preserve that contract when touching either side.
+- iOS has no `shouldInterceptRequest` equivalent for https, so it stays on the plugin transport; the geo map's tile referer workaround (`apps/client/src/widgets/collections/geomap/map.tsx`) has the same limitation.
+
+## Native shells
+
+- **Android `MainActivity`**: sets `TriliumWebViewClient`, draws edge-to-edge with transparent system bars, forwards window insets to the WebView (so the client can pad for the status/navigation bars) and re-applies system bar appearance on configuration change. Nightly and debug builds get a distinct `applicationId` suffix (`.nightly`, `.debug`) and launcher icon so they install side by side (`android/app/build.gradle`).
+- **iOS `ViewController`**: the layout is `body { position: fixed; height: 100vh }` with an inner scrolling container, so WKWebView's reflexive scroll-to-focused-element would drag the toolbar off-screen; the controller pins the outer scroll offset while the keyboard animates and samples the keyboard's top edge every frame into the `--tn-keyboard-gap` CSS variable so the editor toolbar follows an interactive swipe-dismiss. `Keyboard.resize: "native"` in the config is part of the same contract. Change the keyboard/toolbar CSS on the client and this controller together.
+- `limitsNavigationsToAppBoundDomains: true` on iOS.
+
+## Client-side gating
+
+- `isMobileApp()` (`apps/client/src/services/utils.ts`) — `window.Capacitor?.isNativePlatform?.()`: true only inside the native wrapper. Distinct from `isMobile()`, which is the *layout* choice and is also true for a phone browser. Use the former for "there is a native shell" behaviour (e.g. setup flow), the latter for responsive UI. `window.Capacitor` is typed in `apps/client/src/types.d.ts`.
+- There is no Node, no server process and no `apps/server` code at runtime — anything the mobile app needs from "the backend" is core (`packages/trilium-core`), which is why core carries the no-Node-built-ins rules.
+
+## Building and running
+
+```bash
+pnpm --filter @triliumnext/mobile build # = standalone build → apps/standalone/dist
+pnpm --filter @triliumnext/mobile sync # build + `cap sync` (copies dist into android/ and ios/)
+pnpm --filter @triliumnext/mobile run:android # emulator/device (needs ANDROID_HOME, JDK 17+)
+pnpm --filter @triliumnext/mobile open:android # Android Studio
+pnpm --filter @triliumnext/mobile run:ios | open:ios # Xcode (macOS)
+```
+
+CI: `mobile.yml` (pull requests) builds a debug APK via `.github/actions/build-mobile` and an unsigned iOS **Simulator** `.app` on macOS; `nightly.yml` calls the same action with `nightly: "true"` for the signed `assembleRelease` build under the `.nightly` app id. Neither runs unit tests — those live in the standalone suite.
+
+## Testing
+
+Everything JS-side is under the standalone Vitest suite (happy-dom + sql.js):
+
+```bash
+pnpm --filter standalone test ios-interceptors # iOS interceptors
+pnpm --filter standalone test capacitor_http_handler # Android proxy probe / plugin fallback
+pnpm --filter standalone test sw # service-worker routing incl. capacitor:// guard
+pnpm --filter standalone test main # boot wiring (native handler registered, interceptors installed on capacitor:)
+```
+
+Simulate the platform in a spec by stubbing `location.protocol` / `window.Capacitor` (`getPlatform`, `isNativePlatform`, `Plugins.CapacitorHttp`) — see the existing specs for the fixtures. Native Java/Swift has no test harness in the repo; keep logic there minimal and mirror the protocol on the JS side where it is testable.
diff --git a/.claude/skills/developing-electron-desktop/SKILL.md b/.claude/skills/developing-electron-desktop/SKILL.md
new file mode 100644
index 0000000000..f54eb3d4a4
--- /dev/null
+++ b/.claude/skills/developing-electron-desktop/SKILL.md
@@ -0,0 +1,85 @@
+---
+name: developing-electron-desktop
+description: Use when working on the Trilium Electron desktop app (`apps/desktop`) — adding or changing an `electronApi` method / IPC channel, touching `preload.ts`, `main.ts`, `services/window.ts` or any main-process service (tray, printing, dialogs, import/export, spellcheck, autostart, security settings), the `trilium-app://` protocol, launching or debugging the desktop build, or writing tests for desktop code. Covers the process/security model, the four-file recipe for a new Electron API, running (`pnpm desktop:start`) and the known launch errors, and how desktop specs mock `electron`.
+---
+
+# Developing the Electron desktop app
+
+`apps/desktop` runs the **server and the client in one Electron process**: the main process boots `@triliumnext/core` + the Express app from `@triliumnext/server`, and the renderer is the ordinary `apps/client` bundle. There is no HTTP between them — see "How the renderer reaches the server" below. `apps/desktop/src/main.ts` is the entry point; `services/window.ts` creates windows and owns the window/spellcheck IPC.
+
+## Layout
+
+```
+apps/desktop/
+ src/main.ts # startup: platform provider, core init, Express app, windows, tray, IPC setup
+ src/preload.ts # the ONLY bridge renderer ↔ main (contextBridge → window.electronApi)
+ src/protocol.ts # trilium-app:// scheme → dispatch into Express in-process
+ src/ipc_messaging_provider.ts # replaces the WebSocket with ipcMain/webContents.send
+ src/platform_provider.ts # DesktopPlatformProvider (isElectron, getEnv, crash)
+ src/services/window.ts # BrowserWindow creation, webPreferences, window/spellcheck/nav IPC
+ src/services/*.ts # one module per concern: tray, printing, dialog, import, export,
+ # restore, shell, auto_launch, backup_passphrase, security_settings,
+ # custom_dictionary, onenote (+ loopback_oauth), referer, request,
+ # startup_metrics, web_contents_security
+ src/*.spec.ts, services/*.spec.ts # vitest, `pnpm --filter desktop test`
+ spec/build-checks/artifacts.spec.ts # verifies the built dist
+ e2e/ # Playwright against the built app (`pnpm --filter desktop e2e`)
+ scripts/build.ts # esbuild bundle + asset copy into dist/
+ electron-forge/ # packaging (forge.config.ts, icons, dmg, portable/safe-mode launchers)
+```
+
+## Process and security model
+
+- **`nodeIntegration: false`, `contextIsolation: true`, `webviewTag: true`** on every window (`services/window.ts`). The renderer has no Node, no `require("electron")`, no `@electron/remote` (removed — never reintroduce it). Everything crosses through the preload bridge.
+- **`web_contents_security.ts`** vets every `<webview>` in `will-attach-webview` and denies `window.open`, routing allow-listed URLs to the OS. If a new feature needs a popup or a webview privilege, change it there — never relax `webPreferences` at the call site.
+- **Main-process handlers validate their input** and never trust a path from the renderer: OS pickers run in the main process (`dialog.ts`, `import.ts`, `restore.ts`) and hand back a location the *user* chose; `import.ts` mints single-use access grants rather than accepting a path; `shell.ts` gates every channel with a validator that throws. Follow the same shape for anything that touches the filesystem or the OS.
+- **Secrets stay out of the DB where they must**: `security_settings.ts` reads `data_dir/security.json`, `backup_passphrase.ts` uses the OS keyring — the passphrase must not travel inside the backup it protects.
+- **`services/request.ts`** (`ElectronRequestProvider`) uses Electron's `net` so sync honours the system proxy; `referer.ts` keeps hosts that require an http(s) `Referer` working from the `trilium-app://` origin.
+
+## How the renderer reaches the server
+
+- The UI loads from **`trilium-app://app/`**, a privileged custom scheme (`protocol.ts`). `registerTriliumAppScheme()` **must run before `app.ready`** (Electron ignores `registerSchemesAsPrivileged` afterwards and navigation aborts with `(blocked:origin)`); `setupTriliumAppProtocol(expressAppPromise)` installs the handler that synthesises a Node request/response and dispatches through the real Express app — session, CSRF, multer and error middleware all run. Requests arriving before the server is built simply wait on the promise. `apps/server/src/services/electron_request.ts` tags them so auth/CSRF middleware can tell them from external TCP traffic. The same two functions are reused by `apps/edit-docs`.
+- **WebSocket is replaced by IPC**: `ipc_messaging_provider.ts` implements `MessagingProvider` over `webContents.send` / `ipcMain.on`, one client per `webContents.id`; the client side picks it up through `window.electronApi.ws` (`apps/client/src/services/ws.ts`). Don't open a TCP WebSocket from desktop code.
+- Window creation is gated on core init, not full server startup, so the renderer spins up while Express is still building (`coreInitializedPromise` / `expressAppPromise` in `main.ts`).
+
+## Adding an Electron API (renderer → main)
+
+Four files, always together:
+
+1. **Interface** — add the method to the right group interface in `packages/commons/src/lib/electron_api_interface.ts` (`ElectronWindowApi`, `ElectronShellApi`, `ElectronPrintingApi`, …; the groups are listed on `ElectronApi` at the bottom of the file, each with a one-line purpose). New concern → new `ElectronXxxApi` interface and a new key on `ElectronApi`. Doc-comment the method: the client only sees this file.
+2. **Preload** — implement it in `apps/desktop/src/preload.ts` inside the matching group of the `contextBridge.exposeInMainWorld("electronApi", { … } satisfies ElectronApi)` literal. `satisfies` makes the typecheck fail until preload matches the interface. Keep the preload thin: marshal arguments to `ipcRenderer.send` / `invoke` / `sendSync`; no logic.
+3. **Handler** — register the `ipcMain` handler in the service module that owns the concern (`services/shell.ts`, `services/printing.ts`, …, each with a `setupXxxHandlers()` called from `main.ts`), or in `setupWindowing()` in `services/window.ts` for window/spellcheck/navigation. Channel names are kebab-case verbs (`open-external`, `set-full-screen`, `backup-passphrase-set`). Pick the IPC style by shape:
+ - `ipcMain.on(channel, handler)` — fire-and-forget (`ipcRenderer.send`);
+ - `ipcMain.handle(channel, handler)` — async request/response (`ipcRenderer.invoke`);
+ - `ipcMain.on` + `event.returnValue = …` — synchronous query (`ipcRenderer.sendSync`); use sparingly, it blocks the renderer.
+ Main → renderer events go the other way: `webContents.send(channel, …)` in main, an `ipcRenderer.on` subscription exposed as `onXxx(callback)` in preload.
+4. **Tests** — `apps/desktop/src/preload.spec.ts` (asserts the exposed API shape and that each method sends/invokes the right channel; extend the `exposedApi` assertions) and the owning service's `*.spec.ts` for the handler.
+
+Then call it from the client as `window.electronApi?.group.method()` — always optional-chained, since the same client runs in the browser. `window.electronApi` is declared in `apps/client/src/types.d.ts`; gate desktop-only UI on `isElectron()` from `apps/client/src/services/utils.ts` (server side: `utils.isElectron`).
+
+## Strings and platform code
+
+- Main-process user-facing text (tray menu, dialogs, error boxes) goes through `import { t } from "i18next"` with keys in `apps/server/src/assets/translations/en/server.json`. Never hardcode.
+- Platform checks in main use `process.platform`; code shared with core uses `isElectron()`/`isMac()`/`isWindows()` from `@triliumnext/core` utils (functions, only after `initializeCore()`).
+- The preload is compiled to **CJS** (`src/preload.compiled.cjs`, gitignored) — dev by `scripts/electron-start.mts`, prod by `apps/desktop/scripts/build.ts` — because Electron's sandboxed renderer can only load CJS preloads. Don't import ESM-only things into `preload.ts`.
+
+## Running
+
+| Command | What it does |
+|---|---|
+| `pnpm desktop:start` | dev app on port 37743, data in `apps/desktop/data`, Electron profile in `data-electron-37742`; HTTP cache disabled in dev so stale prod assets don't shadow fresh output |
+| `pnpm desktop:start-prod` | `build` + run `dist/` like a release (port 37841, separate data dirs) |
+| `pnpm --filter desktop electron-forge:make` / `:package` | full installers / unpacked app |
+| `pnpm --filter desktop e2e` | Playwright against `dist/main.cjs` (builds first) |
+
+Known launch-time noise and failures — do not "fix" these in app code:
+
+- **`TypeError: Cannot read properties of undefined (reading 'commandLine')`** from `main.ts` (`app.commandLine.appendSwitch(...)`) can appear in the console of Electron-based launches (`desktop:start`, `edit-docs:edit-docs`). The app runs correctly; ignore it unless the user raises it as a bug.
+- **`TypeError: Not running in an Electron environment!`** (from `electron-is-dev`) at startup means the shell inherited **`ELECTRON_RUN_AS_NODE=1`** — common inside VS Code's extension host and AI coding agents. `require("electron")` then resolves to the npm stub's path string. Unset it before launching: `unset ELECTRON_RUN_AS_NODE` (bash/zsh) or `Remove-Item Env:ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue` (PowerShell).
+- **Linux**: `gtk-version=3` and `GlobalShortcutsPortal` switches in `main.ts` are deliberate workarounds (Electron GTK 4 crash; Flatpak/Wayland global shortcuts).
+
+## Testing desktop code
+
+- `pnpm --filter desktop test [pattern]` — Vitest, node environment, `src/**/*.spec.ts`. Specs `vi.mock("electron", …)` and assert on the recorded `ipcMain`/`ipcRenderer` calls (see `preload.spec.ts`, `services/shell.spec.ts` for the pattern). `vitest.config.mts` sets `ELECTRON_OVERRIDE_DIST_PATH` so a dynamic `import("electron")` doesn't blow up where the binary isn't installed — don't remove it.
+- The desktop suite also boots server pieces (`TRILIUM_INTEGRATION_TEST: "memory"`), so it is slower than a client spec; keep the pattern narrow.
+- `spec/build-checks/artifacts.spec.ts` asserts the contents of a built `dist/` (client, assets, `better-sqlite3`, …). It is outside the default `include`, so run it explicitly after `pnpm desktop:build` when touching `scripts/build.ts` or the asset copies (`schema.sql`, `llm/skills`, `share-theme/templates`).
diff --git a/CLAUDE.md b/CLAUDE.md
index 9d0ea7faa1..e3dabedca8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -168,13 +168,8 @@ Shared components live in `apps/client/src/widgets/react/` — **always** reuse
- **Barrel import caution** — `import { x } from "@triliumnext/core"` loads ALL core exports. Early-loading modules like `config.ts` should import specific subpaths (e.g. `@triliumnext/core/src/services/utils/index`) to avoid circular dependencies or initialization ordering issues
- **Electron custom protocol** — In desktop mode, the renderer loads the UI and makes API calls via the `trilium-app://` custom protocol (not HTTP). `apps/desktop/src/protocol.ts` dispatches these requests into the Express app running in the main process; the dispatcher tags them via `apps/server/src/services/electron_request.ts` so auth/CSRF middleware can distinguish them from external TCP traffic
-### Mobile (Capacitor) request routing — Android vs iOS
-
-The mobile app (`apps/mobile/`) wraps the standalone WASM stack in a Capacitor WebView. There is no network backend; the client's API/sync calls (`/api`, `/sync`, `/bootstrap`, `/search`) reach the in-process worker via **two platform-specific request paths**:
-- **Android**: `androidScheme: "https"` works → the app runs at `https://localhost` → the **service worker** (`apps/standalone/src/sw.ts`) routes those requests to the worker.
-- **iOS**: the app runs at **`capacitor://localhost`**, where service workers cannot register, so `apps/standalone/src/main.ts` installs **fetch/XHR/image interceptors** (gated on `location.protocol === "capacitor:"`) instead.
-
-**`iosScheme: "https"` is a no-op on iOS and must not be re-added.** Capacitor rejects it — `CAPInstanceDescriptor.normalize()` checks `WKWebView.handlesURLScheme(scheme) == false`, and WKWebView reserves `http`/`https`, so the scheme is reset to the default `capacitor`. The config line only misleads (it implies an https origin that never exists on iOS). **Do not delete the iOS interceptor path as "dead code"** — it is the only working request path on iOS; a code reviewer assuming `iosScheme:https` ⇒ https origin will wrongly flag it.
+### Mobile (Capacitor) app
+`apps/mobile` wraps the standalone WASM build in a Capacitor WebView — no network backend. Android runs at `https://localhost` and routes API calls through the service worker; iOS runs at `capacitor://localhost`, where no service worker can register, so `apps/standalone/src/ios-interceptors.ts` stands in. **`iosScheme: "https"` is a no-op and must not be re-added, and the iOS interceptor path is not dead code.** Load the **`developing-capacitor-mobile` skill** before touching `apps/mobile`, `ios-interceptors.ts`, `capacitor_http_handler.ts` or the `capacitor:` branches of `sw.ts`/`main.ts`.
### Binary Utilities
@@ -240,17 +235,7 @@ Rules specific to this mechanism:
- There is no `config.translate` bridge and no `lang/*.po` catalogs any more — both were removed. Any doc or plugin still describing them is stale.
### Electron Desktop App
-- Desktop entry point: `apps/desktop/src/main.ts`, window management: `apps/desktop/src/services/window.ts`
-- **Security**: `nodeIntegration` is **disabled** and `contextIsolation` is **enabled**. The renderer has no access to Node.js APIs or Electron internals.
-- **Preload script** (`apps/desktop/src/preload.ts`): Uses `contextBridge.exposeInMainWorld("electronApi", ...)` to expose a whitelisted API to the renderer. Compiled to CJS via esbuild (dev: `scripts/electron-start.mts`, prod: `apps/desktop/scripts/build.ts`).
-- **ElectronApi interface** (`packages/commons/src/lib/electron_api_interface.ts`): Shared type definition used by both the preload script (`satisfies ElectronApi`) and the client (`window.electronApi`). Grouped into sub-objects: `window`, `clipboard`, `shell`, `contextMenu`, `spellcheck`, `tray`, `printing`, `navigation`.
-- **Client-side access**: Use `window.electronApi?.group.method()` — never use `require("electron")` or `dynamicRequire()` in client code.
-- **Adding new Electron APIs**: Add the method to the interface in commons, implement it in `preload.ts`, add the IPC handler in `apps/desktop/src/services/window.ts`, and add a test in `apps/desktop/spec/preload.spec.ts`.
-- **IPC handlers**: Use `electron.ipcMain.on(channel, handler)` for fire-and-forget, `electron.ipcMain.handle(channel, handler)` for async request/response, `ipcMain.on` + `event.returnValue` for synchronous queries.
-- Electron-only features should check `isElectron()` from `apps/client/src/services/utils.ts` (client) or `utils.isElectron` (server)
-- **`@electron/remote` is removed** — do not use it. All renderer↔main communication goes through the preload bridge.
-- **Spurious `electron.app is undefined` error** — when running Electron-based apps (`pnpm desktop:start`, `pnpm edit-docs:edit-docs`, etc.), the console may print `TypeError: Cannot read properties of undefined (reading 'commandLine')` from `apps/desktop/src/main.ts` (the `app.commandLine.appendSwitch("disable-http-cache")` line). This is **not a real failure** — the app runs correctly. Do not try to fix it, guard it, or investigate electron initialization order unless the user explicitly raises it as a bug.
-- **`ELECTRON_RUN_AS_NODE` leak crashes Electron launches** — shells spawned by Electron-based tools (the VS Code extension host, AI coding agents running inside it) often inherit `ELECTRON_RUN_AS_NODE=1`. With it set, launching the desktop app (`pnpm desktop:start`, `pnpm --filter desktop start-prod`, `electron dist`) crashes at startup with `TypeError: Not running in an Electron environment!` (thrown by `electron-is-dev`, because `require("electron")` resolves to the npm stub's path string instead of the built-in module). This is an environment problem, not an app bug — unset the variable before launching: `Remove-Item Env:ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue` (PowerShell) or `unset ELECTRON_RUN_AS_NODE` (bash).
+`apps/desktop` runs server + client in one Electron process; the renderer loads over the `trilium-app://` custom protocol and talks to main only through the preload bridge (`window.electronApi`, typed by `packages/commons/src/lib/electron_api_interface.ts`). `nodeIntegration` is off, `contextIsolation` is on, `@electron/remote` is gone — never `require("electron")` in client code. Adding an API means interface + `preload.ts` + an `ipcMain` handler in the owning service + a spec. Load the **`developing-electron-desktop` skill** for the recipe, the security model, running/launch errors and testing.
### Attribute Inheritance