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
chore(skills): add IPC wiring detail and protocol triage to developing-electron-desktop
Elian Doranbc202bf968bb
diff --git a/.claude/skills/developing-electron-desktop/SKILL.md b/.claude/skills/developing-electron-desktop/SKILL.mdindex f54eb3d4a4..72edfdc81e 100644--- a/.claude/skills/developing-electron-desktop/SKILL.md+++ b/.claude/skills/developing-electron-desktop/SKILL.md@@ -1,6 +1,6 @@---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`.+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 (plus the handler-module map, the send/sendSync/invoke transport table, ipcMain crash-safety and the shell input validators), a runnable ipc-parity checker, triage for `trilium-app://` protocol and WebContents failures (STATUS_BREAKPOINT, (blocked:origin), non-streaming SSE, blocked webview/permission), running (`pnpm desktop:start`) and the known launch errors, and how desktop specs mock `electron`.---# Developing the Electron desktop app@@ -57,6 +57,77 @@ Four files, always together: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`).+### A new handler module is dead until `main.ts` calls its `setupX()`++`ipcMain.on`/`handle` only registers when the module's setup function actually runs, and there is **no startup error** if you forget. The symptom is silent at the source: a `send` channel no-ops, and a `sendSync` channel **hangs the renderer forever**, because synchronous IPC blocks the whole renderer process waiting for a reply that never comes. The setup calls live in one block in `main.ts` (plus `ipcMessaging.init()` further down). Adding a module means adding the call there.++### Which module owns my channel?++The preload API *group* name does not map 1:1 to a handler module — infer from this table, not from the group:++| setup fn (called in `main.ts`) | module | channels it owns |+|---|---|---|+| `setupWindowing()` | `services/window.ts` | the bulk (~31): window lifecycle, zoom, theme, title bar, full-screen, min/max, dev tools, background material, `navigation-history*`, **clipboard** (`copy-image-to-clipboard`, `read-clipboard-text`), **spellchecker language** channels, `web-contents-action` |+| `setupShellHandlers()` | `services/shell.ts` | `open-external`, `open-path`, `show-item-in-folder`, `open-file-url`, `download-url`, `open-custom` |+| `setupPrintingHandlers()` | `services/printing.ts` | `print-note`, `export-as-pdf`, `export-as-pdf-preview`, `save-pdf`, `get-printers`, `print-from-preview`, `print-progress` |+| `registerSecurityIpcHandlers()` | `services/security_settings.ts` | `security-set-backend-scripting`, `security-set-sql-console`, `security-set-lan-access` (all three via `registerToggleHandler`) |+| `setupStartupMetricsIpc()` | `services/startup_metrics.ts` | `report-startup-metric` |+| `setupSystemTray()` | `services/tray.ts` | `reload-tray` |+| `setupCustomDictionary()` | `services/custom_dictionary.ts` | `add-word-to-dictionary` |+| `ipcMessaging.init()` | `ipc_messaging_provider.ts` | `trilium-ws-from-renderer` (the ws bridge; the channel names are the `IPC_FROM_RENDERER`/`IPC_TO_RENDERER` constants) |++Note the splits that defeat guessing by group: spellcheck's `add-word-to-dictionary` is in **custom_dictionary.ts** while the spellchecker-language channels are in **window.ts**, and the **clipboard** handlers live in **window.ts**, not a clipboard module.++### Transport must match the handler kind++Mismatch it and the failure is silent or fatal, never a clear error:++| Renderer need | preload call | main side | if mismatched |+|---|---|---|---|+| fire-and-forget, no return | `ipcRenderer.send(ch, …)` | `ipcMain.on(ch, (event, …) => {})` | sending to a `handle`-only channel is a **silent no-op** |+| synchronous value (**blocks renderer**) | `ipcRenderer.sendSync(ch, arg)` | `ipcMain.on(ch, (event) => { event.returnValue = x })` | forgetting `event.returnValue` **hangs the renderer** |+| async value (Promise) | `ipcRenderer.invoke(ch, …)` | `ipcMain.handle(ch, async (event, …) => x)` | no `handle` registered ⇒ the promise rejects `"No handler registered for '<ch>'"` |+| main → renderer push | `ipcRenderer.on(ch, cb)` + an unsubscribe | `webContents.send(ch, data)` (**not** `ipcMain`) | push channels have **no** `ipcMain` handler — don't "fix" their absence |++**Multiplexed channel:** `navigation-history` is one channel serving several preload methods via a method-name first argument and an `event.returnValue` switch.++### Crash-safety++An unhandled throw inside an `ipcMain.on` listener crashes the **entire main process** — there is no renderer-side rejection to catch it. `shell.ts` carries this warning verbatim next to `open-custom`. Wrap every handler body:++```ts+electron.ipcMain.on("my-channel", (_event, arg: string) => {+ try {+ doThing(validateArg(arg));+ } catch (e) {+ getLog().error(`my-channel failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);+ }+});+```++For an `ipcMain.handle` whose contract is `Promise<string>`, the catch should also **return** the error string, since the renderer awaits it — that is what `open-path`/`open-file-url` do.++### Check the wiring with `ipc-parity.mjs`++A direction-aware parity diff across interface ↔ preload ↔ `ipcMain` handlers ↔ spec. Run it after wiring a channel, or to audit drift:++```bash+node .claude/skills/developing-electron-desktop/scripts/ipc-parity.mjs+```++It reports renderer→main channels with no handler (these hang or no-op), transport/handler-kind mismatches, handler modules whose `setupX()` is never called, handlers with no preload caller (`print-note`/`export-as-pdf` are known legacy orphans), and preload channels with no `preload.spec.ts` assertion. It whitelists push-only channels and is channel-granular, so the multiplexed `navigation-history` doesn't false-positive. Exit code 1 on a fatal finding.++## Validating untrusted renderer input++The renderer is XSS-reachable, so it is **untrusted**. Every fs/shell/url channel validates in the main process and throws on violation. The five validators in `apps/desktop/src/services/shell.ts` are exported and unit-tested:++- `validateOpenExternalUrl` — scheme allowlist from `SHELL_OPEN_EXTERNAL_PROTOCOLS` (commons); blocks Follina (`ms-msdt:`/`search-ms:`), the `smb:`/`ldap:` NTLM leak, and `file:`/`data:`/`jar:`.+- `validateOpenPath` / `validateOpenCustomPath` — canonicalize and sandbox to the data dir / tmp dir; implicitly blocks UNC paths and traversal; reject null bytes and nonexistent files.+- `validateOpenFileUrl` — require `file:` with an empty hostname (blocks the `file://attacker/share` UNC NTLM leak); normalize `file://C:/` → `file:///C:/`.+- `validateDownloadUrl` — same-origin lock by scheme + hostname + port. It cannot use `URL.origin`, because the custom scheme is opaque-origin (`"null"`).++Add a validator for any new channel that takes a path, a URL, or anything else the main process will act on.+## 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.@@ -83,3 +154,16 @@ Known launch-time noise and failures — do not "fix" these in app 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`).++## Debugging the protocol / WebContents boundary++When the symptom isn't a missing channel but the renderer page itself failing — white screen, `STATUS_BREAKPOINT`, `(blocked:origin)`, SSE that never streams, a blocked `<webview>`, a denied permission — the cause is `protocol.ts` or `web_contents_security.ts`, not the IPC bridge. Symptom → cause → fix table: [references/protocol-and-security-triage.md](references/protocol-and-security-triage.md).++## Reference map++| File | What it covers |+|---|---|+| [references/protocol-and-security-triage.md](references/protocol-and-security-triage.md) | `trilium-app://` and the WebContents boundary: `STRIPPED_HEADERS`/STATUS_BREAKPOINT, the privileged-scheme registration ordering, the SSE streaming bridge, the frame-origin guard and its trust model, `<webview>` attach hardening, the permission allowlist, window-open and navigation policy, the YouTube embed referer. |+| [scripts/ipc-parity.mjs](scripts/ipc-parity.mjs) | Runnable parity check across interface ↔ preload ↔ handlers ↔ spec (see above). |++Related skills: **writing-unit-tests** (the `vi.mock("electron")` pattern these specs use), **building-client-ui** (the renderer side that calls `window.electronApi`), **developing-capacitor-mobile** (the other non-browser runtime).diff --git a/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.md b/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.mdnew file mode 100644index 0000000000..a60b00937f--- /dev/null+++ b/.claude/skills/developing-electron-desktop/references/protocol-and-security-triage.md@@ -0,0 +1,35 @@+# `trilium-app://` protocol + WebContents security triage++When the failure isn't a missing IPC channel but the **renderer page itself** misbehaving (white screen, crash, blocked request, non-streaming SSE, a rejected `<webview>` / permission / download), the cause is one of two files:++- [`apps/desktop/src/protocol.ts`](../../../../apps/desktop/src/protocol.ts) — registers the privileged `trilium-app://` scheme and bridges renderer Fetch requests into the in-process Express app.+- [`apps/desktop/src/services/web_contents_security.ts`](../../../../apps/desktop/src/services/web_contents_security.ts) — the per-WebContents security policy (webview attach, window-open, navigation, permissions).++In packaged Electron the renderer loads the **entire** UI from `trilium-app://app/` — every page load, bootstrap, API call, and asset arrives at `protocol.handle` as a Web Fetch `Request` and is dispatched through the real Express stack (session, CSRF, body-parser, multer, error middleware). It is **not** HTTP, which is why HTTP-shaped headers and origins break in surprising ways.++## Symptom → cause → fix++| Symptom | Cause | File / fix |+|---|---|---|+| Renderer aborts with **`STATUS_BREAKPOINT`** (often a white screen on launch) | An http-only / HSTS / COOP / CORP / origin-agent-cluster header leaked onto the `trilium-app://` response. Those headers run during renderer-process setup and trip internal Chromium asserts when the scheme isn't http(s). | Add the header name to `STRIPPED_HEADERS` (`protocol.ts:485`). `normalizeResponseHeaders` (`protocol.ts:500`) drops everything in that set before building the Fetch `Response`. The rationale comment sits just above the set. |+| Navigation aborts with **`(blocked:origin)`** | `registerSchemesAsPrivileged` did not run **synchronously before `app.ready`**, so Chromium treats the scheme as non-standard with an opaque origin. | `registerTriliumAppScheme()` (`protocol.ts:26`) must be called at the very top of `main()` (it is, at the top of `main()`) — before any `await`. The "must be called before `app.ready`" note is in its docstring (its docstring); privileges set: `standard`, `secure`, `supportFetchAPI`, `corsEnabled`, `codeCache`. |+| **SSE / LLM chat stream buffers** until the request ends (no incremental tokens) | The handler never called `res.flushHeaders()`, or the streaming bridge shim is missing/broken. Non-streaming handlers resolve via the buffered `res.on("end")` path; only `flushHeaders()` commits a `ReadableStream` body. | `installStreamingBridge` (`protocol.ts:284`) maps `res.flushHeaders()` → `commit()`, which resolves the Fetch `Response` with a `ReadableStream` and forwards later `res.write(chunk)` into the controller. The handler must call `flushHeaders()` to opt in. The bridge also shims `res.flush` to a no-op to avoid an Express prototype-swap crash (in the same bridge). |+| API call from an **iframe** returns **403** / is cancelled | The frame-origin guard rejected the request: a non-`mainFrame` request whose frame chain contains a non-app (foreign) frame is denied **before** the protocol handler runs. | `installFrameOriginGuard` (`protocol.ts:120`) registers a `webRequest.onBeforeRequest` filter; the pure policy is `isRequestorChainTrusted(resourceType, frameUrls)` (`protocol.ts:143`) — `mainFrame` always allowed; otherwise every committed frame must be the app shell or `devtools:`. A second, weaker check `isDispatchOriginAllowed` (`protocol.ts:173`) 403s any request that *positively* attests a foreign `Origin` (only navigation-style requests carry one). |+| **`<webview>` won't attach** / log shows `Blocked <webview> attach requesting [...]` | The attach requested a banned capability (`preload`, `nodeIntegration`, `nodeIntegrationInSubFrames`, `webSecurity:false`, `allowRunningInsecureContent`) or the wrong/empty session partition. | `hardenWebviewPreferences` (`web_contents_security.ts:79`), called from the `will-attach-webview` hook (`:50`), returns the violation list; a non-empty list `preventDefault()`s the attach. The partition **must** exactly equal `WEBVIEW_SESSION_PARTITION` (`"persist:webview"`) — an unset/empty/different partition is a violation (`:111-115`). The legit Web View note always declares it. |+| **Permission denied** (camera, mic, geolocation, clipboard-read, notifications from a remote embed, …) | Not in `PERMISSION_ALLOWLIST` for that session kind, or the request origin isn't the app shell. Unset handlers would GRANT everything, so deny-by-default is enforced explicitly. | `PERMISSION_ALLOWLIST` (`web_contents_security.ts:150`): `app` = `clipboard-sanitized-write`, `fullscreen`, `notifications`; `guest` = `fullscreen` only. `isPermissionAllowedForOrigin` (`:176`) additionally requires the request to come from `trilium-app://app` (except `fullscreen`, allowed for any origin). Installed on both the default and `WEBVIEW_SESSION_PARTITION` sessions (`:63-66`). |+| `window.open` / `target=_blank` does nothing, or a note link opens in the OS browser | By design: every window-open is denied; for app windows the URL is re-validated through the same scheme allowlist and routed to the OS browser. | `installWindowOpenPolicy` (`web_contents_security.ts:218`) reuses `validateOpenExternalUrl` from `shell.ts`, so a note-content link can't bypass the Follina/`smb:` allowlist. `<webview>` guests are denied outright (no external dispatch). |+| A link/drag navigates an **app window away from Trilium** and gets blocked | The navigation guard only allows the app shell root. | `isNavigationAllowed(targetUrl)` (`web_contents_security.ts:199`): allowed only for `trilium-app:` + the app host at root path (`/`, `/?`, or empty). `<webview>` guests are exempt (they're embedded browsers). The old `localhost` carve-out was removed as dangerous. |+| YouTube embed shows "video player configuration error" | On desktop the renderer origin is `trilium-app://app` (not http(s)), so the embed request goes out with no `Referer`. | `installYouTubeEmbedReferer` (`web_contents_security.ts:293`) injects `Referer: https://triliumnotes.org/` (a non-youtube.com origin) for the embed hosts, never overwriting an existing header. |++## Trust model, in one paragraph++Chromium stamps **no** reliable identifying headers on requests to a privileged custom scheme (`protocol.ts:79-95` documents this empirically for Electron 41): same-origin renderer requests carry no `Origin`, foreign `fetch()` calls *also* carry none, and `corsEnabled` isn't enforced for reads. The only forgeable-proof signal is the **requesting frame chain**, which is main-process-side state (`details.frame` + `.parent`). So the real gate is `installFrameOriginGuard` (frame-chain trust), with `isDispatchOriginAllowed` as a weaker backstop for the rare navigation-style request that does carry an `Origin`. `<webview>` guests are out of scope by construction — they live in `WEBVIEW_SESSION_PARTITION`, where the `trilium-app://` handler is never registered.++## Tests++Both files expose their policy as **pure exported functions** for unit testing without spinning up Electron:++- `protocol.ts`: `isRequestorChainTrusted`, `isDispatchOriginAllowed`, plus `dispatch` exercised via `node-mocks-http`.+- `web_contents_security.ts`: `hardenWebviewPreferences`, `isPermissionAllowed`, `isPermissionAllowedForOrigin`, `isNavigationAllowed`, `withYouTubeEmbedReferer`.++Run with `pnpm --filter desktop test` (e.g. `apps/desktop/src/services/web_contents_security.spec.ts`). See the **writing-unit-tests** skill for the `vi.mock("electron")` pattern.diff --git a/.claude/skills/developing-electron-desktop/scripts/ipc-parity.mjs b/.claude/skills/developing-electron-desktop/scripts/ipc-parity.mjsnew file mode 100644index 0000000000..ab3336d47f--- /dev/null+++ b/.claude/skills/developing-electron-desktop/scripts/ipc-parity.mjs@@ -0,0 +1,277 @@+#!/usr/bin/env node+// Direction-aware IPC parity checker for Trilium's Electron contextBridge.+//+// The desktop bridge has four moving parts that must stay in sync:+// 1. preload.ts — ipcRenderer.send / sendSync / invoke (renderer→main)+// and ipcRenderer.on (main→renderer push).+// 2. handler modules — ipcMain.on / ipcMain.handle (the main-process side).+// 3. main.ts — must call each module's setupX() or the handlers+// never register (the #1 footgun: dead until wired).+// 4. preload.spec.ts — asserts the exact {channel,args} each method emits.+//+// This script diffs them and reports four classes of drift:+// (a) renderer→main channel in preload with NO ipcMain handler+// → send no-ops; sendSync HANGS the renderer; invoke rejects. (exit 1)+// (b) transport/handler-kind mismatch (send/sendSync↔on, invoke↔handle). (exit 1)+// (c) ipcMain handler with NO preload caller (dead / legacy). Advisory.+// (d) preload channel with NO preload.spec.ts assertion (untested). Advisory.+// (e) handler module whose setupX() is never called from main.ts+// → every channel it owns is dead. (exit 1)+//+// It is channel-granular (the multiplexed `navigation-history` collapses to one+// channel, avoiding false positives) and whitelists push-only channels in (a).+//+// Usage:+// node .claude/skills/developing-electron-desktop/scripts/ipc-parity.mjs [--root <dir>] [--json]++import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++// ipcMain handlers that have no preload caller and are known legacy (replaced by+// the preview-based print flow). Reported but not alarming.+const KNOWN_ORPHAN_HANDLERS = new Set(["print-note", "export-as-pdf"]);++const __dirname = dirname(fileURLToPath(import.meta.url));++function findRepoRoot() {+ const argRoot = argValue("--root");+ if (argRoot) return resolve(argRoot);+ // scripts → developing-electron-desktop → skills → .claude → repo root+ const computed = resolve(__dirname, "..", "..", "..", "..");+ if (existsSync(join(computed, "apps", "desktop", "src", "preload.ts"))) return computed;+ return process.cwd();+}++function argValue(flag) {+ const i = process.argv.indexOf(flag);+ return i >= 0 ? process.argv[i + 1] : null;+}++function read(path) {+ return existsSync(path) ? readFileSync(path, "utf8") : "";+}++/** Recursively list *.ts files under `dir`, excluding *.spec.ts. */+function listSourceFiles(dir) {+ const out = [];+ for (const entry of readdirSync(dir)) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) {+ out.push(...listSourceFiles(full));+ } else if (entry.endsWith(".ts") && !entry.endsWith(".spec.ts") && !entry.endsWith(".d.ts")) {+ out.push(full);+ }+ }+ return out;+}++/** All matches of `re` (must have one capture group) as an array of {value, ...extra}. */+function matchAll(text, re, map) {+ const out = [];+ let m;+ while ((m = re.exec(text)) !== null) {+ out.push(map(m));+ }+ return out;+}++function main() {+ const root = findRepoRoot();+ const desktopSrc = join(root, "apps", "desktop", "src");+ const preloadPath = join(desktopSrc, "preload.ts");+ const specPath = join(desktopSrc, "preload.spec.ts");+ const mainPath = join(desktopSrc, "main.ts");++ if (!existsSync(preloadPath)) {+ console.error(`Could not find ${preloadPath}. Pass --root <repo-root>.`);+ process.exit(2);+ }++ const preloadText = read(preloadPath);+ const specText = read(specPath);+ const mainText = read(mainPath);++ // --- preload: renderer→main channels (transport-aware) and push channels ---+ const r2m = new Map(); // channel -> Set<transport>+ for (const { ch, transport } of matchAll(+ preloadText,+ /ipcRenderer\.(send|sendSync|invoke)\(\s*["'`]([^"'`]+)["'`]/g,+ (m) => ({ transport: m[1], ch: m[2] })+ )) {+ if (!r2m.has(ch)) r2m.set(ch, new Set());+ r2m.get(ch).add(transport);+ }+ const pushChannels = new Set(+ matchAll(+ preloadText,+ /ipcRenderer\.(on|removeAllListeners|removeListener)\(\s*["'`]([^"'`]+)["'`]/g,+ (m) => m[2]+ )+ );++ // --- handler modules: ipcMain.on / handle, mapped channel -> {kind, file} ---+ // ipcMain is the AUTHORITATIVE kind map (string literals + same-file const+ // channels like `const IPC_FROM_RENDERER = "..."`). `handled` is a looser+ // set used only for the "missing handler" check: it adds the literals of+ // any module that registers a channel via INDIRECTION (an identifier/param+ // first arg, e.g. security_settings' `ipcMain.handle(channel, ...)`), so+ // those don't false-positive. Normal literal-only modules stay strict.+ const ipcMain = new Map(); // channel -> { kind, file }+ const handled = new Set(); // channels we have evidence are handled main-side+ const handlerFiles = listSourceFiles(desktopSrc).filter((f) => f !== preloadPath);+ for (const file of handlerFiles) {+ const text = read(file);+ const rel = file.slice(root.length + 1);+ const constMap = new Map(+ matchAll(text, /const\s+([A-Za-z_$][\w$]*)\s*=\s*["'`]([^"'`]+)["'`]/g, (m) => [m[1], m[2]])+ );+ // First definition wins; transient re-registrations don't override.+ const define = (ch, kind) => {+ handled.add(ch);+ if (!ipcMain.has(ch)) ipcMain.set(ch, { kind, file: rel });+ };+ for (const { ch, kind } of matchAll(+ text,+ /ipcMain\.(on|handle)\(\s*["'`]([^"'`]+)["'`]/g,+ (m) => ({ kind: m[1], ch: m[2] })+ )) {+ define(ch, kind);+ }+ let hasIndirection = false;+ for (const { ident, kind } of matchAll(+ text,+ /ipcMain\.(on|handle)\(\s*([A-Za-z_$][\w$]*)/g,+ (m) => ({ kind: m[1], ident: m[2] })+ )) {+ hasIndirection = true;+ const lit = constMap.get(ident);+ if (lit) define(lit, kind);+ }+ // A module that registers a channel via a non-literal first arg may name+ // its channels in helper-call literals; trust this file's literals.+ if (hasIndirection) {+ for (const lit of constMap.values()) handled.add(lit);+ for (const lit of matchAll(text, /["'`]([a-z][a-z0-9-]+)["'`]/g, (m) => m[1])) handled.add(lit);+ }+ }++ // --- spec: every channel the spec references in any form ---+ const specChannels = new Set([+ ...matchAll(specText, /channel:\s*["'`]([^"'`]+)["'`]/g, (m) => m[1]),+ ...matchAll(specText, /ipcRendererSyncResults\.set\(\s*["'`]([^"'`:]+):/g, (m) => m[1]),+ ...matchAll(specText, /ipcRendererListeners\.(?:get|has)\(\s*["'`]([^"'`]+)["'`]/g, (m) => m[1])+ ]);++ // --- (e) module registration in main.ts ---+ // Only modules that actually own an ipcMain handler need a setupX() in+ // main.ts. setupWebContentsSecurity (no ipcMain handlers; called+ // transitively by setupWindowing) is correctly excluded.+ const setupFns = new Set();+ for (const file of handlerFiles) {+ const text = read(file);+ if (!/ipcMain\.(on|handle)\(/.test(text)) continue;+ for (const fn of matchAll(+ text,+ /export\s+(?:async\s+)?function\s+((?:setup|register)\w+)\s*\(/g,+ (m) => m[1]+ )) {+ setupFns.add(JSON.stringify({ fn, file: file.slice(root.length + 1) }));+ }+ }++ // --- compute findings ---+ const findings = { missingHandler: [], mismatch: [], deadHandler: [], untested: [], unregistered: [] };++ for (const [ch, transports] of r2m) {+ if (!handled.has(ch)) {+ if (pushChannels.has(ch)) continue; // also a push channel; tolerate+ findings.missingHandler.push({ ch, transports: [...transports] });+ continue;+ }+ const handler = ipcMain.get(ch);+ if (!handler) continue; // handled via indirection; kind not resolvable+ for (const t of transports) {+ const expected = t === "invoke" ? "handle" : "on";+ if (handler.kind !== expected) {+ findings.mismatch.push({ ch, transport: t, expected, got: handler.kind });+ }+ }+ }++ for (const [ch, info] of ipcMain) {+ if (!r2m.has(ch)) {+ findings.deadHandler.push({ ch, file: info.file, known: KNOWN_ORPHAN_HANDLERS.has(ch) });+ }+ }++ for (const ch of [...r2m.keys(), ...pushChannels]) {+ if (!specChannels.has(ch)) findings.untested.push(ch);+ }++ for (const entry of setupFns) {+ const { fn, file } = JSON.parse(entry);+ if (!new RegExp(`\\b${fn}\\s*\\(`).test(mainText)) {+ findings.unregistered.push({ fn, file });+ }+ }+ // The ws provider registers via a class method, not an exported setup fn.+ if (ipcMain.has("trilium-ws-from-renderer") && !/ipcMessaging\.init\s*\(/.test(mainText)) {+ findings.unregistered.push({ fn: "ipcMessaging.init", file: "apps/desktop/src/ipc_messaging_provider.ts" });+ }++ if (process.argv.includes("--json")) {+ console.log(JSON.stringify({ root, counts: countOf(findings), findings }, null, 2));+ } else {+ report(findings, { r2m, ipcMain, pushChannels });+ }++ const fatal = findings.missingHandler.length + findings.mismatch.length + findings.unregistered.length;+ process.exit(fatal > 0 ? 1 : 0);+}++function countOf(f) {+ return Object.fromEntries(Object.entries(f).map(([k, v]) => [k, v.length]));+}++function report(f, stats) {+ const line = "-".repeat(64);+ console.log(line);+ console.log("IPC bridge parity report");+ console.log(line);+ console.log(+ `preload renderer→main channels: ${stats.r2m.size} push channels: ${stats.pushChannels.size} ipcMain handlers: ${stats.ipcMain.size}`+ );+ console.log("");++ section("(a) renderer→main channels with NO ipcMain handler [FATAL: hang/no-op]", f.missingHandler, (x) =>+ ` ${x.ch} (preload uses ${x.transports.join("/")})`+ );+ section("(b) transport / handler-kind mismatch [FATAL]", f.mismatch, (x) =>+ ` ${x.ch}: preload ${x.transport} expects ipcMain.${x.expected}, found ipcMain.${x.got}`+ );+ section("(e) handler module setupX() never called from main.ts [FATAL: channels dead]", f.unregistered, (x) =>+ ` ${x.fn}() (${x.file})`+ );+ section("(c) ipcMain handlers with no preload caller [advisory: dead/legacy]", f.deadHandler, (x) =>+ ` ${x.ch} (${x.file})${x.known ? " — known legacy orphan" : ""}`+ );+ section("(d) preload channels with no preload.spec.ts assertion [advisory: untested]", f.untested, (x) => ` ${x}`);++ const fatal = f.missingHandler.length + f.mismatch.length + f.unregistered.length;+ console.log(line);+ console.log(fatal > 0 ? `RESULT: ${fatal} fatal finding(s) — fix before shipping.` : "RESULT: no fatal findings.");+ console.log(line);+}++function section(title, items, fmt) {+ console.log(title);+ if (items.length === 0) {+ console.log(" (none)");+ } else {+ for (const it of items) console.log(fmt(it));+ }+ console.log("");+}++main();