Skip to content

Build your personal knowledge base with Trilium Notes

docs(claude): record desktop, coverage and mocking findings in the skills

Elian Doran437c37d374b5
diff --git a/.claude/skills/analyzing-coverage/SKILL.md b/.claude/skills/analyzing-coverage/SKILL.md
index f939986516..4a76deae65 100644
--- a/.claude/skills/analyzing-coverage/SKILL.md
+++ b/.claude/skills/analyzing-coverage/SKILL.md
@@ -84,6 +84,8 @@ node ../../.claude/skills/analyzing-coverage/coverage.mjs \
- **Multi-file client runs must `cd apps/client` first.** Running multiple specs from the repo root with `--root apps/client` triggers a vitest "failed to find the runner" crash; a single spec with `--root` is fine.
- **Isolated vs full-suite gaps:** when you run only *your* spec, lines covered by *other* specs in the full suite show as uncovered. That's expected — only your assigned lines need to disappear. Don't chase the rest.
- **`--coverage.reportsDirectory` is relative to `--root`**, so it can double a path prefix — pass a simple relative dir like `./test-output/cov-<slug>`.
+- **A block `if` with no `else` can report a phantom uncovered branch.** `if (x) { … }` can show its fall-through as uncovered even when many tests exercise it — statement hits on the lines after it prove it ran. Don't hunt for a test that cannot exist: rewrite branchlessly, e.g. a latch `flag = cond || flag;` in place of `if (cond) flag = true;` (hit in `apps/desktop/src/services/security_settings.ts`).
+- **A cache-once arm can only be reached once per module instance** — a `coreUtils.isDev() ? dev : prod` expression memoized on first call (`getPreloadScript()` in `services/window.ts` / `printing.ts`) runs one arm and never the other, whatever the tests do. Mock the reachable arm and `/* v8 ignore next N -- … */` the other with a reason naming what does cover it (the production build).
- For provably-dead defensive branches, mark with `/* v8 ignore next N -- reason */` rather than writing a fake test (sanctioned by writing-unit-tests).
## Writing the tests
diff --git a/.claude/skills/developing-electron-desktop/SKILL.md b/.claude/skills/developing-electron-desktop/SKILL.md
index e1bc98c1c7..3f7b9578e7 100644
--- a/.claude/skills/developing-electron-desktop/SKILL.md
+++ b/.claude/skills/developing-electron-desktop/SKILL.md
@@ -42,6 +42,14 @@ apps/desktop/
- **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`).
+## The `main()` prologue runs before the database
+
+Everything from the top of `main()` down to `dbProvider.loadFromFile(…)` runs before `app.on("ready")` and long before `initializeCore()` wires core's SQL layer. Chromium switches (`app.commandLine.appendSwitch`, `app.disableHardwareAcceleration`) must be applied before `ready`, which forces that shape — current readers are `lang` via `getElectronLocale()`, `smoothScrollEnabled` (#10559) and `hardwareAccelerationEnabled` (#10572). Three rules hold in that window:
+
+- **`options.getOptionOrNull()` always returns `null` there.** It falls back to `getSql()`, which throws before the provider is wired, so an option-derived switch silently takes its default (#10559). Read pre-`ready` values with `readDbOption(dbProvider, name)` instead.
+- **Keep the prologue await-free.** `app`, `config` and `dataDirs` are static imports precisely so `ready` cannot fire before the database is open. Adding an `await` — including a `await import(…)` for something already statically available — reintroduces the race that lands a switch too late.
+- **Open the database once.** The `BetterSqlite3Provider` the switches read from is the same instance handed to `initializeCore({ dbConfig: { provider } })`; don't open a second connection. The single-instance lock check stays *before* the open, so a second launch exits without touching the file.
+
## Adding an Electron API (renderer → main)
Four files, always together:
@@ -155,6 +163,11 @@ CJS — the sandboxed renderer can't load an ESM preload, and the worker is spaw
seams took the desktop main process from 348 MB to 287 MB RSS. The
**`analyzing-backend-bundle` skill** has the measurement tools and the seam patterns.
+## Upstream Electron behaviours that bite
+
+- **`session.setSpellCheckerLanguages()` force-enables spell check.** Upstream runs `prefs.SetBoolean(kSpellCheckEnable, !langs.empty())`, so a non-empty language list clobbers an earlier `setSpellCheckerEnabled(false)` — the symptom is spell check reactivating on every launch even though the option is off (#10569). Set the languages **first** and `setSpellCheckerEnabled(enabled)` **last**; `setupSpellcheckForSession()` and `applySpellcheckLanguages()` in `services/window.ts` both re-assert the option afterwards for this reason.
+- **`electron.net` joins repeated header values with a bare comma**, where Node's `http` joins cookie arrays with `"; "` — which is why server↔server sync never hits this and desktop sync does. A `Cookie` header replayed from a raw `set-cookie` array arrives as `…HttpOnly,trilium.sid=x`, which `cookie.parse` reads as one junk key: the session cookie is lost and sync 401s with "Logged in session not found" as soon as a response carries any second `Set-Cookie` (a load-balancer affinity cookie) before Trilium's. `absorbSetCookies()` in `apps/server/src/services/request.ts` merges by name into a single `"; "`-joined string; keep any header a new `net`-based request path sends pre-joined (#10548).
+
## Running
| Command | What it does |
diff --git a/.claude/skills/writing-unit-tests/SKILL.md b/.claude/skills/writing-unit-tests/SKILL.md
index 98c84188c0..1654c14c71 100644
--- a/.claude/skills/writing-unit-tests/SKILL.md
+++ b/.claude/skills/writing-unit-tests/SKILL.md
@@ -79,6 +79,7 @@ coverage: {
- **A green Vitest run is not proof the spec compiles.** Vitest strips types with esbuild, so specs are never type-checked by the run itself — and `apps/client/tsconfig.app.json` deliberately **excludes** `src/**/*.spec.ts(x)`. They are checked by `tsconfig.spec.json`, which `pnpm typecheck` reaches through the project references, so **`pnpm typecheck` is the only thing that catches a broken spec** — but run it **once, after the whole batch of specs is written**, never per file or per edit. It walks the project references and costs real time; spending that repeatedly is the single easiest way to make a test-writing session slow. Passing tests routinely hide mechanical type errors that then fail CI. The recurring ones: `act(() => someExpression)` returning a value where a `void` callback is expected, `Component | undefined` passed where the context wants `| null`, and mock-froca helpers whose default `getNote = vi.fn(async () => undefined)` infers `Promise<undefined>` and rejects a caller's `vi.fn(async () => someNote)` — type such params loosely (`(...args: unknown[]) => Promise<unknown>`).
- **No non-null assertions (`!`)** — never use the TypeScript postfix `!` operator, even in tests. Narrow instead: `becca.getNoteOrThrow(id)`/`getAttachmentOrThrow(id)` instead of `becca.getNote(id)!`; `value?.prop ?? fallback` then assert; or capture into a const after an `expect(x).toBeDefined()`/null check. (Project rule — see `CLAUDE.md` Code Style.)
- **`vi.mock` is hoisted** above imports. Put component/module imports *after* the `vi.mock(...)` calls; mock factories can't reference outer non-hoisted variables. Partial-mock with `async (importOriginal) => ({ ...(await importOriginal()), onlyThis: vi.fn() })`.
+- **`vi.resetModules()` drops `importOriginal`-based partial mocks.** The next dynamic import of the module gets the *real* dependency back, not your stub, and the symptom reads as "the mock isn't applying" rather than as a reset problem. Prefer registering singletons and IPC handlers **once** and ordering the tests instead — put the one that latches module-level state last. Where a reset is genuinely needed (a value cached on first call), mock with a full factory rather than an `importOriginal` partial.
- **Don't assert on translated (i18n) strings** — assert structure/keys/behavior (classes, counts, ids), not human-readable English.
- **happy-dom is not a browser:** `getBoundingClientRect()` returns zeros, `ResizeObserver`/layout/visibility are stubs. Anything pixel/size/scroll-based needs `@vitest/browser`, not happy-dom.
- **`@vitest/browser` real-browser mode IS configured** — the `packages/ckeditor5`, `-mermaid` and `-math` bundles run their co-located `src/**/*.spec.ts` in headless Chrome (`@vitest/browser-webdriverio`; see `packages/ckeditor5/vitest.config.ts`). These are the browser-mode `test:sequential` suites. Reserve real-browser mode for genuine layout/integration needs (CKEditor, Excalidraw, Modal transitions, size measurement); normal unit tests stay on happy-dom.